@unbrained/pm-cli 2026.11.29 → 2026.12.1

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 (168) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/commander-usage.js +10 -10
  3. package/dist/cli/error-guidance.js +5 -5
  4. package/dist/cli/extension-command-help.js +6 -6
  5. package/dist/cli/help-json-payload.js +7 -7
  6. package/dist/cli/main.js +5 -5
  7. package/dist/cli/register-list-query.js +10 -10
  8. package/dist/cli/register-mutation.js +3 -3
  9. package/dist/cli/runtime/invocation-command-path.js +2 -0
  10. package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
  11. package/dist/cli-bundle/bundle-manifest.json +1 -1
  12. package/dist/cli-bundle/chunks/{chunk-JQHLOSSS.js → chunk-3HKPVOAN.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-ZSBPE36C.js → chunk-3KEMIPKG.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-JFPCL45G.js → chunk-4YQMQOUO.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-EYEQC3L2.js → chunk-4YYFY33T.js} +2 -2
  16. package/dist/cli-bundle/chunks/chunk-A5ZEMOVR.js +2 -0
  17. package/dist/cli-bundle/chunks/{chunk-WLZ5KVM2.js → chunk-AHV3CSQG.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-AJLU6KLW.js +2 -0
  19. package/dist/cli-bundle/chunks/{chunk-R6M5OGJH.js → chunk-C6WM6ZN4.js} +3 -3
  20. package/dist/cli-bundle/chunks/chunk-CBUC4X7Q.js +127 -0
  21. package/dist/cli-bundle/chunks/{chunk-K3MVVDLN.js → chunk-CWPR234D.js} +2 -2
  22. package/dist/cli-bundle/chunks/chunk-I4SPJQQI.js +3 -0
  23. package/dist/cli-bundle/chunks/{chunk-VI3A7UZ2.js → chunk-L2ZSSMYY.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-DBASKWBO.js → chunk-MZZ4ZJ5Z.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-CV2B4JUB.js → chunk-NA6D75V5.js} +2 -2
  26. package/dist/cli-bundle/chunks/chunk-NRQCBUYD.js +113 -0
  27. package/dist/cli-bundle/chunks/{chunk-ZK4CY24V.js → chunk-OBPO6V7H.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-3US5T6B2.js → chunk-OKEJ4U2I.js} +7 -7
  29. package/dist/cli-bundle/chunks/{chunk-3E53F7QY.js → chunk-OXC5KBIQ.js} +2 -2
  30. package/dist/cli-bundle/chunks/{chunk-NLHNB2L3.js → chunk-PCDTWL6V.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-LQEB6GSY.js → chunk-Q6GLSAJY.js} +2 -2
  32. package/dist/cli-bundle/chunks/{chunk-3TK2YOVB.js → chunk-Q6K7HWZ7.js} +2 -2
  33. package/dist/cli-bundle/chunks/chunk-QDV7S2QS.js +2 -0
  34. package/dist/cli-bundle/chunks/{chunk-Q6GIFUCW.js → chunk-SY5C3U32.js} +3 -3
  35. package/dist/cli-bundle/chunks/{chunk-L7HON3BE.js → chunk-U7RBJGLF.js} +23 -23
  36. package/dist/cli-bundle/chunks/chunk-WSEIEDEK.js +2 -0
  37. package/dist/cli-bundle/chunks/{chunk-FRYNDVLN.js → chunk-XME6GIFQ.js} +2 -2
  38. package/dist/cli-bundle/chunks/{chunk-WNB62BGK.js → chunk-YSVOXCYH.js} +2 -2
  39. package/dist/cli-bundle/chunks/{chunk-KCR4NF2A.js → chunk-ZL6J6JYT.js} +6 -6
  40. package/dist/cli-bundle/chunks/{field-option-collisions-OZE43TOH.js → field-option-collisions-BBGTV7AD.js} +2 -2
  41. package/dist/cli-bundle/chunks/item-revision-3LENTXYF.js +2 -0
  42. package/dist/cli-bundle/chunks/item-transaction-66RDV7PH.js +2 -0
  43. package/dist/cli-bundle/chunks/{linked-resource-value-list-2655COY2.js → linked-resource-value-list-E2DX52LY.js} +2 -2
  44. package/dist/cli-bundle/chunks/{mutation-actor-QOKPDYM4.js → mutation-actor-NHN33ITJ.js} +2 -2
  45. package/dist/cli-bundle/chunks/{mutation-admission-JNJHB3E6.js → mutation-admission-PGKJTCG6.js} +2 -2
  46. package/dist/cli-bundle/chunks/{register-list-query-YGVUE4YZ.js → register-list-query-7S5QWDTI.js} +11 -11
  47. package/dist/cli-bundle/chunks/{register-mutation-3JVZQDHH.js → register-mutation-2F6JUBST.js} +5 -5
  48. package/dist/cli-bundle/chunks/{register-operations-LCHUHKRA.js → register-operations-ET3UKPYK.js} +2 -2
  49. package/dist/cli-bundle/chunks/{register-setup-IJ7M3VUK.js → register-setup-I63QTFCU.js} +2 -2
  50. package/dist/cli-bundle/chunks/{stage-7BD7U2BX.js → stage-4ZCF74G4.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-NO5MUY4I.js → chunk-2DGKVXFT.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/chunk-2UWKU2BQ.js +3 -0
  53. package/dist/cli-bundle/focused-chunks/{chunk-42SU4LK3.js → chunk-4SCFAWAW.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-LSVRZ4KQ.js → chunk-6BKT6XQN.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/chunk-6IY5CVGJ.js +2 -0
  56. package/dist/cli-bundle/focused-chunks/chunk-7A6SEZEY.js +4 -0
  57. package/dist/cli-bundle/focused-chunks/{chunk-LKTRICZR.js → chunk-BHNBPCHP.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-PPCBCPIZ.js → chunk-EQCQTYKO.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{chunk-NNLENKU7.js → chunk-HTDYNY4L.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{chunk-S5VG7RFY.js → chunk-JPZGC3W4.js} +5 -5
  61. package/dist/cli-bundle/focused-chunks/{chunk-ACTBMSCH.js → chunk-KNBGHCIP.js} +3 -3
  62. package/dist/cli-bundle/focused-chunks/chunk-N64AC5G6.js +100 -0
  63. package/dist/cli-bundle/focused-chunks/{chunk-EUDAUT6T.js → chunk-OG57ESZK.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/{chunk-2CQFGJQ6.js → chunk-P2H3GTJK.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{chunk-QTV6UE2Q.js → chunk-PT7RT3T6.js} +26 -26
  66. package/dist/cli-bundle/focused-chunks/chunk-QZRYGYTI.js +2 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-BPOU2S44.js → chunk-SQ72CVUH.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/chunk-SQMOF65W.js +2 -0
  69. package/dist/cli-bundle/focused-chunks/chunk-T3ILWAEV.js +2 -0
  70. package/dist/cli-bundle/focused-chunks/{chunk-KWKPX36T.js → chunk-TR22GU7M.js} +2 -2
  71. package/dist/cli-bundle/focused-chunks/{chunk-TSZVCALS.js → chunk-TXTPAFHJ.js} +2 -2
  72. package/dist/cli-bundle/focused-chunks/chunk-VK3IE3TS.js +29 -0
  73. package/dist/cli-bundle/focused-chunks/{chunk-GTUPHXKR.js → chunk-VQIC3UZB.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/{chunk-S4AC7OMI.js → chunk-W4JMV7GF.js} +2 -2
  75. package/dist/cli-bundle/focused-chunks/{field-option-collisions-HABQYZMQ.js → field-option-collisions-2C6DLUC4.js} +2 -2
  76. package/dist/cli-bundle/focused-chunks/item-revision-723XCQPS.js +2 -0
  77. package/dist/cli-bundle/focused-chunks/{item-transaction-YZ2PUPGM.js → item-transaction-2K4SFLJ7.js} +2 -2
  78. package/dist/cli-bundle/focused-chunks/{mutation-actor-DJ2VRLKG.js → mutation-actor-DJMZUIZI.js} +2 -2
  79. package/dist/cli-bundle/focused-chunks/mutation-admission-SDWQVVHN.js +2 -0
  80. package/dist/cli-bundle/focused-chunks/{stage-FEJT2UCG.js → stage-QBZIK3T5.js} +2 -2
  81. package/dist/cli-bundle/main.js +27 -27
  82. package/dist/cli-bundle/sdk-authoring.js +1 -1
  83. package/dist/cli-bundle/sdk-contracts.js +1 -1
  84. package/dist/cli-bundle/sdk-core.js +1 -1
  85. package/dist/cli-bundle/sdk-governance.js +1 -1
  86. package/dist/cli-bundle/sdk-graph.js +1 -1
  87. package/dist/cli-bundle/sdk-merge.js +63 -63
  88. package/dist/cli-bundle/sdk-query.js +1 -1
  89. package/dist/cli-bundle/sdk-runtime.js +1 -1
  90. package/dist/cli-bundle/sdk-testing.js +1 -1
  91. package/dist/cli-bundle/sdk.js +2 -2
  92. package/dist/core/extensions/reserved-host-flags.js +1 -1
  93. package/dist/core/shared/secret-rules.d.ts +86 -12
  94. package/dist/core/shared/secret-rules.js +7 -5
  95. package/dist/core/shared/url-credentials.d.ts +4 -2
  96. package/dist/core/shared/url-credentials.js +1 -1
  97. package/dist/sdk/cli-bootstrap.js +1 -1
  98. package/dist/sdk/cli-contracts/flag-contracts.d.ts +50 -0
  99. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  100. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +3 -1
  101. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  102. package/dist/sdk/context-intent-contracts.js +1 -1
  103. package/dist/sdk/extension/command-options.js +1 -1
  104. package/dist/sdk/lifecycle/expect-hash-admission.d.ts +15 -0
  105. package/dist/sdk/lifecycle/expect-hash-admission.js +2 -0
  106. package/dist/sdk/lifecycle/item-revision.d.ts +4 -1
  107. package/dist/sdk/lifecycle/item-revision.js +1 -1
  108. package/dist/sdk/mutation-guard.js +1 -1
  109. package/dist/sdk/output-contracts.js +1 -1
  110. package/dist/sdk/output-projection.d.ts +1 -1
  111. package/dist/sdk/output-projection.js +1 -1
  112. package/dist/sdk/public-surface.json +1 -1
  113. package/dist/sdk/query/aggregate.js +1 -1
  114. package/dist/sdk/query/context.js +1 -1
  115. package/dist/sdk/query/list.js +1 -1
  116. package/dist/sdk/query/next.js +1 -1
  117. package/dist/sdk/query/search-contracts.js +1 -1
  118. package/dist/sdk/read-output/surfaces.js +1 -1
  119. package/dist/sdk/read-output-budget.d.ts +1 -1
  120. package/dist/sdk/read-output-budget.js +1 -1
  121. package/dist/sdk/read-output-contracts.js +1 -1
  122. package/dist/sdk/read-output-rows.js +1 -1
  123. package/docs/COMMANDS.md +37 -0
  124. package/docs/CONFIGURATION.md +22 -3
  125. package/docs/MUTATION_INTEGRITY.md +226 -10
  126. package/docs/READ_OUTPUT_CONTRACTS.md +5 -0
  127. package/docs/SDK.md +35 -9
  128. package/docs/agent-task-token-baseline.json +1 -1
  129. package/marketplace.json +1 -1
  130. package/package.json +1 -1
  131. package/packages/pm-beads/package.json +1 -1
  132. package/packages/pm-calendar/package.json +1 -1
  133. package/packages/pm-command-kit/package.json +1 -1
  134. package/packages/pm-digital-twin/package.json +1 -1
  135. package/packages/pm-governance-audit/package.json +1 -1
  136. package/packages/pm-guide-shell/package.json +1 -1
  137. package/packages/pm-kanban/package.json +1 -1
  138. package/packages/pm-lifecycle-hooks/package.json +1 -1
  139. package/packages/pm-linked-test-adapters/package.json +1 -1
  140. package/packages/pm-search-advanced/package.json +1 -1
  141. package/packages/pm-templates/package.json +1 -1
  142. package/packages/pm-todos/package.json +1 -1
  143. package/packages/pm-vcs/package.json +1 -1
  144. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  145. package/plugins/pm-claude/package.json +1 -1
  146. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  147. package/plugins/pm-codex/package.json +1 -1
  148. package/plugins/pm-codex/plugin.json +1 -1
  149. package/runtime-dependencies.json +1 -1
  150. package/dist/cli-bundle/chunks/chunk-4EBHZBM2.js +0 -2
  151. package/dist/cli-bundle/chunks/chunk-CNZOC6JD.js +0 -2
  152. package/dist/cli-bundle/chunks/chunk-JV7LREUF.js +0 -3
  153. package/dist/cli-bundle/chunks/chunk-NRCGGNOE.js +0 -2
  154. package/dist/cli-bundle/chunks/chunk-PY6A7ULK.js +0 -125
  155. package/dist/cli-bundle/chunks/chunk-RWHS77ME.js +0 -113
  156. package/dist/cli-bundle/chunks/chunk-SV27NNXQ.js +0 -2
  157. package/dist/cli-bundle/chunks/item-revision-3WXNNFLP.js +0 -2
  158. package/dist/cli-bundle/chunks/item-transaction-DJ5GAITL.js +0 -2
  159. package/dist/cli-bundle/focused-chunks/chunk-5NSWNLFE.js +0 -2
  160. package/dist/cli-bundle/focused-chunks/chunk-BPBKHY6H.js +0 -100
  161. package/dist/cli-bundle/focused-chunks/chunk-BZ3PUUPG.js +0 -2
  162. package/dist/cli-bundle/focused-chunks/chunk-KLOHZNJ4.js +0 -2
  163. package/dist/cli-bundle/focused-chunks/chunk-MYWUMVCZ.js +0 -4
  164. package/dist/cli-bundle/focused-chunks/chunk-NZA2LP4Y.js +0 -27
  165. package/dist/cli-bundle/focused-chunks/chunk-TX24L7RQ.js +0 -3
  166. package/dist/cli-bundle/focused-chunks/chunk-WJAUHPXD.js +0 -2
  167. package/dist/cli-bundle/focused-chunks/item-revision-YH5R7YPW.js +0 -2
  168. package/dist/cli-bundle/focused-chunks/mutation-admission-3SECKVKY.js +0 -2
@@ -1,2 +1,2 @@
1
- import{AsyncLocalStorage as tt}from"node:async_hooks";import{attachExtensionReadOutputRows as et}from"./read-output/extension.js";import{quoteCommandArg as I,renderPmCommand as q}from"./command-line.js";import{attachOutputOmissionReceipt as nt}from"./output-projection.js";import{encodeQueryCursor as rt}from"./pagination.js";import{applyReadOutputDimensions as ot,decodeReadOutputContinuationCursor as it,isReadResultOmittedForBudget as z,resolveReadOutputSurface as dt,stabilizeReadOutputReceiptEstimates as ut}from"./read-output-contracts.js";import{estimateReadOutputTokens as T,MAX_ESTIMATE_ITERATIONS as st,readOutputMeasurementFormat as E,registerReadOutputPassHooks as at,resolveReadOutputRecoveryBudget as ct}from"./read-output-budget.js";import{propagateContextUsageServingReceipt as R}from"./context-usage.js";import{readOutputContinuationRowCollections as ft}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 lt,isContinuationTokenKey as _t,isTrackerItemDocumentKey as gt}from"../core/shared/text-normalization.js";const mt="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 bt(){return G.getStore()??U}function Ht(t,e){return G.run(kt(t.workspaceContracts,t.packageContracts),e)}function ht(t,e){const n=t.command.trim().toLowerCase(),r=t.intent.trim().toLowerCase(),i=`${n}:${r}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(n)||!/^[a-z0-9][a-z0-9-]*$/.test(r))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 o=[...new Set(t.included_field_groups.map(d=>d.trim()).filter(Boolean))];if(o.length===0)throw new TypeError(`Context intent ${i} requires included_field_groups`);return{command:n,intent:r,description:t.description.trim(),included_field_groups:o,token_budget:t.token_budget,source:e}}function kt(t=[],e=[]){const n=[{source:"core",contracts:U,allowOverride:!1},{source:"package",contracts:e,allowOverride:!1},{source:"workspace",contracts:t,allowOverride:!0}],r=new Map,i=new Set;for(const o of n){i.clear();for(const d of o.contracts){const s=ht(d,o.source),u=`${s.command}:${s.intent}`;if(i.has(u))throw new TypeError(`Duplicate context intent declaration: ${u}`);if(i.add(u),!o.allowOverride&&r.has(u))throw new TypeError(`Duplicate context intent declaration: ${u}`);r.set(u,s)}}return[...r.values()].sort((o,d)=>o.command.localeCompare(d.command)||o.intent.localeCompare(d.intent))}function X(t,e,n=bt(),r=[]){const i=t.trim().toLowerCase(),o=e.trim().toLowerCase(),d=n.find(a=>a.command===i&&a.intent===o);if(d)return{...d,source:d.source??"core"};const s=n.filter(a=>a.command===i).map(a=>a.intent);if(s.length===0)return;const u=s.map(a=>{const f=Array.from({length:o.length+1},(b,g)=>g);for(let b=1;b<=a.length;b+=1){let g=f[0];f[0]=b;for(let h=1;h<=o.length;h+=1){const j=f[h];f[h]=Math.min(f[h]+1,f[h-1]+1,g+(a[b-1]===o[h-1]?0:1)),g=j}}return{candidate:a,distance:f[o.length]}}).sort((a,f)=>a.distance-f.distance||a.candidate.localeCompare(f.candidate))[0].candidate,c=[i,...r,"--for",o],l=[i,...r,"--for",u],_=q(l);throw new A(`Unknown context intent "${o}" for ${i}. Did you mean "${u}"?`,B.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:o,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(c),allowed_values:[...s].sort(),suggested_retry:_,suggested_retry_args:l}})}function N(t,e){const n=k(t.limit),r=String(n===void 0?e:Math.min(n,e));return(t.limit===void 0||n!==void 0)&&(t.limit=r),r}const W={context:(t,e,n,r)=>{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(r,t.tokenBudget,e.token_budget),o=v("context",e.intent,i,n),d=N(t,o);t.activityLimit===void 0&&(t.activityLimit=d)},get:t=>{t.depth===void 0&&t.fields===void 0&&(t.depth="standard")},list:(t,e,n,r)=>{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(r,t.tokenBudget,e.token_budget),o=v("list",e.intent,i,n);N(t,o)},next:t=>{t.readyOnly===void 0&&(t.readyOnly=!0)},search:(t,e,n,r)=>{t.compact===void 0&&t.full===void 0&&t.fields===void 0&&(t.compact=!0);const i=C(r,t.tokenBudget,e.token_budget),o=v("search",e.intent,i,n);N(t,o)}};function Qt(t,e,n=[]){const r=e.tokenBudget??e.token_budget;if(typeof e.for!="string"){if(r!==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:r};return delete u.token_budget,u}const i=X(t,e.for,void 0,n),o=w(e),d=k(r)!==void 0||typeof o=="number",s={...e};return s.tokenBudget===void 0&&r!==void 0&&(s.tokenBudget=r),delete s.token_budget,typeof o=="number"?s.tokenBudget=String(o):s.tokenBudget===void 0&&(s.tokenBudget=String(i.token_budget)),W[t](s,i,d,o),s}const pt={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,r=!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,o])=>[i,n&&typeof o=="string"&&_t(i)?o:S(o,e,n&&!(r&&gt(e,i)),!1)])):typeof t=="string"?lt(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 yt(t){return w(t)===void 0?"--token-budget":"--output-budget"}function C(t,e,n){return typeof t=="number"?t:wt(e,n)}function wt(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,r){if(t==="get"||t==="next")return;const{overhead:i,rowCost:o}=F(t,e),d=Math.max(t==="context"?1:2,Math.floor((n-i)/o));return r?d:Math.min(t==="context"?20:100,d)}function p(t,e,n){const r=E(n),i=n.outputRowContract===!0||n.output_row_contract===!0;let o=e.estimated_tokens,d=o;for(let s=0;s<st;s+=1){e.estimated_tokens=o;const u=T(i||!Object.hasOwn(t,"row_contract")?t:Object.fromEntries(Object.entries(t).filter(([c])=>c!=="row_contract")),r);if(u===o)return;o=u,d=Math.max(d,o)}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 xt(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 Ct(t,e,n,r){let i=!1;for(;;){if(p(t,e,r),e.estimated_tokens<=e.token_budget||n.length<=1)return i;const o=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(o/n.length)))))),i=!0}}function vt(t,e,n){const r=t.items,i=typeof t.next_cursor=="string",o=i?t.next_cursor:n.after;if(!Array.isArray(r)||typeof o!="string")return!1;const d=J(o);if(d===void 0)return!1;const s=r.length,u=[...r];let c=!1;for(;;){if(c=Ct(t,e,r,n)||c,!c)return!1;const l=xt(r.at(-1));if(l===void 0)return r.splice(0,r.length,...u),p(t,e,n),!1;if(t.next_cursor=rt(d.fingerprint,l,i?d.after_index-(s-r.length):d.after_index+r.length,d.snapshot),p(t,e,n),e.estimated_tokens<=e.token_budget||r.length<=1)break}return typeof t.count=="number"&&(t.count=r.length),typeof t.applied_limit=="number"&&(t.applied_limit=r.length),!0}function Ot(t,e,n,r){if(t==="list"||t==="search")return vt(e,n,r);if(t!=="next"||typeof e.next_cursor=="string")return!1;let i=!1;for(;;){if(p(e,n,r),n.estimated_tokens<=n.token_budget)return i;const o=K[t].map(a=>({key:a,rows:Array.isArray(e[a])?e[a]:[]})).filter(({rows:a})=>a.length>0).sort((a,f)=>f.rows.length-a.rows.length||a.key.localeCompare(f.key))[0];if(o===void 0)return i;const d=K[t].reduce((a,f)=>a+(Array.isArray(e[f])?e[f].length:0),0);if(d<=1)return i;const s=Math.min(o.rows.length,d-1),u=Buffer.byteLength(JSON.stringify(o.rows),"utf8"),c=Math.max(1,Math.ceil(u/o.rows.length)),l=(n.estimated_tokens-n.token_budget)*4,_=Math.min(s,Math.max(1,Math.ceil(l/c)));o.rows.splice(-_,_),i=!0}}function $(t,e,n){if(typeof e.for!="string")return n;const r=t.startsWith("list-")?"list":t;if(!(r in W))return n;const i=r,o=X(i,e.for),d=w(e),s=C(d,e.tokenBudget??e.token_budget,o.token_budget),u={command:i,intent:o.intent,source:o.source,included_field_groups:[...o.included_field_groups],token_budget:s,declared_token_budget:o.token_budget,token_budget_override:s-o.token_budget,estimated_tokens:0,within_budget:!0,degradation:pt[i],declaration_feasible:!0,result_omitted:!1},c={...n},l=v(i,o.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.",c.budget_derived_limit=l,Bt({builtInCommand:i,intent:o.intent},u,c,e)}const _=L.get(e)??0,a=u.token_budget;u.token_budget=a-_;const f=d==="unbounded"?M(c,u,e):It(i,c,u,e,dt(t,e));u.declaration_feasible=u.estimated_tokens<=u.declared_token_budget;const b=V(d,u,f,()=>H(t,i,o.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,b}function M(t,e,n){const r={...t,context_intent:e};return p(r,e,n),r}function It(t,e,n,r,i){let o=M(e,n,r);return n.estimated_tokens>n.token_budget&&(n.degradation="recursive_budget_compaction",o=M(S(e,i),n,r)),n.estimated_tokens>n.token_budget&&Ot(t,o,n,r)&&(n.degradation="budget_row_compaction",p(o,n,r)),o}const L=new WeakMap;function V(t,e,n,r){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:r()},context_intent:e})}const Tt=["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"];function Y(t,e){if(typeof t.after!="string"||t.after.length===0||z(e))return e;const n=J(t.after)?.fingerprint??"opaque_cursor",r={...e};for(const i of Tt)delete r[i];return r.continuation_contract={fingerprint:n,metadata:"reference",restore_with:"omit --after"},r}function m(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Et(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 Rt(t){return typeof t.fields=="string"&&t.fields.trim()!==""?` --fields ${I(t.fields)}`:""}function Bt(t,e,n,r){const i=k(r.limit),o=e.budget_derived_limit;if(i===void 0||i<=o)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 ${o} rows, so it reduced the caller's --limit ${i}.`,e.limit_override={flag:"--limit",requested:i,effective:o,...Number.isSafeInteger(u)?{token_budget_for_requested:u,restore_with:`${yt(r)} ${u}`}:{}};const c=`${mt}:--limit ${i}->${o}`;n.warnings=Array.isArray(n.warnings)?[...n.warnings,c]:[c],m(n.filters)&&(n.filters={...n.filters,requested_limit:String(i)})}function H(t,e,n,r,i,o){const d=Et(e,i),s=e==="get"?"":` --limit ${r.budget_derived_limit??1}`,{output_budget:u}=ct({effective_budget_tokens:r.token_budget,measured_result_tokens:r.estimated_tokens});return`pm ${t}${d}${Rt(o)} --for ${I(n)} --token-budget ${u}${s}`}function y(t,e){if(m(t))return typeof t[e]=="number"?t[e]:void 0}function Q(t,e){let n=t;for(let r=0;r<8;r+=1){At(n);const i=y(n.context_intent,"estimated_tokens"),o=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=ut(n,e),y(n.context_intent,"estimated_tokens")===i&&y(n.read_output,"estimated_tokens")===o&&y(n.read_session,"spent_this_call_tokens")===d)break}return n}function At(t){const e=t.context_intent;m(e)&&Number(e.estimated_tokens)>Number(e.token_budget)&&(e.within_budget=!1)}function Nt(t,e){const n=e.context_intent;if(!m(n)||n.result_omitted===!0)return;const r=n.degradation==="recursive_budget_compaction"||n.degradation==="budget_row_compaction",i={...e};for(const o of ft(t)){const d=e[o.path];if(Array.isArray(d)&&Array.isArray(o.value)&&d.length<=o.value.length){const s=o.value.slice(0,d.length);i[o.path]=r?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 Zt(t,e,n){const r=nt(t,et(t??"",n));if(typeof r!="object"||r===null||Array.isArray(r))return R(n,r),r;const i=t??"",o=r,d=$(i,e,o),s=y(d.context_intent,"estimated_tokens"),u=Nt(o,d),c=O(i,e,n,d,u),l=P(e,c,d.context_intent);if(l===void 0)return St(e,c,d)?Mt(i,e,n,o,d,Number(s),u,c):c;const _={...e};L.set(_,l.estimated-Number(s));const a=$(i,_,o),f=Z(i,e,_,n,a,u),b=f===void 0?l:P(e,f,a.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??c,()=>H(i,g.command,g.intent,g,o,e)))}function St(t,e,n){const r=n.context_intent;return Object.hasOwn(e,"output_budget_exceeded")&&m(r)&&r.result_omitted!==!0&&$t.has(String(r.command))&&(t.outputInclude??t.output_include)===void 0&&(t.outputSession??t.output_session)===void 0}const $t=new Set(["list","search"]);function Mt(t,e,n,r,i,o,d,s){const u=O(t,{...e,outputBudget:"unbounded"},n,{...i,context_intent:{...i.context_intent}},d),c={...e};L.set(c,T(u,E(e))-o);const l=$(t,c,r),_=Z(t,e,c,n,l,d);return _===void 0||Object.hasOwn(_,"output_budget_exceeded")||P(e,_,l.context_intent)!==void 0?s:_}function Z(t,e,n,r,i,o){return z(i)||Lt(e,i)?void 0:O(t,n,r,i,o)}function Lt(t,e){const n=t.outputCursor??t.output_cursor;if(typeof n!="string")return!1;const r=it(n),i=e[r.path];return Array.isArray(i)&&i.length<=r.offset}function P(t,e,n){const r=m(e.context_intent),i=r?e.context_intent:n;if(!m(i)||i.result_omitted===!0||Object.hasOwn(e,"output_budget_exceeded"))return;const o=i,d=r?o.estimated_tokens:T(e,E(t));return w(t)==="unbounded"||d<=o.token_budget?void 0:{receipt:o,estimated:d}}function Dt(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,r,i){const o={...e,outputRowContract:e.outputRowContract===!0||e.output_row_contract===!0};at(o,{...i===void 0?{}:{continuationBinding:Y(e,i)},...Dt(r.context_intent)});const d=ot(t,o,Y(e,r));if(R(n,d),e.outputRowContract===!0||e.output_row_contract===!0||!Object.hasOwn(d,"row_contract"))return m(d.context_intent)?Q(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=Q(s,e);return delete u.row_contract,R(d,u),u}export{mt as CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING,U as PM_CONTEXT_INTENT_CONTRACTS,Qt as applyContextIntentProjection,$ as attachContextIntentReceipt,Zt as attachReadOutputContracts,kt as composeContextIntentContracts,xt as contextIntentRowId,J as decodeContextIntentCursor,bt as getActiveContextIntentContracts,X as resolveContextIntentContract,Ht 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{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};
2
2
  //# sourceMappingURL=context-intent-contracts.js.map
@@ -1,2 +1,2 @@
1
- import{isDeepStrictEqual as k}from"node:util";import{resolvePmCommandOperation as z}from"../cli-contracts/command-aliases.js";import{describeFlagScalarValueFailure as N,resolveExtensionFlagValueContract as F,resolveExtensionLongFlagName as L,EXIT_CODE as m,PmCliError as y,flattenFlagListValue as B,resolveFlagValueKind as pe}from"../runtime-primitives.js";import{RESERVED_EXTENSION_HOST_FLAG_NAMES as ge}from"../../core/extensions/reserved-host-flags.js";const he=new Set(["__proto__","prototype","constructor"]),x=Symbol("looseOptionOccurrences");function h(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(t,o)=>o.toUpperCase())}function me(e,n,t){const o=e[n];if(o===void 0){e[n]=t;return}if(Array.isArray(o)){o.push(t),e[n]=o;return}e[n]=[o,t]}function V(e,n){const t=e[n];if(!t.startsWith("-")||t==="-"||t==="--")return null;if(!t.startsWith("--")){const i=t.indexOf("=");if(i>=0)return{consumed:1,key:t.slice(1,i).trim(),value:t.slice(i+1),attached:!0};const l=t.slice(1).trim(),a=e[n+1];return typeof a=="string"&&!a.startsWith("-")?{consumed:2,key:l,value:a}:{consumed:1,key:l,value:!0}}const o=t.indexOf("=");if(o>=0)return{consumed:1,key:t.slice(2,o).trim(),value:t.slice(o+1),attached:!0};if(t.startsWith("--no-"))return{consumed:1,key:t.slice(5).trim(),value:!1};const r=t.slice(2).trim(),s=e[n+1];return typeof s=="string"&&!s.startsWith("-")?{consumed:2,key:r,value:s}:{consumed:1,key:r,value:!0}}function E(e){return he.has(e)}function K(e){const n=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return pe(n)}function S(e){const n=[],t=L(e.long)??"",o=typeof e.short=="string"?e.short.trim():"";if(t.startsWith("--")){const r=h(t.slice(2));r.length>0&&!E(r)&&n.push(r)}if(o.startsWith("-")&&!o.startsWith("--")){const r=h(o.slice(1));r.length>0&&!E(r)&&n.push(r)}return[...new Set(n)]}function He(e){const n=new Set;for(const t of e)for(const o of S(t))n.add(o);return n}function O(e){const n=L(e.long)??"";if(n.startsWith("--")){const t=h(n.slice(2));if(t.length>0&&!E(t))return t}return S(e)[0]??null}function $(e){const n=L(e.long)??"";if(n.startsWith("--")&&n.length>2)return n;const t=typeof e.short=="string"?e.short.trim():"";return t.startsWith("-")&&!t.startsWith("--")&&t.length>1?t:null}function U(e,n){return[...(n.definitions??e).map(o=>$(o)).filter(o=>o!==null),...n.inheritedFlags??[]]}function Je(e,n,t,o={}){if(n.length===0)return;const r=new Set,s=new Map,i=[],l=U(n,o);for(const a of n){const u=S(a),c=$(a);for(const g of u)r.add(g),a.enabled===!1&&s.set(g,c);a.required===!0&&a.enabled!==!1&&u.length>0&&i.push({keys:u,label:c,definition:a})}for(const a of Object.keys(e)){r.has(a)||I(`--${a}`,`--${a}`,t,l);const u=s.get(a);u&&G(u,t)}for(const a of i){const u=c=>Object.hasOwn(e,c)&&(a.definition.list!==!0||q(a.definition,e[c]));a.keys.some(u)||H(a.definition,a.keys[0],a.label,t)}}function I(e,n,t,o){const r=o.length>0?` Expected one of: ${[...new Set(o)].join(", ")}.`:"";throw new y(`Unknown option '${e}' for extension command '${t}'.${r}`,m.USAGE,{code:"unknown_option",flag:n,required:`Use a flag the command accepts; run pm contracts --command ${t} --flags-only --json to list them.`})}function G(e,n){throw new y(`Option '${e}' is disabled for extension command '${n}'.`,m.USAGE,{code:"extension_option_disabled",flag:e,required:`Remove ${e}; the command declares it with enabled: false.`,why:"A disabled declaration keeps the flag in the contract while refusing every value for it.",examples:[`pm ${n} --help`],nextSteps:[`Run pm contracts --command ${n} --flags-only --json to list the flags this command accepts.`]})}function H(e,n,t,o){const r=F(e),s=r.value_arity==="none"?t:r.value_arity==="optional"?`${t} [${r.value_name}]`:`${t} <${r.value_name}>`;throw new y(`Missing required option '${t}' for extension command '${o}'.`,m.USAGE,{code:"missing_required_option",flag:t,field:n,required:`Pass ${s}.`,why:"The command declares this flag as required, so pm refuses the invocation before the extension handler runs.",examples:[`pm ${o} ${s}`],nextSteps:[`Run pm contracts --command ${o} --flags-only --json to read each flag's sdk_option key.`],recovery:{missing:[t]}})}function ye(e){return typeof e=="string"||e==null?e:String(e)}function Oe(e){if(typeof e=="number")return e;if(typeof e=="string"&&e.trim().length>0){const n=Number(e);return Number.isFinite(n)?n:e}return e}function J(e){if(typeof e=="boolean")return e;if(typeof e=="string"){const n=e.trim().toLowerCase();if(n==="true"||n==="1")return!0;if(n==="false"||n==="0")return!1}return e}const be={string:ye,number:Oe,boolean:J};function b(e,n){return Array.isArray(e)?e.map(t=>b(t,n)):be[n](e)}function D(e,n,t){const o=t?(Array.isArray(e)?e.flat(1/0):[e]).filter(r=>r!=null&&r!==""):B(e);return n?o.map(r=>b(r,n)):o}function q(e,n){return D(n,null,e.repeatable===!0).length>0}function ve(e,n,t,o){return t?D(e,n,o):n?b(e,n):e}function we(e,n,t){const o=Y(e,n);return o.length===0?t:o.map(r=>r.value)}function X(e){return F(e).value_arity==="none"}function R(e,n,t,o,r){const s=$(e),i=r?` for extension command '${r}'`:"",l=t===!0?"no value":JSON.stringify(t);throw new y(`Option '${s}'${i} expects ${o}; received ${l}.`,m.USAGE,{code:"extension_flag_value_invalid",flag:s,required:`Pass ${s} ${n==="number"?"<number>":"<true|false|1|0>"}.`,why:`The flag declares value_type ${n} with value_validation strict, so a malformed token is refused before the extension handler runs.`,nextSteps:[`Re-run with a valid ${n} value for ${s}.`,`Run pm ${r??"<command>"} --help to review the declared flag contract.`]})}function W(e,n){return e.value_validation==="strict"&&n!=="string"}function Y(e,n){const t=e[x];if(!t)return[];const o=new Set(n);return t.filter(r=>o.has(r.key))}function Se(e,n,t,o){if(X(e))for(const r of Y(t,n)){if(r.attached!==!0)continue;const s=e.list===!0&&e.repeatable!==!0?B(r.value):[r.value];for(const i of s){const l=N(b(i,"boolean"),"boolean");l!==null&&R(e,"boolean",i,l.expected,o)}}}function $e(e,n,t,o,r){const s=Array.isArray(t)?t.flat(1/0):[t],i=o?s:s.flatMap(l=>typeof l=="string"?l.split(","):[l]);for(const l of i)if(typeof l=="string"&&l.trim().length===0){const a=N(l,n);R(e,n,l,a.expected,r)}}function M(e,n,t,o){if(!W(e,t))return n;const r=t==="boolean"&&X(e),s=i=>{const l=N(i,t);return l===null?i:r&&typeof i=="string"?!0:R(e,t,i,l.expected,o)};return Array.isArray(n)?n.map(s):s(n)}function xe(e,n,t,o){for(const r of t)if(!(r===n||!Object.hasOwn(e,r))){if(Object.hasOwn(e,n)){if(o){const s=e[n],i=e[r];e[n]=[...Array.isArray(s)?s:[s],...Array.isArray(i)?i:[i]].filter(l=>l!=null)}delete e[r];continue}e[n]=e[r],delete e[r]}}function Z(e,n,t=e,o){if(n.length===0)return e;const r=Object.create(null);for(const[i,l]of Object.entries(e))r[i]=l;const s=new Set(n.map(i=>O(i)).filter(i=>i!==null));for(const i of n){const l=O(i);if(l){const a=S(i).filter(u=>u===l||!s.has(u));Ae(r,i,l,a,t,o)}}return r}function Ae(e,n,t,o,r,s){const i=n.list===!0,l=K(n);l&&!i&&_e(e,n,t,o,l,s),xe(e,t,o,i);const a=n.repeatable===!0;if(!Object.hasOwn(e,t)){n.default!==void 0&&(e[t]=ve(n.default,l,i,a));return}if(l==="boolean"&&W(n,l)&&Se(n,o,r,s),i){e[t]=Le(n,o,r,e[t],l,a,s);return}l&&(e[t]=M(n,b(e[t],l),l,s))}function _e(e,n,t,o,r,s){for(const i of o)i!==t&&Object.hasOwn(e,i)&&M(n,b(e[i],r),r,s)}function Le(e,n,t,o,r,s,i){const l=we(t,n,o);r&&W(e,r)&&$e(e,r,l,s,i);const a=D(l,r,s);return r?M(e,a,r,i):a}function Xe(e){const n=Object.create(null),t=[];Object.defineProperty(n,x,{value:t});let o=0;for(;o<e.length;){const r=V(e,o);if(!r){o+=1;continue}const s=h(r.key);if(s.length===0||E(s)){o+=r.consumed;continue}me(n,s,r.value),t.push({...r,key:s}),o+=r.consumed}return n}function Ye(e){const n=[];let t=0;for(;t<e.length;){if(e[t]==="--"){n.push(...e.slice(t+1));break}const o=V(e,t);if(o){t+=Math.max(1,o.consumed);continue}n.push(e[t]),t+=1}return n}function Ze(e,n){if(n.length===0)return[...e];const t=new Set,o=new Set;for(const i of n){const l=K(i);for(const a of S(i))t.add(a),l==="boolean"&&o.add(a)}if(t.size===0)return[...e];const r=[];let s=0;for(;s<e.length;){if(e[s]==="--"){r.push(...e.slice(s+1));break}const i=V(e,s);if(i){const l=h(i.key);if(t.has(l)){const a=e[s],u=o.has(l)&&!a.includes("=")?1:i.consumed;s+=u;continue}}r.push(e[s]),s+=1}return r}function Qe(e){return O(e)}function Q(e){return e.trim().toLowerCase().split(/\s+/u).filter(n=>n.length>0).join(" ")}function Pe(e,n){const t=Q(n);if(t.length===0)return[];const o=z(t);return e.flags.filter(r=>z(Q(r.target_command))===o).flatMap(r=>[...r.flags])}function P(e,n,t,o){const r=$(e),[s,i]=t;throw new y(`Options '${s}' and '${i}' both set ${r} for extension command '${o}' with different values.`,m.USAGE,{code:"extension_option_spelling_conflict",required:`Pass ${r} once, under the handler key '${n}'.`,why:`'${s}' and '${i}' are spellings of the same declared flag, and pm refuses to choose between two different values.`,nextSteps:[`Remove '${s}' or '${i}' and pass one value as '${n}'.`,`Run pm contracts --command ${o} --flags-only --json to read each flag's sdk_option key.`]})}function en(e,n,t,o={}){if(n.length===0)return e;const r=n.map(c=>c.repeatable===!0&&c.list!==!0?{...c,list:!0}:c),s=re(r),i=Ne(e,s,t),l=new Set([...s.long.values()].map(({handlerKey:c})=>c)),a=Object.create(null),u=Object.create(null);for(const[c,g]of Object.entries(i))l.has(c)?a[c]=g:g===void 0||o.undeclaredKeys==="pass"||Ke(c)?u[c]=g:I(c,Ce(c),t,U(r,{}));return ne(a,r,t),Object.assign(u,Z(a,r,ee(a,s),t))}function ee(e,n){const t=new Set([...n.long.values()].map(({handlerKey:s})=>s)),o=Object.entries(e).filter(([s])=>t.has(s)).flatMap(([s,i])=>(Array.isArray(i)?i.flat(1/0):[i]).map(l=>({consumed:1,key:s,value:l,attached:!0}))),r=Object.create(null);return Object.defineProperty(r,x,{value:o}),r}function ne(e,n,t){for(const o of n){const r=O(o);if(r===null)continue;const s=$(o),i=e[r],l=Object.hasOwn(e,r);o.enabled===!1&&l&&G(s,t);const a=l&&(o.list!==!0||q(o,i));o.required===!0&&o.enabled!==!1&&!a&&H(o,r,s,t),o.list!==!0&&Array.isArray(i)&&Ee(s,t)}}function Ee(e,n){throw new y(`Option '${e}' for extension command '${n}' takes one value; received an array.`,m.USAGE,{code:"extension_flag_value_invalid",flag:e,required:`Pass one value for ${e}, or ask the package to declare it with list: true or repeatable: true.`,why:"The flag is not declared list or repeatable, so pm refuses an array before the extension handler runs instead of handing it a value of the wrong shape.",nextSteps:[`Run pm contracts --command ${n} --flags-only --json to read each flag's value contract.`]})}const te=new Set([...[...ge].flatMap(e=>{const n=e.replace(/^--/u,"");return[n,...n.startsWith("no-")?[n.slice(3)]:[]].flatMap(o=>[h(o),o.replaceAll("-","_")])}),"force","subcommand","inputResponses","requestState"]);function Ke(e){return te.has(e)||te.has(h(e.replace(/^-{1,2}/u,"")))}function Ce(e){return`--${e.replace(/^-+/u,"").replace(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`}function re(e){const n={long:new Map,short:new Map},t=(o,r,s)=>{r.length>0&&!o.has(r)&&o.set(r,s)};for(const o of e){const r=O(o);if(r===null)continue;const s={handlerKey:r,definition:o};t(n.long,r,s);const i=typeof o.short=="string"?o.short.trim():"";i.startsWith("-")&&!i.startsWith("--")&&t(n.short,i.slice(1),s)}return n}function C(e,n){return e.long.get(n)??e.short.get(n.replace(/^-(?!-)/u,""))??e.long.get(h(n.replace(/^-{1,2}/u,"")))}function oe(e,n,t,o){const r=/^(?:--)?no-(.+)$/u.exec(n)?.[1];if(r===void 0||C(e,n)!==void 0)return{spelling:n,value:t};const s=C(e,r);return s===void 0||K(s.definition)!=="boolean"?{spelling:n,value:t}:(s.definition.list===!0||s.definition.repeatable===!0)&&Array.isArray(t)?{spelling:r,value:t.flat(1/0).map(i=>se(n,s.definition,i,o))}:s.definition.list===!0&&t!==void 0?{spelling:r,value:se(n,s.definition,t,o)}:{spelling:r,value:t===void 0?t:j(n,s.definition,t,o)}}function nn(e,n,t){const o=re(e);try{const r=oe(o,n,t,"");if(r.spelling===n)return;const s=C(o,r.spelling);return(s.definition.list===!0||s.definition.repeatable===!0)&&!q(s.definition,r.value)?void 0:{key:s.handlerKey,value:r.value}}catch{return}}function se(e,n,t,o){const r=s=>s.trim().length===0?s:String(j(e,n,s.trim(),o));return t==null?t:typeof t!="string"?j(e,n,t,o):t.trim().length===0?t:n.repeatable===!0||!t.includes(",")?j(e,n,t,o):t.split(",").map(r).join(",")}function j(e,n,t,o){const r=J(t);return typeof r=="boolean"?!r:je(e,n,t,o)}function je(e,n,t,o){const r=$(n);throw new y(`Option '${e}' for extension command '${o}' negates ${r} and expects true, false, 1, or 0; received ${JSON.stringify(t)}.`,m.USAGE,{code:"extension_flag_value_invalid",flag:r,required:`Pass ${r} as true or false, or '${e}' as true.`,why:`'${e}' is the negated spelling of the boolean ${r}, so only a boolean value can be inverted before the extension handler runs.`,nextSteps:[`Run pm contracts --command ${o} --flags-only --json to read each flag's value contract.`]})}function Ne(e,n,t){const o=Object.create(null),r=new Map;for(const[s,i]of Object.entries(e)){const{spelling:l,value:a}=oe(n,s,i,t),u=C(n,l);if(u===void 0)o[l]=a;else if(a!==void 0){const c=r.get(u.handlerKey);c===void 0?(r.set(u.handlerKey,l),o[u.handlerKey]=a):k(ie(u.definition,u.handlerKey,o[u.handlerKey],n,t),ie(u.definition,u.handlerKey,a,n,t))||P(u.definition,u.handlerKey,[c,l],t)}}return o}function ie(e,n,t,o,r){const s={[n]:t};return ne(s,[e],r),Z(s,[e],ee(s,o),r)[n]}function le(e){const n=new Map;for(const t of e){const o=O(t);if(o===null)continue;const r={definition:t,handlerKey:o,kind:K(t),arity:F(t).value_arity,scalar:t.list!==!0},s=[L(t.long),typeof t.short=="string"?t.short.trim():""];for(const i of s.filter(l=>l?.startsWith("-")===!0))n.has(i)||n.set(i,r)}return n}function ae(e,n,t,o=ke){const r=e.optionOf(t),s=n.get(t),i=s!==void 0&&o(s)?s:void 0;if(r!==void 0){const l={arity:r.arity,...r.variadic===!0?{variadic:!0}:{}};if(i?.handlerKey===r.key)return{...l,declared:i};if(s!==void 0)return l;const a=Te(n,t,r,o);return a===void 0?l:{...l,declared:a,negates:!0}}if(!(!e.includesLooseFlags||s===void 0))return i===void 0?{arity:s.arity,loose:!0}:{arity:s.arity,declared:i,loose:!0}}function T(e){return e.length>1&&e.startsWith("-")}const ue=/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/u;function ce(e,n,t){const{tokens:o}=e;let r=0,s,i=!1,l=!1;for(;r<o.length||s!==void 0;){const a=s??o[r++];if(a==="--")return;if(l&&s===void 0&&Fe(e,a))continue;const u=T(a)?De(e,a,o[r],n,t):{consumedByCommander:!1,consumed:0};if(r+=u.consumed,s=u.group,l=u.variadic===!0,!u.consumedByCommander){if(Ve(e.stop,a,i))return;i=!0}}}function Fe(e,n){return!T(n)||e.negativeNumbersAreValues&&ue.test(n)}function Ve(e,n,t){return e!==void 0&&(e.atFirstUnrecognized||!t&&e.atSubcommand(n))}function De(e,n,t,o,r){const s=qe(n,t,o);if(s!==void 0)return r(s.spelling,s.entry,s.value,"loose"),{consumedByCommander:!1,consumed:s.consumed};const i=o(n);if(i!==void 0){const l=i.arity==="required"||i.arity==="optional"&&t!==void 0&&(!T(t)||e.negativeNumbersAreValues&&ue.test(t));return r(n,i,i.negates===!0?!1:l?t:!0,"commander"),{consumedByCommander:!0,consumed:l?1:0,variadic:i.variadic===!0}}return n[1]!=="-"?{consumed:0,...Re(n,o,r)}:{consumedByCommander:We(n,o,r,e.includesLooseFlags?r:()=>{}),consumed:0}}function qe(e,n,t){const o=e.indexOf("="),r=o>1?e.slice(0,o):e,s=t(r);if(s?.loose===!0)return o>1?{spelling:r,entry:s,value:e.slice(o+1),consumed:0}:n!==void 0&&!n.startsWith("-")?{spelling:r,entry:s,value:n,consumed:1}:{spelling:r,entry:s,value:!0,consumed:0};const i=o<0&&e.startsWith("--no-")?t(`--${e.slice(5)}`):void 0;return i?.loose===!0&&i.declared?.kind==="boolean"?{spelling:e,entry:i,value:!1,consumed:0}:void 0}function Re(e,n,t){const o=e.slice(0,2),r=e.length>2?n(o):void 0;return r===void 0||r.loose===!0?{consumedByCommander:!1}:r.arity!=="none"?(t(o,r,e.slice(2),"commander"),{consumedByCommander:!0}):(t(o,r,!0,"commander"),{consumedByCommander:!0,group:`-${e.slice(2)}`})}function We(e,n,t,o){const r=e.indexOf("=");if(r>2){const i=e.slice(0,r),l=n(i);return l!==void 0&&l.arity!=="none"?(t(i,l,e.slice(r+1),"commander"),!0):(l?.declared?.kind==="boolean"&&o(i,l,e.slice(r+1),"loose"),!1)}const s=e.startsWith("--no-")?n(`--${e.slice(5)}`):void 0;return s?.declared?.kind==="boolean"&&o(e,s,!1,"loose"),!1}function tn(e,n,t){const o=le(n),r=new Map;for(const s of e)ce(s,i=>ae(s,o,i),(i,l,a)=>{l.declared!==void 0&&Me(r,l.declared,i,a,t)})}function Me(e,n,t,o,r){const{definition:s,handlerKey:i,kind:l}=n,a=l?b(o,l):o,u=e.get(i)??new Map,c=[...u].find(([g,f])=>g!==t&&!k(f,a));c!==void 0&&P(s,i,[c[0],t],r),u.set(t,a),e.set(i,u)}function Te(e,n,t,o){const r=n.startsWith("--no-")?e.get(`--${n.slice(5)}`):void 0;return r!==void 0&&o(r)&&r.kind==="boolean"&&r.handlerKey===t.key?r:void 0}function ke(e){return e.scalar}function fe(e){return!e.scalar&&e.kind==="boolean"&&e.arity==="none"}function rn(e,n,t){const o=le(t),r=[...new Set(o.values())].filter(fe);if(r.length===0)return e;const s=new Set(t.map(f=>O(f)).filter(f=>f!==null)),i=f=>S(f.definition).filter(d=>d===f.handlerKey||!s.has(d)),l=new Map([...r].reverse().flatMap(f=>i(f).map(d=>[d,f]))),a=new Map;for(const f of n)ce(f,d=>ae(f,o,d,fe)??ze(f,l,d),(d,v,w,A)=>{if(v.declared===void 0)return;const _=a.get(v.declared)??[];_.push(A==="commander"?{value:w}:null),a.set(v.declared,_)});const u=[...a].filter(([,f])=>f.some(d=>d!==null));if(u.length===0)return e;let c=e[x]??[];for(const[f,d]of u){const v=new Set(i(f)),w=c.filter(({key:p})=>v.has(p));if(w.length===0)continue;const A=p=>({consumed:0,key:f.handlerKey,value:p.value});let _=0;const de=d.filter(p=>p===null).length===w.length?d.map(p=>p===null?w[_++]:A(p)):[...w,...d.filter(p=>p!==null).map(A)];c=[...c.filter(({key:p})=>!v.has(p)),...de]}const g=Object.assign(Object.create(null),e);return Object.defineProperty(g,x,{value:c}),g}function ze(e,n,t){const o=!t.startsWith("--")&&e.optionOf(t.slice(0,2))!==void 0;if(!e.includesLooseFlags||o)return;const r=n.get(h(t.replace(/^-+/u,"")));return r===void 0?void 0:{arity:r.arity,declared:r,loose:!0}}export{Z as coerceLooseCommandOptionsWithFlagDefinitions,Pe as collectExtensionFlagDefinitionsForCommand,He as collectLooseCommandOptionKeysForDefinitions,Ye as collectLoosePositionalArgs,en as normalizeDirectExtensionCommandOptions,rn as orderArgvRepeatableSwitchOccurrences,Xe as parseLooseCommandOptions,tn as refuseConflictingArgvOptionSpellings,Qe as resolveExtensionFlagOptionKey,K as resolveLooseOptionCoercionKind,nn as resolveNegatedDeclaredBooleanOption,Ze as stripLooseCommandOptionTokens,Je as validateLooseCommandOptionsWithFlagDefinitions};
1
+ import{isDeepStrictEqual as k}from"node:util";import{resolvePmCommandOperation as z}from"../cli-contracts/command-aliases.js";import{describeFlagScalarValueFailure as N,resolveExtensionFlagValueContract as F,resolveExtensionLongFlagName as L,EXIT_CODE as m,PmCliError as y,flattenFlagListValue as B,resolveFlagValueKind as pe}from"../runtime-primitives.js";import{RESERVED_EXTENSION_HOST_FLAG_NAMES as ge}from"../../core/extensions/reserved-host-flags.js";const he=new Set(["__proto__","prototype","constructor"]),x=Symbol("looseOptionOccurrences");function h(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(t,o)=>o.toUpperCase())}function me(e,n,t){const o=e[n];if(o===void 0){e[n]=t;return}if(Array.isArray(o)){o.push(t),e[n]=o;return}e[n]=[o,t]}function V(e,n){const t=e[n];if(!t.startsWith("-")||t==="-"||t==="--")return null;if(!t.startsWith("--")){const i=t.indexOf("=");if(i>=0)return{consumed:1,key:t.slice(1,i).trim(),value:t.slice(i+1),attached:!0};const l=t.slice(1).trim(),a=e[n+1];return typeof a=="string"&&!a.startsWith("-")?{consumed:2,key:l,value:a}:{consumed:1,key:l,value:!0}}const o=t.indexOf("=");if(o>=0)return{consumed:1,key:t.slice(2,o).trim(),value:t.slice(o+1),attached:!0};if(t.startsWith("--no-"))return{consumed:1,key:t.slice(5).trim(),value:!1};const r=t.slice(2).trim(),s=e[n+1];return typeof s=="string"&&!s.startsWith("-")?{consumed:2,key:r,value:s}:{consumed:1,key:r,value:!0}}function E(e){return he.has(e)}function K(e){const n=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return pe(n)}function S(e){const n=[],t=L(e.long)??"",o=typeof e.short=="string"?e.short.trim():"";if(t.startsWith("--")){const r=h(t.slice(2));r.length>0&&!E(r)&&n.push(r)}if(o.startsWith("-")&&!o.startsWith("--")){const r=h(o.slice(1));r.length>0&&!E(r)&&n.push(r)}return[...new Set(n)]}function He(e){const n=new Set;for(const t of e)for(const o of S(t))n.add(o);return n}function O(e){const n=L(e.long)??"";if(n.startsWith("--")){const t=h(n.slice(2));if(t.length>0&&!E(t))return t}return S(e)[0]??null}function $(e){const n=L(e.long)??"";if(n.startsWith("--")&&n.length>2)return n;const t=typeof e.short=="string"?e.short.trim():"";return t.startsWith("-")&&!t.startsWith("--")&&t.length>1?t:null}function U(e,n){return[...(n.definitions??e).map(o=>$(o)).filter(o=>o!==null),...n.inheritedFlags??[]]}function Je(e,n,t,o={}){if(n.length===0)return;const r=new Set,s=new Map,i=[],l=U(n,o);for(const a of n){const u=S(a),c=$(a);for(const g of u)r.add(g),a.enabled===!1&&s.set(g,c);a.required===!0&&a.enabled!==!1&&u.length>0&&i.push({keys:u,label:c,definition:a})}for(const a of Object.keys(e)){r.has(a)||I(`--${a}`,`--${a}`,t,l);const u=s.get(a);u&&G(u,t)}for(const a of i){const u=c=>Object.hasOwn(e,c)&&(a.definition.list!==!0||W(a.definition,e[c]));a.keys.some(u)||H(a.definition,a.keys[0],a.label,t)}}function I(e,n,t,o){const r=o.length>0?` Expected one of: ${[...new Set(o)].join(", ")}.`:"";throw new y(`Unknown option '${e}' for extension command '${t}'.${r}`,m.USAGE,{code:"unknown_option",flag:n,required:`Use a flag the command accepts; run pm contracts --command ${t} --flags-only --json to list them.`})}function G(e,n){throw new y(`Option '${e}' is disabled for extension command '${n}'.`,m.USAGE,{code:"extension_option_disabled",flag:e,required:`Remove ${e}; the command declares it with enabled: false.`,why:"A disabled declaration keeps the flag in the contract while refusing every value for it.",examples:[`pm ${n} --help`],nextSteps:[`Run pm contracts --command ${n} --flags-only --json to list the flags this command accepts.`]})}function H(e,n,t,o){const r=F(e),s=r.value_arity==="none"?t:r.value_arity==="optional"?`${t} [${r.value_name}]`:`${t} <${r.value_name}>`;throw new y(`Missing required option '${t}' for extension command '${o}'.`,m.USAGE,{code:"missing_required_option",flag:t,field:n,required:`Pass ${s}.`,why:"The command declares this flag as required, so pm refuses the invocation before the extension handler runs.",examples:[`pm ${o} ${s}`],nextSteps:[`Run pm contracts --command ${o} --flags-only --json to read each flag's sdk_option key.`],recovery:{missing:[t]}})}function ye(e){return typeof e=="string"||e==null?e:String(e)}function Oe(e){if(typeof e=="number")return e;if(typeof e=="string"&&e.trim().length>0){const n=Number(e);return Number.isFinite(n)?n:e}return e}function J(e){if(typeof e=="boolean")return e;if(typeof e=="string"){const n=e.trim().toLowerCase();if(n==="true"||n==="1")return!0;if(n==="false"||n==="0")return!1}return e}const be={string:ye,number:Oe,boolean:J};function b(e,n){return Array.isArray(e)?e.map(t=>b(t,n)):be[n](e)}function D(e,n,t){const o=t?(Array.isArray(e)?e.flat(1/0):[e]).filter(r=>r!=null&&r!==""):B(e);return n?o.map(r=>b(r,n)):o}function W(e,n){return D(n,null,e.repeatable===!0).length>0}function ve(e,n,t,o){return t?D(e,n,o):n?b(e,n):e}function we(e,n,t){const o=Y(e,n);return o.length===0?t:o.map(r=>r.value)}function X(e){return F(e).value_arity==="none"}function q(e,n,t,o,r){const s=$(e),i=r?` for extension command '${r}'`:"",l=t===!0?"no value":JSON.stringify(t);throw new y(`Option '${s}'${i} expects ${o}; received ${l}.`,m.USAGE,{code:"extension_flag_value_invalid",flag:s,required:`Pass ${s} ${n==="number"?"<number>":"<true|false|1|0>"}.`,why:`The flag declares value_type ${n} with value_validation strict, so a malformed token is refused before the extension handler runs.`,nextSteps:[`Re-run with a valid ${n} value for ${s}.`,`Run pm ${r??"<command>"} --help to review the declared flag contract.`]})}function R(e,n){return e.value_validation==="strict"&&n!=="string"}function Y(e,n){const t=e[x];if(!t)return[];const o=new Set(n);return t.filter(r=>o.has(r.key))}function Se(e,n,t,o){if(X(e))for(const r of Y(t,n)){if(r.attached!==!0)continue;const s=e.list===!0&&e.repeatable!==!0?B(r.value):[r.value];for(const i of s){const l=N(b(i,"boolean"),"boolean");l!==null&&q(e,"boolean",i,l.expected,o)}}}function $e(e,n,t,o,r){const s=Array.isArray(t)?t.flat(1/0):[t],i=o?s:s.flatMap(l=>typeof l=="string"?l.split(","):[l]);for(const l of i)if(typeof l=="string"&&l.trim().length===0){const a=N(l,n);q(e,n,l,a.expected,r)}}function M(e,n,t,o){if(!R(e,t))return n;const r=t==="boolean"&&X(e),s=i=>{const l=N(i,t);return l===null?i:r&&typeof i=="string"?!0:q(e,t,i,l.expected,o)};return Array.isArray(n)?n.map(s):s(n)}function xe(e,n,t,o){for(const r of t)if(!(r===n||!Object.hasOwn(e,r))){if(Object.hasOwn(e,n)){if(o){const s=e[n],i=e[r];e[n]=[...Array.isArray(s)?s:[s],...Array.isArray(i)?i:[i]].filter(l=>l!=null)}delete e[r];continue}e[n]=e[r],delete e[r]}}function Z(e,n,t=e,o){if(n.length===0)return e;const r=Object.create(null);for(const[i,l]of Object.entries(e))r[i]=l;const s=new Set(n.map(i=>O(i)).filter(i=>i!==null));for(const i of n){const l=O(i);if(l){const a=S(i).filter(u=>u===l||!s.has(u));Ae(r,i,l,a,t,o)}}return r}function Ae(e,n,t,o,r,s){const i=n.list===!0,l=K(n);l&&!i&&_e(e,n,t,o,l,s),xe(e,t,o,i);const a=n.repeatable===!0;if(!Object.hasOwn(e,t)){n.default!==void 0&&(e[t]=ve(n.default,l,i,a));return}if(l==="boolean"&&R(n,l)&&Se(n,o,r,s),i){e[t]=Le(n,o,r,e[t],l,a,s);return}l&&(e[t]=M(n,b(e[t],l),l,s))}function _e(e,n,t,o,r,s){for(const i of o)i!==t&&Object.hasOwn(e,i)&&M(n,b(e[i],r),r,s)}function Le(e,n,t,o,r,s,i){const l=we(t,n,o);r&&R(e,r)&&$e(e,r,l,s,i);const a=D(l,r,s);return r?M(e,a,r,i):a}function Xe(e){const n=Object.create(null),t=[];Object.defineProperty(n,x,{value:t});let o=0;for(;o<e.length;){const r=V(e,o);if(!r){o+=1;continue}const s=h(r.key);if(s.length===0||E(s)){o+=r.consumed;continue}me(n,s,r.value),t.push({...r,key:s}),o+=r.consumed}return n}function Ye(e){const n=[];let t=0;for(;t<e.length;){if(e[t]==="--"){n.push(...e.slice(t+1));break}const o=V(e,t);if(o){t+=Math.max(1,o.consumed);continue}n.push(e[t]),t+=1}return n}function Ze(e,n){if(n.length===0)return[...e];const t=new Set,o=new Set;for(const i of n){const l=K(i);for(const a of S(i))t.add(a),l==="boolean"&&o.add(a)}if(t.size===0)return[...e];const r=[];let s=0;for(;s<e.length;){if(e[s]==="--"){r.push(...e.slice(s+1));break}const i=V(e,s);if(i){const l=h(i.key);if(t.has(l)){const a=e[s],u=o.has(l)&&!a.includes("=")?1:i.consumed;s+=u;continue}}r.push(e[s]),s+=1}return r}function Qe(e){return O(e)}function Q(e){return e.trim().toLowerCase().split(/\s+/u).filter(n=>n.length>0).join(" ")}function Pe(e,n){const t=Q(n);if(t.length===0)return[];const o=z(t);return e.flags.filter(r=>z(Q(r.target_command))===o).flatMap(r=>[...r.flags])}function P(e,n,t,o){const r=$(e),[s,i]=t;throw new y(`Options '${s}' and '${i}' both set ${r} for extension command '${o}' with different values.`,m.USAGE,{code:"extension_option_spelling_conflict",required:`Pass ${r} once, under the handler key '${n}'.`,why:`'${s}' and '${i}' are spellings of the same declared flag, and pm refuses to choose between two different values.`,nextSteps:[`Remove '${s}' or '${i}' and pass one value as '${n}'.`,`Run pm contracts --command ${o} --flags-only --json to read each flag's sdk_option key.`]})}function en(e,n,t,o={}){if(n.length===0)return e;const r=n.map(c=>c.repeatable===!0&&c.list!==!0?{...c,list:!0}:c),s=re(r),i=Ne(e,s,t),l=new Set([...s.long.values()].map(({handlerKey:c})=>c)),a=Object.create(null),u=Object.create(null);for(const[c,g]of Object.entries(i))l.has(c)?a[c]=g:g===void 0||o.undeclaredKeys==="pass"||Ke(c)?u[c]=g:I(c,Ce(c),t,U(r,{}));return ne(a,r,t),Object.assign(u,Z(a,r,ee(a,s),t))}function ee(e,n){const t=new Set([...n.long.values()].map(({handlerKey:s})=>s)),o=Object.entries(e).filter(([s])=>t.has(s)).flatMap(([s,i])=>(Array.isArray(i)?i.flat(1/0):[i]).map(l=>({consumed:1,key:s,value:l,attached:!0}))),r=Object.create(null);return Object.defineProperty(r,x,{value:o}),r}function ne(e,n,t){for(const o of n){const r=O(o);if(r===null)continue;const s=$(o),i=e[r],l=Object.hasOwn(e,r);o.enabled===!1&&l&&G(s,t);const a=l&&(o.list!==!0||W(o,i));o.required===!0&&o.enabled!==!1&&!a&&H(o,r,s,t),o.list!==!0&&Array.isArray(i)&&Ee(s,t)}}function Ee(e,n){throw new y(`Option '${e}' for extension command '${n}' takes one value; received an array.`,m.USAGE,{code:"extension_flag_value_invalid",flag:e,required:`Pass one value for ${e}, or ask the package to declare it with list: true or repeatable: true.`,why:"The flag is not declared list or repeatable, so pm refuses an array before the extension handler runs instead of handing it a value of the wrong shape.",nextSteps:[`Run pm contracts --command ${n} --flags-only --json to read each flag's value contract.`]})}const te=new Set([...[...ge].filter(e=>e.startsWith("--")).flatMap(e=>{const n=e.replace(/^--/u,"");return[n,...n.startsWith("no-")?[n.slice(3)]:[]].flatMap(o=>[h(o),o.replaceAll("-","_")])}),"force","subcommand","inputResponses","requestState"]);function Ke(e){return te.has(e)||te.has(h(e.replace(/^-{1,2}/u,"")))}function Ce(e){return`--${e.replace(/^-+/u,"").replace(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`}function re(e){const n={long:new Map,short:new Map},t=(o,r,s)=>{r.length>0&&!o.has(r)&&o.set(r,s)};for(const o of e){const r=O(o);if(r===null)continue;const s={handlerKey:r,definition:o};t(n.long,r,s);const i=typeof o.short=="string"?o.short.trim():"";i.startsWith("-")&&!i.startsWith("--")&&t(n.short,i.slice(1),s)}return n}function C(e,n){return e.long.get(n)??e.short.get(n.replace(/^-(?!-)/u,""))??e.long.get(h(n.replace(/^-{1,2}/u,"")))}function oe(e,n,t,o){const r=/^(?:--)?no-(.+)$/u.exec(n)?.[1];if(r===void 0||C(e,n)!==void 0)return{spelling:n,value:t};const s=C(e,r);return s===void 0||K(s.definition)!=="boolean"?{spelling:n,value:t}:(s.definition.list===!0||s.definition.repeatable===!0)&&Array.isArray(t)?{spelling:r,value:t.flat(1/0).map(i=>se(n,s.definition,i,o))}:s.definition.list===!0&&t!==void 0?{spelling:r,value:se(n,s.definition,t,o)}:{spelling:r,value:t===void 0?t:j(n,s.definition,t,o)}}function nn(e,n,t){const o=re(e);try{const r=oe(o,n,t,"");if(r.spelling===n)return;const s=C(o,r.spelling);return(s.definition.list===!0||s.definition.repeatable===!0)&&!W(s.definition,r.value)?void 0:{key:s.handlerKey,value:r.value}}catch{return}}function se(e,n,t,o){const r=s=>s.trim().length===0?s:String(j(e,n,s.trim(),o));return t==null?t:typeof t!="string"?j(e,n,t,o):t.trim().length===0?t:n.repeatable===!0||!t.includes(",")?j(e,n,t,o):t.split(",").map(r).join(",")}function j(e,n,t,o){const r=J(t);return typeof r=="boolean"?!r:je(e,n,t,o)}function je(e,n,t,o){const r=$(n);throw new y(`Option '${e}' for extension command '${o}' negates ${r} and expects true, false, 1, or 0; received ${JSON.stringify(t)}.`,m.USAGE,{code:"extension_flag_value_invalid",flag:r,required:`Pass ${r} as true or false, or '${e}' as true.`,why:`'${e}' is the negated spelling of the boolean ${r}, so only a boolean value can be inverted before the extension handler runs.`,nextSteps:[`Run pm contracts --command ${o} --flags-only --json to read each flag's value contract.`]})}function Ne(e,n,t){const o=Object.create(null),r=new Map;for(const[s,i]of Object.entries(e)){const{spelling:l,value:a}=oe(n,s,i,t),u=C(n,l);if(u===void 0)o[l]=a;else if(a!==void 0){const c=r.get(u.handlerKey);c===void 0?(r.set(u.handlerKey,l),o[u.handlerKey]=a):k(ie(u.definition,u.handlerKey,o[u.handlerKey],n,t),ie(u.definition,u.handlerKey,a,n,t))||P(u.definition,u.handlerKey,[c,l],t)}}return o}function ie(e,n,t,o,r){const s={[n]:t};return ne(s,[e],r),Z(s,[e],ee(s,o),r)[n]}function le(e){const n=new Map;for(const t of e){const o=O(t);if(o===null)continue;const r={definition:t,handlerKey:o,kind:K(t),arity:F(t).value_arity,scalar:t.list!==!0},s=[L(t.long),typeof t.short=="string"?t.short.trim():""];for(const i of s.filter(l=>l?.startsWith("-")===!0))n.has(i)||n.set(i,r)}return n}function ae(e,n,t,o=ke){const r=e.optionOf(t),s=n.get(t),i=s!==void 0&&o(s)?s:void 0;if(r!==void 0){const l={arity:r.arity,...r.variadic===!0?{variadic:!0}:{}};if(i?.handlerKey===r.key)return{...l,declared:i};if(s!==void 0)return l;const a=Te(n,t,r,o);return a===void 0?l:{...l,declared:a,negates:!0}}if(!(!e.includesLooseFlags||s===void 0))return i===void 0?{arity:s.arity,loose:!0}:{arity:s.arity,declared:i,loose:!0}}function T(e){return e.length>1&&e.startsWith("-")}const ue=/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/u;function ce(e,n,t){const{tokens:o}=e;let r=0,s,i=!1,l=!1;for(;r<o.length||s!==void 0;){const a=s??o[r++];if(a==="--")return;if(l&&s===void 0&&Fe(e,a))continue;const u=T(a)?De(e,a,o[r],n,t):{consumedByCommander:!1,consumed:0};if(r+=u.consumed,s=u.group,l=u.variadic===!0,!u.consumedByCommander){if(Ve(e.stop,a,i))return;i=!0}}}function Fe(e,n){return!T(n)||e.negativeNumbersAreValues&&ue.test(n)}function Ve(e,n,t){return e!==void 0&&(e.atFirstUnrecognized||!t&&e.atSubcommand(n))}function De(e,n,t,o,r){const s=We(n,t,o);if(s!==void 0)return r(s.spelling,s.entry,s.value,"loose"),{consumedByCommander:!1,consumed:s.consumed};const i=o(n);if(i!==void 0){const l=i.arity==="required"||i.arity==="optional"&&t!==void 0&&(!T(t)||e.negativeNumbersAreValues&&ue.test(t));return r(n,i,i.negates===!0?!1:l?t:!0,"commander"),{consumedByCommander:!0,consumed:l?1:0,variadic:i.variadic===!0}}return n[1]!=="-"?{consumed:0,...qe(n,o,r)}:{consumedByCommander:Re(n,o,r,e.includesLooseFlags?r:()=>{}),consumed:0}}function We(e,n,t){const o=e.indexOf("="),r=o>1?e.slice(0,o):e,s=t(r);if(s?.loose===!0)return o>1?{spelling:r,entry:s,value:e.slice(o+1),consumed:0}:n!==void 0&&!n.startsWith("-")?{spelling:r,entry:s,value:n,consumed:1}:{spelling:r,entry:s,value:!0,consumed:0};const i=o<0&&e.startsWith("--no-")?t(`--${e.slice(5)}`):void 0;return i?.loose===!0&&i.declared?.kind==="boolean"?{spelling:e,entry:i,value:!1,consumed:0}:void 0}function qe(e,n,t){const o=e.slice(0,2),r=e.length>2?n(o):void 0;return r===void 0||r.loose===!0?{consumedByCommander:!1}:r.arity!=="none"?(t(o,r,e.slice(2),"commander"),{consumedByCommander:!0}):(t(o,r,!0,"commander"),{consumedByCommander:!0,group:`-${e.slice(2)}`})}function Re(e,n,t,o){const r=e.indexOf("=");if(r>2){const i=e.slice(0,r),l=n(i);return l!==void 0&&l.arity!=="none"?(t(i,l,e.slice(r+1),"commander"),!0):(l?.declared?.kind==="boolean"&&o(i,l,e.slice(r+1),"loose"),!1)}const s=e.startsWith("--no-")?n(`--${e.slice(5)}`):void 0;return s?.declared?.kind==="boolean"&&o(e,s,!1,"loose"),!1}function tn(e,n,t){const o=le(n),r=new Map;for(const s of e)ce(s,i=>ae(s,o,i),(i,l,a)=>{l.declared!==void 0&&Me(r,l.declared,i,a,t)})}function Me(e,n,t,o,r){const{definition:s,handlerKey:i,kind:l}=n,a=l?b(o,l):o,u=e.get(i)??new Map,c=[...u].find(([g,f])=>g!==t&&!k(f,a));c!==void 0&&P(s,i,[c[0],t],r),u.set(t,a),e.set(i,u)}function Te(e,n,t,o){const r=n.startsWith("--no-")?e.get(`--${n.slice(5)}`):void 0;return r!==void 0&&o(r)&&r.kind==="boolean"&&r.handlerKey===t.key?r:void 0}function ke(e){return e.scalar}function fe(e){return!e.scalar&&e.kind==="boolean"&&e.arity==="none"}function rn(e,n,t){const o=le(t),r=[...new Set(o.values())].filter(fe);if(r.length===0)return e;const s=new Set(t.map(f=>O(f)).filter(f=>f!==null)),i=f=>S(f.definition).filter(d=>d===f.handlerKey||!s.has(d)),l=new Map([...r].reverse().flatMap(f=>i(f).map(d=>[d,f]))),a=new Map;for(const f of n)ce(f,d=>ae(f,o,d,fe)??ze(f,l,d),(d,v,w,A)=>{if(v.declared===void 0)return;const _=a.get(v.declared)??[];_.push(A==="commander"?{value:w}:null),a.set(v.declared,_)});const u=[...a].filter(([,f])=>f.some(d=>d!==null));if(u.length===0)return e;let c=e[x]??[];for(const[f,d]of u){const v=new Set(i(f)),w=c.filter(({key:p})=>v.has(p));if(w.length===0)continue;const A=p=>({consumed:0,key:f.handlerKey,value:p.value});let _=0;const de=d.filter(p=>p===null).length===w.length?d.map(p=>p===null?w[_++]:A(p)):[...w,...d.filter(p=>p!==null).map(A)];c=[...c.filter(({key:p})=>!v.has(p)),...de]}const g=Object.assign(Object.create(null),e);return Object.defineProperty(g,x,{value:c}),g}function ze(e,n,t){const o=!t.startsWith("--")&&e.optionOf(t.slice(0,2))!==void 0;if(!e.includesLooseFlags||o)return;const r=n.get(h(t.replace(/^-+/u,"")));return r===void 0?void 0:{arity:r.arity,declared:r,loose:!0}}export{Z as coerceLooseCommandOptionsWithFlagDefinitions,Pe as collectExtensionFlagDefinitionsForCommand,He as collectLooseCommandOptionKeysForDefinitions,Ye as collectLoosePositionalArgs,en as normalizeDirectExtensionCommandOptions,rn as orderArgvRepeatableSwitchOccurrences,Xe as parseLooseCommandOptions,tn as refuseConflictingArgvOptionSpellings,Qe as resolveExtensionFlagOptionKey,K as resolveLooseOptionCoercionKind,nn as resolveNegatedDeclaredBooleanOption,Ze as stripLooseCommandOptionTokens,Je as validateLooseCommandOptionsWithFlagDefinitions};
2
2
  //# sourceMappingURL=command-options.js.map
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The native action a CLI path names (`package catalog` is `package-catalog`),
3
+ * else the path itself. The `packages` root is Commander's alias of `package`,
4
+ * so it classifies as the action the runtime dispatches.
5
+ */
6
+ export declare function resolveExpectHashAction(path:string):string;
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;
@@ -0,0 +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};
2
+ //# sourceMappingURL=expect-hash-admission.js.map
@@ -1,4 +1,6 @@
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";export type{ItemRevisionRecoveryInvocation,ItemRevisionScope}from "../../core/store/item-mutation-precondition.js";
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
+ /** 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";
2
4
  /** Refusal code for a locked write that found a revision other than the declared one. */
3
5
  export declare const ITEM_REVISION_CONFLICT_CODE="item_revision_conflict";
4
6
  /** Most recent history entries a conflict refusal describes. */
@@ -141,6 +143,7 @@ export declare function itemRevisionUncheckedWarning(id:string):string;
141
143
  * Refuse an expected revision on a native action that never writes items.
142
144
  * Extension and package actions stay admitted because only their handlers
143
145
  * know whether they write; the receipt reports any expectation they never reach.
146
+ * Per-command discovery reads the same predicate (pm-6vk110).
144
147
  */
145
148
  export declare function assertExpectHashAdmissible(path:string,options?:Record<string,unknown>):void;
146
149
  /** Refusal for a revision guard on a command or action that writes no items. */
@@ -1,2 +1,2 @@
1
- import{getActiveExtensionRegistrations as T}from"../../core/extensions/index.js";import{URL_CREDENTIAL_PLACEHOLDER as b,redactUrlCredentialsInToken as N}from"../../core/shared/url-credentials.js";import{hashDocument as O}from"../../core/history/history.js";import{readHistoryEntries as k}from"../../core/history/read.js";import{resolveItemTypeRegistry as H}from"../../core/item/type-registry.js";import{bindItemRevisionScope as f,createItemRevisionScope as _,ITEM_REVISION_CONFLICT_CHANGED_REASON as L,ITEM_REVISION_CONFLICT_UNREADABLE_REASON as M,isItemRevisionRefusalFrom as P,isItemRevisionRefusalScoped as U,itemRevisionConflictGuidance as F,markItemRevisionRefusalScoped as $,retainItemRevisionRefusalTracker as x,itemRevisionScopeReceipt as g,runWithItemRevisionScope as v,activeItemRevisionExpectations as D}from"../../core/store/item-mutation-precondition.js";import{buildItemNotFoundError as q,locateItem as G,readLocatedItem as V}from"../../core/store/item-store.js";import{getHistoryPath as W,resolvePmRoot as j}from"../../core/store/paths.js";import{readSettings as z}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{PM_EXPECT_HASH_ACTIONS as B,PM_TOOL_ACTIONS as J}from"../cli-contracts/enum-contracts.js";import{resolveHistorySubject as K}from"../history/subject.js";import{resolvePhysicalItemId as X}from"../query/declared-blockers.js";import{EMPTY_CANONICAL_DOCUMENT as Y}from"../../core/shared/constants.js";import{isMutationAction as Q}from"../mutation-guard.js";import{isPmCliExpectedError as Z}from"../errors.js";const w="item_revision_conflict",ee=10,I=/^[0-9a-f]{64}$/u;function p(e,n){return new d(`Invalid expected revision ${JSON.stringify(e)}: ${n}.`,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 n=typeof e=="string"?e.trim().toLowerCase():"";if(!I.test(n))throw p(String(e),"the revision is not a 64-character hexadecimal item_hash");return n}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 i=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(i.length===0)throw p(t,"the value is empty");const r=o=>N(t)===t?o:b;return i.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,n){const t=await z(e),i=H(t,T()).type_to_folder,r=await G(e,n,t.id_prefix,t.item_format,i);if(r){const{document:o}=await V(r,{schema:t.schema});if(o.metadata.id!==await X(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 K(e,n,t,i)).id,document:Y}}catch{throw await q(e,n,t.id_prefix,i)}}function l(e){return j(e.cwd??process.cwd(),e.pmRoot)}async function Te(e,n={}){const t=await y(l(n),e);return{id:t.id,item_hash:O(t.document)}}async function E(e,n,t){const i=[];for(const r of n){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>"]});i.push({id:(await y(e,o)).id,itemHash:r.itemHash})}return i}function ie(e){return[...new Set(e.patch.map(n=>{const t=n.path.split("/");return String(t[1]==="metadata"?t[2]:t[1])}))].sort()}async function ne(e,n,t){let i;try{i=await k(W(e,n),n)}catch{return}let r=-1;for(let s=i.length-1;s>=0;s-=1){const a=i[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=i.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,n){if(!u(e))return{};const t=await C(e,n);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 Z(e)&&e.context.code===w}function Ne(e){const n=e.find(t=>u(t));if(n!==void 0)throw n}function Oe(){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,n){if(n===void 0||!u(e)||typeof e.context.item_id!="string"||U(e))return e;const t=e.context.reason===M;if(!t&&e.context.reason!==L)return e;const i=$(x(e,new d(e.message,e.exitCode,{...e.context,...F(e.context.item_id,t,n)})));return i.stack=e.stack,i}async function C(e,n,t){if(!P(e,n))return e;const i=oe(e,t);if(!u(i)||i.context.details!==void 0)return i;const r=i.context.item_id,o=i.context.expected_revision;if(typeof r!="string"||typeof o!="string")return i;let c;try{c=await ne(n,r,o)}catch{return i}if(c===void 0)return i;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=x(i,new d(i.message,i.exitCode,{...i.context,details:s}));return a.stack=i.stack,a}async function S(e,n,t){try{return{result:await v(e,n),...g(e)}}catch(i){throw e.pmRoot===void 0?i:await C(i,e.pmRoot,t)}}function re(e){return e.cwd===void 0&&e.pmRoot===void 0?void 0:{scopeArgs:["--pm-path",l(e)]}}async function ke(e,n,t={}){return S(await se(e,t),n,re(t))}async function se(e,n={}){const t=l(n),i=e.map(({id:o,itemHash:c})=>({id:o,itemHash:R(c)})),r=_();return f(r,t,await E(t,i)),r}function He(e){const n=D(e);return n===void 0||n.length>0}function ce(e){return`expect_hash_unchecked:${e}:no_locked_write_reached_this_item`}const A=new Set(J);function ae(e,n={}){const t=e.trim().replace(/\s+/gu,"-"),i=A.has(t)?t:e;if(A.has(i)&&(!Q(i)||i==="deps")&&!B.has(i))throw de(i);if((i==="test"||i==="test-all")&&n.background===!0)throw new d(`--expect-hash cannot guard ${i} --background: the worker runs in another process.`,m.USAGE,{code:"expect_hash_background_unsupported",required:`Run ${i} in the foreground to guard its result recording, or drop --expect-hash for a background run.`})}function de(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 he(e,n){if(n.length===0||typeof e!="object"||e===null||Array.isArray(e))return e;const t=e,i=Array.isArray(t.warnings)?t.warnings:[];return{...t,warnings:[...i,...n.map(ce)]}}async function Le(e){const n=e.expectHash;if(n!==void 0&&typeof n!="string"&&!(Array.isArray(n)&&n.every(o=>typeof o=="string")))throw p(JSON.stringify(n)??String(n),"expected a string or an array of strings");const t=te(n);if(t.length===0)return e.run();ae(e.action,{background:e.background===!0||e.options?.background===!0});const i=_();f(i,e.pmRoot,await E(e.pmRoot,t,e.defaultId));const r=await S(i,e.run,e.invocation);return he(r.result,r.unchecked)}export{ee as ITEM_REVISION_CONFLICT_CHANGE_LIMIT,w as ITEM_REVISION_CONFLICT_CODE,ae as assertExpectHashAdmissible,se as bindExpectedItemRevisions,f as bindItemRevisionScope,_ as createItemRevisionScope,ne as describeItemRevisionChanges,Le as dispatchWithExpectedItemRevisions,C as enrichItemRevisionConflict,Oe as expectHashInvocationRewrittenError,de as expectHashRequiresMutationError,u as isItemRevisionConflict,He as isTrackerRevisionGuarded,be as itemRevisionConflictRowFields,g as itemRevisionScopeReceipt,ce as itemRevisionUncheckedWarning,R as normalizeExpectedItemHash,te as parseExpectHashSpecs,Te as readItemRevision,E as resolveExpectedItemRevisions,S as runWithBoundItemRevisionScope,v as runWithItemRevisionScope,oe as scopeItemRevisionConflict,Ne as throwFirstItemRevisionConflict,ke as withExpectedItemRevisions};
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};
2
2
  //# sourceMappingURL=item-revision.js.map
@@ -1,2 +1,2 @@
1
- import{SECRET_RULES as _,acceptsStructuredValue as k,findSecretRuleMatches as N,structuredKeyShape as z}from"../core/shared/secret-rules.js";import{EXIT_CODE as w}from"../core/shared/constants.js";import{PmCliError as O}from"../core/shared/errors.js";const P=!0,D=[{action:"append",history_scope:"item"},{action:"claim",history_scope:"item"},{action:"close",history_scope:"item"},{action:"close-many",history_scope:"item"},{action:"close-task",history_scope:"item"},{action:"comments",history_scope:"conditional"},{action:"config",history_scope:"conditional"},{action:"copy",history_scope:"item"},{action:"create",history_scope:"item"},{action:"delete",history_scope:"item"},{action:"deps",history_scope:"conditional"},{action:"discover",history_scope:"item"},{action:"docs",history_scope:"conditional"},{action:"files",history_scope:"conditional"},{action:"focus",history_scope:"conditional"},{action:"gc",history_scope:"conditional"},{action:"history-compact",history_scope:"history"},{action:"history-author-acknowledge",history_scope:"workspace"},{action:"history-redact",history_scope:"history"},{action:"history-repair",history_scope:"history"},{action:"init",history_scope:"workspace"},{action:"install",history_scope:"conditional"},{action:"learnings",history_scope:"conditional"},{action:"notes",history_scope:"conditional"},{action:"package",history_scope:"conditional"},{action:"pause-task",history_scope:"item"},{action:"plan",history_scope:"conditional"},{action:"profile",history_scope:"conditional"},{action:"release",history_scope:"item"},{action:"restore",history_scope:"item"},{action:"schema",history_scope:"conditional"},{action:"start-task",history_scope:"item"},{action:"templates",history_scope:"conditional"},{action:"test",history_scope:"conditional"},{action:"test-all",history_scope:"conditional"},{action:"update",history_scope:"item"},{action:"update-many",history_scope:"item"},{action:"upgrade",history_scope:"conditional"}],y=new Map(D.map(e=>[e.action,e])),U=/^(?:0|[1-9]\d*)$/u,I=2**32-2;function L(e){return U.test(e)&&Number(e)<=I}function E(e){const t=[];for(const n of _){const o=G(n,e);o&&t.push({rule:n,match:o})}return t}function Y(e,t){let n=t.names.get(e);return n===void 0&&(n=E(e),t.names.set(e,n)),n}function b(e,t){let n=t.entries.get(e);return n===void 0&&(n=Array.isArray(e)?Object.getOwnPropertyNames(e).filter(L).map(o=>({name:o,value:e[Number(o)],segment:`[${o}]`,nameMatches:[]})):Object.entries(e).map(([o,r],s)=>{const i=Y(o,t);return{name:o,value:r,segment:i.length>0?`[key ${s}]`:`.${o}`,nameMatches:i}}),t.entries.set(e,n)),n}function R({rule:e,match:t},n,o){const r={rule:e.mutationRule,path:n};return o&&(r.property_name=!0),t.normalizations&&(r.normalizations=t.normalizations),t.normalization_incomplete&&(r.normalization_incomplete=!0),r}function A(e,t){for(let n=t.length-1;n>=0;n-=1)e.push(t[n])}function G(e,t){try{return K(e,t)}catch(n){return S(n)}}function S(e){if(!(e instanceof RangeError))throw e;return{index:0,normalization_incomplete:!0}}function K(e,t){const n=N(e,t),o=n.next().value;if(!o||e.mutationRule!=="absolute_home_path"||o.normalization_incomplete)return o;for(const r of n)if(r.normalization_incomplete)return{...o,normalizations:[...new Set([o.normalizations,r.normalizations].flatMap(s=>s??[]))],normalization_incomplete:!0};return o}function q(e,t){const n=[],o=new WeakSet,r=[{value:e,path:"$"}];for(let s=r.pop();s!==void 0;s=r.pop()){const{value:i,path:c}=s;if(typeof i=="string")for(const u of E(i))n.push(R(u,c,!1));else if(typeof i=="object"&&i!==null&&!o.has(i)){o.add(i);const u=b(i,t);for(const a of u)for(const l of a.nameMatches)n.push(R(l,`${c}${a.segment}`,!0));A(r,u.map(a=>({value:a.value,path:`${c}${a.segment}`})))}}return n}const f=_.filter(e=>"structured"in e),F=f.map(()=>({named:!1,exact:!1})),T=/(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/gu,X=3;function M(e){return e.replace(T,"_")}function W(e){const n=[...e.matchAll(T)].map(o=>o.index).slice(-X).map(o=>`${M(e.slice(0,o))}_${e.slice(o)}`);return[...new Set([e,M(e),...n])]}function B(e){const t=W(e);return f.map(n=>{const o=t.map(r=>z(n,r));return o.includes("exact")?"exact":o.includes("prefixed")?"prefixed":void 0})}const H=f.map(()=>{});function Z(e,t,n,o){const r=b(e,o);if(Array.isArray(e)){const s=n.map(({named:i,exact:c})=>c?"lenient":i?"compact":void 0);return r.map(i=>({value:i.value,path:`${t}${i.segment}`,contexts:n,judgments:s}))}return r.map(({name:s,value:i,segment:c})=>{const u=B(s);return{value:i,path:`${t}${c}`,contexts:n.map(({named:a,exact:l},p)=>({named:a||u[p]!==void 0,exact:l||u[p]==="exact"})),judgments:u.map((a,l)=>a==="exact"?"lenient":a==="prefixed"||n[l].named?"compact":void 0)}})}function J(e,t){const n=[],o=new WeakMap,r=[{value:e,path:"$",contexts:F,judgments:H}];for(let s=r.pop();s!==void 0;s=r.pop()){const{value:i,path:c,contexts:u,judgments:a}=s;if(typeof i=="string"){a.forEach((d,h)=>{const m=f[h];if(d===void 0)return;let g;try{g=k(m,i,d==="compact")}catch($){S($),n.push({rule:m.mutationRule,path:c,normalization_incomplete:!0});return}g&&n.push({rule:m.mutationRule,path:c})});continue}if(typeof i!="object"||i===null)continue;const l=u.map(({named:d,exact:h})=>h?"e":d?"n":"-").join(""),p=o.get(i)??new Set;p.has(l)||(o.set(i,p.add(l)),A(r,Z(i,c,u,t)))}return n}function V(e){const t=new Set,n={entries:new WeakMap,names:new Map};return[...q(e,n),...J(e,n)].filter(o=>{const r=`${o.rule}\0${o.path}\0${o.property_name===!0}`;return t.has(r)?!1:(t.add(r),!0)})}function ie(e){const t=e.author.trim()||"unknown";if(e.settings.require_attributed_author&&t.toLowerCase()==="unknown")throw new O("Mutation author is required by workspace policy.",w.USAGE,{code:"mutation_author_required",required:"Pass --author <id>, set PM_AUTHOR, or configure author_default.",nextSteps:["Retry with --author <stable-agent-id>.","Set PM_AUTHOR for this agent session."]});if(e.settings.secret_guard==="off")return{author:t,findings:[],warnings:[],override_applied:!1};let n;try{n=V(e.payload)}catch{return{author:t,findings:[],warnings:["secret_guard_scan_failed_open"],override_applied:!1}}if(n.length===0)return{author:t,findings:n,warnings:[],override_applied:!1};const o=[...new Set(n.map(r=>r.rule))].sort().join(",");if(e.settings.secret_guard==="block"&&e.force!==!0)throw new O(`Mutation blocked by secret guard (${o}). No detected value was logged.`,w.CONFLICT,{code:"mutation_secret_guard_blocked",required:"Remove the credential-shaped content or retry with --force after explicit review.",nextSteps:["Replace the value with a secret-manager reference.","Use pm history-redact if equivalent content already entered history."],recovery:{recovery_mode:"compact",attempted_command:"pm <mutation> [REDACTED]",normalized_args:["[REDACTED]"],suggested_retry:"Remove credential-shaped content, then retry the mutation."}});return{author:t,findings:n,warnings:[`secret_guard_detected:${n.length}:rules=${o}`,...e.settings.secret_guard==="block"&&e.force===!0?["secret_guard_force_override"]:[]],override_applied:e.settings.secret_guard==="block"&&e.force===!0}}const v=Object.freeze(Object.fromEntries(_.map(e=>[e.mutationRule,e.category])));function Q(e){return Object.hasOwn(v,e)?v[e]:void 0}function j(e,t){return e!==void 0&&t!==void 0&&Object.hasOwn(e,t)?e[t]:void 0}const C=new Set(Reflect.ownKeys(Object.prototype));function ee(e){const t=Reflect.ownKeys(e);if(t.length!==C.size||!t.every(o=>C.has(o)))return!1;const n=Object.getOwnPropertyDescriptor(e,"constructor")?.value;return typeof n=="function"&&Object.getOwnPropertyDescriptor(n,"prototype")?.value===e}function te(e){const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype?!0:Object.getPrototypeOf(t)!==null?!1:Reflect.ownKeys(t).length===0||ee(t)}function x(e,t){const n=Object.hasOwn(e,t)?e[t]:void 0;if(n!==void 0&&(typeof n!="object"||n===null||!te(n)))throw new TypeError(`Secret guard policy ${t} must be an object keyed by ${t==="rules"?"rule":"category"}.`);return n}function se(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("Secret guard policy must be an object with a default decision.");const n=Object.hasOwn(e,"default")?e.default:void 0;if(n===void 0)throw new TypeError("Secret guard policy requires a default decision.");const o=x(e,"categories"),r=x(e,"rules"),s=typeof t=="object"&&t!==null?t.rule:void 0;if(typeof s!="string")throw new TypeError("Secret guard finding must have a string rule.");const i=j(r,s);if(i!==void 0)return i;const c=j(o,Q(s));return c===void 0?n:c}function ce(e){return y.has(e.trim().toLowerCase())}function ae(){return[...y.keys()].sort((e,t)=>e.localeCompare(t))}function ue(e){return y.get(e.trim().toLowerCase())}export{D as PM_MUTATION_ACTION_CONTRACTS,v as SECRET_GUARD_RULE_CATEGORIES,se as decideSecretGuardFinding,ie as evaluateMutationGuard,ue as getMutationActionContract,ce as isMutationAction,ae as listMutationActions,V as scanMutationSecrets,Q as secretGuardRuleCategory};
1
+ import{SECRET_RULES as g,acceptsStructuredValue as D,createSecretDecodedText as P,findSecretRuleMatches as I,isNumericMetadataKey as U,structuredKeyShape as L}from"../core/shared/secret-rules.js";import{EXIT_CODE as b}from"../core/shared/constants.js";import{PmCliError as E}from"../core/shared/errors.js";const K=!0,Y=[{action:"append",history_scope:"item"},{action:"claim",history_scope:"item"},{action:"close",history_scope:"item"},{action:"close-many",history_scope:"item"},{action:"close-task",history_scope:"item"},{action:"comments",history_scope:"conditional"},{action:"config",history_scope:"conditional"},{action:"copy",history_scope:"item"},{action:"create",history_scope:"item"},{action:"delete",history_scope:"item"},{action:"deps",history_scope:"conditional"},{action:"discover",history_scope:"item"},{action:"docs",history_scope:"conditional"},{action:"files",history_scope:"conditional"},{action:"focus",history_scope:"conditional"},{action:"gc",history_scope:"conditional"},{action:"history-compact",history_scope:"history"},{action:"history-author-acknowledge",history_scope:"workspace"},{action:"history-redact",history_scope:"history"},{action:"history-repair",history_scope:"history"},{action:"init",history_scope:"workspace"},{action:"install",history_scope:"conditional"},{action:"learnings",history_scope:"conditional"},{action:"notes",history_scope:"conditional"},{action:"package",history_scope:"conditional"},{action:"pause-task",history_scope:"item"},{action:"plan",history_scope:"conditional"},{action:"profile",history_scope:"conditional"},{action:"release",history_scope:"item"},{action:"restore",history_scope:"item"},{action:"schema",history_scope:"conditional"},{action:"start-task",history_scope:"item"},{action:"templates",history_scope:"conditional"},{action:"test",history_scope:"conditional"},{action:"test-all",history_scope:"conditional"},{action:"update",history_scope:"item"},{action:"update-many",history_scope:"item"},{action:"upgrade",history_scope:"conditional"}],w=new Map(Y.map(e=>[e.action,e])),G=/^(?:0|[1-9]\d*)$/u,q=2**32-2;function F(e){return G.test(e)&&Number(e)<=q}function S(e){const t=[],n=P(e);for(const o of g){const r=W(o,e,n);r&&t.push({rule:o,match:r})}return t}function X(e,t){let n=t.names.get(e);return n===void 0&&(n=S(e),t.names.set(e,n)),n}function A(e,t){let n=t.entries.get(e);return n===void 0&&(n=Array.isArray(e)?Object.getOwnPropertyNames(e).filter(F).map((o,r)=>({name:o,value:e[Number(o)],segment:`[${o}]`,nameMatches:[],position:r})):Object.entries(e).map(([o,r],s)=>{const i=X(o,t);return{name:o,value:r,segment:i.length>0?`[key ${s}]`:`.${o}`,nameMatches:i,position:s}}),t.entries.set(e,n)),n}function R({rule:e,match:t},n,o){const r={rule:e.mutationRule,path:n};return o&&(r.property_name=!0),t.normalizations&&(r.normalizations=t.normalizations),t.normalization_incomplete&&(r.normalization_incomplete=!0),r}function T(e,t){for(let n=t.length-1;n>=0;n-=1)e.push(t[n])}function W(e,t,n){try{return B(e,t,n)}catch(o){return M(o)}}function M(e){if(!(e instanceof RangeError))throw e;return{index:0,normalization_incomplete:!0}}function B(e,t,n){const o=I(e,t,{decodeStrings:!0,decoded:n}),r=o.next().value;if(!r||r.normalization_incomplete)return r;for(const s of o)if(s.normalization_incomplete)return{...r,normalizations:[...new Set([r.normalizations,s.normalizations].flatMap(i=>i??[]))],normalization_incomplete:!0};return r}function H(e,t){const n=[],o=new WeakSet,r=[{value:e,path:"$",identity:C}];for(let s=r.pop();s!==void 0;s=r.pop()){const{value:i,path:c,identity:u}=s;if(typeof i=="string")for(const l of S(i))n.push({finding:R(l,c,!1),identity:u});else if(typeof i=="object"&&i!==null&&!o.has(i)){o.add(i);const l=A(i,t);for(const a of l)for(const d of a.nameMatches)n.push({finding:R(d,`${c}${a.segment}`,!0),identity:m(t,u,a)});T(r,l.map(a=>({value:a.value,path:`${c}${a.segment}`,identity:m(t,u,a)})))}}return n}const C=0;function m(e,t,n){const o=`${t}:${n.position}`;let r=e.locations.get(o);return r===void 0&&(r=e.locations.size+1,e.locations.set(o,r)),r}const h=g.filter(e=>"structured"in e),J=h.map(()=>({named:!1,exact:!1})),j=/(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/gu,Z=3;function v(e){return e.replace(j,"_")}function V(e){const n=[...e.matchAll(j)].map(o=>o.index).slice(-Z).map(o=>`${v(e.slice(0,o))}_${e.slice(o)}`);return[...new Set([e,v(e),...n])]}function Q(e){const t=V(e);return h.map(n=>{const o=t.map(r=>L(n,r));return o.includes("exact")?"exact":o.includes("prefixed")?"prefixed":void 0})}const ee=h.map(()=>{});function te(e,{path:t,identity:n,contexts:o},r){const s=A(e,r);if(Array.isArray(e)){const i=o.map(({named:c,exact:u})=>u?"lenient":c?"compact":void 0);return s.map(c=>({value:c.value,path:`${t}${c.segment}`,identity:m(r,n,c),contexts:o,judgments:i,bound:!1}))}return s.map(i=>{const{name:c,value:u,segment:l}=i,a=Q(c);return{value:u,path:`${t}${l}`,identity:m(r,n,i),bound:U(c),contexts:o.map(({named:d,exact:f},p)=>({named:d||a[p]!==void 0,exact:f||a[p]==="exact"})),judgments:a.map((d,f)=>d==="exact"?"lenient":d==="prefixed"||o[f].named?"compact":void 0)}})}function ne(e){return typeof e=="string"||typeof e=="number"||typeof e=="bigint"}function oe(e,t){const n=[],o=new WeakMap,r=[{value:e,path:"$",identity:C,contexts:J,judgments:ee,bound:!1}];for(let s=r.pop();s!==void 0;s=r.pop()){const{value:i,path:c,identity:u,contexts:l,judgments:a}=s;if(ne(i)){if(s.bound&&typeof i!="string")continue;a.forEach((p,y)=>{const _=h[y];if(p===void 0)return;let O;try{O=D(_,i,p==="compact")}catch(z){M(z),n.push({finding:{rule:_.mutationRule,path:c,normalization_incomplete:!0},identity:u});return}O&&n.push({finding:{rule:_.mutationRule,path:c},identity:u})});continue}if(typeof i!="object"||i===null)continue;const d=l.map(({named:p,exact:y})=>y?"e":p?"n":"-").join(""),f=o.get(i)??new Set;f.has(d)||(o.set(i,f.add(d)),T(r,te(i,s,t)))}return n}function re(e){const t=new Map,n={entries:new WeakMap,names:new Map,locations:new Map},o=[];for(const{finding:r,identity:s}of[...H(e,n),...oe(e,n)]){const i=`${r.rule}\0${s}\0${r.property_name===!0}`,c=t.get(i);c===void 0?(t.set(i,r),o.push(r)):r.normalization_incomplete&&(c.normalization_incomplete=!0)}return o}function le(e){const t=e.author.trim()||"unknown";if(e.settings.require_attributed_author&&t.toLowerCase()==="unknown")throw new E("Mutation author is required by workspace policy.",b.USAGE,{code:"mutation_author_required",required:"Pass --author <id>, set PM_AUTHOR, or configure author_default.",nextSteps:["Retry with --author <stable-agent-id>.","Set PM_AUTHOR for this agent session."]});if(e.settings.secret_guard==="off")return{author:t,findings:[],warnings:[],override_applied:!1};let n;try{n=re(e.payload)}catch{return{author:t,findings:[],warnings:["secret_guard_scan_failed_open"],override_applied:!1}}if(n.length===0)return{author:t,findings:n,warnings:[],override_applied:!1};const o=[...new Set(n.map(r=>r.rule))].sort().join(",");if(e.settings.secret_guard==="block"&&e.force!==!0)throw new E(`Mutation blocked by secret guard (${o}). No detected value was logged.`,b.CONFLICT,{code:"mutation_secret_guard_blocked",required:"Remove the credential-shaped content or retry with --force after explicit review.",nextSteps:["Replace the value with a secret-manager reference.","Use pm history-redact if equivalent content already entered history."],recovery:{recovery_mode:"compact",attempted_command:"pm <mutation> [REDACTED]",normalized_args:["[REDACTED]"],suggested_retry:"Remove credential-shaped content, then retry the mutation."}});return{author:t,findings:n,warnings:[`secret_guard_detected:${n.length}:rules=${o}`,...e.settings.secret_guard==="block"&&e.force===!0?["secret_guard_force_override"]:[]],override_applied:e.settings.secret_guard==="block"&&e.force===!0}}const x=Object.freeze(Object.fromEntries(g.map(e=>[e.mutationRule,e.category])));function ie(e){return Object.hasOwn(x,e)?x[e]:void 0}function $(e,t){return e!==void 0&&t!==void 0&&Object.hasOwn(e,t)?e[t]:void 0}const k=new Set(Reflect.ownKeys(Object.prototype));function se(e){const t=Reflect.ownKeys(e);if(t.length!==k.size||!t.every(o=>k.has(o)))return!1;const n=Object.getOwnPropertyDescriptor(e,"constructor")?.value;return typeof n=="function"&&Object.getOwnPropertyDescriptor(n,"prototype")?.value===e}function ce(e){const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype?!0:Object.getPrototypeOf(t)!==null?!1:Reflect.ownKeys(t).length===0||se(t)}function N(e,t){const n=Object.hasOwn(e,t)?e[t]:void 0;if(n!==void 0&&(typeof n!="object"||n===null||!ce(n)))throw new TypeError(`Secret guard policy ${t} must be an object keyed by ${t==="rules"?"rule":"category"}.`);return n}function pe(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("Secret guard policy must be an object with a default decision.");const n=Object.hasOwn(e,"default")?e.default:void 0;if(n===void 0)throw new TypeError("Secret guard policy requires a default decision.");const o=N(e,"categories"),r=N(e,"rules"),s=typeof t=="object"&&t!==null?t.rule:void 0;if(typeof s!="string")throw new TypeError("Secret guard finding must have a string rule.");const i=$(r,s);if(i!==void 0)return i;const c=$(o,ie(s));return c===void 0?n:c}function fe(e){return w.has(e.trim().toLowerCase())}function me(){return[...w.keys()].sort((e,t)=>e.localeCompare(t))}function he(e){return w.get(e.trim().toLowerCase())}export{Y as PM_MUTATION_ACTION_CONTRACTS,x as SECRET_GUARD_RULE_CATEGORIES,pe as decideSecretGuardFinding,le as evaluateMutationGuard,he as getMutationActionContract,fe as isMutationAction,me as listMutationActions,re as scanMutationSecrets,ie as secretGuardRuleCategory};
2
2
  //# sourceMappingURL=mutation-guard.js.map
@@ -1,2 +1,2 @@
1
- import{resolvePmHistoryOperation as s}from"./cli-contracts/command-aliases.js";import{PM_CORE_COMMAND_NAMES as i}from"./cli-contracts/enum-contracts.js";const c=["mutation_receipt","entity","collection","diagnostic","stream"],d=new Set(["append","claim","close","close-task","copy","create","delete","focus","pause-task","release","restore","start-task","update"]),p=new Set(["close-many","update-many"]),m=new Set(["activity","comments","contracts","events","history","learnings","list","notes","search"]),l=new Set(["aggregate","deps","graph","health","history-redact","history-repair","history-compact","stats","validate"]);function o(e){if(e.command.trim().length===0)throw new TypeError("command must be a non-empty command path");if(!c.includes(e.kind))throw new TypeError(`Unsupported output envelope kind: ${e.kind}`);return e}function a(e){const t=e.trim().replace(/\s+/gu," "),[n=t]=t.split(" ");return p.has(n)?o({command:t,kind:"collection",wrapper_key:"rows",cardinality:"many",format_flag:"--json"}):d.has(n)?o({command:t,kind:"mutation_receipt",wrapper_key:null,cardinality:"one",format_flag:"--json"}):m.has(n)?o({command:t,kind:"collection",wrapper_key:n==="contracts"?null:"items",cardinality:"many",format_flag:"--json"}):l.has(n)?o({command:t,kind:"diagnostic",wrapper_key:null,cardinality:"none",format_flag:"--json"}):o({command:t,kind:n==="get"?"entity":"diagnostic",wrapper_key:n==="get"?"item":null,cardinality:n==="get"?"one":"none",format_flag:"--json"})}const u=i.map(e=>a(e)),f=new Map(u.map(e=>[e.command,e]));function O(e){const t=e.trim().replace(/\s+/gu," ");if(t.length===0)throw new TypeError("command must be a non-empty command path");const[n=t]=s(t).split(" "),r=f.get(n);return r?{...r,command:t}:a(t)}function y(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _(e){return y(e)&&typeof e.id=="string"&&e.id.length>0&&typeof e.status=="string"&&e.status.length>0&&Number.isSafeInteger(e.changed_field_count)&&Number(e.changed_field_count)>=0&&(e.close_reason===void 0||typeof e.close_reason=="string")&&(e.deleted===void 0||typeof e.deleted=="boolean")&&(e.previous_status===void 0||typeof e.previous_status=="string")&&(e.warnings===void 0||Array.isArray(e.warnings))}function w(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(n){throw new TypeError(`Mutation receipt must be valid JSON: ${String(n)}`,{cause:n})}if(!_(t))throw new TypeError("Mutation receipt must be a flat object with top-level id, status, and changed_field_count fields");return{id:t.id,status:t.status,changedFieldCount:t.changed_field_count,...typeof t.close_reason=="string"?{closeReason:t.close_reason}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.previous_status=="string"?{previousStatus:t.previous_status}:{},...Array.isArray(t.warnings)?{warnings:t.warnings}:{}}}export{u as PM_COMMAND_OUTPUT_ENVELOPE_CONTRACTS,c as PM_OUTPUT_ENVELOPE_KINDS,o as definePmCommandOutputEnvelope,_ as isPmMutationReceipt,w as parseMutationReceipt,O as resolvePmCommandOutputEnvelope};
1
+ import{resolvePmHistoryOperation as c}from"./cli-contracts/command-aliases.js";import{PM_CORE_COMMAND_NAMES as d}from"./cli-contracts/enum-contracts.js";const m=["mutation_receipt","entity","collection","diagnostic","stream"],p=new Set(["append","claim","close","close-task","copy","create","delete","focus","pause-task","release","restore","start-task","update"]),l=new Set(["close-many","update-many"]),u=new Set(["activity","comments","contracts","events","history","learnings","list","notes","search"]),f=new Set(["aggregate","deps","graph","health","history-redact","history-repair","history-compact","stats","validate"]);function o(e){if(e.command.trim().length===0)throw new TypeError("command must be a non-empty command path");if(!m.includes(e.kind))throw new TypeError(`Unsupported output envelope kind: ${e.kind}`);return e}function i(e){const t=e.trim().replace(/\s+/gu," "),[n=t]=t.split(" ");return l.has(n)?o({command:t,kind:"collection",wrapper_key:"rows",cardinality:"many",format_flag:"--json"}):p.has(n)?o({command:t,kind:"mutation_receipt",wrapper_key:null,cardinality:"one",format_flag:"--json"}):u.has(n)?o({command:t,kind:"collection",wrapper_key:n==="contracts"?null:"items",cardinality:"many",format_flag:"--json"}):f.has(n)?o({command:t,kind:"diagnostic",wrapper_key:null,cardinality:"none",format_flag:"--json"}):o({command:t,kind:n==="get"?"entity":"diagnostic",wrapper_key:n==="get"?"item":null,cardinality:n==="get"?"one":"none",format_flag:"--json"})}const y=d.map(e=>i(e)),_=new Map(y.map(e=>[e.command,e])),g=new Map([["files lookup",o({command:"files lookup",kind:"collection",wrapper_key:"matches",cardinality:"many",format_flag:"--json"})]]);function E(e){const t=e.trim().replace(/\s+/gu," ");if(t.length===0)throw new TypeError("command must be a non-empty command path");const n=c(t),r=g.get(n);if(r!==void 0)return{...r,command:t};const[s=t]=n.split(" "),a=_.get(s);return a?{...a,command:t}:i(t)}function h(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function O(e){return h(e)&&typeof e.id=="string"&&e.id.length>0&&typeof e.status=="string"&&e.status.length>0&&Number.isSafeInteger(e.changed_field_count)&&Number(e.changed_field_count)>=0&&(e.close_reason===void 0||typeof e.close_reason=="string")&&(e.deleted===void 0||typeof e.deleted=="boolean")&&(e.previous_status===void 0||typeof e.previous_status=="string")&&(e.warnings===void 0||Array.isArray(e.warnings))}function N(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(n){throw new TypeError(`Mutation receipt must be valid JSON: ${String(n)}`,{cause:n})}if(!O(t))throw new TypeError("Mutation receipt must be a flat object with top-level id, status, and changed_field_count fields");return{id:t.id,status:t.status,changedFieldCount:t.changed_field_count,...typeof t.close_reason=="string"?{closeReason:t.close_reason}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.previous_status=="string"?{previousStatus:t.previous_status}:{},...Array.isArray(t.warnings)?{warnings:t.warnings}:{}}}export{y as PM_COMMAND_OUTPUT_ENVELOPE_CONTRACTS,m as PM_OUTPUT_ENVELOPE_KINDS,o as definePmCommandOutputEnvelope,O as isPmMutationReceipt,N as parseMutationReceipt,E as resolvePmCommandOutputEnvelope};
2
2
  //# sourceMappingURL=output-contracts.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"];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";};};
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 w}from"../core/shared/constants.js";import{PmCliError as g}from"../core/shared/errors.js";const _=new WeakMap;function U(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',k={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"],fields:"unsupported"},docs:{row_keys:["docs"],fields:"unsupported"},validate:{row_keys:["checks","warnings"],fields:"unsupported"},contracts:{row_keys:["command_summaries","commands"],fields:"unsupported"}},O=[{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 W(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 F(e,t){const n=O.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 c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const R=new Set([void 0,"tabular_when_uniform"]),j=new Set(["collection","none"]),E=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 A(e){return c(e)&&typeof e.command=="string"&&e.command.trim().length>0&&j.has(e.row_kind)&&u(e.row_keys,!0)&&(e.continuation_row_keys===void 0||u(e.continuation_row_keys,!1))&&E.has(e.fields)&&R.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 S={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"]},v={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"],docs:["docs"],validate:["checks","warnings"],contracts:["command_summaries","commands","selected"]};function C(e,t){const n=e.trim().toLowerCase().split(/\s+/u,1)[0],o=n?.startsWith("list-")?"list":n;if(o==="graph"){const r=typeof t.subcommand=="string"?t.subcommand:"";if(r.length===0)return;const i=S[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=k[o],d=v[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,y)=>c(p)?p[y]: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 x(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 T(e){if(!Array.isArray(e.sections_included))return;const t=a(b,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 D(e,t,n){if(e==="dependency_provenance")return!1;const o=m(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 m(e){const t=e.indexOf(".");return t===-1?void 0:{facet:e.slice(0,t),member:e.slice(t+1)}}function G(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=>m(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})=>D(i,d(i),e)?[i]:[])))}function h(e){if(c(e.projection))return a([{name:"full_item_fields",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_item_fields"]:[]))}function N(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 P(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 I(e,t){const n=x(t);if(n!==void 0)return n;const[o]=e.split(/\s+/u,1);if(o==="context")return T(t);if(o==="get")return G(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 N(t);if(o==="contracts")return P(t)}function K(e,t){if(e===void 0||!c(t))return t;const n=I(e,t),o=t.row_contract,s=A(o)?o:C(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{O as PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS,k as PM_READ_ROW_CONTRACTS,f as PM_READ_ROW_JQ_SELECTOR,W as assertProjectionModeChoice,K as attachOutputOmissionReceipt,a as createOutputOmissionReceipt,A as isReadRowContract,U as registerOutputMaterialFieldGroups,F as resolveModePairedOutputOmissionReceipt,I as resolveOutputOmissionReceipt,C as resolveReadRowContract};
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};
2
2
  //# sourceMappingURL=output-projection.js.map