@unbrained/pm-cli 2026.10.17 → 2026.10.19

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 (256) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +35 -0
  3. package/dist/cli/help-content.js +2 -2
  4. package/dist/cli/register-list-query.js +2 -2
  5. package/dist/cli/register-mutation.js +2 -2
  6. package/dist/cli/register-setup.js +1 -1
  7. package/dist/cli-bundle/bundle-manifest.json +1 -1
  8. package/dist/cli-bundle/chunks/chunk-4CXQSRSP.js +126 -0
  9. package/dist/cli-bundle/chunks/{chunk-EA2CG7UM.js → chunk-4ICKT4GH.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-W3KZ22DW.js → chunk-4MJ6WBMA.js} +2 -2
  11. package/dist/cli-bundle/chunks/chunk-4XFVAXA4.js +2 -0
  12. package/dist/cli-bundle/chunks/{chunk-6ZDKKOKM.js → chunk-5GZSX5HU.js} +72 -66
  13. package/dist/cli-bundle/chunks/{chunk-3QKI3XNX.js → chunk-6DS5CAN2.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-B5QVGCZX.js → chunk-D3EDNAN7.js} +2 -2
  15. package/dist/cli-bundle/chunks/chunk-DMFM5R4G.js +3 -0
  16. package/dist/cli-bundle/chunks/chunk-H3XYP24A.js +70 -0
  17. package/dist/cli-bundle/chunks/chunk-LBEMB3BW.js +6 -0
  18. package/dist/cli-bundle/chunks/chunk-NX7Q4LGN.js +8 -0
  19. package/dist/cli-bundle/chunks/chunk-O2ZRRLAP.js +8 -0
  20. package/dist/cli-bundle/chunks/chunk-OEJ3G7XT.js +20 -0
  21. package/dist/cli-bundle/chunks/{chunk-O4YBC3OM.js → chunk-QBNEZII5.js} +30 -30
  22. package/dist/cli-bundle/chunks/chunk-QG4LMU7A.js +112 -0
  23. package/dist/cli-bundle/chunks/chunk-QKAAZWGC.js +3 -0
  24. package/dist/cli-bundle/chunks/chunk-RUKSEZE7.js +2 -0
  25. package/dist/cli-bundle/chunks/chunk-TK3G3GAP.js +2 -0
  26. package/dist/cli-bundle/chunks/chunk-VS565KBX.js +2 -0
  27. package/dist/cli-bundle/chunks/{chunk-JS3B2M4D.js → chunk-XH7C3A5N.js} +2 -2
  28. package/dist/cli-bundle/chunks/indexed-receipt-blobs-BVSHK4WQ.js +4 -0
  29. package/dist/cli-bundle/chunks/{register-list-query-RU3QZSAQ.js → register-list-query-WQUVDJIH.js} +7 -7
  30. package/dist/cli-bundle/chunks/register-mutation-IWIBQIO3.js +20 -0
  31. package/dist/cli-bundle/chunks/register-operations-SUWOZNDU.js +2 -0
  32. package/dist/cli-bundle/chunks/register-setup-QGM5YJW7.js +2 -0
  33. package/dist/cli-bundle/chunks/settlement-hook-UNFMCKKQ.js +7 -0
  34. package/dist/cli-bundle/chunks/stage-7DELI4Z5.js +2 -0
  35. package/dist/cli-bundle/focused-chunks/{chunk-LDKX4KYJ.js → chunk-2IEWB6MB.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/chunk-3TEIACFU.js +3 -0
  37. package/dist/cli-bundle/focused-chunks/chunk-5YTOYBTZ.js +65 -0
  38. package/dist/cli-bundle/focused-chunks/chunk-AK2CI2GI.js +2 -0
  39. package/dist/cli-bundle/focused-chunks/chunk-BJMPRB7A.js +91 -0
  40. package/dist/cli-bundle/focused-chunks/chunk-ENZMATOY.js +20 -0
  41. package/dist/cli-bundle/focused-chunks/chunk-EOQ6W25I.js +8 -0
  42. package/dist/cli-bundle/focused-chunks/{chunk-FTUZ3JF2.js → chunk-FEN7WOOP.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/chunk-FOA7XKWP.js +2 -0
  44. package/dist/cli-bundle/focused-chunks/chunk-GWTV45SB.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-SIGIGZCG.js → chunk-H6BVQ63U.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-RBLSY6ML.js → chunk-HYMYAGSY.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/chunk-JBJJW2WL.js +6 -0
  48. package/dist/cli-bundle/focused-chunks/chunk-JCLC6HKT.js +8 -0
  49. package/dist/cli-bundle/focused-chunks/{chunk-2IOHHNRT.js → chunk-JDBO7SMR.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-UNTQE37U.js → chunk-KLJN44VY.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/chunk-L4PL3GZR.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-OV2WVLUR.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/chunk-PXDR77TO.js +78 -0
  54. package/dist/cli-bundle/focused-chunks/chunk-RLRMNFLF.js +3 -0
  55. package/dist/cli-bundle/focused-chunks/{chunk-E33QA7PK.js → chunk-SKYLOPU2.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/chunk-VVRXF4JO.js +2 -0
  57. package/dist/cli-bundle/focused-chunks/chunk-WZTEFFQI.js +3 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-Y54ONBEX.js +25 -0
  59. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-QW2VWWJE.js +4 -0
  60. package/dist/cli-bundle/focused-chunks/settlement-hook-X4FNHTOD.js +7 -0
  61. package/dist/cli-bundle/focused-chunks/stage-MZSVQYO4.js +2 -0
  62. package/dist/cli-bundle/main.js +3 -3
  63. package/dist/cli-bundle/sdk-authoring.js +1 -1
  64. package/dist/cli-bundle/sdk-contracts.js +1 -1
  65. package/dist/cli-bundle/sdk-core.js +29 -23
  66. package/dist/cli-bundle/sdk-governance.js +1 -1
  67. package/dist/cli-bundle/sdk-graph.js +1 -1
  68. package/dist/cli-bundle/sdk-merge.js +66 -52
  69. package/dist/cli-bundle/sdk-query.js +1 -1
  70. package/dist/cli-bundle/sdk-runtime.js +1 -1
  71. package/dist/cli-bundle/sdk-testing.js +1 -1
  72. package/dist/cli-bundle/sdk.js +2 -2
  73. package/dist/core/history/event-index.d.ts +8 -1
  74. package/dist/core/history/event-index.js +19 -18
  75. package/dist/core/item/item-format.js +1 -1
  76. package/dist/core/lock/lock.d.ts +8 -1
  77. package/dist/core/lock/lock.js +3 -3
  78. package/dist/core/output/output.js +2 -2
  79. package/dist/core/store/paths.js +1 -1
  80. package/dist/core/telemetry/policy.d.ts +2 -0
  81. package/dist/core/telemetry/policy.js +1 -1
  82. package/dist/core/telemetry/runtime.d.ts +5 -3
  83. package/dist/core/telemetry/runtime.js +3 -3
  84. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  85. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  86. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  87. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +1 -0
  88. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  89. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  90. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  91. package/dist/sdk/extension/install-sources.js +3 -3
  92. package/dist/sdk/extension/shared.js +1 -1
  93. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  94. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  95. package/dist/sdk/governance/health/projection.d.ts +37 -0
  96. package/dist/sdk/governance/health/projection.js +2 -0
  97. package/dist/sdk/governance/health.d.ts +7 -18
  98. package/dist/sdk/governance/health.js +2 -2
  99. package/dist/sdk/history-repair.js +1 -1
  100. package/dist/sdk/merge/driver.js +7 -1
  101. package/dist/sdk/merge/indexed-receipt-blobs.d.ts +2 -0
  102. package/dist/sdk/merge/indexed-receipt-blobs.js +4 -0
  103. package/dist/sdk/merge/install.d.ts +8 -0
  104. package/dist/sdk/merge/install.js +3 -3
  105. package/dist/sdk/merge/receipts.d.ts +6 -0
  106. package/dist/sdk/merge/receipts.js +2 -2
  107. package/dist/sdk/merge/reconcile.d.ts +6 -0
  108. package/dist/sdk/merge/reconcile.js +1 -1
  109. package/dist/sdk/merge/settlement-hook.d.ts +12 -0
  110. package/dist/sdk/merge/settlement-hook.js +7 -0
  111. package/dist/sdk/merge/stage.d.ts +13 -0
  112. package/dist/sdk/merge/stage.js +2 -0
  113. package/dist/sdk/mutation-events.js +1 -1
  114. package/dist/sdk/public-surface.json +1 -1
  115. package/dist/sdk/query/list.d.ts +2 -0
  116. package/dist/sdk/query/list.js +1 -1
  117. package/dist/sdk/runtime-extended-actions.js +1 -1
  118. package/dist/types.d.ts +2 -2
  119. package/dist/types.js +1 -1
  120. package/docs/COMMANDS.md +39 -0
  121. package/docs/CONFIGURATION.md +36 -1
  122. package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +22 -3
  123. package/docs/MERGE_SAFETY.md +88 -5
  124. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +10 -0
  125. package/docs/RELEASING.md +8 -1
  126. package/docs/SDK.md +26 -0
  127. package/docs/SDK_CONTEXT_COORDINATION.md +71 -7
  128. package/docs/SDK_STORAGE_LIFECYCLE.md +24 -2
  129. package/docs/TESTING.md +15 -0
  130. package/docs/examples/ci/github-actions-pm-extension-gate.yml +1 -1
  131. package/docs/examples/ci/gitlab-ci-pm-extension-gate.yml +1 -1
  132. package/docs/examples/ci/jenkins-pm-extension-gate.Jenkinsfile +1 -1
  133. package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
  134. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
  135. package/marketplace.json +1 -1
  136. package/node_modules/@opentelemetry/core/package.json +2 -1
  137. package/node_modules/@opentelemetry/instrumentation/package.json +2 -1
  138. package/node_modules/@opentelemetry/resources/package.json +2 -1
  139. package/node_modules/@opentelemetry/sdk-trace/package.json +2 -1
  140. package/node_modules/@opentelemetry/sdk-trace-base/package.json +2 -1
  141. package/node_modules/@sentry/core/build/cjs/client.js +5 -4
  142. package/node_modules/@sentry/core/build/cjs/tracing/ai/gen-ai-attributes.js +0 -4
  143. package/node_modules/@sentry/core/build/cjs/tracing/ai/utils.js +33 -23
  144. package/node_modules/@sentry/core/build/cjs/tracing/anthropic-ai/index.js +7 -6
  145. package/node_modules/@sentry/core/build/cjs/tracing/anthropic-ai/streaming.js +3 -1
  146. package/node_modules/@sentry/core/build/cjs/tracing/google-genai/index.js +13 -14
  147. package/node_modules/@sentry/core/build/cjs/tracing/google-genai/streaming.js +6 -1
  148. package/node_modules/@sentry/core/build/cjs/tracing/langchain/utils.js +71 -21
  149. package/node_modules/@sentry/core/build/cjs/tracing/langgraph/utils.js +23 -33
  150. package/node_modules/@sentry/core/build/cjs/tracing/openai/streaming.js +6 -0
  151. package/node_modules/@sentry/core/build/cjs/tracing/openai/utils.js +11 -0
  152. package/node_modules/@sentry/core/build/cjs/tracing/workers-ai/utils.js +1 -1
  153. package/node_modules/@sentry/core/build/cjs/utils/eventUtils.js +4 -0
  154. package/node_modules/@sentry/core/build/cjs/utils/prepareEvent.js +2 -2
  155. package/node_modules/@sentry/core/build/cjs/utils/version.js +1 -1
  156. package/node_modules/@sentry/core/build/esm/client.js +6 -5
  157. package/node_modules/@sentry/core/build/esm/package.json +1 -1
  158. package/node_modules/@sentry/core/build/esm/tracing/ai/gen-ai-attributes.js +1 -3
  159. package/node_modules/@sentry/core/build/esm/tracing/ai/utils.js +34 -24
  160. package/node_modules/@sentry/core/build/esm/tracing/anthropic-ai/index.js +8 -7
  161. package/node_modules/@sentry/core/build/esm/tracing/anthropic-ai/streaming.js +3 -1
  162. package/node_modules/@sentry/core/build/esm/tracing/google-genai/index.js +15 -16
  163. package/node_modules/@sentry/core/build/esm/tracing/google-genai/streaming.js +6 -1
  164. package/node_modules/@sentry/core/build/esm/tracing/langchain/utils.js +73 -24
  165. package/node_modules/@sentry/core/build/esm/tracing/langgraph/utils.js +24 -34
  166. package/node_modules/@sentry/core/build/esm/tracing/openai/streaming.js +6 -0
  167. package/node_modules/@sentry/core/build/esm/tracing/openai/utils.js +11 -0
  168. package/node_modules/@sentry/core/build/esm/tracing/workers-ai/utils.js +2 -2
  169. package/node_modules/@sentry/core/build/esm/utils/eventUtils.js +4 -1
  170. package/node_modules/@sentry/core/build/esm/utils/prepareEvent.js +2 -2
  171. package/node_modules/@sentry/core/build/esm/utils/version.js +1 -1
  172. package/node_modules/@sentry/core/build/types/tracing/ai/utils.d.ts +3 -7
  173. package/node_modules/@sentry/core/build/types/tracing/anthropic-ai/types.d.ts +2 -2
  174. package/node_modules/@sentry/core/build/types/tracing/langchain/types.d.ts +15 -0
  175. package/node_modules/@sentry/core/build/types/tracing/langchain/utils.d.ts +1 -0
  176. package/node_modules/@sentry/core/build/types/tracing/langgraph/utils.d.ts +2 -0
  177. package/node_modules/@sentry/core/build/types/tracing/openai/types.d.ts +2 -0
  178. package/node_modules/@sentry/core/build/types/utils/eventUtils.d.ts +2 -1
  179. package/node_modules/@sentry/core/build/types-ts3.8/tracing/ai/utils.d.ts +3 -7
  180. package/node_modules/@sentry/core/build/types-ts3.8/tracing/anthropic-ai/types.d.ts +2 -2
  181. package/node_modules/@sentry/core/build/types-ts3.8/tracing/langchain/types.d.ts +15 -0
  182. package/node_modules/@sentry/core/build/types-ts3.8/tracing/langchain/utils.d.ts +1 -0
  183. package/node_modules/@sentry/core/build/types-ts3.8/tracing/langgraph/utils.d.ts +2 -0
  184. package/node_modules/@sentry/core/build/types-ts3.8/tracing/openai/types.d.ts +2 -0
  185. package/node_modules/@sentry/core/build/types-ts3.8/utils/eventUtils.d.ts +2 -1
  186. package/node_modules/@sentry/core/package.json +1 -1
  187. package/node_modules/@sentry/node/build/esm/package.json +1 -1
  188. package/node_modules/@sentry/node/package.json +5 -5
  189. package/node_modules/@sentry/node-core/build/cjs/integrations/anr/index.js +1 -1
  190. package/node_modules/@sentry/node-core/build/cjs/integrations/local-variables/local-variables-async.js +1 -1
  191. package/node_modules/@sentry/node-core/build/esm/integrations/anr/index.js +1 -1
  192. package/node_modules/@sentry/node-core/build/esm/integrations/anr/worker-script.js +2 -2
  193. package/node_modules/@sentry/node-core/build/esm/integrations/local-variables/local-variables-async.js +1 -1
  194. package/node_modules/@sentry/node-core/build/esm/integrations/local-variables/worker-script.js +1 -1
  195. package/node_modules/@sentry/node-core/build/esm/package.json +1 -1
  196. package/node_modules/@sentry/node-core/package.json +10 -4
  197. package/node_modules/@sentry/opentelemetry/build/esm/package.json +1 -1
  198. package/node_modules/@sentry/opentelemetry/package.json +5 -2
  199. package/node_modules/@sentry/server-utils/build/THIRD-PARTY-LICENSES.txt +55 -55
  200. package/node_modules/@sentry/server-utils/build/esm/package.json +1 -1
  201. package/node_modules/@sentry/server-utils/package.json +2 -2
  202. package/node_modules/@toon-format/toon/README.md +10 -41
  203. package/node_modules/@toon-format/toon/dist/index.d.mts +12 -36
  204. package/node_modules/@toon-format/toon/dist/index.mjs +134 -202
  205. package/node_modules/@toon-format/toon/package.json +2 -2
  206. package/node_modules/debug/package.json +3 -0
  207. package/node_modules/fdir/package.json +3 -0
  208. package/node_modules/has-flag/index.d.ts +39 -0
  209. package/node_modules/has-flag/index.js +8 -0
  210. package/node_modules/has-flag/license +9 -0
  211. package/node_modules/has-flag/package.json +46 -0
  212. package/node_modules/has-flag/readme.md +89 -0
  213. package/node_modules/supports-color/browser.js +5 -0
  214. package/node_modules/supports-color/index.js +135 -0
  215. package/node_modules/supports-color/license +9 -0
  216. package/node_modules/supports-color/package.json +53 -0
  217. package/node_modules/supports-color/readme.md +76 -0
  218. package/package.json +4 -4
  219. package/packages/pm-beads/package.json +1 -1
  220. package/packages/pm-calendar/package.json +1 -1
  221. package/packages/pm-command-kit/package.json +1 -1
  222. package/packages/pm-digital-twin/package.json +1 -1
  223. package/packages/pm-governance-audit/package.json +1 -1
  224. package/packages/pm-guide-shell/package.json +1 -1
  225. package/packages/pm-kanban/package.json +1 -1
  226. package/packages/pm-lifecycle-hooks/package.json +1 -1
  227. package/packages/pm-linked-test-adapters/package.json +1 -1
  228. package/packages/pm-search-advanced/package.json +1 -1
  229. package/packages/pm-templates/package.json +1 -1
  230. package/packages/pm-todos/package.json +1 -1
  231. package/packages/pm-vcs/package.json +1 -1
  232. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  233. package/plugins/pm-claude/package.json +1 -1
  234. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  235. package/plugins/pm-codex/package.json +1 -1
  236. package/plugins/pm-codex/plugin.json +1 -1
  237. package/runtime-dependencies.json +1 -1
  238. package/dist/cli-bundle/chunks/chunk-4PNPDT2N.js +0 -236
  239. package/dist/cli-bundle/chunks/chunk-HY7FQ7QX.js +0 -2
  240. package/dist/cli-bundle/chunks/chunk-J4LPQCET.js +0 -8
  241. package/dist/cli-bundle/chunks/chunk-OZCSXX4D.js +0 -80
  242. package/dist/cli-bundle/chunks/chunk-VMCSTFSO.js +0 -2
  243. package/dist/cli-bundle/chunks/chunk-X2ONXFBP.js +0 -3
  244. package/dist/cli-bundle/chunks/chunk-X53HM753.js +0 -20
  245. package/dist/cli-bundle/chunks/register-mutation-EQYMT32A.js +0 -20
  246. package/dist/cli-bundle/chunks/register-operations-VXBGE4XI.js +0 -2
  247. package/dist/cli-bundle/chunks/register-setup-UUDEGFRO.js +0 -2
  248. package/dist/cli-bundle/focused-chunks/chunk-5JEFDEL3.js +0 -166
  249. package/dist/cli-bundle/focused-chunks/chunk-AH6NX6GM.js +0 -3
  250. package/dist/cli-bundle/focused-chunks/chunk-JXR6UKFM.js +0 -3
  251. package/dist/cli-bundle/focused-chunks/chunk-MBQF6HT6.js +0 -2
  252. package/dist/cli-bundle/focused-chunks/chunk-NZO7GOXD.js +0 -20
  253. package/dist/cli-bundle/focused-chunks/chunk-PYC7BF6Z.js +0 -8
  254. package/dist/cli-bundle/focused-chunks/chunk-QOSVJDOO.js +0 -75
  255. package/dist/cli-bundle/focused-chunks/chunk-RHTH5ILM.js +0 -2
  256. package/dist/cli-bundle/focused-chunks/chunk-TRFVAWF2.js +0 -26
@@ -0,0 +1,78 @@
1
+ import{c as ze,e as Fe,f as $e,h as Ln,i as Hn,j as zn,k as Fn,l as $n,m as Mn}from"./chunk-RLRMNFLF.js";import{h as Jn}from"./chunk-YLVHHWHN.js";import{B as An,Cd as qn,Dc as Wn,Dd as Gn,Ea as jn,Ed as Bn,Fa as T,Fd as V,Ga as M,Ha as ot,Ia as y,ae as Kt,ea as Dn,i as Qe,j as kn,ja as Pn,k as Sn,l as In,lc as Vn,m as On,nc as it,q as et,r as tt,rc as Un,s as Tn,vd as Me,wd as q,x as rt,xd as st,y as nt,yd as Ee,z as Bt,za as we,zd as G}from"./chunk-Y54ONBEX.js";import{B as Cn,C as se,D as ae,E as J,F as Nn,G as Jt,H as He,I as Rn,l as B,t as xn,w as p,x as Le,y as w,z as b}from"./chunk-3TEIACFU.js";import{AsyncLocalStorage as fs}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1fbb183b-c6d8-5834-b4cb-e4fb515572b9")}catch{}})();var Xt=new fs,Kn=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function at(e,t){let r=typeof e=="string"?e.trim():"";return r.length>0?r.slice(0,t):void 0}function ce(e,t){if(e===void 0)return;let r=typeof e=="object"&&e!==null?e:{},n=at(r.id,128),o=at(r.parent_id,128);if(n===void 0||!Kn.test(n)||o!==void 0&&!Kn.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=at(r.label,256);return{id:n,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function ke(e){let t={};for(let[r,n]of Object.entries(e??{}).slice(0,32)){let o=r.trim().toLowerCase().slice(0,64),i=at(n,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function ms(e,t,r){let n=Xt.getStore(),o=ke({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=ce(t.PM_AGENT_EPISODE_ID===void 0?void 0:{id:t.PM_AGENT_EPISODE_ID,label:t.PM_AGENT_EPISODE_LABEL,parent_id:t.PM_AGENT_EPISODE_PARENT_ID},!1),s={...ke(n?.provenance),...o,...ke(e?.provenance)},a=ce(e?.episode,!1)??ce(r,!1)??i??ce(n?.episode,!1);return Object.keys(s).length===0&&a===void 0?void 0:{...Object.keys(s).length===0?{}:{provenance:s},...a===void 0?{}:{episode:a}}}function Yt(e,t){return ms(e.session_context,t,e.client_info?.episode)??{}}function Ul(e,t){let r=Xt.getStore(),n=ce(e.episode,!0),o=ce(r?.episode,!1),i=n!==void 0&&n.parent_id===void 0&&o!==void 0?{...n,parent_id:o.id}:n,s={...ke(r?.provenance),...ke(e.provenance)};return Xt.run({...Object.keys(s).length===0?{}:{provenance:s},...i===void 0?o===void 0?{}:{episode:o}:{episode:i}},t)}function Wl(e){let t=ke(e.provenance),r=ce(e.episode,!0);return{...r===void 0?{}:{PM_AGENT_EPISODE_ID:r.id,...r.label===void 0?{}:{PM_AGENT_EPISODE_LABEL:r.label},...r.parent_id===void 0?{}:{PM_AGENT_EPISODE_PARENT_ID:r.parent_id}},...t.role===void 0?{}:{PM_AGENT_SESSION_ROLE:t.role},...t.topic===void 0?{}:{PM_AGENT_SESSION_TOPIC:t.topic}}}import{AsyncLocalStorage as lr}from"node:async_hooks";import{createHash as vs}from"node:crypto";import P from"node:fs";import oo from"node:os";import ue from"node:path";import{createHash as Xn}from"node:crypto";import{existsSync as Zt,promises as Yn,readFileSync as ps}from"node:fs";import U from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="06c9f6f4-c2f0-549c-9a0f-4f4269cc5f49")}catch{}})();var hs="session.json";function Qt(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function Zn(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,r=["implementer","planner","release-operator"].includes(String(t.role)),n=["high","medium"].includes(String(t.confidence)),o=Qt(t.topic,256),i=Array.isArray(t.evidence)&&t.evidence.length<=32&&t.evidence.every(d=>typeof d=="string"&&d.length<=128),s=Array.isArray(t.active_item_ids)&&t.active_item_ids.length<=64&&t.active_item_ids.every(d=>Qt(d,128)),a=t.focused_item_id===void 0||Qt(t.focused_item_id,128);if([r,n,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function ys(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=Object.entries(e).slice(0,128).flatMap(([r,n])=>{let o=Zn(n);return o&&r.length<=128?[[r,o]]:[]});return t.length>0?Object.fromEntries(t):void 0}function er(e){return U.join(jn(e),hs)}async function Qn(e){try{let t=await Yn.readFile(er(e),"utf8"),r=JSON.parse(t);if(r===null||typeof r!="object"||Array.isArray(r))return{};let n=r,o=n.focused_item,i=ys(n.semantic_attribution);return typeof o=="string"&&o.trim().length>0?{focused_item:o,...i?{semantic_attribution:i}:{}}:i?{semantic_attribution:i}:{}}catch{return{}}}async function tr(e,t){let r=await V(e,"session-state",p.locks.ttl_seconds,"session-state",!1,!0,p.locks.wait_ms);try{let n=await Qn(e);t(n);let o=er(e);await Yn.mkdir(U.dirname(o),{recursive:!0}),await He(o,JSON.stringify(n))}finally{await r()}}function rr(e){return/#([a-f0-9]{24})$/u.exec(e.trim())?.[1]??`author-${Xn("sha256").update(e).digest("hex").slice(0,24)}`}function nr(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].slice(0,32).map(t=>t.slice(0,128))}function or(e){let t=[...new Set(e)].sort((n,o)=>n.localeCompare(o));if(t.length===1)return t[0];let r=`workset:${t.join("+")}`;return r.length<=256?r:`workset:${t.join("+").slice(0,230)}+${Xn("sha256").update(t.join("\0")).digest("hex").slice(0,12)}`}async function ir(e,t,r){await tr(e,n=>{let o={...n.semantic_attribution},i=r(o[t]);i===void 0?delete o[t]:o[t]=i,Object.keys(o).length===0?delete n.semantic_attribution:n.semantic_attribution=o})}async function Ql(e){let t=rr(e.principal);await ir(e.pmRoot,t,r=>{let n=[...new Set([...r?.active_item_ids??[],e.itemId])].slice(-64).sort((i,s)=>i.localeCompare(s)),o=r?.focused_item_id;return{role:"implementer",topic:o??or(n),confidence:o?"high":"medium",rule_version:"v2",evidence:nr([...n.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:n,...o?{focused_item_id:o}:{}}})}async function eu(e){let t=rr(e.principal);await ir(e.pmRoot,t,r=>{if(!r)return;let n=r.active_item_ids.filter(i=>i!==e.itemId);if(n.length===0&&!r.focused_item_id)return;let o=r.focused_item_id;return{...r,role:"release-operator",topic:o??or(n),confidence:o?"high":"medium",evidence:nr([...n.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],`release:${e.itemId}`]),active_item_ids:n}})}async function tu(e){let t=rr(e.principal);await ir(e.pmRoot,t,r=>{let n=r?.active_item_ids??[];if(!e.itemId&&n.length===0)return;let o=e.itemId;return{role:o?"planner":r.role,topic:o??or(n),confidence:o?"high":"medium",rule_version:"v2",evidence:nr([...n.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:n,...o?{focused_item_id:o}:{}}})}function gs(e,t){let r=t.PM_PATH?.trim();if(r){let o=U.resolve(e,r);if(Zt(U.join(o,"settings.json")))return o;let i=U.join(o,".agents","pm");if(Zt(U.join(i,"settings.json")))return i}let n=U.resolve(e);for(let o=0;o<32;o+=1){let i=U.join(n,".agents","pm");if(Zt(U.join(i,"settings.json")))return i;let s=U.dirname(n);if(s===n)break;n=s}}function eo(e){if(!e.key)return;let t=gs(e.cwd,e.env);if(t)try{let r=JSON.parse(ps(er(t),"utf8"));return Zn(r.semantic_attribution?.[e.key])}catch{return}}async function ru(e){return(await Qn(e)).focused_item}async function nu(e,t){await tr(e,r=>{r.focused_item=t})}async function ou(e){await tr(e,t=>{delete t.focused_item})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a69b86e2-6633-5abc-81b7-6a54a592d36c")}catch{}})();var ur=["model","effort","role","topic","version"],lt=new lr,io=new lr,ut=new lr,_r=[{harness:"claude-code",environment_keys:["CLAUDE_CODE","CLAUDECODE"],model_environment_keys:["ANTHROPIC_MODEL","CLAUDE_MODEL"],session_environment_keys:["CLAUDE_CODE_SESSION_ID"],provenance_environment_keys:{effort:["CLAUDE_EFFORT"]},provenance_resolvers:{model:"claude_session_file",version:"claude_session_file"},provenance_unavailable_dimensions:["role","topic"],argv_markers:["claude","claude-code"],client_names:["claude","claude-code","claude code"]},{harness:"codex",environment_keys:["CODEX_HOME","CODEX_CI","CODEX_THREAD_ID"],model_environment_keys:["CODEX_MODEL"],session_environment_keys:["CODEX_THREAD_ID"],provenance_environment_keys:{effort:["CODEX_REASONING_EFFORT","CODEX_EFFORT"],role:["CODEX_SESSION_ROLE"]},provenance_resolvers:{model:"codex_session_file",effort:"codex_session_file",version:"ai_agent_version"},provenance_unavailable_dimensions:["topic"],argv_markers:["codex"],client_names:["codex"]},{harness:"pi",environment_keys:["PI_AGENT","PI_CODING_AGENT"],model_environment_keys:["PI_MODEL"],session_environment_keys:["PI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["pi"],client_names:["pi"]},{harness:"opencode",environment_keys:["OPENCODE","OPENCODE_SESSION_ID"],model_environment_keys:["OPENCODE_MODEL"],session_environment_keys:["OPENCODE_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["opencode"],client_names:["opencode"]},{harness:"cursor",environment_keys:["CURSOR_AGENT","CURSOR_TRACE_ID"],model_environment_keys:["CURSOR_MODEL"],session_environment_keys:["CURSOR_TRACE_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["cursor"],client_names:["cursor"]},{harness:"aider",environment_keys:["AIDER","AIDER_MODEL"],model_environment_keys:["AIDER_MODEL"],session_environment_keys:["AIDER_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["aider"],client_names:["aider"]},{harness:"gemini-cli",environment_keys:["GEMINI_CLI","GEMINI_CLI_HOME"],model_environment_keys:["GEMINI_MODEL"],session_environment_keys:["GEMINI_CLI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["gemini","gemini-cli"],client_names:["gemini","gemini-cli","gemini cli"]},{harness:"ci",environment_keys:["CI","GITHUB_ACTIONS","BUILDKITE","GITLAB_CI"],provenance_unavailable_dimensions:["model","effort","role","topic"],argv_markers:[],client_names:[]}],so=Object.freeze({max_bytes:1048576,max_lines:4096,network_access:!1,subprocess_access:!1}),bs=Object.freeze({...so,max_bytes:4194304}),sr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function ws(e){let t=X(e).provenance_unavailable_dimensions,r=new Set(["model","version",...Object.keys(e.provenance_environment_keys??{}),...Object.keys(e.provenance_resolvers??{})]);return Object.freeze({contract_version:1,adapter_version:"v1",priority:0,harness:e.harness,descriptor:e,supported_dimensions:Object.freeze([...r].sort()),native_sources:Object.freeze(["environment","argv","mcp_client",...Object.values(e.provenance_resolvers??{}).some(n=>n?.endsWith("session_file"))?["session_file"]:[]]),probe_policy:e.harness==="codex"?bs:so,normalization:Object.freeze({model_family:"v1",effort:"v1",preserve_raw:!0}),confidence:"high",waivers:Object.freeze(Object.fromEntries(t.map(n=>[n,"Harness does not expose this dimension."])))})}var ao=Object.freeze(_r.filter(e=>e.harness!=="ci").map(ws).sort((e,t)=>e.harness.localeCompare(t.harness))),le=new Map,Se=new Map;function C(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function K(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function X(e){let t=e.harness.trim().toLowerCase();if(!sr.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:K(e.environment_keys),model_environment_keys:K(e.model_environment_keys),session_environment_keys:K(e.session_environment_keys),provenance_environment_keys:Object.fromEntries(Object.entries(e.provenance_environment_keys??{}).slice(0,32).map(([r,n])=>[r.trim().toLowerCase().slice(0,64),K(n)]).filter(([r])=>sr.test(r))),provenance_resolvers:Object.fromEntries(Object.entries(e.provenance_resolvers??{}).slice(0,32).map(([r,n])=>[r.trim().toLowerCase().slice(0,64),n]).filter(r=>typeof r[0]=="string"&&sr.test(r[0])&&(r[1]==="ai_agent_version"||r[1]==="claude_session_file"||r[1]==="codex_session_file"))),provenance_unavailable_dimensions:K(e.provenance_unavailable_dimensions).map(r=>r.toLowerCase()),argv_markers:K(e.argv_markers).map(r=>r.toLowerCase()),client_names:K(e.client_names).map(r=>r.toLowerCase())}}var co=_r.map(X);function Es(e,t){return JSON.stringify(e)===JSON.stringify(t)}function dt(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(r=>r.length>0).includes(t)||e.trim().toLowerCase()===t}function fr(e=[]){let t=new Map(_r.filter(o=>o.harness!=="ci").map(o=>[o.harness,X(o)]));for(let{adapter:o}of le.values())t.set(o.harness,X(o.descriptor));let r=[...t.values(),...co.filter(o=>o.harness==="ci"),...[...Se.values()].map(o=>o.descriptor),...ut.getStore()?.descriptors??[],...e.map(X)],n=new Set;for(let o of r){if(n.has(o.harness))throw new Error(`Harness signal descriptor collision for "${o.harness}"`);n.add(o.harness)}return r}function mr(e,t){for(let r of t??[]){let n=C(e[r]);if(n)return n.slice(0,256)}}function ks(e,t){if(t==="role"){let r=e.slice(0,8).map(n=>n.trim().toLowerCase()).find(n=>["claim","create","update","close","release","review"].includes(n));if(r==="review")return"reviewer";if(r)return"implementer"}}function lo(e,t){let r=t==="model"?["--model","--agent-model"]:[`--agent-${t}`],n=e.slice(0,8);for(let o=0;o<n.length;o+=1){let i=n[o].slice(0,512);if(r.includes(i))return C(n[o+1])?.slice(0,256);let s=r.find(a=>i.startsWith(`${a}=`));if(s)return C(i.slice(s.length+1))?.slice(0,256)}}var Ss=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function de(e,t){if(e!=="role"||t===void 0)return t;let r=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return Ss.has(r)?r:void 0}function ar(e,t){return C(e?.[t])?.slice(0,256)}var Is=1048576,dr=4194304,ct=new Map,to=Object.freeze({}),cr=new Map,ro=Object.freeze({});function no(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Os(e){let t;try{t=JSON.parse(e)}catch{return ro}let r=no(t);if(!r)return ro;let n=[{value:r,depth:0}],o=0,i,s;for(;n.length>0&&o<64;){let a=n.shift();if(o+=1,i??=C(a.value.model)?.slice(0,256),s??=C(a.value.version)?.slice(0,256),i&&s)break;if(!(a.depth>=4))for(let d of Object.values(a.value)){let l=no(d);l&&n.push({value:l,depth:a.depth+1})}}return Object.freeze({model:i,version:s})}function uo(e){try{return P.lstatSync(e).isFile()?"available":"missing"}catch(t){return se(t)?"missing":"failed"}}function Ts(e,t){let r;try{r=P.readdirSync(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).sort((o,i)=>o.name.localeCompare(i.name)).slice(0,512).map(o=>{let i=ue.join(e,o.name,`${t}.jsonl`);return{candidate:i,status:uo(i)}})}catch(o){return{status:se(o)?"missing":"failed"}}let n=r.filter(({status:o})=>o==="available").map(({candidate:o})=>o);return n.length===0?{status:r.some(({status:o})=>o==="failed")?"failed":"missing"}:n.length>1?{status:"ambiguous"}:{status:"available",path:n[0]}}function _o(e,t){let r=C(t.CLAUDE_CODE_SESSION_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return{status:"unavailable"};let n=ue.resolve(e.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),o=ue.join(e.home_dir??oo.homedir(),".claude","projects"),i=ue.join(o,n,`${r}.jsonl`),s=C(e.session_file),a=s&&ue.basename(s)===`${r}.jsonl`?s:void 0;for(let d of[a,i]){if(!d)continue;let l=uo(d);if(l==="available")return{status:l,path:d};if(l==="failed")return{status:l}}return Ts(o,r)}function As(e,t,r){let n=_o(t,r);if(n.status==="available")try{let o=P.openSync(n.path,P.constants.O_RDONLY|P.constants.O_NOFOLLOW);try{let i=P.fstatSync(o),s=`${n.path}\0${i.size}\0${i.mtimeMs}`,a=cr.get(s);if(a)return a[e];let d=Math.min(i.size,Is),l=Math.min(d,Math.ceil(d/2)),_=Math.min(d-l,i.size-l),v=Buffer.alloc(l);P.readSync(o,v,0,l,0);let O=Buffer.alloc(_);_>0&&P.readSync(o,O,0,_,i.size-_);let S={},I=i.size<=d?Buffer.concat([v,O]).toString("utf8").split(`
2
+ `):[...v.toString("utf8").split(`
3
+ `).slice(0,4096),...O.toString("utf8").split(`
4
+ `).slice(-4096)];for(let D of I){if(D.length===0||D.length>262144)continue;let $=Os(D);if(S.model??=$.model,S.version??=$.version,S.model&&S.version)break}let z=Object.freeze(S);return cr.clear(),cr.set(s,z),z[e]}finally{P.closeSync(o)}}catch{return}}function xs(e,t){let r=0,n=(o,i)=>{if(i>4||r>=512)return;let s;try{s=P.readdirSync(o,{withFileTypes:!0}).sort((a,d)=>d.name.localeCompare(a.name))}catch{return}for(let a of s){if(r+=1,r>512)return;let d=ue.join(o,a.name);if(a.isFile()&&a.name.endsWith(`-${t}.jsonl`))return d;if(a.isDirectory()){let l=n(d,i+1);if(l)return l}}};return n(e,0)}function Cs(e){if(e<=dr)return[{offset:0,length:e}];let t=Math.floor(dr/2);return[{offset:e-t,length:t},{offset:0,length:t}]}function Ns(e,t){if(t.length===0||t.length>262144)return;let r;try{r=JSON.parse(t)}catch{return}if(typeof r!="object"||r===null||Array.isArray(r))return;let n=r;if(n.type!=="turn_context")return;let o=typeof n.payload=="object"&&n.payload!==null?n.payload:void 0;e.model??=C(o?.model)?.slice(0,256),e.effort??=C(o?.effort)?.slice(0,256)}function Rs(e,t){let r={},n=4096;for(let o of Cs(t)){let i=Buffer.alloc(o.length);P.readSync(e,i,0,o.length,o.offset);let s=i.toString("utf8").split(`
5
+ `).reverse().slice(0,n);n-=s.length;for(let a of s)if(Ns(r,a),r.model&&r.effort)break;if(r.model&&r.effort||n<=0)break}return r}function Ds(e,t,r){let n=C(r.CODEX_THREAD_ID);if(!n||!/^[A-Za-z0-9_-]{1,128}$/u.test(n))return;let o=ue.join(t.home_dir??oo.homedir(),".codex","sessions"),i=`${o}\0${n}`,s=ct.get(i);if(s)return s[e];let a=xs(o,n);if(!a){ct.set(i,to);return}try{let d=P.openSync(a,"r");try{let l=P.fstatSync(d).size,_=Rs(d,l);return ct.set(i,_),_[e]}finally{P.closeSync(d)}}catch{ct.set(i,to);return}}function Ps(e,t,r,n){let o=ut.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(C(r.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let i=n?.provenance_resolvers[e];if(i==="claude_session_file")return As(e,t,r);if(i==="codex_session_file")return Ds(e,t,r);if(i==="ai_agent_version"){let s=C(r.AI_AGENT);return!s||!n||!dt(s,n.harness)?void 0:/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(s)?.[1]?.slice(0,256)}}function js(e,t,r,n){if(e==="ai_agent_version"){let o=C(n.AI_AGENT);return o!==void 0&&dt(o,t.harness)?"available":"unavailable"}return e==="codex_session_file"?C(n.CODEX_THREAD_ID)!==void 0?"available":"unavailable":_o(r,n).status}function pr(e){return e||(io.getStore()??{env:process.env,argv:process.argv})}function Ls(e,t,r,n){let o=e.environment_keys.some(a=>C(t[a])!==void 0),i=e.argv_markers.some(a=>r.some(d=>{let l=d.replaceAll("\\","/");return dt(l.slice(l.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>n===a||dt(n,a));return o||i||s}function Hs(e,t){if(!t)return;let r;if(e==="topic"&&(r=t.topic),e==="role"&&(r=t.role),!!r)return{value:r,source:"inferred",confidence:t.confidence,rule_version:t.rule_version,evidence:t.evidence}}function zs(e){let t=e.find(([r])=>r!==void 0);return t?.[0]?{value:t[0],source:t[1]}:void 0}function Fs(e,t,r,n,o,i){let s=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,a=new Set([...ur,...Object.keys(n?.provenance_environment_keys??{})]),d,l,_;a.has(e)&&(d=de(e,C(r[s])?.slice(0,256)),_=de(e,lo(t.argv??[],e)),l=de(e,ks(t.argv??[],e)));let v={...n?.provenance_environment_keys,model:n?.model_environment_keys},O={...t.client_info?.provenance,model:t.client_info?.model},S=ar(o?.provenance,e),I=de(e,mr(r,v[e])),z=de(e,ar(O,e)),D=de(e,ar(t.provenance,e)),$=Ps(e,t,r,n);return zs([[d,"override"],[S,"session"],[_,"argv"],[I,"environment"],[z,"mcp_client"],[D,"host"],[$,"probe"]])??Hs(e,i)??(l?{value:l,source:"argv"}:void 0)}function $s(e,t){if(!(!e||!t))return vs("sha256").update(`pm-agent-instance:v1\0${e}\0${t}`).digest("hex").slice(0,24)}function Ms(e,t,r,n,o){let i=Object.keys(r?.provenance_environment_keys??{}),s=new Set([...ur,...i,...Object.keys(r?.provenance_resolvers??{}),...Object.keys(e.provenance??{}),...Object.keys(e.client_info?.provenance??{}),...Object.keys(n?.provenance??{})]),a={};for(let d of s){let l=Fs(d,e,t,r,n,o);l?a[d]=l:r&&(d!=="version"||r.provenance_unavailable_dimensions.includes(d))&&(a[d]=null)}return a}function mu(e){let t=e.map(X),r=new Map(co.map(i=>[i.harness,i])),n=new Set;for(let i of t){if(n.has(i.harness)||r.has(i.harness))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);let s=Se.get(i.harness);if(s&&!Es(s.descriptor,i))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);n.add(i.harness)}for(let i of t){let s=Se.get(i.harness);Se.set(i.harness,{descriptor:i,registrations:(s?.registrations??0)+1})}let o=!0;return()=>{if(o){o=!1;for(let i of t){let s=Se.get(i.harness);!s||s.registrations<=1?Se.delete(i.harness):s.registrations-=1}}}}function Vs(e){let t=X(e.descriptor),r=e.harness.trim().toLowerCase();if(e.contract_version!==1)throw new Error(`Unsupported provenance adapter contract for "${r}": ${e.contract_version}`);if(t.harness!==r)throw new Error(`Provenance adapter harness "${r}" does not match descriptor "${t.harness}".`);let n=C(e.adapter_version)?.slice(0,64);if(!n)throw new Error(`Provenance adapter "${r}" requires a version.`);if(!Number.isSafeInteger(e.priority))throw new Error(`Provenance adapter "${r}" requires an integer priority.`);if(e.probe_policy.network_access!==!1||e.probe_policy.subprocess_access!==!1||e.probe_policy.max_bytes>dr||e.probe_policy.max_lines>4096)throw new Error(`Provenance adapter "${r}" exceeds the bounded local probe policy.`);return Object.freeze({...e,adapter_version:n,harness:r,descriptor:t,supported_dimensions:Object.freeze(K(e.supported_dimensions).map(o=>o.toLowerCase()).sort()),native_sources:Object.freeze([...new Set(e.native_sources)]),probe_policy:Object.freeze({...e.probe_policy}),normalization:Object.freeze({...e.normalization}),...e.waivers?{waivers:Object.freeze(Object.fromEntries(Object.entries(e.waivers).slice(0,32).map(([o,i])=>[o.slice(0,64),i.slice(0,256)])))}:{}})}function pu(){let e=new Map(ao.map(t=>[t.harness,t]));for(let{adapter:t}of le.values())e.set(t.harness,t);return Object.freeze([...e.values()].sort((t,r)=>t.harness.localeCompare(r.harness)))}function hu(e){let t=e.map(Vs),r=new Map(ao.map(i=>[i.harness,i])),n=new Set;for(let i of t){if(n.has(i.harness))throw new Error(`Provenance adapter collision for "${i.harness}".`);let s=r.get(i.harness);if(s&&i.priority<=s.priority)throw new Error(`Provenance adapter override for "${i.harness}" requires priority greater than ${s.priority}.`);let a=le.get(i.harness);if(a&&JSON.stringify(a.adapter)!==JSON.stringify(i))throw new Error(`Provenance adapter collision for "${i.harness}".`);n.add(i.harness)}for(let i of t){let s=le.get(i.harness);le.set(i.harness,{adapter:i,registrations:(s?.registrations??0)+1})}let o=!0;return()=>{if(o){o=!1;for(let i of t){let s=le.get(i.harness);!s||s.registrations<=1?le.delete(i.harness):s.registrations-=1}}}}function yu(e,t){let r=t.trim().slice(0,256),n=r.toLowerCase();if(e==="model"){let o=/^(gpt-\d+(?:\.\d+)?)/u.exec(n)?.[1];o&&(n=o)}else n=n.replaceAll(/[_\s-]+/gu,""),n={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max",ultra:"ultra"}[n]??n;return{raw:r,normalized:n,vocabulary:"v1"}}function gu(e,t){return io.run(e,t)}function vu(e,t,r={}){let n=e.map(X);return fr(n),ut.run({descriptors:n,probesEnabled:r.probesEnabled!==!1},t)}function hr(e){let t=pr(e),r=t.env??{},n=fr(t.descriptors),o=[...(t.argv??[]).slice(0,3),...t.process_labels??[]].slice(0,64).map(I=>I.slice(0,512)),i=t.client_info?.name.trim().toLowerCase()??"",s=n.find(I=>Ls(I,r,o,i)),a=Yt(t,r),d=[mr(r,s?.session_environment_keys),C(t.client_info?.session)?.slice(0,256)].find(I=>I!==void 0),l=$s(s?.harness,d),_=eo({cwd:t.cwd??process.cwd(),env:r,key:l}),v=Ms(t,r,s,a,_),O=v.model,S=[["harness",s?.harness],["model",O?.value],["model_source",O?.source],["session",d],["instance",l],["provenance",Object.keys(v).length>0?v:void 0],["episode",a.episode]];return Object.fromEntries(S.filter(I=>I[1]!==void 0))}function Us(e){return e==="unavailable"?{status:"unavailable",reason:"harness_unavailable"}:e==="missing"?{status:"unavailable",reason:"resolver_input_missing"}:{status:"failed",reason:"resolver_failed"}}function Ws(e,t,r,n,o,i,s){let a=r?.provenance_resolvers[e];if(t.provenance?.[e])return{status:"resolved",...a?{resolver:a}:{},rule_version:"v1"};if(s)return{status:"unavailable",reason:"invalid_value",rule_version:"v1"};if(a){if(!i)return{status:"unavailable",reason:"probes_disabled",resolver:a,rule_version:"v1"};let d=js(a,r,n,o);return{...Us(d),resolver:a,rule_version:"v1"}}return{status:r?.provenance_unavailable_dimensions.includes(e)?"unavailable":"not_configured",reason:r?.provenance_unavailable_dimensions.includes(e)?"harness_unavailable":"resolver_not_configured",rule_version:"v1"}}function fo(e){let t=pr(e),r=hr(t),n=fr(t.descriptors).find(l=>l.harness===r.harness),o=t.env??{},i=t.probes_enabled!==!1&&ut.getStore()?.probesEnabled!==!1&&!["0","false","off"].includes(C(o.PM_AGENT_PROBES)?.toLowerCase()??""),s=Yt(t,o),a=[o.PM_AGENT_ROLE,s.provenance?.role,mr(o,n?.provenance_environment_keys.role),t.client_info?.provenance?.role,t.provenance?.role,lo(t.argv??[],"role")].some(l=>{let _=C(l)?.slice(0,256);return _!==void 0&&de("role",_)===void 0}),d=Object.fromEntries(ur.map(l=>[l,Ws(l,r,n,t,o,i,l==="role"&&a)]));return{...r,provenance_outcomes:d}}function bu(){return process.env.PM_AUTHOR}function wu(e){e===void 0?delete process.env.PM_AUTHOR:process.env.PM_AUTHOR=e}function Eu(e){return hr(e).harness}function qs(e,t,r){let n=pr(r),o=hr(n);if(e!==void 0){let s=C(e);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(n.env?.PM_AUTHOR!==void 0){let s=C(n.env.PM_AUTHOR);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=C(t);return i?{author:i,source:"configured",...o}:o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function mo(e){let t=lt.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function po(e){let t=lt.getStore();return t?.author!==e?e.startsWith("harness:")?{harness:e.slice(8)}:{}:{...t.harness?{harness:t.harness}:{},...t.model?{model:t.model}:{},...t.model_source?{model_source:t.model_source}:{},...t.session?{session:t.session}:{},...t.instance?{instance:t.instance}:{},...t.provenance?{provenance:t.provenance}:{},...t.episode?{episode:t.episode}:{}}}function ku(e){let t=lt.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function ho(e,t){let r=qs(e,t);return lt.enterWith(r),r.author}import{createHash as Gs}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ca5b60a5-80a7-5e7d-917f-4c7649bcbab6")}catch{}})();var Ou=["sha256","sha512"],Bs="sha256",yo="sha256";function _e(e){if(e===void 0)return Bs;if(e==="sha256"||e==="sha512")return e;throw new TypeError(`unsupported_history_hash_algorithm:${String(e)}`)}function Y(e,t){return Gs(_e(t)).update(e,"utf8").digest("hex")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c35d4830-d7d1-5ee4-99bc-ab52cc3e4e09")}catch{}})();var yr=1,gr=2;function Au(e){return Math.max(vr(e),e.tests?.some(t=>t.updated_by!==void 0||t.updated_at!==void 0)?2:1)}function vr(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=1?t:1}function go(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=1))return e}function Js(e,t=2,r=t){return e<r?"outdated":e>t?"ahead":"current"}function xu(e,t=2,r=t){let n=[],o=[];for(let i of e){let s=Js(i.version,t,r);s==="outdated"?n.push(i.ref):s==="ahead"&&o.push(i.ref)}return{outdated:n.sort((i,s)=>i.localeCompare(s)),ahead:o.sort((i,s)=>i.localeCompare(s))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="515840b7-cf86-5d71-8ac1-beac7fd7c8a8")}catch{}})();var Ks={"in-progress":"in_progress",cancelled:"canceled"};function _t(e,t){if(t){let o=Fn(e,t);if(o)return o}if(typeof e!="string")return;let r=e.trim().toLowerCase();if(!r)return;let n=Ks[r]??r;if(Qe.includes(n))return n}function Xs(e,t){return _t(e,t)??e}function Du(e,t){return t.terminal_statuses.has(Xs(e,t))}import{encode as da}from"@toon-format/toon";import{isDeepStrictEqual as ko}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d5692ce-ec33-5eb4-bd9b-7497ffe25b0e")}catch{}})();var Ys=16;function br(e){let t=e.trim().replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(o=>o.length>0).map(o=>o.toLowerCase());if(t.length===0)return e;let[r,...n]=t;return`${r}${n.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function Zs(e){return[...new Set([Mn(e),br(e.key),br(e.cli_flag),...e.cli_aliases.map(t=>br(t))])]}function wo(e,t){for(let r of Zs(t)){if(!Object.hasOwn(e,r))continue;let n=e[r];if(n!==void 0)return n}}function Eo(e){return Array.isArray(e)?e.flatMap(t=>Eo(t)).map(t=>t.trim()).filter(t=>t.length>0):typeof e=="string"?e.split(/[,\n|]/).map(t=>t.trim()).filter(t=>t.length>0):e==null?[]:[String(e).trim()].filter(t=>t.length>0)}function vo(e,t){if(typeof e=="boolean")return e;if(typeof e=="number"){if(e===1)return!0;if(e===0)return!1}if(typeof e=="string"){let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1}throw new b(`${t} must be one of true|false|1|0|yes|no`,w.USAGE)}function bo(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;let r=typeof e=="string"?e.trim():String(e),n=Number(r);if(!Number.isFinite(n))throw new b(`${t} must be a number`,w.USAGE);return n}function Qs(e,t,r){let n=typeof e=="string"?(()=>{try{return JSON.parse(e)}catch{return}})():e;if(r==="array"&&Array.isArray(n)||r==="object"&&typeof n=="object"&&n!==null&&!Array.isArray(n))return n;throw new b(`${t} must be valid JSON ${r}`,w.USAGE)}function ea(e,t){return t===void 0?!0:t==="array"?Array.isArray(e):t==="object"?typeof e=="object"&&e!==null&&!Array.isArray(e):typeof e===t}function ta(e,t,r){if(t.const!==void 0&&T(e)!==T(t.const))return`${r} must equal ${T(t.const)}`;if(t.enum!==void 0&&!t.enum.some(n=>T(n)===T(e)))return`${r} must be one of ${t.enum.map(n=>T(n)).join("|")}`;if(!ea(e,t.type))return`${r} must match configured type ${String(t.type)}`;if(typeof e=="string"){if(t.min_length!==void 0&&e.length<t.min_length)return`${r} must contain at least ${t.min_length} characters`;if(t.format==="date-time"&&!st(e))return`${r} must be an RFC 3339 date-time`}}function ra(e,t,r,n){if(Array.isArray(e)){if(t.min_items!==void 0&&e.length<t.min_items)return`${r} must contain at least ${t.min_items} items`;if(t.items)for(let[o,i]of e.entries()){let s=ft(i,t.items,`${r}[${o}]`,n+1);if(s)return s}}}function na(e,t,r,n){if(typeof e!="object"||e===null||Array.isArray(e))return;let o=e;for(let i of t.required??[])if(!Object.hasOwn(o,i))return`${r}.${i} is required`;for(let[i,s]of Object.entries(o)){let a=t.properties?.[i];if(!a){if(t.additional_properties===!1)return`${r}.${i} is not allowed`;continue}let d=ft(s,a,`${r}.${i}`,n+1);if(d)return d}}function ft(e,t,r,n=0){if(n>Ys)return`${r} value schema exceeds maximum depth`;let o=ta(e,t,r);if(o)return o;let i=ra(e,t,r,n);if(i)return i;let s=na(e,t,r,n);if(s)return s;if(!t.one_of)return;let a=0;for(let d of t.one_of)if(ft(e,d,r,n+1)===void 0&&(a+=1,a>1))break;return a===1?void 0:`${r} must match exactly one configured schema variant`}function fe(e,t,r){if(!e.value_schema||t===void 0)return t;let n=ft(t,e.value_schema,r);if(n)throw new b(n,w.USAGE);return t}function oa(e,t,r,n){let o=n==="option"&&Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return fe(e,Qs(o,r,e.type),r)}function Ve(e,t,r,n="option"){let o=r??`--${e.cli_flag}`;if(e.type==="array"||e.type==="object")return oa(e,t,o,n);if(e.repeatable||e.type==="string_array"){let s=Eo(t);return e.type==="number"?fe(e,s.map(a=>bo(a,o)),o):e.type==="boolean"?fe(e,s.map(a=>vo(a,o)),o):fe(e,s,o)}let i=Array.isArray(t)?t[t.length-1]:t;if(i!==void 0)return e.type==="number"?fe(e,bo(i,o),o):e.type==="boolean"?fe(e,vo(i,o),o):fe(e,typeof i=="string"?i:String(i),o)}function ia(e,t){return!e.required&&!e.required_on_create?!1:e.required_types.length===0?!0:t?e.required_types.map(r=>r.toLowerCase()).includes(t.trim().toLowerCase()):!1}function $u(e,t,r){let n={},o=[];for(let i of t.command_to_fields.get("create")??[]){let s=wo(e,i);if(s===void 0){ia(i,r)&&o.push(`--${i.cli_flag}`);continue}n[i.metadata_key]=Ve(i,s)}return{values:n,missing_required_flags:[...new Set(o)].sort((i,s)=>i.localeCompare(s))}}function Mu(e,t,r=["update"]){let n={},o=(r??["update"]).flatMap(s=>t.command_to_fields.get(s)??[]),i=new Set;for(let s of o){let a=wo(e,s);a!==void 0&&(i.has(s.metadata_key)||(i.add(s.metadata_key),n[s.metadata_key]=Ve(s,a)))}return n}import{decode as sa}from"@toon-format/toon";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aaa2be03-9478-5fbe-82e6-e4fc86e3735b")}catch{}})();function wr(e){return{value:sa(e),usedScalarBracketEscape:!1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="79626299-17a8-573a-9b66-ce37c65e2f5d")}catch{}})();var aa=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function ca(e){if(e.length===0)return[];let t=e.split(/\r?\n/),r=[];for(let n=0;n<t.length;n+=1){let o=t[n]??"",i=o.match(aa);if(!i)continue;let s=i[1];r.push({line:n+1,marker:s,text:o})}return r}function mt(e){return ca(e)[0]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2789e87f-0706-52e8-8f4c-3855c65c618c")}catch{}})();var Ir=new Set(["schema","tracker","auto","none"]),Ao=new Set(["source","isolated","snapshot"]),la=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),ua=new Set(["passed","failed","stopped","canceled"]),_a=new Set(An);function Te(e){return e.replaceAll("\\","/")}function xo(e){for(let t of e)if(t!==0)return t;return 0}function ht(e){for(let[t,r]of Object.entries(e))r===void 0&&delete e[t]}var Co=["id","title","description","created_at","updated_at"],fa=new Set(B);function No(e){if(e?.schema)return{statusRegistry:zn(e.schema),fieldRegistry:$n(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function ma(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(r=>r.toLowerCase()).includes(t.trim().toLowerCase()):!1}function Z(e){let t=e.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new b(`Invalid item metadata: ${e}`,w.GENERIC_FAILURE,{code:"item_document_invalid",reason:e.includes("required")?"missing_required_field":"schema_validation_error",...t?{field:t}:{},required:"Provide an item document whose metadata satisfies the active runtime schema.",why:e})}function qe(e,t){throw new b(t,w.GENERIC_FAILURE,{code:"item_document_invalid",reason:"syntax_error",format:e,required:`Provide a syntactically valid ${e==="toon"?"TOON":"JSON Markdown"} item document.`,why:"The document could not be decoded far enough to validate item metadata."})}function Ro(e,t){if(!t||typeof e!="object"||e===null)return;let r=vr(e);if(!(r<=gr))throw new b(`Stored item uses format version ${r}; this runtime supports up to ${gr}. Upgrade pm before reading or changing this item.`,w.CONFLICT,{code:"item_format_version_unsupported",format_version:r,required:"Upgrade to a pm runtime supporting the stored item format.",nextSteps:["Preserve the original item and history; do not lower pm_format_version to bypass compatibility checks."]})}function Do(e){let t=new Set(fa);for(let r of e.fieldRegistry?.definitions??[])t.add(r.metadata_key);for(let r of e.extensionFieldNames)t.add(r);return t}function h(e,t){e||Z(t)}function Ge(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&Z(t),e}function Er(e,t){let r=e[t];h(typeof r=="string",`${t} must be a string`),h(q(r),`${t} must be a valid ISO timestamp`)}function So(e,t,r){let n=e[t];n!==void 0&&h(typeof n=="number"&&Number.isInteger(n)&&n>=1,`${r} must be an integer >= 1`)}function Or(e,t,r){let n=e[t];n!==void 0&&(h(typeof n=="string",`${r} must be a string`),h(q(n),`${r} must be a valid ISO timestamp`))}function pa(e){if(e!==void 0){h(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(let t of e){h(typeof t=="string","event.recurrence.by_weekday entries must be strings");let r=t.trim().toLowerCase();h(nt.includes(r),`event.recurrence.by_weekday entries must be one of: ${nt.join(", ")}`)}}}function ha(e){if(e!==void 0){h(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(let t of e)h(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function ya(e){if(e!==void 0){h(Array.isArray(e),"event.recurrence.exdates must be an array");for(let t of e)h(typeof t=="string","event.recurrence.exdates entries must be strings"),h(q(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function ga(e){let t=Ge(e,"event.recurrence must be an object");h(typeof t.freq=="string","event.recurrence.freq must be a string");let r=t.freq.trim().toLowerCase();h(rt.includes(r),`event.recurrence.freq must be one of: ${rt.join(", ")}`),So(t,"interval","event.recurrence.interval"),So(t,"count","event.recurrence.count"),Or(t,"until","event.recurrence.until"),pa(t.by_weekday),ha(t.by_month_day),ya(t.exdates)}function va(e){for(let n of Co)h(typeof e[n]=="string",`${n} is required and must be a string`);let t=e.type;h(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");let r=e.pm_format_version;return r!==void 0&&h(typeof r=="number"&&Number.isInteger(r)&&r>=yr,`pm_format_version must be an integer >= ${yr}`),t}function ba(e,t){let r=e.status;h(typeof r=="string"&&r.trim().length>0,"status must be a non-empty string");let n=t?.statusRegistry,o=_t(r,n),i=n?n.definitions.map(s=>s.id):[...Qe];h(o!==void 0,`status must be one of: ${i.join(", ")}`)}function wa(e){let t=e.priority;h(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");let r=e.tags;h(Array.isArray(r),"tags must be an array");for(let n of r)h(typeof n=="string","tags entries must be strings")}function Ea(e){let t=e.confidence;if(t!==void 0){if(typeof t=="number"){h(Number.isInteger(t)&&t>=0&&t<=100,"confidence number value must be an integer 0..100");return}if(typeof t=="string"){let r=t.trim().toLowerCase(),n=r==="med"||tt.includes(r);h(n,`confidence string value must be one of: ${[...tt,"med"].join(", ")}`);return}h(!1,"confidence must be a number or string")}}function ka(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&Z("severity must be a string");let r=t.trim().toLowerCase(),n=r==="med"||et.includes(r);h(n,`severity value must be one of: ${[...et,"med"].join(", ")}`)}function Sa(e){e.regression!==void 0&&typeof e.regression!="boolean"&&Z("regression must be a boolean")}function Ia(e){let t=e.reminders;if(t!==void 0){h(Array.isArray(t),"reminders must be an array");for(let r of t){let n=Ge(r,"reminders entries must be objects");h(typeof n.at=="string","reminder.at must be a string"),h(q(n.at),"reminder.at must be a valid ISO timestamp"),h(typeof n.text=="string","reminder.text must be a string"),h(n.text.trim().length>0,"reminder.text must not be empty")}}}function Oa(e){for(let t of["title","description","location","timezone"])e[t]!==void 0&&(h(typeof e[t]=="string",`event.${t} must be a string`),h(e[t].trim().length>0,`event.${t} must not be empty`))}function Ta(e){e.recurrence!==void 0&&(ga(e.recurrence),e.recurrence.until!==void 0&&h(G(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function Aa(e){let t=Ge(e,"events entries must be objects");h(typeof t.start_at=="string","event.start_at must be a string"),h(q(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(h(typeof t.end_at=="string","event.end_at must be a string"),h(q(t.end_at),"event.end_at must be a valid ISO timestamp"),h(G(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),Oa(t),t.all_day!==void 0&&h(typeof t.all_day=="boolean","event.all_day must be a boolean"),Ta(t)}function xa(e){let t=e.events;if(t!==void 0){h(Array.isArray(t),"events must be an array");for(let r of t)Aa(r)}}function Ca(e){for(let t of["source_type","source_owner","design","external_ref"]){let r=e[t];r!==void 0&&h(typeof r=="string",`${t} must be a string`)}}function Na(e){let t=e.type_options;if(t===void 0)return;let r=Ge(t,"type_options must be an object");for(let[n,o]of Object.entries(r))h(n.trim().length>0,"type_options keys must be non-empty"),h(typeof o=="string","type_options values must be strings"),h(o.trim().length>0,"type_options values must be non-empty strings")}function Ra(e,t,r){if(r?.fieldRegistry)for(let n of r.fieldRegistry.definitions){let o=e[n.metadata_key];if(o===void 0){ma(n,t)&&Z(`missing required schema field: ${n.metadata_key}`);continue}try{e[n.metadata_key]=Ve(n,o,`metadata field "${n.metadata_key}"`,"metadata")}catch(i){Z(String(i?.message).replace(/^Invalid\s+/u,""))}}}function Da(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let r=Do(t),n=Object.keys(e).filter(o=>!r.has(o)).sort((o,i)=>o.localeCompare(i));n.length!==0&&(t.unknownFieldPolicy==="reject"?Z(`unknown schema fields are not allowed: ${n.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${n.join(",")}`))}function Tr(e,t){let r=Ge(e,"item metadata must be an object"),n=va(r);ba(r,t),wa(r),Ea(r),ka(r),Sa(r),Er(r,"created_at"),Er(r,"updated_at"),r.deadline!==void 0&&Er(r,"deadline"),Ia(r),xa(r),Or(r,"closed_at","closed_at"),Or(r,"completed_at","completed_at"),Ca(r),Na(r),Ra(r,n,t),Da(r,t)}function Pa(e){if(!(!e||e.length===0))return[...e].map((t,r)=>(h(t.created_at===void 0||typeof t.created_at=="string"&&st(t.created_at),`dependencies.${r}.created_at requires a valid timestamp; restore the dependency timestamp from its source record`),{id:t.id.trim(),kind:t.kind,created_at:t.created_at,author:t.author?.trim()||void 0,source_kind:t.source_kind?.trim()||void 0,author_source:t.author_source})).sort((t,r)=>{let n=G(t.created_at??"",r.created_at??"");if(n!==0)return n;let o=t.id.localeCompare(r.id);if(o!==0)return o;let i=t.kind.localeCompare(r.kind);return i!==0?i:(t.source_kind??"").localeCompare(r.source_kind??"")})}function kr(e){if(!(!e||e.length===0))return[...e].sort((t,r)=>{let n=G(t.created_at,r.created_at);if(n!==0)return n;let o=t.text.localeCompare(r.text);return o!==0?o:t.author.localeCompare(r.author)})}function ja(e){if(!e||e.length===0)return;let t=[...e].map(r=>({at:r.at,text:r.text.trim()})).filter(r=>r.text.length>0).sort((r,n)=>{let o=G(r.at,n.at);return o!==0?o:r.text.localeCompare(n.text)});return t.length===0?void 0:t}function La(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!rt.includes(t))return;let r=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>nt.includes(s)))).sort((s,a)=>Bt(s)-Bt(a)),n=Array.from(new Set((e.by_month_day??[]).filter(s=>Number.isInteger(s)&&s>=1&&s<=31).map(s=>s))).sort((s,a)=>s-a),o=Array.from(new Set((e.exdates??[]).map(s=>s.trim()).filter(s=>q(s)))).sort((s,a)=>G(s,a)),i={freq:t,interval:e.interval!==void 0&&e.interval>1?e.interval:void 0,count:e.count,until:e.until?.trim()||void 0,by_weekday:r.length>0?r:void 0,by_month_day:n.length>0?n:void 0,exdates:o.length>0?o:void 0};for(let[s,a]of Object.entries(i))a===void 0&&delete i[s];return i}function Ha(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(za).sort(Fa)}function za(e){let t={start_at:e.start_at,end_at:e.end_at||void 0,title:e.title?.trim()||void 0,description:e.description?.trim()||void 0,location:e.location?.trim()||void 0,all_day:e.all_day,timezone:e.timezone?.trim()||void 0,recurrence:La(e.recurrence)};return ht(t),t}function Fa(e,t){return xo([G(e.start_at,t.start_at),(e.end_at??"").localeCompare(t.end_at??""),(e.title??"").localeCompare(t.title??""),+!!e.all_day-+!!t.all_day,(e.timezone??"").localeCompare(t.timezone??""),(e.location??"").localeCompare(t.location??""),(e.description??"").localeCompare(t.description??""),JSON.stringify(e.recurrence??{}).localeCompare(JSON.stringify(t.recurrence??{}))])}function $a(e){if(!(!e||e.length===0))return e.map(t=>({path:Te(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function Ma(e){if(!e||e.length===0)return;let t=e.map(qa).filter(r=>r.run_id.length>0&&r.started_at.length>0&&r.finished_at.length>0&&r.recorded_at.length>0).sort((r,n)=>xo([G(r.recorded_at,n.recorded_at),r.run_id.localeCompare(n.run_id),r.kind.localeCompare(n.kind)]));return t.length>0?t:void 0}function Ie(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function Va(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function Sr(e){return typeof e=="string"?e:""}function Ua(e){if(!Array.isArray(e))return;let t=e.filter(n=>n!==null&&typeof n=="object"&&typeof n.name=="string"&&n.name.trim().length>0&&typeof n.value=="number"&&Number.isFinite(n.value)&&typeof n.recorded_at=="string"&&n.recorded_at.trim().length>0).map(n=>({name:n.name.trim(),value:n.value,unit:typeof n.unit=="string"&&n.unit.trim()||void 0,threshold:typeof n.threshold=="number"&&Number.isFinite(n.threshold)?n.threshold:void 0,recorded_at:n.recorded_at.trim()})),r=[...new Map(t.map(n=>[n.name,n])).values()].sort((n,o)=>n.name.localeCompare(o.name)).slice(0,32);return r.length>0?r:void 0}function pt(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function Wa(e){if(!Array.isArray(e))return;let t=e.filter(r=>r&&typeof r.command=="string"&&r.command.trim().length>0).slice(0,32).map(r=>({command:r.command.trim(),requested_pm_context_mode:pt(r.requested_pm_context_mode,Ir),pm_context_mode:pt(r.pm_context_mode,Ir),workspace_context_mode:pt(r.workspace_context_mode,Ao),trust_reason:pt(r.trust_reason,la)}));return t.length>0?t:void 0}function qa(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",r=e.kind==="test"||e.kind==="test-all"?e.kind:"test",n=ua.has(e.status)?e.status:"failed",o={run_id:t,kind:r,status:n,started_at:Sr(e.started_at),finished_at:Sr(e.finished_at),recorded_at:Sr(e.recorded_at),attempt:Va(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:Ie(e.passed)??0,failed:Ie(e.failed)??0,skipped:Ie(e.skipped)??0,items:Ie(e.items),linked_tests:Ie(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:Ua(e.measurements),executions:Wa(e.executions)};return ht(o),o}function Ga(e){if(!(!Array.isArray(e)||e.length===0))return e.map(Ya)}function Ue(e){if(!Array.isArray(e))return;let t=[...new Set(e.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0))].sort((r,n)=>r.localeCompare(n));return t.length>0?t:void 0}function Nr(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Rr(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function Io(e){if(!Nr(e))return;let t=Object.entries(e).map(([r,n])=>[r.trim(),String(n).trim()]).filter(([r,n])=>r.length>0&&!Rr(r)&&n.length>0).sort(([r],[n])=>r.localeCompare(n));return t.length>0?Object.fromEntries(t):void 0}function Ba(e){if(!Nr(e))return;let t=Object.entries(e).map(([r,n])=>[r.trim(),Number(n)]).filter(([r,n])=>r.length>0&&!Rr(r)&&Number.isFinite(n)).sort(([r],[n])=>r.localeCompare(n));return t.length>0?Object.fromEntries(t):void 0}function Ja(e){let t=e?.trim().toLowerCase();if(!(!t||!Ir.has(t)))return t}function Ka(e){let t=e?.trim().toLowerCase();if(!(!t||!Ao.has(t)))return t}function Xa(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!Nr(e))return{provenance_invalid:!0};let r=f(e.author),n=f(e.created_at),o=e.source_kind;return!r||!n||!q(n)||o!=="local_mutation"&&o!=="merge_union"?{provenance_invalid:!0}:{provenance:{author:r,created_at:n,source_kind:o,source_ref:f(e.source_ref)}}}function Ya(e){let t={command:e.command?.trim()||void 0,path:e.path?Te(e.path):void 0,scope:e.scope,timeout_seconds:typeof e.timeout_seconds=="number"&&Number.isFinite(e.timeout_seconds)&&e.timeout_seconds>0?e.timeout_seconds:void 0,pm_context_mode:Ja(e.pm_context_mode),workspace_context_mode:Ka(e.workspace_context_mode),...Xa(e.provenance,e.provenance_invalid),updated_by:f(e.updated_by),updated_at:f(e.updated_at),env_set:Io(e.env_set),env_clear:Ue(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:Ue(e.assert_stdout_contains),assert_stdout_regex:Ue(e.assert_stdout_regex),assert_stderr_contains:Ue(e.assert_stderr_contains),assert_stderr_regex:Ue(e.assert_stderr_regex),assert_stdout_min_lines:Ie(e.assert_stdout_min_lines),assert_json_field_equals:Io(e.assert_json_field_equals),assert_json_field_gte:Ba(e.assert_json_field_gte),note:e.note?.trim()||void 0};return ht(t),t}function Za(e){if(!(!e||e.length===0))return[...e].map(t=>({path:Te(t.path),scope:t.scope,note:t.note?.trim()||void 0})).sort((t,r)=>{let n=t.scope.localeCompare(r.scope);if(n!==0)return n;let o=t.path.localeCompare(r.path);return o!==0?o:(t.note??"").localeCompare(r.note??"")})}function f(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Qa(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=f(n.id),i=f(n.kind);if(!o||!i)continue;let s={id:o,kind:i},a=f(n.note);a&&(s.note=a),n.required_before_step===!0&&(s.required_before_step=!0),t.push(s)}return t.length>0?t:void 0}function ec(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=f(n.path);if(!o)continue;let i={path:Te(o)};(n.scope==="project"||n.scope==="global")&&(i.scope=n.scope);let s=f(n.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function tc(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=f(n.command),i=f(n.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=Te(i));let a=f(n.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function rc(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=f(n.path);if(!o)continue;let i={path:Te(o)};(n.scope==="project"||n.scope==="global")&&(i.scope=n.scope);let s=f(n.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function nc(e){if(e===null||typeof e!="object")return;let t=e,r=f(t.id),n=f(t.title),o=f(t.status),i=o&&_a.has(o)?o:void 0,s=Dn(t.order)??Number.NaN,a=typeof t.created_at=="string"?t.created_at:"",d=typeof t.updated_at=="string"?t.updated_at:"";if(!r||!n||!i||!Number.isFinite(s)||!a||!d)return;let l={id:r,order:s,title:n,status:i,created_at:a,updated_at:d};return oc(l,t),l}function oc(e,t){let r=[["body","body"],["owner","owner"],["evidence","evidence"],["blocked_reason","blocked_reason"],["superseded_by","superseded_by"]];for(let[i,s]of r){let a=f(t[s]);a&&(e[i]=a)}let n=typeof t.completed_at=="string"?t.completed_at:void 0;n&&n.length>0&&(e.completed_at=n);let o=[["linked_items","linked_items",Qa],["files","files",ec],["tests","tests",tc],["docs","docs",rc]];for(let[i,s,a]of o){let d=a(t[s]);d&&(e[i]=d)}}function ic(e){if(!Array.isArray(e))return;let t=e.flatMap(r=>{let n=nc(r);return n?[n]:[]});return t.sort((r,n)=>r.order-n.order),t.length>0?t:void 0}function sc(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=typeof n.ts=="string"?n.ts:"",i=typeof n.author=="string"?n.author:"",s=f(n.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},d=f(n.rationale);d&&(a.rationale=d);let l=f(n.evidence);l&&(a.evidence=l);let _=f(n.step_id);_&&(a.step_id=_),t.push(a)}return t.length>0?t:void 0}function ac(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=typeof n.ts=="string"?n.ts:"",i=typeof n.author=="string"?n.author:"",s=f(n.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},d=f(n.step_id);d&&(a.step_id=d),t.push(a)}return t.length>0?t:void 0}function cc(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=f(n.text);if(!o)continue;let i={text:o},s=f(n.command);s&&(i.command=s);let a=f(n.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function dc(e){if(!e)return;let t=Object.entries(e).map(([r,n])=>[r.trim(),n.trim()]).filter(([r,n])=>r.length>0&&n.length>0).sort((r,n)=>r[0].localeCompare(n[0]));if(t.length!==0)return Object.fromEntries(t)}function Oe(e){let t=0;for(;t<e.length&&e[t]===`
6
+ `;)t+=1;return e.slice(t).trimEnd()}function lc(e){if(e===void 0)return;if(typeof e=="number")return e;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(tt.includes(t))return t}function uc(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(et.includes(t))return t}function We(e){return e||void 0}function _c(e,t){let r=e,n=t;for(let[o,i]of Object.entries(n))Rr(o)||Object.prototype.hasOwnProperty.call(r,o)||i===void 0||(r[o]=i)}function fc(e,t){if(!t?.fieldRegistry)return;let r=e;for(let n of t.fieldRegistry.definitions){let o=r[n.metadata_key];o!==void 0&&(r[n.metadata_key]=Ve(n,o,`metadata field "${n.metadata_key}"`,"metadata"))}}function mc(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let r=Do(t),n=Object.keys(e).filter(o=>!r.has(o)).sort((o,i)=>o.localeCompare(i));n.length>0&&t.unknownFieldPolicy==="reject"&&Z(`unknown schema fields are not allowed: ${n.join(", ")}`),n.length>0&&t.onWarning?.(`item_unknown_schema_fields:${n.join(",")}`)}function yt(e,t={}){let r=No(t),n=_t(e.status,r?.statusRegistry)??e.status,o=Array.from(new Set((Array.isArray(e.tags)?e.tags:[]).filter(s=>typeof s=="string").map(s=>s.trim().toLowerCase()).filter(Boolean))).sort((s,a)=>s.localeCompare(a)),i={id:e.id,title:e.title,description:e.description,type:e.type,pm_format_version:go(e.pm_format_version),source_type:f(e.source_type),type_options:dc(e.type_options),status:n,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:Pa(e.dependencies),comments:kr(e.comments),notes:kr(e.notes),learnings:kr(e.learnings),files:$a(e.files),tests:Ga(e.tests),test_runs:Ma(e.test_runs),docs:Za(e.docs),deadline:We(e.deadline),reminders:ja(e.reminders),events:Ha(e.events),closed_at:We(e.closed_at),completed_at:We(e.completed_at),assignee:f(e.assignee),claim_principal:f(e.claim_principal),source_owner:f(e.source_owner),author:We(e.author),estimated_minutes:e.estimated_minutes,acceptance_criteria:e.acceptance_criteria??void 0,design:e.design??void 0,external_ref:e.external_ref??void 0,definition_of_ready:f(e.definition_of_ready),order:e.order,goal:f(e.goal),objective:f(e.objective),value:f(e.value),impact:f(e.impact),outcome:f(e.outcome),why_now:f(e.why_now),parent:f(e.parent),reviewer:f(e.reviewer),risk:e.risk??void 0,confidence:lc(e.confidence),sprint:f(e.sprint),release:f(e.release),blocked_by:f(e.blocked_by),blocked_reason:f(e.blocked_reason),unblock_note:f(e.unblock_note),reporter:f(e.reporter),severity:uc(e.severity),environment:f(e.environment),repro_steps:f(e.repro_steps),resolution:f(e.resolution),expected_result:f(e.expected_result),actual_result:f(e.actual_result),affected_version:f(e.affected_version),fixed_version:f(e.fixed_version),component:f(e.component),regression:e.regression,customer_impact:f(e.customer_impact),close_reason:We(e.close_reason),plan_mode:f(e.plan_mode),plan_scope:f(e.plan_scope),plan_harness:f(e.plan_harness),plan_resume_context:f(e.plan_resume_context),plan_steps:ic(e.plan_steps),plan_decisions:sc(e.plan_decisions),plan_discoveries:ac(e.plan_discoveries),plan_validation:cc(e.plan_validation)};return _c(i,e),fc(i,r),mc(i,r),ht(i),i}function Po(e){return y(e,B)}function pc(e){let t=0,r=!1,n=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(r){if(n){n=!1;continue}if(i==="\\"){n=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="{"){t+=1;continue}if(i==="}"&&(t-=1,t===0))return o}return-1}function hc(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};let t=pc(e);if(t<0)return{frontMatter:"",body:e};let r=e.slice(0,t+1),n=e.slice(t+1).replace(/^\r?\n+/,"");return{frontMatter:r,body:n}}function yc(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,r=t.match(/^[ \t]*---[ \t]*(?:\r?\n|$)/);if(!r)return{content:t,stripped:!1};let n=r[0].length;for(;n<t.length;){let o=t.indexOf(`
7
+ `,n),i=o===-1?t.length:o,s=t.slice(n,i).replace(/\r$/,""),a=o===-1?i:i+1;if(s.trim()==="---")return{content:t.slice(a).replace(/^\s+/,""),stripped:!0};n=a}return{content:t,stripped:!1}}function Ar(e,t){return yt(e,{...t,onWarning:void 0})}function gc(e,t,r={}){let n=yc(e);n.stripped&&r.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");let{frontMatter:o,body:i}=hc(n.content);o||(e.trimStart().startsWith("{")&&qe("json_markdown","JSON front matter is not valid JSON"),qe("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{qe("json_markdown","JSON front matter is not valid JSON")}return Ro(s,r.requireSupportedFormat),Tr(s,t),{metadata:Ar(s,r),body:Oe(i)}}function vc(e,t,r={}){let n;try{n=wr(e).value}catch{qe("toon","TOON item document is not valid TOON")}h(typeof n=="object"&&n!==null&&!Array.isArray(n),"TOON item document must be an object");let o=n;if(Ro(Object.prototype.hasOwnProperty.call(o,"front_matter")?o.front_matter:o,r.requireSupportedFormat),!Co.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&qe("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return Tr(o.front_matter,t),h(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:Ar(o.front_matter,r),body:Oe(typeof o.body=="string"?o.body:"")};let{body:i,...s}=o;return h(i===void 0||typeof i=="string","TOON item document body must be a string"),Tr(s,t),{metadata:Ar(s,r),body:Oe(typeof i=="string"?i:"")}}function bc(e,t={}){let r=yt(e.metadata,t),n=Po(r),o=Oe(e.body??"");Cr(JSON.parse(JSON.stringify(n))),Cr({body:o});let i=JSON.stringify(n,null,2);return o?`${i}
8
+
9
+ ${o}
10
+ `:`${i}
11
+ `}var wc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;function xr(e,t){return typeof e=="string"?Oo(e,t):e===null||typeof e!="object"?null:Array.isArray(e)?To(e.map((r,n)=>()=>xr(r,`${t}[${n}]`))):To(Object.entries(e).map(([r,n])=>()=>{let o=t?`${t}.${r}`:r;return Oo(r,`${o} (key)`)??xr(n,o)}))}function Oo(e,t){let r=e.search(wc);return r<0?null:{path:t,index:r}}function To(e){for(let t of e){let r=t();if(r!==null)return r}return null}function Cr(e){let t=xr(e,"");if(t!==null)throw new b(`Item field ${t.path} contains an unpaired surrogate code unit at index ${t.index}; persisted item text requires well-formed Unicode.`,w.USAGE,{code:"text_unpaired_surrogate",field:t.path,required:"Provide well-formed UTF-16 text: keep emoji and other astral characters whole and avoid lone \\uD800-\\uDFFF JSON escapes.",why:"Persisted item text must remain well-formed in every supported format; a lone surrogate can cause an unclassified encoder fault.",nextSteps:[`Repair the ${t.path} value (for example String.prototype.toWellFormed() or re-truncate on a character boundary) and retry.`,"Run pm <command> --help --json to review the text fields the command accepts."]})}function Ec(e,t={}){let r=yt(e.metadata,t),n=Po(r),o=Oe(e.body??""),i={...n,body:o},s=JSON.parse(JSON.stringify(i));Cr(s);let a=da(s),d;try{d=wr(a).value}catch(l){throw new b("Refusing to persist a TOON item document that the configured decoder cannot read back.",w.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_error",format:"toon",required:"Upgrade or repair the TOON codec before retrying the mutation; no item bytes were written.",why:l instanceof Error?l.message:String(l)})}if(!ko(d,s)){let l=typeof d=="object"&&d!==null&&!Array.isArray(d)?d:{},_=Object.keys(s).find(v=>!ko(s[v],l[v]))??"document";throw new b(`Refusing to persist a lossy TOON item document; round-trip mismatch at field "${_}".`,w.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_mismatch",format:"toon",field:_,required:"Upgrade or repair the TOON codec before retrying the mutation; no item bytes were written.",why:"The encoded document decoded to a value different from the canonical item payload."})}return`${a}
12
+ `}function s_(e,t={}){let r=mt(e);if(r)throw new b(`Merge conflict markers detected in item document at line ${r.line} (${r.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,w.GENERIC_FAILURE,{code:"merge_conflict_markers_detected",reason:"merge_conflict",required:"Resolve merge-conflict markers in the item file before parsing or mutation commands.",why:"Partially merged documents can corrupt item metadata and history integrity.",examples:["git status","git add <resolved-file> && git commit"],nextSteps:["Resolve conflicts, save the file, then rerun the pm command."]});let n=t.format??"toon",o=No(t);return n==="toon"?vc(e,o,t):gc(e,o,t)}function a_(e,t={}){return(t.format??"toon")==="toon"?Ec(e,t):bc(e,t)}function Ae(e,t={}){return{metadata:yt(e.metadata,t),body:Oe(e.body??"")}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cfedb84f-0525-5e02-af0a-d0e5691b5e0a")}catch{}})();async function kc(e,t){let r=await J(e);if(r===null)return{raw:r,entries:[]};if(await it({path:e,scope:"project"}),r.trim()==="")return{raw:r,entries:[]};let n=mt(r);if(n)throw new b(`History for ${t} contains merge conflict markers at line ${n.line} (${n.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,w.GENERIC_FAILURE,{code:"history_merge_conflict_markers_detected",required:"Repair the history stream by resolving merge-conflict markers.",why:"Conflict markers break JSONL parsing and invalidate deterministic audit history.",examples:[`pm history ${t}`,`pm restore ${t} <timestamp-or-version>`],nextSteps:["Resolve or restore the history file, then rerun the command."]});let o=[];for(let[i,s]of r.split(/\r?\n/).entries()){let a=s.trim();if(a)try{o.push(JSON.parse(a))}catch{throw new b(`History for ${t} contains invalid JSON at line ${i+1}. Repair or restore the history stream and retry.`,w.GENERIC_FAILURE,{code:"history_json_invalid",nextSteps:[`Run pm history-repair ${t} --salvage-tail --dry-run to check whether only an invalid suffix is damaged.`]})}}return{raw:r,entries:o}}async function me(e,t){return(await kc(e,t)).entries}import Xr from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3bfeb8d2-52c2-587a-9611-c4d5817cb47e")}catch{}})();function jo(e){let t=[],r=e[0]?.op==="history_compact_baseline",n=r?1:void 0,o=!1;for(let[i,s]of e.entries())s.op==="delete"&&(o=!0),s.op==="create"&&(n!==void 0&&t.push({prior_genesis_index:n,repeated_create_index:i+1,sequence:o?"delete_then_create":r?"checkpoint_then_create":"multiple_creates"}),n??=i+1,o=!1);return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="82c79093-2a40-5b4c-8d41-637b0ae03c4f")}catch{}})();import ui from"fast-json-patch";import ai from"node:fs/promises";import nd from"node:path";import A from"node:fs/promises";import N from"node:path";import{randomUUID as Lr}from"node:crypto";import{createRequire as Cc}from"node:module";import{setImmediate as zo}from"node:timers/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3c2c29c0-0034-54d4-9dbd-2e9af047784e")}catch{}})();var Sc=["docs_add","files_add","history:author-acknowledge","history_author_acknowledge","history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","normalize","release","test_run_track","tests_add","tests_remove","tests_update","update_audit","update_ownership_bypass"],Ic=["append","cancel","claim","close","comment_add","create","learning_add","note_add","reopen"],Oc=new Set(Sc),Tc=new Set(Ic),Ac=new Set(["actual_result","affected_version","assignee","blocked_by","blocked_reason","close_reason","confidence","customer_impact","definition_of_ready","dependencies","docs","environment","expected_result","files","fixed_version","goal","impact","learnings","notes","objective","order","outcome","parent","release","reminders","reporter","repro_steps","resolution","reviewer","severity","sprint","tests","test_runs","unblock_note","updated_at","value","why_now"]);function xc(e){let t=e.path.split("/").filter(Boolean);return t[0]==="metadata"||t[0]==="front_matter"?t[1]:t[0]==="body"?"body":void 0}function xe(e){return e.event_class==="substantive"||e.event_class==="maintenance"?e.event_class:Oc.has(e.op)?"maintenance":Tc.has(e.op)||e.op!=="update"?"substantive":Array.isArray(e.patch)&&e.patch.length>0&&e.patch.every(t=>{let r=xc(t);return r!==void 0&&Ac.has(r)})?"maintenance":"substantive"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="812b558d-59f3-58d6-b04e-6a4f8689e866")}catch{}})();function Lo(e){let t=process.emitWarning;process.emitWarning=(r,...n)=>{r==="SQLite is an experimental feature and might change at any time"&&n[0]==="ExperimentalWarning"||Reflect.apply(t,process,[r,...n])};try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}finally{process.emitWarning=t}}function Ho(e,t){let r=Number.parseInt(e,10);return Number.isFinite(r)&&r>=22?Lo(t):null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="641c311a-5de1-579a-ba44-b9a49978dfe0")}catch{}})();var Nc="history-event-index.sqlite",Hr="6",Rc=8,Go="history-event-index",Dc="history-event-index:append:",Pc=5e3,zr=300,Bo=3e4,jc="history-event-index-invalidation",Lc="history-event-index-invalidations",Hc=zr*2*1e3,Q=Symbol("history-index-changed"),pe=new Map;function he(e){return N.join(e,"runtime",Nc)}function Jo(e){return N.join(e,"runtime","history-event-index-repair-deferred")}async function Ko(e){try{let t=Number(await A.readFile(Jo(e),"utf8")),r=Date.now()-t;return r>=0&&r<Pc}catch{return!1}}async function Fo(e){try{await A.writeFile(Jo(e),`${Date.now()}
13
+ `)}catch{}}function Be(e){return N.join(e,"runtime",Lc)}async function bt(e){let t=await A.readdir(Be(e)).catch(r=>{if(ae(r))return[];throw r});return{pending:t.filter(r=>r.endsWith(".pending")).sort(),committed:t.filter(r=>r.endsWith(".committed")).sort()}}async function $o(e){let t=await bt(e);return{pending:(await Promise.all(t.pending.map(async r=>{let n=/^(\d+)-(unknown|\d+)-(\d+)-.+\.pending$/u.exec(r);if(n!==null){let o=n[2];if(await Bn({pid:Number(n[1]),...o==="unknown"?{}:{process_start_identity:o}},Math.max(0,Date.now()-Number(n[3])),Hc))return r}return await A.rm(N.join(Be(e),r),{force:!0}),null}))).filter(r=>r!==null),committed:t.committed}}async function Pr(e,t,r=Bo){let n=await V(e,jc,zr,`history-event-index-invalidation:${process.pid}`,!1,!1,r,r===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await n()}}async function zc(e){let t=Be(e);await A.mkdir(t,{recursive:!0});let r=Lr(),n=await Gn(),o=N.join(t,`${n.pid}-${n.process_start_identity??"unknown"}-${Date.now()}-${r}.pending`);return await A.writeFile(o,`pending
14
+ `,{flag:"wx"}),{pendingPath:o,committedPath:N.join(t,`${r}.committed`)}}function Fc(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}async function wt(e){try{await A.rm(he(e),{force:!0})}catch{}}async function Mo(e,t){let r=Be(e);await A.mkdir(r,{recursive:!0}),await A.writeFile(N.join(r,`${Lr()}${t?".contended":""}.committed`),`committed
15
+ `,{flag:"wx"}),t||await wt(e)}function Et(e){return e.committed.some(t=>t.endsWith(".contended.committed"))}function jr(e,t){let r;try{return r=new t(he(e)),r.exec("PRAGMA busy_timeout = 0"),r.exec("BEGIN EXCLUSIVE"),!1}catch(n){return Ce(n)}finally{r?.close()}}async function Vo(e,t){return t.pending.length>0||await qn(e,Go,Dc)}async function Xo(e,t,r=Bo,n="rebuild"){let o=await V(e,Go,zr,`history-event-index:${n}:${process.pid}`,!1,!1,r,r===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await o()}}async function Yo(e){let t=N.join(e,"history"),r=await A.readdir(t,{withFileTypes:!0}).catch(s=>{if(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ENOENT")return[];throw s}),n=pe.get(e)??{streams:new Map,ordered_events:[]},o=new Set,i=!pe.has(e);for(let s of r.filter(a=>a.isFile()&&a.name.endsWith(".jsonl")).sort((a,d)=>a.name.localeCompare(d.name))){let a=s.name.slice(0,-6);o.add(a);let d=N.join(t,s.name),l=await A.stat(d,{bigint:!0}),_=[l.dev,l.ino,l.size,l.mtimeNs,l.ctimeNs].join(":");if(n.streams.get(a)?.signature===_)continue;let v=await Zo(d,a);n.streams.set(a,{signature:_,byte_size:Number(l.size),events:v.map((O,S)=>({stream_id:a,stream_offset:S,entry:O}))}),i=!0}for(let s of n.streams.keys())o.has(s)||(n.streams.delete(s),i=!0);if(i&&(n.ordered_events=[...n.streams.values()].flatMap(s=>s.events).sort(Fr)),pe.delete(e),pe.set(e,n),pe.size>Rc){let s=pe.keys().next().value;pe.delete(s)}return{events:n.ordered_events,stream_byte_sizes:new Map([...n.streams].map(([s,a])=>[s,a.byte_size]))}}async function Zo(e,t){let r=await me(e,t);for(let[n,o]of r.entries())if(typeof o.ts!="string"||!Ee(o.ts.trim()))throw new b(`History for ${t} contains an invalid or sub-millisecond timestamp at line ${n+1}. Repair or restore the history stream and retry.`,w.GENERIC_FAILURE,{code:"history_timestamp_invalid"});return r.map(n=>({...n,ts:new Date(n.ts.trim()).toISOString()}))}async function $c(e){return(await Yo(e)).events}var Dr;function St(){return Dr!==void 0||(Dr=Ho(process.versions.node,Cc(import.meta.url))),Dr}function Mc(e){e.exec(`
16
+ PRAGMA journal_mode = OFF;
17
+ PRAGMA synchronous = OFF;
18
+ CREATE TABLE metadata (
19
+ key TEXT PRIMARY KEY,
20
+ value TEXT NOT NULL
21
+ ) STRICT;
22
+ CREATE TABLE events (
23
+ stream_id TEXT NOT NULL,
24
+ stream_offset INTEGER NOT NULL,
25
+ ts TEXT NOT NULL,
26
+ author TEXT NOT NULL,
27
+ agent_harness TEXT,
28
+ agent_instance TEXT,
29
+ op TEXT NOT NULL,
30
+ event_class TEXT NOT NULL CHECK(event_class IN ('substantive', 'maintenance')),
31
+ entry_json TEXT NOT NULL,
32
+ PRIMARY KEY(stream_id, stream_offset)
33
+ ) STRICT;
34
+ CREATE TABLE streams (
35
+ stream_id TEXT PRIMARY KEY,
36
+ byte_size INTEGER NOT NULL CHECK(byte_size >= 0)
37
+ ) STRICT;
38
+ CREATE INDEX events_order
39
+ ON events(ts, stream_id, stream_offset);
40
+ CREATE INDEX events_op_order
41
+ ON events(op, ts, stream_id, stream_offset);
42
+ CREATE INDEX events_class_stream_order
43
+ ON events(event_class, stream_id, ts, stream_offset);
44
+ CREATE INDEX events_author_order
45
+ ON events(author, ts, stream_id, stream_offset);
46
+ CREATE INDEX events_harness_order
47
+ ON events(agent_harness, ts, stream_id, stream_offset);
48
+ CREATE INDEX events_instance_order
49
+ ON events(agent_instance, ts, stream_id, stream_offset);
50
+ `),e.prepare("INSERT INTO metadata(key, value) VALUES ('version', ?)").run(Hr)}function Qo(e,t){let r={...t.entry,ts:new Date(t.entry.ts.trim()).toISOString()};e.prepare(`INSERT INTO events(
51
+ stream_id, stream_offset, ts, author, agent_harness,
52
+ agent_instance, op, event_class, entry_json
53
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.stream_id,t.stream_offset,r.ts,r.author,r.agent_harness??null,r.agent_instance??null,r.op,xe(r),JSON.stringify(r))}function ei(e){let t=JSON.parse(String(e.entry_json));return typeof t.ts!="string"||!Ee(t.ts.trim())?null:{stream_id:String(e.stream_id),stream_offset:Number(e.stream_offset),entry:{...t,ts:new Date(t.ts.trim()).toISOString()}}}function ti(e,t,r){e.prepare(`INSERT INTO streams(stream_id, byte_size) VALUES (?, ?)
54
+ ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size`).run(t,r)}async function Vc(e,t={}){let r=St();return r?Xo(e,async()=>{let n;try{n=await Pr(e,()=>$o(e),t.lockWaitMs)}catch(a){if(a instanceof b&&a.code==="lock_conflict")return!1;throw a}if(n.pending.length>0||Et(n)&&jr(e,r))return!1;let o=he(e);await A.mkdir(N.dirname(o),{recursive:!0});let i=`${o}.${Lr()}.tmp`,s;try{s=new r(i),Mc(s),s.exec("BEGIN IMMEDIATE");let a=await Yo(e);await Uc(s,a),s.exec("COMMIT"),s.close(),s=void 0;let d=await Pr(e,async()=>{let l=await $o(e);return l.pending.length>0||!Fc(n.committed,l.committed)||Et(l)&&jr(e,r)?!1:(await A.rm(o,{force:!0}),await A.rename(i,o),!0)},t.lockWaitMs);return d&&await Promise.all(n.committed.map(l=>A.rm(N.join(Be(e),l),{force:!0}))),d||(await Fo(e),await A.rm(i,{force:!0})),d}catch(a){throw await Fo(e),s?.close(),await A.rm(i,{force:!0}),a}},t.lockWaitMs):!1}async function Uc(e,t){let r=0;for(let n of t.events)Qo(e,n),++r%500===0&&await zo();for(let[n,o]of t.stream_byte_sizes)ti(e,n,o),++r%500===0&&await zo()}function gt(e,t){return!t||t.length===0||t.includes(e)}function Fr(e,t){return e.entry.ts.localeCompare(t.entry.ts)||e.stream_id.localeCompare(t.stream_id)||e.stream_offset-t.stream_offset}function kt(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():e}function Wc(e,t){if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){if(Fr(e,{stream_id:t.after_stream_id,stream_offset:t.after_stream_offset,entry:{...e.entry,ts:kt(t.after_ts)}})<=0)return!1}else if(t.since_ts!==void 0&&e.entry.ts<kt(t.since_ts))return!1;return!0}function qc(e,t){return!t.harnesses||t.harnesses.length===0||t.harnesses.includes(e.entry.agent_harness??"")?!0:e.entry.agent_harness===void 0&&(t.harness_alias_authors??[]).includes(e.entry.author)}function Gc(e,t){return!Wc(e,t)||!gt(e.entry.op,t.ops)||!gt(e.entry.author,t.authors)||!gt(e.entry.agent_instance??"",t.agent_instances)||!gt(e.stream_id,t.stream_ids)||!qc(e,t)?!1:(t.provenance??[]).every(r=>{let n=e.entry.agent_provenance?.[r.dimension]?.value;return n!==void 0&&r.values.includes(n)})}async function R_(e,t){let r=Math.max(0,Math.floor(t.limit)),n=(await $c(e)).filter(o=>Gc(o,t)).slice(0,r+1);return{events:n.slice(0,t.limit),has_more:n.length>t.limit}}async function Bc(e,t){let r=e.prepare("SELECT byte_size FROM streams WHERE stream_id = ?").get(N.basename(t,".jsonl")),n=0;try{n=(await A.stat(t)).size}catch(o){if(!ae(o))throw o}return Number(r?.byte_size??0)===n}async function ri(e,t,r){let n=N.dirname(N.dirname(e)),o=St(),i=!1,s=async()=>{await r(),i=!0};if(!o){await Uo(n,s);return}try{await Xo(n,async()=>{let a=he(n);try{await A.access(a)}catch{await s();return}let d;try{if(d=new o(a),d.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==Hr)throw new TypeError("Unsupported history event index version");if(!await Bc(d,e))throw new TypeError("Stale history event index append base")}catch(_){if(d?.close(),Ce(_))throw _;await Mo(n,!0),await s();return}try{d.exec("PRAGMA busy_timeout = 0"),d.exec("BEGIN IMMEDIATE")}catch(_){throw d.close(),_}let l=!1;try{await s(),l=!0;let _=N.basename(e,".jsonl"),v=d.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(_);Qo(d,{stream_id:_,stream_offset:Number(v.value),entry:t}),ti(d,_,(await A.stat(e)).size),d.exec("COMMIT"),d.close()}catch(_){if(d?.close(),!l)throw _;await Mo(n,Ce(_))}},0,"append")}catch(a){if(i){await wt(n);return}if(!Kc(a))throw a;await Uo(n,s,Ce(a))}}async function Uo(e,t,r=!1){let n=!1,o;try{await Pr(e,async()=>{let i=r||Et(await bt(e)),s=await zc(e);o=s.pendingPath;try{await t(),n=!0}catch(a){throw await A.rm(s.pendingPath,{force:!0}),a}await A.rename(s.pendingPath,i?s.committedPath.replace(/\.committed$/u,".contended.committed"):s.committedPath),i||await wt(e)})}catch(i){if(n){await wt(e);try{await A.rm(o,{force:!0})}catch{}return}throw i}}async function $r(e){await A.rm(he(N.dirname(N.dirname(e))),{force:!0})}function vt(e,t,r,n){!n||n.length===0||(e.push(`${r} IN (${n.map(()=>"?").join(", ")})`),t.push(...n))}function Jc(e,t,r,n){if(!r||r.length===0)return;let o=r.map(()=>"?").join(", "),i=n??[];if(i.length>0){e.push(`(agent_harness IN (${o}) OR (agent_harness IS NULL AND author IN (${i.map(()=>"?").join(", ")})))`),t.push(...r,...i);return}e.push(`agent_harness IN (${o})`),t.push(...r)}async function ni(e,t,r,n){let o;try{let i=await bt(e);if(await Vo(e,i))return Q;let s=await Wo(e);if(i.committed.length>0)return Et(i)&&jr(e,t)?Q:null;if(o=new t(he(e),{readOnly:!0}),o.exec("BEGIN"),o.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==Hr)return null;let a=n(o);if(a===null)return null;let d=Xc(o,r),l=o;o=void 0,l.close();let _=await Qc([...d.keys()],e,r),v=await Zc(d,e,_),O=await bt(e);return O.committed.length>0||await Vo(e,O)||s!==await Wo(e)?Q:v?a:null}catch(i){return Ce(i)?Q:null}finally{o?.close()}}function Ce(e){return typeof e=="object"&&e!==null&&"errcode"in e&&[5,6].includes(e.errcode)}function Kc(e){return Ce(e)||e instanceof b&&e.code==="lock_conflict"}function Xc(e,t){let r=new Map,n=t&&t.length>0?[...new Set(t)]:void 0;if(n===void 0)for(let o of e.prepare("SELECT stream_id, byte_size FROM streams").all())r.set(String(o.stream_id),Number(o.byte_size));else for(let o=0;o<n.length;o+=500){let i=n.slice(o,o+500);for(let s of e.prepare(`SELECT stream_id, byte_size FROM streams WHERE stream_id IN (${i.map(()=>"?").join(", ")})`).all(...i))r.set(String(s.stream_id),Number(s.byte_size))}return r}async function Wo(e){let t=await A.stat(he(e),{bigint:!0});return[t.dev,t.ino,t.size,t.mtimeNs,t.ctimeNs].join(":")}async function D_(e,t){let r=St();if(!r)return{result:null,repair_needed:!1};let n=[],o=[];if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){n.push("(ts > ? OR (ts = ? AND stream_id > ?) OR (ts = ? AND stream_id = ? AND stream_offset > ?))");let a=kt(t.after_ts);o.push(a,a,t.after_stream_id,a,t.after_stream_id,t.after_stream_offset)}else t.since_ts!==void 0&&(n.push("ts >= ?"),o.push(kt(t.since_ts)));vt(n,o,"op",t.ops),vt(n,o,"author",t.authors),Jc(n,o,t.harnesses,t.harness_alias_authors),vt(n,o,"agent_instance",t.agent_instances);for(let a of t.provenance??[])n.push(`json_extract(entry_json, '$.agent_provenance.${a.dimension}.value') IN (${a.values.map(()=>"?").join(", ")})`),o.push(...a.values);vt(n,o,"stream_id",t.stream_ids);let i=n.length===0?"":` WHERE ${n.join(" AND ")}`,s=await ni(e,r,t.stream_ids,a=>{let d=a.prepare(`SELECT stream_id, stream_offset, entry_json
55
+ FROM events${i}
56
+ ORDER BY ts, stream_id, stream_offset
57
+ LIMIT ?`).all(...o,Math.max(0,Math.floor(t.limit))+1),l=d.slice(0,t.limit).map(ei);return l.includes(null)?null:{events:l,has_more:d.length>t.limit}});return{result:s===Q?null:s,repair_needed:s===null&&!await Ko(e)}}function oi(e,t){let r=Object.create(null);for(let n of e){if(!t.has(n.stream_id)||xe(n.entry)!=="substantive")continue;let o=r[n.stream_id];(o===void 0||Fr(o,n)<0)&&(r[n.stream_id]=n)}return r}async function Yc(e,t){if(N.basename(t)!==t)return null;try{return(await A.stat(N.join(e,"history",`${t}.jsonl`))).size}catch(r){if(ae(r))return 0;throw r}}async function Zc(e,t,r){for(let n=0;n<r.length;n+=500){let o=r.slice(n,n+500),i=await Promise.all(o.map(s=>Yc(t,s)));for(let[s,a]of i.entries()){if(a===null)return!1;let d=o[s],l=e.get(d);if(!(a===0&&l===void 0)&&a!==l)return!1}}return!0}async function Qc(e,t,r){if(r&&r.length>0)return[...new Set(r.filter(o=>o.trim().length>0))];let n=await A.readdir(N.join(t,"history"),{withFileTypes:!0}).then(o=>o.filter(i=>i.isFile()&&i.name.endsWith(".jsonl")).map(i=>i.name.slice(0,-6))).catch(o=>{if(ae(o))return[];throw o});return[...new Set([...e,...n])]}async function qo(e,t,r,n){return e?ni(t,e,r,o=>{let i=[];for(let s=0;s<r.length;s+=500){let a=r.slice(s,s+500),d=o.prepare(`SELECT stream_id, stream_offset, entry_json
58
+ FROM (
59
+ SELECT stream_id, stream_offset, entry_json,
60
+ ROW_NUMBER() OVER (
61
+ PARTITION BY stream_id
62
+ ORDER BY ts DESC, stream_offset DESC
63
+ ) AS recency_rank
64
+ FROM events
65
+ WHERE event_class = 'substantive'
66
+ AND stream_id IN (${a.map(()=>"?").join(", ")})
67
+ )
68
+ WHERE recency_rank = 1`).all(...a).map(ei);if(d.includes(null))return null;i.push(...d)}return oi(i,n)}):null}async function P_(e,t){let r=[...new Set(t.filter(a=>a.trim().length>0&&N.basename(a)===a))];if(r.length===0)return{};let n=new Set(r),o=St(),i=await qo(o,e,r,n);if(i!==null&&i!==Q)return i;if(o&&i!==Q&&!await Ko(e))try{if(await Vc(e,{lockWaitMs:0})){let a=await qo(o,e,r,n);if(a!==null&&a!==Q)return a}}catch{}let s=[];return await Promise.all(r.map(async a=>{let d=N.join(e,"history",`${a}.jsonl`);(await Zo(d,a).catch(l=>{if(l instanceof b&&l.code==="history_timestamp_invalid")return[];throw l})).forEach((l,_)=>{s.push({stream_id:a,stream_offset:_,entry:l})})})),oi(s,n)}import Mr from"node:fs/promises";import Ne from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="687cbe24-6d5c-5322-962d-455048eb84b5")}catch{}})();var ed=Ne.join("runtime","history-drift-cache.json"),ii={EINVAL:"invalid_cache_path",EISDIR:"cache_path_is_directory",ENOENT:"invalid_cache_path",ENOTDIR:"invalid_cache_path",ERR_FS_EISDIR:"cache_path_is_directory"};function si(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function td(e){let t=Ne.join(e,ed),r=!1,n="invalid_cache_path";try{r=(await Mr.stat(await Mr.realpath(e))).isDirectory()}catch(o){let i=si(o);n=i===void 0?"unknown":ii[i]??"filesystem_error"}if(!r){Kt(`[pm] warning: history_drift_cache_invalidation_failed:${n}
69
+ `);return}try{await Mr.rm(t,{force:!0})}catch(o){let i=si(o);if(ae(o))return;let s=i===void 0?"unknown":ii[i]??"filesystem_error";Kt(`[pm] warning: history_drift_cache_invalidation_failed:${s}
70
+ `)}}async function It(e){let t=Ne.dirname(Ne.resolve(e));Ne.basename(t)==="history"&&await td(Ne.dirname(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4a3c3c82-0398-549c-8910-fdc69d971cb2")}catch{}})();var od={front_matter:{},body:""},ye=3,Je=[1,2,3],id=1,sd=[1];function _i(e){return Y(T(e),e.hash_algorithm)}function Re(e){return ot(T(e))}function of(e){return ot(T(e))}function qr(e){let t={...e,record_hash_version:id},{record_hash:r,...n}=t;return{...t,record_hash:_i(n)}}function At(e){try{_e(e.hash_algorithm)}catch{return{ok:!1,error:"unsupported_history_hash_algorithm"}}if(e.record_hash_version===void 0&&e.record_hash===void 0)return{ok:!0,coverage:"item_state_only"};if(e.record_hash_version===void 0||e.record_hash===void 0)return{ok:!1,error:"incomplete_record_hash_envelope"};if(!sd.includes(e.record_hash_version))return{ok:!1,error:"unsupported_record_hash_version"};let{record_hash:t,...r}=e;return _i(r)===e.record_hash?{ok:!0,coverage:"record_and_item_state"}:{ok:!1,error:"record_hash_mismatch"}}function ad(e,t){let r={before_hash:e.before_hash,after_hash:e.after_hash,patch_hash:Re(e.patch)};return e.hash_algorithm!==void 0&&(r.hash_algorithm=e.hash_algorithm),e.item_hash_version!==void 0&&(r.item_hash_version=e.item_hash_version),t.retainOriginalPatch&&(r.patch=structuredClone(e.patch)),t.retainPriorRecordHash!==!1&&e.record_hash_version!==void 0&&e.record_hash!==void 0&&(r.record_hash_version=e.record_hash_version,r.record_hash=e.record_hash,r.record=structuredClone(e)),r}function fi(e,t,r={}){let n=At(e);if(!n.ok)throw new TypeError(n.error);let o=Re(e.patch),i=r.retainPriorRecord===!0||e.before_hash!==t.before_hash||e.after_hash!==t.after_hash||e.item_hash_version!==t.item_hash_version||e.hash_algorithm!==t.hash_algorithm||o!==Re(t.patch),s=qr({...t,...i?{reanchor_evidence:[...t.reanchor_evidence??[],ad(e,r)]}:{}}),a=Gr(s);if(!a.ok)throw new TypeError(a.error);return s}function mi(e){return!Array.isArray(e)||Object.keys(e).length!==e.length?!1:e.every(t=>!ge(t)||typeof t.path!="string"?!1:t.op==="move"||t.op==="copy"?typeof t.from=="string":["add","replace","test"].includes(t.op)?Object.hasOwn(t,"value"):t.op==="remove")}function cd(e){return ge(e)&&typeof e.ts=="string"&&typeof e.author=="string"&&typeof e.op=="string"&&typeof e.before_hash=="string"&&typeof e.after_hash=="string"&&mi(e.patch)}function dd(e){let t=e.record_hash_version!==void 0,r=e.record_hash!==void 0;return t===r}function ld(e){return!ge(e)||!dd(e)||typeof e.before_hash!="string"||typeof e.after_hash!="string"||typeof e.patch_hash!="string"||!/^[a-f0-9]{64}$/u.test(e.patch_hash)||e.patch!==void 0&&!mi(e.patch)||e.record_hash_version!==void 0&&typeof e.record_hash_version!="number"||e.record_hash!==void 0&&(typeof e.record_hash!="string"||!/^(?:[a-f0-9]{64}|[a-f0-9]{128})$/u.test(e.record_hash))?!1:e.record===void 0||cd(e.record)}function ud(e){try{for(let t of e){if(!ld(t))return!1;_e(t.hash_algorithm)}return!0}catch{return!1}}function _d(e){let t=e.record;return t!==void 0&&t.before_hash===e.before_hash&&t.after_hash===e.after_hash&&t.item_hash_version===e.item_hash_version&&t.hash_algorithm===e.hash_algorithm&&t.record_hash_version===e.record_hash_version&&t.record_hash===e.record_hash&&Re(t.patch)===e.patch_hash}function fd(e,t,r){if(t.patch&&Re(t.patch)!==t.patch_hash)return{kind:"patch_hash_mismatch"};if(t.record)return _d(t)?{kind:"record",entry:t.record}:{kind:"record_hash_mismatch"};let n=t.patch??e.patch;if(Re(n)!==t.patch_hash)return{kind:"digest_only"};let o={...e,before_hash:t.before_hash,after_hash:t.after_hash,patch:n,hash_algorithm:t.hash_algorithm,...t.item_hash_version===void 0?{}:{item_hash_version:t.item_hash_version},...t.record_hash_version===void 0?{}:{record_hash_version:t.record_hash_version},...t.record_hash===void 0?{}:{record_hash:t.record_hash},...r.length===0?{}:{reanchor_evidence:r}};return t.hash_algorithm===void 0&&delete o.hash_algorithm,r.length===0&&delete o.reanchor_evidence,t.item_hash_version===void 0&&delete o.item_hash_version,t.record_hash_version===void 0||t.record_hash===void 0?{kind:"legacy",entry:o}:{kind:"record",entry:o}}function Gr(e){let t=e.reanchor_evidence;if(t===void 0)return{ok:!0,coverage:"none"};if(!Array.isArray(t)||!ud(t))return{ok:!1,error:"rewrite_evidence_invalid"};if(t.length===0)return{ok:!0,coverage:"none"};let r=e;for(let n=t.length-1;n>=0;n-=1){let o=t[n],i=fd(r,o,t.slice(0,n));if(i.kind==="patch_hash_mismatch")return{ok:!1,error:"rewrite_evidence_patch_hash_mismatch"};if(i.kind==="record_hash_mismatch")return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};if(i.kind==="digest_only")return{ok:!0,coverage:"digest_only"};if(i.kind==="legacy")return{ok:!0,coverage:"legacy_anchor_only"};if(!At(i.entry).ok)return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};r=i.entry}return{ok:!0,coverage:"complete"}}function Ot(e,t){return(e??"").localeCompare(t??"")}function ci(e,t){return(e??0)-(t??0)}function ee(e,t,r){return JSON.stringify(e??r).localeCompare(JSON.stringify(t??r))}function md(e,t){return[e.scope.localeCompare(t.scope),Ot(e.path,t.path),Ot(e.command,t.command),ci(e.timeout_seconds,t.timeout_seconds),Ot(e.pm_context_mode,t.pm_context_mode),+!!e.shared_host_safe-+!!t.shared_host_safe,ee(e.env_clear,t.env_clear,[]),ee(e.env_set,t.env_set,{}),ee(e.assert_stdout_contains,t.assert_stdout_contains,[]),ee(e.assert_stdout_regex,t.assert_stdout_regex,[]),ee(e.assert_stderr_contains,t.assert_stderr_contains,[]),ee(e.assert_stderr_regex,t.assert_stderr_regex,[]),ci(e.assert_stdout_min_lines,t.assert_stdout_min_lines),ee(e.assert_json_field_equals,t.assert_json_field_equals,{}),ee(e.assert_json_field_gte,t.assert_json_field_gte,{}),Ot(e.note,t.note)].find(r=>r!==0)??0}function pd(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(t=>t.replaceAll("~1","/").replaceAll("~0","~")):[]}function hd(e,t){let r=pd(t);if(r.length===0)return!0;let n=e;for(let o of r){let i=/^(0|[1-9]\d*)$/.test(o)?Number(o):-1,s=Array.isArray(n)?i>=0&&i<n.length?n[i]:void 0:ge(n)&&Object.prototype.hasOwnProperty.call(n,o)?n[o]:void 0;if(s===void 0)return!1;n=s}return!0}function yd(e,t){let r=[],n=structuredClone(e);for(let o of t){let i=o.op==="replace"&&!hd(n,o.path)?{...o,op:"add"}:o;r.push(i),n=ui.applyPatch(n,[i],!0,!0).newDocument}return r}function Tt(e,t,r=!1){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};let n=Ae(e),o=t===1||t===2&&r?{...n.metadata,...n.metadata.dependencies===void 0?{}:{dependencies:n.metadata.dependencies.map(s=>({...s,id:s.id.toLowerCase()}))},...n.metadata.tests===void 0?{}:{tests:n.metadata.tests.map(({workspace_context_mode:s,provenance:a,provenance_invalid:d,...l})=>l)},...n.metadata.test_runs===void 0?{}:{test_runs:n.metadata.test_runs.map(({executions:s,...a})=>a)}}:n.metadata,i=t===1&&o.tests?{...o,tests:[...o.tests].sort(md)}:o;return{front_matter:y(i,B),body:n.body}}function di(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};let t=Ae(e);return{metadata:y(t.metadata,B),body:t.body}}function sf(e){return pi(e,ye)}function pi(e,t,r){if(!Je.some(n=>n===t))throw new TypeError(`unsupported_item_hash_version:${String(t)}`);return Y(T(Tt(e,t)),r)}function hi(e,t,r){let n=pi(e,t,r);return t===2?[n,Y(T(Tt(e,t,!0)),r)]:[n]}function af(){return ot(T(od))}function Br(e){let t=Jn(e.op),r=Tt(e.before,ye),n=Tt(e.after,ye),o=di(e.before),i=di(e.after),s=ui.compare(o,i),a=yd(o,s),d=po(e.author),l=d.harness?Object.fromEntries(Object.entries(fo().provenance_outcomes).filter(([S,I])=>I.resolver!==void 0&&(I.status!=="resolved"||d.provenance?.[S]?.source==="probe"))):void 0,_=l===void 0||Object.keys(l).length===0?e.context:{...e.context,agent_provenance_outcomes:l},v=e.hashAlgorithm??yo,O={hash_algorithm:v,ts:e.nowIso,author:e.author,author_source:e.authorSource??mo(e.author),...d.harness?{agent_harness:d.harness}:{},...d.model?{agent_model:d.model}:{},...d.model_source?{agent_model_source:d.model_source}:{},...d.instance?{agent_instance:d.instance}:{},...d.provenance?{agent_provenance:d.provenance}:{},...d.episode?{agent_episode:d.episode}:{},op:t,patch:a,before_hash:Y(T(r),v),after_hash:Y(T(n),v),item_hash_version:ye,message:e.message===void 0?void 0:e.message,..._===void 0?{}:{context:_}};return qr({...O,event_class:xe(O)})}function ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vr(e){return new b(e,w.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function yi(e){let t=e.ts.trim();if(t.length===0)return Me();if(!Ee(t))throw Vr("History timestamp must be a valid RFC 3339 date-time with millisecond precision");if(t!==e.ts)throw Vr("History timestamp must not contain surrounding whitespace");return e.ts}function li(e,t){let r=e.ts;if(typeof r=="string"&&r.trim().length>0){if(!Ee(r))throw Vr("History timestamp must be a valid RFC 3339 date-time with millisecond precision");return e}return{...e,ts:t}}function Ur(e,t){let r=yi(t);if(typeof e=="string"){let n;try{n=JSON.parse(e)}catch{return e}return ge(n)?JSON.stringify(li(n,r)):e}return ge(e)?JSON.stringify(li(e,r)):JSON.stringify(e)}async function gd(e,t,r){if(r===!1)return!0;if(typeof r=="string"){let s=Ur(r,t);return await Wr(e,s),await It(e),await $r(e),!0}if(typeof r!="object"||r===null)return!1;let n=r;if(n.skip===!0)return!0;let o=typeof n.history_path=="string"?n.history_path:e,i=Ur(typeof n.line=="string"?n.line:n.entry??t,t);return await Wr(o,i),await It(o),await $r(o),!0}async function Wr(e,t){let r;try{r=JSON.parse(t)}catch{r=null}if(!ge(r)||r.op!=="create"){await Rn(e,t);return}await ai.mkdir(nd.dirname(e),{recursive:!0});try{await ai.writeFile(e,`${t}
71
+ `,{encoding:"utf8",flag:"wx"})}catch(n){throw n.code!=="EEXIST"?n:new b("This item identity is reserved by an existing history stream.",w.CONFLICT,{code:"item_identity_reserved",required:"Choose a new item ID or restore the original item from its history.",nextSteps:["Run pm history <id> --full, then pm restore <id> <version> to recover the original item."]})}}async function Jr(e,t){let r=await Un("history_append",{history_path:e,entry:t});if(r.handled&&await gd(e,t,r.result))return;let n=t.ts.trim().length>0?t:{...t,ts:yi(t)},o=qr({...n,hash_algorithm:_e(n.hash_algorithm),event_class:xe(n)});await ri(e,o,async()=>{await Wr(e,Ur(o,o))}),await It(e)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c0cb8c7-4d7d-53f8-8ec2-d6dc98fc6dc5")}catch{}})();var vd={metadata:{},body:""};function xt(){return structuredClone(vd)}function yf(e,t=ye,r){return Kr(e,t,r)[0]}function Kr(e,t,r){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return hi(Ct(e),t,r)}catch{}let n=Y(T({replay_fallback:!0,metadata:e.metadata,body:e.body}),r);return t===2?[n,n]:[n]}function bi(e,t,r,n,o){let i=_e(n.hash_algorithm),s=`${r}:${i}`,a=o?.before.get(s)??Kr(e,r,i),d=Kr(t,r,i);return o?.after.set(s,d),{beforeHashes:a,afterHashes:d,pairIndex:a.findIndex((l,_)=>l===n.before_hash&&d[_]===n.after_hash),beforeIndex:a.indexOf(n.before_hash),afterIndex:d.indexOf(n.after_hash)}}function Ct(e){return{metadata:e.metadata,body:e.body}}function gf(e,t={}){return Ae(Ct(e),t)}function vf(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};let t=Ae(e);return{metadata:y(t.metadata,B),body:t.body}}function gi(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function bd(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function wi(e){return Array.isArray(e)?e.filter(bd).map(t=>({...t,path:gi(t.path),from:typeof t.from=="string"?gi(t.from):void 0})):[]}function wd(e){return typeof e=="object"&&e!==null&&"metadata"in e&&"body"in e&&typeof e.body=="string"&&typeof e.metadata=="object"&&e.metadata!==null}function Nt(e,t){try{let r=wi(t),n=Xr.applyPatch(structuredClone(e),r,!0,!0).newDocument;return wd(n)?{ok:!0,document:{metadata:n.metadata,body:n.body}}:{ok:!1,error:new Error("history_replay_invalid_document_shape")}}catch(r){return{ok:!1,error:r}}}function Ed(e){return[...new Set(e.map(t=>t.item_hash_version).filter(t=>t!==void 0&&Je.includes(t)))]}function Ei(e){return e!==void 0&&!Je.includes(e)}function kd(e,t){return e!==void 0?[e]:t===void 0?[...Je]:[t]}function ki(e){let t=At(e);if(!t.ok)return t.error;let r=Gr(e);return r.ok?void 0:r.error}function Sd(e,t){let r=ki(e);if(r)return{ok:!1,error:r};let n=Nt(t,e.patch);return n.ok?{ok:!0,document:n.document}:{ok:!1,error:"patch_apply_failed"}}function Id(e,t){let r=ki(e);if(r)throw new TypeError(`${r}:entry_${t+1}`)}function Od(e,t,r,n,o){let i=[];for(let s of r){let a=bi(e,t,s,n,o);if(i.push({version:s,match:a}),a.pairIndex>=0)break}return i}function Si(e){let t=xt(),r=new Map,n,o,i=jo(e).map(s=>`verify_failed:duplicate_create:entry_${s.repeated_create_index}:prior_${s.prior_genesis_index}`);for(let s=0;s<e.length;s+=1){let a=e[s],d=a.item_hash_version,l=Ei(d);l&&i.push(`verify_failed:unsupported_item_hash_version:${String(d)}:entry_${s+1}`);let _=Sd(a,t);if(!_.ok)return{ok:!1,errors:[...i,`verify_failed:${_.error}:entry_${s+1}`]};if(l){t=_.document,r=new Map,n=void 0,o=void 0;continue}let v=kd(d,o),O={before:r,after:new Map},S=Od(t,_.document,v,a,O),I=S.find(({match:D})=>D.pairIndex>=0);if(I===void 0){let D=S.some(({match:$})=>$.beforeIndex>=0);return{ok:!1,errors:[...i,`verify_failed:${D?"after":"before"}_hash_mismatch:entry_${s+1}`]}}let z=I.version;t=_.document,r=O.after,n=z,o=d??o}return i.length>0?{ok:!1,errors:i,...n===void 0?{}:{item_hash_version:n}}:{ok:!0,errors:[],...n===void 0?{}:{item_hash_version:n}}}function Ke(e){let t=Si(e);return{ok:t.ok,errors:t.errors}}function vi(e,t){try{return{ok:!0,document:Xr.applyPatch(structuredClone(e),[t],!0,!1).newDocument}}catch{return{ok:!1}}}function Td(e,t){let r=structuredClone(e),n=0,o=0;for(let s of wi(t)){let a=vi(r,s);if(a.ok){r=a.document;continue}if(s.op==="replace"){let d=vi(r,{...s,op:"add"});if(d.ok){r=d.document,n+=1;continue}}o+=1}let i=r;return{document:{metadata:typeof i.metadata=="object"&&i.metadata!==null?i.metadata:{},body:typeof i.body=="string"?i.body:e.body},convertedReplaceToAdd:n,skippedOps:o}}function Ad(e){let t=Ed(e);if(t.length===1)return t[0];let r=Si(e);return r.ok&&r.item_hash_version!==void 0?r.item_hash_version:t.length===0?1:ye}function xd(e,t,r=t.patch){let n=Nt(e,r);if(n.ok)return{next:n.document,patch:r,repaired:T(r)!==T(t.patch),converted:0,skipped:0};let o=Td(e,r);return{next:o.document,patch:Xr.compare(e,o.document),repaired:!0,converted:o.convertedReplaceToAdd,skipped:o.skippedOps}}function Cd(e,t,r){return xd(e,t,r.projectPatch?.(t,e))}function bf(e,t=Ad(e),r={}){let n=e.findIndex(S=>Ei(S.item_hash_version));if(n>=0)throw new TypeError(`unsupported_item_hash_version:${String(e[n]?.item_hash_version)}:entry_${n+1}`);let o=xt(),i=[],s=[],a=0,d=0,l=0,_=0,v,O=t!==1||e.some(S=>S.item_hash_version!==void 0);for(let S=0;S<e.length;S+=1){let I=e[S];Id(I,S);let z=Cd(o,I,r),{next:D,patch:$,repaired:Ze,converted:vn,skipped:bn}=z;l+=vn,_+=bn,d+=Number(Ze);let ie=bi(o,D,t,I);v===void 0||r.continuousHashSurface!==!0?v=[ie.pairIndex,ie.beforeIndex,ie.afterIndex,Math.min(v??0,ie.beforeHashes.length-1)].find(_s=>_s>=0):v=Math.min(v,ie.beforeHashes.length-1);let wn=ie.beforeHashes[v],En=ie.afterHashes[v],Gt=wn!==I.before_hash||En!==I.after_hash;Gt&&(a+=1);let be={...I,patch:$,before_hash:wn,after_hash:En};O?be.item_hash_version=t:delete be.item_hash_version;let us=be.item_hash_version!==I.item_hash_version;(Gt||Ze||us)&&(be=fi(I,be,{retainOriginalPatch:Ze})),i.push(be),s.push({index:S+1,rehashed:Gt,patch_repaired:Ze,converted_replace_to_add:vn,skipped_ops:bn}),o=D}return{entries:i,finalDocument:o,entriesRehashed:a,entriesPatchRepaired:d,convertedReplaceToAdd:l,skippedOps:_,details:s,itemHashVersion:t,explicitItemHashVersion:O}}function wf(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
72
+ `)}
73
+ `}import Nd from"node:fs/promises";import De from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="af606b47-d071-5724-b1e7-de4e1e5d7385")}catch{}})();var Pe="_workspace";function Rt(e){return De.join(e,"history",`${Pe}.jsonl`)}function Rd(e,t){return{metadata:{id:Pe,title:"Workspace state",description:"Audited singleton workspace document state.",type:"Chore",status:"open",priority:2,tags:["workspace-history"],created_at:t,updated_at:t,documents:e},body:""}}function Dt(e,t=e.length){let r=xt();for(let n of e.slice(0,t))r=Nt(r,n.patch).document;return Ct(r)}function Yr(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function Pt(e){throw new b(`Workspace history verification failed: ${e.join(", ")}`,w.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...e],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function Ii(e,t){let r=De.resolve(t),n=De.relative(e,r).replaceAll("\\","/");if(n.length===0||n===".."||n.startsWith("../")||De.isAbsolute(n))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:n,absolutePath:r}}async function Pf(e){let t=await me(Rt(e),Pe),r=Ke(t);r.ok||Pt(r.errors);let n=Yr(t.length===0?Le:Dt(t)),o=[],i=[],s=[],a=[];for(let d of Object.keys(n).sort()){let l;try{let _=Ii(e,De.resolve(e,d));if(l=await J(_.absolutePath),l===null){s.push(d);continue}let v=JSON.parse(l);(T(v)===T(n[d])?o:i).push(d)}catch{a.push(d)}}return{ok:i.length===0&&s.length===0&&a.length===0,document_count:Object.keys(n).length,matching_documents:o,mismatched_documents:i,missing_documents:s,unreadable_documents:a}}async function Oi(e){let t=Rt(e.pmRoot),r=await me(t,Pe),n=Ke(r);n.ok||Pt(n.errors);let o=e.idempotencyKey===void 0?void 0:r.find(v=>v.op===`${e.op}:${e.idempotencyKey}`);if(o)return{entry:o,historyPath:t};let i=Me(),s=r.length===0?Le:Dt(r),a=Yr(s),d=a[e.documentPath];if(d!==void 0&&T(d)!==T(e.before))throw new b(`Workspace history state for "${e.documentPath}" changed outside the audited mutation path.`,w.CONFLICT,{code:"workspace_history_state_conflict",reason:"out_of_band_workspace_state",required:"Reconcile the singleton document with its matching _workspace history state before retrying the mutation.",why:"Accepting the write would make the append-only audit stream describe a state that was not actually observed.",examples:["pm history _workspace --verify","pm validate --check-history-drift --fix-hints"],nextSteps:["Review the version-control change that altered the singleton and preserve the intended document plus its matching workspace history.","Rerun the original mutation only after the on-disk singleton agrees with the latest audited workspace state."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify"}});let l=Rd({...a,[e.documentPath]:e.after},r.length===0?i:s.metadata.created_at),_=Br({nowIso:i,author:e.author,op:e.idempotencyKey===void 0?e.op:`${e.op}:${e.idempotencyKey}`,before:s,after:l,message:e.message});return await Jr(t,_),{entry:_,historyPath:t}}async function jf(e){let t=await V(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await Oi(e)}finally{await t()}}async function Lf(e){let t=await V(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let r=Rt(e.pmRoot),n=await me(r,Pe),o=Ke(n);o.ok||Pt(o.errors);let i=n.length===0?Le:Dt(n),s=Br({nowIso:Me(),author:e.author,op:e.op,before:i,after:i,message:e.message,context:e.context});return await Jr(r,s),{entry:s,historyPath:r}}finally{await t()}}async function Ti(e,t){if(t===e.raw)return!1;let r=t===null?null:JSON.parse(t),n=JSON.parse(e.raw);await He(e.filePath,e.raw);try{(t!==null||e.recordCreation!==!1)&&await Oi({pmRoot:e.pmRoot,documentPath:De.relative(e.pmRoot,e.filePath).replaceAll("\\","/"),before:r,after:n,op:e.op,idempotencyKey:e.idempotencyKey,author:e.author,lockTtlSeconds:e.lockTtlSeconds,lockWaitMs:e.lockWaitMs,message:e.message})}catch(o){throw t===null?await Nd.rm(e.filePath,{force:!0}):await He(e.filePath,t),o}return!0}async function Ai(e){let{documentPath:t}=Ii(e.pmRoot,e.filePath),r=await V(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=await J(e.filePath);if(e.dryRun===!0||e.idempotencyKey!==void 0){let i=await me(Rt(e.pmRoot),Pe),s=Ke(i);s.ok||Pt(s.errors);let a=Yr(i.length===0?Le:Dt(i))[t];if(a!==void 0&&T(a)!==T(n===null?null:JSON.parse(n)))throw new b(`Workspace history state for "${t}" changed outside the audited mutation path.`,w.CONFLICT,{code:"workspace_history_state_conflict"});if(e.idempotencyKey!==void 0&&i.some(d=>d.op===`${e.op}:${e.idempotencyKey}`))return{changed:!1,result:void 0,replayed:!0}}let o=await e.mutate(n);return JSON.parse(o.raw),e.dryRun===!0?{changed:n!==o.raw,result:o.result}:{changed:await Ti({...e,raw:o.raw},n),result:o.result}}finally{await r()}}async function Hf(e){let t=await V(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await Ti(e,await J(e.filePath))}finally{await t()}}import{AsyncLocalStorage as Zd}from"node:async_hooks";import{lstat as Qd,realpath as zi}from"node:fs/promises";import Fi from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f4ae942c-f11f-5d24-95bf-a2abf3c226da")}catch{}})();var j={ok:!1},u=e=>typeof e=="string"?{ok:!0,value:e}:j,E=e=>typeof e=="boolean"?{ok:!0,value:e}:j;function x(e={}){return t=>typeof t!="number"||!Number.isFinite(t)||e.int&&(!Number.isInteger(t)||!Number.isSafeInteger(t))||e.positive&&t<=0||typeof e.min=="number"&&t<e.min||typeof e.max=="number"&&t>e.max?j:{ok:!0,value:t}}function k(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:j}function m(e,t){return r=>{if(!Array.isArray(r)||t!==void 0&&r.length>t)return j;let n=[];for(let o of r){let i=e(o);if(!i.ok)return j;n.push(i.value)}return{ok:!0,value:n}}}function Qr(e,t){return r=>typeof r=="string"&&r.length>0&&r.length<=e&&r===r.trim()&&(t===void 0||t.test(r))?{ok:!0,value:r}:j}function c(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function jt(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return j;let r={};for(let[n,o]of Object.entries(t)){let i=e(o);if(!i.ok)return j;r[n]=i.value}return{ok:!0,value:r}}}function g(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return j;let r=t,n={};for(let[o,i]of Object.entries(e)){let s=i(r[o]);if(!s.ok)return j;s.value!==void 0&&(n[o]=s.value)}return{ok:!0,value:n}}}var Dd=g({key:u,values:m(u),required:c(E),aliases:c(m(u)),description:c(u)}),Pd=g({command:k("create","update"),option:u,required:c(E),visible:c(E),enabled:c(E)}),jd=g({name:u,description:c(u),default_status:c(u),execution_role:c(k("agent","human","gate")),folder:c(u),aliases:c(m(u)),required_create_fields:c(m(u)),required_create_repeatables:c(m(u)),options:c(m(Dd)),command_option_policies:c(m(Pd))}),Ld=g({id:u,aliases:c(m(u)),roles:c(m(k(...kn))),description:c(u),order:c(x())}),Hd=g({key:u,metadata_key:c(u),front_matter_key:c(u),cli_flag:c(u),cli_aliases:c(m(u)),description:c(u),type:c(k(...Sn)),commands:c(m(k(...In))),repeatable:c(E),required:c(E),required_on_create:c(E),required_types:c(m(u)),allow_unset:c(E)}),zd=e=>{if(!Array.isArray(e)||e.length!==2)return j;let[t,r]=e;return typeof t!="string"||typeof r!="string"?j:{ok:!0,value:[t,r]}},Fd=g({type:u,allowed_transitions:m(zd)}),$d=c(g({version:c(x({int:!0})),files:c(g({types:c(u),statuses:c(u),fields:c(u),workflows:c(u)})),statuses:c(m(Ld)),fields:c(m(Hd)),workflow:c(g({draft_status:c(u),open_status:c(u),in_progress_status:c(u),blocked_status:c(u),close_status:c(u),canceled_status:c(u)})),type_workflows:c(m(Fd)),unknown_field_policy:c(k(...On))})),Md=c(g({preset:c(k(...Tn)),ownership_enforcement:c(k("none","warn","strict")),create_mode_default:c(k("progressive","strict")),close_validation_default:c(k("off","warn","strict")),require_close_reason:c(E),parent_reference:c(k("warn","strict_error")),metadata_profile:c(k("core","strict","custom")),force_required_for_stale_lock:c(E),create_default_type:c(u),workflow_enforcement:c(k("off","warn","strict")),duplicate_detection_mode:c(k("off","advisory","strict")),duplicate_detection_threshold:c(x({min:0,max:1})),duplicate_detection_limit:c(x({int:!0,min:0,max:20}))})),Vd=g({name:u,disabled:c(E),require_trusted:c(E),require_provenance:c(E),sandbox_profile:c(k("none","restricted","strict")),allowed_capabilities:c(m(u)),blocked_capabilities:c(m(u)),allowed_surfaces:c(m(u)),blocked_surfaces:c(m(u)),allowed_commands:c(m(u)),blocked_commands:c(m(u)),allowed_actions:c(m(u)),blocked_actions:c(m(u)),allowed_services:c(m(u)),blocked_services:c(m(u))}),Zr=k("block","warn"),Ud=e=>typeof e=="string"?Zr(e):g({global:c(Zr),project:c(Zr)})(e),Wd=c(g({mode:c(k("off","warn","enforce")),trust_mode:c(k("off","warn","enforce")),pm_max_version_exceeded_mode:c(Ud),require_provenance:c(E),trusted_extensions:c(m(u)),default_sandbox_profile:c(k("none","restricted","strict")),allowed_extensions:c(m(u)),blocked_extensions:c(m(u)),allowed_capabilities:c(m(u)),blocked_capabilities:c(m(u)),allowed_surfaces:c(m(u)),blocked_surfaces:c(m(u)),allowed_commands:c(m(u)),blocked_commands:c(m(u)),allowed_actions:c(m(u)),blocked_actions:c(m(u)),allowed_services:c(m(u)),blocked_services:c(m(u)),extension_overrides:c(m(Vd))})),ve=Qr(128),qd=g({harness:Qr(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:c(m(ve,64)),model_environment_keys:c(m(ve,64)),session_environment_keys:c(m(ve,64)),provenance_environment_keys:c(jt(m(ve,64))),provenance_resolvers:c(jt(k("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:c(m(ve,64)),argv_markers:c(m(ve,64)),client_names:c(m(ve,64))}),Gd=g({version:x({int:!0}),id_prefix:u,ids:c(g({token_length:c(x({int:!0,min:4,max:12}))})),author_default:u,agent_identity:c(g({probes_enabled:c(E),identity_vocabulary:c(g({version:x({int:!0,positive:!0}),aliases:jt(Qr(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:m(qd)})),mutation_guard:c(g({require_attributed_author:c(E),secret_guard:c(k("off","advise","block")),stale_in_progress_hours:c(x({int:!0,positive:!0}))})),item_format:c(k("toon","json_markdown")),locks:g({ttl_seconds:x({int:!0}),wait_ms:c(x({int:!0,min:0}))}),checkpoints:c(g({retention_days:c(x({int:!0,positive:!0}))})),output:g({default_format:k("toon","json")}),ux:c(g({deprecation_hints:c(E)})),history:c(g({missing_stream:k("auto_create","strict_error"),compact_policy:c(g({enabled:c(E),max_entries:c(x({int:!0,positive:!0})),trigger:c(k("health_warn","auto"))}))})),validation:c(g({sprint_release_format:k("warn","strict_error"),parent_reference:c(k("warn","strict_error")),metadata_profile:c(k("core","strict","custom")),metadata_required_fields:c(m(u)),lifecycle_stale_blocker_reason_patterns:c(m(u)),lifecycle_closure_like_blocked_reason_patterns:c(m(u)),lifecycle_closure_like_resolution_patterns:c(m(u)),lifecycle_closure_like_actual_result_patterns:c(m(u)),estimate_defaults_by_type:c(jt(x({int:!0,positive:!0})))})),governance:Md,workflow:c(g({definition_of_done:m(u)})),testing:c(g({record_results_to_items:E,allow_untrusted_linked_tests:c(E)})),telemetry:c(g({enabled:E,first_run_prompt_completed:c(E),capture_level:c(k("minimal","redacted","max")),endpoint:c(u),installation_id:c(u),retention_days:c(x({int:!0,positive:!0}))})),agent_guidance:c(g({prompt_completed:c(E),declined:c(E),declined_at:c(u),template_version:c(x({int:!0,positive:!0})),last_checked_files:c(m(u))})),item_types:c(g({definitions:m(jd)})),schema:$d,context:c(g({default_depth:c(k("brief","standard","deep")),activity_limit:c(x({int:!0,positive:!0})),stale_threshold_days:c(x({int:!0,positive:!0})),sections:c(g({hierarchy:c(E),activity:c(E),progress:c(E),recently_created:c(E),unparented:c(E),blockers:c(E),files:c(E),workload:c(E),staleness:c(E),tests:c(E)}))})),extensions:g({enabled:m(u),disabled:m(u),policy:Wd}),search:g({score_threshold:x(),hybrid_semantic_weight:c(x()),max_results:x({int:!0}),embedding_model:u,embedding_corpus_max_characters:c(x()),embedding_batch_size:x({int:!0}),embedding_timeout_ms:c(x({int:!0})),scanner_max_batch_retries:x({int:!0}),provider:c(u),default_mode:c(k("auto","keyword","semantic","hybrid")),corpus_fields:c(m(u)),mutation_refresh_policy:c(k("cache_only","semantic_configured","semantic_auto")),query_expansion:c(g({enabled:c(E),provider:c(u)})),rerank:c(g({enabled:c(E),model:c(u),top_k:c(x({int:!0,positive:!0}))})),bm25:c(g({k1:c(x()),b:c(x())}))}),providers:g({openai:g({base_url:u,api_key:u,model:u}),ollama:g({base_url:u,model:u})}),vector_store:g({adapter:c(u),collection_name:c(u),qdrant:g({url:u,api_key:u}),lancedb:g({path:u})})});function en(e){let t=Gd(e);return t.ok?{success:!0,data:t.value}:{success:!1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a0ca9902-540c-50fe-a4e2-9c234c4a01f3")}catch{}})();function Lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tn(e,t,r,n=[]){if(M(e,t)&&(n.length>0||Lt(r)))return r;if(M(e,r)||M(t,r))return t;if((e===void 0||Lt(e))&&Lt(t)&&Lt(r)){let o=e??{},i=new Set([...Object.keys(o),...Object.keys(t),...Object.keys(r)]);return Object.fromEntries([...i].flatMap(s=>{let a=tn(Object.hasOwn(o,s)?o[s]:void 0,Object.hasOwn(t,s)?t[s]:void 0,Object.hasOwn(r,s)?r[s]:void 0,[...n,s]);return a===void 0?[]:[[s,a]]}))}throw new b(`Settings changed concurrently at ${n.join(".")||"<root>"}; read the latest settings and reapply the intended change.`,w.CONFLICT,{reason:"stale_settings_snapshot",required:"Read a fresh settings snapshot and reapply the intended change.",why:"Another writer changed the same setting after this snapshot was read.",examples:["pm config project export --json"],nextSteps:["Read the current settings, then retry the original config operation."]})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="de43e8e6-d7ef-53cc-94b0-ccdf1c4f94a3")}catch{}})();var Bd={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},xi=120;function rn(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function Ni(e){let t=new Map;for(let[r,n]of Object.entries(e))t.set(r.toLowerCase(),n);return t}var Jd=Ni(Bd),Ci=new WeakMap;function Kd(e){let t=Ci.get(e);if(t)return t;let r=Ni(e);return Ci.set(e,r),r}function qf(e,t){let r=(e??"").trim().toLowerCase();if(r.length===0)return xi;if(t){let o=Kd(t).get(r);if(rn(o))return Math.floor(o)}let n=Jd.get(r);return rn(n)?Math.floor(n):xi}function nn(e){let t={};if(e===null||typeof e!="object"||Array.isArray(e))return t;for(let[r,n]of Object.entries(e)){let o=r.trim();o.length===0||!rn(n)||(t[o]=Math.floor(n))}return t}import{stat as Xd}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="78c79deb-5cf0-54fe-b98c-a0d5b3671ab2")}catch{}})();var Ht=new Map;function Ri(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}async function Yd(e){try{let t=await Xd(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function te(e){let t=Ri(e),r=await Promise.all(t.map(n=>Yd(n)));return r.sort((n,o)=>n.path.localeCompare(o.path)),r}function Xe(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){let n=e[r],o=t[r];if(n.path!==o.path||n.mtime_ms!==o.mtime_ms||n.size!==o.size)return!1}return!0}function Di(e){return Ht.get(e)}function zt(e,t){let r=Ri(t.tracked_paths),n=[...t.signatures].map(o=>({path:o.path,mtime_ms:o.mtime_ms,size:o.size})).sort((o,i)=>o.path.localeCompare(i.path));Ht.set(e,{tracked_paths:r,signatures:n,value:t.value})}function re(e){if(e){Ht.delete(e);return}Ht.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bbb5e299-541d-5fff-8422-855c85cf7a31")}catch{}})();var cn=new Zd;async function _m(e,t,r=()=>!0){let n=new Set([Fi.resolve(e)]);try{n.add(await zi(e))}catch{}return cn.run([...cn.getStore()??[],[n,r]],t)}function el(e){let t=Fi.resolve(e);return cn.getStore()?.some(([r,n])=>r.has(t)&&n())??!1}var tl="settings:write",$i=Symbol("pm.settings.persist_source"),rl=128,nl=new Set(["off","advisory","strict"]);function Pi(e){return structuredClone(xn[e])}function ol(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:p.governance.preset}function ji(e,t){let r=typeof t.create_default_type=="string"?t.create_default_type.trim():void 0;return r&&r.length>0&&(e.create_default_type=r),(t.workflow_enforcement==="off"||t.workflow_enforcement==="warn"||t.workflow_enforcement==="strict")&&(e.workflow_enforcement=t.workflow_enforcement),t.require_close_reason===!1&&(e.require_close_reason=!1),e.duplicate_detection_mode=t.duplicate_detection_mode,e.duplicate_detection_threshold=t.duplicate_detection_threshold,e.duplicate_detection_limit=t.duplicate_detection_limit,e}function il(e){return e.preset==="custom"?ji({preset:"custom",ownership_enforcement:e.ownership_enforcement,create_mode_default:e.create_mode_default,close_validation_default:e.close_validation_default,parent_reference:e.parent_reference,metadata_profile:e.metadata_profile,force_required_for_stale_lock:e.force_required_for_stale_lock},e):ji({preset:e.preset},e)}function sl(e){let t=typeof e.create_default_type=="string"?e.create_default_type.trim():void 0,r={};t&&t.length>0&&(r.create_default_type=t),(e.workflow_enforcement==="off"||e.workflow_enforcement==="warn"||e.workflow_enforcement==="strict")&&(r.workflow_enforcement=e.workflow_enforcement),typeof e.require_close_reason=="boolean"&&(r.require_close_reason=e.require_close_reason),nl.has(String(e.duplicate_detection_mode))&&(r.duplicate_detection_mode=e.duplicate_detection_mode);let n=e.duplicate_detection_threshold;[typeof n=="number",Number.isFinite(n),Number(n)>=0,Number(n)<=1].every(Boolean)&&(r.duplicate_detection_threshold=n);let o=e.duplicate_detection_limit;return[typeof o=="number",Number.isSafeInteger(o),Number(o)>=0,Number(o)<=20].every(Boolean)&&(r.duplicate_detection_limit=o),r}function Mi(e){let t=e.governance??{},r=ol(t.preset),n=sl(t);if(r==="custom"){let s=Pi("default"),a=n.require_close_reason??s.require_close_reason;return{preset:r,ownership_enforcement:t.ownership_enforcement??s.ownership_enforcement,create_mode_default:t.create_mode_default??s.create_mode_default,close_validation_default:t.close_validation_default??s.close_validation_default,parent_reference:t.parent_reference??s.parent_reference,metadata_profile:t.metadata_profile??s.metadata_profile,force_required_for_stale_lock:t.force_required_for_stale_lock??s.force_required_for_stale_lock,...n,require_close_reason:a,duplicate_detection_mode:n.duplicate_detection_mode??s.duplicate_detection_mode,duplicate_detection_threshold:n.duplicate_detection_threshold??s.duplicate_detection_threshold,duplicate_detection_limit:n.duplicate_detection_limit??s.duplicate_detection_limit}}let o=Pi(r),i=n.require_close_reason??o.require_close_reason;return{preset:r,...o,...n,require_close_reason:i}}function Vi(){return structuredClone(p)}function Ui(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:p.search.mutation_refresh_policy}function Wi(e){return e==="auto"||e==="keyword"||e==="semantic"||e==="hybrid"?e:"auto"}function qi(e){return typeof e=="boolean"?e:p.search.query_expansion.enabled}function Gi(e){return typeof e!="string"?p.search.query_expansion.provider:e.trim()}function Bi(e){return typeof e=="boolean"?e:p.search.rerank.enabled}function Ji(e){return typeof e!="string"?p.search.rerank.model:e.trim()}function Ki(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:p.search.rerank.top_k}function Xi(e){if(typeof e!="string")return p.vector_store.collection_name;let t=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,rl);return t.length>0?t:p.vector_store.collection_name}function on(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function Yi(e,t){let r=e.schema,n=on(r?.statuses),o=on(r?.fields),i=on(r?.type_workflows);return{persisted_settings:structuredClone(e),source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:je(e.item_types?.definitions),has_source_schema_statuses:n.present,source_schema_statuses:n.values,has_source_schema_fields:o.present,source_schema_fields:o.values,has_source_schema_type_workflows:i.present,source_schema_type_workflows:i.values,runtime_item_type_definitions:je(t.item_types?.definitions),runtime_schema_statuses:structuredClone(t.schema.statuses),runtime_schema_fields:structuredClone(t.schema.fields),runtime_schema_type_workflows:structuredClone(t.schema.type_workflows??[])}}function un(e,t){Object.defineProperty(e,$i,{value:t,writable:!0,configurable:!0,enumerable:!1})}function Zi(e){let t=e[$i];if(!(!t||typeof t!="object"))return t}function Ft(e){let t=structuredClone(e.settings),r=Zi(e.settings);return r&&un(t,r),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function al(e,t,r){let n=Fe(t);return[r,$e(e,n.files.types,ze.types),$e(e,n.files.statuses,ze.statuses),$e(e,n.files.fields,ze.fields),$e(e,n.files.workflows,ze.workflows)]}async function cl(e,t,r){let n=await te(t);zt(e,{tracked_paths:t,signatures:n,value:Ft(r)})}async function dl(e,t,r){try{await cl(e,t,r)}catch{re(e)}}function Li(e,t){return e.find(r=>r.path===t)}function ll(e,t,r){for(let n of r){let o=Li(e,n),i=Li(t,n);if(!o||!i||!Xe([o],[i]))return!1}return!0}async function sn(e,t,r,n,o){try{let i=await te(t);if(!ll(n,i,o)){re(e);return}zt(e,{tracked_paths:t,signatures:i,value:Ft(r)})}catch{re(e)}}function ul(e,t){let r=Fe(e.schema),n=je(e.item_types?.definitions);if(!t)return{item_type_definitions:n,schema_statuses:r.statuses,schema_fields:r.fields,schema_type_workflows:r.type_workflows};let o=r.type_workflows??[],i=M(n,t.runtime_item_type_definitions),s=M(r.statuses,t.runtime_schema_statuses),a=M(r.fields,t.runtime_schema_fields),d=M(o,t.runtime_schema_type_workflows);return{item_type_definitions:i?t.has_source_item_type_definitions?je(t.source_item_type_definitions):[]:n,schema_statuses:s?t.has_source_schema_statuses?structuredClone(t.source_schema_statuses):[]:r.statuses,schema_fields:a?t.has_source_schema_fields?structuredClone(t.source_schema_fields):[]:r.fields,schema_type_workflows:d?t.has_source_schema_type_workflows?structuredClone(t.source_schema_type_workflows):void 0:r.type_workflows}}function W(e){return{settings:Vi(),metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function Qi(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function dn(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function es(e){let t=p.agent_guidance,r=e?.template_version;return{prompt_completed:e?.prompt_completed===!0,declined:e?.declined===!0,declined_at:typeof e?.declined_at=="string"?e.declined_at:t.declined_at,template_version:typeof r=="number"&&Number.isInteger(r)&&r>0?r:t.template_version,last_checked_files:dn(e?.last_checked_files??t.last_checked_files)}}function F(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function _l(e){return e==="off"||e==="warn"||e==="enforce"?e:p.extensions.policy.mode}function fl(e){return e==="off"||e==="warn"||e==="enforce"?e:p.extensions.policy.trust_mode}function ts(e){return e==="none"||e==="restricted"||e==="strict"?e:p.extensions.policy.default_sandbox_profile}function ml(e){let t=e.name.trim().toLowerCase();if(t.length===0)return null;let r={name:t};e.disabled===!0&&(r.disabled=!0),e.require_trusted===!0&&(r.require_trusted=!0),e.require_provenance===!0&&(r.require_provenance=!0),e.sandbox_profile!==void 0&&(r.sandbox_profile=ts(e.sandbox_profile));let n=F(e.allowed_capabilities),o=F(e.blocked_capabilities),i=F(e.allowed_surfaces),s=F(e.blocked_surfaces),a=F(e.allowed_commands),d=F(e.blocked_commands),l=F(e.allowed_actions),_=F(e.blocked_actions),v=F(e.allowed_services),O=F(e.blocked_services);return n.length>0&&(r.allowed_capabilities=n),o.length>0&&(r.blocked_capabilities=o),i.length>0&&(r.allowed_surfaces=i),s.length>0&&(r.blocked_surfaces=s),a.length>0&&(r.allowed_commands=a),d.length>0&&(r.blocked_commands=d),l.length>0&&(r.allowed_actions=l),_.length>0&&(r.blocked_actions=_),v.length>0&&(r.allowed_services=v),O.length>0&&(r.blocked_services=O),r}function pl(e){let t=new Map;for(let r of e??[]){let n=ml(r);n&&t.set(n.name,n)}return[...t.values()].sort((r,n)=>r.name.localeCompare(n.name))}function an(e){return e==="block"||e==="warn"?e:void 0}function hl(e){if(typeof e=="string")return an(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=an(e.global),r=an(e.project);return t===void 0&&r===void 0?void 0:{...t!==void 0?{global:t}:{},...r!==void 0?{project:r}:{}}}}function L(e,t){return F(e?.[t]??p.extensions.policy[t])}function rs(e){let t=hl(e?.pm_max_version_exceeded_mode);return{mode:_l(e?.mode),trust_mode:fl(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:L(e,"trusted_extensions"),default_sandbox_profile:ts(e?.default_sandbox_profile),allowed_extensions:L(e,"allowed_extensions"),blocked_extensions:L(e,"blocked_extensions"),allowed_capabilities:L(e,"allowed_capabilities"),blocked_capabilities:L(e,"blocked_capabilities"),allowed_surfaces:L(e,"allowed_surfaces"),blocked_surfaces:L(e,"blocked_surfaces"),allowed_commands:L(e,"allowed_commands"),blocked_commands:L(e,"blocked_commands"),allowed_actions:L(e,"allowed_actions"),blocked_actions:L(e,"blocked_actions"),allowed_services:L(e,"allowed_services"),blocked_services:L(e,"blocked_services"),extension_overrides:pl(e?.extension_overrides??p.extensions.policy.extension_overrides)}}function ns(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].filter(t=>t.length>0).sort((t,r)=>t.localeCompare(r)).filter(t=>["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"].includes(t))}function ne(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function R(e,t){return e===void 0?t:e}function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function ln(e){return Array.isArray(e)?e:[]}function yl(e,t,r){return{...t.validation,...e.validation,parent_reference:r.parent_reference,metadata_profile:r.metadata_profile,metadata_required_fields:ns(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:ne(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:ne(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:ne(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:ne(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:nn(e.validation?.estimate_defaults_by_type)}}function gl(e,t){return{enabled:e.telemetry?.enabled??t.telemetry.enabled,first_run_prompt_completed:e.telemetry?.first_run_prompt_completed??t.telemetry.first_run_prompt_completed,capture_level:e.telemetry?.capture_level??t.telemetry.capture_level,endpoint:e.telemetry?.endpoint??t.telemetry.endpoint,installation_id:e.telemetry?.installation_id??t.telemetry.installation_id,retention_days:e.telemetry?.retention_days??t.telemetry.retention_days}}function vl(e,t){return{...t.search,...e.search,default_mode:Wi(e.search?.default_mode),mutation_refresh_policy:Ui(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:qi(e.search?.query_expansion?.enabled),provider:Gi(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:Bi(e.search?.rerank?.enabled),model:Ji(e.search?.rerank?.model),top_k:Ki(e.search?.rerank?.top_k)}}}function bl(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:Xi(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function wl(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function El(e,t){return{default_depth:e.context?.default_depth??t.context.default_depth,activity_limit:e.context?.activity_limit??t.context.activity_limit,stale_threshold_days:e.context?.stale_threshold_days??t.context.stale_threshold_days,sections:{...t.context.sections,...e.context?.sections}}}function kl(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function je(e){let t=(e??[]).map(n=>Pn(n)).filter(n=>n!==null),r=new Map;for(let n of t)r.set(n.name.toLowerCase(),n);return[...r.values()].sort((n,o)=>n.name.localeCompare(o.name))}function $t(e){let t=Vi(),r=Mi({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:wl(e,t),locks:{...t.locks,...e.locks},ids:{...t.ids,...e.ids},agent_identity:structuredClone(e.agent_identity??t.agent_identity),mutation_guard:{...t.mutation_guard,...e.mutation_guard},checkpoints:{...t.checkpoints,...e.checkpoints},output:{...t.output,...e.output},ux:{...t.ux,...e.ux},history:{...t.history,...e.history,compact_policy:{...t.history.compact_policy,...e.history?.compact_policy}},validation:yl(e,t,r),governance:r,workflow:{definition_of_done:[...e.workflow?.definition_of_done??t.workflow.definition_of_done]},testing:{record_results_to_items:e.testing?.record_results_to_items??t.testing.record_results_to_items,allow_untrusted_linked_tests:e.testing?.allow_untrusted_linked_tests??t.testing.allow_untrusted_linked_tests},telemetry:gl(e,t),agent_guidance:es(e.agent_guidance??t.agent_guidance),item_types:{definitions:je(e.item_types?.definitions)},schema:Fe(e.schema??t.schema),context:El(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:rs(e.extensions.policy??t.extensions.policy)},search:vl(e,t),providers:kl(e,t),vector_store:bl(e,t)}}function Sl(e){e.agent_identity=y(e.agent_identity,["probes_enabled","identity_vocabulary","harness_signals"]);let t=e.agent_identity;Object.hasOwn(t,"identity_vocabulary")&&(t.identity_vocabulary=y(H(t.identity_vocabulary),["version","aliases"])),e.agent_identity.harness_signals=ln(e.agent_identity.harness_signals).map(r=>y(H(r),["harness","environment_keys","model_environment_keys","session_environment_keys","provenance_environment_keys","provenance_resolvers","provenance_unavailable_dimensions","argv_markers","client_names"])),e.locks=y(e.locks,["ttl_seconds","wait_ms"]),e.ids=y(e.ids,["token_length"]),e.mutation_guard=y(e.mutation_guard,["require_attributed_author","secret_guard","stale_in_progress_hours"]),e.checkpoints=y(e.checkpoints,["retention_days"]),e.output=y(e.output,["default_format"]),e.ux=y(e.ux,["deprecation_hints"]),e.history=y(e.history,["missing_stream","compact_policy"]),e.validation=y(e.validation,["sprint_release_format","parent_reference","metadata_profile","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns","estimate_defaults_by_type"]),e.governance=y(e.governance,["preset","ownership_enforcement","create_mode_default","close_validation_default","require_close_reason","parent_reference","metadata_profile","force_required_for_stale_lock","create_default_type","workflow_enforcement","duplicate_detection_mode","duplicate_detection_threshold","duplicate_detection_limit"]),e.workflow=y(e.workflow,["definition_of_done"]),e.testing=y(e.testing,["record_results_to_items","allow_untrusted_linked_tests"]),e.telemetry=y(e.telemetry,["enabled","first_run_prompt_completed","capture_level","endpoint","installation_id","retention_days"]),e.agent_guidance=y(e.agent_guidance,["prompt_completed","declined","declined_at","template_version","last_checked_files"]),e.item_types=y(e.item_types,["definitions"]),e.schema=y(e.schema,["version","files","statuses","fields","workflow","type_workflows","unknown_field_policy"]),e.schema.files=y(H(e.schema.files),["types","statuses","fields","workflows"]),e.schema.workflow=y(H(e.schema.workflow),["draft_status","open_status","in_progress_status","blocked_status","close_status","canceled_status"]),e.context=y(e.context,["default_depth","activity_limit","stale_threshold_days","sections"]),e.context.sections=y(H(e.context.sections),["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]),e.extensions=y(e.extensions,["enabled","disabled","policy"]),e.extensions.policy=y(H(e.extensions.policy),["mode","trust_mode","pm_max_version_exceeded_mode","require_provenance","trusted_extensions","default_sandbox_profile","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services","extension_overrides"]),e.extensions.policy.extension_overrides=ln(e.extensions.policy.extension_overrides).map(r=>y(H(r),["name","disabled","require_trusted","require_provenance","sandbox_profile","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"])),e.search=y(e.search,["score_threshold","hybrid_semantic_weight","max_results","embedding_model","embedding_corpus_max_characters","embedding_batch_size","embedding_timeout_ms","scanner_max_batch_retries","provider","default_mode","mutation_refresh_policy","query_expansion","rerank"]),e.search.query_expansion=y(H(e.search.query_expansion),["enabled","provider"]),e.search.rerank=y(H(e.search.rerank),["enabled","model","top_k"]),e.providers=y(e.providers,["openai","ollama"]),e.providers.openai=y(H(e.providers.openai),["base_url","api_key","model"]),e.providers.ollama=y(H(e.providers.ollama),["base_url","model"]),e.vector_store=y(e.vector_store,["adapter","collection_name","qdrant","lancedb"]),e.vector_store.qdrant=y(H(e.vector_store.qdrant),["url","api_key"]),e.vector_store.lancedb=y(H(e.vector_store.lancedb),["path"])}function Il(e){return{...e,locks:R(e.locks,p.locks),ids:R(e.ids,p.ids),agent_identity:R(e.agent_identity,p.agent_identity),mutation_guard:R(e.mutation_guard,p.mutation_guard),checkpoints:R(e.checkpoints,p.checkpoints),output:R(e.output,p.output),ux:R(e.ux,p.ux),history:R(e.history,p.history),validation:R(e.validation,p.validation),workflow:R(e.workflow,p.workflow),testing:R(e.testing,p.testing),telemetry:R(e.telemetry,p.telemetry),agent_guidance:R(e.agent_guidance,p.agent_guidance),item_types:R(e.item_types,p.item_types),schema:R(e.schema,p.schema),context:R(e.context,p.context),extensions:R(e.extensions,p.extensions),search:R(e.search,p.search),providers:R(e.providers,p.providers),vector_store:R(e.vector_store,p.vector_store)}}function Ol(e,t){return{...e.validation,parent_reference:t.parent_reference,metadata_profile:t.metadata_profile,metadata_required_fields:ns(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:ne(e.validation?.lifecycle_stale_blocker_reason_patterns??p.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:ne(e.validation?.lifecycle_closure_like_blocked_reason_patterns??p.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:ne(e.validation?.lifecycle_closure_like_resolution_patterns??p.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:ne(e.validation?.lifecycle_closure_like_actual_result_patterns??p.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:nn(e.validation?.estimate_defaults_by_type)}}function Tl(e){return{...p.search,...e.search,default_mode:Wi(e.search?.default_mode),mutation_refresh_policy:Ui(e.search?.mutation_refresh_policy),query_expansion:{...p.search.query_expansion,...e.search?.query_expansion,enabled:qi(e.search?.query_expansion?.enabled),provider:Gi(e.search?.query_expansion?.provider)},rerank:{...p.search.rerank,...e.search?.rerank,enabled:Bi(e.search?.rerank?.enabled),model:Ji(e.search?.rerank?.model),top_k:Ki(e.search?.rerank?.top_k)}}}function Al(e){return{default_depth:e.context?.default_depth??p.context.default_depth,activity_limit:e.context?.activity_limit??p.context.activity_limit,stale_threshold_days:e.context?.stale_threshold_days??p.context.stale_threshold_days,sections:{...p.context.sections,...e.context?.sections}}}function xl(e){return{...e.vector_store,adapter:e.vector_store?.adapter??p.vector_store.adapter,collection_name:Xi(e.vector_store?.collection_name),qdrant:{...e.vector_store?.qdrant},lancedb:{...e.vector_store?.lancedb}}}function Cl(e,t,r,n){return{...e,item_format:"toon",validation:Ol(e,t),governance:t,agent_guidance:es(e.agent_guidance),item_types:{definitions:n.item_type_definitions},schema:{...r,statuses:n.schema_statuses,fields:n.schema_fields,type_workflows:n.schema_type_workflows},search:Tl(e),context:Al(e),extensions:{enabled:dn(e.extensions?.enabled),disabled:dn(e.extensions?.disabled),policy:rs(e.extensions?.policy)},vector_store:xl(e)}}function os(e,t){for(let r of Object.keys(t)){let n=Reflect.get(t,r),o=e[r];typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof o=="object"&&o!==null&&!Array.isArray(o)?os(o,n):e[r]=structuredClone(n)}}function is(e,t,r){let n=new Set([...Object.keys(t),...Object.keys(r)]);for(let o of n){let i=t[o],s=r[o];if(!M(i,s)){if(s===void 0){delete e[o];continue}if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=e[o],d=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{};is(d,i,s),Object.keys(d).length>0?e[o]=d:delete e[o];continue}e[o]=structuredClone(s)}}}var _n=["version","id_prefix","ids","author_default","agent_identity","mutation_guard","item_format","locks","checkpoints","output","ux","history","validation","governance","workflow","testing","telemetry","agent_guidance","item_types","schema","context","extensions","search","providers","vector_store"];function Hi(e,t){let r=Il(e),n=Mi(r),o=Fe(r.schema),i=ul(r,t),s=Cl(r,n,o,i),a=y({...s,governance:il(n)},_n);return Sl(a),a}function Nl(e,t={}){let r=t.source===void 0?t.persist_source:Yi(t.source.validated,$t(t.source.validated)),n=Hi(e,r);if(r){let o=$t(r.source_settings);o.item_types={definitions:structuredClone(r.runtime_item_type_definitions)},o.schema={...o.schema,statuses:structuredClone(r.runtime_schema_statuses),fields:structuredClone(r.runtime_schema_fields),type_workflows:structuredClone(r.runtime_schema_type_workflows)};let i=Hi(o,r);t.source!==void 0&&os(i,t.source.validated);let s=structuredClone(t.source===void 0?r.source_settings:t.source.raw);return is(s,i,n),`${JSON.stringify(y(s,_n),null,2)}
74
+ `}return`${JSON.stringify(n,null,2)}
75
+ `}async function Rl(e){let t;try{t=await zi(e)}catch(a){if(se(a))return W();throw a}let r=we(t),n;try{n=await Qd(r)}catch(a){if(se(a))return W();throw a}if(!n.isFile())throw Jt();let o;try{o=await Nn(r,Jt())}catch(a){if(se(a))return W();throw a}let i;try{i=JSON.parse(o)}catch{return W("settings_read_invalid_json")}let s=en(i);return s.success?{settings:$t(s.data),metadata:{has_explicit_item_format:Qi(i)},warnings:s.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[]}:W("settings_read_invalid_schema")}async function ss(e){if(el(e))return Rl(e);let t=we(e),r=[t];await it({path:t,scope:"project"});let n=Di(e);if(n){let l=await te(n.tracked_paths);if(Xe(l,n.signatures))return Ft(n.value)}let o=await te([t]),i;try{i=await J(t)}catch{return W("settings_read_fs_error")}if(i===null){let l=W();return await sn(e,[t],l,o,[t]),l}let s=await te([t]);if(!Xe(o,s))return re(e),ss(e);let a;try{a=JSON.parse(i)}catch{let l=W("settings_read_invalid_json");return await sn(e,[t],l,s,[t]),l}let d=en(a);if(!d.success){let l=W("settings_read_invalid_schema");return await sn(e,[t],l,s,[t]),l}try{let l=$t(d.data),_=al(e,l.schema,t);r=_;let v=await te(_),O=await Ln(e,l.schema),S=await Hn(e,l.schema),I=await te(_),z={...l,item_types:{definitions:je([...l.item_types.definitions,...ln(S.type_definitions_from_file)])},schema:S.schema};un(z,Yi(d.data,z));let D={settings:z,metadata:{has_explicit_item_format:Qi(a)},warnings:[...d.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...O.created_paths.map($=>`runtime_schema_bootstrap_created:${$}`),...S.warnings]};return O.created_paths.length===0?Xe(v,I)?zt(e,{tracked_paths:_,signatures:I,value:Ft(D)}):re(e):re(e),D}catch{let l=W("settings_read_merge_failed");return await dl(e,r,l),l}}async function fm(e){return(await ss(e)).settings}async function mm(e,t,r=tl){let n=we(e),o=Zi(t),i=Nl(t,{persist_source:o}),s=JSON.parse(i);try{await Ai({pmRoot:e,filePath:n,mutate:a=>{let d=null;if(a!==null)try{d=JSON.parse(a)}catch{throw new b("Existing settings.json is malformed; the settings write was refused.",w.USAGE,{code:"settings_write_invalid_existing_json",reason:"existing_settings_json_malformed",why:"Writing defaults over malformed settings could destroy intended project configuration.",nextSteps:["Repair the syntax in .agents/pm/settings.json, then retry the original command.","Run pm health to confirm the settings warning has cleared."]})}return{raw:o?`${JSON.stringify(y(tn(o.persisted_settings,s,d),_n),null,2)}
76
+ `:i,result:void 0}},op:r,author:ho(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms,recordCreation:!1}),o&&un(t,{...o,persisted_settings:structuredClone(s)}),await Vn({path:n,scope:"project",op:r})}finally{re(e)}}import as from"node:fs";import Ye from"node:path";import{createRequire as Dl}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="19d9b802-1efa-5716-8176-ecbf5b153ff0")}catch{}})();var cs="@unbrained/pm-cli";var mn=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,pn="2026.8.31";function Mt(e){let t=e.match(mn);return t?[Number(t[1]),Number(t[2]),Number(t[3]),Number(t[4]??0)]:null}function Ut(e,t){let r=Mt(e),n=Mt(t);if(!r||!n)return null;for(let o=0;o<r.length;o+=1){let i=r[o]-n[o];if(i!==0)return Math.sign(i)}return 0}function fn(e){return Ut(e,pn)!==-1?3:2}function Vt(e){try{let t=JSON.parse(as.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Pl(e){let t=[...e.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(n=>({inclusive:n[1]==="<=",version:n[2]})),r=e.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?\s+-\s+v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/u);return r?[...t,{inclusive:!0,version:r[1]}]:t}function jl(e){let t=e.split("||").map(r=>Pl(r));return{bounded:t.some(r=>r.length>0),compatible:t.some(r=>r.every(n=>{let o=Ut(pn,n.version);return o!==null&&(n.inclusive?o!==1:o===-1)}))}}function ds(e){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(t=>{let r=e[t];if(typeof r!="object"||r===null)return[];let n=r[cs];return typeof n=="string"?[n.trim()]:[]})}function Ll(e){return ds(e).flatMap(t=>{let r=/^[<!]/u.test(t)?void 0:t.match(mn)?.[0];if(!r)return[];let n=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(t),o=jl(t);return[{version:r,constraint:n?"exact":o.bounded?"range":"minimum",...n?{}:{declaration:t},history_epoch_compatible:n?Ut(r,pn)!==-1:o.compatible}]})}function Hl(e){let t=Vt(Ye.join(e,"package-lock.json"))?.packages;if(typeof t!="object"||t===null)return;let r=t["node_modules/@unbrained/pm-cli"];if(typeof r!="object"||r===null)return;let n=r.version;return typeof n=="string"?n:void 0}function zl(e,t){try{let r=as.readFileSync(Ye.join(e,t),"utf8").split(/\r?\n/u),n=r.findIndex(s=>s.includes(cs));if(n<0)return;let o=r[n].match(/^\s*/u)[0].length,i=[r[n]];for(let s=n+1;s<r.length;s+=1){let a=r[s],d=a.trim(),l=a.match(/^\s*/u)[0].length;if(d.length>0&&l<=o)break;i.push(a)}return i.join(`
77
+ `).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??i[0].match(mn)?.[0]}catch{return}}function Fl(e){let t=[],r=Vt(Ye.join(e,"package.json"));r&&t.push(...Ll(r).map(i=>({...i,source:"package.json"})));let n=Vt(Ye.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof n=="string"&&Mt(n)&&t.push({version:n,source:"installed-package",constraint:"exact",history_epoch_compatible:fn(n)===3});let o=Hl(e);o&&Mt(o)&&t.push({version:o,source:"package-lock.json",constraint:"exact",history_epoch_compatible:fn(o)===3});for(let i of["pnpm-lock.yaml","yarn.lock"]){let s=zl(e,i);s&&t.push({version:s,source:i,constraint:"exact",history_epoch_compatible:fn(s)===3})}return t}function wm(e,t){if(t<=1)return;let{minVersion:r,lt:n}=Dl(import.meta.url)("semver"),o=ds(Vt(Ye.join(e,"package.json"))??{}).find(s=>{try{let a=r(s);return a!==null&&n(a,"2026.10.10")}catch{return!1}}),i=o===void 0?Fl(e).find(s=>Ut(s.version,"2026.10.10")===-1):{version:o,source:"package.json"};if(i)throw new b(`The project selects pm ${i.version}, which cannot safely refuse item format ${t}.`,w.CONFLICT,{code:"project_runtime_item_format_incompatible",reason:i.source,required:"Upgrade project pins, installed SDKs, CI hosts and Git merge drivers before writing guarded item formats.",nextSteps:["Use a pm runtime supporting the required item format throughout the project; preserve original item and history bytes, and never re-anchor history to satisfy an older host."]})}import yn from"node:fs/promises";import Wt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="658ab1c3-da92-5af6-a170-85ed7befaad6")}catch{}})();function oe(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function gn(e){let t=["--pm-path",e,"init","--defaults","--agent-guidance","skip"];return{suggested_retry:Wn(t),suggested_retry_args:t}}function qt(e){return new b(`Tracker root is not a directory at ${e}.`,w.USAGE,{code:"tracker_root_not_directory",reason:"not_a_directory",resolved_path:e,nextSteps:["Pass a tracker directory, usually <workspace>/.agents/pm, rather than a file path."]})}function hn(e){return new b(`Tracker root is not readable at ${e}.`,w.GENERIC_FAILURE,{code:"tracker_root_unreadable",reason:"unreadable",resolved_path:e,nextSteps:["Grant read and directory-search permission to the tracker root, then retry."]})}async function $l(e){let t=Wt.resolve(e),r=Wt.parse(t).root,n=Wt.dirname(t);for(;n!==r;){let o;try{o=await yn.stat(n)}catch(i){if(oe(i,"ENOTDIR"))throw qt(e);if(!oe(i,"ENOENT"))throw i;n=Wt.dirname(n);continue}if(!o.isDirectory())throw qt(e);return}}async function ls(e){let t;try{t=await yn.stat(e)}catch(r){throw oe(r,"ENOENT")?(await $l(e),new b(`Tracker is not initialized at ${e}. Tracker root does not exist. Run pm init first.`,w.NOT_FOUND,{code:"tracker_root_missing",reason:"missing",resolved_path:e,nextSteps:["Confirm the tracker root path or initialize it with the emitted retry."],recovery:gn(e)})):oe(r,"ENOTDIR")?qt(e):oe(r,"EACCES")||oe(r,"EPERM")?hn(e):r}if(!t.isDirectory())throw qt(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw hn(e);try{await(await yn.opendir(e)).close()}catch(r){throw oe(r,"EACCES")||oe(r,"EPERM")?hn(e):r}}async function Ml(e){if(await ls(e),!await Cn(we(e)))throw new b(`Tracker is not initialized at ${e}. Run pm init first.`,w.NOT_FOUND,{code:"tracker_not_initialized",reason:"settings_missing",resolved_path:e,nextSteps:["Initialize the selected tracker root with the emitted retry."],recovery:gn(e)})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5c8194ff-d877-51b8-bd54-d206f85a979c")}catch{}})();export{en as a,ce as b,Yt as c,Ul as d,Wl as e,Qn as f,rr as g,Ql as h,eu as i,tu as j,ru as k,nu as l,ou as m,ur as n,_r as o,ao as p,mu as q,pu as r,hu as s,yu as t,gu as u,vu as v,hr as w,fo as x,bu as y,wu as z,Eu as A,qs as B,ku as C,ho as D,Ou as E,Bs as F,yo as G,_e as H,Y as I,wo as J,Ve as K,$u as L,Mu as M,yr as N,gr as O,Au as P,vr as Q,go as R,Js as S,xu as T,_t as U,Xs as V,Du as W,mt as X,Ya as Y,yt as Z,s_ as _,a_ as $,Ae as aa,kc as ba,me as ca,xe as da,Ho as ea,Vc as fa,R_ as ga,D_ as ha,P_ as ia,td as ja,It as ka,ye as la,Je as ma,of as na,qr as oa,At as pa,fi as qa,sf as ra,hi as sa,af as ta,Br as ua,Jr as va,jo as wa,vd as xa,xt as ya,yf as za,Kr as Aa,Ct as Ba,gf as Ca,vf as Da,wi as Ea,Nt as Fa,Si as Ga,Ke as Ha,Ad as Ia,bf as Ja,wf as Ka,Pe as La,Rt as Ma,Pf as Na,jf as Oa,Lf as Pa,Ai as Qa,Hf as Ra,qf as Sa,re as Ta,_m as Ua,el as Va,Mi as Wa,$t as Xa,Nl as Ya,ss as Za,fm as _a,mm as $a,Fl as ab,wm as bb,ls as cb,Ml as db};
78
+ //# sourceMappingURL=chunk-PXDR77TO.js.map
@@ -0,0 +1,3 @@
1
+ import{Ub as K,i as O,j as N,k as U,l as R,m as j}from"./chunk-Y54ONBEX.js";import{B as q,E as W,m as C,n as P}from"./chunk-3TEIACFU.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2075887b-6d4b-582f-9da2-bab13198f9a5")}catch{}})();var Q=2e3,v=new Map;function S(e){if(typeof e!="string")return"";let t=v.get(e);if(t!==void 0)return t;let r=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return v.size>=Q&&K(v),v.set(e,r),r}import x from"node:path";import{link as ee,mkdir as te,mkdtemp as re,rm as se,writeFile as oe}from"node:fs/promises";import D from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="71c2fed9-81e1-5723-8e34-e6327c07a130")}catch{}})();async function V(e,t){let r=D.dirname(e);await te(r,{recursive:!0});let s=await re(D.join(r,".pm-seed-")),o=D.join(s,"value");try{await oe(o,t,"utf8");try{return await ee(o,e),!0}catch(i){if(i.code==="EEXIST")return!1;throw i}}finally{await se(s,{recursive:!0,force:!0})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6e07b1b6-1757-54dd-8833-9d3f984ccf79")}catch{}})();var m=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),$=P,M=C,ne=["create","update"],ie=new Set(N),ae=new Set(U),le=new Set(R),de=new Set(j),ue=new Set(["string","number","boolean","array","object"]),ce=16;function J(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var fe=[e=>e.type===void 0||typeof e.type=="string"&&ue.has(e.type),e=>!Object.hasOwn(e,"const")||I(e.const),e=>e.enum===void 0||Array.isArray(e.enum)&&e.enum.every(t=>I(t)),e=>e.min_length===void 0||Number.isInteger(e.min_length)&&e.min_length>=0,e=>e.min_items===void 0||Number.isInteger(e.min_items)&&e.min_items>=0,e=>e.format===void 0||e.format==="date-time",e=>e.required===void 0||Array.isArray(e.required)&&e.required.every(t=>typeof t=="string"&&t.length>0),e=>e.additional_properties===void 0||typeof e.additional_properties=="boolean",e=>e.properties===void 0||J(e.properties),e=>e.one_of===void 0||Array.isArray(e.one_of)&&e.one_of.length>0];function I(e,t=new Set){if(e===null||typeof e=="string"||typeof e=="boolean")return!0;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="object"||t.has(e))return!1;t.add(e);let r=Array.isArray(e)?e.every(s=>I(s,t)):Object.values(e).every(s=>I(s,t));return t.delete(e),r}function F(e,t=0,r=new Set){if(!J(e)||t>ce||r.has(e))return;r.add(e);let s=e,o=s.type,i=s.enum,a=s.one_of,l=s.properties,n=s.items,u=s.required,f=s.min_length,d=s.min_items,p=s.format,w=s.additional_properties;if(!fe.every(c=>c(s))){r.delete(e);return}let g=l===void 0?void 0:Object.fromEntries(Object.entries(l).map(([c,b])=>[c,F(b,t+1,r)])),h=n===void 0?void 0:F(n,t+1,r),A=a===void 0?void 0:a.map(c=>F(c,t+1,r));if([...Object.values(g??{}),...n===void 0?[]:[h],...A??[]].some(c=>c===void 0)){r.delete(e);return}return r.delete(e),Object.fromEntries(Object.entries({type:o,const:Object.hasOwn(s,"const")?s.const:void 0,enum:i,min_length:f,min_items:d,format:p,properties:g,required:u===void 0?void 0:[...new Set(u)],additional_properties:w,items:h,one_of:A}).filter(([,c])=>c!==void 0))}function T(e){let t=Array.isArray(e)?e:[];return[...new Set(t.map(r=>typeof r=="string"?r.trim():"").filter(r=>r.length>0))].sort((r,s)=>r.localeCompare(s))}function _(e){if(typeof e!="string"||e.length===0)return;let t=S(e);return t.length>0?t:void 0}function _e(e){return e.startsWith("--")?e.slice(2):e}function H(e){return typeof e=="string"?_e(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function B(e){return e.replaceAll("_","-")}function me(e){let t=e.replaceAll(/[^A-Za-z0-9]+/g," ").trim().split(/\s+/).filter(o=>o.length>0).map(o=>o.toLowerCase());if(t.length===0)return e;let[r,...s]=t;return`${r}${s.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function z(e,t){let r=_(e.id);if(!r)return null;let s=[...new Set(T(e.aliases).map(S).filter(l=>l.length>0))].sort((l,n)=>l.localeCompare(n)),o=T(e.roles).filter(l=>ie.has(l)),i=e.description?.trim(),a=typeof e.order=="number"&&Number.isFinite(e.order)?e.order:t;return{id:r,aliases:s,roles:o,description:i&&i.length>0?i:void 0,order:a}}function pe(e){return{draft_status:_(e?.draft_status),open_status:_(e?.open_status),in_progress_status:_(e?.in_progress_status),blocked_status:_(e?.blocked_status),close_status:_(e?.close_status),canceled_status:_(e?.canceled_status)}}function X(e,t){if(!Array.isArray(t)||t.length!==2)return;let r=S(t[0]),s=S(t[1]);r.length===0||s.length===0||e.pairs.some(o=>o[0]===r&&o[1]===s)||e.pairs.push([r,s])}function ye(e){let t=typeof e?.type=="string"?e.type.trim():"";if(t.length===0||!Array.isArray(e?.allowed_transitions))return null;let r={type:t,pairs:[],denyAll:e.allowed_transitions.length===0};for(let s of e.allowed_transitions)X(r,s);return{typeKey:t.toLowerCase(),record:r}}function we(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let s of e){let o=ye(s);if(o===null)continue;let i=t.get(o.typeKey)??o.record;i.denyAll||=o.record.denyAll;for(let a of o.record.pairs)X(i,a);t.set(o.typeKey,i)}let r=[];for(let s of t.values())(s.pairs.length>0||s.denyAll)&&r.push({type:s.type,allowed_transitions:s.pairs});return r.sort((s,o)=>s.type.localeCompare(o.type)),r.length>0?r:void 0}function Z(e){let t=S(e.key??"");if(!t)return null;let r=S(e.metadata_key??e.front_matter_key??t),s=H(e.cli_flag??B(t));if(!s)return null;let o=T(e.cli_aliases).map(d=>H(d)).filter(d=>d.length>0&&d!==s),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",a=ae.has(i)?i:"string",l=(()=>{let d=T(e.commands).filter(p=>le.has(p));return d.length>0?d:[...ne]})(),n=e.description?.trim(),u=T(e.required_types),f=e.value_schema===void 0?void 0:F(e.value_schema);return e.value_schema!==void 0&&f===void 0?null:{key:t,metadata_key:r,cli_flag:s,cli_aliases:o,description:n&&n.length>0?n:void 0,type:a,commands:l,repeatable:[e.repeatable===!0,a==="string_array"].includes(!0),required:e.required===!0,required_on_create:e.required_on_create===!0,required_types:u,allow_unset:e.allow_unset!==!1,value_schema:f}}function Se(e){let t=new Map;for(let[s,o]of e.entries()){let i=z(o,s);i&&t.set(i.id,i)}let r=Y([...t.values()]);return r.length>0?r:Y(M.map((s,o)=>z(s,o)).filter(s=>s!==null))}function Y(e){return e.sort((t,r)=>t.order===r.order?t.id.localeCompare(r.id):t.order-r.order)}function ge(e){let t=new Map;for(let r of e??[]){let s=Z(r);s&&t.set(s.key,s)}return[...t.values()].sort((r,s)=>r.key.localeCompare(s.key))}function he(e){return{id:e.id,aliases:e.aliases.length>0?[...e.aliases]:void 0,roles:e.roles.length>0?[...e.roles]:void 0,description:e.description,order:e.order}}function Ae(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==B(e.key)?e.cli_flag:void 0,cli_aliases:e.cli_aliases.length>0?[...e.cli_aliases]:void 0,description:e.description,type:e.type,commands:[...e.commands],repeatable:e.repeatable===!0?!0:void 0,required:e.required===!0?!0:void 0,required_on_create:e.required_on_create===!0?!0:void 0,required_types:e.required_types.length>0?[...e.required_types]:void 0,allow_unset:e.allow_unset===!1?!1:void 0,value_schema:e.value_schema}}function be(e){let t=typeof e=="string"?e.trim().toLowerCase():"allow";return de.has(t)?t:"allow"}function E(e){let t={...m,...e?.files},r=e?.statuses&&e.statuses.length>0?e.statuses:M,s=Se(r),o=ge(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:s.map(he),fields:o.map(Ae),workflow:{...$,...pe(e?.workflow)},type_workflows:we(e?.type_workflows),unknown_field_policy:be(e?.unknown_field_policy)}}function ke(e,t,r){try{return JSON.parse(e)}catch{r.push(t);return}}function Te(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.definitions))return t.definitions;if(typeof t.item_types=="object"&&t.item_types!==null){let r=t.item_types;if(Array.isArray(r.definitions))return r.definitions}}function Ee(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.statuses))return t.statuses;if(Array.isArray(t.definitions))return t.definitions}function ve(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.fields))return t.fields;if(Array.isArray(t.definitions))return t.definitions}function Fe(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;return typeof t.workflow=="object"&&t.workflow!==null&&!Array.isArray(t.workflow)?t.workflow:typeof t.workflows=="object"&&t.workflows!==null&&!Array.isArray(t.workflows)?t.workflows:t}function Ie(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(Array.isArray(t.type_workflows))return t.type_workflows}function y(e,t,r){let s=t?.trim()||r;return x.isAbsolute(s)?s:x.join(e,s)}function Ve(e,t){return y(e,t.files.types,m.types)}async function xe(e,t){let r=E(t),s=[{path:y(e,r.files.types,m.types),seed:{definitions:[]}},{path:y(e,r.files.statuses,m.statuses),seed:{statuses:M}},{path:y(e,r.files.fields,m.fields),seed:{fields:[]}},{path:y(e,r.files.workflows,m.workflows),seed:{workflow:$}}],o=[];for(let i of s)await q(i.path)||await V(i.path,`${JSON.stringify(i.seed,null,2)}
2
+ `)&&o.push(i.path);return{created_paths:o}}async function He(e,t){let r=E(t),s=[],o=y(e,r.files.types,m.types),i=y(e,r.files.statuses,m.statuses),a=y(e,r.files.fields,m.fields),l=y(e,r.files.workflows,m.workflows),n,u,f,d,p,w=async(b,G)=>{let L=await W(b);if(L!==null)return ke(L,G,s)},g=await w(o,"runtime_schema_types_invalid_json");g!==void 0&&(n=Te(g),n===void 0&&s.push("runtime_schema_types_invalid_shape"));let h=await w(i,"runtime_schema_statuses_invalid_json");h!==void 0&&(u=Ee(h),u===void 0&&s.push("runtime_schema_statuses_invalid_shape"));let A=await w(a,"runtime_schema_fields_invalid_json");A!==void 0&&(f=ve(A),f===void 0&&s.push("runtime_schema_fields_invalid_shape"));let c=await w(l,"runtime_schema_workflows_invalid_json");return c!==void 0&&(d=Fe(c),d===void 0&&s.push("runtime_schema_workflows_invalid_shape"),p=Ie(c)),{schema:E({...r,statuses:[...r.statuses,...u??[]],fields:[...r.fields,...f??[]],workflow:{...r.workflow,...d},type_workflows:[...r.type_workflows??[],...p??[]]}),type_definitions_from_file:n,warnings:s,created_paths:[]}}function k(e,t,r,s=!1){let o=r.map(a=>_(a)).filter(a=>typeof a=="string").find(a=>e.some(l=>l.id===a));if(s&&o!==void 0)return o;let i=e.find(a=>a.roles.includes(t));return i!==void 0?i.id:o??e[0]?.id}function De(e){let t=new Map,r=new Map;for(let s of e){r.set(s.id,s),t.set(s.id,s.id),t.set(s.id.replaceAll("_","-"),s.id),t.set(s.id.replaceAll("_"," "),s.id);for(let o of s.aliases)t.set(o,s.id),t.set(o.replaceAll("_","-"),s.id),t.set(o.replaceAll("_"," "),s.id)}return{aliasToId:t,byId:r}}function ze(e){let t={activeStatuses:new Set,blockedStatuses:new Set,draftStatuses:new Set,terminalCanceledStatuses:new Set,terminalDoneStatuses:new Set,terminalStatuses:new Set};for(let r of e){let s=new Set(r.roles);(s.has("terminal")||s.has("terminal_done")||s.has("terminal_canceled"))&&t.terminalStatuses.add(r.id),s.has("terminal_done")&&t.terminalDoneStatuses.add(r.id),s.has("terminal_canceled")&&t.terminalCanceledStatuses.add(r.id),s.has("active")&&t.activeStatuses.add(r.id),s.has("blocked")&&t.blockedStatuses.add(r.id),s.has("draft")&&t.draftStatuses.add(r.id)}return t}function Ye(e){let t=E(e),r=t.statuses.map((c,b)=>z(c,b)).filter(c=>c!==null),{aliasToId:s,byId:o}=De(r),{activeStatuses:i,blockedStatuses:a,draftStatuses:l,terminalCanceledStatuses:n,terminalDoneStatuses:u,terminalStatuses:f}=ze(r),d=t.workflow,p=_(d.open_status)??k(r,"default_open",["open","in_progress",O[0]]),w=_(d.in_progress_status)??k(r,"active",["in_progress","in-progress",p],!0),g=_(d.blocked_status)??k(r,"blocked",["blocked"]),h=_(d.close_status)??k(r,"default_close",["closed","done","complete"]),A=_(d.canceled_status)??k(r,"default_cancel",["canceled","cancelled"]);return{definitions:r,by_id:o,alias_to_id:s,terminal_statuses:f,terminal_done_statuses:u,terminal_canceled_statuses:n,active_statuses:i,blocked_statuses:a,draft_statuses:l,open_status:p,in_progress_status:w,blocked_status:g,close_status:h,canceled_status:A}}function Me(e,t){let r=S(e);if(r)return t.alias_to_id.get(r)}function $e(e){let t=E(e),r=new Map,s=t.fields.map(n=>Z(n)).filter(n=>n!==null);for(let n of s)r.set(n.key,n);let o=[...r.values()].sort((n,u)=>n.key.localeCompare(u.key)),i=new Map,a=new Map,l=new Map;for(let n of o){i.set(n.key,n),a.set(n.cli_flag,n);for(let u of n.cli_aliases)a.set(u,n);for(let u of n.commands){let f=l.get(u)??[];f.push(n),l.set(u,f)}}for(let[n,u]of l.entries())u.sort((f,d)=>f.key.localeCompare(d.key)),l.set(n,u);return{definitions:o,by_key:i,by_cli_token:a,command_to_fields:l}}function Je(e){return me(e.key)}function Be(e,t){let r=Me(e,t);return r?t.terminal_statuses.has(r):!1}export{S as a,V as b,m as c,M as d,E as e,y as f,Ve as g,xe as h,He as i,Ye as j,Me as k,$e as l,Je as m,Be as n};
3
+ //# sourceMappingURL=chunk-RLRMNFLF.js.map
@@ -1,4 +1,4 @@
1
- import{f as w,i as y,j,k as B,l as U,o as f,p as X,q as W,r as Y}from"./chunk-RBLSY6ML.js";import{O as H,a as $,b as D}from"./chunk-JXR6UKFM.js";import{c as u,f as M,g as z,i as q}from"./chunk-SIGIGZCG.js";import{Va as F,q as L,t as R}from"./chunk-MBQF6HT6.js";import{e as g,h as K}from"./chunk-AH6NX6GM.js";import{Ja as k,a as N,e as O,f as A,g as x,h as C,o as P}from"./chunk-TRFVAWF2.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3ec1f825-59d1-5ce2-ac76-c628264bd8be")}catch{}})();var Ce=N,Pe=O,$e=C,De=A,Le=x;function G(e,t,n,r){let s=e.flag.slice(2).replace(/[-_]([a-z])/gu,(a,i)=>i.toUpperCase()),o=n.has(s);return{long:t,...r?{short:r}:{},description:e.description??`Standard pm ${e.flag} option.`,...e.required===!0?{required:!0}:{},...e.list===!0?{list:!0}:{},...e.repeatable===!0?{repeatable:!0}:{},value_type:o?"string":"boolean",...o?{value_name:e.value_name??"value"}:{}}}function Q(e,t=[]){let n=new Set(t.flatMap(s=>s.keys)),r=[];for(let s of L(e.map(o=>({...o})))){r.push(G(s,s.flag,n,s.short));for(let o of s.aliases??[])r.push(G(s,o,n))}return r}var Re=Q(R,$),Fe=Q(F,D);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59d16a38-d6df-5695-96e3-28b6e384f76b")}catch{}})();var _=["agile","ops","research"],I={agile:{name:"agile",title:"Agile delivery",summary:"Story/Spike delivery with a review stage, story points, and acceptance ownership.",types:w.agile,statuses:[{id:"review",roles:["active"],aliases:["in-review"],description:"Work is implementation-complete and awaiting peer review."}],fields:[{key:"story_points",type:"number",commands:["create","update","list"],description:"Relative estimation size for a story or spike.",aliases:["points"]},{key:"acceptance_owner",type:"string",commands:["create","update","list"],description:"Stakeholder accountable for accepting the delivered story.",aliases:["acceptor"]}],workflows:[{type:"Story",allowed_transitions:[["open","in_progress"],["in_progress","review"],["review","in_progress"],["review","closed"],["in_progress","blocked"],["blocked","in_progress"]]}],config:[{key:"search_provider",value:"bm25",summary:"Offline BM25 lexical search works without an embedding service."},{key:"search_max_results",value:"20",summary:"Sprint-sized result cap for quick triage."}],templates:[{name:"story",options:{type:"Story",priority:"2",tags:"story",acceptanceCriteria:"Story delivers the stated user outcome with tests and docs updated.",body:`## As a
1
+ import{f as w,i as y,j,k as B,l as U,o as f,p as X,q as W,r as Y}from"./chunk-HYMYAGSY.js";import{O as H,a as $,b as D}from"./chunk-WZTEFFQI.js";import{c as u,f as M,g as z,i as q}from"./chunk-H6BVQ63U.js";import{Va as F,q as L,t as R}from"./chunk-OV2WVLUR.js";import{a as g,d as K}from"./chunk-RLRMNFLF.js";import{da as k,g as P}from"./chunk-Y54ONBEX.js";import{a as N,e as O,f as A,g as x,i as C}from"./chunk-3TEIACFU.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3ec1f825-59d1-5ce2-ac76-c628264bd8be")}catch{}})();var Ce=N,Pe=O,$e=C,De=A,Le=x;function G(e,t,n,r){let s=e.flag.slice(2).replace(/[-_]([a-z])/gu,(a,i)=>i.toUpperCase()),o=n.has(s);return{long:t,...r?{short:r}:{},description:e.description??`Standard pm ${e.flag} option.`,...e.required===!0?{required:!0}:{},...e.list===!0?{list:!0}:{},...e.repeatable===!0?{repeatable:!0}:{},value_type:o?"string":"boolean",...o?{value_name:e.value_name??"value"}:{}}}function Q(e,t=[]){let n=new Set(t.flatMap(s=>s.keys)),r=[];for(let s of L(e.map(o=>({...o})))){r.push(G(s,s.flag,n,s.short));for(let o of s.aliases??[])r.push(G(s,o,n))}return r}var Re=Q(R,$),Fe=Q(F,D);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59d16a38-d6df-5695-96e3-28b6e384f76b")}catch{}})();var _=["agile","ops","research"],I={agile:{name:"agile",title:"Agile delivery",summary:"Story/Spike delivery with a review stage, story points, and acceptance ownership.",types:w.agile,statuses:[{id:"review",roles:["active"],aliases:["in-review"],description:"Work is implementation-complete and awaiting peer review."}],fields:[{key:"story_points",type:"number",commands:["create","update","list"],description:"Relative estimation size for a story or spike.",aliases:["points"]},{key:"acceptance_owner",type:"string",commands:["create","update","list"],description:"Stakeholder accountable for accepting the delivered story.",aliases:["acceptor"]}],workflows:[{type:"Story",allowed_transitions:[["open","in_progress"],["in_progress","review"],["review","in_progress"],["review","closed"],["in_progress","blocked"],["blocked","in_progress"]]}],config:[{key:"search_provider",value:"bm25",summary:"Offline BM25 lexical search works without an embedding service."},{key:"search_max_results",value:"20",summary:"Sprint-sized result cap for quick triage."}],templates:[{name:"story",options:{type:"Story",priority:"2",tags:"story",acceptanceCriteria:"Story delivers the stated user outcome with tests and docs updated.",body:`## As a
2
2
 
3
3
  ## I want
4
4
 
@@ -23,4 +23,4 @@ import{f as w,i as y,j,k as B,l as U,o as f,p as X,q as W,r as Y}from"./chunk-RB
23
23
 
24
24
  ## Conclusion
25
25
  `}}],packages:[{spec:"search-advanced",reason:"Semantic retrieval over experiments and findings."},{spec:"templates",reason:"Consistent experiment and hypothesis scaffolds."},{spec:"beads",reason:"Import structured prior work into the tracker."}]}};function ne(e){if(e===void 0)return;let t=p(e);if(t.length===0)throw new Error("Profile name must not be empty.");if(_.includes(t))return t;throw new Error(`Invalid profile "${e}". Allowed: ${_.join(", ")}.`)}function qe(e){let t=ne(e);if(t===void 0)throw new Error(`Profile name is required. Allowed: ${_.join(", ")}.`);return I[t]}function je(){return _.map(e=>I[e])}function p(e){return e.trim().toLowerCase().replaceAll("-","_")}function J(e){return e.map(t=>t.definition.name).join(", ")}function re(e=[]){let t=_.map(o=>({definition:I[o],source:"builtin"})),n=new Set(_.map(o=>p(o))),r=new Set(n),s=[];for(let o of e){let a=p(o.profile.name);if(n.has(a)){s.push(`Extension "${o.name}" profile "${o.profile.name}" uses a name reserved by a built-in archetype and was ignored.`);continue}if(r.has(a)){s.push(`Profile "${o.profile.name}" from extension "${o.name}" duplicates an already-registered profile and was ignored.`);continue}r.add(a),t.push({definition:o.profile,source:"extension",package:o.name})}return{profiles:t,warnings:s}}function Be(e,t=[]){let{profiles:n,warnings:r}=re(t);if(typeof e!="string"||e.trim().length===0)throw new Error(`Profile name is required. Allowed: ${J(n)}.`);let s=p(e),o=n.find(a=>p(a.definition.name)===s);if(o===void 0)throw new Error(`Invalid profile "${e}". Allowed: ${J(n)}.`);return{resolved:o,warnings:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab26bcb3-fb2a-5f2f-96e7-7965787b924e")}catch{}})();function se(e){return{types:e.types.length,statuses:e.statuses.length,fields:e.fields.length,workflows:e.workflows.length,config:e.config.length,templates:e.templates.length,packages:e.packages.length}}function Ye(e){return{name:e.name,title:e.title,summary:e.summary,composition:se(e),types:e.types.map(t=>S(()=>u(t).name,()=>String(t.name??""))),statuses:e.statuses.map(t=>S(()=>f(t).id,()=>String(t.id??""))),fields:e.fields.map(t=>S(()=>y(t).key,()=>String(t.key??""))),workflows:e.workflows.map(t=>t.type),config:e.config.map(t=>`${t.key}=${t.value}`),templates:e.templates.map(t=>t.name),packages:e.packages.map(t=>({spec:t.spec,reason:t.reason}))}}function S(e,t){try{return e()}catch{return t()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2ae4f6da-17c5-5024-89a2-bb0a4be9a683")}catch{}})();var oe=[{key:"search_provider",path:"search.provider",kind:"string",summary:"Search embedding provider name (e.g. openai, ollama, or an extension provider)."},{key:"search_default_mode",path:"search.default_mode",kind:"string",choices:["auto","keyword","semantic","hybrid"],summary:"Mode a bare pm search runs in: auto (hybrid when semantic search is explicitly configured and runnable, else keyword), or a pinned keyword, semantic, or hybrid."},{key:"search_mutation_refresh_policy",path:"search.mutation_refresh_policy",kind:"string",choices:["cache_only","semantic_configured","semantic_auto"],summary:"Mutation-time search refresh policy: cache_only, semantic_configured, or semantic_auto."},{key:"search_query_expansion_enabled",path:"search.query_expansion.enabled",kind:"boolean",summary:"Enable or disable query expansion for semantic/hybrid search."},{key:"search_query_expansion_provider",path:"search.query_expansion.provider",kind:"string",summary:"Query expansion provider name (built-in openai/ollama or extension provider)."},{key:"search_rerank_enabled",path:"search.rerank.enabled",kind:"boolean",summary:"Enable or disable post-retrieval reranking for hybrid search."},{key:"search_rerank_model",path:"search.rerank.model",kind:"string",summary:"Rerank model name override used by built-in providers."},{key:"search_rerank_top_k",path:"search.rerank.top_k",kind:"integer",min:1,summary:"Number of top hybrid candidates to rerank when rerank is enabled."},{key:"search_embedding_model",path:"search.embedding_model",kind:"string",summary:"Default embedding model name (overrides provider-specific model when set)."},{key:"search_embedding_corpus_max_characters",path:"search.embedding_corpus_max_characters",kind:"integer",min:1,summary:"Maximum semantic corpus characters per item before truncation."},{key:"search_embedding_batch_size",path:"search.embedding_batch_size",kind:"integer",min:1,summary:"Number of items embedded per request batch."},{key:"search_embedding_timeout_ms",path:"search.embedding_timeout_ms",kind:"integer",min:1,summary:"Per-request embedding timeout in milliseconds."},{key:"search_score_threshold",path:"search.score_threshold",kind:"number",summary:"Minimum score for a hit to be returned (0 keeps all matches)."},{key:"search_hybrid_semantic_weight",path:"search.hybrid_semantic_weight",kind:"ratio",summary:"Hybrid mode semantic weight in [0, 1] (1-weight goes to keyword)."},{key:"search_max_results",path:"search.max_results",kind:"integer",min:1,summary:"Default upper bound on search hits when --limit is not supplied."},{key:"search_bm25_k1",path:"search.bm25.k1",kind:"number",min:0,summary:"Offline BM25 term-frequency saturation (k1); higher saturates repeated terms slower (default 1.2)."},{key:"search_bm25_b",path:"search.bm25.b",kind:"ratio",summary:"Offline BM25 document-length normalization (b) in [0, 1]; 0 disables, 1 fully normalizes (default 0.75)."},{key:"openai_base_url",path:"providers.openai.base_url",kind:"string",summary:"OpenAI-compatible API base URL (LM Studio/vLLM also use this)."},{key:"openai_api_key",path:"providers.openai.api_key",kind:"string",summary:"OpenAI-compatible API key."},{key:"openai_model",path:"providers.openai.model",kind:"string",summary:"OpenAI-compatible embedding model name."},{key:"ollama_base_url",path:"providers.ollama.base_url",kind:"string",summary:"Ollama API base URL (typically http://localhost:11434)."},{key:"ollama_model",path:"providers.ollama.model",kind:"string",summary:"Ollama embedding model name (e.g. nomic-embed-text)."},{key:"vector_store_adapter",path:"vector_store.adapter",kind:"string",summary:"Vector store adapter name (lancedb, qdrant, or an extension adapter)."},{key:"vector_store_collection_name",path:"vector_store.collection_name",kind:"string",non_empty:!0,summary:"Vector collection/table name shared by Qdrant and LanceDB adapters."},{key:"qdrant_url",path:"vector_store.qdrant.url",kind:"string",summary:"Qdrant HTTP API URL."},{key:"qdrant_api_key",path:"vector_store.qdrant.api_key",kind:"string",summary:"Qdrant API key (empty if running unauthenticated)."},{key:"lancedb_path",path:"vector_store.lancedb.path",kind:"string",summary:"LanceDB storage path (relative to pm root or absolute)."},{key:"id_prefix",path:"id_prefix",kind:"string",non_empty:!0,summary:'Prefix for generated item IDs (e.g. "pm" produces pm-xxxx).'},{key:"author_default",path:"author_default",kind:"string",non_empty:!0,summary:"Default author recorded on mutations when --author is not supplied."},{key:"agent_identity_probes_enabled",path:"agent_identity.probes_enabled",kind:"boolean",summary:"Allow privacy-bounded local harness provenance probes; no network or subprocess access is permitted."},{key:"mutation_guard_require_attributed_author",path:"mutation_guard.require_attributed_author",kind:"boolean",summary:"Reject mutations whose effective author resolves to unknown."},{key:"mutation_guard_secret_guard",path:"mutation_guard.secret_guard",kind:"string",choices:["off","advise","block"],summary:"Detect credential-shaped mutation content: off, advise, or block."},{key:"mutation_guard_stale_in_progress_hours",path:"mutation_guard.stale_in_progress_hours",kind:"integer",min:1,summary:"Age threshold for unclaimed in-progress work surfaced by health."},{key:"governance_duplicate_detection_mode",path:"governance.duplicate_detection_mode",kind:"string",choices:["off","advisory","strict"],summary:"Create/copy duplicate governance: off, advisory, or strict explicit-bypass enforcement."},{key:"governance_duplicate_detection_threshold",path:"governance.duplicate_detection_threshold",kind:"ratio",summary:"Minimum shared similarity score in [0, 1] for create/copy duplicate governance."},{key:"governance_duplicate_detection_limit",path:"governance.duplicate_detection_limit",kind:"integer",min:0,max:20,summary:"Maximum likely duplicates returned by create/copy governance (0-20)."},{key:"output_default_format",path:"output.default_format",kind:"string",choices:["toon","json"],summary:"Default output format for commands that support it: toon or json."},{key:"ux_deprecation_hints",path:"ux.deprecation_hints",kind:"boolean",summary:"Emit one stderr migration hint for deprecated command aliases."},{key:"locks_ttl_seconds",path:"locks.ttl_seconds",kind:"integer",min:1,summary:"Claim/lock time-to-live in seconds before a stale lock can be reclaimed."},{key:"locks_wait_ms",path:"locks.wait_ms",kind:"integer",min:0,summary:"Bounded jittered wait in milliseconds before a contended item mutation fails with lock_conflict; 0 fails fast. PM_LOCK_WAIT_MS overrides per invocation."},{key:"ids_token_length",path:"ids.token_length",kind:"integer",min:4,max:12,summary:"Random base36 token length for newly minted item ids (4-12, default 4). Raise it to shrink cross-branch id collision odds in concurrent multi-agent workflows (pm-pibw)."},{key:"checkpoints_retention_days",path:"checkpoints.retention_days",kind:"integer",min:1,summary:"Age in days above which pm gc --scope checkpoints prunes bulk-mutation rollback checkpoints."},{key:"schema_unknown_field_policy",path:"schema.unknown_field_policy",kind:"string",choices:["allow","warn","reject"],summary:"How item I/O handles metadata keys not in the field registry: allow, warn, or reject."},{key:"history_compact_policy_enabled",path:"history.compact_policy.enabled",kind:"boolean",summary:"Enable the history-compaction advisory: pm health warns on over-threshold streams."},{key:"history_compact_policy_max_entries",path:"history.compact_policy.max_entries",kind:"integer",min:1,summary:"Entry count above which a history stream is flagged (and the default pm history-compact --all-over threshold)."},{key:"history_compact_policy_trigger",path:"history.compact_policy.trigger",kind:"string",choices:["health_warn","auto"],summary:"History-compaction policy intent: health_warn (advisory only) or auto (scheduled sweeps expected)."}],ae=new Map(oe.flatMap(e=>[[e.key,e],[e.path.toLowerCase().replaceAll("-","_"),e]]));function b(e){if(typeof e!="string")return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length!==0)return ae.get(t)}function ie(e,t){let n=t.trim().toLowerCase();return n==="true"||n==="1"||n==="yes"||n==="on"?{ok:!0,parsed:{descriptor:e,value:!0}}:n==="false"||n==="0"||n==="no"||n==="off"?{ok:!0,parsed:{descriptor:e,value:!1}}:{ok:!1,error:{message:`Config set ${e.key} requires a boolean value (true|false), got "${t}"`}}}function le(e,t,n){return e.non_empty===!0&&n.length===0?{ok:!1,error:{message:`Config set ${e.key} requires a non-empty value`}}:e.choices&&!e.choices.includes(n)?{ok:!1,error:{message:`Config set ${e.key} must be one of ${e.choices.join("|")}, got "${t}"`}}:{ok:!0,parsed:{descriptor:e,value:n}}}function de(e,t,n){if(n.length===0)return{ok:!1,error:{message:`Config set ${e.key} requires a non-empty value`}};let r=Number(n);return Number.isFinite(r)?{ok:!0,value:r}:{ok:!1,error:{message:`Config set ${e.key} requires a finite number, got "${t}"`}}}function ce(e,t,n){return!Number.isInteger(n)||n<0?{ok:!1,error:{message:`Config set ${e.key} requires a non-negative integer, got "${t}"`}}:e.min!==void 0&&n<e.min?{ok:!1,error:{message:`Config set ${e.key} requires an integer >= ${e.min}, got "${t}" (the runtime silently ignores 0 here and falls back to the default)`}}:e.max!==void 0&&n>e.max?{ok:!1,error:{message:`Config set ${e.key} requires an integer <= ${e.max}, got "${t}"`}}:{ok:!0,parsed:{descriptor:e,value:n}}}function me(e,t,n){return n<0||n>1?{ok:!1,error:{message:`Config set ${e.key} requires a number in [0, 1], got "${t}"`}}:{ok:!0,parsed:{descriptor:e,value:n}}}function pe(e,t,n){return e.min!==void 0&&n<e.min?{ok:!1,error:{message:`Config set ${e.key} requires a number >= ${e.min}, got "${t}"`}}:{ok:!0,parsed:{descriptor:e,value:n}}}function v(e,t){if(typeof t!="string")return{ok:!1,error:{message:`Config set ${e.key} requires a string value`}};let n=t.trim();if(e.kind==="boolean")return ie(e,t);if(e.kind==="string")return le(e,t,n);let r=de(e,t,n);return r.ok?e.kind==="integer"?ce(e,t,r.value):e.kind==="ratio"?me(e,t,r.value):pe(e,t,r.value):{ok:!1,error:r.error}}function V(e,t){let n=t.path.split("."),r=e;for(let s of n){if(typeof r!="object"||r===null)return null;let o=Object.getOwnPropertyDescriptor(r,s);if(!o||!Object.hasOwn(o,"value"))return null;r=o.value}return typeof r=="string"||typeof r=="number"||typeof r=="boolean"?r:null}function Ge(e,t,n){let r=t.path.split(".");if(r.some(a=>a.length===0||["__proto__","constructor","prototype"].includes(a)))throw new Error("Unsafe settings path");let s=e;for(let a=0;a<r.length-1;a+=1){let i=r[a],d=Object.getOwnPropertyDescriptor(s,i)?.value;if(typeof d!="object"||d===null||Array.isArray(d)){let c={};Object.defineProperty(s,i,{value:c,writable:!0,enumerable:!0,configurable:!0}),s=c}else s=d}let o=r[r.length-1];return Object.getOwnPropertyDescriptor(s,o)?.value===n?!1:(Object.defineProperty(s,o,{value:n,writable:!0,enumerable:!0,configurable:!0}),!0)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0b04624c-2096-55dc-9dde-b8c76ead72d6")}catch{}})();var it=["profile","types","statuses","fields","workflows","config","templates","packages"],lt=["profile_name_empty","profile_name_not_normalized","profile_title_empty","profile_summary_empty","type_invalid","type_duplicate","status_invalid","status_duplicate","field_invalid","field_duplicate","field_mcp_input_collision","workflow_type_empty","workflow_type_unknown","workflow_duplicate_type","workflow_transition_malformed","workflow_status_unknown","config_key_unknown","config_value_invalid","config_duplicate","template_type_unknown","package_spec_empty"],ue=new Set(K.flatMap(e=>[g(e.id),...(e.aliases??[]).map(t=>g(t))]).filter(e=>e.length>0)),Z=new Set(P.map(e=>e.toLowerCase()));function ye(e,t){e.name.trim().length===0?t.push({severity:"error",code:"profile_name_empty",dimension:"profile",message:"Profile name must not be empty; profile resolution requires a non-blank name."}):e.name!==p(e.name)&&t.push({severity:"warning",code:"profile_name_not_normalized",dimension:"profile",target:e.name,message:`Profile name "${e.name}" is not in canonical form; resolution folds it to "${p(e.name)}" (lowercase, hyphens as underscores).`}),e.title.trim().length===0&&t.push({severity:"warning",code:"profile_title_empty",dimension:"profile",message:"Profile title is empty; list and show surfaces will render a blank title."}),e.summary.trim().length===0&&t.push({severity:"warning",code:"profile_summary_empty",dimension:"profile",message:"Profile summary is empty; list and show surfaces will render a blank archetype description."})}function fe(e,t){let n=new Set,r=new Set;for(let[s,o]of e.types.entries()){let a;try{a=u(o).name}catch(d){t.push({severity:"error",code:"type_invalid",dimension:"types",target:typeof o.name=="string"?o.name:`#${s}`,message:k(d)});continue}let i=a.toLowerCase();if(r.has(i)){t.push({severity:"error",code:"type_duplicate",dimension:"types",target:a,message:`Item type "${a}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}r.add(i),n.add(i)}return n}function he(e,t){let n=new Set,r=new Set;for(let[s,o]of e.statuses.entries()){let a;try{a=f(o)}catch(i){t.push({severity:"error",code:"status_invalid",dimension:"statuses",target:typeof o.id=="string"?o.id:`#${s}`,message:k(i)});continue}if(r.has(a.id)){t.push({severity:"error",code:"status_duplicate",dimension:"statuses",target:a.id,message:`Status "${a.id}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}r.add(a.id),n.add(a.id);for(let i of a.aliases??[])n.add(g(i))}return n}function ge(e,t){let n=new Set;for(let[r,s]of e.fields.entries()){let o;try{o=y(s).key}catch(i){t.push({severity:"error",code:"field_invalid",dimension:"fields",target:typeof s.key=="string"?s.key:`#${r}`,message:k(i)});continue}if(n.has(o)){t.push({severity:"error",code:"field_duplicate",dimension:"fields",target:o,message:`Field "${o}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}n.add(o);let a=H(o);a&&t.push({severity:"warning",code:"field_mcp_input_collision",dimension:"fields",target:o,message:`Field "${o}" collides with canonical MCP property "${a.property}" owned by ${a.owner}; callers must pass the custom value through ${a.nested_path}.`})}}function _e(e,t,n,r){let s=new Set;for(let[o,a]of e.workflows.entries()){let i=a.type.trim().toLowerCase();if(i.length===0){r.push({severity:"error",code:"workflow_type_empty",dimension:"workflows",target:`#${o}`,message:"Workflow has an empty type; the workflow resolver drops entries without a type."});continue}let d=s.has(i);s.add(i),d?r.push({severity:"warning",code:"workflow_duplicate_type",dimension:"workflows",target:a.type,message:`Workflow type "${a.type}" is declared more than once; the later transition set wins.`}):!Z.has(i)&&!t.has(i)&&r.push({severity:"warning",code:"workflow_type_unknown",dimension:"workflows",target:a.type,message:`Workflow governs type "${a.type}" which is neither a built-in type nor declared by this profile; it has no effect unless that type already exists.`});let c=new Set;for(let l of a.allowed_transitions){let m=g(l[0]),T=g(l[1]);if(m.length===0||T.length===0){r.push({severity:"error",code:"workflow_transition_malformed",dimension:"workflows",target:a.type,message:`Workflow "${a.type}" has a transition with an empty status; the workflow resolver silently drops it.`});continue}for(let h of[m,T])ue.has(h)||n.has(h)||c.has(h)||(c.add(h),r.push({severity:"warning",code:"workflow_status_unknown",dimension:"workflows",target:h,message:`Workflow "${a.type}" references status "${h}" which is neither a built-in status nor declared by this profile; transitions to or from it are unreachable.`}))}}}function ke(e,t){let n=new Set;for(let r of e.config){let s=b(r.key);if(s===void 0){t.push({severity:"error",code:"config_key_unknown",dimension:"config",target:r.key,message:`Config knob "${r.key}" is not a recognized setting; apply rejects it with a usage error.`});continue}n.has(s.key)?t.push({severity:"error",code:"config_duplicate",dimension:"config",target:s.key,message:`Config knob "${s.key}" is set more than once; the later value silently overwrites the earlier one.`}):n.add(s.key);let o=v(s,r.value);o.ok||t.push({severity:"error",code:"config_value_invalid",dimension:"config",target:r.key,message:o.error.message})}}function we(e,t,n){for(let r of e.templates){let s=r.options.type;if(typeof s!="string"||s.trim().length===0)continue;let o=s.trim().toLowerCase();!Z.has(o)&&!t.has(o)&&n.push({severity:"warning",code:"template_type_unknown",dimension:"templates",target:r.name,message:`Template "${r.name}" creates type "${s}" which is neither a built-in type nor declared by this profile.`})}}function be(e,t){for(let[n,r]of e.packages.entries())r.spec.trim().length===0&&t.push({severity:"warning",code:"package_spec_empty",dimension:"packages",target:`#${n}`,message:"Package recommendation has an empty spec; it cannot be surfaced as an install hint."})}function dt(e){let t=[];ye(e,t);let n=fe(e,t),r=he(e,t);ge(e,t),_e(e,n,r,t),ke(e,t),we(e,n,t),be(e,t);let s=t.filter(a=>a.severity==="error").length,o=t.length-s;return{profile:e.name,ok:s===0,findings:t,errorCount:s,warningCount:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="be2b507d-2797-570c-b211-46d950edcbde")}catch{}})();function E(e,t,n,r,s){let o=e,a=[];for(let i of t){let d=r(o),c=s(o,i),l=r(c.file);o=c.file;let m=d===l?"unchanged":c.replaced?"update":"add";a.push({key:n(i),status:m})}return{file:o,changes:a,changed:a.some(i=>i.status!=="unchanged")}}function ee(e){return JSON.stringify(e.map(t=>t.join("\0")).sort())}function ve(e,t){let n=e.map(s=>({...s})),r=[];for(let s of t){let o=n.findIndex(i=>i.type===s.type),a={type:s.type,allowed_transitions:s.allowed_transitions};o<0?(n.push(a),r.push({type:s.type,status:"add"})):ee(n[o].allowed_transitions)===ee(s.allowed_transitions)?r.push({type:s.type,status:"unchanged"}):(n[o]=a,r.push({type:s.type,status:"update"}))}return{changes:r,result:n,changed:r.some(s=>s.status!=="unchanged")}}function Ie(e,t){let n=[];for(let r of e.config){let s=b(r.key);if(s===void 0)throw new Error(`Profile "${e.name}" references unknown config key "${r.key}".`);let o=v(s,r.value);if(!o.ok)throw new Error(`Profile "${e.name}" config ${r.key}: ${o.error.message}`);let a=V(t,s),i=a===null?"add":a===o.parsed.value?"unchanged":"update";n.push({key:s.key,path:s.path,value:o.parsed.value,status:i})}return{changes:n,changed:n.some(r=>r.status!=="unchanged")}}function te(e){let t=Object.entries(e).sort(([n],[r])=>n.localeCompare(r));return JSON.stringify(t)}function Se(e,t){let n=[];for(let r of e.templates){let s=t.get(r.name),o;s===void 0?o="add":te(s)===te(r.options)?o="unchanged":o="update",n.push({name:r.name,options:r.options,status:o})}return{changes:n,changed:n.some(r=>r.status!=="unchanged")}}function ft(e,t){let n=E(M(t.typesRaw),e.types,l=>u(l).name,q,(l,m)=>z(l,u(m))),r=E(X(t.statusesRaw),e.statuses,l=>f(l).id,W,(l,m)=>Y(l,f(m))),s=E(j(t.fieldsRaw),e.fields,l=>y(l).key,B,(l,m)=>U(l,y(m))),o=ve(t.workflows,e.workflows),a=Ie(e,t.settings),i=Se(e,t.templates),d=e.packages.map(l=>({spec:l.spec,reason:l.reason,status:t.installedPackages.has(l.spec)?"installed":"recommended"})),c=n.changed||r.changed||s.changed||o.changed||a.changed||i.changed;return{profile:{name:e.name,title:e.title,summary:e.summary},types:n,statuses:r,fields:s,workflows:o,config:a,templates:i,packages:d,changed:c}}export{Ce as a,Pe as b,$e as c,De as d,Le as e,Q as f,Re as g,Fe as h,_ as i,I as j,ne as k,qe as l,je as m,re as n,Be as o,se as p,Ye as q,oe as r,b as s,v as t,V as u,Ge as v,it as w,lt as x,dt as y,ft as z};
26
- //# sourceMappingURL=chunk-E33QA7PK.js.map
26
+ //# sourceMappingURL=chunk-SKYLOPU2.js.map
@@ -0,0 +1,2 @@
1
+ import{constants as r}from"node:fs";import{lstat as d,open as u}from"node:fs/promises";(function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new t.Error().stack;n&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[n]="b063a672-991a-5251-a2f3-6a1c7bcafd2f")}catch{}})();var c={lstat:d,open:u};function b(t){return t.O_NOFOLLOW??0}async function p(t,n,i=c){let l=await i.lstat(t);if(l.isSymbolicLink()||!l.isFile()||l.size>n)return null;let a=await i.open(t,r.O_RDONLY|b(r));try{let s=await a.stat();if(!s.isFile()||s.size>n)return null;let o=Buffer.alloc(s.size),e=0;for(;e<o.length;){let{bytesRead:f}=await a.read(o,e,o.length-e,e);if(f===0)break;e+=f}return(await a.stat()).size===s.size&&e===s.size?o.toString("utf8",0,e):null}finally{await a.close()}}export{p as a};
2
+ //# sourceMappingURL=chunk-VVRXF4JO.js.map