@unbrained/pm-cli 2026.11.7 → 2026.11.8

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 (241) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +69 -48
  3. package/dist/cli/extension-command-help.js +4 -3
  4. package/dist/cli/help-json-payload.js +1 -1
  5. package/dist/cli/main.js +1 -1
  6. package/dist/cli/register-annotations.js +1 -1
  7. package/dist/cli/register-list-query.js +5 -5
  8. package/dist/cli/runtime/annotation-option-retry.js +2 -0
  9. package/dist/cli/runtime/invocation-options.js +1 -1
  10. package/dist/cli-bundle/bundle-manifest.json +1 -1
  11. package/dist/cli-bundle/chunks/chunk-3A5DJZCC.js +116 -0
  12. package/dist/cli-bundle/chunks/chunk-4BMPGUTG.js +9 -0
  13. package/dist/cli-bundle/chunks/{chunk-RFI4O6NU.js → chunk-7GC6WIDR.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-VM6OGNQC.js → chunk-7V6I6X4G.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-MQOZNGPS.js → chunk-AFZS6WFV.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-OIBSKKCO.js → chunk-C4MQFWCM.js} +2 -2
  17. package/dist/cli-bundle/chunks/chunk-CP43BHX3.js +31 -0
  18. package/dist/cli-bundle/chunks/{chunk-WS2N4TQW.js → chunk-DOHZKPPC.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-ETHAZC3F.js → chunk-HESIRIVX.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-JZWFZH2K.js → chunk-JAE5MWLX.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-KPAVZILX.js → chunk-L5BU5FYN.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-3DI6CEF3.js → chunk-LI2HP5OX.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-D53G3NOE.js → chunk-LLTRUVKK.js} +3 -3
  24. package/dist/cli-bundle/chunks/{chunk-BQ5O3CBF.js → chunk-MKW5LGVQ.js} +69 -65
  25. package/dist/cli-bundle/chunks/chunk-NH7QX2M2.js +8 -0
  26. package/dist/cli-bundle/chunks/{chunk-OJZG7Y6S.js → chunk-NKO42JMT.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-XSEDESNW.js → chunk-PE6CZ3PE.js} +2 -2
  28. package/dist/cli-bundle/chunks/chunk-RC6SSFOF.js +2 -0
  29. package/dist/cli-bundle/chunks/{chunk-TGQPCNAD.js → chunk-S4IZIMAO.js} +2 -2
  30. package/dist/cli-bundle/chunks/{chunk-WXVMPLBY.js → chunk-XBUZENP4.js} +2 -2
  31. package/dist/cli-bundle/chunks/chunk-YGUUJHSR.js +2 -0
  32. package/dist/cli-bundle/chunks/{chunk-F3B2ULHB.js → chunk-YUTFMHSG.js} +6 -6
  33. package/dist/cli-bundle/chunks/{chunk-QG6FLDM4.js → chunk-Z3LWNF7C.js} +2 -2
  34. package/dist/cli-bundle/chunks/{item-revision-SPEKTFBB.js → item-revision-TUGZYYXX.js} +2 -2
  35. package/dist/cli-bundle/chunks/item-transaction-2RRBAQN3.js +2 -0
  36. package/dist/cli-bundle/chunks/{mutation-admission-LUXUKISJ.js → mutation-admission-FJ3D66PV.js} +2 -2
  37. package/dist/cli-bundle/chunks/register-list-query-GXP77CX7.js +11 -0
  38. package/dist/cli-bundle/chunks/register-mutation-XJ2DROUM.js +20 -0
  39. package/dist/cli-bundle/chunks/{register-operations-AHDWE2G3.js → register-operations-O5LERXM7.js} +2 -2
  40. package/dist/cli-bundle/chunks/{register-setup-7BGG3CI3.js → register-setup-4VOTYLL2.js} +2 -2
  41. package/dist/cli-bundle/chunks/{stage-S5BYWLGY.js → stage-ZDJL3FGL.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/chunk-2A3QZELL.js +26 -0
  43. package/dist/cli-bundle/focused-chunks/{chunk-JRJOFMI7.js → chunk-3HFENALW.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/chunk-4UOXVFJZ.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-LW4TN5ZM.js → chunk-5YPX3QKU.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-4EXRRSDS.js → chunk-6U5HP6L3.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/chunk-DIEBSC76.js +3 -0
  48. package/dist/cli-bundle/focused-chunks/{chunk-BIDF4KO7.js → chunk-I4YUZW3J.js} +8 -8
  49. package/dist/cli-bundle/focused-chunks/{chunk-AJ2I377F.js → chunk-KBRSA4OK.js} +26 -26
  50. package/dist/cli-bundle/focused-chunks/{chunk-IYJRFJHT.js → chunk-KNF2QTEZ.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/chunk-LTPT5TE7.js +24 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-O7K3X4LH.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/chunk-P4EHEH4C.js +2 -0
  54. package/dist/cli-bundle/focused-chunks/chunk-P6TG33FV.js +82 -0
  55. package/dist/cli-bundle/focused-chunks/chunk-PL6EO4GJ.js +2 -0
  56. package/dist/cli-bundle/focused-chunks/{chunk-LTTMERPN.js → chunk-PSLDGAEY.js} +3 -3
  57. package/dist/cli-bundle/focused-chunks/chunk-SZ2BKK3M.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-TSHRBPTI.js +2 -0
  59. package/dist/cli-bundle/focused-chunks/chunk-ULTSMJYF.js +91 -0
  60. package/dist/cli-bundle/focused-chunks/chunk-UNNLBJRI.js +2 -0
  61. package/dist/cli-bundle/focused-chunks/chunk-UUVRYIKA.js +2 -0
  62. package/dist/cli-bundle/focused-chunks/{chunk-G2VIY6XA.js → chunk-WPXMPGTY.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/chunk-Z2QWZRSL.js +26 -0
  64. package/dist/cli-bundle/focused-chunks/item-revision-XNSRDTFB.js +2 -0
  65. package/dist/cli-bundle/focused-chunks/item-transaction-Q2Z7DDCR.js +2 -0
  66. package/dist/cli-bundle/focused-chunks/mutation-admission-QWC6MLTZ.js +2 -0
  67. package/dist/cli-bundle/focused-chunks/stage-NKH5SKSZ.js +2 -0
  68. package/dist/cli-bundle/main.js +32 -31
  69. package/dist/cli-bundle/sdk-authoring.js +1 -1
  70. package/dist/cli-bundle/sdk-contracts.js +4 -4
  71. package/dist/cli-bundle/sdk-core.js +1 -1
  72. package/dist/cli-bundle/sdk-governance.js +1 -1
  73. package/dist/cli-bundle/sdk-graph.js +1 -1
  74. package/dist/cli-bundle/sdk-merge.js +57 -57
  75. package/dist/cli-bundle/sdk-query.js +1 -1
  76. package/dist/cli-bundle/sdk-runtime.js +1 -1
  77. package/dist/cli-bundle/sdk-testing.js +1 -1
  78. package/dist/cli-bundle/sdk.js +12 -12
  79. package/dist/core/extensions/flag-definition-validation.js +1 -1
  80. package/dist/core/extensions/reserved-host-flags.js +1 -1
  81. package/dist/core/history/history-stream-policy.d.ts +12 -3
  82. package/dist/core/history/history-stream-policy.js +1 -1
  83. package/dist/core/history/projection.d.ts +7 -2
  84. package/dist/core/history/projection.js +1 -1
  85. package/dist/core/item/item-format.d.ts +5 -1
  86. package/dist/core/item/item-format.js +2 -2
  87. package/dist/core/lock/lock.d.ts +1 -1
  88. package/dist/core/lock/lock.js +1 -1
  89. package/dist/core/output/output.d.ts +10 -1
  90. package/dist/core/output/output.js +7 -7
  91. package/dist/core/search/providers.d.ts +3 -2
  92. package/dist/core/search/providers.js +1 -1
  93. package/dist/core/search/vector-stores.d.ts +3 -2
  94. package/dist/core/search/vector-stores.js +1 -1
  95. package/dist/core/sentry/instrument.d.ts +2 -1
  96. package/dist/core/sentry/instrument.js +1 -1
  97. package/dist/mcp/tool-definitions.js +1 -1
  98. package/dist/sdk/annotations.d.ts +44 -1
  99. package/dist/sdk/annotations.js +1 -1
  100. package/dist/sdk/authoring.d.ts +6 -0
  101. package/dist/sdk/authoring.js +1 -1
  102. package/dist/sdk/cli-contracts/flag-contracts.d.ts +15 -0
  103. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  104. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  105. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +6 -0
  106. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  107. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  108. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  109. package/dist/sdk/command-line.d.ts +2 -1
  110. package/dist/sdk/command-line.js +1 -1
  111. package/dist/sdk/comments.d.ts +4 -2
  112. package/dist/sdk/comments.js +1 -1
  113. package/dist/sdk/completion/bash.js +1 -1
  114. package/dist/sdk/completion/fish.js +2 -1
  115. package/dist/sdk/completion/zsh.js +4 -1
  116. package/dist/sdk/context-intent-contracts.d.ts +5 -1
  117. package/dist/sdk/context-intent-contracts.js +1 -1
  118. package/dist/sdk/contracts.d.ts +3 -0
  119. package/dist/sdk/contracts.js +1 -1
  120. package/dist/sdk/core.d.ts +14 -0
  121. package/dist/sdk/core.js +1 -1
  122. package/dist/sdk/corpus-shape.d.ts +2 -2
  123. package/dist/sdk/corpus-shape.js +1 -1
  124. package/dist/sdk/define.d.ts +14 -8
  125. package/dist/sdk/define.js +1 -1
  126. package/dist/sdk/extension/command-options.d.ts +123 -0
  127. package/dist/sdk/extension/command-options.js +2 -0
  128. package/dist/sdk/extension-contracts.d.ts +1 -2
  129. package/dist/sdk/extension-contracts.js +1 -1
  130. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  131. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  132. package/dist/sdk/governance.d.ts +8 -0
  133. package/dist/sdk/governance.js +1 -1
  134. package/dist/sdk/graph.d.ts +5 -0
  135. package/dist/sdk/graph.js +1 -1
  136. package/dist/sdk/index.d.ts +61 -1
  137. package/dist/sdk/index.js +1 -1
  138. package/dist/sdk/learnings.d.ts +4 -2
  139. package/dist/sdk/learnings.js +1 -1
  140. package/dist/sdk/lifecycle/restore.d.ts +1 -1
  141. package/dist/sdk/merge.d.ts +3 -0
  142. package/dist/sdk/merge.js +1 -1
  143. package/dist/sdk/notes.d.ts +4 -2
  144. package/dist/sdk/notes.js +1 -1
  145. package/dist/sdk/public-surface.json +1 -1
  146. package/dist/sdk/query/list.d.ts +5 -1
  147. package/dist/sdk/query/list.js +1 -1
  148. package/dist/sdk/query/search/semantic.d.ts +11 -3
  149. package/dist/sdk/query/search/semantic.js +1 -1
  150. package/dist/sdk/query/search-rendering.d.ts +9 -3
  151. package/dist/sdk/query/search-rendering.js +1 -1
  152. package/dist/sdk/query.d.ts +11 -0
  153. package/dist/sdk/query.js +1 -1
  154. package/dist/sdk/read-output/continuation.d.ts +8 -0
  155. package/dist/sdk/read-output/continuation.js +1 -1
  156. package/dist/sdk/read-output/options.d.ts +1 -1
  157. package/dist/sdk/read-output/options.js +1 -1
  158. package/dist/sdk/read-output/surfaces.js +1 -1
  159. package/dist/sdk/read-output/tail-retention.d.ts +34 -0
  160. package/dist/sdk/read-output/tail-retention.js +2 -0
  161. package/dist/sdk/read-output-budget.d.ts +14 -2
  162. package/dist/sdk/read-output-budget.js +1 -1
  163. package/dist/sdk/read-output-contracts.d.ts +20 -4
  164. package/dist/sdk/read-output-contracts.js +1 -1
  165. package/dist/sdk/read-output-rows.d.ts +7 -3
  166. package/dist/sdk/read-output-rows.js +1 -1
  167. package/dist/sdk/runtime-input.js +1 -1
  168. package/dist/sdk/runtime.d.ts +26 -3
  169. package/dist/sdk/runtime.js +1 -1
  170. package/dist/sdk/test/execution.d.ts +29 -2
  171. package/dist/sdk/test/execution.js +1 -1
  172. package/dist/sdk/testing.d.ts +14 -1
  173. package/dist/sdk/testing.js +1 -1
  174. package/dist/sdk/traceability/source-traceability.d.ts +4 -1
  175. package/dist/sdk/traceability/source-traceability.js +1 -1
  176. package/dist/sdk/workspace-recipe.d.ts +2 -2
  177. package/dist/sdk/workspace-recipe.js +1 -1
  178. package/docs/ARCHITECTURE.md +2 -1
  179. package/docs/COMMANDS.md +4 -1
  180. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +1 -1
  181. package/docs/EXTENSIONS.md +1 -1
  182. package/docs/MCP_OPTION_CONFORMANCE.md +13 -0
  183. package/docs/README.md +1 -1
  184. package/docs/READ_OUTPUT_CONTRACTS.md +78 -0
  185. package/docs/SDK.md +100 -2
  186. package/docs/SDK_CONTEXT_INTEGRITY.md +2 -0
  187. package/docs/agent-task-token-baseline.json +1 -1
  188. package/docs/generated/FLAG_LEXICON_BUDGETS.md +6 -6
  189. package/marketplace.json +1 -1
  190. package/package.json +2 -1
  191. package/packages/pm-beads/package.json +1 -1
  192. package/packages/pm-calendar/package.json +1 -1
  193. package/packages/pm-command-kit/package.json +1 -1
  194. package/packages/pm-digital-twin/package.json +1 -1
  195. package/packages/pm-governance-audit/package.json +1 -1
  196. package/packages/pm-guide-shell/package.json +1 -1
  197. package/packages/pm-kanban/package.json +1 -1
  198. package/packages/pm-lifecycle-hooks/package.json +1 -1
  199. package/packages/pm-linked-test-adapters/package.json +1 -1
  200. package/packages/pm-search-advanced/package.json +1 -1
  201. package/packages/pm-templates/package.json +1 -1
  202. package/packages/pm-todos/package.json +1 -1
  203. package/packages/pm-vcs/package.json +1 -1
  204. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  205. package/plugins/pm-claude/package.json +1 -1
  206. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  207. package/plugins/pm-codex/package.json +1 -1
  208. package/plugins/pm-codex/plugin.json +1 -1
  209. package/runtime-dependencies.json +1 -1
  210. package/dist/cli/extension-command-options.js +0 -2
  211. package/dist/cli-bundle/chunks/chunk-4PPWVIIT.js +0 -2
  212. package/dist/cli-bundle/chunks/chunk-5KHLV7JU.js +0 -116
  213. package/dist/cli-bundle/chunks/chunk-COKKWMSC.js +0 -8
  214. package/dist/cli-bundle/chunks/chunk-O6TIOKCM.js +0 -9
  215. package/dist/cli-bundle/chunks/chunk-WYIDX67P.js +0 -31
  216. package/dist/cli-bundle/chunks/item-transaction-BT55TQXE.js +0 -2
  217. package/dist/cli-bundle/chunks/register-list-query-DU4W7VJU.js +0 -11
  218. package/dist/cli-bundle/chunks/register-mutation-IC2C53QK.js +0 -20
  219. package/dist/cli-bundle/focused-chunks/chunk-4LDOL6U7.js +0 -26
  220. package/dist/cli-bundle/focused-chunks/chunk-4PW5XWVI.js +0 -2
  221. package/dist/cli-bundle/focused-chunks/chunk-A46YSPRF.js +0 -2
  222. package/dist/cli-bundle/focused-chunks/chunk-AI2PYNFI.js +0 -2
  223. package/dist/cli-bundle/focused-chunks/chunk-CWFNQQZE.js +0 -3
  224. package/dist/cli-bundle/focused-chunks/chunk-D3U7FOZR.js +0 -2
  225. package/dist/cli-bundle/focused-chunks/chunk-GFF6BITP.js +0 -2
  226. package/dist/cli-bundle/focused-chunks/chunk-IIBWXNW3.js +0 -3
  227. package/dist/cli-bundle/focused-chunks/chunk-J5N42SKC.js +0 -3
  228. package/dist/cli-bundle/focused-chunks/chunk-KL33JMPC.js +0 -2
  229. package/dist/cli-bundle/focused-chunks/chunk-LH4C7BLB.js +0 -2
  230. package/dist/cli-bundle/focused-chunks/chunk-LTQEYE2L.js +0 -81
  231. package/dist/cli-bundle/focused-chunks/chunk-MESFDQ3H.js +0 -26
  232. package/dist/cli-bundle/focused-chunks/chunk-MWTBAI3V.js +0 -2
  233. package/dist/cli-bundle/focused-chunks/chunk-TWULNB3N.js +0 -2
  234. package/dist/cli-bundle/focused-chunks/chunk-XAC6NP7U.js +0 -2
  235. package/dist/cli-bundle/focused-chunks/chunk-XG3TBYQK.js +0 -23
  236. package/dist/cli-bundle/focused-chunks/chunk-XMZAFKVP.js +0 -91
  237. package/dist/cli-bundle/focused-chunks/item-revision-ELI6NGMY.js +0 -2
  238. package/dist/cli-bundle/focused-chunks/item-transaction-GUGAUY77.js +0 -2
  239. package/dist/cli-bundle/focused-chunks/mutation-admission-54FI37AA.js +0 -2
  240. package/dist/cli-bundle/focused-chunks/stage-OHDJ43T2.js +0 -2
  241. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +0 -472
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="13e57322-501d-5927-8254-f6196854d434")}catch{}})();import{formatBuiltInOutput}from"../core/output/output.js";import{unicodeSafePrefix}from"../core/shared/text-normalization.js";import{countReadOutputRows,readOutputBudgetCollections}from"./read-output-rows.js";const MAX_ESTIMATE_ITERATIONS=8,MAX_COMPACTION_ITERATIONS=64,RECOVERY_MARGIN_NUMERATOR=5,RECOVERY_MARGIN_DENOMINATOR=4,RECOVERY_ROUNDING_TOKENS=100;function projectReadOutputItemToBrief(command,options,result){if(command!=="get"||!isRecord(result.item)||["fields","outputInclude","output_include","outputCursor","output_cursor"].some(key=>options[key]!==void 0)||options.full===!0||options.tree===!0||options.depth!==void 0&&options.depth!=="standard")return;const item=result.item,sections=["linked","claim_state","schedule"],omitted=sections.filter(key=>Object.hasOwn(result,key)),projected=Object.fromEntries(Object.entries(result).filter(([key])=>!sections.includes(key)));projected.item=Object.fromEntries(Object.entries(item).filter(([key])=>key!=="body")),Object.hasOwn(item,"body")&&omitted.push("body");const groups=[...isRecord(result.omission_receipt)&&Array.isArray(result.omission_receipt.omitted_field_groups)?result.omission_receipt.omitted_field_groups:[],...omitted.map(name=>({name,restore_with:`--fields ${name}`}))];return projected.omission_receipt={has_omissions:groups.length>0,omitted_field_group_count:groups.length,omitted_field_groups:groups},projected}function resolveReadOutputRecoveryBudget(input){const binding=Math.trunc(input.effective_budget_tokens),measured=Math.trunc(input.measured_result_tokens);if(!Number.isSafeInteger(binding)||binding<=0||!Number.isSafeInteger(measured)||measured<=0)return{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"};const baseline=Math.max(binding+1,measured),withMargin=Math.ceil(baseline*RECOVERY_MARGIN_NUMERATOR/RECOVERY_MARGIN_DENOMINATOR),rounded=Math.ceil(withMargin/RECOVERY_ROUNDING_TOKENS)*RECOVERY_ROUNDING_TOKENS;return Number.isSafeInteger(rounded)?{output_budget:rounded,recovery_budget_multiplier:rounded/binding,rule_version:"v1"}:{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"}}function preserveReadOutputRowContract(source,target,suppress=!1){const descriptor=Object.getOwnPropertyDescriptor(source,"row_contract");descriptor&&(suppress||descriptor.enumerable===!1)&&Object.defineProperty(target,"row_contract",{...descriptor,enumerable:!1})}function estimateReadOutputTokens(result,format){const rendered=format===void 0?JSON.stringify(result):formatBuiltInOutput(result,format);return Math.ceil(Buffer.byteLength(rendered,"utf8")/4)}function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function compactStrings(value,state,preserveStrings=!1){return typeof value=="string"?preserveStrings||value.length<=240?value:(state.compacted=!0,`${unicodeSafePrefix(value,240)}\u2026`):Array.isArray(value)?value.map(entry=>compactStrings(entry,state,preserveStrings)):isRecord(value)?Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,compactStrings(entry,state,preserveStrings||key==="focus_row_states")])):value}function updateReadOutputReceiptEstimate(result,receipt,format){let estimate=receipt.estimated_tokens;for(let iteration=0;iteration<MAX_ESTIMATE_ITERATIONS;iteration+=1){receipt.estimated_tokens=estimate;const measured=estimateReadOutputTokens(result,format);if(measured===estimate)return;estimate=measured}receipt.estimated_tokens=estimate}function selectCompactionCollection(result,minimumRowsByPath){return readOutputBudgetCollections(result).filter(collection=>(Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length)>Math.max(1,minimumRowsByPath.get(collection.path)??0)).map(collection=>({collection,length:Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length})).sort((left,right)=>right.length-left.length||left.collection.path.localeCompare(right.collection.path))[0]?.collection}function compactRowsToBudget(result,receipt,budget,minimumRowsByPath,format,finalize){for(let iteration=0;iteration<MAX_COMPACTION_ITERATIONS;iteration+=1){if(finalize?.(result),updateReadOutputReceiptEstimate(result,receipt,format),receipt.estimated_tokens<=budget)return;const candidate=selectCompactionCollection(result,minimumRowsByPath);if(!candidate)return;const minimumRows=Math.max(1,minimumRowsByPath.get(candidate.path)??0),values=Array.isArray(candidate.value)?[...candidate.value]:Object.entries(candidate.value),retainPrefix=length=>{if(Array.isArray(candidate.value)){candidate.value.length=length;for(let index=0;index<length;index+=1)candidate.value[index]=values[index]}else{for(const key of Object.keys(candidate.value))delete candidate.value[key];Object.defineProperties(candidate.value,Object.getOwnPropertyDescriptors(Object.fromEntries(values.slice(0,length))))}typeof result.count=="number"&&(result.count=countReadOutputRows(result)),candidate.path==="items"&&(result.applied_limit=length),finalize?.(result),updateReadOutputReceiptEstimate(result,receipt,format)};receipt.rows_compacted=!0,receipt.compacted_row_paths=[...new Set([...receipt.compacted_row_paths??[],candidate.path])].sort((left,right)=>left.localeCompare(right)),result.has_more=!0,result.truncated=!0;let low=minimumRows,high=values.length-1,retained=minimumRows;for(;low<=high;){const middle=Math.floor((low+high)/2);retainPrefix(middle),receipt.estimated_tokens<=budget?(retained=middle,low=middle+1):high=middle-1}retainPrefix(retained)}}function compactReadOutputToBudget(result,receipt,budget,minimumRowsByPath=new Map,format,finalize,preserveStrings=!1){const stringCompactionState={compacted:!1},compacted=Object.fromEntries(Object.entries(result).map(([key,value])=>[key,compactStrings(value,stringCompactionState,preserveStrings&&key==="diff")]));return preserveReadOutputRowContract(result,compacted),receipt.strings_compacted=stringCompactionState.compacted,compacted.read_output=receipt,compactRowsToBudget(compacted,receipt,budget,minimumRowsByPath,format,finalize),updateReadOutputReceiptEstimate(compacted,receipt,format),compacted}export{compactReadOutputToBudget,estimateReadOutputTokens,preserveReadOutputRowContract,projectReadOutputItemToBrief,resolveReadOutputRecoveryBudget,updateReadOutputReceiptEstimate};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="cc4233e3-6eda-535f-a31b-e4c7b2d29404")}catch{}})();import{formatBuiltInOutput}from"../core/output/output.js";import{unicodeSafePrefix}from"../core/shared/text-normalization.js";import{countReadOutputRows,readOutputBudgetCollections}from"./read-output-rows.js";const MAX_ESTIMATE_ITERATIONS=8,MAX_COMPACTION_ITERATIONS=64,RECOVERY_MARGIN_NUMERATOR=5,RECOVERY_MARGIN_DENOMINATOR=4,RECOVERY_ROUNDING_TOKENS=100;function projectReadOutputItemToBrief(command,options,result){if(command!=="get"||!isRecord(result.item)||["fields","outputInclude","output_include","outputCursor","output_cursor"].some(key=>options[key]!==void 0)||options.full===!0||options.tree===!0||options.depth!==void 0&&options.depth!=="standard")return;const item=result.item,sections=["linked","claim_state","schedule"],omitted=sections.filter(key=>Object.hasOwn(result,key)),projected=Object.fromEntries(Object.entries(result).filter(([key])=>!sections.includes(key)));projected.item=Object.fromEntries(Object.entries(item).filter(([key])=>key!=="body")),Object.hasOwn(item,"body")&&omitted.push("body");const groups=[...isRecord(result.omission_receipt)&&Array.isArray(result.omission_receipt.omitted_field_groups)?result.omission_receipt.omitted_field_groups:[],...omitted.map(name=>({name,restore_with:`--fields ${name}`}))];return projected.omission_receipt={has_omissions:groups.length>0,omitted_field_group_count:groups.length,omitted_field_groups:groups},projected}function resolveReadOutputRecoveryBudget(input){const binding=Math.trunc(input.effective_budget_tokens),measured=Math.trunc(input.measured_result_tokens);if(!Number.isSafeInteger(binding)||binding<=0||!Number.isSafeInteger(measured)||measured<=0)return{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"};const baseline=Math.max(binding+1,measured),withMargin=Math.ceil(baseline*RECOVERY_MARGIN_NUMERATOR/RECOVERY_MARGIN_DENOMINATOR),rounded=Math.ceil(withMargin/RECOVERY_ROUNDING_TOKENS)*RECOVERY_ROUNDING_TOKENS;return Number.isSafeInteger(rounded)?{output_budget:rounded,recovery_budget_multiplier:rounded/binding,rule_version:"v1"}:{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"}}function preserveReadOutputRowContract(source,target,suppress=!1){const descriptor=Object.getOwnPropertyDescriptor(source,"row_contract");descriptor&&(suppress||descriptor.enumerable===!1)&&Object.defineProperty(target,"row_contract",{...descriptor,enumerable:!1})}function readOutputMeasurementFormat(options){const format=options.resolvedOutputFormat??options.outputFormat??options.output_format??options.format;return format==="json"||format==="toon"?format:void 0}let activeDeliveredOutput;function withDeliveredOutputRenderer(format,render,run){const previous=activeDeliveredOutput;activeDeliveredOutput={format,render};try{return run()}finally{activeDeliveredOutput=previous}}function estimateReadOutputTokens(result,format){const rendered=format===void 0?JSON.stringify(result):activeDeliveredOutput!==void 0&&activeDeliveredOutput.format===format?renderOutsideDeliveredScope(activeDeliveredOutput,result):formatBuiltInOutput(result,format);return Math.ceil(Buffer.byteLength(rendered,"utf8")/4)}function renderOutsideDeliveredScope(delivered,result){activeDeliveredOutput=void 0;try{return delivered.render(result)}finally{activeDeliveredOutput=delivered}}function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function compactStrings(value,state,preserveStrings=!1){return typeof value=="string"?preserveStrings||value.length<=240?value:(state.compacted=!0,`${unicodeSafePrefix(value,240)}\u2026`):Array.isArray(value)?value.map(entry=>compactStrings(entry,state,preserveStrings)):isRecord(value)?Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,compactStrings(entry,state,preserveStrings||key==="focus_row_states")])):value}function updateReadOutputReceiptEstimate(result,receipt,format){let estimate=receipt.estimated_tokens;for(let iteration=0;iteration<MAX_ESTIMATE_ITERATIONS;iteration+=1){receipt.estimated_tokens=estimate;const measured=estimateReadOutputTokens(result,format);if(measured===estimate)return;estimate=measured}receipt.estimated_tokens=estimate}function selectCompactionCollection(result,minimumRowsByPath){return readOutputBudgetCollections(result).filter(collection=>(Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length)>Math.max(1,minimumRowsByPath.get(collection.path)??0)).map(collection=>({collection,length:Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length})).sort((left,right)=>right.length-left.length||left.collection.path.localeCompare(right.collection.path))[0]?.collection}function compactRowsToBudget(result,receipt,budget,minimumRowsByPath,format,finalize,retainsTail){for(let iteration=0;iteration<MAX_COMPACTION_ITERATIONS;iteration+=1){if(finalize?.(result),updateReadOutputReceiptEstimate(result,receipt,format),receipt.estimated_tokens<=budget)return;const candidate=selectCompactionCollection(result,minimumRowsByPath);if(!candidate)return;const minimumRows=Math.max(1,minimumRowsByPath.get(candidate.path)??0),values=Array.isArray(candidate.value)?[...candidate.value]:Object.entries(candidate.value),tail=retainsTail(candidate.path),retainRows=length=>{const start=tail?values.length-length:0;if(Array.isArray(candidate.value)){candidate.value.length=length;for(let index=0;index<length;index+=1)candidate.value[index]=values[start+index]}else{for(const key of Object.keys(candidate.value))delete candidate.value[key];Object.defineProperties(candidate.value,Object.getOwnPropertyDescriptors(Object.fromEntries(values.slice(start,start+length))))}typeof result.count=="number"&&(result.count=countReadOutputRows(result)),typeof result.returned_count=="number"&&(result.returned_count=countReadOutputRows(result)),candidate.path==="items"&&(result.applied_limit=length),finalize?.(result),updateReadOutputReceiptEstimate(result,receipt,format)};receipt.rows_compacted=!0,receipt.compacted_row_paths=[...new Set([...receipt.compacted_row_paths??[],candidate.path])].sort((left,right)=>left.localeCompare(right)),result.has_more=!0,result.truncated=!0;let low=minimumRows,high=values.length-1,retained=minimumRows;for(;low<=high;){const middle=Math.floor((low+high)/2);retainRows(middle),receipt.estimated_tokens<=budget?(retained=middle,low=middle+1):high=middle-1}retainRows(retained)}}function compactReadOutputToBudget(result,receipt,budget,minimumRowsByPath=new Map,format,finalize,preserveStrings=!1,retainsTail=()=>!1){const stringCompactionState={compacted:!1},compacted=Object.fromEntries(Object.entries(result).map(([key,value])=>[key,compactStrings(value,stringCompactionState,preserveStrings&&key==="diff")]));return preserveReadOutputRowContract(result,compacted),receipt.strings_compacted=stringCompactionState.compacted,compacted.read_output=receipt,compactRowsToBudget(compacted,receipt,budget,minimumRowsByPath,format,finalize,retainsTail),updateReadOutputReceiptEstimate(compacted,receipt,format),compacted}export{MAX_ESTIMATE_ITERATIONS,compactReadOutputToBudget,estimateReadOutputTokens,preserveReadOutputRowContract,projectReadOutputItemToBrief,readOutputMeasurementFormat,resolveReadOutputRecoveryBudget,updateReadOutputReceiptEstimate,withDeliveredOutputRenderer};
2
2
  //# sourceMappingURL=read-output-budget.js.map
@@ -8,7 +8,9 @@ import { PM_READ_OUTPUT_SURFACES } from "./read-output/options.js";
8
8
  export { resolveReadOutputRecoveryBudget } from "./read-output-budget.js";
9
9
  export type { PmReadOutputRecoveryBudget,PmReadOutputRecoveryBudgetInput,} from "./read-output-budget.js";
10
10
  export { decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,readOutputCollectionFingerprint,} from "./read-output/continuation.js";
11
+ export { PM_READ_OUTPUT_TAIL_RETENTION_POLICIES,readOutputRetainsTail,} from "./read-output/tail-retention.js";
11
12
  export type { PmReadOutputContinuationFingerprintPolicy } from "./read-output/continuation.js";
13
+ export type { PmReadOutputDeliveredRowCounter,PmReadOutputTailRetentionPolicy,} from "./read-output/tail-retention.js";
12
14
  import { type PmReadOutputSessionReceipt,type PmReadOutputSessionState } from "./read-output-session.js";
13
15
  import type { PmReadOutputProducerContinuation } from "./context-intent-contracts.js";
14
16
  import type { PmReadOutputSessionResult } from "./read-output/session-result.js";
@@ -71,8 +73,11 @@ command:PmReadOutputSurface;
71
73
  dimensions:Record<PmReadOutputDimension,PmReadOutputDimensionContract>;
72
74
  /** Deterministic precedence from strongest caller declaration to fallback. */
73
75
  precedence:readonly ["canonical","legacy","intent","default"];
74
- /** Stable policy used before budget compaction selects retained rows. */
75
- budget_retention_policy:"ordered_prefix" | "verdict_priority";
76
+ /**
77
+ * Stable policy used before budget compaction selects retained rows:
78
+ * `ordered_suffix` surfaces keep their newest (last) rows and page backwards.
79
+ */
80
+ budget_retention_policy:"ordered_prefix" | "ordered_suffix" | "verdict_priority";
76
81
  /** Exact command-local whole-result modes accepted by `outputInclude`. */
77
82
  projection_modes?:readonly string[];
78
83
  }
@@ -208,12 +213,17 @@ version:1;
208
213
  command:PmReadOutputSurface;
209
214
  /** Dot-delimited declared row path being continued. */
210
215
  path:string;
211
- /** Zero-based index of the first withheld row. */
216
+ /**
217
+ * Forward: zero-based index of the first withheld row. Backward: number of
218
+ * older rows still withheld, so the next page ends just before this index.
219
+ */
212
220
  offset:number;
213
221
  /** Stable pre-projection denominator for the row collection. */
214
222
  total_rows:number;
215
223
  /** Stable identity fingerprint used to refuse stale continuation. */
216
224
  fingerprint:string;
225
+ /** `backward` for a newest-tail collection whose next page holds older rows; absent means forward. */
226
+ direction?:"backward";
217
227
  }
218
228
  /** Result returned when the requested cost ceiling cannot fit useful content. */
219
229
  export interface PmReadOutputBudgetExceeded {
@@ -256,7 +266,7 @@ export type PmReadOutputResultFor<Result,Options> = Options extends unknown ? "o
256
266
  /** Infer possible session values from either spelling accepted by the direct helper. */
257
267
  type ReadOutputSessionOption<Options> = ("outputSession" extends keyof Options ? Options["outputSession"] :never) | ("output_session" extends keyof Options ? Options["output_session"] :never);
258
268
  /** Keep universal budget omissions while adding references only for possible sessions. */
259
- type ReadOutputResultForSession<Result,Options> = Options extends unknown ? PmReadOutputResultFor<Result,{
269
+ export type ReadOutputResultForSession<Result,Options> = Options extends unknown ? PmReadOutputResultFor<Result,{
260
270
  outputSession:ReadOutputSessionOption<Options>;
261
271
  }> :never;
262
272
  /** Canonical CLI flags that opt a read invocation into universal output shaping. */
@@ -305,6 +315,12 @@ export declare function resolveReadOutputDimensions(command:string,options:Recor
305
315
  export declare function stabilizeReadOutputReceiptEstimates(result:Record<string,unknown>,options:Record<string,unknown>):Record<string,unknown>;
306
316
  /** Apply universal field, row, and token bounds and attach an exact receipt. */
307
317
  export declare function applyReadOutputDimensions<Result extends Record<string,unknown>,Options extends Record<string,unknown> = Record<string,unknown>>(command:string,options:Options,result:Result):ReadOutputResultForSession<Result,Options>;
318
+ /**
319
+ * Whether a read envelope withheld its requested result for a budget: the
320
+ * shared `output_budget_exceeded` branch or an omitted read-intent result.
321
+ * Transports treat both as unsuccessful (CLI exit 2).
322
+ */
323
+ export declare function isReadResultOmittedForBudget(result:unknown):boolean;
308
324
  /** Narrow a universal read result to its budget-omission branch. */
309
325
  export declare function isReadOutputBudgetExceeded(result:unknown):result is PmReadOutputBudgetExceeded;
310
326
  /** Resolve only the canonical renderer override for shared CLI output code. */
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="dd173d3c-f3da-53f3-b24c-118364961db7")}catch{}})();import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS,PM_READ_OUTPUT_SURFACES}from"./read-output/options.js";import{resolvePmHistoryOperation}from"./cli-contracts/command-aliases.js";import{resolveExtensionOutputCommand}from"./read-output/extension.js";import{BEHAVIOR_PRESERVING_MIGRATION_HINTS,LEGACY_FLAGS_BY_COMMAND,VALUE_BEARING_INCLUDE_ALIASES,flagSelector,optionKey,readOutputIncludeModeOptionsForSurface,resolveNativeReadOutputSurface}from"./read-output/surfaces.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{compactReadOutputToBudget,estimateReadOutputTokens,projectReadOutputItemToBrief,preserveReadOutputRowContract,resolveReadOutputRecoveryBudget,updateReadOutputReceiptEstimate}from"./read-output-budget.js";import{resolveReadOutputRecoveryBudget as resolveReadOutputRecoveryBudget2}from"./read-output-budget.js";import{resolvePmCommandOutputBudget}from"./cli-contracts/agent-output-contracts.js";import{boundReadOutputRows,countReadOutputRows,mapReadOutputRows,readOutputBudgetCollections,readOutputContinuationRowCollections,readOutputRowPaths,readOutputRowCollections,refreshReadOutputDeliveredCounts}from"./read-output-rows.js";import{applyReadOutputContinuation,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,prioritizeAssuranceAssertions,readOutputCollectionFingerprint}from"./read-output/continuation.js";import{decodeReadOutputContinuationCursor as decodeReadOutputContinuationCursor2,encodeReadOutputContinuationCursor as encodeReadOutputContinuationCursor2,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,readOutputCollectionFingerprint as readOutputCollectionFingerprint2}from"./read-output/continuation.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens}from"./read-output-session.js";import{decodeQueryCursorEnvelope,encodeQueryCursor}from"./pagination.js";import{READ_OUTPUT_INVOCATION_PROVENANCE}from"./read-output/provenance.js";const PM_READ_OUTPUT_DIMENSIONS=["include","amount","cost","encoding"];import{PM_READ_OUTPUT_SURFACES as PM_READ_OUTPUT_SURFACES2}from"./read-output/options.js";const READ_OUTPUT_PRECEDENCE=["canonical","legacy","intent","default"],CANONICAL_OPTIONS=READ_OUTPUT_DIMENSION_FLAGS,PM_READ_OUTPUT_OPTION_FLAGS=Object.freeze(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>CANONICAL_OPTIONS[dimension])),PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS=READ_OUTPUT_COMPOSITION_FLAGS;function migrationHint(flag,dimension){const behaviorHint=BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag];if(behaviorHint!==void 0)return behaviorHint;const suffix=dimension==="include"?VALUE_BEARING_INCLUDE_ALIASES.has(flag)?"<csv>":flagSelector(flag):dimension==="amount"?"<n>":dimension==="cost"?"<tokens>":"<toon|json>";return`${flag} is a compatibility alias; prefer ${CANONICAL_OPTIONS[dimension]} ${suffix}.`}function buildSurfaceContract(command){const legacy=LEGACY_FLAGS_BY_COMMAND[command]??{},dimensions=Object.freeze(Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,Object.freeze({dimension,canonical_option:CANONICAL_OPTIONS[dimension],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((legacy[dimension]??[]).map(flag=>Object.freeze({flag,semantics:BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0?"replacement":"behavior_preserving",migration_hint:migrationHint(flag,dimension),visibility:"hidden_alias"})))})])));return Object.freeze({command,dimensions,precedence:READ_OUTPUT_PRECEDENCE,budget_retention_policy:command==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...readOutputIncludeModeOptionsForSurface(command).keys()])})}const PM_READ_OUTPUT_SURFACE_CONTRACTS=Object.freeze(PM_READ_OUTPUT_SURFACES.map(buildSurfaceContract)),SURFACE_CONTRACT_BY_COMMAND=new Map(PM_READ_OUTPUT_SURFACE_CONTRACTS.map(contract=>[contract.command,contract]));function resolveReadOutputSurface(command,options={}){const normalizedCommand=resolvePmHistoryOperation(command.trim().toLowerCase()),extension=resolveExtensionOutputCommand(normalizedCommand);return extension!==void 0?extension.read_output===void 0?void 0:`extension:${extension.command}`:resolveNativeReadOutputSurface(normalizedCommand,options)}const CANONICAL_OPTION_KEYS=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],HYBRID_READ_MUTATION_KEYS={comments:["add","body","stdin","file","edit","delete"],notes:["add","addJson","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function hasCanonicalReadOutputOptions(options){return CANONICAL_OPTION_KEYS.some(key=>key!=="outputFormat"&&key!=="output_format"&&options[key]!==void 0)}const READ_OUTPUT_VALUE_VALIDATORS=[{keys:["outputInclude","output_include"],valid:value=>stringList(value)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:value=>(parseReadOutputSession(value),!0),message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:value=>typeof value=="string"&&value.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}];function validateReadOutputOptions(command,options){const encoding=options.outputFormat??options.output_format;if(encoding!==void 0&&encoding!=="json"&&encoding!=="toon")throw new PmCliError("--output-format must be toon or json.",EXIT_CODE.USAGE);if(!hasCanonicalReadOutputOptions(options))return;const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand)throw new PmCliError(`Universal output controls apply only to read commands; ${command||"this command"} is not a read surface.`,EXIT_CODE.USAGE);if((HYBRID_READ_MUTATION_KEYS[normalizedCommand]??[]).some(key=>options[key]!==void 0&&options[key]!==!1))throw new PmCliError(`Universal output controls cannot be combined with a ${normalizedCommand} mutation.`,EXIT_CODE.USAGE);for(const validator of READ_OUTPUT_VALUE_VALIDATORS){const value=validator.keys.map(key=>options[key]).find(entry=>entry!==void 0);if(value!==void 0&&!validator.valid(value))throw new PmCliError(validator.message,EXIT_CODE.USAGE)}}function readOutputIncludeModeOptions(command){const surface=resolveReadOutputSurface(command);return surface?readOutputIncludeModeOptionsForSurface(surface):new Map}function applyReadOutputIncludeModes(command,includeValue,commandOptions){const requested=stringList(includeValue)??[],modeOptions=readOutputIncludeModeOptions(command),selectors=[],modes=[],optionsWithProvenance=commandOptions,existingProvenance=optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE],canonicalModes=new Set(existingProvenance?.canonical_include_modes??[]),explicitLegacyAliases=new Set(existingProvenance?.explicit_legacy_aliases??[]);for(const token of requested){const option=modeOptions.get(token);if(option===void 0){selectors.push(token);continue}const legacyFlag=`--${token.replaceAll("_","-")}`;isRequestedOption(readOption(commandOptions,legacyFlag))&&explicitLegacyAliases.add(legacyFlag),commandOptions[option]=!0,modes.push(token),canonicalModes.add(token)}const forwardedGetFieldSelectors=resolveReadOutputSurface(command)==="get"?selectors.filter(selector=>selector!=="item"):[],forwardedGetFields=forwardedGetFieldSelectors.length>0;return forwardedGetFields&&(commandOptions.fields=[...new Set([...stringList(commandOptions.fields)??[],...forwardedGetFieldSelectors])].join(","),canonicalModes.add("fields")),(modes.length>0||forwardedGetFields)&&(optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE]={canonical_include_modes:[...canonicalModes],explicit_legacy_aliases:[...explicitLegacyAliases],...existingProvenance?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors,modes}}function normalizeReadOutputIncludeModeOptions(command,options){const include=options.outputInclude??options.output_include;if(include===void 0)return;const{selectors,modes}=applyReadOutputIncludeModes(command,include,options);if(modes.length===0)return;const residual=selectors.length>0?selectors.join(","):void 0;options.outputInclude=residual,Object.hasOwn(options,"output_include")&&(options.output_include=residual)}function readOption(options,flag){const key=optionKey(flag);if(Object.hasOwn(options,key))return options[key];const snakeKey=flag.slice(2).replaceAll("-","_");if(Object.hasOwn(options,snakeKey))return options[snakeKey];if(flag==="--no-truncate"&&options.truncate===!1)return!0}function isRequestedOption(value){return value!==void 0&&value!==!1&&value!==null}function stringList(value){const normalized=(Array.isArray(value)?value:[value]).flatMap(entry=>typeof entry=="string"?entry.split(","):[]).map(entry=>entry.trim()).filter(Boolean);return normalized.length>0?[...new Set(normalized)]:void 0}function positiveInteger(value){const parsed=typeof value=="number"?value:typeof value=="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function resolveLegacyDimension(contract,options,usable,ignore){for(const alias of contract.legacy_aliases){if(ignore(alias.flag))continue;const value=readOption(options,alias.flag),candidate={value,flag:alias.flag};if(isRequestedOption(value)&&usable(candidate))return candidate}}function resolveIncludeValue(canonical,legacy){const canonicalList=stringList(canonical);if(canonicalList)return{source:"canonical",value:canonicalList};if(legacy)return{source:"legacy",value:stringList(legacy.value)??[flagSelector(legacy.flag)]}}function resolveAmountValue(canonical,legacy){if(canonical==="unbounded")return{source:"canonical",value:"unbounded"};const canonicalLimit=positiveInteger(canonical);if(canonicalLimit!==void 0)return{source:"canonical",value:canonicalLimit};if(!legacy)return;if(legacy.flag==="--no-truncate"||legacy.flag==="--unbounded")return{source:"legacy",value:"unbounded"};const legacyLimit=positiveInteger(legacy.value);return legacyLimit===void 0?void 0:{source:"legacy",value:legacyLimit}}function resolveCostValue(canonical,legacy){if(canonical==="unbounded")return{source:"canonical",value:"unbounded"};const canonicalBudget=positiveInteger(canonical);if(canonicalBudget!==void 0)return{source:"canonical",value:canonicalBudget};if(!legacy)return;const legacyBudget=positiveInteger(legacy.value);return legacyBudget===void 0?void 0:{source:"legacy",value:legacyBudget}}function resolveEncodingValue(canonical,legacy){if(canonical==="json"||canonical==="toon")return{source:"canonical",value:canonical};if(legacy)return legacy.flag==="--stream"||legacy.flag==="--follow"?{source:"legacy",value:"stream"}:legacy.value==="json"||legacy.value==="toon"?{source:"legacy",value:legacy.value}:void 0}function shouldIgnoreReadOutputLegacyAlias(provenance,dimension,flag){if(!provenance)return!1;const explicitLegacyAliases=new Set(provenance.explicit_legacy_aliases);if(provenance.cli_invocation_observed===!0||provenance.sdk_invocation_observed===!0)return!explicitLegacyAliases.has(flag);const forwardedIncludeAliases=new Set(provenance.canonical_include_modes.map(mode=>`--${mode.replaceAll("_","-")}`));return dimension==="include"&&forwardedIncludeAliases.has(flag)&&!explicitLegacyAliases.has(flag)}function hasCompleteReadOutputIntent(command,legacyByDimension,provenance,options){return command.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||isRequestedOption(readOption(options,"--no-truncate"))&&!shouldIgnoreReadOutputLegacyAlias(provenance,"amount","--no-truncate")||legacyByDimension.amount?.flag==="--no-truncate"||legacyByDimension.include?.flag==="--full"||provenance?.canonical_include_modes.includes("full")===!0}function canonicalReadOutputOptionsUsed(resolvedByDimension,provenance){return PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>resolvedByDimension[dimension]?.source==="canonical"||dimension==="include"&&(provenance?.canonical_include_modes.length??0)>0?[CANONICAL_OPTIONS[dimension]]:[])}function resolveReadOutputDimensions(command,options){const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand)return;const contract=SURFACE_CONTRACT_BY_COMMAND.get(normalizedCommand)??buildSurfaceContract(normalizedCommand),invocationProvenance=options[READ_OUTPUT_INVOCATION_PROVENANCE],legacyResolvers={include:candidate=>resolveIncludeValue(void 0,candidate),amount:candidate=>resolveAmountValue(void 0,candidate),cost:candidate=>resolveCostValue(void 0,candidate),encoding:candidate=>resolveEncodingValue(void 0,candidate)},legacyByDimension=Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,resolveLegacyDimension(contract.dimensions[dimension],options,candidate=>legacyResolvers[dimension](candidate)!==void 0,flag=>shouldIgnoreReadOutputLegacyAlias(invocationProvenance,dimension,flag))])),legacyAliasesUsed=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[resolved.flag]:[]}),migrationHints=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[contract.dimensions[dimension].legacy_aliases.find(entry=>entry.flag===resolved.flag).migration_hint]:[]}),encoding=resolveEncodingValue(options.outputFormat??options.output_format,legacyByDimension.encoding),include=resolveIncludeValue(options.outputInclude??options.output_include,legacyByDimension.include),amount=resolveAmountValue(options.outputLimit??options.output_limit,legacyByDimension.amount),explicitCost=resolveCostValue(options.outputBudget??options.output_budget,legacyByDimension.cost),completeResultIntent=hasCompleteReadOutputIntent(command,legacyByDimension,invocationProvenance,options),budget=resolvePmCommandOutputBudget(command,{generateFallback:!0}),resolvedOutputFormat=encoding?.value==="json"||options.resolvedOutputFormat==="json"?"json":"toon",cost=explicitCost??(completeResultIntent?{source:"intent",value:"unbounded"}:{source:"default",value:budget.default_max_estimated_tokens_by_format[resolvedOutputFormat]});return{command:normalizedCommand,include,amount,cost,encoding,canonical_options_used:canonicalReadOutputOptionsUsed({include,amount,cost,encoding},invocationProvenance),legacy_aliases_used:legacyAliasesUsed,migration_hints:migrationHints,precedence:READ_OUTPUT_PRECEDENCE}}function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}const ENVELOPE_KEYS=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]),GET_STABLE_DERIVED_ITEM_SELECTORS=["collection_counts","notes_count","tests_count"];function projectRecordFields(value,selectors){const selected=new Set(selectors.map(selector=>selector.split(".")[0]));return Object.fromEntries(Object.entries(value).filter(([key])=>selected.has(key)))}function getProjectionVocabulary(result){const item=isRecord(result.item)?result.item:{},itemFields=[...new Set([...Object.keys(item),...GET_STABLE_DERIVED_ITEM_SELECTORS.filter(key=>Object.hasOwn(item,key))])].sort((left,right)=>left.localeCompare(right)),sections=Object.keys(result).filter(key=>key!=="item"&&key!=="read_output"&&!ENVELOPE_KEYS.has(key)).sort((left,right)=>left.localeCompare(right));return{item,itemFields,sections,valid:[...itemFields,"item",...itemFields.map(field=>`item.${field}`),...sections]}}function applyGetIncludeProjection(result,selectors){const vocabulary=getProjectionVocabulary(result),unknown=selectors.filter(selector=>!vocabulary.valid.includes(selector));if(unknown.length>0)throw new PmCliError(`Unknown --output-include selector(s) for get: ${unknown.join(", ")}. Valid selectors: ${vocabulary.valid.join(", ")}.`,EXIT_CODE.USAGE);const fullItem=selectors.includes("item"),itemSelectors=selectors.flatMap(selector=>selector.startsWith("item.")?[selector.slice(5)]:vocabulary.itemFields.includes(selector)?[selector]:[]).filter((selector,index,values)=>values.indexOf(selector)===index);if(fullItem&&itemSelectors.length>0)throw new PmCliError("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",EXIT_CODE.USAGE);const selectedSections=new Set(selectors.filter(selector=>vocabulary.sections.includes(selector))),projected=Object.fromEntries(Object.entries(result).filter(([key])=>ENVELOPE_KEYS.has(key)||selectedSections.has(key)));fullItem?projected.item=vocabulary.item:itemSelectors.length>0&&(projected.item=projectRecordFields(vocabulary.item,itemSelectors));const omittedFieldGroups=[...fullItem?[]:itemSelectors.length>0?vocabulary.itemFields.filter(field=>!itemSelectors.includes(field)).map(field=>({name:`item.${field}`,restore_with:`--output-include item.${field}`})):[{name:"item",restore_with:"--output-include item"}],...vocabulary.sections.filter(section=>!selectedSections.has(section)).map(section=>({name:section,restore_with:`--output-include ${section}`}))],combinedOmittedFieldGroups=[...isRecord(projected.omission_receipt)&&Array.isArray(projected.omission_receipt.omitted_field_groups)?projected.omission_receipt.omitted_field_groups:[],...omittedFieldGroups];return projected.omission_receipt={has_omissions:combinedOmittedFieldGroups.length>0,omitted_field_group_count:combinedOmittedFieldGroups.length,omitted_field_groups:combinedOmittedFieldGroups},projected}function countPopulatedRows(result){let populated=0;return mapReadOutputRows({...result},entry=>(isRecord(entry)&&Object.keys(entry).length>0&&(populated+=1),entry)),populated}function rejectEmptyIncludeProjection(command,original,shaped,selectors){if(countPopulatedRows(original)===0||countPopulatedRows(shaped)>0)return;const modes=[...readOutputIncludeModeOptions(command).keys()],domain=modes.length>0?` Declared ${command} projection modes: ${modes.join(", ")}.`:` The ${command} surface declares no projection modes; name row fields instead.`;throw new PmCliError(`Unknown --output-include selector(s) for ${command}: ${selectors.join(", ")}. No selector matched any returned row field.${domain}`,EXIT_CODE.USAGE)}function applyIncludeProjection(command,result,selectors){if(command==="get")return applyGetIncludeProjection(result,selectors);const rows=readOutputRowPaths(result),qualifiedRowSelectors=selectors.flatMap(selector=>rows.flatMap(rowPath=>selector.startsWith(`${rowPath}.`)?[selector.slice(rowPath.length+1)]:[])),selectedRoot=selectors.some(selector=>Object.hasOwn(result,selector.split(".")[0])&&!rows.some(rowPath=>selector.startsWith(`${rowPath}.`)));if(rows.length>0&&(!selectedRoot||qualifiedRowSelectors.length>0)){const projected={...result},rowSelectors=qualifiedRowSelectors.length>0?qualifiedRowSelectors:selectors,shaped=mapReadOutputRows(projected,entry=>isRecord(entry)?projectRecordFields(entry,rowSelectors):entry);return rejectEmptyIncludeProjection(command,result,shaped,rowSelectors),shaped}return Object.fromEntries(Object.entries(result).filter(([key])=>selectors.some(selector=>selector.split(".")[0]===key)||ENVELOPE_KEYS.has(key)))}function applyAmountBound(result,amount){if(amount==="unbounded")return result;const{result:bounded,truncated}=boundReadOutputRows(result,amount);if(!truncated)return bounded;if(bounded.has_more=!0,bounded.truncated=!0,typeof bounded.count=="number"){const activeRowKey=isRecord(bounded.projection)?bounded.projection.row_key:void 0;bounded.count=typeof activeRowKey=="string"&&Array.isArray(bounded[activeRowKey])?bounded[activeRowKey].length:countReadOutputRows(bounded)}return bounded.applied_bound={kind:"output_limit",source:"explicit",value:amount},bounded}function requestedDimensions(resolved){return PM_READ_OUTPUT_DIMENSIONS.filter(dimension=>resolved[dimension]!==void 0&&resolved[dimension]?.source!=="default"||resolved.canonical_options_used.includes(CANONICAL_OPTIONS[dimension]))}function readOutputMeasurementFormat(options){const format=options.resolvedOutputFormat??options.outputFormat??options.output_format??options.format;return format==="json"||format==="toon"?format:void 0}function attachReadOutputSessionContracts(result,state,receipt,format){let withSession=attachReadOutputSessionReceipt(result,state,format);preserveReadOutputRowContract(result,withSession);for(let iteration=0;iteration<8;iteration+=1){const previousReadEstimate=receipt.estimated_tokens,previousSessionEstimate=withSession.read_session.spent_this_call_tokens;updateReadOutputReceiptEstimate(withSession,receipt,format);const previous=withSession;withSession=attachReadOutputSessionReceipt(withSession,state,format),preserveReadOutputRowContract(previous,withSession);const sessionEstimate=withSession.read_session.spent_this_call_tokens;if(receipt.estimated_tokens===previousReadEstimate&&sessionEstimate===previousSessionEstimate)return withSession}return withSession}function stabilizeReadOutputReceiptEstimates(result,options){if(!isRecord(result.read_output))return result;const format=readOutputMeasurementFormat(options),receipt=result.read_output,session=parseReadOutputSession(options.outputSession??options.output_session);return session===void 0?(updateReadOutputReceiptEstimate(result,receipt,format),result):attachReadOutputSessionContracts(result,session,receipt,format)}function attachValidateDiagnosticRowContract(command,result){if(command!=="validate")return result;const projection=isRecord(result.projection)?result.projection:void 0;if(!(Array.isArray(projection?.declared_field_groups)?projection.declared_field_groups:[]).some(group=>isRecord(group)&&group.name==="diagnostic_rows"))return result;const diagnosticCollectionPaths=[...new Set(readOutputBudgetCollections(result).map(({path})=>path).filter(path=>/^checks\.\d+\.details\./u.test(path)))],diagnosticRowKeys=diagnosticCollectionPaths.filter(path=>!diagnosticCollectionPaths.some(candidate=>candidate!==path&&path.startsWith(`${candidate}.`)));if(diagnosticRowKeys.length===0)return result;const existingContract=isRecord(result.row_contract)?result.row_contract:{},existingRowKeys=Array.isArray(existingContract.row_keys)?existingContract.row_keys.filter(entry=>typeof entry=="string"):[],existingContinuationRowKeys=Array.isArray(existingContract.continuation_row_keys)?existingContract.continuation_row_keys.filter(entry=>typeof entry=="string"):[],rowKeys=existingRowKeys.length>0?existingRowKeys:diagnosticRowKeys,continuationRowKeys=[...new Set(diagnosticRowKeys)];return JSON.stringify(rowKeys)===JSON.stringify(existingRowKeys)&&JSON.stringify(continuationRowKeys)===JSON.stringify(existingContinuationRowKeys)?result:{...result,row_contract:{...existingContract,row_keys:rowKeys,continuation_row_keys:continuationRowKeys,jq_selector:typeof existingContract.jq_selector=="string"?existingContract.jq_selector:".checks[].details"}}}function projectReadOutputRows(result,resolved,session,cursor,options){let projected={...result};if(resolved.include?.source==="canonical"&&(projected=applyIncludeProjection(resolved.command,projected,resolved.include.value)),resolved.command==="assurance"&&(projected=prioritizeAssuranceAssertions(projected)),refreshReadOutputDeliveredCounts(projected,result),projected=applyReadOutputContinuation(projected,resolved.command,cursor),resolved.command==="history"&&cursor){const historyRowKeys=["compact_history","provenance_history","history","diff"];if(projected=Object.fromEntries(Object.entries(projected).filter(([key])=>!historyRowKeys.includes(key)||key===cursor.path)),isRecord(projected.projection)&&(projected.projection={...projected.projection,row_key:cursor.path}),isRecord(projected.row_contract)){const rowContract=projected.row_contract;projected.row_contract={...rowContract,row_keys:[cursor.path],...Array.isArray(rowContract.continuation_row_keys)?{continuation_row_keys:[cursor.path]}:{}}}projected.count=Object.keys(projected[cursor.path]).length}const continuationSource=result.count_only===!0?{...projected,count_only:!0,count:result.count}:projected,continuationState=captureReadOutputContinuationState(projected,result,resolved.command,cursor,options);return resolved.amount?.source==="canonical"&&(projected=applyAmountBound(projected,resolved.amount.value),continuationState.cursorContinuesExistingPage&&rebaseCompactedProducerCursor(projected,continuationState.originalItems,continuationState.cursorSource,!0,continuationState.originalItemOffset)),refreshReadOutputDeliveredCounts(projected,continuationSource),{projected:session===void 0?projected:applyReadOutputSessionReferences(projected,session),continuationState}}function resolveBindingReadOutputBudget(resolved,session){return[...resolved.cost!==void 0&&resolved.cost.value!=="unbounded"&&(resolved.cost.source==="canonical"||resolved.cost.source==="default"||resolved.command==="context"&&resolved.cost.source==="legacy")?[{source:resolved.cost.source,tokens:resolved.cost.value}]:[],...session===void 0?[]:[{source:"session",tokens:readOutputSessionRemainingTokens(session)}]].sort((left,right)=>left.tokens-right.tokens)[0]}function canonicalReadOutputReceiptFields(resolved){const canonicalOptions=resolved.canonical_options_used;return canonicalOptions&&canonicalOptions.length>0?{canonical_options_used:canonicalOptions}:{}}function hasContextIntentBudgetReceipt(result,tokens){return isRecord(result.context_intent)&&result.context_intent.command==="context"&&result.context_intent.token_budget===tokens&&result.context_intent.within_budget===!0}function requiresNextSelectionBudgetAudit(resolved,options,result){return resolved.command!=="next"||(options.tokenBudget??options.token_budget)===void 0?!1:!(isRecord(result.context_intent)&&result.context_intent.command==="next"&&result.context_intent.within_budget===!0)}function readOutputBudgetReceiptFields(budget,result={}){return budget?.source==="default"||budget?.source==="legacy"&&!hasContextIntentBudgetReceipt(result,budget.tokens)?{budget_source:budget.source,budget_tokens:budget.tokens}:{}}function omitReadOutputForBudget(resolved,requested,session,bindingBudget,omittedResultEstimatedTokens,format){const minimalReceipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...readOutputBudgetReceiptFields(bindingBudget),precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...session===void 0?{omitted_result_estimated_tokens:omittedResultEstimatedTokens}:{}},omitted={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:minimalReceipt},boundedOmission=session===void 0?omitted:attachReadOutputSessionContracts(omitted,session,minimalReceipt,format);if(session===void 0&&updateReadOutputReceiptEstimate(boundedOmission,minimalReceipt,format),session!==void 0&&minimalReceipt.estimated_tokens>bindingBudget.tokens)throw new PmCliError("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",EXIT_CODE.USAGE);return boundedOmission}function requiresReadOutputAudit(resolved,options,result){return resolved.command==="context"&&resolved.cost?.source==="legacy"&&!hasContextIntentBudgetReceipt(result,resolved.cost.value)||requiresNextSelectionBudgetAudit(resolved,options,result)||options.outputRowContract===!0||options.output_row_contract===!0||resolved.canonical_options_used.includes("--output-include")||resolved.command==="list"&&resolved.canonical_options_used.length>0&&resolved.include?.value.includes("full")===!0}function canReturnReadOutputUnchanged(resolved,session,result,format,options){if(session!==void 0||requiresReadOutputAudit(resolved,options,result))return!1;if(resolved.amount?.source==="canonical"&&resolved.amount.value!=="unbounded"){const limit=resolved.amount.value;if(readOutputRowCollections(result).some(({value})=>(Array.isArray(value)?value.length:Object.keys(value).length)>limit))return!1}return resolved.cost===void 0||resolved.cost.value==="unbounded"||resolved.cost.source==="legacy"&&resolved.command!=="context"||estimateReadOutputTokens(options.outputRowContract===!1?Object.fromEntries(Object.entries(result).filter(([key])=>key!=="row_contract")):result,format)<=resolved.cost.value}function attachReadOutputTruncationDisclosure(projected,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,collectionsBeforeBudget){if(!receipt.rows_compacted)return;const overridden=resolved.amount?.value==="unbounded"?["amount"]:[],afterByPath=new Map(readOutputContinuationRowCollections(projected).map(collection=>[collection.path,Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length])),continuations=[...collectionsBeforeBudget.entries()].flatMap(([path,before])=>{const retainedRows=afterByPath.get(path);if(retainedRows>=before.rows)return[];const offset=before.baseOffset+retainedRows;return[{path,cursor:encodeReadOutputContinuationCursor({command:resolved.command,path,offset,total_rows:before.totalRows,fingerprint:before.fingerprint}),retained_rows:retainedRows,remaining_rows:before.totalRows-offset,total_rows:before.totalRows}]}),primary=continuations[0],continuationHint=primary?"; page --output-cursor":"",budgetHint=bindingBudget.source==="session"?`Truncated by the remaining ${bindingBudget.tokens}-token session budget; start a new output session with a larger token_budget${continuationHint}.`:`${bindingBudget.tokens}-token: raise --output-budget${continuationHint}`;receipt.migration_hints=[budgetHint,...resolved.migration_hints];const recoveryBudget=resolveReadOutputRecoveryBudget({effective_budget_tokens:bindingBudget.tokens,measured_result_tokens:measuredResultTokens});primary&&!continuationCursorRebased&&(typeof projected.next_cursor!="string"||projected.continuation_kind==="output_cursor")&&(projected.next_cursor=primary.cursor),projected.continuation_kind=continuationCursorRebased?"producer_cursor":primary?"output_cursor":"none",projected.output_budget_truncation={reason:"output_budget_reached",budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens,overridden_dimensions:overridden,compacted_row_paths:receipt.compacted_row_paths,continuation_cursor_rebased:continuationCursorRebased,continuation_available:continuations.length>0,recovery_budget_multiplier:primary?1:recoveryBudget.recovery_budget_multiplier,continuations,restore_with:primary?"recovery":`Retry with --output-budget ${recoveryBudget.output_budget} because no declared row collection can be continued.`,recovery:primary?{cursor:primary.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${recoveryBudget.output_budget}`,sdk:{outputBudget:recoveryBudget.output_budget},mcp:{outputBudget:recoveryBudget.output_budget}}}}function rebaseCompactedProducerCursor(projected,originalItems,cursorSource,cursorContinuesExistingPage,originalItemOffset){if(typeof cursorSource!="string"||!Array.isArray(projected.items))return!1;const retainedCount=projected.items.length,originalItemCount=originalItems.length;if(retainedCount===0||retainedCount>=originalItemCount)return!1;let cursor;try{cursor=decodeQueryCursorEnvelope(cursorSource)}catch{return!1}const sourceIndex=cursor.after_index;if(sourceIndex===void 0)return!1;const last=originalItems[retainedCount-1];if(Object.prototype.toString.call(last)!=="[object Object]")return!1;const lastId=Reflect.get(last,"id");if(typeof lastId!="string"||lastId.length===0)return!1;const afterIndex=cursorContinuesExistingPage?sourceIndex-(originalItemCount-retainedCount):sourceIndex+originalItemOffset+retainedCount;return afterIndex<0?!1:(projected.next_cursor=encodeQueryCursor(cursor.fingerprint,lastId,afterIndex,cursor.snapshot),!0)}function captureReadOutputContinuationState(projected,source,command,cursor,options){const collectionsBeforeBudget=new Map(readOutputContinuationRowCollections(projected).map(collection=>{const rows=Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length,continued=cursor?.path===collection.path;return[collection.path,{rows,totalRows:continued?cursor.total_rows:rows,baseOffset:continued?cursor.offset:0,fingerprint:continued?cursor.fingerprint:readOutputCollectionFingerprint(collection.path,collection.value,command)}]})),cursorContinuesExistingPage=typeof projected.next_cursor=="string",originalItemOffset=cursor?.path==="items"?cursor.offset:0;return{collectionsBeforeBudget,originalItems:Array.isArray(source.items)?originalItemOffset>0?source.items.slice(originalItemOffset):source.items:[],originalItemOffset,cursorContinuesExistingPage,cursorSource:cursorContinuesExistingPage?projected.next_cursor:options.after}}function compactReadOutputProjection(projected,source,countOnly,resolved,receipt,bindingBudget,session,continuationState,measuredResultTokens,format){const deliveredSource={...source,count_only:countOnly},assuranceMinimumRows=resolved.command==="assurance"&&Array.isArray(projected.assertions)?projected.assertions.filter(row=>isRecord(row)&&row.verdict!=="pass").length:0,minimumRowsByPath=new Map;if(assuranceMinimumRows>0&&minimumRowsByPath.set("assertions",assuranceMinimumRows),resolved.command==="history"&&Array.isArray(projected.diff))for(const collection of readOutputBudgetCollections(projected))collection.path.startsWith("diff.")&&minimumRowsByPath.set(collection.path,Object.keys(collection.value).length);return compactReadOutputToBudget(projected,receipt,bindingBudget.tokens,minimumRowsByPath,format,compacted=>{refreshReadOutputDeliveredCounts(compacted,deliveredSource);const continuationCursorRebased=rebaseCompactedProducerCursor(compacted,continuationState.originalItems,continuationState.cursorSource,continuationState.cursorContinuesExistingPage,continuationState.originalItemOffset);if(attachReadOutputTruncationDisclosure(compacted,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,continuationState.collectionsBeforeBudget),resolved.command==="history"&&isRecord(compacted.projection)){compacted.has_more=typeof compacted.next_cursor=="string"||compacted.applied_bound?.kind==="output_limit";const rowKey=compacted.projection.row_key;typeof rowKey=="string"&&Array.isArray(compacted[rowKey])&&(compacted.count=compacted[rowKey].length)}session!==void 0&&Object.assign(compacted,attachReadOutputSessionContracts(compacted,session,receipt,format))},resolved.command==="history"&&Array.isArray(projected.diff))}function applyReadOutputDimensions(command,options,result){const resolved=resolveReadOutputDimensions(command,options);if(!resolved)return result;const format=readOutputMeasurementFormat(options),session=parseReadOutputSession(options.outputSession??options.output_session),rawCursor=options.outputCursor??options.output_cursor,cursor=typeof rawCursor=="string"?decodeReadOutputContinuationCursor(rawCursor):void 0,requested=requestedDimensions(resolved),continuationReadyResult=attachValidateDiagnosticRowContract(resolved.command,result);if(cursor===void 0&&canReturnReadOutputUnchanged(resolved,session,continuationReadyResult,format,options))return continuationReadyResult;const bindingBudget=resolveBindingReadOutputBudget(resolved,session),projection=projectReadOutputRows(continuationReadyResult,resolved,session,cursor,options);let projected=projection.projected;preserveReadOutputRowContract(projected,projected,options.outputRowContract===!1);const receipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...readOutputBudgetReceiptFields(bindingBudget,projected),precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:resolved.legacy_aliases_used,migration_hints:resolved.migration_hints,estimated_tokens:0,within_budget:!0,strings_compacted:!1,rows_compacted:!1,result_omitted:!1};if(projected.read_output=receipt,projected=session===void 0?projected:attachReadOutputSessionContracts(projected,session,receipt,format),updateReadOutputReceiptEstimate(projected,receipt,format),bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){const brief=projectReadOutputItemToBrief(resolved.command,options,projected);brief!==void 0&&(receipt.applied_depth="brief",receipt.degradation_reason="output_budget_reached",preserveReadOutputRowContract(projected,brief),projected=stabilizeReadOutputReceiptEstimates(brief,options)),receipt.estimated_tokens>bindingBudget.tokens&&(projected=compactReadOutputProjection(projected,projected,continuationReadyResult.count_only===!0,resolved,receipt,bindingBudget,session,projection.continuationState,receipt.estimated_tokens,format))}return bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens?omitReadOutputForBudget(resolved,requested,session,bindingBudget,receipt.estimated_tokens,format):projected}function isReadOutputBudgetExceeded(result){return isRecord(result)&&isRecord(result.output_budget_exceeded)&&result.output_budget_exceeded.omitted_result===!0&&result.output_budget_exceeded.reason==="requested_budget_infeasible"}function resolveReadOutputEncoding(command,options){const canonical=options.outputFormat??options.output_format;if(canonical==="json"||canonical==="toon")return canonical;const encoding=resolveReadOutputDimensions(command,options)?.encoding;return encoding?.value==="json"||encoding?.value==="toon"?encoding.value:void 0}export{PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACES2 as PM_READ_OUTPUT_SURFACES,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,applyReadOutputIncludeModes,decodeReadOutputContinuationCursor2 as decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor2 as encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,normalizeReadOutputIncludeModeOptions,readOutputCollectionFingerprint2 as readOutputCollectionFingerprint,readOutputIncludeModeOptions,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputRecoveryBudget2 as resolveReadOutputRecoveryBudget,resolveReadOutputSurface,stabilizeReadOutputReceiptEstimates,validateReadOutputOptions};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3da33507-a551-5aee-9bc5-68b0de2384d5")}catch{}})();import{READ_OUTPUT_DIMENSION_FLAGS,READ_OUTPUT_COMPOSITION_FLAGS,PM_READ_OUTPUT_SURFACES}from"./read-output/options.js";import{resolvePmHistoryOperation}from"./cli-contracts/command-aliases.js";import{resolveExtensionOutputCommand}from"./read-output/extension.js";import{BEHAVIOR_PRESERVING_MIGRATION_HINTS,LEGACY_FLAGS_BY_COMMAND,VALUE_BEARING_INCLUDE_ALIASES,flagSelector,optionKey,readOutputIncludeModeOptionsForSurface,resolveNativeReadOutputSurface}from"./read-output/surfaces.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{compactReadOutputToBudget,estimateReadOutputTokens,readOutputMeasurementFormat,projectReadOutputItemToBrief,preserveReadOutputRowContract,resolveReadOutputRecoveryBudget,updateReadOutputReceiptEstimate}from"./read-output-budget.js";import{resolveReadOutputRecoveryBudget as resolveReadOutputRecoveryBudget2}from"./read-output-budget.js";import{resolvePmCommandOutputBudget}from"./cli-contracts/agent-output-contracts.js";import{boundReadOutputRows,countReadOutputRows,mapReadOutputRows,readOutputBudgetCollections,readOutputContinuationRowCollections,readOutputRowPaths,readOutputRowCollections,refreshReadOutputDeliveredCounts}from"./read-output-rows.js";import{applyReadOutputContinuation,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,prioritizeAssuranceAssertions,readOutputCollectionFingerprint,refreshReadOutputDeliveredRowCounters}from"./read-output/continuation.js";import{PM_READ_OUTPUT_TAIL_RETENTION_POLICIES,readOutputRetainsTail}from"./read-output/tail-retention.js";import{decodeReadOutputContinuationCursor as decodeReadOutputContinuationCursor2,encodeReadOutputContinuationCursor as encodeReadOutputContinuationCursor2,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,readOutputCollectionFingerprint as readOutputCollectionFingerprint2}from"./read-output/continuation.js";import{PM_READ_OUTPUT_TAIL_RETENTION_POLICIES as PM_READ_OUTPUT_TAIL_RETENTION_POLICIES2,readOutputRetainsTail as readOutputRetainsTail2}from"./read-output/tail-retention.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens}from"./read-output-session.js";import{decodeQueryCursorEnvelope,encodeQueryCursor}from"./pagination.js";import{READ_OUTPUT_INVOCATION_PROVENANCE}from"./read-output/provenance.js";const PM_READ_OUTPUT_DIMENSIONS=["include","amount","cost","encoding"];import{PM_READ_OUTPUT_SURFACES as PM_READ_OUTPUT_SURFACES2}from"./read-output/options.js";const READ_OUTPUT_PRECEDENCE=["canonical","legacy","intent","default"],CANONICAL_OPTIONS=READ_OUTPUT_DIMENSION_FLAGS,PM_READ_OUTPUT_OPTION_FLAGS=Object.freeze(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>CANONICAL_OPTIONS[dimension])),PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS=READ_OUTPUT_COMPOSITION_FLAGS;function migrationHint(flag,dimension){const behaviorHint=BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag];if(behaviorHint!==void 0)return behaviorHint;const suffix=dimension==="include"?VALUE_BEARING_INCLUDE_ALIASES.has(flag)?"<csv>":flagSelector(flag):dimension==="amount"?"<n>":dimension==="cost"?"<tokens>":"<toon|json>";return`${flag} is a compatibility alias; prefer ${CANONICAL_OPTIONS[dimension]} ${suffix}.`}function buildSurfaceContract(command){const legacy=LEGACY_FLAGS_BY_COMMAND[command]??{},dimensions=Object.freeze(Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,Object.freeze({dimension,canonical_option:CANONICAL_OPTIONS[dimension],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((legacy[dimension]??[]).map(flag=>Object.freeze({flag,semantics:BEHAVIOR_PRESERVING_MIGRATION_HINTS[flag]===void 0?"replacement":"behavior_preserving",migration_hint:migrationHint(flag,dimension),visibility:"hidden_alias"})))})])));return Object.freeze({command,dimensions,precedence:READ_OUTPUT_PRECEDENCE,budget_retention_policy:command==="assurance"?"verdict_priority":Object.hasOwn(PM_READ_OUTPUT_TAIL_RETENTION_POLICIES,command)?"ordered_suffix":"ordered_prefix",projection_modes:Object.freeze([...readOutputIncludeModeOptionsForSurface(command).keys()])})}const PM_READ_OUTPUT_SURFACE_CONTRACTS=Object.freeze(PM_READ_OUTPUT_SURFACES.map(buildSurfaceContract)),SURFACE_CONTRACT_BY_COMMAND=new Map(PM_READ_OUTPUT_SURFACE_CONTRACTS.map(contract=>[contract.command,contract]));function resolveReadOutputSurface(command,options={}){const normalizedCommand=resolvePmHistoryOperation(command.trim().toLowerCase()),extension=resolveExtensionOutputCommand(normalizedCommand);return extension!==void 0?extension.read_output===void 0?void 0:`extension:${extension.command}`:resolveNativeReadOutputSurface(normalizedCommand,options)}const CANONICAL_OPTION_KEYS=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],HYBRID_READ_MUTATION_KEYS={comments:["add","body","comment","text","stdin","file","edit","delete"],notes:["add","note","text","addJson","stdin","file","edit","delete"],learnings:["add","learning","text","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function hasCanonicalReadOutputOptions(options){return CANONICAL_OPTION_KEYS.some(key=>key!=="outputFormat"&&key!=="output_format"&&options[key]!==void 0)}const READ_OUTPUT_VALUE_VALIDATORS=[{keys:["outputInclude","output_include"],valid:value=>stringList(value)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:value=>value==="unbounded"||positiveInteger(value)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:value=>(parseReadOutputSession(value),!0),message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:value=>typeof value=="string"&&value.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}];function validateReadOutputOptions(command,options){const encoding=options.outputFormat??options.output_format;if(encoding!==void 0&&encoding!=="json"&&encoding!=="toon")throw new PmCliError("--output-format must be toon or json.",EXIT_CODE.USAGE);if(!hasCanonicalReadOutputOptions(options))return;const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand)throw new PmCliError(`Universal output controls apply only to read commands; ${command||"this command"} is not a read surface.`,EXIT_CODE.USAGE);if((HYBRID_READ_MUTATION_KEYS[normalizedCommand]??[]).some(key=>options[key]!==void 0&&options[key]!==!1))throw new PmCliError(`Universal output controls cannot be combined with a ${normalizedCommand} mutation.`,EXIT_CODE.USAGE);for(const validator of READ_OUTPUT_VALUE_VALIDATORS){const value=validator.keys.map(key=>options[key]).find(entry=>entry!==void 0);if(value!==void 0&&!validator.valid(value))throw new PmCliError(validator.message,EXIT_CODE.USAGE)}}function readOutputIncludeModeOptions(command){const surface=resolveReadOutputSurface(command);return surface?readOutputIncludeModeOptionsForSurface(surface):new Map}function applyReadOutputIncludeModes(command,includeValue,commandOptions){const requested=stringList(includeValue)??[],modeOptions=readOutputIncludeModeOptions(command),selectors=[],modes=[],optionsWithProvenance=commandOptions,existingProvenance=optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE],canonicalModes=new Set(existingProvenance?.canonical_include_modes??[]),explicitLegacyAliases=new Set(existingProvenance?.explicit_legacy_aliases??[]);for(const token of requested){const option=modeOptions.get(token);if(option===void 0){selectors.push(token);continue}const legacyFlag=`--${token.replaceAll("_","-")}`;isRequestedOption(readOption(commandOptions,legacyFlag))&&explicitLegacyAliases.add(legacyFlag),commandOptions[option]=!0,modes.push(token),canonicalModes.add(token)}const forwardedGetFieldSelectors=resolveReadOutputSurface(command)==="get"?selectors.filter(selector=>selector!=="item"):[],forwardedGetFields=forwardedGetFieldSelectors.length>0;return forwardedGetFields&&(commandOptions.fields=[...new Set([...stringList(commandOptions.fields)??[],...forwardedGetFieldSelectors])].join(","),canonicalModes.add("fields")),(modes.length>0||forwardedGetFields)&&(optionsWithProvenance[READ_OUTPUT_INVOCATION_PROVENANCE]={canonical_include_modes:[...canonicalModes],explicit_legacy_aliases:[...explicitLegacyAliases],...existingProvenance?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors,modes}}function normalizeReadOutputIncludeModeOptions(command,options){const include=options.outputInclude??options.output_include;if(include===void 0)return;const{selectors,modes}=applyReadOutputIncludeModes(command,include,options);if(modes.length===0)return;const residual=selectors.length>0?selectors.join(","):void 0;options.outputInclude=residual,Object.hasOwn(options,"output_include")&&(options.output_include=residual)}function readOption(options,flag){const key=optionKey(flag);if(Object.hasOwn(options,key))return options[key];const snakeKey=flag.slice(2).replaceAll("-","_");if(Object.hasOwn(options,snakeKey))return options[snakeKey];if(flag==="--no-truncate"&&options.truncate===!1)return!0}function isRequestedOption(value){return value!==void 0&&value!==!1&&value!==null}function stringList(value){const normalized=(Array.isArray(value)?value:[value]).flatMap(entry=>typeof entry=="string"?entry.split(","):[]).map(entry=>entry.trim()).filter(Boolean);return normalized.length>0?[...new Set(normalized)]:void 0}function positiveInteger(value){const parsed=typeof value=="number"?value:typeof value=="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function resolveLegacyDimension(contract,options,usable,ignore){for(const alias of contract.legacy_aliases){if(ignore(alias.flag))continue;const value=readOption(options,alias.flag),candidate={value,flag:alias.flag};if(isRequestedOption(value)&&usable(candidate))return candidate}}function resolveIncludeValue(canonical,legacy){const canonicalList=stringList(canonical);if(canonicalList)return{source:"canonical",value:canonicalList};if(legacy)return{source:"legacy",value:stringList(legacy.value)??[flagSelector(legacy.flag)]}}function resolveAmountValue(canonical,legacy){if(canonical==="unbounded")return{source:"canonical",value:"unbounded"};const canonicalLimit=positiveInteger(canonical);if(canonicalLimit!==void 0)return{source:"canonical",value:canonicalLimit};if(!legacy)return;if(legacy.flag==="--no-truncate"||legacy.flag==="--unbounded")return{source:"legacy",value:"unbounded"};const legacyLimit=positiveInteger(legacy.value);return legacyLimit===void 0?void 0:{source:"legacy",value:legacyLimit}}function resolveCostValue(canonical,legacy){if(canonical==="unbounded")return{source:"canonical",value:"unbounded"};const canonicalBudget=positiveInteger(canonical);if(canonicalBudget!==void 0)return{source:"canonical",value:canonicalBudget};if(!legacy)return;const legacyBudget=positiveInteger(legacy.value);return legacyBudget===void 0?void 0:{source:"legacy",value:legacyBudget}}function resolveEncodingValue(canonical,legacy){if(canonical==="json"||canonical==="toon")return{source:"canonical",value:canonical};if(legacy)return legacy.flag==="--stream"||legacy.flag==="--follow"?{source:"legacy",value:"stream"}:legacy.value==="json"||legacy.value==="toon"?{source:"legacy",value:legacy.value}:void 0}function shouldIgnoreReadOutputLegacyAlias(provenance,dimension,flag){if(!provenance)return!1;const explicitLegacyAliases=new Set(provenance.explicit_legacy_aliases);if(provenance.cli_invocation_observed===!0||provenance.sdk_invocation_observed===!0)return!explicitLegacyAliases.has(flag);const forwardedIncludeAliases=new Set(provenance.canonical_include_modes.map(mode=>`--${mode.replaceAll("_","-")}`));return dimension==="include"&&forwardedIncludeAliases.has(flag)&&!explicitLegacyAliases.has(flag)}function hasCompleteReadOutputIntent(command,legacyByDimension,provenance,options){return command.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||isRequestedOption(readOption(options,"--no-truncate"))&&!shouldIgnoreReadOutputLegacyAlias(provenance,"amount","--no-truncate")||legacyByDimension.amount?.flag==="--no-truncate"||legacyByDimension.include?.flag==="--full"||provenance?.canonical_include_modes.includes("full")===!0}function canonicalReadOutputOptionsUsed(resolvedByDimension,provenance){return PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>resolvedByDimension[dimension]?.source==="canonical"||dimension==="include"&&(provenance?.canonical_include_modes.length??0)>0?[CANONICAL_OPTIONS[dimension]]:[])}function resolveReadOutputDimensions(command,options){const normalizedCommand=resolveReadOutputSurface(command,options);if(!normalizedCommand)return;const contract=SURFACE_CONTRACT_BY_COMMAND.get(normalizedCommand)??buildSurfaceContract(normalizedCommand),invocationProvenance=options[READ_OUTPUT_INVOCATION_PROVENANCE],legacyResolvers={include:candidate=>resolveIncludeValue(void 0,candidate),amount:candidate=>resolveAmountValue(void 0,candidate),cost:candidate=>resolveCostValue(void 0,candidate),encoding:candidate=>resolveEncodingValue(void 0,candidate)},legacyByDimension=Object.fromEntries(PM_READ_OUTPUT_DIMENSIONS.map(dimension=>[dimension,resolveLegacyDimension(contract.dimensions[dimension],options,candidate=>legacyResolvers[dimension](candidate)!==void 0,flag=>shouldIgnoreReadOutputLegacyAlias(invocationProvenance,dimension,flag))])),legacyAliasesUsed=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[resolved.flag]:[]}),migrationHints=PM_READ_OUTPUT_DIMENSIONS.flatMap(dimension=>{const resolved=legacyByDimension[dimension];return resolved?[contract.dimensions[dimension].legacy_aliases.find(entry=>entry.flag===resolved.flag).migration_hint]:[]}),encoding=resolveEncodingValue(options.outputFormat??options.output_format,legacyByDimension.encoding),include=resolveIncludeValue(options.outputInclude??options.output_include,legacyByDimension.include),amount=resolveAmountValue(options.outputLimit??options.output_limit,legacyByDimension.amount),explicitCost=resolveCostValue(options.outputBudget??options.output_budget,legacyByDimension.cost),completeResultIntent=hasCompleteReadOutputIntent(command,legacyByDimension,invocationProvenance,options),budget=resolvePmCommandOutputBudget(command,{generateFallback:!0}),resolvedOutputFormat=encoding?.value==="json"||options.resolvedOutputFormat==="json"?"json":"toon",cost=explicitCost??(completeResultIntent?{source:"intent",value:"unbounded"}:{source:"default",value:budget.default_max_estimated_tokens_by_format[resolvedOutputFormat]});return{command:normalizedCommand,include,amount,cost,encoding,canonical_options_used:canonicalReadOutputOptionsUsed({include,amount,cost,encoding},invocationProvenance),legacy_aliases_used:legacyAliasesUsed,migration_hints:migrationHints,precedence:READ_OUTPUT_PRECEDENCE}}function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}const ENVELOPE_KEYS=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]),GET_STABLE_DERIVED_ITEM_SELECTORS=["collection_counts","notes_count","tests_count"];function projectRecordFields(value,selectors){const selected=new Set(selectors.map(selector=>selector.split(".")[0]));return Object.fromEntries(Object.entries(value).filter(([key])=>selected.has(key)))}function getProjectionVocabulary(result){const item=isRecord(result.item)?result.item:{},itemFields=[...new Set([...Object.keys(item),...GET_STABLE_DERIVED_ITEM_SELECTORS.filter(key=>Object.hasOwn(item,key))])].sort((left,right)=>left.localeCompare(right)),sections=Object.keys(result).filter(key=>key!=="item"&&key!=="read_output"&&!ENVELOPE_KEYS.has(key)).sort((left,right)=>left.localeCompare(right));return{item,itemFields,sections,valid:[...itemFields,"item",...itemFields.map(field=>`item.${field}`),...sections]}}function applyGetIncludeProjection(result,selectors){const vocabulary=getProjectionVocabulary(result),unknown=selectors.filter(selector=>!vocabulary.valid.includes(selector));if(unknown.length>0)throw new PmCliError(`Unknown --output-include selector(s) for get: ${unknown.join(", ")}. Valid selectors: ${vocabulary.valid.join(", ")}.`,EXIT_CODE.USAGE);const fullItem=selectors.includes("item"),itemSelectors=selectors.flatMap(selector=>selector.startsWith("item.")?[selector.slice(5)]:vocabulary.itemFields.includes(selector)?[selector]:[]).filter((selector,index,values)=>values.indexOf(selector)===index);if(fullItem&&itemSelectors.length>0)throw new PmCliError("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",EXIT_CODE.USAGE);const selectedSections=new Set(selectors.filter(selector=>vocabulary.sections.includes(selector))),projected=Object.fromEntries(Object.entries(result).filter(([key])=>ENVELOPE_KEYS.has(key)||selectedSections.has(key)));fullItem?projected.item=vocabulary.item:itemSelectors.length>0&&(projected.item=projectRecordFields(vocabulary.item,itemSelectors));const omittedFieldGroups=[...fullItem?[]:itemSelectors.length>0?vocabulary.itemFields.filter(field=>!itemSelectors.includes(field)).map(field=>({name:`item.${field}`,restore_with:`--output-include item.${field}`})):[{name:"item",restore_with:"--output-include item"}],...vocabulary.sections.filter(section=>!selectedSections.has(section)).map(section=>({name:section,restore_with:`--output-include ${section}`}))],combinedOmittedFieldGroups=[...isRecord(projected.omission_receipt)&&Array.isArray(projected.omission_receipt.omitted_field_groups)?projected.omission_receipt.omitted_field_groups:[],...omittedFieldGroups];return projected.omission_receipt={has_omissions:combinedOmittedFieldGroups.length>0,omitted_field_group_count:combinedOmittedFieldGroups.length,omitted_field_groups:combinedOmittedFieldGroups},projected}function countPopulatedRows(result){let populated=0;return mapReadOutputRows({...result},entry=>(isRecord(entry)&&Object.keys(entry).length>0&&(populated+=1),entry)),populated}function rejectEmptyIncludeProjection(command,original,shaped,selectors){if(countPopulatedRows(original)===0||countPopulatedRows(shaped)>0)return;const modes=[...readOutputIncludeModeOptions(command).keys()],domain=modes.length>0?` Declared ${command} projection modes: ${modes.join(", ")}.`:` The ${command} surface declares no projection modes; name row fields instead.`;throw new PmCliError(`Unknown --output-include selector(s) for ${command}: ${selectors.join(", ")}. No selector matched any returned row field.${domain}`,EXIT_CODE.USAGE)}function applyIncludeProjection(command,result,selectors){if(command==="get")return applyGetIncludeProjection(result,selectors);const rows=readOutputRowPaths(result),qualifiedRowSelectors=selectors.flatMap(selector=>rows.flatMap(rowPath=>selector.startsWith(`${rowPath}.`)?[selector.slice(rowPath.length+1)]:[])),selectedRoot=selectors.some(selector=>Object.hasOwn(result,selector.split(".")[0])&&!rows.some(rowPath=>selector.startsWith(`${rowPath}.`)));if(rows.length>0&&(!selectedRoot||qualifiedRowSelectors.length>0)){const projected={...result},rowSelectors=qualifiedRowSelectors.length>0?qualifiedRowSelectors:selectors,shaped=mapReadOutputRows(projected,entry=>isRecord(entry)?projectRecordFields(entry,rowSelectors):entry);return rejectEmptyIncludeProjection(command,result,shaped,rowSelectors),shaped}return Object.fromEntries(Object.entries(result).filter(([key])=>selectors.some(selector=>selector.split(".")[0]===key)||ENVELOPE_KEYS.has(key)))}function applyAmountBound(result,amount,command,collectionsBeforeBound){if(amount==="unbounded")return result;const{result:bounded,truncated}=boundReadOutputRows(result,amount,path=>readOutputRetainsTail(command,path));if(!truncated)return bounded;if(bounded.has_more=!0,bounded.truncated=!0,attachTailRetentionTotal(bounded,command,[...collectionsBeforeBound.entries()].flatMap(([path,before])=>before.rows>amount?[{path,total_rows:before.totalRows}]:[])),typeof bounded.count=="number"){const activeRowKey=isRecord(bounded.projection)?bounded.projection.row_key:void 0;bounded.count=typeof activeRowKey=="string"&&Array.isArray(bounded[activeRowKey])?bounded[activeRowKey].length:countReadOutputRows(bounded)}return typeof bounded.returned_count=="number"&&(bounded.returned_count=countReadOutputRows(bounded)),bounded.applied_bound={kind:"output_limit",source:"explicit",value:amount},bounded}function requestedDimensions(resolved){return PM_READ_OUTPUT_DIMENSIONS.filter(dimension=>resolved[dimension]!==void 0&&resolved[dimension]?.source!=="default"||resolved.canonical_options_used.includes(CANONICAL_OPTIONS[dimension]))}function attachReadOutputSessionContracts(result,state,receipt,format){let withSession=attachReadOutputSessionReceipt(result,state,format);preserveReadOutputRowContract(result,withSession);for(let iteration=0;iteration<8;iteration+=1){const previousReadEstimate=receipt.estimated_tokens,previousSessionEstimate=withSession.read_session.spent_this_call_tokens;updateReadOutputReceiptEstimate(withSession,receipt,format);const previous=withSession;withSession=attachReadOutputSessionReceipt(withSession,state,format),preserveReadOutputRowContract(previous,withSession);const sessionEstimate=withSession.read_session.spent_this_call_tokens;if(receipt.estimated_tokens===previousReadEstimate&&sessionEstimate===previousSessionEstimate)return withSession}return withSession}function stabilizeReadOutputReceiptEstimates(result,options){if(!isRecord(result.read_output))return result;const format=readOutputMeasurementFormat(options),receipt=result.read_output,session=parseReadOutputSession(options.outputSession??options.output_session);return session===void 0?(updateReadOutputReceiptEstimate(result,receipt,format),result):attachReadOutputSessionContracts(result,session,receipt,format)}function attachValidateDiagnosticRowContract(command,result){if(command!=="validate")return result;const projection=isRecord(result.projection)?result.projection:void 0;if(!(Array.isArray(projection?.declared_field_groups)?projection.declared_field_groups:[]).some(group=>isRecord(group)&&group.name==="diagnostic_rows"))return result;const diagnosticCollectionPaths=[...new Set(readOutputBudgetCollections(result).map(({path})=>path).filter(path=>/^checks\.\d+\.details\./u.test(path)))],diagnosticRowKeys=diagnosticCollectionPaths.filter(path=>!diagnosticCollectionPaths.some(candidate=>candidate!==path&&path.startsWith(`${candidate}.`)));if(diagnosticRowKeys.length===0)return result;const existingContract=isRecord(result.row_contract)?result.row_contract:{},existingRowKeys=Array.isArray(existingContract.row_keys)?existingContract.row_keys.filter(entry=>typeof entry=="string"):[],existingContinuationRowKeys=Array.isArray(existingContract.continuation_row_keys)?existingContract.continuation_row_keys.filter(entry=>typeof entry=="string"):[],rowKeys=existingRowKeys.length>0?existingRowKeys:diagnosticRowKeys,continuationRowKeys=[...new Set(diagnosticRowKeys)];return JSON.stringify(rowKeys)===JSON.stringify(existingRowKeys)&&JSON.stringify(continuationRowKeys)===JSON.stringify(existingContinuationRowKeys)?result:{...result,row_contract:{...existingContract,row_keys:rowKeys,continuation_row_keys:continuationRowKeys,jq_selector:typeof existingContract.jq_selector=="string"?existingContract.jq_selector:".checks[].details"}}}function includeProjectionApplies(resolved,result){return resolved.include?.source==="canonical"&&!isReadResultOmittedForBudget(result)}function projectReadOutputRows(result,resolved,session,cursor,options){let projected={...result};if(includeProjectionApplies(resolved,result)&&(projected=applyIncludeProjection(resolved.command,projected,resolved.include.value)),resolved.command==="assurance"&&(projected=prioritizeAssuranceAssertions(projected)),refreshReadOutputDeliveredCounts(projected,result),projected=applyReadOutputContinuation(projected,resolved.command,cursor),resolved.command==="history"&&cursor){const historyRowKeys=["compact_history","provenance_history","history","diff"];if(projected=Object.fromEntries(Object.entries(projected).filter(([key])=>!historyRowKeys.includes(key)||key===cursor.path)),isRecord(projected.projection)&&(projected.projection={...projected.projection,row_key:cursor.path}),isRecord(projected.row_contract)){const rowContract=projected.row_contract;projected.row_contract={...rowContract,row_keys:[cursor.path],...Array.isArray(rowContract.continuation_row_keys)?{continuation_row_keys:[cursor.path]}:{}}}projected.count=Object.keys(projected[cursor.path]).length}const continuationSource=result.count_only===!0?{...projected,count_only:!0,count:result.count}:projected,continuationState=captureReadOutputContinuationState(projected,result,resolved.command,cursor,options);return resolved.amount?.source==="canonical"&&(projected=applyAmountBound(projected,resolved.amount.value,resolved.command,continuationState.collectionsBeforeBudget),continuationState.cursorContinuesExistingPage&&rebaseCompactedProducerCursor(projected,continuationState.originalItems,continuationState.cursorSource,!0,continuationState.originalItemOffset)),refreshReadOutputDeliveredCounts(projected,continuationSource),refreshTailRetentionRowCounters(projected,resolved.command,continuationState),{projected:session===void 0?projected:applyReadOutputSessionReferences(projected,session),continuationState}}function resolveBindingReadOutputBudget(resolved,session){return[...resolved.cost!==void 0&&resolved.cost.value!=="unbounded"&&(resolved.cost.source==="canonical"||resolved.cost.source==="default"||resolved.command==="context"&&resolved.cost.source==="legacy")?[{source:resolved.cost.source,tokens:resolved.cost.value}]:[],...session===void 0?[]:[{source:"session",tokens:readOutputSessionRemainingTokens(session)}]].sort((left,right)=>left.tokens-right.tokens)[0]}function canonicalReadOutputReceiptFields(resolved){const canonicalOptions=resolved.canonical_options_used;return canonicalOptions&&canonicalOptions.length>0?{canonical_options_used:canonicalOptions}:{}}function hasContextIntentBudgetReceipt(result,tokens){return isRecord(result.context_intent)&&result.context_intent.command==="context"&&result.context_intent.token_budget===tokens&&result.context_intent.within_budget===!0}function requiresNextSelectionBudgetAudit(resolved,options,result){return resolved.command!=="next"||(options.tokenBudget??options.token_budget)===void 0?!1:!(isRecord(result.context_intent)&&result.context_intent.command==="next"&&result.context_intent.within_budget===!0)}function readOutputBudgetReceiptFields(budget,result={}){return budget?.source==="default"||budget?.source==="legacy"&&!hasContextIntentBudgetReceipt(result,budget.tokens)?{budget_source:budget.source,budget_tokens:budget.tokens}:{}}function omitReadOutputForBudget(resolved,requested,session,bindingBudget,omittedResultEstimatedTokens,format){const minimalReceipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...readOutputBudgetReceiptFields(bindingBudget),precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...session===void 0?{omitted_result_estimated_tokens:omittedResultEstimatedTokens}:{}},omitted={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:minimalReceipt},boundedOmission=session===void 0?omitted:attachReadOutputSessionContracts(omitted,session,minimalReceipt,format);if(session===void 0&&updateReadOutputReceiptEstimate(boundedOmission,minimalReceipt,format),session!==void 0&&minimalReceipt.estimated_tokens>bindingBudget.tokens)throw new PmCliError("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",EXIT_CODE.USAGE);return boundedOmission}function requiresReadOutputAudit(resolved,options,result){return resolved.command==="context"&&resolved.cost?.source==="legacy"&&!hasContextIntentBudgetReceipt(result,resolved.cost.value)||requiresNextSelectionBudgetAudit(resolved,options,result)||options.outputRowContract===!0||options.output_row_contract===!0||resolved.canonical_options_used.includes("--output-include")||resolved.command==="list"&&resolved.canonical_options_used.length>0&&resolved.include?.value.includes("full")===!0}function canReturnReadOutputUnchanged(resolved,session,result,format,options){if(session!==void 0||isReadResultOmittedForBudget(result)||requiresReadOutputAudit(resolved,options,result))return!1;if(resolved.amount?.source==="canonical"&&resolved.amount.value!=="unbounded"){const limit=resolved.amount.value;if(readOutputRowCollections(result).some(({value})=>(Array.isArray(value)?value.length:Object.keys(value).length)>limit))return!1}return resolved.cost===void 0||resolved.cost.value==="unbounded"||resolved.cost.source==="legacy"&&resolved.command!=="context"||estimateReadOutputTokens(options.outputRowContract===!1?Object.fromEntries(Object.entries(result).filter(([key])=>key!=="row_contract")):result,format)<=resolved.cost.value}function attachTailRetentionTotal(projected,command,continuations){const policy=Object.hasOwn(PM_READ_OUTPUT_TAIL_RETENTION_POLICIES,command)?PM_READ_OUTPUT_TAIL_RETENTION_POLICIES[command]:void 0,withheld=continuations.find(entry=>policy?.paths.includes(entry.path));policy!==void 0&&withheld!==void 0&&typeof projected[policy.total_key]!="number"&&(projected[policy.total_key]=withheld.total_rows)}function refreshTailRetentionRowCounters(delivered,command,continuationState){const path=PM_READ_OUTPUT_TAIL_RETENTION_POLICIES[command]?.paths[0];path!==void 0&&refreshReadOutputDeliveredRowCounters(delivered,command,continuationState.producer,continuationState.collectionsBeforeBudget.get(path)?.rows)}function buildReadOutputContinuation(command,path,before,retainedRows){const offset=before.backward?before.rows-retainedRows:before.baseOffset+retainedRows;return{path,cursor:encodeReadOutputContinuationCursor({command,path,offset,total_rows:before.totalRows,fingerprint:before.fingerprint,...before.backward?{direction:"backward"}:{}}),retained_rows:retainedRows,remaining_rows:before.backward?offset:before.totalRows-offset,total_rows:before.totalRows}}function attachReadOutputTruncationDisclosure(projected,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,collectionsBeforeBudget){if(!receipt.rows_compacted)return;const overridden=resolved.amount?.value==="unbounded"?["amount"]:[],afterByPath=new Map(readOutputContinuationRowCollections(projected).map(collection=>[collection.path,Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length])),continuations=[...collectionsBeforeBudget.entries()].flatMap(([path,before])=>{const retainedRows=afterByPath.get(path);return retainedRows>=before.rows?[]:[buildReadOutputContinuation(resolved.command,path,before,retainedRows)]}),primary=continuations[0];attachTailRetentionTotal(projected,resolved.command,continuations);const continuationHint=primary?"; page --output-cursor":"",budgetHint=bindingBudget.source==="session"?`Truncated by the remaining ${bindingBudget.tokens}-token session budget; start a new output session with a larger token_budget${continuationHint}.`:`${bindingBudget.tokens}-token: raise --output-budget${continuationHint}`;receipt.migration_hints=[budgetHint,...resolved.migration_hints];const recoveryBudget=resolveReadOutputRecoveryBudget({effective_budget_tokens:bindingBudget.tokens,measured_result_tokens:measuredResultTokens});primary&&!continuationCursorRebased&&(typeof projected.next_cursor!="string"||projected.continuation_kind==="output_cursor")&&(projected.next_cursor=primary.cursor),projected.continuation_kind=continuationCursorRebased?"producer_cursor":primary?"output_cursor":"none",projected.output_budget_truncation={reason:"output_budget_reached",budget_source:bindingBudget.source,budget_tokens:bindingBudget.tokens,overridden_dimensions:overridden,compacted_row_paths:receipt.compacted_row_paths,continuation_cursor_rebased:continuationCursorRebased,continuation_available:continuations.length>0,recovery_budget_multiplier:primary?1:recoveryBudget.recovery_budget_multiplier,continuations,restore_with:primary?"recovery":`Retry with --output-budget ${recoveryBudget.output_budget} because no declared row collection can be continued.`,recovery:primary?{cursor:primary.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${recoveryBudget.output_budget}`,sdk:{outputBudget:recoveryBudget.output_budget},mcp:{outputBudget:recoveryBudget.output_budget}}}}function rebaseCompactedProducerCursor(projected,originalItems,cursorSource,cursorContinuesExistingPage,originalItemOffset){if(typeof cursorSource!="string"||!Array.isArray(projected.items))return!1;const retainedCount=projected.items.length,originalItemCount=originalItems.length;if(retainedCount===0||retainedCount>=originalItemCount)return!1;let cursor;try{cursor=decodeQueryCursorEnvelope(cursorSource)}catch{return!1}const sourceIndex=cursor.after_index;if(sourceIndex===void 0)return!1;const last=originalItems[retainedCount-1];if(Object.prototype.toString.call(last)!=="[object Object]")return!1;const lastId=Reflect.get(last,"id");if(typeof lastId!="string"||lastId.length===0)return!1;const afterIndex=cursorContinuesExistingPage?sourceIndex-(originalItemCount-retainedCount):sourceIndex+originalItemOffset+retainedCount;return afterIndex<0?!1:(projected.next_cursor=encodeQueryCursor(cursor.fingerprint,lastId,afterIndex,cursor.snapshot),!0)}function captureReadOutputContinuationState(projected,source,command,cursor,options){const collectionsBeforeBudget=new Map(readOutputContinuationRowCollections(projected).map(collection=>{const rows=Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length,continued=cursor?.path===collection.path,backward=readOutputRetainsTail(command,collection.path);return[collection.path,{rows,totalRows:continued?cursor.total_rows:rows,baseOffset:continued&&!backward?cursor.offset:0,backward,fingerprint:continued?cursor.fingerprint:readOutputCollectionFingerprint(collection.path,collection.value,command)}]})),cursorContinuesExistingPage=typeof projected.next_cursor=="string",originalItemOffset=cursor?.path==="items"?cursor.offset:0;return{collectionsBeforeBudget,originalItems:Array.isArray(source.items)?originalItemOffset>0?source.items.slice(originalItemOffset):source.items:[],originalItemOffset,cursorContinuesExistingPage,cursorSource:cursorContinuesExistingPage?projected.next_cursor:options.after,producer:source}}function compactReadOutputProjection(projected,source,countOnly,resolved,receipt,bindingBudget,session,continuationState,measuredResultTokens,format){const deliveredSource={...source,count_only:countOnly},assuranceMinimumRows=resolved.command==="assurance"&&Array.isArray(projected.assertions)?projected.assertions.filter(row=>isRecord(row)&&row.verdict!=="pass").length:0,minimumRowsByPath=new Map;if(assuranceMinimumRows>0&&minimumRowsByPath.set("assertions",assuranceMinimumRows),resolved.command==="history"&&Array.isArray(projected.diff))for(const collection of readOutputBudgetCollections(projected))collection.path.startsWith("diff.")&&minimumRowsByPath.set(collection.path,Object.keys(collection.value).length);return compactReadOutputToBudget(projected,receipt,bindingBudget.tokens,minimumRowsByPath,format,compacted=>{refreshReadOutputDeliveredCounts(compacted,deliveredSource),refreshTailRetentionRowCounters(compacted,resolved.command,continuationState);const continuationCursorRebased=rebaseCompactedProducerCursor(compacted,continuationState.originalItems,continuationState.cursorSource,continuationState.cursorContinuesExistingPage,continuationState.originalItemOffset);if(attachReadOutputTruncationDisclosure(compacted,resolved,receipt,bindingBudget,continuationCursorRebased,measuredResultTokens,continuationState.collectionsBeforeBudget),resolved.command==="history"&&isRecord(compacted.projection)){compacted.has_more=typeof compacted.next_cursor=="string"||compacted.applied_bound?.kind==="output_limit";const rowKey=compacted.projection.row_key;typeof rowKey=="string"&&Array.isArray(compacted[rowKey])&&(compacted.count=compacted[rowKey].length)}session!==void 0&&Object.assign(compacted,attachReadOutputSessionContracts(compacted,session,receipt,format))},resolved.command==="history"&&Array.isArray(projected.diff),path=>readOutputRetainsTail(resolved.command,path))}function applyReadOutputDimensions(command,options,result){const resolved=resolveReadOutputDimensions(command,options);if(!resolved)return result;const format=readOutputMeasurementFormat(options),session=parseReadOutputSession(options.outputSession??options.output_session),rawCursor=options.outputCursor??options.output_cursor,cursor=typeof rawCursor=="string"?decodeReadOutputContinuationCursor(rawCursor):void 0,requested=requestedDimensions(resolved),continuationReadyResult=attachValidateDiagnosticRowContract(resolved.command,result);if(cursor===void 0&&canReturnReadOutputUnchanged(resolved,session,continuationReadyResult,format,options))return continuationReadyResult;const bindingBudget=resolveBindingReadOutputBudget(resolved,session),projection=projectReadOutputRows(continuationReadyResult,resolved,session,cursor,options);let projected=projection.projected;preserveReadOutputRowContract(projected,projected,options.outputRowContract===!1);const intentOmitted=isReadResultOmittedForBudget(projected),receipt={contract_version:1,command:resolved.command,requested_dimensions:requested,...readOutputBudgetReceiptFields(bindingBudget,projected),precedence:resolved.precedence,...canonicalReadOutputReceiptFields(resolved),legacy_aliases_used:resolved.legacy_aliases_used,migration_hints:resolved.migration_hints,estimated_tokens:0,within_budget:!intentOmitted,strings_compacted:!1,rows_compacted:!1,result_omitted:intentOmitted};if(projected.read_output=receipt,projected=session===void 0?projected:attachReadOutputSessionContracts(projected,session,receipt,format),updateReadOutputReceiptEstimate(projected,receipt,format),bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens){const brief=projectReadOutputItemToBrief(resolved.command,options,projected);brief!==void 0&&(receipt.applied_depth="brief",receipt.degradation_reason="output_budget_reached",preserveReadOutputRowContract(projected,brief),projected=stabilizeReadOutputReceiptEstimates(brief,options)),receipt.estimated_tokens>bindingBudget.tokens&&(projected=compactReadOutputProjection(projected,projected,continuationReadyResult.count_only===!0,resolved,receipt,bindingBudget,session,projection.continuationState,receipt.estimated_tokens,format))}return bindingBudget!==void 0&&receipt.estimated_tokens>bindingBudget.tokens?omitReadOutputForBudget(resolved,requested,session,bindingBudget,receipt.estimated_tokens,format):projected}function isContextIntentResultOmitted(result){return isRecord(result)&&isRecord(result.context_intent)&&result.context_intent.result_omitted===!0}function isReadResultOmittedForBudget(result){return isReadOutputBudgetExceeded(result)||isContextIntentResultOmitted(result)}function isReadOutputBudgetExceeded(result){return isRecord(result)&&isRecord(result.output_budget_exceeded)&&result.output_budget_exceeded.omitted_result===!0&&result.output_budget_exceeded.reason==="requested_budget_infeasible"}function resolveReadOutputEncoding(command,options){const canonical=options.outputFormat??options.output_format;if(canonical==="json"||canonical==="toon")return canonical;const encoding=resolveReadOutputDimensions(command,options)?.encoding;return encoding?.value==="json"||encoding?.value==="toon"?encoding.value:void 0}export{PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACES2 as PM_READ_OUTPUT_SURFACES,PM_READ_OUTPUT_SURFACE_CONTRACTS,PM_READ_OUTPUT_TAIL_RETENTION_POLICIES2 as PM_READ_OUTPUT_TAIL_RETENTION_POLICIES,applyReadOutputDimensions,applyReadOutputIncludeModes,decodeReadOutputContinuationCursor2 as decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor2 as encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,isReadResultOmittedForBudget,normalizeReadOutputIncludeModeOptions,readOutputCollectionFingerprint2 as readOutputCollectionFingerprint,readOutputIncludeModeOptions,readOutputRetainsTail2 as readOutputRetainsTail,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputRecoveryBudget2 as resolveReadOutputRecoveryBudget,resolveReadOutputSurface,stabilizeReadOutputReceiptEstimates,validateReadOutputOptions};
2
2
  //# sourceMappingURL=read-output-contracts.js.map
@@ -12,7 +12,7 @@ path:string;
12
12
  value:unknown[] | Record<string,unknown>;
13
13
  }
14
14
  /** Replace one declared row collection with a suffix beginning at an offset. */
15
- export declare function sliceReadOutputRowCollection(result:Record<string,unknown>,rowPath:string,offset:number):Record<string,unknown>;
15
+ export declare function sliceReadOutputRowCollection(result:Record<string,unknown>,rowPath:string,offset:number,end?:number):Record<string,unknown>;
16
16
  /** Resolve declared row paths, falling back to top-level array properties. */
17
17
  export declare function readOutputRowPaths(result:Record<string,unknown>):string[];
18
18
  /** Resolve collections that may be resumed independently from primary result rows. */
@@ -39,8 +39,12 @@ export declare function countReadOutputRows(result:Record<string,unknown>):numbe
39
39
  * only the owner objects along paths that changed.
40
40
  */
41
41
  export declare function mapReadOutputRows(result:Record<string,unknown>,transform:(row:unknown,path:string,index:number) => unknown):Record<string,unknown>;
42
- /** Bound every declared row collection independently and report truncation. */
43
- export declare function boundReadOutputRows(result:Record<string,unknown>,amount:number):{
42
+ /**
43
+ * Bound every declared row collection independently and report truncation.
44
+ * A path named by `retainsTail` keeps its newest (last) rows instead of its
45
+ * first rows, matching the producer's own latest-N `--limit`.
46
+ */
47
+ export declare function boundReadOutputRows(result:Record<string,unknown>,amount:number,retainsTail?:(path:string) => boolean):{
44
48
  result:Record<string,unknown>;
45
49
  truncated:boolean;
46
50
  };
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b6db58d1-5d89-56b2-adee-13e985ebc675")}catch{}})();const BUDGET_METADATA_ROOT_KEYS=new Set(["applied_bound","completeness","budget_retention_policy","continuation_contract","continuation_kind","continuation_path","filters","omission_receipt","output_budget_truncation","projection","read_output","read_session","row_contract","sorting"]);function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function valueAtPath(result,rowPath){let value=result;for(const segment of rowPath.split("."))if(Array.isArray(value)){if(!/^\d+$/u.test(segment))return;value=value[Number(segment)]}else{if(!isRecord(value))return;value=value[segment]}return value}function replaceValueAtPath(result,rowPath,replacement){const segments=rowPath.split("."),replace=(value,offset)=>{if(offset===segments.length)return replacement;const segment=segments[offset];if(Array.isArray(value)){const index=Number(segment),cloned=[...value];return cloned[index]=replace(value[index],offset+1),cloned}const record=value;return{...record,[segment]:replace(record[segment],offset+1)}};return replace(result,0)}function sliceReadOutputRowCollection(result,rowPath,offset){const collection=readOutputContinuationRowCollections(result).find(entry=>entry.path===rowPath);if(!collection)return result;const replacement=Array.isArray(collection.value)?collection.value.slice(offset):Object.fromEntries(Object.entries(collection.value).slice(offset)),sliced=replaceValueAtPath(result,rowPath,replacement);return isRecord(sliced.summary)&&isRecord(sliced.summary.focus_row_states)&&typeof sliced.summary.focus_row_states[rowPath]=="string"&&(sliced.summary={...sliced.summary,focus_row_states:{...sliced.summary.focus_row_states,[rowPath]:sliced.summary.focus_row_states[rowPath].slice(offset)}}),refreshReadOutputDeliveredCounts(sliced),sliced}function readOutputRowPaths(result){const contract=result.row_contract;return isRecord(contract)&&Array.isArray(contract.row_keys)?contract.row_keys.filter(entry=>typeof entry=="string"&&entry.trim().length>0):Object.entries(result).filter(([,value])=>Array.isArray(value)).map(([key])=>key)}function readOutputContinuationRowPaths(result){const contract=result.row_contract;return isRecord(contract)&&Array.isArray(contract.continuation_row_keys)?contract.continuation_row_keys.filter(entry=>typeof entry=="string"&&entry.trim().length>0):readOutputRowPaths(result)}function readOutputRowCollections(result){return readOutputRowPaths(result).flatMap(rowPath=>{const value=valueAtPath(result,rowPath);return Array.isArray(value)||isRecord(value)?[{path:rowPath,value}]:[]})}function readOutputContinuationRowCollections(result){return readOutputContinuationRowPaths(result).flatMap(rowPath=>{const value=valueAtPath(result,rowPath);return Array.isArray(value)||isRecord(value)?[{path:rowPath,value}]:[]})}function readOutputBudgetCollections(result){const collections=readOutputRowCollections(result),declaredPaths=new Set(collections.map(collection=>collection.path)),visit=(value,path)=>{if(Array.isArray(value)){declaredPaths.has(path)||collections.push({path,value}),value.forEach((entry,index)=>visit(entry,`${path}.${index}`));return}if(isRecord(value))for(const[key,entry]of Object.entries(value))path.length===0&&BUDGET_METADATA_ROOT_KEYS.has(key)||visit(entry,path.length===0?key:`${path}.${key}`)};return visit(result,""),collections}function countReadOutputRows(result){return readOutputRowCollections(result).reduce((total,collection)=>total+(Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length),0)}function mapReadOutputRows(result,transform){let projected=result;for(const collection of readOutputRowCollections(projected)){const replacement=Array.isArray(collection.value)?collection.value.map((row,index)=>transform(row,collection.path,index)):Object.fromEntries(Object.entries(collection.value).map(([key,row],index)=>[key,transform(row,collection.path,index)]));projected=replaceValueAtPath(projected,collection.path,replacement)}return projected}function boundReadOutputRows(result,amount){let projected=result,truncated=!1;for(const collection of readOutputRowCollections(projected)){const entries=Array.isArray(collection.value)?collection.value:Object.entries(collection.value);if(entries.length<=amount)continue;truncated=!0;const replacement=Array.isArray(collection.value)?entries.slice(0,amount):Object.fromEntries(entries.slice(0,amount));projected=replaceValueAtPath(projected,collection.path,replacement)}return{result:projected,truncated}}const FOCUS_KEYS=["high_level","low_level","blocked_fallback"];function focusRowState(row){const state=row.status==="in_progress"?"i":"o";return row.blocked===!0?state.toUpperCase():state}function rememberReadOutputFocusRows(result,rows){if(!isRecord(result.summary)||!isRecord(result.summary.returned_focus))return;const byId=new Map(rows.map(row=>[row.id,row]));result.summary={...result.summary,focus_row_states:Object.fromEntries(FOCUS_KEYS.map(key=>[key,Array.isArray(result[key])?result[key].filter(isRecord).map(row=>focusRowState(byId.get(row.id)??row)).join(""):""]))}}function validatedFocusStates(value,rows){if(value!==void 0){if(typeof value!="string"||value.length!==rows||!/^[iIoO]*$/u.test(value))throw new TypeError("Context focus classification receipt must contain one i/I/o/O code per delivered record");return value}}function deliveredFocusSectionStates(result,source,key,sourceStates){const original=Array.isArray(source[key])?source[key].filter(isRecord):[],originalStates=validatedFocusStates(sourceStates[key],original.length)??original.map(focusRowState).join(""),byId=new Map(original.flatMap((row,index)=>row.id===void 0?[]:[[row.id,originalStates[index]]])),delivered=Array.isArray(result[key])?result[key].filter(isRecord):[];let needsStates=!1;return{states:delivered.map((row,index)=>{const state=byId.get(row.id)??(row.id===void 0?originalStates[index]:void 0)??focusRowState(row);return state!==focusRowState(row)&&(needsStates=!0),state}).join(""),needsStates}}function refreshItemCount(result,source){typeof result.count=="number"&&(result.count_only===!0||source.count_only===!0?typeof source.count=="number"&&(result.count=source.count):Array.isArray(result.items)&&(result.count=result.items.length))}function refreshReadOutputDeliveredCounts(result,source=result){if(refreshItemCount(result,source),!isRecord(result.summary)||!isRecord(result.summary.returned_focus))return;const summary={...result.summary},sourceStates=isRecord(source.summary)&&isRecord(source.summary.focus_row_states)?source.summary.focus_row_states:{},sections=FOCUS_KEYS.map(key=>({key,...deliveredFocusSectionStates(result,source,key,sourceStates)})),states=Object.fromEntries(sections.map(({key,states:states2})=>[key,states2])),needsStates=sections.some(section=>section.needsStates),deliveredStates=Object.values(states).join("");typeof summary.high_level=="number"&&(summary.high_level=Array.isArray(result.high_level)?result.high_level.length:0),typeof summary.low_level=="number"&&(summary.low_level=Array.isArray(result.low_level)?result.low_level.length:0),summary.returned_focus={active_items:deliveredStates.length,in_progress:[...deliveredStates].filter(state=>state.toLowerCase()==="i").length,open:[...deliveredStates].filter(state=>state.toLowerCase()==="o").length,blocked:[...deliveredStates].filter(state=>state===state.toUpperCase()).length},needsStates?summary.focus_row_states=states:delete summary.focus_row_states,result.summary=summary}export{boundReadOutputRows,countReadOutputRows,mapReadOutputRows,readOutputBudgetCollections,readOutputContinuationRowCollections,readOutputContinuationRowPaths,readOutputRowCollections,readOutputRowPaths,refreshReadOutputDeliveredCounts,rememberReadOutputFocusRows,sliceReadOutputRowCollection};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f539ecb5-2f49-5867-96c7-48eddb81a628")}catch{}})();const BUDGET_METADATA_ROOT_KEYS=new Set(["applied_bound","completeness","budget_retention_policy","continuation_contract","continuation_kind","continuation_path","filters","omission_receipt","output_budget_truncation","projection","read_output","read_session","row_contract","sorting"]);function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function valueAtPath(result,rowPath){let value=result;for(const segment of rowPath.split("."))if(Array.isArray(value)){if(!/^\d+$/u.test(segment))return;value=value[Number(segment)]}else{if(!isRecord(value))return;value=value[segment]}return value}function replaceValueAtPath(result,rowPath,replacement){const segments=rowPath.split("."),replace=(value,offset)=>{if(offset===segments.length)return replacement;const segment=segments[offset];if(Array.isArray(value)){const index=Number(segment),cloned=[...value];return cloned[index]=replace(value[index],offset+1),cloned}const record=value;return{...record,[segment]:replace(record[segment],offset+1)}};return replace(result,0)}function sliceReadOutputRowCollection(result,rowPath,offset,end){const collection=readOutputContinuationRowCollections(result).find(entry=>entry.path===rowPath);if(!collection)return result;const replacement=Array.isArray(collection.value)?collection.value.slice(offset,end):Object.fromEntries(Object.entries(collection.value).slice(offset,end)),sliced=replaceValueAtPath(result,rowPath,replacement);return isRecord(sliced.summary)&&isRecord(sliced.summary.focus_row_states)&&typeof sliced.summary.focus_row_states[rowPath]=="string"&&(sliced.summary={...sliced.summary,focus_row_states:{...sliced.summary.focus_row_states,[rowPath]:sliced.summary.focus_row_states[rowPath].slice(offset,end)}}),refreshReadOutputDeliveredCounts(sliced),sliced}function readOutputRowPaths(result){const contract=result.row_contract;return isRecord(contract)&&Array.isArray(contract.row_keys)?contract.row_keys.filter(entry=>typeof entry=="string"&&entry.trim().length>0):Object.entries(result).filter(([,value])=>Array.isArray(value)).map(([key])=>key)}function readOutputContinuationRowPaths(result){const contract=result.row_contract;return isRecord(contract)&&Array.isArray(contract.continuation_row_keys)?contract.continuation_row_keys.filter(entry=>typeof entry=="string"&&entry.trim().length>0):readOutputRowPaths(result)}function readOutputRowCollections(result){return readOutputRowPaths(result).flatMap(rowPath=>{const value=valueAtPath(result,rowPath);return Array.isArray(value)||isRecord(value)?[{path:rowPath,value}]:[]})}function readOutputContinuationRowCollections(result){return readOutputContinuationRowPaths(result).flatMap(rowPath=>{const value=valueAtPath(result,rowPath);return Array.isArray(value)||isRecord(value)?[{path:rowPath,value}]:[]})}function readOutputBudgetCollections(result){const collections=readOutputRowCollections(result),declaredPaths=new Set(collections.map(collection=>collection.path)),visit=(value,path)=>{if(Array.isArray(value)){declaredPaths.has(path)||collections.push({path,value}),value.forEach((entry,index)=>visit(entry,`${path}.${index}`));return}if(isRecord(value))for(const[key,entry]of Object.entries(value))path.length===0&&BUDGET_METADATA_ROOT_KEYS.has(key)||visit(entry,path.length===0?key:`${path}.${key}`)};return visit(result,""),collections}function countReadOutputRows(result){return readOutputRowCollections(result).reduce((total,collection)=>total+(Array.isArray(collection.value)?collection.value.length:Object.keys(collection.value).length),0)}function mapReadOutputRows(result,transform){let projected=result;for(const collection of readOutputRowCollections(projected)){const replacement=Array.isArray(collection.value)?collection.value.map((row,index)=>transform(row,collection.path,index)):Object.fromEntries(Object.entries(collection.value).map(([key,row],index)=>[key,transform(row,collection.path,index)]));projected=replaceValueAtPath(projected,collection.path,replacement)}return projected}function boundReadOutputRows(result,amount,retainsTail=()=>!1){let projected=result,truncated=!1;for(const collection of readOutputRowCollections(projected)){const entries=Array.isArray(collection.value)?collection.value:Object.entries(collection.value);if(entries.length<=amount)continue;truncated=!0;const start=retainsTail(collection.path)?entries.length-amount:0,kept=entries.slice(start,start+amount),replacement=Array.isArray(collection.value)?kept:Object.fromEntries(kept);projected=replaceValueAtPath(projected,collection.path,replacement)}return{result:projected,truncated}}const FOCUS_KEYS=["high_level","low_level","blocked_fallback"];function focusRowState(row){const state=row.status==="in_progress"?"i":"o";return row.blocked===!0?state.toUpperCase():state}function rememberReadOutputFocusRows(result,rows){if(!isRecord(result.summary)||!isRecord(result.summary.returned_focus))return;const byId=new Map(rows.map(row=>[row.id,row]));result.summary={...result.summary,focus_row_states:Object.fromEntries(FOCUS_KEYS.map(key=>[key,Array.isArray(result[key])?result[key].filter(isRecord).map(row=>focusRowState(byId.get(row.id)??row)).join(""):""]))}}function validatedFocusStates(value,rows){if(value!==void 0){if(typeof value!="string"||value.length!==rows||!/^[iIoO]*$/u.test(value))throw new TypeError("Context focus classification receipt must contain one i/I/o/O code per delivered record");return value}}function deliveredFocusSectionStates(result,source,key,sourceStates){const original=Array.isArray(source[key])?source[key].filter(isRecord):[],originalStates=validatedFocusStates(sourceStates[key],original.length)??original.map(focusRowState).join(""),byId=new Map(original.flatMap((row,index)=>row.id===void 0?[]:[[row.id,originalStates[index]]])),delivered=Array.isArray(result[key])?result[key].filter(isRecord):[];let needsStates=!1;return{states:delivered.map((row,index)=>{const state=byId.get(row.id)??(row.id===void 0?originalStates[index]:void 0)??focusRowState(row);return state!==focusRowState(row)&&(needsStates=!0),state}).join(""),needsStates}}function refreshItemCount(result,source){typeof result.count=="number"&&(result.count_only===!0||source.count_only===!0?typeof source.count=="number"&&(result.count=source.count):Array.isArray(result.items)&&(result.count=result.items.length))}function refreshReadOutputDeliveredCounts(result,source=result){if(refreshItemCount(result,source),!isRecord(result.summary)||!isRecord(result.summary.returned_focus))return;const summary={...result.summary},sourceStates=isRecord(source.summary)&&isRecord(source.summary.focus_row_states)?source.summary.focus_row_states:{},sections=FOCUS_KEYS.map(key=>({key,...deliveredFocusSectionStates(result,source,key,sourceStates)})),states=Object.fromEntries(sections.map(({key,states:states2})=>[key,states2])),needsStates=sections.some(section=>section.needsStates),deliveredStates=Object.values(states).join("");typeof summary.high_level=="number"&&(summary.high_level=Array.isArray(result.high_level)?result.high_level.length:0),typeof summary.low_level=="number"&&(summary.low_level=Array.isArray(result.low_level)?result.low_level.length:0),summary.returned_focus={active_items:deliveredStates.length,in_progress:[...deliveredStates].filter(state=>state.toLowerCase()==="i").length,open:[...deliveredStates].filter(state=>state.toLowerCase()==="o").length,blocked:[...deliveredStates].filter(state=>state===state.toUpperCase()).length},needsStates?summary.focus_row_states=states:delete summary.focus_row_states,result.summary=summary}export{boundReadOutputRows,countReadOutputRows,mapReadOutputRows,readOutputBudgetCollections,readOutputContinuationRowCollections,readOutputContinuationRowPaths,readOutputRowCollections,readOutputRowPaths,refreshReadOutputDeliveredCounts,rememberReadOutputFocusRows,sliceReadOutputRowCollection};
2
2
  //# sourceMappingURL=read-output-rows.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d4a2401b-171f-5d8f-87cd-21c0144f2cb9")}catch{}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{asRecordClone}from"../core/shared/primitives.js";import{resolveCheckpointRollbackId}from"../core/checkpoint/mutation-checkpoint.js";import{withLiteralMutationInput}from"./lifecycle/cli-input.js";import{isCliMutationInput}from"../core/item/literal-mutation-input.js";import{assertMutationItemOperand,assertNativeMutationValueTypes}from"./runtime/mutation-value-validation.js";import{foldNullClearsIntoUnset}from"./lifecycle/shared-unset-fields.js";import{normalizeListOptions,normalizeCreateOptions,normalizeUpdateOptions}from"./cli-contracts/registration-helpers.js";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS}from"./cli-contracts/commander-mutation-options.js";import{TOOL_CREATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS}from"./cli-contracts/tool-option-contracts.js";import{PM_TOOL_PARAMETER_PROPERTIES}from"./cli-contracts/tool-parameter-tables.js";import{PM_TOOL_ACTION_PARAMETER_CONTRACTS}from"./cli-contracts/tool-schema.js";import{normalizeBulkIdsValue}from"../core/io/bulk-ids-input.js";import{overlayMutationStdinTokenPolicy,preserveMutationStdinTokenLiterals,transferMutationStdinTokenPolicy}from"../core/item/parse.js";const MCP_MUTATION_TRANSPORT=Symbol("pm.mcp-mutation-transport"),LITERAL_MUTATION_ACTIONS=new Set(["create","update","append"]),MCP_MUTATION_OPTION_CONTRACTS={create:{parameters:TOOL_CREATE_OPTION_CONTRACTS,aliases:CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,strings:CREATE_COMMANDER_STRING_OPTION_CONTRACTS,repeatables:CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS},update:{parameters:TOOL_UPDATE_OPTION_CONTRACTS,aliases:UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,strings:UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,repeatables:UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS}},WORKSPACE_CONTRACTS_CACHE_PRESERVING_ACTIONS=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function markMcpMutationTransportInput(input){return Object.defineProperty(input,MCP_MUTATION_TRANSPORT,{value:!0,enumerable:!0}),input}function isMcpMutationTransportInput(input){return MCP_MUTATION_TRANSPORT in input}function preserveTransportLiteralOptions(source,options){return isMcpMutationTransportInput(source)?preserveMutationStdinTokenLiterals(options):transferMutationStdinTokenPolicy(source,options)}function mutationOptionsWithOverrides(source,overrides,omittedKeys=[]){const options=transferMutationStdinTokenPolicy(source,{...source,...overrides});for(const key of omittedKeys)Reflect.deleteProperty(options,key);return options}function readRuntimeString(args,key){const value=args[key];return typeof value=="string"&&value.trim().length>0?value:void 0}function readRuntimeScalarString(args,key){const value=args[key];return typeof value=="string"?value.trim().length>0?value:void 0:typeof value=="number"&&Number.isFinite(value)?String(value):void 0}function readRuntimeScalarStringAllowBlank(args,key){const value=args[key];return typeof value=="string"?value:typeof value=="number"&&Number.isFinite(value)?String(value):void 0}function isRuntimeRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function parseRuntimeInteger(value,label){if(typeof value=="number"){if(!Number.isInteger(value))throw new PmCliError(`${label} must be a finite integer.`,EXIT_CODE.USAGE);return value}if(typeof value=="string"&&value.trim().length>0){const parsed=Number(value);if(!Number.isInteger(parsed))throw new PmCliError(`${label} must be a finite integer.`,EXIT_CODE.USAGE);return parsed}}function resolveRuntimeLimit(args,options){return typeof args.limit=="number"&&Number.isFinite(args.limit)?args.limit:typeof options.limit=="number"&&Number.isFinite(options.limit)?options.limit:readRuntimeString(args,"limit")??readRuntimeString(options,"limit")}function actionGlobalOptions(args){const outputFormat=readRuntimeString(args,"outputFormat");return{json:!0,quiet:!0,author:readRuntimeString(args,"author"),path:readRuntimeString(args,"path"),noExtensions:args.noExtensions===!0||args.no_extensions===!0,noPager:!0,outputInclude:readRuntimeString(args,"outputInclude"),outputLimit:readRuntimeScalarString(args,"outputLimit"),outputBudget:readRuntimeScalarString(args,"outputBudget"),outputSession:readRuntimeString(args,"outputSession"),outputCursor:readRuntimeString(args,"outputCursor"),outputFormat:outputFormat==="json"||outputFormat==="toon"?outputFormat:void 0}}const ARRAY_TO_CSV_FIELDS=new Set(["tags","blockedBy","blocked_by","skills","fields"]),SCALAR_TO_ARRAY_FIELDS=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"]),ANNOTATION_SCALAR_TO_ARRAY_FIELDS=new Set([...SCALAR_TO_ARRAY_FIELDS].filter(field=>field!=="file")),ARRAY_ADD_REMOVE_ACTIONS=new Set(["files","files-discover","docs","test","test-all"]),SCALAR_ANNOTATION_SOURCE_ACTIONS=new Set(["comments","notes","learnings"]);function assertMcpAnnotationFileUnavailable(action,options){if(!(!SCALAR_ANNOTATION_SOURCE_ACTIONS.has(action)||!Object.prototype.hasOwnProperty.call(options,"file")))throw new PmCliError(`MCP ${action} does not accept options.file. Pass annotation text in options.add instead.`,EXIT_CODE.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}const LIFECYCLE_AUTHOR_ALIAS_ACTIONS=new Set(["claim","release","start-task","pause-task","close-task"]),HOISTED_ACTION_OPTION_KEYS={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"],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"]},CONTRACT_HOISTED_READ_ACTIONS=new Set(["context","get","list","next","search"]),READ_ACTION_OPERAND_KEYS=new Set(["query","keywords"]);function declaredReadActionOptionKeys(action){return CONTRACT_HOISTED_READ_ACTIONS.has(action)?PM_TOOL_ACTION_PARAMETER_CONTRACTS[action].optional.filter(key=>!READ_ACTION_OPERAND_KEYS.has(key)):[]}function nestedOptionPresent(nested,key){const snakeKey=key.replace(/[A-Z]/gu,letter=>`_${letter.toLowerCase()}`);return nested[key]!==void 0||nested[snakeKey]!==void 0}function hoistedActionOptionKeys(action){return[...HOISTED_ACTION_OPTION_KEYS[action]??[],...declaredReadActionOptionKeys(action),...UNIVERSAL_READ_OUTPUT_OPTION_KEYS]}const UNIVERSAL_READ_OUTPUT_OPTION_KEYS=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function normalizeMcpOptionsArrays(options,action=""){const result={},promoteAddRemove=ARRAY_ADD_REMOVE_ACTIONS.has(action),preserveStandaloneNote=action==="files"||action==="files-discover"||action==="docs",scalarToArrayFields=SCALAR_ANNOTATION_SOURCE_ACTIONS.has(action)?ANNOTATION_SCALAR_TO_ARRAY_FIELDS:SCALAR_TO_ARRAY_FIELDS;for(const[key,value]of Object.entries(options)){if(Array.isArray(value)&&ARRAY_TO_CSV_FIELDS.has(key)){result[key]=value.join(",");continue}if(key==="note"&&preserveStandaloneNote){result[key]=value;continue}if(typeof value=="string"&&scalarToArrayFields.has(key)){result[key]=[value];continue}if(typeof value=="string"&&promoteAddRemove&&(key==="add"||key==="remove")){result[key]=[value];continue}result[key]=value}return Object.assign(result,Object.fromEntries(Object.getOwnPropertySymbols(options).map(symbol=>[symbol,Reflect.get(options,symbol)]))),result}function resolveMcpActionAuthor(args,options,action){const author=readRuntimeString(args,"author");return author!==void 0?author:action!==void 0&&LIFECYCLE_AUTHOR_ALIAS_ACTIONS.has(action)?readRuntimeString(args,"assignee")??readRuntimeString(options,"assignee"):void 0}function withResolvedAuthor(options,author){return author!==void 0&&options.author===void 0?{...options,author}:options}function hoistedMcpMutationOptions(action,args,nested){const result={},contracts=MCP_MUTATION_OPTION_CONTRACTS[action],parameters=new Set([...contracts.parameters.map(({param})=>param),...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS.map(({param})=>param),...HOISTED_ACTION_OPTION_KEYS[action],...UNIVERSAL_READ_OUTPUT_OPTION_KEYS,"force"]);for(const param of parameters){const keys=contracts.aliases.find(contract=>contract.keys.includes(param))?.keys??[param];args[param]===void 0||keys.some(key=>nested[key]!==void 0)||(result[param]=args[param])}return result}function refuseMcpMutationValue(action,field){throw new PmCliError(`Invalid MCP ${action} value for "${field}". No changes were made.`,EXIT_CODE.USAGE,{code:"invalid_argument_value",reason:"invalid_mutation_option_value",changed:!1,field,required:`Provide valid ${action} field values and an options object; inspect the pm_${action} input schema for supported types.`})}function assertMcpMutationBooleans(action,args,options){const contracts=MCP_MUTATION_OPTION_CONTRACTS[action],parameters=[...contracts.parameters,...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,{param:"force"}];for(const{param}of parameters){if(asRecordClone(PM_TOOL_PARAMETER_PROPERTIES[param]).type!=="boolean")continue;const invalid=(contracts.aliases.find(contract=>contract.keys.includes(param))?.keys??[param]).find(key=>options[key]!==void 0&&typeof options[key]!="boolean");invalid!==void 0&&refuseMcpMutationValue(action,invalid)}for(const key of["idOnly","fullChangedFields"])args[key]!==void 0&&typeof args[key]!="boolean"&&refuseMcpMutationValue(action,key)}function checkedMcpMutationOptions(action,args,options){args.options!==void 0&&!isRuntimeRecord(args.options)&&refuseMcpMutationValue(action,"options"),assertMcpMutationBooleans(action,args,options);for(const key of ARRAY_TO_CSV_FIELDS){const value=options[key];Array.isArray(value)&&value.some(entry=>typeof entry!="string")&&refuseMcpMutationValue(action,key)}const normalized=normalizeMcpMutationOptions(options,action),contracts=MCP_MUTATION_OPTION_CONTRACTS[action];for(const{keys,target}of contracts.strings)keys.some(key=>options[key]!==void 0)&&normalized[target]===void 0&&refuseMcpMutationValue(action,target);const invalidRepeatable=contracts.repeatables.flatMap(({keys})=>keys).find(key=>{const value=options[key];return value!==void 0&&typeof value!="string"&&(!Array.isArray(value)||value.some(entry=>typeof entry!="string"))});return invalidRepeatable!==void 0&&refuseMcpMutationValue(action,invalidRepeatable),normalized}function normalizedActionOptions(args,action,hoisted,nested){const mcpMutation=(action==="create"||action==="update")&&isMcpMutationTransportInput(args),options={...mcpMutation?hoistedMcpMutationOptions(action,args,nested):hoisted,...nested};if((action==="create"||action==="update")&&!mcpMutation){const cli=isRuntimeRecord(args.options)&&isCliMutationInput(args.options);cli||foldNullClearsIntoUnset(action,options),assertNativeMutationValueTypes(action,options,!0,cli)}return mcpMutation?checkedMcpMutationOptions(action,args,options):normalizeMcpOptionsArrays(options,action)}function literalActionOptions(action,options){return!LITERAL_MUTATION_ACTIONS.has(action??"")||isCliMutationInput(options)?options:withLiteralMutationInput(options)}function optionsWithAuthor(args,action){assertMutationItemOperand(action,args);const sourceOptions=isRuntimeRecord(args.options)?args.options:void 0,baseOptions=asRecordClone(args.options),hoistedTopLevel={},hoistKey=key=>{nestedOptionPresent(baseOptions,key)||args[key]===void 0||(hoistedTopLevel[key]=args[key])};for(const key of hoistedActionOptionKeys(action??""))hoistKey(key);action!==void 0&&isMcpMutationTransportInput(args)&&assertMcpAnnotationFileUnavailable(action,baseOptions);const options=normalizedActionOptions(args,action,hoistedTopLevel,baseOptions);if(action==="history-attest"&&isMcpMutationTransportInput(args)&&(options.output!==void 0||typeof options.verify=="string"))throw new PmCliError("MCP history attest does not accept server-local proof paths. Export the returned JSON bundle and pass that JSON object as verify.",EXIT_CODE.USAGE);const stdinPolicySource=isMcpMutationTransportInput(args)?args:sourceOptions??args,resolved=preserveTransportLiteralOptions(stdinPolicySource,withResolvedAuthor(options,resolveMcpActionAuthor(args,options,action)));return literalActionOptions(action,resolved)}function withAddNoteOption(options){if(options.addNote===void 0)return options;const next={...options};return next.note===void 0&&typeof next.addNote=="string"&&(next.note=next.addNote),delete next.addNote,next}function withFilesDiscoveryOptions(options){const next={...options};return next.discoveryNote!==void 0&&next.note===void 0&&typeof next.discoveryNote=="string"&&(next.note=next.discoveryNote),delete next.discover,delete next.discoveryNote,next}function normalizeActionName(value){const chunks=[];let lastWasSeparator=!0;for(const character of value.trim().toLowerCase()){if(character>="a"&&character<="z"||character>="0"&&character<="9"){chunks.push(character),lastWasSeparator=!1;continue}lastWasSeparator||(chunks.push("-"),lastWasSeparator=!0)}return chunks.at(-1)==="-"&&chunks.pop(),chunks.join("")}function shouldInvalidateWorkspaceContractsCacheAfterAction(action){return!WORKSPACE_CONTRACTS_CACHE_PRESERVING_ACTIONS.has(normalizeActionName(action))}function normalizeCommandPath(value){return value.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function readRuntimeStringArray(value){return Array.isArray(value)?value.map(entry=>String(entry)).filter(entry=>entry.length>0):[]}function extensionOptionsFromArgs(args,options){const reserved=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),passthrough={};for(const[key,value]of Object.entries(args))reserved.has(key)||(passthrough[key]=value);const normalizedOptions={...passthrough,...options};return delete normalizedOptions.args,delete normalizedOptions.author,normalizedOptions}function withMutationCompaction(args,options){const runnerOptions=preserveTransportLiteralOptions(options??{},{...options});return{changedFields:args.fullChangedFields===!0?"full":"compact",idOnly:args.idOnly===!0,runnerOptions}}function mutationListOptions(options){return{type:readRuntimeScalarString(options,"filterType"),tag:readRuntimeScalarString(options,"filterTag"),priority:readRuntimeScalarString(options,"filterPriority"),deadlineBefore:readRuntimeScalarString(options,"filterDeadlineBefore"),deadlineAfter:readRuntimeScalarString(options,"filterDeadlineAfter"),updatedAfter:readRuntimeScalarString(options,"filterUpdatedAfter"),updatedBefore:readRuntimeScalarString(options,"filterUpdatedBefore"),createdAfter:readRuntimeScalarString(options,"filterCreatedAfter"),createdBefore:readRuntimeScalarString(options,"filterCreatedBefore"),ids:normalizeBulkIdsValue(options.ids),assignee:readRuntimeScalarString(options,"filterAssignee"),assigneeFilter:readRuntimeScalarString(options,"filterAssigneeFilter")??readRuntimeScalarString(options,"filterAssignee_filter"),parent:readRuntimeScalarString(options,"filterParent"),sprint:readRuntimeScalarString(options,"filterSprint"),release:readRuntimeScalarString(options,"filterRelease"),limit:readRuntimeScalarString(options,"limit"),offset:readRuntimeScalarString(options,"offset")}}function readGraphIdListOption(value){if(typeof value=="string"&&value.trim().length>0)return value;if(Array.isArray(value))return readRuntimeStringArray(value)}function readGraphBoundOption(value){if(typeof value=="number"&&Number.isFinite(value)||typeof value=="string"&&value.trim().length>0)return value}function graphOptionsFromFlat(options){const kind=readGraphIdListOption(options.kind),exemptIsolate=readGraphIdListOption(options.exemptIsolate),exemptIsolateType=readGraphIdListOption(options.exemptIsolateType);return{...kind===void 0?{}:{kind},maxDepth:readGraphBoundOption(options.maxDepth),limit:readGraphBoundOption(options.limit),after:readRuntimeString(options,"after"),direction:readRuntimeString(options,"direction"),maxPaths:readGraphBoundOption(options.maxPaths),sample:readGraphBoundOption(options.sample),...exemptIsolate===void 0?{}:{exemptIsolate},...exemptIsolateType===void 0?{}:{exemptIsolateType},saveBaseline:options.saveBaseline===!0,rebuild:options.rebuild===!0,clear:options.clear===!0,summary:options.summary===!0,...options.full===!0?{full:!0}:{}}}function normalizeBulkMutationListOptions(options){const normalized=normalizeListOptions(options);return options.ids!==void 0&&(normalized.ids=normalizeBulkIdsValue(options.ids)),normalized}function closeManyOptionsFromFlat(options){return{status:readRuntimeString(options,"filterStatus"),list:isRuntimeRecord(options.list)?normalizeBulkMutationListOptions(options.list):mutationListOptions(options),reason:readRuntimeString(options,"reason"),completedAt:readRuntimeString(options,"completedAt")??readRuntimeString(options,"completed_at"),resolution:readRuntimeString(options,"resolution"),expectedResult:readRuntimeString(options,"expectedResult")??readRuntimeString(options,"expected_result")??readRuntimeString(options,"expected"),actualResult:readRuntimeString(options,"actualResult")??readRuntimeString(options,"actual_result")??readRuntimeString(options,"actual"),validateClose:readRuntimeString(options,"validateClose")??readRuntimeString(options,"validate_close"),author:readRuntimeString(options,"author"),message:readRuntimeString(options,"message"),force:options.force===!0?!0:void 0,dryRun:options.dryRun===!0||options.dry_run===!0?!0:void 0,rollback:resolveCheckpointRollbackId(options.rollback),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1:void 0}}const UPDATE_MANY_FLAT_CONTROL_KEYS=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 updateManyUpdateOptionsFromFlat(options){const update={};for(const[key,value]of Object.entries(options))UPDATE_MANY_FLAT_CONTROL_KEYS.has(key)||(update[key]=value);return normalizeMcpUpdateOptions(update)}function normalizeMcpUpdateOptions(options){return normalizeMcpMutationOptions(options,"update")}function normalizeMcpMutationOptions(options,action){const normalizedInput=normalizeMcpOptionsArrays(options,action),contracts=MCP_MUTATION_OPTION_CONTRACTS[action],booleanishKeys=new Set([...contracts.parameters,...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS].filter(({booleanish})=>booleanish===!0).map(({param})=>param));for(const{keys}of contracts.repeatables)for(const key of keys)typeof normalizedInput[key]=="string"&&(normalizedInput[key]=[normalizedInput[key]]);for(const contract of contracts.strings)for(const key of contract.keys){const value=normalizedInput[key];(typeof value=="number"&&Number.isFinite(value)||value===!1&&booleanishKeys.has(key))&&(normalizedInput[key]=String(value))}return action==="create"?{...normalizeCreateOptions(normalizedInput,{requireType:!1})}:normalizeUpdateOptions(normalizedInput)}function updateManyOptionsFromFlat(options){if(isRuntimeRecord(options.list)||isRuntimeRecord(options.update)){const updateSource=isRuntimeRecord(options.update)?options.update:updateManyUpdateOptionsFromFlat(options),normalizedUpdate=preserveTransportLiteralOptions(options,normalizeMcpUpdateOptions(updateSource));return{status:readRuntimeScalarString(options,"filterStatus"),list:isRuntimeRecord(options.list)?normalizeBulkMutationListOptions(options.list):mutationListOptions(options),update:overlayMutationStdinTokenPolicy(updateSource,normalizedUpdate),dryRun:options.dryRun===!0||options.dry_run===!0?!0:void 0,rollback:resolveCheckpointRollbackId(options.rollback),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1:void 0}}return{status:readRuntimeScalarString(options,"filterStatus"),list:mutationListOptions(options),update:preserveTransportLiteralOptions(options,updateManyUpdateOptionsFromFlat(options)),dryRun:options.dryRun===!0||options.dry_run===!0?!0:void 0,rollback:resolveCheckpointRollbackId(options.rollback),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1:void 0}}function hasExpectHashKey(record){return"expectHash"in record||"expect_hash"in record}function splitExpectHashInput(args){if(!hasExpectHashKey(args)&&!(isRuntimeRecord(args.options)&&hasExpectHashKey(args.options)))return{expectHash:void 0,dispatchArgs:args};const{expectHash,expect_hash:alias,...rest}=args,options=isRuntimeRecord(rest.options)?rest.options:{},{expectHash:nested,expect_hash:nestedAlias,...nestedRest}=options,supplied=[expectHash,alias,nested,nestedAlias].filter(candidate=>candidate!==void 0),merged=supplied.length>1?supplied.flatMap(candidate=>Array.isArray(candidate)?candidate:[candidate]):supplied[0],dispatchArgs=transferMutationStdinTokenPolicy(args,"options"in rest?{...rest,options:isRuntimeRecord(rest.options)?transferMutationStdinTokenPolicy(rest.options,nestedRest):rest.options}:rest);return{expectHash:merged,dispatchArgs}}export{HOISTED_ACTION_OPTION_KEYS,actionGlobalOptions,closeManyOptionsFromFlat,extensionOptionsFromArgs,graphOptionsFromFlat,isMcpMutationTransportInput,isRuntimeRecord,markMcpMutationTransportInput,mutationListOptions,mutationOptionsWithOverrides,normalizeActionName,normalizeCommandPath,normalizeMcpOptionsArrays,normalizeMcpUpdateOptions,optionsWithAuthor,parseRuntimeInteger,readRuntimeScalarString,readRuntimeScalarStringAllowBlank,readRuntimeString,readRuntimeStringArray,resolveRuntimeLimit,shouldInvalidateWorkspaceContractsCacheAfterAction,splitExpectHashInput,updateManyOptionsFromFlat,updateManyUpdateOptionsFromFlat,withAddNoteOption,withFilesDiscoveryOptions,withMutationCompaction};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="70052a03-cde5-5d5c-822b-11f50378a9a1")}catch{}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{asRecordClone}from"../core/shared/primitives.js";import{resolveCheckpointRollbackId}from"../core/checkpoint/mutation-checkpoint.js";import{withLiteralMutationInput}from"./lifecycle/cli-input.js";import{isCliMutationInput}from"../core/item/literal-mutation-input.js";import{assertMutationItemOperand,assertNativeMutationValueTypes}from"./runtime/mutation-value-validation.js";import{foldNullClearsIntoUnset}from"./lifecycle/shared-unset-fields.js";import{normalizeListOptions,normalizeCreateOptions,normalizeUpdateOptions}from"./cli-contracts/registration-helpers.js";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS}from"./cli-contracts/commander-mutation-options.js";import{TOOL_CREATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS}from"./cli-contracts/tool-option-contracts.js";import{PM_TOOL_PARAMETER_PROPERTIES}from"./cli-contracts/tool-parameter-tables.js";import{PM_TOOL_ACTION_PARAMETER_CONTRACTS}from"./cli-contracts/tool-schema.js";import{normalizeBulkIdsValue}from"../core/io/bulk-ids-input.js";import{overlayMutationStdinTokenPolicy,preserveMutationStdinTokenLiterals,transferMutationStdinTokenPolicy}from"../core/item/parse.js";const MCP_MUTATION_TRANSPORT=Symbol("pm.mcp-mutation-transport"),LITERAL_MUTATION_ACTIONS=new Set(["create","update","append"]),MCP_MUTATION_OPTION_CONTRACTS={create:{parameters:TOOL_CREATE_OPTION_CONTRACTS,aliases:CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,strings:CREATE_COMMANDER_STRING_OPTION_CONTRACTS,repeatables:CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS},update:{parameters:TOOL_UPDATE_OPTION_CONTRACTS,aliases:UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,strings:UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,repeatables:UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS}},WORKSPACE_CONTRACTS_CACHE_PRESERVING_ACTIONS=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function markMcpMutationTransportInput(input){return Object.defineProperty(input,MCP_MUTATION_TRANSPORT,{value:!0,enumerable:!0}),input}function isMcpMutationTransportInput(input){return MCP_MUTATION_TRANSPORT in input}function preserveTransportLiteralOptions(source,options){return isMcpMutationTransportInput(source)?preserveMutationStdinTokenLiterals(options):transferMutationStdinTokenPolicy(source,options)}function mutationOptionsWithOverrides(source,overrides,omittedKeys=[]){const options=transferMutationStdinTokenPolicy(source,{...source,...overrides});for(const key of omittedKeys)Reflect.deleteProperty(options,key);return options}function readRuntimeString(args,key){const value=args[key];return typeof value=="string"&&value.trim().length>0?value:void 0}function readRuntimeScalarString(args,key){const value=args[key];return typeof value=="string"?value.trim().length>0?value:void 0:typeof value=="number"&&Number.isFinite(value)?String(value):void 0}function readRuntimeScalarStringAllowBlank(args,key){const value=args[key];return typeof value=="string"?value:typeof value=="number"&&Number.isFinite(value)?String(value):void 0}function isRuntimeRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function parseRuntimeInteger(value,label){if(typeof value=="number"){if(!Number.isInteger(value))throw new PmCliError(`${label} must be a finite integer.`,EXIT_CODE.USAGE);return value}if(typeof value=="string"&&value.trim().length>0){const parsed=Number(value);if(!Number.isInteger(parsed))throw new PmCliError(`${label} must be a finite integer.`,EXIT_CODE.USAGE);return parsed}}function resolveRuntimeLimit(args,options){return typeof args.limit=="number"&&Number.isFinite(args.limit)?args.limit:typeof options.limit=="number"&&Number.isFinite(options.limit)?options.limit:readRuntimeString(args,"limit")??readRuntimeString(options,"limit")}function actionGlobalOptions(args){const outputFormat=readRuntimeString(args,"outputFormat");return{json:!0,quiet:!0,author:readRuntimeString(args,"author"),path:readRuntimeString(args,"path"),noExtensions:args.noExtensions===!0||args.no_extensions===!0,noPager:!0,outputInclude:readRuntimeString(args,"outputInclude"),outputLimit:readRuntimeScalarString(args,"outputLimit"),outputBudget:readRuntimeScalarString(args,"outputBudget"),outputSession:readRuntimeString(args,"outputSession"),outputCursor:readRuntimeString(args,"outputCursor"),outputFormat:outputFormat==="json"||outputFormat==="toon"?outputFormat:void 0}}const ARRAY_TO_CSV_FIELDS=new Set(["tags","blockedBy","blocked_by","skills","fields"]),SCALAR_TO_ARRAY_FIELDS=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"]),ANNOTATION_SCALAR_TO_ARRAY_FIELDS=new Set([...SCALAR_TO_ARRAY_FIELDS].filter(field=>field!=="file")),ARRAY_ADD_REMOVE_ACTIONS=new Set(["files","files-discover","docs","test","test-all"]),SCALAR_ANNOTATION_SOURCE_ACTIONS=new Set(["comments","notes","learnings"]);function assertMcpAnnotationFileUnavailable(action,options){if(!(!SCALAR_ANNOTATION_SOURCE_ACTIONS.has(action)||!Object.prototype.hasOwnProperty.call(options,"file")))throw new PmCliError(`MCP ${action} does not accept options.file. Pass annotation text in options.add instead.`,EXIT_CODE.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}const LIFECYCLE_AUTHOR_ALIAS_ACTIONS=new Set(["claim","release","start-task","pause-task","close-task"]),HOISTED_ACTION_OPTION_KEYS={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"],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"]},CONTRACT_HOISTED_ACTIONS=new Set(["context","get","list","next","search","comments","notes","learnings","files","docs","test"]),ACTION_OPERAND_KEYS=new Set(["query","keywords","id","text"]);function declaredContractActionOptionKeys(action){return CONTRACT_HOISTED_ACTIONS.has(action)?PM_TOOL_ACTION_PARAMETER_CONTRACTS[action].optional.filter(key=>!ACTION_OPERAND_KEYS.has(key)):[]}const CAMEL_CASE_NORMALIZED_ACTIONS=new Set(["comments","notes","learnings","files","docs","test"]);function camelCaseDeclaredOptions(action,options){if(!CAMEL_CASE_NORMALIZED_ACTIONS.has(action??""))return options;const renamed={...options};for(const key of PM_TOOL_ACTION_PARAMETER_CONTRACTS[action].optional){const snakeKey=key.replace(/[A-Z]/gu,letter=>`_${letter.toLowerCase()}`);snakeKey===key||renamed[snakeKey]===void 0||(renamed[key]??=renamed[snakeKey],delete renamed[snakeKey])}return renamed}function foldAnnotationTextOperand(action,args,normalized){if(!SCALAR_ANNOTATION_SOURCE_ACTIONS.has(action??""))return normalized;const options=normalized,text=options.text??args.text;if(text===void 0)return options;if(options.add!==void 0&&options.add!==text){const noun=action.replace(/s$/u,"");throw new PmCliError(`Specify ${noun} text either as text or with add, not both.`,EXIT_CODE.USAGE,{code:"annotation_text_source_conflict",field:"text",required:`Pass the ${noun} text once: text and add are the same source.`})}const folded={...options,add:text};return delete folded.text,folded}function nestedOptionPresent(nested,key){const snakeKey=key.replace(/[A-Z]/gu,letter=>`_${letter.toLowerCase()}`);return nested[key]!==void 0||nested[snakeKey]!==void 0}function hoistedActionOptionKeys(action){return[...HOISTED_ACTION_OPTION_KEYS[action]??[],...declaredContractActionOptionKeys(action),...UNIVERSAL_READ_OUTPUT_OPTION_KEYS]}const UNIVERSAL_READ_OUTPUT_OPTION_KEYS=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function normalizeMcpOptionsArrays(options,action=""){const result={},promoteAddRemove=ARRAY_ADD_REMOVE_ACTIONS.has(action),preserveStandaloneNote=action==="files"||action==="files-discover"||action==="docs",scalarToArrayFields=SCALAR_ANNOTATION_SOURCE_ACTIONS.has(action)?ANNOTATION_SCALAR_TO_ARRAY_FIELDS:SCALAR_TO_ARRAY_FIELDS;for(const[key,value]of Object.entries(options)){if(Array.isArray(value)&&ARRAY_TO_CSV_FIELDS.has(key)){result[key]=value.join(",");continue}if(key==="note"&&preserveStandaloneNote){result[key]=value;continue}if(typeof value=="string"&&scalarToArrayFields.has(key)){result[key]=[value];continue}if(typeof value=="string"&&promoteAddRemove&&(key==="add"||key==="remove")){result[key]=[value];continue}result[key]=value}return Object.assign(result,Object.fromEntries(Object.getOwnPropertySymbols(options).map(symbol=>[symbol,Reflect.get(options,symbol)]))),result}function resolveMcpActionAuthor(args,options,action){const author=readRuntimeString(args,"author");return author!==void 0?author:action!==void 0&&LIFECYCLE_AUTHOR_ALIAS_ACTIONS.has(action)?readRuntimeString(args,"assignee")??readRuntimeString(options,"assignee"):void 0}function withResolvedAuthor(options,author){return author!==void 0&&options.author===void 0?{...options,author}:options}function hoistedMcpMutationOptions(action,args,nested){const result={},contracts=MCP_MUTATION_OPTION_CONTRACTS[action],parameters=new Set([...contracts.parameters.map(({param})=>param),...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS.map(({param})=>param),...HOISTED_ACTION_OPTION_KEYS[action],...UNIVERSAL_READ_OUTPUT_OPTION_KEYS,"force"]);for(const param of parameters){const keys=contracts.aliases.find(contract=>contract.keys.includes(param))?.keys??[param];args[param]===void 0||keys.some(key=>nested[key]!==void 0)||(result[param]=args[param])}return result}function refuseMcpMutationValue(action,field){throw new PmCliError(`Invalid MCP ${action} value for "${field}". No changes were made.`,EXIT_CODE.USAGE,{code:"invalid_argument_value",reason:"invalid_mutation_option_value",changed:!1,field,required:`Provide valid ${action} field values and an options object; inspect the pm_${action} input schema for supported types.`})}function assertMcpMutationBooleans(action,args,options){const contracts=MCP_MUTATION_OPTION_CONTRACTS[action],parameters=[...contracts.parameters,...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,{param:"force"}];for(const{param}of parameters){if(asRecordClone(PM_TOOL_PARAMETER_PROPERTIES[param]).type!=="boolean")continue;const invalid=(contracts.aliases.find(contract=>contract.keys.includes(param))?.keys??[param]).find(key=>options[key]!==void 0&&typeof options[key]!="boolean");invalid!==void 0&&refuseMcpMutationValue(action,invalid)}for(const key of["idOnly","fullChangedFields"])args[key]!==void 0&&typeof args[key]!="boolean"&&refuseMcpMutationValue(action,key)}function checkedMcpMutationOptions(action,args,options){args.options!==void 0&&!isRuntimeRecord(args.options)&&refuseMcpMutationValue(action,"options"),assertMcpMutationBooleans(action,args,options);for(const key of ARRAY_TO_CSV_FIELDS){const value=options[key];Array.isArray(value)&&value.some(entry=>typeof entry!="string")&&refuseMcpMutationValue(action,key)}const normalized=normalizeMcpMutationOptions(options,action),contracts=MCP_MUTATION_OPTION_CONTRACTS[action];for(const{keys,target}of contracts.strings)keys.some(key=>options[key]!==void 0)&&normalized[target]===void 0&&refuseMcpMutationValue(action,target);const invalidRepeatable=contracts.repeatables.flatMap(({keys})=>keys).find(key=>{const value=options[key];return value!==void 0&&typeof value!="string"&&(!Array.isArray(value)||value.some(entry=>typeof entry!="string"))});return invalidRepeatable!==void 0&&refuseMcpMutationValue(action,invalidRepeatable),normalized}function normalizedActionOptions(args,action,hoisted,nested){const mcpMutation=(action==="create"||action==="update")&&isMcpMutationTransportInput(args),options={...mcpMutation?hoistedMcpMutationOptions(action,args,nested):hoisted,...nested};if((action==="create"||action==="update")&&!mcpMutation){const cli=isRuntimeRecord(args.options)&&isCliMutationInput(args.options);cli||foldNullClearsIntoUnset(action,options),assertNativeMutationValueTypes(action,options,!0,cli)}return mcpMutation?checkedMcpMutationOptions(action,args,options):normalizeMcpOptionsArrays(options,action)}function literalActionOptions(action,options){return!LITERAL_MUTATION_ACTIONS.has(action??"")||isCliMutationInput(options)?options:withLiteralMutationInput(options)}function optionsWithAuthor(args,action){assertMutationItemOperand(action,args);const sourceOptions=isRuntimeRecord(args.options)?args.options:void 0,baseOptions=asRecordClone(args.options),hoistedTopLevel={},hoistKey=key=>{nestedOptionPresent(baseOptions,key)||args[key]===void 0||(hoistedTopLevel[key]=args[key])};for(const key of hoistedActionOptionKeys(action??""))hoistKey(key);action!==void 0&&isMcpMutationTransportInput(args)&&assertMcpAnnotationFileUnavailable(action,baseOptions);const options=foldAnnotationTextOperand(action,args,camelCaseDeclaredOptions(action,normalizedActionOptions(args,action,hoistedTopLevel,baseOptions)));if(action==="history-attest"&&isMcpMutationTransportInput(args)&&(options.output!==void 0||typeof options.verify=="string"))throw new PmCliError("MCP history attest does not accept server-local proof paths. Export the returned JSON bundle and pass that JSON object as verify.",EXIT_CODE.USAGE);const stdinPolicySource=isMcpMutationTransportInput(args)?args:sourceOptions??args,resolved=preserveTransportLiteralOptions(stdinPolicySource,withResolvedAuthor(options,resolveMcpActionAuthor(args,options,action)));return literalActionOptions(action,resolved)}function withAddNoteOption(options){if(options.addNote===void 0)return options;const next={...options};return next.note===void 0&&typeof next.addNote=="string"&&(next.note=next.addNote),delete next.addNote,next}function withFilesDiscoveryOptions(options){const next={...options};return next.discoveryNote!==void 0&&next.note===void 0&&typeof next.discoveryNote=="string"&&(next.note=next.discoveryNote),delete next.discover,delete next.discoveryNote,next}function normalizeActionName(value){const chunks=[];let lastWasSeparator=!0;for(const character of value.trim().toLowerCase()){if(character>="a"&&character<="z"||character>="0"&&character<="9"){chunks.push(character),lastWasSeparator=!1;continue}lastWasSeparator||(chunks.push("-"),lastWasSeparator=!0)}return chunks.at(-1)==="-"&&chunks.pop(),chunks.join("")}function shouldInvalidateWorkspaceContractsCacheAfterAction(action){return!WORKSPACE_CONTRACTS_CACHE_PRESERVING_ACTIONS.has(normalizeActionName(action))}function normalizeCommandPath(value){return value.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function readRuntimeStringArray(value){return Array.isArray(value)?value.map(entry=>String(entry)).filter(entry=>entry.length>0):[]}function extensionOptionsFromArgs(args,options){const reserved=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),passthrough={};for(const[key,value]of Object.entries(args))reserved.has(key)||(passthrough[key]=value);const normalizedOptions={...passthrough,...options};return delete normalizedOptions.args,delete normalizedOptions.author,normalizedOptions}function withMutationCompaction(args,options){const runnerOptions=preserveTransportLiteralOptions(options??{},{...options});return{changedFields:args.fullChangedFields===!0?"full":"compact",idOnly:args.idOnly===!0,runnerOptions}}function mutationListOptions(options){return{type:readRuntimeScalarString(options,"filterType"),tag:readRuntimeScalarString(options,"filterTag"),priority:readRuntimeScalarString(options,"filterPriority"),deadlineBefore:readRuntimeScalarString(options,"filterDeadlineBefore"),deadlineAfter:readRuntimeScalarString(options,"filterDeadlineAfter"),updatedAfter:readRuntimeScalarString(options,"filterUpdatedAfter"),updatedBefore:readRuntimeScalarString(options,"filterUpdatedBefore"),createdAfter:readRuntimeScalarString(options,"filterCreatedAfter"),createdBefore:readRuntimeScalarString(options,"filterCreatedBefore"),ids:normalizeBulkIdsValue(options.ids),assignee:readRuntimeScalarString(options,"filterAssignee"),assigneeFilter:readRuntimeScalarString(options,"filterAssigneeFilter")??readRuntimeScalarString(options,"filterAssignee_filter"),parent:readRuntimeScalarString(options,"filterParent"),sprint:readRuntimeScalarString(options,"filterSprint"),release:readRuntimeScalarString(options,"filterRelease"),limit:readRuntimeScalarString(options,"limit"),offset:readRuntimeScalarString(options,"offset")}}function readGraphIdListOption(value){if(typeof value=="string"&&value.trim().length>0)return value;if(Array.isArray(value))return readRuntimeStringArray(value)}function readGraphBoundOption(value){if(typeof value=="number"&&Number.isFinite(value)||typeof value=="string"&&value.trim().length>0)return value}function graphOptionsFromFlat(options){const kind=readGraphIdListOption(options.kind),exemptIsolate=readGraphIdListOption(options.exemptIsolate),exemptIsolateType=readGraphIdListOption(options.exemptIsolateType);return{...kind===void 0?{}:{kind},maxDepth:readGraphBoundOption(options.maxDepth),limit:readGraphBoundOption(options.limit),after:readRuntimeString(options,"after"),direction:readRuntimeString(options,"direction"),maxPaths:readGraphBoundOption(options.maxPaths),sample:readGraphBoundOption(options.sample),...exemptIsolate===void 0?{}:{exemptIsolate},...exemptIsolateType===void 0?{}:{exemptIsolateType},saveBaseline:options.saveBaseline===!0,rebuild:options.rebuild===!0,clear:options.clear===!0,summary:options.summary===!0,...options.full===!0?{full:!0}:{}}}function normalizeBulkMutationListOptions(options){const normalized=normalizeListOptions(options);return options.ids!==void 0&&(normalized.ids=normalizeBulkIdsValue(options.ids)),normalized}function closeManyOptionsFromFlat(options){return{status:readRuntimeString(options,"filterStatus"),list:isRuntimeRecord(options.list)?normalizeBulkMutationListOptions(options.list):mutationListOptions(options),reason:readRuntimeString(options,"reason"),completedAt:readRuntimeString(options,"completedAt")??readRuntimeString(options,"completed_at"),resolution:readRuntimeString(options,"resolution"),expectedResult:readRuntimeString(options,"expectedResult")??readRuntimeString(options,"expected_result")??readRuntimeString(options,"expected"),actualResult:readRuntimeString(options,"actualResult")??readRuntimeString(options,"actual_result")??readRuntimeString(options,"actual"),validateClose:readRuntimeString(options,"validateClose")??readRuntimeString(options,"validate_close"),author:readRuntimeString(options,"author"),message:readRuntimeString(options,"message"),force:options.force===!0?!0:void 0,dryRun:options.dryRun===!0||options.dry_run===!0?!0:void 0,rollback:resolveCheckpointRollbackId(options.rollback),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1:void 0}}const UPDATE_MANY_FLAT_CONTROL_KEYS=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 updateManyUpdateOptionsFromFlat(options){const update={};for(const[key,value]of Object.entries(options))UPDATE_MANY_FLAT_CONTROL_KEYS.has(key)||(update[key]=value);return normalizeMcpUpdateOptions(update)}function normalizeMcpUpdateOptions(options){return normalizeMcpMutationOptions(options,"update")}function normalizeMcpMutationOptions(options,action){const normalizedInput=normalizeMcpOptionsArrays(options,action),contracts=MCP_MUTATION_OPTION_CONTRACTS[action],booleanishKeys=new Set([...contracts.parameters,...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS].filter(({booleanish})=>booleanish===!0).map(({param})=>param));for(const{keys}of contracts.repeatables)for(const key of keys)typeof normalizedInput[key]=="string"&&(normalizedInput[key]=[normalizedInput[key]]);for(const contract of contracts.strings)for(const key of contract.keys){const value=normalizedInput[key];(typeof value=="number"&&Number.isFinite(value)||value===!1&&booleanishKeys.has(key))&&(normalizedInput[key]=String(value))}return action==="create"?{...normalizeCreateOptions(normalizedInput,{requireType:!1})}:normalizeUpdateOptions(normalizedInput)}function updateManyOptionsFromFlat(options){if(isRuntimeRecord(options.list)||isRuntimeRecord(options.update)){const updateSource=isRuntimeRecord(options.update)?options.update:updateManyUpdateOptionsFromFlat(options),normalizedUpdate=preserveTransportLiteralOptions(options,normalizeMcpUpdateOptions(updateSource));return{status:readRuntimeScalarString(options,"filterStatus"),list:isRuntimeRecord(options.list)?normalizeBulkMutationListOptions(options.list):mutationListOptions(options),update:overlayMutationStdinTokenPolicy(updateSource,normalizedUpdate),dryRun:options.dryRun===!0||options.dry_run===!0?!0:void 0,rollback:resolveCheckpointRollbackId(options.rollback),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1:void 0}}return{status:readRuntimeScalarString(options,"filterStatus"),list:mutationListOptions(options),update:preserveTransportLiteralOptions(options,updateManyUpdateOptionsFromFlat(options)),dryRun:options.dryRun===!0||options.dry_run===!0?!0:void 0,rollback:resolveCheckpointRollbackId(options.rollback),checkpoint:options.checkpoint===!1||options.noCheckpoint===!0||options.no_checkpoint===!0?!1:void 0}}function hasExpectHashKey(record){return"expectHash"in record||"expect_hash"in record}function splitExpectHashInput(args){if(!hasExpectHashKey(args)&&!(isRuntimeRecord(args.options)&&hasExpectHashKey(args.options)))return{expectHash:void 0,dispatchArgs:args};const{expectHash,expect_hash:alias,...rest}=args,options=isRuntimeRecord(rest.options)?rest.options:{},{expectHash:nested,expect_hash:nestedAlias,...nestedRest}=options,supplied=[expectHash,alias,nested,nestedAlias].filter(candidate=>candidate!==void 0),merged=supplied.length>1?supplied.flatMap(candidate=>Array.isArray(candidate)?candidate:[candidate]):supplied[0],dispatchArgs=transferMutationStdinTokenPolicy(args,"options"in rest?{...rest,options:isRuntimeRecord(rest.options)?transferMutationStdinTokenPolicy(rest.options,nestedRest):rest.options}:rest);return{expectHash:merged,dispatchArgs}}export{HOISTED_ACTION_OPTION_KEYS,actionGlobalOptions,closeManyOptionsFromFlat,extensionOptionsFromArgs,graphOptionsFromFlat,isMcpMutationTransportInput,isRuntimeRecord,markMcpMutationTransportInput,mutationListOptions,mutationOptionsWithOverrides,normalizeActionName,normalizeCommandPath,normalizeMcpOptionsArrays,normalizeMcpUpdateOptions,optionsWithAuthor,parseRuntimeInteger,readRuntimeScalarString,readRuntimeScalarStringAllowBlank,readRuntimeString,readRuntimeStringArray,resolveRuntimeLimit,shouldInvalidateWorkspaceContractsCacheAfterAction,splitExpectHashInput,updateManyOptionsFromFlat,updateManyUpdateOptionsFromFlat,withAddNoteOption,withFilesDiscoveryOptions,withMutationCompaction};
2
2
  //# sourceMappingURL=runtime-input.js.map
@@ -120,10 +120,12 @@ export type PackageCommandOptions = ExtensionCommandOptions;
120
120
  export type PackageCommandResult = ExtensionCommandResult;
121
121
  export type { Dependency,ItemDocument,ItemMetadata,ItemStatus,ItemType,LinkedDoc,LinkedFile,LinkedTest,LogNote,PmSettings } from "../types/index.js";
122
122
  export type { ClaimNextOptions,CloseTaskResult,GetContractsOptions,PauseTaskResult,PmActionInput,PmActionName,PmActionOptions,PmClientCloseActionOptions,PmClientFullMutationOptions,PmClientMutationOptions,PmClientOptions,PmClientRunArgs,SchemaResult,StartTaskResult,WorkspaceContracts,WorkspaceContractsOptions } from "./runtime-public-contracts.js";
123
- type ReadOptions<Options> = Options & PmReadOutputOptions;
123
+ /** Command options of a read method combined with the universal read-output controls. */
124
+ export type ReadOptions<Options> = Options & PmReadOutputOptions;
124
125
  /** Omitted options carry neither producer cursors nor explicit budget controls. */
125
- type InitialReadOptions = Record<never,never>;
126
- type ReadPromise<Result,Options> = Promise<PmReadOutputResultFor<Result,Options>>;
126
+ export type InitialReadOptions = Record<never,never>;
127
+ /** Promise a PmClient read method returns, typed by the read-output projection its options request. */
128
+ export type ReadPromise<Result,Options> = Promise<PmReadOutputResultFor<Result,Options>>;
127
129
  /**
128
130
  * Programmatic pm client for custom tools, CI jobs, bots, and embedded runtimes.
129
131
  *
@@ -682,3 +684,24 @@ var __pmCliActionRunnerTestHooks:typeof actionRunnerTestHooks | undefined;
682
684
  export type { ContractsCommandOptions,ContractsResult };
683
685
  export { readRequiredString } from "./runtime/context.js";
684
686
  export type { AppendCommandOptions,AppendResult,CommentsCommandOptions,CommentsResult,ConfigCommandOptions,ConfigResult,DepsCommandOptions,DepsResult,DocsCommandOptions,DocsResult,ExtensionCommandOptions,ExtensionCommandResult,FilesCommandOptions,FilesDiscoverOptions,FilesDiscoverResult,FilesLookupOptions,FilesLookupResult,FilesResult,GcCommandOptions,GcResult,HealthResult,InitCommandOptions,InitResult,LearningsCommandOptions,LearningsResult,NotesCommandOptions,NotesResult,ProfileApplyCommandOptions,ProfileApplyResult,ProfileLintResult,ProfileListResult,ProfileResult,ProfileShowResult,ProfileSubcommand,RunHealthOptions,RunSchemaEvolutionMigrationOptions,SchemaAddFieldCommandOptions,SchemaAddFieldResult,SchemaAddStatusCommandOptions,SchemaAddStatusResult,SchemaAddTypeCommandOptions,SchemaAddTypeInferCommandOptions,SchemaAddTypeInferResult,SchemaAddTypeResult,SchemaApplyPresetCommandOptions,SchemaApplyPresetResult,SchemaEvolutionMigrationRequest,SchemaEvolutionMigrationResult,SchemaInspectResult,SchemaListFieldsResult,SchemaListResult,SchemaRemoveFieldCommandOptions,SchemaRemoveFieldResult,SchemaRemoveStatusCommandOptions,SchemaRemoveStatusResult,SchemaRemoveTypeCommandOptions,SchemaRemoveTypeResult,SchemaShowFieldResult,SchemaShowResult,SchemaShowStatusResult,SchemaSubcommand,UpgradeCommandOptions,UpgradeResult,ValidateCommandOptions,ValidateCountsResult,ValidateResult };
687
+ export type { ExtensionRegistrationRegistry,OnReadHookContext,OnWriteHookContext } from "../core/extensions/extension-types.js";
688
+ export type { HistoryHashAlgorithm } from "../core/history/digest.js";
689
+ export type { ItemDocumentFormatOptions } from "../core/item/item-format.js";
690
+ export type { ItemTypeRegistry } from "../core/item/type-registry.js";
691
+ export type { AcquireLockOptions } from "../core/lock/lock.js";
692
+ export type { RuntimeFieldRegistry,RuntimeStatusRegistry } from "../core/schema/runtime-schema.js";
693
+ export type { AuthorSource } from "../core/shared/author.js";
694
+ export type { LocatedItem } from "../core/store/item-store.js";
695
+ export type { BackgroundLogStream,BackgroundTestRunStatus } from "../core/test/background-runs.js";
696
+ export type { ConfidenceTextLevel,HistoryEntry,ItemFormat,RuntimeSchemaSettings } from "../types.js";
697
+ export type { GraphSubcommand } from "./cli-contracts/enum-contracts.js";
698
+ export type { PmCreateActionOptions,PmUpdateActionOptions } from "./cli-contracts/typed-action-inputs.js";
699
+ export type { CompletionRuntimeConfig } from "./completion/shared.js";
700
+ export type { ValidateCheck } from "./governance/validate.js";
701
+ export type { GraphCommandOptions,GraphResult } from "./graph/run.js";
702
+ export type { HistoryCompactBulkCommandOptions,HistoryCompactBulkResult,HistoryCompactCommandOptions,HistoryCompactResult } from "./history-compact.js";
703
+ export type { HistoryRedactCommandOptions,HistoryRedactResult } from "./history-redact.js";
704
+ export type { HistoryRepairAllResult,HistoryRepairCommandOptions,HistoryRepairResult } from "./history-repair.js";
705
+ export type { ClaimNextResult } from "./lifecycle/claim.js";
706
+ export type { UpdateOperationOptions } from "./lifecycle/update.js";
707
+ export type { CalendarOutputFormat } from "./query/calendar.js";