@unbrained/pm-cli 2026.11.28 → 2026.11.29

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 (190) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/commander-usage.js +4 -4
  3. package/dist/cli/error-guidance.js +5 -5
  4. package/dist/cli/linked-resource-value-list.js +2 -0
  5. package/dist/cli-bundle/bundle-manifest.json +1 -1
  6. package/dist/cli-bundle/chunks/{chunk-YEMFOKFG.js → chunk-3AZOATC2.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-LMDIKSDZ.js → chunk-3E53F7QY.js} +8 -8
  8. package/dist/cli-bundle/chunks/{chunk-OFIYA3PI.js → chunk-3TK2YOVB.js} +3 -3
  9. package/dist/cli-bundle/chunks/{chunk-C4O5TZY3.js → chunk-3US5T6B2.js} +60 -60
  10. package/dist/cli-bundle/chunks/chunk-4EBHZBM2.js +2 -0
  11. package/dist/cli-bundle/chunks/{chunk-MGJMQSN4.js → chunk-4QA5O64H.js} +2 -2
  12. package/dist/cli-bundle/chunks/chunk-5EFS7K7Y.js +1 -0
  13. package/dist/cli-bundle/chunks/chunk-CNZOC6JD.js +2 -0
  14. package/dist/cli-bundle/chunks/{chunk-TWRUA2NH.js → chunk-CV2B4JUB.js} +2 -2
  15. package/dist/cli-bundle/chunks/chunk-DBASKWBO.js +2 -0
  16. package/dist/cli-bundle/chunks/{chunk-Q6BGQRCB.js → chunk-EYEQC3L2.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-O2SWNEBW.js → chunk-FRYNDVLN.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-GSLOAEY2.js +2 -0
  19. package/dist/cli-bundle/chunks/{chunk-T7RZPIOB.js → chunk-JFPCL45G.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-CTM26LUE.js → chunk-JQHLOSSS.js} +2 -2
  21. package/dist/cli-bundle/chunks/chunk-JV7LREUF.js +3 -0
  22. package/dist/cli-bundle/chunks/chunk-K3MVVDLN.js +2 -0
  23. package/dist/cli-bundle/chunks/{chunk-6OIHST4I.js → chunk-K672XXGQ.js} +3 -3
  24. package/dist/cli-bundle/chunks/{chunk-T7UTG56V.js → chunk-KCR4NF2A.js} +3 -3
  25. package/dist/cli-bundle/chunks/chunk-L7HON3BE.js +23 -0
  26. package/dist/cli-bundle/chunks/chunk-LQEB6GSY.js +2 -0
  27. package/dist/cli-bundle/chunks/{chunk-ZXERHBMA.js → chunk-NLHNB2L3.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-FG4TNQQM.js → chunk-NRCGGNOE.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-KHFUHGL3.js → chunk-OGVSGXQX.js} +2 -2
  30. package/dist/cli-bundle/chunks/{chunk-CATRDGAB.js → chunk-PY6A7ULK.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-O2WNNIKK.js → chunk-Q6GIFUCW.js} +2 -2
  32. package/dist/cli-bundle/chunks/{chunk-CDUV7DFD.js → chunk-R6M5OGJH.js} +2 -2
  33. package/dist/cli-bundle/chunks/chunk-RWHS77ME.js +113 -0
  34. package/dist/cli-bundle/chunks/chunk-SV27NNXQ.js +2 -0
  35. package/dist/cli-bundle/chunks/chunk-TE6FBDHP.js +4 -0
  36. package/dist/cli-bundle/chunks/{chunk-LRGYV6QQ.js → chunk-VI3A7UZ2.js} +2 -2
  37. package/dist/cli-bundle/chunks/{chunk-E2LQ6LCJ.js → chunk-WLZ5KVM2.js} +2 -2
  38. package/dist/cli-bundle/chunks/chunk-WNB62BGK.js +10 -0
  39. package/dist/cli-bundle/chunks/chunk-X5D5YUHR.js +2 -0
  40. package/dist/cli-bundle/chunks/chunk-ZK4CY24V.js +2 -0
  41. package/dist/cli-bundle/chunks/{chunk-JQYPSABI.js → chunk-ZSBPE36C.js} +2 -2
  42. package/dist/cli-bundle/chunks/field-definition-losses-XKE4DRUA.js +2 -0
  43. package/dist/cli-bundle/chunks/{field-option-collisions-G4LQ2646.js → field-option-collisions-OZE43TOH.js} +2 -2
  44. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-H3MMNXXG.js → indexed-receipt-blobs-DR3FDHND.js} +2 -2
  45. package/dist/cli-bundle/chunks/{item-revision-O7L3AA2W.js → item-revision-3WXNNFLP.js} +2 -2
  46. package/dist/cli-bundle/chunks/item-transaction-DJ5GAITL.js +2 -0
  47. package/dist/cli-bundle/chunks/linked-resource-value-list-2655COY2.js +2 -0
  48. package/dist/cli-bundle/chunks/{mutation-actor-A45DFDEO.js → mutation-actor-QOKPDYM4.js} +2 -2
  49. package/dist/cli-bundle/chunks/mutation-admission-JNJHB3E6.js +2 -0
  50. package/dist/cli-bundle/chunks/{register-list-query-FCPGG2UT.js → register-list-query-YGVUE4YZ.js} +2 -2
  51. package/dist/cli-bundle/chunks/{register-mutation-VD3JX23I.js → register-mutation-3JVZQDHH.js} +2 -2
  52. package/dist/cli-bundle/chunks/register-operations-LCHUHKRA.js +2 -0
  53. package/dist/cli-bundle/chunks/{register-setup-EWAZZWPL.js → register-setup-IJ7M3VUK.js} +2 -2
  54. package/dist/cli-bundle/chunks/runtime-schema-OAIUNQRL.js +2 -0
  55. package/dist/cli-bundle/chunks/{settlement-hook-KWBOSRDZ.js → settlement-hook-BIVNGBZF.js} +2 -2
  56. package/dist/cli-bundle/chunks/{stage-UIDZMTE5.js → stage-7BD7U2BX.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/chunk-26P6C6OO.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-2CQFGJQ6.js +8 -0
  59. package/dist/cli-bundle/focused-chunks/chunk-42SU4LK3.js +2 -0
  60. package/dist/cli-bundle/focused-chunks/{chunk-7P6OGPEG.js → chunk-5NSWNLFE.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{chunk-Y7EC2L2G.js → chunk-ACTBMSCH.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/chunk-BPBKHY6H.js +100 -0
  63. package/dist/cli-bundle/focused-chunks/{chunk-YC3PFFDE.js → chunk-BPOU2S44.js} +57 -57
  64. package/dist/cli-bundle/focused-chunks/chunk-BZ3PUUPG.js +2 -0
  65. package/dist/cli-bundle/focused-chunks/{chunk-AHCOSTL7.js → chunk-CWQLW4ZO.js} +2 -2
  66. package/dist/cli-bundle/focused-chunks/{chunk-7EKKUYN5.js → chunk-EUDAUT6T.js} +3 -3
  67. package/dist/cli-bundle/focused-chunks/chunk-GTUPHXKR.js +2 -0
  68. package/dist/cli-bundle/focused-chunks/{chunk-NGFDPEP7.js → chunk-IRYNVGKH.js} +3 -3
  69. package/dist/cli-bundle/focused-chunks/chunk-JFICNN4T.js +4 -0
  70. package/dist/cli-bundle/focused-chunks/{chunk-J4V3J5MC.js → chunk-KLOHZNJ4.js} +2 -2
  71. package/dist/cli-bundle/focused-chunks/chunk-KPASZGBL.js +2 -0
  72. package/dist/cli-bundle/focused-chunks/{chunk-Q6JCMFGU.js → chunk-KWKPX36T.js} +2 -2
  73. package/dist/cli-bundle/focused-chunks/{chunk-ZYHGQIQ7.js → chunk-LKTRICZR.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/{chunk-OEMI52ZS.js → chunk-LSVRZ4KQ.js} +2 -2
  75. package/dist/cli-bundle/focused-chunks/chunk-MYWUMVCZ.js +4 -0
  76. package/dist/cli-bundle/focused-chunks/{chunk-CQLOYNJY.js → chunk-NNLENKU7.js} +2 -2
  77. package/dist/cli-bundle/focused-chunks/chunk-NO5MUY4I.js +2 -0
  78. package/dist/cli-bundle/focused-chunks/{chunk-XVCMYFQU.js → chunk-NZA2LP4Y.js} +2 -2
  79. package/dist/cli-bundle/focused-chunks/{chunk-HCWDMFWA.js → chunk-PPCBCPIZ.js} +2 -2
  80. package/dist/cli-bundle/focused-chunks/chunk-QTV6UE2Q.js +44 -0
  81. package/dist/cli-bundle/focused-chunks/{chunk-VNU3IFBL.js → chunk-S4AC7OMI.js} +2 -2
  82. package/dist/cli-bundle/focused-chunks/{chunk-YX75PQFO.js → chunk-S5VG7RFY.js} +2 -2
  83. package/dist/cli-bundle/focused-chunks/{chunk-JD45Y2BR.js → chunk-TSZVCALS.js} +2 -2
  84. package/dist/cli-bundle/focused-chunks/{chunk-O33WUEAF.js → chunk-TX24L7RQ.js} +2 -2
  85. package/dist/cli-bundle/focused-chunks/chunk-WJAUHPXD.js +2 -0
  86. package/dist/cli-bundle/focused-chunks/{chunk-4SX2BN4V.js → chunk-XR6MLUVW.js} +2 -2
  87. package/dist/cli-bundle/focused-chunks/field-definition-losses-GGA6FUHD.js +2 -0
  88. package/dist/cli-bundle/focused-chunks/{field-option-collisions-63YQ2J3N.js → field-option-collisions-HABQYZMQ.js} +2 -2
  89. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-PG2VJ3MB.js → indexed-receipt-blobs-EUYZJR5R.js} +2 -2
  90. package/dist/cli-bundle/focused-chunks/{item-revision-PV5O6F5Y.js → item-revision-YH5R7YPW.js} +2 -2
  91. package/dist/cli-bundle/focused-chunks/item-transaction-YZ2PUPGM.js +2 -0
  92. package/dist/cli-bundle/focused-chunks/{mutation-actor-2AAUJG2Z.js → mutation-actor-DJ2VRLKG.js} +2 -2
  93. package/dist/cli-bundle/focused-chunks/mutation-admission-3SECKVKY.js +2 -0
  94. package/dist/cli-bundle/focused-chunks/runtime-schema-IDRXWCC4.js +2 -0
  95. package/dist/cli-bundle/focused-chunks/{settlement-hook-4MGRERCT.js → settlement-hook-Q6MJQKIE.js} +2 -2
  96. package/dist/cli-bundle/focused-chunks/{stage-56RYPMBK.js → stage-FEJT2UCG.js} +2 -2
  97. package/dist/cli-bundle/main.js +26 -26
  98. package/dist/cli-bundle/sdk-authoring.js +1 -1
  99. package/dist/cli-bundle/sdk-contracts.js +1 -1
  100. package/dist/cli-bundle/sdk-core.js +1 -1
  101. package/dist/cli-bundle/sdk-governance.js +1 -1
  102. package/dist/cli-bundle/sdk-graph.js +1 -1
  103. package/dist/cli-bundle/sdk-merge.js +63 -63
  104. package/dist/cli-bundle/sdk-query.js +1 -1
  105. package/dist/cli-bundle/sdk-runtime.js +1 -1
  106. package/dist/cli-bundle/sdk-testing.js +1 -1
  107. package/dist/cli-bundle/sdk.js +1 -1
  108. package/dist/core/extensions/item-fields.d.ts +18 -1
  109. package/dist/core/extensions/item-fields.js +1 -1
  110. package/dist/core/extensions/loader.js +1 -1
  111. package/dist/core/fs/fs-utils.d.ts +8 -0
  112. package/dist/core/fs/fs-utils.js +2 -2
  113. package/dist/core/item/item-type-inspection.js +2 -0
  114. package/dist/core/item/type-registry.js +1 -1
  115. package/dist/core/schema/runtime-schema.d.ts +19 -0
  116. package/dist/core/schema/runtime-schema.js +2 -2
  117. package/dist/core/store/settings.d.ts +7 -0
  118. package/dist/core/store/settings.js +5 -5
  119. package/dist/sdk/extension-command-context.js +2 -2
  120. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  121. package/dist/sdk/governance/validate.js +1 -1
  122. package/dist/sdk/public-surface.json +1 -1
  123. package/dist/sdk/runtime/schema.js +1 -1
  124. package/dist/sdk/schema/field-definition-losses.js +1 -1
  125. package/dist/sdk/schema/schema-file-entry-losses.js +2 -0
  126. package/dist/sdk/test/execution.d.ts +9 -1
  127. package/dist/sdk/test/execution.js +4 -4
  128. package/docs/COMMANDS.md +3 -1
  129. package/docs/CONFIGURATION.md +1 -1
  130. package/docs/EXTENSIONS.md +1 -1
  131. package/docs/SDK_AUDITED_MUTATIONS.md +9 -0
  132. package/marketplace.json +1 -1
  133. package/node_modules/fast-json-patch/README.md +2 -2
  134. package/node_modules/fast-json-patch/dist/fast-json-patch.js +604 -818
  135. package/node_modules/fast-json-patch/dist/fast-json-patch.min.js +4 -8
  136. package/node_modules/fast-json-patch/package.json +14 -17
  137. package/package.json +2 -2
  138. package/packages/pm-beads/package.json +1 -1
  139. package/packages/pm-calendar/package.json +1 -1
  140. package/packages/pm-command-kit/package.json +1 -1
  141. package/packages/pm-digital-twin/package.json +1 -1
  142. package/packages/pm-governance-audit/package.json +1 -1
  143. package/packages/pm-guide-shell/package.json +1 -1
  144. package/packages/pm-kanban/package.json +1 -1
  145. package/packages/pm-lifecycle-hooks/package.json +1 -1
  146. package/packages/pm-linked-test-adapters/package.json +1 -1
  147. package/packages/pm-search-advanced/package.json +1 -1
  148. package/packages/pm-templates/package.json +1 -1
  149. package/packages/pm-todos/package.json +1 -1
  150. package/packages/pm-vcs/package.json +1 -1
  151. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  152. package/plugins/pm-claude/package.json +1 -1
  153. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  154. package/plugins/pm-codex/package.json +1 -1
  155. package/plugins/pm-codex/plugin.json +1 -1
  156. package/runtime-dependencies.json +1 -1
  157. package/dist/cli-bundle/chunks/chunk-2YD2AERA.js +0 -2
  158. package/dist/cli-bundle/chunks/chunk-54AQJTUH.js +0 -3
  159. package/dist/cli-bundle/chunks/chunk-56DKWGHE.js +0 -2
  160. package/dist/cli-bundle/chunks/chunk-56GUDMXN.js +0 -113
  161. package/dist/cli-bundle/chunks/chunk-5ECCMDSU.js +0 -2
  162. package/dist/cli-bundle/chunks/chunk-6RBD2AKU.js +0 -2
  163. package/dist/cli-bundle/chunks/chunk-D3I5AHNN.js +0 -2
  164. package/dist/cli-bundle/chunks/chunk-MO6PPUI6.js +0 -2
  165. package/dist/cli-bundle/chunks/chunk-RGE3XW3A.js +0 -2
  166. package/dist/cli-bundle/chunks/chunk-SP6CDM6B.js +0 -31
  167. package/dist/cli-bundle/chunks/chunk-WKDKBS4P.js +0 -4
  168. package/dist/cli-bundle/chunks/chunk-YLS2N4SN.js +0 -2
  169. package/dist/cli-bundle/chunks/field-definition-losses-JFMMMVTV.js +0 -2
  170. package/dist/cli-bundle/chunks/item-transaction-4XC74ULD.js +0 -2
  171. package/dist/cli-bundle/chunks/mutation-admission-SIUIMAEO.js +0 -2
  172. package/dist/cli-bundle/chunks/register-operations-KHJD4GFZ.js +0 -2
  173. package/dist/cli-bundle/chunks/runtime-schema-3RAXYNG5.js +0 -2
  174. package/dist/cli-bundle/focused-chunks/chunk-5MZXU6HB.js +0 -2
  175. package/dist/cli-bundle/focused-chunks/chunk-64DSKZJN.js +0 -100
  176. package/dist/cli-bundle/focused-chunks/chunk-A5B43EWU.js +0 -2
  177. package/dist/cli-bundle/focused-chunks/chunk-E4C6T3NL.js +0 -2
  178. package/dist/cli-bundle/focused-chunks/chunk-KMGI5GZP.js +0 -2
  179. package/dist/cli-bundle/focused-chunks/chunk-MSLRDKWL.js +0 -4
  180. package/dist/cli-bundle/focused-chunks/chunk-RBOWKXFV.js +0 -8
  181. package/dist/cli-bundle/focused-chunks/chunk-TF57RHS2.js +0 -2
  182. package/dist/cli-bundle/focused-chunks/chunk-X5ZVPFK7.js +0 -4
  183. package/dist/cli-bundle/focused-chunks/chunk-Z4FWJGQG.js +0 -2
  184. package/dist/cli-bundle/focused-chunks/chunk-ZHHFOQSL.js +0 -44
  185. package/dist/cli-bundle/focused-chunks/chunk-ZUAPUBJK.js +0 -2
  186. package/dist/cli-bundle/focused-chunks/field-definition-losses-NUZO3JCP.js +0 -2
  187. package/dist/cli-bundle/focused-chunks/item-transaction-S5QXBGAT.js +0 -2
  188. package/dist/cli-bundle/focused-chunks/mutation-admission-X7HHNERR.js +0 -2
  189. package/dist/cli-bundle/focused-chunks/runtime-schema-5J2ONRNV.js +0 -2
  190. package/node_modules/fast-json-patch/webpack.config.js +0 -63
@@ -1,2 +1,2 @@
1
- import{createUnknownSubcommandError as f}from"../agent/subcommand-recovery.js";import{assertSchemaPreviewSupported as g}from"./schema-preview.js";import{WORKFLOW_POLICY_ACTIONS as S,runWorkflowPolicyAction as h}from"../governance/workflow-policy.js";import{parseRuntimeInteger as l,readRuntimeString as o,readRuntimeStringArray as d}from"../runtime-input.js";import{SCHEMA_SUBCOMMANDS as y,runSchemaAddField as b,runSchemaAddStatus as A,runSchemaAddType as R,runSchemaApplyPreset as w,runSchemaEvolutionMigration as T,runSchemaInferTypes as C,runSchemaList as M,runSchemaListFields as q,runSchemaRemoveField as O,runSchemaRemoveStatus as v,runSchemaRemoveType as F,runSchemaShow as _,runSchemaShowField as I,runSchemaShowStatus as k}from"../schema.js";import{getOwnHandler as P,readRequiredString as p}from"./context.js";function L(r){const e=o(r.args,"subcommand")??p(r.options,"subcommand"),a=r.args.alias??r.options.alias;return{ctx:r,subcommand:e.trim().toLowerCase(),name:o(r.args,"name")??o(r.options,"name"),author:o(r.args,"author")??o(r.options,"author"),force:r.args.force===!0||r.options.force===!0,aliases:a===void 0?void 0:d(a)}}function U(r){const{ctx:e,subcommand:a,name:n,author:t,force:s}=r,u=P({list:()=>M(e.global),show:()=>_(n,e.global),"show-status":()=>k(n,e.global),"list-fields":()=>q(e.global),"show-field":()=>I(n,e.global),"remove-type":()=>F(n,{author:t,force:s},e.global),"remove-field":()=>O(n,{author:t,force:s},e.global),"remove-status":()=>v(n,{author:t,force:s},e.global),"apply-preset":()=>w(o(e.args,"typePreset")??o(e.options,"typePreset"),{author:t,force:s},e.global)},a);return u?u():null}function H(r){const{ctx:e,name:a,author:n,force:t,aliases:s}=r,i=e.args.commands??e.options.commands,u=e.args.requiredTypes??e.options.requiredTypes;return b(a,{type:o(e.args,"fieldType")??o(e.options,"fieldType"),commands:i===void 0?void 0:d(i),description:o(e.args,"description")??o(e.options,"description"),cliFlag:o(e.args,"cliFlag")??o(e.options,"cliFlag"),alias:s,required:e.args.required===!0||e.options.required===!0,requiredOnCreate:e.args.requiredOnCreate===!0||e.options.requiredOnCreate===!0,allowUnset:!(e.args.allowUnset===!1||e.options.allowUnset===!1),requiredTypes:u===void 0?void 0:d(u),author:n,force:t},e.global)}function E(r){const{ctx:e,name:a,author:n,force:t,aliases:s}=r,i=e.args.role??e.options.role;return A(a,{role:i===void 0?void 0:d(i),alias:s,description:o(e.args,"description")??o(e.options,"description"),order:l(e.args.order??e.options.order,"schema add-status order"),author:n,force:t},e.global)}function W(r){const{ctx:e,name:a,author:n,force:t,aliases:s}=r;return R(a,{description:o(e.args,"description")??o(e.options,"description"),defaultStatus:o(e.args,"defaultStatus")??o(e.args,"default_status")??o(e.options,"defaultStatus")??o(e.options,"default_status"),folder:o(e.args,"folder")??o(e.options,"folder"),alias:s,author:n,force:t},e.global)}function N(r){const{ctx:e,subcommand:a,name:n,author:t,force:s}=r,i=o(e.args,"to")??p(e.options,"to"),u=o(e.args,"migrationId")??o(e.args,"migration_id")??o(e.options,"migrationId")??o(e.options,"migration_id"),m=o(e.args,"fieldTypeScope")??o(e.options,"fieldTypeScope")??o(e.args,"type")??o(e.options,"type"),c=a==="rename-type"?{kind:"rename-type",from:n??"",to:i}:a==="rename-field"?{kind:"rename-field",from:n??"",to:i,...m===void 0?{}:{type:m}}:{kind:"remap-status",from:n??"",to:i};return T(c,{migrationId:u,dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:t,force:s},e.global)}function B(r){const e=L(r);g(e.subcommand,r.args.dryRun===!0||r.options.dryRun===!0);const a=S.find(t=>t===e.subcommand);if(a)return h(a,e.name,{definition:r.args.definition??r.options.definition,policy:o(r.args,"policy")??o(r.options,"policy"),message:o(r.args,"message")??o(r.options,"message"),author:e.author,dryRun:r.args.dryRun===!0||r.options.dryRun===!0},r.global);const n=U(e);if(n!==null)return n;if(["rename-type","rename-field","remap-status"].includes(e.subcommand))return N(e);if(e.subcommand==="add-field")return H(e);if(e.subcommand==="add-status")return E(e);if(e.subcommand==="add-type")return r.args.infer===!0||r.options.infer===!0?C({minCount:l(r.args.minCount??r.options.minCount,"schema infer minCount"),apply:r.args.apply===!0||r.options.apply===!0,author:e.author,force:e.force},r.global):W(e);throw f({command_path:"schema",token:e.subcommand,allowed:y,exit_code:64})}export{B as runMcpSchemaAction};
1
+ import{createUnknownSubcommandError as f}from"../agent/subcommand-recovery.js";import{assertSchemaPreviewSupported as g}from"./schema-preview.js";import{WORKFLOW_POLICY_ACTIONS as S,runWorkflowPolicyAction as h}from"../governance/workflow-policy.js";import{parseRuntimeInteger as p,readRuntimeString as o,readRuntimeStringArray as m}from"../runtime-input.js";import{SCHEMA_SUBCOMMANDS as y,runSchemaAddField as b,runSchemaAddStatus as A,runSchemaAddType as R,runSchemaApplyPreset as w,runSchemaEvolutionMigration as T,runSchemaInferTypes as C,runSchemaList as M,runSchemaListFields as q,runSchemaRemoveField as O,runSchemaRemoveStatus as v,runSchemaRemoveType as _,runSchemaShow as F,runSchemaShowField as I,runSchemaShowStatus as P}from"../schema.js";import{getOwnHandler as k,readRequiredString as c}from"./context.js";function L(r){const e=o(r.args,"subcommand")??c(r.options,"subcommand"),a=r.args.alias??r.options.alias;return{ctx:r,subcommand:e.trim().toLowerCase(),name:o(r.args,"name")??o(r.options,"name"),author:o(r.args,"author")??o(r.options,"author"),force:r.args.force===!0||r.options.force===!0,aliases:a===void 0?void 0:m(a)}}function U(r){const{ctx:e,subcommand:a,name:n,author:t,force:s}=r,u=k({list:()=>M(e.global),show:()=>F(n,e.global),"show-status":()=>P(n,e.global),"list-fields":()=>q(e.global),"show-field":()=>I(n,e.global),"remove-type":()=>_(n,{author:t,force:s},e.global),"remove-field":()=>O(n,{author:t,force:s},e.global),"remove-status":()=>v(n,{author:t,force:s},e.global),"apply-preset":()=>w(o(e.args,"typePreset")??o(e.options,"typePreset"),{author:t,force:s},e.global)},a);return u?u():null}function H(r,e){return[r.args[e],r.options[e]].find(a=>typeof a=="string")}function E(r){const{ctx:e,name:a,author:n,force:t}=r,s=e.args.alias??e.options.alias,i=Array.isArray(s)?s.map(l=>String(l)):r.aliases,u=e.args.commands??e.options.commands,d=e.args.requiredTypes??e.options.requiredTypes;return b(a,{type:o(e.args,"fieldType")??o(e.options,"fieldType"),commands:u===void 0?void 0:m(u),description:o(e.args,"description")??o(e.options,"description"),cliFlag:H(e,"cliFlag"),alias:i,required:e.args.required===!0||e.options.required===!0,requiredOnCreate:e.args.requiredOnCreate===!0||e.options.requiredOnCreate===!0,allowUnset:!(e.args.allowUnset===!1||e.options.allowUnset===!1),requiredTypes:d===void 0?void 0:m(d),author:n,force:t},e.global)}function W(r){const{ctx:e,name:a,author:n,force:t,aliases:s}=r,i=e.args.role??e.options.role;return A(a,{role:i===void 0?void 0:m(i),alias:s,description:o(e.args,"description")??o(e.options,"description"),order:p(e.args.order??e.options.order,"schema add-status order"),author:n,force:t},e.global)}function N(r){const{ctx:e,name:a,author:n,force:t,aliases:s}=r;return R(a,{description:o(e.args,"description")??o(e.options,"description"),defaultStatus:o(e.args,"defaultStatus")??o(e.args,"default_status")??o(e.options,"defaultStatus")??o(e.options,"default_status"),folder:o(e.args,"folder")??o(e.options,"folder"),alias:s,author:n,force:t},e.global)}function B(r){const{ctx:e,subcommand:a,name:n,author:t,force:s}=r,i=o(e.args,"to")??c(e.options,"to"),u=o(e.args,"migrationId")??o(e.args,"migration_id")??o(e.options,"migrationId")??o(e.options,"migration_id"),d=o(e.args,"fieldTypeScope")??o(e.options,"fieldTypeScope")??o(e.args,"type")??o(e.options,"type"),l=a==="rename-type"?{kind:"rename-type",from:n??"",to:i}:a==="rename-field"?{kind:"rename-field",from:n??"",to:i,...d===void 0?{}:{type:d}}:{kind:"remap-status",from:n??"",to:i};return T(l,{migrationId:u,dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:t,force:s},e.global)}function D(r){const e=L(r);g(e.subcommand,r.args.dryRun===!0||r.options.dryRun===!0);const a=S.find(t=>t===e.subcommand);if(a)return h(a,e.name,{definition:r.args.definition??r.options.definition,policy:o(r.args,"policy")??o(r.options,"policy"),message:o(r.args,"message")??o(r.options,"message"),author:e.author,dryRun:r.args.dryRun===!0||r.options.dryRun===!0},r.global);const n=U(e);if(n!==null)return n;if(["rename-type","rename-field","remap-status"].includes(e.subcommand))return B(e);if(e.subcommand==="add-field")return E(e);if(e.subcommand==="add-status")return W(e);if(e.subcommand==="add-type")return r.args.infer===!0||r.options.infer===!0?C({minCount:p(r.args.minCount??r.options.minCount,"schema infer minCount"),apply:r.args.apply===!0||r.options.apply===!0,author:e.author,force:e.force},r.global):N(e);throw f({command_path:"schema",token:e.subcommand,allowed:y,exit_code:64})}export{D as runMcpSchemaAction};
2
2
  //# sourceMappingURL=schema.js.map
@@ -1,2 +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};
1
+ import{constants as f}from"node:fs";import{open as _}from"node:fs/promises";import c from"node:path";import{DEFAULT_RUNTIME_SCHEMA_FILE_PATHS as o,filePathForSchemaSection as l,inspectRuntimeFieldDefinition as g,readFieldsFromSchemaFile as p}from"../../core/schema/runtime-schema.js";import{readOptionalRegularFile as y}from"../../core/fs/fs-utils.js";import{getSettingsPath as F}from"../../core/store/paths.js";import{validateSettings as w}from"../../core/store/settings-validator.js";async function u(e){try{const i=await _(e,f.O_RDONLY|f.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=w(e);return i.success?i.data.schema:void 0}async function S(e,i){const t=l(e,i?.files?.fields,o.fields);return p(await u(t))??[]}async function j(e,i){const t=await y(l(e,i?.files?.fields,o.fields));if(t===null)return[];let a;try{a=JSON.parse(t)}catch{return[]}return p(a)??[]}function O(e,i,t,a){return i.flatMap((r,d)=>{const n=a(r,d);if(n.dropped===void 0&&n.ignored.length===0)return[];const s=r?.[t];return[{source:e,index:d,[t]:typeof s=="string"?s:null,...n.dropped===void 0?{}:{dropped:n.dropped},...n.ignored.length===0?{}:{ignored:n.ignored}}]})}function m(e,i){return O(e,i,"key",t=>g(t).loss)}async function k(e,i){const t=v(await u(F(e)));return{inline:t,configured:t?.files===void 0?i:t}}function x(e,i){return c.relative(e,i).split(c.sep).join("/")}async function C(e,i,t){const{inline:a,configured:r}=await k(e,i),d=l(e,r.files?.fields,o.fields),n=[...m("settings.json",a?.fields??[]),...m(x(e,d),await S(e,r))];if(n.length===0)return{details:{},warnings:[]};const s=n.filter(h=>h.dropped!==void 0).length;return{details:{schema_field_definition_loss_count:n.length,schema_field_definition_losses:n.slice(0,t),schema_field_definition_losses_truncated:n.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:[...s>0?[`validate_schema_field_definition_dropped:${s}`]:[],...n.length>s?[`validate_schema_field_definition_partial:${n.length-s}`]:[]]}}export{O as collectDefinitionLosses,j as readAdmittedFieldsFileDefinitions,k as readConfiguredSchema,S as readFieldsFileDefinitions,u as readStoredJson,C as scanFieldDefinitionLosses,x as trackerRelativePath};
2
2
  //# sourceMappingURL=field-definition-losses.js.map
@@ -0,0 +1,2 @@
1
+ import{DEFAULT_RUNTIME_SCHEMA_FILE_PATHS as c,filePathForSchemaSection as f,inspectRuntimeStatusDefinition as g,readStatusesFromSchemaFile as y,readTypeDefinitionsFromSchemaFile as S}from"../../core/schema/runtime-schema.js";import{inspectItemTypeDefinition as F}from"../../core/item/item-type-inspection.js";import{collectDefinitionLosses as h,readConfiguredSchema as v,readStoredJson as _,trackerRelativePath as m}from"./field-definition-losses.js";function u(e,t,i){if(t.length===0)return{details:{},warnings:[]};const s=t.filter(n=>n.dropped!==void 0).length;return{details:{[`schema_${e}_definition_loss_count`]:t.length,[`schema_${e}_definition_losses`]:t.slice(0,i),[`schema_${e}_definition_losses_truncated`]:t.length>i},warnings:[...s>0?[`validate_schema_${e}_definition_dropped:${s}`]:[],...t.length>s?[`validate_schema_${e}_definition_partial:${t.length-s}`]:[]]}}async function P(e,t,i){const{configured:s}=await v(e,t),n=f(e,s.files?.statuses,c.statuses),r=f(e,s.files?.types,c.types),o=u("status",h(m(e,n),y(await _(n))??[],"id",(a,p)=>g(a,p).loss),i),d=u("type",h(m(e,r),S(await _(r))??[],"name",a=>F(a,"schema_file").loss),i),l=[...o.warnings,...d.warnings];return{details:{...o.details,...d.details,...l.length===0?{}:{schema_definition_loss_fix_hint:"A dropped status or type is not registered, and a definition read in part ignores the listed members. Edit or remove the listed entries in the named schema file: give every status an id and every type a name, use strings for names, descriptions, aliases and folders, and agent, human or gate for execution_role."}},warnings:l}}export{P as scanSchemaFileEntryLosses};
2
+ //# sourceMappingURL=schema-file-entry-losses.js.map
@@ -201,7 +201,15 @@ trust_boundary:"provenance";
201
201
  /** Human guidance for reproducible execution without presenting string shape as enforcement. */
202
202
  advisory:string;}
203
203
  /** Classify linked-test commands without pretending string shape is a security boundary. */
204
- export declare function classifyLinkedTestCommandSafety(command:string):LinkedTestCommandSafetyClassification;declare function parseLinkedTestTimeoutSeconds(timeoutSecondsRaw:string|undefined,timeoutAliasRaw:string|undefined):number|undefined;declare function parseAddJsonEntries(raw:string[]|undefined):LinkedTest[];declare function endLinkedTestProgress(context:LinkedTestProgressContext,executionResult:Pick<LinkedTestExecutionResult,"timedOut"|"maxBufferExceeded"|"outputTruncated"|"exitCode"|"signal">,startedAt:number,mode:LinkedTestProgressMode):void;declare function runLinkedTestCommand(command:string,timeoutMs:number,env:NodeJS.ProcessEnv,progressContext:LinkedTestProgressContext,progressMode:LinkedTestProgressMode,cwd?:string):Promise<LinkedTestExecutionResult>;declare function formatLinkedTestExecutionError(result:LinkedTestExecutionResult,timeoutMs:number):string;
204
+ export declare function classifyLinkedTestCommandSafety(command:string):LinkedTestCommandSafetyClassification;declare function parseLinkedTestTimeoutSeconds(timeoutSecondsRaw:string|undefined,timeoutAliasRaw:string|undefined):number|undefined;declare function parseAddJsonEntries(raw:string[]|undefined):LinkedTest[];
205
+ /**
206
+ * Whether one value of a repeatable linked-test flag is a complete entry its
207
+ * own parser admits (pm-gh1791). A usage refusal replays several values after
208
+ * one flag as one occurrence each only when every value is admitted on its
209
+ * own. A bare `--add` value is not, because it may be a word of a command the
210
+ * shell split.
211
+ */
212
+ export declare function admitsLinkedTestFlagValue(flag:string,value:string):boolean;declare function endLinkedTestProgress(context:LinkedTestProgressContext,executionResult:Pick<LinkedTestExecutionResult,"timedOut"|"maxBufferExceeded"|"outputTruncated"|"exitCode"|"signal">,startedAt:number,mode:LinkedTestProgressMode):void;declare function runLinkedTestCommand(command:string,timeoutMs:number,env:NodeJS.ProcessEnv,progressContext:LinkedTestProgressContext,progressMode:LinkedTestProgressMode,cwd?:string):Promise<LinkedTestExecutionResult>;declare function formatLinkedTestExecutionError(result:LinkedTestExecutionResult,timeoutMs:number):string;
205
213
  /** Implements classify linked test failure for the public runtime surface of this module. */
206
214
  export declare function classifyLinkedTestFailure(result:Pick<LinkedTestExecutionResult,"stdout"|"stderr"|"spawnError"|"signal"|"timedOut"|"maxBufferExceeded">):LinkedTestFailureCategory;declare function copyIntoSandboxIfPresent(sourcePath:string,targetPath:string,recursive?:boolean,makeDirectory?:(targetPath:string,options:{recursive:true;})=> Promise<unknown>):Promise<void>;
207
215
  /** Seed settings and extension configuration, auditing schema-only copies against their own initialized history. */
@@ -1,6 +1,6 @@
1
- import{readJsonPathValue as K,splitJsonPathSegments as xt}from"./json-path.js";import{isItemRevisionConflict as Tt}from"../lifecycle/item-revision.js";import{detectEmptyLinkedTestRun as gt,findLinkedTestExecutionReceipt as wt,renderLinkedTestRestoreCommand as Ct,resolveLinkedTestRestoreScope as Pt}from"./execution-receipts.js";import{seedLinkedTestWorkspaceSnapshot as vt}from"./workspace-snapshot.js";import{detectLinkedTestCommandNotFound as St}from"./command-resolution.js";import{updateLinkedTest as Lt,parseLinkedTestUpdateOptions as Et,assertLinkedTestEditUsage as yt}from"./update.js";import{admitLinkedTestRequest as ae,assertLinkedTestCommand as le,linkedTestsHaveSameIdentity as me}from"./entry.js";import{countFailureCategories as Rt,createLinkedTestSetupGate as bt,isLinkedTestSetup as Mt,orderLinkedTestsSetupFirst as Ot,parseLinkedTestPhase as It,resolveSetupWorkspaceRefusal as At,withLinkedTestSetupEntries as jt}from"./run-phases.js";import{assertInitializedTracker as Nt}from"../environment/tracker-preflight.js";import{spawn as Ft}from"node:child_process";import{killProcessTree as fe}from"../../core/shared/process-tree.js";const _e={taskkillTimeoutMs:null};import{cp as pe,mkdir as V,mkdtemp as he,open as J,readdir as z,rm as j,symlink as $t}from"node:fs/promises";import{tmpdir as ke}from"node:os";import f from"node:path";import{getActiveExtensionRegistrations as Dt}from"../../core/extensions/index.js";import{isFileMissingError as Ut,pathExists as D,readFileIfExists as xe}from"../../core/fs/fs-utils.js";import{getWorkspaceHistoryPath as Te,writeWorkspaceJsonWithHistory as ge}from"../../core/history/workspace-history.js";import{resolveItemTypeRegistry as Gt}from"../../core/item/type-registry.js";import{createStdinTokenResolver as Wt,parseCsvKv as we,parseOptionalNumber as Ce}from"../../core/item/parse.js";import{EXIT_CODE as p}from"../../core/shared/constants.js";import{resolveAuthor as I}from"../../core/shared/author.js";import{PmCliError as h}from"../../core/shared/errors.js";import{stableValueEquals as Pe}from"../../core/shared/serialization.js";import{nowIso as U}from"../../core/shared/time.js";import{locateItem as qt,mutateItem as Ht,readLocatedItem as Bt}from"../../core/store/item-store.js";import{getSettingsPath as b,ITEM_FILE_EXTENSIONS as Kt,resolveGlobalPmRoot as Vt,resolvePmRoot as ve}from"../../core/store/paths.js";import{readSettings as Y}from"../../core/store/settings.js";import{appendTrackedTestRunSummary as Jt,buildTrackedTestRunHistory as zt}from"../../core/test/item-test-run-tracking.js";import{runInit as Se}from"../init.js";import{looksLikeStructuredLinkedTestEntry as Yt,normalizeStructuredLinkedTestEntry as Xt}from"./entry.js";import{LINKED_TEST_PM_CONTEXT_MODE_VALUES as Le,LINKED_TEST_PROTECTED_ENV_KEYS as Ee,parseLinkedTestAssertionEqualsMap as Qt,parseLinkedTestAssertionGteMap as Zt,parseLinkedTestBoolean as en,parseLinkedTestContextMode as tn,parseLinkedTestEnvClear as ye,parseLinkedTestEnvSet as Re,parseLinkedTestJsonEntries as nn,parseLinkedTestMinLines as on,parseLinkedTestRegexList as be,parseLinkedTestStringList as Me,parseLinkedTestWorkspaceContextMode as X}from"./parsers.js";import{parseOnlyIndexValue as rn,resolveLinkedTestRunSelection as sn}from"../../core/test/run-selectors.js";import{SCOPE_VALUES as cn}from"../../types/index.js";import{diffTestRunMeasurements as dn,parseTestRunMeasurements as Oe,queryTestRunMeasurementsBelow as un}from"./measurements.js";import{withHostEnvironmentBoundary as an}from"../environment/host-environment-errors.js";import{linkedCollectionMutationFields as Ie,projectLinkedCollectionMutation as Ae,writtenLinkedEntries as ln}from"../linked-artifacts.js";import{SOURCE_CONTEXT_ACCESS_ENV as je}from"../environment/source-context.js";import{assertTestMeasurementExecution as mn,assertTestMeasurementRun as Ne}from"./prerequisites.js";import{acknowledgeLinkedTests as fn,attachLinkedTestMutationProvenance as _n,resolveLinkedTestSourceRef as pn,resolveLinkedTestSourceWorkspaceRoot as hn,resolveLinkedTestTrust as Fe}from"./trust.js";const G=20*1024*1024,kn=3e3,xn=1e4,Tn=5e3,$e=120,gn=new Set(["locks","extensions","runtime"]),wn=new Set(["history","index","search","extensions","locks","runtime"]),Cn=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],Pn=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,vn=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,Sn=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function Q(e,t){const n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;const o=Number.parseInt(n,10);return!Number.isFinite(o)||o<=0?t:o}function Ln(){return Q("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",kn)}function En(){return Q("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",xn)}function yn(){return Q("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",Tn)}import{countFailureCategories as Dr}from"./run-phases.js";function De(e){const t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Ue(e){let t=0,n=0,o=0;for(const r of e){if(r.status==="passed"){t+=1;continue}if(r.status==="failed"||r.status==="refused"){n+=1;continue}o+=1}return{passed:t,failed:n,skipped:o}}function Rn(e){let t=0,n=0,o=0,r=0;for(const s of e){const i=s.execution_context;!i||i.is_pm_command!==!0||(t+=1,i.is_pm_tracker_read_command===!0&&(n+=1),i.mismatch_detected===!0&&(o+=1),i.auto_pm_context_applied===!0&&(r+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:o,auto_remediated:r}}function Ge(e){const t=e??"project";if(!cn.includes(t))throw new h(`Invalid scope "${e}"`,p.USAGE);return t}function N(e){if(!e)return"schema";const t=e.trim().toLowerCase();if(Le.includes(t))return t;throw new h(`Invalid --pm-context value "${e}". Expected one of: ${Le.join(", ")}`,p.USAGE)}function We(e){return X(e??"source","--workspace-context")}function qe(e,t,n){return n?t:X(e.workspace_context_mode,"linked test")??t}function Z(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:N(e.pm_context_mode)}function ee(e,t){return e==="auto"?t?"tracker":"schema":e}function He(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function Be(e){const{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:o}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&o==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function bn(e,t){const n={};if(!e)return n;for(const o of e){const r=Re(o,t);if(r)for(const[s,i]of Object.entries(r))n[s]=i}return n}function Mn(e,t){if(!e)return[];const n=[];for(const o of e){const r=ye(o,t);r&&n.push(...r)}return[...new Set(n)]}import{BUN_GLOBAL_FLAGS_WITH_VALUE as On,NPM_GLOBAL_FLAGS_WITH_VALUE as In,PNPM_GLOBAL_FLAGS_WITH_VALUE as An,SCRIPT_RUN_FLAGS_WITH_VALUE as jn,SCRIPT_RUN_SUBCOMMANDS as Nn,YARN_GLOBAL_FLAGS_WITH_VALUE as Fn,extractPmInvocationArgsFromSegment as te,parseLauncherSubcommand as F,parseNpmExecCommand as $n,parseNpxCommand as Ke,parsePnpmDlxCommand as Dn,resolvePmSubcommandContext as Un,splitNormalizedCommandSegments as W,stripLeadingEnvAssignments as Gn,SHELL_COMMAND_FLAG_PATTERNS as Wn,assertNoRecursiveTestAllCommand as Ve,invokesRecursiveTestAllCommand as qn,normalizeCommandForValidation as q,segmentInvokesRecursiveTestAll as Hn}from"./linked-command-detection.js";import{extractReferencedPmItemIdsFromCommand as Gr}from"./linked-command-detection.js";function Je(e){const t=q(e);return W(t).some(n=>te(n)!==null)}function ne(e){const t=q(e);return W(t).some(n=>{const o=te(n);if(!o)return!1;const r=Un(o);return r?Sn.has(r.subcommand):!1})}function $(e){if(e)return Nn.has(e.subcommand)?F(e.args,jn)?.subcommand:e.subcommand}function oe(e,t){if(e==="npx"||e==="bunx")return Ke(t)?.command;if(e==="pnpm")return $(F(t,An));if(e==="npm")return $(F(t,In));if(e==="yarn")return $(F(t,Fn));if(e==="bun")return $(F(t,On))}function H(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function ze(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function re(e){const t=e.split(" ").filter(i=>i.length>0),n=Gn(t);if(n.length===0)return!1;const[o,...r]=n,s=Wn.get(o);if(s){const i=r.findIndex(c=>s.test(c));return i>=0&&re(r.slice(i+1).join(" "))}return o==="vitest"||o.endsWith("/vitest")||o.endsWith("/vitest.mjs")?!0:o==="node"?Bn(r):Kn(o,r)}function Bn(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function Kn(e,t){return e==="npx"||e==="bunx"?H(Ke(t)?.command):e==="pnpm"||e==="npm"?H((e==="pnpm"?Dn(t):$n(t))?.command)||H(oe(e,t)):(e==="yarn"||e==="bun")&&H(oe(e,t))}function Ar(e){const t=q(e),n=W(t),o=n.some(s=>!ze(s)&&re(s)),r=n.some(ze);return{accepted:!0,command_kind:o?"direct_runner":r?"sandbox_runner":"other",tracker_isolation:"runtime_injected",trust_boundary:"provenance",advisory:o?"Accepted with runtime-injected tracker isolation. Prefer the repository sandbox runner when available for reproducible build and coverage setup.":"Accepted with runtime-injected tracker isolation and provenance checks before execution."}}function Vn(e){if(qn(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function Jn(e){return e?e.map(zn):[]}function zn(e){const t=e.trim(),n=Yt(t)?Xt(we(e,"--add"),"--add"):{command:t},o=x(n.command);if(!o)throw new h("--add requires command=<value> or a bare command (path=<value> is optional metadata)",p.USAGE);return Ve(o),{command:o,path:x(n.path),scope:Ge(n.scope),timeout_seconds:Ye(x(n.timeout_seconds),x(n.timeout)),pm_context_mode:tn(x(n.pm_context_mode),"--add"),workspace_context_mode:X(x(n.workspace_context_mode),"--add"),env_set:Re(x(n.env_set),"--add"),env_clear:ye(x(n.env_clear),"--add"),shared_host_safe:en(x(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Me(x(n.assert_stdout_contains)),assert_stdout_regex:be(x(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Me(x(n.assert_stderr_contains)),assert_stderr_regex:be(x(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:on(x(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Qt(x(n.assert_json_field_equals),"--add"),assert_json_field_gte:Zt(x(n.assert_json_field_gte),"--add"),note:x(n.note),phase:It(n.phase,"--add")}}function x(e){const t=e?.trim();return t&&t.length>0?t:void 0}function Ye(e,t){if(e&&t&&e!==t)throw new h("--add timeout and timeout_seconds must match when both are provided",p.USAGE);const n=e??t;if(n===void 0)return;const o=Math.floor(Ce(n,"timeout_seconds"));if(o<=0)throw new h("--add timeout_seconds must be a positive integer",p.USAGE);return o}function Xe(e){return e?e.flatMap(t=>{const n=nn(t,"--add-json");for(const o of n){const r=o.command;if(!r)throw new h("--add-json requires a non-empty command string",p.USAGE);Ve(r)}return n}):[]}function Yn(e){return e?e.map(t=>{const n=t.trim();if(!n)throw new h("--remove requires command or path value",p.USAGE);const o=/^(command|path)\s*=/i.exec(n);if(o){const r=n.slice(o[0].length).trim();if(!r)throw new h("--remove requires a non-empty command=<value> or path=<value>",p.USAGE);return{kind:o[1].toLowerCase(),value:r}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new h("--remove structured selectors require command=<value> or path=<value>",p.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){const r=we(n,"--remove"),s=r.path!==void 0?"path":"command",i=r.path??r.command;if(!i?.trim())throw new h("--remove requires command=<value> and/or path=<value>",p.USAGE);return{kind:s,value:i.trim()}}return{kind:"either",value:n}}):[]}function Xn(e){return e?[...new Set(e.map(t=>{const n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new h("--remove-index must be a positive integer",p.USAGE);return n}))]:[]}function Qn(e){try{e.stdin?.end()}catch{}}function Qe(e){const t=e.trim().replaceAll(/\s+/g," ");return t.length<=$e?t:`${t.slice(0,$e-3)}...`}function Ze(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function se(e){try{process.stderr.write(`${e}
2
- `)}catch{}}function Zn(e,t){if(!Ze(t))return null;const n=Qe(e.command),o=Date.now();se(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);const r=setInterval(()=>{const s=Date.now()-o;se(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${s} command="${n}"`)},En());return r.unref?.(),r}function et(e,t,n,o){if(!Ze(o))return;const r=Qe(e.command),s=Date.now()-n,c=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",d=[];t.timedOut&&d.push("reason=timeout"),t.maxBufferExceeded&&d.push("reason=max_buffer"),t.outputTruncated&&d.push("output=truncated"),t.signal&&d.push(`signal=${t.signal}`);const a=t.exitCode===null?"null":String(t.exitCode),u=d.length>0?` ${d.join(" ")}`:"";se(`[pm test] linked-test ${e.index}/${e.total} end status=${c} exit_code=${a} elapsed_ms=${s}${u} command="${r}"`)}function eo(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function to(e,t){let n=!1;return async()=>{if(n)return;n=!0;const o=e.pid,r={alive:()=>e.exitCode===null&&e.signalCode===null,kill:()=>{e.exitCode===null&&e.signalCode===null&&e.kill("SIGKILL")}};if(!o||o<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await fe(o,r,_e);return}try{process.kill(-o,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{fe(o,r,_e)},Ln()),t.forceKillTimer.unref?.()}}function no(e){return new Promise(t=>{let n=!1,o=null;const r=(s,i=!1)=>{n||(n=!0,o&&(clearTimeout(o),o=null),i&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(s))};e.on("exit",(s,i)=>{n||(o=setTimeout(()=>{r({code:s,signal:i},!0)},yn()),o.unref?.())}),e.on("close",(s,i)=>{r({code:s,signal:i})})})}function oo(e,t,n,o,r){return Ft(e,{cwd:r,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,o]})}async function tt(e){const t=await J(e,"r");try{const n=(await t.stat()).size,o=Math.min(n,G),r=Buffer.alloc(o);return o>0&&await t.read(r,0,o,0),{text:r.toString("utf8"),truncated:n>G}}finally{await t.close()}}async function nt(e,t,n,o,r,s=process.cwd()){const i=Date.now(),c=await he(f.join(ke(),"pm-linked-test-output-"));try{const d=f.join(c,"stdout.log"),a=f.join(c,"stderr.log"),[u,l]=await Promise.all([J(d,"w"),J(a,"w")]);let k;try{k=oo(e,n,u.fd,l.fd,s)}catch(L){throw await Promise.all([u.close(),l.close()]),L}const w=no(k);let T;k.on("error",L=>{T=L.message}),await Promise.all([u.close(),l.close()]),Qn(k);const _={heartbeat:Zn(o,r),forceKillTimer:null,timedOutTimer:null},g=to(k,_);let v=!1;_.timedOutTimer=setTimeout(()=>{v=!0,g()},t),_.timedOutTimer.unref?.();const{code:E,signal:P}=await w;eo(_);const[O,m]=await Promise.all([tt(d),tt(a)]),C=O.truncated||m.truncated,S=C?`
1
+ import{readJsonPathValue as K,splitJsonPathSegments as Pt}from"./json-path.js";import{isItemRevisionConflict as vt}from"../lifecycle/item-revision.js";import{detectEmptyLinkedTestRun as Lt,findLinkedTestExecutionReceipt as St,renderLinkedTestRestoreCommand as Et,resolveLinkedTestRestoreScope as yt}from"./execution-receipts.js";import{seedLinkedTestWorkspaceSnapshot as Rt}from"./workspace-snapshot.js";import{detectLinkedTestCommandNotFound as bt}from"./command-resolution.js";import{updateLinkedTest as Mt,parseLinkedTestUpdateOptions as Ot,assertLinkedTestEditUsage as It}from"./update.js";import{admitLinkedTestRequest as le,assertLinkedTestCommand as me,linkedTestsHaveSameIdentity as fe}from"./entry.js";import{countFailureCategories as At,createLinkedTestSetupGate as jt,isLinkedTestSetup as Nt,orderLinkedTestsSetupFirst as Ft,parseLinkedTestPhase as $t,resolveSetupWorkspaceRefusal as Dt,withLinkedTestSetupEntries as Ut}from"./run-phases.js";import{assertInitializedTracker as Gt}from"../environment/tracker-preflight.js";import{spawn as Wt}from"node:child_process";import{killProcessTree as _e}from"../../core/shared/process-tree.js";const he={taskkillTimeoutMs:null};import{cp as pe,mkdir as V,mkdtemp as ke,open as J,readdir as z,rm as j,symlink as qt}from"node:fs/promises";import{tmpdir as xe}from"node:os";import f from"node:path";import{getActiveExtensionRegistrations as Ht}from"../../core/extensions/index.js";import{isFileMissingError as Bt,pathExists as D,readFileIfExists as Te}from"../../core/fs/fs-utils.js";import{getWorkspaceHistoryPath as ge,writeWorkspaceJsonWithHistory as we}from"../../core/history/workspace-history.js";import{resolveItemTypeRegistry as Kt}from"../../core/item/type-registry.js";import{createStdinTokenResolver as Vt,parseCsvKv as Ce,parseOptionalNumber as Pe}from"../../core/item/parse.js";import{EXIT_CODE as h}from"../../core/shared/constants.js";import{resolveAuthor as I}from"../../core/shared/author.js";import{PmCliError as p}from"../../core/shared/errors.js";import{stableValueEquals as ve}from"../../core/shared/serialization.js";import{nowIso as U}from"../../core/shared/time.js";import{locateItem as Jt,mutateItem as zt,readLocatedItem as Yt}from"../../core/store/item-store.js";import{getSettingsPath as b,ITEM_FILE_EXTENSIONS as Xt,resolveGlobalPmRoot as Qt,resolvePmRoot as Le}from"../../core/store/paths.js";import{readSettings as Y}from"../../core/store/settings.js";import{appendTrackedTestRunSummary as Zt,buildTrackedTestRunHistory as en}from"../../core/test/item-test-run-tracking.js";import{runInit as Se}from"../init.js";import{assertLinkedTestContext as tn,looksLikeStructuredLinkedTestEntry as Ee,normalizeStructuredLinkedTestEntry as nn}from"./entry.js";import{LINKED_TEST_PM_CONTEXT_MODE_VALUES as ye,LINKED_TEST_PROTECTED_ENV_KEYS as Re,parseLinkedTestAssertionEqualsMap as on,parseLinkedTestAssertionGteMap as rn,parseLinkedTestBoolean as sn,parseLinkedTestContextMode as cn,parseLinkedTestEnvClear as be,parseLinkedTestEnvSet as Me,parseLinkedTestJsonEntries as dn,parseLinkedTestMinLines as un,parseLinkedTestRegexList as Oe,parseLinkedTestStringList as Ie,parseLinkedTestWorkspaceContextMode as X}from"./parsers.js";import{parseOnlyIndexValue as an,resolveLinkedTestRunSelection as ln}from"../../core/test/run-selectors.js";import{SCOPE_VALUES as mn}from"../../types/index.js";import{diffTestRunMeasurements as fn,parseTestRunMeasurements as Ae,queryTestRunMeasurementsBelow as _n}from"./measurements.js";import{withHostEnvironmentBoundary as hn}from"../environment/host-environment-errors.js";import{linkedCollectionMutationFields as je,projectLinkedCollectionMutation as Ne,writtenLinkedEntries as pn}from"../linked-artifacts.js";import{SOURCE_CONTEXT_ACCESS_ENV as Fe}from"../environment/source-context.js";import{assertTestMeasurementExecution as kn,assertTestMeasurementRun as $e}from"./prerequisites.js";import{acknowledgeLinkedTests as xn,attachLinkedTestMutationProvenance as Tn,resolveLinkedTestSourceRef as gn,resolveLinkedTestSourceWorkspaceRoot as wn,resolveLinkedTestTrust as De}from"./trust.js";const G=20*1024*1024,Cn=3e3,Pn=1e4,vn=5e3,Ue=120,Ln=new Set(["locks","extensions","runtime"]),Sn=new Set(["history","index","search","extensions","locks","runtime"]),En=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],yn=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,Rn=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,bn=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function Q(e,t){const n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;const o=Number.parseInt(n,10);return!Number.isFinite(o)||o<=0?t:o}function Mn(){return Q("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",Cn)}function On(){return Q("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",Pn)}function In(){return Q("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",vn)}import{countFailureCategories as Wr}from"./run-phases.js";function Ge(e){const t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function We(e){let t=0,n=0,o=0;for(const r of e){if(r.status==="passed"){t+=1;continue}if(r.status==="failed"||r.status==="refused"){n+=1;continue}o+=1}return{passed:t,failed:n,skipped:o}}function An(e){let t=0,n=0,o=0,r=0;for(const s of e){const i=s.execution_context;!i||i.is_pm_command!==!0||(t+=1,i.is_pm_tracker_read_command===!0&&(n+=1),i.mismatch_detected===!0&&(o+=1),i.auto_pm_context_applied===!0&&(r+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:o,auto_remediated:r}}function qe(e){const t=e??"project";if(!mn.includes(t))throw new p(`Invalid scope "${e}"`,h.USAGE);return t}function N(e){if(!e)return"schema";const t=e.trim().toLowerCase();if(ye.includes(t))return t;throw new p(`Invalid --pm-context value "${e}". Expected one of: ${ye.join(", ")}`,h.USAGE)}function He(e){return X(e??"source","--workspace-context")}function Be(e,t,n){return n?t:X(e.workspace_context_mode,"linked test")??t}function Z(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:N(e.pm_context_mode)}function ee(e,t){return e==="auto"?t?"tracker":"schema":e}function Ke(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function Ve(e){const{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:o}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&o==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function jn(e,t){const n={};if(!e)return n;for(const o of e){const r=Me(o,t);if(r)for(const[s,i]of Object.entries(r))n[s]=i}return n}function Nn(e,t){if(!e)return[];const n=[];for(const o of e){const r=be(o,t);r&&n.push(...r)}return[...new Set(n)]}import{BUN_GLOBAL_FLAGS_WITH_VALUE as Fn,NPM_GLOBAL_FLAGS_WITH_VALUE as $n,PNPM_GLOBAL_FLAGS_WITH_VALUE as Dn,SCRIPT_RUN_FLAGS_WITH_VALUE as Un,SCRIPT_RUN_SUBCOMMANDS as Gn,YARN_GLOBAL_FLAGS_WITH_VALUE as Wn,extractPmInvocationArgsFromSegment as te,parseLauncherSubcommand as F,parseNpmExecCommand as qn,parseNpxCommand as Je,parsePnpmDlxCommand as Hn,resolvePmSubcommandContext as Bn,splitNormalizedCommandSegments as W,stripLeadingEnvAssignments as Kn,SHELL_COMMAND_FLAG_PATTERNS as Vn,assertNoRecursiveTestAllCommand as ze,invokesRecursiveTestAllCommand as Jn,normalizeCommandForValidation as q,segmentInvokesRecursiveTestAll as zn}from"./linked-command-detection.js";import{extractReferencedPmItemIdsFromCommand as Hr}from"./linked-command-detection.js";function Ye(e){const t=q(e);return W(t).some(n=>te(n)!==null)}function ne(e){const t=q(e);return W(t).some(n=>{const o=te(n);if(!o)return!1;const r=Bn(o);return r?bn.has(r.subcommand):!1})}function $(e){if(e)return Gn.has(e.subcommand)?F(e.args,Un)?.subcommand:e.subcommand}function oe(e,t){if(e==="npx"||e==="bunx")return Je(t)?.command;if(e==="pnpm")return $(F(t,Dn));if(e==="npm")return $(F(t,$n));if(e==="yarn")return $(F(t,Wn));if(e==="bun")return $(F(t,Fn))}function H(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function Xe(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function re(e){const t=e.split(" ").filter(i=>i.length>0),n=Kn(t);if(n.length===0)return!1;const[o,...r]=n,s=Vn.get(o);if(s){const i=r.findIndex(c=>s.test(c));return i>=0&&re(r.slice(i+1).join(" "))}return o==="vitest"||o.endsWith("/vitest")||o.endsWith("/vitest.mjs")?!0:o==="node"?Yn(r):Xn(o,r)}function Yn(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function Xn(e,t){return e==="npx"||e==="bunx"?H(Je(t)?.command):e==="pnpm"||e==="npm"?H((e==="pnpm"?Hn(t):qn(t))?.command)||H(oe(e,t)):(e==="yarn"||e==="bun")&&H(oe(e,t))}function Nr(e){const t=q(e),n=W(t),o=n.some(s=>!Xe(s)&&re(s)),r=n.some(Xe);return{accepted:!0,command_kind:o?"direct_runner":r?"sandbox_runner":"other",tracker_isolation:"runtime_injected",trust_boundary:"provenance",advisory:o?"Accepted with runtime-injected tracker isolation. Prefer the repository sandbox runner when available for reproducible build and coverage setup.":"Accepted with runtime-injected tracker isolation and provenance checks before execution."}}function Qn(e){if(Jn(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function Qe(e){return e?e.map(Zn):[]}function Zn(e){const t=e.trim(),n=Ee(t)?nn(Ce(e,"--add"),"--add"):{command:t},o=x(n.command);if(!o)throw new p("--add requires command=<value> or a bare command (path=<value> is optional metadata)",h.USAGE);return ze(o),{command:o,path:x(n.path),scope:qe(n.scope),timeout_seconds:Ze(x(n.timeout_seconds),x(n.timeout)),pm_context_mode:cn(x(n.pm_context_mode),"--add"),workspace_context_mode:X(x(n.workspace_context_mode),"--add"),env_set:Me(x(n.env_set),"--add"),env_clear:be(x(n.env_clear),"--add"),shared_host_safe:sn(x(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Ie(x(n.assert_stdout_contains)),assert_stdout_regex:Oe(x(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Ie(x(n.assert_stderr_contains)),assert_stderr_regex:Oe(x(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:un(x(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:on(x(n.assert_json_field_equals),"--add"),assert_json_field_gte:rn(x(n.assert_json_field_gte),"--add"),note:x(n.note),phase:$t(n.phase,"--add")}}function x(e){const t=e?.trim();return t&&t.length>0?t:void 0}function Ze(e,t){if(e&&t&&e!==t)throw new p("--add timeout and timeout_seconds must match when both are provided",h.USAGE);const n=e??t;if(n===void 0)return;const o=Math.floor(Pe(n,"timeout_seconds"));if(o<=0)throw new p("--add timeout_seconds must be a positive integer",h.USAGE);return o}function se(e){return e?e.flatMap(t=>{const n=dn(t,"--add-json");for(const o of n){const r=o.command;if(!r)throw new p("--add-json requires a non-empty command string",h.USAGE);ze(r)}return n}):[]}function et(e){return e?e.map(t=>{const n=t.trim();if(!n)throw new p("--remove requires command or path value",h.USAGE);const o=/^(command|path)\s*=/i.exec(n);if(o){const r=n.slice(o[0].length).trim();if(!r)throw new p("--remove requires a non-empty command=<value> or path=<value>",h.USAGE);return{kind:o[1].toLowerCase(),value:r}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new p("--remove structured selectors require command=<value> or path=<value>",h.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){const r=Ce(n,"--remove"),s=r.path!==void 0?"path":"command",i=r.path??r.command;if(!i?.trim())throw new p("--remove requires command=<value> and/or path=<value>",h.USAGE);return{kind:s,value:i.trim()}}return{kind:"either",value:n}}):[]}function tt(e){return e?[...new Set(e.map(t=>{const n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new p("--remove-index must be a positive integer",h.USAGE);return n}))]:[]}function nt(e){for(const t of e)tn(t);return e.length>0}function Fr(e,t){try{return e==="--add"?Ee(t.trim())&&nt(Qe([t])):e==="--add-json"?nt(se([t])):e==="--remove"?/^(?:command|path)\s*[:=]/iu.test(t.trim())&&et([t]).length===1:e==="--remove-index"&&tt([t]).length===1}catch{return!1}}function eo(e){try{e.stdin?.end()}catch{}}function ot(e){const t=e.trim().replaceAll(/\s+/g," ");return t.length<=Ue?t:`${t.slice(0,Ue-3)}...`}function rt(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function ie(e){try{process.stderr.write(`${e}
2
+ `)}catch{}}function to(e,t){if(!rt(t))return null;const n=ot(e.command),o=Date.now();ie(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);const r=setInterval(()=>{const s=Date.now()-o;ie(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${s} command="${n}"`)},On());return r.unref?.(),r}function st(e,t,n,o){if(!rt(o))return;const r=ot(e.command),s=Date.now()-n,c=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",d=[];t.timedOut&&d.push("reason=timeout"),t.maxBufferExceeded&&d.push("reason=max_buffer"),t.outputTruncated&&d.push("output=truncated"),t.signal&&d.push(`signal=${t.signal}`);const a=t.exitCode===null?"null":String(t.exitCode),u=d.length>0?` ${d.join(" ")}`:"";ie(`[pm test] linked-test ${e.index}/${e.total} end status=${c} exit_code=${a} elapsed_ms=${s}${u} command="${r}"`)}function no(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function oo(e,t){let n=!1;return async()=>{if(n)return;n=!0;const o=e.pid,r={alive:()=>e.exitCode===null&&e.signalCode===null,kill:()=>{e.exitCode===null&&e.signalCode===null&&e.kill("SIGKILL")}};if(!o||o<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await _e(o,r,he);return}try{process.kill(-o,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{_e(o,r,he)},Mn()),t.forceKillTimer.unref?.()}}function ro(e){return new Promise(t=>{let n=!1,o=null;const r=(s,i=!1)=>{n||(n=!0,o&&(clearTimeout(o),o=null),i&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(s))};e.on("exit",(s,i)=>{n||(o=setTimeout(()=>{r({code:s,signal:i},!0)},In()),o.unref?.())}),e.on("close",(s,i)=>{r({code:s,signal:i})})})}function so(e,t,n,o,r){return Wt(e,{cwd:r,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,o]})}async function it(e){const t=await J(e,"r");try{const n=(await t.stat()).size,o=Math.min(n,G),r=Buffer.alloc(o);return o>0&&await t.read(r,0,o,0),{text:r.toString("utf8"),truncated:n>G}}finally{await t.close()}}async function ct(e,t,n,o,r,s=process.cwd()){const i=Date.now(),c=await ke(f.join(xe(),"pm-linked-test-output-"));try{const d=f.join(c,"stdout.log"),a=f.join(c,"stderr.log"),[u,l]=await Promise.all([J(d,"w"),J(a,"w")]);let k;try{k=so(e,n,u.fd,l.fd,s)}catch(S){throw await Promise.all([u.close(),l.close()]),S}const w=ro(k);let T;k.on("error",S=>{T=S.message}),await Promise.all([u.close(),l.close()]),eo(k);const _={heartbeat:to(o,r),forceKillTimer:null,timedOutTimer:null},g=oo(k,_);let v=!1;_.timedOutTimer=setTimeout(()=>{v=!0,g()},t),_.timedOutTimer.unref?.();const{code:E,signal:P}=await w;no(_);const[O,m]=await Promise.all([it(d),it(a)]),C=O.truncated||m.truncated,L=C?`
3
3
  [pm linked-test output truncated at ${G} bytes per stream; the child process continued to completion]
4
- `:"";!T&&await St(e,{exitCode:E,stderr:m.text},n,s)&&(T="Linked test executable was not found. Install the tool or update the linked command before retrying.");const y={stdout:`${O.text}${S}`,stderr:m.text,exitCode:E,signal:P,timedOut:v,maxBufferExceeded:!1,outputTruncated:C,spawnError:T};return et(o,y,i,r),y}finally{await j(c,{recursive:!0,force:!0})}}function ot(e,t){const n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${G} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);const o=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,r=e.spawnError?.trim()||o||"Linked test command failed.";return n.length===0?r:`${r} ${n.join(" ")}`}function ro(e){const t=[e.spawnError??"",e.stderr,e.stdout].join(`
5
- `);return Cn.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>Pn.test(n)&&vn.test(n))}function so(e){return ro(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function rt(e,t){for(const[n,o]of Object.entries(t.env_set))Ee.has(n.toUpperCase())||(e[n]=o);for(const n of t.env_clear)Ee.has(n.toUpperCase())||delete e[n]}function io(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function co(e,t){const n={...e.env_set,...t.env_set},o=[...new Set([...e.env_clear,...t.env_clear??[]])],r=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:o,shared_host_safe:r}}function st(e,t,n){return{env_set:bn(e,"--env-set"),env_clear:Mn(t,"--env-clear"),shared_host_safe:n===!0}}async function A(e,t,n=!1,o=V){if(await D(e))try{await an("seed_linked_test",async()=>{if(await o(f.dirname(t),{recursive:!0}),n){await pe(e,t,{recursive:!0,force:!0});return}await pe(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(r){if(typeof r=="object"&&r!==null&&"code"in r&&Ut(r))return;throw r}}async function ie(e,t,n,o=!1){for(const[r,s]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(o){const i=await xe(b(r));if(i!==null){const c=await Y(s);await ge({pmRoot:s,filePath:b(s),raw:i,op:"settings:write",author:I(void 0,c.author_default),lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await A(b(r),b(s));await A(f.join(n.projectPmRoot,"extensions"),f.join(e,"extensions"),!0),await A(f.join(n.globalPmRoot,"extensions"),f.join(t,"extensions"),!0)}async function ce(e,t){if(!await D(e))return;const n=await z(e,{withFileTypes:!0});for(const o of n){if(gn.has(o.name))continue;const r=f.join(e,o.name),s=f.join(t,o.name);if(o.isDirectory()){await A(r,s,!0);continue}o.isFile()&&await A(r,s)}}async function de(e,t){const n=await xe(b(e));if(n===null||await D(Te(e)))return;const o=await Y(t);await j(Te(t),{force:!0}),await j(b(t),{force:!0}),await ge({pmRoot:t,filePath:b(t),raw:n,op:"settings:write",author:I(void 0,o.author_default),lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function M(e){if(!await D(e))return 0;let t=0;const n=await z(e,{withFileTypes:!0});for(const o of n){if(!o.isDirectory()||wn.has(o.name))continue;const r=f.join(e,o.name);let s;try{s=await z(r,{withFileTypes:!0})}catch{continue}for(const i of s)i.isFile()&&Kt.some(c=>i.name.toLowerCase().endsWith(c))&&(t+=1)}return t}function it(e){const t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function uo(e){const t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;const n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function ao(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?Pe(e,t):Object.is(e,t)}function ct(e,t,n){const o=[];o.push(...dt("stdout",t,e.assert_stdout_contains)),o.push(...ut("stdout",t,e.assert_stdout_regex)),o.push(...dt("stderr",n,e.assert_stderr_contains)),o.push(...ut("stderr",n,e.assert_stderr_regex)),o.push(...lo(t,e.assert_stdout_min_lines));const r=e.assert_json_field_equals??{},s=e.assert_json_field_gte??{};if(!(Object.keys(r).length>0||Object.keys(s).length>0))return o;let c;try{c=JSON.parse(t)}catch(d){return o.push(`stdout is not valid JSON for assert_json_field_* checks: ${d instanceof Error?d.message:String(d)}`),o}for(const[d,a]of Object.entries(r)){const u=K(c,d);if(!u.found){o.push(`assert_json_field_equals missing path "${d}"`);continue}const l=uo(a);ao(u.value,l)||o.push(`assert_json_field_equals mismatch at "${d}" (expected=${JSON.stringify(l)} actual=${JSON.stringify(u.value)})`)}for(const[d,a]of Object.entries(s)){const u=K(c,d);if(!u.found){o.push(`assert_json_field_gte missing path "${d}"`);continue}if(typeof u.value!="number"||!Number.isFinite(u.value)){o.push(`assert_json_field_gte path "${d}" resolved to non-numeric value`);continue}u.value<a&&o.push(`assert_json_field_gte failed at "${d}" (expected >= ${a}, actual ${u.value})`)}return o}function dt(e,t,n){const o=[];for(const r of n??[])t.includes(r)||o.push(`${e} missing required text: "${r}"`);return o}function ut(e,t,n){const o=[];for(const r of n??[])try{new RegExp(r,"m").test(t)||o.push(`${e} failed regex assertion: /${r}/m`)}catch(s){o.push(`${e} regex assertion is invalid: /${r}/ (${s instanceof Error?s.message:String(s)})`)}return o}function lo(e,t){if(typeof t!="number")return[];const n=e.split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}function at(e){const t=q(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:W(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&re(n))}function mo(e){return{root:e,schemaProjectPmPath:f.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:f.join(e,"schema","global"),trackerProjectPmPath:f.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:f.join(e,"tracker","global"),workspaceSnapshotRoot:f.join(e,"workspace","project"),workspaceIsolatedRoot:f.join(e,"workspace","isolated")}}function fo(e,t,n){return e.some(o=>qe(o,t,n)==="snapshot")}async function _o(e,t){const n=f.join(e,".agents"),o=f.join(n,"pm");await V(n,{recursive:!0}),await j(o,{recursive:!0,force:!0}),await $t(t,o,process.platform==="win32"?"junction":"dir")}async function lt(e,t=Se,n=!0){const o={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},o),await t(void 0,{path:e.schemaGlobalPmPath},o),n&&(await t(void 0,{path:e.trackerProjectPmPath},o),await t(void 0,{path:e.trackerGlobalPmPath},o))}async function po(e,t,n){t&&(await ie(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await ie(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await ce(t.projectPmRoot,e.trackerProjectPmPath),await ce(t.globalPmRoot,e.trackerGlobalPmPath),await de(t.projectPmRoot,e.trackerProjectPmPath),await de(t.globalPmRoot,e.trackerGlobalPmPath)))}function mt(e,t,n){return e.some(o=>{const r=o.command??"",s=r.length>0&&ne(r),i=n?.autoPmContext===!0&&s?"auto":Z(o,t,n?.overrideLinkedPmContext===!0);return ee(i,s)==="tracker"})}async function ho(e,t){return{sourceProjectItemCount:t?await M(t.projectPmRoot):0,sourceGlobalItemCount:t?await M(t.globalPmRoot):0,schemaProjectItemCount:await M(e.schemaProjectPmPath),schemaGlobalItemCount:await M(e.schemaGlobalPmPath),trackerProjectItemCount:await M(e.trackerProjectPmPath),trackerGlobalItemCount:await M(e.trackerGlobalPmPath)}}function ft(e){const t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,o=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,r=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,i=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,c=e.workspaceContextMode==="isolated"?"":i;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:o,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:r,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==r||e.counts.sourceGlobalItemCount!==s),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:i,source_workspace_root:c,trust:e.trust}}async function ko(e){const t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?N(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,o=n?Je(n):!1,r=o&&n?ne(n):!1,s=e.options?.autoPmContext===!0&&r,i=s?"auto":Z(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),c=ee(i,r),d=c==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await _o(e.layout.workspaceSnapshotRoot,d);const a=e.options?.pmRoot?await Fe(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await Fe(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:ft({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:o,isPmTrackerReadCommand:r,requestedPmContextMode:i,effectivePmContextMode:c,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:a})}}function _t(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function xo(e,t,n,o){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...o?{stdout:o.stdout,stderr:o.stderr}:{},error:n}}function To(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function go(e){if(e.executionContext.trust.trusted)return null;const t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;const o=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return To(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${o}`)}function wo(e){if(!e.linkedTest.command)return _t(e.linkedTest,e.executionContext,"No command configured for this linked test.");const t=Vn(e.linkedTest.command);return t?_t(e.linkedTest,e.executionContext,t):null}function Co(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?B(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?B(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function B(e,t,n){return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",execution_context:t,error:n}}function Po(e){const t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;const o=Be({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),r=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return B(e.linkedTest,e.executionContext,`${r} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${o}`)}function vo(e){const t=wo(e);if(t)return t;const n=go(e);if(n)return n;const o=Co(e);if(o)return o;const r=Po(e);return r||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!He(e.linkedTest)?B(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function So(e){const t=co(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return rt(n,e.runtimeDirectives),rt(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&io(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode!=="source"&&(delete n.PM_BUILD_CONSUMER_LEASE,delete n.PM_BUILD_CONSUMER_LEASE_ROOT),e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[je]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[je]="read_only"),n}function Lo(e,t,n,o){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr,...o?{execution_receipt:o}:{}}}function pt(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function Eo(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:it(e.execution),failure_category:so(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:ot(e.execution,e.timeoutMs)}}function yo(e){const t=wt(e.execution.stdout,e.execution.stderr),n=e.linkedTest.phase!=="setup"&&at(e.linkedTest.command??"");if(e.options?.failOnEmptyTestRun===!0||n){const r=gt(e.execution.stdout,e.execution.stderr);if(r)return pt({...e,emptyRunSignal:r});if(n&&!t)return pt({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}const o=ct(e.linkedTest,e.execution.stdout,e.execution.stderr);return o.length>0?xo(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${o.join("; ")}`,e.execution):Lo(e.linkedTest,e.executionContext,e.execution,t)}async function Ro(e){const t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,o=await nt(t,n,So(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return o.exitCode===0&&!o.timedOut&&!o.maxBufferExceeded?yo({...e,execution:o}):Eo({...e,execution:o,timeoutMs:n})}async function bo(e,t,n){const o=Ot(e);for(const g of o)le(g.command);const r=[],s=await he(f.join(ke(),"pm-linked-test-")),i=mo(s),c=N(n?.pmContext),d=We(n?.workspaceContext),a=n?.progress===!0?"always":"auto",u=st(n?.envSet,n?.envClear,n?.sharedHostSafe),l=n?.sourceRoots,k=hn(),w=mt(o,c,n),T=fo(o,d,n?.overrideLinkedWorkspaceContext===!0),_=await pn(k);try{await lt(i,Se,w),await V(i.workspaceIsolatedRoot,{recursive:!0}),await po(i,l,w),T&&await vt(k,i.workspaceSnapshotRoot,l?.projectPmRoot,w);const g=await ho(i,l),v=bt(),E=m=>qe(m,d,n?.overrideLinkedWorkspaceContext===!0),P=new Set(o.filter(m=>!Mt(m)).map(E)),O=async(m,C)=>{const S=v.options(m,n),y=E(m),L=At(m,y,P);if(L)return L;const R=await ko({linkedTest:m,layout:i,counts:g,sourceRoots:l,runLevelPmContextMode:c,options:n,requestedWorkspaceContextMode:d,workspaceContextMode:y,currentSourceRef:_,sourceWorkspaceRoot:k});return vo({linkedTest:m,executionContext:R.executionContext,runLevelPmContextMode:c,linkedOverridePmContextMode:R.linkedOverridePmContextMode,options:S})??await Ro({linkedTest:m,index:C,total:o.length,defaultTimeoutSeconds:t,runtimeDirectives:u,progressMode:a,executionContext:R.executionContext,options:S})};for(let m=0;m<o.length;m+=1){const C=o[m];r.push(v.blocked(C)??v.record(C,await O(C,m)))}}finally{await j(i.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}function Mo(e,t){const n=[...t];return e.filter(o=>{const r=n.findIndex(s=>me(s,o));return r>=0&&n.splice(r,1),r<0}).length}async function Oo(e){const{id:t,pmRoot:n,settings:o,typeToFolder:r}=e,s=await qt(n,t,o.id_prefix,o.item_format,r);if(!s)throw new h(`Item ${t} not found`,p.NOT_FOUND);const i=await Bt(s,{schema:o.schema});return{itemId:s.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function Io(e,t){const n=[...e];for(const o of t)n.some(r=>me(r,o))||n.push(o);return n}function Ao(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};const o=new Set(n),r=e.filter((s,i)=>o.has(i+1)?!1:!t.some(c=>c.kind==="command"?s.command===c.value:c.kind==="path"?s.path===c.value:s.command===c.value||s.path===c.value));return{tests:r,removed:e.length-r.length}}function jo(e,t,n,o){return Ao(Io(e,t),n,o)}function No(e){return[e.timeout!==void 0,e.progress===!0,(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.fullOutput===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function ht(e){if(No(e)&&e.run!==!0)throw new h("--timeout, --progress, --env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, --full-output, and --auto-pm-context require --run",p.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new h("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",p.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new h("--match, --only-index, and --only-last require --run",p.USAGE)}async function Fo(e){const{id:t,options:n,pmRoot:o,settings:r,typeToFolder:s,adds:i,removes:c,removeIndexes:d}=e;if(i.length===0&&c.length===0&&d.length===0)return Oo({id:t,pmRoot:o,settings:r,typeToFolder:s});let a=0,u=[];const l=await Ht({pmRoot:o,settings:r,id:t,op:i.length>0?"tests_add":"tests_remove",author:I(n.author,r.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(w){const T=w.metadata.tests??[],_=jo(T,i,c,d);if(ae(()=>ue(n,_.tests)),a=_.removed,(c.length>0||d.length>0)&&a===0)throw new h("No linked tests matched the requested removal selector",p.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...c.map(g=>`${g.kind}=${g.value}`),...d.map(g=>`index=${g}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return w.metadata.tests=_.tests,u=T,{changedFields:Pe(T,_.tests)?[]:["tests"]}}}),k=l.item.tests??[];return{itemId:l.item.id,tests:k,testRuns:l.item.test_runs??[],changed:l.changedFields.length>0,removed:a,written:l.changedFields.length>0?ln(u,k):[],storedRemoved:Mo(u,k)}}function ue(e,t){const n=N(e.pmContext);We(e.workspaceContext),st(e.envSet,e.envClear,e.sharedHostSafe);const o={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:rn(e.onlyIndex),onlyLast:e.onlyLast},r=e.timeout===void 0?void 0:Ce(e.timeout,"--timeout");if(r!==void 0&&r<=0)throw new h(`--timeout must be a positive number (got "${e.timeout}")`,p.USAGE);ht(e);const s=e.run===!0?jt(sn(t,o),t):void 0;if(s)for(const i of s.selected)le(i.command);return{defaultTimeoutSeconds:r,pmContextMode:n,runSelection:s,testsToRun:s?.selected??t}}async function $o(e){const{options:t,runOptions:n,pmRoot:o}=e;return t.run!==!0?[]:await bo(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun===!0||(t.measure?.length??0)>0,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:o,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:o,globalPmRoot:Vt(process.cwd())}})}function Do(e,t){const n=[];if(e.run===!0&&e.checkContext===!0){const o=Rn(t);n.push(`context_preflight:checked_pm_commands=${o.checked_pm_commands};tracker_read_commands=${o.tracker_read_commands};mismatches=${o.mismatches};auto_remediated=${o.auto_remediated}`)}return n}function Uo(e){const t=Ue(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),o=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),r=U(),s=Oe(e.options.measure,r);return{run_id:De("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:r,recorded_at:r,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:o&&o.length>0?o:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:s.length>0?s:void 0,executions:e.runResults.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}}async function Go(e){const{options:t,pmRoot:n,settings:o,itemId:r,runStartedAt:s,runResults:i,failOnSkippedTriggered:c,warnings:d}=e;if(t.run!==!0||!s)return;const a=Uo({options:t,runStartedAt:s,runResults:i,failOnSkippedTriggered:c});if(o.testing.record_results_to_items!==!0)return{entry:a,receipt:{recorded:!1,reason:"tracking_disabled",run_id:a.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await Jt({pmRoot:n,settings:o,itemId:r,author:I(t.author,o.author_default),message:`Track test run summary (${a.run_id})`,entry:a}),{entry:a,receipt:{recorded:!0,reason:"recorded",run_id:a.run_id}}}catch(u){if(Tt(u))throw u;return d.push(`test_result_tracking_failed:${r}:${u instanceof Error?u.message:String(u)}`),{entry:a,receipt:{recorded:!1,reason:"write_failed",run_id:a.run_id}}}}function kt(e,t,n){let o;if(e.metricBelow!==void 0){const r=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,r).trim(),i=e.metricBelow.slice(r+1).trim(),c=Number(i);if(r<=0||s.length===0||i.length===0||!Number.isFinite(c))throw new h("--metric-below must use name=value",p.USAGE);o=un(t,s,c)}return{measurements:n?.measurements,metric_below:o,metric_diff:e.metricDiff===void 0?void 0:dn(t,e.metricDiff)}}async function Wo(e,t,n){if(e.acknowledgeLinkedTests===!0)return fn(t,n,U())}function qo(e){const{item:t,runResults:n,failureCategories:o,runSelection:r,failOnSkippedTriggered:s,warnings:i,recording:c,measurementProjection:d,restoreScope:a}=e,u=Bo(t,e.fullHistory),l=Ho(t,r,u,a),{counts:k,receipts:w}=Ie(u);return{ok:n.every(T=>T.status!=="failed"&&T.status!=="refused")&&s!==!0,id:t.itemId,tests:l.tests,...l.omitted,run_results:n,...e.ran?{failure_categories:o}:{},selection:r?{selector:r.selector,requested:r.requested,selected_indexes:r.selected_indexes,selected_count:r.selected_count,skipped_count:r.skipped_count,...r.setup_indexes?{setup_indexes:r.setup_indexes}:{}}:void 0,fail_on_skipped_triggered:s?!0:void 0,warnings:i.length>0?i:void 0,changed:t.changed||c?.receipt.recorded===!0,...c?{evidence_recording:c.receipt}:{},count:l.count,...t.removed>0?{removed:t.removed}:{},...k,...d,...w}}function Ho(e,t,n,o){return n!==void 0?{tests:n.entries,count:n.returned_count,omitted:{}}:t!==void 0&&t.selector!==null&&t.skipped_count>0?{tests:t.selected,count:e.tests.length,omitted:{tests_omitted:{count:e.tests.length-t.selected.length,restore_with:Ct(e.itemId,o)}}}:{tests:e.tests,count:e.tests.length,omitted:{}}}function Bo(e,t){if(e.written!==void 0)return Ae({collectionKey:"tests",stored:e.tests,written:e.written,removedCount:e.storedRemoved,fullHistory:t})}function Ko(e,t){const n=e.tests[e.updated_index-1],o=Ae({collectionKey:"tests",stored:e.tests,written:e.changed&&n!==void 0?[n]:[],removedCount:0,fullHistory:t}),{counts:r,receipts:s}=Ie(o);return{...e,tests:o.entries,run_results:[],count:o.returned_count,...r,...s}}async function jr(e,t,n){const o=Et(t);if(o){yt(t),ht(t),Ne(e,t,n,ve(process.cwd(),n.path));const R=await Lt(e,{...o,author:t.author,message:t.message,force:t.force},n);return Ko(R,t.fullHistory===!0)}const r=Wt(),s=ve(process.cwd(),n.path);await Nt(s);const i=await Y(s);Ne(e,t,n,s),Oe(t.measure,"validation"),kt(t,[],void 0);const c=Gt(i,Dt()),d=await r.resolveList(t.add,"--add"),a=await r.resolveList(t.addJson,"--add-json"),u=await r.resolveList(t.remove,"--remove"),l=[...Jn(d),...Xe(a)],k=await _n(l,I(t.author,i.author_default),U())??[],w=Yn(u),T=Xn(t.removeIndex),_=await Fo({id:e,options:t,pmRoot:s,settings:i,typeToFolder:c.type_to_folder,adds:k,removes:w,removeIndexes:T}),g=ae(()=>ue(t,_.tests)),v=await Wo(t,s,_.tests),E=t.run===!0?U():void 0,P=await $o({options:t,runOptions:g,pmRoot:s,untrustedLinkedTestsPolicyEnabled:i.testing.allow_untrusted_linked_tests});mn(e,t,n,s,P);const O=Rt(P),m=t.run===!0&&t.failOnSkipped===!0&&P.some(R=>R.status==="skipped"),C=Do(t,P);v&&C.push(`linked_test_trust_acknowledged:${v.acknowledged}`);const S=await Go({options:t,pmRoot:s,settings:i,itemId:_.itemId,runStartedAt:E,runResults:P,failOnSkippedTriggered:m,warnings:C}),y=S?.receipt.recorded?zt([..._.testRuns,S.entry]):_.testRuns,L=kt(t,y,S?.entry);return qo({item:_,runResults:P,failureCategories:O,runSelection:g.runSelection,failOnSkippedTriggered:m,warnings:C,recording:S,measurementProjection:L,restoreScope:Pt(n,s),ran:t.run===!0,fullHistory:t.fullHistory===!0})}const Nr={buildLinkedTestExecutionContext:ft,buildPmContextMismatchHint:Be,commandInvokesPmCli:Je,commandInvokesPmTrackerReadCommand:ne,commandUsesTestNameFilter:at,copyIntoSandboxIfPresent:A,countLinkedTestItemFiles:M,ensureScope:Ge,evaluateLinkedTestAssertions:ct,endLinkedTestProgress:et,extractPmInvocationArgsFromSegment:te,firstDirectTestRunnerSubcommand:oe,formatLinkedTestExecutionError:ot,hasLinkedTestAssertions:He,initializeLinkedTestSandboxes:lt,linkedTestsRequireTrackerData:mt,parseAddJsonEntries:Xe,parseLinkedTestTimeoutSeconds:Ye,parsePmContextMode:N,readJsonPathValue:K,resolveAuthor:I,resolveDirectRunnerSubcommand:$,resolveLinkedTestEffectiveContextMode:ee,resolveLinkedTestFailureExitCode:it,resolveLinkedTestRequestedContextMode:Z,resolveTestRunOptions:ue,resolveTrackedRunId:De,runLinkedTestCommand:nt,seedMissingLinkedTestSettingsHistory:de,seedLinkedTestSandbox:ie,seedLinkedTestTrackerData:ce,segmentInvokesRecursiveTestAll:Hn,splitJsonPathSegments:xt,summarizeRunResultStatuses:Ue};export{Nr as _testOnlyTestCommand,Ar as classifyLinkedTestCommandSafety,so as classifyLinkedTestFailure,Dr as countFailureCategories,Gr as extractReferencedPmItemIdsFromCommand,it as resolveLinkedTestFailureExitCode,bo as runLinkedTests,jr as runTest,Rn as summarizeContextPreflight};
4
+ `:"";!T&&await bt(e,{exitCode:E,stderr:m.text},n,s)&&(T="Linked test executable was not found. Install the tool or update the linked command before retrying.");const y={stdout:`${O.text}${L}`,stderr:m.text,exitCode:E,signal:P,timedOut:v,maxBufferExceeded:!1,outputTruncated:C,spawnError:T};return st(o,y,i,r),y}finally{await j(c,{recursive:!0,force:!0})}}function dt(e,t){const n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${G} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);const o=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,r=e.spawnError?.trim()||o||"Linked test command failed.";return n.length===0?r:`${r} ${n.join(" ")}`}function io(e){const t=[e.spawnError??"",e.stderr,e.stdout].join(`
5
+ `);return En.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>yn.test(n)&&Rn.test(n))}function co(e){return io(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function ut(e,t){for(const[n,o]of Object.entries(t.env_set))Re.has(n.toUpperCase())||(e[n]=o);for(const n of t.env_clear)Re.has(n.toUpperCase())||delete e[n]}function uo(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function ao(e,t){const n={...e.env_set,...t.env_set},o=[...new Set([...e.env_clear,...t.env_clear??[]])],r=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:o,shared_host_safe:r}}function at(e,t,n){return{env_set:jn(e,"--env-set"),env_clear:Nn(t,"--env-clear"),shared_host_safe:n===!0}}async function A(e,t,n=!1,o=V){if(await D(e))try{await hn("seed_linked_test",async()=>{if(await o(f.dirname(t),{recursive:!0}),n){await pe(e,t,{recursive:!0,force:!0});return}await pe(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(r){if(typeof r=="object"&&r!==null&&"code"in r&&Bt(r))return;throw r}}async function ce(e,t,n,o=!1){for(const[r,s]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(o){const i=await Te(b(r));if(i!==null){const c=await Y(s);await we({pmRoot:s,filePath:b(s),raw:i,op:"settings:write",author:I(void 0,c.author_default),lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await A(b(r),b(s));await A(f.join(n.projectPmRoot,"extensions"),f.join(e,"extensions"),!0),await A(f.join(n.globalPmRoot,"extensions"),f.join(t,"extensions"),!0)}async function de(e,t){if(!await D(e))return;const n=await z(e,{withFileTypes:!0});for(const o of n){if(Ln.has(o.name))continue;const r=f.join(e,o.name),s=f.join(t,o.name);if(o.isDirectory()){await A(r,s,!0);continue}o.isFile()&&await A(r,s)}}async function ue(e,t){const n=await Te(b(e));if(n===null||await D(ge(e)))return;const o=await Y(t);await j(ge(t),{force:!0}),await j(b(t),{force:!0}),await we({pmRoot:t,filePath:b(t),raw:n,op:"settings:write",author:I(void 0,o.author_default),lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function M(e){if(!await D(e))return 0;let t=0;const n=await z(e,{withFileTypes:!0});for(const o of n){if(!o.isDirectory()||Sn.has(o.name))continue;const r=f.join(e,o.name);let s;try{s=await z(r,{withFileTypes:!0})}catch{continue}for(const i of s)i.isFile()&&Xt.some(c=>i.name.toLowerCase().endsWith(c))&&(t+=1)}return t}function lt(e){const t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function lo(e){const t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;const n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function mo(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?ve(e,t):Object.is(e,t)}function mt(e,t,n){const o=[];o.push(...ft("stdout",t,e.assert_stdout_contains)),o.push(..._t("stdout",t,e.assert_stdout_regex)),o.push(...ft("stderr",n,e.assert_stderr_contains)),o.push(..._t("stderr",n,e.assert_stderr_regex)),o.push(...fo(t,e.assert_stdout_min_lines));const r=e.assert_json_field_equals??{},s=e.assert_json_field_gte??{};if(!(Object.keys(r).length>0||Object.keys(s).length>0))return o;let c;try{c=JSON.parse(t)}catch(d){return o.push(`stdout is not valid JSON for assert_json_field_* checks: ${d instanceof Error?d.message:String(d)}`),o}for(const[d,a]of Object.entries(r)){const u=K(c,d);if(!u.found){o.push(`assert_json_field_equals missing path "${d}"`);continue}const l=lo(a);mo(u.value,l)||o.push(`assert_json_field_equals mismatch at "${d}" (expected=${JSON.stringify(l)} actual=${JSON.stringify(u.value)})`)}for(const[d,a]of Object.entries(s)){const u=K(c,d);if(!u.found){o.push(`assert_json_field_gte missing path "${d}"`);continue}if(typeof u.value!="number"||!Number.isFinite(u.value)){o.push(`assert_json_field_gte path "${d}" resolved to non-numeric value`);continue}u.value<a&&o.push(`assert_json_field_gte failed at "${d}" (expected >= ${a}, actual ${u.value})`)}return o}function ft(e,t,n){const o=[];for(const r of n??[])t.includes(r)||o.push(`${e} missing required text: "${r}"`);return o}function _t(e,t,n){const o=[];for(const r of n??[])try{new RegExp(r,"m").test(t)||o.push(`${e} failed regex assertion: /${r}/m`)}catch(s){o.push(`${e} regex assertion is invalid: /${r}/ (${s instanceof Error?s.message:String(s)})`)}return o}function fo(e,t){if(typeof t!="number")return[];const n=e.split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}function ht(e){const t=q(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:W(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&re(n))}function _o(e){return{root:e,schemaProjectPmPath:f.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:f.join(e,"schema","global"),trackerProjectPmPath:f.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:f.join(e,"tracker","global"),workspaceSnapshotRoot:f.join(e,"workspace","project"),workspaceIsolatedRoot:f.join(e,"workspace","isolated")}}function ho(e,t,n){return e.some(o=>Be(o,t,n)==="snapshot")}async function po(e,t){const n=f.join(e,".agents"),o=f.join(n,"pm");await V(n,{recursive:!0}),await j(o,{recursive:!0,force:!0}),await qt(t,o,process.platform==="win32"?"junction":"dir")}async function pt(e,t=Se,n=!0){const o={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},o),await t(void 0,{path:e.schemaGlobalPmPath},o),n&&(await t(void 0,{path:e.trackerProjectPmPath},o),await t(void 0,{path:e.trackerGlobalPmPath},o))}async function ko(e,t,n){t&&(await ce(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await ce(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await de(t.projectPmRoot,e.trackerProjectPmPath),await de(t.globalPmRoot,e.trackerGlobalPmPath),await ue(t.projectPmRoot,e.trackerProjectPmPath),await ue(t.globalPmRoot,e.trackerGlobalPmPath)))}function kt(e,t,n){return e.some(o=>{const r=o.command??"",s=r.length>0&&ne(r),i=n?.autoPmContext===!0&&s?"auto":Z(o,t,n?.overrideLinkedPmContext===!0);return ee(i,s)==="tracker"})}async function xo(e,t){return{sourceProjectItemCount:t?await M(t.projectPmRoot):0,sourceGlobalItemCount:t?await M(t.globalPmRoot):0,schemaProjectItemCount:await M(e.schemaProjectPmPath),schemaGlobalItemCount:await M(e.schemaGlobalPmPath),trackerProjectItemCount:await M(e.trackerProjectPmPath),trackerGlobalItemCount:await M(e.trackerGlobalPmPath)}}function xt(e){const t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,o=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,r=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,i=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,c=e.workspaceContextMode==="isolated"?"":i;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:o,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:r,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==r||e.counts.sourceGlobalItemCount!==s),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:i,source_workspace_root:c,trust:e.trust}}async function To(e){const t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?N(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,o=n?Ye(n):!1,r=o&&n?ne(n):!1,s=e.options?.autoPmContext===!0&&r,i=s?"auto":Z(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),c=ee(i,r),d=c==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await po(e.layout.workspaceSnapshotRoot,d);const a=e.options?.pmRoot?await De(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await De(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:xt({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:o,isPmTrackerReadCommand:r,requestedPmContextMode:i,effectivePmContextMode:c,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:a})}}function Tt(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function go(e,t,n,o){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...o?{stdout:o.stdout,stderr:o.stderr}:{},error:n}}function wo(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function Co(e){if(e.executionContext.trust.trusted)return null;const t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;const o=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return wo(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${o}`)}function Po(e){if(!e.linkedTest.command)return Tt(e.linkedTest,e.executionContext,"No command configured for this linked test.");const t=Qn(e.linkedTest.command);return t?Tt(e.linkedTest,e.executionContext,t):null}function vo(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?B(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?B(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function B(e,t,n){return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",execution_context:t,error:n}}function Lo(e){const t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;const o=Ve({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),r=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return B(e.linkedTest,e.executionContext,`${r} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${o}`)}function So(e){const t=Po(e);if(t)return t;const n=Co(e);if(n)return n;const o=vo(e);if(o)return o;const r=Lo(e);return r||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!Ke(e.linkedTest)?B(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function Eo(e){const t=ao(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return ut(n,e.runtimeDirectives),ut(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&uo(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode!=="source"&&(delete n.PM_BUILD_CONSUMER_LEASE,delete n.PM_BUILD_CONSUMER_LEASE_ROOT),e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[Fe]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[Fe]="read_only"),n}function yo(e,t,n,o){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr,...o?{execution_receipt:o}:{}}}function gt(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function Ro(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:lt(e.execution),failure_category:co(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:dt(e.execution,e.timeoutMs)}}function bo(e){const t=St(e.execution.stdout,e.execution.stderr),n=e.linkedTest.phase!=="setup"&&ht(e.linkedTest.command??"");if(e.options?.failOnEmptyTestRun===!0||n){const r=Lt(e.execution.stdout,e.execution.stderr);if(r)return gt({...e,emptyRunSignal:r});if(n&&!t)return gt({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}const o=mt(e.linkedTest,e.execution.stdout,e.execution.stderr);return o.length>0?go(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${o.join("; ")}`,e.execution):yo(e.linkedTest,e.executionContext,e.execution,t)}async function Mo(e){const t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,o=await ct(t,n,Eo(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return o.exitCode===0&&!o.timedOut&&!o.maxBufferExceeded?bo({...e,execution:o}):Ro({...e,execution:o,timeoutMs:n})}async function Oo(e,t,n){const o=Ft(e);for(const g of o)me(g.command);const r=[],s=await ke(f.join(xe(),"pm-linked-test-")),i=_o(s),c=N(n?.pmContext),d=He(n?.workspaceContext),a=n?.progress===!0?"always":"auto",u=at(n?.envSet,n?.envClear,n?.sharedHostSafe),l=n?.sourceRoots,k=wn(),w=kt(o,c,n),T=ho(o,d,n?.overrideLinkedWorkspaceContext===!0),_=await gn(k);try{await pt(i,Se,w),await V(i.workspaceIsolatedRoot,{recursive:!0}),await ko(i,l,w),T&&await Rt(k,i.workspaceSnapshotRoot,l?.projectPmRoot,w);const g=await xo(i,l),v=jt(),E=m=>Be(m,d,n?.overrideLinkedWorkspaceContext===!0),P=new Set(o.filter(m=>!Nt(m)).map(E)),O=async(m,C)=>{const L=v.options(m,n),y=E(m),S=Dt(m,y,P);if(S)return S;const R=await To({linkedTest:m,layout:i,counts:g,sourceRoots:l,runLevelPmContextMode:c,options:n,requestedWorkspaceContextMode:d,workspaceContextMode:y,currentSourceRef:_,sourceWorkspaceRoot:k});return So({linkedTest:m,executionContext:R.executionContext,runLevelPmContextMode:c,linkedOverridePmContextMode:R.linkedOverridePmContextMode,options:L})??await Mo({linkedTest:m,index:C,total:o.length,defaultTimeoutSeconds:t,runtimeDirectives:u,progressMode:a,executionContext:R.executionContext,options:L})};for(let m=0;m<o.length;m+=1){const C=o[m];r.push(v.blocked(C)??v.record(C,await O(C,m)))}}finally{await j(i.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return r}function Io(e,t){const n=[...t];return e.filter(o=>{const r=n.findIndex(s=>fe(s,o));return r>=0&&n.splice(r,1),r<0}).length}async function Ao(e){const{id:t,pmRoot:n,settings:o,typeToFolder:r}=e,s=await Jt(n,t,o.id_prefix,o.item_format,r);if(!s)throw new p(`Item ${t} not found`,h.NOT_FOUND);const i=await Yt(s,{schema:o.schema});return{itemId:s.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function jo(e,t){const n=[...e];for(const o of t)n.some(r=>fe(r,o))||n.push(o);return n}function No(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};const o=new Set(n),r=e.filter((s,i)=>o.has(i+1)?!1:!t.some(c=>c.kind==="command"?s.command===c.value:c.kind==="path"?s.path===c.value:s.command===c.value||s.path===c.value));return{tests:r,removed:e.length-r.length}}function Fo(e,t,n,o){return No(jo(e,t),n,o)}function $o(e){return[e.timeout!==void 0,e.progress===!0,(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.fullOutput===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function wt(e){if($o(e)&&e.run!==!0)throw new p("--timeout, --progress, --env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, --full-output, and --auto-pm-context require --run",h.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new p("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",h.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new p("--match, --only-index, and --only-last require --run",h.USAGE)}async function Do(e){const{id:t,options:n,pmRoot:o,settings:r,typeToFolder:s,adds:i,removes:c,removeIndexes:d}=e;if(i.length===0&&c.length===0&&d.length===0)return Ao({id:t,pmRoot:o,settings:r,typeToFolder:s});let a=0,u=[];const l=await zt({pmRoot:o,settings:r,id:t,op:i.length>0?"tests_add":"tests_remove",author:I(n.author,r.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(w){const T=w.metadata.tests??[],_=Fo(T,i,c,d);if(le(()=>ae(n,_.tests)),a=_.removed,(c.length>0||d.length>0)&&a===0)throw new p("No linked tests matched the requested removal selector",h.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...c.map(g=>`${g.kind}=${g.value}`),...d.map(g=>`index=${g}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return w.metadata.tests=_.tests,u=T,{changedFields:ve(T,_.tests)?[]:["tests"]}}}),k=l.item.tests??[];return{itemId:l.item.id,tests:k,testRuns:l.item.test_runs??[],changed:l.changedFields.length>0,removed:a,written:l.changedFields.length>0?pn(u,k):[],storedRemoved:Io(u,k)}}function ae(e,t){const n=N(e.pmContext);He(e.workspaceContext),at(e.envSet,e.envClear,e.sharedHostSafe);const o={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:an(e.onlyIndex),onlyLast:e.onlyLast},r=e.timeout===void 0?void 0:Pe(e.timeout,"--timeout");if(r!==void 0&&r<=0)throw new p(`--timeout must be a positive number (got "${e.timeout}")`,h.USAGE);wt(e);const s=e.run===!0?Ut(ln(t,o),t):void 0;if(s)for(const i of s.selected)me(i.command);return{defaultTimeoutSeconds:r,pmContextMode:n,runSelection:s,testsToRun:s?.selected??t}}async function Uo(e){const{options:t,runOptions:n,pmRoot:o}=e;return t.run!==!0?[]:await Oo(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun===!0||(t.measure?.length??0)>0,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:o,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:o,globalPmRoot:Qt(process.cwd())}})}function Go(e,t){const n=[];if(e.run===!0&&e.checkContext===!0){const o=An(t);n.push(`context_preflight:checked_pm_commands=${o.checked_pm_commands};tracker_read_commands=${o.tracker_read_commands};mismatches=${o.mismatches};auto_remediated=${o.auto_remediated}`)}return n}function Wo(e){const t=We(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),o=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),r=U(),s=Ae(e.options.measure,r);return{run_id:Ge("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:r,recorded_at:r,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:o&&o.length>0?o:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:s.length>0?s:void 0,executions:e.runResults.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}}async function qo(e){const{options:t,pmRoot:n,settings:o,itemId:r,runStartedAt:s,runResults:i,failOnSkippedTriggered:c,warnings:d}=e;if(t.run!==!0||!s)return;const a=Wo({options:t,runStartedAt:s,runResults:i,failOnSkippedTriggered:c});if(o.testing.record_results_to_items!==!0)return{entry:a,receipt:{recorded:!1,reason:"tracking_disabled",run_id:a.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await Zt({pmRoot:n,settings:o,itemId:r,author:I(t.author,o.author_default),message:`Track test run summary (${a.run_id})`,entry:a}),{entry:a,receipt:{recorded:!0,reason:"recorded",run_id:a.run_id}}}catch(u){if(vt(u))throw u;return d.push(`test_result_tracking_failed:${r}:${u instanceof Error?u.message:String(u)}`),{entry:a,receipt:{recorded:!1,reason:"write_failed",run_id:a.run_id}}}}function Ct(e,t,n){let o;if(e.metricBelow!==void 0){const r=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,r).trim(),i=e.metricBelow.slice(r+1).trim(),c=Number(i);if(r<=0||s.length===0||i.length===0||!Number.isFinite(c))throw new p("--metric-below must use name=value",h.USAGE);o=_n(t,s,c)}return{measurements:n?.measurements,metric_below:o,metric_diff:e.metricDiff===void 0?void 0:fn(t,e.metricDiff)}}async function Ho(e,t,n){if(e.acknowledgeLinkedTests===!0)return xn(t,n,U())}function Bo(e){const{item:t,runResults:n,failureCategories:o,runSelection:r,failOnSkippedTriggered:s,warnings:i,recording:c,measurementProjection:d,restoreScope:a}=e,u=Vo(t,e.fullHistory),l=Ko(t,r,u,a),{counts:k,receipts:w}=je(u);return{ok:n.every(T=>T.status!=="failed"&&T.status!=="refused")&&s!==!0,id:t.itemId,tests:l.tests,...l.omitted,run_results:n,...e.ran?{failure_categories:o}:{},selection:r?{selector:r.selector,requested:r.requested,selected_indexes:r.selected_indexes,selected_count:r.selected_count,skipped_count:r.skipped_count,...r.setup_indexes?{setup_indexes:r.setup_indexes}:{}}:void 0,fail_on_skipped_triggered:s?!0:void 0,warnings:i.length>0?i:void 0,changed:t.changed||c?.receipt.recorded===!0,...c?{evidence_recording:c.receipt}:{},count:l.count,...t.removed>0?{removed:t.removed}:{},...k,...d,...w}}function Ko(e,t,n,o){return n!==void 0?{tests:n.entries,count:n.returned_count,omitted:{}}:t!==void 0&&t.selector!==null&&t.skipped_count>0?{tests:t.selected,count:e.tests.length,omitted:{tests_omitted:{count:e.tests.length-t.selected.length,restore_with:Et(e.itemId,o)}}}:{tests:e.tests,count:e.tests.length,omitted:{}}}function Vo(e,t){if(e.written!==void 0)return Ne({collectionKey:"tests",stored:e.tests,written:e.written,removedCount:e.storedRemoved,fullHistory:t})}function Jo(e,t){const n=e.tests[e.updated_index-1],o=Ne({collectionKey:"tests",stored:e.tests,written:e.changed&&n!==void 0?[n]:[],removedCount:0,fullHistory:t}),{counts:r,receipts:s}=je(o);return{...e,tests:o.entries,run_results:[],count:o.returned_count,...r,...s}}async function $r(e,t,n){const o=Ot(t);if(o){It(t),wt(t),$e(e,t,n,Le(process.cwd(),n.path));const R=await Mt(e,{...o,author:t.author,message:t.message,force:t.force},n);return Jo(R,t.fullHistory===!0)}const r=Vt(),s=Le(process.cwd(),n.path);await Gt(s);const i=await Y(s);$e(e,t,n,s),Ae(t.measure,"validation"),Ct(t,[],void 0);const c=Kt(i,Ht()),d=await r.resolveList(t.add,"--add"),a=await r.resolveList(t.addJson,"--add-json"),u=await r.resolveList(t.remove,"--remove"),l=[...Qe(d),...se(a)],k=await Tn(l,I(t.author,i.author_default),U())??[],w=et(u),T=tt(t.removeIndex),_=await Do({id:e,options:t,pmRoot:s,settings:i,typeToFolder:c.type_to_folder,adds:k,removes:w,removeIndexes:T}),g=le(()=>ae(t,_.tests)),v=await Ho(t,s,_.tests),E=t.run===!0?U():void 0,P=await Uo({options:t,runOptions:g,pmRoot:s,untrustedLinkedTestsPolicyEnabled:i.testing.allow_untrusted_linked_tests});kn(e,t,n,s,P);const O=At(P),m=t.run===!0&&t.failOnSkipped===!0&&P.some(R=>R.status==="skipped"),C=Go(t,P);v&&C.push(`linked_test_trust_acknowledged:${v.acknowledged}`);const L=await qo({options:t,pmRoot:s,settings:i,itemId:_.itemId,runStartedAt:E,runResults:P,failOnSkippedTriggered:m,warnings:C}),y=L?.receipt.recorded?en([..._.testRuns,L.entry]):_.testRuns,S=Ct(t,y,L?.entry);return Bo({item:_,runResults:P,failureCategories:O,runSelection:g.runSelection,failOnSkippedTriggered:m,warnings:C,recording:L,measurementProjection:S,restoreScope:yt(n,s),ran:t.run===!0,fullHistory:t.fullHistory===!0})}const Dr={buildLinkedTestExecutionContext:xt,buildPmContextMismatchHint:Ve,commandInvokesPmCli:Ye,commandInvokesPmTrackerReadCommand:ne,commandUsesTestNameFilter:ht,copyIntoSandboxIfPresent:A,countLinkedTestItemFiles:M,ensureScope:qe,evaluateLinkedTestAssertions:mt,endLinkedTestProgress:st,extractPmInvocationArgsFromSegment:te,firstDirectTestRunnerSubcommand:oe,formatLinkedTestExecutionError:dt,hasLinkedTestAssertions:Ke,initializeLinkedTestSandboxes:pt,linkedTestsRequireTrackerData:kt,parseAddJsonEntries:se,parseLinkedTestTimeoutSeconds:Ze,parsePmContextMode:N,readJsonPathValue:K,resolveAuthor:I,resolveDirectRunnerSubcommand:$,resolveLinkedTestEffectiveContextMode:ee,resolveLinkedTestFailureExitCode:lt,resolveLinkedTestRequestedContextMode:Z,resolveTestRunOptions:ae,resolveTrackedRunId:Ge,runLinkedTestCommand:ct,seedMissingLinkedTestSettingsHistory:ue,seedLinkedTestSandbox:ce,seedLinkedTestTrackerData:de,segmentInvokesRecursiveTestAll:zn,splitJsonPathSegments:Pt,summarizeRunResultStatuses:We};export{Dr as _testOnlyTestCommand,Fr as admitsLinkedTestFlagValue,Nr as classifyLinkedTestCommandSafety,co as classifyLinkedTestFailure,Wr as countFailureCategories,Hr as extractReferencedPmItemIdsFromCommand,lt as resolveLinkedTestFailureExitCode,Oo as runLinkedTests,$r as runTest,An as summarizeContextPreflight};
6
6
  //# sourceMappingURL=execution.js.map
package/docs/COMMANDS.md CHANGED
@@ -1219,6 +1219,8 @@ Linked files and docs keep reviews reproducible. `deps` is read-only and project
1219
1219
 
1220
1220
  A `files`, `docs` or `test` write (`--add`, `--add-json`, `--add-glob`, `--remove`, `--remove-index`, `--migrate`, or a linked-test `--update`/`--update-index` edit) returns only the entries it added or rewrote, so its reply no longer grows with the stored list ([pm-gh1700](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1700.toon); tracker record excluded from npm). `count` is the number of entries returned and `total_count` the number stored. `mutation_receipt` reports `changed_count`, `removed_count` and `full_history_included`, and `omission_receipt` names the `full_history` selector when stored entries were withheld, exactly as for comments. For `files` and `docs` adds, `mutation_receipt.link_outcomes` reports each requested link as `added`, `note_added`, `note_replaced`, `note_appended` or `unchanged`. A retried identical add, or an `--add-glob` that matches nothing, returns no entries and `changed_count: 0`; the receipt reports entries as storage saved them (normalized paths included). Pass `--full-history` (SDK `fullHistory`, MCP `full`) to receive the whole collection after a write. The implicit post-write path check validates the returned links; `--validate-paths` validates every stored path. `failure_categories` appears only when `pm test` ran linked tests.
1221
1221
 
1222
+ Each `--add`, `--add-glob`, `--remove` and `--migrate` occurrence takes exactly one value, so an item id written after the flag (`pm files --add a.ts <id>`) stays unambiguous. Several values after one occurrence (`pm files <id> --add a.ts b.ts c.ts`, or an unquoted shell glob) are refused with `linked_resource_value_list` (exit 2, nothing written) ([pm-gh1791](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1791.toon); tracker record excluded from npm). The first line names the repeat-flag fix, and `recovery.suggested_retry_args` gives the exact command with one flag per value. An invocation that reads stdin (a `-` value, an inline `--flag=-`, or a `--stdin` flag) or carries URL credentials gets no executable retry, because a copied command would read the terminal instead of the piped input, or run with redacted credentials; the guidance asks for one flag per value with the same input piped again, or with the credentials restored. Tokens are read with the command's own Commander options, including the global options the program declares, so `pm files --json <id> --add a b` and `pm item files --add a.ts <id> --remove b.ts c.ts` (the first operand is the id, as Commander assigns it) get the same retry while `pm files <id> --output-limit --add a b`, where Commander takes `--add` as the limit, does not; a required option followed by an option-like token, or a subcommand operand (`pm files --note N discover …`), gets no value-list recovery, because Commander's own parse order decides those. The copyable command is offered only when it is the exact argv: a value holding a control character (text output replaces it), or one that needs cmd.exe quoting under `PM_COMMAND_SHELL=cmd` or anywhere on Windows (cmd.exe drops line breaks, and npm's `pm.cmd` hands any shell's arguments to cmd.exe, which re-parses quoted metacharacters), leaves only `suggested_retry_args`. `--measure` gets no value-list retry, because its attribute grammar is coalesced by the bootstrap. An executable retry is offered only for plain values (no whitespace, comma, `=`, `:` or backtick, and for `pm docs` no Markdown link punctuation `[]()`) that the flag's own parser accepts. A structured value (`path=…`, `path:…`, `pattern:…`, a doc label before a URL) may be one argument the shell split (`--add path:a.ts,note:fix the bug`), so the refusal asks for quoting and gives no executable retry. `pm test` gives the same retry only when the linked-test parser admits every value as a complete entry (a structured `--add` entry with a command, a `command=` or `path=` selector for `--remove`, a JSON entry for `--add-json`, a positive position for `--remove-index`); an unquoted command split by the shell keeps `linked_test_value_not_quoted`.
1223
+
1222
1224
  When note prose in an `--add` entry is misread as a new key (`note=see, host:port` opens a key `host` after the comma), the refusal is `linked_artifact_note_key_misread`. It names the segment and key in the message and in `details` (`misread_segment`, `misread_key`, `note`, the underlying `cause`), and `recovery.suggested_retry_args` replays the whole invocation (every entry, `--add-glob`, `--remove`, `--migrate` and control) with that entry's note quoted as `note="…"`, so its commas stay prose; passing the prose through the standalone `--note` flag in a single-entry call works too ([pm-pwqiao](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-pwqiao.toon); tracker record excluded from npm). Every other refusal, including a typo key with no note, keeps its own message.
1223
1225
 
1224
1226
  Structured key/value forms reject unrecognized keys with an `Allowed keys: …` error (matching `test --add`), so a typoed key (`lable=` instead of `label=`) fails fast instead of being silently dropped: `--add`/`--file`/`--doc` accept `path,scope,note`; `--add-glob` accepts `pattern,glob,path,scope,note`; `--remove` accepts `path`; `--migrate` accepts `from,to`; create/update `--dep` accepts `id,kind,type,author,created_at,source_kind`; `--reminder` accepts `at,date,text,title`; `--event` accepts `start,date,end,duration,title,description,location,timezone,all_day` and the `recur_*` recurrence keys. A key set twice in one entry (`path=a.txt,path=b.txt`, or note prose such as `note=moved here, path: b.txt`) is refused with `structured_entry_key_repeated` instead of silently keeping the last value ([pm-oglm0t](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-oglm0t.toon); tracker record excluded from npm); the comment, note and learning seed fallbacks store such prose verbatim. Set `source_kind=global` for a dependency owned by another workspace: pm preserves its id verbatim, materializes it as an external graph endpoint, and excludes it from dangling-local-reference findings. Explicit remote locators also retain their spelling; other dependency and parent references share local `id_prefix` normalization, including uppercase and `#` shorthand. Bare values (`--add src/cli/main.ts`) skip key validation.
@@ -1706,7 +1708,7 @@ pm create Spike "Investigate retry backoff"
1706
1708
  - `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
1709
  - `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
1710
  - 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 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.
1711
+ - `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, through the CLI, `PmClient.schemaAddField` (`cliFlag: " "`, `alias: [""]`) and MCP alike ([pm-f0s4g8](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-f0s4g8.toon); repository tracker record, excluded from npm). 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
1712
  - `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
1713
  - `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
1714
  - `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.
@@ -862,7 +862,7 @@ 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).
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). A status or type entry with a wrong-typed member (a numeric `description`, a non-string alias, an `order` that is not a number, a `folder` or `default_status` that is not a string, an option or command-option policy that is not a record with string keys) keeps the entry and ignores that member, so it no longer fails the settings read. An `execution_role` in `schema/types.json` other than `agent`, `human` or `gate` fails closed: the type reads as `human` and is never offered for agent dispatch, while an extension registration with one is still refused. A `required`, `visible` or `enabled` switch that is not a boolean is ignored in a schema file (so `required: "false"` adds no requirement), and a command-option policy carrying one is dropped whole, so it never replaces a valid policy for the same option, a list with no usable entry (only wrong-typed or blank strings) reads as absent rather than as an explicit empty override (so `required_create_fields: [5, " "]` keeps the built-in requirements), and an option or command-option policy with a blank key, or an option whose `values` allowlist has no usable value, is dropped and reported instead of admitting any value. A schema file path that names a directory or a named pipe fails hydration instead of stalling the read. `pm validate --check-metadata` names every dropped or partly read status and type entry with its file and position (`validate_schema_status_definition_dropped:<n>`, `validate_schema_status_definition_partial:<n>`, `validate_schema_type_definition_dropped:<n>` and `validate_schema_type_definition_partial:<n>`, rows under `schema_status_definition_losses` and `schema_type_definition_losses`) ([pm-x17o8l](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-x17o8l.toon); repository tracker record, excluded from npm).
866
866
 
867
867
  End-to-end example — add a required-on-create `component` string field on `Task` items:
868
868
 
@@ -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). 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).
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). Two active packages that declare one field with different types keep the first declaration in activation order; each later declaration with another type is dropped with `extension_item_field_type_conflict:<layer>:<package>:<field>:<type>:kept=<layer>:<package>:<type>`, which names both packages and both types and which `pm package doctor` and `pm health` report, so create and update keep working for every field. Before, such a pair made every create and update exit 2, including writes that never touched the field ([pm-2ze9nt](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-2ze9nt.toon); repository 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).
@@ -88,6 +88,15 @@ registry drops (a blank alias) cannot shadow an option, so on a stored entry it
88
88
  stays a `pm validate --check-metadata` report; only a newly supplied one is
89
89
  refused
90
90
  ([pm-2nwcgg](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-2nwcgg.toon);
91
+ tracker record excluded from npm). Each side is judged as the settings read
92
+ hydrates it: when the schema files of the stored settings do not hydrate (a
93
+ schema file path that names a directory, for example), the read falls back to
94
+ defaults and no stored definition is active, so a proposal that repairs
95
+ hydration judges each definition that becomes effective (the last one per key,
96
+ as the registry reads them), while a proposal that leaves hydration failing
97
+ activates and judges no stored definition (its own new or changed inline
98
+ definitions are judged either way)
99
+ ([pm-8dbagz](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-8dbagz.toon);
91
100
  tracker record excluded from npm).
92
101
 
93
102
  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.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"}]}
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.29","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.29","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"}]}
@@ -3,7 +3,7 @@ JSON-Patch
3
3
 
4
4
  > A leaner and meaner implementation of JSON-Patch. Small footprint. High performance.
5
5
 
6
- [![Build Status](https://travis-ci.org/Starcounter-Jack/JSON-Patch.svg?branch=master)](https://travis-ci.org/Starcounter-Jack/JSON-Patch)
6
+ [![Test](https://github.com/Starcounter-Jack/JSON-Patch/actions/workflows/test.yml/badge.svg)](https://github.com/Starcounter-Jack/JSON-Patch/actions/workflows/test.yml)
7
7
 
8
8
  With JSON-Patch, you can:
9
9
  - **apply** patches (arrays) and single operations on JS object
@@ -11,7 +11,7 @@ With JSON-Patch, you can:
11
11
  - **observe** for changes and **generate** patches when a change is detected
12
12
  - **compare** two objects to obtain the difference
13
13
 
14
- Tested in Firefox, Chrome, Edge, Safari, IE11, Deno and Node.js
14
+ Tested in Chromium, Firefox, WebKit, Deno and Node.js
15
15
 
16
16
 
17
17
  ## Why you should use JSON-Patch