@unbrained/pm-cli 2026.11.25 → 2026.11.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/commander-usage.js +9 -9
  3. package/dist/cli/error-guidance.js +5 -5
  4. package/dist/cli/help-content.js +4 -4
  5. package/dist/cli/register-setup.js +1 -1
  6. package/dist/cli/runtime/selection.js +1 -1
  7. package/dist/cli-bundle/bundle-manifest.json +1 -1
  8. package/dist/cli-bundle/chunks/{chunk-CZEMEPPQ.js → chunk-5CMR4R5V.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-YIGBEY7K.js → chunk-5M7UTO2G.js} +2 -2
  10. package/dist/cli-bundle/chunks/chunk-63AVXDZS.js +2 -0
  11. package/dist/cli-bundle/chunks/{chunk-CONBVY2O.js → chunk-66TNCHHG.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-LPW7S5KA.js → chunk-6NJ3BONB.js} +2 -2
  13. package/dist/cli-bundle/chunks/chunk-AVHRMUXJ.js +3 -0
  14. package/dist/cli-bundle/chunks/{chunk-FVY7U3SU.js → chunk-HTT52JL3.js} +37 -37
  15. package/dist/cli-bundle/chunks/{chunk-OS5W4ZG2.js → chunk-J25DZRYJ.js} +31 -31
  16. package/dist/cli-bundle/chunks/chunk-J6TFG34A.js +4 -0
  17. package/dist/cli-bundle/chunks/{chunk-K34FR5CO.js → chunk-JX475QVU.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-KP75JTTO.js +35 -0
  19. package/dist/cli-bundle/chunks/chunk-KS47NGMQ.js +69 -0
  20. package/dist/cli-bundle/chunks/{chunk-BVJMVU4Z.js → chunk-O23KTJL6.js} +6 -6
  21. package/dist/cli-bundle/chunks/{chunk-DF6A7C32.js → chunk-OFX2VA5Z.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-FHLOGAGA.js → chunk-QVDEZBSV.js} +2 -2
  23. package/dist/cli-bundle/chunks/chunk-SIRZ4VMT.js +2 -0
  24. package/dist/cli-bundle/chunks/{chunk-C4KIZQHW.js → chunk-VC4BJIA7.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-GBVF2ZB3.js → chunk-W7SPEGSP.js} +2 -2
  26. package/dist/cli-bundle/chunks/chunk-WY7467RY.js +3 -0
  27. package/dist/cli-bundle/chunks/{chunk-7EPYCU7U.js → chunk-X6TE47CS.js} +5 -5
  28. package/dist/cli-bundle/chunks/chunk-XB6QEVUK.js +2 -0
  29. package/dist/cli-bundle/chunks/chunk-XYX4CXFR.js +2 -0
  30. package/dist/cli-bundle/chunks/{chunk-SCIPT7WF.js → chunk-Y5U7QCNX.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-L6VS7F3R.js → chunk-YGK6SA7P.js} +2 -2
  32. package/dist/cli-bundle/chunks/{chunk-OWK2JL4I.js → chunk-ZGV4ZXDS.js} +2 -2
  33. package/dist/cli-bundle/chunks/{chunk-CNUFU454.js → chunk-ZILIHDDY.js} +41 -41
  34. package/dist/cli-bundle/chunks/{field-option-collisions-QE65APSD.js → field-option-collisions-UL6BIPAK.js} +2 -2
  35. package/dist/cli-bundle/chunks/{item-revision-INDHJV6X.js → item-revision-WNUDY5DM.js} +2 -2
  36. package/dist/cli-bundle/chunks/item-transaction-ER3OWOPV.js +2 -0
  37. package/dist/cli-bundle/chunks/{mutation-actor-KU7BMLUN.js → mutation-actor-SFYTD2ZB.js} +2 -2
  38. package/dist/cli-bundle/chunks/{mutation-admission-3OMCTQD4.js → mutation-admission-AVOOT3KH.js} +2 -2
  39. package/dist/cli-bundle/chunks/{register-list-query-3GV3LBOT.js → register-list-query-Q7UW2EPV.js} +2 -2
  40. package/dist/cli-bundle/chunks/{register-mutation-GZLF47SX.js → register-mutation-YNW7E3T4.js} +2 -2
  41. package/dist/cli-bundle/chunks/{register-operations-PBJZGCAL.js → register-operations-DAUTQCIO.js} +2 -2
  42. package/dist/cli-bundle/chunks/register-setup-VSURGF7V.js +2 -0
  43. package/dist/cli-bundle/chunks/{stage-3WIZBD4N.js → stage-N5GDBS5A.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-X4EWD6TL.js → chunk-24W63UPP.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/{chunk-C3FEDTSD.js → chunk-2XGHBYDA.js} +26 -26
  46. package/dist/cli-bundle/focused-chunks/{chunk-ZLRRII55.js → chunk-3QRMY6KF.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/{chunk-PKX2EHE3.js → chunk-4HLZOOZI.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/chunk-52PHSTGP.js +27 -0
  49. package/dist/cli-bundle/focused-chunks/{chunk-YYEWIKNI.js → chunk-7FKGIJEB.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/chunk-7GZMOLQY.js +15 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-AL47ODFZ.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-AN4NFFLL.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/{chunk-BYQK5DGH.js → chunk-B2HJI6KA.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-JOKRDFMQ.js → chunk-C2HW7BSE.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/{chunk-TQIKDFOD.js → chunk-GISZWMBS.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-BOIMP2AR.js → chunk-GUAT4OAC.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-VU2PH4PF.js → chunk-H4JBS477.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-XKLBTDJ7.js → chunk-HGJ4MILN.js} +37 -37
  59. package/dist/cli-bundle/focused-chunks/{chunk-TRL4JDWX.js → chunk-HSWL6L2O.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{chunk-SXC2EO3E.js → chunk-I4GY7HAP.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/chunk-KMG4O2IU.js +4 -0
  62. package/dist/cli-bundle/focused-chunks/{chunk-4LQL4EO6.js → chunk-N7ZAMULP.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{chunk-UWWAVXG4.js → chunk-REORRDPH.js} +3 -3
  64. package/dist/cli-bundle/focused-chunks/{chunk-MB56Y4M6.js → chunk-SXWUKNTY.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{chunk-5RBC4WSE.js → chunk-UGQ2EXTU.js} +58 -59
  66. package/dist/cli-bundle/focused-chunks/chunk-YPOATPTX.js +3 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-7SSGTGZO.js → chunk-ZZYJS74B.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/{field-option-collisions-5ROXGUME.js → field-option-collisions-BP7ILGQK.js} +2 -2
  69. package/dist/cli-bundle/focused-chunks/{item-revision-KYMSQVZE.js → item-revision-NOHVIOQQ.js} +2 -2
  70. package/dist/cli-bundle/focused-chunks/{item-transaction-I4HLVHEJ.js → item-transaction-O26COBOJ.js} +2 -2
  71. package/dist/cli-bundle/focused-chunks/{mutation-actor-GGOQKAE6.js → mutation-actor-HVJV5S76.js} +2 -2
  72. package/dist/cli-bundle/focused-chunks/{mutation-admission-OS36ZCMH.js → mutation-admission-JRICEVYN.js} +2 -2
  73. package/dist/cli-bundle/focused-chunks/{stage-4ZFWJUKO.js → stage-NSX6ASBZ.js} +2 -2
  74. package/dist/cli-bundle/main.js +26 -26
  75. package/dist/cli-bundle/sdk-authoring.js +1 -1
  76. package/dist/cli-bundle/sdk-contracts.js +4 -4
  77. package/dist/cli-bundle/sdk-core.js +1 -1
  78. package/dist/cli-bundle/sdk-governance.js +1 -1
  79. package/dist/cli-bundle/sdk-graph.js +1 -1
  80. package/dist/cli-bundle/sdk-merge.js +63 -63
  81. package/dist/cli-bundle/sdk-query.js +1 -1
  82. package/dist/cli-bundle/sdk-runtime.js +1 -1
  83. package/dist/cli-bundle/sdk-testing.js +1 -1
  84. package/dist/cli-bundle/sdk.js +11 -11
  85. package/dist/core/extensions/index.js +1 -1
  86. package/dist/core/reproducibility/context.d.ts +2 -0
  87. package/dist/core/reproducibility/context.js +1 -1
  88. package/dist/core/shared/command-line.d.ts +2 -2
  89. package/dist/core/shared/command-line.js +1 -1
  90. package/dist/core/shared/secret-rules.js +5 -5
  91. package/dist/sdk/cli-bootstrap.d.ts +17 -0
  92. package/dist/sdk/cli-bootstrap.js +1 -1
  93. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  94. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  95. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  96. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  97. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  98. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  99. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  100. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  101. package/dist/sdk/cli-contracts.d.ts +1 -1
  102. package/dist/sdk/cli-contracts.js +1 -1
  103. package/dist/sdk/completion/shared.d.ts +1 -1
  104. package/dist/sdk/completion/shared.js +1 -1
  105. package/dist/sdk/extension/bundled-catalog.js +1 -1
  106. package/dist/sdk/extension/install-sources.js +5 -5
  107. package/dist/sdk/extension/listing-fields.d.ts +15 -0
  108. package/dist/sdk/extension/listing-fields.js +2 -0
  109. package/dist/sdk/extension/managed-update-status.js +1 -1
  110. package/dist/sdk/extension/npm-spec.d.ts +18 -0
  111. package/dist/sdk/extension/npm-spec.js +2 -0
  112. package/dist/sdk/extension/static-inventory.d.ts +53 -1
  113. package/dist/sdk/extension/static-inventory.js +1 -1
  114. package/dist/sdk/extension/update-check.js +1 -1
  115. package/dist/sdk/extension/update-observations.js +3 -0
  116. package/dist/sdk/extension/upgrade-hints.js +2 -0
  117. package/dist/sdk/extension.d.ts +2 -0
  118. package/dist/sdk/extension.js +1 -1
  119. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  120. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  121. package/dist/sdk/governance/upgrade.d.ts +7 -2
  122. package/dist/sdk/governance/upgrade.js +2 -2
  123. package/dist/sdk/index.d.ts +1 -1
  124. package/dist/sdk/public-surface.json +1 -1
  125. package/dist/sdk/query/context.d.ts +20 -7
  126. package/dist/sdk/query/context.js +4 -2
  127. package/dist/sdk/runtime-input.js +1 -1
  128. package/dist/sdk/testing.d.ts +20 -2
  129. package/docs/COMMANDS.md +19 -1
  130. package/docs/CONFIGURATION.md +1 -1
  131. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +6 -0
  132. package/docs/EXTENSION_LIFECYCLE.md +72 -2
  133. package/docs/MUTATION_INTEGRITY.md +47 -0
  134. package/docs/SDK.md +24 -3
  135. package/marketplace.json +1 -1
  136. package/package.json +1 -1
  137. package/packages/pm-beads/package.json +1 -1
  138. package/packages/pm-calendar/package.json +1 -1
  139. package/packages/pm-command-kit/package.json +1 -1
  140. package/packages/pm-digital-twin/package.json +1 -1
  141. package/packages/pm-governance-audit/package.json +1 -1
  142. package/packages/pm-guide-shell/package.json +1 -1
  143. package/packages/pm-kanban/package.json +1 -1
  144. package/packages/pm-lifecycle-hooks/package.json +1 -1
  145. package/packages/pm-linked-test-adapters/package.json +1 -1
  146. package/packages/pm-search-advanced/package.json +1 -1
  147. package/packages/pm-templates/package.json +1 -1
  148. package/packages/pm-todos/package.json +1 -1
  149. package/packages/pm-vcs/package.json +1 -1
  150. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  151. package/plugins/pm-claude/package.json +1 -1
  152. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  153. package/plugins/pm-codex/package.json +1 -1
  154. package/plugins/pm-codex/plugin.json +1 -1
  155. package/runtime-dependencies.json +1 -1
  156. package/dist/cli-bundle/chunks/chunk-4FZH5BTV.js +0 -2
  157. package/dist/cli-bundle/chunks/chunk-GZI7ZAB7.js +0 -2
  158. package/dist/cli-bundle/chunks/chunk-LOX3VY4T.js +0 -2
  159. package/dist/cli-bundle/chunks/chunk-VA4T37Q4.js +0 -70
  160. package/dist/cli-bundle/chunks/chunk-WQOEVGLQ.js +0 -2
  161. package/dist/cli-bundle/chunks/chunk-XHCIOLJP.js +0 -3
  162. package/dist/cli-bundle/chunks/chunk-XKWJONAO.js +0 -2
  163. package/dist/cli-bundle/chunks/chunk-ZBOQEZ2H.js +0 -33
  164. package/dist/cli-bundle/chunks/chunk-ZLICQPRG.js +0 -3
  165. package/dist/cli-bundle/chunks/item-transaction-LCKK4XXB.js +0 -2
  166. package/dist/cli-bundle/chunks/register-setup-ZLJEF6NZ.js +0 -2
  167. package/dist/cli-bundle/focused-chunks/chunk-3Y5PTQ2F.js +0 -27
  168. package/dist/cli-bundle/focused-chunks/chunk-A4R57E4K.js +0 -2
  169. package/dist/cli-bundle/focused-chunks/chunk-IAOKVKWW.js +0 -2
  170. package/dist/cli-bundle/focused-chunks/chunk-VMYVN36N.js +0 -13
  171. package/dist/cli-bundle/focused-chunks/chunk-WL2R7T5G.js +0 -2
  172. package/dist/cli-bundle/focused-chunks/chunk-WVA5KOXF.js +0 -3
@@ -1,8 +1,3 @@
1
- /**
2
- * @module sdk/query/context
3
- *
4
- * Implements the pm context command surface and its agent-facing runtime behavior.
5
- */
6
1
  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
2
  /** Supported values accepted by the context output contract. */
8
3
  export declare const CONTEXT_OUTPUT_VALUES:readonly["markdown","toon","json","ndjson"];
@@ -226,10 +221,28 @@ total:number;
226
221
  ok:number;
227
222
  /** Number of degraded installed extensions. */
228
223
  degraded:number;
224
+ /** Copies static discovery selects (not activation truth; no module is imported) whose last observed `pm package manage` check found a newer release (pm-gh1778). */
225
+ updates_available?:number;
226
+ /** One live `pm package manage --<scope>` check per scope with a known update, whose remediation names the upgrade; present only when `updates_available` is above zero. */
227
+ next?:string[];
229
228
  /** Per-package static discovery health. */
230
- packages:Array<{name:string;status:"ok"|"degraded";}>;
229
+ packages:ContextExtensionHealthRow[];
231
230
  /** Whether package rows were capped. */
232
231
  truncated?:true;}
232
+ /** One installed copy in `extension_health` (pm-gh1778). */
233
+ export interface ContextExtensionHealthRow{
234
+ /** Manifest name, or the directory name when the manifest is unreadable. */
235
+ name:string;
236
+ /** Storage scope of this copy. */
237
+ scope?:"project"|"global";
238
+ /** Manifest version, or null when unreadable. */
239
+ version?:string|null;
240
+ /** Static discovery health of this copy. */
241
+ status:"ok"|"degraded";
242
+ /** Newer version the last `pm package manage` check observed for this installed version; null when none is known. */
243
+ update?:string|null;
244
+ /** Scope of the same-named copy static discovery selects instead of this one; null when this copy is the selected one. Static selection, not activation truth. */
245
+ shadowed_by?:"project"|"global"|null;}
233
246
  interface ContextAgendaSummary{events:number;items:number;deadlines:number;reminders:number;scheduled:number;}
234
247
  interface ContextSummary{
235
248
  /** Population counters honor item filters and parent scope, never output limits. */
@@ -405,6 +418,6 @@ export declare function renderContextMarkdown(result:ContextResult):string;
405
418
  */
406
419
  export declare function applyContextTagProjection(result:ContextResult,noTags:boolean):void;
407
420
  /** Resolve the optional static extension-health projection without module imports. */
408
- export declare function resolveContextExtensionHealthProjection(omitted:boolean,pmRoot:string,settings:PmSettings):Promise<Pick<ContextResult,"extension_health">>;
421
+ export declare function resolveContextExtensionHealthProjection(omitted:boolean,pmRoot:string,settings:PmSettings,noExtensions?:boolean):Promise<Pick<ContextResult,"extension_health">>;
409
422
  /** Implements run context for the public runtime surface of this module. */
410
423
  export declare function runContext(options:ContextOptions,global:GlobalOptions):Promise<ContextResult>;
@@ -1,3 +1,5 @@
1
- import{scanInProgressWork as Qe}from"../governance/stale-work.js";import{SETTINGS_DEFAULTS as Ye,EXIT_CODE as b,PmCliError as w,compareTimestampStrings as V,nowIso as et,isTerminalStatus as ce,normalizeStatusForRegistry as _,normalizeStatusInput as j,resolveRuntimeStatusRegistry as tt,resolvePmRoot as de,readSettings as nt,resolveAuthor as ot,discoverExtensions as st,resolveItemTypeRegistry as it}from"../runtime-primitives.js";import{getActiveExtensionRegistrations as rt}from"../../core/extensions/index.js";import{collectDependencyBlockedIds as at,resolveItemBlockers as le,resolveItemExecutionRole as ct,computeActionabilityReport as dt}from"../actionability.js";import{CONTEXT_DEPTH_VALUES as ue,CONTEXT_SECTION_VALUES as K}from"../../types/index.js";import{parseIntegerLimit as fe}from"./parsers.js";import{runCalendar as lt}from"./calendar.js";import{runList as pe}from"./list.js";import{readRecentActivity as ut}from"./activity.js";import{scoreContextCandidatesWithActiveExtensions as ft}from"../context-relevance.js";import{buildItemContextRelevanceCandidates as ao}from"../context-relevance.js";import{createQueryFingerprint as pt,encodeQueryCursor as mt,resolveQueryCursorStart as ht,selectCursorSemanticOptions as _t}from"../pagination.js";import{rememberReadOutputFocusRows as gt,refreshReadOutputDeliveredCounts as kt}from"../read-output-rows.js";import{CONTEXT_FLAG_CONTRACTS as yt}from"../cli-contracts/flag-contracts.js";import{packContextCandidates as bt}from"../context-packing.js";import{attachContextUsageServingReceipt as wt,collectContextUsageDeliveredItemIds as $t,readContextUsageAffinity as Ct,recordContextUsageServing as St}from"../context-usage.js";import{readWorkspaceContextSignals as vt}from"../context-signal-store.js";import{readWorkspaceMemory as xt,selectWorkspaceMemory as Tt}from"../workspace-memory.js";import{detectAgentIdentity as It}from"../../core/shared/author.js";import{readSessionState as Et,semanticAttributionKey as Lt}from"../../core/session/session-state.js";import{semanticAttributionAffinity as At}from"../context/semantic-session-attribution.js";const Ot=["markdown","toon","json","ndjson"],M=new Set(["Epic","Feature"]),J=10,me=1e4,he=["hierarchy","activity","progress","recently_created","unparented","workload"],Nt=[...he,"blockers","files","staleness","tests"],Ft=/^(\d{4})-(\d{2})-(\d{2})/,Dt=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/,jt=/^(\d{4})(\d{2})(\d{2})$/,Mt=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?(Z|[+-]\d{2}:?\d{2})?$/i;function Pt(e){if(!e)return;const t=e.trim().toLowerCase();if(!Ot.includes(t))throw new w("Context format must be one of markdown|toon|json|ndjson",b.USAGE);return t}const _e=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 Ut(e){if(e===void 0)return;const t=[];for(const n of e.split(",")){const s=n.trim().toLowerCase();if(s.length!==0){if(!_e.has(s))throw new w(`Context --fields value not projectable: ${s} (valid: ${[..._e].join(", ")})`,b.USAGE);t.includes(s)||t.push(s)}}if(t.length===0)throw new w("Context --fields requires at least one field name",b.USAGE);return t}function L(e,t){return e.map(n=>{const s={},o=n;for(const i of t)s[i]=o[i]??null;return s})}function to(e,t){const n=Pt(e.format);if(t.json&&n&&n!=="json"&&n!=="ndjson")throw new w("Cannot combine --json with --format markdown|toon",b.USAGE);return t.json?n==="ndjson"?"ndjson":"json":n??"toon"}function ge(e,t){return fe(e,"--limit")??(t==="full"?Number.MAX_SAFE_INTEGER:J)}function Bt(e,t){if(e===void 0)return t;const n=typeof e=="number"?e:Number(e);if(!Number.isInteger(n)||n<1)throw new w("--token-budget must be a positive integer",b.USAGE);return n}function ke(e,t){return t>=me&&e===Number.MAX_SAFE_INTEGER?J:e}function Ht(e,t){if(!e)return t.default_depth;const n=e.trim().toLowerCase();if(!ue.includes(n))throw new w(`Context --depth must be one of ${ue.join("|")}`,b.USAGE);return n}function Gt(e,t,n){if(e&&e.length>0){const o=[];for(const i of e){const r=i.trim().toLowerCase();if(!K.includes(r))throw new w(`Context --section must be one of ${K.join("|")}`,b.USAGE);o.includes(r)||o.push(r)}return o}return t==="brief"?[]:t==="full"?[...K]:(t==="deep"?Nt:he).filter(o=>n.sections[o])}function ye(e,t){return e?fe(e,"--activity-limit")??t.activity_limit:t.activity_limit}function be(e,t){if(!e)return t.stale_threshold_days;const n=e.trim().toLowerCase(),s=/^(\d+)d?$/.exec(n);if(!s)throw new w("--stale-threshold must be a number of days (e.g. 7 or 7d)",b.USAGE);const o=parseInt(s[1],10);if(o<=0)throw new w("--stale-threshold must be positive",b.USAGE);return o}function P(e){return _(e.in_progress_status,e)}function Z(e,t){const n=_(e,t),s=j("blocked",t),o=j("draft",t);return n===P(t)?0:t.active_statuses.has(n)?1:s&&n===s?2:o&&n===o?3:t.blocked_statuses.has(n)?5:t.terminal_statuses.has(n)?7:6}function x(e,t){const n=j("closed",t);return _(e,t)===n}function U(e,t){return _(e,t)===P(t)}function q(e,t){const n=_(e,t);return n!==P(t)&&t.active_statuses.has(n)}function we(e,t){return t.blocked_statuses.has(_(e,t))}const Rt=["compact","brief","fields","includeBody","include_body","parent"];function $e(e){const t={...e};for(const n of Rt)delete t[n];return t}function Ce(e,t){const n=t.trim().toLowerCase(),s=e.find(c=>c.id.trim().toLowerCase()===n);if(!s)return{ids:new Set,found:!1};const o=N(e),i=T(s.id,o);return{ids:new Set([s.id,...i.map(c=>c.id)].map(c=>c.trim().toLowerCase())),found:!0}}function Se(e){if(e===void 0)return;const t=e.trim();if(t.length===0)throw new w("Context --parent requires an item id",b.USAGE);return t}function ve(e,t){const n=e??null,s=t??null;return n===null&&s===null?0:n===null?1:s===null?-1:n-s}function xe(e,t){const n=e??null,s=t??null;return n===null&&s===null?0:n===null?1:s===null?-1:V(n,s)}function zt(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}function Xt(e){const t=Ft.exec(e)??Dt.exec(e);if(!t)return!0;const n=Number.parseInt(t[1],10),s=Number.parseInt(t[2],10),o=Number.parseInt(t[3],10);return s>=1&&s<=12&&o>=1&&o<=zt(n,s-1)}function Wt(e){const t=jt.exec(e);if(t)return`${t[1]}-${t[2]}-${t[3]}`;const n=Mt.exec(e);if(n){const[,s,o,i,r,c,a,l]=n,f=a?`:${a}`:"",d=l&&l.length===5&&l!=="Z"?`${l.slice(0,3)}:${l.slice(3)}`:l??"";return`${s}-${o}-${i}T${r}:${c}${f}${d}`}return e}function Q(e){if(typeof e!="string")return Number.NaN;const t=e.trim();if(t.length===0||!Xt(t))return Number.NaN;const n=Date.parse(Wt(t));return Number.isFinite(n)?n:Number.NaN}function B(e){const t=Q(e);return Number.isFinite(t)?new Date(t).toISOString():""}function Te(e){const t=Q(e);return Number.isFinite(t)?new Date(t).toISOString().slice(0,10):"unknown"}function H(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function A(e,t,n){const s=Z(e.status,n)-Z(t.status,n);if(s!==0)return s;const o=e.priority-t.priority;if(o!==0)return o;const i=ve(e.order,t.order);if(i!==0)return i;const r=xe(e.deadline,t.deadline);if(r!==0)return r;const c=V(B(t.updated_at),B(e.updated_at)),a=e.id.localeCompare(t.id);return c!==0?c:a}function G(e){return Math.max(1,Math.ceil(Buffer.byteLength(JSON.stringify(e),"utf8")/4))}function Vt(e,t,n=new Set,s="context"){return bt(e.ranked.map(o=>({id:o.id,item:o.item,rank:o.rank,score:o.score,required:n.has(o.id),cluster:o.item.parent?.trim()||o.item.type,token_costs:{identity:G({id:o.id,title:o.item.title}),summary:G({id:o.id,title:o.item.title,type:o.item.type,status:o.item.status,priority:o.item.priority,parent:o.item.parent}),full:G(o.item)}})),{tokenBudget:t,profile:s,latencyBudgetMs:25})}function Kt(e){return{...e,included:e.included.map(t=>({id:t.id,projection:t.projection,tokens:t.tokens}))}}function Jt(e,t,n){const s=n===void 0?e.ranked:e.ranked.filter(o=>n.has(o.id));return{model:e.model,available_signals:e.available_signals,items:s.map(o=>({id:o.id,rank:o.rank,baseline_rank:o.baseline_rank,score:o.score,contributions:o.contributions,...o.signal_provenance===void 0?{}:{recency:o.signal_provenance.recency}})),candidate_count:e.ranked.length,omitted_count:e.ranked.length-s.length,...t?{feature_store:{source:t.snapshot.source,cache_status:t.cache_status,source_cursor:t.snapshot.source_cursor,generated_at:t.snapshot.generated_at}}:{}}}function O(e,t){return t>0?Math.round(e*100/t):0}function N(e){const t=new Map;for(const n of e){const s=H(n.parent);if(!s)continue;const o=t.get(s)??[];o.push(n),t.set(s,o)}return t}function R(e,t,n){const s={id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,order:e.order??null,deadline:e.deadline??null,assignee:e.assignee??null,tags:Array.isArray(e.tags)?[...e.tags]:[],updated_at:e.updated_at,parent:H(e.parent)};if(t&&n){const o=T(e.id,n),i=o.length;if(i>0){const r=o.filter(c=>x(c.status,t)).length;s.children_total=i,s.children_closed=r,s.completion_pct=O(r,i)}}return s}function Ie(e){let t=0,n=0,s=0;const o=new Set;for(const i of e){if(o.add(i.item_id),i.kind==="deadline"){t+=1;continue}if(i.kind==="reminder"){n+=1;continue}s+=1}return{events:e.length,items:o.size,deadlines:t,reminders:n,scheduled:s}}function Y(...e){return[...new Set(e.flatMap(t=>t??[]))].sort((t,n)=>t.localeCompare(n))}function Ee(e,t){return e.filter(n=>!t.terminal_statuses.has(_(n.item_status,t)))}function Le(e,t,n,s){const o=new Map;for(const a of e)o.set(a.id,a);const i=N(e),r=new Set(t.filter(a=>M.has(a.type)).map(a=>a.id)),c=[];for(const a of r){const l=o.get(a);if(!l)continue;const f=T(a,i),d=i.get(a)??[];let p=0,$=0,y=0,g=0;for(const h of f)x(h.status,n)?p++:U(h.status,n)?y++:we(h.status,n)?g++:q(h.status,n)&&$++;const I=d.sort((h,C)=>A(h,C,n)).slice(0,s).map(h=>{const C=T(h.id,i),m=C.filter(k=>x(k.status,n)).length;return{id:h.id,title:h.title,type:h.type,status:h.status,children_total:C.length,children_closed:m}});c.push({id:l.id,title:l.title,type:l.type,status:l.status,children_total:f.length,children_closed:p,children_open:$,children_in_progress:y,children_blocked:g,children:I})}return c.sort((a,l)=>{const f=o.get(a.id),d=o.get(l.id);return A(f,d,n)}).slice(0,s)}function T(e,t){const n=[],s=[e],o=new Set;for(;s.length>0;){const i=s.pop();if(o.has(i))continue;o.add(i);const r=t.get(i)??[];for(const c of r)n.push(c),s.push(c.id)}return n}const no={buildActivity:Ae,buildBlockers:Ne,buildChildrenByParent:N,buildHierarchy:Le,buildHotFiles:Fe,buildProgress:Oe,buildRecentlyCreated:Me,buildStaleness:je,buildTestHealth:Ue,buildUnparented:Pe,buildWorkload:De,collectDescendants:T,collectSubtreeIds:Ce,compareCriticalItems:A,compareOptionalDeadline:xe,compareOptionalOrder:ve,completionPct:O,dateTokenForTimestamp:Te,filterTerminalCalendarEvents:Ee,formatAgendaLine:Ge,isBlockedStatus:we,isClosedStatus:x,isInProgressStatus:U,isOpenStatus:q,mergeSortedWarnings:Y,normalizedParentId:H,parseActivityLimit:ye,parseContextLimit:ge,resolveContextLimitAtScale:ke,parseContextParent:Se,parseContextTimestampMs:Q,parseStaleThresholdDays:be,sortableTimestamp:B,statusRank:Z,stripListProjectionFlags:$e,summarizeAgenda:Ie,toContextFocusItem:R};async function Ae(e,t){return ut({limit:e},t)}function Oe(e,t,n,s,o){const i=new Map;for(const a of e){if(!a.parent)continue;const l=i.get(a.parent)??[];l.push(a),i.set(a.parent,l)}const r=t.filter(a=>M.has(a.type)),c=[];for(const a of r){const l=T(a.id,i),f=l.length;if(f===0)continue;let d=0,p=0,$=0,y=0;for(const g of l)x(g.status,s)?d++:n.has(g.id.trim().toLowerCase())?y++:U(g.status,s)?$++:q(g.status,s)&&p++;c.push({id:a.id,title:a.title,type:a.type,total:f,closed:d,open:p,in_progress:$,blocked:y,completion_pct:O(d,f)})}return c.sort((a,l)=>a.completion_pct-l.completion_pct).slice(0,o)}function Ne(e,t,n,s){const o=new Map(t.map(i=>[i.id.trim().toLowerCase(),i]));return e.slice(0,s).map(i=>{const r=le(i,o,n),c=r.find(l=>!l.resolved)?.id??r[0]?.id??null,a=c?o.get(c.trim().toLowerCase()):void 0;return{id:i.id,title:i.title,blocked_by:c,blocked_by_title:a?.title??null,blocked_by_status:a?.status??null,blocked_reason:i.blocked_reason??null,unblock_note:i.unblock_note??null}})}function Fe(e,t){const n=new Map;for(const s of e)for(const o of s.files??[]){const i=n.get(o.path)??new Set;i.add(s.id),n.set(o.path,i)}return[...n.entries()].map(([s,o])=>({path:s,references:o.size,items:[...o].sort()})).sort((s,o)=>o.references-s.references).slice(0,t)}function De(e,t,n){const s=new Map;for(const o of e){const i=o.assignee??null,r=s.get(i)??[];r.push(o),s.set(i,r)}return[...s.entries()].map(([o,i])=>({assignee:o,active:i.length,in_progress:i.filter(r=>U(r.status,t)).length,items:i.map(r=>r.id).sort()})).sort((o,i)=>i.active-o.active).slice(0,n)}function je(e,t,n,s){const o=new Date(n).getTime()-t*24*60*60*1e3;return e.filter(i=>new Date(i.updated_at).getTime()<o).map(i=>({id:i.id,title:i.title,status:i.status,updated_at:i.updated_at,stale_days:Math.floor((new Date(n).getTime()-new Date(i.updated_at).getTime())/(1440*60*1e3))})).sort((i,r)=>r.stale_days-i.stale_days).slice(0,s)}function Me(e,t,n,s){return e.map(o=>({item:o,sortKey:B(o.created_at)})).sort((o,i)=>{const r=V(i.sortKey,o.sortKey);return r!==0?r:o.item.id.localeCompare(i.item.id)}).slice(0,s).map(({item:o})=>({...R(o,t,n),created_at:o.created_at}))}function Pe(e,t,n,s){return e.filter(o=>!H(o.parent)&&!M.has(o.type)).sort((o,i)=>A(o,i,t)).slice(0,s).map(o=>R(o,t,n))}function Ue(e){let t=0,n=0,s=0,o=0,i=0;const r=[];for(const c of e){(c.tests??[]).length>0&&t++;const a=c.test_runs??[];if(a.length>0){n++;let l=!1;for(const f of a)s+=f.passed??0,o+=f.failed??0,i+=f.skipped??0,(f.failed??0)>0&&(l=!0);l&&r.push(c.id)}}return{scope:"matching_active_items",total_items:e.length,items_with_tests:t,items_with_recent_runs:n,recent_runs:{passed:s,failed:o,skipped:i},items_failing:r.sort()}}function Be(e){return`${new Date(e).toISOString().slice(11,16)}Z`}function He(e){const t=e.order===null?"-":String(e.order),n=e.deadline??"-",s=e.parent?` parent:${e.parent}`:"",o=e.children_total!==void 0&&e.children_closed!==void 0&&e.completion_pct!==void 0?` children:${e.children_closed}/${e.children_total} done:${e.completion_pct}%`:"",i=e.blocked===!0?` blocked:${e.blocker_ids?.join(",")||"lifecycle"}`:"";return`${e.id} p${e.priority} ${e.status} ${e.type} order:${t} deadline:${n}${s}${o}${i} ${e.title}`}function Zt(e,t){const n=e;return t.map(s=>{const o=n[s];return Array.isArray(o)?`${s}:${o.join(",")}`:`${s}:${o??"-"}`}).join(" ")}function Ge(e){if("reference_only"in e){const n=e.kind==="reminder"?` \u2014 ${e.reminder_text??"reminder"}`:e.kind==="event"?` \u2014 ${e.event_title??"event"}${e.event_recurring?" (recurring)":""}`:"";return`${Be(e.at)} [${e.kind}] ${e.item_id} (see focus item)${n}`}const t=`${Be(e.at)} [${e.kind}] ${e.item_id} p${e.item_priority} ${e.item_status} ${e.item_title}`;if(e.kind==="reminder")return`${t} \u2014 ${e.reminder_text}`;if(e.kind==="event"){const n=e.event_recurring?" (recurring)":"",s=e.event_title??e.item_title;return`${t} \u2014 ${s}${n}`}return t}function Re(e,t,n,s,o){if(e.push(`## ${t}`),n.length===0)e.push(s);else for(const i of n)e.push(`- ${o(i)}`);e.push("")}function qt(e,t,n){if(t.blocked_fallback.length!==0){e.push("## Blocked fallback");for(const s of t.blocked_fallback)e.push(`- ${n(s)}`);e.push("")}}function Qt(e,t){if(e.push("## Agenda"),e.push(`- events: ${t.agenda.summary.events} (deadlines: ${t.agenda.summary.deadlines}, reminders: ${t.agenda.summary.reminders}, scheduled: ${t.agenda.summary.scheduled})`),t.agenda.events.length===0)e.push("No agenda events matched the selected filters.");else for(const n of t.agenda.events)e.push(`- ${Ge(n)}`);e.push("")}function Yt(e,t){if(!(!t.hierarchy||t.hierarchy.length===0)){e.push("## Hierarchy");for(const n of t.hierarchy){const s=O(n.children_closed,n.children_total);e.push(`- ${n.id} ${n.type} ${n.status} "${n.title}" [${n.children_closed}/${n.children_total} done ${s}%]`);for(const o of n.children){const i=O(o.children_closed,o.children_total);e.push(` - ${o.id} ${o.type} ${o.status} "${o.title}" [${o.children_closed}/${o.children_total} done ${i}%]`)}}e.push("")}}function en(e,t){if(!(!t.progress||t.progress.length===0)){e.push("## Progress");for(const n of t.progress)e.push(`- ${n.id} "${n.title}" ${n.completion_pct}% (${n.closed}/${n.total} closed, ${n.in_progress} wip, ${n.open} open, ${n.blocked} blocked)`);e.push("")}}function tn(e,t,n,s){if(!(!t.recently_created||t.recently_created.length===0)){e.push("## Recently created");for(const o of t.recently_created)e.push(n?`- ${s(o)}`:`- ${Te(o.created_at)} ${He(o)}`);e.push("")}}function nn(e,t,n){if(!(!t.unparented||t.unparented.length===0)){e.push("## Unparented");for(const s of t.unparented)e.push(`- ${n(s)}`);e.push("")}}function on(e,t){const n=t.activity_history_read;if(!((!t.activity||t.activity.length===0)&&n===void 0)){e.push("## Recent activity");for(const s of t.activity??[]){const o=s.msg?` ${s.msg}`:"";e.push(`- ${s.ts.slice(0,16)}Z ${s.id} ${s.op} by:${s.author}${o}`)}n!==void 0&&e.push(`- history read: ${n.reason}, ${n.streams_read}/${n.streams_total} streams parsed`),e.push("")}}function sn(e,t){if(!(!t.blockers||t.blockers.length===0)){e.push("## Blockers");for(const n of t.blockers){const s=n.blocked_by?`blocked_by:${n.blocked_by}(${n.blocked_by_status??"?"})`:"blocked_by:-",o=n.blocked_reason?` reason:"${n.blocked_reason}"`:"",i=n.unblock_note?` unblock:"${n.unblock_note}"`:"";e.push(`- ${n.id} "${n.title}" ${s}${o}${i}`)}e.push("")}}function rn(e,t){if(!(!t.files||t.files.length===0)){e.push("## Hot files");for(const n of t.files)e.push(`- ${n.path} refs:${n.references} items:[${n.items.join(",")}]`);e.push("")}}function an(e,t){if(!(!t.workload||t.workload.length===0)){e.push("## Workload");for(const n of t.workload){const s=n.assignee??"(unassigned)";e.push(`- ${s} active:${n.active} wip:${n.in_progress} items:[${n.items.join(",")}]`)}e.push("")}}function cn(e,t){if(!(!t.staleness||t.staleness.length===0)){e.push("## Stale items");for(const n of t.staleness)e.push(`- ${n.id} ${n.status} stale:${n.stale_days}d last:${n.updated_at.slice(0,10)} "${n.title}"`);e.push("")}}function dn(e,t,n){const s=[];let o=0;for(const i of e.items_failing){if(s.length>=t)break;const r=G(i);if(o+r>n)break;s.push(i),o+=r}return s}function ln(e,t){if(!t.tests)return;e.push("## Test health"),e.push(`- ${t.tests.scope}: ${t.tests.total_items}`),e.push(`- items_with_tests: ${t.tests.items_with_tests}`),e.push(`- items_with_recent_runs: ${t.tests.items_with_recent_runs}`),e.push(`- passed: ${t.tests.recent_runs.passed}, failed: ${t.tests.recent_runs.failed}, skipped: ${t.tests.recent_runs.skipped}`);const n=dn(t.tests,t.applied_limit??J,t.filters.token_budget);n.length>0&&e.push(`- items_failing: [${n.join(",")}]`);const s=t.tests.items_failing.length-n.length;s>0&&e.push(`- items_failing_omitted: ${s}`),e.push("")}function un(e,t){t.summary.active_items===0&&t.summary.blocked===0&&t.agenda.summary.events===0&&(e.push("## Suggestions"),e.push("No active work items or upcoming events. Consider:"),e.push('- `pm create --type Task --title "..."` to add a new work item'),e.push("- `pm list --status closed --limit 5` to review recent completions"),e.push("- `pm search <keywords>` to find related past work"),e.push("- `pm aggregate` for a full project status overview"))}function fn(e){return[e.in_progress_unowned===void 0?"":`, in_progress_unowned: ${e.in_progress_unowned}`,e.in_progress_idle===void 0?"":`, in_progress_idle: ${e.in_progress_idle}`].join("")}function pn(e){const t=fn(e);return e.active_items===e.open+e.in_progress?[`- active_items: ${e.active_items} (in_progress: ${e.in_progress}${t}, open: ${e.open})`]:[`- active_items: ${e.active_items} (open: ${e.open})`,`- in_progress: ${e.in_progress} (outside active_items${t})`]}function oo(e){const t=[],n=e.focus_fields,s=i=>n?Zt(i,n):He(i);if(t.push("# pm context"),t.push(""),t.push(`- now: ${e.now}`),t.push(`- depth: ${e.depth}`),e.filters.parent&&t.push(`- scope: subtree of ${e.filters.parent}`),t.push(...pn(e.summary)),e.summary.total_items!==void 0&&t.push(`- total_items: ${e.summary.total_items} (closed: ${e.summary.closed??0}, canceled: ${e.summary.canceled??0})`),t.push(`- agenda_events: ${e.summary.agenda_events}`),t.push(`- blocked_fallback_used: ${e.summary.blocked_fallback_used}`),e.extension_health){const i=e.extension_health.packages.filter(r=>r.status==="degraded").map(r=>r.name);t.push(`- extensions: ${e.extension_health.ok} ok, ${e.extension_health.degraded} degraded${i.length>0?` (${i.join(", ")})`:""}`)}const o=e.sections_included.filter(i=>i!=="blockers"||(e.blockers?.length??0)>0);if(o.length>0&&t.push(`- sections: ${o.join(", ")}`),t.push(""),Re(t,"High-level focus",e.high_level,"No high-level active items.",s),Re(t,"Low-level focus",e.low_level,"No low-level active items.",s),qt(t,e,s),Qt(t,e),e.workspace_memory){t.push("## Workspace memory");for(const i of e.workspace_memory.rollups)t.push(`- ${i.kind}:${i.key} \u2014 ${i.label} (${i.item_count} completed, latest ${i.last_closed_at})`);t.push("")}return Yt(t,e),en(t,e),tn(t,e,n,s),nn(t,e,s),on(t,e),sn(t,e),rn(t,e),an(t,e),cn(t,e),ln(t,e),un(t,e),t.join(`
2
- `)}const mn=new Set(["status","no_truncate","limit","sort","order"]);function hn(e){const{runtime_filters:t,...n}=e;return Object.keys(n).some(s=>!mn.has(s))||Object.keys(Object(t)).length>0}async function _n(e,t){return hn(t.filters)?(await pe(void 0,ze({},{excludeTerminal:!1}),e)).items:t.items}async function gn(e,t){const n=de(process.cwd(),t.path),s=await nt(n),o=s.context??Ye.context,i=tt(s.schema),r=Ht(e.depth,o),c=ge(e.limit??e.maxItems,r);return{settings:s,contextSettings:o,statusRegistry:i,depth:r,limit:c,sectionsIncluded:Gt(e.section,r,o),activityLimit:ye(e.activityLimit,o),staleThresholdDays:be(e.staleThreshold,o),parentScope:Se(e.parent),focusFields:Ut(e.fields),baseListOptions:$e(e)}}function kn(e){return e.some(t=>["hierarchy","progress","blockers","staleness","recently_created","unparented"].includes(t))}function ze(e,t){return{...e,...t,noTruncate:!0,limit:void 0,offset:void 0,after:void 0}}async function yn(e,t){const n=await pe(void 0,ze(t.baseListOptions,{excludeTerminal:!1}),e),s=n.items,o=await _n(e,n);let i=s.filter(a=>!ce(a.status,t.statusRegistry)),r=s;const c=bn(t.parentScope,o);return c&&(i=i.filter(a=>c.has(a.id.trim().toLowerCase())),r=r.filter(a=>c.has(a.id.trim().toLowerCase()))),{listed:n,listedItemMetadata:i,allItems:r,fullCorpus:s,edgeCorpus:o,subtreeIds:c}}function bn(e,t){if(e===void 0)return;const n=Ce(t,e);if(!n.found)throw new w(`Context --parent item not found: ${e}`,b.NOT_FOUND);return n.ids}function wn(e,t,n,s){const o=new Set(dt(e,t,n,s).containers.map(i=>i.item.id));return new Set(e.filter(i=>M.has(i.type)||o.has(i.id)||ct(i.type,s)!=="agent").map(i=>i.id))}async function $n(e,t,n,s,o,i,r,c,a,l,f,d,p,$,y,g){const I=[...e].sort((u,v)=>A(u,v,o)),h=await Ct({pmRoot:p,author:a,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),C=await vt(I,{pmRoot:p,storeKey:"context",statusRegistry:o,now:c,author:a,usageAffinity:h.affinity,claimFocus:y}),m=await ft("context",C.candidates),k=m.ranked.map(u=>u.item),z=o.active_statuses,E=k.filter(u=>z.has(_(u.status,o))),F=d?ht(E,l,f,u=>u.id):0,S=d?E.slice(F,F+r):E,te=d&&S.length>0&&F+S.length<E.length,ne=te&&S.length>0?mt(f,S[S.length-1].id,F+S.length-1):void 0,Xe=k.filter(u=>s.has(u.id.trim().toLowerCase())),We=new Set([...S.map(u=>u.id),...Xe.filter(u=>!z.has(_(u.status,o))).slice(0,r).map(u=>u.id)]),oe=Vt({...m,ranked:m.ranked.filter(u=>We.has(u.id))},$,new Set(Object.entries(y??{}).filter(([,u])=>u>=1).map(([u])=>u))),se=oe.included.map(u=>u.item),D=se.filter(u=>z.has(_(u.status,o))),ie=se.filter(u=>s.has(u.id.trim().toLowerCase())),Ve=N(t),Ke=kn(i)?Ve:void 0,Je=new Map(n.map(u=>[u.id.trim().toLowerCase(),u])),X=u=>{const v=R(u,o,Ke);return s.has(u.id.trim().toLowerCase())&&(v.blocked=!0,v.blocker_ids=le(u,Je,o).filter(W=>!W.resolved).map(W=>W.id)),v},re=wn(D,n,o,g),Ze=D.filter(u=>re.has(u.id)).slice(0,d?S.length:r).map(X),qe=D.filter(u=>!re.has(u.id)).slice(0,d?S.length:r).map(X),ae=E.length===0;return{activeItems:D,blockedItems:ie,highLevel:Ze,lowLevel:qe,blockedFallback:ae?ie.slice(0,r).map(X):[],blockedFallbackUsed:ae,ranking:m,packing:oe,featureStore:C,pageExtras:{...d?{applied_limit:r}:{},...te?{has_more:!0,truncated:!0}:{},...ne?{next_cursor:ne}:{}}}}function Cn(e,t){return pt("context",{pmRoot:t,options:_t(e,yt)})}function Sn(e,t){return e.limit!==void 0||e.maxItems!==void 0||e.after!==void 0||t>=me}async function vn(e,t,n,s){const o={...t.baseListOptions,after:void 0,view:"agenda",include:"all",limit:t.parentScope===void 0?String(t.limit):void 0},i=await lt(o,e),r=n===void 0?i.events:i.events.filter(l=>n.has(l.item_id.trim().toLowerCase())),c=Ee(r,t.statusRegistry).slice(0,t.limit),a=c.map(l=>s.has(l.item_id)?{at:l.at,date:l.date,kind:l.kind,item_id:l.item_id,reference_only:!0,...l.kind==="reminder"?{reminder_text:l.reminder_text}:{},...l.kind==="event"?{event_title:l.event_title,event_recurring:l.event_recurring}:{}}:l);return{agenda:i,agendaEvents:a,agendaSummary:Ie(c)}}function ee(e,t,n){const s=_(String(t),n);return e.filter(o=>_(o.status,n)===s).length}async function xn(e){const{runtime:t,allItems:n,fullCorpus:s,blockedIds:o,focusGroups:i,now:r,global:c}=e,a=N(n),l=n.filter(d=>!ce(d.status,t.statusRegistry)),f=d=>t.sectionsIncluded.includes(d);return{hierarchy:f("hierarchy")?Le(n,i.activeItems,t.statusRegistry,t.limit):void 0,activity:f("activity")?await Ae(t.activityLimit,c):void 0,progress:f("progress")?Oe(n,i.activeItems,o,t.statusRegistry,t.limit):void 0,blockersSection:f("blockers")?Ne(i.blockedItems,s,t.statusRegistry,t.limit):void 0,recentlyCreated:f("recently_created")?Me(l,t.statusRegistry,a,t.limit):void 0,unparented:f("unparented")?Pe(l,t.statusRegistry,a,t.limit):void 0,filesSection:f("files")?Fe(i.activeItems,t.limit):void 0,workload:f("workload")?De(i.activeItems,t.statusRegistry,t.limit):void 0,staleness:f("staleness")?je(l,t.staleThresholdDays,r,t.limit):void 0,tests:f("tests")?Ue(n.filter(d=>t.statusRegistry.active_statuses.has(_(d.status,t.statusRegistry)))):void 0}}function Tn(e,t,n,s){const o=j("canceled",t),i=e.filter(c=>t.active_statuses.has(_(c.status,t))),r=ee(e,t.in_progress_status,t);return{scope:"matching_items",active_items:i.length,open:i.length-ee(i,t.in_progress_status,t),in_progress:r,...s.unowned.count>0?{in_progress_unowned:s.unowned.count}:{},...s.idle.count>0?{in_progress_idle:s.idle.count}:{},blocked:e.filter(c=>n.has(c.id.trim().toLowerCase())).length,total_items:e.length,closed:e.filter(c=>x(c.status,t)).length,canceled:e.filter(c=>_(c.status,t)===o).length}}function In(e,t,n){t.hierarchy&&(e.hierarchy=t.hierarchy),t.activity&&(e.activity=t.activity.rows,t.activity.history_read&&(e.activity_history_read=t.activity.history_read)),t.progress&&(e.progress=t.progress),t.blockersSection&&(e.blockers=t.blockersSection),t.recentlyCreated&&(e.recently_created=t.recentlyCreated),t.unparented&&(e.unparented=t.unparented),t.filesSection&&(e.files=t.filesSection),t.workload&&(e.workload=t.workload),t.staleness&&(e.staleness=t.staleness),t.tests&&(e.tests=t.tests),n!==void 0&&n.length>0&&(e.warning_details=n)}function En(e,t){t&&(e.focus_fields=t,e.high_level=L(e.high_level,t),e.low_level=L(e.low_level,t),e.blocked_fallback=L(e.blocked_fallback,t),e.recently_created&&(e.recently_created=L(e.recently_created,t)),e.unparented&&(e.unparented=L(e.unparented,t)))}function Ln(e,t){const n=[e.high_level,e.low_level,e.blocked_fallback,e.recently_created??[],e.unparented??[]].flat();if(t){for(const i of n)delete i.tags,delete i.tags_inherited;return}const s=new Map(n.map(i=>[i.id,i])),o=new Map(n.map(i=>[i.id,i.tags?[...i.tags].sort().join("\0"):void 0]));for(const i of n){if(!i.parent||!i.tags)continue;const r=s.get(i.parent);r&&o.get(i.id)===o.get(r.id)&&(delete i.tags,i.tags_inherited=r.id)}}function An(e,t,n){t.length>0||n.length>0||e.agenda.events.length>0||(e.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 On(e,t,n,s){try{const o=new Set(t.packing.included.map(a=>a.id)),i=t.ranking.ranked.map(a=>({id:a.id,rank:a.rank,included:o.has(a.id)})),r=new Set(i.map(a=>a.id));for(const a of $t(e,"context"))r.has(a)||(i.push({id:a,rank:i.length+1,included:!1}),r.add(a));const c=await St({pmRoot:n,author:s,surface:"context",profile:t.packing.profile,rows:i,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});wt(e,c)}catch{e.warnings=Y(e.warnings,["context_usage_feedback_write_failed"])}}async function Nn(e,t,n){if(e)return{};const o=(await st({pmRoot:t,settings:n,cwd:process.cwd(),noExtensions:!1})).discovered.map(r=>({name:r.name??r.directory,status:r.status==="ok"?"ok":"degraded"})).sort((r,c)=>r.name.localeCompare(c.name)),i=o.filter(r=>r.status==="degraded").length;return o.length===0?{}:{extension_health:{total:o.length,ok:o.length-i,degraded:i,packages:o.slice(0,20),...o.length>20?{truncated:!0}:{}}}}async function Fn(e,t){const n=It(),s=await Et(e),o=n.instance||Lt(t);return At(s.semantic_attribution?.[o])}async function so(e,t){const n=de(process.cwd(),t.path),s=await gn(e,t),o=await yn(t,s),i=ke(s.limit,o.fullCorpus.length),r={...s,limit:i,tokenBudget:Bt(e.tokenBudget,Math.max(256,i*160))},c=ot(void 0,r.settings.author_default),a=await Fn(n,c),l=Nn(e.noExtensionHealth===!0,n,r.settings),f=at(o.edgeCorpus,r.statusRegistry),d=await $n(o.listedItemMetadata,o.allItems,o.edgeCorpus,f,r.statusRegistry,r.sectionsIncluded,r.limit,et(),c,e.after,Cn(e,n),Sn(e,o.fullCorpus.length),n,r.tokenBudget,a,it(r.settings,rt())),p=await vn(t,r,o.subtreeIds,new Set([...d.highLevel,...d.lowLevel,...d.blockedFallback].map(k=>k.id))),$=await xt(o.fullCorpus,{pmRoot:n,statusRegistry:r.statusRegistry,now:p.agenda.now}),y=Y(o.listed.warnings,p.agenda.warnings,d.ranking.warnings,[...d.featureStore.warnings],$.warnings),g=ee(d.activeItems,r.statusRegistry.in_progress_status,r.statusRegistry),I=d.activeItems.length-g,h=await xn({runtime:r,allItems:o.allItems,fullCorpus:o.edgeCorpus,blockedIds:f,focusGroups:d,now:p.agenda.now,global:t}),C=Tn(o.allItems,r.statusRegistry,f,await Qe(n,o.allItems,{in_progress_status:r.statusRegistry.in_progress_status,status_registry:r.statusRegistry,threshold_hours:r.settings.mutation_guard.stale_in_progress_hours,now:new Date(p.agenda.now)})),m={output_default:"toon",now:p.agenda.now,depth:r.depth,sections_included:r.sectionsIncluded,window:{anchor:p.agenda.anchor,start:p.agenda.range.start,end:p.agenda.range.end,past:p.agenda.range.past,from:p.agenda.range.from,to:p.agenda.range.to},filters:{type:e.type??null,tag:e.tag??null,priority:e.priority??null,assignee:e.assignee??null,assignee_filter:e.assigneeFilter??null,sprint:e.sprint??null,release:e.release??null,limit:e.limit??e.maxItems??null,parent:r.parentScope??null,token_budget:r.tokenBudget,runtime_filters:o.listed.filters.runtime_filters??p.agenda.filters.runtime_filters??{}},summary:{returned_focus:{active_items:d.activeItems.length,in_progress:g,open:I,blocked:d.blockedItems.length},blocked_fallback_used:d.blockedFallbackUsed,high_level:d.highLevel.length,low_level:d.lowLevel.length,agenda_events:p.agendaSummary.events,...C},high_level:d.highLevel,low_level:d.lowLevel,blocked_fallback:d.blockedFallback,agenda:{summary:p.agendaSummary,events:p.agendaEvents},...d.pageExtras};return m.workspace_memory=Tt($,Math.min(800,Math.floor(r.tokenBudget*.2))),Object.assign(m,await l),In(m,h,d.featureStore.warning_details),Ln(m,e.noTags===!0),e.explainRanking===!0&&(m.ranking=Jt(d.ranking,d.featureStore,new Set([...d.highLevel,...d.lowLevel,...d.blockedFallback].map(k=>k.id))),m.packing=Kt(d.packing)),gt(m,[...d.highLevel,...d.lowLevel,...d.blockedFallback].map(k=>({id:k.id,status:_(k.status,r.statusRegistry)===P(r.statusRegistry)?"in_progress":"open",blocked:k.blocked}))),En(m,r.focusFields),kt(m),y.length>0&&(m.warnings=y),An(m,d.activeItems,d.blockedItems),await On(m,d,n,c),m}export{Ot as CONTEXT_OUTPUT_VALUES,no as _testOnly,Ln as applyContextTagProjection,N as buildChildrenByParent,ao as buildItemContextRelevanceCandidates,Ce as collectSubtreeIds,A as compareCriticalItems,Y as mergeSortedWarnings,Vt as packRankedContextItems,Ht as parseContextDepth,Ut as parseContextFocusFields,Gt as parseContextSections,L as projectContextFocusRows,oo as renderContextMarkdown,Nn as resolveContextExtensionHealthProjection,to as resolveContextOutputFormat,Bt as resolveContextTokenBudget,so as runContext,R as toContextFocusItem,Kt as toContextPackingSummary,Jt as toContextRankingSummary};
1
+ import Ye from"node:path";import{scanInProgressWork as et}from"../governance/stale-work.js";import{SETTINGS_DEFAULTS as tt,EXIT_CODE as $,PmCliError as v,compareTimestampStrings as K,nowIso as nt,isTerminalStatus as de,normalizeStatusForRegistry as y,normalizeStatusInput as j,resolveRuntimeStatusRegistry as ot,resolvePmRoot as le,readSettings as st,resolveAuthor as rt,discoverExtensions as it,resolveItemTypeRegistry as at}from"../runtime-primitives.js";import{getActiveExtensionRegistrations as ct}from"../../core/extensions/index.js";import{findApplicableUpdateObservation as dt,readExtensionUpdateObservations as lt,readStrictManagedRecords as ut,resolveObservedUpdateVersion as ft}from"../extension/update-observations.js";import{buildExtensionUpgradeHints as pt}from"../extension/upgrade-hints.js";import{collectDependencyBlockedIds as mt,resolveItemBlockers as ue,resolveItemExecutionRole as ht,computeActionabilityReport as _t}from"../actionability.js";import{CONTEXT_DEPTH_VALUES as fe,CONTEXT_SECTION_VALUES as J}from"../../types/index.js";import{parseIntegerLimit as pe}from"./parsers.js";import{runCalendar as gt}from"./calendar.js";import{runList as me}from"./list.js";import{readRecentActivity as kt}from"./activity.js";import{scoreContextCandidatesWithActiveExtensions as yt}from"../context-relevance.js";import{buildItemContextRelevanceCandidates as $o}from"../context-relevance.js";import{createQueryFingerprint as bt,encodeQueryCursor as wt,resolveQueryCursorStart as $t,selectCursorSemanticOptions as vt}from"../pagination.js";import{rememberReadOutputFocusRows as Ct,refreshReadOutputDeliveredCounts as St}from"../read-output-rows.js";import{CONTEXT_FLAG_CONTRACTS as xt}from"../cli-contracts/flag-contracts.js";import{packContextCandidates as Tt}from"../context-packing.js";import{attachContextUsageServingReceipt as Et,collectContextUsageDeliveredItemIds as It,readContextUsageAffinity as Lt,recordContextUsageServing as At}from"../context-usage.js";import{readWorkspaceContextSignals as Ot}from"../context-signal-store.js";import{readWorkspaceMemory as Nt,selectWorkspaceMemory as Ft}from"../workspace-memory.js";import{detectAgentIdentity as Mt}from"../../core/shared/author.js";import{readSessionState as jt,semanticAttributionKey as Dt}from"../../core/session/session-state.js";import{semanticAttributionAffinity as Ut}from"../context/semantic-session-attribution.js";const Pt=["markdown","toon","json","ndjson"],D=new Set(["Epic","Feature"]),Z=10,he=1e4,_e=["hierarchy","activity","progress","recently_created","unparented","workload"],Ht=[..._e,"blockers","files","staleness","tests"],Bt=/^(\d{4})-(\d{2})-(\d{2})/,Rt=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/,Gt=/^(\d{4})(\d{2})(\d{2})$/,zt=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?(Z|[+-]\d{2}:?\d{2})?$/i;function Xt(e){if(!e)return;const t=e.trim().toLowerCase();if(!Pt.includes(t))throw new v("Context format must be one of markdown|toon|json|ndjson",$.USAGE);return t}const ge=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 Wt(e){if(e===void 0)return;const t=[];for(const n of e.split(",")){const s=n.trim().toLowerCase();if(s.length!==0){if(!ge.has(s))throw new v(`Context --fields value not projectable: ${s} (valid: ${[...ge].join(", ")})`,$.USAGE);t.includes(s)||t.push(s)}}if(t.length===0)throw new v("Context --fields requires at least one field name",$.USAGE);return t}function L(e,t){return e.map(n=>{const s={},o=n;for(const r of t)s[r]=o[r]??null;return s})}function _o(e,t){const n=Xt(e.format);if(t.json&&n&&n!=="json"&&n!=="ndjson")throw new v("Cannot combine --json with --format markdown|toon",$.USAGE);return t.json?n==="ndjson"?"ndjson":"json":n??"toon"}function ke(e,t){return pe(e,"--limit")??(t==="full"?Number.MAX_SAFE_INTEGER:Z)}function Vt(e,t){if(e===void 0)return t;const n=typeof e=="number"?e:Number(e);if(!Number.isInteger(n)||n<1)throw new v("--token-budget must be a positive integer",$.USAGE);return n}function ye(e,t){return t>=he&&e===Number.MAX_SAFE_INTEGER?Z:e}function Kt(e,t){if(!e)return t.default_depth;const n=e.trim().toLowerCase();if(!fe.includes(n))throw new v(`Context --depth must be one of ${fe.join("|")}`,$.USAGE);return n}function Jt(e,t,n){if(e&&e.length>0){const o=[];for(const r of e){const i=r.trim().toLowerCase();if(!J.includes(i))throw new v(`Context --section must be one of ${J.join("|")}`,$.USAGE);o.includes(i)||o.push(i)}return o}return t==="brief"?[]:t==="full"?[...J]:(t==="deep"?Ht:_e).filter(o=>n.sections[o])}function be(e,t){return e?pe(e,"--activity-limit")??t.activity_limit:t.activity_limit}function we(e,t){if(!e)return t.stale_threshold_days;const n=e.trim().toLowerCase(),s=/^(\d+)d?$/.exec(n);if(!s)throw new v("--stale-threshold must be a number of days (e.g. 7 or 7d)",$.USAGE);const o=parseInt(s[1],10);if(o<=0)throw new v("--stale-threshold must be positive",$.USAGE);return o}function U(e){return y(e.in_progress_status,e)}function q(e,t){const n=y(e,t),s=j("blocked",t),o=j("draft",t);return n===U(t)?0:t.active_statuses.has(n)?1:s&&n===s?2:o&&n===o?3:t.blocked_statuses.has(n)?5:t.terminal_statuses.has(n)?7:6}function T(e,t){const n=j("closed",t);return y(e,t)===n}function P(e,t){return y(e,t)===U(t)}function Q(e,t){const n=y(e,t);return n!==U(t)&&t.active_statuses.has(n)}function $e(e,t){return t.blocked_statuses.has(y(e,t))}const Zt=["compact","brief","fields","includeBody","include_body","parent"];function ve(e){const t={...e};for(const n of Zt)delete t[n];return t}function Ce(e,t){const n=t.trim().toLowerCase(),s=e.find(c=>c.id.trim().toLowerCase()===n);if(!s)return{ids:new Set,found:!1};const o=N(e),r=E(s.id,o);return{ids:new Set([s.id,...r.map(c=>c.id)].map(c=>c.trim().toLowerCase())),found:!0}}function Se(e){if(e===void 0)return;const t=e.trim();if(t.length===0)throw new v("Context --parent requires an item id",$.USAGE);return t}function xe(e,t){const n=e??null,s=t??null;return n===null&&s===null?0:n===null?1:s===null?-1:n-s}function Te(e,t){const n=e??null,s=t??null;return n===null&&s===null?0:n===null?1:s===null?-1:K(n,s)}function qt(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}function Qt(e){const t=Bt.exec(e)??Rt.exec(e);if(!t)return!0;const n=Number.parseInt(t[1],10),s=Number.parseInt(t[2],10),o=Number.parseInt(t[3],10);return s>=1&&s<=12&&o>=1&&o<=qt(n,s-1)}function Yt(e){const t=Gt.exec(e);if(t)return`${t[1]}-${t[2]}-${t[3]}`;const n=zt.exec(e);if(n){const[,s,o,r,i,c,a,l]=n,f=a?`:${a}`:"",d=l&&l.length===5&&l!=="Z"?`${l.slice(0,3)}:${l.slice(3)}`:l??"";return`${s}-${o}-${r}T${i}:${c}${f}${d}`}return e}function Y(e){if(typeof e!="string")return Number.NaN;const t=e.trim();if(t.length===0||!Qt(t))return Number.NaN;const n=Date.parse(Yt(t));return Number.isFinite(n)?n:Number.NaN}function H(e){const t=Y(e);return Number.isFinite(t)?new Date(t).toISOString():""}function Ee(e){const t=Y(e);return Number.isFinite(t)?new Date(t).toISOString().slice(0,10):"unknown"}function B(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function A(e,t,n){const s=q(e.status,n)-q(t.status,n);if(s!==0)return s;const o=e.priority-t.priority;if(o!==0)return o;const r=xe(e.order,t.order);if(r!==0)return r;const i=Te(e.deadline,t.deadline);if(i!==0)return i;const c=K(H(t.updated_at),H(e.updated_at)),a=e.id.localeCompare(t.id);return c!==0?c:a}function R(e){return Math.max(1,Math.ceil(Buffer.byteLength(JSON.stringify(e),"utf8")/4))}function en(e,t,n=new Set,s="context"){return Tt(e.ranked.map(o=>({id:o.id,item:o.item,rank:o.rank,score:o.score,required:n.has(o.id),cluster:o.item.parent?.trim()||o.item.type,token_costs:{identity:R({id:o.id,title:o.item.title}),summary:R({id:o.id,title:o.item.title,type:o.item.type,status:o.item.status,priority:o.item.priority,parent:o.item.parent}),full:R(o.item)}})),{tokenBudget:t,profile:s,latencyBudgetMs:25})}function tn(e){return{...e,included:e.included.map(t=>({id:t.id,projection:t.projection,tokens:t.tokens}))}}function nn(e,t,n){const s=n===void 0?e.ranked:e.ranked.filter(o=>n.has(o.id));return{model:e.model,available_signals:e.available_signals,items:s.map(o=>({id:o.id,rank:o.rank,baseline_rank:o.baseline_rank,score:o.score,contributions:o.contributions,...o.signal_provenance===void 0?{}:{recency:o.signal_provenance.recency}})),candidate_count:e.ranked.length,omitted_count:e.ranked.length-s.length,...t?{feature_store:{source:t.snapshot.source,cache_status:t.cache_status,source_cursor:t.snapshot.source_cursor,generated_at:t.snapshot.generated_at}}:{}}}function O(e,t){return t>0?Math.round(e*100/t):0}function N(e){const t=new Map;for(const n of e){const s=B(n.parent);if(!s)continue;const o=t.get(s)??[];o.push(n),t.set(s,o)}return t}function G(e,t,n){const s={id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,order:e.order??null,deadline:e.deadline??null,assignee:e.assignee??null,tags:Array.isArray(e.tags)?[...e.tags]:[],updated_at:e.updated_at,parent:B(e.parent)};if(t&&n){const o=E(e.id,n),r=o.length;if(r>0){const i=o.filter(c=>T(c.status,t)).length;s.children_total=r,s.children_closed=i,s.completion_pct=O(i,r)}}return s}function Ie(e){let t=0,n=0,s=0;const o=new Set;for(const r of e){if(o.add(r.item_id),r.kind==="deadline"){t+=1;continue}if(r.kind==="reminder"){n+=1;continue}s+=1}return{events:e.length,items:o.size,deadlines:t,reminders:n,scheduled:s}}function ee(...e){return[...new Set(e.flatMap(t=>t??[]))].sort((t,n)=>t.localeCompare(n))}function Le(e,t){return e.filter(n=>!t.terminal_statuses.has(y(n.item_status,t)))}function Ae(e,t,n,s){const o=new Map;for(const a of e)o.set(a.id,a);const r=N(e),i=new Set(t.filter(a=>D.has(a.type)).map(a=>a.id)),c=[];for(const a of i){const l=o.get(a);if(!l)continue;const f=E(a,r),d=r.get(a)??[];let m=0,u=0,g=0,k=0;for(const _ of f)T(_.status,n)?m++:P(_.status,n)?g++:$e(_.status,n)?k++:Q(_.status,n)&&u++;const C=d.sort((_,b)=>A(_,b,n)).slice(0,s).map(_=>{const b=E(_.id,r),h=b.filter(w=>T(w.status,n)).length;return{id:_.id,title:_.title,type:_.type,status:_.status,children_total:b.length,children_closed:h}});c.push({id:l.id,title:l.title,type:l.type,status:l.status,children_total:f.length,children_closed:m,children_open:u,children_in_progress:g,children_blocked:k,children:C})}return c.sort((a,l)=>{const f=o.get(a.id),d=o.get(l.id);return A(f,d,n)}).slice(0,s)}function E(e,t){const n=[],s=[e],o=new Set;for(;s.length>0;){const r=s.pop();if(o.has(r))continue;o.add(r);const i=t.get(r)??[];for(const c of i)n.push(c),s.push(c.id)}return n}const go={buildActivity:Oe,buildBlockers:Fe,buildChildrenByParent:N,buildHierarchy:Ae,buildHotFiles:Me,buildProgress:Ne,buildRecentlyCreated:Ue,buildStaleness:De,buildTestHealth:He,buildUnparented:Pe,buildWorkload:je,collectDescendants:E,collectSubtreeIds:Ce,compareCriticalItems:A,compareOptionalDeadline:Te,compareOptionalOrder:xe,completionPct:O,dateTokenForTimestamp:Ee,filterTerminalCalendarEvents:Le,formatAgendaLine:Ge,isBlockedStatus:$e,isClosedStatus:T,isInProgressStatus:P,isOpenStatus:Q,mergeSortedWarnings:ee,normalizedParentId:B,parseActivityLimit:be,parseContextLimit:ke,resolveContextLimitAtScale:ye,parseContextParent:Se,parseContextTimestampMs:Y,parseStaleThresholdDays:we,sortableTimestamp:H,statusRank:q,stripListProjectionFlags:ve,summarizeAgenda:Ie,toContextFocusItem:G};async function Oe(e,t){return kt({limit:e},t)}function Ne(e,t,n,s,o){const r=new Map;for(const a of e){if(!a.parent)continue;const l=r.get(a.parent)??[];l.push(a),r.set(a.parent,l)}const i=t.filter(a=>D.has(a.type)),c=[];for(const a of i){const l=E(a.id,r),f=l.length;if(f===0)continue;let d=0,m=0,u=0,g=0;for(const k of l)T(k.status,s)?d++:n.has(k.id.trim().toLowerCase())?g++:P(k.status,s)?u++:Q(k.status,s)&&m++;c.push({id:a.id,title:a.title,type:a.type,total:f,closed:d,open:m,in_progress:u,blocked:g,completion_pct:O(d,f)})}return c.sort((a,l)=>a.completion_pct-l.completion_pct).slice(0,o)}function Fe(e,t,n,s){const o=new Map(t.map(r=>[r.id.trim().toLowerCase(),r]));return e.slice(0,s).map(r=>{const i=ue(r,o,n),c=i.find(l=>!l.resolved)?.id??i[0]?.id??null,a=c?o.get(c.trim().toLowerCase()):void 0;return{id:r.id,title:r.title,blocked_by:c,blocked_by_title:a?.title??null,blocked_by_status:a?.status??null,blocked_reason:r.blocked_reason??null,unblock_note:r.unblock_note??null}})}function Me(e,t){const n=new Map;for(const s of e)for(const o of s.files??[]){const r=n.get(o.path)??new Set;r.add(s.id),n.set(o.path,r)}return[...n.entries()].map(([s,o])=>({path:s,references:o.size,items:[...o].sort()})).sort((s,o)=>o.references-s.references).slice(0,t)}function je(e,t,n){const s=new Map;for(const o of e){const r=o.assignee??null,i=s.get(r)??[];i.push(o),s.set(r,i)}return[...s.entries()].map(([o,r])=>({assignee:o,active:r.length,in_progress:r.filter(i=>P(i.status,t)).length,items:r.map(i=>i.id).sort()})).sort((o,r)=>r.active-o.active).slice(0,n)}function De(e,t,n,s){const o=new Date(n).getTime()-t*24*60*60*1e3;return e.filter(r=>new Date(r.updated_at).getTime()<o).map(r=>({id:r.id,title:r.title,status:r.status,updated_at:r.updated_at,stale_days:Math.floor((new Date(n).getTime()-new Date(r.updated_at).getTime())/(1440*60*1e3))})).sort((r,i)=>i.stale_days-r.stale_days).slice(0,s)}function Ue(e,t,n,s){return e.map(o=>({item:o,sortKey:H(o.created_at)})).sort((o,r)=>{const i=K(r.sortKey,o.sortKey);return i!==0?i:o.item.id.localeCompare(r.item.id)}).slice(0,s).map(({item:o})=>({...G(o,t,n),created_at:o.created_at}))}function Pe(e,t,n,s){return e.filter(o=>!B(o.parent)&&!D.has(o.type)).sort((o,r)=>A(o,r,t)).slice(0,s).map(o=>G(o,t,n))}function He(e){let t=0,n=0,s=0,o=0,r=0;const i=[];for(const c of e){(c.tests??[]).length>0&&t++;const a=c.test_runs??[];if(a.length>0){n++;let l=!1;for(const f of a)s+=f.passed??0,o+=f.failed??0,r+=f.skipped??0,(f.failed??0)>0&&(l=!0);l&&i.push(c.id)}}return{scope:"matching_active_items",total_items:e.length,items_with_tests:t,items_with_recent_runs:n,recent_runs:{passed:s,failed:o,skipped:r},items_failing:i.sort()}}function Be(e){return`${new Date(e).toISOString().slice(11,16)}Z`}function Re(e){const t=e.order===null?"-":String(e.order),n=e.deadline??"-",s=e.parent?` parent:${e.parent}`:"",o=e.children_total!==void 0&&e.children_closed!==void 0&&e.completion_pct!==void 0?` children:${e.children_closed}/${e.children_total} done:${e.completion_pct}%`:"",r=e.blocked===!0?` blocked:${e.blocker_ids?.join(",")||"lifecycle"}`:"";return`${e.id} p${e.priority} ${e.status} ${e.type} order:${t} deadline:${n}${s}${o}${r} ${e.title}`}function on(e,t){const n=e;return t.map(s=>{const o=n[s];return Array.isArray(o)?`${s}:${o.join(",")}`:`${s}:${o??"-"}`}).join(" ")}function Ge(e){if("reference_only"in e){const n=e.kind==="reminder"?` \u2014 ${e.reminder_text??"reminder"}`:e.kind==="event"?` \u2014 ${e.event_title??"event"}${e.event_recurring?" (recurring)":""}`:"";return`${Be(e.at)} [${e.kind}] ${e.item_id} (see focus item)${n}`}const t=`${Be(e.at)} [${e.kind}] ${e.item_id} p${e.item_priority} ${e.item_status} ${e.item_title}`;if(e.kind==="reminder")return`${t} \u2014 ${e.reminder_text}`;if(e.kind==="event"){const n=e.event_recurring?" (recurring)":"",s=e.event_title??e.item_title;return`${t} \u2014 ${s}${n}`}return t}function ze(e,t,n,s,o){if(e.push(`## ${t}`),n.length===0)e.push(s);else for(const r of n)e.push(`- ${o(r)}`);e.push("")}function sn(e,t,n){if(t.blocked_fallback.length!==0){e.push("## Blocked fallback");for(const s of t.blocked_fallback)e.push(`- ${n(s)}`);e.push("")}}function rn(e,t){if(e.push("## Agenda"),e.push(`- events: ${t.agenda.summary.events} (deadlines: ${t.agenda.summary.deadlines}, reminders: ${t.agenda.summary.reminders}, scheduled: ${t.agenda.summary.scheduled})`),t.agenda.events.length===0)e.push("No agenda events matched the selected filters.");else for(const n of t.agenda.events)e.push(`- ${Ge(n)}`);e.push("")}function an(e,t){if(!(!t.hierarchy||t.hierarchy.length===0)){e.push("## Hierarchy");for(const n of t.hierarchy){const s=O(n.children_closed,n.children_total);e.push(`- ${n.id} ${n.type} ${n.status} "${n.title}" [${n.children_closed}/${n.children_total} done ${s}%]`);for(const o of n.children){const r=O(o.children_closed,o.children_total);e.push(` - ${o.id} ${o.type} ${o.status} "${o.title}" [${o.children_closed}/${o.children_total} done ${r}%]`)}}e.push("")}}function cn(e,t){if(!(!t.progress||t.progress.length===0)){e.push("## Progress");for(const n of t.progress)e.push(`- ${n.id} "${n.title}" ${n.completion_pct}% (${n.closed}/${n.total} closed, ${n.in_progress} wip, ${n.open} open, ${n.blocked} blocked)`);e.push("")}}function dn(e,t,n,s){if(!(!t.recently_created||t.recently_created.length===0)){e.push("## Recently created");for(const o of t.recently_created)e.push(n?`- ${s(o)}`:`- ${Ee(o.created_at)} ${Re(o)}`);e.push("")}}function ln(e,t,n){if(!(!t.unparented||t.unparented.length===0)){e.push("## Unparented");for(const s of t.unparented)e.push(`- ${n(s)}`);e.push("")}}function un(e,t){const n=t.activity_history_read;if(!((!t.activity||t.activity.length===0)&&n===void 0)){e.push("## Recent activity");for(const s of t.activity??[]){const o=s.msg?` ${s.msg}`:"";e.push(`- ${s.ts.slice(0,16)}Z ${s.id} ${s.op} by:${s.author}${o}`)}n!==void 0&&e.push(`- history read: ${n.reason}, ${n.streams_read}/${n.streams_total} streams parsed`),e.push("")}}function fn(e,t){if(!(!t.blockers||t.blockers.length===0)){e.push("## Blockers");for(const n of t.blockers){const s=n.blocked_by?`blocked_by:${n.blocked_by}(${n.blocked_by_status??"?"})`:"blocked_by:-",o=n.blocked_reason?` reason:"${n.blocked_reason}"`:"",r=n.unblock_note?` unblock:"${n.unblock_note}"`:"";e.push(`- ${n.id} "${n.title}" ${s}${o}${r}`)}e.push("")}}function pn(e,t){if(!(!t.files||t.files.length===0)){e.push("## Hot files");for(const n of t.files)e.push(`- ${n.path} refs:${n.references} items:[${n.items.join(",")}]`);e.push("")}}function mn(e,t){if(!(!t.workload||t.workload.length===0)){e.push("## Workload");for(const n of t.workload){const s=n.assignee??"(unassigned)";e.push(`- ${s} active:${n.active} wip:${n.in_progress} items:[${n.items.join(",")}]`)}e.push("")}}function hn(e,t){if(!(!t.staleness||t.staleness.length===0)){e.push("## Stale items");for(const n of t.staleness)e.push(`- ${n.id} ${n.status} stale:${n.stale_days}d last:${n.updated_at.slice(0,10)} "${n.title}"`);e.push("")}}function _n(e,t,n){const s=[];let o=0;for(const r of e.items_failing){if(s.length>=t)break;const i=R(r);if(o+i>n)break;s.push(r),o+=i}return s}function gn(e,t){if(!t.tests)return;e.push("## Test health"),e.push(`- ${t.tests.scope}: ${t.tests.total_items}`),e.push(`- items_with_tests: ${t.tests.items_with_tests}`),e.push(`- items_with_recent_runs: ${t.tests.items_with_recent_runs}`),e.push(`- passed: ${t.tests.recent_runs.passed}, failed: ${t.tests.recent_runs.failed}, skipped: ${t.tests.recent_runs.skipped}`);const n=_n(t.tests,t.applied_limit??Z,t.filters.token_budget);n.length>0&&e.push(`- items_failing: [${n.join(",")}]`);const s=t.tests.items_failing.length-n.length;s>0&&e.push(`- items_failing_omitted: ${s}`),e.push("")}function kn(e,t){t.summary.active_items===0&&t.summary.blocked===0&&t.agenda.summary.events===0&&(e.push("## Suggestions"),e.push("No active work items or upcoming events. Consider:"),e.push('- `pm create --type Task --title "..."` to add a new work item'),e.push("- `pm list --status closed --limit 5` to review recent completions"),e.push("- `pm search <keywords>` to find related past work"),e.push("- `pm aggregate` for a full project status overview"))}function yn(e){return[e.in_progress_unowned===void 0?"":`, in_progress_unowned: ${e.in_progress_unowned}`,e.in_progress_idle===void 0?"":`, in_progress_idle: ${e.in_progress_idle}`].join("")}function bn(e){const t=yn(e);return e.active_items===e.open+e.in_progress?[`- active_items: ${e.active_items} (in_progress: ${e.in_progress}${t}, open: ${e.open})`]:[`- active_items: ${e.active_items} (open: ${e.open})`,`- in_progress: ${e.in_progress} (outside active_items${t})`]}function ko(e){const t=[],n=e.focus_fields,s=r=>n?on(r,n):Re(r);t.push("# pm context"),t.push(""),t.push(`- now: ${e.now}`),t.push(`- depth: ${e.depth}`),e.filters.parent&&t.push(`- scope: subtree of ${e.filters.parent}`),t.push(...bn(e.summary)),e.summary.total_items!==void 0&&t.push(`- total_items: ${e.summary.total_items} (closed: ${e.summary.closed??0}, canceled: ${e.summary.canceled??0})`),t.push(`- agenda_events: ${e.summary.agenda_events}`),t.push(`- blocked_fallback_used: ${e.summary.blocked_fallback_used}`),e.extension_health&&t.push(...Bn(e.extension_health));const o=e.sections_included.filter(r=>r!=="blockers"||(e.blockers?.length??0)>0);if(o.length>0&&t.push(`- sections: ${o.join(", ")}`),t.push(""),ze(t,"High-level focus",e.high_level,"No high-level active items.",s),ze(t,"Low-level focus",e.low_level,"No low-level active items.",s),sn(t,e,s),rn(t,e),e.workspace_memory){t.push("## Workspace memory");for(const r of e.workspace_memory.rollups)t.push(`- ${r.kind}:${r.key} \u2014 ${r.label} (${r.item_count} completed, latest ${r.last_closed_at})`);t.push("")}return an(t,e),cn(t,e),dn(t,e,n,s),ln(t,e,s),un(t,e),fn(t,e),pn(t,e),mn(t,e),hn(t,e),gn(t,e),kn(t,e),t.join(`
2
+ `)}const wn=new Set(["status","no_truncate","limit","sort","order"]);function $n(e){const{runtime_filters:t,...n}=e;return Object.keys(n).some(s=>!wn.has(s))||Object.keys(Object(t)).length>0}async function vn(e,t){return $n(t.filters)?(await me(void 0,Xe({},{excludeTerminal:!1}),e)).items:t.items}async function Cn(e,t){const n=le(process.cwd(),t.path),s=await st(n),o=s.context??tt.context,r=ot(s.schema),i=Kt(e.depth,o),c=ke(e.limit??e.maxItems,i);return{settings:s,contextSettings:o,statusRegistry:r,depth:i,limit:c,sectionsIncluded:Jt(e.section,i,o),activityLimit:be(e.activityLimit,o),staleThresholdDays:we(e.staleThreshold,o),parentScope:Se(e.parent),focusFields:Wt(e.fields),baseListOptions:ve(e)}}function Sn(e){return e.some(t=>["hierarchy","progress","blockers","staleness","recently_created","unparented"].includes(t))}function Xe(e,t){return{...e,...t,noTruncate:!0,limit:void 0,offset:void 0,after:void 0}}async function xn(e,t){const n=await me(void 0,Xe(t.baseListOptions,{excludeTerminal:!1}),e),s=n.items,o=await vn(e,n);let r=s.filter(a=>!de(a.status,t.statusRegistry)),i=s;const c=Tn(t.parentScope,o);return c&&(r=r.filter(a=>c.has(a.id.trim().toLowerCase())),i=i.filter(a=>c.has(a.id.trim().toLowerCase()))),{listed:n,listedItemMetadata:r,allItems:i,fullCorpus:s,edgeCorpus:o,subtreeIds:c}}function Tn(e,t){if(e===void 0)return;const n=Ce(t,e);if(!n.found)throw new v(`Context --parent item not found: ${e}`,$.NOT_FOUND);return n.ids}function En(e,t,n,s){const o=new Set(_t(e,t,n,s).containers.map(r=>r.item.id));return new Set(e.filter(r=>D.has(r.type)||o.has(r.id)||ht(r.type,s)!=="agent").map(r=>r.id))}async function In(e,t,n,s,o,r,i,c,a,l,f,d,m,u,g,k){const C=[...e].sort((p,x)=>A(p,x,o)),_=await Lt({pmRoot:m,author:a,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),b=await Ot(C,{pmRoot:m,storeKey:"context",statusRegistry:o,now:c,author:a,usageAffinity:_.affinity,claimFocus:g}),h=await yt("context",b.candidates),w=h.ranked.map(p=>p.item),X=o.active_statuses,I=w.filter(p=>X.has(y(p.status,o))),F=d?$t(I,l,f,p=>p.id):0,S=d?I.slice(F,F+i):I,ne=d&&S.length>0&&F+S.length<I.length,oe=ne&&S.length>0?wt(f,S[S.length-1].id,F+S.length-1):void 0,We=w.filter(p=>s.has(p.id.trim().toLowerCase())),Ve=new Set([...S.map(p=>p.id),...We.filter(p=>!X.has(y(p.status,o))).slice(0,i).map(p=>p.id)]),se=en({...h,ranked:h.ranked.filter(p=>Ve.has(p.id))},u,new Set(Object.entries(g??{}).filter(([,p])=>p>=1).map(([p])=>p))),re=se.included.map(p=>p.item),M=re.filter(p=>X.has(y(p.status,o))),ie=re.filter(p=>s.has(p.id.trim().toLowerCase())),Ke=N(t),Je=Sn(r)?Ke:void 0,Ze=new Map(n.map(p=>[p.id.trim().toLowerCase(),p])),W=p=>{const x=G(p,o,Je);return s.has(p.id.trim().toLowerCase())&&(x.blocked=!0,x.blocker_ids=ue(p,Ze,o).filter(V=>!V.resolved).map(V=>V.id)),x},ae=En(M,n,o,k),qe=M.filter(p=>ae.has(p.id)).slice(0,d?S.length:i).map(W),Qe=M.filter(p=>!ae.has(p.id)).slice(0,d?S.length:i).map(W),ce=I.length===0;return{activeItems:M,blockedItems:ie,highLevel:qe,lowLevel:Qe,blockedFallback:ce?ie.slice(0,i).map(W):[],blockedFallbackUsed:ce,ranking:h,packing:se,featureStore:b,pageExtras:{...d?{applied_limit:i}:{},...ne?{has_more:!0,truncated:!0}:{},...oe?{next_cursor:oe}:{}}}}function Ln(e,t){return bt("context",{pmRoot:t,options:vt(e,xt)})}function An(e,t){return e.limit!==void 0||e.maxItems!==void 0||e.after!==void 0||t>=he}async function On(e,t,n,s){const o={...t.baseListOptions,after:void 0,view:"agenda",include:"all",limit:t.parentScope===void 0?String(t.limit):void 0},r=await gt(o,e),i=n===void 0?r.events:r.events.filter(l=>n.has(l.item_id.trim().toLowerCase())),c=Le(i,t.statusRegistry).slice(0,t.limit),a=c.map(l=>s.has(l.item_id)?{at:l.at,date:l.date,kind:l.kind,item_id:l.item_id,reference_only:!0,...l.kind==="reminder"?{reminder_text:l.reminder_text}:{},...l.kind==="event"?{event_title:l.event_title,event_recurring:l.event_recurring}:{}}:l);return{agenda:r,agendaEvents:a,agendaSummary:Ie(c)}}function te(e,t,n){const s=y(String(t),n);return e.filter(o=>y(o.status,n)===s).length}async function Nn(e){const{runtime:t,allItems:n,fullCorpus:s,blockedIds:o,focusGroups:r,now:i,global:c}=e,a=N(n),l=n.filter(d=>!de(d.status,t.statusRegistry)),f=d=>t.sectionsIncluded.includes(d);return{hierarchy:f("hierarchy")?Ae(n,r.activeItems,t.statusRegistry,t.limit):void 0,activity:f("activity")?await Oe(t.activityLimit,c):void 0,progress:f("progress")?Ne(n,r.activeItems,o,t.statusRegistry,t.limit):void 0,blockersSection:f("blockers")?Fe(r.blockedItems,s,t.statusRegistry,t.limit):void 0,recentlyCreated:f("recently_created")?Ue(l,t.statusRegistry,a,t.limit):void 0,unparented:f("unparented")?Pe(l,t.statusRegistry,a,t.limit):void 0,filesSection:f("files")?Me(r.activeItems,t.limit):void 0,workload:f("workload")?je(r.activeItems,t.statusRegistry,t.limit):void 0,staleness:f("staleness")?De(l,t.staleThresholdDays,i,t.limit):void 0,tests:f("tests")?He(n.filter(d=>t.statusRegistry.active_statuses.has(y(d.status,t.statusRegistry)))):void 0}}function Fn(e,t,n,s){const o=j("canceled",t),r=e.filter(c=>t.active_statuses.has(y(c.status,t))),i=te(e,t.in_progress_status,t);return{scope:"matching_items",active_items:r.length,open:r.length-te(r,t.in_progress_status,t),in_progress:i,...s.unowned.count>0?{in_progress_unowned:s.unowned.count}:{},...s.idle.count>0?{in_progress_idle:s.idle.count}:{},blocked:e.filter(c=>n.has(c.id.trim().toLowerCase())).length,total_items:e.length,closed:e.filter(c=>T(c.status,t)).length,canceled:e.filter(c=>y(c.status,t)===o).length}}function Mn(e,t,n){t.hierarchy&&(e.hierarchy=t.hierarchy),t.activity&&(e.activity=t.activity.rows,t.activity.history_read&&(e.activity_history_read=t.activity.history_read)),t.progress&&(e.progress=t.progress),t.blockersSection&&(e.blockers=t.blockersSection),t.recentlyCreated&&(e.recently_created=t.recentlyCreated),t.unparented&&(e.unparented=t.unparented),t.filesSection&&(e.files=t.filesSection),t.workload&&(e.workload=t.workload),t.staleness&&(e.staleness=t.staleness),t.tests&&(e.tests=t.tests),n!==void 0&&n.length>0&&(e.warning_details=n)}function jn(e,t){t&&(e.focus_fields=t,e.high_level=L(e.high_level,t),e.low_level=L(e.low_level,t),e.blocked_fallback=L(e.blocked_fallback,t),e.recently_created&&(e.recently_created=L(e.recently_created,t)),e.unparented&&(e.unparented=L(e.unparented,t)))}function Dn(e,t){const n=[e.high_level,e.low_level,e.blocked_fallback,e.recently_created??[],e.unparented??[]].flat();if(t){for(const r of n)delete r.tags,delete r.tags_inherited;return}const s=new Map(n.map(r=>[r.id,r])),o=new Map(n.map(r=>[r.id,r.tags?[...r.tags].sort().join("\0"):void 0]));for(const r of n){if(!r.parent||!r.tags)continue;const i=s.get(r.parent);i&&o.get(r.id)===o.get(i.id)&&(delete r.tags,r.tags_inherited=i.id)}}function Un(e,t,n){t.length>0||n.length>0||e.agenda.events.length>0||(e.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 Pn(e,t,n,s){try{const o=new Set(t.packing.included.map(a=>a.id)),r=t.ranking.ranked.map(a=>({id:a.id,rank:a.rank,included:o.has(a.id)})),i=new Set(r.map(a=>a.id));for(const a of It(e,"context"))i.has(a)||(r.push({id:a,rank:r.length+1,included:!1}),i.add(a));const c=await At({pmRoot:n,author:s,surface:"context",profile:t.packing.profile,rows:r,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});Et(e,c)}catch{e.warnings=ee(e.warnings,["context_usage_feedback_write_failed"])}}async function Hn(e,t,n,s=!1){if(e)return{};const o=await it({pmRoot:t,settings:n,cwd:process.cwd(),noExtensions:!1});if(o.discovered.length===0)return{};const r=await Promise.all(["project","global"].map(async u=>{const g=o.roots[u],[k,C]=await Promise.all([lt(Ye.dirname(g)),ut(g).then(_=>_??[])]);return[u,{observations:k,records:C}]})),i=new Map(r),c=new Map(o.effective.map(u=>[u.name,u.layer])),a=new Set(o.effective.map(u=>`${u.layer}:${u.directory}`)),l=new Set,f=o.discovered.map(u=>{const g=u.name??u.directory,k=u.name===null?void 0:c.get(u.name),C=i.get(u.layer),_=C.records.find(h=>h.directory===u.directory),b={name:g,scope:u.layer,version:u.version,status:u.status==="ok"?"ok":"degraded",update:ft(dt(C.observations,{name:g,version:u.version,updated_at:_?.updated_at,source:_?.source})),shadowed_by:k!==void 0&&!a.has(`${u.layer}:${u.directory}`)?k:null};return a.has(`${u.layer}:${u.directory}`)&&l.add(b),b}).sort((u,g)=>u.name.localeCompare(g.name)||u.scope.localeCompare(g.scope)),d=f.filter(u=>u.status==="degraded").length,m=f.filter(u=>typeof u.update=="string"&&l.has(u));return{extension_health:{total:f.length,ok:f.length-d,degraded:d,updates_available:m.length,...m.length>0?{next:pt(m,t,s)}:{},packages:f.slice(0,20),...f.length>20?{truncated:!0}:{}}}}function Bn(e){const t=e.packages.filter(r=>r.status==="degraded").map(r=>z(r.name)),n=e.next,s=n===void 0?"":`, ${String(e.updates_available)} with a known update (check with the commands below)`,o=e.packages.filter(r=>r.status==="degraded"||typeof r.update=="string"||typeof r.shadowed_by=="string");return[`- extensions: ${e.ok} ok, ${e.degraded} degraded${t.length>0?` (${t.join(", ")})`:""}${s}`,...o.map(Gn),...(n??[]).map(Rn)]}function Rn(e){return new RegExp("\\p{Cc}","u").test(e.replace(/[\n\t]/gu,""))?"- a live check command is not shown because the tracker path contains terminal control characters; read it from the JSON `next` field":zn(e)}function Gn(e){const t=[e.status,...typeof e.update=="string"?[`update ${z(e.update)}`]:[],...typeof e.shadowed_by=="string"?[`shadowed by ${e.shadowed_by}`]:[]];return` - ${z(e.name)} (${e.scope??"unknown scope"}, ${z(e.version??"unknown version")}): ${t.join(", ")}`}function z(e){return e.replace(/[\r\n]+/gu," ").replace(new RegExp("\\p{Cc}","gu"),"\uFFFD").replace(/[\\`*_[\]<>|~]/gu,"\\$&")}function zn(e){const t=Math.max(0,...[...e.matchAll(/`+/gu)].map(s=>s[0].length)),n="`".repeat(Math.max(3,t+1));return`${n}sh
3
+ ${e}
4
+ ${n}`}async function Xn(e,t){const n=Mt(),s=await jt(e),o=n.instance||Dt(t);return Ut(s.semantic_attribution?.[o])}async function yo(e,t){const n=le(process.cwd(),t.path),s=await Cn(e,t),o=await xn(t,s),r=ye(s.limit,o.fullCorpus.length),i={...s,limit:r,tokenBudget:Vt(e.tokenBudget,Math.max(256,r*160))},c=rt(void 0,i.settings.author_default),a=await Xn(n,c),l=Hn(e.noExtensionHealth===!0,n,i.settings,t.noExtensions===!0),f=mt(o.edgeCorpus,i.statusRegistry),d=await In(o.listedItemMetadata,o.allItems,o.edgeCorpus,f,i.statusRegistry,i.sectionsIncluded,i.limit,nt(),c,e.after,Ln(e,n),An(e,o.fullCorpus.length),n,i.tokenBudget,a,at(i.settings,ct())),m=await On(t,i,o.subtreeIds,new Set([...d.highLevel,...d.lowLevel,...d.blockedFallback].map(w=>w.id))),u=await Nt(o.fullCorpus,{pmRoot:n,statusRegistry:i.statusRegistry,now:m.agenda.now}),g=ee(o.listed.warnings,m.agenda.warnings,d.ranking.warnings,[...d.featureStore.warnings],u.warnings),k=te(d.activeItems,i.statusRegistry.in_progress_status,i.statusRegistry),C=d.activeItems.length-k,_=await Nn({runtime:i,allItems:o.allItems,fullCorpus:o.edgeCorpus,blockedIds:f,focusGroups:d,now:m.agenda.now,global:t}),b=Fn(o.allItems,i.statusRegistry,f,await et(n,o.allItems,{in_progress_status:i.statusRegistry.in_progress_status,status_registry:i.statusRegistry,threshold_hours:i.settings.mutation_guard.stale_in_progress_hours,now:new Date(m.agenda.now)})),h={output_default:"toon",now:m.agenda.now,depth:i.depth,sections_included:i.sectionsIncluded,window:{anchor:m.agenda.anchor,start:m.agenda.range.start,end:m.agenda.range.end,past:m.agenda.range.past,from:m.agenda.range.from,to:m.agenda.range.to},filters:{type:e.type??null,tag:e.tag??null,priority:e.priority??null,assignee:e.assignee??null,assignee_filter:e.assigneeFilter??null,sprint:e.sprint??null,release:e.release??null,limit:e.limit??e.maxItems??null,parent:i.parentScope??null,token_budget:i.tokenBudget,runtime_filters:o.listed.filters.runtime_filters??m.agenda.filters.runtime_filters??{}},summary:{returned_focus:{active_items:d.activeItems.length,in_progress:k,open:C,blocked:d.blockedItems.length},blocked_fallback_used:d.blockedFallbackUsed,high_level:d.highLevel.length,low_level:d.lowLevel.length,agenda_events:m.agendaSummary.events,...b},high_level:d.highLevel,low_level:d.lowLevel,blocked_fallback:d.blockedFallback,agenda:{summary:m.agendaSummary,events:m.agendaEvents},...d.pageExtras};return h.workspace_memory=Ft(u,Math.min(800,Math.floor(i.tokenBudget*.2))),Object.assign(h,await l),Mn(h,_,d.featureStore.warning_details),Dn(h,e.noTags===!0),e.explainRanking===!0&&(h.ranking=nn(d.ranking,d.featureStore,new Set([...d.highLevel,...d.lowLevel,...d.blockedFallback].map(w=>w.id))),h.packing=tn(d.packing)),Ct(h,[...d.highLevel,...d.lowLevel,...d.blockedFallback].map(w=>({id:w.id,status:y(w.status,i.statusRegistry)===U(i.statusRegistry)?"in_progress":"open",blocked:w.blocked}))),jn(h,i.focusFields),St(h),g.length>0&&(h.warnings=g),Un(h,d.activeItems,d.blockedItems),await Pn(h,d,n,c),h}export{Pt as CONTEXT_OUTPUT_VALUES,go as _testOnly,Dn as applyContextTagProjection,N as buildChildrenByParent,$o as buildItemContextRelevanceCandidates,Ce as collectSubtreeIds,A as compareCriticalItems,ee as mergeSortedWarnings,en as packRankedContextItems,Kt as parseContextDepth,Wt as parseContextFocusFields,Jt as parseContextSections,L as projectContextFocusRows,ko as renderContextMarkdown,Hn as resolveContextExtensionHealthProjection,_o as resolveContextOutputFormat,Vt as resolveContextTokenBudget,yo as runContext,G as toContextFocusItem,tn as toContextPackingSummary,nn as toContextRankingSummary};
3
5
  //# sourceMappingURL=context.js.map
@@ -1,2 +1,2 @@
1
- import{EXIT_CODE as p}from"../core/shared/constants.js";import{PmCliError as m}from"../core/shared/errors.js";import{asRecordClone as I}from"../core/shared/primitives.js";import{resolveCheckpointRollbackId as C}from"../core/checkpoint/mutation-checkpoint.js";import{withLiteralMutationInput as q}from"./lifecycle/cli-input.js";import{isCliMutationInput as M}from"../core/item/literal-mutation-input.js";import{assertMutationItemOperand as V,assertNativeMutationValueTypes as W}from"./runtime/mutation-value-validation.js";import{foldNullClearsIntoUnset as J}from"./lifecycle/shared-unset-fields.js";import{normalizeListOptions as Z,normalizeCreateOptions as X,normalizeUpdateOptions as Q}from"./cli-contracts/registration-helpers.js";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS as ee,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS as te,CREATE_COMMANDER_STRING_OPTION_CONTRACTS as ne,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS as k,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS as re,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS as ie}from"./cli-contracts/commander-mutation-options.js";import{TOOL_CREATE_OPTION_CONTRACTS as oe,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS as N,TOOL_UPDATE_OPTION_CONTRACTS as se}from"./cli-contracts/tool-option-contracts.js";import{PM_TOOL_PARAMETER_PROPERTIES as ae}from"./cli-contracts/tool-parameter-tables.js";import{PM_TOOL_ACTION_PARAMETER_CONTRACTS as P}from"./cli-contracts/tool-schema.js";import{normalizeBulkIdsValue as v}from"../core/io/bulk-ids-input.js";import{overlayMutationStdinTokenPolicy as ue,preserveMutationStdinTokenLiterals as le,transferMutationStdinTokenPolicy as y}from"../core/item/parse.js";const w=Symbol("pm.mcp-mutation-transport"),fe=new Set(["create","update","append"]),T={create:{parameters:oe,aliases:ee,strings:ne,repeatables:te},update:{parameters:se,aliases:k,strings:ie,repeatables:re}},de=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function Qe(e){return Object.defineProperty(e,w,{value:!0,enumerable:!0}),e}function _(e){return w in e}function S(e,t){return _(e)?le(t):y(e,t)}function et(e,t,n=[]){const r=y(e,{...e,...t});for(const a of n)Reflect.deleteProperty(r,a);return r}function u(e,t){const n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function f(e,t){const n=e[t];return typeof n=="string"?n.trim().length>0?n:void 0:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function tt(e,t){const n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function d(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function nt(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new m(`${t} must be a finite integer.`,p.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){const n=Number(e);if(!Number.isInteger(n))throw new m(`${t} must be a finite integer.`,p.USAGE);return n}}function rt(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:u(e,"limit")??u(t,"limit")}function it(e){const t=u(e,"outputFormat");return{json:!0,quiet:!0,author:u(e,"author"),path:u(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:u(e,"outputInclude"),outputLimit:f(e,"outputLimit"),outputBudget:f(e,"outputBudget"),outputSession:u(e,"outputSession"),outputCursor:u(e,"outputCursor"),outputFormat:t==="json"||t==="toon"?t:void 0}}const U=new Set(["tags","blockedBy","blocked_by","skills","fields"]),L=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),ce=new Set([...L].filter(e=>e!=="file")),pe=new Set(["files","files-discover","docs","test","test-all"]),E=new Set(["comments","notes","learnings"]);function me(e,t){if(!(!E.has(e)||!Object.prototype.hasOwnProperty.call(t,"file")))throw new m(`MCP ${e} does not accept options.file. Pass annotation text in options.add instead.`,p.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}const Ae=new Set(["claim","release","start-task","pause-task","close-task"]),D={history:["order"],"history-attest":["verify","output","hashAlgorithm"],list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate","inheritFocus"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt","releaseAssignment"],claim:["start","next","ifAvailable","takeoverStale"],"start-task":["takeoverStale"],release:["pause","handoff"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun","offline"],package:["dryRun","offline"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},Oe=new Set(["context","get","list","next","search","comments","notes","learnings","files","docs","test"]),he=new Set(["query","keywords","id","text"]);function ye(e){return Oe.has(e)?P[e].optional.filter(t=>!he.has(t)):[]}const _e=new Set(["claim","start-task","comments","notes","learnings","files","docs","test"]);function Te(e,t){if(!_e.has(e??""))return t;const n={...t};for(const r of P[e].optional){const a=r.replace(/[A-Z]/gu,s=>`_${s.toLowerCase()}`);a===r||n[a]===void 0||(n[r]??=n[a],delete n[a])}return n}function Se(e,t,n){if(!E.has(e??""))return n;const r=n,a=r.text??t.text;if(a===void 0)return r;if(r.add!==void 0&&r.add!==a){const i=e.replace(/s$/u,"");throw new m(`Specify ${i} text either as text or with add, not both.`,p.USAGE,{code:"annotation_text_source_conflict",field:"text",required:`Pass the ${i} text once: text and add are the same source.`})}const s={...r,add:a};return delete s.text,s}function Re(e,t){const n=t.replace(/[A-Z]/gu,r=>`_${r.toLowerCase()}`);return e[t]!==void 0||e[n]!==void 0}function Ce(e){return[...D[e]??[],...ye(e),...F]}const F=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function B(e,t=""){const n={},r=pe.has(t),a=t==="files"||t==="files-discover"||t==="docs",s=E.has(t)?ce:L;for(const[i,o]of Object.entries(e)){if(Array.isArray(o)&&U.has(i)){n[i]=o.join(",");continue}if(i==="note"&&a){n[i]=o;continue}if(typeof o=="string"&&s.has(i)){n[i]=[o];continue}if(typeof o=="string"&&r&&(i==="add"||i==="remove")){n[i]=[o];continue}n[i]=o}return Object.assign(n,Object.fromEntries(Object.getOwnPropertySymbols(e).map(i=>[i,Reflect.get(e,i)]))),n}function Ne(e,t,n){const r=u(e,"author");return r!==void 0?r:n!==void 0&&Ae.has(n)?u(e,"assignee")??u(t,"assignee"):void 0}function Ee(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function xe(e,t,n){const r={},a=T[e],s=new Set([...a.parameters.map(({param:i})=>i),...N.map(({param:i})=>i),...D[e],...F,"force"]);for(const i of s){const o=a.aliases.find(l=>l.keys.includes(i))?.keys??[i];t[i]===void 0||o.some(l=>n[l]!==void 0)||(r[i]=t[i])}return r}function O(e,t){throw new m(`Invalid MCP ${e} value for "${t}". No changes were made.`,p.USAGE,{code:"invalid_argument_value",reason:"invalid_mutation_option_value",changed:!1,field:t,required:`Provide valid ${e} field values and an options object; inspect the pm_${e} input schema for supported types.`})}function be(e,t,n){const r=T[e],a=[...r.parameters,...N,{param:"force"}];for(const{param:s}of a){if(I(ae[s]).type!=="boolean")continue;const o=(r.aliases.find(l=>l.keys.includes(s))?.keys??[s]).find(l=>n[l]!==void 0&&typeof n[l]!="boolean");o!==void 0&&O(e,o)}for(const s of["idOnly","fullChangedFields"])t[s]!==void 0&&typeof t[s]!="boolean"&&O(e,s)}function ge(e,t,n){t.options!==void 0&&!d(t.options)&&O(e,"options"),be(e,t,n);for(const i of U){const o=n[i];Array.isArray(o)&&o.some(l=>typeof l!="string")&&O(e,i)}const r=z(n,e),a=T[e];for(const{keys:i,target:o}of a.strings)i.some(l=>n[l]!==void 0)&&r[o]===void 0&&O(e,o);const s=a.repeatables.flatMap(({keys:i})=>i).find(i=>{const o=n[i];return o!==void 0&&typeof o!="string"&&(!Array.isArray(o)||o.some(l=>typeof l!="string"))});return s!==void 0&&O(e,s),r}function Ie(e,t,n,r,a){const s=(t==="create"||t==="update")&&_(e),i={...s?xe(t,e,r):n,...r};if((t==="create"||t==="update")&&!s){const o=d(e.options)&&M(e.options);o||J(t,i),W(t,i,!0,o)}return s?ge(t,e,i):a?B(i,t):i}function Me(e,t){return!fe.has(e??"")||M(t)?t:q(t)}function ot(e,t,{nativeAction:n=!0}={}){V(t,e);const r=d(e.options)?e.options:void 0,a=I(e.options),s={},i=c=>{Re(a,c)||e[c]===void 0||(s[c]=e[c])};for(const c of Ce(t??""))i(c);t!==void 0&&_(e)&&me(t,a);const o=Se(t,e,Te(t,Ie(e,t,s,a,n)));if(t==="history-attest"&&_(e)&&(o.output!==void 0||typeof o.verify=="string"))throw new m("MCP history attest does not accept server-local proof paths. Export the returned JSON bundle and pass that JSON object as verify.",p.USAGE);const l=_(e)?e:r??e,A=S(l,Ee(o,Ne(e,o,t)));return Me(t,A)}function st(e){if(e.addNote===void 0)return e;const t={...e};return t.note===void 0&&typeof t.addNote=="string"&&(t.note=t.addNote),delete t.addNote,t}function at(e){const t={...e};return t.discoveryNote!==void 0&&t.note===void 0&&typeof t.discoveryNote=="string"&&(t.note=t.discoveryNote),delete t.discover,delete t.discoveryNote,t}function ke(e){const t=[];let n=!0;for(const r of e.trim().toLowerCase()){if(r>="a"&&r<="z"||r>="0"&&r<="9"){t.push(r),n=!1;continue}n||(t.push("-"),n=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function ut(e){return!de.has(ke(e))}function lt(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function Pe(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function ft(e,t){const n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),r={};for(const[s,i]of Object.entries(e))n.has(s)||(r[s]=i);const a={...r,...t};return delete a.args,delete a.author,a}function dt(e,t){const n=S(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function x(e){return{type:f(e,"filterType"),tag:f(e,"filterTag"),priority:f(e,"filterPriority"),deadlineBefore:f(e,"filterDeadlineBefore"),deadlineAfter:f(e,"filterDeadlineAfter"),updatedAfter:f(e,"filterUpdatedAfter"),updatedBefore:f(e,"filterUpdatedBefore"),createdAfter:f(e,"filterCreatedAfter"),createdBefore:f(e,"filterCreatedBefore"),ids:v(e.ids),assignee:f(e,"filterAssignee"),assigneeFilter:f(e,"filterAssigneeFilter")??f(e,"filterAssignee_filter"),parent:f(e,"filterParent"),sprint:f(e,"filterSprint"),release:f(e,"filterRelease"),limit:f(e,"limit"),offset:f(e,"offset")}}function b(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return Pe(e)}function R(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function ct(e){const t=b(e.kind),n=b(e.exemptIsolate),r=b(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:R(e.maxDepth),limit:R(e.limit),after:u(e,"after"),direction:u(e,"direction"),maxPaths:R(e.maxPaths),sample:R(e.sample),...n===void 0?{}:{exemptIsolate:n},...r===void 0?{}:{exemptIsolateType:r},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function j(e){const t=Z(e);return e.ids!==void 0&&(t.ids=v(e.ids)),t}function pt(e){return{status:u(e,"filterStatus"),list:d(e.list)?j(e.list):x(e),reason:u(e,"reason"),completedAt:u(e,"completedAt")??u(e,"completed_at"),resolution:u(e,"resolution"),expectedResult:u(e,"expectedResult")??u(e,"expected_result")??u(e,"expected"),actualResult:u(e,"actualResult")??u(e,"actual_result")??u(e,"actual"),validateClose:u(e,"validateClose")??u(e,"validate_close"),author:u(e,"author"),message:u(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:C(e.rollback),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}const g=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function $(e){const t={};for(const[n,r]of Object.entries(e))g.has(n)||(t[n]=r);return G(t)}function G(e){return z(e,"update")}function z(e,t){const n=B(e,t),r=T[t],a=new Set([...r.parameters,...N].filter(({booleanish:s})=>s===!0).map(({param:s})=>s));for(const{keys:s}of r.repeatables)for(const i of s)typeof n[i]=="string"&&(n[i]=[n[i]]);for(const s of r.strings)for(const i of s.keys){const o=n[i];(typeof o=="number"&&Number.isFinite(o)||o===!1&&a.has(i))&&(n[i]=String(o))}return t==="create"?{...X(n,{requireType:!1})}:Q(n)}const ve=new Map(k.flatMap(({target:e,keys:t})=>t.map(n=>[n,e])));function we(e){return e.startsWith("filter")||e==="ids"||e==="limit"||e==="offset"}function K(e,t){throw new m(`update-many "${e}" cannot be null. No changes were made.`,p.USAGE,{code:"invalid_argument_value",reason:"invalid_mutation_option_value",changed:!1,field:e,required:t})}function Ue(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!g.has(t)))}function Y(e,t,n){if(!e)return;const r=d(t.list)?t.list:{},a=d(t.update)?t.update:void 0,s=Object.keys(t).find(o=>t[o]===null&&(a!==void 0||g.has(o)||we(o)))??Object.keys(r).filter(o=>r[o]===null).map(o=>`list.${o}`)[0];s!==void 0&&K(s,`"${s}" selects rows or controls the run: omit it or pass a value. To clear an item field, pass null on the field itself${a===void 0?"":" inside update"}.`);const i=a??Ue(t);for(const[o,l]of Object.entries(i)){if(l!==null)continue;const A=ve.get(o);A===void 0&&K(o,`Pass unset: ["${o}"] to clear a field, or omit "${o}".`),n[A]=null}}const Le=["author","message"];function De(e,t){const n=Object.fromEntries(Le.filter(r=>typeof e[r]=="string"&&t[r]===void 0).map(r=>[r,e[r]]));return e.force===!0&&t.force===void 0&&(n.force=!0),Object.keys(n).length===0?t:y(t,{...t,...n})}function mt(e,t=!1){if(d(e.list)||d(e.update)){const r=d(e.update)?De(e,e.update):$(e),a=S(e,G(r));return Y(t,e,a),{status:f(e,"filterStatus"),list:d(e.list)?j(e.list):x(e),update:ue(r,a),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:C(e.rollback),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}const n=S(e,$(e));return Y(t,e,n),{status:f(e,"filterStatus"),list:x(e),update:n,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:C(e.rollback),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}function H(e){return"expectHash"in e||"expect_hash"in e}function At(e){if(!H(e)&&!(d(e.options)&&H(e.options)))return{expectHash:void 0,dispatchArgs:e};const{expectHash:t,expect_hash:n,...r}=e,a=d(r.options)?r.options:{},{expectHash:s,expect_hash:i,...o}=a,l=[t,n,s,i].filter(h=>h!==void 0),A=l.length>1?l.flatMap(h=>Array.isArray(h)?h:[h]):l[0],c=y(e,"options"in r?{...r,options:d(r.options)?y(r.options,o):r.options}:r);return{expectHash:A,dispatchArgs:c}}export{D as HOISTED_ACTION_OPTION_KEYS,g as UPDATE_MANY_FLAT_CONTROL_KEYS,it as actionGlobalOptions,pt as closeManyOptionsFromFlat,ft as extensionOptionsFromArgs,ct as graphOptionsFromFlat,_ as isMcpMutationTransportInput,d as isRuntimeRecord,Qe as markMcpMutationTransportInput,x as mutationListOptions,et as mutationOptionsWithOverrides,ke as normalizeActionName,lt as normalizeCommandPath,B as normalizeMcpOptionsArrays,G as normalizeMcpUpdateOptions,ot as optionsWithAuthor,nt as parseRuntimeInteger,f as readRuntimeScalarString,tt as readRuntimeScalarStringAllowBlank,u as readRuntimeString,Pe as readRuntimeStringArray,rt as resolveRuntimeLimit,ut as shouldInvalidateWorkspaceContractsCacheAfterAction,At as splitExpectHashInput,mt as updateManyOptionsFromFlat,$ as updateManyUpdateOptionsFromFlat,st as withAddNoteOption,at as withFilesDiscoveryOptions,dt as withMutationCompaction};
1
+ import{EXIT_CODE as p}from"../core/shared/constants.js";import{PmCliError as m}from"../core/shared/errors.js";import{asRecordClone as I}from"../core/shared/primitives.js";import{resolveCheckpointRollbackId as C}from"../core/checkpoint/mutation-checkpoint.js";import{withLiteralMutationInput as q}from"./lifecycle/cli-input.js";import{isCliMutationInput as M}from"../core/item/literal-mutation-input.js";import{assertMutationItemOperand as V,assertNativeMutationValueTypes as W}from"./runtime/mutation-value-validation.js";import{foldNullClearsIntoUnset as J}from"./lifecycle/shared-unset-fields.js";import{normalizeListOptions as Z,normalizeCreateOptions as X,normalizeUpdateOptions as Q}from"./cli-contracts/registration-helpers.js";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS as ee,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS as te,CREATE_COMMANDER_STRING_OPTION_CONTRACTS as ne,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS as k,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS as re,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS as ie}from"./cli-contracts/commander-mutation-options.js";import{TOOL_CREATE_OPTION_CONTRACTS as oe,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS as N,TOOL_UPDATE_OPTION_CONTRACTS as se}from"./cli-contracts/tool-option-contracts.js";import{PM_TOOL_PARAMETER_PROPERTIES as ae}from"./cli-contracts/tool-parameter-tables.js";import{PM_TOOL_ACTION_PARAMETER_CONTRACTS as P}from"./cli-contracts/tool-schema.js";import{normalizeBulkIdsValue as v}from"../core/io/bulk-ids-input.js";import{overlayMutationStdinTokenPolicy as ue,preserveMutationStdinTokenLiterals as le,transferMutationStdinTokenPolicy as y}from"../core/item/parse.js";const w=Symbol("pm.mcp-mutation-transport"),fe=new Set(["create","update","append"]),T={create:{parameters:oe,aliases:ee,strings:ne,repeatables:te},update:{parameters:se,aliases:k,strings:ie,repeatables:re}},de=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function Qe(e){return Object.defineProperty(e,w,{value:!0,enumerable:!0}),e}function _(e){return w in e}function S(e,t){return _(e)?le(t):y(e,t)}function et(e,t,n=[]){const r=y(e,{...e,...t});for(const a of n)Reflect.deleteProperty(r,a);return r}function u(e,t){const n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function f(e,t){const n=e[t];return typeof n=="string"?n.trim().length>0?n:void 0:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function tt(e,t){const n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function d(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function nt(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new m(`${t} must be a finite integer.`,p.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){const n=Number(e);if(!Number.isInteger(n))throw new m(`${t} must be a finite integer.`,p.USAGE);return n}}function rt(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:u(e,"limit")??u(t,"limit")}function it(e){const t=u(e,"outputFormat");return{json:!0,quiet:!0,author:u(e,"author"),path:u(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:u(e,"outputInclude"),outputLimit:f(e,"outputLimit"),outputBudget:f(e,"outputBudget"),outputSession:u(e,"outputSession"),outputCursor:u(e,"outputCursor"),outputFormat:t==="json"||t==="toon"?t:void 0}}const U=new Set(["tags","blockedBy","blocked_by","skills","fields"]),L=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),ce=new Set([...L].filter(e=>e!=="file")),pe=new Set(["files","files-discover","docs","test","test-all"]),E=new Set(["comments","notes","learnings"]);function me(e,t){if(!(!E.has(e)||!Object.prototype.hasOwnProperty.call(t,"file")))throw new m(`MCP ${e} does not accept options.file. Pass annotation text in options.add instead.`,p.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}const Ae=new Set(["claim","release","start-task","pause-task","close-task"]),D={history:["order"],"history-attest":["verify","output","hashAlgorithm"],list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate","inheritFocus"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt","releaseAssignment"],claim:["start","next","ifAvailable","takeoverStale"],"start-task":["takeoverStale"],release:["pause","handoff"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun","offline","fields","scope"],package:["dryRun","offline","fields","scope"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},Oe=new Set(["context","get","list","next","search","comments","notes","learnings","files","docs","test"]),he=new Set(["query","keywords","id","text"]);function ye(e){return Oe.has(e)?P[e].optional.filter(t=>!he.has(t)):[]}const _e=new Set(["claim","start-task","comments","notes","learnings","files","docs","test"]);function Te(e,t){if(!_e.has(e??""))return t;const n={...t};for(const r of P[e].optional){const a=r.replace(/[A-Z]/gu,s=>`_${s.toLowerCase()}`);a===r||n[a]===void 0||(n[r]??=n[a],delete n[a])}return n}function Se(e,t,n){if(!E.has(e??""))return n;const r=n,a=r.text??t.text;if(a===void 0)return r;if(r.add!==void 0&&r.add!==a){const i=e.replace(/s$/u,"");throw new m(`Specify ${i} text either as text or with add, not both.`,p.USAGE,{code:"annotation_text_source_conflict",field:"text",required:`Pass the ${i} text once: text and add are the same source.`})}const s={...r,add:a};return delete s.text,s}function Re(e,t){const n=t.replace(/[A-Z]/gu,r=>`_${r.toLowerCase()}`);return e[t]!==void 0||e[n]!==void 0}function Ce(e){return[...D[e]??[],...ye(e),...F]}const F=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function B(e,t=""){const n={},r=pe.has(t),a=t==="files"||t==="files-discover"||t==="docs",s=E.has(t)?ce:L;for(const[i,o]of Object.entries(e)){if(Array.isArray(o)&&U.has(i)){n[i]=o.join(",");continue}if(i==="note"&&a){n[i]=o;continue}if(typeof o=="string"&&s.has(i)){n[i]=[o];continue}if(typeof o=="string"&&r&&(i==="add"||i==="remove")){n[i]=[o];continue}n[i]=o}return Object.assign(n,Object.fromEntries(Object.getOwnPropertySymbols(e).map(i=>[i,Reflect.get(e,i)]))),n}function Ne(e,t,n){const r=u(e,"author");return r!==void 0?r:n!==void 0&&Ae.has(n)?u(e,"assignee")??u(t,"assignee"):void 0}function Ee(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function xe(e,t,n){const r={},a=T[e],s=new Set([...a.parameters.map(({param:i})=>i),...N.map(({param:i})=>i),...D[e],...F,"force"]);for(const i of s){const o=a.aliases.find(l=>l.keys.includes(i))?.keys??[i];t[i]===void 0||o.some(l=>n[l]!==void 0)||(r[i]=t[i])}return r}function O(e,t){throw new m(`Invalid MCP ${e} value for "${t}". No changes were made.`,p.USAGE,{code:"invalid_argument_value",reason:"invalid_mutation_option_value",changed:!1,field:t,required:`Provide valid ${e} field values and an options object; inspect the pm_${e} input schema for supported types.`})}function be(e,t,n){const r=T[e],a=[...r.parameters,...N,{param:"force"}];for(const{param:s}of a){if(I(ae[s]).type!=="boolean")continue;const o=(r.aliases.find(l=>l.keys.includes(s))?.keys??[s]).find(l=>n[l]!==void 0&&typeof n[l]!="boolean");o!==void 0&&O(e,o)}for(const s of["idOnly","fullChangedFields"])t[s]!==void 0&&typeof t[s]!="boolean"&&O(e,s)}function ge(e,t,n){t.options!==void 0&&!d(t.options)&&O(e,"options"),be(e,t,n);for(const i of U){const o=n[i];Array.isArray(o)&&o.some(l=>typeof l!="string")&&O(e,i)}const r=z(n,e),a=T[e];for(const{keys:i,target:o}of a.strings)i.some(l=>n[l]!==void 0)&&r[o]===void 0&&O(e,o);const s=a.repeatables.flatMap(({keys:i})=>i).find(i=>{const o=n[i];return o!==void 0&&typeof o!="string"&&(!Array.isArray(o)||o.some(l=>typeof l!="string"))});return s!==void 0&&O(e,s),r}function Ie(e,t,n,r,a){const s=(t==="create"||t==="update")&&_(e),i={...s?xe(t,e,r):n,...r};if((t==="create"||t==="update")&&!s){const o=d(e.options)&&M(e.options);o||J(t,i),W(t,i,!0,o)}return s?ge(t,e,i):a?B(i,t):i}function Me(e,t){return!fe.has(e??"")||M(t)?t:q(t)}function ot(e,t,{nativeAction:n=!0}={}){V(t,e);const r=d(e.options)?e.options:void 0,a=I(e.options),s={},i=c=>{Re(a,c)||e[c]===void 0||(s[c]=e[c])};for(const c of Ce(t??""))i(c);t!==void 0&&_(e)&&me(t,a);const o=Se(t,e,Te(t,Ie(e,t,s,a,n)));if(t==="history-attest"&&_(e)&&(o.output!==void 0||typeof o.verify=="string"))throw new m("MCP history attest does not accept server-local proof paths. Export the returned JSON bundle and pass that JSON object as verify.",p.USAGE);const l=_(e)?e:r??e,A=S(l,Ee(o,Ne(e,o,t)));return Me(t,A)}function st(e){if(e.addNote===void 0)return e;const t={...e};return t.note===void 0&&typeof t.addNote=="string"&&(t.note=t.addNote),delete t.addNote,t}function at(e){const t={...e};return t.discoveryNote!==void 0&&t.note===void 0&&typeof t.discoveryNote=="string"&&(t.note=t.discoveryNote),delete t.discover,delete t.discoveryNote,t}function ke(e){const t=[];let n=!0;for(const r of e.trim().toLowerCase()){if(r>="a"&&r<="z"||r>="0"&&r<="9"){t.push(r),n=!1;continue}n||(t.push("-"),n=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function ut(e){return!de.has(ke(e))}function lt(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function Pe(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function ft(e,t){const n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),r={};for(const[s,i]of Object.entries(e))n.has(s)||(r[s]=i);const a={...r,...t};return delete a.args,delete a.author,a}function dt(e,t){const n=S(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function x(e){return{type:f(e,"filterType"),tag:f(e,"filterTag"),priority:f(e,"filterPriority"),deadlineBefore:f(e,"filterDeadlineBefore"),deadlineAfter:f(e,"filterDeadlineAfter"),updatedAfter:f(e,"filterUpdatedAfter"),updatedBefore:f(e,"filterUpdatedBefore"),createdAfter:f(e,"filterCreatedAfter"),createdBefore:f(e,"filterCreatedBefore"),ids:v(e.ids),assignee:f(e,"filterAssignee"),assigneeFilter:f(e,"filterAssigneeFilter")??f(e,"filterAssignee_filter"),parent:f(e,"filterParent"),sprint:f(e,"filterSprint"),release:f(e,"filterRelease"),limit:f(e,"limit"),offset:f(e,"offset")}}function b(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return Pe(e)}function R(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function ct(e){const t=b(e.kind),n=b(e.exemptIsolate),r=b(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:R(e.maxDepth),limit:R(e.limit),after:u(e,"after"),direction:u(e,"direction"),maxPaths:R(e.maxPaths),sample:R(e.sample),...n===void 0?{}:{exemptIsolate:n},...r===void 0?{}:{exemptIsolateType:r},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function j(e){const t=Z(e);return e.ids!==void 0&&(t.ids=v(e.ids)),t}function pt(e){return{status:u(e,"filterStatus"),list:d(e.list)?j(e.list):x(e),reason:u(e,"reason"),completedAt:u(e,"completedAt")??u(e,"completed_at"),resolution:u(e,"resolution"),expectedResult:u(e,"expectedResult")??u(e,"expected_result")??u(e,"expected"),actualResult:u(e,"actualResult")??u(e,"actual_result")??u(e,"actual"),validateClose:u(e,"validateClose")??u(e,"validate_close"),author:u(e,"author"),message:u(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:C(e.rollback),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}const g=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function $(e){const t={};for(const[n,r]of Object.entries(e))g.has(n)||(t[n]=r);return G(t)}function G(e){return z(e,"update")}function z(e,t){const n=B(e,t),r=T[t],a=new Set([...r.parameters,...N].filter(({booleanish:s})=>s===!0).map(({param:s})=>s));for(const{keys:s}of r.repeatables)for(const i of s)typeof n[i]=="string"&&(n[i]=[n[i]]);for(const s of r.strings)for(const i of s.keys){const o=n[i];(typeof o=="number"&&Number.isFinite(o)||o===!1&&a.has(i))&&(n[i]=String(o))}return t==="create"?{...X(n,{requireType:!1})}:Q(n)}const ve=new Map(k.flatMap(({target:e,keys:t})=>t.map(n=>[n,e])));function we(e){return e.startsWith("filter")||e==="ids"||e==="limit"||e==="offset"}function K(e,t){throw new m(`update-many "${e}" cannot be null. No changes were made.`,p.USAGE,{code:"invalid_argument_value",reason:"invalid_mutation_option_value",changed:!1,field:e,required:t})}function Ue(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!g.has(t)))}function Y(e,t,n){if(!e)return;const r=d(t.list)?t.list:{},a=d(t.update)?t.update:void 0,s=Object.keys(t).find(o=>t[o]===null&&(a!==void 0||g.has(o)||we(o)))??Object.keys(r).filter(o=>r[o]===null).map(o=>`list.${o}`)[0];s!==void 0&&K(s,`"${s}" selects rows or controls the run: omit it or pass a value. To clear an item field, pass null on the field itself${a===void 0?"":" inside update"}.`);const i=a??Ue(t);for(const[o,l]of Object.entries(i)){if(l!==null)continue;const A=ve.get(o);A===void 0&&K(o,`Pass unset: ["${o}"] to clear a field, or omit "${o}".`),n[A]=null}}const Le=["author","message"];function De(e,t){const n=Object.fromEntries(Le.filter(r=>typeof e[r]=="string"&&t[r]===void 0).map(r=>[r,e[r]]));return e.force===!0&&t.force===void 0&&(n.force=!0),Object.keys(n).length===0?t:y(t,{...t,...n})}function mt(e,t=!1){if(d(e.list)||d(e.update)){const r=d(e.update)?De(e,e.update):$(e),a=S(e,G(r));return Y(t,e,a),{status:f(e,"filterStatus"),list:d(e.list)?j(e.list):x(e),update:ue(r,a),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:C(e.rollback),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}const n=S(e,$(e));return Y(t,e,n),{status:f(e,"filterStatus"),list:x(e),update:n,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:C(e.rollback),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}function H(e){return"expectHash"in e||"expect_hash"in e}function At(e){if(!H(e)&&!(d(e.options)&&H(e.options)))return{expectHash:void 0,dispatchArgs:e};const{expectHash:t,expect_hash:n,...r}=e,a=d(r.options)?r.options:{},{expectHash:s,expect_hash:i,...o}=a,l=[t,n,s,i].filter(h=>h!==void 0),A=l.length>1?l.flatMap(h=>Array.isArray(h)?h:[h]):l[0],c=y(e,"options"in r?{...r,options:d(r.options)?y(r.options,o):r.options}:r);return{expectHash:A,dispatchArgs:c}}export{D as HOISTED_ACTION_OPTION_KEYS,g as UPDATE_MANY_FLAT_CONTROL_KEYS,it as actionGlobalOptions,pt as closeManyOptionsFromFlat,ft as extensionOptionsFromArgs,ct as graphOptionsFromFlat,_ as isMcpMutationTransportInput,d as isRuntimeRecord,Qe as markMcpMutationTransportInput,x as mutationListOptions,et as mutationOptionsWithOverrides,ke as normalizeActionName,lt as normalizeCommandPath,B as normalizeMcpOptionsArrays,G as normalizeMcpUpdateOptions,ot as optionsWithAuthor,nt as parseRuntimeInteger,f as readRuntimeScalarString,tt as readRuntimeScalarStringAllowBlank,u as readRuntimeString,Pe as readRuntimeStringArray,rt as resolveRuntimeLimit,ut as shouldInvalidateWorkspaceContractsCacheAfterAction,At as splitExpectHashInput,mt as updateManyOptionsFromFlat,$ as updateManyUpdateOptionsFromFlat,st as withAddNoteOption,at as withFilesDiscoveryOptions,dt as withMutationCompaction};
2
2
  //# sourceMappingURL=runtime-input.js.map
@@ -414,8 +414,26 @@ export declare function deactivateExtensionForTest(module:unknown,options?:Deact
414
414
  * through the same definition-driven normalizer as CLI dispatch and
415
415
  * `PmClient.run` (pm-gh1665): a declared CLI spelling such as `status-filter`
416
416
  * folds into the handler key `statusFilter`, declared defaults and value
417
- * coercion apply, two spellings with different values are refused with
418
- * `extension_option_spelling_conflict`, and undeclared keys pass through.
417
+ * coercion apply, and two spellings with different values are refused with
418
+ * `extension_option_spelling_conflict`. On a command that declares flags, an
419
+ * undeclared key with a defined value is refused with `unknown_option` (exit 2)
420
+ * before the handler (a key whose value is `undefined` counts as omitted and is
421
+ * forwarded as it is)
422
+ * runs, exactly as the CLI refuses an unknown flag, and an array for a flag
423
+ * that is not `list` or `repeatable` is refused with
424
+ * `extension_flag_value_invalid` (pm-gh1726, pm-gh1727). Host-owned keys (the
425
+ * reserved host flags such as `json` or `quiet`) skip extension-option
426
+ * normalization once host validation accepts them; host validation still refuses
427
+ * a read-output control such as `outputLimit` on a command that neither declares
428
+ * `read_output` nor extends a native read contract (a handler extending `notes`
429
+ * admits it on a read invocation). Undeclared keys
430
+ * still pass through verbatim in three cases only: a command that declares no
431
+ * flags (pm-4of199 owns that refusal), a hand-built registry with no flag
432
+ * registrations, and a native command path such as `list` that an extension
433
+ * extends or overrides, whose native contract owns every other key (pm-gh1780).
434
+ * To unit-test a handler with a free option bag, call the handler function
435
+ * directly; to exercise the dispatch contract, declare every option the test
436
+ * passes.
419
437
  *
420
438
  * Throws a descriptive error (listing the available handler command paths) when
421
439
  * no handler is registered for `command`, since that is a wiring/typo bug in the
package/docs/COMMANDS.md CHANGED
@@ -115,8 +115,10 @@ Use `--with-packages` for one-step agent setup when bundled package commands sho
115
115
 
116
116
  ```bash
117
117
  pm package # bare command defaults to --explore (list installed)
118
+ pm package list # installed packages in the selected scope, offline
119
+ pm package list --global --fields name,version,update
118
120
  pm package install '*' --project
119
- pm package catalog --project
121
+ pm package catalog --project # bundled first-party catalog
120
122
  pm package manage --project --output-format json
121
123
  pm package install npm:@scope/pm-package --project
122
124
  pm package describe --project # by-name surface map of every loaded package
@@ -130,6 +132,22 @@ pm package upgrade --cli-only --repair
130
132
  ```
131
133
 
132
134
  `pm package` is the canonical package-first workflow. `pm package` and the hidden `pm extension` alias default to `--explore` on a bare invocation so agents can list installed packages without remembering an action flag. `pm package install '*'`, shell-expanded `pm package install *`, and `pm package install all` install bundled first-party packages. `pm install`, `pm upgrade`, and `pm extension` remain executable as deprecated compatibility spellings declared in `PM_COMMAND_ALIAS_CONTRACTS`; they emit a migration hint and must not appear in documentation or skills as instructions.
135
+ `pm package list` (an alias of `pm package inventory`) lists the packages
136
+ installed in the selected scope without activating their code, with an `update`
137
+ column holding the newer version the last `pm package manage` check observed for
138
+ that installed version (`null` when none is known), and an `updates_available`
139
+ count. `pm package catalog` lists what pm bundles. `list`, `explore`, `manage`
140
+ and `catalog` take the same `--fields` contract: a comma-separated subset of the
141
+ row keys. An unknown key is refused with the listing's legal domain: human text
142
+ bounds a long domain, and `--json` carries it in `recovery.allowed_values` and
143
+ `refusal.legal_domain` within the default diagnostic budget (a refusal that
144
+ would exceed it is trimmed as
145
+ [Diagnostic Output Contracts](DIAGNOSTIC_OUTPUT_CONTRACTS.md) describe; the SDK
146
+ error context always holds the complete domain).
147
+ `explore` and `manage` rows leave the embedded `contributions` map out unless
148
+ `--fields` asks for it; `pm package describe` maps every registered surface
149
+ ([pm-gh1777](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1777.toon),
150
+ tracker record excluded from npm).
133
151
  `pm package catalog` emits one row per package, with every resolvable bundled
134
152
  alias preserved in `aliases`; totals therefore measure packages rather than
135
153
  alias-index entries. `pm package manage` participates in the universal read
@@ -245,7 +245,7 @@ underscore aliases remain accepted for compatibility.
245
245
  | `PM_OLLAMA_MODEL` | choose default Ollama embedding model |
246
246
  | `PM_DISABLE_OLLAMA_AUTO_DEFAULTS` | disable implicit Ollama search defaults |
247
247
  | `PM_CONTEXT_USAGE_DISABLED` | set to `1` to disable the derived context/next usage-feedback ledger with zero filesystem reads or writes |
248
- | `PM_COMMAND_SHELL` | shell the pm commands printed in recovery guidance (`suggested_retry`, `restore_with`, next steps) are quoted for: `posix` (also `sh`, `bash`, `zsh`), `cmd` (also `cmd.exe`) or `powershell` (also `pwsh`), case-insensitive. Default: `cmd` on Windows, `posix` elsewhere; an empty or unrecognized value keeps the default. In the `cmd` form, an argument that contains `%` or `"` has every cmd.exe metacharacter caret-escaped and a caret after each `%`, so cmd.exe cannot expand `%VAR%` or split the line at `&`. That holds as long as no environment variable is defined whose name starts with `^`, and while delayed expansion (`cmd /v:on`) stays off, its default. cmd.exe ends a command at a line break, which no quoting carries, so the cmd form renders each line break inside an argument as a space. npm's `pm.cmd` launcher parses its arguments a second time, so an argument holding `"` together with `^`, `&`, `\|`, `<` or `>` needs the native entry point (`node <install>/dist/cli.js`) or PowerShell's `pm.ps1`. The `powershell` form uses single-quoted literals, so `$`, `$(...)`, backticks and `%` never expand. Arguments then reach the native command exactly under PowerShell 7.3 or later in its default argument-passing mode. Windows PowerShell 5.1, and `$PSNativeCommandArgumentPassing = 'Legacy'`, drop empty arguments and mangle embedded double quotes. The `posix` form single-quotes an argument that holds `!`, which interactive bash and zsh would history-expand inside double quotes, and quotes a token that starts with `=`, which zsh expands to a command path ([GH-1774](https://github.com/unbraind/pm-cli/issues/1774)) |
248
+ | `PM_COMMAND_SHELL` | shell the pm commands printed in recovery guidance (`suggested_retry`, `restore_with`, next steps) are quoted for: `posix` (also `sh`, `bash`, `zsh`), `cmd` (also `cmd.exe`) or `powershell` (also `pwsh`), case-insensitive. Default: `cmd` on Windows, `posix` elsewhere; an empty or unrecognized value keeps the default. In the `cmd` form, an argument that contains `%` or `"` has every cmd.exe metacharacter caret-escaped and a caret after each `%`, so cmd.exe cannot expand `%VAR%` or split the line at `&`. That holds as long as no environment variable is defined whose name starts with `^`, and while delayed expansion (`cmd /v:on`) stays off, its default. cmd.exe ends a command at a line break, which no quoting carries, so the cmd form renders each line break inside an argument as a space. npm's `pm.cmd` launcher parses its arguments a second time, so an argument holding `"` together with `^`, `&`, `\|`, `<` or `>` needs the native entry point (`node <install>/dist/cli.js`) or PowerShell's `pm.ps1`. The `powershell` form uses single-quoted literals, so `$`, `$(...)`, backticks and `%` never expand. Arguments then reach the native command exactly under PowerShell 7.3 or later in its default argument-passing mode. Windows PowerShell 5.1, and `$PSNativeCommandArgumentPassing = 'Legacy'`, drop empty arguments and mangle embedded double quotes. The `posix` form single-quotes an argument that holds `!`, which interactive bash and zsh would history-expand inside double quotes, and also one that holds a line break or ends in a backslash: bash 3.2, the macOS system shell, misreads those double-quoted spellings when it scans a line for history expansion, so a later `!` would look live and its expansion pass would cut the line after the first non-ASCII character ([pm-jzrtsr](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-jzrtsr.toon); tracker record excluded from npm). It also quotes a token that starts with `=`, which zsh expands to a command path ([GH-1774](https://github.com/unbraind/pm-cli/issues/1774)) |
249
249
  | `PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS` | budget of each managed-package update lookup (`npm view` or `git ls-remote`) in integer milliseconds; default `10000`, clamped to `1000`–`25000`; `pm package manage --fix-managed-state` keeps the default because it looks up under the extension state lock. A lookup that runs out reports `npm_registry_lookup_timed_out` or `github_remote_lookup_timed_out` with `update_check_timeout_ms` |
250
250
 
251
251
  For command-level tracker targeting, prefer `--pm-path <tracker-root>`. The old
@@ -72,6 +72,12 @@ metadata described above. An absent `refusal` therefore
72
72
  does not prove that the producer supplied no legal domain. The original SDK
73
73
  error context retains the producer's complete domain; CLI JSON has its own
74
74
  ceiling and is not an unlimited restoration channel.
75
+ Human text lists at most eight legal values and counts the rest as
76
+ `allowed_values_omitted`, except that a domain of twelve or fewer values prints
77
+ whole when no token budget is tightening the rendering, because a CLI agent
78
+ cannot read the SDK error context the omission notice points to
79
+ ([pm-gh1778](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1778.toon),
80
+ tracker record excluded from npm).
75
81
  For malformed producer domains, text prioritizes the incomplete-domain notice
76
82
  and a bounded preview of whole usable choices even when producer next steps,
77
83
  verification errors, or recovery coordinates are oversized. An oversized close
@@ -10,8 +10,9 @@ Verified replacements and disabled compatibility findings are tracked by
10
10
 
11
11
  ## Read-only configured inventory
12
12
 
13
- Use `pm package inventory --project --json` (or `--global`) for a host GET route
14
- or agent read. Pass a name to receive an explicit `absent` row. The public SDK
13
+ Use `pm package list --project --json` (an alias of `pm package inventory`; or
14
+ `--global`) for a host GET route or agent read. Pass a name to receive an
15
+ explicit `absent` row, and `--fields name,version,update` for compact rows. The public SDK
15
16
  equivalent is `inspectStaticExtensionInventory({ pmRoot, scope, name })` from
16
17
  `@unbrained/pm-cli/sdk`. Both read settings, managed metadata, and manifests
17
18
  without importing package entrypoints, running hooks, checking for updates,
@@ -19,6 +20,75 @@ adopting installs, or writing workspace files. An absent managed-state file is
19
20
  reported separately from an invalid one. `complete: false` and `errors` mean
20
21
  the list must not be treated as authoritative; the CLI also exits nonzero.
21
22
 
23
+ Each installed row carries `update`: the newer version the last
24
+ `pm package manage` freshness check observed for exactly that installation, or
25
+ `null` when none is known. `manage` records what each check answered in the
26
+ untracked `runtime/extension-update-observations.json` of the scope
27
+ (`.agents/pm/runtime/` or the global pm root). Under a per-scope lock the
28
+ record is rebuilt from the managed state on disk at that moment: each current
29
+ installation keeps the latest observation taken against it, from this check or
30
+ an earlier one, and rows for replaced or removed installations are dropped, so
31
+ concurrent checks keep each other's answers and the record never outgrows the
32
+ managed packages. A check that timed out or failed records nothing for that
33
+ package. An observation names the manifest version and the managed record's
34
+ `updated_at` it was taken against, so any install that changes the version or
35
+ the source, including a commit-only reinstall of a repository source, retires
36
+ it; reinstalling the identical version from the identical source keeps it,
37
+ because its answer still applies. A registry `latest` that is not
38
+ newer than the installed npm version under SemVer precedence is recorded as no
39
+ update, because upgrading to it would downgrade; `pm package manage` applies the
40
+ same verdict. A cached verdict is used only when the live check could have
41
+ given it: a registry row must match that check's exact-version rule and SemVer
42
+ comparison against the record's own npm version, and a repository row must
43
+ carry the remote commit. A bounded (1 MiB) regular file is read only when the record
44
+ entry is a regular file and the opened descriptor is one too, and nothing is
45
+ written while `runtime/` is a link or not a directory (checked before and after
46
+ the lock is taken): a link, FIFO or oversized file reads as no knowledge. Node
47
+ has no directory-relative file API, so a process that can replace the
48
+ tracker's own `runtime/` between that check and the write could redirect it;
49
+ such a process already controls the tracker state the record describes. A
50
+ check time more than five minutes in the future reads as a clock error, and a
51
+ check under a pinned reproducible clock (`PM_CLOCK`/`PM_SEED`) records nothing,
52
+ because pinned times cannot order the record. The record is derived state: a failed write is the
53
+ warning `extension_update_observation_write_failed`, never a failed check.
54
+
55
+ `pm context` reads the same observations offline for its `extension_health`
56
+ block. Rows are `{name, scope, version, status, update, shadowed_by}`:
57
+ `shadowed_by` names the scope whose same-named copy the runtime loads instead
58
+ (project shadows global), so a copy installed in both scopes is told apart.
59
+ `updates_available` counts the copies static discovery selects (a shadowed or
60
+ disabled copy keeps its row but is not counted; this is static selection, not
61
+ activation truth, since no package module is imported) with a known update, and
62
+ `next` names one live check per scope with a known update, `pm package manage
63
+ --<scope>`, only when that count is above zero; the check re-reads each
64
+ source (the npm registry for a registry package, the Git remote for a
65
+ repository package) and shows its update evidence (`update_available`, plus
66
+ `last_update_remote_version` for npm or `last_update_remote_commit` for a
67
+ repository), and its remediation says to reinstall the
68
+ updated sources (`pm package upgrade <name> --<scope>` upgrades one). The hint names no package, so
69
+ no manifest-controlled name can select another installation, become an option,
70
+ or lose its quoting, and the Markdown rendering puts each hint in its own fenced
71
+ block, which keeps line breaks and shell escapes verbatim (a tracker path with
72
+ any other terminal control character is not written raw; the Markdown points to
73
+ the exact JSON `next` value instead). Every hint names the
74
+ absolute tracker the read served (`--pm-path`), because manage's activation
75
+ probe resolves it even for a global check, and a caller's explicit
76
+ `--no-extensions` carries over, because manage's live check runs before that
77
+ probe. A global hint assumes the caller's
78
+ environment, like any command: under a relative `PM_GLOBAL_PATH`, run it from
79
+ the same directory. An npm source that is not a registry install
80
+ (classified with npm's own spec parser: a path, tarball, `file:`, git or URL
81
+ spec) is never compared with a registry release, by `manage` or by the offline
82
+ readers, and `pm package upgrade` reinstalls every such artifact from its own
83
+ spec instead of moving it to a registry tag. Corrupt or unreadable managed metadata in a scope means unknown
84
+ updates there, never a failed `pm context`; a managed-state path that is not a
85
+ regular file is outside that guarantee, because extension discovery, which
86
+ `pm context` runs first, still reads the file directly. `pm package list` refuses the
87
+ row-shaping read-output controls it cannot apply (`read_output_surface_unsupported`) and
88
+ keeps `--output-format` and an unbounded `--output-budget`
89
+ ([pm-gh1778](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1778.toon),
90
+ tracker record excluded from npm).
91
+
22
92
  `configured_enabled` is the effective saved enablement setting, while
23
93
  `runtime_active` is always `null`. The static read does not prove that a package
24
94
  will activate successfully. `pm package explore`, `manage`, `doctor`, and
@@ -377,6 +377,53 @@ pieces (`password="$PW","…"`, a YAML single-quoted scalar whose doubled
377
377
  quotes are data), and a closing quote that another quote or a word follows
378
378
  (`echo "api_key=${EMPTY}""…"`) continues the shell word, as before.
379
379
 
380
+ The same rule ends the value of a quoted key that sits in a string
381
+ ([pm-gh1781](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1781.toon);
382
+ tracker record excluded from npm), so a member such as
383
+ `'password': '${BUILD_PASSWORD}'` inside compact JSON text
384
+ (`{"title":"'password': '${BUILD_PASSWORD}'","updated":"…"}`) is judged as in
385
+ pretty-printed JSON, and a whole `$NAME` or `%NAME%` value there is a
386
+ placeholder too. Only a value with a quote after its first character, or
387
+ right after it, reads the lexer; for a key nested in a container already
388
+ judged, the lexer resumes from a checkpoint kept every 1024 code units, so the
389
+ structured pass stays linear. A quote right after a letter, digit or
390
+ underscore opens no string, but in a shell it can open a segment of the word
391
+ (`foo"[" --'password'=${EMPTY}",""…"`, or `foo'["' …`, where the double
392
+ quote sits inside the single-quoted segment), and from there the lexer cannot
393
+ tell a segment's closing quote from a string's opening one, of either kind. A
394
+ line that declined a quote therefore reads as shell, where a closing quote
395
+ that more characters follow continues the word: no later string on the line
396
+ is trusted to end a value, and the value keeps its quoted pieces. A cut
397
+ only ever removes a finding, so it is made only where the string state is
398
+ unambiguous; keeping that distrust local to the affected segment is owned by
399
+ [pm-ghgf4a](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-ghgf4a.toon)
400
+ (tracker record excluded from npm). A Python string prefix (`r"…"`, `b'…'`, `rb"…"`, `f"…"` and the
401
+ other combinations) opens its string with the escapes an unprefixed one has,
402
+ so `b'…\'` closes where a shell closes it: a prefix alone never shows Python
403
+ context. A Python string that escapes an apostrophe therefore reads as a
404
+ shell close, and a later member on its line keeps the conservative reading
405
+ (a false positive [pm-ghgf4a](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-ghgf4a.toon)
406
+ owns, never a hidden literal). Outside every string a backslash before a quote
407
+ is a shell escape but a literal path separator to PowerShell and cmd.exe
408
+ (`C:\temp\"…"`), so it makes the line ambiguous in the same way. In JSON text
409
+ every quote opens, closes or is escaped, so none is declined there.
410
+
411
+ A single-quoted value is judged under each reading a format gives it.
412
+ - **Decoded:** with Python and JavaScript escapes decoded.
413
+ - **Backslashes kept:** over the span the escape-aware scan closes. This is
414
+ an upper bound for Python, which keeps an unrecognized escape such as `\q`.
415
+ - **Text:** the reading a shell word and a TOML literal string share, where a
416
+ backslash never escapes. The value ends at its first closing quote and keeps
417
+ the pieces joined after it, so a quoted piece that ends in a backslash and
418
+ the characters joined after it reach Bash as one word. For YAML, which escapes a quote by doubling it, this reading is
419
+ a scanner's approximation.
420
+
421
+ A span the escape-aware scan leaves open because its last quote is escaped
422
+ is not read with its backslashes kept, since that would count the quote as
423
+ data. So `'\\\\\\\'` (seven backslashes) is seven data characters in the
424
+ text reading and four in the decoded one, both below the literal minimum,
425
+ while eight backslashes are still reported.
426
+
380
427
  A whole Windows variable (`%DB_PASSWORD%`) is a placeholder for every
381
428
  key-named rule. `cmd.exe` reads `set NAME=value` to the end of the line, so an
382
429
  unquoted text value is whole only when nothing but blanks follows it on its
package/docs/SDK.md CHANGED
@@ -994,8 +994,27 @@ _behavior_ (`result.result`) rather than only that the command is wired. The
994
994
  same normalizer as CLI dispatch and `PmClient.run`: `"status-filter"` reaches
995
995
  the handler as `statusFilter`, declared defaults and coercion apply, and two
996
996
  spellings with different values are refused (see
997
- [Handler keys and ownership](#handler-keys-and-ownership)). A hand-built
998
- registry has no declared flags, so its options pass through verbatim. A clean
997
+ [Handler keys and ownership](#handler-keys-and-ownership)). On a command that
998
+ declares flags, an undeclared key with a defined value is refused with
999
+ `unknown_option` (exit 2) before the handler runs, exactly as the CLI refuses
1000
+ an unknown flag (a key whose value is `undefined` counts as omitted and is
1001
+ forwarded as it is), and an
1002
+ array for a flag that is not `list` or `repeatable` is refused with
1003
+ `extension_flag_value_invalid`; host-owned keys (the reserved host flags such
1004
+ as `json` or `quiet`) skip extension-option normalization once host validation
1005
+ accepts them, and host validation still refuses a read-output control such as
1006
+ `outputLimit` on a command that neither declares `read_output` nor extends a
1007
+ native read contract (a handler extending `notes` admits it on a read
1008
+ invocation through the native contract). Undeclared keys pass through
1009
+ verbatim in three cases only: a command that declares no flags
1010
+ ([pm-4of199](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-4of199.toon),
1011
+ tracker record excluded from npm, owns that refusal), a hand-built registry
1012
+ with no flag registrations, and a native command path such as `list` that an
1013
+ extension extends or overrides. To unit-test a handler with a free option bag,
1014
+ call the handler function directly; to exercise the dispatch contract, declare
1015
+ every option the test passes
1016
+ ([pm-gh1780](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1780.toon),
1017
+ tracker record excluded from npm). A clean
999
1018
  run yields `{ handled: true, result, warnings: [] }`; a handler that throws a
1000
1019
  non-exit error yields `{ handled: false, warnings: [code], errorMessage }` so the
1001
1020
  failure can be asserted. Returned objects may declare `exit_code` from `1`
@@ -3695,7 +3714,9 @@ or `powershell`), otherwise `cmd` on Windows and `posix` elsewhere. Pass a
3695
3714
  explicitly. `quoteCmdCommandArg` caret-escapes an argument that holds `%` or
3696
3715
  `"`, so cmd.exe can neither expand `%VAR%` nor split the line.
3697
3716
  `quotePowerShellCommandArg` emits a single-quoted literal, and
3698
- `quotePosixCommandArg` single-quotes an argument that holds `!`. The
3717
+ `quotePosixCommandArg` single-quotes an argument that holds `!` or a line
3718
+ break, or ends in a backslash, the spellings bash 3.2's history scanner
3719
+ would misread in double quotes. The
3699
3720
  redaction rules above recognize a credential in every one of these
3700
3721
  spellings, also when the rendered command is embedded in a JSON string.
3701
3722