@unbrained/pm-cli 2026.11.13 → 2026.11.15

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 (289) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +1 -1
  3. package/dist/cli/extension-command-help.js +2 -2
  4. package/dist/cli/register-mutation.js +2 -2
  5. package/dist/cli/register-operations.js +1 -1
  6. package/dist/cli-bundle/bundle-manifest.json +1 -1
  7. package/dist/cli-bundle/chunks/chunk-6UTBX62V.js +2 -0
  8. package/dist/cli-bundle/chunks/{chunk-GWVP23RZ.js → chunk-7AODVNHX.js} +2 -2
  9. package/dist/cli-bundle/chunks/chunk-ASGAELBQ.js +9 -0
  10. package/dist/cli-bundle/chunks/{chunk-PUU5DXSV.js → chunk-DBUBX4DL.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-5LG5YZYF.js → chunk-E4B2HWH7.js} +13 -13
  12. package/dist/cli-bundle/chunks/chunk-E74OMFBZ.js +6 -0
  13. package/dist/cli-bundle/chunks/chunk-FSE624WQ.js +2 -0
  14. package/dist/cli-bundle/chunks/chunk-FYOIH56R.js +20 -0
  15. package/dist/cli-bundle/chunks/chunk-GAFALSR2.js +8 -0
  16. package/dist/cli-bundle/chunks/{chunk-LKVFPQNY.js → chunk-GCSKHCYK.js} +2 -2
  17. package/dist/cli-bundle/chunks/chunk-HMVZSXB4.js +8 -0
  18. package/dist/cli-bundle/chunks/chunk-IXV5UM4U.js +31 -0
  19. package/dist/cli-bundle/chunks/chunk-J6L3Q5J4.js +3 -0
  20. package/dist/cli-bundle/chunks/chunk-KLWGIEDC.js +114 -0
  21. package/dist/cli-bundle/chunks/chunk-KSLPRST2.js +10 -0
  22. package/dist/cli-bundle/chunks/chunk-LC6DL446.js +3 -0
  23. package/dist/cli-bundle/chunks/{chunk-UFZQPKQS.js → chunk-NAX554KY.js} +35 -35
  24. package/dist/cli-bundle/chunks/chunk-PMIGRSNZ.js +2 -0
  25. package/dist/cli-bundle/chunks/chunk-Q6GBRK27.js +3 -0
  26. package/dist/cli-bundle/chunks/chunk-QZNDEZYI.js +2 -0
  27. package/dist/cli-bundle/chunks/chunk-S5UXBECQ.js +2 -0
  28. package/dist/cli-bundle/chunks/{chunk-UJMQP2HP.js → chunk-TESRFVGF.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-GXGMMIZN.js → chunk-VWKLTHYQ.js} +80 -70
  30. package/dist/cli-bundle/chunks/chunk-YJNY5MKP.js +2 -0
  31. package/dist/cli-bundle/chunks/chunk-YLPZE2TK.js +2 -0
  32. package/dist/cli-bundle/chunks/{chunk-RSAN2YUU.js → chunk-ZVDXGAYV.js} +2 -2
  33. package/dist/cli-bundle/chunks/chunk-ZWUS65LN.js +2 -0
  34. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-I6RQGD6Y.js → indexed-receipt-blobs-42Y2CSEQ.js} +2 -2
  35. package/dist/cli-bundle/chunks/item-revision-JCEDTAVX.js +2 -0
  36. package/dist/cli-bundle/chunks/item-transaction-BSMGKZ4S.js +2 -0
  37. package/dist/cli-bundle/chunks/mutation-actor-IQHBRFAJ.js +2 -0
  38. package/dist/cli-bundle/chunks/mutation-admission-DF6BFGG6.js +2 -0
  39. package/dist/cli-bundle/chunks/{register-list-query-JNJY2D3N.js → register-list-query-DNKPQB76.js} +2 -2
  40. package/dist/cli-bundle/chunks/register-mutation-WVTDFLEF.js +20 -0
  41. package/dist/cli-bundle/chunks/register-operations-NR5MTT5T.js +2 -0
  42. package/dist/cli-bundle/chunks/register-setup-2RTG3LII.js +2 -0
  43. package/dist/cli-bundle/chunks/{settlement-hook-JHXLUBEN.js → settlement-hook-W5ULPKIE.js} +2 -2
  44. package/dist/cli-bundle/chunks/stage-YFNK7U26.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-Q3OA5OAK.js → chunk-2UQFFVQK.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/chunk-52H6AELE.js +2 -0
  47. package/dist/cli-bundle/focused-chunks/{chunk-J3LQQP3N.js → chunk-63FM3TIG.js} +7 -7
  48. package/dist/cli-bundle/focused-chunks/{chunk-VGFKTSGY.js → chunk-7GCAZJT4.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/chunk-BSY6FZ3Y.js +2 -0
  50. package/dist/cli-bundle/focused-chunks/chunk-CZZKAGHE.js +91 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-DRBXOAGY.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-DXMQ32EH.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/chunk-EALGFJRP.js +78 -0
  54. package/dist/cli-bundle/focused-chunks/chunk-FK2X6MJY.js +44 -0
  55. package/dist/cli-bundle/focused-chunks/{chunk-IDAYTYNN.js → chunk-JE3MFEQZ.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-JR75B6HU.js → chunk-JRRHN2PZ.js} +12 -12
  57. package/dist/cli-bundle/focused-chunks/chunk-JXA77YIV.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-LQZ5F6LE.js +3 -0
  59. package/dist/cli-bundle/focused-chunks/chunk-LSWUTTE6.js +6 -0
  60. package/dist/cli-bundle/focused-chunks/chunk-QXOFSZR6.js +3 -0
  61. package/dist/cli-bundle/focused-chunks/chunk-RMCODWHZ.js +65 -0
  62. package/dist/cli-bundle/focused-chunks/chunk-S6GTALM4.js +24 -0
  63. package/dist/cli-bundle/focused-chunks/chunk-UPUIDGNJ.js +2 -0
  64. package/dist/cli-bundle/focused-chunks/{chunk-TVJ2PHAK.js → chunk-W2KIQ7RF.js} +3 -3
  65. package/dist/cli-bundle/focused-chunks/chunk-WGYR3X6O.js +26 -0
  66. package/dist/cli-bundle/focused-chunks/chunk-WVYXR3YX.js +2 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-ZJF6ZA7B.js → chunk-XQZKGTZV.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/{chunk-4LFE3FQL.js → chunk-YTNUUEY6.js} +2 -2
  69. package/dist/cli-bundle/focused-chunks/chunk-YZUBG4W2.js +6 -0
  70. package/dist/cli-bundle/focused-chunks/chunk-Z6HCQYSW.js +8 -0
  71. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-7XGVHYAO.js → indexed-receipt-blobs-LSBWMXKS.js} +2 -2
  72. package/dist/cli-bundle/focused-chunks/item-revision-YO7YGQYE.js +2 -0
  73. package/dist/cli-bundle/focused-chunks/item-transaction-7A3Q4CAJ.js +2 -0
  74. package/dist/cli-bundle/focused-chunks/mutation-actor-UQHBNHOF.js +2 -0
  75. package/dist/cli-bundle/focused-chunks/mutation-admission-G565NLPE.js +2 -0
  76. package/dist/cli-bundle/focused-chunks/{settlement-hook-H56537UV.js → settlement-hook-UXN76GMA.js} +2 -2
  77. package/dist/cli-bundle/focused-chunks/stage-F3YJGNRK.js +2 -0
  78. package/dist/cli-bundle/main.js +7 -7
  79. package/dist/cli-bundle/sdk-authoring.js +1 -1
  80. package/dist/cli-bundle/sdk-contracts.js +3 -3
  81. package/dist/cli-bundle/sdk-core.js +1 -1
  82. package/dist/cli-bundle/sdk-governance.js +1 -1
  83. package/dist/cli-bundle/sdk-graph.js +1 -1
  84. package/dist/cli-bundle/sdk-merge.js +57 -57
  85. package/dist/cli-bundle/sdk-query.js +1 -1
  86. package/dist/cli-bundle/sdk-runtime.js +1 -1
  87. package/dist/cli-bundle/sdk-testing.js +1 -1
  88. package/dist/cli-bundle/sdk.js +11 -11
  89. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  90. package/dist/core/extensions/extension-types.d.ts +30 -0
  91. package/dist/core/extensions/extension-types.js +1 -1
  92. package/dist/core/extensions/index.d.ts +21 -1
  93. package/dist/core/extensions/index.js +1 -1
  94. package/dist/core/extensions/mutation-actor-snapshot.js +2 -0
  95. package/dist/core/extensions/mutation-actor.js +2 -0
  96. package/dist/core/item/deferred-fields.js +2 -0
  97. package/dist/core/item/item-format-version.d.ts +8 -6
  98. package/dist/core/item/item-format-version.js +1 -1
  99. package/dist/core/item/item-format.js +2 -2
  100. package/dist/core/lock/lock.js +3 -3
  101. package/dist/core/output/linked-test-projection.js +6 -0
  102. package/dist/core/output/output.d.ts +7 -0
  103. package/dist/core/output/output.js +9 -7
  104. package/dist/core/schema/runtime-field-values.d.ts +4 -0
  105. package/dist/core/schema/runtime-field-values.js +1 -1
  106. package/dist/core/session/session-state.js +1 -1
  107. package/dist/core/shared/item-metadata-contract.js +1 -1
  108. package/dist/core/shared/text-normalization.d.ts +24 -0
  109. package/dist/core/shared/text-normalization.js +1 -1
  110. package/dist/core/shared/url-credentials.js +1 -1
  111. package/dist/core/store/item-store.js +1 -1
  112. package/dist/core/test/run-selectors.d.ts +3 -1
  113. package/dist/core/test/run-selectors.js +1 -1
  114. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  115. package/dist/sdk/annotations.js +1 -1
  116. package/dist/sdk/authoring.d.ts +1 -1
  117. package/dist/sdk/authoring.js +1 -1
  118. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  119. package/dist/sdk/cli-contracts/completeness.js +1 -1
  120. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  121. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  122. package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
  123. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +1 -1
  124. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  125. package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +1 -1
  126. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  127. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  128. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  129. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  130. package/dist/sdk/completion/bash.js +1 -1
  131. package/dist/sdk/completion/fish.js +6 -1
  132. package/dist/sdk/completion/zsh.js +6 -1
  133. package/dist/sdk/context-intent-contracts.js +1 -1
  134. package/dist/sdk/docs.d.ts +3 -1
  135. package/dist/sdk/docs.js +1 -1
  136. package/dist/sdk/environment/project-runtime-compatibility.d.ts +8 -1
  137. package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
  138. package/dist/sdk/extension/command-options.d.ts +23 -4
  139. package/dist/sdk/extension/command-options.js +1 -1
  140. package/dist/sdk/extension/native-command-options.js +2 -0
  141. package/dist/sdk/files.d.ts +3 -1
  142. package/dist/sdk/files.js +1 -1
  143. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  144. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  145. package/dist/sdk/governance/health.js +1 -1
  146. package/dist/sdk/governance/lifecycle-dependency-cycles.d.ts +12 -0
  147. package/dist/sdk/governance/lifecycle-dependency-cycles.js +2 -0
  148. package/dist/sdk/governance/validate-deferred-fields.js +2 -0
  149. package/dist/sdk/governance/validate.d.ts +2 -2
  150. package/dist/sdk/governance/validate.js +1 -1
  151. package/dist/sdk/guide-topics.js +1 -1
  152. package/dist/sdk/index.d.ts +1 -1
  153. package/dist/sdk/index.js +1 -1
  154. package/dist/sdk/item-transaction.d.ts +2 -2
  155. package/dist/sdk/item-transaction.js +1 -1
  156. package/dist/sdk/lifecycle/claim.d.ts +5 -1
  157. package/dist/sdk/lifecycle/claim.js +1 -1
  158. package/dist/sdk/lifecycle/close.js +1 -1
  159. package/dist/sdk/lifecycle/copy.js +1 -1
  160. package/dist/sdk/lifecycle/create-deferrals.js +2 -0
  161. package/dist/sdk/lifecycle/create.d.ts +6 -2
  162. package/dist/sdk/lifecycle/create.js +1 -1
  163. package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
  164. package/dist/sdk/lifecycle/plan.js +1 -1
  165. package/dist/sdk/lifecycle/restore.js +1 -1
  166. package/dist/sdk/lifecycle/shared-unset-fields.d.ts +7 -1
  167. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  168. package/dist/sdk/linked-artifacts.d.ts +45 -3
  169. package/dist/sdk/linked-artifacts.js +2 -2
  170. package/dist/sdk/merge/three-way.d.ts +1 -1
  171. package/dist/sdk/merge/three-way.js +2 -2
  172. package/dist/sdk/output/table-rows.d.ts +28 -4
  173. package/dist/sdk/output/table-rows.js +1 -1
  174. package/dist/sdk/output.d.ts +1 -1
  175. package/dist/sdk/output.js +1 -1
  176. package/dist/sdk/package-import-adapters.d.ts +9 -1
  177. package/dist/sdk/package-import-adapters.js +1 -1
  178. package/dist/sdk/pagination.js +1 -1
  179. package/dist/sdk/public-surface.json +1 -1
  180. package/dist/sdk/query/complete-list.d.ts +14 -5
  181. package/dist/sdk/query/complete-list.js +1 -1
  182. package/dist/sdk/query/list.js +1 -1
  183. package/dist/sdk/query/projection-contracts.d.ts +6 -0
  184. package/dist/sdk/query/projection-contracts.js +1 -1
  185. package/dist/sdk/read-output/continuation.js +1 -1
  186. package/dist/sdk/read-output/extension.js +1 -1
  187. package/dist/sdk/read-output-budget.js +1 -1
  188. package/dist/sdk/runtime-input.d.ts +6 -2
  189. package/dist/sdk/runtime-input.js +1 -1
  190. package/dist/sdk/runtime-primitives.d.ts +1 -1
  191. package/dist/sdk/runtime-primitives.js +1 -1
  192. package/dist/sdk/runtime.d.ts +2 -2
  193. package/dist/sdk/runtime.js +1 -1
  194. package/dist/sdk/structured-mutations.js +1 -1
  195. package/dist/sdk/test/batch.d.ts +5 -2
  196. package/dist/sdk/test/batch.js +2 -2
  197. package/dist/sdk/test/command-args.js +1 -1
  198. package/dist/sdk/test/entry.js +2 -2
  199. package/dist/sdk/test/execution.d.ts +10 -7
  200. package/dist/sdk/test/execution.js +2 -2
  201. package/dist/sdk/test/parsers.js +1 -1
  202. package/dist/sdk/test/prerequisites.d.ts +1 -1
  203. package/dist/sdk/test/prerequisites.js +1 -1
  204. package/dist/sdk/test/run-phases.d.ts +44 -0
  205. package/dist/sdk/test/run-phases.js +2 -0
  206. package/dist/sdk/testing.d.ts +15 -2
  207. package/dist/sdk/testing.js +1 -1
  208. package/dist/types.d.ts +11 -1
  209. package/dist/types.js +1 -1
  210. package/docs/AGENT_OUTPUT_ENCODINGS.md +16 -4
  211. package/docs/COMMANDS.md +31 -4
  212. package/docs/EXTENSIONS.md +1 -1
  213. package/docs/LINKED_TEST_EDITS.md +2 -1
  214. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +6 -3
  215. package/docs/README.md +2 -2
  216. package/docs/READ_OUTPUT_CONTRACTS.md +23 -2
  217. package/docs/SDK.md +129 -6
  218. package/docs/TESTING.md +64 -1
  219. package/docs/WORKSPACE_CONCURRENCY.md +5 -1
  220. package/docs/generated/FLAG_LEXICON_BUDGETS.md +9 -9
  221. package/marketplace.json +1 -1
  222. package/package.json +6 -4
  223. package/packages/pm-beads/package.json +1 -1
  224. package/packages/pm-calendar/extensions/calendar/command-definitions.ts +2 -0
  225. package/packages/pm-calendar/package.json +1 -1
  226. package/packages/pm-command-kit/package.json +1 -1
  227. package/packages/pm-digital-twin/package.json +1 -1
  228. package/packages/pm-governance-audit/package.json +1 -1
  229. package/packages/pm-guide-shell/package.json +1 -1
  230. package/packages/pm-kanban/package.json +1 -1
  231. package/packages/pm-lifecycle-hooks/package.json +1 -1
  232. package/packages/pm-linked-test-adapters/package.json +1 -1
  233. package/packages/pm-search-advanced/package.json +1 -1
  234. package/packages/pm-templates/package.json +1 -1
  235. package/packages/pm-todos/extensions/todos/runtime.ts +3 -0
  236. package/packages/pm-todos/package.json +1 -1
  237. package/packages/pm-vcs/package.json +1 -1
  238. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  239. package/plugins/pm-claude/package.json +1 -1
  240. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  241. package/plugins/pm-codex/package.json +1 -1
  242. package/plugins/pm-codex/plugin.json +1 -1
  243. package/runtime-dependencies.json +1 -1
  244. package/CHANGELOG.md +0 -4793
  245. package/dist/cli-bundle/chunks/chunk-36E4L2R4.js +0 -2
  246. package/dist/cli-bundle/chunks/chunk-4WD4CHVH.js +0 -8
  247. package/dist/cli-bundle/chunks/chunk-6UXBWMEM.js +0 -2
  248. package/dist/cli-bundle/chunks/chunk-CO7RWLCM.js +0 -2
  249. package/dist/cli-bundle/chunks/chunk-COTC2QOR.js +0 -6
  250. package/dist/cli-bundle/chunks/chunk-FAYX6C7H.js +0 -2
  251. package/dist/cli-bundle/chunks/chunk-GIAJX2QJ.js +0 -9
  252. package/dist/cli-bundle/chunks/chunk-HQINCDF6.js +0 -116
  253. package/dist/cli-bundle/chunks/chunk-IYDIPXBO.js +0 -2
  254. package/dist/cli-bundle/chunks/chunk-L4F4ZHGR.js +0 -2
  255. package/dist/cli-bundle/chunks/chunk-O4ZLEN4T.js +0 -3
  256. package/dist/cli-bundle/chunks/chunk-O6PBQMD7.js +0 -2
  257. package/dist/cli-bundle/chunks/chunk-O6T24Z3M.js +0 -2
  258. package/dist/cli-bundle/chunks/chunk-OQCVU2SG.js +0 -8
  259. package/dist/cli-bundle/chunks/chunk-QSSENTXG.js +0 -20
  260. package/dist/cli-bundle/chunks/chunk-TCYIGAQG.js +0 -31
  261. package/dist/cli-bundle/chunks/chunk-URWNUZQZ.js +0 -3
  262. package/dist/cli-bundle/chunks/chunk-UYARS5XF.js +0 -3
  263. package/dist/cli-bundle/chunks/item-revision-G5OVYGZ5.js +0 -2
  264. package/dist/cli-bundle/chunks/item-transaction-I2X2P4TW.js +0 -2
  265. package/dist/cli-bundle/chunks/mutation-admission-SET4KY73.js +0 -2
  266. package/dist/cli-bundle/chunks/register-mutation-WTHZHPOP.js +0 -20
  267. package/dist/cli-bundle/chunks/register-operations-EZP3EG6A.js +0 -2
  268. package/dist/cli-bundle/chunks/register-setup-THFZP23A.js +0 -2
  269. package/dist/cli-bundle/chunks/stage-JXJILTYE.js +0 -2
  270. package/dist/cli-bundle/focused-chunks/chunk-2ZPGEGTB.js +0 -2
  271. package/dist/cli-bundle/focused-chunks/chunk-3MB47JLT.js +0 -2
  272. package/dist/cli-bundle/focused-chunks/chunk-5KTOMFLR.js +0 -44
  273. package/dist/cli-bundle/focused-chunks/chunk-5NTLNE54.js +0 -26
  274. package/dist/cli-bundle/focused-chunks/chunk-ADBFVDTG.js +0 -8
  275. package/dist/cli-bundle/focused-chunks/chunk-CSKDIMQP.js +0 -2
  276. package/dist/cli-bundle/focused-chunks/chunk-FNIX62V6.js +0 -3
  277. package/dist/cli-bundle/focused-chunks/chunk-G6ERMFJ5.js +0 -3
  278. package/dist/cli-bundle/focused-chunks/chunk-IYV3IPRF.js +0 -65
  279. package/dist/cli-bundle/focused-chunks/chunk-QGQJBQCH.js +0 -2
  280. package/dist/cli-bundle/focused-chunks/chunk-RIMNSVFA.js +0 -26
  281. package/dist/cli-bundle/focused-chunks/chunk-VGJDKDKA.js +0 -2
  282. package/dist/cli-bundle/focused-chunks/chunk-VGUQ4V47.js +0 -82
  283. package/dist/cli-bundle/focused-chunks/chunk-VTOTZ5UC.js +0 -91
  284. package/dist/cli-bundle/focused-chunks/chunk-WFVZ7GGR.js +0 -2
  285. package/dist/cli-bundle/focused-chunks/chunk-ZOGEQFGH.js +0 -2
  286. package/dist/cli-bundle/focused-chunks/item-revision-IF7E7BVY.js +0 -2
  287. package/dist/cli-bundle/focused-chunks/item-transaction-5TFWIOXI.js +0 -2
  288. package/dist/cli-bundle/focused-chunks/mutation-admission-KELM46JF.js +0 -2
  289. package/dist/cli-bundle/focused-chunks/stage-UAKMQTCI.js +0 -2
@@ -1,5 +1,5 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="54aee8ec-9ef4-54d4-92fa-f4104b3ec4cc")}catch{}})();import{isFileMissingError}from"../fs/fs-utils.js";import{constants as fsConstants}from"node:fs";import fs from"node:fs/promises";import path from"node:path";import{createHash,randomUUID}from"node:crypto";import{runActiveOnReadHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{toErrorMessage}from"../shared/primitives.js";import{getLockPath}from"../store/paths.js";import{nowIso}from"../shared/time.js";import{LOCK_PATH_UNSAFE_CODE,assertLockEntryNotSymlink,inspectConfinedLockDirectory,verifyConfinedLockCreation}from"./lock-confinement.js";import{captureProcessIdentity,captureLockOwnerIdentity,inspectLockOwner,isProcessIdentityAlive,parseLinuxProcessStartIdentity,readProcessStartIdentity}from"./lock-owner.js";import{captureProcessIdentity as captureProcessIdentity2,isProcessIdentityAlive as isProcessIdentityAlive2,readProcessStartIdentity as readProcessStartIdentity2}from"./lock-owner.js";function parseLockInfo(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return{info:null,warnings:["lock_info_invalid_json"]}}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return{info:null,warnings:["lock_info_invalid_shape"]};const candidate=parsed,id=candidate.id,pid=candidate.pid,owner=candidate.owner,token=candidate.token,createdAt=candidate.created_at,ttlSeconds=candidate.ttl_seconds;return typeof id!="string"||typeof pid!="number"||!Number.isFinite(pid)||typeof owner!="string"||token!==void 0&&(typeof token!="string"||token.trim().length===0)||typeof createdAt!="string"||typeof ttlSeconds!="number"||!Number.isFinite(ttlSeconds)?{info:null,warnings:["lock_info_invalid_shape"]}:{info:{id,pid,owner,...typeof token=="string"?{token}:{},created_at:createdAt,ttl_seconds:ttlSeconds,host_identity:candidate.host_identity,process_start_identity:candidate.process_start_identity},warnings:[]}}async function readLockInfo(lockPath,emitReadHook=!0){try{const raw=await fs.readFile(lockPath,"utf8");return emitReadHook&&await runActiveOnReadHooks({path:lockPath,scope:"project"}),parseLockInfo(raw)}catch(error){return isFileMissingError(error)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}async function isLockCreateContention(error,lockPath,platform=process.platform){if(isErrno(error,"EEXIST"))return!0;if(!isErrno(error,"EPERM")&&!isErrno(error,"EACCES")&&!isErrno(error,"EBUSY"))return!1;try{return await fs.lstat(lockPath),!0}catch(probeError){if(platform!=="win32"||!isFileMissingError(probeError)&&!isErrno(probeError,"EPERM")&&!isErrno(probeError,"EACCES")&&!isErrno(probeError,"EBUSY"))return!1}try{return await fs.access(path.dirname(lockPath),fsConstants.W_OK),!0}catch{return!1}}async function emitLockWriteHook(lockPath,op){await runActiveOnWriteHooks({path:lockPath,scope:"project",op})}async function buildLockPayload(id,owner,ttlSeconds,token=randomUUID()){return{...await captureLockOwnerIdentity(),id,pid:process.pid,owner,token,created_at:nowIso(),ttl_seconds:ttlSeconds}}async function createLockFile(pmRoot,lockPath,id,owner,ttlSeconds,token,createParentDirectories){const existingDirectory=await inspectConfinedLockDirectory(pmRoot,lockPath,id);createParentDirectories&&existingDirectory===null&&await fs.mkdir(path.dirname(lockPath),{recursive:!0});const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate===null)throw await fs.access(path.dirname(lockPath)),Object.assign(new Error("Lock initialization is contended"),{code:"EEXIST"});let createdAt;try{const directory=await inspectConfinedLockDirectory(pmRoot,lockPath,id,!1),handle=await fs.open(lockPath,"wx");try{await verifyConfinedLockCreation({pmRoot,lockPath,id,handle,directory})}catch(error){throw await handle.close(),error}try{try{const payload=await buildLockPayload(id,owner,ttlSeconds,token);createdAt=payload.created_at,await handle.writeFile(`${JSON.stringify(payload,null,2)}
2
- `,"utf8")}finally{await handle.close()}}catch(error){throw await unlinkLockWithHook(lockPath,"lock:release"),error}}finally{await releaseCleanupGate()}return await emitLockWriteHook(lockPath,"lock:create"),createdAt}async function unlinkLockWithHook(lockPath,op){try{return await fs.unlink(lockPath),await emitLockWriteHook(lockPath,op),!0}catch{return!1}}async function releaseOwnedLock(lockPath,id,owner,token){const startedAtMs=performance.now();let backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;for(;;){const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate!==null){try{const current2=await readLockInfo(lockPath,!1);isOwnedLock(current2.info,id,owner,token)&&await unlinkLockWithHook(lockPath,"lock:release")}finally{await releaseCleanupGate()}return}const current=await readLockInfo(lockPath,!1);if(!isOwnedLock(current.info,id,owner,token))return;const elapsedMs=performance.now()-startedAtMs;if(elapsedMs>=LOCK_RELEASE_GATE_WAIT_MS)return;await sleepWithJitter(Math.min(backoffMs,LOCK_RELEASE_GATE_WAIT_MS-elapsedMs)),backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}function isOwnedLock(info,id,owner,token){return info?.id===id&&info.pid===process.pid&&info.owner===owner&&info.token===token}function isStaleLock(info,ttlSeconds){const createdAtMs=info?.created_at?Date.parse(info.created_at):Number.NaN;return(Number.isFinite(createdAtMs)?Date.now()-createdAtMs:Number.POSITIVE_INFINITY)>ttlSeconds*1e3}async function isConfirmedDeadLock(info){return info!==null&&Number.isFinite(Date.parse(info.created_at))&&await inspectLockOwner(info)==="dead"}async function isReclaimableLock(info,ttlSeconds){return isStaleLock(info,ttlSeconds)||await isConfirmedDeadLock(info)}async function hasUnexpiredLockOwner(pmRoot,id,ownerPrefix){const{info}=await readLockInfo(getLockPath(pmRoot,id),!1);return info!==null&&info.owner.startsWith(ownerPrefix)&&!await isReclaimableLock(info,info.ttl_seconds)}function lockOwnerSuffix(info){return info?.owner?` (owner ${info.owner})`:""}const LOCK_WAIT_INITIAL_DELAY_MS=25,LOCK_WAIT_MAX_DELAY_MS=200,LOCK_CONFLICT_RETRY_HINT_MS=250,LOCK_PROGRESS_MAX_WAIT_MS=12e4,MAX_STALE_LOCK_REMOVALS=3,STALE_CLEANUP_GATE_SUFFIX=".stale-cleanup",STALE_CLEANUP_GATE_OWNER_FILE="owner.json",STALE_CLEANUP_GATE_STALE_MS=1e4,LOCK_RELEASE_GATE_WAIT_MS=STALE_CLEANUP_GATE_STALE_MS+LOCK_WAIT_MAX_DELAY_MS;function parseNonNegativeIntegerWaitMs(value){if(typeof value=="string"){const trimmed=value.trim();if(!/^\d+$/.test(trimmed))return;const parsed=Number(trimmed);return Number.isSafeInteger(parsed)?parsed:void 0}if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return Math.trunc(value)}function resolveLockWaitMs(waitMs){const envRaw=process.env.PM_LOCK_WAIT_MS,envParsed=parseNonNegativeIntegerWaitMs(envRaw);if(envParsed!==void 0)return envParsed;const callerParsed=parseNonNegativeIntegerWaitMs(waitMs);return callerParsed!==void 0?callerParsed:0}function cappedLockWaitMs(waitMs,maxWaitMs){return Math.min(resolveLockWaitMs(waitMs),maxWaitMs??1/0)}function sleepWithJitter(baseDelayMs){const jitteredMs=Math.max(1,Math.round(baseDelayMs*(.5+Math.random())));return new Promise(resolve=>setTimeout(resolve,jitteredMs))}async function buildLockConflictError(id,info,waitedMs,ownerHandoffs=0){waitedMs=Math.floor(waitedMs);const ownerState=await inspectLockOwner(info),handoffSuffix=ownerHandoffs>0?` across ${ownerHandoffs} owner handoff(s)`:"",waitedSuffix=waitedMs>0?` after waiting ${waitedMs}ms${handoffSuffix}`:"";return new PmCliError(`Item ${id} is locked${lockOwnerSuffix(info)} (owner process ${ownerState})${waitedSuffix}`,EXIT_CODE.CONFLICT,{code:"lock_conflict",item_id:id,reason:`lock_owner_${ownerState}`,required:"Wait for the owner to release the lock, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget when contention is expected. Inspect stale receipts with pm gc --scope locks --dry-run.",recovery:{retry_after_ms:LOCK_CONFLICT_RETRY_HINT_MS,...waitedMs>0?{waited_ms:waitedMs,owner_handoffs:ownerHandoffs}:{}}})}function createLockWaitTracker(waitBudgetMs,totalCeilingMs){const startedAtMs=performance.now();let stallStartedAtMs=startedAtMs,observedGeneration,ownerHandoffs=0;return{startedAtMs,observe(info){const nowMs=performance.now(),generation=lockGenerationKey(info);observedGeneration!==void 0&&generation!==observedGeneration&&(ownerHandoffs+=1,stallStartedAtMs=nowMs),observedGeneration=generation;const elapsedMs=nowMs-startedAtMs,stalledMs=nowMs-stallStartedAtMs;return{exhausted:waitBudgetMs===0||stalledMs>=waitBudgetMs||elapsedMs>=totalCeilingMs,elapsedMs,remainingMs:Math.min(waitBudgetMs-stalledMs,totalCeilingMs-elapsedMs),ownerHandoffs}}}}function resolveLockWaitCeilingMs(waitBudgetMs,maxWaitMs,waitPolicy){return waitPolicy!=="progress"||maxWaitMs!==void 0?waitBudgetMs:Math.max(waitBudgetMs,LOCK_PROGRESS_MAX_WAIT_MS)}function lockGenerationKey(info){return info===null?"released":info.token??`${info.pid}:${info.owner}:${info.created_at}`}function describeLease(lease){const expiresAtMs=Date.parse(lease.acquiredAt)+lease.ttlSeconds*1e3;return{owner:lease.owner,acquired_at:lease.acquiredAt,ttl_seconds:lease.ttlSeconds,expires_at:new Date(expiresAtMs).toISOString()}}function describeLockLoss(id,lease,current,reason){const leaseLabel=`the lease acquired at ${lease.acquiredAt} (ttl ${lease.ttlSeconds}s)`;if(reason==="fence_gate_unavailable")return{summary:`Lock for ${id} could not be verified before commit: ${leaseLabel} could not enter its commit fence because the stale-cleanup gate stayed held.`,required:"Retry the same operation; this writer's change was not committed. Inspect pm gc --scope locks --dry-run if the stale-cleanup gate stays held."};const holder=current===null?"the lock no longer exists":`it is now held by ${current.owner} since ${current.created_at}`;return{summary:`Lock for ${id} was lost before commit: ${leaseLabel} is no longer owned by this writer, and ${holder}.`,required:"Re-read the item and apply the mutation again; this writer's change was not committed and the newer value was kept. Keep mutation work shorter than locks.ttl_seconds, or raise locks.ttl_seconds for long-running callbacks."}}function buildLockLostError(id,lease,current,reason){const{summary,required}=describeLockLoss(id,lease,current,reason);return new PmCliError(`${summary} Nothing was written.`,EXIT_CODE.CONFLICT,{code:"lock_lost",item_id:id,reason,lease:describeLease(lease),current_owner:current===null?null:{owner:current.owner,pid:current.pid,created_at:current.created_at,ttl_seconds:current.ttl_seconds},required,recovery:{retry_after_ms:LOCK_CONFLICT_RETRY_HINT_MS}})}async function waitForStaleCleanupGate(lockPath,id){const startedAtMs=performance.now();let backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;for(;;){const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate!==null)return releaseCleanupGate;const elapsedMs=performance.now()-startedAtMs;if(elapsedMs>=LOCK_RELEASE_GATE_WAIT_MS)return null;await sleepWithJitter(Math.min(backoffMs,LOCK_RELEASE_GATE_WAIT_MS-elapsedMs)),backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}async function fenceOwnedLock(lockPath,id,lease,commit){const releaseCleanupGate=await waitForStaleCleanupGate(lockPath,id);if(releaseCleanupGate===null){const current=await readLockInfo(lockPath,!1);throw buildLockLostError(id,lease,current.info,"fence_gate_unavailable")}try{const current=await readLockInfo(lockPath,!1);if(!isOwnedLock(current.info,id,lease.owner,lease.token))throw buildLockLostError(id,lease,current.info,current.info===null?"lease_released":"lease_taken_over");return await commit()}finally{await releaseCleanupGate()}}function resolveLockOverrideRelease(result){if(typeof result=="function")return result;if(typeof result=="object"&&result!==null&&"release"in result){const release=result.release;return typeof release=="function"?release:null}return null}function throwIfStaleLockNeedsForce(id,lockInfo,force,forceRequired){if(!force&&forceRequired){const warningSuffix=lockInfo.warnings.length>0?` (${lockInfo.warnings.join(",")})`:"";throw new PmCliError(`Item ${id} lock is stale${warningSuffix}; rerun with --force when supported for this command`,EXIT_CODE.CONFLICT)}}function parseStaleCleanupGateOwner(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return null}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return null;const candidate=parsed,pid=candidate.pid,token=candidate.token,processStartIdentity=candidate.process_start_identity;return typeof pid!="number"||!Number.isInteger(pid)||pid<=0||typeof token!="string"||token.length===0||processStartIdentity!==void 0&&(typeof processStartIdentity!="string"||!/^\d+$/u.test(processStartIdentity))?null:{pid,token,host_identity:candidate.host_identity,...typeof processStartIdentity=="string"?{process_start_identity:processStartIdentity}:{}}}async function readStaleCleanupGateOwner(gatePath){try{return parseStaleCleanupGateOwner(await fs.readFile(path.join(gatePath,STALE_CLEANUP_GATE_OWNER_FILE),"utf8"))}catch(error){return isFileMissingError(error)?null:void 0}}async function removeStaleCleanupGateDirectory(gatePath){try{return await fs.rm(gatePath,{recursive:!0,force:!0}),!0}catch{return!1}}async function releaseStaleCleanupGate(gatePath,token){let owner=await readStaleCleanupGateOwner(gatePath);for(let attempt=0;owner===void 0&&attempt<3;attempt+=1)await sleepWithJitter(LOCK_WAIT_INITIAL_DELAY_MS),owner=await readStaleCleanupGateOwner(gatePath);!owner||owner.token!==token||await removeStaleCleanupGateDirectory(gatePath)}async function tryCreateStaleCleanupGate(gatePath){try{await fs.mkdir(gatePath)}catch(error){return isErrno(error,"EEXIST"),null}const owner={...await captureProcessIdentity(),host_identity:(await captureLockOwnerIdentity()).host_identity,token:randomUUID()};try{await fs.writeFile(path.join(gatePath,STALE_CLEANUP_GATE_OWNER_FILE),`${JSON.stringify(owner)}
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="be5b7a07-492a-5ca6-b607-059251a7cea3")}catch{}})();import{isFileMissingError}from"../fs/fs-utils.js";import{constants as fsConstants}from"node:fs";import fs from"node:fs/promises";import path from"node:path";import{createHash,randomUUID}from"node:crypto";import{runActiveOnReadHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{toErrorMessage}from"../shared/primitives.js";import{getLockPath,getSettingsPath,resolvePmRoot}from"../store/paths.js";import{renderPmCommand}from"../shared/command-line.js";import{nowIso}from"../shared/time.js";import{LOCK_PATH_UNSAFE_CODE,assertLockEntryNotSymlink,inspectConfinedLockDirectory,verifyConfinedLockCreation}from"./lock-confinement.js";import{captureProcessIdentity,captureLockOwnerIdentity,inspectLockOwner,isProcessIdentityAlive,parseLinuxProcessStartIdentity,readProcessStartIdentity}from"./lock-owner.js";import{captureProcessIdentity as captureProcessIdentity2,isProcessIdentityAlive as isProcessIdentityAlive2,readProcessStartIdentity as readProcessStartIdentity2}from"./lock-owner.js";function parseLockInfo(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return{info:null,warnings:["lock_info_invalid_json"]}}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return{info:null,warnings:["lock_info_invalid_shape"]};const candidate=parsed,id=candidate.id,pid=candidate.pid,owner=candidate.owner,token=candidate.token,createdAt=candidate.created_at,ttlSeconds=candidate.ttl_seconds;return typeof id!="string"||typeof pid!="number"||!Number.isFinite(pid)||typeof owner!="string"||token!==void 0&&(typeof token!="string"||token.trim().length===0)||typeof createdAt!="string"||typeof ttlSeconds!="number"||!Number.isFinite(ttlSeconds)?{info:null,warnings:["lock_info_invalid_shape"]}:{info:{id,pid,owner,...typeof token=="string"?{token}:{},created_at:createdAt,ttl_seconds:ttlSeconds,host_identity:candidate.host_identity,process_start_identity:candidate.process_start_identity},warnings:[]}}async function readLockInfo(lockPath,emitReadHook=!0){try{const raw=await fs.readFile(lockPath,"utf8");return emitReadHook&&await runActiveOnReadHooks({path:lockPath,scope:"project"}),parseLockInfo(raw)}catch(error){return isFileMissingError(error)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}async function isLockCreateContention(error,lockPath,platform=process.platform){if(isErrno(error,"EEXIST"))return!0;if(!isErrno(error,"EPERM")&&!isErrno(error,"EACCES")&&!isErrno(error,"EBUSY"))return!1;try{return await fs.lstat(lockPath),!0}catch(probeError){if(platform!=="win32"||!isFileMissingError(probeError)&&!isErrno(probeError,"EPERM")&&!isErrno(probeError,"EACCES")&&!isErrno(probeError,"EBUSY"))return!1}try{return await fs.access(path.dirname(lockPath),fsConstants.W_OK),!0}catch{return!1}}async function emitLockWriteHook(lockPath,op){await runActiveOnWriteHooks({path:lockPath,scope:"project",op})}async function buildLockPayload(id,owner,ttlSeconds,token=randomUUID()){return{...await captureLockOwnerIdentity(),id,pid:process.pid,owner,token,created_at:nowIso(),ttl_seconds:ttlSeconds}}async function createLockFile(pmRoot,lockPath,id,owner,ttlSeconds,token,createParentDirectories){const existingDirectory=await inspectConfinedLockDirectory(pmRoot,lockPath,id);createParentDirectories&&existingDirectory===null&&await fs.mkdir(path.dirname(lockPath),{recursive:!0});const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate===null)throw await fs.access(path.dirname(lockPath)),Object.assign(new Error("Lock initialization is contended"),{code:"EEXIST"});let createdAt;try{const directory=await inspectConfinedLockDirectory(pmRoot,lockPath,id,!1),handle=await fs.open(lockPath,"wx");try{await verifyConfinedLockCreation({pmRoot,lockPath,id,handle,directory})}catch(error){throw await handle.close(),error}try{try{const payload=await buildLockPayload(id,owner,ttlSeconds,token);createdAt=payload.created_at,await handle.writeFile(`${JSON.stringify(payload,null,2)}
2
+ `,"utf8")}finally{await handle.close()}}catch(error){throw await unlinkLockWithHook(lockPath,"lock:release"),error}}finally{await releaseCleanupGate()}return await emitLockWriteHook(lockPath,"lock:create"),createdAt}async function unlinkLockWithHook(lockPath,op){try{return await fs.unlink(lockPath),await emitLockWriteHook(lockPath,op),!0}catch{return!1}}async function releaseOwnedLock(lockPath,id,owner,token){const startedAtMs=performance.now();let backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;for(;;){const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate!==null){try{const current2=await readLockInfo(lockPath,!1);isOwnedLock(current2.info,id,owner,token)&&await unlinkLockWithHook(lockPath,"lock:release")}finally{await releaseCleanupGate()}return}const current=await readLockInfo(lockPath,!1);if(!isOwnedLock(current.info,id,owner,token))return;const elapsedMs=performance.now()-startedAtMs;if(elapsedMs>=LOCK_RELEASE_GATE_WAIT_MS)return;await sleepWithJitter(Math.min(backoffMs,LOCK_RELEASE_GATE_WAIT_MS-elapsedMs)),backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}function isOwnedLock(info,id,owner,token){return info?.id===id&&info.pid===process.pid&&info.owner===owner&&info.token===token}function isStaleLock(info,ttlSeconds){const createdAtMs=info?.created_at?Date.parse(info.created_at):Number.NaN;return(Number.isFinite(createdAtMs)?Date.now()-createdAtMs:Number.POSITIVE_INFINITY)>ttlSeconds*1e3}async function isConfirmedDeadLock(info){return info!==null&&Number.isFinite(Date.parse(info.created_at))&&await inspectLockOwner(info)==="dead"}async function isReclaimableLock(info,ttlSeconds){return isStaleLock(info,ttlSeconds)||await isConfirmedDeadLock(info)}async function hasUnexpiredLockOwner(pmRoot,id,ownerPrefix){const{info}=await readLockInfo(getLockPath(pmRoot,id),!1);return info!==null&&info.owner.startsWith(ownerPrefix)&&!await isReclaimableLock(info,info.ttl_seconds)}function lockOwnerSuffix(info){return info?.owner?` (owner ${info.owner})`:""}const LOCK_WAIT_INITIAL_DELAY_MS=25,LOCK_WAIT_MAX_DELAY_MS=200,LOCK_CONFLICT_RETRY_HINT_MS=250,LOCK_PROGRESS_MAX_WAIT_MS=12e4,MAX_STALE_LOCK_REMOVALS=3,STALE_CLEANUP_GATE_SUFFIX=".stale-cleanup",STALE_CLEANUP_GATE_OWNER_FILE="owner.json",STALE_CLEANUP_GATE_STALE_MS=1e4,LOCK_RELEASE_GATE_WAIT_MS=STALE_CLEANUP_GATE_STALE_MS+LOCK_WAIT_MAX_DELAY_MS;function parseNonNegativeIntegerWaitMs(value){if(typeof value=="string"){const trimmed=value.trim();if(!/^\d+$/.test(trimmed))return;const parsed=Number(trimmed);return Number.isSafeInteger(parsed)?parsed:void 0}if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return Math.trunc(value)}function resolveLockWaitMs(waitMs){const envRaw=process.env.PM_LOCK_WAIT_MS,envParsed=parseNonNegativeIntegerWaitMs(envRaw);if(envParsed!==void 0)return envParsed;const callerParsed=parseNonNegativeIntegerWaitMs(waitMs);return callerParsed!==void 0?callerParsed:0}function cappedLockWaitMs(waitMs,maxWaitMs){return Math.min(resolveLockWaitMs(waitMs),maxWaitMs??1/0)}function sleepWithJitter(baseDelayMs){const jitteredMs=Math.max(1,Math.round(baseDelayMs*(.5+Math.random())));return new Promise(resolve=>setTimeout(resolve,jitteredMs))}async function buildLockConflictError(id,info,waitedMs,ownerHandoffs=0){waitedMs=Math.floor(waitedMs);const ownerState=await inspectLockOwner(info),handoffSuffix=ownerHandoffs>0?` across ${ownerHandoffs} owner handoff(s)`:"",waitedSuffix=waitedMs>0?` after waiting ${waitedMs}ms${handoffSuffix}`:"";return new PmCliError(`Item ${id} is locked${lockOwnerSuffix(info)} (owner process ${ownerState})${waitedSuffix}`,EXIT_CODE.CONFLICT,{code:"lock_conflict",item_id:id,reason:`lock_owner_${ownerState}`,required:"Wait for the owner to release the lock, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget when contention is expected. Inspect stale receipts with pm gc --scope locks --dry-run.",recovery:{retry_after_ms:LOCK_CONFLICT_RETRY_HINT_MS,...waitedMs>0?{waited_ms:waitedMs,owner_handoffs:ownerHandoffs}:{}}})}function createLockWaitTracker(waitBudgetMs,totalCeilingMs){const startedAtMs=performance.now();let stallStartedAtMs=startedAtMs,observedGeneration,ownerHandoffs=0;return{startedAtMs,observe(info){const nowMs=performance.now(),generation=lockGenerationKey(info);observedGeneration!==void 0&&generation!==observedGeneration&&(ownerHandoffs+=1,stallStartedAtMs=nowMs),observedGeneration=generation;const elapsedMs=nowMs-startedAtMs,stalledMs=nowMs-stallStartedAtMs;return{exhausted:waitBudgetMs===0||stalledMs>=waitBudgetMs||elapsedMs>=totalCeilingMs,elapsedMs,remainingMs:Math.min(waitBudgetMs-stalledMs,totalCeilingMs-elapsedMs),ownerHandoffs}}}}function resolveLockWaitCeilingMs(waitBudgetMs,maxWaitMs,waitPolicy){return waitPolicy!=="progress"||maxWaitMs!==void 0?waitBudgetMs:Math.max(waitBudgetMs,LOCK_PROGRESS_MAX_WAIT_MS)}function lockGenerationKey(info){return info===null?"released":info.token??`${info.pid}:${info.owner}:${info.created_at}`}function describeLease(lease){const expiresAtMs=Date.parse(lease.acquiredAt)+lease.ttlSeconds*1e3;return{owner:lease.owner,acquired_at:lease.acquiredAt,ttl_seconds:lease.ttlSeconds,expires_at:new Date(expiresAtMs).toISOString()}}function describeLockLoss(id,lease,current,reason){const leaseLabel=`the lease acquired at ${lease.acquiredAt} (ttl ${lease.ttlSeconds}s)`;if(reason==="fence_gate_unavailable")return{summary:`Lock for ${id} could not be verified before commit: ${leaseLabel} could not enter its commit fence because the stale-cleanup gate stayed held.`,required:"Retry the same operation; this writer's change was not committed. Inspect pm gc --scope locks --dry-run if the stale-cleanup gate stays held."};const holder=current===null?"the lock no longer exists":`it is now held by ${current.owner} since ${current.created_at}`;return{summary:`Lock for ${id} was lost before commit: ${leaseLabel} is no longer owned by this writer, and ${holder}.`,required:"Re-read the item and apply the mutation again; this writer's change was not committed and the newer value was kept. Keep mutation work shorter than locks.ttl_seconds, or raise locks.ttl_seconds for long-running callbacks."}}function buildLockLostError(id,lease,current,reason){const{summary,required}=describeLockLoss(id,lease,current,reason);return new PmCliError(`${summary} Nothing was written.`,EXIT_CODE.CONFLICT,{code:"lock_lost",item_id:id,reason,lease:describeLease(lease),current_owner:current===null?null:{owner:current.owner,pid:current.pid,created_at:current.created_at,ttl_seconds:current.ttl_seconds},required,recovery:{retry_after_ms:LOCK_CONFLICT_RETRY_HINT_MS}})}async function waitForStaleCleanupGate(lockPath,id){const startedAtMs=performance.now();let backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;for(;;){const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate!==null)return releaseCleanupGate;const elapsedMs=performance.now()-startedAtMs;if(elapsedMs>=LOCK_RELEASE_GATE_WAIT_MS)return null;await sleepWithJitter(Math.min(backoffMs,LOCK_RELEASE_GATE_WAIT_MS-elapsedMs)),backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}async function fenceOwnedLock(lockPath,id,lease,commit){const releaseCleanupGate=await waitForStaleCleanupGate(lockPath,id);if(releaseCleanupGate===null){const current=await readLockInfo(lockPath,!1);throw buildLockLostError(id,lease,current.info,"fence_gate_unavailable")}try{const current=await readLockInfo(lockPath,!1);if(!isOwnedLock(current.info,id,lease.owner,lease.token))throw buildLockLostError(id,lease,current.info,current.info===null?"lease_released":"lease_taken_over");return await commit()}finally{await releaseCleanupGate()}}function resolveLockOverrideRelease(result){if(typeof result=="function")return result;if(typeof result=="object"&&result!==null&&"release"in result){const release=result.release;return typeof release=="function"?release:null}return null}async function staleLockCleanupStep(lockPath,relativeLockPath,gcRemovable){const lockRoot=path.dirname(path.dirname(lockPath)),manual=`Remove ${relativeLockPath} under ${path.relative(process.cwd(),lockRoot)||"."} once its owner is confirmed gone, then retry the same command.`;if(!gcRemovable)return`${manual} pm gc --scope locks keeps this lock: its metadata cannot be read or dated, or its own TTL has not run out.`;try{await fs.access(getSettingsPath(lockRoot))}catch{return manual}const cwd=process.cwd(),scope=path.resolve(resolvePmRoot(cwd))===path.resolve(lockRoot)?[]:["--pm-path",path.relative(cwd,lockRoot)||"."];return`Run ${renderPmCommand([...scope,"gc","--scope","locks"])} (add --dry-run to preview), then retry the same command.`}function isGcRemovableLock(lockInfo){return lockInfo.info!==null&&lockInfo.warnings.length===0&&Number.isFinite(Date.parse(lockInfo.info.created_at))&&isStaleLock(lockInfo.info,lockInfo.info.ttl_seconds)}async function throwIfStaleLockNeedsForce(id,lockPath,lockInfo,force,forceRequired){if(!force&&forceRequired){const warningSuffix=lockInfo.warnings.length>0?` (${lockInfo.warnings.join(",")})`:"",relativeLockPath=`locks/${path.basename(lockPath)}`;throw new PmCliError(`Lock ${id} is stale${warningSuffix}; remove the expired lease, or rerun with --force where this command accepts it`,EXIT_CODE.CONFLICT,{code:"stale_lock_requires_override",details:{lock_id:id,lock_path:relativeLockPath},why:`The lease in ${relativeLockPath} is past its TTL, and force_required_for_stale_lock keeps an expired lease until it is removed explicitly.`,required:"Remove the expired lease, then retry the same command.",nextSteps:[await staleLockCleanupStep(lockPath,relativeLockPath,isGcRemovableLock(lockInfo))]})}}function parseStaleCleanupGateOwner(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return null}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return null;const candidate=parsed,pid=candidate.pid,token=candidate.token,processStartIdentity=candidate.process_start_identity;return typeof pid!="number"||!Number.isInteger(pid)||pid<=0||typeof token!="string"||token.length===0||processStartIdentity!==void 0&&(typeof processStartIdentity!="string"||!/^\d+$/u.test(processStartIdentity))?null:{pid,token,host_identity:candidate.host_identity,...typeof processStartIdentity=="string"?{process_start_identity:processStartIdentity}:{}}}async function readStaleCleanupGateOwner(gatePath){try{return parseStaleCleanupGateOwner(await fs.readFile(path.join(gatePath,STALE_CLEANUP_GATE_OWNER_FILE),"utf8"))}catch(error){return isFileMissingError(error)?null:void 0}}async function removeStaleCleanupGateDirectory(gatePath){try{return await fs.rm(gatePath,{recursive:!0,force:!0}),!0}catch{return!1}}async function releaseStaleCleanupGate(gatePath,token){let owner=await readStaleCleanupGateOwner(gatePath);for(let attempt=0;owner===void 0&&attempt<3;attempt+=1)await sleepWithJitter(LOCK_WAIT_INITIAL_DELAY_MS),owner=await readStaleCleanupGateOwner(gatePath);!owner||owner.token!==token||await removeStaleCleanupGateDirectory(gatePath)}async function tryCreateStaleCleanupGate(gatePath){try{await fs.mkdir(gatePath)}catch(error){return isErrno(error,"EEXIST"),null}const owner={...await captureProcessIdentity(),host_identity:(await captureLockOwnerIdentity()).host_identity,token:randomUUID()};try{await fs.writeFile(path.join(gatePath,STALE_CLEANUP_GATE_OWNER_FILE),`${JSON.stringify(owner)}
3
3
  `,"utf8")}catch{return await removeStaleCleanupGateDirectory(gatePath),null}return owner}async function retireCleanupGateGeneration(gatePath,token){const recoveries=path.join(path.dirname(gatePath),"recoveries"),generation=createHash("sha256").update(token).digest("hex");try{return await fs.mkdir(recoveries,{recursive:!0}),(await readStaleCleanupGateOwner(gatePath))?.token!==token?!1:(await fs.rename(gatePath,path.join(recoveries,`gate-${generation}`)),!0)}catch{return!1}}async function removeExpiredStaleCleanupGate(gatePath){let gateAgeMs;try{const stats=await fs.stat(gatePath);gateAgeMs=Date.now()-stats.mtimeMs}catch(error){return isFileMissingError(error)}const owner=await readStaleCleanupGateOwner(gatePath);if(owner===void 0)return!1;if(owner!==null){if(await inspectLockOwner(owner)==="dead")return retireCleanupGateGeneration(gatePath,owner.token);if(owner.host_identity!==void 0)return!1}return gateAgeMs<=STALE_CLEANUP_GATE_STALE_MS||owner!==null&&await isProcessIdentityAlive(owner,gateAgeMs,Number.POSITIVE_INFINITY)?!1:owner!==null?retireCleanupGateGeneration(gatePath,owner.token):removeStaleCleanupGateDirectory(gatePath)}async function acquireStaleCleanupGate(lockPath,_id){const gatePath=`${lockPath}${STALE_CLEANUP_GATE_SUFFIX}`,owner=await tryCreateStaleCleanupGate(gatePath);if(owner!==null)return async()=>releaseStaleCleanupGate(gatePath,owner.token);if(!await removeExpiredStaleCleanupGate(gatePath))return null;const recoveredOwner=await tryCreateStaleCleanupGate(gatePath);return recoveredOwner===null?null:async()=>releaseStaleCleanupGate(gatePath,recoveredOwner.token)}async function recordDeadLockRecovery(lockPath,raw){const directory=path.join(path.dirname(lockPath),"recoveries");await fs.mkdir(directory,{recursive:!0}),await fs.writeFile(path.join(directory,`${randomUUID()}.json`),`${JSON.stringify({event:"owner_dead_recovery_attempt",recorded_at:nowIso(),lock:JSON.parse(raw)})}
4
- `,{encoding:"utf8",flag:"wx",mode:384})}async function removeConfirmedStaleLock(params){const releaseCleanupGate=await acquireStaleCleanupGate(params.lockPath,params.id);if(releaseCleanupGate===null)return{lockInfo:params.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{const currentLockInfo=await readLockInfo(params.lockPath);if(currentLockInfo.info===null&&currentLockInfo.warnings.length===0)return{lockInfo:currentLockInfo,shouldRetryCreate:!0,staleRemovalCounted:!1};const ownerDead=await isConfirmedDeadLock(currentLockInfo.info);if(!isStaleLock(currentLockInfo.info,params.ttlSeconds)&&!ownerDead)return{lockInfo:currentLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};if(throwIfStaleLockNeedsForce(params.id,currentLockInfo,params.force||ownerDead,params.forceRequiredForStaleLock),params.staleRemovals>=MAX_STALE_LOCK_REMOVALS)throw await buildLockConflictError(params.id,currentLockInfo.info,performance.now()-params.startedAtMs);return ownerDead&&await recordDeadLockRecovery(params.lockPath,JSON.stringify(currentLockInfo.info)),{lockInfo:currentLockInfo,shouldRetryCreate:await unlinkLockWithHook(params.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await releaseCleanupGate()}}async function assertLockCreateContention(error,pmRoot,lockPath,id){if(error instanceof PmCliError&&error.code===LOCK_PATH_UNSAFE_CODE)throw error;if(!await isLockCreateContention(error,lockPath))throw new PmCliError(`Failed to acquire lock for ${id}: ${toErrorMessage(error)}`,EXIT_CODE.GENERIC_FAILURE);await assertLockEntryNotSymlink(pmRoot,lockPath,id)}const _testOnly={parseLockInfo,readLockInfo,isErrno,isLockCreateContention,buildLockPayload,isStaleLock,lockOwnerSuffix,resolveLockWaitMs,lockGenerationKey,parseLinuxProcessStartIdentity,readProcessStartIdentity,acquireStaleCleanupGate,removeConfirmedStaleLock};async function acquireLock(pmRoot,id,ttlSeconds,owner,force=!1,forceRequiredForStaleLock=!0,waitMs,options={}){return(await acquireLockLease(pmRoot,id,ttlSeconds,owner,force,forceRequiredForStaleLock,waitMs,options)).release}async function acquireLockLease(pmRoot,id,ttlSeconds,owner,force=!1,forceRequiredForStaleLock=!0,waitMs,options={}){const maxWaitMs=parseNonNegativeIntegerWaitMs(options.maxWaitMs),lockOverride=await runActiveServiceOverride("lock_acquire",{pm_root:pmRoot,id,ttl_seconds:ttlSeconds,owner,force,force_required_for_stale_lock:forceRequiredForStaleLock,...maxWaitMs===void 0?{}:{max_wait_ms:maxWaitMs}});if(lockOverride.handled){const release=resolveLockOverrideRelease(lockOverride.result);if(release)return{release:async()=>{await Promise.resolve(release()),await runActiveServiceOverride("lock_release",{pm_root:pmRoot,id,owner})},fence:commit=>commit()}}const lockPath=getLockPath(pmRoot,id),waitBudgetMs=cappedLockWaitMs(waitMs,maxWaitMs),totalCeilingMs=resolveLockWaitCeilingMs(waitBudgetMs,maxWaitMs,options.waitPolicy),waitTracker=createLockWaitTracker(waitBudgetMs,totalCeilingMs),startedAtMs=waitTracker.startedAtMs;let staleRemovals=0,backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;const token=randomUUID();for(;;)try{const acquiredAt=await createLockFile(pmRoot,lockPath,id,owner,ttlSeconds,token,options.createParentDirectories!==!1),lease={owner,token,acquiredAt,ttlSeconds};return{release:async()=>{await releaseOwnedLock(lockPath,id,owner,token),await runActiveServiceOverride("lock_release",{pm_root:pmRoot,id,owner})},fence:commit=>fenceOwnedLock(lockPath,id,lease,commit)}}catch(error){await assertLockCreateContention(error,pmRoot,lockPath,id);let lockInfo=await readLockInfo(lockPath);if(await isReclaimableLock(lockInfo.info,ttlSeconds)){const staleRemoval=await removeConfirmedStaleLock({lockPath,id,ttlSeconds,force,forceRequiredForStaleLock,staleRemovals,waitBudgetMs,startedAtMs,fallbackLockInfo:lockInfo});if(lockInfo=staleRemoval.lockInfo,staleRemoval.staleRemovalCounted&&(staleRemovals+=1),staleRemoval.shouldRetryCreate)continue}const observation=waitTracker.observe(lockInfo.info);if(observation.exhausted)throw await buildLockConflictError(id,lockInfo.info,waitBudgetMs===0?0:observation.elapsedMs,observation.ownerHandoffs);await sleepWithJitter(Math.min(backoffMs,observation.remainingMs)),backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}export{_testOnly,acquireLock,acquireLockLease,acquireStaleCleanupGate,captureProcessIdentity2 as captureProcessIdentity,hasUnexpiredLockOwner,isProcessIdentityAlive2 as isProcessIdentityAlive,readProcessStartIdentity2 as readProcessStartIdentity,recordDeadLockRecovery,waitForStaleCleanupGate};
4
+ `,{encoding:"utf8",flag:"wx",mode:384})}async function removeConfirmedStaleLock(params){const releaseCleanupGate=await acquireStaleCleanupGate(params.lockPath,params.id);if(releaseCleanupGate===null)return{lockInfo:params.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{const currentLockInfo=await readLockInfo(params.lockPath);if(currentLockInfo.info===null&&currentLockInfo.warnings.length===0)return{lockInfo:currentLockInfo,shouldRetryCreate:!0,staleRemovalCounted:!1};const ownerDead=await isConfirmedDeadLock(currentLockInfo.info);if(!isStaleLock(currentLockInfo.info,params.ttlSeconds)&&!ownerDead)return{lockInfo:currentLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};if(await throwIfStaleLockNeedsForce(params.id,params.lockPath,currentLockInfo,params.force||ownerDead,params.forceRequiredForStaleLock),params.staleRemovals>=MAX_STALE_LOCK_REMOVALS)throw await buildLockConflictError(params.id,currentLockInfo.info,performance.now()-params.startedAtMs);return ownerDead&&await recordDeadLockRecovery(params.lockPath,JSON.stringify(currentLockInfo.info)),{lockInfo:currentLockInfo,shouldRetryCreate:await unlinkLockWithHook(params.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await releaseCleanupGate()}}async function assertLockCreateContention(error,pmRoot,lockPath,id){if(error instanceof PmCliError&&error.code===LOCK_PATH_UNSAFE_CODE)throw error;if(!await isLockCreateContention(error,lockPath))throw new PmCliError(`Failed to acquire lock for ${id}: ${toErrorMessage(error)}`,EXIT_CODE.GENERIC_FAILURE);await assertLockEntryNotSymlink(pmRoot,lockPath,id)}const _testOnly={parseLockInfo,readLockInfo,isErrno,isLockCreateContention,buildLockPayload,isStaleLock,lockOwnerSuffix,resolveLockWaitMs,lockGenerationKey,parseLinuxProcessStartIdentity,readProcessStartIdentity,acquireStaleCleanupGate,removeConfirmedStaleLock};async function acquireLock(pmRoot,id,ttlSeconds,owner,force=!1,forceRequiredForStaleLock=!0,waitMs,options={}){return(await acquireLockLease(pmRoot,id,ttlSeconds,owner,force,forceRequiredForStaleLock,waitMs,options)).release}async function acquireLockLease(pmRoot,id,ttlSeconds,owner,force=!1,forceRequiredForStaleLock=!0,waitMs,options={}){const maxWaitMs=parseNonNegativeIntegerWaitMs(options.maxWaitMs),lockOverride=await runActiveServiceOverride("lock_acquire",{pm_root:pmRoot,id,ttl_seconds:ttlSeconds,owner,force,force_required_for_stale_lock:forceRequiredForStaleLock,...maxWaitMs===void 0?{}:{max_wait_ms:maxWaitMs}});if(lockOverride.handled){const release=resolveLockOverrideRelease(lockOverride.result);if(release)return{release:async()=>{await Promise.resolve(release()),await runActiveServiceOverride("lock_release",{pm_root:pmRoot,id,owner})},fence:commit=>commit()}}const lockPath=getLockPath(pmRoot,id),waitBudgetMs=cappedLockWaitMs(waitMs,maxWaitMs),totalCeilingMs=resolveLockWaitCeilingMs(waitBudgetMs,maxWaitMs,options.waitPolicy),waitTracker=createLockWaitTracker(waitBudgetMs,totalCeilingMs),startedAtMs=waitTracker.startedAtMs;let staleRemovals=0,backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;const token=randomUUID();for(;;)try{const acquiredAt=await createLockFile(pmRoot,lockPath,id,owner,ttlSeconds,token,options.createParentDirectories!==!1),lease={owner,token,acquiredAt,ttlSeconds};return{release:async()=>{await releaseOwnedLock(lockPath,id,owner,token),await runActiveServiceOverride("lock_release",{pm_root:pmRoot,id,owner})},fence:commit=>fenceOwnedLock(lockPath,id,lease,commit)}}catch(error){await assertLockCreateContention(error,pmRoot,lockPath,id);let lockInfo=await readLockInfo(lockPath);if(await isReclaimableLock(lockInfo.info,ttlSeconds)){const staleRemoval=await removeConfirmedStaleLock({lockPath,id,ttlSeconds,force,forceRequiredForStaleLock,staleRemovals,waitBudgetMs,startedAtMs,fallbackLockInfo:lockInfo});if(lockInfo=staleRemoval.lockInfo,staleRemoval.staleRemovalCounted&&(staleRemovals+=1),staleRemoval.shouldRetryCreate)continue}const observation=waitTracker.observe(lockInfo.info);if(observation.exhausted)throw await buildLockConflictError(id,lockInfo.info,waitBudgetMs===0?0:observation.elapsedMs,observation.ownerHandoffs);await sleepWithJitter(Math.min(backoffMs,observation.remainingMs)),backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}export{_testOnly,acquireLock,acquireLockLease,acquireStaleCleanupGate,captureProcessIdentity2 as captureProcessIdentity,hasUnexpiredLockOwner,isProcessIdentityAlive2 as isProcessIdentityAlive,readProcessStartIdentity2 as readProcessStartIdentity,recordDeadLockRecovery,waitForStaleCleanupGate};
5
5
  //# sourceMappingURL=lock.js.map
@@ -0,0 +1,6 @@
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1f8bc22d-02b9-522a-a2cd-0d34bf6e3ec3")}catch{}})();import{stripVTControlCharacters}from"node:util";const QUIET_LINKED_TEST_STREAM_TAIL_LINES=6,QUIET_LINKED_TEST_STREAM_TAIL_CHARS=480,LINKED_TEST_FULL_OUTPUT_FLAG="--full-output",LINKED_TEST_STREAM_KEYS=["stdout","stderr"];function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function projectLinkedTestReply(command,value,options){if(command==="test"){const omitted=new Set;return withStreamOmissionReceipt(projectLinkedTestRun(value,options,omitted),omitted,"run_results")}return command==="test-all"?projectLinkedTestBatch(value,options):value}function projectLinkedTestBatch(value,options){if(!isPlainObject(value)||!Array.isArray(value.results)||!value.results.every(isPlainObject))return value;const omitted=new Set,results=value.results.map(entry=>projectLinkedTestRun(entry,options,omitted)),shared=resolveSharedExecutionContext(results.filter(entry=>Array.isArray(entry.run_results)&&entry.run_results.length>0)),projected={...value,...shared===void 0?{}:{execution_context:shared},results:shared===void 0?results:results.map(entry=>{const{execution_context:_hoisted,...rest}=entry;return rest})};return withStreamOmissionReceipt(projected,omitted,"results.run_results")}function projectLinkedTestRun(value,options,omitted){if(!isPlainObject(value)||!Array.isArray(value.run_results))return value;const sourceRows=value.run_results;if(!sourceRows.every(isPlainObject))return value;const quiet=isQuietLinkedTestSuccess(value,sourceRows),reduceContext=quiet&&!options.fullContext,rows=quiet?sourceRows.map(row=>reduceQuietRow(row,options,omitted)):sourceRows,sharedContext=resolveSharedExecutionContext(rows),runResults=sharedContext===void 0?rows:rows.map(row=>withoutHoistedContext(row,options,omitted)),{failure_categories:_zeroCategories,...withoutCategories}=value;return{...options.lean&&reduceContext?withoutCategories:value,...sharedContext===void 0?{}:{execution_context:sharedContext},run_results:runResults}}function reduceQuietRow(row,options,omitted){const bounded=options.fullOutput?row:boundQuietRowStreams(row,omitted);return options.fullContext?bounded:{...bounded,execution_context:projectLinkedTestDecisionContext(bounded.execution_context)}}function withoutHoistedContext(row,options,omitted){const{execution_context:_executionContext,stdout,stderr,...rest}=row;if(!options.lean||options.fullOutput||row.status!=="passed"||keepsDiagnosticStreams(row))return{...rest,stdout,stderr};const{stdout_omitted_bytes:_stdoutBytes,stderr_omitted_bytes:_stderrBytes,...delivered}=rest;for(const[key,stream]of[["stdout",stdout],["stderr",stderr]])typeof stream=="string"&&stream.length>0&&omitted.add(key);return delivered}function resolveSharedExecutionContext(rows){const contexts=rows.map(row=>row.execution_context).filter(context=>context!==void 0);if(contexts.length!==rows.length||contexts.length===0)return;const first=JSON.stringify(contexts[0]);return contexts.every(context=>JSON.stringify(context)===first)?contexts[0]:void 0}function isQuietLinkedTestSuccess(value,rows){if(value.ok!==!0||rows.length===0)return!1;const quietRow=row=>row.status==="passed"&&isPlainObject(row.execution_context)&&row.execution_context.mismatch_detected===!1;if(!rows.every(quietRow))return!1;const categories=value.failure_categories;return!(isPlainObject(categories)&&Object.values(categories).some(count=>count!==0))}function projectLinkedTestDecisionContext(context){const trust=isPlainObject(context.trust)?context.trust:{};return{pm_context_mode:context.pm_context_mode,workspace_context_mode:context.workspace_context_mode,mismatch_detected:!1,...typeof trust.trusted=="boolean"?{trusted:trust.trusted}:{},...trust.reason===void 0?{}:{trust_reason:trust.reason},restore_with:"not retained; a run with --check-context reports the full context"}}function keepsDiagnosticStreams(row){return isUntrustedRow(row)||isPlainObject(row.execution_context)&&row.execution_context.mismatch_detected===!0}function isUntrustedRow(row){const context=row.execution_context;return isPlainObject(context)?context.trusted===!1||isPlainObject(context.trust)&&context.trust.trusted===!1:!1}function boundQuietRowStreams(row,omitted){if(isUntrustedRow(row))return row;let projected=row;for(const key of LINKED_TEST_STREAM_KEYS){const stream=row[key];if(typeof stream!="string")continue;const tail=quietStreamTail(stream);tail!==stream&&(omitted.add(key),projected={...projected,[key]:tail,[`${key}_omitted_bytes`]:Buffer.byteLength(stream,"utf8")-Buffer.byteLength(tail,"utf8")})}return projected}function quietStreamTail(stream){if(stream.trim().length===0)return stream.length<=2?stream:"";const lines=stripVTControlCharacters(stream).split(`
2
+ `).map(line=>line.replace(/\r+$/u,"").split("\r").at(-1).trimEnd()).filter(line=>line.trim().length>0).slice(-QUIET_LINKED_TEST_STREAM_TAIL_LINES),tail=Array.from(lines.join(`
3
+ `)).slice(-QUIET_LINKED_TEST_STREAM_TAIL_CHARS).join("");return stream.endsWith(`
4
+ `)&&tail.length>0?`${tail}
5
+ `:tail}function withStreamOmissionReceipt(value,omitted,rowPath){if(omitted.size===0||!isPlainObject(value))return value;const receipt=isPlainObject(value.omission_receipt)?value.omission_receipt:{},groups=[...Array.isArray(receipt.omitted_field_groups)?receipt.omitted_field_groups:[],...LINKED_TEST_STREAM_KEYS.filter(key=>omitted.has(key)).map(key=>({name:`${rowPath}.${key}`,restore_with:LINKED_TEST_FULL_OUTPUT_FLAG}))];return{...value,omission_receipt:{...receipt,has_omissions:!0,omitted_field_group_count:groups.length,omitted_field_groups:groups}}}export{LINKED_TEST_FULL_OUTPUT_FLAG,QUIET_LINKED_TEST_STREAM_TAIL_CHARS,QUIET_LINKED_TEST_STREAM_TAIL_LINES,projectLinkedTestReply,quietStreamTail};
6
+ //# sourceMappingURL=linked-test-projection.js.map
@@ -71,6 +71,13 @@ preserveEmptyItemCollections?:boolean;
71
71
  positionalRowPaths?:readonly string[];}
72
72
  /** Resolve command ownership and suppression before projecting and rendering the result. */
73
73
  export declare function formatOutput(result:unknown,options:OutputOptions):string;
74
+ /**
75
+ * The mutation-receipt projection `printResult` applies before command-result
76
+ * overrides, services and rendering run: `--id-only`, `--full-changed-fields`,
77
+ * `--no-changed-fields`, or the compact envelope by default. Shared with the
78
+ * extension test harness so its read-output admission judges the same value.
79
+ */
80
+ export declare function projectPrintedResult(result:unknown,options:Pick<OutputOptions,"idOnly"|"fullChangedFields"|"noChangedFields">):unknown;
74
81
  /** Apply declared exit codes and mutation projection before writing a nonquiet result. */
75
82
  export declare function printResult(result:unknown,options:OutputOptions):void;
76
83
  /** Apply the error service override and emit one newline-terminated diagnostic. */
@@ -1,20 +1,22 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a378018f-b981-5e5e-98a4-45d190039473")}catch{}})();import{getActiveCommandContext,runActiveCommandOverride,runActiveRendererOverride,runActiveServiceOverrideSync,setActiveCommandResult}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{isHostOutputSuppressed}from"./output-control.js";import{projectMutationResult}from"./mutation-projection.js";import{attachReadOutputContracts}from"../../sdk/context-intent-contracts.js";import{attachOutputTokenAccounting}from"../../sdk/output-token-accounting.js";import{propagateContextUsageServingReceipt}from"../../sdk/context-usage.js";import{isReadResultOmittedForBudget,resolveReadOutputEncoding,resolveReadOutputSurface}from"../../sdk/read-output-contracts.js";import{readOutputPositionalRowPaths}from"../../sdk/read-output/positional-rows.js";import{GET_FACET_ROOTS}from"../../sdk/query/get-facet-roots.js";import{withDeliveredOutputRenderer}from"../../sdk/read-output-budget.js";import{encode as encodeToon}from"@toon-format/toon";import{encodePmTableRows}from"../../sdk/output/table-rows.js";import{projectPmBriefListEnvelope,projectPmBriefSearchEnvelope}from"../../sdk/output/list-envelope.js";import{prepareWellFormedOutputText}from"../shared/output-unicode.js";const DECLARED_PROCESS_EXIT_CODES=new Set(Object.values(EXIT_CODE)),COLLECTION_COUNT_ALIASES=new Map([["notes_count","notes"],["tests_count","tests"]]),NATIVE_OUTPUT_MARKER="__pm_native_output";let streamErrorHandlersInstalled=!1;function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function setActiveCommandResultOmitted(source){const omitted={read_output:{result_omitted:!0}};propagateContextUsageServingReceipt(source,omitted),setActiveCommandResult(omitted)}function setActiveCommandDeliveryResult(result,receiptSource,structuredDeliveryPreserved){if(structuredDeliveryPreserved){setActiveCommandResult(result);return}setActiveCommandResultOmitted(receiptSource)}function stripNativeOutputMarker(result){if(!isPlainObject(result)||result[NATIVE_OUTPUT_MARKER]!==!0)return result;const{[NATIVE_OUTPUT_MARKER]:_marker,...rest}=result;return rest}function isBrokenPipeError(error){return typeof error=="object"&&error!==null&&error.code==="EPIPE"}function markStdoutBrokenPipeExitCode(){(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=EXIT_CODE.SUCCESS)}function markStderrBrokenPipeExitCode(){(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE)}function markBrokenPipeExitCode(target){if(target==="stdout"){markStdoutBrokenPipeExitCode();return}markStderrBrokenPipeExitCode()}function handleUnhandledStreamError(error){const unhandled=error instanceof Error?error:new Error(String(error));setImmediate(()=>{throw unhandled})}function installStreamErrorHandlers(){streamErrorHandlersInstalled||(streamErrorHandlersInstalled=!0,process.stdout.on("error",error=>{if(isBrokenPipeError(error)){markBrokenPipeExitCode("stdout");return}handleUnhandledStreamError(error)}),process.stderr.on("error",error=>{if(isBrokenPipeError(error)){markBrokenPipeExitCode("stderr");return}handleUnhandledStreamError(error)}))}function writeToStream(target,text){installStreamErrorHandlers();try{return target==="stdout"?process.stdout.write(text):process.stderr.write(text),!0}catch(error){if(isBrokenPipeError(error))return markBrokenPipeExitCode(target),!1;throw error}}function writeStdout(text){return writeToStream("stdout",text)}function writeStderr(text){return writeToStream("stderr",text)}function renderScalar(value){return typeof value=="string"?JSON.stringify(value):typeof value=="number"||typeof value=="boolean"?String(value):value===null?"null":JSON.stringify(value)}function indentToon(encoded,depth){const indent=" ".repeat(depth);return encoded.split(`
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f33393ac-6b72-5e46-92a5-f276d1fbfff1")}catch{}})();import{getActiveCommandContext,runActiveCommandOverride,runActiveRendererOverride,runActiveServiceOverrideSync,setActiveCommandResult}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{isHostOutputSuppressed}from"./output-control.js";import{projectMutationResult}from"./mutation-projection.js";import{projectLinkedTestReply}from"./linked-test-projection.js";import{attachReadOutputContracts}from"../../sdk/context-intent-contracts.js";import{attachOutputTokenAccounting}from"../../sdk/output-token-accounting.js";import{propagateContextUsageServingReceipt}from"../../sdk/context-usage.js";import{isReadResultOmittedForBudget,resolveReadOutputEncoding,resolveReadOutputSurface}from"../../sdk/read-output-contracts.js";import{readOutputPositionalRowPaths}from"../../sdk/read-output/positional-rows.js";import{GET_FACET_ROOTS}from"../../sdk/query/get-facet-roots.js";import{withDeliveredOutputRenderer}from"../../sdk/read-output-budget.js";import{encode as encodeToon}from"@toon-format/toon";import{encodePmTableRows,projectPmTableEncodingForToon}from"../../sdk/output/table-rows.js";import{projectPmBriefListEnvelope,projectPmBriefSearchEnvelope}from"../../sdk/output/list-envelope.js";import{prepareWellFormedOutputText}from"../shared/output-unicode.js";const DECLARED_PROCESS_EXIT_CODES=new Set(Object.values(EXIT_CODE)),COLLECTION_COUNT_ALIASES=new Map([["notes_count","notes"],["tests_count","tests"]]),NATIVE_OUTPUT_MARKER="__pm_native_output";let streamErrorHandlersInstalled=!1;function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function setActiveCommandResultOmitted(source){const omitted={read_output:{result_omitted:!0}};propagateContextUsageServingReceipt(source,omitted),setActiveCommandResult(omitted)}function setActiveCommandDeliveryResult(result,receiptSource,structuredDeliveryPreserved){if(structuredDeliveryPreserved){setActiveCommandResult(result);return}setActiveCommandResultOmitted(receiptSource)}function stripNativeOutputMarker(result){if(!isPlainObject(result)||result[NATIVE_OUTPUT_MARKER]!==!0)return result;const{[NATIVE_OUTPUT_MARKER]:_marker,...rest}=result;return rest}function isBrokenPipeError(error){return typeof error=="object"&&error!==null&&error.code==="EPIPE"}function markStdoutBrokenPipeExitCode(){(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=EXIT_CODE.SUCCESS)}function markStderrBrokenPipeExitCode(){(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE)}function markBrokenPipeExitCode(target){if(target==="stdout"){markStdoutBrokenPipeExitCode();return}markStderrBrokenPipeExitCode()}function handleUnhandledStreamError(error){const unhandled=error instanceof Error?error:new Error(String(error));setImmediate(()=>{throw unhandled})}function installStreamErrorHandlers(){streamErrorHandlersInstalled||(streamErrorHandlersInstalled=!0,process.stdout.on("error",error=>{if(isBrokenPipeError(error)){markBrokenPipeExitCode("stdout");return}handleUnhandledStreamError(error)}),process.stderr.on("error",error=>{if(isBrokenPipeError(error)){markBrokenPipeExitCode("stderr");return}handleUnhandledStreamError(error)}))}function writeToStream(target,text){installStreamErrorHandlers();try{return target==="stdout"?process.stdout.write(text):process.stderr.write(text),!0}catch(error){if(isBrokenPipeError(error))return markBrokenPipeExitCode(target),!1;throw error}}function writeStdout(text){return writeToStream("stdout",text)}function writeStderr(text){return writeToStream("stderr",text)}function renderScalar(value){return typeof value=="string"?JSON.stringify(value):typeof value=="number"||typeof value=="boolean"?String(value):value===null?"null":JSON.stringify(value)}function indentToon(encoded,depth){const indent=" ".repeat(depth);return encoded.split(`
2
2
  `).map(line=>`${indent}${line}`).join(`
3
- `)}function isNestedTableCandidateBounded(rows){const columns=new Set;let presentCells=0;for(const row of rows){const keys=Object.keys(row);presentCells+=keys.length;for(const key of keys)columns.add(key)}return rows.length*columns.size<=presentCells*2}function renderToonObjectEntry(key,entry,depth,allowNestedTable){const indent=" ".repeat(depth);if(!isPlainObject(entry)&&!Array.isArray(entry))return`${indent}${key}: ${renderScalar(entry)}`;if(key==="omission_receipt"&&isCompleteOmissionReceipt(entry))return`${indent}${key}: complete`;if(Array.isArray(entry)){if(entry.length===0)return`${indent}${key}: []`;const expanded=indentToon(encodeToon({[key]:entry}),depth);return allowNestedTable&&entry.length>=1&&entry.every(isPlainObject)&&isNestedTableCandidateBounded(entry)?[!1,!0].map(compact=>{const table=encodePmTableRows(entry,{compact});return indentToon(encodeToon({[key]:table.rows,[`${key}_encoding`]:table.encoding}),depth)}).reduce((smallest,candidate)=>Buffer.byteLength(candidate)<Buffer.byteLength(smallest)?candidate:smallest,expanded):expanded}return isPlainObject(entry)&&Object.keys(entry).length===0?`${indent}${key}: {}`:`${indent}${key}:
4
- ${renderToonValue(entry,depth+1)}`}function compactToonArray(values,policy,preserveEmpty){const compactedEntries=values.map(entry=>compactToonValue(entry,policy,preserveEmpty||policy.preserveRowFacts&&isPlainObject(entry))).filter(entry=>entry!==void 0);return compactedEntries.length>0||preserveEmpty?compactedEntries:void 0}function compactToonValue(value,policy={omitDuplicateCountAliases:!0,preserveRowFacts:!0},preserveEmpty=!1){if(value===null)return preserveEmpty?null:void 0;if(Array.isArray(value))return compactToonArray(value,policy,preserveEmpty);if(isPlainObject(value)){const compacted=[],entries=Object.entries(value).filter(([key,entry])=>{const canonicalCount=COLLECTION_COUNT_ALIASES.get(key);return!policy.omitDuplicateCountAliases||canonicalCount===void 0||!isPlainObject(value.collection_counts)||entry!==value.collection_counts[canonicalCount]});for(const[key,entry]of entries){if(key==="omitted_field_groups"&&Array.isArray(entry)&&entry.length===0){compacted.push([key,[]]);continue}const compactedEntry=compactToonValue(entry,policy,preserveEmpty);compactedEntry!==void 0&&compacted.push([key,compactedEntry])}return compacted.length>0||preserveEmpty?Object.fromEntries(compacted):void 0}return value}function renderToonValue(value,depth){const indent=" ".repeat(depth);if(Array.isArray(value))return value.length===0?"[]":indentToon(encodeToon(value),depth);if(isPlainObject(value)){const entries=Object.entries(value);return entries.length===0?"{}":entries.map(([key,entry])=>renderToonObjectEntry(key,entry,depth,!Object.hasOwn(value,`${key}_encoding`)&&!(key==="checks"&&isPlainObject(value.verdict)&&value.verdict.authority==="ok"))).join(`
3
+ `)}function isNestedTableCandidateBounded(rows){const columns=new Set;let presentCells=0;for(const row of rows){const keys=Object.keys(row);presentCells+=keys.length;for(const key of keys)columns.add(key)}return rows.length*columns.size<=presentCells*2}function renderToonObjectEntry(key,entry,depth,allowNestedTable){const indent=" ".repeat(depth);if(!isPlainObject(entry)&&!Array.isArray(entry))return`${indent}${key}: ${renderScalar(entry)}`;const receipt=key==="omission_receipt"?renderToonOmissionReceipt(entry,depth):void 0;if(receipt!==void 0)return receipt;if(Array.isArray(entry)){if(entry.length===0)return`${indent}${key}: []`;const expanded=indentToon(encodeToon({[key]:entry}),depth);return allowNestedTable&&entry.length>=1&&entry.every(isPlainObject)&&isNestedTableCandidateBounded(entry)?[!1,!0].map(compact=>{const table=encodePmTableRows(entry,{compact});return indentToon(encodeToon({[key]:table.rows,[`${key}_encoding`]:projectPmTableEncodingForToon(table.encoding)}),depth)}).reduce((smallest,candidate)=>Buffer.byteLength(candidate)<Buffer.byteLength(smallest)?candidate:smallest,expanded):expanded}return isPlainObject(entry)&&Object.keys(entry).length===0?`${indent}${key}: {}`:`${indent}${key}:
4
+ ${renderToonValue(entry,depth+1)}`}function renderToonOmissionReceipt(entry,depth){const indent=" ".repeat(depth);if(isCompleteOmissionReceipt(entry))return`${indent}omission_receipt: complete`;const named=isPlainObject(entry)?projectDerivableOmissionReceipt(entry):void 0;if(named===void 0)return;const rowsText=`${indent}omission_receipt:
5
+ ${renderToonValue(entry,depth+1)}`,namedText=`${indent}omission_receipt:
6
+ ${renderToonValue(named,depth+1)}`;return Buffer.byteLength(namedText)<Buffer.byteLength(rowsText)?namedText:rowsText}function projectDerivableOmissionReceipt(receipt){const groups=receipt.omitted_field_groups;if(!Array.isArray(groups)||groups.length===0||Object.hasOwn(receipt,"restore_with"))return;const names=[];let prefix;for(const group of groups){if(!isPlainObject(group)||Object.keys(group).length!==2)return;const{name,restore_with:restoreWith}=group;if(typeof name!="string"||name.length===0||typeof restoreWith!="string"||!restoreWith.endsWith(name))return;const groupPrefix=restoreWith.slice(0,restoreWith.length-name.length);if(prefix!==void 0&&groupPrefix!==prefix)return;prefix=groupPrefix,names.push(name)}return Object.fromEntries(Object.entries(receipt).flatMap(([key,value])=>key==="omitted_field_groups"?[[key,names],["restore_with",`${prefix}<name>`]]:[[key,value]]))}function compactToonArray(values,policy,preserveEmpty){const compactedEntries=values.map(entry=>compactToonValue(entry,policy,preserveEmpty||policy.preserveRowFacts&&isPlainObject(entry))).filter(entry=>entry!==void 0);return compactedEntries.length>0||preserveEmpty?compactedEntries:void 0}function compactToonValue(value,policy={omitDuplicateCountAliases:!0,preserveRowFacts:!0},preserveEmpty=!1){if(value===null)return preserveEmpty?null:void 0;if(Array.isArray(value))return compactToonArray(value,policy,preserveEmpty);if(isPlainObject(value)){const compacted=[],entries=Object.entries(value).filter(([key,entry])=>{const canonicalCount=COLLECTION_COUNT_ALIASES.get(key);return!policy.omitDuplicateCountAliases||canonicalCount===void 0||!isPlainObject(value.collection_counts)||entry!==value.collection_counts[canonicalCount]});for(const[key,entry]of entries){if(key==="omitted_field_groups"&&Array.isArray(entry)&&entry.length===0){compacted.push([key,[]]);continue}const compactedEntry=compactToonValue(entry,policy,preserveEmpty);compactedEntry!==void 0&&compacted.push([key,compactedEntry])}return compacted.length>0||preserveEmpty?Object.fromEntries(compacted):void 0}return value}function renderToonValue(value,depth){const indent=" ".repeat(depth);if(Array.isArray(value))return value.length===0?"[]":indentToon(encodeToon(value),depth);if(isPlainObject(value)){const entries=Object.entries(value);return entries.length===0?"{}":entries.map(([key,entry])=>renderToonObjectEntry(key,entry,depth,!Object.hasOwn(value,`${key}_encoding`)&&!(key==="checks"&&isPlainObject(value.verdict)&&value.verdict.authority==="ok"))).join(`
5
7
  `)}return`${indent}${renderScalar(value)}`}function renderDefaultMarkdownResult(value){if(!isPlainObject(value)||value.output_default!=="markdown"||typeof value.view!="string"||!Array.isArray(value.events)||!Array.isArray(value.days))return null;const lines=[`# pm calendar (${value.view})`,""],summary=isPlainObject(value.summary)?value.summary:{};if(lines.push(`- events: ${String(summary.events??0)}`),lines.push(""),value.events.length===0)return lines.push("No calendar events matched the selected filters."),`${lines.join(`
6
8
  `)}
7
9
  `;for(const event of value.events){if(!isPlainObject(event))continue;const kind=typeof event.kind=="string"?event.kind:"event",title=typeof event.item_title=="string"?event.item_title:"",itemId=typeof event.item_id=="string"?event.item_id:"",reminderText=typeof event.reminder_text=="string"&&event.reminder_text.length>0?` ${event.reminder_text}`:"";lines.push(`- [${kind}] ${itemId} ${title}${reminderText}`.trim())}return`${lines.join(`
8
10
  `)}
9
- `}const LEAN_READ_ENVELOPE_ECHO_KEYS=new Set(["filters","now","projection","sorting"]);function projectLeanJsonValue(value){const compacted=compactToonValue(value,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!isPlainObject(compacted)||!Array.isArray(compacted.items))return compacted??null;const projected=Object.fromEntries(Object.entries(compacted).filter(([key])=>!LEAN_READ_ENVELOPE_ECHO_KEYS.has(key)));return projected.has_more!==!0&&delete projected.next_cursor,projected}function projectLinkedTestEvidence(value,lean){if(!isPlainObject(value)||!Array.isArray(value.run_results)||!value.run_results.every(isPlainObject))return value;const rows=value.run_results,sharedContext=resolveSharedExecutionContext(rows),runResults=rows.map(row=>{const{execution_context:_executionContext,stdout,stderr,...rest}=row;return sharedContext===void 0?row:!lean||row.status!=="passed"?{...rest,stdout,stderr}:rest});return lean&&isQuietLinkedTestSuccess(value,sharedContext,rows)?projectQuietLinkedTestSuccess(value,sharedContext,runResults):{...value,...sharedContext===void 0?{}:{execution_context:sharedContext},run_results:runResults}}function resolveSharedExecutionContext(rows){const contexts=rows.map(row=>row.execution_context).filter(context=>context!==void 0);if(contexts.length!==rows.length||contexts.length===0)return;const first=JSON.stringify(contexts[0]);return contexts.every(context=>JSON.stringify(context)===first)?contexts[0]:void 0}function isQuietLinkedTestSuccess(value,sharedContext,rows){if(value.ok!==!0||!isPlainObject(sharedContext)||sharedContext.mismatch_detected!==!1||!rows.every(row=>row.status==="passed"))return!1;const categories=value.failure_categories;return!(isPlainObject(categories)&&Object.values(categories).some(count=>count!==0))}function projectQuietLinkedTestSuccess(value,context,runResults){const{failure_categories:_zeroCategories,...rest}=value,trust=isPlainObject(context.trust)?context.trust:{};return{...rest,execution_context:{pm_context_mode:context.pm_context_mode,workspace_context_mode:context.workspace_context_mode,mismatch_detected:!1,...typeof trust.trusted=="boolean"?{trusted:trust.trusted}:{},...trust.reason===void 0?{}:{trust_reason:trust.reason},restore_with:"not retained; a run without --lean reports the full context"},run_results:runResults}}function projectEmptyCheckDetails(value){return!isPlainObject(value)||value.ok!==!0||!isPlainObject(value.verdict)||value.verdict.authority!=="ok"||!Array.isArray(value.checks)?value:{...value,checks:value.checks.map(omitEmptySuccessfulCheckDetails)}}function omitEmptySuccessfulCheckDetails(check){if(!isPlainObject(check)||check.ok!==!0||!isPlainObject(check.details)||Object.keys(check.details).length!==0)return check;const{details:_details,...rest}=check;return rest}function formatBuiltInOutput(result,format,lean=!1,toon={}){if(result=prepareWellFormedOutputText(result),format==="json"){const value=lean?projectLeanJsonValue(result):result,briefList=isPlainObject(result)&&isPlainObject(result.projection)&&result.projection.mode==="brief"&&Array.isArray(result.items);return`${JSON.stringify(value,null,briefList?void 0:2)}
11
+ `}const LEAN_READ_ENVELOPE_ECHO_KEYS=new Set(["filters","now","projection","sorting"]);function projectLeanJsonValue(value){const compacted=compactToonValue(value,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!isPlainObject(compacted)||!Array.isArray(compacted.items))return compacted??null;const projected=Object.fromEntries(Object.entries(compacted).filter(([key])=>!LEAN_READ_ENVELOPE_ECHO_KEYS.has(key)));return projected.has_more!==!0&&delete projected.next_cursor,projected}function projectEmptyCheckDetails(value){return!isPlainObject(value)||value.ok!==!0||!isPlainObject(value.verdict)||value.verdict.authority!=="ok"||!Array.isArray(value.checks)?value:{...value,checks:value.checks.map(omitEmptySuccessfulCheckDetails)}}function omitEmptySuccessfulCheckDetails(check){if(!isPlainObject(check)||check.ok!==!0||!isPlainObject(check.details)||Object.keys(check.details).length!==0)return check;const{details:_details,...rest}=check;return rest}function formatBuiltInOutput(result,format,lean=!1,toon={}){if(result=prepareWellFormedOutputText(result),format==="json"){const value=lean?projectLeanJsonValue(result):result,briefList=isPlainObject(result)&&isPlainObject(result.projection)&&result.projection.mode==="brief"&&Array.isArray(result.items);return`${JSON.stringify(value,null,briefList?void 0:2)}
10
12
  `}const compactedToon=restorePositionalRows(result,restoreRequestedEmptyCollections(result,compactToonValue(projectEmptyCheckDetails(projectPmBriefSearchEnvelope(projectPmBriefListEnvelope(result))),TOON_COMPACTION_POLICY),toon.preserveEmptyItemCollections===!0),toon.positionalRowPaths??[]);return compactedToon===void 0?`{}
11
13
  `:`${renderToonValue(compactedToon,0)}
12
14
  `}const TOON_COMPACTION_POLICY={omitDuplicateCountAliases:!0,preserveRowFacts:!0};function restoreEmptyCollections(source,compacted,preserveEmpty=!1){if(Array.isArray(source)){if(source.length===0)return[];const kept2=Array.isArray(compacted)?compacted:[],aligned=kept2.length===source.length;let next=0;const rows=source.flatMap(row=>{const rowPreservesEmpty=preserveEmpty||isPlainObject(row),dropped=!aligned&&compactToonValue(row,TOON_COMPACTION_POLICY,rowPreservesEmpty)===void 0,restored=restoreEmptyCollections(row,dropped?void 0:kept2[next++],rowPreservesEmpty);return restored===void 0?[]:[restored]});return rows.length>0?rows:compacted}if(!isPlainObject(source))return compacted;const kept=isPlainObject(compacted)?compacted:{},entries=Object.entries(source).flatMap(([key,value])=>{const restored=restoreEmptyCollections(value,Object.hasOwn(kept,key)?kept[key]:void 0,preserveEmpty);return restored===void 0?[]:[[key,restored]]});return entries.length>0||Object.keys(source).length===0?Object.fromEntries(entries):compacted}function restoreRequestedEmptyCollections(source,compacted,preserve){if(!preserve||!isPlainObject(source))return compacted;const base=isPlainObject(compacted)?compacted:{},restored=new Map(Object.keys(source).filter(key=>key==="item"||GET_FACET_ROOTS.has(key)).map(key=>[key,restoreEmptyCollections(source[key],base[key])]));return mergeRestoredEntries(source,base,restored)}function mergeRestoredEntries(source,base,restored){const entries=Object.entries(base).map(([key,value])=>[key,restored.has(key)?restored.get(key):value]),sourceKeys=Object.keys(source);for(const[key,value]of restored){if(Object.hasOwn(base,key)||value===void 0)continue;const later=new Set(sourceKeys.slice(sourceKeys.indexOf(key)+1)),position=entries.findIndex(([entryKey])=>later.has(entryKey));entries.splice(position===-1?entries.length:position,0,[key,value])}return Object.fromEntries(entries)}function restorePositionalRows(source,compacted,paths){if(!isPlainObject(source))return compacted;const restorable=paths.filter(path=>{const rows=source[path];return Array.isArray(rows)&&rows.some(row=>compactToonValue(row,TOON_COMPACTION_POLICY,isPlainObject(row))===void 0)});if(restorable.length===0)return compacted;const base=isPlainObject(compacted)?compacted:{},restored=new Map(restorable.map(path=>[path,source[path].map(row=>compactToonValue(row,TOON_COMPACTION_POLICY,!0))]));return mergeRestoredEntries(source,base,restored)}const COMPLETE_OMISSION_RECEIPT=JSON.stringify({has_omissions:!1,omitted_field_group_count:0,omitted_field_groups:[]});function isCompleteOmissionReceipt(value){const entries=Object.entries(Object(value)).sort(([left],[right])=>left.localeCompare(right));return JSON.stringify(Object.fromEntries(entries))===COMPLETE_OMISSION_RECEIPT}function resolveOutputService(effectiveResult,nativeOutput,options,format){const serviceOverride=nativeOutput?{handled:!1,result:effectiveResult,warnings:[]}:runActiveServiceOverrideSync("output_format",{command:options.command,args:options.commandArgs,command_options:options.commandOptions,global:{...options},pm_root:options.pmRoot,format,options:{...options},result:effectiveResult}),legacyPayloadEchoWarning=serviceOverride.warnings.find(warning=>warning.startsWith("extension_output_format_payload_echo_deprecated:"));return legacyPayloadEchoWarning!==void 0&&writeStderr(`Warning: ${legacyPayloadEchoWarning}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
13
15
  `),serviceOverride.handled&&typeof serviceOverride.result=="string"?{result:serviceOverride.result,rendered:serviceOverride.result.endsWith(`
14
16
  `)?serviceOverride.result:`${serviceOverride.result}
15
- `,structuredDeliveryPreserved:!1}:{result:serviceOverride.handled?serviceOverride.result:effectiveResult,rendered:null,structuredDeliveryPreserved:!serviceOverride.handled||isPlainObject(serviceOverride.result)}}function formatEffectiveOutput(effectiveResult,nativeOutput,options,defaultFormat){const activeCommandContext=getActiveCommandContext(),command=options.command??activeCommandContext?.command,commandOptions={...activeCommandContext?.options,...options.commandOptions,...Object.fromEntries([["outputInclude",options.outputInclude],["outputLimit",options.outputLimit],["outputBudget",options.outputBudget],["outputFormat",options.outputFormat],["outputSession",options.outputSession],["outputCursor",options.outputCursor],["outputRowContract",options.outputRowContract]].filter(entry=>entry[1]!==void 0))},format=resolveReadOutputEncoding(command??"",commandOptions)??defaultFormat,resolvedCommandOptions={...commandOptions,resolvedOutputFormat:format},effectiveOptions={...options,command,commandOptions:resolvedCommandOptions},service=resolveOutputService(effectiveResult,nativeOutput,effectiveOptions,format),renderNative=nativeRenderer(format,command,resolvedCommandOptions,options.lean===!0);if(service.rendered!==null)return deliverServiceRendering(service.rendered,{format,renderNative,contract:()=>attachReadOutputContracts(command,resolvedCommandOptions,effectiveResult),effectiveResult,quiet:options.quiet===!0});const outputResult=service.result;propagateContextUsageServingReceipt(effectiveResult,outputResult);const projectedOutputResult=command==="test"?projectLinkedTestEvidence(outputResult,options.lean===!0):outputResult;let nativeFallback=!1;return deliverContractedRead({format,contract:()=>attachReadOutputContracts(command,resolvedCommandOptions,projectedOutputResult),renderDelivered:value=>{if(format==="toon"){const markdownDefault=renderDefaultMarkdownResult(value);if(markdownDefault!==null)return{text:markdownDefault,custom:!1}}const rendererOverride=nativeOutput||nativeFallback||isReadResultOmittedForBudget(value)?{rendered:null}:runActiveRendererOverride(format,value);return rendererOverride.rendered!==null?{text:rendererOverride.rendered.endsWith(`
17
+ `,structuredDeliveryPreserved:!1}:{result:serviceOverride.handled?serviceOverride.result:effectiveResult,rendered:null,structuredDeliveryPreserved:!serviceOverride.handled||isPlainObject(serviceOverride.result)}}function formatEffectiveOutput(effectiveResult,nativeOutput,options,defaultFormat){const activeCommandContext=getActiveCommandContext(),command=options.command??activeCommandContext?.command,commandOptions={...activeCommandContext?.options,...options.commandOptions,...Object.fromEntries([["outputInclude",options.outputInclude],["outputLimit",options.outputLimit],["outputBudget",options.outputBudget],["outputFormat",options.outputFormat],["outputSession",options.outputSession],["outputCursor",options.outputCursor],["outputRowContract",options.outputRowContract]].filter(entry=>entry[1]!==void 0))},format=resolveReadOutputEncoding(command??"",commandOptions)??defaultFormat,resolvedCommandOptions={...commandOptions,resolvedOutputFormat:format},effectiveOptions={...options,command,commandOptions:resolvedCommandOptions},service=resolveOutputService(effectiveResult,nativeOutput,effectiveOptions,format),renderNative=nativeRenderer(format,command,resolvedCommandOptions,options.lean===!0);if(service.rendered!==null)return deliverServiceRendering(service.rendered,{format,renderNative,contract:()=>attachReadOutputContracts(command,resolvedCommandOptions,effectiveResult),effectiveResult,quiet:options.quiet===!0});const outputResult=service.result;propagateContextUsageServingReceipt(effectiveResult,outputResult);const projectedOutputResult=projectLinkedTestReply(command,outputResult,{lean:options.lean===!0,fullContext:commandOptions.checkContext===!0,fullOutput:commandOptions.fullOutput===!0});let nativeFallback=!1;return deliverContractedRead({format,contract:()=>attachReadOutputContracts(command,resolvedCommandOptions,projectedOutputResult),renderDelivered:value=>{if(format==="toon"){const markdownDefault=renderDefaultMarkdownResult(value);if(markdownDefault!==null)return{text:markdownDefault,custom:!1}}const rendererOverride=nativeOutput||nativeFallback||isReadResultOmittedForBudget(value)?{rendered:null}:runActiveRendererOverride(format,value);return rendererOverride.rendered!==null?{text:rendererOverride.rendered.endsWith(`
16
18
  `)?rendererOverride.rendered:`${rendererOverride.rendered}
17
- `,custom:!0}:{text:renderNative(value),custom:!1}},renderNative,useNativeRendering:()=>{nativeFallback=!0},structuredDeliveryPreserved:service.structuredDeliveryPreserved,tokenAccounting:options.tokenAccounting===!0,quiet:options.quiet===!0,effectiveResult})}function nativeRenderer(format,command,commandOptions,lean){if(format==="json")return value=>formatBuiltInOutput(value,"json",lean);const selectedFields=commandOptions.fields,preserveEmptyItemCollections=command==="get"&&typeof selectedFields=="string"&&selectedFields.trim().length>0,positionalRowPaths=readOutputPositionalRowPaths(command===void 0?void 0:resolveReadOutputSurface(command,commandOptions));return value=>formatBuiltInOutput(value,"toon",!1,{preserveEmptyItemCollections,positionalRowPaths})}function deliverServiceRendering(serviceRendered,delivery){const audited=withDeliveredOutputRenderer(delivery.format,value=>isReadResultOmittedForBudget(value)?delivery.renderNative(value):serviceRendered,delivery.contract);return isReadResultOmittedForBudget(audited)?(process.exitCode||=EXIT_CODE.USAGE,setActiveCommandDeliveryResult(audited,delivery.effectiveResult,!delivery.quiet),delivery.renderNative(audited)):(setActiveCommandResultOmitted(delivery.effectiveResult),serviceRendered)}function deliverContractedRead(delivery){let contracted=withDeliveredOutputRenderer(delivery.format,value=>delivery.renderDelivered(value).text,delivery.contract),unaccounted=delivery.renderDelivered(contracted);unaccounted.custom&&receiptsUnderstateDelivery(contracted,unaccounted.text)&&(delivery.useNativeRendering(),contracted=withDeliveredOutputRenderer(delivery.format,delivery.renderNative,delivery.contract),unaccounted={text:delivery.renderNative(contracted),custom:!1}),isReadResultOmittedForBudget(contracted)&&(process.exitCode||=EXIT_CODE.USAGE);let structuredDeliveryPreserved=delivery.structuredDeliveryPreserved&&!unaccounted.custom;if(!delivery.tokenAccounting)return setActiveCommandDeliveryResult(contracted,delivery.effectiveResult,!delivery.quiet&&structuredDeliveryPreserved),unaccounted.text;const renderResolvedOutput=value=>{const delivered=delivery.renderDelivered(value);return delivered.custom&&(structuredDeliveryPreserved=!1),delivered.text},accountedOutputResult=attachOutputTokenAccounting(contracted,renderResolvedOutput),rendered=renderResolvedOutput(accountedOutputResult);return setActiveCommandDeliveryResult(accountedOutputResult,delivery.effectiveResult,!delivery.quiet&&structuredDeliveryPreserved),rendered}const DELIVERED_TOKEN_RECEIPTS=[["read_output","estimated_tokens"],["context_intent","estimated_tokens"],["read_session","spent_this_call_tokens"]];function receiptsUnderstateDelivery(value,text){const deliveredTokens=Math.ceil(Buffer.byteLength(text,"utf8")/4),record=Object(value);return DELIVERED_TOKEN_RECEIPTS.some(([receipt,field])=>{const section=record[receipt],estimate=isPlainObject(section)?section[field]:void 0;return typeof estimate=="number"&&estimate<deliveredTokens})}function formatOutput(result,options){const commandOverride=runActiveCommandOverride(result),suppressedOutput=isHostOutputSuppressed(commandOverride.result)?commandOverride.result:null,nativeResult=commandOverride.result,nativeOutput=isPlainObject(nativeResult)&&nativeResult[NATIVE_OUTPUT_MARKER]===!0,effectiveResult=suppressedOutput?suppressedOutput.result:stripNativeOutputMarker(commandOverride.result);if(setActiveCommandResult(effectiveResult),suppressedOutput)return setActiveCommandResultOmitted(effectiveResult),"";const defaultFormat=options.json===!0||options.json===void 0&&options.defaultOutputFormat==="json"?"json":"toon";return formatEffectiveOutput(effectiveResult,nativeOutput,options,defaultFormat)}function printResult(result,options){isPlainObject(result)&&Number.isInteger(result.exit_code)&&DECLARED_PROCESS_EXIT_CODES.has(Number(result.exit_code))&&(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=Number(result.exit_code));const projected=options.idOnly?projectMutationResult(result,{idOnly:!0}):options.fullChangedFields?result:options.noChangedFields?projectMutationResult(result,{changedFields:"compact"}):projectMutationResult(result,{compactEnvelope:!0}),rendered=formatOutput(projected,options);options.quiet||writeStdout(rendered)}function printError(message){const override=runActiveServiceOverrideSync("error_format",{message}),rendered=override.handled&&typeof override.result=="string"?override.result:message;writeStderr(rendered.endsWith(`
19
+ `,custom:!0}:{text:renderNative(value),custom:!1}},renderNative,useNativeRendering:()=>{nativeFallback=!0},structuredDeliveryPreserved:service.structuredDeliveryPreserved,tokenAccounting:options.tokenAccounting===!0,quiet:options.quiet===!0,effectiveResult})}function nativeRenderer(format,command,commandOptions,lean){if(format==="json")return value=>formatBuiltInOutput(value,"json",lean);const selectedFields=commandOptions.fields,preserveEmptyItemCollections=command==="get"&&typeof selectedFields=="string"&&selectedFields.trim().length>0,positionalRowPaths=readOutputPositionalRowPaths(command===void 0?void 0:resolveReadOutputSurface(command,commandOptions));return value=>formatBuiltInOutput(value,"toon",!1,{preserveEmptyItemCollections,positionalRowPaths})}function deliverServiceRendering(serviceRendered,delivery){const audited=withDeliveredOutputRenderer(delivery.format,value=>isReadResultOmittedForBudget(value)?delivery.renderNative(value):serviceRendered,delivery.contract);return isReadResultOmittedForBudget(audited)?(process.exitCode||=EXIT_CODE.USAGE,setActiveCommandDeliveryResult(audited,delivery.effectiveResult,!delivery.quiet),delivery.renderNative(audited)):(setActiveCommandResultOmitted(delivery.effectiveResult),serviceRendered)}function deliverContractedRead(delivery){let contracted=withDeliveredOutputRenderer(delivery.format,value=>delivery.renderDelivered(value).text,delivery.contract),unaccounted=delivery.renderDelivered(contracted);unaccounted.custom&&receiptsUnderstateDelivery(contracted,unaccounted.text)&&(delivery.useNativeRendering(),contracted=withDeliveredOutputRenderer(delivery.format,delivery.renderNative,delivery.contract),unaccounted={text:delivery.renderNative(contracted),custom:!1}),isReadResultOmittedForBudget(contracted)&&(process.exitCode||=EXIT_CODE.USAGE);let structuredDeliveryPreserved=delivery.structuredDeliveryPreserved&&!unaccounted.custom;if(!delivery.tokenAccounting)return setActiveCommandDeliveryResult(contracted,delivery.effectiveResult,!delivery.quiet&&structuredDeliveryPreserved),unaccounted.text;const renderResolvedOutput=value=>{const delivered=delivery.renderDelivered(value);return delivered.custom&&(structuredDeliveryPreserved=!1),delivered.text},accountedOutputResult=attachOutputTokenAccounting(contracted,renderResolvedOutput),rendered=renderResolvedOutput(accountedOutputResult);return setActiveCommandDeliveryResult(accountedOutputResult,delivery.effectiveResult,!delivery.quiet&&structuredDeliveryPreserved),rendered}const DELIVERED_TOKEN_RECEIPTS=[["read_output","estimated_tokens"],["context_intent","estimated_tokens"],["read_session","spent_this_call_tokens"]];function receiptsUnderstateDelivery(value,text){const deliveredTokens=Math.ceil(Buffer.byteLength(text,"utf8")/4),record=Object(value);return DELIVERED_TOKEN_RECEIPTS.some(([receipt,field])=>{const section=record[receipt],estimate=isPlainObject(section)?section[field]:void 0;return typeof estimate=="number"&&estimate<deliveredTokens})}function formatOutput(result,options){const commandOverride=runActiveCommandOverride(result),suppressedOutput=isHostOutputSuppressed(commandOverride.result)?commandOverride.result:null,nativeResult=commandOverride.result,nativeOutput=isPlainObject(nativeResult)&&nativeResult[NATIVE_OUTPUT_MARKER]===!0,effectiveResult=suppressedOutput?suppressedOutput.result:stripNativeOutputMarker(commandOverride.result);return setActiveCommandResult(effectiveResult),suppressedOutput?(setActiveCommandResultOmitted(effectiveResult),""):formatEffectiveOutput(effectiveResult,nativeOutput,options,resolveDefaultOutputFormat(options))}function resolveDefaultOutputFormat(options){return options.json===!0||options.json===void 0&&options.defaultOutputFormat==="json"?"json":"toon"}function projectPrintedResult(result,options){return options.idOnly?projectMutationResult(result,{idOnly:!0}):options.fullChangedFields?result:options.noChangedFields?projectMutationResult(result,{changedFields:"compact"}):projectMutationResult(result,{compactEnvelope:!0})}function printResult(result,options){isPlainObject(result)&&Number.isInteger(result.exit_code)&&DECLARED_PROCESS_EXIT_CODES.has(Number(result.exit_code))&&(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=Number(result.exit_code));const rendered=formatOutput(projectPrintedResult(result,options),options);options.quiet||writeStdout(rendered)}function printError(message){const override=runActiveServiceOverrideSync("error_format",{message}),rendered=override.handled&&typeof override.result=="string"?override.result:message;writeStderr(rendered.endsWith(`
18
20
  `)?rendered:`${rendered}
19
- `)}const outputTestOnly={compactToonValue,renderToonValue};export{formatBuiltInOutput,formatOutput,outputTestOnly,printError,printResult,writeStderr,writeStdout};
21
+ `)}const outputTestOnly={compactToonValue,renderToonValue};export{formatBuiltInOutput,formatOutput,outputTestOnly,printError,printResult,projectPrintedResult,writeStderr,writeStdout};
20
22
  //# sourceMappingURL=output.js.map
@@ -25,10 +25,14 @@ export declare function runtimeFieldCliFlagRoute(definition:RuntimeFieldDefiniti
25
25
  * `--review.url` keeps the literal key `review.url`.
26
26
  */
27
27
  export declare function commanderOptionAttribute(flag:string):string;
28
+ /** Every option key a schema field's value can arrive under: its key, flag and aliases in each accepted spelling. */
29
+ export declare function resolveCandidateOptionKeys(definition:RuntimeFieldDefinitionResolved):string[];
28
30
  /** Implements read runtime field option value for the public runtime surface of this module. */
29
31
  export declare function readRuntimeFieldOptionValue(options:Record<string,unknown>,definition:RuntimeFieldDefinitionResolved):unknown;
30
32
  /** Validate a declared field; option arrays represent repeated flags, while metadata containers retain their exact shape. */
31
33
  export declare function coerceRuntimeFieldValue(definition:RuntimeFieldDefinitionResolved,rawValue:unknown,labelOverride?:string,inputKind?:"option"|"metadata"):unknown;
34
+ /** True when a schema field must hold a value when an item of `itemTypeName` is created. */
35
+ export declare function shouldRequireFieldOnCreate(definition:RuntimeFieldDefinitionResolved,itemTypeName:string|undefined):boolean;
32
36
  /** Implements collect runtime create field values for the public runtime surface of this module. */
33
37
  export declare function collectRuntimeCreateFieldValues(options:Record<string,unknown>,fieldRegistry:RuntimeFieldRegistry,itemTypeName:string|undefined):{values:Record<string,unknown>;missing_required_flags:string[];};
34
38
  /** Implements collect runtime update field values for the public runtime surface of this module. */
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d1e62e3f-c165-5713-a074-070806d85b32")}catch{}})();import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{stableStringify}from"../shared/serialization.js";import{isRfc3339DateTime}from"../shared/time.js";import{runtimeFieldOptionTarget}from"./runtime-schema.js";import{assertIdentityFieldsWithoutUrlCredentials}from"../shared/url-credentials.js";const MAX_VALUE_SCHEMA_DEPTH=16;function toCamelToken(value){const segments=value.trim().replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(segment=>segment.length>0).map(segment=>segment.toLowerCase());if(segments.length===0)return value;const[first,...rest]=segments;return`${first}${rest.map(segment=>`${segment.slice(0,1).toUpperCase()}${segment.slice(1)}`).join("")}`}function runtimeFieldSdkOptionName(definition,registry,reservedOptions=new Set,command){if(hasStorageTwin(definition,registry,command))return;const taken=foreignRuntimeFieldOptionNames(definition,registry,reservedOptions,command),readOrder=resolveCandidateOptionKeys(definition);return[toCamelToken(definition.cli_flag),...readOrder].find(name=>!taken.has(name)&&isUnshadowedOptionKey(name,readOrder,taken))}function isUnshadowedOptionKey(key,readOrder,taken){for(const earlier of readOrder){if(earlier===key)break;if(taken.has(earlier))return!1}return!0}function hasStorageTwin(definition,registry,command){return registry.definitions.some(candidate=>candidate!==definition&&candidate.metadata_key===definition.metadata_key&&(command===void 0||candidate.commands.includes(command)))}function foreignRuntimeFieldOptionNames(definition,registry,reservedOptions,command){return new Set([...reservedOptions,...registry.definitions.filter(candidate=>candidate!==definition&&(command===void 0||candidate.commands.includes(command))).flatMap(candidate=>resolveCandidateOptionKeys(candidate))])}function isNegatingFlag(flag){return flag.replace(/^-+/u,"").startsWith("no-")}function runtimeFieldFlagToken(flag){return flag.startsWith("-")?flag:`--${flag}`}function runtimeFieldCliFlagRoute(definition,registry,reserved,command){if(hasStorageTwin(definition,registry,command))return;const taken=foreignRuntimeFieldOptionNames(definition,registry,reserved.options,command),readOrder=resolveCandidateOptionKeys(definition);return[definition.cli_flag,...definition.cli_aliases].find(flag=>{const key=commanderOptionAttribute(flag);return isNegatingFlag(flag)||reserved.flags.has(runtimeFieldFlagToken(flag))||taken.has(key)?!1:isUnshadowedOptionKey(key,readOrder,taken)})}function commanderOptionAttribute(flag){return flag.replace(/^-+/u,"").replace(/^no-/u,"").split("-").reduce((name,word)=>`${name}${word.charAt(0).toUpperCase()}${word.slice(1)}`)}function resolveCandidateOptionKeys(definition){return[...new Set([runtimeFieldOptionTarget(definition),toCamelToken(definition.key),toCamelToken(definition.cli_flag),...definition.cli_aliases.map(alias=>toCamelToken(alias)),...[definition.cli_flag,...definition.cli_aliases].filter(flag=>!isNegatingFlag(flag)).map(flag=>commanderOptionAttribute(flag))])]}function readRuntimeFieldOptionValue(options,definition){for(const candidateKey of resolveCandidateOptionKeys(definition)){if(!Object.hasOwn(options,candidateKey))continue;const value=options[candidateKey];if(value!==void 0)return value}}function normalizeStringArrayValue(value){return Array.isArray(value)?value.flatMap(entry=>normalizeStringArrayValue(entry)).map(entry=>entry.trim()).filter(entry=>entry.length>0):typeof value=="string"?value.split(/[,\n|]/).map(entry=>entry.trim()).filter(entry=>entry.length>0):value==null?[]:[String(value).trim()].filter(entry=>entry.length>0)}function parseBooleanValue(raw,label){if(typeof raw=="boolean")return raw;if(typeof raw=="number"){if(raw===1)return!0;if(raw===0)return!1}if(typeof raw=="string"){const normalized=raw.trim().toLowerCase();if(normalized==="true"||normalized==="1"||normalized==="yes")return!0;if(normalized==="false"||normalized==="0"||normalized==="no")return!1}throw new PmCliError(`${label} must be one of true|false|1|0|yes|no`,EXIT_CODE.USAGE)}function parseNumberValue(raw,label){if(typeof raw=="number"&&Number.isFinite(raw))return raw;const candidate=typeof raw=="string"?raw.trim():String(raw),parsed=Number(candidate);if(!Number.isFinite(parsed))throw new PmCliError(`${label} must be a number`,EXIT_CODE.USAGE);return parsed}function parseJsonContainerValue(raw,label,expectedType){const parsed=typeof raw=="string"?(()=>{try{return JSON.parse(raw)}catch{return}})():raw;if(expectedType==="array"&&Array.isArray(parsed)||expectedType==="object"&&typeof parsed=="object"&&parsed!==null&&!Array.isArray(parsed))return parsed;throw new PmCliError(`${label} must be valid JSON ${expectedType}`,EXIT_CODE.USAGE)}function valueMatchesSchemaType(value,type){return type===void 0?!0:type==="array"?Array.isArray(value):type==="object"?typeof value=="object"&&value!==null&&!Array.isArray(value):typeof value===type}function runtimeFieldPrimitiveSchemaError(value,schema,path){if(schema.const!==void 0&&stableStringify(value)!==stableStringify(schema.const))return`${path} must equal ${stableStringify(schema.const)}`;if(schema.enum!==void 0&&!schema.enum.some(candidate=>stableStringify(candidate)===stableStringify(value)))return`${path} must be one of ${schema.enum.map(entry=>stableStringify(entry)).join("|")}`;if(!valueMatchesSchemaType(value,schema.type))return`${path} must match configured type ${String(schema.type)}`;if(typeof value=="string"){if(schema.min_length!==void 0&&value.length<schema.min_length)return`${path} must contain at least ${schema.min_length} characters`;if(schema.format==="date-time"&&!isRfc3339DateTime(value))return`${path} must be an RFC 3339 date-time`}}function runtimeFieldArraySchemaError(value,schema,path,depth){if(Array.isArray(value)){if(schema.min_items!==void 0&&value.length<schema.min_items)return`${path} must contain at least ${schema.min_items} items`;if(schema.items)for(const[index,entry]of value.entries()){const error=runtimeFieldSchemaError(entry,schema.items,`${path}[${index}]`,depth+1);if(error)return error}}}function runtimeFieldObjectSchemaError(value,schema,path,depth){if(typeof value!="object"||value===null||Array.isArray(value))return;const record=value;for(const key of schema.required??[])if(!Object.hasOwn(record,key))return`${path}.${key} is required`;for(const[key,entry]of Object.entries(record)){const propertySchema=schema.properties?.[key];if(!propertySchema){if(schema.additional_properties===!1)return`${path}.${key} is not allowed`;continue}const error=runtimeFieldSchemaError(entry,propertySchema,`${path}.${key}`,depth+1);if(error)return error}}function runtimeFieldSchemaError(value,schema,path,depth=0){if(depth>MAX_VALUE_SCHEMA_DEPTH)return`${path} value schema exceeds maximum depth`;const directError=runtimeFieldPrimitiveSchemaError(value,schema,path);if(directError)return directError;const arrayError=runtimeFieldArraySchemaError(value,schema,path,depth);if(arrayError)return arrayError;const objectError=runtimeFieldObjectSchemaError(value,schema,path,depth);if(objectError)return objectError;if(!schema.one_of)return;let matches=0;for(const candidate of schema.one_of)if(runtimeFieldSchemaError(value,candidate,path,depth+1)===void 0&&(matches+=1,matches>1))break;return matches===1?void 0:`${path} must match exactly one configured schema variant`}function validateRuntimeFieldValue(definition,value,label){if(!definition.value_schema||value===void 0)return value;const error=runtimeFieldSchemaError(value,definition.value_schema,label);if(error)throw new PmCliError(error,EXIT_CODE.USAGE);return value}function coerceRuntimeContainerValue(definition,rawValue,label,inputKind){const raw=inputKind==="option"&&Array.isArray(rawValue)?rawValue[rawValue.length-1]:rawValue;if(raw!==void 0)return validateRuntimeFieldValue(definition,parseJsonContainerValue(raw,label,definition.type),label)}function coerceRuntimeFieldValue(definition,rawValue,labelOverride,inputKind="option"){const label=labelOverride??`--${definition.cli_flag}`;if(definition.type==="array"||definition.type==="object")return coerceRuntimeContainerValue(definition,rawValue,label,inputKind);if(definition.repeatable||definition.type==="string_array"){const values=normalizeStringArrayValue(rawValue);return definition.type==="number"?validateRuntimeFieldValue(definition,values.map(value=>parseNumberValue(value,label)),label):definition.type==="boolean"?validateRuntimeFieldValue(definition,values.map(value=>parseBooleanValue(value,label)),label):validateRuntimeFieldValue(definition,values,label)}const scalarRaw=Array.isArray(rawValue)?rawValue[rawValue.length-1]:rawValue;if(scalarRaw!==void 0)return definition.type==="number"?validateRuntimeFieldValue(definition,parseNumberValue(scalarRaw,label),label):definition.type==="boolean"?validateRuntimeFieldValue(definition,parseBooleanValue(scalarRaw,label),label):validateRuntimeFieldValue(definition,typeof scalarRaw=="string"?scalarRaw:String(scalarRaw),label)}function shouldRequireFieldOnCreate(definition,itemTypeName){return!definition.required&&!definition.required_on_create?!1:definition.required_types.length===0?!0:itemTypeName?definition.required_types.map(value=>value.toLowerCase()).includes(itemTypeName.trim().toLowerCase()):!1}function collectRuntimeCreateFieldValues(options,fieldRegistry,itemTypeName){const values={},missingRequiredFlags=[];for(const definition of fieldRegistry.command_to_fields.get("create")??[]){const rawValue=readRuntimeFieldOptionValue(options,definition);if(rawValue===void 0){shouldRequireFieldOnCreate(definition,itemTypeName)&&missingRequiredFlags.push(`--${definition.cli_flag}`);continue}values[definition.metadata_key]=coerceRuntimeFieldValue(definition,rawValue)}return{values,missing_required_flags:[...new Set(missingRequiredFlags)].sort((left,right)=>left.localeCompare(right))}}function collectRuntimeUpdateFieldValues(options,fieldRegistry,commands=["update"]){const values={},definitions=(commands??["update"]).flatMap(command=>fieldRegistry.command_to_fields.get(command)??[]),seen=new Set;for(const definition of definitions){const rawValue=readRuntimeFieldOptionValue(options,definition);rawValue!==void 0&&(seen.has(definition.metadata_key)||(seen.add(definition.metadata_key),values[definition.metadata_key]=coerceRuntimeFieldValue(definition,rawValue)))}return assertIdentityFieldsWithoutUrlCredentials(values),values}export{coerceRuntimeFieldValue,collectRuntimeCreateFieldValues,collectRuntimeUpdateFieldValues,commanderOptionAttribute,readRuntimeFieldOptionValue,runtimeFieldCliFlagRoute,runtimeFieldFlagToken,runtimeFieldSdkOptionName};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="9b51a9f9-e57f-5998-837e-c6c442ca1c9b")}catch{}})();import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{stableStringify}from"../shared/serialization.js";import{isRfc3339DateTime}from"../shared/time.js";import{runtimeFieldOptionTarget}from"./runtime-schema.js";import{assertIdentityFieldsWithoutUrlCredentials}from"../shared/url-credentials.js";const MAX_VALUE_SCHEMA_DEPTH=16;function toCamelToken(value){const segments=value.trim().replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(segment=>segment.length>0).map(segment=>segment.toLowerCase());if(segments.length===0)return value;const[first,...rest]=segments;return`${first}${rest.map(segment=>`${segment.slice(0,1).toUpperCase()}${segment.slice(1)}`).join("")}`}function runtimeFieldSdkOptionName(definition,registry,reservedOptions=new Set,command){if(hasStorageTwin(definition,registry,command))return;const taken=foreignRuntimeFieldOptionNames(definition,registry,reservedOptions,command),readOrder=resolveCandidateOptionKeys(definition);return[toCamelToken(definition.cli_flag),...readOrder].find(name=>!taken.has(name)&&isUnshadowedOptionKey(name,readOrder,taken))}function isUnshadowedOptionKey(key,readOrder,taken){for(const earlier of readOrder){if(earlier===key)break;if(taken.has(earlier))return!1}return!0}function hasStorageTwin(definition,registry,command){return registry.definitions.some(candidate=>candidate!==definition&&candidate.metadata_key===definition.metadata_key&&(command===void 0||candidate.commands.includes(command)))}function foreignRuntimeFieldOptionNames(definition,registry,reservedOptions,command){return new Set([...reservedOptions,...registry.definitions.filter(candidate=>candidate!==definition&&(command===void 0||candidate.commands.includes(command))).flatMap(candidate=>resolveCandidateOptionKeys(candidate))])}function isNegatingFlag(flag){return flag.replace(/^-+/u,"").startsWith("no-")}function runtimeFieldFlagToken(flag){return flag.startsWith("-")?flag:`--${flag}`}function runtimeFieldCliFlagRoute(definition,registry,reserved,command){if(hasStorageTwin(definition,registry,command))return;const taken=foreignRuntimeFieldOptionNames(definition,registry,reserved.options,command),readOrder=resolveCandidateOptionKeys(definition);return[definition.cli_flag,...definition.cli_aliases].find(flag=>{const key=commanderOptionAttribute(flag);return isNegatingFlag(flag)||reserved.flags.has(runtimeFieldFlagToken(flag))||taken.has(key)?!1:isUnshadowedOptionKey(key,readOrder,taken)})}function commanderOptionAttribute(flag){return flag.replace(/^-+/u,"").replace(/^no-/u,"").split("-").reduce((name,word)=>`${name}${word.charAt(0).toUpperCase()}${word.slice(1)}`)}function resolveCandidateOptionKeys(definition){return[...new Set([runtimeFieldOptionTarget(definition),toCamelToken(definition.key),toCamelToken(definition.cli_flag),...definition.cli_aliases.map(alias=>toCamelToken(alias)),...[definition.cli_flag,...definition.cli_aliases].filter(flag=>!isNegatingFlag(flag)).map(flag=>commanderOptionAttribute(flag))])]}function readRuntimeFieldOptionValue(options,definition){for(const candidateKey of resolveCandidateOptionKeys(definition)){if(!Object.hasOwn(options,candidateKey))continue;const value=options[candidateKey];if(value!==void 0)return value}}function normalizeStringArrayValue(value){return Array.isArray(value)?value.flatMap(entry=>normalizeStringArrayValue(entry)).map(entry=>entry.trim()).filter(entry=>entry.length>0):typeof value=="string"?value.split(/[,\n|]/).map(entry=>entry.trim()).filter(entry=>entry.length>0):value==null?[]:[String(value).trim()].filter(entry=>entry.length>0)}function parseBooleanValue(raw,label){if(typeof raw=="boolean")return raw;if(typeof raw=="number"){if(raw===1)return!0;if(raw===0)return!1}if(typeof raw=="string"){const normalized=raw.trim().toLowerCase();if(normalized==="true"||normalized==="1"||normalized==="yes")return!0;if(normalized==="false"||normalized==="0"||normalized==="no")return!1}throw new PmCliError(`${label} must be one of true|false|1|0|yes|no`,EXIT_CODE.USAGE)}function parseNumberValue(raw,label){if(typeof raw=="number"&&Number.isFinite(raw))return raw;const candidate=typeof raw=="string"?raw.trim():String(raw),parsed=Number(candidate);if(!Number.isFinite(parsed))throw new PmCliError(`${label} must be a number`,EXIT_CODE.USAGE);return parsed}function parseJsonContainerValue(raw,label,expectedType){const parsed=typeof raw=="string"?(()=>{try{return JSON.parse(raw)}catch{return}})():raw;if(expectedType==="array"&&Array.isArray(parsed)||expectedType==="object"&&typeof parsed=="object"&&parsed!==null&&!Array.isArray(parsed))return parsed;throw new PmCliError(`${label} must be valid JSON ${expectedType}`,EXIT_CODE.USAGE)}function valueMatchesSchemaType(value,type){return type===void 0?!0:type==="array"?Array.isArray(value):type==="object"?typeof value=="object"&&value!==null&&!Array.isArray(value):typeof value===type}function runtimeFieldPrimitiveSchemaError(value,schema,path){if(schema.const!==void 0&&stableStringify(value)!==stableStringify(schema.const))return`${path} must equal ${stableStringify(schema.const)}`;if(schema.enum!==void 0&&!schema.enum.some(candidate=>stableStringify(candidate)===stableStringify(value)))return`${path} must be one of ${schema.enum.map(entry=>stableStringify(entry)).join("|")}`;if(!valueMatchesSchemaType(value,schema.type))return`${path} must match configured type ${String(schema.type)}`;if(typeof value=="string"){if(schema.min_length!==void 0&&value.length<schema.min_length)return`${path} must contain at least ${schema.min_length} characters`;if(schema.format==="date-time"&&!isRfc3339DateTime(value))return`${path} must be an RFC 3339 date-time`}}function runtimeFieldArraySchemaError(value,schema,path,depth){if(Array.isArray(value)){if(schema.min_items!==void 0&&value.length<schema.min_items)return`${path} must contain at least ${schema.min_items} items`;if(schema.items)for(const[index,entry]of value.entries()){const error=runtimeFieldSchemaError(entry,schema.items,`${path}[${index}]`,depth+1);if(error)return error}}}function runtimeFieldObjectSchemaError(value,schema,path,depth){if(typeof value!="object"||value===null||Array.isArray(value))return;const record=value;for(const key of schema.required??[])if(!Object.hasOwn(record,key))return`${path}.${key} is required`;for(const[key,entry]of Object.entries(record)){const propertySchema=schema.properties?.[key];if(!propertySchema){if(schema.additional_properties===!1)return`${path}.${key} is not allowed`;continue}const error=runtimeFieldSchemaError(entry,propertySchema,`${path}.${key}`,depth+1);if(error)return error}}function runtimeFieldSchemaError(value,schema,path,depth=0){if(depth>MAX_VALUE_SCHEMA_DEPTH)return`${path} value schema exceeds maximum depth`;const directError=runtimeFieldPrimitiveSchemaError(value,schema,path);if(directError)return directError;const arrayError=runtimeFieldArraySchemaError(value,schema,path,depth);if(arrayError)return arrayError;const objectError=runtimeFieldObjectSchemaError(value,schema,path,depth);if(objectError)return objectError;if(!schema.one_of)return;let matches=0;for(const candidate of schema.one_of)if(runtimeFieldSchemaError(value,candidate,path,depth+1)===void 0&&(matches+=1,matches>1))break;return matches===1?void 0:`${path} must match exactly one configured schema variant`}function validateRuntimeFieldValue(definition,value,label){if(!definition.value_schema||value===void 0)return value;const error=runtimeFieldSchemaError(value,definition.value_schema,label);if(error)throw new PmCliError(error,EXIT_CODE.USAGE);return value}function coerceRuntimeContainerValue(definition,rawValue,label,inputKind){const raw=inputKind==="option"&&Array.isArray(rawValue)?rawValue[rawValue.length-1]:rawValue;if(raw!==void 0)return validateRuntimeFieldValue(definition,parseJsonContainerValue(raw,label,definition.type),label)}function coerceRuntimeFieldValue(definition,rawValue,labelOverride,inputKind="option"){const label=labelOverride??`--${definition.cli_flag}`;if(definition.type==="array"||definition.type==="object")return coerceRuntimeContainerValue(definition,rawValue,label,inputKind);if(definition.repeatable||definition.type==="string_array"){const values=normalizeStringArrayValue(rawValue);return definition.type==="number"?validateRuntimeFieldValue(definition,values.map(value=>parseNumberValue(value,label)),label):definition.type==="boolean"?validateRuntimeFieldValue(definition,values.map(value=>parseBooleanValue(value,label)),label):validateRuntimeFieldValue(definition,values,label)}const scalarRaw=Array.isArray(rawValue)?rawValue[rawValue.length-1]:rawValue;if(scalarRaw!==void 0)return definition.type==="number"?validateRuntimeFieldValue(definition,parseNumberValue(scalarRaw,label),label):definition.type==="boolean"?validateRuntimeFieldValue(definition,parseBooleanValue(scalarRaw,label),label):validateRuntimeFieldValue(definition,typeof scalarRaw=="string"?scalarRaw:String(scalarRaw),label)}function shouldRequireFieldOnCreate(definition,itemTypeName){return!definition.required&&!definition.required_on_create?!1:definition.required_types.length===0?!0:itemTypeName?definition.required_types.map(value=>value.toLowerCase()).includes(itemTypeName.trim().toLowerCase()):!1}function collectRuntimeCreateFieldValues(options,fieldRegistry,itemTypeName){const values={},missingRequiredFlags=[];for(const definition of fieldRegistry.command_to_fields.get("create")??[]){const rawValue=readRuntimeFieldOptionValue(options,definition);if(rawValue===void 0){shouldRequireFieldOnCreate(definition,itemTypeName)&&missingRequiredFlags.push(`--${definition.cli_flag}`);continue}values[definition.metadata_key]=coerceRuntimeFieldValue(definition,rawValue)}return{values,missing_required_flags:[...new Set(missingRequiredFlags)].sort((left,right)=>left.localeCompare(right))}}function collectRuntimeUpdateFieldValues(options,fieldRegistry,commands=["update"]){const values={},definitions=(commands??["update"]).flatMap(command=>fieldRegistry.command_to_fields.get(command)??[]),seen=new Set;for(const definition of definitions){const rawValue=readRuntimeFieldOptionValue(options,definition);rawValue!==void 0&&(seen.has(definition.metadata_key)||(seen.add(definition.metadata_key),values[definition.metadata_key]=coerceRuntimeFieldValue(definition,rawValue)))}return assertIdentityFieldsWithoutUrlCredentials(values),values}export{coerceRuntimeFieldValue,collectRuntimeCreateFieldValues,collectRuntimeUpdateFieldValues,commanderOptionAttribute,readRuntimeFieldOptionValue,resolveCandidateOptionKeys,runtimeFieldCliFlagRoute,runtimeFieldFlagToken,runtimeFieldSdkOptionName,shouldRequireFieldOnCreate};
2
2
  //# sourceMappingURL=runtime-field-values.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="06c9f6f4-c2f0-549c-9a0f-4f4269cc5f49")}catch{}})();import{createHash}from"node:crypto";import{existsSync,promises as fs,readFileSync}from"node:fs";import path from"node:path";import{writeFileAtomic}from"../fs/fs-utils.js";import{acquireLock}from"../lock/lock.js";import{SETTINGS_DEFAULTS}from"../shared/constants.js";import{getRuntimePath}from"../store/paths.js";const SESSION_FILENAME="session.json";function isBoundedNonEmptyString(value,maximum){return typeof value=="string"&&value.length>0&&value.length<=maximum}function parseSemanticAttribution(value){if(value===null||typeof value!="object"||Array.isArray(value))return;const record=value,validRole=["implementer","planner","release-operator"].includes(String(record.role)),validConfidence=["high","medium"].includes(String(record.confidence)),validTopic=isBoundedNonEmptyString(record.topic,256),validEvidence=Array.isArray(record.evidence)&&record.evidence.length<=32&&record.evidence.every(entry=>typeof entry=="string"&&entry.length<=128),validActiveItems=Array.isArray(record.active_item_ids)&&record.active_item_ids.length<=64&&record.active_item_ids.every(entry=>isBoundedNonEmptyString(entry,128)),validFocus=record.focused_item_id===void 0||isBoundedNonEmptyString(record.focused_item_id,128);if([validRole,validConfidence,validTopic,validEvidence,validActiveItems,validFocus,record.rule_version==="v2"].every(Boolean))return record}function parseSemanticAttributionMap(value){if(value===null||typeof value!="object"||Array.isArray(value))return;const entries=Object.entries(value).slice(0,128).flatMap(([key,attribution])=>{const parsed=parseSemanticAttribution(attribution);return parsed&&key.length<=128?[[key,parsed]]:[]});return entries.length>0?Object.fromEntries(entries):void 0}function getSessionStatePath(pmRoot){return path.join(getRuntimePath(pmRoot),SESSION_FILENAME)}async function readSessionState(pmRoot){try{const raw=await fs.readFile(getSessionStatePath(pmRoot),"utf8"),parsed=JSON.parse(raw);if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))return{};const record=parsed,focused=record.focused_item,semanticAttribution=parseSemanticAttributionMap(record.semantic_attribution);return typeof focused=="string"&&focused.trim().length>0?{focused_item:focused,...semanticAttribution?{semantic_attribution:semanticAttribution}:{}}:semanticAttribution?{semantic_attribution:semanticAttribution}:{}}catch{return{}}}async function mutateSessionState(pmRoot,mutate){const release=await acquireLock(pmRoot,"session-state",SETTINGS_DEFAULTS.locks.ttl_seconds,"session-state",!1,!0,SETTINGS_DEFAULTS.locks.wait_ms);try{const state=await readSessionState(pmRoot);mutate(state);const target=getSessionStatePath(pmRoot);await fs.mkdir(path.dirname(target),{recursive:!0}),await writeFileAtomic(target,JSON.stringify(state))}finally{await release()}}function semanticAttributionKey(principal){return/#([a-f0-9]{24})$/u.exec(principal.trim())?.[1]??`author-${createHash("sha256").update(principal).digest("hex").slice(0,24)}`}function normalizedEvidence(values){return[...new Set(values.map(value=>value.trim()).filter(Boolean))].slice(0,32).map(value=>value.slice(0,128))}function worksetTopic(activeItemIds){const ids=[...new Set(activeItemIds)].sort((left,right)=>left.localeCompare(right));if(ids.length===1)return ids[0];const complete=`workset:${ids.join("+")}`;return complete.length<=256?complete:`workset:${ids.join("+").slice(0,230)}+${createHash("sha256").update(ids.join("\0")).digest("hex").slice(0,12)}`}async function updateSemanticAttribution(pmRoot,key,mutate){await mutateSessionState(pmRoot,state=>{const attributions={...state.semantic_attribution},next=mutate(attributions[key]);next===void 0?delete attributions[key]:attributions[key]=next,Object.keys(attributions).length===0?delete state.semantic_attribution:state.semantic_attribution=attributions})}async function recordClaimedWorkAttribution(params){const key=semanticAttributionKey(params.principal);await updateSemanticAttribution(params.pmRoot,key,current=>{const activeItemIds=[...new Set([...current?.active_item_ids??[],params.itemId])].slice(-64).sort((left,right)=>left.localeCompare(right)),focusedItemId=current?.focused_item_id;return{role:"implementer",topic:focusedItemId??worksetTopic(activeItemIds),confidence:focusedItemId?"high":"medium",rule_version:"v2",evidence:normalizedEvidence([...activeItemIds.map(id=>`claim:${id}`),...focusedItemId?[`focus:${focusedItemId}`]:[],...(params.lineageIds??[]).map(id=>`lineage:${id}`)]),active_item_ids:activeItemIds,...focusedItemId?{focused_item_id:focusedItemId}:{}}})}async function releaseClaimedWorkAttribution(params){const key=semanticAttributionKey(params.principal);await updateSemanticAttribution(params.pmRoot,key,current=>{if(!current)return;const activeItemIds=current.active_item_ids.filter(id=>id!==params.itemId);if(activeItemIds.length===0&&!current.focused_item_id)return;const focusedItemId=current.focused_item_id;return{...current,role:"release-operator",topic:focusedItemId??worksetTopic(activeItemIds),confidence:focusedItemId?"high":"medium",evidence:normalizedEvidence([...activeItemIds.map(id=>`claim:${id}`),...focusedItemId?[`focus:${focusedItemId}`]:[],`release:${params.itemId}`]),active_item_ids:activeItemIds}})}async function recordFocusedWorkAttribution(params){const key=semanticAttributionKey(params.principal);await updateSemanticAttribution(params.pmRoot,key,current=>{const activeItemIds=current?.active_item_ids??[];if(!params.itemId&&activeItemIds.length===0)return;const focusedItemId=params.itemId;return{role:focusedItemId?"planner":current.role,topic:focusedItemId??worksetTopic(activeItemIds),confidence:focusedItemId?"high":"medium",rule_version:"v2",evidence:normalizedEvidence([...activeItemIds.map(id=>`claim:${id}`),...focusedItemId?[`focus:${focusedItemId}`]:[],...(params.lineageIds??[]).map(id=>`lineage:${id}`)]),active_item_ids:activeItemIds,...focusedItemId?{focused_item_id:focusedItemId}:{}}})}function resolveAttributionRoot(cwd,env){const configured=env.PM_PATH?.trim();if(configured){const resolved=path.resolve(cwd,configured);if(existsSync(path.join(resolved,"settings.json")))return resolved;const nested=path.join(resolved,".agents","pm");if(existsSync(path.join(nested,"settings.json")))return nested}let cursor=path.resolve(cwd);for(let depth=0;depth<32;depth+=1){const candidate=path.join(cursor,".agents","pm");if(existsSync(path.join(candidate,"settings.json")))return candidate;const parent=path.dirname(cursor);if(parent===cursor)break;cursor=parent}}function readAgentSemanticAttributionSync(params){if(!params.key)return;const pmRoot=resolveAttributionRoot(params.cwd,params.env);if(pmRoot)try{const parsed=JSON.parse(readFileSync(getSessionStatePath(pmRoot),"utf8"));return parseSemanticAttribution(parsed.semantic_attribution?.[params.key])}catch{return}}async function getFocusedItem(pmRoot){return(await readSessionState(pmRoot)).focused_item}async function setFocusedItem(pmRoot,id){await mutateSessionState(pmRoot,state=>{state.focused_item=id})}async function clearFocusedItem(pmRoot){await mutateSessionState(pmRoot,state=>{delete state.focused_item})}export{clearFocusedItem,getFocusedItem,getSessionStatePath,readAgentSemanticAttributionSync,readSessionState,recordClaimedWorkAttribution,recordFocusedWorkAttribution,releaseClaimedWorkAttribution,semanticAttributionKey,setFocusedItem};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b86f3679-07fa-5566-b8cb-fb05ab89dd31")}catch{}})();import{createHash}from"node:crypto";import{existsSync,promises as fs,readFileSync}from"node:fs";import path from"node:path";import{writeFileAtomic}from"../fs/fs-utils.js";import{acquireLockLease}from"../lock/lock.js";import{SETTINGS_DEFAULTS}from"../shared/constants.js";import{getRuntimePath}from"../store/paths.js";const SESSION_FILENAME="session.json";function isBoundedNonEmptyString(value,maximum){return typeof value=="string"&&value.length>0&&value.length<=maximum}function parseSemanticAttribution(value){if(value===null||typeof value!="object"||Array.isArray(value))return;const record=value,validRole=["implementer","planner","release-operator"].includes(String(record.role)),validConfidence=["high","medium"].includes(String(record.confidence)),validTopic=isBoundedNonEmptyString(record.topic,256),validEvidence=Array.isArray(record.evidence)&&record.evidence.length<=32&&record.evidence.every(entry=>typeof entry=="string"&&entry.length<=128),validActiveItems=Array.isArray(record.active_item_ids)&&record.active_item_ids.length<=64&&record.active_item_ids.every(entry=>isBoundedNonEmptyString(entry,128)),validFocus=record.focused_item_id===void 0||isBoundedNonEmptyString(record.focused_item_id,128);if([validRole,validConfidence,validTopic,validEvidence,validActiveItems,validFocus,record.rule_version==="v2"].every(Boolean))return record}function parseSemanticAttributionMap(value){if(value===null||typeof value!="object"||Array.isArray(value))return;const entries=Object.entries(value).slice(0,128).flatMap(([key,attribution])=>{const parsed=parseSemanticAttribution(attribution);return parsed&&key.length<=128?[[key,parsed]]:[]});return entries.length>0?Object.fromEntries(entries):void 0}function getSessionStatePath(pmRoot){return path.join(getRuntimePath(pmRoot),SESSION_FILENAME)}async function readSessionState(pmRoot){try{const raw=await fs.readFile(getSessionStatePath(pmRoot),"utf8"),parsed=JSON.parse(raw);if(parsed===null||typeof parsed!="object"||Array.isArray(parsed))return{};const record=parsed,focused=record.focused_item,semanticAttribution=parseSemanticAttributionMap(record.semantic_attribution);return typeof focused=="string"&&focused.trim().length>0?{focused_item:focused,...semanticAttribution?{semantic_attribution:semanticAttribution}:{}}:semanticAttribution?{semantic_attribution:semanticAttribution}:{}}catch{return{}}}async function mutateSessionState(pmRoot,mutate){const lease=await acquireLockLease(pmRoot,"session-state",SETTINGS_DEFAULTS.locks.ttl_seconds,"session-state",!1,!1,SETTINGS_DEFAULTS.locks.wait_ms);try{const state=await readSessionState(pmRoot);mutate(state);const target=getSessionStatePath(pmRoot);await lease.fence(async()=>{await fs.mkdir(path.dirname(target),{recursive:!0}),await writeFileAtomic(target,JSON.stringify(state))})}finally{await lease.release()}}function semanticAttributionKey(principal){return/#([a-f0-9]{24})$/u.exec(principal.trim())?.[1]??`author-${createHash("sha256").update(principal).digest("hex").slice(0,24)}`}function normalizedEvidence(values){return[...new Set(values.map(value=>value.trim()).filter(Boolean))].slice(0,32).map(value=>value.slice(0,128))}function worksetTopic(activeItemIds){const ids=[...new Set(activeItemIds)].sort((left,right)=>left.localeCompare(right));if(ids.length===1)return ids[0];const complete=`workset:${ids.join("+")}`;return complete.length<=256?complete:`workset:${ids.join("+").slice(0,230)}+${createHash("sha256").update(ids.join("\0")).digest("hex").slice(0,12)}`}async function updateSemanticAttribution(pmRoot,key,mutate){await mutateSessionState(pmRoot,state=>{const attributions={...state.semantic_attribution},next=mutate(attributions[key]);next===void 0?delete attributions[key]:attributions[key]=next,Object.keys(attributions).length===0?delete state.semantic_attribution:state.semantic_attribution=attributions})}async function recordClaimedWorkAttribution(params){const key=semanticAttributionKey(params.principal);await updateSemanticAttribution(params.pmRoot,key,current=>{const activeItemIds=[...new Set([...current?.active_item_ids??[],params.itemId])].slice(-64).sort((left,right)=>left.localeCompare(right)),focusedItemId=current?.focused_item_id;return{role:"implementer",topic:focusedItemId??worksetTopic(activeItemIds),confidence:focusedItemId?"high":"medium",rule_version:"v2",evidence:normalizedEvidence([...activeItemIds.map(id=>`claim:${id}`),...focusedItemId?[`focus:${focusedItemId}`]:[],...(params.lineageIds??[]).map(id=>`lineage:${id}`)]),active_item_ids:activeItemIds,...focusedItemId?{focused_item_id:focusedItemId}:{}}})}async function releaseClaimedWorkAttribution(params){const key=semanticAttributionKey(params.principal);await updateSemanticAttribution(params.pmRoot,key,current=>{if(!current)return;const activeItemIds=current.active_item_ids.filter(id=>id!==params.itemId);if(activeItemIds.length===0&&!current.focused_item_id)return;const focusedItemId=current.focused_item_id;return{...current,role:"release-operator",topic:focusedItemId??worksetTopic(activeItemIds),confidence:focusedItemId?"high":"medium",evidence:normalizedEvidence([...activeItemIds.map(id=>`claim:${id}`),...focusedItemId?[`focus:${focusedItemId}`]:[],`release:${params.itemId}`]),active_item_ids:activeItemIds}})}async function recordFocusedWorkAttribution(params){const key=semanticAttributionKey(params.principal);await updateSemanticAttribution(params.pmRoot,key,current=>{const activeItemIds=current?.active_item_ids??[];if(!params.itemId&&activeItemIds.length===0)return;const focusedItemId=params.itemId;return{role:focusedItemId?"planner":current.role,topic:focusedItemId??worksetTopic(activeItemIds),confidence:focusedItemId?"high":"medium",rule_version:"v2",evidence:normalizedEvidence([...activeItemIds.map(id=>`claim:${id}`),...focusedItemId?[`focus:${focusedItemId}`]:[],...(params.lineageIds??[]).map(id=>`lineage:${id}`)]),active_item_ids:activeItemIds,...focusedItemId?{focused_item_id:focusedItemId}:{}}})}function resolveAttributionRoot(cwd,env){const configured=env.PM_PATH?.trim();if(configured){const resolved=path.resolve(cwd,configured);if(existsSync(path.join(resolved,"settings.json")))return resolved;const nested=path.join(resolved,".agents","pm");if(existsSync(path.join(nested,"settings.json")))return nested}let cursor=path.resolve(cwd);for(let depth=0;depth<32;depth+=1){const candidate=path.join(cursor,".agents","pm");if(existsSync(path.join(candidate,"settings.json")))return candidate;const parent=path.dirname(cursor);if(parent===cursor)break;cursor=parent}}function readAgentSemanticAttributionSync(params){if(!params.key)return;const pmRoot=resolveAttributionRoot(params.cwd,params.env);if(pmRoot)try{const parsed=JSON.parse(readFileSync(getSessionStatePath(pmRoot),"utf8"));return parseSemanticAttribution(parsed.semantic_attribution?.[params.key])}catch{return}}async function getFocusedItem(pmRoot){return(await readSessionState(pmRoot)).focused_item}async function setFocusedItem(pmRoot,id){await mutateSessionState(pmRoot,state=>{state.focused_item=id})}async function clearFocusedItem(pmRoot){await mutateSessionState(pmRoot,state=>{delete state.focused_item})}export{clearFocusedItem,getFocusedItem,getSessionStatePath,readAgentSemanticAttributionSync,readSessionState,recordClaimedWorkAttribution,recordFocusedWorkAttribution,releaseClaimedWorkAttribution,semanticAttributionKey,setFocusedItem};
2
2
  //# sourceMappingURL=session-state.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3d6df465-e82e-57d8-a687-6c2e720c99c1")}catch{}})();const ITEM_PROJECT_CONTEXT_KEYS=["goal","objective","value","impact","outcome","why_now","parent","reviewer","risk","confidence","sprint","release","blocked_by","blocked_reason","unblock_note","reporter","severity","environment","repro_steps","resolution","expected_result","actual_result"],ITEM_METADATA_KEY_ORDER_VALUES=["id","title","description","type","pm_format_version","source_type","type_options","status","priority","tags","created_at","updated_at","deadline","reminders","events","closed_at","completed_at","assignee","claim_principal","source_owner","author","estimated_minutes","acceptance_criteria","design","external_ref","definition_of_ready","order",...ITEM_PROJECT_CONTEXT_KEYS,"affected_version","fixed_version","component","regression","customer_impact","dependencies","comments","notes","learnings","files","tests","test_runs","docs","close_reason","duplicate_of","plan_mode","plan_scope","plan_harness","plan_resume_context","plan_validation","plan_decisions","plan_discoveries","plan_steps"],ITEM_METADATA_KEY_ORDER=ITEM_METADATA_KEY_ORDER_VALUES;export{ITEM_METADATA_KEY_ORDER,ITEM_PROJECT_CONTEXT_KEYS};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="58db2e8f-05e5-5ffc-a8dd-a73966142f47")}catch{}})();const ITEM_PROJECT_CONTEXT_KEYS=["goal","objective","value","impact","outcome","why_now","parent","reviewer","risk","confidence","sprint","release","blocked_by","blocked_reason","unblock_note","reporter","severity","environment","repro_steps","resolution","expected_result","actual_result"],ITEM_METADATA_KEY_ORDER_VALUES=["id","title","description","type","pm_format_version","source_type","type_options","status","priority","tags","created_at","updated_at","deadline","reminders","events","closed_at","completed_at","assignee","claim_principal","source_owner","author","estimated_minutes","acceptance_criteria","deferred_fields","design","external_ref","definition_of_ready","order",...ITEM_PROJECT_CONTEXT_KEYS,"affected_version","fixed_version","component","regression","customer_impact","dependencies","comments","notes","learnings","files","tests","test_runs","docs","close_reason","duplicate_of","plan_mode","plan_scope","plan_harness","plan_resume_context","plan_validation","plan_decisions","plan_discoveries","plan_steps"],ITEM_METADATA_KEY_ORDER=ITEM_METADATA_KEY_ORDER_VALUES;export{ITEM_METADATA_KEY_ORDER,ITEM_PROJECT_CONTEXT_KEYS};
2
2
  //# sourceMappingURL=item-metadata-contract.js.map
@@ -7,6 +7,30 @@
7
7
  export declare function normalizeLowercaseWhitespace(value:string):string;
8
8
  /** Return a UTF-16 prefix without splitting a valid surrogate pair at its boundary. */
9
9
  export declare function unicodeSafePrefix(value:string,end:number):string;
10
+ /** UTF-16 code units a budgeted read keeps of an explanatory string it compacts. */
11
+ export declare const COMPACTED_STRING_LENGTH=240;
12
+ /**
13
+ * Shorten an explanatory string the way budgeted reads do: a Unicode-safe
14
+ * prefix followed by a marker naming how many code units were omitted, so a
15
+ * write path can recognise text copied from a compacted read (pm-n98pir).
16
+ * Compaction is idempotent: a string that already ends with a marker right
17
+ * after its kept prefix is returned unchanged, so a later budget stage never
18
+ * counts the marker as omitted source text.
19
+ */
20
+ export declare function compactExplanatoryString(value:string):string;
21
+ /** Return how many code units a compacted string omitted, or undefined when the text does not end with the compaction marker. */
22
+ export declare function readCompactionMarker(text:string):number|undefined;
23
+ /**
24
+ * Whether an output key names a continuation token (`cursor`, `next_cursor`,
25
+ * `output_cursor`, `source_cursor`, ...). A token is machine input for the
26
+ * next call, so compaction never shortens it (GH-1710).
27
+ */
28
+ export declare function isContinuationTokenKey(key:string):boolean;
29
+ /**
30
+ * Whether a cursor argument carries an ellipsis, which no encoder emits: the
31
+ * caller pasted a value a compacted read shortened (GH-1710).
32
+ */
33
+ export declare function isCompactedCursorArgument(value:string):boolean;
10
34
  /** Implements tokenize alpha numeric for the public runtime surface of this module. */
11
35
  export declare function tokenizeAlphaNumeric(value:string):string[];
12
36
  /** Implements jaccard similarity for the public runtime surface of this module. */
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4a7b042c-7fb8-57a5-8f94-de44f82d7589")}catch{}})();function normalizeLowercaseWhitespace(value){return value.trim().toLowerCase().replace(/\s+/g," ")}function unicodeSafePrefix(value,end){const prefix=value.slice(0,end),last=prefix.charCodeAt(prefix.length-1),next=value.charCodeAt(prefix.length);return last>=55296&&last<=56319&&next>=56320&&next<=57343?prefix.slice(0,-1):prefix}function tokenizeAlphaNumeric(value){return normalizeLowercaseWhitespace(value).split(/[^a-z0-9]+/).filter(token=>token.length>0)}function jaccardSimilarity(leftTokens,rightTokens){if(leftTokens.length===0&&rightTokens.length===0)return 1;if(leftTokens.length===0||rightTokens.length===0)return 0;const leftSet=new Set(leftTokens),rightSet=new Set(rightTokens);let intersection=0;for(const token of leftSet)rightSet.has(token)&&(intersection+=1);const union=new Set([...leftSet,...rightSet]).size;return intersection/union}export{jaccardSimilarity,normalizeLowercaseWhitespace,tokenizeAlphaNumeric,unicodeSafePrefix};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="21f779fe-fa2c-50d1-893d-8c6d47fbc56a")}catch{}})();function normalizeLowercaseWhitespace(value){return value.trim().toLowerCase().replace(/\s+/g," ")}function unicodeSafePrefix(value,end){const prefix=value.slice(0,end),last=prefix.charCodeAt(prefix.length-1),next=value.charCodeAt(prefix.length);return last>=55296&&last<=56319&&next>=56320&&next<=57343?prefix.slice(0,-1):prefix}const COMPACTED_STRING_LENGTH=240,COMPACTION_MARKER_PATTERN=/\u2026\[\+([1-9]\d*) chars\]$/u;function compactExplanatoryString(value){if(value.length<=COMPACTED_STRING_LENGTH)return value;const marker=COMPACTION_MARKER_PATTERN.exec(value);if(marker!==null&&marker.index<=COMPACTED_STRING_LENGTH)return value;const prefix=unicodeSafePrefix(value,COMPACTED_STRING_LENGTH);return`${prefix}\u2026[+${value.length-prefix.length} chars]`}function readCompactionMarker(text){const match=COMPACTION_MARKER_PATTERN.exec(text.trimEnd());return match?Number(match[1]):void 0}function isContinuationTokenKey(key){return key==="cursor"||key.endsWith("_cursor")}function isCompactedCursorArgument(value){return value.includes("\u2026")}function tokenizeAlphaNumeric(value){return normalizeLowercaseWhitespace(value).split(/[^a-z0-9]+/).filter(token=>token.length>0)}function jaccardSimilarity(leftTokens,rightTokens){if(leftTokens.length===0&&rightTokens.length===0)return 1;if(leftTokens.length===0||rightTokens.length===0)return 0;const leftSet=new Set(leftTokens),rightSet=new Set(rightTokens);let intersection=0;for(const token of leftSet)rightSet.has(token)&&(intersection+=1);const union=new Set([...leftSet,...rightSet]).size;return intersection/union}export{COMPACTED_STRING_LENGTH,compactExplanatoryString,isCompactedCursorArgument,isContinuationTokenKey,jaccardSimilarity,normalizeLowercaseWhitespace,readCompactionMarker,tokenizeAlphaNumeric,unicodeSafePrefix};
2
2
  //# sourceMappingURL=text-normalization.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4c000977-ebd7-5f07-93c7-32363e9ef2d9")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{quoteWindowsCommandArg}from"./command-line.js";import{EXIT_CODE}from"./constants.js";import{PmCliError}from"./errors.js";const URL_CREDENTIAL_PLACEHOLDER="[redacted]";function provablyWithoutUserinfo(token,colon){if(/[\t\n\r]/u.test(token)||!/(?:^|[^A-Za-z0-9+.-])(?:https?|wss?|ftp)$/iu.test(token.slice(0,colon)))return!1;let authority=colon+1;for(;token[authority]==="/"||token[authority]==="\\";)authority+=1;const delimiter=token.indexOf("/",authority)-authority;if(delimiter<0)return!1;const authorityEnd=authority+delimiter;return!/[:@%]/u.test(token.slice(authority,authorityEnd))&&!/[:%]|[/\\][/\\]/u.test(token.slice(authorityEnd))}function userinfoBounds(token){const at=Math.max(token.lastIndexOf("@"),token.toLowerCase().lastIndexOf("%40")),colon=token.indexOf(":");if(at<0||colon<0||colon>at)return;let start=colon+1;for(;start<at&&start<colon+3&&(token[start]==="/"||token[start]==="\\");)start+=1;return start===at||provablyWithoutUserinfo(token,colon)?void 0:[start,at]}function redactUrlCredentialsInToken(token){const bounds=userinfoBounds(token);return bounds?`${token.slice(0,bounds[0])}${URL_CREDENTIAL_PLACEHOLDER}${token.slice(bounds[1])}`:token}function redactIdentityCredentials(identity){return redactUrlCredentialsInToken(identity)}const IDENTITY_FIELDS=["author","assignee","claim_principal"];function redactIdentityFields(values){const redacted={...values};for(const field of IDENTITY_FIELDS)typeof redacted[field]=="string"&&(redacted[field]=redactIdentityCredentials(redacted[field]));return redacted}function assertIdentityWithoutUrlCredentials(identity,source){if(!(typeof identity!="string"||userinfoBounds(identity.trim())===void 0))throw new PmCliError(`${source} must not carry URL credentials: an identity is a name, never a credential.`,EXIT_CODE.USAGE,{code:"invalid_argument_value",field:source,required:`Set ${source} to a plain name such as agent-a, without user:password@ or token@ userinfo.`,nextSteps:[`Rerun with ${source} set to a plain name.`]})}function parseIdentityOption(value,source){return assertIdentityWithoutUrlCredentials(value,source),value}const NESTED_IDENTITY_PATHS=[["comments","author"],["notes","author"],["learnings","author"],["dependencies","author"],["plan_decisions","author"],["plan_discoveries","author"],["tests","provenance","author"]],IDENTITY_VALUE_DEPTH=4;function assertIdentityValueWithoutUrlCredentials(value,source,depth=0){if(typeof value=="string"){assertIdentityWithoutUrlCredentials(value,source);return}if(!(depth>=IDENTITY_VALUE_DEPTH||typeof value!="object"||value===null))for(const entry of Object.values(value))assertIdentityValueWithoutUrlCredentials(entry,source,depth+1)}function readEntryPath(entry,path){let node=entry;for(const key of path){if(typeof node!="object"||node===null||Array.isArray(node))return;node=node[key]}return node}function assertIdentityFieldsWithoutUrlCredentials(values){const record=values;for(const field of IDENTITY_FIELDS)assertIdentityValueWithoutUrlCredentials(record[field],field);for(const[collection,...path]of NESTED_IDENTITY_PATHS){const entries=record[collection];Array.isArray(entries)&&entries.forEach((entry,index)=>{assertIdentityValueWithoutUrlCredentials(readEntryPath(entry,path),`${collection}[${index}].${path.join(".")}`)})}}function redactOptionalIdentityCredentials(value){return typeof value=="string"?redactIdentityCredentials(value):value}const MIN_FRAGMENT_LENGTH=6,MAX_REGISTERED_FRAGMENTS=65536,NO_INVOCATION={carried:!1,fragments:new Set,fragmentLength:MIN_FRAGMENT_LENGTH,shortSpellings:[]},invocations=new AsyncLocalStorage;function lowerPreservingLength(text){const lowered=text.toLowerCase();if(lowered.length===text.length)return lowered;let result="";for(const unit of text){const lower=unit.toLowerCase();result+=lower.length===unit.length?lower:unit}return result}function spanSpellings(span){return[span,span.replaceAll(/(["\\$`])/gu,"\\$1"),quoteWindowsCommandArg(`${span}@`).slice(1,-2),JSON.stringify(span).slice(1,-1)]}function userinfoSecret(userinfo){const colon=userinfo.indexOf(":");return colon>=0&&colon<userinfo.length-1?userinfo.slice(colon+1):userinfo}function describeInvocation(argv){const unique=new Set;let carried=!1;for(const token of argv){const bounds=userinfoBounds(token);if(bounds){carried=!0;for(const spelling of spanSpellings(userinfoSecret(token.slice(bounds[0],bounds[1]))))unique.add(lowerPreservingLength(spelling))}}const spellings=[...unique],positions=spellings.reduce((total,spelling)=>total+Math.max(0,spelling.length-MIN_FRAGMENT_LENGTH+1)+1,0),stride=Math.max(1,Math.ceil(positions/MAX_REGISTERED_FRAGMENTS)),fragmentLength=Math.max(MIN_FRAGMENT_LENGTH,stride),fragments=new Set,shortSpellings=new Set;for(const spelling of spellings){if(spelling.length<fragmentLength){(spelling.length>=MIN_FRAGMENT_LENGTH||/\s/u.test(spelling))&&shortSpellings.add(spelling);continue}for(let index=0;index+fragmentLength<=spelling.length;index+=stride)fragments.add(spelling.slice(index,index+fragmentLength));fragments.add(spelling.slice(-fragmentLength))}return{carried,fragments,fragmentLength,shortSpellings:[...shortSpellings]}}function removeRegisteredFragments(text,invocation){const lowered=lowerPreservingLength(text),covered=new Uint8Array(text.length);let found=!1;const width=invocation.fragmentLength;for(let index=0;index+width<=lowered.length;index+=1)invocation.fragments.has(lowered.slice(index,index+width))&&(covered.fill(1,index,index+width),found=!0);for(const spelling of invocation.shortSpellings)for(let index=lowered.indexOf(spelling);index>=0;index=lowered.indexOf(spelling,index+1))covered.fill(1,index,index+spelling.length),found=!0;if(!found)return text;let result="";for(let index=0;index<text.length;index+=1)covered[index]?(index===0||!covered[index-1])&&(result+=URL_CREDENTIAL_PLACEHOLDER):result+=text[index];return result}function runWithUrlCredentialInvocation(argv,run){return invocations.run(describeInvocation(argv),run)}function invocationCarriesUrlCredentials(){return(invocations.getStore()??NO_INVOCATION).carried}function redactUrlCredentialsInText(text){const invocation=invocations.getStore()??NO_INVOCATION,redacted=invocation.carried?removeRegisteredFragments(text,invocation):text;return/@|%40/iu.test(redacted)?redacted.replaceAll(/\S+/gu,redactUrlCredentialsInToken):redacted}export{URL_CREDENTIAL_PLACEHOLDER,assertIdentityFieldsWithoutUrlCredentials,assertIdentityWithoutUrlCredentials,invocationCarriesUrlCredentials,parseIdentityOption,redactIdentityCredentials,redactIdentityFields,redactOptionalIdentityCredentials,redactUrlCredentialsInText,redactUrlCredentialsInToken,runWithUrlCredentialInvocation};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4252fc2e-3190-516e-a34b-0e2f6749be20")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{quoteWindowsCommandArg}from"./command-line.js";import{EXIT_CODE}from"./constants.js";import{PmCliError}from"./errors.js";const URL_CREDENTIAL_PLACEHOLDER="[redacted]";function provablyWithoutUserinfo(token,colon){if(/[\t\n\r]/u.test(token)||!/(?:^|[^A-Za-z0-9+.-])(?:https?|wss?|ftp)$/iu.test(token.slice(0,colon)))return!1;let authority=colon+1;for(;token[authority]==="/"||token[authority]==="\\";)authority+=1;const delimiter=token.indexOf("/",authority)-authority;if(delimiter<0)return!1;const authorityEnd=authority+delimiter;return!/[:@%]/u.test(token.slice(authority,authorityEnd))&&!/[:%]|[/\\][/\\]/u.test(token.slice(authorityEnd))}function userinfoBounds(token){const at=Math.max(token.lastIndexOf("@"),token.toLowerCase().lastIndexOf("%40")),colon=token.indexOf(":");if(at<0||colon<0||colon>at)return;let start=colon+1;for(;start<at&&start<colon+3&&(token[start]==="/"||token[start]==="\\");)start+=1;return start===at||provablyWithoutUserinfo(token,colon)?void 0:[start,at]}function redactUrlCredentialsInToken(token){const bounds=userinfoBounds(token);return bounds?`${token.slice(0,bounds[0])}${URL_CREDENTIAL_PLACEHOLDER}${token.slice(bounds[1])}`:token}function redactIdentityCredentials(identity){return redactUrlCredentialsInToken(identity)}const IDENTITY_FIELDS=["author","assignee","claim_principal"];function redactIdentityFields(values){const redacted={...values};for(const field of IDENTITY_FIELDS)typeof redacted[field]=="string"&&(redacted[field]=redactIdentityCredentials(redacted[field]));return redacted}function assertIdentityWithoutUrlCredentials(identity,source){if(!(typeof identity!="string"||userinfoBounds(identity.trim())===void 0))throw new PmCliError(`${source} must not carry URL credentials: an identity is a name, never a credential.`,EXIT_CODE.USAGE,{code:"invalid_argument_value",field:source,required:`Set ${source} to a plain name such as agent-a, without user:password@ or token@ userinfo.`,nextSteps:[`Rerun with ${source} set to a plain name.`]})}function parseIdentityOption(value,source){return assertIdentityWithoutUrlCredentials(value,source),value}const NESTED_IDENTITY_PATHS=[["comments","author"],["notes","author"],["learnings","author"],["dependencies","author"],["plan_decisions","author"],["plan_discoveries","author"],["plan_steps","owner"],["tests","provenance","author"],["tests","updated_by"]],IDENTITY_VALUE_DEPTH=4;function assertIdentityValueWithoutUrlCredentials(value,source,depth=0){if(typeof value=="string"){assertIdentityWithoutUrlCredentials(value,source);return}if(!(depth>=IDENTITY_VALUE_DEPTH||typeof value!="object"||value===null))for(const entry of Object.values(value))assertIdentityValueWithoutUrlCredentials(entry,source,depth+1)}function readEntryPath(entry,path){let node=entry;for(const key of path){if(typeof node!="object"||node===null||Array.isArray(node))return;node=node[key]}return node}function assertIdentityFieldsWithoutUrlCredentials(values){const record=values;for(const field of IDENTITY_FIELDS)assertIdentityValueWithoutUrlCredentials(record[field],field);for(const[collection,...path]of NESTED_IDENTITY_PATHS){const entries=record[collection];Array.isArray(entries)&&entries.forEach((entry,index)=>{assertIdentityValueWithoutUrlCredentials(readEntryPath(entry,path),`${collection}[${index}].${path.join(".")}`)})}}function redactOptionalIdentityCredentials(value){return typeof value=="string"?redactIdentityCredentials(value):value}const MIN_FRAGMENT_LENGTH=6,MAX_REGISTERED_FRAGMENTS=65536,NO_INVOCATION={carried:!1,fragments:new Set,fragmentLength:MIN_FRAGMENT_LENGTH,shortSpellings:[]},invocations=new AsyncLocalStorage;function lowerPreservingLength(text){const lowered=text.toLowerCase();if(lowered.length===text.length)return lowered;let result="";for(const unit of text){const lower=unit.toLowerCase();result+=lower.length===unit.length?lower:unit}return result}function spanSpellings(span){return[span,span.replaceAll(/(["\\$`])/gu,"\\$1"),quoteWindowsCommandArg(`${span}@`).slice(1,-2),JSON.stringify(span).slice(1,-1)]}function userinfoSecret(userinfo){const colon=userinfo.indexOf(":");return colon>=0&&colon<userinfo.length-1?userinfo.slice(colon+1):userinfo}function describeInvocation(argv){const unique=new Set;let carried=!1;for(const token of argv){const bounds=userinfoBounds(token);if(bounds){carried=!0;for(const spelling of spanSpellings(userinfoSecret(token.slice(bounds[0],bounds[1]))))unique.add(lowerPreservingLength(spelling))}}const spellings=[...unique],positions=spellings.reduce((total,spelling)=>total+Math.max(0,spelling.length-MIN_FRAGMENT_LENGTH+1)+1,0),stride=Math.max(1,Math.ceil(positions/MAX_REGISTERED_FRAGMENTS)),fragmentLength=Math.max(MIN_FRAGMENT_LENGTH,stride),fragments=new Set,shortSpellings=new Set;for(const spelling of spellings){if(spelling.length<fragmentLength){(spelling.length>=MIN_FRAGMENT_LENGTH||/\s/u.test(spelling))&&shortSpellings.add(spelling);continue}for(let index=0;index+fragmentLength<=spelling.length;index+=stride)fragments.add(spelling.slice(index,index+fragmentLength));fragments.add(spelling.slice(-fragmentLength))}return{carried,fragments,fragmentLength,shortSpellings:[...shortSpellings]}}function removeRegisteredFragments(text,invocation){const lowered=lowerPreservingLength(text),covered=new Uint8Array(text.length);let found=!1;const width=invocation.fragmentLength;for(let index=0;index+width<=lowered.length;index+=1)invocation.fragments.has(lowered.slice(index,index+width))&&(covered.fill(1,index,index+width),found=!0);for(const spelling of invocation.shortSpellings)for(let index=lowered.indexOf(spelling);index>=0;index=lowered.indexOf(spelling,index+1))covered.fill(1,index,index+spelling.length),found=!0;if(!found)return text;let result="";for(let index=0;index<text.length;index+=1)covered[index]?(index===0||!covered[index-1])&&(result+=URL_CREDENTIAL_PLACEHOLDER):result+=text[index];return result}function runWithUrlCredentialInvocation(argv,run){return invocations.run(describeInvocation(argv),run)}function invocationCarriesUrlCredentials(){return(invocations.getStore()??NO_INVOCATION).carried}function redactUrlCredentialsInText(text){const invocation=invocations.getStore()??NO_INVOCATION,redacted=invocation.carried?removeRegisteredFragments(text,invocation):text;return/@|%40/iu.test(redacted)?redacted.replaceAll(/\S+/gu,redactUrlCredentialsInToken):redacted}export{URL_CREDENTIAL_PLACEHOLDER,assertIdentityFieldsWithoutUrlCredentials,assertIdentityWithoutUrlCredentials,invocationCarriesUrlCredentials,parseIdentityOption,redactIdentityCredentials,redactIdentityFields,redactOptionalIdentityCredentials,redactUrlCredentialsInText,redactUrlCredentialsInToken,runWithUrlCredentialInvocation};
2
2
  //# sourceMappingURL=url-credentials.js.map