@unbrained/pm-cli 2026.11.20 → 2026.11.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/pm-sdk/SKILL.md +1 -1
- package/.agents/skills/pm-test-audit/SKILL.md +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/CONTRIBUTING.md +2 -1
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/register-list-query.js +2 -2
- package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2DXRTIC6.js +21 -0
- package/dist/cli-bundle/chunks/{chunk-XK25TAJZ.js → chunk-5647LU3A.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-OXG5XPC7.js → chunk-6QLEXRUG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-MGYAJONE.js → chunk-AHQB7W2H.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3BOR22MC.js → chunk-BKSVHOWI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KQSPKWFH.js → chunk-CASX6SFI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZVEHACE6.js → chunk-CIKGG34F.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KDDIHGAO.js → chunk-D6ILFXZY.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-M5D3CEMY.js → chunk-IUIOTAF6.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-GXGW6KHB.js → chunk-JVGRFU5H.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-2IZGNOGT.js → chunk-KVBIMFUG.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-5LF5QZT3.js → chunk-NCFCBKIP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-HJQ3XPS3.js → chunk-NT5AKFE5.js} +30 -30
- package/dist/cli-bundle/chunks/chunk-PJXKA4QU.js +125 -0
- package/dist/cli-bundle/chunks/{chunk-KEBLUTC3.js → chunk-RMIRNYRG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6HRPGEBF.js → chunk-RULHZRFN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-FF4TXJDH.js → chunk-S6HB3WL2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4QQPM3IY.js → chunk-SA4BNP3Q.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-DG2EOOFX.js → chunk-SRVTCYAU.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4TZW4NLM.js → chunk-WELSVDPU.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6X2AGUOT.js → chunk-XHJ3H5PL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZAO7VGX3.js → chunk-XWHJIRNV.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-YJEBK7HU.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-FOYRE23V.js → chunk-YKJKQ7DM.js} +43 -43
- package/dist/cli-bundle/chunks/{chunk-Y4LXVPA5.js → chunk-YMUSRWV4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-HQYIKAC6.js → chunk-YR2KEBHP.js} +2 -2
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-ELEMA7IW.js → indexed-receipt-blobs-ITTXIN4K.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-GE2CQECR.js → item-revision-R5SZPJZ5.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-7DFCG73I.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-actor-5GYX7LP3.js → mutation-actor-3TG636XG.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-72TYKPGU.js → mutation-admission-LICSDNNO.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-OQZZEWEB.js → register-list-query-SPGPS3OS.js} +10 -10
- package/dist/cli-bundle/chunks/{register-mutation-YZEUZ6XT.js → register-mutation-WWVECKFQ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-JNVCF7EW.js → register-operations-L6HFJNWD.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-LDKULZSD.js → register-setup-K7UFG5TD.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-E5LHZ4RD.js → settlement-hook-BXN5LEQD.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-Q2QZ2IBG.js → stage-57KH3KAC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-IXYBN6D2.js → chunk-3IRCYJI5.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-DH4DHL6V.js → chunk-3V53UBHN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-7SB6VKEI.js → chunk-532WZV65.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-KQJNJZKP.js → chunk-7A4QWNZX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-CU2BRAOX.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-MJP3TFVW.js → chunk-CWWKRI5P.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-FPKVHC3Q.js → chunk-HGFNL5XI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-IQK5NPMG.js +13 -0
- package/dist/cli-bundle/focused-chunks/{chunk-UATP3RK3.js → chunk-J63D6QST.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZKGGGU2K.js → chunk-JMQJBZQ5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-O25KFLLA.js → chunk-LNHUE4VV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BZCLW5V7.js → chunk-MKM5NKD7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-5VSXKA35.js → chunk-NP72ZDXE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PZSTRYTA.js → chunk-OSLQD5VH.js} +37 -37
- package/dist/cli-bundle/focused-chunks/{chunk-V55XZFOP.js → chunk-QGKLRXP7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TNKI6WKG.js → chunk-QSJW6NSQ.js} +53 -53
- package/dist/cli-bundle/focused-chunks/{chunk-PKMDWIP3.js → chunk-RPE6IX26.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-SRDQSA6M.js +91 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PQXTZLK3.js → chunk-UOC6257J.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SJE3PYPI.js → chunk-URJ2E6AS.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-WXMI4AV5.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PRFEOCNZ.js → chunk-XCJSHNXK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-QNJQPJWO.js → chunk-XQQSSKJI.js} +5 -5
- package/dist/cli-bundle/focused-chunks/{chunk-JUYJ7NXL.js → chunk-YOAYY3HE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-ZTRFCPH7.js → indexed-receipt-blobs-AF4U3F3D.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-revision-OXDZHMJ7.js → item-revision-3V3UIP5X.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-transaction-54VSTT6L.js → item-transaction-HLBW7B3J.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-actor-6DYIF6NH.js → mutation-actor-62HKR5IO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-2BYXANVJ.js → mutation-admission-X4PF2SG3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-OUBUN45C.js → settlement-hook-ARYCZQY4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-FGHSB3QX.js → stage-O7T7CXBB.js} +2 -2
- package/dist/cli-bundle/main.js +25 -25
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +58 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/extensions/index.d.ts +2 -0
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/fs/fs-utils.d.ts +3 -1
- package/dist/core/fs/fs-utils.js +1 -1
- package/dist/core/history/history-stream-policy.js +1 -1
- package/dist/core/history/read.d.ts +11 -1
- package/dist/core/history/read.js +1 -1
- package/dist/core/history/stream-summary.d.ts +129 -0
- package/dist/core/history/stream-summary.js +3 -0
- package/dist/core/shared/errors.d.ts +8 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/url-credentials.js +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +2 -2
- package/dist/sdk/governance/gc.js +1 -1
- package/dist/sdk/governance/health-merge-evidence.js +1 -1
- package/dist/sdk/governance/validate.js +1 -1
- package/dist/sdk/governance/workspace-position.js +1 -1
- package/dist/sdk/history-provenance.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/merge/index.d.ts +1 -1
- package/dist/sdk/merge/index.js +1 -1
- package/dist/sdk/merge/install.d.ts +20 -6
- package/dist/sdk/merge/install.js +3 -3
- package/dist/sdk/merge/worktree-config.js +2 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/activity.d.ts +67 -5
- package/dist/sdk/query/activity.js +1 -1
- package/dist/sdk/query/context.d.ts +13 -3
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query.d.ts +1 -1
- package/dist/sdk/query.js +1 -1
- package/docs/COMMANDS.md +56 -2
- package/docs/MERGE_SAFETY.md +8 -0
- package/docs/MUTATION_INTEGRITY.md +3 -1
- package/docs/PERFORMANCE.md +17 -2
- package/docs/README.md +6 -4
- package/docs/SDK.md +25 -1
- package/docs/TESTING.md +8 -697
- package/docs/WORKSPACE_POSITION_AND_LIFECYCLE.md +1 -1
- package/marketplace.json +1 -1
- package/package.json +6 -2
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-5OFMWP3Q.js +0 -3
- package/dist/cli-bundle/chunks/chunk-7ESF676D.js +0 -125
- package/dist/cli-bundle/chunks/chunk-7EZZ4W7O.js +0 -20
- package/dist/cli-bundle/chunks/chunk-VS565KBX.js +0 -2
- package/dist/cli-bundle/chunks/chunk-W4TLA5H3.js +0 -8
- package/dist/cli-bundle/chunks/item-transaction-YSAWJRA2.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-3LRSQXCN.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-FOA7XKWP.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-I7XBR2RM.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-SIPDQBJI.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-TRCXANRR.js +0 -12
- package/docs/MCP_2026_07_28_CONFORMANCE.md +0 -41
- package/docs/QUALITY_EVIDENCE.md +0 -130
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +0 -117
- package/docs/performance/cli-transport-overhead.md +0 -51
- package/docs/performance/runner-qualification.md +0 -36
- package/docs/performance/sdk-entrypoint-import-costs.md +0 -32
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{type GlobalOptions}from "../runtime-primitives.js";import type{HistoryEntry}from "../../types/index.js";import{type OutputOmissionReceipt}from "../output-projection.js";import{type HistoryProvenanceRow,type HistoryProvenanceSummary}from "../history-provenance.js";
|
|
1
|
+
import{type GlobalOptions}from "../runtime-primitives.js";import{type HistoryStreamBounds,type HistoryStreamSummaryFallback}from "../../core/history/stream-summary.js";import type{HistoryEntry}from "../../types/index.js";import{type OutputOmissionReceipt}from "../output-projection.js";import{type HistoryProvenanceRow,type HistoryProvenanceSummary}from "../history-provenance.js";
|
|
2
2
|
/** Documents the activity command options payload exchanged by command, SDK, and package integrations. */
|
|
3
3
|
export interface ActivityCommandOptions{
|
|
4
4
|
/** Stable identifier used to reference this record across commands and storage. */
|
|
@@ -108,10 +108,72 @@ applied_bound:{kind:"limit"|"unbounded";source:"default"|"explicit";value:number
|
|
|
108
108
|
/** Constant-size description of the selected time window and matching corpus. */
|
|
109
109
|
activity_summary?:{window:{from:string|null;to:string|null;};event_count:number;item_count:number;author_count:number;operation_counts:Record<string,number>;};
|
|
110
110
|
/** Constant-size provenance completeness metrics. */
|
|
111
|
-
provenance_summary?:HistoryProvenanceSummary;
|
|
111
|
+
provenance_summary?:HistoryProvenanceSummary;
|
|
112
|
+
/** Present only when a tracker that keeps derived stream bounds could not bound this read by its window. */
|
|
113
|
+
history_read?:ActivityHistoryReadReceipt;}
|
|
114
|
+
/**
|
|
115
|
+
* Constant-size disclosure that a read on a tracker large enough to keep
|
|
116
|
+
* derived stream bounds was not bounded by its window, so its cost followed
|
|
117
|
+
* the history archive (GH-1664). Bounded reads emit no receipt.
|
|
118
|
+
*/
|
|
119
|
+
export interface ActivityHistoryReadReceipt{
|
|
120
|
+
/**
|
|
121
|
+
* `summary_missing` / `summary_invalid` / `summary_stale`: the derived bounds
|
|
122
|
+
* were absent, unreadable, or current for at most half of the streams, and
|
|
123
|
+
* this read rebuilds them; `irregular_timestamps`: most streams hold
|
|
124
|
+
* timestamps that are not canonical millisecond UTC, so bounds cannot
|
|
125
|
+
* exclude them; `read_hooks_active`: an extension observes every stream
|
|
126
|
+
* read; `unwindowed_query`: no `--from` bound and most streams were parsed
|
|
127
|
+
* (add `--from` to bound the read); `window_reaches_most_streams`: the
|
|
128
|
+
* bounds were current but the window (or, for recent rows, a clock pinned
|
|
129
|
+
* before most streams' newest entries) still reached most streams.
|
|
130
|
+
*/
|
|
131
|
+
reason:HistoryStreamSummaryFallback|"unwindowed_query"|"window_reaches_most_streams";
|
|
132
|
+
/** History streams parsed by this read. */
|
|
133
|
+
streams_read:number;
|
|
134
|
+
/** History streams present when the read began. */
|
|
135
|
+
streams_total:number;}
|
|
136
|
+
/** Bounded recent-activity rows for context-style readers that need no page cursor. */
|
|
137
|
+
export interface RecentActivityResult{
|
|
138
|
+
/** Newest matching events, in the activity sort order. */
|
|
139
|
+
rows:CompactActivityEntry[];
|
|
140
|
+
/** Present only when a tracker that keeps derived stream bounds could not bound this read. */
|
|
141
|
+
history_read?:ActivityHistoryReadReceipt;}
|
|
142
|
+
interface ActivityFilters{id:string|undefined;op:string|undefined;author:string|undefined;from:string|undefined;to:string|undefined;limit:number|undefined;limitSource:"default"|"explicit";harness:string|readonly string[]|undefined;agentInstance:string|readonly string[]|undefined;provenance:string|readonly string[]|undefined;}
|
|
112
143
|
interface ActivityItemMetadata{title:string;type:string;status:string;}
|
|
113
|
-
declare function parseNonEmptyFilter(raw:string|undefined,flagLabel:string):string|undefined;declare function parseRangeBound(raw:string|undefined,nowValue:string,fieldLabel:string):string|undefined;declare function includeByTimeWindow(entry:ActivityEntry,from:string|undefined,to:string|undefined):boolean;declare function limitEntries<T>(values:T[],limit:number|undefined):T[];declare function readActivityString(value:unknown,fallback?:string):string;declare function normalizeActivityEntry(id:string,entry:HistoryEntry):ActivityEntry;declare function sortActivity(entries:ActivityEntry[]):ActivityEntry[];declare function listHistoryFiles(historyDir:string):Promise<string[]>;
|
|
144
|
+
declare function parseNonEmptyFilter(raw:string|undefined,flagLabel:string):string|undefined;declare function parseRangeBound(raw:string|undefined,nowValue:string,fieldLabel:string):string|undefined;declare function includeByTimeWindow(entry:ActivityEntry,from:string|undefined,to:string|undefined):boolean;declare function limitEntries<T>(values:T[],limit:number|undefined):T[];declare function readActivityString(value:unknown,fallback?:string):string;declare function normalizeActivityEntry(id:string,entry:HistoryEntry):ActivityEntry;declare function sortActivity(entries:ActivityEntry[]):ActivityEntry[];declare function listHistoryFiles(historyDir:string):Promise<string[]>;
|
|
145
|
+
/**
|
|
146
|
+
* Whether trusted bounds leave any entry of the stream inside `[from, to)`.
|
|
147
|
+
* Window bounds are canonical instants (resolveIsoOrRelative) and regular
|
|
148
|
+
* entry timestamps compare chronologically under compareTimestampStrings, so
|
|
149
|
+
* the newest entry below `from` or the oldest at or after `to` excludes every
|
|
150
|
+
* entry; irregular streams are always read.
|
|
151
|
+
*/
|
|
152
|
+
declare function streamMayMatchWindow(bounds:HistoryStreamBounds,filters:Pick<ActivityFilters,"from"|"to">):boolean;
|
|
153
|
+
/**
|
|
154
|
+
* Whether an unread regular stream can still place an entry above `last`.
|
|
155
|
+
* Its entries sort no earlier than its newest timestamp, and entries tied on
|
|
156
|
+
* that timestamp sort by item id, which is the stream's own id.
|
|
157
|
+
*/
|
|
158
|
+
declare function streamCanOutrank(newest:string,streamId:string,last:ActivityEntry):boolean;interface DeferredActivityStream{file:string;
|
|
159
|
+
/** Position in history-file order, the complete read's tie-breaker. */
|
|
160
|
+
position:number;id:string;newest:string;}
|
|
161
|
+
/**
|
|
162
|
+
* Order unread regular streams by the activity order of their best possible
|
|
163
|
+
* entry (newest timestamp, then item id, then file order for distinct names
|
|
164
|
+
* that collate equally), so once one stream cannot outrank the last selected
|
|
165
|
+
* row, no later stream can either.
|
|
166
|
+
*/
|
|
167
|
+
declare function compareDeferredStreams(left:DeferredActivityStream,right:DeferredActivityStream):number;declare function buildActivityDigest(activity:readonly ActivityEntry[],itemsById:ReadonlyMap<string,ActivityItemMetadata>):ActivityDigestEntry[];declare function activityOperationCounts(activity:readonly Pick<ActivityEntry,"op">[]):Record<string,number>;
|
|
114
168
|
/** Public contract for test only, shared by SDK and presentation-layer consumers. */
|
|
115
|
-
export declare const _testOnly:{parseNonEmptyFilter:typeof parseNonEmptyFilter;parseRangeBound:typeof parseRangeBound;includeByTimeWindow:typeof includeByTimeWindow;limitEntries:typeof limitEntries;readActivityString:typeof readActivityString;normalizeActivityEntry:typeof normalizeActivityEntry;sortActivity:typeof sortActivity;listHistoryFiles:typeof listHistoryFiles;buildActivityDigest:typeof buildActivityDigest;activityOperationCounts:typeof activityOperationCounts;};
|
|
169
|
+
export declare const _testOnly:{parseNonEmptyFilter:typeof parseNonEmptyFilter;parseRangeBound:typeof parseRangeBound;includeByTimeWindow:typeof includeByTimeWindow;limitEntries:typeof limitEntries;readActivityString:typeof readActivityString;normalizeActivityEntry:typeof normalizeActivityEntry;sortActivity:typeof sortActivity;streamMayMatchWindow:typeof streamMayMatchWindow;streamCanOutrank:typeof streamCanOutrank;compareDeferredStreams:typeof compareDeferredStreams;listHistoryFiles:typeof listHistoryFiles;buildActivityDigest:typeof buildActivityDigest;activityOperationCounts:typeof activityOperationCounts;};
|
|
116
170
|
/** Implements run activity for the public runtime surface of this module. */
|
|
117
|
-
export declare function runActivity(options:ActivityCommandOptions,global:GlobalOptions):Promise<ActivityResult>;
|
|
171
|
+
export declare function runActivity(options:ActivityCommandOptions,global:GlobalOptions):Promise<ActivityResult>;
|
|
172
|
+
/**
|
|
173
|
+
* Read the newest compact activity rows without a page cursor or totals.
|
|
174
|
+
* Rows equal the first page of `pm activity --raw --limit <limit>`. The limit
|
|
175
|
+
* caps the rows returned, not the history parsed: trusted stream bounds let
|
|
176
|
+
* the read skip streams that cannot reach those rows, but a tracker under the
|
|
177
|
+
* summary threshold (500 streams) parses every stream, with no receipt.
|
|
178
|
+
*/
|
|
179
|
+
export declare function readRecentActivity(options:{limit:number;},global:GlobalOptions):Promise<RecentActivityResult>;export{};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="aa1ede64-e578-57da-9194-1cd646cee915")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{isFileMissingError}from"../../core/fs/fs-utils.js";import fs from"node:fs/promises";import path from"node:path";import{getActiveExtensionRegistrations,runActiveOnReadHooks,enforceHistoryStreamPolicyForItems,resolveItemTypeRegistry,EXIT_CODE,PmCliError,compareTimestampStrings,resolveIsoOrRelative,listAllItemMetadataLight,resolvePmRoot,readSettings}from"../runtime-primitives.js";import{readHistoryEntries}from"../history-read.js";import{parseLimit}from"./parsers.js";import{fingerprintWindowRows,paginateWindowQuery,resolveWindowQueryClock}from"./window-pagination.js";import{resolveModePairedOutputOmissionReceipt}from"../output-projection.js";import{compileHistoryProvenanceMatcher,projectHistoryProvenance,resolveHistoryProvenanceDimensions,summarizeHistoryProvenance}from"../history-provenance.js";const DEFAULT_COMPACT_ACTIVITY_LIMIT=20,DEFAULT_FULL_ACTIVITY_LIMIT=5,DEFAULT_DIGEST_ACTIVITY_LIMIT=15,DEFAULT_DIGEST_WINDOW="-24h";function normalizeActivityProjectionOptions(options){const normalized={...options};return normalized.full===!0?(normalized.raw=!0,normalized.compact=!1):normalized.raw===!0&&normalized.compact===void 0&&(normalized.compact=!0),delete normalized.full,normalized}const ACTIVITY_ROW_KEY_BY_MODE={digest:"activity_digest",compact:"compact_activity",provenance:"provenance_activity",full:"activity"};function parseNonEmptyFilter(raw,flagLabel){if(raw===void 0)return;const normalized=raw.trim();if(normalized.length===0)throw new PmCliError(`${flagLabel} must not be empty`,EXIT_CODE.USAGE);return normalized}function parseRangeBound(raw,nowValue,fieldLabel){if(raw===void 0)return;const normalized=raw.trim();if(normalized.length===0)throw new PmCliError("Activity time bounds must not be empty",EXIT_CODE.USAGE);const relativeInput=fieldLabel==="--from"&&/^\d+[hdwm]$/iu.test(normalized)?`-${normalized}`:normalized;return resolveIsoOrRelative(relativeInput,new Date(nowValue),fieldLabel)}function includeByTimeWindow(entry,from,to){return!(entry.ts.length===0&&(from||to)||from&&compareTimestampStrings(entry.ts,from)<0||to&&compareTimestampStrings(entry.ts,to)>=0)}function limitEntries(values,limit){return limit===void 0?values:values.slice(0,limit)}function readActivityString(value,fallback=""){return typeof value=="string"?value:fallback}function normalizeActivityEntry(id,entry){return{...entry,id,ts:readActivityString(entry.ts),author:readActivityString(entry.author,"unknown"),op:readActivityString(entry.op,"unknown"),patch:Array.isArray(entry.patch)?entry.patch:[],before_hash:readActivityString(entry.before_hash),after_hash:readActivityString(entry.after_hash)}}function sortActivity(entries){return[...entries].sort((a,b)=>{const byTimestamp=b.ts.localeCompare(a.ts);if(byTimestamp!==0)return byTimestamp;const byId=a.id.localeCompare(b.id);return byId!==0?byId:a.op.localeCompare(b.op)})}async function listHistoryFiles(historyDir){try{return(await fs.readdir(historyDir)).filter(entry=>entry.endsWith(".jsonl")).sort((a,b)=>a.localeCompare(b))}catch(error){if(isFileMissingError(error))return[];throw error}}function resolveActivityProjectionMode(options){return options.raw!==!0&&options.compact!==!0&&options.provenance!==!0?"digest":options.provenance===!0?"provenance":options.compact===!0||options.raw===!0&&options.compact!==!1?"compact":"full"}function resolveActivityLimit(options,explicitLimit,projectionMode){if(options.unbounded!==!0)return explicitLimit!==void 0?explicitLimit:projectionMode==="digest"?DEFAULT_DIGEST_ACTIVITY_LIMIT:projectionMode==="compact"?DEFAULT_COMPACT_ACTIVITY_LIMIT:DEFAULT_FULL_ACTIVITY_LIMIT}function resolveActivityFilters(options,projectionMode,nowValue){const digest=projectionMode==="digest",to=parseRangeBound(options.to??(digest||options.unbounded!==!0?nowValue:void 0),nowValue,"--to"),from=parseRangeBound(options.from??(digest?DEFAULT_DIGEST_WINDOW:void 0),options.from===void 0&&digest?to:nowValue,"--from");if(from&&to&&compareTimestampStrings(from,to)>=0)throw new PmCliError("Activity --from must be before --to",EXIT_CODE.USAGE);const explicitLimit=parseLimit(options.limit);if(options.unbounded===!0&&explicitLimit!==void 0)throw new PmCliError("Activity --unbounded cannot be combined with --limit",EXIT_CODE.USAGE);return{id:parseNonEmptyFilter(options.id,"Activity --id"),op:parseNonEmptyFilter(options.op,"Activity --op"),author:parseNonEmptyFilter(options.author,"Activity --author"),from,to,limit:resolveActivityLimit(options,explicitLimit,projectionMode),limitSource:options.unbounded===!0||explicitLimit!==void 0?"explicit":"default",harness:options.harness,agentInstance:options.agentInstance,provenance:options.provenanceFilter}}async function resolveActivityRuntimeContext(global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);return await assertInitializedTracker(pmRoot),{pmRoot,settings:await readSettings(pmRoot)}}async function prepareActivityHistoryRead(context){const typeRegistry=resolveItemTypeRegistry(context.settings,getActiveExtensionRegistrations()),items=await listAllItemMetadataLight(context.pmRoot,context.settings.item_format,typeRegistry.type_to_folder,void 0,context.settings.schema);await enforceHistoryStreamPolicyForItems({pmRoot:context.pmRoot,settings:context.settings,itemIds:items.map(item=>item.id),commandLabel:"activity"});const historyDir=path.join(context.pmRoot,"history");return await runActiveOnReadHooks({path:historyDir,scope:"project"}),{historyDir,itemsById:new Map(items.map(item=>[item.id,{title:item.title,type:item.type,status:item.status}]))}}function includeActivityEntry(entry,candidate,filters){return filters.op&&entry.op!==filters.op||filters.author&&entry.author!==filters.author?!1:includeByTimeWindow(candidate,filters.from,filters.to)}async function collectActivityEntries(historyDir,filters){const combined=[];for(const file of await listHistoryFiles(historyDir)){const id=file.slice(0,-6);if(filters.id&&id!==filters.id)continue;const entries=await readHistoryEntries(path.join(historyDir,file),id);for(const entry of entries){const candidate=normalizeActivityEntry(id,entry);includeActivityEntry(entry,candidate,filters)&&combined.push(candidate)}}return combined}function formatCompactActivity(activity){return activity.map(entry=>({id:entry.id,op:entry.op,ts:entry.ts,author:entry.author,...entry.message?{msg:entry.message}:{}}))}function boundedOperationSummary(counts){const ordered=[...counts.entries()].sort(([leftOp,leftCount],[rightOp,rightCount])=>rightCount-leftCount||leftOp.localeCompare(rightOp)),visible=ordered.slice(0,4).map(([op,count])=>`${op}:${count}`);return ordered.length>visible.length&&visible.push(`+${ordered.length-visible.length}`),visible.join(",")}function buildActivityDigest(activity,itemsById){const grouped=new Map;for(const entry of activity){const current=grouped.get(entry.id);if(current===void 0){grouped.set(entry.id,{firstTs:entry.ts,lastTs:entry.ts,eventCount:1,operations:new Map([[entry.op,1]])});continue}current.eventCount+=1,compareTimestampStrings(entry.ts,current.firstTs)<0&&(current.firstTs=entry.ts),compareTimestampStrings(entry.ts,current.lastTs)>0&&(current.lastTs=entry.ts),current.operations.set(entry.op,(current.operations.get(entry.op)??0)+1)}return[...grouped.entries()].map(([id,summary])=>{const item=itemsById.get(id);return{id,type:item?.type??"unknown",status:item?.status??"unknown",title:(item?.title??"(item metadata unavailable)").slice(0,160),event_count:summary.eventCount,first_ts:summary.firstTs,last_ts:summary.lastTs,operations:boundedOperationSummary(summary.operations)}}).sort((left,right)=>compareTimestampStrings(right.last_ts,left.last_ts)||left.id.localeCompare(right.id))}function activityOperationCounts(activity){const counts=new Map;for(const entry of activity)counts.set(entry.op,(counts.get(entry.op)??0)+1);const ordered=[...counts.entries()].sort((left,right)=>right[1]-left[1]||left[0].localeCompare(right[0])),visible=ordered.slice(0,8);return visible.length<ordered.length&&visible.push([`+${String(ordered.length-visible.length)}`,ordered.slice(visible.length).reduce((total,[,count])=>total+count,0)]),Object.fromEntries(visible)}function projectActivityRows(projectionMode,matchingActivity,pageOptions,itemsById,projectProvenance){if(projectionMode==="digest"){const{rows,...page2}=paginateWindowQuery(buildActivityDigest(matchingActivity,itemsById),pageOptions);return{rows:{activity_digest:rows},compact:!1,page:page2}}const{rows:activity,...page}=paginateWindowQuery(matchingActivity,pageOptions);return projectionMode==="compact"?{rows:{compact_activity:formatCompactActivity(activity)},compact:!0,page}:projectionMode==="provenance"?{rows:{provenance_activity:activity.map(projectProvenance)},compact:!1,page}:{rows:{activity},compact:!1,page}}const _testOnly={parseNonEmptyFilter,parseRangeBound,includeByTimeWindow,limitEntries,readActivityString,normalizeActivityEntry,sortActivity,listHistoryFiles,buildActivityDigest,activityOperationCounts};async function runActivity(options,global2){const context=await resolveActivityRuntimeContext(global2),projectionMode=resolveActivityProjectionMode(options),clock=resolveWindowQueryClock("activity",options.after),filters=resolveActivityFilters(options,projectionMode,clock),prepared=await prepareActivityHistoryRead(context),provenanceDimensions=resolveHistoryProvenanceDimensions(context.settings.agent_identity.harness_signals),vocabulary=context.settings.agent_identity.identity_vocabulary,matchesProvenance=compileHistoryProvenanceMatcher({harness:filters.harness,agentInstance:filters.agentInstance,provenance:filters.provenance},vocabulary,provenanceDimensions),matchingActivity=sortActivity(await collectActivityEntries(prepared.historyDir,filters)).filter(matchesProvenance),projected=projectActivityRows(projectionMode,matchingActivity,{command:"activity",after:options.after,clock,limit:filters.limit,query:{pmRoot:context.pmRoot,projectionMode,filters:{...filters,limit:void 0,limitSource:void 0},matching_activity_digest:projectionMode==="digest"?fingerprintWindowRows(matchingActivity):void 0,vocabulary,provenanceDimensions}},prepared.itemsById,entry=>projectHistoryProvenance(entry,vocabulary,{itemId:entry.id}));return{...projected.rows,compact:projected.compact,projection:{mode:projectionMode,row_key:ACTIVITY_ROW_KEY_BY_MODE[projectionMode]},omission_receipt:resolveModePairedOutputOmissionReceipt("activity",projectionMode),...projected.page,window:{anchor:clock,from:filters.from??null,to:filters.to??null},limit:filters.limit??null,...projectionMode==="digest"?{activity_summary:{window:{from:filters.from,to:filters.to},event_count:matchingActivity.length,item_count:projected.page.total_count,author_count:new Set(matchingActivity.map(entry=>entry.author)).size,operation_counts:activityOperationCounts(matchingActivity)}}:{},...options.provenanceSummary===!0?{provenance_summary:summarizeHistoryProvenance(matchingActivity,vocabulary,provenanceDimensions)}:{},applied_bound:{kind:filters.limit===void 0?"unbounded":"limit",source:filters.limitSource,value:filters.limit??null}}}export{_testOnly,normalizeActivityProjectionOptions,runActivity};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7fcacd5d-10f6-5edf-ba12-2fdf6242e06c")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{isFileMissingError}from"../../core/fs/fs-utils.js";import fs from"node:fs/promises";import path from"node:path";import{getActiveExtensionRegistrations,runActiveOnReadHooks,enforceHistoryStreamPolicyForItems,resolveItemTypeRegistry,EXIT_CODE,PmCliError,compareTimestampStrings,resolveIsoOrRelative,listAllItemMetadataLight,resolvePmRoot,readSettings}from"../runtime-primitives.js";import{hasActiveOnReadHooks}from"../../core/extensions/index.js";import{readHistorySnapshot,readIdentifiedHistorySnapshot}from"../../core/history/read.js";import{openHistoryStreamSummary}from"../../core/history/stream-summary.js";import{parseLimit}from"./parsers.js";import{fingerprintWindowRows,paginateWindowQuery,resolveWindowQueryClock}from"./window-pagination.js";import{resolveModePairedOutputOmissionReceipt}from"../output-projection.js";import{compileHistoryProvenanceMatcher,projectHistoryProvenance,resolveHistoryProvenanceDimensions,summarizeHistoryProvenance}from"../history-provenance.js";const DEFAULT_COMPACT_ACTIVITY_LIMIT=20,DEFAULT_FULL_ACTIVITY_LIMIT=5,DEFAULT_DIGEST_ACTIVITY_LIMIT=15,DEFAULT_DIGEST_WINDOW="-24h";function normalizeActivityProjectionOptions(options){const normalized={...options};return normalized.full===!0?(normalized.raw=!0,normalized.compact=!1):normalized.raw===!0&&normalized.compact===void 0&&(normalized.compact=!0),delete normalized.full,normalized}const ACTIVITY_ROW_KEY_BY_MODE={digest:"activity_digest",compact:"compact_activity",provenance:"provenance_activity",full:"activity"};function parseNonEmptyFilter(raw,flagLabel){if(raw===void 0)return;const normalized=raw.trim();if(normalized.length===0)throw new PmCliError(`${flagLabel} must not be empty`,EXIT_CODE.USAGE);return normalized}function parseRangeBound(raw,nowValue,fieldLabel){if(raw===void 0)return;const normalized=raw.trim();if(normalized.length===0)throw new PmCliError("Activity time bounds must not be empty",EXIT_CODE.USAGE);const relativeInput=fieldLabel==="--from"&&/^\d+[hdwm]$/iu.test(normalized)?`-${normalized}`:normalized;return resolveIsoOrRelative(relativeInput,new Date(nowValue),fieldLabel)}function includeByTimeWindow(entry,from,to){return!(entry.ts.length===0&&(from||to)||from&&compareTimestampStrings(entry.ts,from)<0||to&&compareTimestampStrings(entry.ts,to)>=0)}function limitEntries(values,limit){return limit===void 0?values:values.slice(0,limit)}function readActivityString(value,fallback=""){return typeof value=="string"?value:fallback}function normalizeActivityEntry(id,entry){return{...entry,id,ts:readActivityString(entry.ts),author:readActivityString(entry.author,"unknown"),op:readActivityString(entry.op,"unknown"),patch:Array.isArray(entry.patch)?entry.patch:[],before_hash:readActivityString(entry.before_hash),after_hash:readActivityString(entry.after_hash)}}function compareActivityEntries(a,b){const byTimestamp=b.ts.localeCompare(a.ts);if(byTimestamp!==0)return byTimestamp;const byId=a.id.localeCompare(b.id);return byId!==0?byId:a.op.localeCompare(b.op)}function sortActivity(entries){return[...entries].sort(compareActivityEntries)}async function listHistoryFiles(historyDir){try{return(await fs.readdir(historyDir)).filter(entry=>entry.endsWith(".jsonl")).sort((a,b)=>a.localeCompare(b))}catch(error){if(isFileMissingError(error))return[];throw error}}function resolveActivityProjectionMode(options){return options.raw!==!0&&options.compact!==!0&&options.provenance!==!0?"digest":options.provenance===!0?"provenance":options.compact===!0||options.raw===!0&&options.compact!==!1?"compact":"full"}function resolveActivityLimit(options,explicitLimit,projectionMode){if(options.unbounded!==!0)return explicitLimit!==void 0?explicitLimit:projectionMode==="digest"?DEFAULT_DIGEST_ACTIVITY_LIMIT:projectionMode==="compact"?DEFAULT_COMPACT_ACTIVITY_LIMIT:DEFAULT_FULL_ACTIVITY_LIMIT}function resolveActivityFilters(options,projectionMode,nowValue){const digest=projectionMode==="digest",to=parseRangeBound(options.to??(digest||options.unbounded!==!0?nowValue:void 0),nowValue,"--to"),from=parseRangeBound(options.from??(digest?DEFAULT_DIGEST_WINDOW:void 0),options.from===void 0&&digest?to:nowValue,"--from");if(from&&to&&compareTimestampStrings(from,to)>=0)throw new PmCliError("Activity --from must be before --to",EXIT_CODE.USAGE);const explicitLimit=parseLimit(options.limit);if(options.unbounded===!0&&explicitLimit!==void 0)throw new PmCliError("Activity --unbounded cannot be combined with --limit",EXIT_CODE.USAGE);return{id:parseNonEmptyFilter(options.id,"Activity --id"),op:parseNonEmptyFilter(options.op,"Activity --op"),author:parseNonEmptyFilter(options.author,"Activity --author"),from,to,limit:resolveActivityLimit(options,explicitLimit,projectionMode),limitSource:options.unbounded===!0||explicitLimit!==void 0?"explicit":"default",harness:options.harness,agentInstance:options.agentInstance,provenance:options.provenanceFilter}}async function resolveActivityRuntimeContext(global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);return await assertInitializedTracker(pmRoot),{pmRoot,settings:await readSettings(pmRoot)}}async function prepareActivityHistoryRead(context){const typeRegistry=resolveItemTypeRegistry(context.settings,getActiveExtensionRegistrations()),items=await listAllItemMetadataLight(context.pmRoot,context.settings.item_format,typeRegistry.type_to_folder,void 0,context.settings.schema);await enforceHistoryStreamPolicyForItems({pmRoot:context.pmRoot,settings:context.settings,itemIds:items.map(item=>item.id),commandLabel:"activity"});const historyDir=path.join(context.pmRoot,"history");return await runActiveOnReadHooks({path:historyDir,scope:"project"}),{historyDir,itemsById:new Map(items.map(item=>[item.id,{title:item.title,type:item.type,status:item.status}]))}}function includeActivityEntry(entry,candidate,filters){return filters.op&&entry.op!==filters.op||filters.author&&entry.author!==filters.author?!1:includeByTimeWindow(candidate,filters.from,filters.to)}function historyStreamId(file){return file.slice(0,-6)}function streamMayMatchWindow(bounds,filters){return bounds.count===0?!1:bounds.irregular?!0:filters.from&&compareTimestampStrings(bounds.newest,filters.from)<0?!1:!(filters.to&&compareTimestampStrings(bounds.oldest,filters.to)>=0)}async function openActivityStreamRead(pmRoot,historyDir,filters){const files=(await listHistoryFiles(historyDir)).filter(file=>!filters.id||historyStreamId(file)===filters.id);return{summary:await openHistoryStreamSummary({pmRoot,historyDir,files}),files,streamsRead:0,revalidatedStale:0,irregularRead:0,hooksActivated:!1}}function readHooksEndPruning(read){return!read.summary.enabled||!hasActiveOnReadHooks()?!1:(read.hooksActivated=!0,!0)}async function finishBoundedRead(read,skipped,readStream){let pending=[...skipped];const readPending=async selected=>{const now=pending.filter(selected);pending=pending.filter(stream=>!selected(stream));for(const stream of now)await readStream(stream)};if(pending.length>0&&!readHooksEndPruning(read)){const changed=new Set(await read.summary.revalidate(pending.map(({file})=>file)));readHooksEndPruning(read)||(read.revalidatedStale=changed.size,await readPending(({file})=>changed.has(file)))}await read.summary.commit(),pending.length>0&&(read.hooksActivated||readHooksEndPruning(read))&&await readPending(()=>!0)}async function readActivityStream(read,historyDir,file,filters,target){const id=historyStreamId(file),historyPath=path.join(historyDir,file);read.summary.trusted(file)?.irregular===!0&&(read.irregularRead+=1);const snapshot=read.summary.enabled?await readIdentifiedHistorySnapshot(historyPath,id):{...await readHistorySnapshot(historyPath,id),source:null};snapshot.raw_bytes!==null&&(read.streamsRead+=1),read.summary.record(file,snapshot);for(const entry of snapshot.entries){const candidate=normalizeActivityEntry(id,entry);includeActivityEntry(entry,candidate,filters)&&target.push(candidate)}}function activityHistoryReadReceipt(read,unwindowed){const{summary,files,streamsRead,revalidatedStale,irregularRead}=read,parsedMost=summary.enabled&&streamsRead*2>files.length,staleReads=summary.staleAtOpen+revalidatedStale,queryReason=(staleReads+irregularRead)*2>streamsRead?staleReads>=irregularRead?"summary_stale":"irregular_timestamps":unwindowed?"unwindowed_query":"window_reaches_most_streams",reason=read.hooksActivated?"read_hooks_active":summary.fallback??(parsedMost?queryReason:void 0);return reason===void 0?void 0:{reason,streams_read:streamsRead,streams_total:files.length}}async function collectActivityEntries(pmRoot,historyDir,filters){const read=await openActivityStreamRead(pmRoot,historyDir,filters),rowsByPosition=read.files.map(()=>[]),skipped=[];for(const[position,file]of read.files.entries()){const bounds=read.summary.trusted(file);if(bounds!==void 0&&!streamMayMatchWindow(bounds,filters)){skipped.push({file,position});continue}await readActivityStream(read,historyDir,file,filters,rowsByPosition[position])}await finishBoundedRead(read,skipped,({file,position})=>readActivityStream(read,historyDir,file,filters,rowsByPosition[position]));const combined=rowsByPosition.flat(),receipt=activityHistoryReadReceipt(read,filters.from===void 0);return receipt===void 0?{entries:combined}:{entries:combined,history_read:receipt}}function streamCanOutrank(newest,streamId,last){const byTimestamp=newest.localeCompare(last.ts);return byTimestamp>0||byTimestamp===0&&streamId.localeCompare(last.id)<=0}function compareDeferredStreams(left,right){return right.newest.localeCompare(left.newest)||left.id.localeCompare(right.id)||left.position-right.position}class RecentActivityPool{rows=[];filePosition=new WeakMap;cutoff;limit;constructor(limit){this.limit=limit}async read(read,historyDir,filters,stream){const start=this.rows.length;await readActivityStream(read,historyDir,stream.file,filters,this.rows);for(let index=start;index<this.rows.length;index+=1)this.filePosition.set(this.rows[index],stream.position)}admits(stream){return this.limit===0?!1:this.cutoff===void 0||streamCanOutrank(stream.newest,stream.id,this.cutoff)}cutWhenFull(){this.rows.length>=(this.cutoff===void 0?this.limit:2*this.limit)&&this.cut()}cut(){return this.rows=this.rows.sort((left,right)=>compareActivityEntries(left,right)||this.filePosition.get(left)-this.filePosition.get(right)).slice(0,this.limit),this.cutoff=this.limit>0&&this.rows.length===this.limit?this.rows[this.limit-1]:void 0,this.rows}}function partitionRecentActivityStreams(read,filters){const readFirst=[],deferred=[],outsideWindow=[];for(const[position,file]of read.files.entries()){const bounds=read.summary.trusted(file);if(bounds!==void 0&&!streamMayMatchWindow(bounds,filters)){outsideWindow.push({file,position});continue}bounds!==void 0&&!bounds.irregular?deferred.push({file,position,id:historyStreamId(file),newest:bounds.newest}):readFirst.push({file,position})}return{readFirst,deferred:deferred.sort(compareDeferredStreams),outsideWindow}}async function collectRecentActivityEntries(pmRoot,historyDir,filters,limit){const read=await openActivityStreamRead(pmRoot,historyDir,filters),{readFirst,deferred,outsideWindow}=partitionRecentActivityStreams(read,filters),pool=new RecentActivityPool(limit);for(const stream of readFirst)await pool.read(read,historyDir,filters,stream),pool.cutWhenFull();pool.cut();let consumed=0;for(const stream of deferred){if(!pool.admits(stream))break;await pool.read(read,historyDir,filters,stream),pool.cutWhenFull(),consumed+=1}const skipped=[...deferred.slice(consumed),...outsideWindow];await finishBoundedRead(read,skipped,async stream=>{await pool.read(read,historyDir,filters,stream),pool.cutWhenFull()});const entries=pool.cut(),receipt=activityHistoryReadReceipt(read,!1);return receipt===void 0?{entries}:{entries,history_read:receipt}}function formatCompactActivity(activity){return activity.map(entry=>({id:entry.id,op:entry.op,ts:entry.ts,author:entry.author,...entry.message?{msg:entry.message}:{}}))}function boundedOperationSummary(counts){const ordered=[...counts.entries()].sort(([leftOp,leftCount],[rightOp,rightCount])=>rightCount-leftCount||leftOp.localeCompare(rightOp)),visible=ordered.slice(0,4).map(([op,count])=>`${op}:${count}`);return ordered.length>visible.length&&visible.push(`+${ordered.length-visible.length}`),visible.join(",")}function buildActivityDigest(activity,itemsById){const grouped=new Map;for(const entry of activity){const current=grouped.get(entry.id);if(current===void 0){grouped.set(entry.id,{firstTs:entry.ts,lastTs:entry.ts,eventCount:1,operations:new Map([[entry.op,1]])});continue}current.eventCount+=1,compareTimestampStrings(entry.ts,current.firstTs)<0&&(current.firstTs=entry.ts),compareTimestampStrings(entry.ts,current.lastTs)>0&&(current.lastTs=entry.ts),current.operations.set(entry.op,(current.operations.get(entry.op)??0)+1)}return[...grouped.entries()].map(([id,summary])=>{const item=itemsById.get(id);return{id,type:item?.type??"unknown",status:item?.status??"unknown",title:(item?.title??"(item metadata unavailable)").slice(0,160),event_count:summary.eventCount,first_ts:summary.firstTs,last_ts:summary.lastTs,operations:boundedOperationSummary(summary.operations)}}).sort((left,right)=>compareTimestampStrings(right.last_ts,left.last_ts)||left.id.localeCompare(right.id))}function activityOperationCounts(activity){const counts=new Map;for(const entry of activity)counts.set(entry.op,(counts.get(entry.op)??0)+1);const ordered=[...counts.entries()].sort((left,right)=>right[1]-left[1]||left[0].localeCompare(right[0])),visible=ordered.slice(0,8);return visible.length<ordered.length&&visible.push([`+${String(ordered.length-visible.length)}`,ordered.slice(visible.length).reduce((total,[,count])=>total+count,0)]),Object.fromEntries(visible)}function projectActivityRows(projectionMode,matchingActivity,pageOptions,itemsById,projectProvenance){if(projectionMode==="digest"){const{rows,...page2}=paginateWindowQuery(buildActivityDigest(matchingActivity,itemsById),pageOptions);return{rows:{activity_digest:rows},compact:!1,page:page2}}const{rows:activity,...page}=paginateWindowQuery(matchingActivity,pageOptions);return projectionMode==="compact"?{rows:{compact_activity:formatCompactActivity(activity)},compact:!0,page}:projectionMode==="provenance"?{rows:{provenance_activity:activity.map(projectProvenance)},compact:!1,page}:{rows:{activity},compact:!1,page}}const _testOnly={parseNonEmptyFilter,parseRangeBound,includeByTimeWindow,limitEntries,readActivityString,normalizeActivityEntry,sortActivity,streamMayMatchWindow,streamCanOutrank,compareDeferredStreams,listHistoryFiles,buildActivityDigest,activityOperationCounts};async function runActivity(options,global2){const context=await resolveActivityRuntimeContext(global2),projectionMode=resolveActivityProjectionMode(options),clock=resolveWindowQueryClock("activity",options.after),filters=resolveActivityFilters(options,projectionMode,clock),prepared=await prepareActivityHistoryRead(context),provenanceDimensions=resolveHistoryProvenanceDimensions(context.settings.agent_identity.harness_signals),vocabulary=context.settings.agent_identity.identity_vocabulary,matchesProvenance=compileHistoryProvenanceMatcher({harness:filters.harness,agentInstance:filters.agentInstance,provenance:filters.provenance},vocabulary,provenanceDimensions),collected=await collectActivityEntries(context.pmRoot,prepared.historyDir,filters),matchingActivity=sortActivity(collected.entries).filter(matchesProvenance),projected=projectActivityRows(projectionMode,matchingActivity,{command:"activity",after:options.after,clock,limit:filters.limit,query:{pmRoot:context.pmRoot,projectionMode,filters:{...filters,limit:void 0,limitSource:void 0},matching_activity_digest:projectionMode==="digest"?fingerprintWindowRows(matchingActivity):void 0,vocabulary,provenanceDimensions}},prepared.itemsById,entry=>projectHistoryProvenance(entry,vocabulary,{itemId:entry.id}));return{...projected.rows,compact:projected.compact,projection:{mode:projectionMode,row_key:ACTIVITY_ROW_KEY_BY_MODE[projectionMode]},omission_receipt:resolveModePairedOutputOmissionReceipt("activity",projectionMode),...projected.page,window:{anchor:clock,from:filters.from??null,to:filters.to??null},limit:filters.limit??null,...projectionMode==="digest"?{activity_summary:{window:{from:filters.from,to:filters.to},event_count:matchingActivity.length,item_count:projected.page.total_count,author_count:new Set(matchingActivity.map(entry=>entry.author)).size,operation_counts:activityOperationCounts(matchingActivity)}}:{},...options.provenanceSummary===!0?{provenance_summary:summarizeHistoryProvenance(matchingActivity,vocabulary,provenanceDimensions)}:{},applied_bound:{kind:filters.limit===void 0?"unbounded":"limit",source:filters.limitSource,value:filters.limit??null},...collected.history_read?{history_read:collected.history_read}:{}}}async function readRecentActivity(options,global2){const context=await resolveActivityRuntimeContext(global2),clock=resolveWindowQueryClock("activity",void 0),filters=resolveActivityFilters({compact:!0,limit:String(options.limit)},"compact",clock),prepared=await prepareActivityHistoryRead(context),collected=await collectRecentActivityEntries(context.pmRoot,prepared.historyDir,filters,filters.limit);return{rows:formatCompactActivity(collected.entries),...collected.history_read?{history_read:collected.history_read}:{}}}export{_testOnly,normalizeActivityProjectionOptions,readRecentActivity,runActivity};
|
|
2
2
|
//# sourceMappingURL=activity.js.map
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Implements the pm context command surface and its agent-facing runtime behavior.
|
|
5
5
|
*/
|
|
6
|
-
import type{PmReadOutputMetadata}from "../read-output-contracts.js";import{type GlobalOptions,type RuntimeStatusRegistry}from "../runtime-primitives.js";import type{ContextDepth,ContextSectionName,ContextSettings,ItemMetadata,ItemStatus,PmSettings}from "../../types/index.js";import{type CalendarRow}from "./calendar.js";import{type CompactActivityEntry}from "./activity.js";import{type ContextRelevanceContributions,type ContextRecencyEvidence,type ContextRelevanceReport,type ContextRelevanceSignalName}from "../context-relevance.js";export{buildItemContextRelevanceCandidates}from "../context-relevance.js";import{type ContextPackingReport}from "../context-packing.js";import{type ContextSignalStoreReadResult}from "../context-signal-store.js";import{type WorkspaceMemoryRollup}from "../workspace-memory.js";
|
|
6
|
+
import type{PmReadOutputMetadata}from "../read-output-contracts.js";import{type GlobalOptions,type RuntimeStatusRegistry}from "../runtime-primitives.js";import type{ContextDepth,ContextSectionName,ContextSettings,ItemMetadata,ItemStatus,PmSettings}from "../../types/index.js";import{type CalendarRow}from "./calendar.js";import{type ActivityHistoryReadReceipt,type CompactActivityEntry,type RecentActivityResult}from "./activity.js";import{type ContextRelevanceContributions,type ContextRecencyEvidence,type ContextRelevanceReport,type ContextRelevanceSignalName}from "../context-relevance.js";export{buildItemContextRelevanceCandidates}from "../context-relevance.js";import{type ContextPackingReport}from "../context-packing.js";import{type ContextSignalStoreReadResult}from "../context-signal-store.js";import{type WorkspaceMemoryRollup}from "../workspace-memory.js";
|
|
7
7
|
/** Supported values accepted by the context output contract. */
|
|
8
8
|
export declare const CONTEXT_OUTPUT_VALUES:readonly["markdown","toon","json","ndjson"];
|
|
9
9
|
/** Restricts context output format values accepted by command, SDK, and storage contracts. */
|
|
@@ -237,7 +237,13 @@ scope?:"matching_items";
|
|
|
237
237
|
/** Counts for the bounded focus selection, separate from the matching population. */
|
|
238
238
|
returned_focus?:{active_items:number;in_progress:number;open:number;blocked:number;};
|
|
239
239
|
/** Optional per-section role/blocker codes for projected rows: i/I in progress, o/O open; uppercase is blocked. */
|
|
240
|
-
focus_row_states?:Record<string,string>;active_items:number;
|
|
240
|
+
focus_row_states?:Record<string,string>;active_items:number;
|
|
241
|
+
/**
|
|
242
|
+
* Items in `workflow.in_progress_status`, whatever role it carries, so both
|
|
243
|
+
* advisories below count subsets of it (GH-1756). It equals
|
|
244
|
+
* `active_items - open` while that status carries the `active` role.
|
|
245
|
+
*/
|
|
246
|
+
in_progress:number;
|
|
241
247
|
/** In-progress items with no assignee, so no live claim; omitted when zero (GH-1724). */
|
|
242
248
|
in_progress_unowned?:number;
|
|
243
249
|
/** In-progress items idle past `mutation_guard.stale_in_progress_hours`, owned or not; omitted when zero (GH-1724). */
|
|
@@ -270,6 +276,8 @@ agenda:{summary:ContextAgendaSummary;events:ContextAgendaEvent[];};
|
|
|
270
276
|
hierarchy?:HierarchyNode[];
|
|
271
277
|
/** Value that configures or reports activity for this contract. */
|
|
272
278
|
activity?:CompactActivityEntry[];
|
|
279
|
+
/** Present only when a tracker that keeps derived stream bounds could not bound the activity section (GH-1664). */
|
|
280
|
+
activity_history_read?:ActivityHistoryReadReceipt;
|
|
273
281
|
/** Value that configures or reports progress for this contract. */
|
|
274
282
|
progress?:ProgressEntry[];
|
|
275
283
|
/** Value that configures or reports blockers for this contract. */
|
|
@@ -382,7 +390,9 @@ export declare function toContextFocusItem(item:ItemMetadata,statusRegistry?:Run
|
|
|
382
390
|
/** Combines warning groups into a stable, duplicate-free lexical ordering. */
|
|
383
391
|
export declare function mergeSortedWarnings(...warningGroups:Array<string[]|undefined>):string[];declare function filterTerminalCalendarEvents(events:CalendarRow[],statusRegistry:RuntimeStatusRegistry):CalendarRow[];declare function buildHierarchy(allItems:ItemMetadata[],activeItems:ItemMetadata[],statusRegistry:RuntimeStatusRegistry,limit:number):HierarchyNode[];declare function collectDescendants(parentId:string,childrenByParent:Map<string,ItemMetadata[]>):ItemMetadata[];
|
|
384
392
|
/** Public contract for test only, shared by SDK and presentation-layer consumers. */
|
|
385
|
-
export declare const _testOnly:{buildActivity:typeof buildActivity;buildBlockers:typeof buildBlockers;buildChildrenByParent:typeof buildChildrenByParent;buildHierarchy:typeof buildHierarchy;buildHotFiles:typeof buildHotFiles;buildProgress:typeof buildProgress;buildRecentlyCreated:typeof buildRecentlyCreated;buildStaleness:typeof buildStaleness;buildTestHealth:typeof buildTestHealth;buildUnparented:typeof buildUnparented;buildWorkload:typeof buildWorkload;collectDescendants:typeof collectDescendants;collectSubtreeIds:typeof collectSubtreeIds;compareCriticalItems:typeof compareCriticalItems;compareOptionalDeadline:typeof compareOptionalDeadline;compareOptionalOrder:typeof compareOptionalOrder;completionPct:typeof completionPct;dateTokenForTimestamp:typeof dateTokenForTimestamp;filterTerminalCalendarEvents:typeof filterTerminalCalendarEvents;formatAgendaLine:typeof formatAgendaLine;isBlockedStatus:typeof isBlockedStatus;isClosedStatus:typeof isClosedStatus;isInProgressStatus:typeof isInProgressStatus;isOpenStatus:typeof isOpenStatus;mergeSortedWarnings:typeof mergeSortedWarnings;normalizedParentId:typeof normalizedParentId;parseActivityLimit:typeof parseActivityLimit;parseContextLimit:typeof parseContextLimit;resolveContextLimitAtScale:typeof resolveContextLimitAtScale;parseContextParent:typeof parseContextParent;parseContextTimestampMs:typeof parseContextTimestampMs;parseStaleThresholdDays:typeof parseStaleThresholdDays;sortableTimestamp:typeof sortableTimestamp;statusRank:typeof statusRank;stripListProjectionFlags:typeof stripListProjectionFlags;summarizeAgenda:typeof summarizeAgenda;toContextFocusItem:typeof toContextFocusItem;};
|
|
393
|
+
export declare const _testOnly:{buildActivity:typeof buildActivity;buildBlockers:typeof buildBlockers;buildChildrenByParent:typeof buildChildrenByParent;buildHierarchy:typeof buildHierarchy;buildHotFiles:typeof buildHotFiles;buildProgress:typeof buildProgress;buildRecentlyCreated:typeof buildRecentlyCreated;buildStaleness:typeof buildStaleness;buildTestHealth:typeof buildTestHealth;buildUnparented:typeof buildUnparented;buildWorkload:typeof buildWorkload;collectDescendants:typeof collectDescendants;collectSubtreeIds:typeof collectSubtreeIds;compareCriticalItems:typeof compareCriticalItems;compareOptionalDeadline:typeof compareOptionalDeadline;compareOptionalOrder:typeof compareOptionalOrder;completionPct:typeof completionPct;dateTokenForTimestamp:typeof dateTokenForTimestamp;filterTerminalCalendarEvents:typeof filterTerminalCalendarEvents;formatAgendaLine:typeof formatAgendaLine;isBlockedStatus:typeof isBlockedStatus;isClosedStatus:typeof isClosedStatus;isInProgressStatus:typeof isInProgressStatus;isOpenStatus:typeof isOpenStatus;mergeSortedWarnings:typeof mergeSortedWarnings;normalizedParentId:typeof normalizedParentId;parseActivityLimit:typeof parseActivityLimit;parseContextLimit:typeof parseContextLimit;resolveContextLimitAtScale:typeof resolveContextLimitAtScale;parseContextParent:typeof parseContextParent;parseContextTimestampMs:typeof parseContextTimestampMs;parseStaleThresholdDays:typeof parseStaleThresholdDays;sortableTimestamp:typeof sortableTimestamp;statusRank:typeof statusRank;stripListProjectionFlags:typeof stripListProjectionFlags;summarizeAgenda:typeof summarizeAgenda;toContextFocusItem:typeof toContextFocusItem;};
|
|
394
|
+
/** Newest compact rows only: the section needs no page cursor or archive-wide totals. */
|
|
395
|
+
declare function buildActivity(activityLimit:number,global:GlobalOptions):Promise<RecentActivityResult>;declare function buildProgress(allItems:ItemMetadata[],activeItems:ItemMetadata[],blockedIds:ReadonlySet<string>,statusRegistry:RuntimeStatusRegistry,limit:number):ProgressEntry[];declare function buildBlockers(blockedItems:ItemMetadata[],fullCorpus:ItemMetadata[],statusRegistry:RuntimeStatusRegistry,limit:number):BlockerEntry[];declare function buildHotFiles(activeItems:ItemMetadata[],limit:number):HotFile[];declare function buildWorkload(activeItems:ItemMetadata[],statusRegistry:RuntimeStatusRegistry,limit:number):WorkloadEntry[];declare function buildStaleness(allNonTerminal:ItemMetadata[],staleThresholdDays:number,now:string,limit:number):StaleEntry[];declare function buildRecentlyCreated(allNonTerminal:ItemMetadata[],statusRegistry:RuntimeStatusRegistry,childrenByParent:Map<string,ItemMetadata[]>,limit:number):RecentContextItem[];declare function buildUnparented(allNonTerminal:ItemMetadata[],statusRegistry:RuntimeStatusRegistry,childrenByParent:Map<string,ItemMetadata[]>,limit:number):ContextFocusItem[];
|
|
386
396
|
/** Count linked tests and stored runs across the complete matching active population. */
|
|
387
397
|
declare function buildTestHealth(activeItems:ItemMetadata[]):TestHealthSummary;declare function formatAgendaLine(event:ContextAgendaEvent):string;
|
|
388
398
|
/** Implements render context markdown for the public runtime surface of this module. */
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7db8326c-9354-529d-9977-42e3fe8881f1")}catch{}})();import{scanInProgressWork}from"../governance/stale-work.js";import{SETTINGS_DEFAULTS,EXIT_CODE,PmCliError,compareTimestampStrings,nowIso,isTerminalStatus,normalizeStatusForRegistry,normalizeStatusInput,resolveRuntimeStatusRegistry,resolvePmRoot,readSettings,resolveAuthor,discoverExtensions,resolveItemTypeRegistry}from"../runtime-primitives.js";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{collectDependencyBlockedIds,resolveItemBlockers,resolveItemExecutionRole,computeActionabilityReport}from"../actionability.js";import{CONTEXT_DEPTH_VALUES,CONTEXT_SECTION_VALUES}from"../../types/index.js";import{parseIntegerLimit}from"./parsers.js";import{runCalendar}from"./calendar.js";import{runList}from"./list.js";import{runActivity}from"./activity.js";import{scoreContextCandidatesWithActiveExtensions}from"../context-relevance.js";import{buildItemContextRelevanceCandidates}from"../context-relevance.js";import{createQueryFingerprint,encodeQueryCursor,resolveQueryCursorStart,selectCursorSemanticOptions}from"../pagination.js";import{rememberReadOutputFocusRows,refreshReadOutputDeliveredCounts}from"../read-output-rows.js";import{CONTEXT_FLAG_CONTRACTS}from"../cli-contracts/flag-contracts.js";import{packContextCandidates}from"../context-packing.js";import{attachContextUsageServingReceipt,collectContextUsageDeliveredItemIds,readContextUsageAffinity,recordContextUsageServing}from"../context-usage.js";import{readWorkspaceContextSignals}from"../context-signal-store.js";import{readWorkspaceMemory,selectWorkspaceMemory}from"../workspace-memory.js";import{detectAgentIdentity}from"../../core/shared/author.js";import{readSessionState,semanticAttributionKey}from"../../core/session/session-state.js";import{semanticAttributionAffinity}from"../context/semantic-session-attribution.js";const CONTEXT_OUTPUT_VALUES=["markdown","toon","json","ndjson"],HIGH_LEVEL_TYPES=new Set(["Epic","Feature"]),DEFAULT_CONTEXT_LIMIT=10,CONTEXT_SCALE_THRESHOLD=1e4,STANDARD_SECTIONS=["hierarchy","activity","progress","recently_created","unparented","workload"],DEEP_SECTIONS=[...STANDARD_SECTIONS,"blockers","files","staleness","tests"],LEADING_HYPHEN_DATE=/^(\d{4})-(\d{2})-(\d{2})/,LEADING_COMPACT_DATE=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/,COMPACT_DATE=/^(\d{4})(\d{2})(\d{2})$/,COMPACT_DATETIME=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?(Z|[+-]\d{2}:?\d{2})?$/i;function parseOutputFormat(raw){if(!raw)return;const normalized=raw.trim().toLowerCase();if(!CONTEXT_OUTPUT_VALUES.includes(normalized))throw new PmCliError("Context format must be one of markdown|toon|json|ndjson",EXIT_CODE.USAGE);return normalized}const FOCUS_PROJECTION_FIELDS=new Set(["id","title","type","status","priority","order","deadline","assignee","tags","tags_inherited","updated_at","parent","children_total","children_closed","completion_pct","blocked","blocker_ids","created_at"]);function parseContextFocusFields(raw){if(raw===void 0)return;const fields=[];for(const token of raw.split(",")){const normalized=token.trim().toLowerCase();if(normalized.length!==0){if(!FOCUS_PROJECTION_FIELDS.has(normalized))throw new PmCliError(`Context --fields value not projectable: ${normalized} (valid: ${[...FOCUS_PROJECTION_FIELDS].join(", ")})`,EXIT_CODE.USAGE);fields.includes(normalized)||fields.push(normalized)}}if(fields.length===0)throw new PmCliError("Context --fields requires at least one field name",EXIT_CODE.USAGE);return fields}function projectContextFocusRows(rows,fields){return rows.map(row=>{const projected={},source=row;for(const field of fields)projected[field]=source[field]??null;return projected})}function resolveContextOutputFormat(options,global2){const commandFormat=parseOutputFormat(options.format);if(global2.json&&commandFormat&&commandFormat!=="json"&&commandFormat!=="ndjson")throw new PmCliError("Cannot combine --json with --format markdown|toon",EXIT_CODE.USAGE);return global2.json?commandFormat==="ndjson"?"ndjson":"json":commandFormat??"toon"}function parseContextLimit(raw,depth){return parseIntegerLimit(raw,"--limit")??(depth==="full"?Number.MAX_SAFE_INTEGER:DEFAULT_CONTEXT_LIMIT)}function resolveContextTokenBudget(raw,fallback){if(raw===void 0)return fallback;const parsed=typeof raw=="number"?raw:Number(raw);if(!Number.isInteger(parsed)||parsed<1)throw new PmCliError("--token-budget must be a positive integer",EXIT_CODE.USAGE);return parsed}function resolveContextLimitAtScale(limit,itemCount){return itemCount>=CONTEXT_SCALE_THRESHOLD&&limit===Number.MAX_SAFE_INTEGER?DEFAULT_CONTEXT_LIMIT:limit}function parseContextDepth(raw,settings){if(!raw)return settings.default_depth;const normalized=raw.trim().toLowerCase();if(!CONTEXT_DEPTH_VALUES.includes(normalized))throw new PmCliError(`Context --depth must be one of ${CONTEXT_DEPTH_VALUES.join("|")}`,EXIT_CODE.USAGE);return normalized}function parseContextSections(raw,depth,settings){if(raw&&raw.length>0){const sections=[];for(const value of raw){const normalized=value.trim().toLowerCase();if(!CONTEXT_SECTION_VALUES.includes(normalized))throw new PmCliError(`Context --section must be one of ${CONTEXT_SECTION_VALUES.join("|")}`,EXIT_CODE.USAGE);sections.includes(normalized)||sections.push(normalized)}return sections}return depth==="brief"?[]:depth==="full"?[...CONTEXT_SECTION_VALUES]:(depth==="deep"?DEEP_SECTIONS:STANDARD_SECTIONS).filter(section=>settings.sections[section])}function parseActivityLimit(raw,settings){return raw?parseIntegerLimit(raw,"--activity-limit")??settings.activity_limit:settings.activity_limit}function parseStaleThresholdDays(raw,settings){if(!raw)return settings.stale_threshold_days;const trimmed=raw.trim().toLowerCase(),match=/^(\d+)d?$/.exec(trimmed);if(!match)throw new PmCliError("--stale-threshold must be a number of days (e.g. 7 or 7d)",EXIT_CODE.USAGE);const days=parseInt(match[1],10);if(days<=0)throw new PmCliError("--stale-threshold must be positive",EXIT_CODE.USAGE);return days}function statusRank(status,statusRegistry){const normalizedStatus=normalizeStatusForRegistry(status,statusRegistry),blockedStatus=normalizeStatusInput("blocked",statusRegistry),draftStatus=normalizeStatusInput("draft",statusRegistry);return normalizedStatus===statusRegistry.in_progress_status?0:statusRegistry.active_statuses.has(normalizedStatus)?1:blockedStatus&&normalizedStatus===blockedStatus?2:draftStatus&&normalizedStatus===draftStatus?3:statusRegistry.blocked_statuses.has(normalizedStatus)?5:statusRegistry.terminal_statuses.has(normalizedStatus)?7:6}function isClosedStatus(status,statusRegistry){const closeStatus=normalizeStatusInput("closed",statusRegistry);return normalizeStatusForRegistry(status,statusRegistry)===closeStatus}function isInProgressStatus(status,statusRegistry){return normalizeStatusForRegistry(status,statusRegistry)===statusRegistry.in_progress_status}function isOpenStatus(status,statusRegistry){const normalizedStatus=normalizeStatusForRegistry(status,statusRegistry);return normalizedStatus!==statusRegistry.in_progress_status&&statusRegistry.active_statuses.has(normalizedStatus)}function isBlockedStatus(status,statusRegistry){return statusRegistry.blocked_statuses.has(normalizeStatusForRegistry(status,statusRegistry))}const LIST_PROJECTION_FLAGS=["compact","brief","fields","includeBody","include_body","parent"];function stripListProjectionFlags(options){const copy={...options};for(const key of LIST_PROJECTION_FLAGS)delete copy[key];return copy}function collectSubtreeIds(corpus,parentId){const target=parentId.trim().toLowerCase(),anchor=corpus.find(item=>item.id.trim().toLowerCase()===target);if(!anchor)return{ids:new Set,found:!1};const childrenByParent=buildChildrenByParent(corpus),descendants=collectDescendants(anchor.id,childrenByParent);return{ids:new Set([anchor.id,...descendants.map(item=>item.id)].map(id=>id.trim().toLowerCase())),found:!0}}function parseContextParent(raw){if(raw===void 0)return;const trimmed=raw.trim();if(trimmed.length===0)throw new PmCliError("Context --parent requires an item id",EXIT_CODE.USAGE);return trimmed}function compareOptionalOrder(left,right){const leftValue=left??null,rightValue=right??null;return leftValue===null&&rightValue===null?0:leftValue===null?1:rightValue===null?-1:leftValue-rightValue}function compareOptionalDeadline(left,right){const leftValue=left??null,rightValue=right??null;return leftValue===null&&rightValue===null?0:leftValue===null?1:rightValue===null?-1:compareTimestampStrings(leftValue,rightValue)}function daysInUtcMonth(year,monthIndex){return new Date(Date.UTC(year,monthIndex+1,0)).getUTCDate()}function hasNoInvalidDatePrefix(value){const match=LEADING_HYPHEN_DATE.exec(value)??LEADING_COMPACT_DATE.exec(value);if(!match)return!0;const year=Number.parseInt(match[1],10),month=Number.parseInt(match[2],10),day=Number.parseInt(match[3],10);return month>=1&&month<=12&&day>=1&&day<=daysInUtcMonth(year,month-1)}function normalizeTimestampCandidate(value){const compactDate=COMPACT_DATE.exec(value);if(compactDate)return`${compactDate[1]}-${compactDate[2]}-${compactDate[3]}`;const compactDateTime=COMPACT_DATETIME.exec(value);if(compactDateTime){const[,year,month,day,hour,minute,secondRaw,offsetRaw]=compactDateTime,second=secondRaw?`:${secondRaw}`:"",offset=offsetRaw&&offsetRaw.length===5&&offsetRaw!=="Z"?`${offsetRaw.slice(0,3)}:${offsetRaw.slice(3)}`:offsetRaw??"";return`${year}-${month}-${day}T${hour}:${minute}${second}${offset}`}return value}function parseContextTimestampMs(value){if(typeof value!="string")return Number.NaN;const trimmed=value.trim();if(trimmed.length===0||!hasNoInvalidDatePrefix(trimmed))return Number.NaN;const parsed=Date.parse(normalizeTimestampCandidate(trimmed));return Number.isFinite(parsed)?parsed:Number.NaN}function sortableTimestamp(value){const parsed=parseContextTimestampMs(value);return Number.isFinite(parsed)?new Date(parsed).toISOString():""}function dateTokenForTimestamp(value){const parsed=parseContextTimestampMs(value);return Number.isFinite(parsed)?new Date(parsed).toISOString().slice(0,10):"unknown"}function normalizedParentId(value){if(typeof value!="string")return null;const trimmed=value.trim();return trimmed.length>0?trimmed:null}function compareCriticalItems(left,right,statusRegistry){const byStatus=statusRank(left.status,statusRegistry)-statusRank(right.status,statusRegistry);if(byStatus!==0)return byStatus;const byPriority=left.priority-right.priority;if(byPriority!==0)return byPriority;const byOrder=compareOptionalOrder(left.order,right.order);if(byOrder!==0)return byOrder;const byDeadline=compareOptionalDeadline(left.deadline,right.deadline);if(byDeadline!==0)return byDeadline;const byUpdated=compareTimestampStrings(sortableTimestamp(right.updated_at),sortableTimestamp(left.updated_at)),byId=left.id.localeCompare(right.id);return byUpdated!==0?byUpdated:byId}function estimateJsonTokens(value){return Math.max(1,Math.ceil(Buffer.byteLength(JSON.stringify(value),"utf8")/4))}function packRankedContextItems(report,tokenBudget,requiredIds=new Set,profile="context"){return packContextCandidates(report.ranked.map(entry=>({id:entry.id,item:entry.item,rank:entry.rank,score:entry.score,required:requiredIds.has(entry.id),cluster:entry.item.parent?.trim()||entry.item.type,token_costs:{identity:estimateJsonTokens({id:entry.id,title:entry.item.title}),summary:estimateJsonTokens({id:entry.id,title:entry.item.title,type:entry.item.type,status:entry.item.status,priority:entry.item.priority,parent:entry.item.parent}),full:estimateJsonTokens(entry.item)}})),{tokenBudget,profile,latencyBudgetMs:25})}function toContextPackingSummary(report){return{...report,included:report.included.map(entry=>({id:entry.id,projection:entry.projection,tokens:entry.tokens}))}}function toContextRankingSummary(report,featureStore,servedItemIds){const ranked=servedItemIds===void 0?report.ranked:report.ranked.filter(entry=>servedItemIds.has(entry.id));return{model:report.model,available_signals:report.available_signals,items:ranked.map(entry=>({id:entry.id,rank:entry.rank,baseline_rank:entry.baseline_rank,score:entry.score,contributions:entry.contributions,...entry.signal_provenance===void 0?{}:{recency:entry.signal_provenance.recency}})),candidate_count:report.ranked.length,omitted_count:report.ranked.length-ranked.length,...featureStore?{feature_store:{source:featureStore.snapshot.source,cache_status:featureStore.cache_status,source_cursor:featureStore.snapshot.source_cursor,generated_at:featureStore.snapshot.generated_at}}:{}}}function completionPct(closed,total){return total>0?Math.round(closed*100/total):0}function buildChildrenByParent(allItems){const childrenByParent=new Map;for(const item of allItems){const parent=normalizedParentId(item.parent);if(!parent)continue;const children=childrenByParent.get(parent)??[];children.push(item),childrenByParent.set(parent,children)}return childrenByParent}function toContextFocusItem(item,statusRegistry,childrenByParent){const focus={id:item.id,title:item.title,type:item.type,status:item.status,priority:item.priority,order:item.order??null,deadline:item.deadline??null,assignee:item.assignee??null,tags:Array.isArray(item.tags)?[...item.tags]:[],updated_at:item.updated_at,parent:normalizedParentId(item.parent)};if(statusRegistry&&childrenByParent){const descendants=collectDescendants(item.id,childrenByParent),total=descendants.length;if(total>0){const closed=descendants.filter(desc=>isClosedStatus(desc.status,statusRegistry)).length;focus.children_total=total,focus.children_closed=closed,focus.completion_pct=completionPct(closed,total)}}return focus}function summarizeAgenda(events){let deadlines=0,reminders=0,scheduled=0;const itemIds=new Set;for(const event of events){if(itemIds.add(event.item_id),event.kind==="deadline"){deadlines+=1;continue}if(event.kind==="reminder"){reminders+=1;continue}scheduled+=1}return{events:events.length,items:itemIds.size,deadlines,reminders,scheduled}}function mergeSortedWarnings(...warningGroups){return[...new Set(warningGroups.flatMap(group=>group??[]))].sort((left,right)=>left.localeCompare(right))}function filterTerminalCalendarEvents(events,statusRegistry){return events.filter(event=>!statusRegistry.terminal_statuses.has(normalizeStatusForRegistry(event.item_status,statusRegistry)))}function buildHierarchy(allItems,activeItems,statusRegistry,limit){const itemMap=new Map;for(const item of allItems)itemMap.set(item.id,item);const childrenByParent=buildChildrenByParent(allItems),activeHighLevelIds=new Set(activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)).map(item=>item.id)),nodes=[];for(const parentId of activeHighLevelIds){const parent=itemMap.get(parentId);if(!parent)continue;const allDescendants=collectDescendants(parentId,childrenByParent),childItems=childrenByParent.get(parentId)??[];let closedCount=0,openCount=0,inProgressCount=0,blockedCount=0;for(const desc of allDescendants)isClosedStatus(desc.status,statusRegistry)?closedCount++:isInProgressStatus(desc.status,statusRegistry)?inProgressCount++:isBlockedStatus(desc.status,statusRegistry)?blockedCount++:isOpenStatus(desc.status,statusRegistry)&&openCount++;const children=childItems.sort((a,b)=>compareCriticalItems(a,b,statusRegistry)).slice(0,limit).map(child=>{const grandchildren=collectDescendants(child.id,childrenByParent),gcClosed=grandchildren.filter(gc=>isClosedStatus(gc.status,statusRegistry)).length;return{id:child.id,title:child.title,type:child.type,status:child.status,children_total:grandchildren.length,children_closed:gcClosed}});nodes.push({id:parent.id,title:parent.title,type:parent.type,status:parent.status,children_total:allDescendants.length,children_closed:closedCount,children_open:openCount,children_in_progress:inProgressCount,children_blocked:blockedCount,children})}return nodes.sort((a,b)=>{const aParent=itemMap.get(a.id),bParent=itemMap.get(b.id);return compareCriticalItems(aParent,bParent,statusRegistry)}).slice(0,limit)}function collectDescendants(parentId,childrenByParent){const result=[],stack=[parentId],visited=new Set;for(;stack.length>0;){const current=stack.pop();if(visited.has(current))continue;visited.add(current);const children=childrenByParent.get(current)??[];for(const child of children)result.push(child),stack.push(child.id)}return result}const _testOnly={buildActivity,buildBlockers,buildChildrenByParent,buildHierarchy,buildHotFiles,buildProgress,buildRecentlyCreated,buildStaleness,buildTestHealth,buildUnparented,buildWorkload,collectDescendants,collectSubtreeIds,compareCriticalItems,compareOptionalDeadline,compareOptionalOrder,completionPct,dateTokenForTimestamp,filterTerminalCalendarEvents,formatAgendaLine,isBlockedStatus,isClosedStatus,isInProgressStatus,isOpenStatus,mergeSortedWarnings,normalizedParentId,parseActivityLimit,parseContextLimit,resolveContextLimitAtScale,parseContextParent,parseContextTimestampMs,parseStaleThresholdDays,sortableTimestamp,statusRank,stripListProjectionFlags,summarizeAgenda,toContextFocusItem};async function buildActivity(activityLimit,global2){return(await runActivity({compact:!0,limit:String(activityLimit)},global2)).compact_activity??[]}function buildProgress(allItems,activeItems,blockedIds,statusRegistry,limit){const childrenByParent=new Map;for(const item of allItems){if(!item.parent)continue;const children=childrenByParent.get(item.parent)??[];children.push(item),childrenByParent.set(item.parent,children)}const activeHighLevel=activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)),entries=[];for(const parent of activeHighLevel){const descendants=collectDescendants(parent.id,childrenByParent),total=descendants.length;if(total===0)continue;let closed=0,open=0,inProgress=0,blocked=0;for(const desc of descendants)isClosedStatus(desc.status,statusRegistry)?closed++:blockedIds.has(desc.id.trim().toLowerCase())?blocked++:isInProgressStatus(desc.status,statusRegistry)?inProgress++:isOpenStatus(desc.status,statusRegistry)&&open++;entries.push({id:parent.id,title:parent.title,type:parent.type,total,closed,open,in_progress:inProgress,blocked,completion_pct:completionPct(closed,total)})}return entries.sort((a,b)=>a.completion_pct-b.completion_pct).slice(0,limit)}function buildBlockers(blockedItems,fullCorpus,statusRegistry,limit){const itemsById=new Map(fullCorpus.map(item=>[item.id.trim().toLowerCase(),item]));return blockedItems.slice(0,limit).map(item=>{const blockers=resolveItemBlockers(item,itemsById,statusRegistry),blockedBy=blockers.find(blocker=>!blocker.resolved)?.id??blockers[0]?.id??null,blockerItem=blockedBy?itemsById.get(blockedBy.trim().toLowerCase()):void 0;return{id:item.id,title:item.title,blocked_by:blockedBy,blocked_by_title:blockerItem?.title??null,blocked_by_status:blockerItem?.status??null,blocked_reason:item.blocked_reason??null,unblock_note:item.unblock_note??null}})}function buildHotFiles(activeItems,limit){const fileMap=new Map;for(const item of activeItems)for(const file of item.files??[]){const existing=fileMap.get(file.path)??new Set;existing.add(item.id),fileMap.set(file.path,existing)}return[...fileMap.entries()].map(([filePath,itemIds])=>({path:filePath,references:itemIds.size,items:[...itemIds].sort()})).sort((a,b)=>b.references-a.references).slice(0,limit)}function buildWorkload(activeItems,statusRegistry,limit){const groups=new Map;for(const item of activeItems){const key=item.assignee??null,existing=groups.get(key)??[];existing.push(item),groups.set(key,existing)}return[...groups.entries()].map(([assignee,items])=>({assignee,active:items.length,in_progress:items.filter(item=>isInProgressStatus(item.status,statusRegistry)).length,items:items.map(item=>item.id).sort()})).sort((a,b)=>b.active-a.active).slice(0,limit)}function buildStaleness(allNonTerminal,staleThresholdDays,now,limit){const cutoffMs=new Date(now).getTime()-staleThresholdDays*24*60*60*1e3;return allNonTerminal.filter(item=>new Date(item.updated_at).getTime()<cutoffMs).map(item=>({id:item.id,title:item.title,status:item.status,updated_at:item.updated_at,stale_days:Math.floor((new Date(now).getTime()-new Date(item.updated_at).getTime())/(1440*60*1e3))})).sort((a,b)=>b.stale_days-a.stale_days).slice(0,limit)}function buildRecentlyCreated(allNonTerminal,statusRegistry,childrenByParent,limit){return allNonTerminal.map(item=>({item,sortKey:sortableTimestamp(item.created_at)})).sort((left,right)=>{const byCreated=compareTimestampStrings(right.sortKey,left.sortKey);return byCreated!==0?byCreated:left.item.id.localeCompare(right.item.id)}).slice(0,limit).map(({item})=>({...toContextFocusItem(item,statusRegistry,childrenByParent),created_at:item.created_at}))}function buildUnparented(allNonTerminal,statusRegistry,childrenByParent,limit){return allNonTerminal.filter(item=>!normalizedParentId(item.parent)&&!HIGH_LEVEL_TYPES.has(item.type)).sort((left,right)=>compareCriticalItems(left,right,statusRegistry)).slice(0,limit).map(item=>toContextFocusItem(item,statusRegistry,childrenByParent))}function buildTestHealth(activeItems){let itemsWithTests=0,itemsWithRecentRuns=0,passed=0,failed=0,skipped=0;const itemsFailing=[];for(const item of activeItems){(item.tests??[]).length>0&&itemsWithTests++;const runs=item.test_runs??[];if(runs.length>0){itemsWithRecentRuns++;let itemHasFailure=!1;for(const run of runs)passed+=run.passed??0,failed+=run.failed??0,skipped+=run.skipped??0,(run.failed??0)>0&&(itemHasFailure=!0);itemHasFailure&&itemsFailing.push(item.id)}}return{scope:"matching_active_items",total_items:activeItems.length,items_with_tests:itemsWithTests,items_with_recent_runs:itemsWithRecentRuns,recent_runs:{passed,failed,skipped},items_failing:itemsFailing.sort()}}function formatClock(timestamp){return`${new Date(timestamp).toISOString().slice(11,16)}Z`}function formatFocusLine(item){const orderToken=item.order===null?"-":String(item.order),deadlineToken=item.deadline??"-",parentToken=item.parent?` parent:${item.parent}`:"",progressToken=item.children_total!==void 0&&item.children_closed!==void 0&&item.completion_pct!==void 0?` children:${item.children_closed}/${item.children_total} done:${item.completion_pct}%`:"",blockedToken=item.blocked===!0?` blocked:${item.blocker_ids?.join(",")||"lifecycle"}`:"";return`${item.id} p${item.priority} ${item.status} ${item.type} order:${orderToken} deadline:${deadlineToken}${parentToken}${progressToken}${blockedToken} ${item.title}`}function formatProjectedFocusLine(item,fields){const source=item;return fields.map(field=>{const value=source[field];return Array.isArray(value)?`${field}:${value.join(",")}`:`${field}:${value??"-"}`}).join(" ")}function formatAgendaLine(event){if("reference_only"in event){const suffix=event.kind==="reminder"?` \u2014 ${event.reminder_text??"reminder"}`:event.kind==="event"?` \u2014 ${event.event_title??"event"}${event.event_recurring?" (recurring)":""}`:"";return`${formatClock(event.at)} [${event.kind}] ${event.item_id} (see focus item)${suffix}`}const base=`${formatClock(event.at)} [${event.kind}] ${event.item_id} p${event.item_priority} ${event.item_status} ${event.item_title}`;if(event.kind==="reminder")return`${base} \u2014 ${event.reminder_text}`;if(event.kind==="event"){const recurringSuffix=event.event_recurring?" (recurring)":"",title=event.event_title??event.item_title;return`${base} \u2014 ${title}${recurringSuffix}`}return base}function pushContextFocusSection(lines,title,rows,emptyText,renderFocus){if(lines.push(`## ${title}`),rows.length===0)lines.push(emptyText);else for(const item of rows)lines.push(`- ${renderFocus(item)}`);lines.push("")}function pushBlockedFallbackSection(lines,result,renderFocus){if(result.blocked_fallback.length!==0){lines.push("## Blocked fallback");for(const item of result.blocked_fallback)lines.push(`- ${renderFocus(item)}`);lines.push("")}}function pushAgendaSection(lines,result){if(lines.push("## Agenda"),lines.push(`- events: ${result.agenda.summary.events} (deadlines: ${result.agenda.summary.deadlines}, reminders: ${result.agenda.summary.reminders}, scheduled: ${result.agenda.summary.scheduled})`),result.agenda.events.length===0)lines.push("No agenda events matched the selected filters.");else for(const event of result.agenda.events)lines.push(`- ${formatAgendaLine(event)}`);lines.push("")}function pushHierarchySection(lines,result){if(!(!result.hierarchy||result.hierarchy.length===0)){lines.push("## Hierarchy");for(const node of result.hierarchy){const pct=completionPct(node.children_closed,node.children_total);lines.push(`- ${node.id} ${node.type} ${node.status} "${node.title}" [${node.children_closed}/${node.children_total} done ${pct}%]`);for(const child of node.children){const cpct=completionPct(child.children_closed,child.children_total);lines.push(` - ${child.id} ${child.type} ${child.status} "${child.title}" [${child.children_closed}/${child.children_total} done ${cpct}%]`)}}lines.push("")}}function pushProgressSection(lines,result){if(!(!result.progress||result.progress.length===0)){lines.push("## Progress");for(const entry of result.progress)lines.push(`- ${entry.id} "${entry.title}" ${entry.completion_pct}% (${entry.closed}/${entry.total} closed, ${entry.in_progress} wip, ${entry.open} open, ${entry.blocked} blocked)`);lines.push("")}}function pushRecentlyCreatedSection(lines,result,focusFields,renderFocus){if(!(!result.recently_created||result.recently_created.length===0)){lines.push("## Recently created");for(const item of result.recently_created)lines.push(focusFields?`- ${renderFocus(item)}`:`- ${dateTokenForTimestamp(item.created_at)} ${formatFocusLine(item)}`);lines.push("")}}function pushUnparentedSection(lines,result,renderFocus){if(!(!result.unparented||result.unparented.length===0)){lines.push("## Unparented");for(const item of result.unparented)lines.push(`- ${renderFocus(item)}`);lines.push("")}}function pushActivitySection(lines,result){if(!(!result.activity||result.activity.length===0)){lines.push("## Recent activity");for(const entry of result.activity){const msg=entry.msg?` ${entry.msg}`:"";lines.push(`- ${entry.ts.slice(0,16)}Z ${entry.id} ${entry.op} by:${entry.author}${msg}`)}lines.push("")}}function pushBlockersSection(lines,result){if(!(!result.blockers||result.blockers.length===0)){lines.push("## Blockers");for(const entry of result.blockers){const by=entry.blocked_by?`blocked_by:${entry.blocked_by}(${entry.blocked_by_status??"?"})`:"blocked_by:-",reason=entry.blocked_reason?` reason:"${entry.blocked_reason}"`:"",note=entry.unblock_note?` unblock:"${entry.unblock_note}"`:"";lines.push(`- ${entry.id} "${entry.title}" ${by}${reason}${note}`)}lines.push("")}}function pushFilesSection(lines,result){if(!(!result.files||result.files.length===0)){lines.push("## Hot files");for(const file of result.files)lines.push(`- ${file.path} refs:${file.references} items:[${file.items.join(",")}]`);lines.push("")}}function pushWorkloadSection(lines,result){if(!(!result.workload||result.workload.length===0)){lines.push("## Workload");for(const entry of result.workload){const who=entry.assignee??"(unassigned)";lines.push(`- ${who} active:${entry.active} wip:${entry.in_progress} items:[${entry.items.join(",")}]`)}lines.push("")}}function pushStalenessSection(lines,result){if(!(!result.staleness||result.staleness.length===0)){lines.push("## Stale items");for(const entry of result.staleness)lines.push(`- ${entry.id} ${entry.status} stale:${entry.stale_days}d last:${entry.updated_at.slice(0,10)} "${entry.title}"`);lines.push("")}}function boundedTestHealthFailures(tests,limit,tokenBudget){const included=[];let usedTokens=0;for(const id of tests.items_failing){if(included.length>=limit)break;const tokens=estimateJsonTokens(id);if(usedTokens+tokens>tokenBudget)break;included.push(id),usedTokens+=tokens}return included}function pushTestHealthSection(lines,result){if(!result.tests)return;lines.push("## Test health"),lines.push(`- ${result.tests.scope}: ${result.tests.total_items}`),lines.push(`- items_with_tests: ${result.tests.items_with_tests}`),lines.push(`- items_with_recent_runs: ${result.tests.items_with_recent_runs}`),lines.push(`- passed: ${result.tests.recent_runs.passed}, failed: ${result.tests.recent_runs.failed}, skipped: ${result.tests.recent_runs.skipped}`);const failures=boundedTestHealthFailures(result.tests,result.applied_limit??DEFAULT_CONTEXT_LIMIT,result.filters.token_budget);failures.length>0&&lines.push(`- items_failing: [${failures.join(",")}]`);const omitted=result.tests.items_failing.length-failures.length;omitted>0&&lines.push(`- items_failing_omitted: ${omitted}`),lines.push("")}function pushEmptyContextSuggestions(lines,result){result.summary.active_items===0&&result.summary.blocked===0&&result.agenda.summary.events===0&&(lines.push("## Suggestions"),lines.push("No active work items or upcoming events. Consider:"),lines.push('- `pm create --type Task --title "..."` to add a new work item'),lines.push("- `pm list --status closed --limit 5` to review recent completions"),lines.push("- `pm search <keywords>` to find related past work"),lines.push("- `pm aggregate` for a full project status overview"))}function renderUnattendedCounts(summary){return[summary.in_progress_unowned===void 0?"":`, in_progress_unowned: ${summary.in_progress_unowned}`,summary.in_progress_idle===void 0?"":`, in_progress_idle: ${summary.in_progress_idle}`].join("")}function renderContextMarkdown(result){const lines=[],focusFields=result.focus_fields,renderFocus=item=>focusFields?formatProjectedFocusLine(item,focusFields):formatFocusLine(item);if(lines.push("# pm context"),lines.push(""),lines.push(`- now: ${result.now}`),lines.push(`- depth: ${result.depth}`),result.filters.parent&&lines.push(`- scope: subtree of ${result.filters.parent}`),lines.push(`- active_items: ${result.summary.active_items} (in_progress: ${result.summary.in_progress}${renderUnattendedCounts(result.summary)}, open: ${result.summary.open})`),result.summary.total_items!==void 0&&lines.push(`- total_items: ${result.summary.total_items} (closed: ${result.summary.closed??0}, canceled: ${result.summary.canceled??0})`),lines.push(`- agenda_events: ${result.summary.agenda_events}`),lines.push(`- blocked_fallback_used: ${result.summary.blocked_fallback_used}`),result.extension_health){const degradedNames=result.extension_health.packages.filter(entry=>entry.status==="degraded").map(entry=>entry.name);lines.push(`- extensions: ${result.extension_health.ok} ok, ${result.extension_health.degraded} degraded${degradedNames.length>0?` (${degradedNames.join(", ")})`:""}`)}const renderedSections=result.sections_included.filter(section=>section!=="blockers"||(result.blockers?.length??0)>0);if(renderedSections.length>0&&lines.push(`- sections: ${renderedSections.join(", ")}`),lines.push(""),pushContextFocusSection(lines,"High-level focus",result.high_level,"No high-level active items.",renderFocus),pushContextFocusSection(lines,"Low-level focus",result.low_level,"No low-level active items.",renderFocus),pushBlockedFallbackSection(lines,result,renderFocus),pushAgendaSection(lines,result),result.workspace_memory){lines.push("## Workspace memory");for(const rollup of result.workspace_memory.rollups)lines.push(`- ${rollup.kind}:${rollup.key} \u2014 ${rollup.label} (${rollup.item_count} completed, latest ${rollup.last_closed_at})`);lines.push("")}return pushHierarchySection(lines,result),pushProgressSection(lines,result),pushRecentlyCreatedSection(lines,result,focusFields,renderFocus),pushUnparentedSection(lines,result,renderFocus),pushActivitySection(lines,result),pushBlockersSection(lines,result),pushFilesSection(lines,result),pushWorkloadSection(lines,result),pushStalenessSection(lines,result),pushTestHealthSection(lines,result),pushEmptyContextSuggestions(lines,result),lines.join(`
|
|
2
|
-
`)}const CONTEXT_UNFILTERED_LIST_ECHO_KEYS=new Set(["status","no_truncate","limit","sort","order"]);function contextListWasFiltered(filters){const{runtime_filters:runtimeFilters,...selection}=filters;return Object.keys(selection).some(key=>!CONTEXT_UNFILTERED_LIST_ECHO_KEYS.has(key))||Object.keys(Object(runtimeFilters)).length>0}async function loadContextEdgeCorpus(global2,listed){return contextListWasFiltered(listed.filters)?(await runList(void 0,buildUnpaginatedContextListOptions({},{excludeTerminal:!1}),global2)).items:listed.items}async function resolveContextRuntime(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),settings=await readSettings(pmRoot),contextSettings=settings.context??SETTINGS_DEFAULTS.context,statusRegistry=resolveRuntimeStatusRegistry(settings.schema),depth=parseContextDepth(options.depth,contextSettings),limit=parseContextLimit(options.limit??options.maxItems,depth);return{settings,contextSettings,statusRegistry,depth,limit,sectionsIncluded:parseContextSections(options.section,depth,contextSettings),activityLimit:parseActivityLimit(options.activityLimit,contextSettings),staleThresholdDays:parseStaleThresholdDays(options.staleThreshold,contextSettings),parentScope:parseContextParent(options.parent),focusFields:parseContextFocusFields(options.fields),baseListOptions:stripListProjectionFlags(options)}}function contextNeedsAllItems(sectionsIncluded){return sectionsIncluded.some(section=>["hierarchy","progress","blockers","staleness","recently_created","unparented"].includes(section))}function buildUnpaginatedContextListOptions(baseListOptions,extra){return{...baseListOptions,...extra,noTruncate:!0,limit:void 0,offset:void 0,after:void 0}}async function loadContextCorpus(global2,runtime){const listed=await runList(void 0,buildUnpaginatedContextListOptions(runtime.baseListOptions,{excludeTerminal:!1}),global2),fullCorpus=listed.items,edgeCorpus=await loadContextEdgeCorpus(global2,listed);let listedItemMetadata=fullCorpus.filter(item=>!isTerminalStatus(item.status,runtime.statusRegistry)),allItems=fullCorpus;const subtreeIds=resolveContextSubtreeIds(runtime.parentScope,edgeCorpus);return subtreeIds&&(listedItemMetadata=listedItemMetadata.filter(item=>subtreeIds.has(item.id.trim().toLowerCase())),allItems=allItems.filter(item=>subtreeIds.has(item.id.trim().toLowerCase()))),{listed,listedItemMetadata,allItems,fullCorpus,edgeCorpus,subtreeIds}}function resolveContextSubtreeIds(parentScope,fullCorpus){if(parentScope===void 0)return;const subtree=collectSubtreeIds(fullCorpus,parentScope);if(!subtree.found)throw new PmCliError(`Context --parent item not found: ${parentScope}`,EXIT_CODE.NOT_FOUND);return subtree.ids}function collectHighLevelContextIds(activeItems,fullCorpus,statusRegistry,typeRegistry){const containers=new Set(computeActionabilityReport(activeItems,fullCorpus,statusRegistry,typeRegistry).containers.map(entry=>entry.item.id));return new Set(activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)||containers.has(item.id)||resolveItemExecutionRole(item.type,typeRegistry)!=="agent").map(item=>item.id))}async function resolveContextFocusGroups(listedItemMetadata,allItems,fullCorpus,blockedIds,statusRegistry,sectionsIncluded,limit,now,author,cursor,cursorFingerprint,useBoundedPage,pmRoot,tokenBudget,claimFocus,typeRegistry){const structural=[...listedItemMetadata].sort((left,right)=>compareCriticalItems(left,right,statusRegistry)),usage=await readContextUsageAffinity({pmRoot,author,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),featureStore=await readWorkspaceContextSignals(structural,{pmRoot,storeKey:"context",statusRegistry,now,author,usageAffinity:usage.affinity,claimFocus}),ranking=await scoreContextCandidatesWithActiveExtensions("context",featureStore.candidates),ranked=ranking.ranked.map(entry=>entry.item),activeStatuses=statusRegistry.active_statuses,rankedActiveItems=ranked.filter(item=>activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),pageStart=useBoundedPage?resolveQueryCursorStart(rankedActiveItems,cursor,cursorFingerprint,item=>item.id):0,focusPage=useBoundedPage?rankedActiveItems.slice(pageStart,pageStart+limit):rankedActiveItems,hasMore=useBoundedPage&&focusPage.length>0&&pageStart+focusPage.length<rankedActiveItems.length,nextCursor=hasMore&&focusPage.length>0?encodeQueryCursor(cursorFingerprint,focusPage[focusPage.length-1].id,pageStart+focusPage.length-1):void 0,rankedBlockedItems=ranked.filter(item=>blockedIds.has(item.id.trim().toLowerCase())),packingIds=new Set([...focusPage.map(item=>item.id),...rankedBlockedItems.filter(item=>!activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))).slice(0,limit).map(item=>item.id)]),packing=packRankedContextItems({...ranking,ranked:ranking.ranked.filter(entry=>packingIds.has(entry.id))},tokenBudget,new Set(Object.entries(claimFocus??{}).filter(([,affinity])=>affinity>=1).map(([id])=>id))),packedItems=packing.included.map(entry=>entry.item),activeItems=packedItems.filter(item=>activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),blockedItems=packedItems.filter(item=>blockedIds.has(item.id.trim().toLowerCase())),childrenByParent=buildChildrenByParent(allItems),focusChildrenByParent=contextNeedsAllItems(sectionsIncluded)?childrenByParent:void 0,fullCorpusById=new Map(fullCorpus.map(item=>[item.id.trim().toLowerCase(),item])),projectFocusItem=item=>{const focus=toContextFocusItem(item,statusRegistry,focusChildrenByParent);return blockedIds.has(item.id.trim().toLowerCase())&&(focus.blocked=!0,focus.blocker_ids=resolveItemBlockers(item,fullCorpusById,statusRegistry).filter(blocker=>!blocker.resolved).map(blocker=>blocker.id)),focus},highLevelIds=collectHighLevelContextIds(activeItems,fullCorpus,statusRegistry,typeRegistry),highLevel=activeItems.filter(item=>highLevelIds.has(item.id)).slice(0,useBoundedPage?focusPage.length:limit).map(projectFocusItem),lowLevel=activeItems.filter(item=>!highLevelIds.has(item.id)).slice(0,useBoundedPage?focusPage.length:limit).map(projectFocusItem),blockedFallbackUsed=rankedActiveItems.length===0;return{activeItems,blockedItems,highLevel,lowLevel,blockedFallback:blockedFallbackUsed?blockedItems.slice(0,limit).map(projectFocusItem):[],blockedFallbackUsed,ranking,packing,featureStore,pageExtras:{...useBoundedPage?{applied_limit:limit}:{},...hasMore?{has_more:!0,truncated:!0}:{},...nextCursor?{next_cursor:nextCursor}:{}}}}function buildContextCursorFingerprint(options,pmRoot){return createQueryFingerprint("context",{pmRoot,options:selectCursorSemanticOptions(options,CONTEXT_FLAG_CONTRACTS)})}function shouldPageContextFocus(options,corpusItemCount){return options.limit!==void 0||options.maxItems!==void 0||options.after!==void 0||corpusItemCount>=CONTEXT_SCALE_THRESHOLD}async function buildContextAgenda(global2,runtime,subtreeIds,listedFocusIds){const calendarOptions={...runtime.baseListOptions,after:void 0,view:"agenda",include:"all",limit:runtime.parentScope===void 0?String(runtime.limit):void 0},agenda=await runCalendar(calendarOptions,global2),scopedAgenda=subtreeIds===void 0?agenda.events:agenda.events.filter(event=>subtreeIds.has(event.item_id.trim().toLowerCase())),fullAgendaEvents=filterTerminalCalendarEvents(scopedAgenda,runtime.statusRegistry).slice(0,runtime.limit),agendaEvents=fullAgendaEvents.map(event=>listedFocusIds.has(event.item_id)?{at:event.at,date:event.date,kind:event.kind,item_id:event.item_id,reference_only:!0,...event.kind==="reminder"?{reminder_text:event.reminder_text}:{},...event.kind==="event"?{event_title:event.event_title,event_recurring:event.event_recurring}:{}}:event);return{agenda,agendaEvents,agendaSummary:summarizeAgenda(fullAgendaEvents)}}function countContextStatus(items,status,statusRegistry){const targetStatus=String(status);return items.filter(item=>normalizeStatusForRegistry(item.status,statusRegistry)===targetStatus).length}async function buildOptionalContextSections(params){const{runtime,allItems,fullCorpus,blockedIds,focusGroups,now,global:global2}=params,childrenByParent=buildChildrenByParent(allItems),allNonTerminal=allItems.filter(item=>!isTerminalStatus(item.status,runtime.statusRegistry)),has=section=>runtime.sectionsIncluded.includes(section);return{hierarchy:has("hierarchy")?buildHierarchy(allItems,focusGroups.activeItems,runtime.statusRegistry,runtime.limit):void 0,activity:has("activity")?await buildActivity(runtime.activityLimit,global2):void 0,progress:has("progress")?buildProgress(allItems,focusGroups.activeItems,blockedIds,runtime.statusRegistry,runtime.limit):void 0,blockersSection:has("blockers")?buildBlockers(focusGroups.blockedItems,fullCorpus,runtime.statusRegistry,runtime.limit):void 0,recentlyCreated:has("recently_created")?buildRecentlyCreated(allNonTerminal,runtime.statusRegistry,childrenByParent,runtime.limit):void 0,unparented:has("unparented")?buildUnparented(allNonTerminal,runtime.statusRegistry,childrenByParent,runtime.limit):void 0,filesSection:has("files")?buildHotFiles(focusGroups.activeItems,runtime.limit):void 0,workload:has("workload")?buildWorkload(focusGroups.activeItems,runtime.statusRegistry,runtime.limit):void 0,staleness:has("staleness")?buildStaleness(allNonTerminal,runtime.staleThresholdDays,now,runtime.limit):void 0,tests:has("tests")?buildTestHealth(allItems.filter(item=>runtime.statusRegistry.active_statuses.has(normalizeStatusForRegistry(item.status,runtime.statusRegistry)))):void 0}}function buildContextSummaryExtras(allItems,statusRegistry,blockedIds,inProgressWork){const canceledStatus=normalizeStatusInput("canceled",statusRegistry),activeItems=allItems.filter(item=>statusRegistry.active_statuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),inProgress=countContextStatus(activeItems,statusRegistry.in_progress_status,statusRegistry);return{scope:"matching_items",active_items:activeItems.length,open:activeItems.length-inProgress,in_progress:inProgress,...inProgressWork.unowned.count>0?{in_progress_unowned:inProgressWork.unowned.count}:{},...inProgressWork.idle.count>0?{in_progress_idle:inProgressWork.idle.count}:{},blocked:allItems.filter(item=>blockedIds.has(item.id.trim().toLowerCase())).length,total_items:allItems.length,closed:allItems.filter(item=>isClosedStatus(item.status,statusRegistry)).length,canceled:allItems.filter(item=>normalizeStatusForRegistry(item.status,statusRegistry)===canceledStatus).length}}function attachOptionalContextSections(result,sections,warningDetails){sections.hierarchy&&(result.hierarchy=sections.hierarchy),sections.activity&&(result.activity=sections.activity),sections.progress&&(result.progress=sections.progress),sections.blockersSection&&(result.blockers=sections.blockersSection),sections.recentlyCreated&&(result.recently_created=sections.recentlyCreated),sections.unparented&&(result.unparented=sections.unparented),sections.filesSection&&(result.files=sections.filesSection),sections.workload&&(result.workload=sections.workload),sections.staleness&&(result.staleness=sections.staleness),sections.tests&&(result.tests=sections.tests),warningDetails!==void 0&&warningDetails.length>0&&(result.warning_details=warningDetails)}function applyContextFocusProjection(result,focusFields){focusFields&&(result.focus_fields=focusFields,result.high_level=projectContextFocusRows(result.high_level,focusFields),result.low_level=projectContextFocusRows(result.low_level,focusFields),result.blocked_fallback=projectContextFocusRows(result.blocked_fallback,focusFields),result.recently_created&&(result.recently_created=projectContextFocusRows(result.recently_created,focusFields)),result.unparented&&(result.unparented=projectContextFocusRows(result.unparented,focusFields)))}function applyContextTagProjection(result,noTags){const rows=[result.high_level,result.low_level,result.blocked_fallback,result.recently_created??[],result.unparented??[]].flat();if(noTags){for(const row of rows)delete row.tags,delete row.tags_inherited;return}const rowsById=new Map(rows.map(row=>[row.id,row])),originalTagSignatures=new Map(rows.map(row=>[row.id,row.tags?[...row.tags].sort().join("\0"):void 0]));for(const row of rows){if(!row.parent||!row.tags)continue;const parent=rowsById.get(row.parent);parent&&originalTagSignatures.get(row.id)===originalTagSignatures.get(parent.id)&&(delete row.tags,row.tags_inherited=parent.id)}}function maybeAttachEmptyContextSuggestions(result,activeItems,blockedItems){activeItems.length>0||blockedItems.length>0||result.agenda.events.length>0||(result.suggestions=['pm create --type Task --title "..." to add a new work item',"pm list --status closed --limit 5 to review recent completions","pm search <keywords> to find related past work","pm aggregate for a full project status overview"])}async function attachContextUsageFeedback(result,focusGroups,pmRoot,author){try{const included=new Set(focusGroups.packing.included.map(entry=>entry.id)),rows=focusGroups.ranking.ranked.map(entry=>({id:entry.id,rank:entry.rank,included:included.has(entry.id)})),rankedIds=new Set(rows.map(row=>row.id));for(const id of collectContextUsageDeliveredItemIds(result,"context"))rankedIds.has(id)||(rows.push({id,rank:rows.length+1,included:!1}),rankedIds.add(id));const receipt=await recordContextUsageServing({pmRoot,author,surface:"context",profile:focusGroups.packing.profile,rows,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});attachContextUsageServingReceipt(result,receipt)}catch{result.warnings=mergeSortedWarnings(result.warnings,["context_usage_feedback_write_failed"])}}async function resolveContextExtensionHealthProjection(omitted,pmRoot,settings){if(omitted)return{};const packages=(await discoverExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:!1})).discovered.map(diagnostic=>({name:diagnostic.name??diagnostic.directory,status:diagnostic.status==="ok"?"ok":"degraded"})).sort((left,right)=>left.name.localeCompare(right.name)),degraded=packages.filter(entry=>entry.status==="degraded").length;return packages.length===0?{}:{extension_health:{total:packages.length,ok:packages.length-degraded,degraded,packages:packages.slice(0,20),...packages.length>20?{truncated:!0}:{}}}}async function resolveContextSemanticAffinity(pmRoot,author){const identity=detectAgentIdentity(),semanticState=await readSessionState(pmRoot),attributionKey=identity.instance||semanticAttributionKey(author);return semanticAttributionAffinity(semanticState.semantic_attribution?.[attributionKey])}async function runContext(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),resolvedRuntime=await resolveContextRuntime(options,global2),corpus=await loadContextCorpus(global2,resolvedRuntime),scaledLimit=resolveContextLimitAtScale(resolvedRuntime.limit,corpus.fullCorpus.length),runtime={...resolvedRuntime,limit:scaledLimit,tokenBudget:resolveContextTokenBudget(options.tokenBudget,Math.max(256,scaledLimit*160))},author=resolveAuthor(void 0,runtime.settings.author_default),claimFocus=await resolveContextSemanticAffinity(pmRoot,author),extensionHealthPromise=resolveContextExtensionHealthProjection(options.noExtensionHealth===!0,pmRoot,runtime.settings),blockedIds=collectDependencyBlockedIds(corpus.edgeCorpus,runtime.statusRegistry),focusGroups=await resolveContextFocusGroups(corpus.listedItemMetadata,corpus.allItems,corpus.edgeCorpus,blockedIds,runtime.statusRegistry,runtime.sectionsIncluded,runtime.limit,nowIso(),author,options.after,buildContextCursorFingerprint(options,pmRoot),shouldPageContextFocus(options,corpus.fullCorpus.length),pmRoot,runtime.tokenBudget,claimFocus,resolveItemTypeRegistry(runtime.settings,getActiveExtensionRegistrations())),agendaContext=await buildContextAgenda(global2,runtime,corpus.subtreeIds,new Set([...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(item=>item.id))),workspaceMemory=await readWorkspaceMemory(corpus.fullCorpus,{pmRoot,statusRegistry:runtime.statusRegistry,now:agendaContext.agenda.now}),warnings=mergeSortedWarnings(corpus.listed.warnings,agendaContext.agenda.warnings,focusGroups.ranking.warnings,[...focusGroups.featureStore.warnings],workspaceMemory.warnings),inProgressCount=countContextStatus(focusGroups.activeItems,runtime.statusRegistry.in_progress_status,runtime.statusRegistry),openCount=focusGroups.activeItems.length-inProgressCount,sections=await buildOptionalContextSections({runtime,allItems:corpus.allItems,fullCorpus:corpus.edgeCorpus,blockedIds,focusGroups,now:agendaContext.agenda.now,global:global2}),summaryExtras=buildContextSummaryExtras(corpus.allItems,runtime.statusRegistry,blockedIds,await scanInProgressWork(pmRoot,corpus.allItems,{in_progress_status:runtime.statusRegistry.in_progress_status,status_registry:runtime.statusRegistry,threshold_hours:runtime.settings.mutation_guard.stale_in_progress_hours,now:new Date(agendaContext.agenda.now)})),result={output_default:"toon",now:agendaContext.agenda.now,depth:runtime.depth,sections_included:runtime.sectionsIncluded,window:{anchor:agendaContext.agenda.anchor,start:agendaContext.agenda.range.start,end:agendaContext.agenda.range.end,past:agendaContext.agenda.range.past,from:agendaContext.agenda.range.from,to:agendaContext.agenda.range.to},filters:{type:options.type??null,tag:options.tag??null,priority:options.priority??null,assignee:options.assignee??null,assignee_filter:options.assigneeFilter??null,sprint:options.sprint??null,release:options.release??null,limit:options.limit??options.maxItems??null,parent:runtime.parentScope??null,token_budget:runtime.tokenBudget,runtime_filters:corpus.listed.filters.runtime_filters??agendaContext.agenda.filters.runtime_filters??{}},summary:{returned_focus:{active_items:focusGroups.activeItems.length,in_progress:inProgressCount,open:openCount,blocked:focusGroups.blockedItems.length},blocked_fallback_used:focusGroups.blockedFallbackUsed,high_level:focusGroups.highLevel.length,low_level:focusGroups.lowLevel.length,agenda_events:agendaContext.agendaSummary.events,...summaryExtras},high_level:focusGroups.highLevel,low_level:focusGroups.lowLevel,blocked_fallback:focusGroups.blockedFallback,agenda:{summary:agendaContext.agendaSummary,events:agendaContext.agendaEvents},...focusGroups.pageExtras};return result.workspace_memory=selectWorkspaceMemory(workspaceMemory,Math.min(800,Math.floor(runtime.tokenBudget*.2))),Object.assign(result,await extensionHealthPromise),attachOptionalContextSections(result,sections,focusGroups.featureStore.warning_details),applyContextTagProjection(result,options.noTags===!0),options.explainRanking===!0&&(result.ranking=toContextRankingSummary(focusGroups.ranking,focusGroups.featureStore,new Set([...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(entry=>entry.id))),result.packing=toContextPackingSummary(focusGroups.packing)),rememberReadOutputFocusRows(result,[...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(row=>({id:row.id,status:normalizeStatusForRegistry(row.status,runtime.statusRegistry)===runtime.statusRegistry.in_progress_status?"in_progress":"open",blocked:row.blocked}))),applyContextFocusProjection(result,runtime.focusFields),refreshReadOutputDeliveredCounts(result),warnings.length>0&&(result.warnings=warnings),maybeAttachEmptyContextSuggestions(result,focusGroups.activeItems,focusGroups.blockedItems),await attachContextUsageFeedback(result,focusGroups,pmRoot,author),result}export{CONTEXT_OUTPUT_VALUES,_testOnly,applyContextTagProjection,buildChildrenByParent,buildItemContextRelevanceCandidates,collectSubtreeIds,compareCriticalItems,mergeSortedWarnings,packRankedContextItems,parseContextDepth,parseContextFocusFields,parseContextSections,projectContextFocusRows,renderContextMarkdown,resolveContextExtensionHealthProjection,resolveContextOutputFormat,resolveContextTokenBudget,runContext,toContextFocusItem,toContextPackingSummary,toContextRankingSummary};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b502c71a-acf7-5813-9717-b6517be31c6c")}catch{}})();import{scanInProgressWork}from"../governance/stale-work.js";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{readRecentActivity}from"./activity.js";import{scoreContextCandidatesWithActiveExtensions}from"../context-relevance.js";import{buildItemContextRelevanceCandidates}from"../context-relevance.js";import{createQueryFingerprint,encodeQueryCursor,resolveQueryCursorStart,selectCursorSemanticOptions}from"../pagination.js";import{rememberReadOutputFocusRows,refreshReadOutputDeliveredCounts}from"../read-output-rows.js";import{CONTEXT_FLAG_CONTRACTS}from"../cli-contracts/flag-contracts.js";import{packContextCandidates}from"../context-packing.js";import{attachContextUsageServingReceipt,collectContextUsageDeliveredItemIds,readContextUsageAffinity,recordContextUsageServing}from"../context-usage.js";import{readWorkspaceContextSignals}from"../context-signal-store.js";import{readWorkspaceMemory,selectWorkspaceMemory}from"../workspace-memory.js";import{detectAgentIdentity}from"../../core/shared/author.js";import{readSessionState,semanticAttributionKey}from"../../core/session/session-state.js";import{semanticAttributionAffinity}from"../context/semantic-session-attribution.js";const CONTEXT_OUTPUT_VALUES=["markdown","toon","json","ndjson"],HIGH_LEVEL_TYPES=new Set(["Epic","Feature"]),DEFAULT_CONTEXT_LIMIT=10,CONTEXT_SCALE_THRESHOLD=1e4,STANDARD_SECTIONS=["hierarchy","activity","progress","recently_created","unparented","workload"],DEEP_SECTIONS=[...STANDARD_SECTIONS,"blockers","files","staleness","tests"],LEADING_HYPHEN_DATE=/^(\d{4})-(\d{2})-(\d{2})/,LEADING_COMPACT_DATE=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/,COMPACT_DATE=/^(\d{4})(\d{2})(\d{2})$/,COMPACT_DATETIME=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?(Z|[+-]\d{2}:?\d{2})?$/i;function parseOutputFormat(raw){if(!raw)return;const normalized=raw.trim().toLowerCase();if(!CONTEXT_OUTPUT_VALUES.includes(normalized))throw new PmCliError("Context format must be one of markdown|toon|json|ndjson",EXIT_CODE.USAGE);return normalized}const FOCUS_PROJECTION_FIELDS=new Set(["id","title","type","status","priority","order","deadline","assignee","tags","tags_inherited","updated_at","parent","children_total","children_closed","completion_pct","blocked","blocker_ids","created_at"]);function parseContextFocusFields(raw){if(raw===void 0)return;const fields=[];for(const token of raw.split(",")){const normalized=token.trim().toLowerCase();if(normalized.length!==0){if(!FOCUS_PROJECTION_FIELDS.has(normalized))throw new PmCliError(`Context --fields value not projectable: ${normalized} (valid: ${[...FOCUS_PROJECTION_FIELDS].join(", ")})`,EXIT_CODE.USAGE);fields.includes(normalized)||fields.push(normalized)}}if(fields.length===0)throw new PmCliError("Context --fields requires at least one field name",EXIT_CODE.USAGE);return fields}function projectContextFocusRows(rows,fields){return rows.map(row=>{const projected={},source=row;for(const field of fields)projected[field]=source[field]??null;return projected})}function resolveContextOutputFormat(options,global2){const commandFormat=parseOutputFormat(options.format);if(global2.json&&commandFormat&&commandFormat!=="json"&&commandFormat!=="ndjson")throw new PmCliError("Cannot combine --json with --format markdown|toon",EXIT_CODE.USAGE);return global2.json?commandFormat==="ndjson"?"ndjson":"json":commandFormat??"toon"}function parseContextLimit(raw,depth){return parseIntegerLimit(raw,"--limit")??(depth==="full"?Number.MAX_SAFE_INTEGER:DEFAULT_CONTEXT_LIMIT)}function resolveContextTokenBudget(raw,fallback){if(raw===void 0)return fallback;const parsed=typeof raw=="number"?raw:Number(raw);if(!Number.isInteger(parsed)||parsed<1)throw new PmCliError("--token-budget must be a positive integer",EXIT_CODE.USAGE);return parsed}function resolveContextLimitAtScale(limit,itemCount){return itemCount>=CONTEXT_SCALE_THRESHOLD&&limit===Number.MAX_SAFE_INTEGER?DEFAULT_CONTEXT_LIMIT:limit}function parseContextDepth(raw,settings){if(!raw)return settings.default_depth;const normalized=raw.trim().toLowerCase();if(!CONTEXT_DEPTH_VALUES.includes(normalized))throw new PmCliError(`Context --depth must be one of ${CONTEXT_DEPTH_VALUES.join("|")}`,EXIT_CODE.USAGE);return normalized}function parseContextSections(raw,depth,settings){if(raw&&raw.length>0){const sections=[];for(const value of raw){const normalized=value.trim().toLowerCase();if(!CONTEXT_SECTION_VALUES.includes(normalized))throw new PmCliError(`Context --section must be one of ${CONTEXT_SECTION_VALUES.join("|")}`,EXIT_CODE.USAGE);sections.includes(normalized)||sections.push(normalized)}return sections}return depth==="brief"?[]:depth==="full"?[...CONTEXT_SECTION_VALUES]:(depth==="deep"?DEEP_SECTIONS:STANDARD_SECTIONS).filter(section=>settings.sections[section])}function parseActivityLimit(raw,settings){return raw?parseIntegerLimit(raw,"--activity-limit")??settings.activity_limit:settings.activity_limit}function parseStaleThresholdDays(raw,settings){if(!raw)return settings.stale_threshold_days;const trimmed=raw.trim().toLowerCase(),match=/^(\d+)d?$/.exec(trimmed);if(!match)throw new PmCliError("--stale-threshold must be a number of days (e.g. 7 or 7d)",EXIT_CODE.USAGE);const days=parseInt(match[1],10);if(days<=0)throw new PmCliError("--stale-threshold must be positive",EXIT_CODE.USAGE);return days}function progressStatusOf(statusRegistry){return normalizeStatusForRegistry(statusRegistry.in_progress_status,statusRegistry)}function statusRank(status,statusRegistry){const normalizedStatus=normalizeStatusForRegistry(status,statusRegistry),blockedStatus=normalizeStatusInput("blocked",statusRegistry),draftStatus=normalizeStatusInput("draft",statusRegistry);return normalizedStatus===progressStatusOf(statusRegistry)?0:statusRegistry.active_statuses.has(normalizedStatus)?1:blockedStatus&&normalizedStatus===blockedStatus?2:draftStatus&&normalizedStatus===draftStatus?3:statusRegistry.blocked_statuses.has(normalizedStatus)?5:statusRegistry.terminal_statuses.has(normalizedStatus)?7:6}function isClosedStatus(status,statusRegistry){const closeStatus=normalizeStatusInput("closed",statusRegistry);return normalizeStatusForRegistry(status,statusRegistry)===closeStatus}function isInProgressStatus(status,statusRegistry){return normalizeStatusForRegistry(status,statusRegistry)===progressStatusOf(statusRegistry)}function isOpenStatus(status,statusRegistry){const normalizedStatus=normalizeStatusForRegistry(status,statusRegistry);return normalizedStatus!==progressStatusOf(statusRegistry)&&statusRegistry.active_statuses.has(normalizedStatus)}function isBlockedStatus(status,statusRegistry){return statusRegistry.blocked_statuses.has(normalizeStatusForRegistry(status,statusRegistry))}const LIST_PROJECTION_FLAGS=["compact","brief","fields","includeBody","include_body","parent"];function stripListProjectionFlags(options){const copy={...options};for(const key of LIST_PROJECTION_FLAGS)delete copy[key];return copy}function collectSubtreeIds(corpus,parentId){const target=parentId.trim().toLowerCase(),anchor=corpus.find(item=>item.id.trim().toLowerCase()===target);if(!anchor)return{ids:new Set,found:!1};const childrenByParent=buildChildrenByParent(corpus),descendants=collectDescendants(anchor.id,childrenByParent);return{ids:new Set([anchor.id,...descendants.map(item=>item.id)].map(id=>id.trim().toLowerCase())),found:!0}}function parseContextParent(raw){if(raw===void 0)return;const trimmed=raw.trim();if(trimmed.length===0)throw new PmCliError("Context --parent requires an item id",EXIT_CODE.USAGE);return trimmed}function compareOptionalOrder(left,right){const leftValue=left??null,rightValue=right??null;return leftValue===null&&rightValue===null?0:leftValue===null?1:rightValue===null?-1:leftValue-rightValue}function compareOptionalDeadline(left,right){const leftValue=left??null,rightValue=right??null;return leftValue===null&&rightValue===null?0:leftValue===null?1:rightValue===null?-1:compareTimestampStrings(leftValue,rightValue)}function daysInUtcMonth(year,monthIndex){return new Date(Date.UTC(year,monthIndex+1,0)).getUTCDate()}function hasNoInvalidDatePrefix(value){const match=LEADING_HYPHEN_DATE.exec(value)??LEADING_COMPACT_DATE.exec(value);if(!match)return!0;const year=Number.parseInt(match[1],10),month=Number.parseInt(match[2],10),day=Number.parseInt(match[3],10);return month>=1&&month<=12&&day>=1&&day<=daysInUtcMonth(year,month-1)}function normalizeTimestampCandidate(value){const compactDate=COMPACT_DATE.exec(value);if(compactDate)return`${compactDate[1]}-${compactDate[2]}-${compactDate[3]}`;const compactDateTime=COMPACT_DATETIME.exec(value);if(compactDateTime){const[,year,month,day,hour,minute,secondRaw,offsetRaw]=compactDateTime,second=secondRaw?`:${secondRaw}`:"",offset=offsetRaw&&offsetRaw.length===5&&offsetRaw!=="Z"?`${offsetRaw.slice(0,3)}:${offsetRaw.slice(3)}`:offsetRaw??"";return`${year}-${month}-${day}T${hour}:${minute}${second}${offset}`}return value}function parseContextTimestampMs(value){if(typeof value!="string")return Number.NaN;const trimmed=value.trim();if(trimmed.length===0||!hasNoInvalidDatePrefix(trimmed))return Number.NaN;const parsed=Date.parse(normalizeTimestampCandidate(trimmed));return Number.isFinite(parsed)?parsed:Number.NaN}function sortableTimestamp(value){const parsed=parseContextTimestampMs(value);return Number.isFinite(parsed)?new Date(parsed).toISOString():""}function dateTokenForTimestamp(value){const parsed=parseContextTimestampMs(value);return Number.isFinite(parsed)?new Date(parsed).toISOString().slice(0,10):"unknown"}function normalizedParentId(value){if(typeof value!="string")return null;const trimmed=value.trim();return trimmed.length>0?trimmed:null}function compareCriticalItems(left,right,statusRegistry){const byStatus=statusRank(left.status,statusRegistry)-statusRank(right.status,statusRegistry);if(byStatus!==0)return byStatus;const byPriority=left.priority-right.priority;if(byPriority!==0)return byPriority;const byOrder=compareOptionalOrder(left.order,right.order);if(byOrder!==0)return byOrder;const byDeadline=compareOptionalDeadline(left.deadline,right.deadline);if(byDeadline!==0)return byDeadline;const byUpdated=compareTimestampStrings(sortableTimestamp(right.updated_at),sortableTimestamp(left.updated_at)),byId=left.id.localeCompare(right.id);return byUpdated!==0?byUpdated:byId}function estimateJsonTokens(value){return Math.max(1,Math.ceil(Buffer.byteLength(JSON.stringify(value),"utf8")/4))}function packRankedContextItems(report,tokenBudget,requiredIds=new Set,profile="context"){return packContextCandidates(report.ranked.map(entry=>({id:entry.id,item:entry.item,rank:entry.rank,score:entry.score,required:requiredIds.has(entry.id),cluster:entry.item.parent?.trim()||entry.item.type,token_costs:{identity:estimateJsonTokens({id:entry.id,title:entry.item.title}),summary:estimateJsonTokens({id:entry.id,title:entry.item.title,type:entry.item.type,status:entry.item.status,priority:entry.item.priority,parent:entry.item.parent}),full:estimateJsonTokens(entry.item)}})),{tokenBudget,profile,latencyBudgetMs:25})}function toContextPackingSummary(report){return{...report,included:report.included.map(entry=>({id:entry.id,projection:entry.projection,tokens:entry.tokens}))}}function toContextRankingSummary(report,featureStore,servedItemIds){const ranked=servedItemIds===void 0?report.ranked:report.ranked.filter(entry=>servedItemIds.has(entry.id));return{model:report.model,available_signals:report.available_signals,items:ranked.map(entry=>({id:entry.id,rank:entry.rank,baseline_rank:entry.baseline_rank,score:entry.score,contributions:entry.contributions,...entry.signal_provenance===void 0?{}:{recency:entry.signal_provenance.recency}})),candidate_count:report.ranked.length,omitted_count:report.ranked.length-ranked.length,...featureStore?{feature_store:{source:featureStore.snapshot.source,cache_status:featureStore.cache_status,source_cursor:featureStore.snapshot.source_cursor,generated_at:featureStore.snapshot.generated_at}}:{}}}function completionPct(closed,total){return total>0?Math.round(closed*100/total):0}function buildChildrenByParent(allItems){const childrenByParent=new Map;for(const item of allItems){const parent=normalizedParentId(item.parent);if(!parent)continue;const children=childrenByParent.get(parent)??[];children.push(item),childrenByParent.set(parent,children)}return childrenByParent}function toContextFocusItem(item,statusRegistry,childrenByParent){const focus={id:item.id,title:item.title,type:item.type,status:item.status,priority:item.priority,order:item.order??null,deadline:item.deadline??null,assignee:item.assignee??null,tags:Array.isArray(item.tags)?[...item.tags]:[],updated_at:item.updated_at,parent:normalizedParentId(item.parent)};if(statusRegistry&&childrenByParent){const descendants=collectDescendants(item.id,childrenByParent),total=descendants.length;if(total>0){const closed=descendants.filter(desc=>isClosedStatus(desc.status,statusRegistry)).length;focus.children_total=total,focus.children_closed=closed,focus.completion_pct=completionPct(closed,total)}}return focus}function summarizeAgenda(events){let deadlines=0,reminders=0,scheduled=0;const itemIds=new Set;for(const event of events){if(itemIds.add(event.item_id),event.kind==="deadline"){deadlines+=1;continue}if(event.kind==="reminder"){reminders+=1;continue}scheduled+=1}return{events:events.length,items:itemIds.size,deadlines,reminders,scheduled}}function mergeSortedWarnings(...warningGroups){return[...new Set(warningGroups.flatMap(group=>group??[]))].sort((left,right)=>left.localeCompare(right))}function filterTerminalCalendarEvents(events,statusRegistry){return events.filter(event=>!statusRegistry.terminal_statuses.has(normalizeStatusForRegistry(event.item_status,statusRegistry)))}function buildHierarchy(allItems,activeItems,statusRegistry,limit){const itemMap=new Map;for(const item of allItems)itemMap.set(item.id,item);const childrenByParent=buildChildrenByParent(allItems),activeHighLevelIds=new Set(activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)).map(item=>item.id)),nodes=[];for(const parentId of activeHighLevelIds){const parent=itemMap.get(parentId);if(!parent)continue;const allDescendants=collectDescendants(parentId,childrenByParent),childItems=childrenByParent.get(parentId)??[];let closedCount=0,openCount=0,inProgressCount=0,blockedCount=0;for(const desc of allDescendants)isClosedStatus(desc.status,statusRegistry)?closedCount++:isInProgressStatus(desc.status,statusRegistry)?inProgressCount++:isBlockedStatus(desc.status,statusRegistry)?blockedCount++:isOpenStatus(desc.status,statusRegistry)&&openCount++;const children=childItems.sort((a,b)=>compareCriticalItems(a,b,statusRegistry)).slice(0,limit).map(child=>{const grandchildren=collectDescendants(child.id,childrenByParent),gcClosed=grandchildren.filter(gc=>isClosedStatus(gc.status,statusRegistry)).length;return{id:child.id,title:child.title,type:child.type,status:child.status,children_total:grandchildren.length,children_closed:gcClosed}});nodes.push({id:parent.id,title:parent.title,type:parent.type,status:parent.status,children_total:allDescendants.length,children_closed:closedCount,children_open:openCount,children_in_progress:inProgressCount,children_blocked:blockedCount,children})}return nodes.sort((a,b)=>{const aParent=itemMap.get(a.id),bParent=itemMap.get(b.id);return compareCriticalItems(aParent,bParent,statusRegistry)}).slice(0,limit)}function collectDescendants(parentId,childrenByParent){const result=[],stack=[parentId],visited=new Set;for(;stack.length>0;){const current=stack.pop();if(visited.has(current))continue;visited.add(current);const children=childrenByParent.get(current)??[];for(const child of children)result.push(child),stack.push(child.id)}return result}const _testOnly={buildActivity,buildBlockers,buildChildrenByParent,buildHierarchy,buildHotFiles,buildProgress,buildRecentlyCreated,buildStaleness,buildTestHealth,buildUnparented,buildWorkload,collectDescendants,collectSubtreeIds,compareCriticalItems,compareOptionalDeadline,compareOptionalOrder,completionPct,dateTokenForTimestamp,filterTerminalCalendarEvents,formatAgendaLine,isBlockedStatus,isClosedStatus,isInProgressStatus,isOpenStatus,mergeSortedWarnings,normalizedParentId,parseActivityLimit,parseContextLimit,resolveContextLimitAtScale,parseContextParent,parseContextTimestampMs,parseStaleThresholdDays,sortableTimestamp,statusRank,stripListProjectionFlags,summarizeAgenda,toContextFocusItem};async function buildActivity(activityLimit,global2){return readRecentActivity({limit:activityLimit},global2)}function buildProgress(allItems,activeItems,blockedIds,statusRegistry,limit){const childrenByParent=new Map;for(const item of allItems){if(!item.parent)continue;const children=childrenByParent.get(item.parent)??[];children.push(item),childrenByParent.set(item.parent,children)}const activeHighLevel=activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)),entries=[];for(const parent of activeHighLevel){const descendants=collectDescendants(parent.id,childrenByParent),total=descendants.length;if(total===0)continue;let closed=0,open=0,inProgress=0,blocked=0;for(const desc of descendants)isClosedStatus(desc.status,statusRegistry)?closed++:blockedIds.has(desc.id.trim().toLowerCase())?blocked++:isInProgressStatus(desc.status,statusRegistry)?inProgress++:isOpenStatus(desc.status,statusRegistry)&&open++;entries.push({id:parent.id,title:parent.title,type:parent.type,total,closed,open,in_progress:inProgress,blocked,completion_pct:completionPct(closed,total)})}return entries.sort((a,b)=>a.completion_pct-b.completion_pct).slice(0,limit)}function buildBlockers(blockedItems,fullCorpus,statusRegistry,limit){const itemsById=new Map(fullCorpus.map(item=>[item.id.trim().toLowerCase(),item]));return blockedItems.slice(0,limit).map(item=>{const blockers=resolveItemBlockers(item,itemsById,statusRegistry),blockedBy=blockers.find(blocker=>!blocker.resolved)?.id??blockers[0]?.id??null,blockerItem=blockedBy?itemsById.get(blockedBy.trim().toLowerCase()):void 0;return{id:item.id,title:item.title,blocked_by:blockedBy,blocked_by_title:blockerItem?.title??null,blocked_by_status:blockerItem?.status??null,blocked_reason:item.blocked_reason??null,unblock_note:item.unblock_note??null}})}function buildHotFiles(activeItems,limit){const fileMap=new Map;for(const item of activeItems)for(const file of item.files??[]){const existing=fileMap.get(file.path)??new Set;existing.add(item.id),fileMap.set(file.path,existing)}return[...fileMap.entries()].map(([filePath,itemIds])=>({path:filePath,references:itemIds.size,items:[...itemIds].sort()})).sort((a,b)=>b.references-a.references).slice(0,limit)}function buildWorkload(activeItems,statusRegistry,limit){const groups=new Map;for(const item of activeItems){const key=item.assignee??null,existing=groups.get(key)??[];existing.push(item),groups.set(key,existing)}return[...groups.entries()].map(([assignee,items])=>({assignee,active:items.length,in_progress:items.filter(item=>isInProgressStatus(item.status,statusRegistry)).length,items:items.map(item=>item.id).sort()})).sort((a,b)=>b.active-a.active).slice(0,limit)}function buildStaleness(allNonTerminal,staleThresholdDays,now,limit){const cutoffMs=new Date(now).getTime()-staleThresholdDays*24*60*60*1e3;return allNonTerminal.filter(item=>new Date(item.updated_at).getTime()<cutoffMs).map(item=>({id:item.id,title:item.title,status:item.status,updated_at:item.updated_at,stale_days:Math.floor((new Date(now).getTime()-new Date(item.updated_at).getTime())/(1440*60*1e3))})).sort((a,b)=>b.stale_days-a.stale_days).slice(0,limit)}function buildRecentlyCreated(allNonTerminal,statusRegistry,childrenByParent,limit){return allNonTerminal.map(item=>({item,sortKey:sortableTimestamp(item.created_at)})).sort((left,right)=>{const byCreated=compareTimestampStrings(right.sortKey,left.sortKey);return byCreated!==0?byCreated:left.item.id.localeCompare(right.item.id)}).slice(0,limit).map(({item})=>({...toContextFocusItem(item,statusRegistry,childrenByParent),created_at:item.created_at}))}function buildUnparented(allNonTerminal,statusRegistry,childrenByParent,limit){return allNonTerminal.filter(item=>!normalizedParentId(item.parent)&&!HIGH_LEVEL_TYPES.has(item.type)).sort((left,right)=>compareCriticalItems(left,right,statusRegistry)).slice(0,limit).map(item=>toContextFocusItem(item,statusRegistry,childrenByParent))}function buildTestHealth(activeItems){let itemsWithTests=0,itemsWithRecentRuns=0,passed=0,failed=0,skipped=0;const itemsFailing=[];for(const item of activeItems){(item.tests??[]).length>0&&itemsWithTests++;const runs=item.test_runs??[];if(runs.length>0){itemsWithRecentRuns++;let itemHasFailure=!1;for(const run of runs)passed+=run.passed??0,failed+=run.failed??0,skipped+=run.skipped??0,(run.failed??0)>0&&(itemHasFailure=!0);itemHasFailure&&itemsFailing.push(item.id)}}return{scope:"matching_active_items",total_items:activeItems.length,items_with_tests:itemsWithTests,items_with_recent_runs:itemsWithRecentRuns,recent_runs:{passed,failed,skipped},items_failing:itemsFailing.sort()}}function formatClock(timestamp){return`${new Date(timestamp).toISOString().slice(11,16)}Z`}function formatFocusLine(item){const orderToken=item.order===null?"-":String(item.order),deadlineToken=item.deadline??"-",parentToken=item.parent?` parent:${item.parent}`:"",progressToken=item.children_total!==void 0&&item.children_closed!==void 0&&item.completion_pct!==void 0?` children:${item.children_closed}/${item.children_total} done:${item.completion_pct}%`:"",blockedToken=item.blocked===!0?` blocked:${item.blocker_ids?.join(",")||"lifecycle"}`:"";return`${item.id} p${item.priority} ${item.status} ${item.type} order:${orderToken} deadline:${deadlineToken}${parentToken}${progressToken}${blockedToken} ${item.title}`}function formatProjectedFocusLine(item,fields){const source=item;return fields.map(field=>{const value=source[field];return Array.isArray(value)?`${field}:${value.join(",")}`:`${field}:${value??"-"}`}).join(" ")}function formatAgendaLine(event){if("reference_only"in event){const suffix=event.kind==="reminder"?` \u2014 ${event.reminder_text??"reminder"}`:event.kind==="event"?` \u2014 ${event.event_title??"event"}${event.event_recurring?" (recurring)":""}`:"";return`${formatClock(event.at)} [${event.kind}] ${event.item_id} (see focus item)${suffix}`}const base=`${formatClock(event.at)} [${event.kind}] ${event.item_id} p${event.item_priority} ${event.item_status} ${event.item_title}`;if(event.kind==="reminder")return`${base} \u2014 ${event.reminder_text}`;if(event.kind==="event"){const recurringSuffix=event.event_recurring?" (recurring)":"",title=event.event_title??event.item_title;return`${base} \u2014 ${title}${recurringSuffix}`}return base}function pushContextFocusSection(lines,title,rows,emptyText,renderFocus){if(lines.push(`## ${title}`),rows.length===0)lines.push(emptyText);else for(const item of rows)lines.push(`- ${renderFocus(item)}`);lines.push("")}function pushBlockedFallbackSection(lines,result,renderFocus){if(result.blocked_fallback.length!==0){lines.push("## Blocked fallback");for(const item of result.blocked_fallback)lines.push(`- ${renderFocus(item)}`);lines.push("")}}function pushAgendaSection(lines,result){if(lines.push("## Agenda"),lines.push(`- events: ${result.agenda.summary.events} (deadlines: ${result.agenda.summary.deadlines}, reminders: ${result.agenda.summary.reminders}, scheduled: ${result.agenda.summary.scheduled})`),result.agenda.events.length===0)lines.push("No agenda events matched the selected filters.");else for(const event of result.agenda.events)lines.push(`- ${formatAgendaLine(event)}`);lines.push("")}function pushHierarchySection(lines,result){if(!(!result.hierarchy||result.hierarchy.length===0)){lines.push("## Hierarchy");for(const node of result.hierarchy){const pct=completionPct(node.children_closed,node.children_total);lines.push(`- ${node.id} ${node.type} ${node.status} "${node.title}" [${node.children_closed}/${node.children_total} done ${pct}%]`);for(const child of node.children){const cpct=completionPct(child.children_closed,child.children_total);lines.push(` - ${child.id} ${child.type} ${child.status} "${child.title}" [${child.children_closed}/${child.children_total} done ${cpct}%]`)}}lines.push("")}}function pushProgressSection(lines,result){if(!(!result.progress||result.progress.length===0)){lines.push("## Progress");for(const entry of result.progress)lines.push(`- ${entry.id} "${entry.title}" ${entry.completion_pct}% (${entry.closed}/${entry.total} closed, ${entry.in_progress} wip, ${entry.open} open, ${entry.blocked} blocked)`);lines.push("")}}function pushRecentlyCreatedSection(lines,result,focusFields,renderFocus){if(!(!result.recently_created||result.recently_created.length===0)){lines.push("## Recently created");for(const item of result.recently_created)lines.push(focusFields?`- ${renderFocus(item)}`:`- ${dateTokenForTimestamp(item.created_at)} ${formatFocusLine(item)}`);lines.push("")}}function pushUnparentedSection(lines,result,renderFocus){if(!(!result.unparented||result.unparented.length===0)){lines.push("## Unparented");for(const item of result.unparented)lines.push(`- ${renderFocus(item)}`);lines.push("")}}function pushActivitySection(lines,result){const receipt=result.activity_history_read;if(!((!result.activity||result.activity.length===0)&&receipt===void 0)){lines.push("## Recent activity");for(const entry of result.activity??[]){const msg=entry.msg?` ${entry.msg}`:"";lines.push(`- ${entry.ts.slice(0,16)}Z ${entry.id} ${entry.op} by:${entry.author}${msg}`)}receipt!==void 0&&lines.push(`- history read: ${receipt.reason}, ${receipt.streams_read}/${receipt.streams_total} streams parsed`),lines.push("")}}function pushBlockersSection(lines,result){if(!(!result.blockers||result.blockers.length===0)){lines.push("## Blockers");for(const entry of result.blockers){const by=entry.blocked_by?`blocked_by:${entry.blocked_by}(${entry.blocked_by_status??"?"})`:"blocked_by:-",reason=entry.blocked_reason?` reason:"${entry.blocked_reason}"`:"",note=entry.unblock_note?` unblock:"${entry.unblock_note}"`:"";lines.push(`- ${entry.id} "${entry.title}" ${by}${reason}${note}`)}lines.push("")}}function pushFilesSection(lines,result){if(!(!result.files||result.files.length===0)){lines.push("## Hot files");for(const file of result.files)lines.push(`- ${file.path} refs:${file.references} items:[${file.items.join(",")}]`);lines.push("")}}function pushWorkloadSection(lines,result){if(!(!result.workload||result.workload.length===0)){lines.push("## Workload");for(const entry of result.workload){const who=entry.assignee??"(unassigned)";lines.push(`- ${who} active:${entry.active} wip:${entry.in_progress} items:[${entry.items.join(",")}]`)}lines.push("")}}function pushStalenessSection(lines,result){if(!(!result.staleness||result.staleness.length===0)){lines.push("## Stale items");for(const entry of result.staleness)lines.push(`- ${entry.id} ${entry.status} stale:${entry.stale_days}d last:${entry.updated_at.slice(0,10)} "${entry.title}"`);lines.push("")}}function boundedTestHealthFailures(tests,limit,tokenBudget){const included=[];let usedTokens=0;for(const id of tests.items_failing){if(included.length>=limit)break;const tokens=estimateJsonTokens(id);if(usedTokens+tokens>tokenBudget)break;included.push(id),usedTokens+=tokens}return included}function pushTestHealthSection(lines,result){if(!result.tests)return;lines.push("## Test health"),lines.push(`- ${result.tests.scope}: ${result.tests.total_items}`),lines.push(`- items_with_tests: ${result.tests.items_with_tests}`),lines.push(`- items_with_recent_runs: ${result.tests.items_with_recent_runs}`),lines.push(`- passed: ${result.tests.recent_runs.passed}, failed: ${result.tests.recent_runs.failed}, skipped: ${result.tests.recent_runs.skipped}`);const failures=boundedTestHealthFailures(result.tests,result.applied_limit??DEFAULT_CONTEXT_LIMIT,result.filters.token_budget);failures.length>0&&lines.push(`- items_failing: [${failures.join(",")}]`);const omitted=result.tests.items_failing.length-failures.length;omitted>0&&lines.push(`- items_failing_omitted: ${omitted}`),lines.push("")}function pushEmptyContextSuggestions(lines,result){result.summary.active_items===0&&result.summary.blocked===0&&result.agenda.summary.events===0&&(lines.push("## Suggestions"),lines.push("No active work items or upcoming events. Consider:"),lines.push('- `pm create --type Task --title "..."` to add a new work item'),lines.push("- `pm list --status closed --limit 5` to review recent completions"),lines.push("- `pm search <keywords>` to find related past work"),lines.push("- `pm aggregate` for a full project status overview"))}function renderUnattendedCounts(summary){return[summary.in_progress_unowned===void 0?"":`, in_progress_unowned: ${summary.in_progress_unowned}`,summary.in_progress_idle===void 0?"":`, in_progress_idle: ${summary.in_progress_idle}`].join("")}function renderActiveSummaryLines(summary){const unattended=renderUnattendedCounts(summary);return summary.active_items===summary.open+summary.in_progress?[`- active_items: ${summary.active_items} (in_progress: ${summary.in_progress}${unattended}, open: ${summary.open})`]:[`- active_items: ${summary.active_items} (open: ${summary.open})`,`- in_progress: ${summary.in_progress} (outside active_items${unattended})`]}function renderContextMarkdown(result){const lines=[],focusFields=result.focus_fields,renderFocus=item=>focusFields?formatProjectedFocusLine(item,focusFields):formatFocusLine(item);if(lines.push("# pm context"),lines.push(""),lines.push(`- now: ${result.now}`),lines.push(`- depth: ${result.depth}`),result.filters.parent&&lines.push(`- scope: subtree of ${result.filters.parent}`),lines.push(...renderActiveSummaryLines(result.summary)),result.summary.total_items!==void 0&&lines.push(`- total_items: ${result.summary.total_items} (closed: ${result.summary.closed??0}, canceled: ${result.summary.canceled??0})`),lines.push(`- agenda_events: ${result.summary.agenda_events}`),lines.push(`- blocked_fallback_used: ${result.summary.blocked_fallback_used}`),result.extension_health){const degradedNames=result.extension_health.packages.filter(entry=>entry.status==="degraded").map(entry=>entry.name);lines.push(`- extensions: ${result.extension_health.ok} ok, ${result.extension_health.degraded} degraded${degradedNames.length>0?` (${degradedNames.join(", ")})`:""}`)}const renderedSections=result.sections_included.filter(section=>section!=="blockers"||(result.blockers?.length??0)>0);if(renderedSections.length>0&&lines.push(`- sections: ${renderedSections.join(", ")}`),lines.push(""),pushContextFocusSection(lines,"High-level focus",result.high_level,"No high-level active items.",renderFocus),pushContextFocusSection(lines,"Low-level focus",result.low_level,"No low-level active items.",renderFocus),pushBlockedFallbackSection(lines,result,renderFocus),pushAgendaSection(lines,result),result.workspace_memory){lines.push("## Workspace memory");for(const rollup of result.workspace_memory.rollups)lines.push(`- ${rollup.kind}:${rollup.key} \u2014 ${rollup.label} (${rollup.item_count} completed, latest ${rollup.last_closed_at})`);lines.push("")}return pushHierarchySection(lines,result),pushProgressSection(lines,result),pushRecentlyCreatedSection(lines,result,focusFields,renderFocus),pushUnparentedSection(lines,result,renderFocus),pushActivitySection(lines,result),pushBlockersSection(lines,result),pushFilesSection(lines,result),pushWorkloadSection(lines,result),pushStalenessSection(lines,result),pushTestHealthSection(lines,result),pushEmptyContextSuggestions(lines,result),lines.join(`
|
|
2
|
+
`)}const CONTEXT_UNFILTERED_LIST_ECHO_KEYS=new Set(["status","no_truncate","limit","sort","order"]);function contextListWasFiltered(filters){const{runtime_filters:runtimeFilters,...selection}=filters;return Object.keys(selection).some(key=>!CONTEXT_UNFILTERED_LIST_ECHO_KEYS.has(key))||Object.keys(Object(runtimeFilters)).length>0}async function loadContextEdgeCorpus(global2,listed){return contextListWasFiltered(listed.filters)?(await runList(void 0,buildUnpaginatedContextListOptions({},{excludeTerminal:!1}),global2)).items:listed.items}async function resolveContextRuntime(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),settings=await readSettings(pmRoot),contextSettings=settings.context??SETTINGS_DEFAULTS.context,statusRegistry=resolveRuntimeStatusRegistry(settings.schema),depth=parseContextDepth(options.depth,contextSettings),limit=parseContextLimit(options.limit??options.maxItems,depth);return{settings,contextSettings,statusRegistry,depth,limit,sectionsIncluded:parseContextSections(options.section,depth,contextSettings),activityLimit:parseActivityLimit(options.activityLimit,contextSettings),staleThresholdDays:parseStaleThresholdDays(options.staleThreshold,contextSettings),parentScope:parseContextParent(options.parent),focusFields:parseContextFocusFields(options.fields),baseListOptions:stripListProjectionFlags(options)}}function contextNeedsAllItems(sectionsIncluded){return sectionsIncluded.some(section=>["hierarchy","progress","blockers","staleness","recently_created","unparented"].includes(section))}function buildUnpaginatedContextListOptions(baseListOptions,extra){return{...baseListOptions,...extra,noTruncate:!0,limit:void 0,offset:void 0,after:void 0}}async function loadContextCorpus(global2,runtime){const listed=await runList(void 0,buildUnpaginatedContextListOptions(runtime.baseListOptions,{excludeTerminal:!1}),global2),fullCorpus=listed.items,edgeCorpus=await loadContextEdgeCorpus(global2,listed);let listedItemMetadata=fullCorpus.filter(item=>!isTerminalStatus(item.status,runtime.statusRegistry)),allItems=fullCorpus;const subtreeIds=resolveContextSubtreeIds(runtime.parentScope,edgeCorpus);return subtreeIds&&(listedItemMetadata=listedItemMetadata.filter(item=>subtreeIds.has(item.id.trim().toLowerCase())),allItems=allItems.filter(item=>subtreeIds.has(item.id.trim().toLowerCase()))),{listed,listedItemMetadata,allItems,fullCorpus,edgeCorpus,subtreeIds}}function resolveContextSubtreeIds(parentScope,fullCorpus){if(parentScope===void 0)return;const subtree=collectSubtreeIds(fullCorpus,parentScope);if(!subtree.found)throw new PmCliError(`Context --parent item not found: ${parentScope}`,EXIT_CODE.NOT_FOUND);return subtree.ids}function collectHighLevelContextIds(activeItems,fullCorpus,statusRegistry,typeRegistry){const containers=new Set(computeActionabilityReport(activeItems,fullCorpus,statusRegistry,typeRegistry).containers.map(entry=>entry.item.id));return new Set(activeItems.filter(item=>HIGH_LEVEL_TYPES.has(item.type)||containers.has(item.id)||resolveItemExecutionRole(item.type,typeRegistry)!=="agent").map(item=>item.id))}async function resolveContextFocusGroups(listedItemMetadata,allItems,fullCorpus,blockedIds,statusRegistry,sectionsIncluded,limit,now,author,cursor,cursorFingerprint,useBoundedPage,pmRoot,tokenBudget,claimFocus,typeRegistry){const structural=[...listedItemMetadata].sort((left,right)=>compareCriticalItems(left,right,statusRegistry)),usage=await readContextUsageAffinity({pmRoot,author,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),featureStore=await readWorkspaceContextSignals(structural,{pmRoot,storeKey:"context",statusRegistry,now,author,usageAffinity:usage.affinity,claimFocus}),ranking=await scoreContextCandidatesWithActiveExtensions("context",featureStore.candidates),ranked=ranking.ranked.map(entry=>entry.item),activeStatuses=statusRegistry.active_statuses,rankedActiveItems=ranked.filter(item=>activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),pageStart=useBoundedPage?resolveQueryCursorStart(rankedActiveItems,cursor,cursorFingerprint,item=>item.id):0,focusPage=useBoundedPage?rankedActiveItems.slice(pageStart,pageStart+limit):rankedActiveItems,hasMore=useBoundedPage&&focusPage.length>0&&pageStart+focusPage.length<rankedActiveItems.length,nextCursor=hasMore&&focusPage.length>0?encodeQueryCursor(cursorFingerprint,focusPage[focusPage.length-1].id,pageStart+focusPage.length-1):void 0,rankedBlockedItems=ranked.filter(item=>blockedIds.has(item.id.trim().toLowerCase())),packingIds=new Set([...focusPage.map(item=>item.id),...rankedBlockedItems.filter(item=>!activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))).slice(0,limit).map(item=>item.id)]),packing=packRankedContextItems({...ranking,ranked:ranking.ranked.filter(entry=>packingIds.has(entry.id))},tokenBudget,new Set(Object.entries(claimFocus??{}).filter(([,affinity])=>affinity>=1).map(([id])=>id))),packedItems=packing.included.map(entry=>entry.item),activeItems=packedItems.filter(item=>activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),blockedItems=packedItems.filter(item=>blockedIds.has(item.id.trim().toLowerCase())),childrenByParent=buildChildrenByParent(allItems),focusChildrenByParent=contextNeedsAllItems(sectionsIncluded)?childrenByParent:void 0,fullCorpusById=new Map(fullCorpus.map(item=>[item.id.trim().toLowerCase(),item])),projectFocusItem=item=>{const focus=toContextFocusItem(item,statusRegistry,focusChildrenByParent);return blockedIds.has(item.id.trim().toLowerCase())&&(focus.blocked=!0,focus.blocker_ids=resolveItemBlockers(item,fullCorpusById,statusRegistry).filter(blocker=>!blocker.resolved).map(blocker=>blocker.id)),focus},highLevelIds=collectHighLevelContextIds(activeItems,fullCorpus,statusRegistry,typeRegistry),highLevel=activeItems.filter(item=>highLevelIds.has(item.id)).slice(0,useBoundedPage?focusPage.length:limit).map(projectFocusItem),lowLevel=activeItems.filter(item=>!highLevelIds.has(item.id)).slice(0,useBoundedPage?focusPage.length:limit).map(projectFocusItem),blockedFallbackUsed=rankedActiveItems.length===0;return{activeItems,blockedItems,highLevel,lowLevel,blockedFallback:blockedFallbackUsed?blockedItems.slice(0,limit).map(projectFocusItem):[],blockedFallbackUsed,ranking,packing,featureStore,pageExtras:{...useBoundedPage?{applied_limit:limit}:{},...hasMore?{has_more:!0,truncated:!0}:{},...nextCursor?{next_cursor:nextCursor}:{}}}}function buildContextCursorFingerprint(options,pmRoot){return createQueryFingerprint("context",{pmRoot,options:selectCursorSemanticOptions(options,CONTEXT_FLAG_CONTRACTS)})}function shouldPageContextFocus(options,corpusItemCount){return options.limit!==void 0||options.maxItems!==void 0||options.after!==void 0||corpusItemCount>=CONTEXT_SCALE_THRESHOLD}async function buildContextAgenda(global2,runtime,subtreeIds,listedFocusIds){const calendarOptions={...runtime.baseListOptions,after:void 0,view:"agenda",include:"all",limit:runtime.parentScope===void 0?String(runtime.limit):void 0},agenda=await runCalendar(calendarOptions,global2),scopedAgenda=subtreeIds===void 0?agenda.events:agenda.events.filter(event=>subtreeIds.has(event.item_id.trim().toLowerCase())),fullAgendaEvents=filterTerminalCalendarEvents(scopedAgenda,runtime.statusRegistry).slice(0,runtime.limit),agendaEvents=fullAgendaEvents.map(event=>listedFocusIds.has(event.item_id)?{at:event.at,date:event.date,kind:event.kind,item_id:event.item_id,reference_only:!0,...event.kind==="reminder"?{reminder_text:event.reminder_text}:{},...event.kind==="event"?{event_title:event.event_title,event_recurring:event.event_recurring}:{}}:event);return{agenda,agendaEvents,agendaSummary:summarizeAgenda(fullAgendaEvents)}}function countContextStatus(items,status,statusRegistry){const targetStatus=normalizeStatusForRegistry(String(status),statusRegistry);return items.filter(item=>normalizeStatusForRegistry(item.status,statusRegistry)===targetStatus).length}async function buildOptionalContextSections(params){const{runtime,allItems,fullCorpus,blockedIds,focusGroups,now,global:global2}=params,childrenByParent=buildChildrenByParent(allItems),allNonTerminal=allItems.filter(item=>!isTerminalStatus(item.status,runtime.statusRegistry)),has=section=>runtime.sectionsIncluded.includes(section);return{hierarchy:has("hierarchy")?buildHierarchy(allItems,focusGroups.activeItems,runtime.statusRegistry,runtime.limit):void 0,activity:has("activity")?await buildActivity(runtime.activityLimit,global2):void 0,progress:has("progress")?buildProgress(allItems,focusGroups.activeItems,blockedIds,runtime.statusRegistry,runtime.limit):void 0,blockersSection:has("blockers")?buildBlockers(focusGroups.blockedItems,fullCorpus,runtime.statusRegistry,runtime.limit):void 0,recentlyCreated:has("recently_created")?buildRecentlyCreated(allNonTerminal,runtime.statusRegistry,childrenByParent,runtime.limit):void 0,unparented:has("unparented")?buildUnparented(allNonTerminal,runtime.statusRegistry,childrenByParent,runtime.limit):void 0,filesSection:has("files")?buildHotFiles(focusGroups.activeItems,runtime.limit):void 0,workload:has("workload")?buildWorkload(focusGroups.activeItems,runtime.statusRegistry,runtime.limit):void 0,staleness:has("staleness")?buildStaleness(allNonTerminal,runtime.staleThresholdDays,now,runtime.limit):void 0,tests:has("tests")?buildTestHealth(allItems.filter(item=>runtime.statusRegistry.active_statuses.has(normalizeStatusForRegistry(item.status,runtime.statusRegistry)))):void 0}}function buildContextSummaryExtras(allItems,statusRegistry,blockedIds,inProgressWork){const canceledStatus=normalizeStatusInput("canceled",statusRegistry),activeItems=allItems.filter(item=>statusRegistry.active_statuses.has(normalizeStatusForRegistry(item.status,statusRegistry))),inProgress=countContextStatus(allItems,statusRegistry.in_progress_status,statusRegistry);return{scope:"matching_items",active_items:activeItems.length,open:activeItems.length-countContextStatus(activeItems,statusRegistry.in_progress_status,statusRegistry),in_progress:inProgress,...inProgressWork.unowned.count>0?{in_progress_unowned:inProgressWork.unowned.count}:{},...inProgressWork.idle.count>0?{in_progress_idle:inProgressWork.idle.count}:{},blocked:allItems.filter(item=>blockedIds.has(item.id.trim().toLowerCase())).length,total_items:allItems.length,closed:allItems.filter(item=>isClosedStatus(item.status,statusRegistry)).length,canceled:allItems.filter(item=>normalizeStatusForRegistry(item.status,statusRegistry)===canceledStatus).length}}function attachOptionalContextSections(result,sections,warningDetails){sections.hierarchy&&(result.hierarchy=sections.hierarchy),sections.activity&&(result.activity=sections.activity.rows,sections.activity.history_read&&(result.activity_history_read=sections.activity.history_read)),sections.progress&&(result.progress=sections.progress),sections.blockersSection&&(result.blockers=sections.blockersSection),sections.recentlyCreated&&(result.recently_created=sections.recentlyCreated),sections.unparented&&(result.unparented=sections.unparented),sections.filesSection&&(result.files=sections.filesSection),sections.workload&&(result.workload=sections.workload),sections.staleness&&(result.staleness=sections.staleness),sections.tests&&(result.tests=sections.tests),warningDetails!==void 0&&warningDetails.length>0&&(result.warning_details=warningDetails)}function applyContextFocusProjection(result,focusFields){focusFields&&(result.focus_fields=focusFields,result.high_level=projectContextFocusRows(result.high_level,focusFields),result.low_level=projectContextFocusRows(result.low_level,focusFields),result.blocked_fallback=projectContextFocusRows(result.blocked_fallback,focusFields),result.recently_created&&(result.recently_created=projectContextFocusRows(result.recently_created,focusFields)),result.unparented&&(result.unparented=projectContextFocusRows(result.unparented,focusFields)))}function applyContextTagProjection(result,noTags){const rows=[result.high_level,result.low_level,result.blocked_fallback,result.recently_created??[],result.unparented??[]].flat();if(noTags){for(const row of rows)delete row.tags,delete row.tags_inherited;return}const rowsById=new Map(rows.map(row=>[row.id,row])),originalTagSignatures=new Map(rows.map(row=>[row.id,row.tags?[...row.tags].sort().join("\0"):void 0]));for(const row of rows){if(!row.parent||!row.tags)continue;const parent=rowsById.get(row.parent);parent&&originalTagSignatures.get(row.id)===originalTagSignatures.get(parent.id)&&(delete row.tags,row.tags_inherited=parent.id)}}function maybeAttachEmptyContextSuggestions(result,activeItems,blockedItems){activeItems.length>0||blockedItems.length>0||result.agenda.events.length>0||(result.suggestions=['pm create --type Task --title "..." to add a new work item',"pm list --status closed --limit 5 to review recent completions","pm search <keywords> to find related past work","pm aggregate for a full project status overview"])}async function attachContextUsageFeedback(result,focusGroups,pmRoot,author){try{const included=new Set(focusGroups.packing.included.map(entry=>entry.id)),rows=focusGroups.ranking.ranked.map(entry=>({id:entry.id,rank:entry.rank,included:included.has(entry.id)})),rankedIds=new Set(rows.map(row=>row.id));for(const id of collectContextUsageDeliveredItemIds(result,"context"))rankedIds.has(id)||(rows.push({id,rank:rows.length+1,included:!1}),rankedIds.add(id));const receipt=await recordContextUsageServing({pmRoot,author,surface:"context",profile:focusGroups.packing.profile,rows,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});attachContextUsageServingReceipt(result,receipt)}catch{result.warnings=mergeSortedWarnings(result.warnings,["context_usage_feedback_write_failed"])}}async function resolveContextExtensionHealthProjection(omitted,pmRoot,settings){if(omitted)return{};const packages=(await discoverExtensions({pmRoot,settings,cwd:process.cwd(),noExtensions:!1})).discovered.map(diagnostic=>({name:diagnostic.name??diagnostic.directory,status:diagnostic.status==="ok"?"ok":"degraded"})).sort((left,right)=>left.name.localeCompare(right.name)),degraded=packages.filter(entry=>entry.status==="degraded").length;return packages.length===0?{}:{extension_health:{total:packages.length,ok:packages.length-degraded,degraded,packages:packages.slice(0,20),...packages.length>20?{truncated:!0}:{}}}}async function resolveContextSemanticAffinity(pmRoot,author){const identity=detectAgentIdentity(),semanticState=await readSessionState(pmRoot),attributionKey=identity.instance||semanticAttributionKey(author);return semanticAttributionAffinity(semanticState.semantic_attribution?.[attributionKey])}async function runContext(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),resolvedRuntime=await resolveContextRuntime(options,global2),corpus=await loadContextCorpus(global2,resolvedRuntime),scaledLimit=resolveContextLimitAtScale(resolvedRuntime.limit,corpus.fullCorpus.length),runtime={...resolvedRuntime,limit:scaledLimit,tokenBudget:resolveContextTokenBudget(options.tokenBudget,Math.max(256,scaledLimit*160))},author=resolveAuthor(void 0,runtime.settings.author_default),claimFocus=await resolveContextSemanticAffinity(pmRoot,author),extensionHealthPromise=resolveContextExtensionHealthProjection(options.noExtensionHealth===!0,pmRoot,runtime.settings),blockedIds=collectDependencyBlockedIds(corpus.edgeCorpus,runtime.statusRegistry),focusGroups=await resolveContextFocusGroups(corpus.listedItemMetadata,corpus.allItems,corpus.edgeCorpus,blockedIds,runtime.statusRegistry,runtime.sectionsIncluded,runtime.limit,nowIso(),author,options.after,buildContextCursorFingerprint(options,pmRoot),shouldPageContextFocus(options,corpus.fullCorpus.length),pmRoot,runtime.tokenBudget,claimFocus,resolveItemTypeRegistry(runtime.settings,getActiveExtensionRegistrations())),agendaContext=await buildContextAgenda(global2,runtime,corpus.subtreeIds,new Set([...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(item=>item.id))),workspaceMemory=await readWorkspaceMemory(corpus.fullCorpus,{pmRoot,statusRegistry:runtime.statusRegistry,now:agendaContext.agenda.now}),warnings=mergeSortedWarnings(corpus.listed.warnings,agendaContext.agenda.warnings,focusGroups.ranking.warnings,[...focusGroups.featureStore.warnings],workspaceMemory.warnings),inProgressCount=countContextStatus(focusGroups.activeItems,runtime.statusRegistry.in_progress_status,runtime.statusRegistry),openCount=focusGroups.activeItems.length-inProgressCount,sections=await buildOptionalContextSections({runtime,allItems:corpus.allItems,fullCorpus:corpus.edgeCorpus,blockedIds,focusGroups,now:agendaContext.agenda.now,global:global2}),summaryExtras=buildContextSummaryExtras(corpus.allItems,runtime.statusRegistry,blockedIds,await scanInProgressWork(pmRoot,corpus.allItems,{in_progress_status:runtime.statusRegistry.in_progress_status,status_registry:runtime.statusRegistry,threshold_hours:runtime.settings.mutation_guard.stale_in_progress_hours,now:new Date(agendaContext.agenda.now)})),result={output_default:"toon",now:agendaContext.agenda.now,depth:runtime.depth,sections_included:runtime.sectionsIncluded,window:{anchor:agendaContext.agenda.anchor,start:agendaContext.agenda.range.start,end:agendaContext.agenda.range.end,past:agendaContext.agenda.range.past,from:agendaContext.agenda.range.from,to:agendaContext.agenda.range.to},filters:{type:options.type??null,tag:options.tag??null,priority:options.priority??null,assignee:options.assignee??null,assignee_filter:options.assigneeFilter??null,sprint:options.sprint??null,release:options.release??null,limit:options.limit??options.maxItems??null,parent:runtime.parentScope??null,token_budget:runtime.tokenBudget,runtime_filters:corpus.listed.filters.runtime_filters??agendaContext.agenda.filters.runtime_filters??{}},summary:{returned_focus:{active_items:focusGroups.activeItems.length,in_progress:inProgressCount,open:openCount,blocked:focusGroups.blockedItems.length},blocked_fallback_used:focusGroups.blockedFallbackUsed,high_level:focusGroups.highLevel.length,low_level:focusGroups.lowLevel.length,agenda_events:agendaContext.agendaSummary.events,...summaryExtras},high_level:focusGroups.highLevel,low_level:focusGroups.lowLevel,blocked_fallback:focusGroups.blockedFallback,agenda:{summary:agendaContext.agendaSummary,events:agendaContext.agendaEvents},...focusGroups.pageExtras};return result.workspace_memory=selectWorkspaceMemory(workspaceMemory,Math.min(800,Math.floor(runtime.tokenBudget*.2))),Object.assign(result,await extensionHealthPromise),attachOptionalContextSections(result,sections,focusGroups.featureStore.warning_details),applyContextTagProjection(result,options.noTags===!0),options.explainRanking===!0&&(result.ranking=toContextRankingSummary(focusGroups.ranking,focusGroups.featureStore,new Set([...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(entry=>entry.id))),result.packing=toContextPackingSummary(focusGroups.packing)),rememberReadOutputFocusRows(result,[...focusGroups.highLevel,...focusGroups.lowLevel,...focusGroups.blockedFallback].map(row=>({id:row.id,status:normalizeStatusForRegistry(row.status,runtime.statusRegistry)===progressStatusOf(runtime.statusRegistry)?"in_progress":"open",blocked:row.blocked}))),applyContextFocusProjection(result,runtime.focusFields),refreshReadOutputDeliveredCounts(result),warnings.length>0&&(result.warnings=warnings),maybeAttachEmptyContextSuggestions(result,focusGroups.activeItems,focusGroups.blockedItems),await attachContextUsageFeedback(result,focusGroups,pmRoot,author),result}export{CONTEXT_OUTPUT_VALUES,_testOnly,applyContextTagProjection,buildChildrenByParent,buildItemContextRelevanceCandidates,collectSubtreeIds,compareCriticalItems,mergeSortedWarnings,packRankedContextItems,parseContextDepth,parseContextFocusFields,parseContextSections,projectContextFocusRows,renderContextMarkdown,resolveContextExtensionHealthProjection,resolveContextOutputFormat,resolveContextTokenBudget,runContext,toContextFocusItem,toContextPackingSummary,toContextRankingSummary};
|
|
3
3
|
//# sourceMappingURL=context.js.map
|
package/dist/sdk/query.d.ts
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Provides focused read, search, pagination, and context-ranking primitives.
|
|
5
5
|
*/
|
|
6
|
-
export * from "./query/list.js";export type{PmReadOutputMetadata}from "./read-output-contracts.js";export * from "./query/complete-list.js";export * from "./query/search.js";export{runActivity,type ActivityCommandOptions,type ActivityEntry,type ActivityResult,type CompactActivityEntry,}from "./query/activity.js";export * from "./query/aggregate.js";export * from "./query/calendar.js";export{CONTEXT_OUTPUT_VALUES,applyContextTagProjection,buildChildrenByParent,collectSubtreeIds,compareCriticalItems,mergeSortedWarnings,packRankedContextItems,parseContextDepth,parseContextFocusFields,parseContextSections,projectContextFocusRows,renderContextMarkdown,resolveContextOutputFormat,resolveContextTokenBudget,runContext,toContextFocusItem,toContextPackingSummary,toContextRankingSummary,type BlockerEntry,type ContextAgendaEvent,type ContextFocusItem,type ContextOptions,type ContextOutputFormat,type ContextPackingSummary,type ContextRankingSummary,type ContextResult,type HierarchyChild,type HierarchyNode,type HotFile,type ProgressEntry,type RecentContextItem,type StaleEntry,type TestHealthSummary,type WorkloadEntry,}from "./query/context.js";export * from "./query/get.js";export * from "./query/history.js";export * from "./query/next.js";export * from "./actionability.js";export * from "./query/search-pagination.js";export * from "./query/search-rendering.js";export * from "./query/item-filter-options.js";export * from "./query/multi-value-filters.js";export * from "./query/parsers.js";export * from "./pagination.js";export * from "./item-children.js";export * from "./item-metadata-index.js";export * from "./context-packing.js";export * from "./output/fit-envelope.js";export * from "./context-relevance.js";export * from "./context-signal-store.js";export * from "./context-usage.js";export * from "./workspace-memory.js";export * from "./duplicates.js";export{evaluateMetricFloors,parseEvalMetricFloors,EVAL_METRIC_NAMES,type EvalMetricFloors,}from "../core/search/eval-thresholds.js";export{analyzeDuplicateItems,type DuplicateItemInput,type DuplicateItemsAnalysis}from "./similarity.js";export{measureItemMetadataReadWork,type ItemMetadataReadWork}from "../core/store/item-metadata-read-work.js";export{executeEmbeddingBatchesWithRetry,type EmbeddingBatchReceipt,type EmbeddingBatchExecutionOptions,type EmbeddingBatchExecutionResult,type EmbeddingBatchProgressEvent,}from "../core/search/embedding-batches.js";export type{EmbeddingProviderConfig}from "../core/search/providers.js";export type{ItemTypeRegistry}from "../core/item/type-registry.js";export type{RuntimeStatusRegistry}from "../core/schema/runtime-schema.js";export type{GlobalOptions}from "../core/shared/command-types.js";export type{ContextDepth,ContextSectionName,ContextSettings,HistoryEntry,ItemMetadata,ItemStatus,ItemType,LinkScope,PmSettings}from "../types.js";export type{ContentFieldFilters}from "../core/governance/content-fields.js";export type{MissingMetadataFilters}from "../core/governance/metadata-coverage.js";export type{CliFlagContract}from "./cli-contracts/flag-contracts.js";export type{FilterValueEchoEntry}from "./query/list.js";export type{SearchRenderingQueryExpansion,SearchRenderingRerank}from "./query/search-rendering.js";export type{ImplicitSemanticFallbackReason,VectorIndexRecovery,VectorIndexRecoveryRegistrations}from "./query/search/semantic.js";export type{FindDuplicateClustersOptions}from "./similarity.js";
|
|
6
|
+
export * from "./query/list.js";export type{PmReadOutputMetadata}from "./read-output-contracts.js";export * from "./query/complete-list.js";export * from "./query/search.js";export{readRecentActivity,runActivity,type ActivityCommandOptions,type ActivityEntry,type ActivityHistoryReadReceipt,type ActivityResult,type CompactActivityEntry,type RecentActivityResult,}from "./query/activity.js";export * from "./query/aggregate.js";export * from "./query/calendar.js";export{CONTEXT_OUTPUT_VALUES,applyContextTagProjection,buildChildrenByParent,collectSubtreeIds,compareCriticalItems,mergeSortedWarnings,packRankedContextItems,parseContextDepth,parseContextFocusFields,parseContextSections,projectContextFocusRows,renderContextMarkdown,resolveContextOutputFormat,resolveContextTokenBudget,runContext,toContextFocusItem,toContextPackingSummary,toContextRankingSummary,type BlockerEntry,type ContextAgendaEvent,type ContextFocusItem,type ContextOptions,type ContextOutputFormat,type ContextPackingSummary,type ContextRankingSummary,type ContextResult,type HierarchyChild,type HierarchyNode,type HotFile,type ProgressEntry,type RecentContextItem,type StaleEntry,type TestHealthSummary,type WorkloadEntry,}from "./query/context.js";export * from "./query/get.js";export * from "./query/history.js";export * from "./query/next.js";export * from "./actionability.js";export * from "./query/search-pagination.js";export * from "./query/search-rendering.js";export * from "./query/item-filter-options.js";export * from "./query/multi-value-filters.js";export * from "./query/parsers.js";export * from "./pagination.js";export * from "./item-children.js";export * from "./item-metadata-index.js";export * from "./context-packing.js";export * from "./output/fit-envelope.js";export * from "./context-relevance.js";export * from "./context-signal-store.js";export * from "./context-usage.js";export * from "./workspace-memory.js";export * from "./duplicates.js";export{evaluateMetricFloors,parseEvalMetricFloors,EVAL_METRIC_NAMES,type EvalMetricFloors,}from "../core/search/eval-thresholds.js";export{analyzeDuplicateItems,type DuplicateItemInput,type DuplicateItemsAnalysis}from "./similarity.js";export{measureItemMetadataReadWork,type ItemMetadataReadWork}from "../core/store/item-metadata-read-work.js";export{executeEmbeddingBatchesWithRetry,type EmbeddingBatchReceipt,type EmbeddingBatchExecutionOptions,type EmbeddingBatchExecutionResult,type EmbeddingBatchProgressEvent,}from "../core/search/embedding-batches.js";export type{EmbeddingProviderConfig}from "../core/search/providers.js";export type{ItemTypeRegistry}from "../core/item/type-registry.js";export type{RuntimeStatusRegistry}from "../core/schema/runtime-schema.js";export type{GlobalOptions}from "../core/shared/command-types.js";export type{ContextDepth,ContextSectionName,ContextSettings,HistoryEntry,ItemMetadata,ItemStatus,ItemType,LinkScope,PmSettings}from "../types.js";export type{ContentFieldFilters}from "../core/governance/content-fields.js";export type{MissingMetadataFilters}from "../core/governance/metadata-coverage.js";export type{CliFlagContract}from "./cli-contracts/flag-contracts.js";export type{FilterValueEchoEntry}from "./query/list.js";export type{SearchRenderingQueryExpansion,SearchRenderingRerank}from "./query/search-rendering.js";export type{ImplicitSemanticFallbackReason,VectorIndexRecovery,VectorIndexRecoveryRegistrations}from "./query/search/semantic.js";export type{FindDuplicateClustersOptions}from "./similarity.js";
|
package/dist/sdk/query.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="92de6b54-8d32-5394-964c-854d01cea810")}catch{}})();export*from"./query/list.js";export*from"./query/complete-list.js";export*from"./query/search.js";import{readRecentActivity,runActivity}from"./query/activity.js";export*from"./query/aggregate.js";export*from"./query/calendar.js";import{CONTEXT_OUTPUT_VALUES,applyContextTagProjection,buildChildrenByParent,collectSubtreeIds,compareCriticalItems,mergeSortedWarnings,packRankedContextItems,parseContextDepth,parseContextFocusFields,parseContextSections,projectContextFocusRows,renderContextMarkdown,resolveContextOutputFormat,resolveContextTokenBudget,runContext,toContextFocusItem,toContextPackingSummary,toContextRankingSummary}from"./query/context.js";export*from"./query/get.js";export*from"./query/history.js";export*from"./query/next.js";export*from"./actionability.js";export*from"./query/search-pagination.js";export*from"./query/search-rendering.js";export*from"./query/item-filter-options.js";export*from"./query/multi-value-filters.js";export*from"./query/parsers.js";export*from"./pagination.js";export*from"./item-children.js";export*from"./item-metadata-index.js";export*from"./context-packing.js";export*from"./output/fit-envelope.js";export*from"./context-relevance.js";export*from"./context-signal-store.js";export*from"./context-usage.js";export*from"./workspace-memory.js";export*from"./duplicates.js";import{evaluateMetricFloors,parseEvalMetricFloors,EVAL_METRIC_NAMES}from"../core/search/eval-thresholds.js";import{analyzeDuplicateItems}from"./similarity.js";import{measureItemMetadataReadWork}from"../core/store/item-metadata-read-work.js";import{executeEmbeddingBatchesWithRetry}from"../core/search/embedding-batches.js";export{CONTEXT_OUTPUT_VALUES,EVAL_METRIC_NAMES,analyzeDuplicateItems,applyContextTagProjection,buildChildrenByParent,collectSubtreeIds,compareCriticalItems,evaluateMetricFloors,executeEmbeddingBatchesWithRetry,measureItemMetadataReadWork,mergeSortedWarnings,packRankedContextItems,parseContextDepth,parseContextFocusFields,parseContextSections,parseEvalMetricFloors,projectContextFocusRows,readRecentActivity,renderContextMarkdown,resolveContextOutputFormat,resolveContextTokenBudget,runActivity,runContext,toContextFocusItem,toContextPackingSummary,toContextRankingSummary};
|
|
2
2
|
//# sourceMappingURL=query.js.map
|