@unbrained/pm-cli 2026.12.2 → 2026.12.3

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 (157) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/commander-usage.js +4 -4
  3. package/dist/cli/expected-revisions.js +1 -1
  4. package/dist/cli/extension-command-help.js +4 -4
  5. package/dist/cli/main.js +5 -5
  6. package/dist/cli/runtime/invocation-rewrites.js +1 -1
  7. package/dist/cli/runtime-field-commands.js +2 -0
  8. package/dist/cli-bundle/bundle-manifest.json +1 -1
  9. package/dist/cli-bundle/chunks/chunk-3ESBFEQC.js +2 -0
  10. package/dist/cli-bundle/chunks/chunk-46AZP5QW.js +2 -0
  11. package/dist/cli-bundle/chunks/{chunk-OBPO6V7H.js → chunk-5WTBF4M4.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-3KEMIPKG.js → chunk-6TOZQ5BQ.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-4YYFY33T.js → chunk-AHVOEE7F.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-CQHB3ZZH.js +2 -0
  15. package/dist/cli-bundle/chunks/chunk-DZPOS3YT.js +2 -0
  16. package/dist/cli-bundle/chunks/{chunk-ROTEELDL.js → chunk-E5ADC3HT.js} +65 -65
  17. package/dist/cli-bundle/chunks/{chunk-SY5C3U32.js → chunk-E5HO7HWP.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-3HKPVOAN.js → chunk-EDJ3KR2H.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-TKUG2X24.js → chunk-FWQNWPIV.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-7NAO7I75.js → chunk-H4U3LEOD.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-MZZ4ZJ5Z.js → chunk-HNMED75Y.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-SDXCJZKB.js → chunk-HPCMM74Q.js} +22 -22
  23. package/dist/cli-bundle/chunks/{chunk-WSEIEDEK.js → chunk-ITM4AMVM.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-Q6K7HWZ7.js → chunk-IW4A3I4N.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-7V65VACG.js → chunk-JJ73G5UT.js} +2 -2
  26. package/dist/cli-bundle/chunks/chunk-L4HMFRHB.js +2 -0
  27. package/dist/cli-bundle/chunks/{chunk-GOEQXVOI.js → chunk-LTQWPQ7H.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-UNBW2LF3.js → chunk-MRT3ADO4.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-ZL6J6JYT.js → chunk-PBMLIV74.js} +2 -2
  30. package/dist/cli-bundle/chunks/{chunk-G6TARHFK.js → chunk-PJMGWJKU.js} +2 -2
  31. package/dist/cli-bundle/chunks/chunk-Q2HMDV56.js +9 -0
  32. package/dist/cli-bundle/chunks/{chunk-OXC5KBIQ.js → chunk-RRBNCL63.js} +2 -2
  33. package/dist/cli-bundle/chunks/{chunk-CBUC4X7Q.js → chunk-TDOF7BKO.js} +3 -3
  34. package/dist/cli-bundle/chunks/chunk-UXEZXGAD.js +113 -0
  35. package/dist/cli-bundle/chunks/{chunk-PCDTWL6V.js → chunk-W7HA65EO.js} +2 -2
  36. package/dist/cli-bundle/chunks/{chunk-I4SPJQQI.js → chunk-XGNUDSCG.js} +3 -3
  37. package/dist/cli-bundle/chunks/{chunk-AHV3CSQG.js → chunk-XKJ5NWQ7.js} +2 -2
  38. package/dist/cli-bundle/chunks/{field-option-collisions-BBGTV7AD.js → field-option-collisions-DXKTKW6J.js} +2 -2
  39. package/dist/cli-bundle/chunks/item-revision-DXEF4XBU.js +2 -0
  40. package/dist/cli-bundle/chunks/item-transaction-EANA7V4W.js +2 -0
  41. package/dist/cli-bundle/chunks/{linked-resource-value-list-ZBIY4H23.js → linked-resource-value-list-5JRGUDUB.js} +2 -2
  42. package/dist/cli-bundle/chunks/{mutation-actor-NHN33ITJ.js → mutation-actor-S5G7FMNG.js} +2 -2
  43. package/dist/cli-bundle/chunks/{mutation-admission-PGKJTCG6.js → mutation-admission-HQVNPOXV.js} +2 -2
  44. package/dist/cli-bundle/chunks/{register-list-query-7S5QWDTI.js → register-list-query-SQF5PSJ4.js} +2 -2
  45. package/dist/cli-bundle/chunks/{register-mutation-EK6DVIQK.js → register-mutation-4AQ4CEBL.js} +2 -2
  46. package/dist/cli-bundle/chunks/{register-operations-6MURXE4V.js → register-operations-76P7OM4P.js} +2 -2
  47. package/dist/cli-bundle/chunks/{register-setup-RW26X3GJ.js → register-setup-T6OEOZK3.js} +2 -2
  48. package/dist/cli-bundle/chunks/{stage-4ZCF74G4.js → stage-KUICZHSF.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{chunk-4SCFAWAW.js → chunk-3LHBKFPD.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/chunk-4DDXERKN.js +2 -0
  51. package/dist/cli-bundle/focused-chunks/{chunk-JPZGC3W4.js → chunk-4YU75CWI.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/{chunk-TXTPAFHJ.js → chunk-5JQVPQMN.js} +2 -2
  53. package/dist/cli-bundle/focused-chunks/{chunk-KNBGHCIP.js → chunk-5Z4DXYBZ.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/chunk-7DOP5HEZ.js +44 -0
  55. package/dist/cli-bundle/focused-chunks/{chunk-TR22GU7M.js → chunk-AX4RBJ7B.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-7A6SEZEY.js → chunk-BEHQCHQV.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/chunk-BUIF6CMZ.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-E2IWEJL5.js +3 -0
  59. package/dist/cli-bundle/focused-chunks/chunk-GBU7GKNJ.js +2 -0
  60. package/dist/cli-bundle/focused-chunks/{chunk-EQCQTYKO.js → chunk-K35KTBDZ.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{chunk-VQIC3UZB.js → chunk-KNST4PGF.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/{chunk-P2H3GTJK.js → chunk-L2XJB5PK.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/chunk-L6NOGC4N.js +100 -0
  64. package/dist/cli-bundle/focused-chunks/{chunk-VK3IE3TS.js → chunk-LWIIDPAV.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{chunk-6IY5CVGJ.js → chunk-M54BMYG4.js} +2 -2
  66. package/dist/cli-bundle/focused-chunks/{chunk-6BKT6XQN.js → chunk-NEK7RX3N.js} +2 -2
  67. package/dist/cli-bundle/focused-chunks/{chunk-BHNBPCHP.js → chunk-OKGWIW6C.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/{chunk-2DGKVXFT.js → chunk-RFDSSOTZ.js} +2 -2
  69. package/dist/cli-bundle/focused-chunks/chunk-SSX5YBDC.js +2 -0
  70. package/dist/cli-bundle/focused-chunks/{chunk-OG57ESZK.js → chunk-TIEQVIFN.js} +2 -2
  71. package/dist/cli-bundle/focused-chunks/{chunk-3COWDIPX.js → chunk-VEUBDQDP.js} +2 -2
  72. package/dist/cli-bundle/focused-chunks/{chunk-2UWKU2BQ.js → chunk-WDHNPNHX.js} +3 -3
  73. package/dist/cli-bundle/focused-chunks/{field-option-collisions-2C6DLUC4.js → field-option-collisions-32X7FP3H.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/item-revision-GUYSVVQD.js +2 -0
  75. package/dist/cli-bundle/focused-chunks/{item-transaction-LQLQLZE7.js → item-transaction-MLKHZPL7.js} +2 -2
  76. package/dist/cli-bundle/focused-chunks/{mutation-actor-DJMZUIZI.js → mutation-actor-RDZJTRW2.js} +2 -2
  77. package/dist/cli-bundle/focused-chunks/{mutation-admission-SDWQVVHN.js → mutation-admission-IQB6XL75.js} +2 -2
  78. package/dist/cli-bundle/focused-chunks/{stage-QBZIK3T5.js → stage-AA7LORZ2.js} +2 -2
  79. package/dist/cli-bundle/main.js +27 -27
  80. package/dist/cli-bundle/sdk-authoring.js +1 -1
  81. package/dist/cli-bundle/sdk-contracts.js +1 -1
  82. package/dist/cli-bundle/sdk-core.js +1 -1
  83. package/dist/cli-bundle/sdk-governance.js +1 -1
  84. package/dist/cli-bundle/sdk-graph.js +1 -1
  85. package/dist/cli-bundle/sdk-merge.js +63 -63
  86. package/dist/cli-bundle/sdk-query.js +1 -1
  87. package/dist/cli-bundle/sdk-runtime.js +1 -1
  88. package/dist/cli-bundle/sdk-testing.js +1 -1
  89. package/dist/cli-bundle/sdk.js +9 -9
  90. package/dist/core/extensions/loader.d.ts +8 -0
  91. package/dist/core/extensions/loader.js +1 -1
  92. package/dist/core/item/actionability.js +1 -1
  93. package/dist/core/output/output.js +16 -16
  94. package/dist/mcp/server.js +1 -1
  95. package/dist/sdk/cli-contracts/enum-contracts.d.ts +25 -1
  96. package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
  97. package/dist/sdk/cli-contracts/flag-contracts.d.ts +1 -1
  98. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  99. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  100. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  101. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  102. package/dist/sdk/context-intent-contracts.js +1 -1
  103. package/dist/sdk/lifecycle/expect-hash-admission.d.ts +27 -8
  104. package/dist/sdk/lifecycle/expect-hash-admission.js +1 -1
  105. package/dist/sdk/lifecycle/item-revision.d.ts +12 -4
  106. package/dist/sdk/lifecycle/item-revision.js +1 -1
  107. package/dist/sdk/output-projection.d.ts +1 -1
  108. package/dist/sdk/output-projection.js +1 -1
  109. package/dist/sdk/public-surface.json +1 -1
  110. package/dist/sdk/read-output/surfaces.js +1 -1
  111. package/dist/sdk/runtime/schema.js +1 -1
  112. package/dist/sdk/runtime-input.d.ts +6 -0
  113. package/dist/sdk/runtime-input.js +1 -1
  114. package/dist/sdk/runtime-primitives.d.ts +1 -1
  115. package/dist/sdk/runtime-primitives.js +1 -1
  116. package/dist/sdk/runtime.js +1 -1
  117. package/docs/COMMANDS.md +23 -5
  118. package/docs/EXTENSIONS.md +1 -1
  119. package/docs/SDK.md +15 -2
  120. package/marketplace.json +1 -1
  121. package/package.json +1 -1
  122. package/packages/pm-beads/package.json +1 -1
  123. package/packages/pm-calendar/package.json +1 -1
  124. package/packages/pm-command-kit/package.json +1 -1
  125. package/packages/pm-digital-twin/package.json +1 -1
  126. package/packages/pm-governance-audit/package.json +1 -1
  127. package/packages/pm-guide-shell/package.json +1 -1
  128. package/packages/pm-kanban/package.json +1 -1
  129. package/packages/pm-lifecycle-hooks/package.json +1 -1
  130. package/packages/pm-linked-test-adapters/package.json +1 -1
  131. package/packages/pm-search-advanced/package.json +1 -1
  132. package/packages/pm-templates/package.json +1 -1
  133. package/packages/pm-todos/package.json +1 -1
  134. package/packages/pm-vcs/package.json +1 -1
  135. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  136. package/plugins/pm-claude/package.json +1 -1
  137. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  138. package/plugins/pm-codex/package.json +1 -1
  139. package/plugins/pm-codex/plugin.json +1 -1
  140. package/runtime-dependencies.json +1 -1
  141. package/dist/cli-bundle/chunks/chunk-A5ZEMOVR.js +0 -2
  142. package/dist/cli-bundle/chunks/chunk-C6WM6ZN4.js +0 -9
  143. package/dist/cli-bundle/chunks/chunk-HZZLSBIJ.js +0 -2
  144. package/dist/cli-bundle/chunks/chunk-L2ZSSMYY.js +0 -2
  145. package/dist/cli-bundle/chunks/chunk-NRQCBUYD.js +0 -113
  146. package/dist/cli-bundle/chunks/chunk-QDV7S2QS.js +0 -2
  147. package/dist/cli-bundle/chunks/chunk-V2S4XAX3.js +0 -2
  148. package/dist/cli-bundle/chunks/item-revision-3LENTXYF.js +0 -2
  149. package/dist/cli-bundle/chunks/item-transaction-56J5OCHA.js +0 -2
  150. package/dist/cli-bundle/focused-chunks/chunk-HTDYNY4L.js +0 -2
  151. package/dist/cli-bundle/focused-chunks/chunk-J72TRWR5.js +0 -44
  152. package/dist/cli-bundle/focused-chunks/chunk-N64AC5G6.js +0 -100
  153. package/dist/cli-bundle/focused-chunks/chunk-QZRYGYTI.js +0 -2
  154. package/dist/cli-bundle/focused-chunks/chunk-SQMOF65W.js +0 -2
  155. package/dist/cli-bundle/focused-chunks/chunk-T3ILWAEV.js +0 -2
  156. package/dist/cli-bundle/focused-chunks/chunk-W4JMV7GF.js +0 -3
  157. package/dist/cli-bundle/focused-chunks/item-revision-723XCQPS.js +0 -2
@@ -1,2 +1,2 @@
1
- import{normalizeUniqueStringList as U}from"./string-lists.js";import{PM_EXPECT_HASH_ACTIONS as W,PM_TOOL_ACTIONS as h}from"./enum-contracts.js";import{TOOL_CREATE_OPTION_CONTRACTS as K,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS as E,TOOL_UPDATE_OPTION_CONTRACTS as Y,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS as j,TOOL_CONTEXT_OPTION_CONTRACTS as G,TOOL_ACTIVITY_OPTION_CONTRACTS as H,TOOL_LIST_FILTER_OPTION_CONTRACTS as $,TOOL_AGGREGATE_OPTION_CONTRACTS as B,TOOL_SEARCH_FILTER_OPTION_CONTRACTS as z,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS as J}from"./tool-option-contracts.js";import{PM_TOOL_PARAMETER_PROPERTIES as R,PM_TOOL_PARAMETER_METADATA as V,PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES as X,PM_TOOL_ACTION_SCOPED_PARAMETER_METADATA as Z,PLAN_ACTION_PARAMETER_PROPERTIES as _,PLAN_ACTION_PARAMETER_METADATA as g}from"./tool-parameter-tables.js";import{toUniqueFlagContracts as Q,withFlagAliasMetadata as ee}from"./flag-contracts.js";import{resolveReadOutputSurface as te}from"../read-output-contracts.js";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS as re,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS as oe}from"./commander-mutation-options.js";const ae={...X,"history-attest":{verify:{type:"object",additionalProperties:!0},output:{not:{}}}},y={...R,pause:{type:"boolean"},handoff:{type:"string"},releaseAssignment:{type:"boolean"},hashAlgorithm:{type:"string",enum:["sha256","sha512"]}},u={...V,pause:{description:"Return work to its configured open status before releasing ownership."},handoff:{description:"Release into a configured non-terminal queue with a required evidence message."},releaseAssignment:{description:"Release assignment after recording closure evidence."},hashAlgorithm:{description:"Digest for detached history bundles; defaults to sha256."}},ne=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],ie=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],se=new Set(["action","cwd","options",...Object.keys(y).filter(e=>e!=="severity")]);function ke(e){const t=e.trim().toLowerCase();let r="";for(let o=0;o<t.length;o+=1){const a=t[o];if(a!=="-"&&a!=="_"){r+=a;continue}let n=o+1;for(;t[n]==="-"||t[n]==="_";)n+=1;const i=t[n];if(i!==void 0&&(i>="a"&&i<="z"||i>="0"&&i<="9")){r+=i.toUpperCase(),o=n;continue}r+=t.slice(o,n),o=n-1}return se.has(r)?{field:e,property:r,owner:"mcp_tool_input",nested_path:r==="expectHash"?`options.field (${e}=<value>)`:`options.${r}`}:void 0}const le={create:["fullChangedFields","idOnly"],copy:["fullChangedFields","idOnly"],update:["fullChangedFields","idOnly"],"item-reopen":["fullChangedFields","idOnly"],close:["fullChangedFields","idOnly"],claim:["fullChangedFields","idOnly"],release:["fullChangedFields","idOnly"],"start-task":["fullChangedFields","idOnly"],"pause-task":["fullChangedFields","idOnly"],"close-task":["fullChangedFields","idOnly"],restore:["fullChangedFields","idOnly"],append:["fullChangedFields"],"update-many":["fullChangedFields"],"close-many":["fullChangedFields"],assurance:["fullChangedFields","idOnly"]},de=["createMode","status","deadline","estimate","acceptanceCriteria","definitionOfReady","order","rank","goal","objective","value","impact","outcome","whyNow","assignee","reviewer","risk","confidence","sprint","release","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact","comment","note","learning","reminder","event","typeOption"],ce=Object.freeze({"close-many":["list","expected_result","expected","actual_result","actual","validate_close","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],"update-many":["list","update","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],...Object.fromEntries(h.filter(e=>e==="upgrade"||e==="install"||e==="extension"||e==="package"||e.startsWith("extension-")||e.startsWith("package-")).map(e=>[e,["project","local","global"]]))});function s(e){return U(e)}const pe=s([...K.map(e=>e.param),...E.map(e=>e.param)]),v=s([...Y.map(e=>e.param),...E.map(e=>e.param),"force"]),ue=s([...j.map(e=>e.param),...v.filter(e=>e!=="allowMissingParent"&&e!=="completedAt"),"dryRun","rollback","noCheckpoint"]),me=s([...J.map(e=>e.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),C=s([...G.map(e=>e.param),"past","section"]),fe=s([...H.map(e=>e.param),"stream"]),A=s([...$.map(e=>e.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),c=A.filter(e=>e!=="all"&&e!=="status"),d=[[{property:"today",schema:{const:!0}},{property:"recent",schema:{const:!0}}],[{property:"today",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}],[{property:"recent",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}]],ye=[[{property:"summary",schema:{const:!0}},{property:"schemaOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"flagsOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}]],Oe=s([...B.map(e=>e.param),"count","completion","includeUnparented"]),he=s(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...z.map(e=>e.param)]),P=s(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","includeGates","includeContainers","tokenBudget","explainRanking"]),l=["author","message","force"],Ae=["releaseAssignment","text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],m=["author","assignee","message","force"],Te=["dryRun","target","scope","capability","declarative","github","ref","init","install","uninstall","explore","manage","offline","describe","markdown","output","reload","doctor","catalog","list","adopt","adoptAll","activate","deactivate","runtimeProbe","fixManagedState","isolated","ignoreGlobal","detail","trace","watch","strictExit","failOnWarn","fields"];function b(e){return{[`${e}-init`]:{required:["target"],optional:["scope","capability",...e==="package"?["declarative"]:[]]},[`${e}-install`]:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},[`${e}-uninstall`]:{required:["target"],optional:["scope"]},[`${e}-explore`]:{optional:["scope","fields"]},[`${e}-manage`]:{optional:["scope","runtimeProbe","fixManagedState","offline","fields"]},[`${e}-describe`]:{optional:["target","scope","markdown","output"]},[`${e}-reload`]:{optional:["scope","watch"]},[`${e}-doctor`]:{optional:["scope","detail","trace","fixManagedState","isolated","ignoreGlobal","strictExit","failOnWarn"]},[`${e}-catalog`]:{optional:["scope","fields"]},[`${e}-adopt`]:{required:["target"],optional:["scope","github","ref"]},[`${e}-adopt-all`]:{optional:["scope"]},[`${e}-activate`]:{required:["target"],optional:["scope"]},[`${e}-deactivate`]:{required:["target"],optional:["scope"]},[e]:{optional:Te,dependentAnyOfRequired:[{property:"dryRun",value:!0,anyOfRequired:[["install","target"],["install","github"]]}],mutuallyExclusiveWhen:[[{property:"dryRun",schema:{const:!0}},{property:"install",schema:{const:!1}}]]}}}const S={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","inheritFocus","allowMissingParent","tags","priority","body","description","author","message"]},q={optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]},f={init:{optional:["prefix","idPrefix","workspace","preset","typePreset","defaults","author","agentGuidance","withPackages","mergeFence","force","verbose"]},config:{required:["scope","configAction"],optional:["key","value","criterion","clearCriteria","format","policy"]},...b("extension"),...b("package"),"package-upgrade":q,install:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},upgrade:q,create:{required:["title","description","type","status","priority","message"],optional:pe},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:A,mutuallyExclusiveWhen:d},"list-all":{optional:A,mutuallyExclusiveWhen:d},"list-draft":{optional:c,mutuallyExclusiveWhen:d},"list-open":{optional:c,mutuallyExclusiveWhen:d},"list-in-progress":{optional:c,mutuallyExclusiveWhen:d},"list-blocked":{optional:c,mutuallyExclusiveWhen:d},"list-closed":{optional:c,mutuallyExclusiveWhen:d},"list-canceled":{optional:c,mutuallyExclusiveWhen:d},aggregate:{optional:Oe},guide:{optional:["list","format","depth"]},context:{optional:C},ctx:{optional:C},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:he,anyOfRequired:[["query"],["keywords"]]},eval:{optional:["mode","k","failUnder","queries","format"]},events:{optional:["verify","since","type","author","item","limit","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","cursorMode"]},merge:{required:["subcommand"],optional:["dryRun","preCommitHook","stage","author","message","force","includeReconciled","artifact","basePath","oursPath","theirsPath","output","outputPath","itemPath","prefer"]},workspace:{required:["subcommand"],optional:["snapshotAction","name","target","dryRun","force","author","message","lockTtlSeconds","lockWaitMs"],conditionalRequired:[{property:"subcommand",value:"snapshot",required:["snapshotAction"]}]},meet:S,event:S,remind:{required:["title"],optional:["at","text","parent","inheritFocus","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...P,"for"]},reindex:{optional:["mode","progress"]},history:{required:["id"],optional:["limit","order","compact","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","diff","verify","field","strictExit","failOnWarn","format"]},"history-attest":{optional:["verify","output","hashAlgorithm"],mutuallyExclusive:[["verify","hashAlgorithm"]]},"history-redact":{required:["id"],optional:["literal","regex","replacement","dryRun",...l],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance","salvageTail","appendOnly",...l],oneOfRequired:[["id"],["all"]],mutuallyExclusiveWhen:[[{property:"appendOnly",schema:{const:!0}},{property:"salvageTail",schema:{const:!0}}],[{property:"appendOnly",schema:{const:!0}},{property:"normalizeProvenance",schema:{const:!0}}],[{property:"salvageTail",schema:{const:!0}},{property:"all",schema:{const:!0}}],[{property:"salvageTail",schema:{const:!0}},{property:"normalizeProvenance",schema:{const:!0}}]]},"history-author-acknowledge":{optional:["historyEvent","allActionable","dryRun","planFingerprint","limit","attributedAuthor","reviewer","reason"],oneOfRequired:[["historyEvent"],["allActionable"]]},"history-compact":{optional:["id","before","ids","allOver","closed","allStreams","minEntries","dryRun",...l]},schema:{mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"policy-mode"}},{property:"name",schema:{not:{enum:["advise","refuse"]}}}]],required:["subcommand"],optional:["definition","policy","message","name","description","defaultStatus","folder","alias","role","order","fieldType","commands","cliFlag","required","requiredOnCreate","allowUnset","requiredTypes","typePreset","infer","minCount","apply","to","migrationId","fieldTypeScope","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"policy-put",required:["definition"]},{property:"subcommand",value:"policy-remove",required:["name"]},{property:"subcommand",value:"policy-mode",required:["name"]},{property:"subcommand",value:"policy-check",required:["name"]},{property:"subcommand",value:"policy-approve",required:["name","policy"]},{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"show-status",required:["name"]},{property:"subcommand",value:"add-type",required:["name"]},{property:"subcommand",value:"remove-type",required:["name"]},{property:"subcommand",value:"add-status",required:["name"]},{property:"subcommand",value:"remove-status",required:["name"]},{property:"subcommand",value:"add-field",required:["name"]},{property:"subcommand",value:"remove-field",required:["name"]},{property:"subcommand",value:"show-field",required:["name"]},{property:"subcommand",value:"rename-type",required:["name","to"]},{property:"subcommand",value:"rename-field",required:["name","to"]},{property:"subcommand",value:"remap-status",required:["name","to"]},{property:"subcommand",value:"apply-preset",required:["typePreset"]}]},profile:{required:["subcommand"],optional:["name","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"apply",required:["name"]},{property:"subcommand",value:"lint",required:["name"]}]},plan:{required:["subcommand"],optional:["id","stepRef","reorderTo","title","description","template","scope","parent","inheritFocus","related","blocks","blockedBy","harness","mode","resumeContext","tags","priority",...de,"body","claim","fromSearch","stepTitle","step","stepBody","stepOwner","stepStatus","stepEvidence","stepBlockedReason","stepReplacement","dependsOn","link","linkKind","linkNote","promoteToItemDep","allowMultipleActive","file","test","doc","decisionText","decision","decisionRationale","decisionEvidence","discoveryText","discovery","validationText","validation","validationCommand","validationExpected","depth","fields","steps","materializeType","materializeParent","materializeTags","field",...l]},activity:{optional:fe},restore:{required:["id","target"],optional:l},update:{required:["id"],optional:v,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:ue,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...Ae,...l]},"close-many":{optional:me},delete:{required:["id"],optional:["dryRun",...l]},append:{required:["id","body"],optional:l},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent","expectAt",...l],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent","expectAt",...l],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"],["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","ifAbsent"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent","expectAt",...l],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","ifAbsent"]]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","noteConflict","discover","apply","discoveryNote","appendStable","validatePaths","full","lookupPath","scope","limit","offset","noTruncate","strictRead","explain","lines","decisionDepth",...l],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]},{property:"noteConflict",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","noteConflict","list","validatePaths","full",...l],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]},{property:"noteConflict",anyOfRequired:[["add"],["addGlob"]]}]},deps:{required:["id"],optional:["format","maxDepth","collapse","summary","full","nodeLimit","edgeLimit","tokenBudget","cursor","direction","kind"]},graph:{required:["subcommand"],optional:["id","target","kind","maxDepth","limit","after","direction","maxPaths","sample","exemptIsolate","exemptIsolateType","saveBaseline","rebuild","clear","summary","full"]},test:{required:["id"],optional:["list","add","addJson","remove","removeIndex","update","updateIndex","setJson","run","match","onlyIndex","onlyLast","full","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","acknowledgeLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","fullOutput","autoPmContext","measure","metricBelow","metricDiff",...l],dependentAnyOfRequired:[{property:"update",anyOfRequired:[["setJson"]]},{property:"updateIndex",anyOfRequired:[["setJson"]]},{property:"setJson",anyOfRequired:[["update"],["updateIndex"]]}],mutuallyExclusive:[["update","updateIndex"],["acknowledgeLinkedTests","run"],["acknowledgeLinkedTests","background"]]},"test-all":{optional:["status","limit","offset","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","fullOutput","autoPmContext"]},telemetry:{optional:["subcommand","limit"]},"test-runs-list":{optional:["status","limit"]},"test-runs-status":{required:["runId"]},"test-runs-logs":{required:["runId"],optional:["stream","tail"]},"test-runs-stop":{required:["runId"],optional:["force"]},"test-runs-resume":{required:["runId"],optional:["author"]},stats:{optional:["includeEmpty","storage","metadataCoverage","fieldUtilization","byAssignee","byTag","byPriority","tagPrefix","measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]},duplicates:{optional:["status","since","threshold","limit","exhaustive"]},health:{optional:["strictDirectories","requireMergeDrivers","strictExit","failOnWarn","checkOnly","checkTelemetry","noRefresh","refreshVectors","verboseStaleItems","verboseAuthorEvents","brief","summary","skipVectors","skipIntegrity","skipDrift","full"]},validate:{optional:["checkCompleteness","checkStorageIntegrity","checkMetadata","metadataProfile","checkResolution","checkLifecycle","checkStaleBlockers","dependencyCycleSeverity","parentCycleSeverity","checkFiles","scanMode","includePmInternals","verboseFileLists","verboseDiagnostics","allAffectedIds","strictExit","failOnWarn","fixHints","autoFix","dryRun","fixScope","pruneMissing","checkHistoryDrift","checkCommandReferences","counts","full"]},assurance:{required:["subcommand"],optional:["kind","id","definition","trigger","treeId","gate","limit","dryRun","author","message","preset","owner","apply","enforcement"],conditionalRequired:[{property:"subcommand",value:"list",required:["kind"]},{property:"subcommand",value:"show",required:["kind","id"]},{property:"subcommand",value:"put",required:["kind","id","definition"]},{property:"subcommand",value:"remove",required:["kind","id"]},{property:"subcommand",value:"run",required:["id","trigger"]},{property:"subcommand",value:"apply",required:["preset","owner"]},{property:"subcommand",value:"derive",required:["owner"]},{property:"subcommand",value:"risk",required:["definition"]},{property:"subcommand",value:"lineages",required:["definition"]},{property:"subcommand",value:"promote",required:["id","enforcement"]}],mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"risk"}},{property:"definition",schema:{not:{required:["policy","change"]}}}],[{property:"subcommand",schema:{const:"lineages"}},{property:"definition",schema:{anyOf:[{required:["change"]},{not:{required:["policy"]}}]}}]]},gc:{optional:["dryRun","gcScope"]},contracts:{optional:["contractAction","command","summary","schemaOnly","flagsOnly","availabilityOnly","runtimeOnly","activeOnly","full"],mutuallyExclusiveWhen:ye},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["start","id","next","ifAvailable","takeoverStale","maxAttempts","includeDecisions",...P,...m],oneOfRequired:[["id"],["next"]],mutuallyExclusiveWhen:[[{property:"start",schema:{const:!0}},{property:"ifAvailable",schema:{const:!0}},{property:"id",schema:{type:"string"}}],[{property:"takeoverStale",schema:{const:!0}},{property:"force",schema:{const:!0}}],[{property:"takeoverStale",schema:{const:!0}},{property:"next",schema:{const:!0}}]]},release:{required:["id"],optional:["pause","handoff",...m],dependentAnyOfRequired:[{property:"handoff",anyOfRequired:[["message"]]}],mutuallyExclusiveWhen:[[{property:"pause",schema:{const:!0}},{property:"handoff",schema:{type:"string"}}]]},"start-task":{required:["id"],optional:[...m,"takeoverStale"],mutuallyExclusiveWhen:[[{property:"takeoverStale",schema:{const:!0}},{property:"force",schema:{const:!0}}]]},"pause-task":{required:["id"],optional:m},"close-task":{required:["id"],optional:["text","validateClose",...m]},"item-reopen":{required:["id","reason"],optional:["status","expectedResult","author","message","force"]}},Le=Object.freeze(Object.fromEntries(h.map(e=>[e,f[e]])));function x(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,t=>t.toUpperCase()).concat(".")}function M(e,t){const r=typeof t=="object"&&t!==null?{...t}:{},o=u[e];return{...r,description:o?.description??x(e),...o?.examples?{examples:o.examples}:{}}}function Ee(e,t){if(e==="history-attest"&&t==="verify")return{description:"Compare all retained history streams with a detached JSON proof object. Server-local proof paths are not accepted over MCP."};if(e==="history-attest"&&t==="output")return{description:"Local CLI/SDK only. MCP rejects this field; save the returned JSON bundle on the client."};if(e==="claim"&&t==="start")return{description:"Move the claimed item to its configured in-progress status; with next, the selected item is claimed and started in one locked write."};if((e==="list"||e.startsWith("list-"))&&t==="all")return{description:"Return items from every lifecycle status instead of the default active-status set."};if(e==="plan"&&Object.prototype.hasOwnProperty.call(g,t))return g[t];const r=Z[e];return r&&Object.prototype.hasOwnProperty.call(r,t)?r[t]:u[t]}function I(e,t,r){const o=typeof r=="object"&&r!==null?{...r}:{},a=Ee(e,t);return{...o,description:a?.description??x(t),...a?.examples?{examples:a.examples}:{}}}function Re(e,t){if(e==="claim"&&t==="start")return{type:"boolean"};const r=ae[e];return r&&Object.prototype.hasOwnProperty.call(r,t)?r[t]:e==="plan"&&Object.prototype.hasOwnProperty.call(_,t)?_[t]:(e==="get"||e==="history"||e==="search")&&t==="format"?{type:"string",enum:["json","toon"]}:t==="pause"||t==="handoff"||t==="releaseAssignment"||t==="hashAlgorithm"?y[t]:R[t]}function _e(e,t){const r={action:{const:e,description:u.action?.description??"Tool action to execute."}};for(const o of t){if(o==="action")continue;const a=Re(e,o);a&&(r[o]=I(e,o,a))}return r}function ge(e,t){const r=t.flat();return t.map(o=>{const a=r.filter(n=>!o.includes(n));return{required:[...o],...a.length>0?{not:{anyOf:a.map(n=>({required:[n]}))}}:{},...e==="history-repair"&&o.includes("all")?{properties:{all:{const:!0}}}:e==="claim"&&o.includes("next")?{properties:{next:{const:!0}}}:{}}})}function N(e,t){return{...t===void 0?{}:{properties:{[e]:{const:t}}},required:[e]}}function ve(e){const t=[];if(e.conditionalRequired&&e.conditionalRequired.length>0)for(const r of e.conditionalRequired)t.push({if:N(r.property,r.value),then:{required:r.required}});if(e.dependentAnyOfRequired&&e.dependentAnyOfRequired.length>0)for(const r of e.dependentAnyOfRequired)t.push({if:N(r.property,r.value),then:{anyOf:r.anyOfRequired.map(o=>({required:[...o]}))}});if(e.mutuallyExclusive&&e.mutuallyExclusive.length>0)for(const r of e.mutuallyExclusive)t.push({not:{required:s(r)}});if(e.mutuallyExclusiveWhen&&e.mutuallyExclusiveWhen.length>0)for(const r of e.mutuallyExclusiveWhen)t.push({not:{allOf:r.map(o=>({properties:{[o.property]:o.schema},required:[o.property]}))}});return t}function k(e){if(!Object.prototype.hasOwnProperty.call(f,e))return;const t=f[e],r=le[e]??[];return s(["action",...ne,...te(e)!==void 0?ie:[],...r,...W.has(e)?["expectHash"]:[],...t.required??[],...t.optional??[]])}function we(e){const t=k(e);if(t===void 0)return;const r=e==="create"?re:e==="update"?oe:[];return s([...t,...r.flatMap(({keys:o,target:a})=>[a,...o]),...ce[e]??[]])}function T(e){const t=f[e],r=s(t.required??[]),o=k(e),a={type:"object",additionalProperties:!1,required:["action",...r],title:`pm action "${e}" parameters`,properties:_e(e,o)};t.anyOfRequired&&t.anyOfRequired.length>0&&(a.anyOf=t.anyOfRequired.map(i=>({required:[...i]}))),t.oneOfRequired&&t.oneOfRequired.length>0&&(a.oneOf=ge(e,t.oneOfRequired));const n=ve(t);return n.length>0&&(a.allOf=n),a}function De(e,t={}){const r=T(e),o={...r.properties};delete o.action;const a=[...r.anyOf??[],...r.oneOf??[]],n=(t.required??r.required.map(String)).filter(p=>p==="action"?!1:t.required===void 0?!0:!a.some(O=>O.required?.map(String).includes(p))),i={type:"object",additionalProperties:t.additionalProperties??!0,properties:{...o,options:{type:"object",additionalProperties:!0,description:"Advanced command options forwarded to the selected pm action."},...t.properties},required:n};return r.anyOf!==void 0&&(i.anyOf=r.anyOf),r.oneOf!==void 0&&(i.oneOf=r.oneOf),r.allOf!==void 0&&(i.allOf=r.allOf),i}function L(e){let t;const r=()=>t??=e();return new Proxy({},{get:(o,a)=>r()[a],has:(o,a)=>a in r(),ownKeys:()=>Reflect.ownKeys(r()),getOwnPropertyDescriptor:(o,a)=>{const n=Reflect.getOwnPropertyDescriptor(r(),a);return n&&(n.configurable=!0),n}})}const w="4.28.1",Ce=w.split(".")[0],Pe="1.12.0",Fe=L(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${Ce}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":w,type:"object",oneOf:h.map(e=>T(e))}));function D(e,t){const r=M(e,t);if(typeof r.type=="string")return r;const a=(Array.isArray(r.anyOf)?r.anyOf:[]).find(p=>typeof p.type=="string");if(a){const{anyOf:p,...O}=r;return{...a,...O}}const{anyOf:n,...i}=r;return{...i,type:"string"}}function F(){const e={action:{type:"string",description:u.action?.description??"Tool action to execute."},options:{type:"object",additionalProperties:!0,description:"Advanced command options object forwarded to the selected pm action."}};for(const t of Object.keys(y).sort())e[t]=D(t,y[t]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":Pe,type:"object",additionalProperties:!1,required:["action"],properties:e}}const Ue=L(F),We={buildActionScopedToolSchema:T,buildProviderCompatibleToolSchema:F,decorateActionScopedToolParameterDefinition:I,decorateToolParameterDefinition:M,toolActionSchemaContracts:f,toolParameterMetadata:u,toProviderCompatibleParameterDefinition:D,toUniqueFlagContracts:Q,withFlagAliasMetadata:ee};export{Ae as CLOSE_ACTION_OPTION_KEYS,de as PLAN_CREATE_METADATA_PARAMETER_KEYS,Ue as PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,Pe as PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,Le as PM_TOOL_ACTION_PARAMETER_CONTRACTS,Fe as PM_TOOL_PARAMETERS_SCHEMA,Ce as PM_TOOL_PARAMETERS_SCHEMA_MAJOR,w as PM_TOOL_PARAMETERS_SCHEMA_VERSION,se as PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,We as _testOnlyCliContracts,De as buildPmActionToolInputSchema,we as pmToolActionNestedOptionKeys,k as pmToolActionParameterKeys,ke as resolvePmToolCustomFieldCollision};
1
+ import{normalizeUniqueStringList as W}from"./string-lists.js";import{PM_EXPECT_HASH_ACTIONS as Y,PM_EXPECT_HASH_CONDITIONAL_ACTIONS as G,PM_EXPECT_HASH_HANDLER_DECIDED_ACTIONS as $,PM_EXPECT_HASH_SCHEMA_SUBCOMMANDS as B,PM_TOOL_ACTIONS as h}from"./enum-contracts.js";import{TOOL_CREATE_OPTION_CONTRACTS as V,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS as _,TOOL_UPDATE_OPTION_CONTRACTS as z,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS as J,TOOL_CONTEXT_OPTION_CONTRACTS as X,TOOL_ACTIVITY_OPTION_CONTRACTS as Z,TOOL_LIST_FILTER_OPTION_CONTRACTS as Q,TOOL_AGGREGATE_OPTION_CONTRACTS as ee,TOOL_SEARCH_FILTER_OPTION_CONTRACTS as te,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS as re}from"./tool-option-contracts.js";import{PM_TOOL_PARAMETER_PROPERTIES as R,PM_TOOL_PARAMETER_METADATA as oe,PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES as ae,PM_TOOL_ACTION_SCOPED_PARAMETER_METADATA as ne,PLAN_ACTION_PARAMETER_PROPERTIES as g,PLAN_ACTION_PARAMETER_METADATA as C}from"./tool-parameter-tables.js";import{toUniqueFlagContracts as ie,withFlagAliasMetadata as se}from"./flag-contracts.js";import{resolveReadOutputSurface as le}from"../read-output-contracts.js";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS as pe,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS as de}from"./commander-mutation-options.js";const ce={...ae,"history-attest":{verify:{type:"object",additionalProperties:!0},output:{not:{}}}},f={...R,pause:{type:"boolean"},handoff:{type:"string"},releaseAssignment:{type:"boolean"},hashAlgorithm:{type:"string",enum:["sha256","sha512"]}},u={...oe,pause:{description:"Return work to its configured open status before releasing ownership."},handoff:{description:"Release into a configured non-terminal queue with a required evidence message."},releaseAssignment:{description:"Release assignment after recording closure evidence."},hashAlgorithm:{description:"Digest for detached history bundles; defaults to sha256."}},ue=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],me=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],ye=new Set(["action","cwd","options",...Object.keys(f).filter(e=>e!=="severity")]);function Ge(e){const t=e.trim().toLowerCase();let r="";for(let o=0;o<t.length;o+=1){const a=t[o];if(a!=="-"&&a!=="_"){r+=a;continue}let n=o+1;for(;t[n]==="-"||t[n]==="_";)n+=1;const i=t[n];if(i!==void 0&&(i>="a"&&i<="z"||i>="0"&&i<="9")){r+=i.toUpperCase(),o=n;continue}r+=t.slice(o,n),o=n-1}return ye.has(r)?{field:e,property:r,owner:"mcp_tool_input",nested_path:r==="expectHash"?`options.field (${e}=<value>)`:`options.${r}`}:void 0}const fe={create:["fullChangedFields","idOnly"],copy:["fullChangedFields","idOnly"],update:["fullChangedFields","idOnly"],"item-reopen":["fullChangedFields","idOnly"],close:["fullChangedFields","idOnly"],claim:["fullChangedFields","idOnly"],release:["fullChangedFields","idOnly"],"start-task":["fullChangedFields","idOnly"],"pause-task":["fullChangedFields","idOnly"],"close-task":["fullChangedFields","idOnly"],restore:["fullChangedFields","idOnly"],append:["fullChangedFields"],"update-many":["fullChangedFields"],"close-many":["fullChangedFields"],assurance:["fullChangedFields","idOnly"]},Oe=["createMode","status","deadline","estimate","acceptanceCriteria","definitionOfReady","order","rank","goal","objective","value","impact","outcome","whyNow","assignee","reviewer","risk","confidence","sprint","release","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact","comment","note","learning","reminder","event","typeOption"],he=Object.freeze({"close-many":["list","expected_result","expected","actual_result","actual","validate_close","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],"update-many":["list","update","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],...Object.fromEntries(h.filter(e=>e==="upgrade"||e==="install"||e==="extension"||e==="package"||e.startsWith("extension-")||e.startsWith("package-")).map(e=>[e,["project","local","global"]]))});function s(e){return W(e)}const Ae=s([...V.map(e=>e.param),..._.map(e=>e.param)]),v=s([...z.map(e=>e.param),..._.map(e=>e.param),"force"]),Te=s([...J.map(e=>e.param),...v.filter(e=>e!=="allowMissingParent"&&e!=="completedAt"),"dryRun","rollback","noCheckpoint"]),Ee=s([...re.map(e=>e.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),P=s([...X.map(e=>e.param),"past","section"]),_e=s([...Z.map(e=>e.param),"stream"]),A=s([...Q.map(e=>e.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),c=A.filter(e=>e!=="all"&&e!=="status"),p=[[{property:"today",schema:{const:!0}},{property:"recent",schema:{const:!0}}],[{property:"today",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}],[{property:"recent",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}]],Re=[[{property:"summary",schema:{const:!0}},{property:"schemaOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"flagsOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}]],ge=s([...ee.map(e=>e.param),"count","completion","includeUnparented"]),Ce=s(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...te.map(e=>e.param)]),S=s(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","includeGates","includeContainers","tokenBudget","explainRanking"]),l=["author","message","force"],ve=["releaseAssignment","text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],m=["author","assignee","message","force"],Pe=["dryRun","target","scope","capability","declarative","github","ref","init","install","uninstall","explore","manage","offline","describe","markdown","output","reload","doctor","catalog","list","adopt","adoptAll","activate","deactivate","runtimeProbe","fixManagedState","isolated","ignoreGlobal","detail","trace","watch","strictExit","failOnWarn","fields"];function b(e){return{[`${e}-init`]:{required:["target"],optional:["scope","capability",...e==="package"?["declarative"]:[]]},[`${e}-install`]:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},[`${e}-uninstall`]:{required:["target"],optional:["scope"]},[`${e}-explore`]:{optional:["scope","fields"]},[`${e}-manage`]:{optional:["scope","runtimeProbe","fixManagedState","offline","fields"]},[`${e}-describe`]:{optional:["target","scope","markdown","output"]},[`${e}-reload`]:{optional:["scope","watch"]},[`${e}-doctor`]:{optional:["scope","detail","trace","fixManagedState","isolated","ignoreGlobal","strictExit","failOnWarn"]},[`${e}-catalog`]:{optional:["scope","fields"]},[`${e}-adopt`]:{required:["target"],optional:["scope","github","ref"]},[`${e}-adopt-all`]:{optional:["scope"]},[`${e}-activate`]:{required:["target"],optional:["scope"]},[`${e}-deactivate`]:{required:["target"],optional:["scope"]},[e]:{optional:Pe,dependentAnyOfRequired:[{property:"dryRun",value:!0,anyOfRequired:[["install","target"],["install","github"]]}],mutuallyExclusiveWhen:[[{property:"dryRun",schema:{const:!0}},{property:"install",schema:{const:!1}}]]}}}const q={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","inheritFocus","allowMissingParent","tags","priority","body","description","author","message"]},x={optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]};function Se(e){return`^\\s*(?:${e.map(r=>[...r].map(o=>/[a-z]/u.test(o)?`[${o}${o.toUpperCase()}]`:o.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")).join("")).join("|")})\\s*$`}const be=Se(B),M={type:"string",pattern:be},I=["expectHash","expect_hash"],N={not:{type:"array",maxItems:0}},qe=T({anyOf:[...I.map(e=>({properties:{[e]:N},required:[e]})),{properties:{options:{type:"object",anyOf:I.map(e=>({properties:{[e]:N},required:[e]}))}},required:["options"]}]},{anyOf:[{properties:{subcommand:M},required:["subcommand"]},{properties:{subcommand:{not:{type:"string",pattern:"\\S"}},options:{type:"object",properties:{subcommand:M},required:["subcommand"]}},required:["options"]}]}),xe={schema:qe},y={init:{optional:["prefix","idPrefix","workspace","preset","typePreset","defaults","author","agentGuidance","withPackages","mergeFence","force","verbose"]},config:{required:["scope","configAction"],optional:["key","value","criterion","clearCriteria","format","policy"]},...b("extension"),...b("package"),"package-upgrade":x,install:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},upgrade:x,create:{required:["title","description","type","status","priority","message"],optional:Ae},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:A,mutuallyExclusiveWhen:p},"list-all":{optional:A,mutuallyExclusiveWhen:p},"list-draft":{optional:c,mutuallyExclusiveWhen:p},"list-open":{optional:c,mutuallyExclusiveWhen:p},"list-in-progress":{optional:c,mutuallyExclusiveWhen:p},"list-blocked":{optional:c,mutuallyExclusiveWhen:p},"list-closed":{optional:c,mutuallyExclusiveWhen:p},"list-canceled":{optional:c,mutuallyExclusiveWhen:p},aggregate:{optional:ge},guide:{optional:["list","format","depth"]},context:{optional:P},ctx:{optional:P},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:Ce,anyOfRequired:[["query"],["keywords"]]},eval:{optional:["mode","k","failUnder","queries","format"]},events:{optional:["verify","since","type","author","item","limit","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","cursorMode"]},merge:{required:["subcommand"],optional:["dryRun","preCommitHook","stage","author","message","force","includeReconciled","artifact","basePath","oursPath","theirsPath","output","outputPath","itemPath","prefer"]},workspace:{required:["subcommand"],optional:["snapshotAction","name","target","dryRun","force","author","message","lockTtlSeconds","lockWaitMs"],conditionalRequired:[{property:"subcommand",value:"snapshot",required:["snapshotAction"]}]},meet:q,event:q,remind:{required:["title"],optional:["at","text","parent","inheritFocus","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...S,"for"]},reindex:{optional:["mode","progress"]},history:{required:["id"],optional:["limit","order","compact","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","diff","verify","field","strictExit","failOnWarn","format"]},"history-attest":{optional:["verify","output","hashAlgorithm"],mutuallyExclusive:[["verify","hashAlgorithm"]]},"history-redact":{required:["id"],optional:["literal","regex","replacement","dryRun",...l],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance","salvageTail","appendOnly",...l],oneOfRequired:[["id"],["all"]],mutuallyExclusiveWhen:[[{property:"appendOnly",schema:{const:!0}},{property:"salvageTail",schema:{const:!0}}],[{property:"appendOnly",schema:{const:!0}},{property:"normalizeProvenance",schema:{const:!0}}],[{property:"salvageTail",schema:{const:!0}},{property:"all",schema:{const:!0}}],[{property:"salvageTail",schema:{const:!0}},{property:"normalizeProvenance",schema:{const:!0}}]]},"history-author-acknowledge":{optional:["historyEvent","allActionable","dryRun","planFingerprint","limit","attributedAuthor","reviewer","reason"],oneOfRequired:[["historyEvent"],["allActionable"]]},"history-compact":{optional:["id","before","ids","allOver","closed","allStreams","minEntries","dryRun",...l]},schema:{mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"policy-mode"}},{property:"name",schema:{not:{enum:["advise","refuse"]}}}]],required:["subcommand"],optional:["definition","policy","message","name","description","defaultStatus","folder","alias","role","order","fieldType","commands","cliFlag","required","requiredOnCreate","allowUnset","requiredTypes","typePreset","infer","minCount","apply","to","migrationId","fieldTypeScope","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"policy-put",required:["definition"]},{property:"subcommand",value:"policy-remove",required:["name"]},{property:"subcommand",value:"policy-mode",required:["name"]},{property:"subcommand",value:"policy-check",required:["name"]},{property:"subcommand",value:"policy-approve",required:["name","policy"]},{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"show-status",required:["name"]},{property:"subcommand",value:"add-type",required:["name"]},{property:"subcommand",value:"remove-type",required:["name"]},{property:"subcommand",value:"add-status",required:["name"]},{property:"subcommand",value:"remove-status",required:["name"]},{property:"subcommand",value:"add-field",required:["name"]},{property:"subcommand",value:"remove-field",required:["name"]},{property:"subcommand",value:"show-field",required:["name"]},{property:"subcommand",value:"rename-type",required:["name","to"]},{property:"subcommand",value:"rename-field",required:["name","to"]},{property:"subcommand",value:"remap-status",required:["name","to"]},{property:"subcommand",value:"apply-preset",required:["typePreset"]}]},profile:{required:["subcommand"],optional:["name","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"apply",required:["name"]},{property:"subcommand",value:"lint",required:["name"]}]},plan:{required:["subcommand"],optional:["id","stepRef","reorderTo","title","description","template","scope","parent","inheritFocus","related","blocks","blockedBy","harness","mode","resumeContext","tags","priority",...Oe,"body","claim","fromSearch","stepTitle","step","stepBody","stepOwner","stepStatus","stepEvidence","stepBlockedReason","stepReplacement","dependsOn","link","linkKind","linkNote","promoteToItemDep","allowMultipleActive","file","test","doc","decisionText","decision","decisionRationale","decisionEvidence","discoveryText","discovery","validationText","validation","validationCommand","validationExpected","depth","fields","steps","materializeType","materializeParent","materializeTags","field",...l]},activity:{optional:_e},restore:{required:["id","target"],optional:l},update:{required:["id"],optional:v,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:Te,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...ve,...l]},"close-many":{optional:Ee},delete:{required:["id"],optional:["dryRun",...l]},append:{required:["id","body"],optional:l},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent","expectAt",...l],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent","expectAt",...l],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"],["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","ifAbsent"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent","expectAt",...l],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"],["expectAt","ifAbsent"]]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","noteConflict","discover","apply","discoveryNote","appendStable","validatePaths","full","lookupPath","scope","limit","offset","noTruncate","strictRead","explain","lines","decisionDepth",...l],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]},{property:"noteConflict",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","noteConflict","list","validatePaths","full",...l],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]},{property:"noteConflict",anyOfRequired:[["add"],["addGlob"]]}]},deps:{required:["id"],optional:["format","maxDepth","collapse","summary","full","nodeLimit","edgeLimit","tokenBudget","cursor","direction","kind"]},graph:{required:["subcommand"],optional:["id","target","kind","maxDepth","limit","after","direction","maxPaths","sample","exemptIsolate","exemptIsolateType","saveBaseline","rebuild","clear","summary","full"]},test:{required:["id"],optional:["list","add","addJson","remove","removeIndex","update","updateIndex","setJson","run","match","onlyIndex","onlyLast","full","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","acknowledgeLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","fullOutput","autoPmContext","measure","metricBelow","metricDiff",...l],dependentAnyOfRequired:[{property:"update",anyOfRequired:[["setJson"]]},{property:"updateIndex",anyOfRequired:[["setJson"]]},{property:"setJson",anyOfRequired:[["update"],["updateIndex"]]}],mutuallyExclusive:[["update","updateIndex"],["acknowledgeLinkedTests","run"],["acknowledgeLinkedTests","background"]]},"test-all":{optional:["status","limit","offset","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","fullOutput","autoPmContext"]},telemetry:{optional:["subcommand","limit"]},"test-runs-list":{optional:["status","limit"]},"test-runs-status":{required:["runId"]},"test-runs-logs":{required:["runId"],optional:["stream","tail"]},"test-runs-stop":{required:["runId"],optional:["force"]},"test-runs-resume":{required:["runId"],optional:["author"]},stats:{optional:["includeEmpty","storage","metadataCoverage","fieldUtilization","byAssignee","byTag","byPriority","tagPrefix","measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]},duplicates:{optional:["status","since","threshold","limit","exhaustive"]},health:{optional:["strictDirectories","requireMergeDrivers","strictExit","failOnWarn","checkOnly","checkTelemetry","noRefresh","refreshVectors","verboseStaleItems","verboseAuthorEvents","brief","summary","skipVectors","skipIntegrity","skipDrift","full"]},validate:{optional:["checkCompleteness","checkStorageIntegrity","checkMetadata","metadataProfile","checkResolution","checkLifecycle","checkStaleBlockers","dependencyCycleSeverity","parentCycleSeverity","checkFiles","scanMode","includePmInternals","verboseFileLists","verboseDiagnostics","allAffectedIds","strictExit","failOnWarn","fixHints","autoFix","dryRun","fixScope","pruneMissing","checkHistoryDrift","checkCommandReferences","counts","full"]},assurance:{required:["subcommand"],optional:["kind","id","definition","trigger","treeId","gate","limit","dryRun","author","message","preset","owner","apply","enforcement"],conditionalRequired:[{property:"subcommand",value:"list",required:["kind"]},{property:"subcommand",value:"show",required:["kind","id"]},{property:"subcommand",value:"put",required:["kind","id","definition"]},{property:"subcommand",value:"remove",required:["kind","id"]},{property:"subcommand",value:"run",required:["id","trigger"]},{property:"subcommand",value:"apply",required:["preset","owner"]},{property:"subcommand",value:"derive",required:["owner"]},{property:"subcommand",value:"risk",required:["definition"]},{property:"subcommand",value:"lineages",required:["definition"]},{property:"subcommand",value:"promote",required:["id","enforcement"]}],mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"risk"}},{property:"definition",schema:{not:{required:["policy","change"]}}}],[{property:"subcommand",schema:{const:"lineages"}},{property:"definition",schema:{anyOf:[{required:["change"]},{not:{required:["policy"]}}]}}]]},gc:{optional:["dryRun","gcScope"]},contracts:{optional:["contractAction","command","summary","schemaOnly","flagsOnly","availabilityOnly","runtimeOnly","activeOnly","full"],mutuallyExclusiveWhen:Re},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["start","id","next","ifAvailable","takeoverStale","maxAttempts","includeDecisions",...S,...m],oneOfRequired:[["id"],["next"]],mutuallyExclusiveWhen:[[{property:"start",schema:{const:!0}},{property:"ifAvailable",schema:{const:!0}},{property:"id",schema:{type:"string"}}],[{property:"takeoverStale",schema:{const:!0}},{property:"force",schema:{const:!0}}],[{property:"takeoverStale",schema:{const:!0}},{property:"next",schema:{const:!0}}]]},release:{required:["id"],optional:["pause","handoff",...m],dependentAnyOfRequired:[{property:"handoff",anyOfRequired:[["message"]]}],mutuallyExclusiveWhen:[[{property:"pause",schema:{const:!0}},{property:"handoff",schema:{type:"string"}}]]},"start-task":{required:["id"],optional:[...m,"takeoverStale"],mutuallyExclusiveWhen:[[{property:"takeoverStale",schema:{const:!0}},{property:"force",schema:{const:!0}}]]},"pause-task":{required:["id"],optional:m},"close-task":{required:["id"],optional:["text","validateClose",...m]},"item-reopen":{required:["id","reason"],optional:["status","expectedResult","author","message","force"]}},$e=Object.freeze(Object.fromEntries(h.map(e=>[e,y[e]])));function L(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,t=>t.toUpperCase()).concat(".")}function k(e,t){const r=typeof t=="object"&&t!==null?{...t}:{},o=u[e];return{...r,description:o?.description??L(e),...o?.examples?{examples:o.examples}:{}}}function Me(e,t){if(e==="history-attest"&&t==="verify")return{description:"Compare all retained history streams with a detached JSON proof object. Server-local proof paths are not accepted over MCP."};if(e==="history-attest"&&t==="output")return{description:"Local CLI/SDK only. MCP rejects this field; save the returned JSON bundle on the client."};if(e==="claim"&&t==="start")return{description:"Move the claimed item to its configured in-progress status; with next, the selected item is claimed and started in one locked write."};if((e==="list"||e.startsWith("list-"))&&t==="all")return{description:"Return items from every lifecycle status instead of the default active-status set."};if(e==="plan"&&Object.prototype.hasOwnProperty.call(C,t))return C[t];const r=ne[e];return r&&Object.prototype.hasOwnProperty.call(r,t)?r[t]:u[t]}function D(e,t,r){const o=typeof r=="object"&&r!==null?{...r}:{},a=Me(e,t);return{...o,description:a?.description??L(t),...a?.examples?{examples:a.examples}:{}}}function Ie(e,t){if(e==="claim"&&t==="start")return{type:"boolean"};const r=ce[e];return r&&Object.prototype.hasOwnProperty.call(r,t)?r[t]:e==="plan"&&Object.prototype.hasOwnProperty.call(g,t)?g[t]:(e==="get"||e==="history"||e==="search")&&t==="format"?{type:"string",enum:["json","toon"]}:t==="pause"||t==="handoff"||t==="releaseAssignment"||t==="hashAlgorithm"?f[t]:R[t]}function Ne(e,t){const r={action:{const:e,description:u.action?.description??"Tool action to execute."}};for(const o of t){if(o==="action")continue;const a=Ie(e,o);a&&(r[o]=D(e,o,a))}return r}function Le(e,t){const r=t.flat();return t.map(o=>{const a=r.filter(n=>!o.includes(n));return{required:[...o],...a.length>0?{not:{anyOf:a.map(n=>({required:[n]}))}}:{},...e==="history-repair"&&o.includes("all")?{properties:{all:{const:!0}}}:e==="claim"&&o.includes("next")?{properties:{next:{const:!0}}}:{}}})}function T(e,t){return{if:e,then:t}}function w(e,t){return{...t===void 0?{}:{properties:{[e]:{const:t}}},required:[e]}}function ke(e){const t=[];if(e.conditionalRequired&&e.conditionalRequired.length>0)for(const r of e.conditionalRequired)t.push(T(w(r.property,r.value),{required:r.required}));if(e.dependentAnyOfRequired&&e.dependentAnyOfRequired.length>0)for(const r of e.dependentAnyOfRequired)t.push(T(w(r.property,r.value),{anyOf:r.anyOfRequired.map(o=>({required:[...o]}))}));if(e.mutuallyExclusive&&e.mutuallyExclusive.length>0)for(const r of e.mutuallyExclusive)t.push({not:{required:s(r)}});if(e.mutuallyExclusiveWhen&&e.mutuallyExclusiveWhen.length>0)for(const r of e.mutuallyExclusiveWhen)t.push({not:{allOf:r.map(o=>({properties:{[o.property]:o.schema},required:[o.property]}))}});return t}function H(e){if(!Object.prototype.hasOwnProperty.call(y,e))return;const t=y[e],r=fe[e]??[];return s(["action",...ue,...le(e)!==void 0?me:[],...r,...Y.has(e)||G.has(e)||$.has(e)?["expectHash"]:[],...t.required??[],...t.optional??[]])}function Be(e){const t=H(e);if(t===void 0)return;const r=e==="create"?pe:e==="update"?de:[];return s([...t,...r.flatMap(({keys:o,target:a})=>[a,...o]),...he[e]??[],...t.includes("expectHash")?["expect_hash"]:[]])}function E(e){const t=y[e],r=s(t.required??[]),o=H(e),a={type:"object",additionalProperties:!1,required:["action",...r],title:`pm action "${e}" parameters`,properties:Ne(e,o)};t.anyOfRequired&&t.anyOfRequired.length>0&&(a.anyOf=t.anyOfRequired.map(d=>({required:[...d]}))),t.oneOfRequired&&t.oneOfRequired.length>0&&(a.oneOf=Le(e,t.oneOfRequired));const n=xe[e],i=[...ke(t),...n===void 0?[]:[n]];return i.length>0&&(a.allOf=i),a}function Ve(e,t={}){const r=E(e),o={...r.properties};delete o.action;const a=[...r.anyOf??[],...r.oneOf??[]],n=(t.required??r.required.map(String)).filter(d=>d==="action"?!1:t.required===void 0?!0:!a.some(O=>O.required?.map(String).includes(d))),i={type:"object",additionalProperties:t.additionalProperties??!0,properties:{...o,options:{type:"object",additionalProperties:!0,description:"Advanced command options forwarded to the selected pm action."},...t.properties},required:n};return r.anyOf!==void 0&&(i.anyOf=r.anyOf),r.oneOf!==void 0&&(i.oneOf=r.oneOf),r.allOf!==void 0&&(i.allOf=r.allOf),i}function F(e){let t;const r=()=>t??=e();return new Proxy({},{get:(o,a)=>r()[a],has:(o,a)=>a in r(),ownKeys:()=>Reflect.ownKeys(r()),getOwnPropertyDescriptor:(o,a)=>{const n=Reflect.getOwnPropertyDescriptor(r(),a);return n&&(n.configurable=!0),n}})}const U="4.28.1",De=U.split(".")[0],we="1.12.0",ze=F(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${De}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":U,type:"object",oneOf:h.map(e=>E(e))}));function j(e,t){const r=k(e,t);if(typeof r.type=="string")return r;const a=(Array.isArray(r.anyOf)?r.anyOf:[]).find(d=>typeof d.type=="string");if(a){const{anyOf:d,...O}=r;return{...a,...O}}const{anyOf:n,...i}=r;return{...i,type:"string"}}function K(){const e={action:{type:"string",description:u.action?.description??"Tool action to execute."},options:{type:"object",additionalProperties:!0,description:"Advanced command options object forwarded to the selected pm action."}};for(const t of Object.keys(f).sort())e[t]=j(t,f[t]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":we,type:"object",additionalProperties:!1,required:["action"],properties:e}}const Je=F(K),Xe={buildActionScopedToolSchema:E,buildProviderCompatibleToolSchema:K,decorateActionScopedToolParameterDefinition:D,decorateToolParameterDefinition:k,toolActionSchemaContracts:y,toolParameterMetadata:u,toProviderCompatibleParameterDefinition:j,toUniqueFlagContracts:ie,withFlagAliasMetadata:se};export{ve as CLOSE_ACTION_OPTION_KEYS,Oe as PLAN_CREATE_METADATA_PARAMETER_KEYS,Je as PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,we as PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,$e as PM_TOOL_ACTION_PARAMETER_CONTRACTS,ze as PM_TOOL_PARAMETERS_SCHEMA,De as PM_TOOL_PARAMETERS_SCHEMA_MAJOR,U as PM_TOOL_PARAMETERS_SCHEMA_VERSION,ye as PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,Xe as _testOnlyCliContracts,Ve as buildPmActionToolInputSchema,Be as pmToolActionNestedOptionKeys,H as pmToolActionParameterKeys,Ge as resolvePmToolCustomFieldCollision};
2
2
  //# sourceMappingURL=tool-schema.js.map
@@ -1,2 +1,2 @@
1
- import{AsyncLocalStorage as tt}from"node:async_hooks";import{attachExtensionReadOutputRows as et,resolveExtensionOutputCommand as nt}from"./read-output/extension.js";import{quoteCommandArg as I,renderPmCommand as q}from"./command-line.js";import{attachOutputOmissionReceipt as rt}from"./output-projection.js";import{decodeQueryCursorEnvelope as ot,encodeQueryCursor as it}from"./pagination.js";import{applyReadOutputDimensions as dt,decodeReadOutputContinuationCursor as ut,isReadResultOmittedForBudget as z,resolveReadOutputSurface as st,stabilizeReadOutputReceiptEstimates as ct}from"./read-output-contracts.js";import{estimateReadOutputTokens as E,MAX_ESTIMATE_ITERATIONS as at,readOutputMeasurementFormat as T,registerReadOutputPassHooks as ft,resolveReadOutputRecoveryBudget as lt}from"./read-output-budget.js";import{propagateContextUsageServingReceipt as R}from"./context-usage.js";import{readOutputContinuationRowCollections as _t}from"./read-output-rows.js";import{EXIT_CODE as B}from"../core/shared/constants.js";import{PmCliError as A}from"../core/shared/errors.js";import{compactExplanatoryString as gt,isContinuationTokenKey as mt,isTrackerItemDocumentKey as bt}from"../core/shared/text-normalization.js";const ht="limit_overridden_by_intent",U=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),G=new tt;function kt(){return G.getStore()??U}function jt(t,e){return G.run(yt(t.workspaceContracts,t.packageContracts),e)}function pt(t,e){const n=t.command.trim().toLowerCase(),o=t.intent.trim().toLowerCase(),i=`${n}:${o}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(n)||!/^[a-z0-9][a-z0-9-]*$/.test(o))throw new TypeError(`Invalid context intent command or name: ${i}`);if(t.description.trim().length===0)throw new TypeError(`Context intent ${i} requires a non-empty description`);if(!Number.isSafeInteger(t.token_budget)||t.token_budget<=0)throw new TypeError(`Context intent ${i} requires a positive integer token_budget`);const r=[...new Set(t.included_field_groups.map(d=>d.trim()).filter(Boolean))];if(r.length===0)throw new TypeError(`Context intent ${i} requires included_field_groups`);return{command:n,intent:o,description:t.description.trim(),included_field_groups:r,token_budget:t.token_budget,source:e}}function yt(t=[],e=[]){const n=[{source:"core",contracts:U,allowOverride:!1},{source:"package",contracts:e,allowOverride:!1},{source:"workspace",contracts:t,allowOverride:!0}],o=new Map,i=new Set;for(const r of n){i.clear();for(const d of r.contracts){const s=pt(d,r.source),u=`${s.command}:${s.intent}`;if(i.has(u))throw new TypeError(`Duplicate context intent declaration: ${u}`);if(i.add(u),!r.allowOverride&&o.has(u))throw new TypeError(`Duplicate context intent declaration: ${u}`);o.set(u,s)}}return[...o.values()].sort((r,d)=>r.command.localeCompare(d.command)||r.intent.localeCompare(d.intent))}function X(t,e,n=kt(),o=[]){const i=t.trim().toLowerCase(),r=e.trim().toLowerCase(),d=n.find(c=>c.command===i&&c.intent===r);if(d)return{...d,source:d.source??"core"};const s=n.filter(c=>c.command===i).map(c=>c.intent);if(s.length===0)return;const u=s.map(c=>{const f=Array.from({length:r.length+1},(b,g)=>g);for(let b=1;b<=c.length;b+=1){let g=f[0];f[0]=b;for(let h=1;h<=r.length;h+=1){const j=f[h];f[h]=Math.min(f[h]+1,f[h-1]+1,g+(c[b-1]===r[h-1]?0:1)),g=j}}return{candidate:c,distance:f[r.length]}}).sort((c,f)=>c.distance-f.distance||c.candidate.localeCompare(f.candidate))[0].candidate,a=[i,...o,"--for",r],l=[i,...o,"--for",u],_=q(l);throw new A(`Unknown context intent "${r}" for ${i}. Did you mean "${u}"?`,B.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:r,required:`Use a declared ${i} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[_],recovery:{recovery_mode:"compact",attempted_command:q(a),allowed_values:[...s].sort(),suggested_retry:_,suggested_retry_args:l}})}function N(t,e){const n=k(t.limit),o=String(n===void 0?e:Math.min(n,e));return(t.limit===void 0||n!==void 0)&&(t.limit=o),o}const W={context:(t,e,n,o)=>{t.section===void 0&&t.depth===void 0&&(t.section=e.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]),t.depth===void 0&&(t.depth=e.intent==="handoff"?"deep":"standard");const i=C(o,t.tokenBudget,e.token_budget),r=v("context",e.intent,i,n),d=N(t,r);t.activityLimit===void 0&&(t.activityLimit=d)},get:t=>{t.depth===void 0&&t.fields===void 0&&(t.depth="standard")},list:(t,e,n,o)=>{t.brief===void 0&&t.compact===void 0&&t.full===void 0&&t.fields===void 0&&(t.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");const i=C(o,t.tokenBudget,e.token_budget),r=v("list",e.intent,i,n);N(t,r)},next:t=>{t.readyOnly===void 0&&(t.readyOnly=!0)},search:(t,e,n,o)=>{t.compact===void 0&&t.full===void 0&&t.fields===void 0&&(t.compact=!0);const i=C(o,t.tokenBudget,e.token_budget),r=v("search",e.intent,i,n);N(t,r)}};function te(t,e,n=[]){const o=e.tokenBudget??e.token_budget;if(typeof e.for!="string"){if(o!==void 0&&(t==="get"||t==="list"||t==="search"))throw new A("--token-budget requires a declared context intent selected with --for",B.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(e.tokenBudget!==void 0||e.token_budget===void 0)return e;const u={...e,tokenBudget:o};return delete u.token_budget,u}const i=X(t,e.for,void 0,n),r=w(e),d=k(o)!==void 0||typeof r=="number",s={...e};return s.tokenBudget===void 0&&o!==void 0&&(s.tokenBudget=o),delete s.token_budget,typeof r=="number"?s.tokenBudget=String(r):s.tokenBudget===void 0&&(s.tokenBudget=String(i.token_budget)),W[t](s,i,d,r),s}const wt={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},x=256;function S(t,e,n=!0,o=!0){return Array.isArray(t)?t.map(i=>S(i,e,n,!1)):t!==null&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([i,r])=>[i,n&&typeof r=="string"&&mt(i)?r:S(r,e,n&&!(o&&bt(e,i)),!1)])):typeof t=="string"?gt(t):t}function k(t){const e=typeof t=="number"?t:typeof t=="string"&&/^\d+$/u.test(t.trim())?Number(t):Number.NaN;return Number.isSafeInteger(e)&&e>0?e:void 0}function w(t){const e=t.outputBudget??t.output_budget;return e==="unbounded"?e:k(e)}function xt(t){return w(t)===void 0?"--token-budget":"--output-budget"}function C(t,e,n){return typeof t=="number"?t:Ct(e,n)}function Ct(t,e){const n=k(t);if(n===void 0)return e;if(n<x)throw new A(`Context intent token budget must be at least ${x}`,B.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(t),required:`Use an integer token budget of at least ${x}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${x} or omit the override.`]});return n}function F(t,e){const n=t==="context"&&e==="orient";return t==="context"?n?{overhead:1200,rowCost:600}:{overhead:800,rowCost:500}:{overhead:t==="list"?520:480,rowCost:16}}function v(t,e,n,o){if(t==="get"||t==="next")return;const{overhead:i,rowCost:r}=F(t,e),d=Math.max(t==="context"?1:2,Math.floor((n-i)/r));return o?d:Math.min(t==="context"?20:100,d)}function p(t,e,n){const o=T(n),i=n.outputRowContract===!0||n.output_row_contract===!0;let r=e.estimated_tokens,d=r;for(let s=0;s<at;s+=1){e.estimated_tokens=r;const u=E(i||!Object.hasOwn(t,"row_contract")?t:Object.fromEntries(Object.entries(t).filter(([a])=>a!=="row_contract")),o);if(u===r)return;r=u,d=Math.max(d,r)}e.estimated_tokens=d}const K={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function J(t){try{const e=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));return typeof e.fingerprint!="string"||!Number.isSafeInteger(e.after_index)?void 0:{fingerprint:e.fingerprint,after_index:e.after_index,...typeof e.snapshot=="string"?{snapshot:e.snapshot}:{}}}catch{return}}function vt(t){if(t===null||typeof t!="object")return;if(typeof t.id=="string")return t.id;const e=t.item?.id;return typeof e=="string"?e:void 0}function Ot(t,e,n,o){let i=!1;for(;;){if(p(t,e,o),e.estimated_tokens<=e.token_budget||n.length<=1)return i;const r=Buffer.byteLength(JSON.stringify(n),"utf8"),d=(e.estimated_tokens-e.token_budget)*4;n.splice(-Math.min(n.length-1,Math.max(1,Math.ceil(d/Math.max(1,Math.ceil(r/n.length)))))),i=!0}}function It(t,e,n){const o=t.items,i=typeof t.next_cursor=="string",r=i?t.next_cursor:n.after;if(!Array.isArray(o)||typeof r!="string")return!1;const d=J(r);if(d===void 0)return!1;const s=o.length,u=[...o];let a=!1;for(;;){if(a=Ot(t,e,o,n)||a,!a)return!1;const l=vt(o.at(-1));if(l===void 0)return o.splice(0,o.length,...u),p(t,e,n),!1;if(t.next_cursor=it(d.fingerprint,l,i?d.after_index-(s-o.length):d.after_index+o.length,d.snapshot),p(t,e,n),e.estimated_tokens<=e.token_budget||o.length<=1)break}return typeof t.count=="number"&&(t.count=o.length),typeof t.applied_limit=="number"&&(t.applied_limit=o.length),!0}function Et(t,e,n,o){if(t==="list"||t==="search")return It(e,n,o);if(t!=="next"||typeof e.next_cursor=="string")return!1;let i=!1;for(;;){if(p(e,n,o),n.estimated_tokens<=n.token_budget)return i;const r=K[t].map(c=>({key:c,rows:Array.isArray(e[c])?e[c]:[]})).filter(({rows:c})=>c.length>0).sort((c,f)=>f.rows.length-c.rows.length||c.key.localeCompare(f.key))[0];if(r===void 0)return i;const d=K[t].reduce((c,f)=>c+(Array.isArray(e[f])?e[f].length:0),0);if(d<=1)return i;const s=Math.min(r.rows.length,d-1),u=Buffer.byteLength(JSON.stringify(r.rows),"utf8"),a=Math.max(1,Math.ceil(u/r.rows.length)),l=(n.estimated_tokens-n.token_budget)*4,_=Math.min(s,Math.max(1,Math.ceil(l/a)));r.rows.splice(-_,_),i=!0}}function $(t,e,n){if(typeof e.for!="string")return n;const o=t.startsWith("list-")?"list":t;if(!(o in W))return n;const i=o,r=X(i,e.for),d=w(e),s=C(d,e.tokenBudget??e.token_budget,r.token_budget),u={command:i,intent:r.intent,source:r.source,included_field_groups:[...r.included_field_groups],token_budget:s,declared_token_budget:r.token_budget,token_budget_override:s-r.token_budget,estimated_tokens:0,within_budget:!0,degradation:wt[i],declaration_feasible:!0,result_omitted:!1},a={...n},l=v(i,r.intent,u.token_budget,k(e.tokenBudget??e.token_budget)!==void 0||typeof d=="number");if(l!==void 0){const g=k(e.limit),h=g!==void 0&&g<l;u.budget_derived_limit=l,u.binding_constraint=h?"explicit_limit":"token_budget",u.limit_reason=h?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",a.budget_derived_limit=l,St({builtInCommand:i,intent:r.intent},u,a,e)}const _=L.get(e)??0,c=u.token_budget;u.token_budget=c-_;const f=d==="unbounded"?M(a,u,e):Tt(i,a,u,e,st(t,e));u.declaration_feasible=u.estimated_tokens<=u.declared_token_budget;const b=V(d,u,f,()=>Y(t,i,r.intent,{...u,token_budget:c,estimated_tokens:u.estimated_tokens+_},a,e));return u.result_omitted&&(u.estimated_tokens+=_,u.declaration_feasible=u.estimated_tokens<=u.declared_token_budget),u.token_budget=c,b}function M(t,e,n){const o={...t,context_intent:e};return p(o,e,n),o}function Tt(t,e,n,o,i){let r=M(e,n,o);return n.estimated_tokens>n.token_budget&&(n.degradation="recursive_budget_compaction",r=M(S(e,i),n,o)),n.estimated_tokens>n.token_budget&&Et(t,r,n,o)&&(n.degradation="budget_row_compaction",p(r,n,o)),r}const L=new WeakMap;function V(t,e,n,o){return e.estimated_tokens<=e.token_budget||(e.within_budget=!1,t==="unbounded")?n:(e.degradation="budget_receipt_only",e.result_omitted=!0,typeof t=="number"?{output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},context_intent:e}:{budget_exceeded:{omitted_result:!0,reason:e.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:o()},context_intent:e})}const Rt=["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"];function Bt(t,e){if(typeof e!="string"||e.length===0)return!1;if(nt(t)===void 0)return!0;try{return ot(e),!0}catch{return!1}}function Q(t,e,n){if(!Bt(t,e.after)||z(n))return n;const o=J(e.after)?.fingerprint??"opaque_cursor",i={...n};for(const r of Rt)delete i[r];return i.continuation_contract={fingerprint:o,metadata:"reference",restore_with:"omit --after"},i}function m(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function At(t,e){const n=t==="get"&&m(e.item)&&typeof e.item.id=="string"?e.item.id:t==="search"&&typeof e.query=="string"?e.query:void 0;return n===void 0?"":` ${I(n)}`}function Nt(t){return typeof t.fields=="string"&&t.fields.trim()!==""?` --fields ${I(t.fields)}`:""}function St(t,e,n,o){const i=k(o.limit),r=e.budget_derived_limit;if(i===void 0||i<=r)return;const{overhead:d,rowCost:s}=F(t.builtInCommand,t.intent),u=Math.max(e.token_budget,d+s*i);e.limit_reason=`The ${e.token_budget}-token ${t.intent} budget carries ${r} rows, so it reduced the caller's --limit ${i}.`,e.limit_override={flag:"--limit",requested:i,effective:r,...Number.isSafeInteger(u)?{token_budget_for_requested:u,restore_with:`${xt(o)} ${u}`}:{}};const a=`${ht}:--limit ${i}->${r}`;n.warnings=Array.isArray(n.warnings)?[...n.warnings,a]:[a],m(n.filters)&&(n.filters={...n.filters,requested_limit:String(i)})}function Y(t,e,n,o,i,r){const d=At(e,i),s=e==="get"?"":` --limit ${o.budget_derived_limit??1}`,{output_budget:u}=lt({effective_budget_tokens:o.token_budget,measured_result_tokens:o.estimated_tokens});return`pm ${t}${d}${Nt(r)} --for ${I(n)} --token-budget ${u}${s}`}function y(t,e){if(m(t))return typeof t[e]=="number"?t[e]:void 0}function H(t,e){let n=t;for(let o=0;o<8;o+=1){$t(n);const i=y(n.context_intent,"estimated_tokens"),r=y(n.read_output,"estimated_tokens"),d=y(n.read_session,"spent_this_call_tokens");if(m(n.context_intent)&&n.context_intent.result_omitted!==!0&&p(n,n.context_intent,e),n=ct(n,e),y(n.context_intent,"estimated_tokens")===i&&y(n.read_output,"estimated_tokens")===r&&y(n.read_session,"spent_this_call_tokens")===d)break}return n}function $t(t){const e=t.context_intent;m(e)&&Number(e.estimated_tokens)>Number(e.token_budget)&&(e.within_budget=!1)}function Mt(t,e){const n=e.context_intent;if(!m(n)||n.result_omitted===!0)return;const o=n.degradation==="recursive_budget_compaction"||n.degradation==="budget_row_compaction",i={...e};for(const r of _t(t)){const d=e[r.path];if(Array.isArray(d)&&Array.isArray(r.value)&&d.length<=r.value.length){const s=r.value.slice(0,d.length);i[r.path]=o?s.map(D):s}}return i}function D(t){return Array.isArray(t)?t.map(D):t!==null&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,D(n)])):t}function ee(t,e,n){const o=rt(t,et(t??"",n));if(typeof o!="object"||o===null||Array.isArray(o))return R(n,o),o;const i=t??"",r=o,d=$(i,e,r),s=y(d.context_intent,"estimated_tokens"),u=Mt(r,d),a=O(i,e,n,d,u),l=P(e,a,d.context_intent);if(l===void 0)return Lt(e,a,d)?Pt(i,e,n,r,d,Number(s),u,a):a;const _={...e};L.set(_,l.estimated-Number(s));const c=$(i,_,r),f=Z(i,e,_,n,c,u),b=f===void 0?l:P(e,f,c.context_intent);if(b===void 0)return f;const g={...b.receipt,estimated_tokens:b.estimated};return O(i,{...e,outputCursor:void 0,output_cursor:void 0},n,V(w(e),g,f??a,()=>Y(i,g.command,g.intent,g,r,e)))}function Lt(t,e,n){const o=n.context_intent;return Object.hasOwn(e,"output_budget_exceeded")&&m(o)&&o.result_omitted!==!0&&Dt.has(String(o.command))&&(t.outputInclude??t.output_include)===void 0&&(t.outputSession??t.output_session)===void 0}const Dt=new Set(["list","search"]);function Pt(t,e,n,o,i,r,d,s){const u=O(t,{...e,outputBudget:"unbounded"},n,{...i,context_intent:{...i.context_intent}},d),a={...e};L.set(a,E(u,T(e))-r);const l=$(t,a,o),_=Z(t,e,a,n,l,d);return _===void 0||Object.hasOwn(_,"output_budget_exceeded")||P(e,_,l.context_intent)!==void 0?s:_}function Z(t,e,n,o,i,r){return z(i)||qt(e,i)?void 0:O(t,n,o,i,r)}function qt(t,e){const n=t.outputCursor??t.output_cursor;if(typeof n!="string")return!1;const o=ut(n),i=e[o.path];return Array.isArray(i)&&i.length<=o.offset}function P(t,e,n){const o=m(e.context_intent),i=o?e.context_intent:n;if(!m(i)||i.result_omitted===!0||Object.hasOwn(e,"output_budget_exceeded"))return;const r=i,d=o?r.estimated_tokens:E(e,T(t));return w(t)==="unbounded"||d<=r.token_budget?void 0:{receipt:r,estimated:d}}function zt(t){return!m(t)||t.result_omitted===!0?{}:{mirrorEstimate:(e,n)=>{m(e.context_intent)&&(e.context_intent.estimated_tokens=n)}}}function O(t,e,n,o,i){const r={...e,outputRowContract:e.outputRowContract===!0||e.output_row_contract===!0};ft(r,{...i===void 0?{}:{continuationBinding:Q(t,e,i)},...zt(o.context_intent)});const d=dt(t,r,Q(t,e,o));if(R(n,d),e.outputRowContract===!0||e.output_row_contract===!0||!Object.hasOwn(d,"row_contract"))return m(d.context_intent)?H(d,e):d;const s=Object.fromEntries(Object.entries(d).filter(([a])=>a!=="row_contract"));Object.defineProperty(s,"row_contract",{value:d.row_contract,enumerable:!1,configurable:!0});const u=H(s,e);return delete u.row_contract,R(d,u),u}export{ht as CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING,U as PM_CONTEXT_INTENT_CONTRACTS,te as applyContextIntentProjection,$ as attachContextIntentReceipt,ee as attachReadOutputContracts,yt as composeContextIntentContracts,vt as contextIntentRowId,J as decodeContextIntentCursor,kt as getActiveContextIntentContracts,X as resolveContextIntentContract,jt as runWithContextIntentContracts};
1
+ import{AsyncLocalStorage as tt}from"node:async_hooks";import{attachExtensionReadOutputRows as et,resolveExtensionOutputCommand as nt}from"./read-output/extension.js";import{quoteCommandArg as I,renderPmCommand as q}from"./command-line.js";import{attachOutputOmissionReceipt as rt}from"./output-projection.js";import{resolveNativeReadOutputSurface as ot}from"./read-output/surfaces.js";import{decodeQueryCursorEnvelope as it,encodeQueryCursor as dt}from"./pagination.js";import{applyReadOutputDimensions as ut,decodeReadOutputContinuationCursor as st,isReadResultOmittedForBudget as z,resolveReadOutputSurface as at,stabilizeReadOutputReceiptEstimates as ct}from"./read-output-contracts.js";import{estimateReadOutputTokens as E,MAX_ESTIMATE_ITERATIONS as ft,readOutputMeasurementFormat as T,registerReadOutputPassHooks as lt,resolveReadOutputRecoveryBudget as _t}from"./read-output-budget.js";import{propagateContextUsageServingReceipt as R}from"./context-usage.js";import{readOutputContinuationRowCollections as gt}from"./read-output-rows.js";import{EXIT_CODE as B}from"../core/shared/constants.js";import{PmCliError as A}from"../core/shared/errors.js";import{compactExplanatoryString as mt,isContinuationTokenKey as bt,isTrackerItemDocumentKey as ht}from"../core/shared/text-normalization.js";const kt="limit_overridden_by_intent",U=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),G=new tt;function pt(){return G.getStore()??U}function ee(t,e){return G.run(wt(t.workspaceContracts,t.packageContracts),e)}function yt(t,e){const n=t.command.trim().toLowerCase(),i=t.intent.trim().toLowerCase(),o=`${n}:${i}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(n)||!/^[a-z0-9][a-z0-9-]*$/.test(i))throw new TypeError(`Invalid context intent command or name: ${o}`);if(t.description.trim().length===0)throw new TypeError(`Context intent ${o} requires a non-empty description`);if(!Number.isSafeInteger(t.token_budget)||t.token_budget<=0)throw new TypeError(`Context intent ${o} requires a positive integer token_budget`);const r=[...new Set(t.included_field_groups.map(d=>d.trim()).filter(Boolean))];if(r.length===0)throw new TypeError(`Context intent ${o} requires included_field_groups`);return{command:n,intent:i,description:t.description.trim(),included_field_groups:r,token_budget:t.token_budget,source:e}}function wt(t=[],e=[]){const n=[{source:"core",contracts:U,allowOverride:!1},{source:"package",contracts:e,allowOverride:!1},{source:"workspace",contracts:t,allowOverride:!0}],i=new Map,o=new Set;for(const r of n){o.clear();for(const d of r.contracts){const s=yt(d,r.source),u=`${s.command}:${s.intent}`;if(o.has(u))throw new TypeError(`Duplicate context intent declaration: ${u}`);if(o.add(u),!r.allowOverride&&i.has(u))throw new TypeError(`Duplicate context intent declaration: ${u}`);i.set(u,s)}}return[...i.values()].sort((r,d)=>r.command.localeCompare(d.command)||r.intent.localeCompare(d.intent))}function X(t,e,n=pt(),i=[]){const o=t.trim().toLowerCase(),r=e.trim().toLowerCase(),d=n.find(a=>a.command===o&&a.intent===r);if(d)return{...d,source:d.source??"core"};const s=n.filter(a=>a.command===o).map(a=>a.intent);if(s.length===0)return;const u=s.map(a=>{const l=Array.from({length:r.length+1},(m,h)=>h);for(let m=1;m<=a.length;m+=1){let h=l[0];l[0]=m;for(let g=1;g<=r.length;g+=1){const j=l[g];l[g]=Math.min(l[g]+1,l[g-1]+1,h+(a[m-1]===r[g-1]?0:1)),h=j}}return{candidate:a,distance:l[r.length]}}).sort((a,l)=>a.distance-l.distance||a.candidate.localeCompare(l.candidate))[0].candidate,c=[o,...i,"--for",r],f=[o,...i,"--for",u],_=q(f);throw new A(`Unknown context intent "${r}" for ${o}. Did you mean "${u}"?`,B.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:r,required:`Use a declared ${o} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[_],recovery:{recovery_mode:"compact",attempted_command:q(c),allowed_values:[...s].sort(),suggested_retry:_,suggested_retry_args:f}})}function N(t,e){const n=k(t.limit),i=String(n===void 0?e:Math.min(n,e));return(t.limit===void 0||n!==void 0)&&(t.limit=i),i}const W={context:(t,e,n,i)=>{t.section===void 0&&t.depth===void 0&&(t.section=e.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]),t.depth===void 0&&(t.depth=e.intent==="handoff"?"deep":"standard");const o=C(i,t.tokenBudget,e.token_budget),r=v("context",e.intent,o,n),d=N(t,r);t.activityLimit===void 0&&(t.activityLimit=d)},get:t=>{t.depth===void 0&&t.fields===void 0&&(t.depth="standard")},list:(t,e,n,i)=>{t.brief===void 0&&t.compact===void 0&&t.full===void 0&&t.fields===void 0&&(t.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");const o=C(i,t.tokenBudget,e.token_budget),r=v("list",e.intent,o,n);N(t,r)},next:t=>{t.readyOnly===void 0&&(t.readyOnly=!0)},search:(t,e,n,i)=>{t.compact===void 0&&t.full===void 0&&t.fields===void 0&&(t.compact=!0);const o=C(i,t.tokenBudget,e.token_budget),r=v("search",e.intent,o,n);N(t,r)}};function ne(t,e,n=[]){const i=e.tokenBudget??e.token_budget;if(typeof e.for!="string"){if(i!==void 0&&(t==="get"||t==="list"||t==="search"))throw new A("--token-budget requires a declared context intent selected with --for",B.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(e.tokenBudget!==void 0||e.token_budget===void 0)return e;const u={...e,tokenBudget:i};return delete u.token_budget,u}const o=X(t,e.for,void 0,n),r=w(e),d=k(i)!==void 0||typeof r=="number",s={...e};return s.tokenBudget===void 0&&i!==void 0&&(s.tokenBudget=i),delete s.token_budget,typeof r=="number"?s.tokenBudget=String(r):s.tokenBudget===void 0&&(s.tokenBudget=String(o.token_budget)),W[t](s,o,d,r),s}const xt={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},x=256;function S(t,e,n=!0,i=!0){return Array.isArray(t)?t.map(o=>S(o,e,n,!1)):t!==null&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([o,r])=>[o,n&&typeof r=="string"&&bt(o)?r:S(r,e,n&&!(i&&ht(e,o)),!1)])):typeof t=="string"?mt(t):t}function k(t){const e=typeof t=="number"?t:typeof t=="string"&&/^\d+$/u.test(t.trim())?Number(t):Number.NaN;return Number.isSafeInteger(e)&&e>0?e:void 0}function w(t){const e=t.outputBudget??t.output_budget;return e==="unbounded"?e:k(e)}function Ct(t){return w(t)===void 0?"--token-budget":"--output-budget"}function C(t,e,n){return typeof t=="number"?t:vt(e,n)}function vt(t,e){const n=k(t);if(n===void 0)return e;if(n<x)throw new A(`Context intent token budget must be at least ${x}`,B.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(t),required:`Use an integer token budget of at least ${x}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${x} or omit the override.`]});return n}function F(t,e){const n=t==="context"&&e==="orient";return t==="context"?n?{overhead:1200,rowCost:600}:{overhead:800,rowCost:500}:{overhead:t==="list"?520:480,rowCost:16}}function v(t,e,n,i){if(t==="get"||t==="next")return;const{overhead:o,rowCost:r}=F(t,e),d=Math.max(t==="context"?1:2,Math.floor((n-o)/r));return i?d:Math.min(t==="context"?20:100,d)}function p(t,e,n){const i=T(n),o=n.outputRowContract===!0||n.output_row_contract===!0;let r=e.estimated_tokens,d=r;for(let s=0;s<ft;s+=1){e.estimated_tokens=r;const u=E(o||!Object.hasOwn(t,"row_contract")?t:Object.fromEntries(Object.entries(t).filter(([c])=>c!=="row_contract")),i);if(u===r)return;r=u,d=Math.max(d,r)}e.estimated_tokens=d}const K={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function J(t){try{const e=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));return typeof e.fingerprint!="string"||!Number.isSafeInteger(e.after_index)?void 0:{fingerprint:e.fingerprint,after_index:e.after_index,...typeof e.snapshot=="string"?{snapshot:e.snapshot}:{}}}catch{return}}function Ot(t){if(t===null||typeof t!="object")return;if(typeof t.id=="string")return t.id;const e=t.item?.id;return typeof e=="string"?e:void 0}function It(t,e,n,i){let o=!1;for(;;){if(p(t,e,i),e.estimated_tokens<=e.token_budget||n.length<=1)return o;const r=Buffer.byteLength(JSON.stringify(n),"utf8"),d=(e.estimated_tokens-e.token_budget)*4;n.splice(-Math.min(n.length-1,Math.max(1,Math.ceil(d/Math.max(1,Math.ceil(r/n.length)))))),o=!0}}function Et(t,e,n){const i=t.items,o=typeof t.next_cursor=="string",r=o?t.next_cursor:n.after;if(!Array.isArray(i)||typeof r!="string")return!1;const d=J(r);if(d===void 0)return!1;const s=i.length,u=[...i];let c=!1;for(;;){if(c=It(t,e,i,n)||c,!c)return!1;const f=Ot(i.at(-1));if(f===void 0)return i.splice(0,i.length,...u),p(t,e,n),!1;if(t.next_cursor=dt(d.fingerprint,f,o?d.after_index-(s-i.length):d.after_index+i.length,d.snapshot),p(t,e,n),e.estimated_tokens<=e.token_budget||i.length<=1)break}return typeof t.count=="number"&&(t.count=i.length),typeof t.applied_limit=="number"&&(t.applied_limit=i.length),!0}function Tt(t,e,n,i){if(t==="list"||t==="search")return Et(e,n,i);if(t!=="next"||typeof e.next_cursor=="string")return!1;let o=!1;for(;;){if(p(e,n,i),n.estimated_tokens<=n.token_budget)return o;const r=K[t].map(a=>({key:a,rows:Array.isArray(e[a])?e[a]:[]})).filter(({rows:a})=>a.length>0).sort((a,l)=>l.rows.length-a.rows.length||a.key.localeCompare(l.key))[0];if(r===void 0)return o;const d=K[t].reduce((a,l)=>a+(Array.isArray(e[l])?e[l].length:0),0);if(d<=1)return o;const s=Math.min(r.rows.length,d-1),u=Buffer.byteLength(JSON.stringify(r.rows),"utf8"),c=Math.max(1,Math.ceil(u/r.rows.length)),f=(n.estimated_tokens-n.token_budget)*4,_=Math.min(s,Math.max(1,Math.ceil(f/c)));r.rows.splice(-_,_),o=!0}}function $(t,e,n){if(typeof e.for!="string")return n;const i=t.startsWith("list-")?"list":t;if(!(i in W))return n;const o=i,r=X(o,e.for),d=w(e),s=C(d,e.tokenBudget??e.token_budget,r.token_budget),u={command:o,intent:r.intent,source:r.source,included_field_groups:[...r.included_field_groups],token_budget:s,declared_token_budget:r.token_budget,token_budget_override:s-r.token_budget,estimated_tokens:0,within_budget:!0,degradation:xt[o],declaration_feasible:!0,result_omitted:!1},c={...n},f=v(o,r.intent,u.token_budget,k(e.tokenBudget??e.token_budget)!==void 0||typeof d=="number");if(f!==void 0){const h=k(e.limit),g=h!==void 0&&h<f;u.budget_derived_limit=f,u.binding_constraint=g?"explicit_limit":"token_budget",u.limit_reason=g?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",c.budget_derived_limit=f,$t({builtInCommand:o,intent:r.intent},u,c,e)}const _=L.get(e)??0,a=u.token_budget;u.token_budget=a-_;const l=d==="unbounded"?M(c,u,e):Rt(o,c,u,e,at(t,e));u.declaration_feasible=u.estimated_tokens<=u.declared_token_budget;const m=V(d,u,l,()=>Y(t,o,r.intent,{...u,token_budget:a,estimated_tokens:u.estimated_tokens+_},c,e));return u.result_omitted&&(u.estimated_tokens+=_,u.declaration_feasible=u.estimated_tokens<=u.declared_token_budget),u.token_budget=a,m}function M(t,e,n){const i={...t,context_intent:e};return p(i,e,n),i}function Rt(t,e,n,i,o){let r=M(e,n,i);return n.estimated_tokens>n.token_budget&&(n.degradation="recursive_budget_compaction",r=M(S(e,o),n,i)),n.estimated_tokens>n.token_budget&&Tt(t,r,n,i)&&(n.degradation="budget_row_compaction",p(r,n,i)),r}const L=new WeakMap;function V(t,e,n,i){return e.estimated_tokens<=e.token_budget||(e.within_budget=!1,t==="unbounded")?n:(e.degradation="budget_receipt_only",e.result_omitted=!0,typeof t=="number"?{output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},context_intent:e}:{budget_exceeded:{omitted_result:!0,reason:e.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:i()},context_intent:e})}const Bt=["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"];function At(t,e){if(typeof e!="string"||e.length===0)return!1;if(nt(t)===void 0)return!0;try{return it(e),!0}catch{return!1}}function Q(t,e,n){if(!At(t,e.after)||z(n))return n;const i=J(e.after)?.fingerprint??"opaque_cursor",o={...n};for(const r of Bt)delete o[r];return o.continuation_contract={fingerprint:i,metadata:"reference",restore_with:"omit --after"},o}function b(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Nt(t,e){const n=t==="get"&&b(e.item)&&typeof e.item.id=="string"?e.item.id:t==="search"&&typeof e.query=="string"?e.query:void 0;return n===void 0?"":` ${I(n)}`}function St(t){return typeof t.fields=="string"&&t.fields.trim()!==""?` --fields ${I(t.fields)}`:""}function $t(t,e,n,i){const o=k(i.limit),r=e.budget_derived_limit;if(o===void 0||o<=r)return;const{overhead:d,rowCost:s}=F(t.builtInCommand,t.intent),u=Math.max(e.token_budget,d+s*o);e.limit_reason=`The ${e.token_budget}-token ${t.intent} budget carries ${r} rows, so it reduced the caller's --limit ${o}.`,e.limit_override={flag:"--limit",requested:o,effective:r,...Number.isSafeInteger(u)?{token_budget_for_requested:u,restore_with:`${Ct(i)} ${u}`}:{}};const c=`${kt}:--limit ${o}->${r}`;n.warnings=Array.isArray(n.warnings)?[...n.warnings,c]:[c],b(n.filters)&&(n.filters={...n.filters,requested_limit:String(o)})}function Y(t,e,n,i,o,r){const d=Nt(e,o),s=e==="get"?"":` --limit ${i.budget_derived_limit??1}`,{output_budget:u}=_t({effective_budget_tokens:i.token_budget,measured_result_tokens:i.estimated_tokens});return`pm ${t}${d}${St(r)} --for ${I(n)} --token-budget ${u}${s}`}function y(t,e){if(b(t))return typeof t[e]=="number"?t[e]:void 0}function H(t,e){let n=t;for(let i=0;i<8;i+=1){Mt(n);const o=y(n.context_intent,"estimated_tokens"),r=y(n.read_output,"estimated_tokens"),d=y(n.read_session,"spent_this_call_tokens");if(b(n.context_intent)&&n.context_intent.result_omitted!==!0&&p(n,n.context_intent,e),n=ct(n,e),y(n.context_intent,"estimated_tokens")===o&&y(n.read_output,"estimated_tokens")===r&&y(n.read_session,"spent_this_call_tokens")===d)break}return n}function Mt(t){const e=t.context_intent;b(e)&&Number(e.estimated_tokens)>Number(e.token_budget)&&(e.within_budget=!1)}function Lt(t,e){const n=e.context_intent;if(!b(n)||n.result_omitted===!0)return;const i=n.degradation==="recursive_budget_compaction"||n.degradation==="budget_row_compaction",o={...e};for(const r of gt(t)){const d=e[r.path];if(Array.isArray(d)&&Array.isArray(r.value)&&d.length<=r.value.length){const s=r.value.slice(0,d.length);o[r.path]=i?s.map(D):s}}return o}function D(t){return Array.isArray(t)?t.map(D):t!==null&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,D(n)])):t}function re(t,e,n){const i=ot((t??"").trim().toLowerCase(),e)==="package-catalog"?"package-catalog":t,o=rt(i,et(t??"",n));if(typeof o!="object"||o===null||Array.isArray(o))return R(n,o),o;const r=t??"",d=o,s=$(r,e,d),u=y(s.context_intent,"estimated_tokens"),c=Lt(d,s),f=O(r,e,n,s,c),_=P(e,f,s.context_intent);if(_===void 0)return Dt(e,f,s)?qt(r,e,n,d,s,Number(u),c,f):f;const a={...e};L.set(a,_.estimated-Number(u));const l=$(r,a,d),m=Z(r,e,a,n,l,c),h=m===void 0?_:P(e,m,l.context_intent);if(h===void 0)return m;const g={...h.receipt,estimated_tokens:h.estimated};return O(r,{...e,outputCursor:void 0,output_cursor:void 0},n,V(w(e),g,m??f,()=>Y(r,g.command,g.intent,g,d,e)))}function Dt(t,e,n){const i=n.context_intent;return Object.hasOwn(e,"output_budget_exceeded")&&b(i)&&i.result_omitted!==!0&&Pt.has(String(i.command))&&(t.outputInclude??t.output_include)===void 0&&(t.outputSession??t.output_session)===void 0}const Pt=new Set(["list","search"]);function qt(t,e,n,i,o,r,d,s){const u=O(t,{...e,outputBudget:"unbounded"},n,{...o,context_intent:{...o.context_intent}},d),c={...e};L.set(c,E(u,T(e))-r);const f=$(t,c,i),_=Z(t,e,c,n,f,d);return _===void 0||Object.hasOwn(_,"output_budget_exceeded")||P(e,_,f.context_intent)!==void 0?s:_}function Z(t,e,n,i,o,r){return z(o)||zt(e,o)?void 0:O(t,n,i,o,r)}function zt(t,e){const n=t.outputCursor??t.output_cursor;if(typeof n!="string")return!1;const i=st(n),o=e[i.path];return Array.isArray(o)&&o.length<=i.offset}function P(t,e,n){const i=b(e.context_intent),o=i?e.context_intent:n;if(!b(o)||o.result_omitted===!0||Object.hasOwn(e,"output_budget_exceeded"))return;const r=o,d=i?r.estimated_tokens:E(e,T(t));return w(t)==="unbounded"||d<=r.token_budget?void 0:{receipt:r,estimated:d}}function Ut(t){return!b(t)||t.result_omitted===!0?{}:{mirrorEstimate:(e,n)=>{b(e.context_intent)&&(e.context_intent.estimated_tokens=n)}}}function O(t,e,n,i,o){const r={...e,outputRowContract:e.outputRowContract===!0||e.output_row_contract===!0};lt(r,{...o===void 0?{}:{continuationBinding:Q(t,e,o)},...Ut(i.context_intent)});const d=ut(t,r,Q(t,e,i));if(R(n,d),e.outputRowContract===!0||e.output_row_contract===!0||!Object.hasOwn(d,"row_contract"))return b(d.context_intent)?H(d,e):d;const s=Object.fromEntries(Object.entries(d).filter(([c])=>c!=="row_contract"));Object.defineProperty(s,"row_contract",{value:d.row_contract,enumerable:!1,configurable:!0});const u=H(s,e);return delete u.row_contract,R(d,u),u}export{kt as CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING,U as PM_CONTEXT_INTENT_CONTRACTS,ne as applyContextIntentProjection,$ as attachContextIntentReceipt,re as attachReadOutputContracts,wt as composeContextIntentContracts,Ot as contextIntentRowId,J as decodeContextIntentCursor,pt as getActiveContextIntentContracts,X as resolveContextIntentContract,ee as runWithContextIntentContracts};
2
2
  //# sourceMappingURL=context-intent-contracts.js.map
@@ -5,11 +5,30 @@
5
5
  */
6
6
  export declare function resolveExpectHashAction(path:string):string;
7
7
  /**
8
- * Whether a command path admits `--expect-hash`. A native action that never
9
- * writes items refuses it (`deps` is a conditional mutation in the history
10
- * inventory, but only reads), and so do a statically dispatched inventory and
11
- * a read-only subcommand of a writer root.
12
- * Extension and package actions stay admitted because only their handlers know
13
- * whether they write.
14
- */
15
- export declare function isExpectHashAdmissibleAction(path:string):boolean;
8
+ * The action an SDK or MCP call's guard is judged on: the caller's own action
9
+ * name when it is native, since an alias such as `package-catalog` names its
10
+ * operation exactly as `pm package catalog` does, else the action it resolves
11
+ * to (an extension action, or a non-native shorthand such as `ctx`).
12
+ */
13
+ export declare function resolveExpectHashCallAction(requested:string|undefined,resolved:string):string;
14
+ /**
15
+ * Whether a command path admits `--expect-hash` in at least one mode, the
16
+ * answer discovery publishes. A native action admits it when it can write an
17
+ * existing item (`PM_EXPECT_HASH_ACTIONS`), and `schema` does in its item
18
+ * rewriting migrations and policy approvals; reads refuse it, and so do native writers that create
19
+ * new items or write only settings and caches (`create`, `copy`, `config`,
20
+ * `gc`, `profile`; pm-oehf5s). A statically dispatched inventory and a
21
+ * read-only subcommand of a writer root refuse it too. Extension and package
22
+ * actions stay admitted because only their handlers know whether they write.
23
+ */
24
+ export declare function isExpectHashAdmissibleAction(path:string):boolean;
25
+ /**
26
+ * Whether one invocation admits `--expect-hash`, the answer the runtime
27
+ * enforces: as {@link isExpectHashAdmissibleAction}, except that `schema`
28
+ * admits it only for the subcommands that rewrite existing items.
29
+ */
30
+ export declare function isExpectHashAdmissibleInvocation(path:string,subcommand:unknown):boolean;
31
+ /** The schema subcommands that admit the guard, for refusal guidance that names the same list. */
32
+ export declare function expectHashAdmittedSchemaSubcommands():readonly string[];
33
+ /** The mode condition discovery states beside an admitted guard, when the action admits it only in some modes. */
34
+ export declare function expectHashAdmissionCondition(path:string):string|undefined;
@@ -1,2 +1,2 @@
1
- import{PM_EXPECT_HASH_ACTIONS as i,PM_TOOL_ACTIONS as n}from"../cli-contracts/enum-contracts.js";import{STATIC_INVENTORY_COMMAND_PATHS as r}from"../cli-contracts/flag-contracts.js";import{isMutationAction as c}from"../mutation-guard.js";const s=new Set(n),a=new Set(["files lookup","item files lookup"]);function A(e){const t=e.trim().replace(/^packages(?=\s|$)/u,"package").replace(/\s+/gu,"-");return s.has(t)?t:e}function m(e){const t=e.trim().replace(/\s+/gu," ");if(r.has(t)||a.has(t))return!1;const o=A(e);return!(s.has(o)&&(!c(o)||o==="deps")&&!i.has(o))}export{m as isExpectHashAdmissibleAction,A as resolveExpectHashAction};
1
+ import{PM_EXPECT_HASH_ACTIONS as r,PM_EXPECT_HASH_CONDITIONAL_ACTIONS as c,PM_EXPECT_HASH_HANDLER_DECIDED_ACTIONS as A,PM_EXPECT_HASH_SCHEMA_SUBCOMMANDS as a,PM_TOOL_ACTIONS as _}from"../cli-contracts/enum-contracts.js";import{STATIC_INVENTORY_COMMAND_PATHS as E}from"../cli-contracts/flag-contracts.js";const i=new Set(_),S=new Set(["files lookup","item files lookup"]);function o(e){const t=e.trim().replace(/^packages(?=\s|$)/u,"package").replace(/\s+/gu,"-");return i.has(t)?t:e}function l(e,t){return e!==void 0&&i.has(e)?e:t}const s=a;function p(e){const t=e.trim().replace(/\s+/gu," ");if(E.has(t)||S.has(t))return!1;const n=o(e);return!i.has(n)||r.has(n)||c.has(n)||A.has(n)}function T(e,t){return p(e)?o(e)!=="schema"||typeof t=="string"&&s.includes(t.trim().toLowerCase()):!1}function h(){return s}function H(e){return o(e)==="schema"?`Applies only to ${s.join(", ")}, which write existing items.`:void 0}export{H as expectHashAdmissionCondition,h as expectHashAdmittedSchemaSubcommands,p as isExpectHashAdmissibleAction,T as isExpectHashAdmissibleInvocation,o as resolveExpectHashAction,l as resolveExpectHashCallAction};
2
2
  //# sourceMappingURL=expect-hash-admission.js.map
@@ -1,6 +1,6 @@
1
1
  import{bindItemRevisionScope,createItemRevisionScope,itemRevisionScopeReceipt,runWithItemRevisionScope,type ItemRevisionRecoveryInvocation,type ItemRevisionScope}from "../../core/store/item-mutation-precondition.js";import{PmCliError,type PmCliErrorDetails}from "../../core/shared/errors.js";
2
2
  /** Re-exported so presentation layers judge `--expect-hash` admission through this public module (pm-6vk110). */
3
- export{isExpectHashAdmissibleAction}from "./expect-hash-admission.js";export type{ItemRevisionRecoveryInvocation,ItemRevisionScope}from "../../core/store/item-mutation-precondition.js";
3
+ export{expectHashAdmissionCondition,isExpectHashAdmissibleAction}from "./expect-hash-admission.js";export type{ItemRevisionRecoveryInvocation,ItemRevisionScope}from "../../core/store/item-mutation-precondition.js";
4
4
  /** Refusal code for a locked write that found a revision other than the declared one. */
5
5
  export declare const ITEM_REVISION_CONFLICT_CODE="item_revision_conflict";
6
6
  /** Most recent history entries a conflict refusal describes. */
@@ -146,17 +146,25 @@ export declare function itemRevisionUncheckedWarning(id:string):string;
146
146
  * Per-command discovery reads the same predicate (pm-6vk110).
147
147
  */
148
148
  export declare function assertExpectHashAdmissible(path:string,options?:Record<string,unknown>):void;
149
- /** Refusal for a revision guard on a command or action that writes no items. */
150
- export declare function expectHashRequiresMutationError(action:string):PmCliError;
149
+ /**
150
+ * Refusal for a revision guard on a command or action that writes no existing
151
+ * item. `create` and `copy` do write items, but only new ones, so the message
152
+ * says to remove the guard there rather than calling them reads.
153
+ */
154
+ export declare function expectHashRequiresMutationError(action:string,subcommand?:unknown):PmCliError;
151
155
  /**
152
156
  * Generic-dispatch entry for the `expectHash` action parameter used by MCP and
153
157
  * `PmClient.run`. Tokens follow the CLI grammar: a bare hash binds to the
154
158
  * action's `id`, and `<id>=<hash>` names the target explicitly.
155
159
  */
156
- export declare function dispatchWithExpectedItemRevisions<T>(params:{action:string;expectHash:unknown;defaultId?:string;pmRoot:string;run:()=> Promise<T>;
160
+ export declare function dispatchWithExpectedItemRevisions<T>(params:{action:string;
161
+ /** The caller's own action name before alias resolution, which names the operation a guard is judged on. */
162
+ requestedAction?:string;expectHash:unknown;defaultId?:string;pmRoot:string;run:()=> Promise<T>;
157
163
  /** Nested action options, consulted for modes the guard cannot cover (background test workers). */
158
164
  options?:Record<string,unknown>;
159
165
  /** Top-level background flag, consulted like `options.background`. */
160
166
  background?:unknown;
167
+ /** The verb a subcommand-dispatched action runs, resolved as its handler resolves it. */
168
+ subcommand?:unknown;
161
169
  /** Invocation whose tracker scope a revision refusal's recovery commands replay. */
162
170
  invocation?:ItemRevisionRecoveryInvocation;}):Promise<T>;
@@ -1,2 +1,2 @@
1
- import{getActiveExtensionRegistrations as S}from"../../core/extensions/index.js";import{URL_CREDENTIAL_PLACEHOLDER as b,redactUrlCredentialsInToken as T}from"../../core/shared/url-credentials.js";import{hashDocument as H}from"../../core/history/history.js";import{readHistoryEntries as N}from"../../core/history/read.js";import{resolveItemTypeRegistry as k}from"../../core/item/type-registry.js";import{bindItemRevisionScope as f,createItemRevisionScope as _,ITEM_REVISION_CONFLICT_CHANGED_REASON as O,ITEM_REVISION_CONFLICT_UNREADABLE_REASON as L,isItemRevisionRefusalFrom as U,isItemRevisionRefusalScoped as F,itemRevisionConflictGuidance as M,markItemRevisionRefusalScoped as P,retainItemRevisionRefusalTracker as l,itemRevisionScopeReceipt as g,runWithItemRevisionScope as v,activeItemRevisionExpectations as $}from"../../core/store/item-mutation-precondition.js";import{buildItemNotFoundError as D,locateItem as q,readLocatedItem as G}from"../../core/store/item-store.js";import{getHistoryPath as W,resolvePmRoot as V}from"../../core/store/paths.js";import{readSettings as j}from"../../core/store/settings.js";import{EXIT_CODE as m}from"../../core/shared/constants.js";import{PmCliError as d}from"../../core/shared/errors.js";import{isExpectHashAdmissibleAction as z,resolveExpectHashAction as B}from"./expect-hash-admission.js";import{isExpectHashAdmissibleAction as Le}from"./expect-hash-admission.js";import{resolveHistorySubject as J}from"../history/subject.js";import{resolvePhysicalItemId as K}from"../query/declared-blockers.js";import{EMPTY_CANONICAL_DOCUMENT as X}from"../../core/shared/constants.js";import{isPmCliExpectedError as Y}from"../errors.js";const w="item_revision_conflict",Q=10,R=/^[0-9a-f]{64}$/u;function p(e,i){return new d(`Invalid expected revision ${JSON.stringify(e)}: ${i}.`,m.USAGE,{code:"expect_hash_invalid",value:e,required:"Pass the 64-character item_hash from pm get <id> --json, optionally as <id>=<item_hash>.",examples:["--expect-hash <item_hash>","--expect-hash pm-a1b2=<item_hash>"]})}function I(e){const i=typeof e=="string"?e.trim().toLowerCase():"";if(!R.test(i))throw p(String(e),"the revision is not a 64-character hexadecimal item_hash");return i}function Z(e){return(e===void 0?[]:typeof e=="string"?[e]:e).flatMap(t=>{if(typeof t!="string")throw p(String(t),"expected a string");const n=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw p(t,"the value is empty");const r=o=>T(t)===t?o:b;return n.map(o=>{const c=o.lastIndexOf("="),s=c===-1?void 0:o.slice(0,c).trim();if(s!==void 0&&s.length===0)throw p(r(o),"the item id before = is empty");const a=c===-1?o:o.slice(c+1);if(!R.test(a.trim().toLowerCase()))throw p(r(a),"the revision is not a 64-character hexadecimal item_hash");const h=I(a);return s===void 0?{itemHash:h}:{id:s,itemHash:h}})})}async function E(e,i){const t=await j(e),n=k(t,S()).type_to_folder,r=await q(e,i,t.id_prefix,t.item_format,n);if(r){const{document:o}=await G(r,{schema:t.schema});if(o.metadata.id!==await K(r.itemPath,r.id))throw new d(`Item file ${r.id} embeds the id ${o.metadata.id}; no revision can be bound to an item whose identity is in conflict.`,m.CONFLICT,{code:"item_identity_conflict",item_id:r.id,required:`Repair ${r.id}'s identity first (pm validate reports it; pm restore ${r.id} <version> recovers a recorded state), then read its item_hash again.`});return{id:o.metadata.id,document:o}}try{return{id:(await J(e,i,t,n)).id,document:X}}catch{throw await D(e,i,t.id_prefix,n)}}function x(e){return V(e.cwd??process.cwd(),e.pmRoot)}async function Ce(e,i={}){const t=await E(x(i),e);return{id:t.id,item_hash:H(t.document)}}async function y(e,i,t){const n=[];for(const r of i){const o=r.id??t;if(o===void 0||o.trim().length===0)throw new d("A bare expected revision needs an item to bind to.",m.USAGE,{code:"expect_hash_target_required",required:"This command has no single item argument; name each target as --expect-hash <id>=<item_hash>.",examples:["--expect-hash pm-a1b2=<item_hash>"]});n.push({id:(await E(e,o)).id,itemHash:r.itemHash})}return n}function ee(e){return[...new Set(e.patch.map(i=>{const t=i.path.split("/");return String(t[1]==="metadata"?t[2]:t[1])}))].sort()}async function te(e,i,t){let n;try{n=await N(W(e,i),i)}catch{return}let r=-1;for(let s=n.length-1;s>=0;s-=1){const a=n[s];if(a.after_hash===t){r=s+1;break}if(a.before_hash===t){r=s;break}}if(r===-1)return{expected_revision_recorded:!1,changes_since:[],changes_since_omitted:0};const o=n.slice(r),c=o.slice(-Q);return{expected_revision_recorded:!0,changes_since:c.map(s=>({ts:s.ts,op:s.op,author:s.author,fields:ee(s)})),changes_since_omitted:o.length-c.length}}async function Ae(e,i){if(!u(e))return{};const t=await C(e,i);return{error_code:w,expected_revision:String(t.context.expected_revision),current_revision:String(t.context.current_revision),details:t.context.details}}function u(e){return Y(e)&&e.context.code===w}function Se(e){const i=e.find(t=>u(t));if(i!==void 0)throw i}function be(){return new d("--expect-hash cannot guard an invocation an extension override rewrote: which item it writes is not provable.",m.USAGE,{code:"expect_hash_invocation_rewritten",required:"Run the command without the rewriting extension (--no-extensions), or drop --expect-hash.",why:"An extension parser or preflight override changed this invocation's tracker or arguments, and final dispatch, the extension SDK client and the guard do not share one rewritten view."})}function ie(e,i){if(i===void 0||!u(e)||typeof e.context.item_id!="string"||F(e))return e;const t=e.context.reason===L;if(!t&&e.context.reason!==O)return e;const n=P(l(e,new d(e.message,e.exitCode,{...e.context,...M(e.context.item_id,t,i)})));return n.stack=e.stack,n}async function C(e,i,t){if(!U(e,i))return e;const n=ie(e,t);if(!u(n)||n.context.details!==void 0)return n;const r=n.context.item_id,o=n.context.expected_revision;if(typeof r!="string"||typeof o!="string")return n;let c;try{c=await te(i,r,o)}catch{return n}if(c===void 0)return n;const s={expected_revision_recorded:c.expected_revision_recorded,changes_since:c.changes_since.map(h=>({ts:h.ts,op:h.op,author:h.author,fields:[...h.fields]})),changes_since_omitted:c.changes_since_omitted},a=l(n,new d(n.message,n.exitCode,{...n.context,details:s}));return a.stack=n.stack,a}async function A(e,i,t){try{return{result:await v(e,i),...g(e)}}catch(n){throw e.pmRoot===void 0?n:await C(n,e.pmRoot,t)}}function ne(e){return e.cwd===void 0&&e.pmRoot===void 0?void 0:{scopeArgs:["--pm-path",x(e)]}}async function Te(e,i,t={}){return A(await oe(e,t),i,ne(t))}async function oe(e,i={}){const t=x(i),n=e.map(({id:o,itemHash:c})=>({id:o,itemHash:I(c)})),r=_();return f(r,t,await y(t,n)),r}function He(e){const i=$(e);return i===void 0||i.length>0}function re(e){return`expect_hash_unchecked:${e}:no_locked_write_reached_this_item`}function se(e,i={}){const t=B(e);if(!z(e))throw ce(t);if((t==="test"||t==="test-all")&&i.background===!0)throw new d(`--expect-hash cannot guard ${t} --background: the worker runs in another process.`,m.USAGE,{code:"expect_hash_background_unsupported",required:`Run ${t} in the foreground to guard its result recording, or drop --expect-hash for a background run.`})}function ce(e){return new d(`--expect-hash guards item writes, and ${e} is not a mutation.`,m.USAGE,{code:"expect_hash_requires_mutation",required:"Use --expect-hash (MCP/SDK expectHash) only on a command or action that writes items."})}function ae(e,i){if(i.length===0||typeof e!="object"||e===null||Array.isArray(e))return e;const t=e,n=Array.isArray(t.warnings)?t.warnings:[];return{...t,warnings:[...n,...i.map(re)]}}async function Ne(e){const i=e.expectHash;if(i!==void 0&&typeof i!="string"&&!(Array.isArray(i)&&i.every(o=>typeof o=="string")))throw p(JSON.stringify(i)??String(i),"expected a string or an array of strings");const t=Z(i);if(t.length===0)return e.run();se(e.action,{background:e.background===!0||e.options?.background===!0});const n=_();f(n,e.pmRoot,await y(e.pmRoot,t,e.defaultId));const r=await A(n,e.run,e.invocation);return ae(r.result,r.unchecked)}export{Q as ITEM_REVISION_CONFLICT_CHANGE_LIMIT,w as ITEM_REVISION_CONFLICT_CODE,se as assertExpectHashAdmissible,oe as bindExpectedItemRevisions,f as bindItemRevisionScope,_ as createItemRevisionScope,te as describeItemRevisionChanges,Ne as dispatchWithExpectedItemRevisions,C as enrichItemRevisionConflict,be as expectHashInvocationRewrittenError,ce as expectHashRequiresMutationError,Le as isExpectHashAdmissibleAction,u as isItemRevisionConflict,He as isTrackerRevisionGuarded,Ae as itemRevisionConflictRowFields,g as itemRevisionScopeReceipt,re as itemRevisionUncheckedWarning,I as normalizeExpectedItemHash,Z as parseExpectHashSpecs,Ce as readItemRevision,y as resolveExpectedItemRevisions,A as runWithBoundItemRevisionScope,v as runWithItemRevisionScope,ie as scopeItemRevisionConflict,Se as throwFirstItemRevisionConflict,Te as withExpectedItemRevisions};
1
+ import{getActiveExtensionRegistrations as S}from"../../core/extensions/index.js";import{URL_CREDENTIAL_PLACEHOLDER as b,redactUrlCredentialsInToken as H}from"../../core/shared/url-credentials.js";import{hashDocument as T}from"../../core/history/history.js";import{readHistoryEntries as N}from"../../core/history/read.js";import{resolveItemTypeRegistry as k}from"../../core/item/type-registry.js";import{bindItemRevisionScope as f,createItemRevisionScope as x,ITEM_REVISION_CONFLICT_CHANGED_REASON as O,ITEM_REVISION_CONFLICT_UNREADABLE_REASON as L,isItemRevisionRefusalFrom as $,isItemRevisionRefusalScoped as U,itemRevisionConflictGuidance as F,markItemRevisionRefusalScoped as M,retainItemRevisionRefusalTracker as _,itemRevisionScopeReceipt as g,runWithItemRevisionScope as w,activeItemRevisionExpectations as P}from"../../core/store/item-mutation-precondition.js";import{buildItemNotFoundError as q,locateItem as D,readLocatedItem as G}from"../../core/store/item-store.js";import{getHistoryPath as W,resolvePmRoot as j}from"../../core/store/paths.js";import{readSettings as V}from"../../core/store/settings.js";import{EXIT_CODE as m}from"../../core/shared/constants.js";import{PmCliError as d}from"../../core/shared/errors.js";import{expectHashAdmittedSchemaSubcommands as z,isExpectHashAdmissibleInvocation as B,resolveExpectHashAction as J,resolveExpectHashCallAction as K}from"./expect-hash-admission.js";import{expectHashAdmissionCondition as Ue,isExpectHashAdmissibleAction as Fe}from"./expect-hash-admission.js";import{resolveHistorySubject as X}from"../history/subject.js";import{resolvePhysicalItemId as Y}from"../query/declared-blockers.js";import{EMPTY_CANONICAL_DOCUMENT as Q}from"../../core/shared/constants.js";import{isPmCliExpectedError as Z}from"../errors.js";const v="item_revision_conflict",ee=10,I=/^[0-9a-f]{64}$/u;function p(e,i){return new d(`Invalid expected revision ${JSON.stringify(e)}: ${i}.`,m.USAGE,{code:"expect_hash_invalid",value:e,required:"Pass the 64-character item_hash from pm get <id> --json, optionally as <id>=<item_hash>.",examples:["--expect-hash <item_hash>","--expect-hash pm-a1b2=<item_hash>"]})}function R(e){const i=typeof e=="string"?e.trim().toLowerCase():"";if(!I.test(i))throw p(String(e),"the revision is not a 64-character hexadecimal item_hash");return i}function te(e){return(e===void 0?[]:typeof e=="string"?[e]:e).flatMap(t=>{if(typeof t!="string")throw p(String(t),"expected a string");const n=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw p(t,"the value is empty");const r=o=>H(t)===t?o:b;return n.map(o=>{const c=o.lastIndexOf("="),s=c===-1?void 0:o.slice(0,c).trim();if(s!==void 0&&s.length===0)throw p(r(o),"the item id before = is empty");const a=c===-1?o:o.slice(c+1);if(!I.test(a.trim().toLowerCase()))throw p(r(a),"the revision is not a 64-character hexadecimal item_hash");const h=R(a);return s===void 0?{itemHash:h}:{id:s,itemHash:h}})})}async function y(e,i){const t=await V(e),n=k(t,S()).type_to_folder,r=await D(e,i,t.id_prefix,t.item_format,n);if(r){const{document:o}=await G(r,{schema:t.schema});if(o.metadata.id!==await Y(r.itemPath,r.id))throw new d(`Item file ${r.id} embeds the id ${o.metadata.id}; no revision can be bound to an item whose identity is in conflict.`,m.CONFLICT,{code:"item_identity_conflict",item_id:r.id,required:`Repair ${r.id}'s identity first (pm validate reports it; pm restore ${r.id} <version> recovers a recorded state), then read its item_hash again.`});return{id:o.metadata.id,document:o}}try{return{id:(await X(e,i,t,n)).id,document:Q}}catch{throw await q(e,i,t.id_prefix,n)}}function l(e){return j(e.cwd??process.cwd(),e.pmRoot)}async function Se(e,i={}){const t=await y(l(i),e);return{id:t.id,item_hash:T(t.document)}}async function E(e,i,t){const n=[];for(const r of i){const o=r.id??t;if(o===void 0||o.trim().length===0)throw new d("A bare expected revision needs an item to bind to.",m.USAGE,{code:"expect_hash_target_required",required:"This command has no single item argument; name each target as --expect-hash <id>=<item_hash>.",examples:["--expect-hash pm-a1b2=<item_hash>"]});n.push({id:(await y(e,o)).id,itemHash:r.itemHash})}return n}function ie(e){return[...new Set(e.patch.map(i=>{const t=i.path.split("/");return String(t[1]==="metadata"?t[2]:t[1])}))].sort()}async function ne(e,i,t){let n;try{n=await N(W(e,i),i)}catch{return}let r=-1;for(let s=n.length-1;s>=0;s-=1){const a=n[s];if(a.after_hash===t){r=s+1;break}if(a.before_hash===t){r=s;break}}if(r===-1)return{expected_revision_recorded:!1,changes_since:[],changes_since_omitted:0};const o=n.slice(r),c=o.slice(-ee);return{expected_revision_recorded:!0,changes_since:c.map(s=>({ts:s.ts,op:s.op,author:s.author,fields:ie(s)})),changes_since_omitted:o.length-c.length}}async function be(e,i){if(!u(e))return{};const t=await A(e,i);return{error_code:v,expected_revision:String(t.context.expected_revision),current_revision:String(t.context.current_revision),details:t.context.details}}function u(e){return Z(e)&&e.context.code===v}function He(e){const i=e.find(t=>u(t));if(i!==void 0)throw i}function Te(){return new d("--expect-hash cannot guard an invocation an extension override rewrote: which item it writes is not provable.",m.USAGE,{code:"expect_hash_invocation_rewritten",required:"Run the command without the rewriting extension (--no-extensions), or drop --expect-hash.",why:"An extension parser or preflight override changed this invocation's tracker or arguments, and final dispatch, the extension SDK client and the guard do not share one rewritten view."})}function oe(e,i){if(i===void 0||!u(e)||typeof e.context.item_id!="string"||U(e))return e;const t=e.context.reason===L;if(!t&&e.context.reason!==O)return e;const n=M(_(e,new d(e.message,e.exitCode,{...e.context,...F(e.context.item_id,t,i)})));return n.stack=e.stack,n}async function A(e,i,t){if(!$(e,i))return e;const n=oe(e,t);if(!u(n)||n.context.details!==void 0)return n;const r=n.context.item_id,o=n.context.expected_revision;if(typeof r!="string"||typeof o!="string")return n;let c;try{c=await ne(i,r,o)}catch{return n}if(c===void 0)return n;const s={expected_revision_recorded:c.expected_revision_recorded,changes_since:c.changes_since.map(h=>({ts:h.ts,op:h.op,author:h.author,fields:[...h.fields]})),changes_since_omitted:c.changes_since_omitted},a=_(n,new d(n.message,n.exitCode,{...n.context,details:s}));return a.stack=n.stack,a}async function C(e,i,t){try{return{result:await w(e,i),...g(e)}}catch(n){throw e.pmRoot===void 0?n:await A(n,e.pmRoot,t)}}function re(e){return e.cwd===void 0&&e.pmRoot===void 0?void 0:{scopeArgs:["--pm-path",l(e)]}}async function Ne(e,i,t={}){return C(await se(e,t),i,re(t))}async function se(e,i={}){const t=l(i),n=e.map(({id:o,itemHash:c})=>({id:o,itemHash:R(c)})),r=x();return f(r,t,await E(t,n)),r}function ke(e){const i=P(e);return i===void 0||i.length>0}function ce(e){return`expect_hash_unchecked:${e}:no_locked_write_reached_this_item`}function ae(e,i={}){const t=J(e);if(!B(e,i.subcommand))throw de(t,i.subcommand);if((t==="test"||t==="test-all")&&i.background===!0)throw new d(`--expect-hash cannot guard ${t} --background: the worker runs in another process.`,m.USAGE,{code:"expect_hash_background_unsupported",required:`Run ${t} in the foreground to guard its result recording, or drop --expect-hash for a background run.`})}function de(e,i){const t=e==="create"||e==="copy"?`--expect-hash guards writes to an existing item, and ${e} writes only new items.`:e==="schema"?`--expect-hash guards writes to existing items, and schema ${typeof i=="string"?i:"without a verb"} writes none; only ${z().join(", ")} do.`:`--expect-hash guards writes to existing items, and ${e} writes none.`;return new d(t,m.USAGE,{code:"expect_hash_requires_mutation",required:"Use --expect-hash (MCP/SDK expectHash) only on a command or action that writes an existing item; remove it from this call, and guard a later write to the item instead."})}function he(e,i){if(i.length===0||typeof e!="object"||e===null||Array.isArray(e))return e;const t=e,n=Array.isArray(t.warnings)?t.warnings:[];return{...t,warnings:[...n,...i.map(ce)]}}async function Oe(e){const i=e.expectHash;if(i!==void 0&&typeof i!="string"&&!(Array.isArray(i)&&i.every(o=>typeof o=="string")))throw p(JSON.stringify(i)??String(i),"expected a string or an array of strings");const t=te(i);if(t.length===0)return e.run();ae(K(e.requestedAction,e.action),{background:e.background===!0||e.options?.background===!0,subcommand:e.subcommand});const n=x();f(n,e.pmRoot,await E(e.pmRoot,t,e.defaultId));const r=await C(n,e.run,e.invocation);return he(r.result,r.unchecked)}export{ee as ITEM_REVISION_CONFLICT_CHANGE_LIMIT,v as ITEM_REVISION_CONFLICT_CODE,ae as assertExpectHashAdmissible,se as bindExpectedItemRevisions,f as bindItemRevisionScope,x as createItemRevisionScope,ne as describeItemRevisionChanges,Oe as dispatchWithExpectedItemRevisions,A as enrichItemRevisionConflict,Ue as expectHashAdmissionCondition,Te as expectHashInvocationRewrittenError,de as expectHashRequiresMutationError,Fe as isExpectHashAdmissibleAction,u as isItemRevisionConflict,ke as isTrackerRevisionGuarded,be as itemRevisionConflictRowFields,g as itemRevisionScopeReceipt,ce as itemRevisionUncheckedWarning,R as normalizeExpectedItemHash,te as parseExpectHashSpecs,Se as readItemRevision,E as resolveExpectedItemRevisions,C as runWithBoundItemRevisionScope,w as runWithItemRevisionScope,oe as scopeItemRevisionConflict,He as throwFirstItemRevisionConflict,Ne as withExpectedItemRevisions};
2
2
  //# sourceMappingURL=item-revision.js.map
@@ -43,7 +43,7 @@ toon_encoding?:"tabular_when_uniform";}
43
43
  /** Universal selector for results carrying a {@link ReadRowContract}. */
44
44
  export declare const PM_READ_ROW_JQ_SELECTOR=".row_contract.row_keys[] as $key | getpath($key | split(\".\")) | if type == \"array\" then .[] else if type == \"object\" then to_entries[] else empty end end";
45
45
  /** Static row declarations shared by CLI, SDK, MCP, and package consumers. */
46
- export declare const PM_READ_ROW_CONTRACTS:{readonly context:{readonly row_keys:readonly["high_level","low_level"];readonly fields:"supported";};readonly get:{readonly row_keys:readonly["children"];readonly fields:"supported";};readonly list:{readonly row_keys:readonly["items"];readonly fields:"supported";};readonly next:{readonly row_keys:readonly["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"];readonly fields:"unsupported";};readonly search:{readonly row_keys:readonly["items"];readonly fields:"supported";};readonly activity:{readonly row_keys:readonly["activity_digest","compact_activity","provenance_activity","activity"];readonly fields:"unsupported";};readonly history:{readonly row_keys:readonly["compact_history","provenance_history","history","diff"];readonly fields:"unsupported";};readonly deps:{readonly row_keys:readonly["graph.nodes","graph.edges","context.nodes","context.edges"];readonly fields:"unsupported";};readonly health:{readonly row_keys:readonly["checks"];readonly fields:"unsupported";};readonly aggregate:{readonly row_keys:readonly["groups"];readonly fields:"unsupported";};readonly duplicates:{readonly row_keys:readonly["clusters"];readonly fields:"unsupported";};readonly stats:{readonly row_keys:readonly["by_type","by_status"];readonly fields:"unsupported";};readonly comments:{readonly row_keys:readonly["comments"];readonly fields:"unsupported";};readonly notes:{readonly row_keys:readonly["notes"];readonly fields:"unsupported";};readonly learnings:{readonly row_keys:readonly["learnings"];readonly fields:"unsupported";};readonly files:{readonly row_keys:readonly["files","matches"];readonly fields:"unsupported";};readonly docs:{readonly row_keys:readonly["docs"];readonly fields:"unsupported";};readonly validate:{readonly row_keys:readonly["checks","warnings"];readonly fields:"unsupported";};readonly contracts:{readonly row_keys:readonly["command_summaries","commands"];readonly fields:"unsupported";};};
46
+ export declare const PM_READ_ROW_CONTRACTS:{readonly context:{readonly row_keys:readonly["high_level","low_level"];readonly fields:"supported";};readonly get:{readonly row_keys:readonly["children"];readonly fields:"supported";};readonly list:{readonly row_keys:readonly["items"];readonly fields:"supported";};readonly next:{readonly row_keys:readonly["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"];readonly fields:"unsupported";};readonly search:{readonly row_keys:readonly["items"];readonly fields:"supported";};readonly activity:{readonly row_keys:readonly["activity_digest","compact_activity","provenance_activity","activity"];readonly fields:"unsupported";};readonly history:{readonly row_keys:readonly["compact_history","provenance_history","history","diff"];readonly fields:"unsupported";};readonly deps:{readonly row_keys:readonly["graph.nodes","graph.edges","context.nodes","context.edges"];readonly fields:"unsupported";};readonly health:{readonly row_keys:readonly["checks"];readonly fields:"unsupported";};readonly aggregate:{readonly row_keys:readonly["groups"];readonly fields:"unsupported";};readonly duplicates:{readonly row_keys:readonly["clusters"];readonly fields:"unsupported";};readonly stats:{readonly row_keys:readonly["by_type","by_status"];readonly fields:"unsupported";};readonly comments:{readonly row_keys:readonly["comments"];readonly fields:"unsupported";};readonly notes:{readonly row_keys:readonly["notes"];readonly fields:"unsupported";};readonly learnings:{readonly row_keys:readonly["learnings"];readonly fields:"unsupported";};readonly files:{readonly row_keys:readonly["files","matches"];readonly fields:"unsupported";};readonly docs:{readonly row_keys:readonly["docs"];readonly fields:"unsupported";};readonly validate:{readonly row_keys:readonly["checks","warnings"];readonly fields:"unsupported";};readonly contracts:{readonly row_keys:readonly["command_summaries","commands"];readonly fields:"unsupported";};readonly "package-catalog":{readonly row_keys:readonly["details.packages"];readonly fields:"supported";};};
47
47
  /** Contract for a command whose output modes expose mutually exclusive row shapes. */
48
48
  export interface ModePairedOutputProjectionContract{
49
49
  /** Stable command name. */
@@ -1,2 +1,2 @@
1
- import{EXIT_CODE as g}from"../core/shared/constants.js";import{PmCliError as k}from"../core/shared/errors.js";import{resolvePmCommandOperation as O}from"./cli-contracts/command-aliases.js";const _=new WeakMap;function K(e,t){_.set(e,new Set(t))}const f='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end',u={context:{row_keys:["high_level","low_level"],fields:"supported"},get:{row_keys:["children"],fields:"supported"},list:{row_keys:["items"],fields:"supported"},next:{row_keys:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],fields:"unsupported"},search:{row_keys:["items"],fields:"supported"},activity:{row_keys:["activity_digest","compact_activity","provenance_activity","activity"],fields:"unsupported"},history:{row_keys:["compact_history","provenance_history","history","diff"],fields:"unsupported"},deps:{row_keys:["graph.nodes","graph.edges","context.nodes","context.edges"],fields:"unsupported"},health:{row_keys:["checks"],fields:"unsupported"},aggregate:{row_keys:["groups"],fields:"unsupported"},duplicates:{row_keys:["clusters"],fields:"unsupported"},stats:{row_keys:["by_type","by_status"],fields:"unsupported"},comments:{row_keys:["comments"],fields:"unsupported"},notes:{row_keys:["notes"],fields:"unsupported"},learnings:{row_keys:["learnings"],fields:"unsupported"},files:{row_keys:["files","matches"],fields:"unsupported"},docs:{row_keys:["docs"],fields:"unsupported"},validate:{row_keys:["checks","warnings"],fields:"unsupported"},contracts:{row_keys:["command_summaries","commands"],fields:"unsupported"}},b=[{command:"activity",complete_mode:"full",omissions_by_mode:{digest:[{name:"event_rows",restore_with:"--raw"}],compact:[{name:"provenance",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}},{command:"history",complete_mode:"full",omissions_by_mode:{compact:[{name:"raw_history",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}}];function $(e,t,n){if(e&&t)throw new k(`${n} cannot be combined with --full`,g.USAGE)}function a(e,t=new Set){const n=e.filter(o=>!t.has(o.name)).map(o=>({...o}));return{has_omissions:n.length>0,omitted_field_group_count:n.length,omitted_field_groups:n}}function q(e,t){const n=b.find(s=>s.command===e);if(n===void 0)throw new TypeError(`Unknown mode-paired output command: ${e}`);if(t===n.complete_mode)return a([]);const o=n.omissions_by_mode[t];if(o===void 0)throw new TypeError(`Unknown ${e} output mode: ${t}`);return a(o)}const R=[{name:"hierarchy",restore_with:"--section hierarchy"},{name:"activity",restore_with:"--section activity"},{name:"progress",restore_with:"--section progress"},{name:"blockers",restore_with:"--section blockers"},{name:"recently_created",restore_with:"--section recently_created"},{name:"unparented",restore_with:"--section unparented"},{name:"files",restore_with:"--section files"},{name:"workload",restore_with:"--section workload"},{name:"staleness",restore_with:"--section staleness"},{name:"tests",restore_with:"--section tests"}];function c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const j=new Set([void 0,"tabular_when_uniform"]),E=new Set(["collection","none"]),A=new Set(["supported","unsupported"]);function m(e,t){return Array.isArray(e)&&(t||e.length>0)&&e.every(n=>typeof n=="string"&&n.length>0)&&new Set(e).size===e.length}function S(e){return c(e)&&typeof e.command=="string"&&e.command.trim().length>0&&E.has(e.row_kind)&&m(e.row_keys,!0)&&(e.continuation_row_keys===void 0||m(e.continuation_row_keys,!1))&&A.has(e.fields)&&j.has(e.toon_encoding)&&(e.row_kind==="collection"?e.row_keys.length>0&&typeof e.jq_selector=="string"&&e.jq_selector.trim().length>0:e.row_keys.length===0&&e.jq_selector===void 0)}const v={ancestors:["ids"],descendants:["ids"],predecessors:["ids"],successors:["ids"],paths:["paths"],impact:["affected"],audit:["findings"],communities:["communities"],redundancy:["redundant"],dominators:["bottlenecks"],slack:["rows"],centrality:["rows"],articulation:["articulation_points","bridges"],plan:["steps"]},C={context:["sections_included","high_level","low_level"],get:["item"],list:["items","projection"],next:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items","projection"],activity:["activity_digest","compact_activity","provenance_activity","activity"],history:["compact_history","provenance_history","history","diff"],deps:["tree","graph","projection"],health:["checks"],aggregate:["groups"],duplicates:["clusters"],stats:["totals","by_type","by_status"],comments:["comments"],notes:["notes"],learnings:["learnings"],files:["files","matches"],docs:["docs"],validate:["checks","warnings"],contracts:["command_summaries","commands","selected"]};function x(e){const t=e.split(/\s+/u,1)[0];return t==="graph"||t.startsWith("list-")||Object.hasOwn(u,t)?t:O(e).split(/\s+/u,1)[0]}function T(e,t){const n=x(e.trim().toLowerCase()),o=n?.startsWith("list-")?"list":n;if(o==="graph"){const r=typeof t.subcommand=="string"?t.subcommand:"";if(r.length===0)return;const i=v[r];if(i===void 0)return;const l=i.filter(p=>Array.isArray(t[p])||c(t[p]));return{command:"graph",row_kind:l.length>0?"collection":"none",row_keys:l,fields:"unsupported",...l.length>0?{jq_selector:f}:{},toon_encoding:"tabular_when_uniform"}}const s=u[o],d=C[o];return s===void 0||d===void 0||!d.some(r=>Object.hasOwn(t,r))?void 0:(()=>{const r=s.row_keys.filter(i=>{const l=i.split(".").reduce((p,w)=>c(p)?p[w]:void 0,t);return Array.isArray(l)||c(l)});return{command:o,row_kind:r.length>0?"collection":"none",row_keys:r,fields:s.fields,...r.length>0?{jq_selector:f}:{},toon_encoding:"tabular_when_uniform"}})()}function D(e){if(!c(e.projection)||typeof e.projection.mode!="string"||e.projection.mode.trim().length===0)return;const t=e.projection.declared_field_groups,n=e.projection.included_field_groups;if(!Array.isArray(t)||!Array.isArray(n))return;const o=t.filter(r=>c(r)&&typeof r.name=="string"&&r.name.trim().length>0&&typeof r.restore_with=="string"&&r.restore_with.trim().length>0),s=n.filter(r=>typeof r=="string");if(o.length!==t.length||s.length!==n.length)return;const d=new Set(o.map(r=>r.name));if(!(d.size!==o.length||new Set(s).size!==s.length||s.some(r=>!d.has(r))))return a(o,new Set(s))}function G(e){if(!Array.isArray(e.sections_included))return;const t=a(R,new Set(e.sections_included.filter(n=>typeof n=="string")));return c(e.summary)&&e.summary.scope==="matching_items"&&(t.summary_scope="matching_items"),t}function N(e,t,n){if(e==="dependency_provenance")return!1;const o=h(e);if(o!==void 0){const s=n[o.facet];return c(s)&&Object.hasOwn(s,o.member)}return Object.hasOwn(t,e)||(e==="reminders"||e==="events")&&c(n.schedule)&&Object.hasOwn(n.schedule,e)||["files","tests","docs"].includes(e)&&c(n.linked)&&Array.isArray(n.linked[e])&&n.linked[e].length>0}function h(e){const t=e.indexOf(".");return t===-1?void 0:{facet:e.slice(0,t),member:e.slice(t+1)}}function P(e){if(!c(e.item))return;const t=e.item,n=["comments","notes","learnings","files","tests","docs","reminders","events"],o=["body","children","claim_state","linked","schedule"],s=_.get(e),d=i=>n.includes(i)||i==="body"||i==="dependency_provenance"?t:e,r=["body",...n,...o.slice(1),...s?.has("dependency_provenance")?["dependency_provenance"]:[],...s?.has("blockers")||Object.hasOwn(e,"blockers")?["blockers"]:[],...[...s??[]].filter(i=>h(i)!==void 0)].filter(i=>s===void 0||s.has(i)||Object.hasOwn(d(i),i)).map(i=>({name:i,restore_with:i==="blockers"?"--full":i==="dependency_provenance"?"--fields dependencies":`--fields ${i}`}));return a(r,new Set(r.flatMap(({name:i})=>N(i,d(i),e)?[i]:[])))}function y(e){if(c(e.projection))return a([{name:"full_item_fields",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_item_fields"]:[]))}function I(e){if(!c(e.projection))return a([]);if(typeof e.projection.mode=="string")return a([{name:"full_check_details",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_check_details"]:[]))}function M(e){if(!(!c(e.selected)||typeof e.selected.summary!="boolean"))return a([{name:"full_contract_catalog",restore_with:"--full"}],new Set(e.selected.summary?[]:["full_contract_catalog"]))}function L(e,t){const n=D(t);if(n!==void 0)return n;const[o]=e.split(/\s+/u,1);if(o==="context")return G(t);if(o==="get")return P(t);if(o==="list"||o.startsWith("list-"))return y(t);if(o==="search")return y(t)??a([{name:"projection_metadata",restore_with:"--full"}]);if(o==="health")return I(t);if(o==="contracts")return M(t)}function z(e,t){if(e===void 0||!c(t))return t;const n=L(e,t),o=t.row_contract,s=S(o)?o:T(e,t),d=s!==void 0?{...t,row_contract:s}:Object.hasOwn(t,"row_contract")?Object.fromEntries(Object.entries(t).filter(([r])=>r!=="row_contract")):t;return c(d.omission_receipt)||n===void 0?d:{...d,omission_receipt:n}}export{b as PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS,u as PM_READ_ROW_CONTRACTS,f as PM_READ_ROW_JQ_SELECTOR,$ as assertProjectionModeChoice,z as attachOutputOmissionReceipt,a as createOutputOmissionReceipt,S as isReadRowContract,K as registerOutputMaterialFieldGroups,q as resolveModePairedOutputOmissionReceipt,L as resolveOutputOmissionReceipt,T as resolveReadRowContract};
1
+ import{EXIT_CODE as w}from"../core/shared/constants.js";import{PmCliError as g}from"../core/shared/errors.js";import{resolvePmCommandOperation as k}from"./cli-contracts/command-aliases.js";import{PACKAGE_CATALOG_SPELLINGS as O}from"./read-output/surfaces.js";const p=new WeakMap;function Y(e,t){p.set(e,new Set(t))}const _='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end',f={context:{row_keys:["high_level","low_level"],fields:"supported"},get:{row_keys:["children"],fields:"supported"},list:{row_keys:["items"],fields:"supported"},next:{row_keys:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],fields:"unsupported"},search:{row_keys:["items"],fields:"supported"},activity:{row_keys:["activity_digest","compact_activity","provenance_activity","activity"],fields:"unsupported"},history:{row_keys:["compact_history","provenance_history","history","diff"],fields:"unsupported"},deps:{row_keys:["graph.nodes","graph.edges","context.nodes","context.edges"],fields:"unsupported"},health:{row_keys:["checks"],fields:"unsupported"},aggregate:{row_keys:["groups"],fields:"unsupported"},duplicates:{row_keys:["clusters"],fields:"unsupported"},stats:{row_keys:["by_type","by_status"],fields:"unsupported"},comments:{row_keys:["comments"],fields:"unsupported"},notes:{row_keys:["notes"],fields:"unsupported"},learnings:{row_keys:["learnings"],fields:"unsupported"},files:{row_keys:["files","matches"],fields:"unsupported"},docs:{row_keys:["docs"],fields:"unsupported"},validate:{row_keys:["checks","warnings"],fields:"unsupported"},contracts:{row_keys:["command_summaries","commands"],fields:"unsupported"},"package-catalog":{row_keys:["details.packages"],fields:"supported"}},R=[{command:"activity",complete_mode:"full",omissions_by_mode:{digest:[{name:"event_rows",restore_with:"--raw"}],compact:[{name:"provenance",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}},{command:"history",complete_mode:"full",omissions_by_mode:{compact:[{name:"raw_history",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}}];function z(e,t,n){if(e&&t)throw new g(`${n} cannot be combined with --full`,w.USAGE)}function a(e,t=new Set){const n=e.filter(o=>!t.has(o.name)).map(o=>({...o}));return{has_omissions:n.length>0,omitted_field_group_count:n.length,omitted_field_groups:n}}function H(e,t){const n=R.find(s=>s.command===e);if(n===void 0)throw new TypeError(`Unknown mode-paired output command: ${e}`);if(t===n.complete_mode)return a([]);const o=n.omissions_by_mode[t];if(o===void 0)throw new TypeError(`Unknown ${e} output mode: ${t}`);return a(o)}const b=[{name:"hierarchy",restore_with:"--section hierarchy"},{name:"activity",restore_with:"--section activity"},{name:"progress",restore_with:"--section progress"},{name:"blockers",restore_with:"--section blockers"},{name:"recently_created",restore_with:"--section recently_created"},{name:"unparented",restore_with:"--section unparented"},{name:"files",restore_with:"--section files"},{name:"workload",restore_with:"--section workload"},{name:"staleness",restore_with:"--section staleness"},{name:"tests",restore_with:"--section tests"}];function d(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const A=new Set([void 0,"tabular_when_uniform"]),E=new Set(["collection","none"]),S=new Set(["supported","unsupported"]);function u(e,t){return Array.isArray(e)&&(t||e.length>0)&&e.every(n=>typeof n=="string"&&n.length>0)&&new Set(e).size===e.length}function j(e){return d(e)&&typeof e.command=="string"&&e.command.trim().length>0&&E.has(e.row_kind)&&u(e.row_keys,!0)&&(e.continuation_row_keys===void 0||u(e.continuation_row_keys,!1))&&S.has(e.fields)&&A.has(e.toon_encoding)&&(e.row_kind==="collection"?e.row_keys.length>0&&typeof e.jq_selector=="string"&&e.jq_selector.trim().length>0:e.row_keys.length===0&&e.jq_selector===void 0)}const v={ancestors:["ids"],descendants:["ids"],predecessors:["ids"],successors:["ids"],paths:["paths"],impact:["affected"],audit:["findings"],communities:["communities"],redundancy:["redundant"],dominators:["bottlenecks"],slack:["rows"],centrality:["rows"],articulation:["articulation_points","bridges"],plan:["steps"]},C={context:["sections_included","high_level","low_level"],get:["item"],list:["items","projection"],next:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items","projection"],activity:["activity_digest","compact_activity","provenance_activity","activity"],history:["compact_history","provenance_history","history","diff"],deps:["tree","graph","projection"],health:["checks"],aggregate:["groups"],duplicates:["clusters"],stats:["totals","by_type","by_status"],comments:["comments"],notes:["notes"],learnings:["learnings"],files:["files","matches"],docs:["docs"],validate:["checks","warnings"],contracts:["command_summaries","commands","selected"],"package-catalog":["details"]},x=new Set(["package","packages","extension"]);function T(e){const t=e.replace(/\s+/gu," ");if(O.has(t)||x.has(t))return"package-catalog";const n=e.split(/\s+/u,1)[0];return n==="graph"||n.startsWith("list-")||Object.hasOwn(f,n)?n:k(e).split(/\s+/u,1)[0]}function G(e,t){const n=C[e];return n===void 0||!n.some(o=>Object.hasOwn(t,o))?!1:e!=="package-catalog"||t.action==="catalog"}function D(e,t){const n=T(e.trim().toLowerCase()),o=n?.startsWith("list-")?"list":n;if(o==="graph"){const c=typeof t.subcommand=="string"?t.subcommand:"";if(c.length===0)return;const i=v[c];if(i===void 0)return;const r=i.filter(l=>Array.isArray(t[l])||d(t[l]));return{command:"graph",row_kind:r.length>0?"collection":"none",row_keys:r,fields:"unsupported",...r.length>0?{jq_selector:_}:{},toon_encoding:"tabular_when_uniform"}}const s=f[o];return s===void 0||!G(o,t)?void 0:(()=>{const c=s.row_keys.filter(i=>{const r=i.split(".").reduce((l,y)=>d(l)?l[y]:void 0,t);return Array.isArray(r)||d(r)});return{command:o,row_kind:c.length>0?"collection":"none",row_keys:c,fields:s.fields,...c.length>0?{jq_selector:_}:{},toon_encoding:"tabular_when_uniform"}})()}function L(e){if(!d(e.projection)||typeof e.projection.mode!="string"||e.projection.mode.trim().length===0)return;const t=e.projection.declared_field_groups,n=e.projection.included_field_groups;if(!Array.isArray(t)||!Array.isArray(n))return;const o=t.filter(i=>d(i)&&typeof i.name=="string"&&i.name.trim().length>0&&typeof i.restore_with=="string"&&i.restore_with.trim().length>0),s=n.filter(i=>typeof i=="string");if(o.length!==t.length||s.length!==n.length)return;const c=new Set(o.map(i=>i.name));if(!(c.size!==o.length||new Set(s).size!==s.length||s.some(i=>!c.has(i))))return a(o,new Set(s))}function P(e){if(!Array.isArray(e.sections_included))return;const t=a(b,new Set(e.sections_included.filter(n=>typeof n=="string")));return d(e.summary)&&e.summary.scope==="matching_items"&&(t.summary_scope="matching_items"),t}function N(e,t,n){if(e==="dependency_provenance")return!1;const o=m(e);if(o!==void 0){const s=n[o.facet];return d(s)&&Object.hasOwn(s,o.member)}return Object.hasOwn(t,e)||(e==="reminders"||e==="events")&&d(n.schedule)&&Object.hasOwn(n.schedule,e)||["files","tests","docs"].includes(e)&&d(n.linked)&&Array.isArray(n.linked[e])&&n.linked[e].length>0}function m(e){const t=e.indexOf(".");return t===-1?void 0:{facet:e.slice(0,t),member:e.slice(t+1)}}function I(e){if(!d(e.item))return;const t=e.item,n=["comments","notes","learnings","files","tests","docs","reminders","events"],o=["body","children","claim_state","linked","schedule"],s=p.get(e),c=r=>n.includes(r)||r==="body"||r==="dependency_provenance"?t:e,i=["body",...n,...o.slice(1),...s?.has("dependency_provenance")?["dependency_provenance"]:[],...s?.has("blockers")||Object.hasOwn(e,"blockers")?["blockers"]:[],...[...s??[]].filter(r=>m(r)!==void 0)].filter(r=>s===void 0||s.has(r)||Object.hasOwn(c(r),r)).map(r=>({name:r,restore_with:r==="blockers"?"--full":r==="dependency_provenance"?"--fields dependencies":`--fields ${r}`}));return a(i,new Set(i.flatMap(({name:r})=>N(r,c(r),e)?[r]:[])))}function h(e){if(d(e.projection))return a([{name:"full_item_fields",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_item_fields"]:[]))}function M(e){if(!d(e.projection))return a([]);if(typeof e.projection.mode=="string")return a([{name:"full_check_details",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_check_details"]:[]))}function U(e){if(!(!d(e.selected)||typeof e.selected.summary!="boolean"))return a([{name:"full_contract_catalog",restore_with:"--full"}],new Set(e.selected.summary?[]:["full_contract_catalog"]))}function W(e,t){const n=L(t);if(n!==void 0)return n;const[o]=e.split(/\s+/u,1);if(o==="context")return P(t);if(o==="get")return I(t);if(o==="list"||o.startsWith("list-"))return h(t);if(o==="search")return h(t)??a([{name:"projection_metadata",restore_with:"--full"}]);if(o==="health")return M(t);if(o==="contracts")return U(t)}function J(e,t){if(e===void 0||!d(t))return t;const n=W(e,t),o=t.row_contract,s=j(o)?o:D(e,t),c=s!==void 0?{...t,row_contract:s}:Object.hasOwn(t,"row_contract")?Object.fromEntries(Object.entries(t).filter(([i])=>i!=="row_contract")):t;return d(c.omission_receipt)||n===void 0?c:{...c,omission_receipt:n}}export{R as PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS,f as PM_READ_ROW_CONTRACTS,_ as PM_READ_ROW_JQ_SELECTOR,z as assertProjectionModeChoice,J as attachOutputOmissionReceipt,a as createOutputOmissionReceipt,j as isReadRowContract,Y as registerOutputMaterialFieldGroups,H as resolveModePairedOutputOmissionReceipt,W as resolveOutputOmissionReceipt,D as resolveReadRowContract};
2
2
  //# sourceMappingURL=output-projection.js.map