@unbrained/pm-cli 2026.11.26 → 2026.11.28

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 (185) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli-bundle/bundle-manifest.json +1 -1
  3. package/dist/cli-bundle/chunks/{chunk-BITDGTAX.js → chunk-2YD2AERA.js} +2 -2
  4. package/dist/cli-bundle/chunks/chunk-54AQJTUH.js +3 -0
  5. package/dist/cli-bundle/chunks/chunk-56DKWGHE.js +2 -0
  6. package/dist/cli-bundle/chunks/chunk-56GUDMXN.js +113 -0
  7. package/dist/cli-bundle/chunks/chunk-5ECCMDSU.js +2 -0
  8. package/dist/cli-bundle/chunks/chunk-6RBD2AKU.js +2 -0
  9. package/dist/cli-bundle/chunks/{chunk-PQSEEVOA.js → chunk-C4O5TZY3.js} +46 -46
  10. package/dist/cli-bundle/chunks/chunk-CATRDGAB.js +125 -0
  11. package/dist/cli-bundle/chunks/{chunk-5FY2VHRF.js → chunk-CDUV7DFD.js} +2 -2
  12. package/dist/cli-bundle/chunks/chunk-CTM26LUE.js +4 -0
  13. package/dist/cli-bundle/chunks/chunk-D3I5AHNN.js +2 -0
  14. package/dist/cli-bundle/chunks/chunk-E2LQ6LCJ.js +2 -0
  15. package/dist/cli-bundle/chunks/{chunk-B2GM6KOM.js → chunk-FG4TNQQM.js} +2 -2
  16. package/dist/cli-bundle/chunks/chunk-JQYPSABI.js +2 -0
  17. package/dist/cli-bundle/chunks/chunk-LMDIKSDZ.js +9 -0
  18. package/dist/cli-bundle/chunks/chunk-LRGYV6QQ.js +2 -0
  19. package/dist/cli-bundle/chunks/chunk-MO6PPUI6.js +2 -0
  20. package/dist/cli-bundle/chunks/chunk-O2SWNEBW.js +8 -0
  21. package/dist/cli-bundle/chunks/{chunk-5AAIRHNE.js → chunk-O2WNNIKK.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-LNZKNVMT.js → chunk-OFIYA3PI.js} +3 -3
  23. package/dist/cli-bundle/chunks/{chunk-DYL2N3OC.js → chunk-Q6BGQRCB.js} +2 -2
  24. package/dist/cli-bundle/chunks/chunk-RGE3XW3A.js +2 -0
  25. package/dist/cli-bundle/chunks/chunk-SP6CDM6B.js +31 -0
  26. package/dist/cli-bundle/chunks/{chunk-T3GJPXIZ.js → chunk-T7RZPIOB.js} +14 -14
  27. package/dist/cli-bundle/chunks/{chunk-MNFCJNQA.js → chunk-T7UTG56V.js} +4 -4
  28. package/dist/cli-bundle/chunks/chunk-TWRUA2NH.js +3 -0
  29. package/dist/cli-bundle/chunks/chunk-WKDKBS4P.js +4 -0
  30. package/dist/cli-bundle/chunks/chunk-YEMFOKFG.js +2 -0
  31. package/dist/cli-bundle/chunks/{chunk-ZDL45VTB.js → chunk-YLS2N4SN.js} +2 -2
  32. package/dist/cli-bundle/chunks/{chunk-FWBR3OW7.js → chunk-ZXERHBMA.js} +2 -2
  33. package/dist/cli-bundle/chunks/field-definition-losses-JFMMMVTV.js +2 -0
  34. package/dist/cli-bundle/chunks/field-option-collisions-G4LQ2646.js +2 -0
  35. package/dist/cli-bundle/{focused-chunks/item-revision-RPTXN7WW.js → chunks/item-revision-O7L3AA2W.js} +2 -2
  36. package/dist/cli-bundle/chunks/item-transaction-4XC74ULD.js +2 -0
  37. package/dist/cli-bundle/chunks/mutation-actor-A45DFDEO.js +2 -0
  38. package/dist/cli-bundle/chunks/mutation-admission-SIUIMAEO.js +2 -0
  39. package/dist/cli-bundle/chunks/{register-list-query-EKSCZWEZ.js → register-list-query-FCPGG2UT.js} +2 -2
  40. package/dist/cli-bundle/chunks/{register-mutation-ZIAOKKUJ.js → register-mutation-VD3JX23I.js} +2 -2
  41. package/dist/cli-bundle/chunks/register-operations-KHJD4GFZ.js +2 -0
  42. package/dist/cli-bundle/chunks/register-setup-EWAZZWPL.js +2 -0
  43. package/dist/cli-bundle/chunks/runtime-schema-3RAXYNG5.js +2 -0
  44. package/dist/cli-bundle/chunks/{settlement-hook-ESAAEBRM.js → settlement-hook-KWBOSRDZ.js} +2 -2
  45. package/dist/cli-bundle/chunks/stage-UIDZMTE5.js +2 -0
  46. package/dist/cli-bundle/focused-chunks/chunk-5MZXU6HB.js +2 -0
  47. package/dist/cli-bundle/focused-chunks/chunk-64DSKZJN.js +100 -0
  48. package/dist/cli-bundle/focused-chunks/{chunk-YSZZSV6M.js → chunk-7EKKUYN5.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/chunk-7P6OGPEG.js +2 -0
  50. package/dist/cli-bundle/focused-chunks/chunk-A5B43EWU.js +2 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-AHCOSTL7.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-CQLOYNJY.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/chunk-E4C6T3NL.js +2 -0
  54. package/dist/cli-bundle/focused-chunks/{chunk-3GQRWIT5.js → chunk-HCWDMFWA.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/{chunk-GQBWI4KA.js → chunk-J4V3J5MC.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/chunk-JD45Y2BR.js +91 -0
  57. package/dist/cli-bundle/focused-chunks/chunk-KMGI5GZP.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-MSLRDKWL.js +4 -0
  59. package/dist/cli-bundle/focused-chunks/chunk-O33WUEAF.js +3 -0
  60. package/dist/cli-bundle/focused-chunks/{chunk-QNWNUQSJ.js → chunk-OEMI52ZS.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{chunk-AAB3ZR7Z.js → chunk-Q6JCMFGU.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/chunk-RBOWKXFV.js +8 -0
  63. package/dist/cli-bundle/focused-chunks/chunk-TF57RHS2.js +2 -0
  64. package/dist/cli-bundle/focused-chunks/{chunk-TNVLDU7Z.js → chunk-VNU3IFBL.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/chunk-X5ZVPFK7.js +4 -0
  66. package/dist/cli-bundle/focused-chunks/chunk-XVCMYFQU.js +27 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-RDELKGLS.js → chunk-Y7EC2L2G.js} +3 -3
  68. package/dist/cli-bundle/focused-chunks/{chunk-FQWKESMI.js → chunk-YC3PFFDE.js} +56 -56
  69. package/dist/cli-bundle/focused-chunks/{chunk-QSRXF6XS.js → chunk-YX75PQFO.js} +2 -2
  70. package/dist/cli-bundle/focused-chunks/{chunk-KEZ4VXYD.js → chunk-Z4FWJGQG.js} +2 -2
  71. package/dist/cli-bundle/focused-chunks/chunk-ZHHFOQSL.js +44 -0
  72. package/dist/cli-bundle/focused-chunks/chunk-ZUAPUBJK.js +2 -0
  73. package/dist/cli-bundle/focused-chunks/{chunk-NXUFVQ33.js → chunk-ZYHGQIQ7.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/field-definition-losses-NUZO3JCP.js +2 -0
  75. package/dist/cli-bundle/focused-chunks/field-option-collisions-63YQ2J3N.js +2 -0
  76. package/dist/cli-bundle/focused-chunks/item-revision-PV5O6F5Y.js +2 -0
  77. package/dist/cli-bundle/focused-chunks/item-transaction-S5QXBGAT.js +2 -0
  78. package/dist/cli-bundle/{chunks/mutation-actor-HGG47KXV.js → focused-chunks/mutation-actor-2AAUJG2Z.js} +2 -2
  79. package/dist/cli-bundle/focused-chunks/mutation-admission-X7HHNERR.js +2 -0
  80. package/dist/cli-bundle/focused-chunks/runtime-schema-5J2ONRNV.js +2 -0
  81. package/dist/cli-bundle/focused-chunks/stage-56RYPMBK.js +2 -0
  82. package/dist/cli-bundle/main.js +2 -2
  83. package/dist/cli-bundle/sdk-authoring.js +1 -1
  84. package/dist/cli-bundle/sdk-contracts.js +1 -1
  85. package/dist/cli-bundle/sdk-core.js +1 -1
  86. package/dist/cli-bundle/sdk-governance.js +1 -1
  87. package/dist/cli-bundle/sdk-graph.js +1 -1
  88. package/dist/cli-bundle/sdk-merge.js +63 -63
  89. package/dist/cli-bundle/sdk-query.js +1 -1
  90. package/dist/cli-bundle/sdk-runtime.js +1 -1
  91. package/dist/cli-bundle/sdk-testing.js +1 -1
  92. package/dist/cli-bundle/sdk.js +2 -2
  93. package/dist/core/extensions/index.js +1 -1
  94. package/dist/core/extensions/item-fields.d.ts +15 -1
  95. package/dist/core/extensions/item-fields.js +1 -1
  96. package/dist/core/extensions/loader.js +1 -1
  97. package/dist/core/profile/profile-lint.js +1 -1
  98. package/dist/core/schema/runtime-schema.d.ts +20 -1
  99. package/dist/core/schema/runtime-schema.js +2 -2
  100. package/dist/core/shared/command-line.d.ts +2 -2
  101. package/dist/core/shared/command-line.js +1 -1
  102. package/dist/core/shared/secret-rules.js +5 -5
  103. package/dist/sdk/agent/refusal-reachability.d.ts +1 -1
  104. package/dist/sdk/extension/command-options.d.ts +8 -0
  105. package/dist/sdk/extension/command-options.js +1 -1
  106. package/dist/sdk/extension-command-context.js +2 -2
  107. package/dist/sdk/governance/validate.js +1 -1
  108. package/dist/sdk/lifecycle/create.js +1 -1
  109. package/dist/sdk/lifecycle/update.js +2 -2
  110. package/dist/sdk/profile.js +1 -1
  111. package/dist/sdk/read-output-contracts.js +1 -1
  112. package/dist/sdk/schema/field-definition-losses.js +2 -0
  113. package/dist/sdk/schema/field-option-collisions.js +1 -1
  114. package/dist/sdk/schema.js +2 -2
  115. package/docs/COMMANDS.md +1 -1
  116. package/docs/CONFIGURATION.md +3 -1
  117. package/docs/EXTENSIONS.md +1 -1
  118. package/docs/MUTATION_INTEGRITY.md +47 -0
  119. package/docs/SDK.md +3 -1
  120. package/docs/SDK_AUDITED_MUTATIONS.md +12 -3
  121. package/marketplace.json +1 -1
  122. package/package.json +1 -1
  123. package/packages/pm-beads/package.json +1 -1
  124. package/packages/pm-calendar/package.json +1 -1
  125. package/packages/pm-command-kit/package.json +1 -1
  126. package/packages/pm-digital-twin/package.json +1 -1
  127. package/packages/pm-governance-audit/package.json +1 -1
  128. package/packages/pm-guide-shell/package.json +1 -1
  129. package/packages/pm-kanban/package.json +1 -1
  130. package/packages/pm-lifecycle-hooks/package.json +1 -1
  131. package/packages/pm-linked-test-adapters/package.json +1 -1
  132. package/packages/pm-search-advanced/package.json +1 -1
  133. package/packages/pm-templates/package.json +1 -1
  134. package/packages/pm-todos/package.json +1 -1
  135. package/packages/pm-vcs/package.json +1 -1
  136. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  137. package/plugins/pm-claude/package.json +1 -1
  138. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  139. package/plugins/pm-codex/package.json +1 -1
  140. package/plugins/pm-codex/plugin.json +1 -1
  141. package/runtime-dependencies.json +1 -1
  142. package/dist/cli-bundle/chunks/chunk-5BPDT7G2.js +0 -2
  143. package/dist/cli-bundle/chunks/chunk-7F3UFYZA.js +0 -2
  144. package/dist/cli-bundle/chunks/chunk-CBBKXTJG.js +0 -2
  145. package/dist/cli-bundle/chunks/chunk-DUJSME77.js +0 -3
  146. package/dist/cli-bundle/chunks/chunk-GQXK4KKH.js +0 -31
  147. package/dist/cli-bundle/chunks/chunk-HOLQZ56F.js +0 -8
  148. package/dist/cli-bundle/chunks/chunk-HTGN24XM.js +0 -3
  149. package/dist/cli-bundle/chunks/chunk-IGW3RVJC.js +0 -3
  150. package/dist/cli-bundle/chunks/chunk-KCRRTJ4X.js +0 -125
  151. package/dist/cli-bundle/chunks/chunk-KES4VHU4.js +0 -2
  152. package/dist/cli-bundle/chunks/chunk-NDS4MXZX.js +0 -2
  153. package/dist/cli-bundle/chunks/chunk-QMM46SJM.js +0 -4
  154. package/dist/cli-bundle/chunks/chunk-RFK3ERYX.js +0 -2
  155. package/dist/cli-bundle/chunks/chunk-SX76UGEY.js +0 -3
  156. package/dist/cli-bundle/chunks/chunk-WZOJSHJT.js +0 -113
  157. package/dist/cli-bundle/chunks/chunk-XRCE4QNL.js +0 -9
  158. package/dist/cli-bundle/chunks/field-option-collisions-CGRJEAPQ.js +0 -2
  159. package/dist/cli-bundle/chunks/item-revision-FGDR5NSF.js +0 -2
  160. package/dist/cli-bundle/chunks/item-transaction-C3KAMEYO.js +0 -2
  161. package/dist/cli-bundle/chunks/mutation-admission-LLHIRY6O.js +0 -2
  162. package/dist/cli-bundle/chunks/register-operations-ECVBZ5FM.js +0 -2
  163. package/dist/cli-bundle/chunks/register-setup-3QYD5H4H.js +0 -2
  164. package/dist/cli-bundle/chunks/runtime-schema-Y4SHTEXL.js +0 -2
  165. package/dist/cli-bundle/chunks/stage-RSCSUYEJ.js +0 -2
  166. package/dist/cli-bundle/focused-chunks/chunk-3BR5NWQI.js +0 -2
  167. package/dist/cli-bundle/focused-chunks/chunk-AVLB4L7M.js +0 -44
  168. package/dist/cli-bundle/focused-chunks/chunk-FW5Q26HA.js +0 -2
  169. package/dist/cli-bundle/focused-chunks/chunk-IWEGGRRD.js +0 -2
  170. package/dist/cli-bundle/focused-chunks/chunk-JUG3BAZZ.js +0 -2
  171. package/dist/cli-bundle/focused-chunks/chunk-NSFS3VWP.js +0 -100
  172. package/dist/cli-bundle/focused-chunks/chunk-OCKKIECS.js +0 -3
  173. package/dist/cli-bundle/focused-chunks/chunk-R6QFPHWW.js +0 -3
  174. package/dist/cli-bundle/focused-chunks/chunk-RFJ3MEFP.js +0 -27
  175. package/dist/cli-bundle/focused-chunks/chunk-RMJKVQYE.js +0 -3
  176. package/dist/cli-bundle/focused-chunks/chunk-UA2JNKMY.js +0 -4
  177. package/dist/cli-bundle/focused-chunks/chunk-VV2QF5IE.js +0 -91
  178. package/dist/cli-bundle/focused-chunks/chunk-WHHFPATO.js +0 -8
  179. package/dist/cli-bundle/focused-chunks/chunk-YNRW2FWB.js +0 -2
  180. package/dist/cli-bundle/focused-chunks/field-option-collisions-WV6GPYYP.js +0 -2
  181. package/dist/cli-bundle/focused-chunks/item-transaction-A6MVNPT7.js +0 -2
  182. package/dist/cli-bundle/focused-chunks/mutation-actor-6ZVW6OME.js +0 -2
  183. package/dist/cli-bundle/focused-chunks/mutation-admission-2DA4CINP.js +0 -2
  184. package/dist/cli-bundle/focused-chunks/runtime-schema-YXPYDD2C.js +0 -2
  185. package/dist/cli-bundle/focused-chunks/stage-RG3PKST7.js +0 -2
@@ -1,2 +1,2 @@
1
- import{READ_OUTPUT_DIMENSION_FLAGS as yt,READ_OUTPUT_COMPOSITION_FLAGS as wt,PM_READ_OUTPUT_SURFACES as Rt}from"./read-output/options.js";import{resolvePmHistoryOperation as bt}from"./cli-contracts/command-aliases.js";import{resolveExtensionOutputCommand as At}from"./read-output/extension.js";import{BEHAVIOR_PRESERVING_MIGRATION_HINTS as L,LEGACY_FLAGS_BY_COMMAND as Ct,VALUE_BEARING_INCLUDE_ALIASES as Et,flagSelector as G,optionKey as kt,readOutputIncludeModeOptionsForSurface as $,resolveNativeReadOutputSurface as Tt}from"./read-output/surfaces.js";import{EXIT_CODE as w}from"../core/shared/constants.js";import{PmCliError as R}from"../core/shared/errors.js";import{compactReadOutputToBudget as St,estimateReadOutputTokens as xt,readOutputMeasurementFormat as q,projectReadOutputItemToBrief as It,preserveReadOutputRowContract as k,mirrorReadOutputReceiptEstimate as jt,resolveReadOutputPassHooks as V,resolveReadOutputRecoveryBudget as vt,updateReadOutputReceiptEstimate as T}from"./read-output-budget.js";import{resolveReadOutputRecoveryBudget as en}from"./read-output-budget.js";import{resolvePmCommandOutputBudget as Ut}from"./cli-contracts/agent-output-contracts.js";import{boundReadOutputRows as Pt,countReadOutputRows as z,mapReadOutputRows as K,readOutputBudgetCollections as H,readOutputContinuationRowCollections as v,readOutputRowPaths as Nt,readOutputRowCollections as Mt,refreshReadOutputDeliveredCounts as U}from"./read-output-rows.js";import{applyReadOutputContinuation as Dt,decodeReadOutputContinuationCursor as Ft,encodeReadOutputContinuationCursor as Bt,prioritizeAssuranceAssertions as Lt,readOutputCollectionFingerprint as Gt,refreshReadOutputDeliveredRowCounters as $t}from"./read-output/continuation.js";import{PM_READ_OUTPUT_TAIL_RETENTION_POLICIES as S,readOutputRetainsTail as x}from"./read-output/tail-retention.js";import{decodeReadOutputContinuationCursor as on,encodeReadOutputContinuationCursor as un,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES as rn,readOutputCollectionFingerprint as sn}from"./read-output/continuation.js";import{PM_READ_OUTPUT_TAIL_RETENTION_POLICIES as cn,readOutputRetainsTail as dn}from"./read-output/tail-retention.js";import{applyReadOutputSessionReferences as qt,attachReadOutputSessionReceipt as Y,parseReadOutputSession as P,readOutputSessionRemainingTokens as Vt}from"./read-output-session.js";import{decodeQueryCursorEnvelope as zt,encodeQueryCursor as Kt}from"./pagination.js";import{READ_OUTPUT_INVOCATION_PROVENANCE as N}from"./read-output/provenance.js";const b=["include","amount","cost","encoding"];import{PM_READ_OUTPUT_SURFACES as fn}from"./read-output/options.js";const W=["canonical","legacy","intent","default"],C=yt,qe=Object.freeze(b.map(t=>C[t])),Ve=wt;function Ht(t,e){const n=L[t];if(n!==void 0)return n;const o=e==="include"?Et.has(t)?"<csv>":G(t):e==="amount"?"<n>":e==="cost"?"<tokens>":"<toon|json>";return`${t} is a compatibility alias; prefer ${C[e]} ${o}.`}function J(t){const e=Ct[t]??{},n=Object.freeze(Object.fromEntries(b.map(o=>[o,Object.freeze({dimension:o,canonical_option:C[o],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((e[o]??[]).map(u=>Object.freeze({flag:u,semantics:L[u]===void 0?"replacement":"behavior_preserving",migration_hint:Ht(u,o),visibility:"hidden_alias"})))})])));return Object.freeze({command:t,dimensions:n,precedence:W,budget_retention_policy:t==="assurance"?"verdict_priority":Object.hasOwn(S,t)?"ordered_suffix":"ordered_prefix",projection_modes:Object.freeze([...$(t).keys()])})}const Yt=Object.freeze(Rt.map(J)),Wt=new Map(Yt.map(t=>[t.command,t]));function I(t,e={}){const n=bt(t.trim().toLowerCase()),o=At(n);return o!==void 0?o.read_output===void 0?void 0:`extension:${o.command}`:Tt(n,e)}const X=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],Q={comments:["add","body","comment","text","stdin","file","edit","delete"],notes:["add","note","text","addJson","stdin","file","edit","delete"],learnings:["add","learning","text","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function Jt(t){return X.some(e=>e!=="outputFormat"&&e!=="output_format"&&t[e]!==void 0)}const Xt=[{keys:["outputInclude","output_include"],valid:t=>E(t)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:t=>t==="unbounded"||A(t)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:t=>t==="unbounded"||A(t)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:t=>(P(t),!0),message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:t=>typeof t=="string"&&t.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}],ze="read_output_surface_unsupported",Ke="read_output_mutation_conflict",Z=[{flag:"--output-include",keys:["outputInclude","output_include"]},{flag:"--output-limit",keys:["outputLimit","output_limit"]},{flag:"--output-budget",keys:["outputBudget","output_budget"]},{flag:"--output-session",keys:["outputSession","output_session"]},{flag:"--output-cursor",keys:["outputCursor","output_cursor"]},{flag:"--output-row-contract",keys:["outputRowContract","output_row_contract"]}],He=Z.map(({flag:t})=>t);function Qt(t,e,n){const o=Z.filter(({keys:s})=>s.some(d=>e[d]!==void 0)),u=o.map(({flag:s})=>s),i=o.flatMap(({keys:s})=>s.filter(d=>e[d]!==void 0)),r=u.join(", ");return new R(`Universal output controls (${r}) cannot be combined with a ${t} mutation; nothing was written.`,w.USAGE,{code:"read_output_mutation_conflict",field:u[0],details:{surface:t,output_controls:u,output_option_keys:i,mutation_options:[...n]},required:`Retry the ${t} mutation without ${r}. To bound or page the result, read it with those controls in a separate call after the write.`,why:"Universal output controls shape a read. A mutation returns its own bounded receipt, so the controls have nothing to shape and the write is refused before it runs.",examples:[...Zt[t]]})}const Zt={comments:['pm comments <id> --add "<text>"',"pm comments <id> --output-limit 5"],notes:['pm notes <id> --add "<text>"',"pm notes <id> --output-limit 5"],learnings:['pm learnings <id> --add "<text>"',"pm learnings <id> --output-limit 5"],files:["pm files <id> --add path=<path>","pm files <id> --output-limit 5"],docs:["pm docs <id> --add path=<path>","pm docs <id> --output-limit 5"],"package-catalog":["pm package install <source> --project","pm package catalog --output-limit 5"]},te=new Set(["comments","notes","learnings"]);function Ye(t,e){const n=e[1];return te.has(t)&&typeof n=="string"?{add:n}:{}}function We(t,e){const n=e.outputFormat??e.output_format;if(n!==void 0&&n!=="json"&&n!=="toon")throw new R("--output-format must be toon or json.",w.USAGE);if(!Jt(e))return;const o=I(t,e);if(!o){const u=X.filter(i=>e[i]!==void 0);throw new R(`Universal output controls apply only to read commands; ${t||"this command"} is not a read surface.`,w.USAGE,{code:"read_output_surface_unsupported",details:{command:t||null,output_option_keys:u},required:"Drop the universal output controls, or run a read command. An extension command accepts them only when it declares read_output.",why:"Universal output controls shape a read's rows; a command that is not a read surface has no rows for them to bound, page or project."})}if(Object.hasOwn(Q,o)){const u=o,i=Q[u].filter(r=>e[r]!==void 0&&e[r]!==!1);if(i.length>0)throw Qt(u,e,i)}for(const u of Xt){const i=u.keys.map(r=>e[r]).find(r=>r!==void 0);if(i!==void 0&&!u.valid(i))throw new R(u.message,w.USAGE)}}function tt(t){const e=I(t);return e?$(e):new Map}function ee(t,e,n){const o=E(e)??[],u=tt(t),i=[],r=[],s=n,d=s[N],f=new Set(d?.canonical_include_modes??[]),l=new Set(d?.explicit_legacy_aliases??[]);for(const c of o){const _=u.get(c);if(_===void 0){i.push(c);continue}const O=`--${c.replaceAll("_","-")}`;D(M(n,O))&&l.add(O),n[_]=!0,r.push(c),f.add(c)}const a=I(t)==="get"?i.filter(c=>c!=="item"):[],p=a.length>0;return p&&(n.fields=[...new Set([...E(n.fields)??[],...a])].join(","),f.add("fields")),(r.length>0||p)&&(s[N]={canonical_include_modes:[...f],explicit_legacy_aliases:[...l],...d?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors:i,modes:r}}function Je(t,e){const n=e.outputInclude??e.output_include;if(n===void 0)return;const{selectors:o,modes:u}=ee(t,n,e);if(u.length===0)return;const i=o.length>0?o.join(","):void 0;e.outputInclude=i,Object.hasOwn(e,"output_include")&&(e.output_include=i)}function M(t,e){const n=kt(e);if(Object.hasOwn(t,n))return t[n];const o=e.slice(2).replaceAll("-","_");if(Object.hasOwn(t,o))return t[o];if(e==="--no-truncate"&&t.truncate===!1)return!0}function D(t){return t!==void 0&&t!==!1&&t!==null}function E(t){const n=(Array.isArray(t)?t:[t]).flatMap(o=>typeof o=="string"?o.split(","):[]).map(o=>o.trim()).filter(Boolean);return n.length>0?[...new Set(n)]:void 0}function A(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 ne(t,e,n,o){for(const u of t.legacy_aliases){if(o(u.flag))continue;const i=M(e,u.flag),r={value:i,flag:u.flag};if(D(i)&&n(r))return r}}function et(t,e){const n=E(t);if(n)return{source:"canonical",value:n};if(e)return{source:"legacy",value:E(e.value)??[G(e.flag)]}}function nt(t,e){if(t==="unbounded")return{source:"canonical",value:"unbounded"};const n=A(t);if(n!==void 0)return{source:"canonical",value:n};if(!e)return;if(e.flag==="--no-truncate"||e.flag==="--unbounded")return{source:"legacy",value:"unbounded"};const o=A(e.value);return o===void 0?void 0:{source:"legacy",value:o}}function ot(t,e){if(t==="unbounded")return{source:"canonical",value:"unbounded"};const n=A(t);if(n!==void 0)return{source:"canonical",value:n};if(!e)return;const o=A(e.value);return o===void 0?void 0:{source:"legacy",value:o}}function ut(t,e){if(t==="json"||t==="toon")return{source:"canonical",value:t};if(e)return e.flag==="--stream"||e.flag==="--follow"?{source:"legacy",value:"stream"}:e.value==="json"||e.value==="toon"?{source:"legacy",value:e.value}:void 0}function it(t,e,n){if(!t)return!1;const o=new Set(t.explicit_legacy_aliases);if(t.cli_invocation_observed===!0||t.sdk_invocation_observed===!0)return!o.has(n);const u=new Set(t.canonical_include_modes.map(i=>`--${i.replaceAll("_","-")}`));return e==="include"&&u.has(n)&&!o.has(n)}function oe(t,e,n,o){return t.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||D(M(o,"--no-truncate"))&&!it(n,"amount","--no-truncate")||e.amount?.flag==="--no-truncate"||e.include?.flag==="--full"||n?.canonical_include_modes.includes("full")===!0}function ue(t,e){return b.flatMap(n=>t[n]?.source==="canonical"||n==="include"&&(e?.canonical_include_modes.length??0)>0?[C[n]]:[])}function rt(t,e){const n=I(t,e);if(!n)return;const o=Wt.get(n)??J(n),u=e[N],i={include:g=>et(void 0,g),amount:g=>nt(void 0,g),cost:g=>ot(void 0,g),encoding:g=>ut(void 0,g)},r=Object.fromEntries(b.map(g=>[g,ne(o.dimensions[g],e,y=>i[g](y)!==void 0,y=>it(u,g,y))])),s=b.flatMap(g=>{const y=r[g];return y?[y.flag]:[]}),d=b.flatMap(g=>{const y=r[g];return y?[o.dimensions[g].legacy_aliases.find(ht=>ht.flag===y.flag).migration_hint]:[]}),f=ut(e.outputFormat??e.output_format,r.encoding),l=et(e.outputInclude??e.output_include,r.include),a=nt(e.outputLimit??e.output_limit,r.amount),p=ot(e.outputBudget??e.output_budget,r.cost),c=oe(t,r,u,e),_=Ut(t,{generateFallback:!0}),O=f?.value==="json"||e.resolvedOutputFormat==="json"?"json":"toon",h=p??(c?{source:"intent",value:"unbounded"}:{source:"default",value:_.default_max_estimated_tokens_by_format[O]});return{command:n,include:l,amount:a,cost:h,encoding:f,canonical_options_used:ue({include:l,amount:a,cost:h,encoding:f},u),legacy_aliases_used:s,migration_hints:d,precedence:W}}function m(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}const F=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]),ie=["collection_counts","notes_count","tests_count"];function st(t,e){const n=new Set(e.map(o=>o.split(".")[0]));return Object.fromEntries(Object.entries(t).filter(([o])=>n.has(o)))}function re(t){const e=m(t.item)?t.item:{},n=[...new Set([...Object.keys(e),...ie.filter(u=>Object.hasOwn(e,u))])].sort((u,i)=>u.localeCompare(i)),o=Object.keys(t).filter(u=>u!=="item"&&u!=="read_output"&&!F.has(u)).sort((u,i)=>u.localeCompare(i));return{item:e,itemFields:n,sections:o,valid:[...n,"item",...n.map(u=>`item.${u}`),...o]}}function se(t,e){const n=re(t),o=e.filter(a=>!n.valid.includes(a));if(o.length>0)throw new R(`Unknown --output-include selector(s) for get: ${o.join(", ")}. Valid selectors: ${n.valid.join(", ")}.`,w.USAGE);const u=e.includes("item"),i=e.flatMap(a=>a.startsWith("item.")?[a.slice(5)]:n.itemFields.includes(a)?[a]:[]).filter((a,p,c)=>c.indexOf(a)===p);if(u&&i.length>0)throw new R("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",w.USAGE);const r=new Set(e.filter(a=>n.sections.includes(a))),s=Object.fromEntries(Object.entries(t).filter(([a])=>F.has(a)||r.has(a)));u?s.item=n.item:i.length>0&&(s.item=st(n.item,i));const d=[...u?[]:i.length>0?n.itemFields.filter(a=>!i.includes(a)).map(a=>({name:`item.${a}`,restore_with:`--output-include item.${a}`})):[{name:"item",restore_with:"--output-include item"}],...n.sections.filter(a=>!r.has(a)).map(a=>({name:a,restore_with:`--output-include ${a}`}))],l=[...m(s.omission_receipt)&&Array.isArray(s.omission_receipt.omitted_field_groups)?s.omission_receipt.omitted_field_groups:[],...d];return s.omission_receipt={has_omissions:l.length>0,omitted_field_group_count:l.length,omitted_field_groups:l},s}function at(t){let e=0;return K({...t},n=>(m(n)&&Object.keys(n).length>0&&(e+=1),n)),e}function ae(t,e,n,o){if(at(e)===0||at(n)>0)return;const u=[...tt(t).keys()],i=u.length>0?` Declared ${t} projection modes: ${u.join(", ")}.`:` The ${t} surface declares no projection modes; name row fields instead.`;throw new R(`Unknown --output-include selector(s) for ${t}: ${o.join(", ")}. No selector matched any returned row field.${i}`,w.USAGE)}function ce(t,e,n){if(t==="get")return se(e,n);const o=Nt(e),u=n.flatMap(r=>o.flatMap(s=>r.startsWith(`${s}.`)?[r.slice(s.length+1)]:[])),i=n.some(r=>Object.hasOwn(e,r.split(".")[0])&&!o.some(s=>r.startsWith(`${s}.`)));if(o.length>0&&(!i||u.length>0)){const r={...e},s=u.length>0?u:n,d=K(r,f=>m(f)?st(f,s):f);return ae(t,e,d,s),d}return Object.fromEntries(Object.entries(e).filter(([r])=>n.some(s=>s.split(".")[0]===r)||F.has(r)))}function de(t,e,n,o){if(e==="unbounded")return t;const{result:u,truncated:i}=Pt(t,e,r=>x(n,r));if(!i)return u;if(u.has_more=!0,u.truncated=!0,_t(u,n,[...o.entries()].flatMap(([r,s])=>s.rows>e?[{path:r,total_rows:s.totalRows}]:[])),typeof u.count=="number"){const r=m(u.projection)?u.projection.row_key:void 0;u.count=typeof r=="string"&&Array.isArray(u[r])?u[r].length:z(u)}return typeof u.returned_count=="number"&&(u.returned_count=z(u)),u.applied_bound={kind:"output_limit",source:"explicit",value:e},u}function le(t){return b.filter(e=>t[e]!==void 0&&t[e]?.source!=="default"||t.canonical_options_used.includes(C[e]))}function j(t,e,n,o){let u=Y(t,e,o);k(t,u);for(let i=0;i<8;i+=1){const r=n.estimated_tokens,s=u.read_session.spent_this_call_tokens;T(u,n,o);const d=u;u=Y(u,e,o),k(d,u);const f=u.read_session.spent_this_call_tokens;if(n.estimated_tokens===r&&f===s)return u}return u}function fe(t,e){if(!m(t.read_output))return t;const n=q(e),o=t.read_output,u=P(e.outputSession??e.output_session);return u===void 0?(T(t,o,n),t):j(t,u,o,n)}function ct(t,e){if(t!=="validate")return e;const n=m(e.projection)?e.projection:void 0;if(!(Array.isArray(n?.declared_field_groups)?n.declared_field_groups:[]).some(a=>m(a)&&a.name==="diagnostic_rows"))return e;const u=[...new Set(H(e).map(({path:a})=>a).filter(a=>/^checks\.\d+\.details\./u.test(a)))],i=u.filter(a=>!u.some(p=>p!==a&&a.startsWith(`${p}.`)));if(i.length===0)return e;const r=m(e.row_contract)?e.row_contract:{},s=Array.isArray(r.row_keys)?r.row_keys.filter(a=>typeof a=="string"):[],d=Array.isArray(r.continuation_row_keys)?r.continuation_row_keys.filter(a=>typeof a=="string"):[],f=s.length>0?s:i,l=[...new Set(i)];return JSON.stringify(f)===JSON.stringify(s)&&JSON.stringify(l)===JSON.stringify(d)?e:{...e,row_contract:{...r,row_keys:f,continuation_row_keys:l,jq_selector:typeof r.jq_selector=="string"?r.jq_selector:".checks[].details"}}}function pe(t,e){return t.include?.source==="canonical"&&!B(e)}function dt(t,e){let n={...t};return pe(e,t)&&(n=ce(e.command,n,e.include.value)),e.command==="assurance"?Lt(n):n}function _e(t,e){const n=V(e)?.continuationBinding;if(n===void 0)return;const o=dt(ct(t.command,n),t);return new Map(v(o).filter(u=>!x(t.command,u.path)).map(u=>[u.path,u]))}function me(t,e,n,o,u){let i=dt(t,e);U(i,t);const r=_e(e,u);if(i=Dt(i,e.command,o,r),e.command==="history"&&o){const f=["compact_history","provenance_history","history","diff"];if(i=Object.fromEntries(Object.entries(i).filter(([l])=>!f.includes(l)||l===o.path)),m(i.projection)&&(i.projection={...i.projection,row_key:o.path}),m(i.row_contract)){const l=i.row_contract;i.row_contract={...l,row_keys:[o.path],...Array.isArray(l.continuation_row_keys)?{continuation_row_keys:[o.path]}:{}}}i.count=Object.keys(i[o.path]).length}const s=t.count_only===!0?{...i,count_only:!0,count:t.count}:i,d=Ae(i,t,e.command,o,u,r);return e.amount?.source==="canonical"&&(i=de(i,e.amount.value,e.command,d.collectionsBeforeBudget),d.cursorContinuesExistingPage&&gt(i,d.originalItems,d.cursorSource,!0,d.originalItemOffset)),U(i,s),mt(i,e.command,d),{projected:n===void 0?i:qt(i,n),continuationState:d}}function ge(t,e){return[...t.cost!==void 0&&t.cost.value!=="unbounded"&&(t.cost.source==="canonical"||t.cost.source==="default"||t.command==="context"&&t.cost.source==="legacy")?[{source:t.cost.source,tokens:t.cost.value}]:[],...e===void 0?[]:[{source:"session",tokens:Vt(e)}]].sort((o,u)=>o.tokens-u.tokens)[0]}function lt(t){const e=t.canonical_options_used;return e&&e.length>0?{canonical_options_used:e}:{}}function ft(t,e){return m(t.context_intent)&&t.context_intent.command==="context"&&t.context_intent.token_budget===e&&t.context_intent.within_budget===!0}function Oe(t,e,n){return t.command!=="next"||(e.tokenBudget??e.token_budget)===void 0?!1:!(m(n.context_intent)&&n.context_intent.command==="next"&&n.context_intent.within_budget===!0)}function pt(t,e={}){return t?.source==="default"||t?.source==="legacy"&&!ft(e,t.tokens)?{budget_source:t.source,budget_tokens:t.tokens}:{}}function he(t,e,n,o,u,i){const r={contract_version:1,command:t.command,requested_dimensions:e,...pt(o),precedence:t.precedence,...lt(t),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...n===void 0?{omitted_result_estimated_tokens:u}:{}},s={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:r},d=n===void 0?s:j(s,n,r,i);if(n===void 0&&T(d,r,i),n!==void 0&&r.estimated_tokens>o.tokens)throw new R("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",w.USAGE);return d}function ye(t,e,n){return t.command==="context"&&t.cost?.source==="legacy"&&!ft(n,t.cost.value)||Oe(t,e,n)||e.outputRowContract===!0||e.output_row_contract===!0||t.canonical_options_used.includes("--output-include")||t.command==="list"&&t.canonical_options_used.length>0&&t.include?.value.includes("full")===!0}function we(t,e,n,o,u){if(e!==void 0||B(n)||ye(t,u,n))return!1;if(t.amount?.source==="canonical"&&t.amount.value!=="unbounded"){const i=t.amount.value;if(Mt(n).some(({value:r})=>(Array.isArray(r)?r.length:Object.keys(r).length)>i))return!1}return t.cost===void 0||t.cost.value==="unbounded"||t.cost.source==="legacy"&&t.command!=="context"||xt(u.outputRowContract===!1?Object.fromEntries(Object.entries(n).filter(([i])=>i!=="row_contract")):n,o)<=t.cost.value}function _t(t,e,n){const o=Object.hasOwn(S,e)?S[e]:void 0,u=n.find(i=>o?.paths.includes(i.path));o!==void 0&&u!==void 0&&typeof t[o.total_key]!="number"&&(t[o.total_key]=u.total_rows)}function mt(t,e,n){const o=S[e]?.paths[0];o!==void 0&&$t(t,e,n.producer,n.collectionsBeforeBudget.get(o)?.rows)}function Re(t,e,n,o){const u=n.backward?n.rows-o:n.baseOffset+o;return{path:e,cursor:Bt({command:t,path:e,offset:u,total_rows:n.totalRows,fingerprint:n.fingerprint,...n.backward?{direction:"backward"}:{}}),retained_rows:o,remaining_rows:n.backward?u:n.totalRows-u,total_rows:n.totalRows}}function be(t,e,n,o,u,i,r){if(!n.rows_compacted)return;const s=e.amount?.value==="unbounded"?["amount"]:[],d=new Map(v(t).map(_=>[_.path,Array.isArray(_.value)?_.value.length:Object.keys(_.value).length])),f=[...r.entries()].flatMap(([_,O])=>{const h=d.get(_);return h>=O.rows?[]:[Re(e.command,_,O,h)]}),l=f[0];_t(t,e.command,f);const a=l?"; page --output-cursor":"",p=o.source==="session"?`Truncated by the remaining ${o.tokens}-token session budget; start a new output session with a larger token_budget${a}.`:`${o.tokens}-token: raise --output-budget${a}`;n.migration_hints=[p,...e.migration_hints];const c=vt({effective_budget_tokens:o.tokens,measured_result_tokens:i});l&&!u&&(typeof t.next_cursor!="string"||t.continuation_kind==="output_cursor")&&(t.next_cursor=l.cursor),t.continuation_kind=u?"producer_cursor":l?"output_cursor":"none",t.output_budget_truncation={reason:"output_budget_reached",budget_source:o.source,budget_tokens:o.tokens,overridden_dimensions:s,compacted_row_paths:n.compacted_row_paths,continuation_cursor_rebased:u,continuation_available:f.length>0,recovery_budget_multiplier:l?1:c.recovery_budget_multiplier,continuations:f,restore_with:l?"recovery":`Retry with --output-budget ${c.output_budget} because no declared row collection can be continued.`,recovery:l?{cursor:l.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${c.output_budget}`,sdk:{outputBudget:c.output_budget},mcp:{outputBudget:c.output_budget}}}}function gt(t,e,n,o,u){if(typeof n!="string"||!Array.isArray(t.items))return!1;const i=t.items.length,r=e.length;if(i===0||i>=r)return!1;let s;try{s=zt(n)}catch{return!1}const d=s.after_index;if(d===void 0)return!1;const f=e[i-1];if(Object.prototype.toString.call(f)!=="[object Object]")return!1;const l=Reflect.get(f,"id");if(typeof l!="string"||l.length===0)return!1;const a=o?d-(r-i):d+u+i;return a<0?!1:(t.next_cursor=Kt(s.fingerprint,l,a,s.snapshot),!0)}function Ot(t){return Array.isArray(t)?t.length:Object.keys(t).length}function Ae(t,e,n,o,u,i){const r=new Map(v(t).map(f=>{const l=Ot(f.value),a=o?.path===f.path,p=x(n,f.path),c=i?.get(f.path)??f;let _;return[f.path,{rows:l,totalRows:a?o.total_rows:Ot(c.value),baseOffset:a&&!p?o.offset:0,backward:p,get fingerprint(){return _??=a?o.fingerprint:Gt(f.path,c.value,n),_}}]})),s=typeof t.next_cursor=="string",d=o?.path==="items"?o.offset:0;return{collectionsBeforeBudget:r,originalItems:Array.isArray(e.items)?d>0?e.items.slice(d):e.items:[],originalItemOffset:d,cursorContinuesExistingPage:s,cursorSource:s?t.next_cursor:u.after,producer:e}}function Ce(t,e,n,o,u,i,r,s,d,f){const l={...e,count_only:n},a=o.command==="assurance"&&Array.isArray(t.assertions)?t.assertions.filter(c=>m(c)&&c.verdict!=="pass").length:0,p=new Map;if(a>0&&p.set("assertions",a),o.command==="history"&&Array.isArray(t.diff))for(const c of H(t))c.path.startsWith("diff.")&&p.set(c.path,Object.keys(c.value).length);return St(t,u,i.tokens,p,f,c=>{U(c,l),mt(c,o.command,s);const _=gt(c,s.originalItems,s.cursorSource,s.cursorContinuesExistingPage,s.originalItemOffset);if(be(c,o,u,i,_,d,s.collectionsBeforeBudget),o.command==="history"&&m(c.projection)){c.has_more=typeof c.next_cursor=="string"||c.applied_bound?.kind==="output_limit";const O=c.projection.row_key;typeof O=="string"&&Array.isArray(c[O])&&(c.count=c[O].length)}r!==void 0&&Object.assign(c,j(c,r,u,f))},o.command==="history"&&Array.isArray(t.diff),c=>x(o.command,c),o.command)}function Xe(t,e,n){const o=rt(t,e);if(!o)return n;const u=q(e),i=P(e.outputSession??e.output_session),r=e.outputCursor??e.output_cursor,s=typeof r=="string"?Ft(r):void 0,d=le(o),f=ct(o.command,n);if(s===void 0&&we(o,i,f,u,e))return f;const l=ge(o,i),a=me(f,o,i,s,e);let p=a.projected;k(p,p,e.outputRowContract===!1);const c=B(p),_={contract_version:1,command:o.command,requested_dimensions:d,...pt(l,p),precedence:o.precedence,...lt(o),legacy_aliases_used:o.legacy_aliases_used,migration_hints:o.migration_hints,estimated_tokens:0,within_budget:!c,strings_compacted:!1,rows_compacted:!1,result_omitted:c};p.read_output=_;const O=V(e)?.mirrorEstimate;if(O!==void 0&&jt(_,O),p=i===void 0?p:j(p,i,_,u),T(p,_,u),l!==void 0&&_.estimated_tokens>l.tokens){const h=It(o.command,e,p);h!==void 0&&(_.applied_depth="brief",_.degradation_reason="output_budget_reached",k(p,h),p=fe(h,e)),_.estimated_tokens>l.tokens&&(p=Ce(p,p,f.count_only===!0,o,_,l,i,a.continuationState,_.estimated_tokens,u))}return l!==void 0&&_.estimated_tokens>l.tokens?he(o,d,i,l,_.estimated_tokens,u):p}function Ee(t){return m(t)&&m(t.context_intent)&&t.context_intent.result_omitted===!0}function B(t){return ke(t)||Ee(t)}function ke(t){return m(t)&&m(t.output_budget_exceeded)&&t.output_budget_exceeded.omitted_result===!0&&t.output_budget_exceeded.reason==="requested_budget_infeasible"}function Qe(t,e){const n=e.outputFormat??e.output_format;if(n==="json"||n==="toon")return n;const o=rt(t,e)?.encoding;return o?.value==="json"||o?.value==="toon"?o.value:void 0}export{Ve as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,rn as PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,b as PM_READ_OUTPUT_DIMENSIONS,qe as PM_READ_OUTPUT_OPTION_FLAGS,fn as PM_READ_OUTPUT_SURFACES,Yt as PM_READ_OUTPUT_SURFACE_CONTRACTS,cn as PM_READ_OUTPUT_TAIL_RETENTION_POLICIES,Ke as READ_OUTPUT_MUTATION_CONFLICT_CODE,He as READ_OUTPUT_SHAPING_CONTROL_FLAGS,ze as READ_OUTPUT_SURFACE_UNSUPPORTED_CODE,Ye as annotationPositionalMutationOptions,Xe as applyReadOutputDimensions,ee as applyReadOutputIncludeModes,on as decodeReadOutputContinuationCursor,un as encodeReadOutputContinuationCursor,ke as isReadOutputBudgetExceeded,B as isReadResultOmittedForBudget,Je as normalizeReadOutputIncludeModeOptions,sn as readOutputCollectionFingerprint,tt as readOutputIncludeModeOptions,dn as readOutputRetainsTail,rt as resolveReadOutputDimensions,Qe as resolveReadOutputEncoding,en as resolveReadOutputRecoveryBudget,I as resolveReadOutputSurface,fe as stabilizeReadOutputReceiptEstimates,We as validateReadOutputOptions};
1
+ import{READ_OUTPUT_DIMENSION_FLAGS as wt,READ_OUTPUT_COMPOSITION_FLAGS as Rt,PM_READ_OUTPUT_SURFACES as bt}from"./read-output/options.js";import{resolvePmHistoryOperation as L}from"./cli-contracts/command-aliases.js";import{resolveExtensionOutputCommand as At}from"./read-output/extension.js";import{BEHAVIOR_PRESERVING_MIGRATION_HINTS as G,LEGACY_FLAGS_BY_COMMAND as Ct,VALUE_BEARING_INCLUDE_ALIASES as Et,flagSelector as $,optionKey as kt,readOutputIncludeModeOptionsForSurface as q,resolveNativeReadOutputSurface as Tt}from"./read-output/surfaces.js";import{EXIT_CODE as w}from"../core/shared/constants.js";import{PmCliError as R}from"../core/shared/errors.js";import{compactReadOutputToBudget as St,estimateReadOutputTokens as xt,readOutputMeasurementFormat as V,projectReadOutputItemToBrief as It,preserveReadOutputRowContract as k,mirrorReadOutputReceiptEstimate as jt,resolveReadOutputPassHooks as z,resolveReadOutputRecoveryBudget as vt,updateReadOutputReceiptEstimate as T}from"./read-output-budget.js";import{resolveReadOutputRecoveryBudget as en}from"./read-output-budget.js";import{resolvePmCommandOutputBudget as Ut}from"./cli-contracts/agent-output-contracts.js";import{boundReadOutputRows as Pt,countReadOutputRows as K,mapReadOutputRows as H,readOutputBudgetCollections as Y,readOutputContinuationRowCollections as v,readOutputRowPaths as Nt,readOutputRowCollections as Mt,refreshReadOutputDeliveredCounts as U}from"./read-output-rows.js";import{applyReadOutputContinuation as Dt,decodeReadOutputContinuationCursor as Ft,encodeReadOutputContinuationCursor as Bt,prioritizeAssuranceAssertions as Lt,readOutputCollectionFingerprint as Gt,refreshReadOutputDeliveredRowCounters as $t}from"./read-output/continuation.js";import{PM_READ_OUTPUT_TAIL_RETENTION_POLICIES as S,readOutputRetainsTail as x}from"./read-output/tail-retention.js";import{decodeReadOutputContinuationCursor as on,encodeReadOutputContinuationCursor as un,PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES as rn,readOutputCollectionFingerprint as sn}from"./read-output/continuation.js";import{PM_READ_OUTPUT_TAIL_RETENTION_POLICIES as cn,readOutputRetainsTail as dn}from"./read-output/tail-retention.js";import{applyReadOutputSessionReferences as qt,attachReadOutputSessionReceipt as W,parseReadOutputSession as P,readOutputSessionRemainingTokens as Vt}from"./read-output-session.js";import{decodeQueryCursorEnvelope as zt,encodeQueryCursor as Kt}from"./pagination.js";import{READ_OUTPUT_INVOCATION_PROVENANCE as N}from"./read-output/provenance.js";const b=["include","amount","cost","encoding"];import{PM_READ_OUTPUT_SURFACES as fn}from"./read-output/options.js";const J=["canonical","legacy","intent","default"],C=wt,qe=Object.freeze(b.map(t=>C[t])),Ve=Rt;function Ht(t,e){const n=G[t];if(n!==void 0)return n;const o=e==="include"?Et.has(t)?"<csv>":$(t):e==="amount"?"<n>":e==="cost"?"<tokens>":"<toon|json>";return`${t} is a compatibility alias; prefer ${C[e]} ${o}.`}function X(t){const e=Ct[t]??{},n=Object.freeze(Object.fromEntries(b.map(o=>[o,Object.freeze({dimension:o,canonical_option:C[o],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((e[o]??[]).map(u=>Object.freeze({flag:u,semantics:G[u]===void 0?"replacement":"behavior_preserving",migration_hint:Ht(u,o),visibility:"hidden_alias"})))})])));return Object.freeze({command:t,dimensions:n,precedence:J,budget_retention_policy:t==="assurance"?"verdict_priority":Object.hasOwn(S,t)?"ordered_suffix":"ordered_prefix",projection_modes:Object.freeze([...q(t).keys()])})}const Yt=Object.freeze(bt.map(X)),Wt=new Map(Yt.map(t=>[t.command,t]));function I(t,e={}){const n=L(t.trim().toLowerCase()),o=At(n);return o!==void 0?o.read_output===void 0?void 0:`extension:${o.command}`:Tt(n,e)}const Q=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],Z={comments:["add","body","comment","text","stdin","file","edit","delete"],notes:["add","note","text","addJson","stdin","file","edit","delete"],learnings:["add","learning","text","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function Jt(t){return Q.some(e=>e!=="outputFormat"&&e!=="output_format"&&t[e]!==void 0)}const Xt=[{keys:["outputInclude","output_include"],valid:t=>E(t)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:t=>t==="unbounded"||A(t)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:t=>t==="unbounded"||A(t)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:t=>(P(t),!0),message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:t=>typeof t=="string"&&t.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}],ze="read_output_surface_unsupported",Ke="read_output_mutation_conflict",tt=[{flag:"--output-include",keys:["outputInclude","output_include"]},{flag:"--output-limit",keys:["outputLimit","output_limit"]},{flag:"--output-budget",keys:["outputBudget","output_budget"]},{flag:"--output-session",keys:["outputSession","output_session"]},{flag:"--output-cursor",keys:["outputCursor","output_cursor"]},{flag:"--output-row-contract",keys:["outputRowContract","output_row_contract"]}],He=tt.map(({flag:t})=>t);function Qt(t,e,n){const o=tt.filter(({keys:s})=>s.some(d=>e[d]!==void 0)),u=o.map(({flag:s})=>s),i=o.flatMap(({keys:s})=>s.filter(d=>e[d]!==void 0)),r=u.join(", ");return new R(`Universal output controls (${r}) cannot be combined with a ${t} mutation; nothing was written.`,w.USAGE,{code:"read_output_mutation_conflict",field:u[0],details:{surface:t,output_controls:u,output_option_keys:i,mutation_options:[...n]},required:`Retry the ${t} mutation without ${r}. To bound or page the result, read it with those controls in a separate call after the write.`,why:"Universal output controls shape a read. A mutation returns its own bounded receipt, so the controls have nothing to shape and the write is refused before it runs.",examples:[...Zt[t]]})}const Zt={comments:['pm comments <id> --add "<text>"',"pm comments <id> --output-limit 5"],notes:['pm notes <id> --add "<text>"',"pm notes <id> --output-limit 5"],learnings:['pm learnings <id> --add "<text>"',"pm learnings <id> --output-limit 5"],files:["pm files <id> --add path=<path>","pm files <id> --output-limit 5"],docs:["pm docs <id> --add path=<path>","pm docs <id> --output-limit 5"],"package-catalog":["pm package install <source> --project","pm package catalog --output-limit 5"]},te=new Set(["comments","notes","learnings"]);function Ye(t,e){const n=e[1];return te.has(L(t.trim().toLowerCase()))&&typeof n=="string"?{add:n}:{}}function We(t,e){const n=e.outputFormat??e.output_format;if(n!==void 0&&n!=="json"&&n!=="toon")throw new R("--output-format must be toon or json.",w.USAGE);if(!Jt(e))return;const o=I(t,e);if(!o){const u=Q.filter(i=>e[i]!==void 0);throw new R(`Universal output controls apply only to read commands; ${t||"this command"} is not a read surface.`,w.USAGE,{code:"read_output_surface_unsupported",details:{command:t||null,output_option_keys:u},required:"Drop the universal output controls, or run a read command. An extension command accepts them only when it declares read_output.",why:"Universal output controls shape a read's rows; a command that is not a read surface has no rows for them to bound, page or project."})}if(Object.hasOwn(Z,o)){const u=o,i=Z[u].filter(r=>e[r]!==void 0&&e[r]!==!1);if(i.length>0)throw Qt(u,e,i)}for(const u of Xt){const i=u.keys.map(r=>e[r]).find(r=>r!==void 0);if(i!==void 0&&!u.valid(i))throw new R(u.message,w.USAGE)}}function et(t){const e=I(t);return e?q(e):new Map}function ee(t,e,n){const o=E(e)??[],u=et(t),i=[],r=[],s=n,d=s[N],f=new Set(d?.canonical_include_modes??[]),l=new Set(d?.explicit_legacy_aliases??[]);for(const c of o){const _=u.get(c);if(_===void 0){i.push(c);continue}const O=`--${c.replaceAll("_","-")}`;D(M(n,O))&&l.add(O),n[_]=!0,r.push(c),f.add(c)}const a=I(t)==="get"?i.filter(c=>c!=="item"):[],p=a.length>0;return p&&(n.fields=[...new Set([...E(n.fields)??[],...a])].join(","),f.add("fields")),(r.length>0||p)&&(s[N]={canonical_include_modes:[...f],explicit_legacy_aliases:[...l],...d?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors:i,modes:r}}function Je(t,e){const n=e.outputInclude??e.output_include;if(n===void 0)return;const{selectors:o,modes:u}=ee(t,n,e);if(u.length===0)return;const i=o.length>0?o.join(","):void 0;e.outputInclude=i,Object.hasOwn(e,"output_include")&&(e.output_include=i)}function M(t,e){const n=kt(e);if(Object.hasOwn(t,n))return t[n];const o=e.slice(2).replaceAll("-","_");if(Object.hasOwn(t,o))return t[o];if(e==="--no-truncate"&&t.truncate===!1)return!0}function D(t){return t!==void 0&&t!==!1&&t!==null}function E(t){const n=(Array.isArray(t)?t:[t]).flatMap(o=>typeof o=="string"?o.split(","):[]).map(o=>o.trim()).filter(Boolean);return n.length>0?[...new Set(n)]:void 0}function A(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 ne(t,e,n,o){for(const u of t.legacy_aliases){if(o(u.flag))continue;const i=M(e,u.flag),r={value:i,flag:u.flag};if(D(i)&&n(r))return r}}function nt(t,e){const n=E(t);if(n)return{source:"canonical",value:n};if(e)return{source:"legacy",value:E(e.value)??[$(e.flag)]}}function ot(t,e){if(t==="unbounded")return{source:"canonical",value:"unbounded"};const n=A(t);if(n!==void 0)return{source:"canonical",value:n};if(!e)return;if(e.flag==="--no-truncate"||e.flag==="--unbounded")return{source:"legacy",value:"unbounded"};const o=A(e.value);return o===void 0?void 0:{source:"legacy",value:o}}function ut(t,e){if(t==="unbounded")return{source:"canonical",value:"unbounded"};const n=A(t);if(n!==void 0)return{source:"canonical",value:n};if(!e)return;const o=A(e.value);return o===void 0?void 0:{source:"legacy",value:o}}function it(t,e){if(t==="json"||t==="toon")return{source:"canonical",value:t};if(e)return e.flag==="--stream"||e.flag==="--follow"?{source:"legacy",value:"stream"}:e.value==="json"||e.value==="toon"?{source:"legacy",value:e.value}:void 0}function rt(t,e,n){if(!t)return!1;const o=new Set(t.explicit_legacy_aliases);if(t.cli_invocation_observed===!0||t.sdk_invocation_observed===!0)return!o.has(n);const u=new Set(t.canonical_include_modes.map(i=>`--${i.replaceAll("_","-")}`));return e==="include"&&u.has(n)&&!o.has(n)}function oe(t,e,n,o){return t.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||D(M(o,"--no-truncate"))&&!rt(n,"amount","--no-truncate")||e.amount?.flag==="--no-truncate"||e.include?.flag==="--full"||n?.canonical_include_modes.includes("full")===!0}function ue(t,e){return b.flatMap(n=>t[n]?.source==="canonical"||n==="include"&&(e?.canonical_include_modes.length??0)>0?[C[n]]:[])}function st(t,e){const n=I(t,e);if(!n)return;const o=Wt.get(n)??X(n),u=e[N],i={include:g=>nt(void 0,g),amount:g=>ot(void 0,g),cost:g=>ut(void 0,g),encoding:g=>it(void 0,g)},r=Object.fromEntries(b.map(g=>[g,ne(o.dimensions[g],e,y=>i[g](y)!==void 0,y=>rt(u,g,y))])),s=b.flatMap(g=>{const y=r[g];return y?[y.flag]:[]}),d=b.flatMap(g=>{const y=r[g];return y?[o.dimensions[g].legacy_aliases.find(yt=>yt.flag===y.flag).migration_hint]:[]}),f=it(e.outputFormat??e.output_format,r.encoding),l=nt(e.outputInclude??e.output_include,r.include),a=ot(e.outputLimit??e.output_limit,r.amount),p=ut(e.outputBudget??e.output_budget,r.cost),c=oe(t,r,u,e),_=Ut(t,{generateFallback:!0}),O=f?.value==="json"||e.resolvedOutputFormat==="json"?"json":"toon",h=p??(c?{source:"intent",value:"unbounded"}:{source:"default",value:_.default_max_estimated_tokens_by_format[O]});return{command:n,include:l,amount:a,cost:h,encoding:f,canonical_options_used:ue({include:l,amount:a,cost:h,encoding:f},u),legacy_aliases_used:s,migration_hints:d,precedence:J}}function m(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}const F=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]),ie=["collection_counts","notes_count","tests_count"];function at(t,e){const n=new Set(e.map(o=>o.split(".")[0]));return Object.fromEntries(Object.entries(t).filter(([o])=>n.has(o)))}function re(t){const e=m(t.item)?t.item:{},n=[...new Set([...Object.keys(e),...ie.filter(u=>Object.hasOwn(e,u))])].sort((u,i)=>u.localeCompare(i)),o=Object.keys(t).filter(u=>u!=="item"&&u!=="read_output"&&!F.has(u)).sort((u,i)=>u.localeCompare(i));return{item:e,itemFields:n,sections:o,valid:[...n,"item",...n.map(u=>`item.${u}`),...o]}}function se(t,e){const n=re(t),o=e.filter(a=>!n.valid.includes(a));if(o.length>0)throw new R(`Unknown --output-include selector(s) for get: ${o.join(", ")}. Valid selectors: ${n.valid.join(", ")}.`,w.USAGE);const u=e.includes("item"),i=e.flatMap(a=>a.startsWith("item.")?[a.slice(5)]:n.itemFields.includes(a)?[a]:[]).filter((a,p,c)=>c.indexOf(a)===p);if(u&&i.length>0)throw new R("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",w.USAGE);const r=new Set(e.filter(a=>n.sections.includes(a))),s=Object.fromEntries(Object.entries(t).filter(([a])=>F.has(a)||r.has(a)));u?s.item=n.item:i.length>0&&(s.item=at(n.item,i));const d=[...u?[]:i.length>0?n.itemFields.filter(a=>!i.includes(a)).map(a=>({name:`item.${a}`,restore_with:`--output-include item.${a}`})):[{name:"item",restore_with:"--output-include item"}],...n.sections.filter(a=>!r.has(a)).map(a=>({name:a,restore_with:`--output-include ${a}`}))],l=[...m(s.omission_receipt)&&Array.isArray(s.omission_receipt.omitted_field_groups)?s.omission_receipt.omitted_field_groups:[],...d];return s.omission_receipt={has_omissions:l.length>0,omitted_field_group_count:l.length,omitted_field_groups:l},s}function ct(t){let e=0;return H({...t},n=>(m(n)&&Object.keys(n).length>0&&(e+=1),n)),e}function ae(t,e,n,o){if(ct(e)===0||ct(n)>0)return;const u=[...et(t).keys()],i=u.length>0?` Declared ${t} projection modes: ${u.join(", ")}.`:` The ${t} surface declares no projection modes; name row fields instead.`;throw new R(`Unknown --output-include selector(s) for ${t}: ${o.join(", ")}. No selector matched any returned row field.${i}`,w.USAGE)}function ce(t,e,n){if(t==="get")return se(e,n);const o=Nt(e),u=n.flatMap(r=>o.flatMap(s=>r.startsWith(`${s}.`)?[r.slice(s.length+1)]:[])),i=n.some(r=>Object.hasOwn(e,r.split(".")[0])&&!o.some(s=>r.startsWith(`${s}.`)));if(o.length>0&&(!i||u.length>0)){const r={...e},s=u.length>0?u:n,d=H(r,f=>m(f)?at(f,s):f);return ae(t,e,d,s),d}return Object.fromEntries(Object.entries(e).filter(([r])=>n.some(s=>s.split(".")[0]===r)||F.has(r)))}function de(t,e,n,o){if(e==="unbounded")return t;const{result:u,truncated:i}=Pt(t,e,r=>x(n,r));if(!i)return u;if(u.has_more=!0,u.truncated=!0,mt(u,n,[...o.entries()].flatMap(([r,s])=>s.rows>e?[{path:r,total_rows:s.totalRows}]:[])),typeof u.count=="number"){const r=m(u.projection)?u.projection.row_key:void 0;u.count=typeof r=="string"&&Array.isArray(u[r])?u[r].length:K(u)}return typeof u.returned_count=="number"&&(u.returned_count=K(u)),u.applied_bound={kind:"output_limit",source:"explicit",value:e},u}function le(t){return b.filter(e=>t[e]!==void 0&&t[e]?.source!=="default"||t.canonical_options_used.includes(C[e]))}function j(t,e,n,o){let u=W(t,e,o);k(t,u);for(let i=0;i<8;i+=1){const r=n.estimated_tokens,s=u.read_session.spent_this_call_tokens;T(u,n,o);const d=u;u=W(u,e,o),k(d,u);const f=u.read_session.spent_this_call_tokens;if(n.estimated_tokens===r&&f===s)return u}return u}function fe(t,e){if(!m(t.read_output))return t;const n=V(e),o=t.read_output,u=P(e.outputSession??e.output_session);return u===void 0?(T(t,o,n),t):j(t,u,o,n)}function dt(t,e){if(t!=="validate")return e;const n=m(e.projection)?e.projection:void 0;if(!(Array.isArray(n?.declared_field_groups)?n.declared_field_groups:[]).some(a=>m(a)&&a.name==="diagnostic_rows"))return e;const u=[...new Set(Y(e).map(({path:a})=>a).filter(a=>/^checks\.\d+\.details\./u.test(a)))],i=u.filter(a=>!u.some(p=>p!==a&&a.startsWith(`${p}.`)));if(i.length===0)return e;const r=m(e.row_contract)?e.row_contract:{},s=Array.isArray(r.row_keys)?r.row_keys.filter(a=>typeof a=="string"):[],d=Array.isArray(r.continuation_row_keys)?r.continuation_row_keys.filter(a=>typeof a=="string"):[],f=s.length>0?s:i,l=[...new Set(i)];return JSON.stringify(f)===JSON.stringify(s)&&JSON.stringify(l)===JSON.stringify(d)?e:{...e,row_contract:{...r,row_keys:f,continuation_row_keys:l,jq_selector:typeof r.jq_selector=="string"?r.jq_selector:".checks[].details"}}}function pe(t,e){return t.include?.source==="canonical"&&!B(e)}function lt(t,e){let n={...t};return pe(e,t)&&(n=ce(e.command,n,e.include.value)),e.command==="assurance"?Lt(n):n}function _e(t,e){const n=z(e)?.continuationBinding;if(n===void 0)return;const o=lt(dt(t.command,n),t);return new Map(v(o).filter(u=>!x(t.command,u.path)).map(u=>[u.path,u]))}function me(t,e,n,o,u){let i=lt(t,e);U(i,t);const r=_e(e,u);if(i=Dt(i,e.command,o,r),e.command==="history"&&o){const f=["compact_history","provenance_history","history","diff"];if(i=Object.fromEntries(Object.entries(i).filter(([l])=>!f.includes(l)||l===o.path)),m(i.projection)&&(i.projection={...i.projection,row_key:o.path}),m(i.row_contract)){const l=i.row_contract;i.row_contract={...l,row_keys:[o.path],...Array.isArray(l.continuation_row_keys)?{continuation_row_keys:[o.path]}:{}}}i.count=Object.keys(i[o.path]).length}const s=t.count_only===!0?{...i,count_only:!0,count:t.count}:i,d=Ae(i,t,e.command,o,u,r);return e.amount?.source==="canonical"&&(i=de(i,e.amount.value,e.command,d.collectionsBeforeBudget),d.cursorContinuesExistingPage&&Ot(i,d.originalItems,d.cursorSource,!0,d.originalItemOffset)),U(i,s),gt(i,e.command,d),{projected:n===void 0?i:qt(i,n),continuationState:d}}function ge(t,e){return[...t.cost!==void 0&&t.cost.value!=="unbounded"&&(t.cost.source==="canonical"||t.cost.source==="default"||t.command==="context"&&t.cost.source==="legacy")?[{source:t.cost.source,tokens:t.cost.value}]:[],...e===void 0?[]:[{source:"session",tokens:Vt(e)}]].sort((o,u)=>o.tokens-u.tokens)[0]}function ft(t){const e=t.canonical_options_used;return e&&e.length>0?{canonical_options_used:e}:{}}function pt(t,e){return m(t.context_intent)&&t.context_intent.command==="context"&&t.context_intent.token_budget===e&&t.context_intent.within_budget===!0}function Oe(t,e,n){return t.command!=="next"||(e.tokenBudget??e.token_budget)===void 0?!1:!(m(n.context_intent)&&n.context_intent.command==="next"&&n.context_intent.within_budget===!0)}function _t(t,e={}){return t?.source==="default"||t?.source==="legacy"&&!pt(e,t.tokens)?{budget_source:t.source,budget_tokens:t.tokens}:{}}function he(t,e,n,o,u,i){const r={contract_version:1,command:t.command,requested_dimensions:e,..._t(o),precedence:t.precedence,...ft(t),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...n===void 0?{omitted_result_estimated_tokens:u}:{}},s={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:r},d=n===void 0?s:j(s,n,r,i);if(n===void 0&&T(d,r,i),n!==void 0&&r.estimated_tokens>o.tokens)throw new R("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",w.USAGE);return d}function ye(t,e,n){return t.command==="context"&&t.cost?.source==="legacy"&&!pt(n,t.cost.value)||Oe(t,e,n)||e.outputRowContract===!0||e.output_row_contract===!0||t.canonical_options_used.includes("--output-include")||t.command==="list"&&t.canonical_options_used.length>0&&t.include?.value.includes("full")===!0}function we(t,e,n,o,u){if(e!==void 0||B(n)||ye(t,u,n))return!1;if(t.amount?.source==="canonical"&&t.amount.value!=="unbounded"){const i=t.amount.value;if(Mt(n).some(({value:r})=>(Array.isArray(r)?r.length:Object.keys(r).length)>i))return!1}return t.cost===void 0||t.cost.value==="unbounded"||t.cost.source==="legacy"&&t.command!=="context"||xt(u.outputRowContract===!1?Object.fromEntries(Object.entries(n).filter(([i])=>i!=="row_contract")):n,o)<=t.cost.value}function mt(t,e,n){const o=Object.hasOwn(S,e)?S[e]:void 0,u=n.find(i=>o?.paths.includes(i.path));o!==void 0&&u!==void 0&&typeof t[o.total_key]!="number"&&(t[o.total_key]=u.total_rows)}function gt(t,e,n){const o=S[e]?.paths[0];o!==void 0&&$t(t,e,n.producer,n.collectionsBeforeBudget.get(o)?.rows)}function Re(t,e,n,o){const u=n.backward?n.rows-o:n.baseOffset+o;return{path:e,cursor:Bt({command:t,path:e,offset:u,total_rows:n.totalRows,fingerprint:n.fingerprint,...n.backward?{direction:"backward"}:{}}),retained_rows:o,remaining_rows:n.backward?u:n.totalRows-u,total_rows:n.totalRows}}function be(t,e,n,o,u,i,r){if(!n.rows_compacted)return;const s=e.amount?.value==="unbounded"?["amount"]:[],d=new Map(v(t).map(_=>[_.path,Array.isArray(_.value)?_.value.length:Object.keys(_.value).length])),f=[...r.entries()].flatMap(([_,O])=>{const h=d.get(_);return h>=O.rows?[]:[Re(e.command,_,O,h)]}),l=f[0];mt(t,e.command,f);const a=l?"; page --output-cursor":"",p=o.source==="session"?`Truncated by the remaining ${o.tokens}-token session budget; start a new output session with a larger token_budget${a}.`:`${o.tokens}-token: raise --output-budget${a}`;n.migration_hints=[p,...e.migration_hints];const c=vt({effective_budget_tokens:o.tokens,measured_result_tokens:i});l&&!u&&(typeof t.next_cursor!="string"||t.continuation_kind==="output_cursor")&&(t.next_cursor=l.cursor),t.continuation_kind=u?"producer_cursor":l?"output_cursor":"none",t.output_budget_truncation={reason:"output_budget_reached",budget_source:o.source,budget_tokens:o.tokens,overridden_dimensions:s,compacted_row_paths:n.compacted_row_paths,continuation_cursor_rebased:u,continuation_available:f.length>0,recovery_budget_multiplier:l?1:c.recovery_budget_multiplier,continuations:f,restore_with:l?"recovery":`Retry with --output-budget ${c.output_budget} because no declared row collection can be continued.`,recovery:l?{cursor:l.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${c.output_budget}`,sdk:{outputBudget:c.output_budget},mcp:{outputBudget:c.output_budget}}}}function Ot(t,e,n,o,u){if(typeof n!="string"||!Array.isArray(t.items))return!1;const i=t.items.length,r=e.length;if(i===0||i>=r)return!1;let s;try{s=zt(n)}catch{return!1}const d=s.after_index;if(d===void 0)return!1;const f=e[i-1];if(Object.prototype.toString.call(f)!=="[object Object]")return!1;const l=Reflect.get(f,"id");if(typeof l!="string"||l.length===0)return!1;const a=o?d-(r-i):d+u+i;return a<0?!1:(t.next_cursor=Kt(s.fingerprint,l,a,s.snapshot),!0)}function ht(t){return Array.isArray(t)?t.length:Object.keys(t).length}function Ae(t,e,n,o,u,i){const r=new Map(v(t).map(f=>{const l=ht(f.value),a=o?.path===f.path,p=x(n,f.path),c=i?.get(f.path)??f;let _;return[f.path,{rows:l,totalRows:a?o.total_rows:ht(c.value),baseOffset:a&&!p?o.offset:0,backward:p,get fingerprint(){return _??=a?o.fingerprint:Gt(f.path,c.value,n),_}}]})),s=typeof t.next_cursor=="string",d=o?.path==="items"?o.offset:0;return{collectionsBeforeBudget:r,originalItems:Array.isArray(e.items)?d>0?e.items.slice(d):e.items:[],originalItemOffset:d,cursorContinuesExistingPage:s,cursorSource:s?t.next_cursor:u.after,producer:e}}function Ce(t,e,n,o,u,i,r,s,d,f){const l={...e,count_only:n},a=o.command==="assurance"&&Array.isArray(t.assertions)?t.assertions.filter(c=>m(c)&&c.verdict!=="pass").length:0,p=new Map;if(a>0&&p.set("assertions",a),o.command==="history"&&Array.isArray(t.diff))for(const c of Y(t))c.path.startsWith("diff.")&&p.set(c.path,Object.keys(c.value).length);return St(t,u,i.tokens,p,f,c=>{U(c,l),gt(c,o.command,s);const _=Ot(c,s.originalItems,s.cursorSource,s.cursorContinuesExistingPage,s.originalItemOffset);if(be(c,o,u,i,_,d,s.collectionsBeforeBudget),o.command==="history"&&m(c.projection)){c.has_more=typeof c.next_cursor=="string"||c.applied_bound?.kind==="output_limit";const O=c.projection.row_key;typeof O=="string"&&Array.isArray(c[O])&&(c.count=c[O].length)}r!==void 0&&Object.assign(c,j(c,r,u,f))},o.command==="history"&&Array.isArray(t.diff),c=>x(o.command,c),o.command)}function Xe(t,e,n){const o=st(t,e);if(!o)return n;const u=V(e),i=P(e.outputSession??e.output_session),r=e.outputCursor??e.output_cursor,s=typeof r=="string"?Ft(r):void 0,d=le(o),f=dt(o.command,n);if(s===void 0&&we(o,i,f,u,e))return f;const l=ge(o,i),a=me(f,o,i,s,e);let p=a.projected;k(p,p,e.outputRowContract===!1);const c=B(p),_={contract_version:1,command:o.command,requested_dimensions:d,..._t(l,p),precedence:o.precedence,...ft(o),legacy_aliases_used:o.legacy_aliases_used,migration_hints:o.migration_hints,estimated_tokens:0,within_budget:!c,strings_compacted:!1,rows_compacted:!1,result_omitted:c};p.read_output=_;const O=z(e)?.mirrorEstimate;if(O!==void 0&&jt(_,O),p=i===void 0?p:j(p,i,_,u),T(p,_,u),l!==void 0&&_.estimated_tokens>l.tokens){const h=It(o.command,e,p);h!==void 0&&(_.applied_depth="brief",_.degradation_reason="output_budget_reached",k(p,h),p=fe(h,e)),_.estimated_tokens>l.tokens&&(p=Ce(p,p,f.count_only===!0,o,_,l,i,a.continuationState,_.estimated_tokens,u))}return l!==void 0&&_.estimated_tokens>l.tokens?he(o,d,i,l,_.estimated_tokens,u):p}function Ee(t){return m(t)&&m(t.context_intent)&&t.context_intent.result_omitted===!0}function B(t){return ke(t)||Ee(t)}function ke(t){return m(t)&&m(t.output_budget_exceeded)&&t.output_budget_exceeded.omitted_result===!0&&t.output_budget_exceeded.reason==="requested_budget_infeasible"}function Qe(t,e){const n=e.outputFormat??e.output_format;if(n==="json"||n==="toon")return n;const o=st(t,e)?.encoding;return o?.value==="json"||o?.value==="toon"?o.value:void 0}export{Ve as PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,rn as PM_READ_OUTPUT_CONTINUATION_FINGERPRINT_POLICIES,b as PM_READ_OUTPUT_DIMENSIONS,qe as PM_READ_OUTPUT_OPTION_FLAGS,fn as PM_READ_OUTPUT_SURFACES,Yt as PM_READ_OUTPUT_SURFACE_CONTRACTS,cn as PM_READ_OUTPUT_TAIL_RETENTION_POLICIES,Ke as READ_OUTPUT_MUTATION_CONFLICT_CODE,He as READ_OUTPUT_SHAPING_CONTROL_FLAGS,ze as READ_OUTPUT_SURFACE_UNSUPPORTED_CODE,Ye as annotationPositionalMutationOptions,Xe as applyReadOutputDimensions,ee as applyReadOutputIncludeModes,on as decodeReadOutputContinuationCursor,un as encodeReadOutputContinuationCursor,ke as isReadOutputBudgetExceeded,B as isReadResultOmittedForBudget,Je as normalizeReadOutputIncludeModeOptions,sn as readOutputCollectionFingerprint,et as readOutputIncludeModeOptions,dn as readOutputRetainsTail,st as resolveReadOutputDimensions,Qe as resolveReadOutputEncoding,en as resolveReadOutputRecoveryBudget,I as resolveReadOutputSurface,fe as stabilizeReadOutputReceiptEstimates,We as validateReadOutputOptions};
2
2
  //# sourceMappingURL=read-output-contracts.js.map
@@ -0,0 +1,2 @@
1
+ import{constants as o}from"node:fs";import{open as _}from"node:fs/promises";import l from"node:path";import{DEFAULT_RUNTIME_SCHEMA_FILE_PATHS as f,filePathForSchemaSection as c,inspectRuntimeFieldDefinition as u,readFieldsFromSchemaFile as g}from"../../core/schema/runtime-schema.js";import{getSettingsPath as y}from"../../core/store/paths.js";import{validateSettings as F}from"../../core/store/settings-validator.js";async function m(e){try{const i=await _(e,o.O_RDONLY|o.O_NONBLOCK);try{return(await i.stat()).isFile()?JSON.parse(await i.readFile("utf8")):void 0}finally{await i.close()}}catch{return}}function v(e){const i=F(e);return i.success?i.data.schema:void 0}async function w(e,i){const t=c(e,i?.files?.fields,f.fields);return g(await m(t))??[]}function p(e,i){return i.flatMap((t,a)=>{const{loss:n}=u(t);if(n.dropped===void 0&&n.ignored.length===0)return[];const d=t?.key;return[{source:e,index:a,key:typeof d=="string"?d:null,...n.dropped===void 0?{}:{dropped:n.dropped},...n.ignored.length===0?{}:{ignored:n.ignored}}]})}async function E(e,i,t){const a=v(await m(y(e))),n=a?.files===void 0?i:a,d=c(e,n.files?.fields,f.fields),s=[...p("settings.json",a?.fields??[]),...p(l.relative(e,d).split(l.sep).join("/"),await w(e,n))];if(s.length===0)return{details:{},warnings:[]};const r=s.filter(h=>h.dropped!==void 0).length;return{details:{schema_field_definition_loss_count:s.length,schema_field_definition_losses:s.slice(0,t),schema_field_definition_losses_truncated:s.length>t,schema_field_definition_loss_fix_hint:"A dropped definition registers no option and a field read in part ignores the listed members. Re-register a file-backed field with valid values: pm schema add-field <key> --cli-flag <flag> --alias <alias> --commands <commands>. add-field replaces the type, commands, description, flag, aliases and requirement settings it is given but keeps value_schema, metadata_key, front_matter_key and repeatable, so edit or remove those members in the fields file. Edit or remove an entry stored inline in settings.json there."},warnings:[...r>0?[`validate_schema_field_definition_dropped:${r}`]:[],...s.length>r?[`validate_schema_field_definition_partial:${s.length-r}`]:[]]}}export{w as readFieldsFileDefinitions,E as scanFieldDefinitionLosses};
2
+ //# sourceMappingURL=field-definition-losses.js.map
@@ -1,2 +1,2 @@
1
- import{GLOBAL_FLAG_CONTRACTS as y,resolveSubcommandFlagContractsForCommand as k}from"../cli-contracts/flag-contracts.js";import{BUILTIN_FIELD_KEYS as w}from"../../core/schema/fields-file.js";import{EXIT_CODE as d,ITEM_METADATA_KEY_ORDER as A}from"../../core/shared/constants.js";import{PmCliError as m}from"../../core/shared/errors.js";import{commanderOptionAttribute as F,resolveCandidateOptionKeys as C}from"../../core/schema/runtime-field-values.js";import{normalizeCliToken as S,resolveRuntimeFieldRegistry as p}from"../../core/schema/runtime-schema.js";import{describeFieldFlagSpellingDefect as v,isShortFieldFlagSpelling as s}from"./field-flag-spelling.js";function g(e){return e.trim().toLowerCase().replace(/^-+/u,"")}function _(e){const o=g(e),i=C({key:o,cli_flag:o,cli_aliases:[]});return[...new Set([...i,F(o)])]}const E=new Set(A.filter(e=>!w.has(e))),O={flag:"--help",short:"-h"},h=new Map;function x(e){let o=h.get(e);if(o===void 0){const i=new Map,n=new Map;for(const l of[...k(e),...y,O]){for(const a of[l.flag,...l.aliases??[]].flatMap(_))i.has(a)||i.set(a,l.flag);l.short!==void 0&&!n.has(l.short)&&n.set(l.short,l.flag)}o={long:i,short:n},h.set(e,o)}return o}function $(e,o){return s(e)?o.short.get(e.trim()):_(e).map(i=>o.long.get(i)).find(i=>i!==void 0)}function r(e){const o=[];for(const i of e){const n=[...new Set([i.cli_flag,...i.cli_aliases,i.key].map(l=>s(l)?l.trim():g(l)))];for(const l of i.commands)o.push(...b(i.key,n,l.replaceAll("_","-")))}return o.sort((i,n)=>i.field.localeCompare(n.field)||i.command.localeCompare(n.command)||i.option.localeCompare(n.option))}function b(e,o,i){const n=x(i),l=new Map;for(const a of o){if(E.has(e)&&a.replaceAll("-","_")===e)continue;const t=$(a,n);t===void 0||l.has(t)||l.set(t,{field:e,command:i,field_flag:s(a)?a:`--${a.replaceAll("_","-")}`,option:t})}return[...l.values()]}function T(e){return r([{key:e.key,cli_flag:e.cliFlag??e.key.replaceAll("_","-"),cli_aliases:e.cliAliases,commands:e.commands}])}function c(e){return e.flatMap(o=>[...new Set([o.cli_flag,...o.cli_aliases])].flatMap(i=>{const n=v(i);return n===void 0?[]:[{field:o.key,spelling:i,reason:n}]}))}function D(e){return c([{key:e.key,cli_flag:e.cliFlag??e.key.replaceAll("_","-"),cli_aliases:e.cliAliases}])}function I(e){return`${JSON.stringify(e.spelling)} ${e.reason}`}function M(e){return`${e.field_flag} shadows built-in ${e.option} on pm ${e.command}`}function U(e,o){const i=p(e).definitions,n=r(i),l=c(i),a=l.length===0?{details:{},warnings:[]}:{details:{schema_field_flag_invalid_count:l.length,schema_field_flag_invalid:l.slice(0,o),schema_field_flag_invalid_truncated:l.length>o,schema_field_flag_invalid_fix_hint:"Re-register the field with one flag and one spelling per alias: pm schema add-field <key> --cli-flag <flag> --alias <alias>. A short alias is one dash and one character. Edit a field defined inline in settings.json there."},warnings:[`validate_schema_field_flag_invalid:${l.length}`]};return n.length===0?a:{details:{...a.details,schema_field_option_collision_count:n.length,schema_field_option_collisions:n.slice(0,o),schema_field_option_collisions_truncated:n.length>o,schema_field_option_collision_fix_hint:"Rename a file-backed field without losing item values: pm schema rename-field <key> --to <new-key>. For a colliding flag, alias or command list, re-register the same key: pm schema add-field <key> --cli-flag <flag> --commands <commands>. Edit a field defined inline in settings.json there."},warnings:[...a.warnings,`validate_schema_field_option_collision:${n.length}`]}}function Y(e){f(e.key,D(e)),u(e.key,e.commands,T(e))}function q(e){const o=[e.cli_flag,...Array.isArray(e.cli_aliases)?e.cli_aliases:[]].filter(n=>typeof n=="string");f(e.key,o.filter(n=>S(n).length===0).map(n=>({field:e.key,spelling:n,reason:"is empty"})));const i=p({fields:[e]}).definitions;f(e.key,c(i)),u(e.key,i.flatMap(n=>n.commands),r(i))}function f(e,o){if(o.length!==0)throw new m(`Cannot define custom field "${e}": flag ${o.map(I).join("; ")}. The command it is registered for could not register it as one option.`,d.USAGE,{code:"schema_field_flag_invalid",field:e,flag:o[0].spelling,required:"Each custom field flag and alias must be one option spelling: a long name without spaces, pipes, commas, '=' or brackets, or a short flag of one dash and one character.",nextSteps:[`Pass one spelling per --alias, for example pm schema add-field ${e} --alias <first> --alias <second>.`]})}function u(e,o,i){if(i.length===0)return;const n={key:e,commands:o},l=new Set(i.map(t=>t.command)),a=n.commands.filter(t=>!l.has(t.replaceAll("_","-")));throw new m(`Cannot define custom field "${n.key}": ${i.map(M).join("; ")}. The built-in option would stop working for that command.`,d.USAGE,{code:"schema_field_option_collision",field:n.key,flag:i[0].option,required:"A custom field's key, flag and aliases must differ from every built-in option of each command it is registered for.",nextSteps:[`Rename the field with a project-specific prefix, for example pm schema add-field project_${n.key}.`,...a.length>0?[`Or register "${n.key}" only where its option is free: --commands ${a.join(",")}.`]:[]]})}export{q as assertFieldDefinitionOptionsAvailable,Y as assertFieldOptionsAvailable,I as describeFieldFlagSpellingDefectLine,M as describeFieldOptionCollision,D as resolveAddFieldFlagSpellingDefects,T as resolveAddFieldOptionCollisions,c as resolveFieldFlagSpellingDefects,r as resolveFieldOptionCollisions,U as scanFieldOptionCollisions};
1
+ import{GLOBAL_FLAG_CONTRACTS as F,resolveSubcommandFlagContractsForCommand as w}from"../cli-contracts/flag-contracts.js";import{BUILTIN_FIELD_KEYS as C}from"../../core/schema/fields-file.js";import{EXIT_CODE as m,ITEM_METADATA_KEY_ORDER as S}from"../../core/shared/constants.js";import{PmCliError as p}from"../../core/shared/errors.js";import{commanderOptionAttribute as v,resolveCandidateOptionKeys as E}from"../../core/schema/runtime-field-values.js";import{normalizeCliToken as O,resolveRuntimeFieldRegistry as g}from"../../core/schema/runtime-schema.js";import{describeFieldFlagSpellingDefect as x,isShortFieldFlagSpelling as r}from"./field-flag-spelling.js";function _(e){return e.trim().toLowerCase().replace(/^-+/u,"")}function u(e){const n=_(e),i=E({key:n,cli_flag:n,cli_aliases:[]});return[...new Set([...i,v(n)])]}const $=new Set(S.filter(e=>!C.has(e))),h={flag:"--help",short:"-h"},y=new Map;function b(e){let n=y.get(e);if(n===void 0){const i=new Map,o=new Map;for(const l of[...w(e),...F,h]){for(const t of[l.flag,...l.aliases??[]].flatMap(u))i.has(t)||i.set(t,l.flag);l.short!==void 0&&!o.has(l.short)&&o.set(l.short,l.flag)}n={long:i,short:o},y.set(e,n)}return n}function D(e,n){return r(e)?n.short.get(e.trim()):u(e).map(i=>n.long.get(i)).find(i=>i!==void 0)}function c(e){const n=[];for(const i of e){const o=a=>r(a)?a.trim():_(a),l=[...new Set([i.cli_flag,...i.cli_aliases].map(o))],t=o(i.key);for(const a of i.commands)n.push(...T(i.key,l,l.includes(t)?void 0:t,a.replaceAll("_","-")))}return n.sort((i,o)=>i.field.localeCompare(o.field)||i.command.localeCompare(o.command)||i.option.localeCompare(o.option))}function T(e,n,i,o){const l=b(o),t=new Map;for(const a of i===void 0?n:[...n,i]){if($.has(e)&&a.replaceAll("-","_")===e)continue;const s=D(a,l);s===void 0||t.has(s)||a===i&&s===h.flag||t.set(s,{field:e,command:o,field_flag:r(a)?a:`--${a.replaceAll("_","-")}`,option:s})}return[...t.values()]}function I(e){return c([{key:e.key,cli_flag:e.cliFlag??e.key.replaceAll("_","-"),cli_aliases:e.cliAliases,commands:e.commands}])}function f(e){return e.flatMap(n=>[...new Set([n.cli_flag,...n.cli_aliases])].flatMap(i=>{const o=x(i);return o===void 0?[]:[{field:n.key,spelling:i,reason:o}]}))}function M(e,n){return[...k(e.key,n?.cliFlag,n?.aliases),...f([{key:e.key,cli_flag:e.cliFlag??e.key.replaceAll("_","-"),cli_aliases:e.cliAliases}])]}function L(e){return`${JSON.stringify(e.spelling)} ${e.reason}`}function R(e){return`${e.field_flag} shadows built-in ${e.option} on pm ${e.command}`}function q(e,n){const i=g(e).definitions,o=c(i),l=f(i),t=l.length===0?{details:{},warnings:[]}:{details:{schema_field_flag_invalid_count:l.length,schema_field_flag_invalid:l.slice(0,n),schema_field_flag_invalid_truncated:l.length>n,schema_field_flag_invalid_fix_hint:"Re-register the field with one flag and one spelling per alias: pm schema add-field <key> --cli-flag <flag> --alias <alias>. A short alias is one dash and one character. Edit a field defined inline in settings.json there."},warnings:[`validate_schema_field_flag_invalid:${l.length}`]};return o.length===0?t:{details:{...t.details,schema_field_option_collision_count:o.length,schema_field_option_collisions:o.slice(0,n),schema_field_option_collisions_truncated:o.length>n,schema_field_option_collision_fix_hint:"Rename a file-backed field without losing item values: pm schema rename-field <key> --to <new-key>. For a colliding flag, alias or command list, re-register the same key: pm schema add-field <key> --cli-flag <flag> --commands <commands>. Edit a field defined inline in settings.json there."},warnings:[...t.warnings,`validate_schema_field_option_collision:${o.length}`]}}function z(e,n){d(e.key,M(e,n)),A(e.key,e.commands,I(e))}function k(e,n,i){return[n,...Array.isArray(i)?i:[]].filter(o=>typeof o=="string"&&O(o).length===0).map(o=>({field:e,spelling:o,reason:"is empty"}))}function H(e){d(e.key,k(e.key,e.cli_flag,e.cli_aliases));const n=g({fields:[e]}).definitions;d(e.key,f(n)),A(e.key,n.flatMap(i=>i.commands),c(n))}function d(e,n){if(n.length!==0)throw new p(`Cannot define custom field "${e}": flag ${n.map(L).join("; ")}. The command it is registered for could not register it as one option.`,m.USAGE,{code:"schema_field_flag_invalid",field:e,flag:n[0].spelling,required:"Each custom field flag and alias must be one option spelling: a long name without spaces, pipes, commas, '=' or brackets, or a short flag of one dash and one character.",nextSteps:[`Pass one spelling per --alias, for example pm schema add-field ${e} --alias <first> --alias <second>.`]})}function A(e,n,i){if(i.length===0)return;const o={key:e,commands:n},l=new Set(i.map(a=>a.command)),t=o.commands.filter(a=>!l.has(a.replaceAll("_","-")));throw new p(`Cannot define custom field "${o.key}": ${i.map(R).join("; ")}. The built-in option would stop working for that command.`,m.USAGE,{code:"schema_field_option_collision",field:o.key,flag:i[0].option,required:"A custom field's key, flag and aliases must differ from every built-in option of each command it is registered for.",nextSteps:[`Rename the field with a project-specific prefix, for example pm schema add-field project_${o.key}.`,...t.length>0?[`Or register "${o.key}" only where its option is free: --commands ${t.join(",")}.`]:[]]})}export{H as assertFieldDefinitionOptionsAvailable,z as assertFieldOptionsAvailable,L as describeFieldFlagSpellingDefectLine,R as describeFieldOptionCollision,M as resolveAddFieldFlagSpellingDefects,I as resolveAddFieldOptionCollisions,f as resolveFieldFlagSpellingDefects,c as resolveFieldOptionCollisions,q as scanFieldOptionCollisions};
2
2
  //# sourceMappingURL=field-option-collisions.js.map
@@ -1,8 +1,8 @@
1
- import{assertInitializedTracker as Se}from"./environment/tracker-preflight.js";import $e from"node:path";import{mkdir as ve}from"node:fs/promises";import{resolveAuthor as T}from"../core/shared/author.js";import{pathExists as Ee,readFileIfExists as k}from"../core/fs/fs-utils.js";import{writeWorkspaceJsonWithHistory as ke}from"../core/history/workspace-history.js";import{acquireLock as x}from"../core/lock/lock.js";import{refreshMergeAttributeFenceIfInstalled as Ae}from"./merge/install.js";import{assertAliasesAvailable as Re,assertTypeFolderAvailable as be,escapeForDoubleQuotes as N,normalizeAddTypeInput as ae,parseItemTypesFile as D,removeItemType as Fe,serializeItemTypesFile as B,upsertItemType as X}from"../core/schema/item-types-file.js";import{assertStatusTokensAvailable as ne,BUILTIN_STATUS_IDS as re,normalizeAddStatusInput as Ie,normalizeStatusToken as C,parseStatusDefsFile as ie,removeStatusDef as Te,serializeStatusDefsFile as ce,upsertStatusDef as xe}from"../core/schema/status-defs-file.js";import{normalizeAddFieldInput as Ce,normalizeFieldKey as V,parseFieldsFile as le,removeField as Le,serializeFieldsFile as ue,upsertField as Ue}from"../core/schema/fields-file.js";import{normalizeTypePresetName as Pe,resolveTypePresetDefinitions as me,TYPE_PRESET_NAMES as je}from"../core/schema/type-presets.js";import{inferTypesFromTitles as qe}from"../core/schema/type-inference.js";import{DEFAULT_RUNTIME_SCHEMA_FILE_PATHS as G,filePathForSchemaSection as O,normalizeRuntimeSchemaSettings as A,resolveRuntimeFieldRegistry as Z,resolveRuntimeStatusRegistry as K}from"../core/schema/runtime-schema.js";import{normalizeItemTypeFolder as Ne,resolveItemTypeRegistry as H,toDefaultFolder as Ge}from"../core/item/type-registry.js";import{listAllItemMetadataLight as W}from"../core/store/item-store.js";import{EXIT_CODE as h}from"../core/shared/constants.js";import{PmCliError as y}from"../core/shared/errors.js";import{nowIso as S}from"../core/shared/time.js";import{getActiveExtensionRegistrations as j,runActiveOnWriteHooks as R}from"../core/extensions/index.js";import{resolvePmRoot as b}from"../core/store/paths.js";import{readSettings as F,resolveGovernanceKnobs as L}from"../core/store/settings.js";import{assertFieldOptionsAvailable as Oe}from"./schema/field-option-collisions.js";import{resolvePmToolCustomFieldCollision as He}from"./cli-contracts/tool-schema.js";import{WORKFLOW_POLICY_ACTIONS as ze}from"./governance/workflow-policy.js";export*from"./governance/workflow-policy.js";const At=[...ze,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"];import{formatSchemaEvolutionMigrationHuman as ss,runSchemaEvolutionMigration as os}from"./schema-migration.js";import{planSchemaEvolutionMigration as ns}from"./schema-migration.js";const Y="schema-types",pe="schema-statuses",fe="schema-fields";function U(e){return ke({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function Rt(e,t,o){const s=b(process.cwd(),o.path);await I(s);let a;try{a=ae({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(d){throw new y(d instanceof Error?d.message:String(d),h.USAGE)}const n=await F(s),c=A(n.schema),r=O(s,c.files.types,G.types),m=[],p=T(t.author,n.author_default),g=L(n),l=await x(s,Y,n.locks.ttl_seconds,p,!!t.force,g.force_required_for_stale_lock,n.locks.wait_ms);let f;try{const d=await k(r);let i;try{i=D(d)}catch(u){throw new y(u instanceof Error?u.message:String(u),h.GENERIC_FAILURE)}try{Re(a,i);const u=new Map,w=H(n,j());for(const[$,v]of Object.entries(w.type_to_folder)){const _=v.trim().toLowerCase();_.length>0&&!u.has(_)&&u.set(_,$)}be(a,i,u)}catch(u){throw new y(u instanceof Error?u.message:String(u),h.USAGE)}f=X(i,a),f.replaced&&f.previousName!==void 0&&f.previousName!==f.definition.name&&m.push(`type_recased:${f.previousName}->${f.definition.name}`),await U({pmRoot:s,filePath:r,raw:B(f.file),op:"schema:add-type",author:p,settings:n}),await te(s,[f.definition],m,"schema:add-type-folder"),m.push(...await R({path:r,scope:"project",op:"schema:add-type"}))}finally{await l()}return await de(s,m),{action:"add-type",registered:!0,replaced:f.replaced,type:f.definition,file:{path:r,definitions:f.file.definitions.length},warnings:P(m),generated_at:S()}}async function I(e){await Se(e)}async function de(e,t){try{const o=await Ae(e);o.status==="refreshed"?t.push("merge_fence_refreshed"):o.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function P(e){return[...new Set(e)].sort((t,o)=>t.localeCompare(o))}async function De(e,t,o,s){const a=H(t,j()),n=s.trim().toLowerCase();return(await W(e,t.item_format,a.type_to_folder,[],o)).filter(r=>typeof r.type=="string"&&r.type.toLowerCase()===n).length}async function Me(e,t,o,s){const a=H(t,j()),n=K(o),c=C(s);return(await W(e,t.item_format,a.type_to_folder,[],o)).filter(m=>{const p=typeof m.status=="string"?m.status:"";return(n.alias_to_id.get(C(p))??C(p))===c}).length}async function Be(e,t,o,s,a){if(a.length===0||re.has(a))return;const n=await Me(t,o,s,a);n>0&&e.push(`items_using_status:${n}`);const c=he(s.workflow,a);c.length>0&&e.push(`status_referenced_by_workflow:${c.join(",")}`)}function he(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,s])=>s!==void 0&&C(s)===t).map(([s])=>s)}async function bt(e,t,o){const s=b(process.cwd(),o.path);await I(s);const a=await F(s),n=A(a.schema),c=O(s,n.files.types,G.types),r=[],m=T(t.author,a.author_default),p=L(a),g=await x(s,Y,a.locks.ttl_seconds,m,!!t.force,p.force_required_for_stale_lock,a.locks.wait_ms);let l;try{const f=await k(c);let d;try{d=D(f)}catch(i){throw new y(i instanceof Error?i.message:String(i),h.GENERIC_FAILURE)}try{l=Fe(d,e)}catch(i){throw new y(i instanceof Error?i.message:String(i),h.USAGE)}if(l.removed){const i=(l.definition?.name??e??"").trim();if(i.length>0){const u=await De(s,a,n,i);u>0&&r.push(`items_using_type:${u}`)}await U({pmRoot:s,filePath:c,raw:B(l.file),op:"schema:remove-type",author:m,settings:a}),r.push(...await R({path:c,scope:"project",op:"schema:remove-type"}))}}finally{await g()}return l.removed&&await de(s,r),{action:"remove-type",removed:l.removed,...l.definition?{type:l.definition}:{},file:{path:c,definitions:l.file.definitions.length},warnings:P(r),generated_at:S()}}function ee(e,t){return O(e,t.files.statuses,G.statuses)}function J(e,t){return O(e,t.files.fields,G.fields)}function ye(e,t){return O(e,t.files.types,G.types)}async function te(e,t,o,s){for(const a of t){const n=Ne(a.folder??Ge(a.name)),c=$e.join(e,n);await Ee(c)||(await ve(c,{recursive:!0}),o.push(...await R({path:c,scope:"project",op:s})))}}function se(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function Ke(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function We(e){const t=new Map;for(const o of e){const s=C(o.id);if(s.length!==0){t.set(s,s);for(const a of Array.isArray(o.aliases)?o.aliases:[]){const n=C(a);n.length>0&&!t.has(n)&&t.set(n,s)}}}return t}async function Ft(e,t,o){const s=b(process.cwd(),o.path);await I(s);let a;try{a=Ie({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(w){throw new y(w instanceof Error?w.message:String(w),h.USAGE)}const n=await F(s),c=A(n.schema),r=ee(s,c),m=K(c);try{ne(a,m.alias_to_id)}catch(w){throw new y(w instanceof Error?w.message:String(w),h.USAGE)}const p=Ke(m.by_id.get(a.id));if((a.roles??p?.roles??[]).length===0)throw new y(`Status "${a.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,h.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${N(a.id)}" --role active`,`pm schema add-status "${N(a.id)}" --role blocked`]});const l=[],f=T(t.author,n.author_default),d=L(n),i=await x(s,pe,n.locks.ttl_seconds,f,!!t.force,d.force_required_for_stale_lock,n.locks.wait_ms);let u;try{const w=await k(r);let $;try{$=ie(w)}catch(_){throw new y(_ instanceof Error?_.message:String(_),h.GENERIC_FAILURE)}const v=We($.statuses);try{ne(a,v)}catch(_){throw new y(_ instanceof Error?_.message:String(_),h.USAGE)}u=xe($,a,p),await U({pmRoot:s,filePath:r,raw:ce(u.file),op:"schema:add-status",author:f,settings:n}),l.push(...await R({path:r,scope:"project",op:"schema:add-status"}))}finally{await i()}return{action:"add-status",registered:!0,replaced:u.replaced,status:u.definition,file:{path:r,statuses:u.file.statuses.length},warnings:P(l),generated_at:S()}}async function It(e,t,o){const s=b(process.cwd(),o.path);await I(s);const a=await F(s),n=A(a.schema),c=ee(s,n),r=[],m=T(t.author,a.author_default),p=L(a),g=await x(s,pe,a.locks.ttl_seconds,m,!!t.force,p.force_required_for_stale_lock,a.locks.wait_ms);let l;try{const f=await k(c);let d;try{d=ie(f)}catch(i){throw new y(i instanceof Error?i.message:String(i),h.GENERIC_FAILURE)}try{l=Te(d,e)}catch(i){throw new y(i instanceof Error?i.message:String(i),h.USAGE)}if(l.removed){const i=C(l.definition?.id??e);await Be(r,s,a,n,i),await U({pmRoot:s,filePath:c,raw:ce(l.file),op:"schema:remove-status",author:m,settings:a}),r.push(...await R({path:c,scope:"project",op:"schema:remove-status"}))}}finally{await g()}return{action:"remove-status",removed:l.removed,...l.definition?{status:l.definition}:{},file:{path:c,statuses:l.file.statuses.length},warnings:P(r),generated_at:S()}}function we(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function Ye(e,t,o){return{...we(e),source:t,...o?{extension:o}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function _e(e){return{id:e.id,source:re.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function ge(e,t,o){const s=e.toLowerCase();return o.has(s)?"extension":t.has(s)?"custom":"builtin"}function Je(){const e=new Map,t=j();for(const o of t?.item_types??[]){const s=o.types;if(Array.isArray(s))for(const a of s){if(typeof a!="object"||a===null||Array.isArray(a))continue;const n=a.name;typeof n=="string"&&n.trim().length>0&&e.set(n.trim().toLowerCase(),{layer:o.layer,name:o.name})}}return e}function Qe(e){const t=K(e),o=[],s=[];for(const a of t.definitions){const n=_e(a);n.source==="builtin"?o.push(n):s.push(n)}return{builtin:o,custom:s}}async function M(e){const t=b(process.cwd(),e.path);await I(t);const o=await F(t),s=A(o.schema),a=O(t,s.files.types,G.types),n=ee(t,s),c=H(o,j()),r=Je(),m=new Set((o.item_types?.definitions??[]).map(p=>p.name.trim().toLowerCase()).filter(p=>p.length>0&&!r.has(p)));return{pmRoot:t,typesPath:a,statusesPath:n,byType:c.by_type,customNames:m,extensionProvenance:r,schema:s}}async function Tt(e){const t=await M(e),o=[],s=[],a=[];for(const r of Object.values(t.byType).sort((m,p)=>m.name.localeCompare(p.name))){const m=ge(r.name,t.customNames,new Set(t.extensionProvenance.keys())),p=we(r);m==="extension"?a.push(p):m==="custom"?s.push(p):o.push(p)}const n=Qe(t.schema),c=Z(t.schema).definitions.map(se);return{action:"list",builtin:o,custom:s,extension:a,counts:{builtin:o.length,custom:s.length,extension:a.length,total:o.length+s.length+a.length},statuses:{builtin:n.builtin,custom:n.custom,counts:{builtin:n.builtin.length,custom:n.custom.length,total:n.builtin.length+n.custom.length}},fields:{custom:c,counts:{total:c.length}},file:{path:t.typesPath},generated_at:S()}}async function xt(e,t){const o=(e??"").trim();if(o.length===0)throw new y("Type name must not be empty.",h.USAGE);const s=await M(t),a=Object.values(s.byType).find(n=>n.name.toLowerCase()===o.toLowerCase()||n.aliases.some(c=>c.toLowerCase()===o.toLowerCase()));if(!a)throw new y(`Unknown item type "${o}". Run pm schema list to inspect registered types, or pm schema add-type "${N(o)}" to register it.`,h.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:Ye(a,ge(a.name,s.customNames,new Set(s.extensionProvenance.keys())),s.extensionProvenance.get(a.name.toLowerCase())),file:{path:s.typesPath},generated_at:S()}}async function Ct(e,t){const o=C(e);if(o.length===0)throw new y("Status id must not be empty.",h.USAGE);const s=await M(t),a=K(s.schema),n=a.alias_to_id.get(o)??o,c=a.by_id.get(n);if(!c)throw new y(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${N(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:_e(c),file:{path:s.statusesPath},generated_at:S()}}async function Lt(e,t,o){const s=b(process.cwd(),o.path);await I(s);let a;try{a=Ce({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(i){throw new y(i instanceof Error?i.message:String(i),h.USAGE)}Oe(a);const n=await F(s),c=A(n.schema),r=J(s,c),m=[],p=He(a.key);p&&m.push(`custom_field_mcp_input_collision:${p.field}:${p.property}:${p.owner}:use=${p.nested_path}`);const g=T(t.author,n.author_default),l=L(n),f=await x(s,fe,n.locks.ttl_seconds,g,!!t.force,l.force_required_for_stale_lock,n.locks.wait_ms);let d;try{const i=await k(r);let u;try{u=le(i)}catch(w){throw new y(w instanceof Error?w.message:String(w),h.GENERIC_FAILURE)}d=Ue(u,a),await U({pmRoot:s,filePath:r,raw:ue(d.file),op:"schema:add-field",author:g,settings:n}),m.push(...await R({path:r,scope:"project",op:"schema:add-field"}))}finally{await f()}return{action:"add-field",registered:!0,replaced:d.replaced,field:d.definition,file:{path:r,fields:d.file.fields.length},warnings:P(m),generated_at:S()}}async function Xe(e,t,o,s){const a=H(t,j());return(await W(e,t.item_format,a.type_to_folder,[],o)).filter(c=>{const r=c[s];return r==null?!1:Array.isArray(r)?r.length>0:typeof r=="string"?r.trim().length>0:!0}).length}async function Ut(e,t,o){const s=b(process.cwd(),o.path);await I(s);const a=await F(s),n=A(a.schema),c=J(s,n),r=[],m=T(t.author,a.author_default),p=L(a),g=await x(s,fe,a.locks.ttl_seconds,m,!!t.force,p.force_required_for_stale_lock,a.locks.wait_ms);let l;try{const f=await k(c);let d;try{d=le(f)}catch(i){throw new y(i instanceof Error?i.message:String(i),h.GENERIC_FAILURE)}try{l=Le(d,e)}catch(i){throw new y(i instanceof Error?i.message:String(i),h.USAGE)}if(l.removed){const i=V(l.definition?.key??e),u=V(l.definition?.metadata_key??l.definition?.front_matter_key??i);if(u.length>0){const w=await Xe(s,a,n,u);w>0&&r.push(`items_using_field:${w}`)}await U({pmRoot:s,filePath:c,raw:ue(l.file),op:"schema:remove-field",author:m,settings:a}),r.push(...await R({path:c,scope:"project",op:"schema:remove-field"}))}}finally{await g()}return{action:"remove-field",removed:l.removed,...l.definition?{field:l.definition}:{},file:{path:c,fields:l.file.fields.length},warnings:P(r),generated_at:S()}}async function Pt(e){const t=await M(e),o=Z(t.schema).definitions.map(se);return{action:"list-fields",fields:o,counts:{total:o.length},file:{path:J(t.pmRoot,t.schema)},generated_at:S()}}async function jt(e,t){const o=V(e);if(o.length===0)throw new y("Field key must not be empty.",h.USAGE);const s=await M(t),a=Z(s.schema).by_key.get(o);if(!a)throw new y(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${N(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:se(a),file:{path:J(s.pmRoot,s.schema)},generated_at:S()}}async function qt(e,t,o){const s=b(process.cwd(),o.path);await I(s);let a;try{const u=Pe(e);if(u===void 0)throw new Error(`Type preset name is required. Allowed: ${je.join(", ")}.`);a=u}catch(u){throw new y(u instanceof Error?u.message:String(u),h.USAGE)}const n=await F(s),c=A(n.schema),r=ye(s,c),m=[],p=T(t.author,n.author_default),g=L(n),l=[],f=[];let d;const i=await x(s,Y,n.locks.ttl_seconds,p,!!t.force,g.force_required_for_stale_lock,n.locks.wait_ms);try{const u=await k(r);let w;try{w=D(u)}catch(v){throw new y(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let $=w;for(const v of me(a)){const _=X($,v);$=_.file,(_.replaced?f:l).push(_.definition.name)}d=$.definitions.length,await U({pmRoot:s,filePath:r,raw:B($),op:"schema:apply-preset",author:p,settings:n}),await te(s,me(a),m,"schema:apply-preset-folder"),m.push(...await R({path:r,scope:"project",op:"schema:apply-preset"}))}finally{await i()}return{action:"apply-preset",preset:a,registered:l,replaced:f,file:{path:r,definitions:d},warnings:P(m),generated_at:S()}}function Ve(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new y("--min-count must be a positive integer (>= 1).",h.USAGE);return e}async function Nt(e,t){const o=b(process.cwd(),t.path);await I(o);const s=await F(o),a=A(s.schema),n=ye(o,a),c=Ve(e.minCount),r=H(s,j()),p=(await W(o,s.item_format,r.type_to_folder,[],a)).map(_=>typeof _.title=="string"?_.title:""),g=qe(p,{minCount:c}),l=[],f=[],d=[],i=[];let u;if(!e.apply){let _;try{_=D(await k(n))}catch(q){throw new y(q instanceof Error?q.message:String(q),h.GENERIC_FAILURE)}return u=_.definitions.length,{action:"infer-types",applied:!1,min_count:c,candidates:g,registered:f,replaced:d,skipped:i,file:{path:n,definitions:u},warnings:l,generated_at:S()}}const w=T(e.author,s.author_default),$=L(s),v=await x(o,Y,s.locks.ttl_seconds,w,!!e.force,$.force_required_for_stale_lock,s.locks.wait_ms);try{const _=await k(n);let q;try{q=D(_)}catch(E){throw new y(E instanceof Error?E.message:String(E),h.GENERIC_FAILURE)}let z=q;for(const E of g){if(E.shadows_builtin){i.push({name:E.name,reason:"shadows_builtin"});continue}let oe;try{oe=ae({name:E.name})}catch{i.push({name:E.name,reason:"invalid_type_token"});continue}const Q=X(z,oe);z=Q.file,(Q.replaced?d:f).push(Q.definition.name)}u=z.definitions.length,await U({pmRoot:o,filePath:n,raw:B(z),op:"schema:infer-types",author:w,settings:s}),await te(o,z.definitions.filter(E=>f.includes(E.name)||d.includes(E.name)),l,"schema:infer-types-folder"),l.push(...await R({path:n,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:c,candidates:g,registered:f,replaced:d,skipped:i,file:{path:n,definitions:u},warnings:P(l),generated_at:S()}}function Gt(e){const t=e.replaced?"Updated":"Registered",o=e.type.aliases&&e.type.aliases.length>0?` (aliases: ${e.type.aliases.join(", ")})`:"";return`${t} custom item type "${e.type.name}"${o} in ${e.file.path}. Run: pm create "${N(e.type.name)}" "<title>"`}function Ot(e){return e.removed?`Removed custom item type "${e.type?.name??"(unknown)"}" from ${e.file.path}.`:`No custom item type matched; nothing removed from ${e.file.path}.`}function Ht(e){const t=e.replaced?"Updated":"Registered",o=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",s=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${o}${s} in ${e.file.path}.`}function zt(e){return e.removed?`Removed custom status "${e.status?.id??"(unknown)"}" from ${e.file.path}.`:`No custom status matched; nothing removed from ${e.file.path}.`}function Dt(e){const t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(const[o,s]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])s.length!==0&&t.push(`${o}: ${s.map(a=>a.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(const[o,s]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])s.length!==0&&t.push(`${o}: ${s.map(a=>a.id).join(", ")}`);return t.push(`custom fields: ${e.fields.counts.total} total`),e.fields.custom.length>0&&t.push(`fields: ${e.fields.custom.map(o=>`${o.key} (${o.type}, ${o.cli_flag})`).join(", ")}`),t.push("Inspect one: pm schema show <Type>"),t.push("Inspect one status: pm schema show-status <status>"),t.push("Inspect one field: pm schema show-field <key>"),t.join(`
1
+ import{assertInitializedTracker as Se}from"./environment/tracker-preflight.js";import $e from"node:path";import{mkdir as ve}from"node:fs/promises";import{resolveAuthor as T}from"../core/shared/author.js";import{pathExists as Ee,readFileIfExists as k}from"../core/fs/fs-utils.js";import{writeWorkspaceJsonWithHistory as ke}from"../core/history/workspace-history.js";import{acquireLock as x}from"../core/lock/lock.js";import{refreshMergeAttributeFenceIfInstalled as Ae}from"./merge/install.js";import{assertAliasesAvailable as Re,assertTypeFolderAvailable as Fe,escapeForDoubleQuotes as N,normalizeAddTypeInput as ae,parseItemTypesFile as D,removeItemType as be,serializeItemTypesFile as B,upsertItemType as X}from"../core/schema/item-types-file.js";import{assertStatusTokensAvailable as ne,BUILTIN_STATUS_IDS as re,normalizeAddStatusInput as Ie,normalizeStatusToken as C,parseStatusDefsFile as ie,removeStatusDef as Te,serializeStatusDefsFile as ce,upsertStatusDef as xe}from"../core/schema/status-defs-file.js";import{normalizeAddFieldInput as Ce,normalizeFieldKey as V,parseFieldsFile as le,removeField as Le,serializeFieldsFile as ue,upsertField as Ue}from"../core/schema/fields-file.js";import{normalizeTypePresetName as Pe,resolveTypePresetDefinitions as me,TYPE_PRESET_NAMES as je}from"../core/schema/type-presets.js";import{inferTypesFromTitles as qe}from"../core/schema/type-inference.js";import{DEFAULT_RUNTIME_SCHEMA_FILE_PATHS as G,filePathForSchemaSection as O,normalizeRuntimeSchemaSettings as A,resolveRuntimeFieldRegistry as Z,resolveRuntimeStatusRegistry as K}from"../core/schema/runtime-schema.js";import{normalizeItemTypeFolder as Ne,resolveItemTypeRegistry as H,toDefaultFolder as Ge}from"../core/item/type-registry.js";import{listAllItemMetadataLight as W}from"../core/store/item-store.js";import{EXIT_CODE as h}from"../core/shared/constants.js";import{PmCliError as y}from"../core/shared/errors.js";import{nowIso as S}from"../core/shared/time.js";import{getActiveExtensionRegistrations as j,runActiveOnWriteHooks as R}from"../core/extensions/index.js";import{resolvePmRoot as F}from"../core/store/paths.js";import{readSettings as b,resolveGovernanceKnobs as L}from"../core/store/settings.js";import{assertFieldOptionsAvailable as Oe}from"./schema/field-option-collisions.js";import{resolvePmToolCustomFieldCollision as He}from"./cli-contracts/tool-schema.js";import{WORKFLOW_POLICY_ACTIONS as ze}from"./governance/workflow-policy.js";export*from"./governance/workflow-policy.js";const At=[...ze,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"];import{formatSchemaEvolutionMigrationHuman as ss,runSchemaEvolutionMigration as os}from"./schema-migration.js";import{planSchemaEvolutionMigration as ns}from"./schema-migration.js";const Y="schema-types",pe="schema-statuses",fe="schema-fields";function U(e){return ke({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function Rt(e,t,o){const s=F(process.cwd(),o.path);await I(s);let a;try{a=ae({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(d){throw new y(d instanceof Error?d.message:String(d),h.USAGE)}const n=await b(s),c=A(n.schema),r=O(s,c.files.types,G.types),m=[],p=T(t.author,n.author_default),g=L(n),l=await x(s,Y,n.locks.ttl_seconds,p,!!t.force,g.force_required_for_stale_lock,n.locks.wait_ms);let f;try{const d=await k(r);let i;try{i=D(d)}catch(u){throw new y(u instanceof Error?u.message:String(u),h.GENERIC_FAILURE)}try{Re(a,i);const u=new Map,w=H(n,j());for(const[$,v]of Object.entries(w.type_to_folder)){const _=v.trim().toLowerCase();_.length>0&&!u.has(_)&&u.set(_,$)}Fe(a,i,u)}catch(u){throw new y(u instanceof Error?u.message:String(u),h.USAGE)}f=X(i,a),f.replaced&&f.previousName!==void 0&&f.previousName!==f.definition.name&&m.push(`type_recased:${f.previousName}->${f.definition.name}`),await U({pmRoot:s,filePath:r,raw:B(f.file),op:"schema:add-type",author:p,settings:n}),await te(s,[f.definition],m,"schema:add-type-folder"),m.push(...await R({path:r,scope:"project",op:"schema:add-type"}))}finally{await l()}return await de(s,m),{action:"add-type",registered:!0,replaced:f.replaced,type:f.definition,file:{path:r,definitions:f.file.definitions.length},warnings:P(m),generated_at:S()}}async function I(e){await Se(e)}async function de(e,t){try{const o=await Ae(e);o.status==="refreshed"?t.push("merge_fence_refreshed"):o.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function P(e){return[...new Set(e)].sort((t,o)=>t.localeCompare(o))}async function De(e,t,o,s){const a=H(t,j()),n=s.trim().toLowerCase();return(await W(e,t.item_format,a.type_to_folder,[],o)).filter(r=>typeof r.type=="string"&&r.type.toLowerCase()===n).length}async function Me(e,t,o,s){const a=H(t,j()),n=K(o),c=C(s);return(await W(e,t.item_format,a.type_to_folder,[],o)).filter(m=>{const p=typeof m.status=="string"?m.status:"";return(n.alias_to_id.get(C(p))??C(p))===c}).length}async function Be(e,t,o,s,a){if(a.length===0||re.has(a))return;const n=await Me(t,o,s,a);n>0&&e.push(`items_using_status:${n}`);const c=he(s.workflow,a);c.length>0&&e.push(`status_referenced_by_workflow:${c.join(",")}`)}function he(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,s])=>s!==void 0&&C(s)===t).map(([s])=>s)}async function Ft(e,t,o){const s=F(process.cwd(),o.path);await I(s);const a=await b(s),n=A(a.schema),c=O(s,n.files.types,G.types),r=[],m=T(t.author,a.author_default),p=L(a),g=await x(s,Y,a.locks.ttl_seconds,m,!!t.force,p.force_required_for_stale_lock,a.locks.wait_ms);let l;try{const f=await k(c);let d;try{d=D(f)}catch(i){throw new y(i instanceof Error?i.message:String(i),h.GENERIC_FAILURE)}try{l=be(d,e)}catch(i){throw new y(i instanceof Error?i.message:String(i),h.USAGE)}if(l.removed){const i=(l.definition?.name??e??"").trim();if(i.length>0){const u=await De(s,a,n,i);u>0&&r.push(`items_using_type:${u}`)}await U({pmRoot:s,filePath:c,raw:B(l.file),op:"schema:remove-type",author:m,settings:a}),r.push(...await R({path:c,scope:"project",op:"schema:remove-type"}))}}finally{await g()}return l.removed&&await de(s,r),{action:"remove-type",removed:l.removed,...l.definition?{type:l.definition}:{},file:{path:c,definitions:l.file.definitions.length},warnings:P(r),generated_at:S()}}function ee(e,t){return O(e,t.files.statuses,G.statuses)}function J(e,t){return O(e,t.files.fields,G.fields)}function ye(e,t){return O(e,t.files.types,G.types)}async function te(e,t,o,s){for(const a of t){const n=Ne(a.folder??Ge(a.name)),c=$e.join(e,n);await Ee(c)||(await ve(c,{recursive:!0}),o.push(...await R({path:c,scope:"project",op:s})))}}function se(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function Ke(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function We(e){const t=new Map;for(const o of e){const s=C(o.id);if(s.length!==0){t.set(s,s);for(const a of Array.isArray(o.aliases)?o.aliases:[]){const n=C(a);n.length>0&&!t.has(n)&&t.set(n,s)}}}return t}async function bt(e,t,o){const s=F(process.cwd(),o.path);await I(s);let a;try{a=Ie({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(w){throw new y(w instanceof Error?w.message:String(w),h.USAGE)}const n=await b(s),c=A(n.schema),r=ee(s,c),m=K(c);try{ne(a,m.alias_to_id)}catch(w){throw new y(w instanceof Error?w.message:String(w),h.USAGE)}const p=Ke(m.by_id.get(a.id));if((a.roles??p?.roles??[]).length===0)throw new y(`Status "${a.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,h.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${N(a.id)}" --role active`,`pm schema add-status "${N(a.id)}" --role blocked`]});const l=[],f=T(t.author,n.author_default),d=L(n),i=await x(s,pe,n.locks.ttl_seconds,f,!!t.force,d.force_required_for_stale_lock,n.locks.wait_ms);let u;try{const w=await k(r);let $;try{$=ie(w)}catch(_){throw new y(_ instanceof Error?_.message:String(_),h.GENERIC_FAILURE)}const v=We($.statuses);try{ne(a,v)}catch(_){throw new y(_ instanceof Error?_.message:String(_),h.USAGE)}u=xe($,a,p),await U({pmRoot:s,filePath:r,raw:ce(u.file),op:"schema:add-status",author:f,settings:n}),l.push(...await R({path:r,scope:"project",op:"schema:add-status"}))}finally{await i()}return{action:"add-status",registered:!0,replaced:u.replaced,status:u.definition,file:{path:r,statuses:u.file.statuses.length},warnings:P(l),generated_at:S()}}async function It(e,t,o){const s=F(process.cwd(),o.path);await I(s);const a=await b(s),n=A(a.schema),c=ee(s,n),r=[],m=T(t.author,a.author_default),p=L(a),g=await x(s,pe,a.locks.ttl_seconds,m,!!t.force,p.force_required_for_stale_lock,a.locks.wait_ms);let l;try{const f=await k(c);let d;try{d=ie(f)}catch(i){throw new y(i instanceof Error?i.message:String(i),h.GENERIC_FAILURE)}try{l=Te(d,e)}catch(i){throw new y(i instanceof Error?i.message:String(i),h.USAGE)}if(l.removed){const i=C(l.definition?.id??e);await Be(r,s,a,n,i),await U({pmRoot:s,filePath:c,raw:ce(l.file),op:"schema:remove-status",author:m,settings:a}),r.push(...await R({path:c,scope:"project",op:"schema:remove-status"}))}}finally{await g()}return{action:"remove-status",removed:l.removed,...l.definition?{status:l.definition}:{},file:{path:c,statuses:l.file.statuses.length},warnings:P(r),generated_at:S()}}function we(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function Ye(e,t,o){return{...we(e),source:t,...o?{extension:o}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function _e(e){return{id:e.id,source:re.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function ge(e,t,o){const s=e.toLowerCase();return o.has(s)?"extension":t.has(s)?"custom":"builtin"}function Je(){const e=new Map,t=j();for(const o of t?.item_types??[]){const s=o.types;if(Array.isArray(s))for(const a of s){if(typeof a!="object"||a===null||Array.isArray(a))continue;const n=a.name;typeof n=="string"&&n.trim().length>0&&e.set(n.trim().toLowerCase(),{layer:o.layer,name:o.name})}}return e}function Qe(e){const t=K(e),o=[],s=[];for(const a of t.definitions){const n=_e(a);n.source==="builtin"?o.push(n):s.push(n)}return{builtin:o,custom:s}}async function M(e){const t=F(process.cwd(),e.path);await I(t);const o=await b(t),s=A(o.schema),a=O(t,s.files.types,G.types),n=ee(t,s),c=H(o,j()),r=Je(),m=new Set((o.item_types?.definitions??[]).map(p=>p.name.trim().toLowerCase()).filter(p=>p.length>0&&!r.has(p)));return{pmRoot:t,typesPath:a,statusesPath:n,byType:c.by_type,customNames:m,extensionProvenance:r,schema:s}}async function Tt(e){const t=await M(e),o=[],s=[],a=[];for(const r of Object.values(t.byType).sort((m,p)=>m.name.localeCompare(p.name))){const m=ge(r.name,t.customNames,new Set(t.extensionProvenance.keys())),p=we(r);m==="extension"?a.push(p):m==="custom"?s.push(p):o.push(p)}const n=Qe(t.schema),c=Z(t.schema).definitions.map(se);return{action:"list",builtin:o,custom:s,extension:a,counts:{builtin:o.length,custom:s.length,extension:a.length,total:o.length+s.length+a.length},statuses:{builtin:n.builtin,custom:n.custom,counts:{builtin:n.builtin.length,custom:n.custom.length,total:n.builtin.length+n.custom.length}},fields:{custom:c,counts:{total:c.length}},file:{path:t.typesPath},generated_at:S()}}async function xt(e,t){const o=(e??"").trim();if(o.length===0)throw new y("Type name must not be empty.",h.USAGE);const s=await M(t),a=Object.values(s.byType).find(n=>n.name.toLowerCase()===o.toLowerCase()||n.aliases.some(c=>c.toLowerCase()===o.toLowerCase()));if(!a)throw new y(`Unknown item type "${o}". Run pm schema list to inspect registered types, or pm schema add-type "${N(o)}" to register it.`,h.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:Ye(a,ge(a.name,s.customNames,new Set(s.extensionProvenance.keys())),s.extensionProvenance.get(a.name.toLowerCase())),file:{path:s.typesPath},generated_at:S()}}async function Ct(e,t){const o=C(e);if(o.length===0)throw new y("Status id must not be empty.",h.USAGE);const s=await M(t),a=K(s.schema),n=a.alias_to_id.get(o)??o,c=a.by_id.get(n);if(!c)throw new y(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${N(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:_e(c),file:{path:s.statusesPath},generated_at:S()}}async function Lt(e,t,o){const s=F(process.cwd(),o.path);await I(s);let a;try{a=Ce({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(i){throw new y(i instanceof Error?i.message:String(i),h.USAGE)}Oe(a,{cliFlag:t.cliFlag,aliases:t.alias});const n=await b(s),c=A(n.schema),r=J(s,c),m=[],p=He(a.key);p&&m.push(`custom_field_mcp_input_collision:${p.field}:${p.property}:${p.owner}:use=${p.nested_path}`);const g=T(t.author,n.author_default),l=L(n),f=await x(s,fe,n.locks.ttl_seconds,g,!!t.force,l.force_required_for_stale_lock,n.locks.wait_ms);let d;try{const i=await k(r);let u;try{u=le(i)}catch(w){throw new y(w instanceof Error?w.message:String(w),h.GENERIC_FAILURE)}d=Ue(u,a),await U({pmRoot:s,filePath:r,raw:ue(d.file),op:"schema:add-field",author:g,settings:n}),m.push(...await R({path:r,scope:"project",op:"schema:add-field"}))}finally{await f()}return{action:"add-field",registered:!0,replaced:d.replaced,field:d.definition,file:{path:r,fields:d.file.fields.length},warnings:P(m),generated_at:S()}}async function Xe(e,t,o,s){const a=H(t,j());return(await W(e,t.item_format,a.type_to_folder,[],o)).filter(c=>{const r=c[s];return r==null?!1:Array.isArray(r)?r.length>0:typeof r=="string"?r.trim().length>0:!0}).length}async function Ut(e,t,o){const s=F(process.cwd(),o.path);await I(s);const a=await b(s),n=A(a.schema),c=J(s,n),r=[],m=T(t.author,a.author_default),p=L(a),g=await x(s,fe,a.locks.ttl_seconds,m,!!t.force,p.force_required_for_stale_lock,a.locks.wait_ms);let l;try{const f=await k(c);let d;try{d=le(f)}catch(i){throw new y(i instanceof Error?i.message:String(i),h.GENERIC_FAILURE)}try{l=Le(d,e)}catch(i){throw new y(i instanceof Error?i.message:String(i),h.USAGE)}if(l.removed){const i=V(l.definition?.key??e),u=V(l.definition?.metadata_key??l.definition?.front_matter_key??i);if(u.length>0){const w=await Xe(s,a,n,u);w>0&&r.push(`items_using_field:${w}`)}await U({pmRoot:s,filePath:c,raw:ue(l.file),op:"schema:remove-field",author:m,settings:a}),r.push(...await R({path:c,scope:"project",op:"schema:remove-field"}))}}finally{await g()}return{action:"remove-field",removed:l.removed,...l.definition?{field:l.definition}:{},file:{path:c,fields:l.file.fields.length},warnings:P(r),generated_at:S()}}async function Pt(e){const t=await M(e),o=Z(t.schema).definitions.map(se);return{action:"list-fields",fields:o,counts:{total:o.length},file:{path:J(t.pmRoot,t.schema)},generated_at:S()}}async function jt(e,t){const o=V(e);if(o.length===0)throw new y("Field key must not be empty.",h.USAGE);const s=await M(t),a=Z(s.schema).by_key.get(o);if(!a)throw new y(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${N(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:se(a),file:{path:J(s.pmRoot,s.schema)},generated_at:S()}}async function qt(e,t,o){const s=F(process.cwd(),o.path);await I(s);let a;try{const u=Pe(e);if(u===void 0)throw new Error(`Type preset name is required. Allowed: ${je.join(", ")}.`);a=u}catch(u){throw new y(u instanceof Error?u.message:String(u),h.USAGE)}const n=await b(s),c=A(n.schema),r=ye(s,c),m=[],p=T(t.author,n.author_default),g=L(n),l=[],f=[];let d;const i=await x(s,Y,n.locks.ttl_seconds,p,!!t.force,g.force_required_for_stale_lock,n.locks.wait_ms);try{const u=await k(r);let w;try{w=D(u)}catch(v){throw new y(v instanceof Error?v.message:String(v),h.GENERIC_FAILURE)}let $=w;for(const v of me(a)){const _=X($,v);$=_.file,(_.replaced?f:l).push(_.definition.name)}d=$.definitions.length,await U({pmRoot:s,filePath:r,raw:B($),op:"schema:apply-preset",author:p,settings:n}),await te(s,me(a),m,"schema:apply-preset-folder"),m.push(...await R({path:r,scope:"project",op:"schema:apply-preset"}))}finally{await i()}return{action:"apply-preset",preset:a,registered:l,replaced:f,file:{path:r,definitions:d},warnings:P(m),generated_at:S()}}function Ve(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new y("--min-count must be a positive integer (>= 1).",h.USAGE);return e}async function Nt(e,t){const o=F(process.cwd(),t.path);await I(o);const s=await b(o),a=A(s.schema),n=ye(o,a),c=Ve(e.minCount),r=H(s,j()),p=(await W(o,s.item_format,r.type_to_folder,[],a)).map(_=>typeof _.title=="string"?_.title:""),g=qe(p,{minCount:c}),l=[],f=[],d=[],i=[];let u;if(!e.apply){let _;try{_=D(await k(n))}catch(q){throw new y(q instanceof Error?q.message:String(q),h.GENERIC_FAILURE)}return u=_.definitions.length,{action:"infer-types",applied:!1,min_count:c,candidates:g,registered:f,replaced:d,skipped:i,file:{path:n,definitions:u},warnings:l,generated_at:S()}}const w=T(e.author,s.author_default),$=L(s),v=await x(o,Y,s.locks.ttl_seconds,w,!!e.force,$.force_required_for_stale_lock,s.locks.wait_ms);try{const _=await k(n);let q;try{q=D(_)}catch(E){throw new y(E instanceof Error?E.message:String(E),h.GENERIC_FAILURE)}let z=q;for(const E of g){if(E.shadows_builtin){i.push({name:E.name,reason:"shadows_builtin"});continue}let oe;try{oe=ae({name:E.name})}catch{i.push({name:E.name,reason:"invalid_type_token"});continue}const Q=X(z,oe);z=Q.file,(Q.replaced?d:f).push(Q.definition.name)}u=z.definitions.length,await U({pmRoot:o,filePath:n,raw:B(z),op:"schema:infer-types",author:w,settings:s}),await te(o,z.definitions.filter(E=>f.includes(E.name)||d.includes(E.name)),l,"schema:infer-types-folder"),l.push(...await R({path:n,scope:"project",op:"schema:infer-types"}))}finally{await v()}return{action:"infer-types",applied:!0,min_count:c,candidates:g,registered:f,replaced:d,skipped:i,file:{path:n,definitions:u},warnings:P(l),generated_at:S()}}function Gt(e){const t=e.replaced?"Updated":"Registered",o=e.type.aliases&&e.type.aliases.length>0?` (aliases: ${e.type.aliases.join(", ")})`:"";return`${t} custom item type "${e.type.name}"${o} in ${e.file.path}. Run: pm create "${N(e.type.name)}" "<title>"`}function Ot(e){return e.removed?`Removed custom item type "${e.type?.name??"(unknown)"}" from ${e.file.path}.`:`No custom item type matched; nothing removed from ${e.file.path}.`}function Ht(e){const t=e.replaced?"Updated":"Registered",o=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",s=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${o}${s} in ${e.file.path}.`}function zt(e){return e.removed?`Removed custom status "${e.status?.id??"(unknown)"}" from ${e.file.path}.`:`No custom status matched; nothing removed from ${e.file.path}.`}function Dt(e){const t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(const[o,s]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])s.length!==0&&t.push(`${o}: ${s.map(a=>a.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(const[o,s]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])s.length!==0&&t.push(`${o}: ${s.map(a=>a.id).join(", ")}`);return t.push(`custom fields: ${e.fields.counts.total} total`),e.fields.custom.length>0&&t.push(`fields: ${e.fields.custom.map(o=>`${o.key} (${o.type}, ${o.cli_flag})`).join(", ")}`),t.push("Inspect one: pm schema show <Type>"),t.push("Inspect one status: pm schema show-status <status>"),t.push("Inspect one field: pm schema show-field <key>"),t.join(`
2
2
  `)}function Mt(e){const t=[`type: ${e.type.name}`,`source: ${e.type.source}`,`folder: ${e.type.folder}`];return e.type.default_status&&t.push(`default_status: ${e.type.default_status}`),e.type.aliases.length>0&&t.push(`aliases: ${e.type.aliases.join(", ")}`),e.type.description&&t.push(`description: ${e.type.description}`),e.type.options.length>0&&t.push(`options: ${e.type.options.map(o=>o.key).join(", ")}`),t.join(`
3
3
  `)}function Bt(e){const t=[`status: ${e.status.id}`,`source: ${e.status.source}`];return e.status.roles.length>0&&t.push(`roles: ${e.status.roles.join(", ")}`),e.status.aliases.length>0&&t.push(`aliases: ${e.status.aliases.join(", ")}`),e.status.description&&t.push(`description: ${e.status.description}`),typeof e.status.order=="number"&&t.push(`order: ${e.status.order}`),t.join(`
4
4
  `)}function Ze(e){const t=[];e.required&&t.push("required"),e.required_on_create&&t.push("required_on_create"),e.allow_unset||t.push("no_unset");const o=t.length>0?` [${t.join(", ")}]`:"";return`${e.key} (${e.type}) ${e.cli_flag} commands=${e.commands.join("/")}${o}`}function Kt(e){return`${e.replaced?"Updated":"Registered"} custom field "${e.field.key}" in ${e.file.path}. Use it: pm create "<title>" --${(e.field.cli_flag??e.field.key).replaceAll("_","-")} <value>`}function Wt(e){return e.removed?`Removed custom field "${e.field?.key??"(unknown)"}" from ${e.file.path}.`:`No custom field matched; nothing removed from ${e.file.path}.`}function Yt(e){const t=[`Custom fields: ${e.counts.total} total`];for(const o of e.fields)t.push(` ${Ze(o)}`);return t.push("Inspect one: pm schema show-field <key>"),t.join(`
5
5
  `)}function Jt(e){const t=e.field,o=[`field: ${t.key}`,`type: ${t.type}`,`cli_flag: ${t.cli_flag}`,`commands: ${t.commands.join(", ")}`];return t.cli_aliases.length>0&&o.push(`cli_aliases: ${t.cli_aliases.join(", ")}`),t.description&&o.push(`description: ${t.description}`),t.required&&o.push("required: true"),t.required_on_create&&o.push("required_on_create: true"),t.allow_unset||o.push("allow_unset: false"),t.required_types.length>0&&o.push(`required_types: ${t.required_types.join(", ")}`),o.join(`
6
6
  `)}function Qt(e){const t=e.registered.length>0?`registered: ${e.registered.join(", ")}`:"",o=e.replaced.length>0?`updated: ${e.replaced.join(", ")}`:"",s=[t,o].filter(a=>a.length>0).join("; ");return`Applied "${e.preset}" type preset to ${e.file.path}${s.length>0?` (${s})`:""}.`}function Xt(e){if(e.candidates.length===0)return`No title-prefix conventions found with at least ${e.min_count} items. Lower the threshold with --min-count <n>.`;const t=e.applied?[`Inferred and registered custom types from title prefixes (min-count ${e.min_count}):`]:[`Inferred custom type candidates from title prefixes (min-count ${e.min_count}, dry-run):`];for(const o of e.candidates){const s=o.shadows_builtin?" [shadows built-in, skipped]":"";t.push(` ${o.name} <- "${o.prefix}" (${o.count} items)${s}`)}return e.applied?(e.registered.length>0&&t.push(`registered: ${e.registered.join(", ")}`),e.replaced.length>0&&t.push(`updated: ${e.replaced.join(", ")}`)):t.push("Re-run with --apply to register the non-shadowing candidates."),t.join(`
7
- `)}const Vt={workflowSlotsReferencing:he};export{At as SCHEMA_SUBCOMMANDS,Vt as _testOnlySchemaCommand,te as ensureTypeFolderScaffold,Kt as formatSchemaAddFieldHuman,Ht as formatSchemaAddStatusHuman,Gt as formatSchemaAddTypeHuman,Qt as formatSchemaApplyPresetHuman,ss as formatSchemaEvolutionMigrationHuman,Xt as formatSchemaInferTypesHuman,Yt as formatSchemaListFieldsHuman,Dt as formatSchemaListHuman,Wt as formatSchemaRemoveFieldHuman,zt as formatSchemaRemoveStatusHuman,Ot as formatSchemaRemoveTypeHuman,Jt as formatSchemaShowFieldHuman,Mt as formatSchemaShowHuman,Bt as formatSchemaShowStatusHuman,ns as planSchemaEvolutionMigration,Lt as runSchemaAddField,Ft as runSchemaAddStatus,Rt as runSchemaAddType,qt as runSchemaApplyPreset,os as runSchemaEvolutionMigration,Nt as runSchemaInferTypes,Tt as runSchemaList,Pt as runSchemaListFields,Ut as runSchemaRemoveField,It as runSchemaRemoveStatus,bt as runSchemaRemoveType,xt as runSchemaShow,jt as runSchemaShowField,Ct as runSchemaShowStatus};
7
+ `)}const Vt={workflowSlotsReferencing:he};export{At as SCHEMA_SUBCOMMANDS,Vt as _testOnlySchemaCommand,te as ensureTypeFolderScaffold,Kt as formatSchemaAddFieldHuman,Ht as formatSchemaAddStatusHuman,Gt as formatSchemaAddTypeHuman,Qt as formatSchemaApplyPresetHuman,ss as formatSchemaEvolutionMigrationHuman,Xt as formatSchemaInferTypesHuman,Yt as formatSchemaListFieldsHuman,Dt as formatSchemaListHuman,Wt as formatSchemaRemoveFieldHuman,zt as formatSchemaRemoveStatusHuman,Ot as formatSchemaRemoveTypeHuman,Jt as formatSchemaShowFieldHuman,Mt as formatSchemaShowHuman,Bt as formatSchemaShowStatusHuman,ns as planSchemaEvolutionMigration,Lt as runSchemaAddField,bt as runSchemaAddStatus,Rt as runSchemaAddType,qt as runSchemaApplyPreset,os as runSchemaEvolutionMigration,Nt as runSchemaInferTypes,Tt as runSchemaList,Pt as runSchemaListFields,Ut as runSchemaRemoveField,It as runSchemaRemoveStatus,Ft as runSchemaRemoveType,xt as runSchemaShow,jt as runSchemaShowField,Ct as runSchemaShowStatus};
8
8
  //# sourceMappingURL=schema.js.map
package/docs/COMMANDS.md CHANGED
@@ -1706,7 +1706,7 @@ pm create Spike "Investigate retry backoff"
1706
1706
  - `add-status <id>` writes a custom lifecycle status (idempotent UPSERT keyed on the normalized id; re-adding sets `replaced: true`). Roles are validated against the runtime status roles: `draft`, `active`, `blocked`, `terminal`, `terminal_done`, `terminal_canceled`, `default_open`, `default_close`, `default_cancel`.
1707
1707
  - `remove-status <id>` removes a custom status. The six built-in statuses (`open`, `in_progress`, `blocked`, `closed`, `canceled`, `draft`) are refused. It WARNS (non-blocking) with `items_using_status:<N>` when items currently use that status.
1708
1708
  - Built-in types (Chore, Decision, Epic, Event, Feature, Issue, Meeting, Milestone, Plan, Reminder, Task) are reserved and cannot be redefined or removed.
1709
- - `add-field <key>` registers a custom metadata field in `.agents/pm/schema/fields.json` (shape: `{ "fields": [RuntimeFieldDefinition...] }`). Each custom field dynamically registers a CLI flag on create/update (and any other commands you list) so projects can capture typed project-specific metadata without hand-editing JSON. It is an idempotent UPSERT keyed on the normalized key, and refuses keys that shadow a built-in field. It also refuses a field whose key, flag or alias equals a built-in option of a command it is registered for (`schema_field_option_collision`, exit 2): the parser keeps one option per name, so `pm schema add-field full --commands create,list` would make `pm list --full` read as a field filter. Names are compared as the option keys a value is read under, so punctuation counts as a word break (`token.budget` equals `--token-budget`). The refusal names each shadowed option per command and, when some requested commands are free, the narrower `--commands` list. `severity` is the one built-in a field may redefine. `pm profile apply` and `pm schema rename-field` (for the target name, dry run included) refuse the same way, `pm profile lint` reports `field_option_collision`, and `pm validate --check-metadata` reports fields already stored as `validate_schema_field_option_collision:<n>` with rows under `schema_field_option_collisions` ([pm-pta8um](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-pta8um.toon); repository-only tracker record excluded from npm). Each flag and alias must also be one option spelling: a long name without spaces, pipes, commas, `=` or brackets, or a short flag of one dash and one character. A spelling the parser would split (`--alias 'full|deep'` registers a second `--full`) or a malformed short flag (`-xy`) is refused with `schema_field_flag_invalid` (exit 2) by `add-field`, `profile apply` and `rename-field`; `pm profile lint` reports `field_flag_invalid`. A short spelling is compared with the command's own short flags (`-p` is `--priority` on create and update), and `-h`/`--help` are reserved on every command. `pm validate --check-metadata` reports stored spellings as `validate_schema_field_flag_invalid:<n>` with rows under `schema_field_flag_invalid` (a stored definition the registry drops entirely, such as an empty flag, is not reported yet: [pm-x9r2h3](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-x9r2h3.toon), repository tracker record excluded from npm), and the CLI skips such a spelling when it registers field options, so a stored definition can no longer stop a command from starting or take over help; an SDK caller checks one spelling with `describeFieldFlagSpellingDefect` from `@unbrained/pm-cli/sdk`, which returns the reason or `undefined` ([pm-8patuh](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-8patuh.toon); repository tracker record, excluded from npm). `list-fields` / `show-field <key>` inspect registered fields; `remove-field <key>` drops one and WARNS (non-blocking) with `items_using_field:<N>` when items still carry a value. See [CONFIGURATION.md](CONFIGURATION.md) for the full `schema/fields.json` format.
1709
+ - `add-field <key>` registers a custom metadata field in `.agents/pm/schema/fields.json` (shape: `{ "fields": [RuntimeFieldDefinition...] }`). Each custom field dynamically registers a CLI flag on create/update (and any other commands you list) so projects can capture typed project-specific metadata without hand-editing JSON. It is an idempotent UPSERT keyed on the normalized key, and refuses keys that shadow a built-in field. It also refuses a field whose key, flag or alias equals a built-in option of a command it is registered for (`schema_field_option_collision`, exit 2): the parser keeps one option per name, so `pm schema add-field full --commands create,list` would make `pm list --full` read as a field filter. Names are compared as the option keys a value is read under, so punctuation counts as a word break (`token.budget` equals `--token-budget`). The refusal names each shadowed option per command and, when some requested commands are free, the narrower `--commands` list. `severity` is the one built-in a field may redefine. `pm profile apply` and `pm schema rename-field` (for the target name, dry run included) refuse the same way, `pm profile lint` reports `field_option_collision`, and `pm validate --check-metadata` reports fields already stored as `validate_schema_field_option_collision:<n>` with rows under `schema_field_option_collisions` ([pm-pta8um](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-pta8um.toon); repository-only tracker record excluded from npm). Each flag and alias must also be one option spelling: a long name without spaces, pipes, commas, `=` or brackets, or a short flag of one dash and one character. A spelling the parser would split (`--alias 'full|deep'` registers a second `--full`) or a malformed short flag (`-xy`) is refused with `schema_field_flag_invalid` (exit 2) by `add-field`, `profile apply` and `rename-field`; `pm profile lint` reports `field_flag_invalid`. A supplied `--cli-flag` or `--alias` that normalizes to nothing (`--cli-flag ' '`) is refused the same way instead of being read as omitted. A short spelling is compared with the command's own short flags (`-p` is `--priority` on create and update), and `-h`/`--help` are reserved on every command as flags and aliases; a key `help` behind another flag (`--cli-flag help-topic`) is free, because the help option never delivers a parsed value ([pm-2nwcgg](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-2nwcgg.toon); repository tracker record, excluded from npm). `pm validate --check-metadata` reports stored spellings as `validate_schema_field_flag_invalid:<n>` with rows under `schema_field_flag_invalid`, and a stored definition the registry drops or reads only in part, such as an empty flag or a blank alias, as `validate_schema_field_definition_dropped:<n>` or `validate_schema_field_definition_partial:<n>` with rows under `schema_field_definition_losses` ([pm-x9r2h3](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-x9r2h3.toon), repository tracker record excluded from npm), and the CLI skips such a spelling when it registers field options, so a stored definition can no longer stop a command from starting or take over help; an SDK caller checks one spelling with `describeFieldFlagSpellingDefect` from `@unbrained/pm-cli/sdk`, which returns the reason or `undefined` ([pm-8patuh](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-8patuh.toon); repository tracker record, excluded from npm). `list-fields` / `show-field <key>` inspect registered fields; `remove-field <key>` drops one and WARNS (non-blocking) with `items_using_field:<N>` when items still carry a value. See [CONFIGURATION.md](CONFIGURATION.md) for the full `schema/fields.json` format.
1710
1710
  - `apply-preset <agile|ops|research>` batch-registers a domain type preset into an already-initialized project (the same vocabulary `pm init --type-preset` seeds); it is idempotent (re-running reports `replaced` entries) and shares its definitions with init.
1711
1711
  - `add-type --infer` scans existing item titles for stable `PREFIX-`/`PREFIX:` conventions and proposes them as custom types. It previews candidates by default (dry-run); pass `--apply` to register the non-shadowing candidates and `--min-count <n>` to tune the per-prefix threshold (default 10). Candidates whose name resolves to a built-in type are reported and skipped.
1712
1712
  - `rename-type`, `rename-field`, and `remap-status` are lossless migration verbs. The runtime derives a deterministic workspace-and-request-bound migration id for resumable retries; `--migration-id` remains an optional authoritative override for external orchestration. Start with `--dry-run --json` to inspect the derived id, fingerprint, affected count, and ordered per-item changes without persisting a plan. Execution stages the target definition, writes immutable history on every affected item and the workspace stream, then retires the source. A field rename refuses any item that already has the target key; `--type <Type>` optionally restricts a field rename.
@@ -245,7 +245,7 @@ underscore aliases remain accepted for compatibility.
245
245
  | `PM_OLLAMA_MODEL` | choose default Ollama embedding model |
246
246
  | `PM_DISABLE_OLLAMA_AUTO_DEFAULTS` | disable implicit Ollama search defaults |
247
247
  | `PM_CONTEXT_USAGE_DISABLED` | set to `1` to disable the derived context/next usage-feedback ledger with zero filesystem reads or writes |
248
- | `PM_COMMAND_SHELL` | shell the pm commands printed in recovery guidance (`suggested_retry`, `restore_with`, next steps) are quoted for: `posix` (also `sh`, `bash`, `zsh`), `cmd` (also `cmd.exe`) or `powershell` (also `pwsh`), case-insensitive. Default: `cmd` on Windows, `posix` elsewhere; an empty or unrecognized value keeps the default. In the `cmd` form, an argument that contains `%` or `"` has every cmd.exe metacharacter caret-escaped and a caret after each `%`, so cmd.exe cannot expand `%VAR%` or split the line at `&`. That holds as long as no environment variable is defined whose name starts with `^`, and while delayed expansion (`cmd /v:on`) stays off, its default. cmd.exe ends a command at a line break, which no quoting carries, so the cmd form renders each line break inside an argument as a space. npm's `pm.cmd` launcher parses its arguments a second time, so an argument holding `"` together with `^`, `&`, `\|`, `<` or `>` needs the native entry point (`node <install>/dist/cli.js`) or PowerShell's `pm.ps1`. The `powershell` form uses single-quoted literals, so `$`, `$(...)`, backticks and `%` never expand. Arguments then reach the native command exactly under PowerShell 7.3 or later in its default argument-passing mode. Windows PowerShell 5.1, and `$PSNativeCommandArgumentPassing = 'Legacy'`, drop empty arguments and mangle embedded double quotes. The `posix` form single-quotes an argument that holds `!`, which interactive bash and zsh would history-expand inside double quotes, and quotes a token that starts with `=`, which zsh expands to a command path ([GH-1774](https://github.com/unbraind/pm-cli/issues/1774)) |
248
+ | `PM_COMMAND_SHELL` | shell the pm commands printed in recovery guidance (`suggested_retry`, `restore_with`, next steps) are quoted for: `posix` (also `sh`, `bash`, `zsh`), `cmd` (also `cmd.exe`) or `powershell` (also `pwsh`), case-insensitive. Default: `cmd` on Windows, `posix` elsewhere; an empty or unrecognized value keeps the default. In the `cmd` form, an argument that contains `%` or `"` has every cmd.exe metacharacter caret-escaped and a caret after each `%`, so cmd.exe cannot expand `%VAR%` or split the line at `&`. That holds as long as no environment variable is defined whose name starts with `^`, and while delayed expansion (`cmd /v:on`) stays off, its default. cmd.exe ends a command at a line break, which no quoting carries, so the cmd form renders each line break inside an argument as a space. npm's `pm.cmd` launcher parses its arguments a second time, so an argument holding `"` together with `^`, `&`, `\|`, `<` or `>` needs the native entry point (`node <install>/dist/cli.js`) or PowerShell's `pm.ps1`. The `powershell` form uses single-quoted literals, so `$`, `$(...)`, backticks and `%` never expand. Arguments then reach the native command exactly under PowerShell 7.3 or later in its default argument-passing mode. Windows PowerShell 5.1, and `$PSNativeCommandArgumentPassing = 'Legacy'`, drop empty arguments and mangle embedded double quotes. The `posix` form single-quotes an argument that holds `!`, which interactive bash and zsh would history-expand inside double quotes, and also one that holds a line break or ends in a backslash: bash 3.2, the macOS system shell, misreads those double-quoted spellings when it scans a line for history expansion, so a later `!` would look live and its expansion pass would cut the line after the first non-ASCII character ([pm-jzrtsr](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-jzrtsr.toon); tracker record excluded from npm). It also quotes a token that starts with `=`, which zsh expands to a command path ([GH-1774](https://github.com/unbraind/pm-cli/issues/1774)) |
249
249
  | `PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS` | budget of each managed-package update lookup (`npm view` or `git ls-remote`) in integer milliseconds; default `10000`, clamped to `1000`–`25000`; `pm package manage --fix-managed-state` keeps the default because it looks up under the extension state lock. A lookup that runs out reports `npm_registry_lookup_timed_out` or `github_remote_lookup_timed_out` with `update_check_timeout_ms` |
250
250
 
251
251
  For command-level tracker targeting, prefer `--pm-path <tracker-root>`. The old
@@ -862,6 +862,8 @@ Fields live in `.agents/pm/schema/fields.json` with the shape `{ "fields": [Runt
862
862
  - `description` — surfaced in `--help`.
863
863
  - `value_schema` — optional recursive JSON-value validation applied after CLI coercion and before create/update persistence. It supports `type`, `const`, `enum`, `min_length`, `min_items`, `format: "date-time"`, object `properties`/`required`/`additional_properties`, array `items`, and exact-one `one_of` variants. This lets project-defined fields enforce domain semantics without custom command code.
864
864
 
865
+ The registry skips a definition it cannot use instead of failing: one whose key or `cli_flag` normalizes to nothing, whose `value_schema` is invalid, or which is not an object, and one whose explicit `metadata_key` names nothing while its key is built-in item metadata (elsewhere such a key falls back to the field key). It also ignores a blank alias, an unknown `type` (read as `string`) or command, a `description` that is not a string, a `repeatable`, `required`, `required_on_create` or `allow_unset` value that is not a boolean, and a `value_schema` keyword it does not read (such as `minLength`; the supported spelling is `min_length`), which is then not enforced. `pm validate --check-metadata` names every such stored entry, in `schema/fields.json` or inline in `settings.json` (judged as settings validation admits it), with its position and reason (`validate_schema_field_definition_dropped:<n>` and `validate_schema_field_definition_partial:<n>`, rows under `schema_field_definition_losses`). A `null` or scalar entry in `schema/fields.json`, `schema/statuses.json` or `schema/types.json`, or a type entry without a string `name`, is skipped with a `runtime_schema_<section>_entry_invalid:<n>` warning that `pm health` reports (a skipped status keeps its position, which is the implicit order of the statuses after it); before, one such entry discarded every setting in favour of its default ([pm-x9r2h3](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-x9r2h3.toon); repository tracker record, excluded from npm).
866
+
865
867
  End-to-end example — add a required-on-create `component` string field on `Task` items:
866
868
 
867
869
  ```jsonc
@@ -306,7 +306,7 @@ Use the public SDK barrel. Do not deep-import from `src/core` or `dist/core`.
306
306
  - `api.extension` is a read-only identity (`name`, `layer`, `version`, `capabilities`, `pm_min_version?`, `pm_max_version?`, `source_package?`) for self-identifying logs and version gating without re-reading the manifest.
307
307
  - `api.registerCommand(definition)` adds package-owned commands; `read_output` opts readers into the [SDK output contract](SDK.md#minimal-command-extension).
308
308
  - `api.registerFlags(command, flags)` adds runtime command flags. A flag may declare `value_type` (canonical; the legacy `type` alias is honored only when `value_type` is absent), `list: true` to accumulate repeated/comma-joined values like core `--tags`, a `default` applied when the flag is omitted, and `value_validation: "strict"` to refuse malformed `number`/`boolean` tokens before the handler runs (the default `"coerce"` forwards the raw token). The handler reads each flag from `context.options` under its camel-case handler key (`--status-filter` → `statusFilter`), published as `sdk_option` by `pm contracts --command <command> --flags-only --json`; CLI, `PmClient.run`, MCP, and `runRegisteredCommandForTest` all deliver that key with the same defaults and coercion, and host flags such as `--json`, `--author`, and `--pm-path` arrive in `context.global` and are listed as `inherited_flags`. On the CLI, a command that declares flags refuses any other option with `unknown_option` before the handler runs (a command that declares none still receives undeclared options for now, see pm-4of199 in the SDK guide), and two spellings of one flag with different values (`--status-filter open -s closed`) are refused with `extension_option_spelling_conflict`, so declare every option a handler reads. See [Handler keys and ownership](SDK.md#handler-keys-and-ownership).
309
- - `api.registerItemFields(fields)` adds custom metadata fields. Agents can set declared fields with repeatable `pm create --field name=value` and `pm update <id> --field name=value`; undeclared names are rejected. Extension declarations are matched first; a name that no active extension declares but the project schema does (for example `gate_evidence`) is refused with `project_schema_field_requires_declared_flag`, which names a CLI flag and an SDK option that each set only that field (each is omitted when every spelling is shared with another declared field or with an option of the command itself) and, on the CLI, an executable `suggested_retry_args` that rewrites only that assignment. The guidance follows the invoking scope (a bulk `update-many` row is routed under `update_many`, not `update`), and when the same invocation already sets that field through a declared flag, alias or option, no route or retry is offered, because the retry would carry two values for one field ([pm-wftvem](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-wftvem.toon); tracker record excluded from npm); reserved core keys keep `core_item_field_requires_dedicated_flag`. `SchemaFieldDefinition.type` is the same closed union used by `pm schema add-field`: `string | number | boolean | string_array | array | object`. Unsupported values fail at compile time for TypeScript authors and at activation for JavaScript packages, with a did-you-mean hint on typos. `string_array` is the repeatable string collection; `array` and `object` require JSON containers. Active fields support `get`, `list` and `search` projections with `--fields name` or `--fields item.name`, preserving declared value types through `PmClient` and CLI reads. Disabled packages do not contribute selectors. Tracked by [pm-gh1571](../.agents/pm/issues/pm-gh1571.toon). Item fields an extension registers are set through the repeatable `--field name=value` assignment, not through a per-field option, so a name such as `full` or `limit` leaves `pm list --full`, `pm list --limit` and `pm search --full` working as before; the built-in option collision check that `pm schema add-field` applies does not apply to them. Such a name still meets the projection-mode vocabulary of `--output-include` (`full` there selects the full projection), so select it with `--fields <name>` ([pm-3s4jwl](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-3s4jwl.toon); tracker record excluded from npm).
309
+ - `api.registerItemFields(fields)` adds custom metadata fields. Agents can set declared fields with repeatable `pm create --field name=value` and `pm update <id> --field name=value`; undeclared names are rejected. Extension declarations are matched first; a name that no active extension declares but the project schema does (for example `gate_evidence`) is refused with `project_schema_field_requires_declared_flag`, which names a CLI flag and an SDK option that each set only that field (each is omitted when every spelling is shared with another declared field or with an option of the command itself) and, on the CLI, an executable `suggested_retry_args` that rewrites only that assignment. The guidance follows the invoking scope (a bulk `update-many` row is routed under `update_many`, not `update`), and when the same invocation already sets that field through a declared flag, alias or option, no route or retry is offered, because the retry would carry two values for one field ([pm-wftvem](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-wftvem.toon); tracker record excluded from npm); reserved core keys keep `core_item_field_requires_dedicated_flag`. `SchemaFieldDefinition.type` is the same closed union used by `pm schema add-field`: `string | number | boolean | string_array | array | object`. Unsupported values fail at compile time for TypeScript authors and at activation for JavaScript packages, with a did-you-mean hint on typos. `string_array` is the repeatable string collection; `array` and `object` require JSON containers. Active fields support `get`, `list` and `search` projections with `--fields name` or `--fields item.name`, preserving declared value types through `PmClient` and CLI reads. Disabled packages do not contribute selectors. Tracked by [pm-gh1571](../.agents/pm/issues/pm-gh1571.toon). Item fields an extension registers are set through the repeatable `--field name=value` assignment, not through a per-field option, so a name such as `full` or `limit` leaves `pm list --full`, `pm list --limit` and `pm search --full` working as before; the built-in option collision check that `pm schema add-field` applies does not apply to them. Such a name still meets the projection-mode vocabulary of `--output-include` (`full` there selects the full projection), so select it with `--fields <name>` ([pm-3s4jwl](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-3s4jwl.toon); tracker record excluded from npm). A field named after built-in item metadata (`priority`, `status` and the other reserved keys in `RESERVED_ITEM_FIELD_NAMES`) is dropped at activation with the warning `extension_item_field_reserved:<layer>:<package>:<field>:rename=<prefix>_<field>`, which `pm package doctor` and `pm health` report; the package's other fields and every `pm create` and `pm update` keep working. Before, one such field made every create and update exit 2 with an untyped `command_failed` ([pm-dhlij3](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-dhlij3.toon); tracker record excluded from npm).
310
310
  - Custom fields whose camel-case option name is already owned by a canonical MCP input remain usable through `options.<name>`, but authoring surfaces report the collision instead of allowing silent top-level shadowing. `pm schema add-field`, `pm profile lint`, and `pm package doctor` name the field, canonical `mcp_tool_input` owner, and nested recovery path. SDK authors can preflight the same rule with `resolvePmToolCustomFieldCollision`. A separate, stricter rule covers CLI options: a field whose key, flag or alias equals a built-in option of a command it is registered for is refused by `pm schema add-field` and `pm profile apply` with `schema_field_option_collision`, because the built-in option would stop working there; give profile fields a project-specific prefix or list only commands where the name is free.
311
311
  - `api.registerItemTypes(types)` adds custom item types.
312
312
  - `api.registerRelationshipKinds(definitions)` adds validated graph semantics. Definitions declare direction, inverse spelling, ordering/precedence, hierarchy, cardinality, lifecycle, aliases, payload schema, compatibility version, and self-edge policy. Active definitions govern CLI, MCP, and SDK dependency mutation admission as well as workspace graph assembly; mutation aliases are stored canonically. Requires the `schema` capability and is governed by the `schema.relationshipkinds` policy surface. See [relationship mutation admission](RELATIONSHIP_GRAPH.md#contract), tracked by [pm-7dsolo](../.agents/pm/issues/pm-7dsolo.toon).
@@ -377,6 +377,53 @@ pieces (`password="$PW","…"`, a YAML single-quoted scalar whose doubled
377
377
  quotes are data), and a closing quote that another quote or a word follows
378
378
  (`echo "api_key=${EMPTY}""…"`) continues the shell word, as before.
379
379
 
380
+ The same rule ends the value of a quoted key that sits in a string
381
+ ([pm-gh1781](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1781.toon);
382
+ tracker record excluded from npm), so a member such as
383
+ `'password': '${BUILD_PASSWORD}'` inside compact JSON text
384
+ (`{"title":"'password': '${BUILD_PASSWORD}'","updated":"…"}`) is judged as in
385
+ pretty-printed JSON, and a whole `$NAME` or `%NAME%` value there is a
386
+ placeholder too. Only a value with a quote after its first character, or
387
+ right after it, reads the lexer; for a key nested in a container already
388
+ judged, the lexer resumes from a checkpoint kept every 1024 code units, so the
389
+ structured pass stays linear. A quote right after a letter, digit or
390
+ underscore opens no string, but in a shell it can open a segment of the word
391
+ (`foo"[" --'password'=${EMPTY}",""…"`, or `foo'["' …`, where the double
392
+ quote sits inside the single-quoted segment), and from there the lexer cannot
393
+ tell a segment's closing quote from a string's opening one, of either kind. A
394
+ line that declined a quote therefore reads as shell, where a closing quote
395
+ that more characters follow continues the word: no later string on the line
396
+ is trusted to end a value, and the value keeps its quoted pieces. A cut
397
+ only ever removes a finding, so it is made only where the string state is
398
+ unambiguous; keeping that distrust local to the affected segment is owned by
399
+ [pm-ghgf4a](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-ghgf4a.toon)
400
+ (tracker record excluded from npm). A Python string prefix (`r"…"`, `b'…'`, `rb"…"`, `f"…"` and the
401
+ other combinations) opens its string with the escapes an unprefixed one has,
402
+ so `b'…\'` closes where a shell closes it: a prefix alone never shows Python
403
+ context. A Python string that escapes an apostrophe therefore reads as a
404
+ shell close, and a later member on its line keeps the conservative reading
405
+ (a false positive [pm-ghgf4a](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-ghgf4a.toon)
406
+ owns, never a hidden literal). Outside every string a backslash before a quote
407
+ is a shell escape but a literal path separator to PowerShell and cmd.exe
408
+ (`C:\temp\"…"`), so it makes the line ambiguous in the same way. In JSON text
409
+ every quote opens, closes or is escaped, so none is declined there.
410
+
411
+ A single-quoted value is judged under each reading a format gives it.
412
+ - **Decoded:** with Python and JavaScript escapes decoded.
413
+ - **Backslashes kept:** over the span the escape-aware scan closes. This is
414
+ an upper bound for Python, which keeps an unrecognized escape such as `\q`.
415
+ - **Text:** the reading a shell word and a TOML literal string share, where a
416
+ backslash never escapes. The value ends at its first closing quote and keeps
417
+ the pieces joined after it, so a quoted piece that ends in a backslash and
418
+ the characters joined after it reach Bash as one word. For YAML, which escapes a quote by doubling it, this reading is
419
+ a scanner's approximation.
420
+
421
+ A span the escape-aware scan leaves open because its last quote is escaped
422
+ is not read with its backslashes kept, since that would count the quote as
423
+ data. So `'\\\\\\\'` (seven backslashes) is seven data characters in the
424
+ text reading and four in the decoded one, both below the literal minimum,
425
+ while eight backslashes are still reported.
426
+
380
427
  A whole Windows variable (`%DB_PASSWORD%`) is a placeholder for every
381
428
  key-named rule. `cmd.exe` reads `set NAME=value` to the end of the line, so an
382
429
  unquoted text value is whole only when nothing but blanks follows it on its
package/docs/SDK.md CHANGED
@@ -3714,7 +3714,9 @@ or `powershell`), otherwise `cmd` on Windows and `posix` elsewhere. Pass a
3714
3714
  explicitly. `quoteCmdCommandArg` caret-escapes an argument that holds `%` or
3715
3715
  `"`, so cmd.exe can neither expand `%VAR%` nor split the line.
3716
3716
  `quotePowerShellCommandArg` emits a single-quoted literal, and
3717
- `quotePosixCommandArg` single-quotes an argument that holds `!`. The
3717
+ `quotePosixCommandArg` single-quotes an argument that holds `!` or a line
3718
+ break, or ends in a backslash, the spellings bash 3.2's history scanner
3719
+ would misread in double quotes. The
3718
3720
  redaction rules above recognize a credential in every one of these
3719
3721
  spellings, also when the rendered command is embedded in a JSON string.
3720
3722
 
@@ -76,9 +76,18 @@ a flag or alias the parser would split is refused with
76
76
  `schema_field_flag_invalid`, and an option that shadows a built-in option of a
77
77
  command the field is registered for with `schema_field_option_collision`. A
78
78
  definition left exactly as stored is not judged again, so an unrelated write
79
- keeps a legacy definition, which `pm validate --check-metadata` keeps reporting
80
- unless the registry drops it entirely (pm-x9r2h3 tracks reporting those)
81
- ([pm-3s4jwl](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-3s4jwl.toon);
79
+ keeps a legacy definition, which `pm validate --check-metadata` keeps reporting,
80
+ including one the registry drops entirely
81
+ ([pm-3s4jwl](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-3s4jwl.toon),
82
+ [pm-x9r2h3](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-x9r2h3.toon);
83
+ tracker records excluded from npm). The registry reads the last definition of
84
+ each key, the fields file after the inline list, so a stored copy that a
85
+ proposal makes effective, such as an earlier duplicate exposed by removing the
86
+ later one, is judged as a change, as the registry resolves it. A spelling the
87
+ registry drops (a blank alias) cannot shadow an option, so on a stored entry it
88
+ stays a `pm validate --check-metadata` report; only a newly supplied one is
89
+ refused
90
+ ([pm-2nwcgg](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-2nwcgg.toon);
82
91
  tracker record excluded from npm).
83
92
 
84
93
  Request `includePreview: true` to receive an optional `preview` settings tree
package/marketplace.json CHANGED
@@ -1 +1 @@
1
- {"name":"pm","owner":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"description":"Official marketplace for pm CLI — native git-based project management for Claude Code and AI coding agents.","version":"2026.11.26","plugins":[{"name":"pm-claude","source":"./plugins/pm-claude","description":"Native pm CLI integration for Claude Code — 32 MCP tools, 14 workflow skills with slash invocations, 4 subagents, hybrid TUI task tracking, session context injection, and coordination subagents for git-based project management without leaving Claude Code.","version":"2026.11.26","author":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"homepage":"https://github.com/unbraind/pm-cli","repository":"https://github.com/unbraind/pm-cli","license":"MIT","keywords":["pm-cli","project-management","mcp","tasks","agents","workflows","git-native","task-tracker","ai"],"category":"productivity"}]}
1
+ {"name":"pm","owner":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"description":"Official marketplace for pm CLI — native git-based project management for Claude Code and AI coding agents.","version":"2026.11.28","plugins":[{"name":"pm-claude","source":"./plugins/pm-claude","description":"Native pm CLI integration for Claude Code — 32 MCP tools, 14 workflow skills with slash invocations, 4 subagents, hybrid TUI task tracking, session context injection, and coordination subagents for git-based project management without leaving Claude Code.","version":"2026.11.28","author":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"homepage":"https://github.com/unbraind/pm-cli","repository":"https://github.com/unbraind/pm-cli","license":"MIT","keywords":["pm-cli","project-management","mcp","tasks","agents","workflows","git-native","task-tracker","ai"],"category":"productivity"}]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unbrained/pm-cli",
3
- "version": "2026.11.26",
3
+ "version": "2026.11.28",
4
4
  "description": "Git-native project management CLI for humans and agents.",
5
5
  "type": "module",
6
6
  "packageManager": "pnpm@11.28.5",
@@ -1 +1 @@
1
- {"name":"@unbrained/pm-beads","version":"2026.11.26","private":true,"type":"module","description":"First-party pm package for importing Beads JSONL records.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-beads#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-beads"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","project-management","beads"],"pm":{"aliases":["beads"],"extensions":["extensions/beads"],"catalog":{"display_name":"Beads Import","category":"migration","summary":"Import Beads JSONL records into pm while preserving source IDs.","tags":["migration","beads","import"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-beads#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-beads","report":"https://github.com/unbraind/pm-cli/issues"}},"docs":["README.md"],"examples":["README.md"]}}
1
+ {"name":"@unbrained/pm-beads","version":"2026.11.28","private":true,"type":"module","description":"First-party pm package for importing Beads JSONL records.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-beads#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-beads"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","project-management","beads"],"pm":{"aliases":["beads"],"extensions":["extensions/beads"],"catalog":{"display_name":"Beads Import","category":"migration","summary":"Import Beads JSONL records into pm while preserving source IDs.","tags":["migration","beads","import"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-beads#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-beads","report":"https://github.com/unbraind/pm-cli/issues"}},"docs":["README.md"],"examples":["README.md"]}}
@@ -1 +1 @@
1
- {"name":"@unbrained/pm-calendar","version":"2026.11.26","private":true,"type":"module","description":"First-party pm package for calendar and agenda views.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-calendar#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-calendar"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","project-management","calendar","agenda"],"pm":{"aliases":["calendar"],"extensions":["extensions/calendar"],"catalog":{"display_name":"Calendar Views","category":"workflow","summary":"Show agenda, day, week, and month views for deadlines, reminders, and scheduled events.","tags":["calendar","agenda","workflow"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-calendar#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-calendar","report":"https://github.com/unbraind/pm-cli/issues"}},"docs":["README.md"],"examples":["README.md"]}}
1
+ {"name":"@unbrained/pm-calendar","version":"2026.11.28","private":true,"type":"module","description":"First-party pm package for calendar and agenda views.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-calendar#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-calendar"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","project-management","calendar","agenda"],"pm":{"aliases":["calendar"],"extensions":["extensions/calendar"],"catalog":{"display_name":"Calendar Views","category":"workflow","summary":"Show agenda, day, week, and month views for deadlines, reminders, and scheduled events.","tags":["calendar","agenda","workflow"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-calendar#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-calendar","report":"https://github.com/unbraind/pm-cli/issues"}},"docs":["README.md"],"examples":["README.md"]}}
@@ -1 +1 @@
1
- {"name":"@unbrained/pm-command-kit","version":"2026.11.26","private":true,"type":"module","description":"First-party pm exemplar package for the commands capability: registerCommand, registerFlags, and registerParser.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-command-kit#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-command-kit"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","project-management","sdk","commands","exemplar"],"pm":{"aliases":["command-kit"],"extensions":["extensions/command-kit"],"catalog":{"display_name":"Command Kit Exemplar","category":"sdk","summary":"Copy-paste-able exemplar for registerCommand, registerFlags, and registerParser.","tags":["sdk","commands","parser","exemplar"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-command-kit#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-command-kit","report":"https://github.com/unbraind/pm-cli/issues"}},"docs":["README.md"],"examples":["README.md"]}}
1
+ {"name":"@unbrained/pm-command-kit","version":"2026.11.28","private":true,"type":"module","description":"First-party pm exemplar package for the commands capability: registerCommand, registerFlags, and registerParser.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-command-kit#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-command-kit"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","project-management","sdk","commands","exemplar"],"pm":{"aliases":["command-kit"],"extensions":["extensions/command-kit"],"catalog":{"display_name":"Command Kit Exemplar","category":"sdk","summary":"Copy-paste-able exemplar for registerCommand, registerFlags, and registerParser.","tags":["sdk","commands","parser","exemplar"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-command-kit#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-command-kit","report":"https://github.com/unbraind/pm-cli/issues"}},"docs":["README.md"],"examples":["README.md"]}}
@@ -1 +1 @@
1
- {"name":"@unbrained/pm-digital-twin","version":"2026.11.26","private":true,"type":"module","description":"Beyond-PM exemplar: a temporal production-facility digital twin built entirely on public pm SDK and extension primitives.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-digital-twin#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-digital-twin"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","sdk","digital-twin","event-sourcing","temporal-graph","exemplar"],"pm":{"aliases":["digital-twin","twin"],"extensions":["extensions/digital-twin"],"catalog":{"display_name":"Digital Twin SDK Exemplar","category":"sdk","summary":"Temporal facility graph proving event replay, point-in-time state, invariants, federation, checkpoints, and compact exports through public SDK contracts.","tags":["sdk","digital-twin","event-sourcing","graph","offline-first","exemplar"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-digital-twin#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-digital-twin","report":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-digital-twin/GAP_REPORT.md"}},"docs":["README.md","GAP_REPORT.md"],"examples":["README.md"]}}
1
+ {"name":"@unbrained/pm-digital-twin","version":"2026.11.28","private":true,"type":"module","description":"Beyond-PM exemplar: a temporal production-facility digital twin built entirely on public pm SDK and extension primitives.","homepage":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-digital-twin#readme","repository":{"type":"git","url":"git+https://github.com/unbraind/pm-cli.git","directory":"packages/pm-digital-twin"},"bugs":{"url":"https://github.com/unbraind/pm-cli/issues"},"keywords":["pm-package","sdk","digital-twin","event-sourcing","temporal-graph","exemplar"],"pm":{"aliases":["digital-twin","twin"],"extensions":["extensions/digital-twin"],"catalog":{"display_name":"Digital Twin SDK Exemplar","category":"sdk","summary":"Temporal facility graph proving event replay, point-in-time state, invariants, federation, checkpoints, and compact exports through public SDK contracts.","tags":["sdk","digital-twin","event-sourcing","graph","offline-first","exemplar"],"links":{"docs":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-digital-twin#readme","repository":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-digital-twin","report":"https://github.com/unbraind/pm-cli/tree/main/packages/pm-digital-twin/GAP_REPORT.md"}},"docs":["README.md","GAP_REPORT.md"],"examples":["README.md"]}}