@unbrained/pm-cli 2026.11.22 → 2026.11.24

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 (912) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/after-command-context-usage.js +1 -1
  3. package/dist/cli/argv-utils.js +1 -1
  4. package/dist/cli/bootstrap-args.js +1 -1
  5. package/dist/cli/bundle-integrity.js +2 -2
  6. package/dist/cli/command-namespaces.js +1 -1
  7. package/dist/cli/commander-usage.js +11 -11
  8. package/dist/cli/commands/annotations/comments.js +1 -1
  9. package/dist/cli/commands/annotations/docs.js +1 -1
  10. package/dist/cli/commands/annotations/files.js +1 -1
  11. package/dist/cli/commands/annotations/learnings.js +1 -1
  12. package/dist/cli/commands/annotations/notes.js +1 -1
  13. package/dist/cli/commands/extension/describe.js +1 -1
  14. package/dist/cli/commands/extension/extension.js +1 -1
  15. package/dist/cli/commands/extension/scaffold.js +1 -1
  16. package/dist/cli/commands/extension/shared.js +1 -1
  17. package/dist/cli/commands/governance/gc.js +1 -1
  18. package/dist/cli/commands/governance/health.js +1 -1
  19. package/dist/cli/commands/governance/telemetry.js +1 -1
  20. package/dist/cli/commands/governance/validate.js +1 -1
  21. package/dist/cli/commands/history/activity.js +1 -1
  22. package/dist/cli/commands/history/history-compact.js +1 -1
  23. package/dist/cli/commands/history/history-redact.js +1 -1
  24. package/dist/cli/commands/history/history-repair.js +1 -1
  25. package/dist/cli/commands/history/history.js +1 -1
  26. package/dist/cli/commands/history/restore.js +1 -1
  27. package/dist/cli/commands/lifecycle/append.js +1 -1
  28. package/dist/cli/commands/lifecycle/claim.js +1 -1
  29. package/dist/cli/commands/lifecycle/close-many.js +1 -1
  30. package/dist/cli/commands/lifecycle/close.js +1 -1
  31. package/dist/cli/commands/lifecycle/copy.js +1 -1
  32. package/dist/cli/commands/lifecycle/create.js +1 -1
  33. package/dist/cli/commands/lifecycle/delete.js +1 -1
  34. package/dist/cli/commands/lifecycle/focus.js +1 -1
  35. package/dist/cli/commands/lifecycle/plan.js +1 -1
  36. package/dist/cli/commands/lifecycle/update-many.js +1 -1
  37. package/dist/cli/commands/lifecycle/update.js +1 -1
  38. package/dist/cli/commands/query/aggregate.js +1 -1
  39. package/dist/cli/commands/query/context.js +1 -1
  40. package/dist/cli/commands/query/deps.js +1 -1
  41. package/dist/cli/commands/query/duplicates.js +1 -1
  42. package/dist/cli/commands/query/eval.js +1 -1
  43. package/dist/cli/commands/query/get.js +1 -1
  44. package/dist/cli/commands/query/graph.js +1 -1
  45. package/dist/cli/commands/query/list.js +1 -1
  46. package/dist/cli/commands/query/next.js +1 -1
  47. package/dist/cli/commands/query/search.js +1 -1
  48. package/dist/cli/commands/query/stats.js +1 -1
  49. package/dist/cli/commands/test/test-all.js +1 -1
  50. package/dist/cli/commands/test/test-runs.js +1 -1
  51. package/dist/cli/commands/test/test.js +1 -1
  52. package/dist/cli/commands/workspace/config.js +1 -1
  53. package/dist/cli/commands/workspace/contracts.js +1 -1
  54. package/dist/cli/commands/workspace/init.js +1 -1
  55. package/dist/cli/commands/workspace/merge.js +1 -1
  56. package/dist/cli/commands/workspace/profile.js +1 -1
  57. package/dist/cli/commands/workspace/schema.js +1 -1
  58. package/dist/cli/commands/workspace/upgrade.js +1 -1
  59. package/dist/cli/context-intent-invocation.js +1 -1
  60. package/dist/cli/description-stdin.js +1 -1
  61. package/dist/cli/error-guidance.js +5 -5
  62. package/dist/cli/expected-revisions.js +1 -1
  63. package/dist/cli/extension-command-help.js +6 -6
  64. package/dist/cli/extension-recovery.js +1 -1
  65. package/dist/cli/help-content.js +5 -5
  66. package/dist/cli/help-json-payload.js +7 -7
  67. package/dist/cli/invocation-profile.js +2 -2
  68. package/dist/cli/main.js +5 -5
  69. package/dist/cli/migration-gates.js +1 -1
  70. package/dist/cli/option-values.js +1 -1
  71. package/dist/cli/preflight-warnings.js +3 -3
  72. package/dist/cli/public.js +1 -1
  73. package/dist/cli/register-annotations.js +1 -1
  74. package/dist/cli/register-assurance.js +1 -1
  75. package/dist/cli/register-files-lookup.js +1 -1
  76. package/dist/cli/register-history-activity.js +1 -1
  77. package/dist/cli/register-history-author.js +1 -1
  78. package/dist/cli/register-history-maintenance.js +2 -2
  79. package/dist/cli/register-list-query.js +10 -10
  80. package/dist/cli/register-mutation-options.js +0 -1
  81. package/dist/cli/register-mutation.js +6 -6
  82. package/dist/cli/register-operations.js +1 -1
  83. package/dist/cli/register-setup.js +1 -1
  84. package/dist/cli/register-structured-mutation.js +1 -1
  85. package/dist/cli/registration-helpers.js +1 -1
  86. package/dist/cli/runtime/activation.js +1 -1
  87. package/dist/cli/runtime/annotation-option-retry.js +1 -1
  88. package/dist/cli/runtime/close-fields-retry.js +1 -1
  89. package/dist/cli/runtime/field-route-retry.js +1 -1
  90. package/dist/cli/runtime/invocation-options.js +1 -1
  91. package/dist/cli/runtime/invocation-rewrites.js +1 -1
  92. package/dist/cli/runtime/projection-retry.js +1 -1
  93. package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
  94. package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
  95. package/dist/cli/runtime/selection.js +1 -1
  96. package/dist/cli/runtime/telemetry-outcome.js +1 -1
  97. package/dist/cli/runtime-compatibility-boundary.js +4 -4
  98. package/dist/cli/schema/registration.js +15 -15
  99. package/dist/cli/schema-registration-helpers.js +1 -1
  100. package/dist/cli/search-refresh.js +1 -1
  101. package/dist/cli/stats-analytics-json.js +1 -1
  102. package/dist/cli/telemetry-flush.js +1 -1
  103. package/dist/cli-bundle/bundle-manifest.json +1 -1
  104. package/dist/cli-bundle/chunks/chunk-23K6DQQY.js +9 -0
  105. package/dist/cli-bundle/chunks/chunk-37UDIJ2K.js +3 -0
  106. package/dist/cli-bundle/chunks/chunk-5DUP4AZA.js +2 -0
  107. package/dist/cli-bundle/chunks/chunk-6H36ZHMI.js +2 -0
  108. package/dist/cli-bundle/chunks/chunk-7IROAPWI.js +3 -0
  109. package/dist/cli-bundle/chunks/chunk-7VRFEURZ.js +33 -0
  110. package/dist/cli-bundle/chunks/chunk-7X253M6Z.js +3 -0
  111. package/dist/cli-bundle/chunks/chunk-AA52P34H.js +3 -0
  112. package/dist/cli-bundle/chunks/chunk-AWB5KBJS.js +2 -0
  113. package/dist/cli-bundle/chunks/chunk-D6PDUKUG.js +9 -0
  114. package/dist/cli-bundle/chunks/chunk-DQDRA3SW.js +2 -0
  115. package/dist/cli-bundle/chunks/chunk-FXJYZBWV.js +113 -0
  116. package/dist/cli-bundle/chunks/chunk-HNKK2UG6.js +8 -0
  117. package/dist/cli-bundle/chunks/chunk-HZZLSBIJ.js +2 -0
  118. package/dist/cli-bundle/chunks/chunk-I2OJ5B4A.js +2 -0
  119. package/dist/cli-bundle/chunks/chunk-I3BFCKZR.js +2 -0
  120. package/dist/cli-bundle/chunks/chunk-MXUSC5RS.js +31 -0
  121. package/dist/cli-bundle/chunks/chunk-PLIUU37C.js +3 -0
  122. package/dist/cli-bundle/chunks/chunk-PQUBVRV5.js +2 -0
  123. package/dist/cli-bundle/chunks/chunk-PW7U7WCE.js +3 -0
  124. package/dist/cli-bundle/chunks/chunk-PZA7QECY.js +1 -0
  125. package/dist/cli-bundle/chunks/chunk-SLFRSZK6.js +1 -0
  126. package/dist/cli-bundle/chunks/chunk-SSALO4DB.js +2 -0
  127. package/dist/cli-bundle/chunks/chunk-STOOTHZZ.js +2 -0
  128. package/dist/cli-bundle/chunks/chunk-TKRY22SO.js +2 -0
  129. package/dist/cli-bundle/chunks/{chunk-B76TFRO2.js → chunk-TVIJ2VCU.js} +93 -93
  130. package/dist/cli-bundle/chunks/chunk-VJSGUXGU.js +3 -0
  131. package/dist/cli-bundle/chunks/chunk-WWTPNIC2.js +6 -0
  132. package/dist/cli-bundle/chunks/chunk-XFADNMGD.js +2 -0
  133. package/dist/cli-bundle/chunks/chunk-YOPTAIBD.js +125 -0
  134. package/dist/cli-bundle/chunks/chunk-YW2HBHRO.js +70 -0
  135. package/dist/cli-bundle/chunks/chunk-YYT3MIRF.js +3 -0
  136. package/dist/cli-bundle/chunks/chunk-Z7MFVRDV.js +2 -0
  137. package/dist/cli-bundle/chunks/chunk-ZOX4SWRL.js +8 -0
  138. package/dist/cli-bundle/chunks/chunk-ZYCOM4MS.js +9 -0
  139. package/dist/cli-bundle/chunks/context-budget-recovery-M5RFUEFG.js +2 -0
  140. package/dist/cli-bundle/chunks/field-option-collisions-W66HSWMK.js +2 -0
  141. package/dist/cli-bundle/chunks/indexed-receipt-blobs-BPYKN5Q7.js +4 -0
  142. package/dist/cli-bundle/{focused-chunks/item-revision-2O6MLPEX.js → chunks/item-revision-D3LSBNIR.js} +2 -2
  143. package/dist/cli-bundle/chunks/item-transaction-M6NTBYH3.js +2 -0
  144. package/dist/cli-bundle/chunks/mutation-actor-OKL3CQVX.js +2 -0
  145. package/dist/cli-bundle/chunks/mutation-admission-EKPEOZMF.js +2 -0
  146. package/dist/cli-bundle/chunks/{register-list-query-RR5KACJ3.js → register-list-query-3LBV6CS2.js} +11 -11
  147. package/dist/cli-bundle/chunks/register-mutation-72AGTMNE.js +21 -0
  148. package/dist/cli-bundle/chunks/register-operations-XERFG2SH.js +2 -0
  149. package/dist/cli-bundle/chunks/register-setup-W22L34Z4.js +2 -0
  150. package/dist/cli-bundle/chunks/runtime-schema-JP2KBHBY.js +2 -0
  151. package/dist/cli-bundle/chunks/settlement-hook-6MR32OOC.js +7 -0
  152. package/dist/cli-bundle/chunks/stage-T2LKWN7C.js +2 -0
  153. package/dist/cli-bundle/focused-chunks/chunk-24VRBNKE.js +26 -0
  154. package/dist/cli-bundle/focused-chunks/chunk-3ELVASVA.js +2 -0
  155. package/dist/cli-bundle/focused-chunks/chunk-3GT4A3ZN.js +44 -0
  156. package/dist/cli-bundle/focused-chunks/chunk-3OCDKITJ.js +3 -0
  157. package/dist/cli-bundle/focused-chunks/chunk-3Z7MCUJM.js +3 -0
  158. package/dist/cli-bundle/focused-chunks/chunk-46MP7IZN.js +5 -0
  159. package/dist/cli-bundle/focused-chunks/chunk-5LDBS6MS.js +91 -0
  160. package/dist/cli-bundle/focused-chunks/chunk-A6VEMCRR.js +3 -0
  161. package/dist/cli-bundle/focused-chunks/chunk-AIDL2ZNT.js +3 -0
  162. package/dist/cli-bundle/focused-chunks/chunk-B6BNHKUW.js +78 -0
  163. package/dist/cli-bundle/focused-chunks/chunk-BKPUUW5O.js +1 -0
  164. package/dist/cli-bundle/focused-chunks/chunk-BWOVFE5B.js +2 -0
  165. package/dist/cli-bundle/focused-chunks/chunk-C7WHWI7K.js +3 -0
  166. package/dist/cli-bundle/focused-chunks/chunk-EUQGZPGO.js +2 -0
  167. package/dist/cli-bundle/focused-chunks/chunk-FDZPRJXJ.js +27 -0
  168. package/dist/cli-bundle/focused-chunks/chunk-GXP7Q4XM.js +2 -0
  169. package/dist/cli-bundle/focused-chunks/chunk-HL47UQZJ.js +8 -0
  170. package/dist/cli-bundle/focused-chunks/chunk-IIP6LZ5E.js +2 -0
  171. package/dist/cli-bundle/focused-chunks/chunk-K53OIT5J.js +2 -0
  172. package/dist/cli-bundle/focused-chunks/chunk-LMFIAQ2V.js +2 -0
  173. package/dist/cli-bundle/focused-chunks/chunk-LMU7DDOA.js +2 -0
  174. package/dist/cli-bundle/focused-chunks/chunk-OZOCEB2Q.js +8 -0
  175. package/dist/cli-bundle/focused-chunks/chunk-Q2HY44LV.js +13 -0
  176. package/dist/cli-bundle/focused-chunks/chunk-REFMQY47.js +2 -0
  177. package/dist/cli-bundle/focused-chunks/chunk-RIE3SJSE.js +9 -0
  178. package/dist/cli-bundle/focused-chunks/chunk-RIQUIHYU.js +3 -0
  179. package/dist/cli-bundle/focused-chunks/chunk-RLO2HCZT.js +2 -0
  180. package/dist/cli-bundle/focused-chunks/chunk-SMMOZ3H3.js +100 -0
  181. package/dist/cli-bundle/focused-chunks/chunk-UVTUX54T.js +2 -0
  182. package/dist/cli-bundle/focused-chunks/chunk-X6CXWWNB.js +2 -0
  183. package/dist/cli-bundle/focused-chunks/chunk-XDBHD4CY.js +8 -0
  184. package/dist/cli-bundle/focused-chunks/chunk-YD66IRSL.js +2 -0
  185. package/dist/cli-bundle/focused-chunks/chunk-Z7W2RQIB.js +2 -0
  186. package/dist/cli-bundle/focused-chunks/context-budget-recovery-CSJV3TY3.js +2 -0
  187. package/dist/cli-bundle/focused-chunks/field-option-collisions-UODPSV6W.js +2 -0
  188. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-EGEJMG3G.js +4 -0
  189. package/dist/cli-bundle/focused-chunks/item-revision-QH7RNBX4.js +2 -0
  190. package/dist/cli-bundle/focused-chunks/item-transaction-ZO72OINF.js +2 -0
  191. package/dist/cli-bundle/focused-chunks/mutation-actor-PHVLKG4I.js +2 -0
  192. package/dist/cli-bundle/focused-chunks/mutation-admission-ZSG5OECH.js +2 -0
  193. package/dist/cli-bundle/focused-chunks/runtime-schema-6RQMIDTN.js +2 -0
  194. package/dist/cli-bundle/focused-chunks/settlement-hook-FMLGKG7J.js +7 -0
  195. package/dist/cli-bundle/focused-chunks/stage-AQMKRVX4.js +2 -0
  196. package/dist/cli-bundle/main.js +27 -27
  197. package/dist/cli-bundle/sdk-authoring.js +1 -1
  198. package/dist/cli-bundle/sdk-contracts.js +5 -5
  199. package/dist/cli-bundle/sdk-core.js +1 -1
  200. package/dist/cli-bundle/sdk-governance.js +1 -1
  201. package/dist/cli-bundle/sdk-graph.js +1 -1
  202. package/dist/cli-bundle/sdk-merge.js +66 -66
  203. package/dist/cli-bundle/sdk-query.js +1 -1
  204. package/dist/cli-bundle/sdk-runtime.js +1 -1
  205. package/dist/cli-bundle/sdk-testing.js +1 -1
  206. package/dist/cli-bundle/sdk.js +13 -13
  207. package/dist/cli.js +1 -1
  208. package/dist/core/checkpoint/checkpoint-gc.js +1 -1
  209. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  210. package/dist/core/checkpoint/mutation-context.js +1 -1
  211. package/dist/core/config/nested-settings.js +1 -1
  212. package/dist/core/config/positional-value.js +1 -1
  213. package/dist/core/diagnostics/remediation.js +1 -1
  214. package/dist/core/extensions/activation-summary-markdown.js +2 -2
  215. package/dist/core/extensions/activation-summary.js +1 -1
  216. package/dist/core/extensions/activation-transaction.js +1 -1
  217. package/dist/core/extensions/capability-usage.js +1 -1
  218. package/dist/core/extensions/command-hook-context.js +1 -1
  219. package/dist/core/extensions/command-metadata-contract.js +1 -1
  220. package/dist/core/extensions/command-visibility-tier.js +1 -1
  221. package/dist/core/extensions/contribution-inventory.js +1 -1
  222. package/dist/core/extensions/exporter-output-contract.js +1 -1
  223. package/dist/core/extensions/extension-candidate.js +1 -1
  224. package/dist/core/extensions/extension-capability-aliases.js +1 -1
  225. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  226. package/dist/core/extensions/extension-policy.js +1 -1
  227. package/dist/core/extensions/extension-registries.js +1 -1
  228. package/dist/core/extensions/extension-runtime-helpers.js +1 -1
  229. package/dist/core/extensions/extension-types.js +1 -1
  230. package/dist/core/extensions/flag-definition-validation.js +1 -1
  231. package/dist/core/extensions/flag-value-types.js +1 -1
  232. package/dist/core/extensions/index.js +1 -1
  233. package/dist/core/extensions/item-field-types.js +1 -1
  234. package/dist/core/extensions/item-fields.js +1 -1
  235. package/dist/core/extensions/loader.js +1 -1
  236. package/dist/core/extensions/manifest-parser.js +1 -1
  237. package/dist/core/extensions/manifest-schema.js +1 -1
  238. package/dist/core/extensions/module-graph-snapshot.js +1 -1
  239. package/dist/core/extensions/mutation-actor-snapshot.js +1 -1
  240. package/dist/core/extensions/mutation-actor.js +1 -1
  241. package/dist/core/extensions/preflight-ownership.js +1 -1
  242. package/dist/core/extensions/read-output-contract.js +1 -1
  243. package/dist/core/extensions/registration-contracts.js +1 -1
  244. package/dist/core/extensions/registration-validation.js +1 -1
  245. package/dist/core/extensions/registration-values.js +1 -1
  246. package/dist/core/extensions/reserved-host-flags.js +1 -1
  247. package/dist/core/extensions/runtime-registrations.js +1 -1
  248. package/dist/core/extensions/service-ownership.js +1 -1
  249. package/dist/core/extensions/version-compat.js +1 -1
  250. package/dist/core/extensions/version-diagnostics.js +1 -1
  251. package/dist/core/fs/atomic-create.js +1 -1
  252. package/dist/core/fs/file-glob.js +1 -1
  253. package/dist/core/fs/fs-utils.js +2 -2
  254. package/dist/core/fs/host-environment-errors.js +1 -1
  255. package/dist/core/fs/index.js +1 -1
  256. package/dist/core/fs/path-utils.js +1 -1
  257. package/dist/core/governance/content-fields.js +1 -1
  258. package/dist/core/governance/issue-codes.js +1 -1
  259. package/dist/core/governance/metadata-coverage.js +1 -1
  260. package/dist/core/history/bridge.js +1 -1
  261. package/dist/core/history/digest.js +1 -1
  262. package/dist/core/history/drift-cache.js +3 -3
  263. package/dist/core/history/drift-scan.js +1 -1
  264. package/dist/core/history/event-classification.js +1 -1
  265. package/dist/core/history/event-index.js +11 -11
  266. package/dist/core/history/history-compact-bulk.js +1 -1
  267. package/dist/core/history/history-diff.js +1 -1
  268. package/dist/core/history/history-rewrite.js +1 -1
  269. package/dist/core/history/history-storage-stats.js +1 -1
  270. package/dist/core/history/history-stream-policy.js +1 -1
  271. package/dist/core/history/history.js +2 -2
  272. package/dist/core/history/identity.js +1 -1
  273. package/dist/core/history/index.js +1 -1
  274. package/dist/core/history/operation-contract.js +1 -1
  275. package/dist/core/history/projection.js +1 -1
  276. package/dist/core/history/read.js +1 -1
  277. package/dist/core/history/replay.js +2 -2
  278. package/dist/core/history/stream-summary.js +2 -2
  279. package/dist/core/history/tombstone.js +1 -1
  280. package/dist/core/history/version-address.js +1 -1
  281. package/dist/core/history/workspace-history.js +2 -2
  282. package/dist/core/io/body-file.js +1 -1
  283. package/dist/core/io/bulk-ids-input.js +2 -2
  284. package/dist/core/item/actionability.js +1 -1
  285. package/dist/core/item/deferred-fields.js +1 -1
  286. package/dist/core/item/dependency-reference.js +1 -1
  287. package/dist/core/item/id.js +1 -1
  288. package/dist/core/item/index.js +1 -1
  289. package/dist/core/item/item-format-version.js +1 -1
  290. package/dist/core/item/item-format.js +7 -7
  291. package/dist/core/item/item-record.js +1 -1
  292. package/dist/core/item/item-type-definition.js +1 -1
  293. package/dist/core/item/literal-mutation-input.js +1 -1
  294. package/dist/core/item/parent-reference-policy.js +1 -1
  295. package/dist/core/item/parse.js +8 -8
  296. package/dist/core/item/plan-lifecycle.js +1 -1
  297. package/dist/core/item/priority.js +1 -1
  298. package/dist/core/item/sprint-release-format.js +1 -1
  299. package/dist/core/item/status-filter.js +1 -1
  300. package/dist/core/item/status.js +1 -1
  301. package/dist/core/item/toon-decode.js +1 -1
  302. package/dist/core/item/type-registry.js +1 -1
  303. package/dist/core/item/type-synonyms.js +1 -1
  304. package/dist/core/lock/index.js +1 -1
  305. package/dist/core/lock/lock-confinement.js +1 -1
  306. package/dist/core/lock/lock-gc.js +1 -1
  307. package/dist/core/lock/lock-owner.js +1 -1
  308. package/dist/core/lock/lock.js +4 -4
  309. package/dist/core/output/linked-test-projection.js +5 -5
  310. package/dist/core/output/mutation-projection.js +1 -1
  311. package/dist/core/output/output-control.js +1 -1
  312. package/dist/core/output/output.js +19 -19
  313. package/dist/core/output/query-summary.js +1 -1
  314. package/dist/core/output/tabular.js +3 -3
  315. package/dist/core/packages/manifest.js +1 -1
  316. package/dist/core/packages/root.js +1 -1
  317. package/dist/core/policy/workflow-policy-schema.js +1 -1
  318. package/dist/core/policy/workflow-policy-store.js +1 -1
  319. package/dist/core/policy/workflow-policy.js +1 -1
  320. package/dist/core/profile/profile-describe.js +1 -1
  321. package/dist/core/profile/profile-lint.d.ts +1 -1
  322. package/dist/core/profile/profile-lint.js +1 -1
  323. package/dist/core/profile/profile-plan.js +1 -1
  324. package/dist/core/profile/profile-presets.js +4 -4
  325. package/dist/core/reproducibility/context.js +1 -1
  326. package/dist/core/schema/fields-file.js +2 -2
  327. package/dist/core/schema/item-types-file.js +2 -2
  328. package/dist/core/schema/runtime-field-filters.js +1 -1
  329. package/dist/core/schema/runtime-field-values.js +1 -1
  330. package/dist/core/schema/runtime-schema.d.ts +2 -0
  331. package/dist/core/schema/runtime-schema.js +2 -2
  332. package/dist/core/schema/status-defs-file.js +2 -2
  333. package/dist/core/schema/status-token.js +1 -1
  334. package/dist/core/schema/type-inference.js +1 -1
  335. package/dist/core/schema/type-presets.js +1 -1
  336. package/dist/core/schema/type-workflows.js +1 -1
  337. package/dist/core/search/background-refresh.js +2 -2
  338. package/dist/core/search/bm25.js +1 -1
  339. package/dist/core/search/cache.js +2 -2
  340. package/dist/core/search/corpus.js +1 -1
  341. package/dist/core/search/embedding-batches.js +1 -1
  342. package/dist/core/search/eval-thresholds.js +1 -1
  343. package/dist/core/search/eval.js +1 -1
  344. package/dist/core/search/http-client.js +1 -1
  345. package/dist/core/search/providers.js +1 -1
  346. package/dist/core/search/relevance.js +1 -1
  347. package/dist/core/search/semantic-defaults.js +1 -1
  348. package/dist/core/search/staleness.js +1 -1
  349. package/dist/core/search/vector-stores.js +2 -2
  350. package/dist/core/search/vectorization-metadata.js +1 -1
  351. package/dist/core/sentry/helpers.js +1 -1
  352. package/dist/core/sentry/instrument.js +1 -1
  353. package/dist/core/sentry/sensitive-assignments.js +1 -1
  354. package/dist/core/session/session-state.js +1 -1
  355. package/dist/core/shared/agent-session-context.js +1 -1
  356. package/dist/core/shared/author.js +5 -5
  357. package/dist/core/shared/command-line.js +1 -1
  358. package/dist/core/shared/command-types.js +0 -1
  359. package/dist/core/shared/conflict-markers.js +1 -1
  360. package/dist/core/shared/constants.js +1 -1
  361. package/dist/core/shared/error-details.js +1 -1
  362. package/dist/core/shared/errors.js +1 -1
  363. package/dist/core/shared/html-entity-decode.js +1 -1
  364. package/dist/core/shared/index.js +1 -1
  365. package/dist/core/shared/item-metadata-contract.js +1 -1
  366. package/dist/core/shared/lazy-module.js +1 -1
  367. package/dist/core/shared/levenshtein.js +1 -1
  368. package/dist/core/shared/memo.js +1 -1
  369. package/dist/core/shared/numeric-parsers.js +1 -1
  370. package/dist/core/shared/option-alias-visibility.js +1 -1
  371. package/dist/core/shared/output-unicode.js +1 -1
  372. package/dist/core/shared/primitives.js +1 -1
  373. package/dist/core/shared/process-tree.js +2 -2
  374. package/dist/core/shared/secret-rules.js +5 -5
  375. package/dist/core/shared/serial-queue.js +1 -1
  376. package/dist/core/shared/serialization.js +1 -1
  377. package/dist/core/shared/split-comma-list.js +1 -1
  378. package/dist/core/shared/text-normalization.js +1 -1
  379. package/dist/core/shared/time.js +2 -2
  380. package/dist/core/shared/url-credentials.js +1 -1
  381. package/dist/core/store/index.js +1 -1
  382. package/dist/core/store/item-format-migration.js +1 -1
  383. package/dist/core/store/item-metadata-cache.js +1 -1
  384. package/dist/core/store/item-metadata-query-index.js +11 -11
  385. package/dist/core/store/item-metadata-read-work.js +1 -1
  386. package/dist/core/store/item-mutation-precondition.js +1 -1
  387. package/dist/core/store/item-store.js +1 -1
  388. package/dist/core/store/paths.js +1 -1
  389. package/dist/core/store/settings-concurrency.js +1 -1
  390. package/dist/core/store/settings-read-cache.js +1 -1
  391. package/dist/core/store/settings-sections.js +2 -2
  392. package/dist/core/store/settings-validator.js +1 -1
  393. package/dist/core/store/settings.d.ts +3 -1
  394. package/dist/core/store/settings.js +6 -6
  395. package/dist/core/store/sqlite-runtime.js +1 -1
  396. package/dist/core/store/tracker-preflight.js +1 -1
  397. package/dist/core/store/transaction-coordinator-scope.js +1 -1
  398. package/dist/core/telemetry/consent.js +3 -3
  399. package/dist/core/telemetry/observability.js +1 -1
  400. package/dist/core/telemetry/policy.js +1 -1
  401. package/dist/core/telemetry/read-sampling.js +2 -2
  402. package/dist/core/telemetry/runtime.js +9 -9
  403. package/dist/core/test/background-runs.js +4 -4
  404. package/dist/core/test/item-test-run-tracking.js +1 -1
  405. package/dist/core/test/run-selectors.js +1 -1
  406. package/dist/core/validate/estimate-defaults.js +1 -1
  407. package/dist/core/validate/fix-planning.js +1 -1
  408. package/dist/core/validate/linked-artifact-reference.js +1 -1
  409. package/dist/core/validate/missing-by-type.js +1 -1
  410. package/dist/core/validate/missing-link-owners.js +1 -1
  411. package/dist/core/validate/stale-file-classification.js +1 -1
  412. package/dist/mcp/http-server.js +5 -5
  413. package/dist/mcp/legacy-adapter.js +1 -1
  414. package/dist/mcp/runtime-capabilities.js +1 -1
  415. package/dist/mcp/server.js +4 -4
  416. package/dist/mcp/tool-definitions.js +1 -1
  417. package/dist/sdk/actionability.js +1 -1
  418. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  419. package/dist/sdk/agent/command-recovery.js +1 -1
  420. package/dist/sdk/agent/command-suggestions.js +1 -1
  421. package/dist/sdk/agent/create-option-policy.js +1 -1
  422. package/dist/sdk/agent/identity-config.js +1 -1
  423. package/dist/sdk/agent/item-addressing.js +1 -1
  424. package/dist/sdk/agent/linked-resource-recovery.js +1 -1
  425. package/dist/sdk/agent/refusal-closure-census.js +2 -2
  426. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
  427. package/dist/sdk/agent/subcommand-recovery.js +1 -1
  428. package/dist/sdk/agent-capability-contracts.js +3 -3
  429. package/dist/sdk/agent-session-context.js +1 -1
  430. package/dist/sdk/annotations.js +1 -1
  431. package/dist/sdk/author-attribution.js +1 -1
  432. package/dist/sdk/cli-bootstrap.js +1 -1
  433. package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -5
  434. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  435. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  436. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
  437. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  438. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  439. package/dist/sdk/cli-contracts/completeness.js +1 -1
  440. package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
  441. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  442. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -2
  443. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  444. package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
  445. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  446. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
  447. package/dist/sdk/cli-contracts/string-lists.js +1 -1
  448. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  449. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  450. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  451. package/dist/sdk/cli-contracts/typed-action-inputs.js +0 -1
  452. package/dist/sdk/cli-contracts.js +1 -1
  453. package/dist/sdk/cli-program.js +1 -1
  454. package/dist/sdk/command-line.js +1 -1
  455. package/dist/sdk/comments.js +1 -1
  456. package/dist/sdk/compile-cache.js +1 -1
  457. package/dist/sdk/completion/bash.js +2 -2
  458. package/dist/sdk/completion/fish.js +72 -72
  459. package/dist/sdk/completion/shared.js +1 -1
  460. package/dist/sdk/completion/zsh.js +75 -75
  461. package/dist/sdk/completion.js +1 -1
  462. package/dist/sdk/config.js +1 -1
  463. package/dist/sdk/context/recency.js +1 -1
  464. package/dist/sdk/context/semantic-session-attribution.js +1 -1
  465. package/dist/sdk/context/usage-egress.js +1 -1
  466. package/dist/sdk/context/usage-ledger.js +6 -6
  467. package/dist/sdk/context-intent-contracts.js +1 -1
  468. package/dist/sdk/context-intent-runtime.js +1 -1
  469. package/dist/sdk/context-packing.js +1 -1
  470. package/dist/sdk/context-relevance.js +1 -1
  471. package/dist/sdk/context-signal-store.js +2 -2
  472. package/dist/sdk/context-usage.js +1 -1
  473. package/dist/sdk/dependencies/context-budget-recovery.js +1 -1
  474. package/dist/sdk/dependencies.js +1 -1
  475. package/dist/sdk/dependency-flag-validation.js +1 -1
  476. package/dist/sdk/dependency-provenance.js +1 -1
  477. package/dist/sdk/docs.js +1 -1
  478. package/dist/sdk/duplicates.js +1 -1
  479. package/dist/sdk/environment/host-environment-errors.js +1 -1
  480. package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
  481. package/dist/sdk/environment/source-context.js +1 -1
  482. package/dist/sdk/environment/tracker-preflight.js +1 -1
  483. package/dist/sdk/error-code-catalog.js +1 -1
  484. package/dist/sdk/error-runtime.js +1 -1
  485. package/dist/sdk/errors.js +1 -1
  486. package/dist/sdk/eval.js +1 -1
  487. package/dist/sdk/extension/author-manifest.js +1 -1
  488. package/dist/sdk/extension/bundled-catalog.js +1 -1
  489. package/dist/sdk/extension/command-options.d.ts +26 -1
  490. package/dist/sdk/extension/command-options.js +1 -1
  491. package/dist/sdk/extension/concurrency.js +1 -1
  492. package/dist/sdk/extension/copy-scope.js +1 -1
  493. package/dist/sdk/extension/custom-field-collisions.js +1 -1
  494. package/dist/sdk/extension/describe.js +3 -3
  495. package/dist/sdk/extension/doctor.js +1 -1
  496. package/dist/sdk/extension/install-plan.js +1 -1
  497. package/dist/sdk/extension/install-receipts.js +1 -1
  498. package/dist/sdk/extension/install-runtime.js +3 -3
  499. package/dist/sdk/extension/install-snapshot.js +1 -1
  500. package/dist/sdk/extension/install-sources.js +5 -5
  501. package/dist/sdk/extension/managed-state.js +2 -2
  502. package/dist/sdk/extension/managed-update-status.js +1 -1
  503. package/dist/sdk/extension/migrations.js +2 -2
  504. package/dist/sdk/extension/native-command-options.js +1 -1
  505. package/dist/sdk/extension/output-ownership.js +1 -1
  506. package/dist/sdk/extension/runtime-summary.js +1 -1
  507. package/dist/sdk/extension/scaffold.js +11 -11
  508. package/dist/sdk/extension/shared.js +1 -1
  509. package/dist/sdk/extension/source-resolution.js +1 -1
  510. package/dist/sdk/extension/static-inventory.js +1 -1
  511. package/dist/sdk/extension/update-check.js +1 -1
  512. package/dist/sdk/extension-command-context.js +2 -2
  513. package/dist/sdk/extension-contracts.js +1 -1
  514. package/dist/sdk/extension.js +1 -1
  515. package/dist/sdk/files.js +1 -1
  516. package/dist/sdk/flag-invocation-contracts.js +1 -1
  517. package/dist/sdk/generated/error-code-catalog-rows.js +1 -1
  518. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  519. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  520. package/dist/sdk/generated-error-code-catalog.js +1 -1
  521. package/dist/sdk/governance/assurance-action-contracts.js +0 -1
  522. package/dist/sdk/governance/assurance-action.js +1 -1
  523. package/dist/sdk/governance/assurance-limits.js +1 -1
  524. package/dist/sdk/governance/assurance-mutation-error.js +1 -1
  525. package/dist/sdk/governance/assurance-presets.js +1 -1
  526. package/dist/sdk/governance/assurance-runtime.js +1 -1
  527. package/dist/sdk/governance/assurance.js +4 -4
  528. package/dist/sdk/governance/boundary-fixtures.js +1 -1
  529. package/dist/sdk/governance/closure-timestamps.js +1 -1
  530. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
  531. package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
  532. package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
  533. package/dist/sdk/governance/defect-recurrence.js +2 -2
  534. package/dist/sdk/governance/extension-host-version.js +1 -1
  535. package/dist/sdk/governance/gc.js +1 -1
  536. package/dist/sdk/governance/health/history-drift-remedies.js +1 -1
  537. package/dist/sdk/governance/health/projection.js +1 -1
  538. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  539. package/dist/sdk/governance/health.js +2 -2
  540. package/dist/sdk/governance/hierarchy-validation.js +1 -1
  541. package/dist/sdk/governance/in-progress-work-health.js +1 -1
  542. package/dist/sdk/governance/lifecycle-dependency-cycles.js +1 -1
  543. package/dist/sdk/governance/linked-file-report.js +1 -1
  544. package/dist/sdk/governance/merge-receipt-history.js +1 -1
  545. package/dist/sdk/governance/provenance-health.js +4 -4
  546. package/dist/sdk/governance/reindex.js +5 -5
  547. package/dist/sdk/governance/stale-work.js +1 -1
  548. package/dist/sdk/governance/status-role-diagnostics.js +1 -1
  549. package/dist/sdk/governance/storage-integrity.js +1 -1
  550. package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
  551. package/dist/sdk/governance/upgrade.js +2 -2
  552. package/dist/sdk/governance/validate-deferred-fields.js +1 -1
  553. package/dist/sdk/governance/validate-history-drift.js +1 -1
  554. package/dist/sdk/governance/validate-item-reader.js +1 -1
  555. package/dist/sdk/governance/validate-normalization.js +1 -1
  556. package/dist/sdk/governance/validate.js +1 -1
  557. package/dist/sdk/governance/workflow-completeness.js +1 -1
  558. package/dist/sdk/governance/workflow-policy.js +3 -3
  559. package/dist/sdk/governance/workspace-position.js +2 -2
  560. package/dist/sdk/graph/analytics.js +1 -1
  561. package/dist/sdk/graph/assembly.js +1 -1
  562. package/dist/sdk/graph/cache.js +1 -1
  563. package/dist/sdk/graph/cardinality-integrity.js +1 -1
  564. package/dist/sdk/graph/centrality.js +1 -1
  565. package/dist/sdk/graph/deadline-scheduling.js +1 -1
  566. package/dist/sdk/graph/durable-cache.js +1 -1
  567. package/dist/sdk/graph/governance-contracts.js +1 -1
  568. package/dist/sdk/graph/governance.js +1 -1
  569. package/dist/sdk/graph/hierarchy-integrity.js +1 -1
  570. package/dist/sdk/graph/lifecycle-coverage.js +1 -1
  571. package/dist/sdk/graph/mutation-advisory.js +1 -1
  572. package/dist/sdk/graph/query-contracts.js +1 -1
  573. package/dist/sdk/graph/remediation.js +1 -1
  574. package/dist/sdk/graph/run.js +1 -1
  575. package/dist/sdk/graph/scheduling.js +1 -1
  576. package/dist/sdk/graph/traversal.js +1 -1
  577. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
  578. package/dist/sdk/guide-topics.js +1 -1
  579. package/dist/sdk/guide.js +7 -7
  580. package/dist/sdk/history/append-only-repair.js +4 -4
  581. package/dist/sdk/history/attestation-command.js +2 -2
  582. package/dist/sdk/history/attestation-contract.js +1 -1
  583. package/dist/sdk/history/attestation-scan.js +1 -1
  584. package/dist/sdk/history/attestation.js +1 -1
  585. package/dist/sdk/history/maintenance.js +1 -1
  586. package/dist/sdk/history/reanchor-refusal.js +1 -1
  587. package/dist/sdk/history/reseed.js +1 -1
  588. package/dist/sdk/history/salvage.js +5 -5
  589. package/dist/sdk/history/subject.js +1 -1
  590. package/dist/sdk/history-analytics.js +1 -1
  591. package/dist/sdk/history-compact.js +1 -1
  592. package/dist/sdk/history-mcp.js +1 -1
  593. package/dist/sdk/history-provenance.js +1 -1
  594. package/dist/sdk/history-read.js +1 -1
  595. package/dist/sdk/history-redact.js +1 -1
  596. package/dist/sdk/history-repair.js +1 -1
  597. package/dist/sdk/improvement-ledger-validation.js +1 -1
  598. package/dist/sdk/improvement-ledger.js +2 -2
  599. package/dist/sdk/index.d.ts +1 -1
  600. package/dist/sdk/init-agent-guidance.js +10 -10
  601. package/dist/sdk/init.js +14 -14
  602. package/dist/sdk/invocation-author.js +1 -1
  603. package/dist/sdk/item-children.js +1 -1
  604. package/dist/sdk/item-metadata-index.js +1 -1
  605. package/dist/sdk/item-schedule.js +1 -1
  606. package/dist/sdk/item-transaction.js +1 -1
  607. package/dist/sdk/learnings.js +1 -1
  608. package/dist/sdk/lifecycle/append.js +3 -3
  609. package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
  610. package/dist/sdk/lifecycle/claim.js +1 -1
  611. package/dist/sdk/lifecycle/cli-input.js +1 -1
  612. package/dist/sdk/lifecycle/close-many.js +1 -1
  613. package/dist/sdk/lifecycle/close.js +1 -1
  614. package/dist/sdk/lifecycle/copy.js +1 -1
  615. package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
  616. package/dist/sdk/lifecycle/core-item-fields.js +1 -1
  617. package/dist/sdk/lifecycle/create-deferrals.js +1 -1
  618. package/dist/sdk/lifecycle/create.js +1 -1
  619. package/dist/sdk/lifecycle/delete.js +1 -1
  620. package/dist/sdk/lifecycle/dependency-removal.js +1 -1
  621. package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
  622. package/dist/sdk/lifecycle/focus.js +1 -1
  623. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
  624. package/dist/sdk/lifecycle/item-revision.js +1 -1
  625. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
  626. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
  627. package/dist/sdk/lifecycle/mcp-actions.js +1 -1
  628. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
  629. package/dist/sdk/lifecycle/mutation-command-options.js +0 -1
  630. package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
  631. package/dist/sdk/lifecycle/mutation-option-validation.js +1 -1
  632. package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
  633. package/dist/sdk/lifecycle/plan.js +1 -1
  634. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
  635. package/dist/sdk/lifecycle/release-handoff.js +1 -1
  636. package/dist/sdk/lifecycle/reopen.js +1 -1
  637. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -2
  638. package/dist/sdk/lifecycle/repeated-terminal-state.js +1 -1
  639. package/dist/sdk/lifecycle/restore.js +1 -1
  640. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  641. package/dist/sdk/lifecycle/start-blockers.js +1 -1
  642. package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
  643. package/dist/sdk/lifecycle/task-composition.js +1 -1
  644. package/dist/sdk/lifecycle/update-many.js +1 -1
  645. package/dist/sdk/lifecycle/update.js +2 -2
  646. package/dist/sdk/lifecycle/workflow-transition.js +1 -1
  647. package/dist/sdk/lifecycle-completion.js +1 -1
  648. package/dist/sdk/lifecycle-policy.js +1 -1
  649. package/dist/sdk/linked-artifacts.js +2 -2
  650. package/dist/sdk/mcp/apps.js +5 -5
  651. package/dist/sdk/mcp/authorization.js +1 -1
  652. package/dist/sdk/mcp/discovery.js +1 -1
  653. package/dist/sdk/mcp/executable.js +4 -4
  654. package/dist/sdk/mcp/interactions.js +1 -1
  655. package/dist/sdk/mcp/protocol.js +1 -1
  656. package/dist/sdk/mcp/skills.js +3 -3
  657. package/dist/sdk/mcp/subscriptions.js +1 -1
  658. package/dist/sdk/mcp/tasks.js +2 -2
  659. package/dist/sdk/mcp/transport.js +1 -1
  660. package/dist/sdk/merge/abandoned-receipts.js +1 -1
  661. package/dist/sdk/merge/driver.js +7 -7
  662. package/dist/sdk/merge/history-scalar-rebase.js +1 -1
  663. package/dist/sdk/merge/ignored-artifacts.js +1 -1
  664. package/dist/sdk/merge/index.js +1 -1
  665. package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
  666. package/dist/sdk/merge/install.js +6 -6
  667. package/dist/sdk/merge/receipt-file-boundary.js +1 -1
  668. package/dist/sdk/merge/receipt-operation.js +1 -1
  669. package/dist/sdk/merge/receipt-schema.js +1 -1
  670. package/dist/sdk/merge/receipts.js +4 -4
  671. package/dist/sdk/merge/reconcile.js +1 -1
  672. package/dist/sdk/merge/settlement-hook.js +4 -4
  673. package/dist/sdk/merge/stage.js +1 -1
  674. package/dist/sdk/merge/three-way.js +9 -9
  675. package/dist/sdk/merge/worktree-config.js +2 -2
  676. package/dist/sdk/merge.js +1 -1
  677. package/dist/sdk/mutation-events.js +1 -1
  678. package/dist/sdk/mutation-guard.js +1 -1
  679. package/dist/sdk/notes.js +1 -1
  680. package/dist/sdk/output/fit-envelope.js +1 -1
  681. package/dist/sdk/output/list-envelope.js +1 -1
  682. package/dist/sdk/output/table-rows.js +1 -1
  683. package/dist/sdk/output-contracts.js +1 -1
  684. package/dist/sdk/output-projection.js +1 -1
  685. package/dist/sdk/output-token-accounting.js +1 -1
  686. package/dist/sdk/output.js +2 -2
  687. package/dist/sdk/ownership-source.js +1 -1
  688. package/dist/sdk/package-import-adapters.js +1 -1
  689. package/dist/sdk/package-migrations.js +1 -1
  690. package/dist/sdk/package-runtime-options.js +1 -1
  691. package/dist/sdk/pagination.js +1 -1
  692. package/dist/sdk/profile.js +5 -5
  693. package/dist/sdk/provenance.js +1 -1
  694. package/dist/sdk/public-surface.json +1 -1
  695. package/dist/sdk/query/activity.js +1 -1
  696. package/dist/sdk/query/aggregate.js +1 -1
  697. package/dist/sdk/query/calendar.js +4 -4
  698. package/dist/sdk/query/complete-list.js +1 -1
  699. package/dist/sdk/query/context.js +2 -2
  700. package/dist/sdk/query/declared-blockers.js +1 -1
  701. package/dist/sdk/query/duplicate-candidates.js +1 -1
  702. package/dist/sdk/query/get-facet-roots.js +1 -1
  703. package/dist/sdk/query/get.js +1 -1
  704. package/dist/sdk/query/history.js +1 -1
  705. package/dist/sdk/query/item-filter-options.js +0 -1
  706. package/dist/sdk/query/light-metadata.js +1 -1
  707. package/dist/sdk/query/list-filter-shared.js +1 -1
  708. package/dist/sdk/query/list.js +1 -1
  709. package/dist/sdk/query/multi-value-filters.js +1 -1
  710. package/dist/sdk/query/next-ranking-policy.js +1 -1
  711. package/dist/sdk/query/next-ready-budget.js +1 -1
  712. package/dist/sdk/query/next.js +2 -2
  713. package/dist/sdk/query/parsers.js +1 -1
  714. package/dist/sdk/query/projection-contracts.js +1 -1
  715. package/dist/sdk/query/search/corpus.js +2 -2
  716. package/dist/sdk/query/search/filters.js +1 -1
  717. package/dist/sdk/query/search/input.js +1 -1
  718. package/dist/sdk/query/search/lexical.js +1 -1
  719. package/dist/sdk/query/search/response.js +1 -1
  720. package/dist/sdk/query/search/semantic.js +3 -3
  721. package/dist/sdk/query/search/types.js +0 -1
  722. package/dist/sdk/query/search-contracts.js +1 -1
  723. package/dist/sdk/query/search-pagination.js +1 -1
  724. package/dist/sdk/query/search-rendering.js +1 -1
  725. package/dist/sdk/query/search.js +1 -1
  726. package/dist/sdk/query/window-pagination.js +1 -1
  727. package/dist/sdk/query/workspace-contracts.js +1 -1
  728. package/dist/sdk/read-output/continuation.js +1 -1
  729. package/dist/sdk/read-output/extension.js +1 -1
  730. package/dist/sdk/read-output/options.js +1 -1
  731. package/dist/sdk/read-output/positional-rows.js +1 -1
  732. package/dist/sdk/read-output/provenance.js +1 -1
  733. package/dist/sdk/read-output/session-result.js +0 -1
  734. package/dist/sdk/read-output/surfaces.js +1 -1
  735. package/dist/sdk/read-output/tail-retention.js +1 -1
  736. package/dist/sdk/read-output-budget.js +1 -1
  737. package/dist/sdk/read-output-contracts.d.ts +11 -0
  738. package/dist/sdk/read-output-contracts.js +1 -1
  739. package/dist/sdk/read-output-rows.js +1 -1
  740. package/dist/sdk/read-output-session.js +1 -1
  741. package/dist/sdk/relationship-analytics.js +1 -1
  742. package/dist/sdk/relationship-context.js +1 -1
  743. package/dist/sdk/relationship-history.js +6 -6
  744. package/dist/sdk/relationship-kinds/contract.js +1 -1
  745. package/dist/sdk/relationships.js +1 -1
  746. package/dist/sdk/reproducibility/process.js +1 -1
  747. package/dist/sdk/runtime/actions.js +1 -1
  748. package/dist/sdk/runtime/context.js +1 -1
  749. package/dist/sdk/runtime/mutation-admission.js +1 -1
  750. package/dist/sdk/runtime/mutation-value-validation.js +1 -1
  751. package/dist/sdk/runtime/schema-preview.js +1 -1
  752. package/dist/sdk/runtime/schema.js +1 -1
  753. package/dist/sdk/runtime-action-aliases.js +1 -1
  754. package/dist/sdk/runtime-extended-actions.js +1 -1
  755. package/dist/sdk/runtime-input.d.ts +2 -0
  756. package/dist/sdk/runtime-input.js +1 -1
  757. package/dist/sdk/runtime-primitives.js +1 -1
  758. package/dist/sdk/runtime-public-contracts.js +0 -1
  759. package/dist/sdk/runtime-stats-options.js +1 -1
  760. package/dist/sdk/runtime.d.ts +5 -3
  761. package/dist/sdk/runtime.js +1 -1
  762. package/dist/sdk/scheduling-shortcuts.js +1 -1
  763. package/dist/sdk/schema/field-flag-spelling.d.ts +22 -0
  764. package/dist/sdk/schema/field-flag-spelling.js +2 -0
  765. package/dist/sdk/schema/field-option-collisions.js +2 -0
  766. package/dist/sdk/schema-migration.js +4 -4
  767. package/dist/sdk/schema.js +7 -7
  768. package/dist/sdk/search-refresh-worker.js +1 -1
  769. package/dist/sdk/similarity-scoring.js +1 -1
  770. package/dist/sdk/similarity.js +1 -1
  771. package/dist/sdk/start-task-status.js +1 -1
  772. package/dist/sdk/stats.js +1 -1
  773. package/dist/sdk/structured-mutations.js +1 -1
  774. package/dist/sdk/telemetry-flush.js +1 -1
  775. package/dist/sdk/telemetry.js +4 -4
  776. package/dist/sdk/templates.js +3 -3
  777. package/dist/sdk/test/batch.js +2 -2
  778. package/dist/sdk/test/command-args.js +1 -1
  779. package/dist/sdk/test/command-resolution.js +2 -2
  780. package/dist/sdk/test/entry.js +2 -2
  781. package/dist/sdk/test/execution-receipts.js +2 -2
  782. package/dist/sdk/test/execution.js +5 -5
  783. package/dist/sdk/test/json-path.js +1 -1
  784. package/dist/sdk/test/linked-command-detection.js +1 -1
  785. package/dist/sdk/test/measurements.js +1 -1
  786. package/dist/sdk/test/parsers.js +1 -1
  787. package/dist/sdk/test/prerequisites.js +1 -1
  788. package/dist/sdk/test/receipt-index-snapshot.js +1 -1
  789. package/dist/sdk/test/run-phases.js +1 -1
  790. package/dist/sdk/test/runs.js +1 -1
  791. package/dist/sdk/test/trust.js +2 -2
  792. package/dist/sdk/test/update.js +1 -1
  793. package/dist/sdk/test/workspace-snapshot.js +1 -1
  794. package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
  795. package/dist/sdk/traceability/source-traceability.js +2 -2
  796. package/dist/sdk/tracker-root-discovery.js +1 -1
  797. package/dist/sdk/transactions/item-finalization.js +1 -1
  798. package/dist/sdk/workspace-contracts-cache.js +1 -1
  799. package/dist/sdk/workspace-contracts.js +1 -1
  800. package/dist/sdk/workspace-memory.js +2 -2
  801. package/dist/sdk/workspace-snapshot.js +5 -5
  802. package/dist/sdk/workspace-transaction-gc.js +1 -1
  803. package/dist/sdk/workspace-transaction.js +2 -2
  804. package/dist/sdk/workspace.js +6 -6
  805. package/dist/types/index.js +1 -1
  806. package/dist/types.js +1 -1
  807. package/docs/COMMANDS.md +1 -1
  808. package/docs/EXTENSIONS.md +2 -2
  809. package/docs/READ_OUTPUT_CONTRACTS.md +2 -0
  810. package/docs/SDK.md +94 -5
  811. package/docs/SDK_AUDITED_MUTATIONS.md +11 -0
  812. package/marketplace.json +1 -1
  813. package/package.json +2 -1
  814. package/packages/pm-beads/package.json +1 -1
  815. package/packages/pm-calendar/package.json +1 -1
  816. package/packages/pm-command-kit/package.json +1 -1
  817. package/packages/pm-digital-twin/package.json +1 -1
  818. package/packages/pm-governance-audit/package.json +1 -1
  819. package/packages/pm-guide-shell/package.json +1 -1
  820. package/packages/pm-kanban/package.json +1 -1
  821. package/packages/pm-lifecycle-hooks/package.json +1 -1
  822. package/packages/pm-linked-test-adapters/package.json +1 -1
  823. package/packages/pm-search-advanced/package.json +1 -1
  824. package/packages/pm-templates/package.json +1 -1
  825. package/packages/pm-todos/package.json +1 -1
  826. package/packages/pm-vcs/package.json +1 -1
  827. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  828. package/plugins/pm-claude/package.json +1 -1
  829. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  830. package/plugins/pm-codex/package.json +1 -1
  831. package/plugins/pm-codex/plugin.json +1 -1
  832. package/runtime-dependencies.json +1 -1
  833. package/scripts/finalize-build.mjs +63 -24
  834. package/scripts/prepare-build-cache.mjs +28 -1
  835. package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +0 -9
  836. package/dist/cli-bundle/chunks/chunk-4TB5D6HL.js +0 -125
  837. package/dist/cli-bundle/chunks/chunk-5ZMVLWE3.js +0 -2
  838. package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +0 -33
  839. package/dist/cli-bundle/chunks/chunk-AR4NP5HI.js +0 -3
  840. package/dist/cli-bundle/chunks/chunk-B4PPFOPY.js +0 -3
  841. package/dist/cli-bundle/chunks/chunk-CAR2L5NW.js +0 -8
  842. package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
  843. package/dist/cli-bundle/chunks/chunk-EIGUKEV6.js +0 -2
  844. package/dist/cli-bundle/chunks/chunk-GTPCAJMZ.js +0 -8
  845. package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +0 -2
  846. package/dist/cli-bundle/chunks/chunk-HC2OPETM.js +0 -2
  847. package/dist/cli-bundle/chunks/chunk-HKUV74K3.js +0 -2
  848. package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +0 -115
  849. package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +0 -2
  850. package/dist/cli-bundle/chunks/chunk-J2LABXBL.js +0 -2
  851. package/dist/cli-bundle/chunks/chunk-J52BEBSS.js +0 -2
  852. package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +0 -3
  853. package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +0 -3
  854. package/dist/cli-bundle/chunks/chunk-OJTMGDON.js +0 -31
  855. package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +0 -2
  856. package/dist/cli-bundle/chunks/chunk-TC6XLIYO.js +0 -2
  857. package/dist/cli-bundle/chunks/chunk-U7EL3AYA.js +0 -3
  858. package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +0 -6
  859. package/dist/cli-bundle/chunks/chunk-X6MIWTTT.js +0 -2
  860. package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +0 -2
  861. package/dist/cli-bundle/chunks/chunk-XFHPKXAE.js +0 -71
  862. package/dist/cli-bundle/chunks/chunk-YHVLVSEZ.js +0 -9
  863. package/dist/cli-bundle/chunks/chunk-YMUSRWV4.js +0 -9
  864. package/dist/cli-bundle/chunks/chunk-YR2KEBHP.js +0 -2
  865. package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +0 -2
  866. package/dist/cli-bundle/chunks/indexed-receipt-blobs-ITTXIN4K.js +0 -4
  867. package/dist/cli-bundle/chunks/item-revision-4QBMZXKX.js +0 -2
  868. package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +0 -2
  869. package/dist/cli-bundle/chunks/mutation-actor-FWLYWJ37.js +0 -2
  870. package/dist/cli-bundle/chunks/mutation-admission-7ZDCK3G2.js +0 -2
  871. package/dist/cli-bundle/chunks/register-mutation-57AJQWFV.js +0 -21
  872. package/dist/cli-bundle/chunks/register-operations-RKWST7CU.js +0 -2
  873. package/dist/cli-bundle/chunks/register-setup-CMI23PC5.js +0 -2
  874. package/dist/cli-bundle/chunks/settlement-hook-BXN5LEQD.js +0 -7
  875. package/dist/cli-bundle/chunks/stage-4KDVXC5Z.js +0 -2
  876. package/dist/cli-bundle/focused-chunks/chunk-2ZD7275J.js +0 -2
  877. package/dist/cli-bundle/focused-chunks/chunk-324AHXJO.js +0 -2
  878. package/dist/cli-bundle/focused-chunks/chunk-3IRCYJI5.js +0 -3
  879. package/dist/cli-bundle/focused-chunks/chunk-3V53UBHN.js +0 -9
  880. package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +0 -91
  881. package/dist/cli-bundle/focused-chunks/chunk-4JZITIJB.js +0 -2
  882. package/dist/cli-bundle/focused-chunks/chunk-4KTFKSS3.js +0 -2
  883. package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +0 -78
  884. package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +0 -2
  885. package/dist/cli-bundle/focused-chunks/chunk-BRZV7BFV.js +0 -8
  886. package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +0 -2
  887. package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +0 -3
  888. package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +0 -2
  889. package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +0 -2
  890. package/dist/cli-bundle/focused-chunks/chunk-HDEKFSOK.js +0 -2
  891. package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +0 -2
  892. package/dist/cli-bundle/focused-chunks/chunk-IWOXAUDU.js +0 -2
  893. package/dist/cli-bundle/focused-chunks/chunk-ML3JHCC6.js +0 -6
  894. package/dist/cli-bundle/focused-chunks/chunk-OPGOOP25.js +0 -2
  895. package/dist/cli-bundle/focused-chunks/chunk-RE7ZWT7D.js +0 -27
  896. package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +0 -3
  897. package/dist/cli-bundle/focused-chunks/chunk-RQ252B6V.js +0 -8
  898. package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +0 -2
  899. package/dist/cli-bundle/focused-chunks/chunk-URGHTTT3.js +0 -8
  900. package/dist/cli-bundle/focused-chunks/chunk-USPYKWQG.js +0 -13
  901. package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +0 -102
  902. package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +0 -44
  903. package/dist/cli-bundle/focused-chunks/chunk-WZWXGDYY.js +0 -26
  904. package/dist/cli-bundle/focused-chunks/chunk-YKSLZPLT.js +0 -2
  905. package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +0 -2
  906. package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +0 -2
  907. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-AF4U3F3D.js +0 -4
  908. package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +0 -2
  909. package/dist/cli-bundle/focused-chunks/mutation-actor-TCYDPUGG.js +0 -2
  910. package/dist/cli-bundle/focused-chunks/mutation-admission-LY73EJWM.js +0 -2
  911. package/dist/cli-bundle/focused-chunks/settlement-hook-ARYCZQY4.js +0 -7
  912. package/dist/cli-bundle/focused-chunks/stage-DQ7RQQ52.js +0 -2
@@ -0,0 +1,3 @@
1
+ import{a as A,c as b,d as C,e as E,k as S,m as x}from"./chunk-WWTPNIC2.js";import{lb as w,mb as R,nb as k}from"./chunk-7VRFEURZ.js";import{Ka as v,pa as p,sa as g,ta as a}from"./chunk-ZYCOM4MS.js";import{ca as O,od as B}from"./chunk-YOPTAIBD.js";import{Af as y,Ih as I,uf as H,zf as u}from"./chunk-FXJYZBWV.js";import{A as c,C as f}from"./chunk-YYT3MIRF.js";function _(r,e){if(typeof r!="string")return;let o=Number.parseInt(r,10);if(!/^\d+$/.test(r.trim())||!Number.isSafeInteger(o))throw new f(`history-compact ${e} must be a non-negative integer.`,c.USAGE);return o}async function D(r,e,o){let t=p(o),s=Date.now(),i=await O(a(e,"ids")),l=i===void 0?void 0:B(i),m=_(e.allOver,"--all-over"),d=_(e.minEntries,"--min-entries");if(e.closed===!0&&e.allStreams===!0)throw new f("history-compact: --closed and --all-streams are mutually exclusive; pick one lifecycle scope.",c.USAGE);let n=e.closed===!0?"closed":e.allStreams===!0?"all-streams":void 0;if((l!==void 0||m!==void 0||n!==void 0)&&typeof e.before=="string")throw new f("history-compact: --before applies only in single-id mode (bulk mode always compacts full streams).",c.USAGE);if(b(r,{ids:l,allOver:m,scope:n}),r!==void 0&&d!==void 0)throw new f("history-compact: --min-entries applies only in bulk mode (single-id mode compacts the named stream).",c.USAGE);if(r===void 0){let h=await C({ids:l,scope:n,allOver:m,minEntries:d,dryRun:e.dryRun===!0,author:a(e,"author"),message:a(e,"message"),force:!!e.force},t);u(h,t),h.totals.items_errored>0&&(process.exitCode=c.GENERIC_FAILURE)}else{let h=await A(r,{before:a(e,"before"),dryRun:e.dryRun===!0,author:a(e,"author"),message:a(e,"message"),force:!!e.force},t);u(h,t)}t.profile&&y(`profile:command=history-compact took_ms=${Date.now()-s}`)}async function N(r,e,o,t){let s=p(t),i=Date.now(),l=await x(r,e,{author:a(o,"author"),message:a(o,"message"),force:!!o.force},s);await v(s,l),u(l,s),s.profile&&y(`profile:command=restore took_ms=${Date.now()-i}`)}async function F(r,e){let o=p(e),t=await S({verify:a(r,"verify"),output:a(r,"output"),hashAlgorithm:a(r,"hashAlgorithm")},o);"format"in t?(I(t),o.quiet||H(`${JSON.stringify(t,null,2)}
2
+ `)):u(t,o),"ok"in t&&!t.ok&&(process.exitCode=c.GENERIC_FAILURE)}function ee(r,e){r.command(e?"attest":"history-attest",{hidden:!e}).summary("Export or verify history proof.").option("--verify <file>","Compare retained streams with a detached JSON proof").option("--output <file>","Create a proof file and return a compact receipt").option("--hash-algorithm <name>","Bundle digest algorithm: sha256 (default) or sha512").description("Export exact-byte history commitments, or verify an independently retained proof without tracker writes.").action(F),r.command("restore",{hidden:!e}).summary("Restore a version.").argument("<id>","Item id").argument("<target>","Restore target timestamp or version number").option("--author <value>","Mutation author").option("--message <value>","History message").option("--force","Force ownership/lock override").description("Restore an item to an earlier timestamp or version.").action(N),r.command(e?"redact":"history-redact",{hidden:!e}).summary("Redact sensitive values.").argument("<id>","Item id").option("--literal <value>","Literal; repeatable",g).option("--regex <value>","Raw RegExp source (repeatable; e.g. /var/[a-z]+) or /pattern/flags. Leading-slash input is a literal only when the final unescaped slash is followed by supported JavaScript flag letters or nothing.",g).option("--replacement <value>",'Default: "[redacted]"').option("--dry-run","Preview; no item/history edits").option("--author <value>","Author").option("--message <value>","Audit marker message").option("--force","Override owner/lock").description("Redact and reseal item history.").action(async(o,t,s)=>{let i=p(s),l=Date.now(),m=Array.isArray(t.literal)?t.literal:void 0,d=Array.isArray(t.regex)?t.regex:void 0,n=await E(o,{literal:m,regex:d,replacement:a(t,"replacement"),dryRun:t.dryRun===!0,author:a(t,"author"),message:a(t,"message"),force:!!t.force},i);n.changed&&!n.dry_run&&await v(i,n),u(n,i),i.profile&&y(`profile:command=history-redact took_ms=${Date.now()-l}`)}),r.command(e?"repair":"history-repair",{hidden:!e}).summary("Repair drift.").argument("[id]","Item id (omit with --all)").option("--salvage-tail","Recover invalid tail; requires verified prefix").option("--append-only","Bridge breaks; never rewrite entries").option("--all","Scan every stream for drift and repair each drifted stream in one audited pass").option("--dry-run","Preview the re-anchor impact without writing the history file").option("--normalize-provenance","Remove invalid provenance; return aggregate-only evidence").option("--author <value>","Mutation author").option("--message <value>","Audit history message for the repair marker entry").option("--force","Force ownership/lock override").description("Re-anchor a drifted item history chain (recompute hashes, reconcile with the on-disk item) and record an audit marker. Use --all to repair every drifted stream.").action(async(o,t,s)=>{let i=p(s),l=Date.now(),m=t.all===!0;R(o,m);let d={dryRun:t.dryRun===!0,author:a(t,"author"),message:a(t,"message"),force:!!t.force,normalizeProvenance:t.normalizeProvenance===!0,salvageTail:t.salvageTail===!0,appendOnly:t.appendOnly===!0};if(m){let n=await k(d,i);u(n,i),n.totals.failed>0&&(process.exitCode=c.GENERIC_FAILURE)}else{let n=await w(o,d,i);u(n,i)}i.profile&&y(`profile:command=history-repair took_ms=${Date.now()-l}`)}),r.command(e?"compact":"history-compact",{hidden:!e}).summary("Compact streams.").argument("[id]","Item id (omit when using a bulk selector)").option("--before <value>","Compact entries strictly before this version number or ISO timestamp (single-id mode only)").option("--ids <value>","Bulk IDs: comma/newline text, - stdin, or @path file").option("--all-over <n>","Bulk: compact every stream with more than N entries").option("--closed","Bulk: compact only closed (terminal) items' streams").option("--all-streams","Bulk: compact every history stream regardless of lifecycle state").option("--min-entries <n>","Bulk: skip streams with at most N entries (already compact; default 3)").option("--dry-run","Preview compaction impact without writing the history file").option("--author <value>","Mutation author").option("--message <value>","Audit history message for the compaction marker entry").option("--force","Force ownership/lock override").description("Compact item history streams into a synthetic baseline plus retained tail entries. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to compact many.").action(D)}export{ee as a};
3
+ //# sourceMappingURL=chunk-VJSGUXGU.js.map
@@ -0,0 +1,6 @@
1
+ import{$ as Io,B as Eo,C as bo,Eb as Mo,F as So,Gb as Fo,Ib as To,Jb as Po,Ka as Ao,N as xo,O as Ro,R as ko,S as kt,T as It,U as ze,e as ho,i as ge,ib as Co,j as po,jb as Ve,k as go,l as We,m as yo,mc as Ho,n as _o,q as wo,qc as Oo,r as vo}from"./chunk-7VRFEURZ.js";import{a as co,b as lo}from"./chunk-STOOTHZZ.js";import{c as bt,j as so,r as ao}from"./chunk-Z7MFVRDV.js";import{a as pe,b as K}from"./chunk-PQUBVRV5.js";import{Ba as Oe,Cb as Xn,Db as Jn,Eb as $e,Fb as Zn,Gb as Ue,Hb as Ge,Ib as Be,Jb as eo,Ma as Dn,Na as Nn,Nb as to,Ob as Et,Ra as $n,T as $,Va as H,Xa as Un,Xb as ro,Ya as re,Z as Fn,Za as vt,_ as Tn,_a as Gn,aa as Pn,ba as Hn,da as wt,dd as no,ea as On,eb as Bn,fa as Te,hd as oo,ka as qn,mb as Le,ob as je,od as io,pb as zn,qb as qe,rb as De,sb as Vn,tb as Kn,ub as Ne,wb as Qn,xa as He,xb as Yn}from"./chunk-YOPTAIBD.js";import{B as Wn,I as O,a as Pe,b as Ln,c as jn,v as P}from"./chunk-23K6DQQY.js";import{Ab as Ce,Ac as me,Ba as ce,Bb as Me,Bc as pt,Ca as Re,Cc as T,Cf as yt,Dc as nn,Dh as x,Ec as fe,Ef as _n,Fc as on,Ga as ke,Ha as Kr,Hc as sn,Ic as gt,Ie as un,Je as mn,Jf as wn,Kf as vn,Kh as Cn,Lc as an,Lh as _t,Mf as En,Nb as en,Ne as fn,Nf as bn,Oh as te,Pc as cn,Pe as hn,Pf as Sn,Rh as Mn,Sh as he,Tf as V,Uf as xn,V as D,_e as pn,ab as I,ag as Rn,ba as k,bb as ft,ca as Wr,cd as ee,da as zr,eb as Ae,fa as z,gb as Xr,ha as xe,id as dn,ig as kn,jb as Jr,jg as In,lb as de,lg as An,mf as gn,nc as Fe,nf as yn,oc as tn,od as ln,sc as le,ta as ut,xc as rn,yc as ht,zb as Zr,zc as ue}from"./chunk-FXJYZBWV.js";import{gb as fo,h as St,i as xt,k as Rt,l as uo,m as mo}from"./chunk-I2OJ5B4A.js";import{A as Vr,K as S,N as Ie,O as Qr,P as Yr,Q as mt,a as F,s as J}from"./chunk-7IROAPWI.js";import{O as N,Q as Z}from"./chunk-7X253M6Z.js";import{A as h,C as p,E as Se,G as Br,K as L,u as Ur,z as Gr}from"./chunk-YYT3MIRF.js";import jo from"node:fs/promises";import qo from"node:path";function cs(e,t,r){let n=new Set,o=[];for(let i of e){let s=i.trim();if(s.length===0||n.has(s))continue;n.add(s);let a=t.get(s);if(a===void 0){o.push({id:s,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=r){o.push({id:s,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:s,entries:a.entries,selected:!0,skip_reason:null})}return o}function ds(e,t){let r=[...e].sort((o,i)=>i.entries-o.entries||o.id.localeCompare(i.id)),n=[];for(let o of r){if(t.scope==="closed"&&o.bucket!=="closed"){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}n.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return n}function Lo(e,t){if(t.ids!==void 0&&t.ids.length>0){let r=new Map(e.map(n=>[n.id,n]));return cs(t.ids,r,t.minEntries)}return ds(e,t)}function ls(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let r=e.trim();if(r.length===0)throw new p("history-compact --before requires a non-empty value.",h.USAGE);if(/^\d+$/.test(r)){let i=Number.parseInt(r,10),s=H(t);if(!Number.isSafeInteger(i)||i<s+1||i>s+t.length+1)throw new p(`history-compact --before version must be between ${s+1} and ${s+t.length+1}.`,h.USAGE);let a=i-s-1;return{kind:"version",raw:r,compactCount:a,retainedCount:t.length-a}}let n=Date.parse(r);if(!Number.isFinite(n))throw new p(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,h.USAGE);let o=0;for(let[i,s]of t.entries()){let a=Date.parse(s.ts);if(!Number.isFinite(a))throw new p(`History for this item contains invalid timestamp at entry ${i+1}.`,h.GENERIC_FAILURE);if(a>=n)break;o+=1}return{kind:"timestamp",raw:r,compactCount:o,retainedCount:t.length-o}}function us(e,t){let r=ue(),n=ue();for(let o=0;o<e.length;o+=1){let i=e[o];r=re(r,i.patch,o+1,i.op),o+1===t&&(n=structuredClone(r))}return{checkpoint:n,finalReplay:r}}function ms(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let r=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:_n.some(n=>(r.item_hash_version===void 0||r.item_hash_version===n)&&pt(fe(e.document),n,I(r.hash_algorithm)).includes(r.after_hash))}}function fs(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function hs(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function ps(e,t){let r=e.slice(0,t).findIndex(o=>!no(o));if(r===-1)return;let n=Number.isFinite(Date.parse(e[r].ts))?"a malformed record or compaction receipt":"invalid timestamp";throw new p(`History for this item contains ${n} at entry ${r+1}.`,h.GENERIC_FAILURE)}function gs(e,t){let r=e[t.start].ts,n=e.slice(0,t.end+1).map(i=>Date.parse(i.ts));if(!n.every(Number.isFinite))return["that boundary",`Choose a --before timestamp at or before "${r}".`,`Run pm history-compact <id> --before "${r}".`];let o=new Date(n.reduce((i,s)=>Math.max(i,s),Number.NEGATIVE_INFINITY)).toISOString();return["that boundary",`Choose a --before timestamp at or before "${r}", or after "${o}".`,`Run pm history-compact <id> --before "${r}", or with a timestamp after "${o}".`]}function ys(e,t){let r=t-1,n=(sn(e).bridged_segments??[]).find(({start:d,end:l})=>d<=r&&r<l);if(n===void 0)return;let o=H(e,!0),[i,s,a]=o===null?gs(e,n):[`version ${o+t}`,`Choose --before ${o+n.start+1} or lower, or --before ${o+n.end+2} or higher.`,`Run pm history-compact <id> --before ${o+n.start+1} or --before ${o+n.end+2}.`];throw new p(`history-compact cannot checkpoint ${i}: it lies inside a bridged segment whose states cannot be reconstructed.`,h.USAGE,{code:"history_compact_boundary_bridged",required:s,nextSteps:[a]})}function _s(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};ys(e.historyEntries,e.boundary.compactCount);let{checkpoint:t,finalReplay:r}=us(e.historyEntries,e.boundary.compactCount),n=e.historyEntries.slice(e.boundary.compactCount),o=H(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],s=V({hashAlgorithm:I(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:T(ue()),after:T(t),message:hs(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",last_activity_at:oo(e.historyEntries.slice(0,e.boundary.compactCount)),pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:wn(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),a=[vn({...s,before_hash:pt(ue(),i.item_hash_version??1,I(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version,...i.replay_inexact===!0?{replay_inexact:!0}:{}}),...n];return e.dryRun||a.push(V({nowIso:S(),author:e.author,op:"history_compact",before:T(r),after:T(r),message:fs(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function ws(e,t,r){let{pmRoot:n,settings:o,typeRegistry:i}=await pe(r.path),s=await K(n,e,o,i.type_to_folder);return Ve({pmRoot:n,subject:s,settings:o,typeRegistry:i,operation:"history-compact",options:t,transform:a=>vs(s,t,a)})}function vs(e,t,r){let n=e.historyPath,o=r.entries,i=r.verification;if(!i.ok)throw new p(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,h.CONFLICT);let s=ls(t.before,o);ps(o,s.compactCount);let a=s.compactCount>0,d=!!t.dryRun,l=r.author,c=[];a||c.push("history_compact_noop_before_boundary");let u=ms(r.loadedItem,o);u.matchedChainBefore===!1&&c.push("history_compact_item_chain_mismatch");let{rewrittenEntries:m,baselineEntryAdded:f,auditEntryAdded:_}=_s({historyEntries:o,boundary:s,changed:a,dryRun:d,author:l,options:t}),y=H(o,!0),g=s.retainedCount>0&&y!==null?y+s.compactCount+1:null;return{changed:a,rewrittenEntries:m,report:({verification:w,warnings:v})=>({id:e.id,dry_run:d,changed:a,compact_boundary:{kind:s.kind,before:s.raw,entries_compacted:s.compactCount,entries_retained:s.retainedCount,first_retained_entry:g},history:{path:n,entries_scanned:o.length,entries_after:m.length,baseline_entry_added:f,audit_entry_added:_,verify_ok:w.ok,verify_errors:w.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:u.matchedChainBefore},warnings:[...new Set([...c,...v])].sort((b,E)=>b.localeCompare(E)),generated_at:S()})}}var Es=3;function bs(e){for(let r of["allOver","minEntries"]){let n=e[r];if(n!==void 0&&(!Number.isSafeInteger(n)||n<0))throw new p(`history-compact ${r} must be a non-negative safe integer.`,h.USAGE)}let t=Hn(e.ids);if(e.ids!==void 0&&t==="")throw new p("history-compact ids requires at least one valid item ID.",h.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:Pn(t)}}function Hd(e,t){let r=t.ids!==void 0&&t.ids.length>0,n=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(r?1:0)+(n?1:0)===0)throw new p("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",h.USAGE);if(e!==void 0&&(r||n))throw new p("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",h.USAGE);if(r&&n)throw new p("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",h.USAGE)}function Ss(e){let t=0;for(let r of e.split(/\r?\n/))r.trim().length>0&&(t+=1);return t}async function xs(e){let t=N(e.settings.schema),r=We(t),n=await Ne(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(n.map(l=>[l.id,r.classify(l.status)])),i=qo.join(e.pmRoot,"history"),s=[],a=[];if(!await Se(i))return{candidates:s,preselectionErrors:a};let d=(await jo.readdir(i)).filter(l=>l.endsWith(".jsonl")).sort((l,c)=>l.localeCompare(c));for(let l of d){let c=qo.join(i,l),u=l.slice(0,-6);try{let m=await jo.readFile(c,"utf8");await he({path:c,scope:"project"}),s.push({id:u,entries:Ss(m),bucket:o.get(u)??null})}catch(m){a.push({id:u,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:m instanceof Error?m.message:String(m)})}}return{candidates:s,preselectionErrors:a}}async function Rs(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await ws(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t),...await ao(t,e.pmRoot)}}}}async function Od(e,t){let r=bs(e),{pmRoot:n,settings:o,typeRegistry:i}=await pe(t.path),{candidates:s,preselectionErrors:a}=await xs({pmRoot:n,settings:o,typeToFolder:i.type_to_folder}),d=r.ids!==void 0&&r.ids.length>0?"ids":"scan",l=e.minEntries??Es,c=o.history.compact_policy,u=d==="scan"&&e.allOver===void 0&&c.enabled,m=e.allOver??(u?c.max_entries:void 0),f=Lo(s,{ids:r.ids,scope:e.scope,minEntries:l,allOver:m}),_=!!e.dryRun,y=[...a],g={streams_considered:s.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let w of f){let v=await Rs({pmRoot:n,row:w,options:r,dryRun:_,global:t});if(y.push(v.result),!v.selected){g.items_skipped+=1;continue}g.selected+=1,v.compacted&&(g.items_compacted+=1),v.errored&&(g.items_errored+=1)}return{bulk:!0,dry_run:_,mode:d,scope:e.scope??null,criteria:{min_entries:l,all_over:m??null,policy_threshold_applied:u},totals:g,results:y,generated_at:S()}}import Ct from"node:fs/promises";function Mt(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function No(e){let t=[];for(let r of e)t.includes(r)||t.push(r);return t.includes("g")||t.push("g"),t.join("")}function At(e,t){return new p(`Invalid --regex value at --regex #${e}: ${t}`,h.USAGE,{code:"invalid_argument_value",field:"regex",reason:"invalid_regex",changed:!1,required:`Correct --regex #${e}: use a non-empty raw source or /pattern/flags with valid JavaScript flags.`})}function $o(e,t=1){let r=e.trim();if(r.length===0)throw At(t,"provide a non-empty pattern.");let n=r,o="g";if(r.startsWith("/")&&r.length>1){let i=r.lastIndexOf("/"),s=0;for(let a=i-1;a>=0&&r[a]==="\\";a--)s++;i>0&&s%2===0&&/^[dgimsuvy]*$/u.test(r.slice(i+1))&&(n=r.slice(1,i),o=No(r.slice(i+1)))}if(n.length===0)throw At(t,"an empty pattern is not allowed.");try{new RegExp(n,o)}catch{throw At(t,"provide a valid JavaScript regular expression.")}return{kind:"regex",source:n,flags:o}}function Uo(e,t){let r=[...new Set(Mt(e).map(s=>s.trim()))].filter(s=>s.length>0).map(s=>({kind:"literal",value:s})),n=new Set,o=Mt(t).flatMap((s,a)=>{let d=s.trim();return n.has(d)?[]:(n.add(d),[$o(d,a+1)])}),i=[...r,...o];if(i.length===0)throw new p("history-redact requires at least one matcher via --literal or --regex.",h.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return i}function Go(e,t,r){if(t.length===0)return{value:e,replacements:0};let n=0,o=0;for(;n<=e.length;){let i=e.indexOf(t,n);if(i===-1)break;o+=1,n=i+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(r),replacements:o}}function Bo(e,t,r){let n=new RegExp(t.source,t.flags),o=[...e.matchAll(n)];return o.length===0?{value:e,replacements:0}:{value:e.replace(n,r),replacements:o.length}}function Ft(e,t,r){let n=e,o=0;for(let i of t){let s=i.kind==="literal"?Go(n,i.value,r):Bo(n,i,r);n=s.value,o+=s.replacements}return{value:n,replacements:o}}function ye(e,t,r){if(typeof e=="string")return Ft(e,t,r);if(Array.isArray(e)){let n=0;return{value:e.map(i=>{let s=ye(i,t,r);return n+=s.replacements,s.value}),replacements:n}}if(typeof e=="object"&&e!==null){let n=0,o={};for(let[i,s]of Object.entries(e)){let a=ye(s,t,r);n+=a.replacements,o[i]=a.value}return{value:o,replacements:n}}return{value:e,replacements:0}}function Do(e,t,r){let n=0;return{patch:e.map(i=>{if(!Object.prototype.hasOwnProperty.call(i,"value"))return i;let s=ye(i.value,t,r);return n+=s.replacements,s.replacements>0?{...i,value:s.value}:i}),replacements:n}}function ks(e){let t=structuredClone(ht),r=0,n=0;for(let o=0;o<e.length;o+=1){let i=e[o];me(t,void 0,I(i.hash_algorithm))!==i.before_hash&&(r+=1),t=re(t,i.patch,o+1,i.op),me(t,void 0,I(i.hash_algorithm))!==i.after_hash&&(n+=1)}return{hashMismatchesBefore:r,hashMismatchesAfter:n,finalDocument:t}}function Is(e,t,r){let n=0,o=!1,i=!1,s=e.message;if(typeof e.message=="string"){let l=Ft(e.message,t,r);s=l.value,n+=l.replacements,l.replacements>0&&(o=!0)}let a=Do(e.patch,t,r);n+=a.replacements,o||=a.replacements>0;let d=e.reanchor_evidence?.map(l=>{let c=l.patch?Do(l.patch,t,r):{patch:void 0,replacements:0},u=l.record?ye(l.record,t,r):{value:void 0,replacements:0};n+=c.replacements,n+=u.replacements;let m=c.replacements>0||u.replacements>0;if(o||=m,!m)return l;i=!0;let{patch:f,record:_,record_hash:y,record_hash_version:g,...w}=l;return c.replacements>0?w:{...w,patch:l.patch}});return{entry:{...e,message:s,patch:a.patch,...d?{reanchor_evidence:d}:{}},replacements:n,changed:o,reanchorEvidenceRedacted:i}}function As(e,t,r){let n=structuredClone(ht),o=0,i=0,s=[],a=rn(e),d=[...a.unlocated,...a.undigested];if(d.length>0)throw new p(`history-redact refuses a stream whose bridge at record ${Math.min(...d)+1} does not prove its segment; repair the history first.`,h.GENERIC_FAILURE,{code:"history_redact_bridge_unlocated",required:"Every bridge's segment digest must match the records it covers, so redaction can keep that segment's versions refused.",nextSteps:["Run pm history-repair <id> --dry-run to see how the stream would be repaired."]});let l=an(a.segments);for(let c=0;c<e.length;c+=1){let u=e[c],m=En(u);if(!m.ok)throw new p(`history-redact refuses invalid immutable record ${c+1} (${m.error}).`,h.GENERIC_FAILURE);let f=Is(u,t,r);i+=f.replacements,f.changed&&(o+=1);let _=me(n,void 0,I(u.hash_algorithm));n=re(n,f.entry.patch,c+1,f.entry.op);let y=me(n,void 0,I(u.hash_algorithm)),{bridge:g,...w}=f.entry;s.push(bn(u,{...w,...l.has(c)?{replay_inexact:!0}:{},before_hash:_,after_hash:y},{retainPriorRecord:f.changed||g!==void 0,retainPriorRecordHash:!f.changed}))}return{entries:s,finalDocument:n,entriesChanged:o,replacements:i}}function Wo(e){return Object.keys(e.metadata).length>0}function Cs(e){if(!Wo(e.finalDocument))return{raw:null,path:null,document:null};let t=Me(T(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new p("history-redact would change the item id; narrow your patterns.",h.USAGE);return{document:t,path:z(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:Ce(t,{format:"toon",schema:e.settings.schema})}}function Ms(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function Fs(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let r=e.nextItemDocument??T(e.rewritten.finalDocument);return t.push(V({nowIso:S(),author:e.author,op:"history_redact",before:r,after:r,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function Ts(e){let t=[];return{applyRewrite:async({historyRawUnderLock:r})=>{let n=await Le(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);let i=new Map;e.currentItem.path&&e.currentItem.raw!==null&&i.set(e.currentItem.path,e.currentItem.raw);let s=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await L(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await Ct.rm(e.currentItem.path,{force:!0}),await L(e.subject.historyPath,cn(e.rewrittenEntries))}catch(d){try{await Ps(e.subject.historyPath,r,o,i)}finally{await yt(e.subject.historyPath)}throw d}await yt(e.subject.historyPath);let a=e.nextItem.path??e.currentItem.path;a&&(t=await je({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:a,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await n().catch(a=>{s=()=>{throw a}})}s()},afterWrite:async()=>[...t,...await Hs(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function Ps(e,t,r,n){t===null?await Ct.rm(e,{force:!0}):await L(e,t);for(let o of r){let i=n.get(o);i===void 0?await Ct.rm(o,{force:!0}):await L(o,i)}}async function Hs(e,t){let r=[],n=new Set(t.filter(o=>o!==null));for(let o of n)r.push(...await te({path:o,scope:"project",op:"history_redact"}));return r.push(...await te({path:e,scope:"project",op:"history_redact:history"})),r}async function el(e,t,r){let{pmRoot:n,settings:o,typeRegistry:i}=await pe(r.path),s=t.replacement??"",a=s.length===0,d=a?"[redacted]":s,l=Uo(t.literal,t.regex),c=await K(n,e,o,i.type_to_folder);return Ve({pmRoot:n,subject:c,settings:o,typeRegistry:i,operation:"history-redact",options:t,transform:u=>Os({pmRoot:n,subject:c,settings:o,typeRegistry:i,options:t,rules:l,replacement:d,replacementIsDefault:a},u)})}function Os(e,t){let{pmRoot:r,subject:n,settings:o,typeRegistry:i,options:s,rules:a,replacement:d,replacementIsDefault:l}=e,c=t.entries,u=ks(c),m=As(c,a,d),f=u.hashMismatchesBefore+u.hashMismatchesAfter,_=!!s.dryRun,y=m.replacements>0,g=[];f>0&&g.push(`history_redact_preexisting_hash_mismatches:${f}`),y||g.push("history_redact_no_matches");let w={raw:t.loadedItem?.raw??null,path:n.located?.itemPath??null,document:t.loadedItem?.document??null},v=Cs({pmRoot:r,subject:n,settings:o,typeToFolder:i.type_to_folder,finalDocument:m.finalDocument}),b=(w.path??null)!==(v.path??null)||(w.raw??null)!==(v.raw??null),E=t.author,X=Ms(s,m),{rewrittenEntries:R,auditEntryAdded:lt}=Fs({rewritten:m,dryRun:_,changed:y,nextItemDocument:v.document,author:E,message:X});return{changed:y,rewrittenEntries:R,...Ts({pmRoot:r,subject:n,settings:o,typeRegistry:i,currentItem:w,nextItem:v,author:E,rewrittenEntries:R}),report:({verification:q,warnings:ae})=>({id:n.id,dry_run:_,changed:y,patterns:{literal_count:a.filter(B=>B.kind==="literal").length,regex_count:a.filter(B=>B.kind==="regex").length,total_count:a.length,replacement_is_default:l},history:{path:n.historyPath,entries_scanned:c.length,entries_changed:m.entriesChanged,replacements:m.replacements,hash_mismatches_before:u.hashMismatchesBefore,hash_mismatches_after:u.hashMismatchesAfter,preexisting_hash_mismatches:f,audit_entry_added:lt,verify_ok:q.ok,verify_errors:q.errors},item:{existed_before:w.path!==null,exists_after:v.path!==null,path_before:w.path,path_after:v.path,changed:b},warnings:[...new Set([...g,...ae])].sort((B,W)=>B.localeCompare(W)),generated_at:S()})}}var tl={applyLiteralRule:Go,applyRegexRule:Bo,buildRedactionRules:Uo,hasItemMetadata:Wo,normalizeRegexFlags:No,normalizeStringArrayInput:Mt,parseRegexRule:$o,redactStringValue:Ft,redactUnknownValue:ye};var Tt={format:"pm-history-attestation",version:1,stream_hash:"exact_file_bytes",rollup_hash:"stable_json_without_workspace_digest",ordering:"stream_id_code_unit_ascending",consistency:"per_stream_snapshot_with_change_detection",trust:"independently_retained_bundle"};import{createHash as Ls}from"node:crypto";import{isUtf8 as js}from"node:buffer";import _e from"node:fs/promises";import Pt from"node:path";async function zo(e){try{return(await _e.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(Br(t))return[];throw t}}function qs(e,t,r,n){let o=t.at(-1),i;for(let d=t.length-1;d>=0;d-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(t[d].op)){i=t[d];break}let s=t[0]?.context?.history_compaction,a=typeof s=="object"&&s!==null&&"pruned_stream_digest"in s&&typeof s.pruned_stream_digest=="string"?s.pruned_stream_digest:null;return{id:e,entries:t.length,bytes:r,stream_digest:n,latest_after_hash:o?.after_hash??null,latest_record_hash:o?.record_hash??null,latest_hash_algorithm:o?I(o.hash_algorithm):null,rewrite_count:t.reduce((d,l)=>d+(l.reanchor_evidence?.length??0),0),checkpoint_digest:a,last_maintenance:i?{op:i.op,ts:i.ts,record_hash:i.record_hash??null}:null}}function Ds(e,t,r){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!js(t))return null;let n=[];for(let o of t.toString("utf8").split(/\r?\n/u)){if(!o.trim())continue;let i=JSON.parse(o);if(typeof i!="object"||i===null||Array.isArray(i))return null;let s=i;if(![s.op,s.author,s.ts,s.before_hash,s.after_hash].every(a=>typeof a=="string")||!Array.isArray(s.patch))return null;n.push(s)}return gt(n).ok?qs(e,n,t.length,r):null}catch{return null}}async function Ht(e,t){if(!(await _e.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let r=Pt.join(e,"history"),n=await zo(r),o=new Map,i=[];for(let s of n){let a=s.slice(0,-6),d={id:a,digest:null,stream:null};i.push(d);let l=Pt.join(r,s);try{let c=await _e.lstat(l);if(o.set(s,F([c.ino,c.size,c.mtimeMs,c.ctimeMs])),!c.isFile())continue;let u=await _e.readFile(l);d.digest=Ls(t).update(u).digest("hex"),d.stream=Ds(a,u,d.digest)}catch{}}if(F(n)!==F(await zo(r)))throw new TypeError("attestation history inventory changed during read; retry");for(let[s,a]of o){let d=await _e.lstat(Pt.join(r,s));if(a!==F([d.ino,d.size,d.mtimeMs,d.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}return i}function Ot(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Lt(e,t){return Object.keys(e).length===t.length&&t.every(r=>Object.hasOwn(e,r))}function ne(e,t){return typeof e=="string"&&(t==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(e)}function Ns(e){return e.entries===0?[e.latest_hash_algorithm,e.latest_after_hash,e.latest_record_hash,e.checkpoint_digest,e.last_maintenance].every(t=>t===null)&&e.rewrite_count===0:e.latest_hash_algorithm!=="sha256"&&e.latest_hash_algorithm!=="sha512"?!1:ne(e.latest_after_hash,e.latest_hash_algorithm)&&(e.latest_record_hash===null||ne(e.latest_record_hash,e.latest_hash_algorithm))}function $s(e){return e===null?!0:!Ot(e)||!Lt(e,["op","ts","record_hash"])?!1:typeof e.op=="string"&&["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(e.op)&&typeof e.ts=="string"&&Ie(e.ts)&&(e.record_hash===null||ne(e.record_hash,"sha256")||ne(e.record_hash,"sha512"))}function Us(e,t){return!Ot(e)||!Lt(e,["id","entries","bytes","stream_digest","latest_after_hash","latest_record_hash","latest_hash_algorithm","rewrite_count","checkpoint_digest","last_maintenance"])?!1:typeof e.id=="string"&&/^[A-Za-z0-9_-]+$/u.test(e.id)&&[e.entries,e.bytes,e.rewrite_count].every(r=>typeof r=="number"&&Number.isSafeInteger(r)&&r>=0)&&ne(e.stream_digest,t)&&Ns(e)&&(e.checkpoint_digest===null||ne(e.checkpoint_digest,"sha256"))&&$s(e.last_maintenance)}function Vo(e){if(!Ot(e)||!Lt(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==Tt.format||e.version!==1||typeof e.generated_at!="string"||!Ie(e.generated_at)||!Array.isArray(e.streams)||e.hash_algorithm!=="sha256"&&e.hash_algorithm!=="sha512")throw new TypeError("Invalid history attestation format");let t=e.hash_algorithm,r;for(let i of e.streams){if(!Us(i,t))throw new TypeError("Invalid history attestation stream");let s=i.id;if(r!==void 0&&s<=r)throw new TypeError("Invalid history attestation stream order");r=s}let{workspace_digest:n,...o}=e;if(ft(F(o),t)!==n)throw new TypeError("History attestation rollup mismatch");return e}async function Ko(e={}){let t=I(e.hashAlgorithm),r=e.generatedAt??S();if(!Ie(r))throw new TypeError("Invalid history attestation timestamp");let n=await Ht(k(e.cwd??process.cwd(),e.pmRoot),t),o=n.filter(s=>s.stream===null);if(o.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${o.map(s=>s.id).join(", ")}`);let i={format:Tt.format,version:1,hash_algorithm:t,generated_at:r,streams:n.map(s=>s.stream)};return Vo({...i,workspace_digest:ft(F(i),t)})}async function Qo(e,t={}){let r=Vo(e),n=await Ht(k(t.cwd??process.cwd(),t.pmRoot),r.hash_algorithm),o=new Map(n.map(c=>[c.id,c])),i=new Map(r.streams.map(c=>[c.id,c])),s=r.streams.filter(c=>!o.has(c.id)).map(c=>c.id),a=n.filter(c=>!i.has(c.id)).map(c=>c.id),d=n.filter(c=>c.stream===null).map(c=>c.id),l=[];for(let c of r.streams){let u=o.get(c.id);u&&(u.digest!==c.stream_digest||F(u.stream)!==F(c))&&l.push({id:c.id,before_digest:c.stream_digest,after_digest:u.digest,last_maintenance:u.stream?.last_maintenance??null})}return{ok:s.length+a.length+d.length+l.length===0,workspace_digest:r.workspace_digest,streams_checked:n.length,changed_streams:l.map(c=>c.id),missing_streams:s,added_streams:a,invalid_streams:d,transitions:l}}import Yo from"node:fs/promises";async function Il(e,t){for(let n of["verify","output","hashAlgorithm"]){let o=e[n];if(!(n==="verify"&&typeof o=="object"&&o!==null)&&o!==void 0&&(typeof o!="string"||o.trim().length===0))throw new p(`history attest ${n} requires a nonempty string.`,h.USAGE)}if(e.verify!==void 0){if(e.output!==void 0||e.hashAlgorithm!==void 0)throw new p("history attest --verify cannot be combined with --output or --hash-algorithm",h.USAGE);let n;try{n=typeof e.verify=="string"?JSON.parse(await Yo.readFile(e.verify,"utf8")):e.verify}catch{throw new p("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",h.USAGE)}return Qo(n,{pmRoot:t.path})}let r=await Ko({pmRoot:t.path,hashAlgorithm:I(e.hashAlgorithm)});if(e.output===void 0)return r;try{await Yo.writeFile(e.output,`${JSON.stringify(r,null,2)}
2
+ `,{flag:"wx",mode:384})}catch{throw new p("Cannot create history attestation proof. Choose --output with a new filename in a writable directory; existing files are never overwritten.",h.USAGE)}return{output:e.output,workspace_digest:r.workspace_digest,streams:r.streams.length}}import Gs from"fast-json-patch";import jt from"node:fs/promises";function qt(e){return{schema:e.schema,extensionFieldNames:$(x())}}async function Xo(e,t,r){let n=await Vn(e,qt(t));return n.error===null?{raw:n.raw,document:n.document}:{raw:n.raw,document:Jo(r),recovered:!0}}function Bs(e,t){return Un(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function Jo(e){let t=vt(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:Me(T(t))}async function Ws(e,t,r,n){let o=await K(e,t,r,n),i=o.located?await Te({pmRoot:e,settings:r,itemId:o.id,commandLabel:"restore"}):{warnings:[]};return{...o,historyPolicyWarnings:i.warnings}}function zs(e,t){let r=fe(e),n=fe(t),o=Gs.compare(r,n),i=new Set;for(let s of o){if(s.path==="/body"||s.path.startsWith("/body/")){i.add("body");continue}let a=s.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];i.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(i).sort((s,a)=>s.localeCompare(a))}async function Vs(e){let t=await Co({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:r=>Xo(r,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function Ks(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:Jo(t),originalRaw:null}}function Qs(e){let t=e.document.metadata.assignee?.trim(),r=t&&t!==e.author&&!e.force,n=Vr(t);if(!r)return[];if(e.enforcement==="strict")throw new p(`Item ${e.resolvedId} is assigned to ${n}. Use --force to override.`,h.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${n}`]:[]}function Ys(e){return Object.keys(e).length===0?void 0:e}async function Xs(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await L(e.existingItemPath,e.resolvedOriginalRaw),await jt.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await L(e.existingItemPath,e.resolvedOriginalRaw);return}await jt.rm(e.restoredItemPath,{force:!0})}async function Js(e){return[...await te({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await te({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function Kl(e,t,r,n){let o=k(process.cwd(),n.path);await O(o);let i=await P(o),s=D(i,x()),a=await Ws(o,e,i,s.type_to_folder),d=a.id,{raw:l,entries:c}=await tn(a.historyPath,d);if(c.length===0)throw new p(`No history exists for ${d}; restore is unavailable.`,h.NOT_FOUND);let u=Bs(t,c),m=Gn(vt(c,u.historyIndex),u),f=nn(m,qt(i));if(f.metadata.id!==d)throw new p(`Restore target resolved to item ${f.metadata.id}, expected ${d}.`,h.GENERIC_FAILURE);let y=(a.located?await Xo(a.located,i,c):null)?.raw??null,g=Fe(r.author,i.author_default),w=await en(o,d,i.locks.ttl_seconds,g,!!r.force,i.governance.force_required_for_stale_lock,i.locks.wait_ms,{waitPolicy:"progress"}),v=w.release;try{let{loadedItemUnderLock:b,existingItemPath:E}=await Vs({pmRoot:o,subject:a,settings:i,typeRegistry:s,historyRawBeforeLock:l,currentItemRawBeforeLock:y,history:c}),X="toon",R=Ks(b,c);b?.recovered===!0&&Rn(o,d,b.raw),kn(o,b?.document??Gr,d),f.metadata.pm_format_version=Xr(Math.max(Ae(f.metadata),Ae(R.document.metadata))),Wn(Wr(o),Ae(f.metadata));let lt=Qs({document:R.document,author:g,force:r.force,enforcement:i.governance.ownership_enforcement,resolvedId:d}),q=zs(R.document,f),ae=await Bn({pmRoot:o,settings:i,operation:"restore",author:g,before:R.document,after:f});await Mn({pm_root:o,operation:"restore",before:R.document,after:f,changed_fields:q,author:g,sdk:Qn({pmRoot:o,settings:i,typeToFolder:s.type_to_folder})});let B=Ce(f,{format:X,...qt(i)}),W=z(o,f.metadata.type,d,X,s.type_to_folder),ns=await w.fence(async()=>{let is=await Le(o,g),$r;try{await L(W,B),E&&W!==E&&await jt.rm(E);let ss=V({nowIso:S(),author:g,op:"restore",before:R.document,after:f,message:r.message,context:Ys({...ae.decisions.length===0?{}:{workflow_policies:ae.decisions},...An(o,[d,R.document.metadata.id,f.metadata.id],"restore")})});try{await xn(a.historyPath,ss)}catch(as){throw await Xs({existingItemPath:E,resolvedOriginalRaw:R.originalRaw,restoredItemPath:W}),as}$r=await je({pmRoot:o,preferredFormat:i.item_format,typeToFolder:s.type_to_folder,schema:i.schema,itemPath:W,previousItemPath:E??void 0,document:f})}finally{await is()}return $r});In(o,f,d);let os=await Js({restoredItemPath:W,historyPath:a.historyPath,before:R.document,after:f});Cn({id:f.metadata.id,op:"restore",item_type:f.metadata.type,previous_status:R.document.metadata.status,status:f.metadata.status,previous:_t(R.document.metadata,q),current:_t(f.metadata,q),changed_fields:q});let Dr=c[u.historyIndex],Nr=H(c,!0);return{item:f.metadata,restored_from:{kind:u.kind,target:u.raw,history_index:u.historyIndex+1,version:Nr===null?null:Nr+u.historyIndex+1,entry_ts:Dr.ts,entry_op:Dr.op},changed_fields:q,warnings:[...ae.warnings,...b?.recovered?["restore_unreadable_item_recovered"]:[],...a.historyPolicyWarnings,...lt,...ns,...os]}}finally{await v()}}var Zs=["status","type","tag","priority","deadlineBefore","deadlineAfter","updatedAfter","updatedBefore","createdAfter","createdBefore","ids","assignee","assigneeFilter","parent","sprint","release"],ea=["filterAcMissing","filterEstimatesMissing","filterResolutionMissing","filterMetadataMissing","filterReviewerMissing","filterRiskMissing","filterConfidenceMissing","filterSprintMissing","filterReleaseMissing","hasNotes","hasLearnings","hasFiles","hasDocs","hasTests","hasComments","hasDeps","hasBody","hasLinkedCommand","noNotes","noLearnings","noFiles","noDocs","noTests","noComments","noDeps","emptyBody","noLinkedCommand"];function ta(e){return e!=null&&(typeof e!="string"||e.split(",").some(t=>t.trim().length>0))}function Yl(e,t,r={}){let n=r.includePagination!==!1;return[t,...Zs.map(i=>e?.[i]),...n?[e?.limit,e?.offset]:[]].some(ta)||ea.some(i=>e?.[i]===!0)}function Zo(e){return{type:e.type,tag:e.tag,priority:e.priority,deadlineBefore:e.deadlineBefore,deadlineAfter:e.deadlineAfter,assignee:e.assignee,assigneeFilter:e.assigneeFilter,parent:e.parent,sprint:e.sprint,release:e.release}}var ei=["parent","type","priority","status","assignee","tags","sprint","release"];function ri(e,t){let r=He(e,t,{strict:!0,flagLabel:"--status"});if(!(!r||r.length===0))return r}function ni(e,t=["estimate","estimated_minutes","priority"]){let r=e.sum?.trim(),n=e.avg?.trim(),o=r&&r.length>0?r:void 0,i=n&&n.length>0?n:void 0;if(!o&&!i)return null;if(o&&i&&o!==i)throw new p("Aggregate --sum and --avg must target the same numeric field",h.USAGE);let s=o??i;if(!t.includes(s))throw new p(`Aggregate numeric field "${s}" is not registered. Allowed: ${t.join(", ")}`,h.USAGE);return{field:s,sum:o!==void 0,avg:i!==void 0}}function oi(e){let t=e?.trim()??"status";if(t.length===0)throw new p("--group-by requires at least one field name",h.USAGE);let r=io(t);if(r.length===0)throw new p("--group-by requires a comma-separated list of fields",h.USAGE);for(let n of r)if(!ei.includes(n))throw new p(`Aggregate group fields must be one of ${ei.join("|")}; received "${n}"`,h.USAGE);return r}function ii(e){let t=[...new Set(e.map(r=>r.trim().toLowerCase()).filter(r=>r.length>0))].sort((r,n)=>r.localeCompare(n));return t.length===0?null:t.join(",")}function si(e,t){switch(e){case"parent":return t.parent??null;case"type":return t.type;case"priority":return t.priority;case"status":return t.status;case"assignee":return t.assignee??null;case"tags":return ii(t.tags);case"sprint":return t.sprint??null;case"release":return t.release??null;default:return null}}function ai(e,t){let r=e??null,n=t??null;return r===n?0:r===null?1:n===null?-1:typeof r=="number"&&typeof n=="number"?r-n:String(r).localeCompare(String(n))}function Ke(e,t){return e.map(r=>`${r}:${JSON.stringify(t[r]??null)}`).join("|")}var ra={parent:"(unparented)",type:"(untyped)",priority:"(no priority)",status:"(no status)",assignee:"(unassigned)",tags:"(untagged)",sprint:"(no sprint)",release:"(no release)"};function ti(e,t){return t==null||t===""?ra[e]:String(t)}function na(e,t){return e.length===1?ti(e[0],t[e[0]]):e.map(r=>`${r}=${ti(r,t[r])}`).join(" | ")}function ci(e,t,r){for(let n of r){let o=ai(e.group[n],t.group[n]);if(o!==0)return o}return 0}function di(e,t){let n=e[t];if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){let o=n.trim();if(o.length===0)return null;let i=Number(o);if(Number.isFinite(i))return i}return null}function li(e,t){return t<=0?0:Math.round(e/t*1e4)/100}function Dt(e,t,r){let n=Jr(String(t),r)??t;if(n===r.open_status){e.open_count+=1;return}if(n==="in_progress"||r.active_statuses.has(n)&&n!==r.open_status){e.in_progress_count+=1;return}if(r.terminal_done_statuses.has(n)||n===r.close_status){e.closed_count+=1;return}e.other_count+=1}function oa(e,t){return{row:{group:e,count:1},numeric_count:t===null?0:1,numeric_sum:t??0,null_count:t===null?1:0,open_count:0,in_progress_count:0,closed_count:0,other_count:0}}function ia(e,t){if(t===null){e.null_count+=1;return}e.numeric_count+=1,e.numeric_sum+=t}function sa(e){e.accumulator.row.count+=1,e.includeCompletion&&Dt(e.accumulator,e.item.status,e.statusRegistry),e.numericAggregation!==null&&ia(e.accumulator,e.numericValue)}function aa(e,t,r,n){for(let o of t){let i=Ke(r,o),s=e.get(i);if(s){sa({...n,accumulator:s});continue}let a=oa(o,n.numericValue);n.includeCompletion&&Dt(a,n.item.status,n.statusRegistry),e.set(i,a)}}function ca(e,t){let r={};for(let n of e)r[n]=si(n,t);return r}function da(e,t,r){let n=[ca(e,t)];if(r==="tuple")return n;for(let o of e){let i=t[o];if(!Array.isArray(i))continue;let s=[...new Set(i.map(a=>a.trim().toLowerCase()).filter(Boolean))].sort();s.length!==0&&(n=n.flatMap(a=>s.map(d=>({...a,[o]:d}))))}return n}function la(e,t,r,n){let o={...e.row,group_label:na(t,e.row.group)};return r&&(o.open=e.open_count,o.in_progress=e.in_progress_count,o.closed=e.closed_count,o.other=e.other_count,o.completion_pct=li(e.closed_count,e.row.count)),n!==null&&(o.null_count=e.null_count,n.sum&&(o.sum=e.numeric_sum),n.avg&&(o.avg=e.numeric_count===0?null:e.numeric_sum/e.numeric_count)),o}function ua(e){return{group_by:e.groupBy,set_mode:e.setMode,count:!0,completion:e.includeCompletion,include_unparented:e.includeUnparented,status:e.status?.[0]??null,status_values:e.status,type:e.options.type??null,tag:e.options.tag??null,priority:e.options.priority??null,deadline_before:e.options.deadlineBefore??null,deadline_after:e.options.deadlineAfter??null,assignee:e.options.assignee??null,assignee_filter:e.options.assigneeFilter??null,parent:e.options.parent??null,sprint:e.options.sprint??null,release:e.options.release??null,...e.numericAggregation!==null?{sum:e.options.sum??null,avg:e.options.avg??null,numeric_field:e.numericAggregation.field}:{}}}async function ru(e,t){if(e.count===!1)throw new p("Aggregate grouped counts are always enabled; omit count=false.",h.USAGE);let r=k(process.cwd(),t.path),n=await P(r),o=N(n.schema),i=["estimate","estimated_minutes","priority",...Z(n.schema).definitions.filter(b=>b.type==="number").map(b=>b.metadata_key)],s=oi(e.groupBy),a=e.setMode??"element";if(a!=="element"&&a!=="tuple")throw new p("Aggregate --set-mode must be element or tuple",h.USAGE);let d=ri(e.status,o),l=ni(e,[...new Set(i)].sort((b,E)=>b.localeCompare(E))),c=e.completion===!0,u=e.includeUnparented===!0,m=await ze(void 0,{...Zo(e),status:e.status,noTruncate:!0,strictRead:!0},t),f=new Map,_=0,y=0,g=0;for(let b of m.items){let E=b;if(s.includes("parent")&&E.parent===void 0&&!u){_+=1;continue}let X=l===null?null:di(E,l.field),R=da(s,E,a);aa(f,R,s,{item:E,statusRegistry:o,includeCompletion:c,numericAggregation:l,numericValue:X}),g+=R.length,y+=1}let w=[...f.values()].map(b=>la(b,s,c,l)).sort((b,E)=>ci(b,E,s)),v=m.warnings&&m.warnings.length>0?m.warnings:void 0;return{...ma(w,s,e),count:w.length,totals:{items_considered:m.items.length,items_grouped:y,items_skipped_unparented:_,group_memberships:g},filters:ua({groupBy:s,setMode:a,includeCompletion:c,includeUnparented:u,status:d,options:e,numericAggregation:l}),now:S(),...v?{warnings:v}:{}}}function ma(e,t,r){let n=Io(r.limit,"limit")??50,o=r.after===void 0?-1:e.findIndex(a=>Ke(t,a.group)===r.after);if(r.after!==void 0&&o<0)throw new p("Aggregate --after cursor is absent from the current grouping; restart without --after.",h.USAGE);let i=e.slice(o+1,o+1+n),s=o+1+i.length<e.length;return{groups:i,returned_count:i.length,truncated:s,next_after:s?Ke(t,i.at(-1).group):null}}var nu={buildGroupKey:Ke,compareAggregateRows:ci,compareNullableGroupValue:ai,completionPct:li,normalizeTagGroupValue:ii,parseGroupBy:oi,parseNumericAggregation:ni,parseStatus:ri,readNumericAggregateValue:di,resolveGroupValue:si,updateCompletionCounts:Dt};var ui=1e6,mi=20;function fi(e,t,r,n=mi){if(!Number.isSafeInteger(n)||n<0)throw new p("Child projection sample limit must be a non-negative integer.",h.USAGE);let o=e.trim().toLowerCase(),i={},s=[],a=0;for(let g of t){if(a+=1,a>ui)throw new p(`Child projection exceeded the ${ui.toLocaleString("en-US")} item safety bound.`,h.GENERIC_FAILURE,{code:"child_projection_item_bound_exceeded",required:"Use an indexed or parent-filtered metadata source.",why:"Unbounded graph scans can exhaust memory in universal project stores.",nextSteps:["Build the derived item index, then retry the parent read."]});s.push(g)}let d=new Map(s.map(g=>[g.id.trim().toLowerCase(),g])),l=So(bo(s,Eo())),c=new Set(l.children_by_parent.get(o)??[]);for(let g of s)g.parent?.trim().toLowerCase()===o&&c.add(g.id.trim().toLowerCase());let u=[...c].map(g=>d.get(g)),m=0;for(let g of u){let w=g.status.trim().toLowerCase();i[w]=(i[w]??0)+1,de(w,r)||(m+=1)}u.sort((g,w)=>g.id.localeCompare(w.id));let f=u.slice(0,n).map(g=>({id:g.id,title:g.title,type:g.type,status:g.status,priority:g.priority})),_=u.length>f.length,y=n===0?mi:n;return{count:u.length,active:m,by_status:Object.fromEntries(Object.entries(i).sort(([g],[w])=>g.localeCompare(w))),sample:f,sample_limit:n,truncated:_,next_offset:_?f.length:null,continuation:_?`pm list --status all --parent ${e} --offset ${f.length} --limit ${y}`:null,scanned:a}}var fa=new Set(["event","meeting","reminder"]);function ha(e){return fa.has(e.type.trim().toLowerCase())||e.deadline!==void 0||(e.reminders?.length??0)>0||(e.events?.length??0)>0}function Qe(e){if(!ha(e))return;let t=[...e.events??[]].sort((n,o)=>n.start_at.localeCompare(o.start_at)),r=t[0];return{deadline:e.deadline??null,start_at:r?.start_at??null,end_at:r?.end_at??null,location:r?.location??null,reminders:[...e.reminders??[]],events:t}}var ga=new Set(["epic","feature","milestone","plan"]),ya=new Set(Object.keys(Ur).map(e=>e.toLowerCase()));function Ut(e){return Object.fromEntries(["comments","notes","learnings","files","tests","docs","reminders","events"].map(r=>[r,e[r]?.length??0]))}function _a(e,t,r,n,o){let i=Ut(e);return[...t.length>0?["body"]:[],...Object.entries(i).flatMap(([s,a])=>a>0?[s]:[]),...i.files+i.tests+i.docs>0?["linked"]:[],...r===void 0?["children"]:r.count>0?["children"]:[],...typeof e.assignee=="string"&&e.assignee.trim().length>0?["claim_state"]:[],...Qe(e)?["schedule"]:[],...n&&bt(e).length>0?["blockers"]:[],...!o.full&&e.dependencies?.some(({id:s,kind:a,...d})=>Object.values(d).some(l=>l!==void 0))?["dependency_provenance"]:[]]}function pi(e){let t=e.trim().toLowerCase();return t.length>0&&(ga.has(t)||!ya.has(t))}function hi(e){return{ts:e.ts,author:e.author,message:e.message??null}}function wa(e,t){let r=e?.trim(),n=r&&r.length>0?r:null,o=[...t].reverse().find(s=>s.op==="claim"),i=[...t].reverse().find(s=>s.op==="release");return{claimed:n!==null,assignee:n,last_claim:o?hi(o):null,last_release:i?hi(i):null}}function va(e){if(e===void 0||e.trim().length===0)return"standard";let t=e.trim().toLowerCase();if(t==="full")return"deep";if(St.includes(t))return t;throw new p("Get --depth must be one of brief|standard|deep|full",h.USAGE,{field:"depth",value:e,recovery:{allowed_values:[...xt]}})}function Ea(e,t,r){let n=Ut(e),o={...e};if(!r&&e.dependencies!==void 0&&(o.dependencies=e.dependencies.map(({id:_,kind:y})=>({id:_,kind:y}))),t==="deep")return{...o,comments:e.comments??[],notes:e.notes??[],learnings:e.learnings??[],files:e.files??[],tests:e.tests??[],docs:e.docs??[],reminders:e.reminders??[],events:e.events??[],notes_count:n.notes,tests_count:n.tests,collection_counts:n};let{comments:i,notes:s,learnings:a,files:d,tests:l,docs:c,reminders:u,events:m,...f}=o;return{...f,notes_count:e.notes?.length??0,tests_count:e.tests?.length??0,collection_counts:n}}function ba(e){if(e===void 0)return null;let t=e.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0)throw new p("Get --fields requires a comma-separated list of field names",h.USAGE);return t}function ie(e){return e.startsWith("item.")?e.slice(5):e}function Sa(e,t,r){if(e===null)return;let n=Rt(t),o=new Set(n),i=e.filter(s=>{let a=ie(s);return!o.has(s)&&!o.has(a)});if(i.length>0){let s=["get",r,"--fields",e.filter(a=>!i.includes(a)).join(",")||"id,title,status"];throw new p(`Unknown get --fields value(s): ${i.join(", ")}`,h.USAGE,{code:"unknown_field_projection",examples:["pm get <id> --fields id,title,status,type,updated_at","pm get <id> --fields id,title,claim_state","pm get <id> --fields id,title,body,linked.files"],recovery:{allowed_values:n,suggested_retry:J(s),suggested_retry_args:s}})}}var xa=new Set(["comments","notes","learnings","files","tests","test_runs","docs","reminders","events","dependencies","plan_steps","plan_decisions","plan_discoveries","plan_validation"]);function Ra(e,t,r){return Object.hasOwn(t,r)?t[r]:e[r]!==void 0?e[r]:xa.has(r)?[]:void 0}function ka(e,t){if(e==="item.item_hash")return!1;let r=t.indexOf(".");return r===-1?gn.has(t):yn.has(t.slice(0,r))}function Ia(e,t){let r=e,n={notes_count:e.notes?.length??0,tests_count:e.tests?.length??0,collection_counts:Ut(e)},o={id:e.id};for(let i of t){let s=ie(i);ka(i,s)||(o[s]=Ra(r,n,s))}return o}function Ye(e,t){return e?.some(r=>r===t||r===`item.${t}`)??!1}function oe(e,t){return e.some(r=>{let n=ie(r);return n===t||n.startsWith(`${t}.`)})}function Aa(e,t){if(e.full&&(e.fields!==void 0||e.depth!==void 0))throw new p("Get projection options are mutually exclusive; remove the extra projection flag and retry.",h.USAGE,{code:"projection_options_mutually_exclusive",flag:"--full",recovery:{suggested_retry:J(["get",t,"--full"]),suggested_retry_args:["get",t,"--full"]}});if(e.tree!==!0&&e.treeDepth!==void 0)throw new p("Get --tree-depth requires --tree",h.USAGE);if(e.at!==void 0&&e.tree===!0)throw new p("Get --at cannot be combined with --tree because workspace-level historical projections are not yet indexed.",h.USAGE);return{depth:e.full?"deep":va(e.depth),full:e.full===!0||e.depth?.trim().toLowerCase()==="full",treeDepth:e.tree===!0?ho(e.treeDepth,"--tree-depth"):void 0,fields:ba(e.fields),fieldProjection:e.fields!==void 0}}async function Ca(e,t,r){let n=k(process.cwd(),t.path);await O(n);let o=await P(n),i=D(o,x());if(r!==void 0){let d=await lo(e,r,{pmRoot:t.path});return{pmRoot:n,settings:o,typeToFolder:i.type_to_folder,locatedId:d.document.metadata.id,metadata:d.document.metadata,body:d.document.body,historical:d}}let s=await qe(n,e,o.id_prefix,o.item_format,i.type_to_folder);if(!s)throw await Yn(n,e,o.id_prefix,i.type_to_folder);let a=await De(s,{schema:o.schema});return{pmRoot:n,settings:o,typeToFolder:i.type_to_folder,locatedId:s.id,metadata:a.document.metadata,body:a.document.body}}function Ma(e,t,r,n){let o=[...Z(t.schema).definitions.map(i=>i.metadata_key),...$(x())];if(Sa(e,o,n),r&&oe(e??[],"children"))throw new p("Get --at cannot project children because workspace-level historical relationships are not yet indexed.",h.USAGE);if(r&&oe(e??[],"blockers"))throw new p("Get --at cannot project current blocker statuses; read the current item with --fields blockers instead.",h.USAGE)}function Nt(e){let{fieldProjection:t,depth:r,fields:n,field:o}=e;return t?o==="body"||o==="linked"?Ye(n,o):oe(n,o):r!=="brief"}async function Fa(e,t){if(!t)return;let r=xe(e.pmRoot,e.locatedId),n=await le(r,e.locatedId);return wa(e.metadata.assignee,e.historical?n.slice(0,e.historical.target.historyIndex+1):n)}function Ta(e,t,r){t.historical===void 0&&(r.fieldProjection&&!r.fields.includes("item_hash")||(e.item_hash=Sn({metadata:t.metadata,body:t.body})))}var gi=["files","tests","docs"],Pa=["claimed","assignee","last_claim","last_release"];function Ha(e,t,r,n){let o=gi.filter(i=>n||Ye(r,`linked.${i}`));o.length!==0&&(e.linked=Object.fromEntries(o.map(i=>[i,t.metadata[i]??[]])))}function Oa(e,t){return t===null||Ye(t,"claim_state")?e:Object.fromEntries(Pa.filter(r=>t.some(n=>ie(n)===`claim_state.${r}`)).map(r=>[r,e[r]]))}var La={linked:new Set(gi),schedule:new Set(["deadline","reminders","events"]),claim_state:new Set(["assignee"])};function $t(e,t,r){let n=e.map(ie);if(n.includes(t))return[];let o=`${t}.`;if(!n.some(s=>s.startsWith(o)))return[];let i=La[t];return Object.entries(r).flatMap(([s,a])=>!n.includes(`${o}${s}`)&&!(i.has(s)&&n.includes(s))&&ja(a)?[`${o}${s}`]:[])}function ja(e){return e!=null&&e!==!1&&!(Array.isArray(e)&&e.length===0)}function qa(e,t,r){return[...$t(t,"linked",{files:e.metadata.files,tests:e.metadata.tests,docs:e.metadata.docs}),...r?$t(t,"claim_state",r):[],...$t(t,"schedule",Qe(e.metadata)??{})]}async function Da(e,t){if(!t)return;let r=N(e.settings.schema),n=await Ne(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema);return fi(e.locatedId,n,r)}async function Na(e,t,r){if(t.historical!==void 0||!(r.fieldProjection?oe(r.fields,"blockers"):r.depth!=="brief")||bt(t.metadata).length===0)return;let n=await so({pmRoot:t.pmRoot,settings:t.settings,typeToFolder:t.typeToFolder,metadata:t.metadata});e.blockers={scope:"declared",open:n.filter(o=>!o.resolved).map(({resolved:o,...i})=>i),closed_count:n.filter(o=>o.resolved).length},!r.fieldProjection&&!r.full&&delete e.item.blocked_by}function $a(e,t,r,n){if(!n)return;let o=Qe(t.metadata);if(o){if(r===null||Ye(r,"schedule")){e.schedule=o;return}e.schedule=Object.fromEntries(Object.entries(o).filter(([i])=>r.some(s=>ie(s)===`schedule.${i}`)))}}async function Ua(e,t,r,n){if(t.tree!==!0)return;let o=await ze(void 0,{parent:e.locatedId,tree:!0,treeDepth:r===void 0?void 0:String(r),full:!0},n);return{root_id:e.locatedId,root_title:e.metadata.title,depth_limit:r??null,count:o.count,items:o.items.map(i=>i)}}async function Cu(e,t,r={}){let n=Aa(r,e),o=await Ca(e,t,r.at);Ma(n.fields,o.settings,o.historical!==void 0,o.locatedId);let i=Nt({...n,field:"body"}),s=Nt({...n,field:"linked"}),a=Nt({...n,field:"claim_state"}),d=o.historical===void 0&&(n.fieldProjection?oe(n.fields,"children"):n.depth==="deep"&&(n.full||pi(o.metadata.type))),l=n.fieldProjection?oe(n.fields,"schedule"):n.depth!=="brief",c=await Fa(o,a),u={item:n.fieldProjection?Ia(o.metadata,n.fields):Ea(o.metadata,n.depth,n.full)};i&&(u.item.body=o.body),Ta(u,o,n),Ha(u,o,n.fields,s),c&&(u.claim_state=Oa(c,n.fields)),$a(u,o,n.fields,l),await Na(u,o,n);let m=await Da(o,d);m!==void 0&&(u.children=m);let f=await Ua(o,r,n.treeDepth,t);if(f!==void 0&&(u.tree=f),o.historical&&(u.reconstructed=!0,u.as_of_version=o.historical.as_of_version,u.as_of_timestamp=o.historical.as_of_timestamp),o.historical===void 0)try{await pn({pmRoot:o.pmRoot,author:Fe(void 0,o.settings.author_default),itemIds:[o.locatedId],intent:"get"})}catch{}return dn(u,n.fieldProjection?qa(o,n.fields,c):_a(o.metadata,o.body,m,o.historical===void 0,n)),u}var Mu={shouldAutoIncludeGetChildren:pi};function Ga(e,t){return t===void 0?e:e.slice(Math.max(0,e.length-t))}function Ba(e,t){return e.map(({entry:r,version:n})=>{let o=new Set,i=on(r.patch);for(let s of i)o.add(wt(s.path)),s.from&&o.add(wt(s.from));return{index:n,...t?{version:t.offset===null?null:t.offset+n}:{},ts:r.ts,op:r.op,author:r.author,patch_ops:i.length,changed_fields:[...o].sort((s,a)=>s.localeCompare(a))}})}function Wa(e){if(e[0]?.op!=="history_compact_baseline")return;let t=H(e,!0);return{offset:t,first_version:t===null?null:t+1,last_version:t===null?null:t+e.length}}async function za(e,t){let r=k(process.cwd(),t.path);await O(r);let n=await P(r),o=D(n,x()),i=e.trim()===Pe,s=i?Pe:qn(e,n.id_prefix),a=await qe(r,s,n.id_prefix,n.item_format,o.type_to_folder),d=a?.id??s,l=i?Ln(r):xe(r,d);if(!a&&!await Se(l))throw new p(`Item ${e} not found`,h.NOT_FOUND);return a&&await Te({pmRoot:r,settings:n,itemId:a.id,commandLabel:"history"}),{historyPath:l,located:a,resolvedId:d,settings:n}}function Va(e){let{resolvedId:t,selectedHistory:r,options:n,limit:o,addressing:i,vocabulary:s,total:a}=e,d=n.compact===!0,l=(n.order??(d||n.provenance===!0?"newest_first":"oldest_first"))==="newest_first",c=l?[...r].reverse():r,u=c.map(({entry:w})=>w),m=d?Ba(c,i):void 0,f=n.provenance===!0?c.map(({entry:w,durableVersion:v})=>Fo(w,s,{itemId:t,version:v})):void 0,_=n.provenance===!0?"provenance":d?"compact":"full",y={compact:{compact_history:m},provenance:{provenance_history:f},full:{history:u}}[_];return{id:t,...y,compact:d,projection:{mode:_,row_key:{compact:"compact_history",provenance:"provenance_history",full:"history"}[_]},omission_receipt:ln("history",_),count:u.length,total:a,order:l?"newest_first":"oldest_first",limit:o??null,version_addressing:i}}async function Nu(e,t,r){if(t.order!==void 0&&t.order!=="oldest_first"&&t.order!=="newest_first")throw new p("--order must be oldest_first or newest_first",h.USAGE);let n=Oe(t.limit),{historyPath:o,located:i,resolvedId:s,settings:a}=await za(e,r),d=await le(o,s),l=Wa(d),c=a.agent_identity.identity_vocabulary,u=Mo(a.agent_identity.harness_signals),m=To({harness:t.harness,agentInstance:t.agentInstance,provenance:t.provenanceFilter},c,u),f=Ka(d).filter(({entry:g})=>m(g)),_=Ga(f,n),y=Va({resolvedId:s,selectedHistory:_,options:t,limit:n,addressing:l,vocabulary:c,total:f.length});if(t.provenanceSummary===!0&&(y.provenance_summary=Po(f.map(({entry:g})=>g),c,u)),t.diff||t.field!==void 0){let g=new Set(_.map(({version:w})=>w));y.diff=On(d,{windowStartIndex:(_[0]?.version??d.length+1)-1,field:t.field}).filter(w=>g.has(w.index)),y.order==="newest_first"&&y.diff.reverse()}if(t.verify){let g=i?(await De(i,{schema:a.schema})).document:void 0;if(y.verification=co(d,g),s===Pe&&y.verification.ok){let w=await jn(k(process.cwd(),r.path));y.verification={...y.verification,ok:w.ok,errors:w.ok?y.verification.errors:[...y.verification.errors,"verify_failed:workspace_state_mismatch"],workspace_state_matches_latest:w.ok,workspace_state_mismatches:w.mismatched_documents,workspace_state_missing:w.missing_documents,workspace_state_unreadable:w.unreadable_documents}}}return y}function Ka(e){let t=H(e,!0);return e.map((r,n)=>({entry:r,version:n+1,durableVersion:t===null?void 0:t+n+1}))}function Qa(e){if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(t!=="keyword"&&t!=="semantic"&&t!=="hybrid")throw new p("Search mode must be one of keyword|semantic|hybrid",h.USAGE);return t}function Xe(e){return e===!0}function yi(e){return Kr(e,0,1)??void 0}function _i(e){if(e===void 0)return"or";let t=e.trim().toLowerCase();if(t!=="and"&&t!=="or"&&t!=="exact")throw new p("Search --match-mode must be one of and|or|exact",h.USAGE);return t}function wi(e){if(e==null||e==="")return;let t=typeof e=="number"?e:Number(String(e).trim());if(!Number.isFinite(t)||t<0)throw new p("Search --min-score must be a finite number >= 0",h.USAGE);return t}function Q(e,t){if(e==null)return;let r=String(e).trim();if(r.length!==0)return mt(r,new Date,t)}function A(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function Gt(e,t){if(e!==void 0)return mt(e,new Date,t)}function Ya(e){if(e===void 0)return;let t=e.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0)throw new p("Search --fields requires a comma-separated list of field names",h.USAGE);return[...new Set(t)]}function Je(e,t="<query>"){let r=e.compact===!0,n=e.full===!0,o=Ya(e.fields);if(Number(r)+Number(n)+ +(o!==void 0)>1)throw new p("Search projection options are mutually exclusive. Use one of --compact, --full, or --fields.",h.USAGE,{code:"projection_options_mutually_exclusive",recovery:{suggested_retry:J(["search",t,"--full"]),suggested_retry_args:["search",t,"--full"]}});return r?{mode:"compact",fields:[...uo]}:n?{mode:"full",fields:[]}:o?{mode:"fields",fields:o}:{mode:"full",fields:[]}}function Bt(e,t,r="<query>"){if(e.mode!=="fields")return;let n=mo([...t.definitions.flatMap(s=>[s.key,s.metadata_key]),...$(x())]),o=new Set(n),i=e.fields.filter(s=>{let a=s.trim();return!o.has(a)});if(i.length>0){let s=["search",r,"--fields",e.fields.filter(a=>!i.includes(a)).join(",")||"id,title,status,score"];throw new p(`Unknown search --fields value(s): ${i.join(", ")}`,h.USAGE,{code:"unknown_field_projection",examples:["pm search <query> --fields id,title,status,score","pm search <query> --fields id,title,item.description,matched_fields"],nextSteps:["Use item.<field> for explicit item metadata fields, or run pm search --help for projection examples."],recovery:{allowed_values:n,suggested_retry:J(s),suggested_retry_args:s}})}}function Ze(e){let t=A(e);if(!t)throw new p("Search query must not be empty",h.USAGE);return t.split(/\s+/u).filter(Boolean)}function Wt(e){let t=e.search?.max_results;return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):50}var Xa=["auto","keyword","semantic","hybrid"];function Ja(e){let t=e.search?.default_mode;if(typeof t!="string")return"auto";let r=t.trim().toLowerCase();return Xa.includes(r)?r:"auto"}function zt(e){if(typeof e.requested=="string"&&e.requested.trim().length>0)return{mode:Qa(e.requested),source:"explicit"};let t=Ja(e.settings);return t!=="auto"?{mode:t,source:"settings"}:{mode:e.semanticRunnable?"hybrid":"keyword",source:"auto"}}function Vt(e){let t=e.search?.score_threshold;return typeof t=="number"&&Number.isFinite(t)?t:0}function Kt(e){let t=e.search?.hybrid_semantic_weight;return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=1?t:.7}function Qt(e){let t={title_exact_bonus:10,title_weight:48,description_weight:5,tags_weight:6,status_weight:2,body_weight:1,comments_weight:1,notes_weight:1,learnings_weight:1,reminders_weight:2,events_weight:2,dependencies_weight:3,linked_content_weight:1},r=e.search?.tuning;if(!r)return t;let n=(o,i)=>typeof o=="number"&&Number.isFinite(o)&&o>=0?o:i;return{title_exact_bonus:n(r.title_exact_bonus,t.title_exact_bonus),title_weight:n(r.title_weight,t.title_weight),description_weight:n(r.description_weight,t.description_weight),tags_weight:n(r.tags_weight,t.tags_weight),status_weight:n(r.status_weight,t.status_weight),body_weight:n(r.body_weight,t.body_weight),comments_weight:n(r.comments_weight,t.comments_weight),notes_weight:n(r.notes_weight,t.notes_weight),learnings_weight:n(r.learnings_weight,t.learnings_weight),reminders_weight:n(r.reminders_weight,t.reminders_weight),events_weight:n(r.events_weight,t.events_weight),dependencies_weight:n(r.dependencies_weight,t.dependencies_weight),linked_content_weight:n(r.linked_content_weight,t.linked_content_weight)}}import Za from"node:path";function Yt(e){return mn("search",{pmRoot:e.pmRoot===void 0?void 0:Za.resolve(e.pmRoot),query:e.query.trim(),mode:e.mode,options:un(e.searchOptions,fo)})}function vi(e){let t=hn(e.sorted,{cursor:e.searchOptions.after,fingerprint:Yt(e),limit:e.limit,readId:r=>r.item.id});return{limited:t.rows,pageExtras:{applied_limit:e.limit,...t.has_more?{has_more:!0,truncated:!0}:{},...t.next_cursor?{next_cursor:t.next_cursor}:{}}}}function Ei(e){if(typeof e!="string")return!1;let t=e.split(",").map(r=>r.trim().toLowerCase()).filter(Boolean);return t.length===1&&t[0]==="all"}var ec=[{optionKey:"status",summaryKey:"status",normalize:e=>Ei(e)?"all":e},{optionKey:"type",summaryKey:"type"},{optionKey:"tag",summaryKey:"tag"},{optionKey:"priority",summaryKey:"priority"},{optionKey:"deadlineBefore",summaryKey:"deadline_before"},{optionKey:"deadlineAfter",summaryKey:"deadline_after"},{optionKey:"updatedAfter",summaryKey:"updated_after"},{optionKey:"updatedBefore",summaryKey:"updated_before"},{optionKey:"createdAfter",summaryKey:"created_after"},{optionKey:"createdBefore",summaryKey:"created_before"},{optionKey:"assignee",summaryKey:"assignee"},{optionKey:"sprint",summaryKey:"sprint"},{optionKey:"release",summaryKey:"release"},{optionKey:"parent",summaryKey:"parent"}];function Y(e){let{mode:t,matchMode:r,options:n,includeLinked:o,titleExact:i,phraseExact:s,scoreThreshold:a,hybridSemanticWeight:d,runtimeFieldFilters:l}=e,c={};return ko(c,n,ec),Object.assign(c,It(n)),Object.assign(c,kt(n)),r!==void 0&&r!=="or"&&(c.match_mode=r),o&&(c.include_linked=!0),i&&(c.title_exact=!0),s&&(c.phrase_exact=!0),a>0&&(c.score_threshold=a),t==="hybrid"&&n.semanticWeight!==void 0&&(c.hybrid_semantic_weight=d),n.limit!==void 0&&(c.limit=n.limit),l&&Object.keys(l).length>0&&(c.runtime_filters=l),c}function et(e){let{effectiveMode:t,matchMode:r,options:n,includeLinked:o,titleExact:i,phraseExact:s,scoreThreshold:a,hybridSemanticWeight:d,queryExpansion:l,rerank:c,runtimeFieldFilters:u}=e,m=f=>f??null;return{mode:t,match_mode:r,status:n.status===void 0||Ei(n.status)?"all":n.status,type:m(n.type),tag:m(n.tag),priority:m(n.priority),deadline_before:m(n.deadlineBefore),deadline_after:m(n.deadlineAfter),updated_after:m(n.updatedAfter),updated_before:m(n.updatedBefore),created_after:m(n.createdAfter),created_before:m(n.createdBefore),assignee:m(n.assignee),sprint:m(n.sprint),release:m(n.release),parent:m(n.parent),...It(n),...kt(n),include_linked:o,title_exact:i,phrase_exact:s,score_threshold:a,hybrid_semantic_weight:t==="hybrid"?d:null,query_expansion_enabled:l.enabled,query_expansion_provider:l.provider,rerank_enabled:c.enabled,rerank_model:c.model,rerank_top_k:c.top_k,limit:m(n.limit),runtime_filters:u}}var tc=1.2,rc=.75;function Xt(e){return ee(e)}function nc(e){let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);return t}function Si(e){let t=[],r=new Map,n=0;for(let i of e){let s=Xt(i.text),a=nc(s);n+=s.length;for(let d of a.keys())r.set(d,(r.get(d)??0)+1);t.push({id:i.id,termFrequencies:a,length:s.length})}let o=t.length;return{documents:t,documentFrequency:r,documentCount:o,averageDocumentLength:o>0?n/o:0}}function oc(e,t){return Math.log(1+(e-t+.5)/(t+.5))}function xi(e,t,r){let n=new Map;if(e.documentCount===0||e.averageDocumentLength===0)return n;let o=[...new Set(t.filter(s=>s.length>0))];if(o.length===0)return n;let i=new Map;for(let s of o){let a=e.documentFrequency.get(s);a!==void 0&&i.set(s,oc(e.documentCount,a))}if(i.size===0)return n;for(let s of e.documents){let a=0;for(let[d,l]of i){let c=s.termFrequencies.get(d);if(c===void 0)continue;let u=1-r.b+r.b*s.length/e.averageDocumentLength,m=c+r.k1*u;a+=l*(c*(r.k1+1)/m)}a>0&&n.set(s.id,a)}return n}function bi(e,t,r,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.min(n,Math.max(r,e))}function Ri(e){let t=r=>typeof r=="string"?[r]:typeof r=="number"?[String(r)]:Array.isArray(r)?r.flatMap(t):typeof r=="object"&&r!==null?Object.values(r).flatMap(t):[];return t(Object.values(e)).join(" ")}function ki(e){let t=e?.search?.bm25;return{k1:bi(t?.k1,tc,0,1e3),b:bi(t?.b,rc,0,1)}}var Jt=4,ic=20,sc=200,ac=new Set(["a","an","and","for","from","in","into","of","on","or","the","to","with"]);function Zt(e,t){let r=[],n=new Set;for(let o of e){let i=o.trim().replaceAll(/\s+/g," ");if(i.length===0)continue;let s=i.toLowerCase();if(!n.has(s)&&(n.add(s),r.push(i),r.length>=t))break}return r}function cc(e){let t=e.toLowerCase();return t.length>4&&t.endsWith("ies")?`${t.slice(0,-3)}y`:t.length>4&&(t.endsWith("ches")||t.endsWith("shes")||t.endsWith("xes")||t.endsWith("zes")||t.endsWith("sses"))?t.slice(0,-2):t.length>3&&t.endsWith("s")&&!t.endsWith("ss")&&!t.endsWith("us")&&!t.endsWith("is")&&!t.endsWith("as")?t.slice(0,-1):t}function dc(e){let t=e.toLowerCase();return t.length>2&&(!t.endsWith("s")||t.endsWith("ss"))?t.endsWith("y")&&!/[aeiou]y$/u.test(t)?`${t.slice(0,-1)}ies`:t.endsWith("ch")||t.endsWith("sh")||t.endsWith("x")||t.endsWith("z")||t.endsWith("ss")?`${t}es`:`${t}s`:t}function Ii(e,t=Jt){let r=e.trim().replaceAll(/\s+/g," ");if(r.length===0)return[];let n=ee(r);if(n.length===0)return[r];let o=n.filter(a=>!ac.has(a.toLowerCase())),i=n.map(a=>cc(a)),s=o.map(a=>dc(a));return Zt([r,n.join(" "),o.join(" "),i.join(" "),s.join(" ")],Math.max(1,t))}function Ai(e){let t=Array.isArray(e)?e:e?.queries;return Array.isArray(t)?Zt(t.filter(r=>typeof r=="string"),Jt):[]}function Ci(e,t,r){return Zt([...e,...t],Math.max(1,r))}function Mi(e,t){let n=e.search?.query_expansion,o=ce(n?.provider);return{enabled:n?.enabled===!0,provider:o??t,max_queries:Jt}}function Fi(e,t){let n=e.search?.rerank,o=ce(n?.model),s=ke(n?.top_k)??ic;return{enabled:n?.enabled===!0,model:o??t,top_k:Math.min(sc,s)}}function Ti(e){let t=Array.isArray(e)?e:e?.hits;if(!Array.isArray(t))return[];let r=new Map;for(let o of t){if(typeof o!="object"||o===null)continue;let i=ce(o.id),s=o.score;if(!i||typeof s!="number"||!Number.isFinite(s))continue;let a=r.get(i);(a===void 0||s>a)&&r.set(i,s)}let n=[...r.entries()].map(([o,i])=>({id:o,score:i}));return n.sort((o,i)=>o.score!==i.score?i.score-o.score:o.id.localeCompare(i.id)),n}function lc(e,t){let r=e.length,n=0;for(let o=0;o<r;o+=1)n+=e[o]*t[o];return n}function Pi(e){let t=0;for(let r=0;r<e.length;r+=1)t+=e[r]*e[r];return Math.sqrt(t)}function uc(e,t,r){if(!e||!t||e.length===0||t.length===0||e.length!==t.length)return 0;let n=lc(e,t),o=Pi(t),i=r*o;return!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(o)||!Number.isFinite(i)||i===0?0:Math.max(-1,Math.min(1,n/i))}async function Hi(e,t,r,n,o){if(n.length===0)return new Map;let i=ce(t)??e.model,s=i===e.model?e:{...e,model:i},a=[r.trim(),...n.map(m=>m.text)],d=await $e(s,a,o?{timeout_ms:o}:{}),l=d[0];if(!l)return new Map;let c=Pi(l),u=new Map;for(let m=0;m<n.length;m+=1){let f=n[m],_=d[m+1];if(!_)continue;let y=uc(l,_,c);u.set(f.id,Math.max(0,Math.min(1,(y+1)/2)))}return u}function se(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function j(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string"):[]}function we(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.kind=="string"):[]}function er(e){let t=e.metadata;return[t.title,t.description,t.status,se(t.tags).join(" "),e.body,j(t.comments).map(r=>r.text).join(" "),j(t.notes).map(r=>r.text).join(" "),j(t.learnings).map(r=>r.text).join(" "),Ue(t).join(" "),Ge(t).join(" "),we(t.dependencies).map(r=>`${r.id} ${r.kind}`).join(" "),Be(t)]}function tr(e,t){return er(e).some(r=>A(r).includes(t))}function rr(e,t,r){return!r.titleExact&&!r.phraseExact?e:e.filter(n=>!(r.titleExact&&A(n.metadata.title)!==t||r.phraseExact&&!tr(n,t)))}function mc(e){if(e&&[...e].some(t=>t.toLowerCase()==="none"||t.toLowerCase()==="null"))throw new p('--assignee no longer accepts "none" or "null".',h.USAGE)}function fc(e,t,r){let n=ge(e.assignee,{label:"--assignee"});mc(n);let o=xo(e),i=Ro(e);return{typeFilter:po(e.type,t),tagFilter:ge(e.tag,{label:"--tag",normalize:s=>s.toLowerCase()}),priorityFilter:go(e.priority),deadlineBefore:Gt(e.deadlineBefore,"deadline-before"),deadlineAfter:Gt(e.deadlineAfter,"deadline-after"),updatedAfter:Q(e.updatedAfter,"updated-after"),updatedBefore:Q(e.updatedBefore,"updated-before"),createdAfter:Q(e.createdAfter,"created-after"),createdBefore:Q(e.createdBefore,"created-before"),assigneeFilter:n,sprintFilter:ge(e.sprint,{label:"--sprint"}),releaseFilter:ge(e.release,{label:"--release"}),parentFilter:e.parent?.trim(),statusSet:r&&r.length>0?new Set(r):void 0,missingMetadataFilters:o,missingMetadataActive:yo(o),contentFieldFilters:i,contentFiltersActive:wo(i)}}function hc(e,t){return pc(e,t)&&Yr(e,t)&&gc(e,t)}function pc(e,t){if(t.statusSet&&!t.statusSet.has(e.status)||t.typeFilter&&!t.typeFilter.has(e.type))return!1;let r=t.tagFilter;return!(r&&!se(e.tags).some(n=>r.has(n))||t.priorityFilter!==void 0&&!t.priorityFilter.has(e.priority))}function gc(e,t){return!(t.assigneeFilter!==void 0&&(e.assignee===void 0||!t.assigneeFilter.has(e.assignee))||t.sprintFilter!==void 0&&(e.sprint===void 0||!t.sprintFilter.has(e.sprint))||t.releaseFilter!==void 0&&(e.release===void 0||!t.releaseFilter.has(e.release))||t.parentFilter!==void 0&&e.parent!==t.parentFilter)}function yc(e,t,r,n){let o=e.metadata;return!(!hc(o,t)||!Nn(o,r)||t.missingMetadataActive&&!_o(o,t.missingMetadataFilters,n)||t.contentFiltersActive&&!vo(o,t.contentFieldFilters))}function nr(e,t,r,n,o,i){let s=fc(t,r,o);return e.filter(a=>yc(a,s,n,i))}var _c=2,wc=120,vc=6,Ec=40,bc=1e3,Sc=900,xc="\xAB",Rc="\xBB",Oi=60;function tt(e,t){let r=0,n=0;for(;;){let o=e.indexOf(t,n);if(o<0)return r;r+=1,n=o+t.length}}var Li=[{name:"title",weightKey:"title_weight",value:e=>e.metadata.title},{name:"description",weightKey:"description_weight",value:e=>e.metadata.description},{name:"tags",weightKey:"tags_weight",value:e=>se(e.metadata.tags).join(" ")},{name:"status",weightKey:"status_weight",value:e=>typeof e.metadata.status=="string"?e.metadata.status:""},{name:"body",weightKey:"body_weight",value:e=>e.body},{name:"comments",weightKey:"comments_weight",value:e=>j(e.metadata.comments).map(t=>t.text).join(" ")},{name:"notes",weightKey:"notes_weight",value:e=>j(e.metadata.notes).map(t=>t.text).join(" ")},{name:"learnings",weightKey:"learnings_weight",value:e=>j(e.metadata.learnings).map(t=>t.text).join(" ")},{name:"reminders",weightKey:"reminders_weight",value:e=>Ue(e.metadata).join(" ")},{name:"events",weightKey:"events_weight",value:e=>Ge(e.metadata).join(" ")},{name:"dependencies",weightKey:"dependencies_weight",value:e=>we(e.metadata.dependencies).map(t=>`${t.id} ${t.kind}`).join(" ")},{name:"plan",weightKey:"body_weight",value:e=>Be(e.metadata)}],kc=new Map(Li.map(e=>[e.name,e]));function or(e,t){let r=t.filter(o=>o.length>0).sort((o,i)=>i.length-o.length).map(o=>o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));if(r.length===0)return e;let n=new RegExp(r.join("|"),"gi");return e.replace(n,o=>`${xc}${o}${Rc}`)}function ir(e,t){if(e.length===0)return null;let r=e.toLowerCase(),n=-1,o=0;for(let c of t){if(c.length===0)continue;let u=r.indexOf(c);u>=0&&(n<0||u<n)&&(n=u,o=c.length)}if(n<0)return null;let i=Math.max(0,n-Oi),s=Math.min(e.length,n+o+Oi),a=or(e.slice(i,s),t),d=i>0?"\u2026":"",l=s<e.length?"\u2026":"";return`${d}${a}${l}`}function rt(e,t,r){let n=[];for(let o of t){let i=kc.get(o);if(i===void 0)continue;let s=ir(i.value(e),r);s!==null&&n.push({field:o,snippet:s})}return n}function Ic(e,t,r){return[...Li.map(n=>({name:n.name,value:n.value(e),weight:r[n.weightKey]})),{name:"linked_content",value:t,weight:r.linked_content_weight}]}function Ac(e,t,r){let n=A(e.id),o=typeof r=="string"?r.trim().toLowerCase():"",i=A(o),s=i.length>0&&n.startsWith(i)?n.slice(i.length).trim():n;return t!==n&&t!==s?null:{item:e,score:t===n?bc:Sc,matched_fields:["id"],matched_all_terms:!0,exact_id_match:!0}}function Cc(e,t,r,n,o){for(let i of e){let s=t.get(i)??0;s>0&&(o.score+=s*n.title_exact_bonus,o.matched.add("title"),o.matchedTokens.add(i));for(let a of r){let d=tt(a.value.toLowerCase(),i);d>0&&(o.score+=d*a.weight,o.matched.add(a.name),o.matchedTokens.add(i))}}}function Mc(e,t,r,n){A(e.title)===t&&(n.score+=wc,n.matched.add("title"));for(let i of r){let s=tt(A(i.value),t);s>0&&(n.score+=s*i.weight*vc,n.matched.add(i.name))}}function sr(e,t,r,n,o,i,s=!1){let a=e.metadata,d=Ac(a,r,i);if(d)return d;let l=new Map;for(let y of ee(a.title))l.set(y,(l.get(y)??0)+1);let c=Ic(e,n,o),u={score:0,matched:new Set,matchedTokens:new Set};Cc(t,l,c,o,u);let m=new Set(t),f=m.size>0&&u.matchedTokens.size===m.size;return s&&m.size>1&&f&&(u.score+=Ec),t.length>=_c&&r.includes(" ")&&Mc(a,r,c,u),u.score<=0?null:{item:a,score:u.score,matched_fields:[...u.matched].sort((y,g)=>y.localeCompare(g)),matched_all_terms:f}}function ar(e,t){return[...e].sort((r,n)=>{let o=n.score-r.score;if(o!==0)return o;let i=de(r.item.status,t),s=de(n.item.status,t);if(i!==s)return i?1:-1;let a=r.item.priority-n.item.priority;if(a!==0)return a;let d=Qr(n.item.updated_at,r.item.updated_at);return d!==0?d:r.item.id.localeCompare(n.item.id)})}function cr(e,t,r,n,o,i,s,a=!1){return sr(e,t,r,n?o.get(e.metadata.id)??"":"",i,s,a)}function ve(e){if(e.size===0)return new Map;let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let o of e.values())t=Math.min(t,o),r=Math.max(r,o);if(r===t)return new Map([...e.keys()].map(o=>[o,1]));let n=new Map;for(let[o,i]of e)n.set(o,(i-t)/(r-t));return n}function ot(e){let t=[],r=e;for(let n=0;n<5&&r&&typeof r=="object";n+=1){let o=r.code;typeof o=="string"&&t.push(o.toLowerCase()),r=r.cause}return t.join(" ")}function it(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase(),r=ot(e),n=`${t} ${r}`;return n.includes("timed out")||n.includes("timeout")||n.includes("etimedout")?"timeout":n.includes("econnrefused")||n.includes("connection refused")||n.includes("connect ")||n.includes("enotfound")||n.includes("eai_again")||n.includes("econnreset")||n.includes("fetch failed")?"connection":"error"}function dr(e,t){let r=it(t);return`search_${e}_fallback:${r}:using_keyword_mode`}function ji(e){return e?.commands?.some(r=>r.command.trim()==="reindex")===!0?{command:"pm reindex --mode hybrid",args:["reindex","--mode","hybrid"]}:{command:"pm install search-advanced --project",args:["install","search-advanced","--project"],follow_up_command:"pm reindex --mode hybrid",follow_up_args:["reindex","--mode","hybrid"]}}async function lr(e,t,r){try{let n=await ro(e);n.warnings.length>0&&r.push(...n.warnings);let o=Ao(t.map(s=>({id:s.metadata.id,updated_at:s.metadata.updated_at})),n.entries);if(o.length===0)return;let i=ji(x());r.push(...qi(o.length,i)),process.stderr.write(`[pm] warning: ${o.length} item${o.length===1?" is":"s are"} new or modified since the last reindex and ${o.length===1?"is":"are"} NOT in the semantic index yet \u2014 run '${i.command}'${i.follow_up_command?`, then '${i.follow_up_command}'`:""}. (Write-time embedding is governed by search.mutation_refresh_policy; staleness means the embed was skipped, failed, or the backend was unreachable.)
3
+ `)}catch{}}function qi(e,t){return[`vector_index_stale:${e}`,`vector_index_recovery:${t.args.join(" ")}`,...t.follow_up_args?[`vector_index_recovery_follow_up:${t.follow_up_args.join(" ")}`]:[]]}function st(e,t,r,n){if(!t.active)throw new p(`Search mode '${e}' requires a configured embedding provider in settings.providers.openai or settings.providers.ollama`,h.USAGE);if(!r.active&&!n)throw new p(`Search mode '${e}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,h.USAGE);return{provider:t.active,vectorStore:r.active??null}}var C=Re;function Ee(e){let t=x(),r=Fn(t,e);if(!r)return null;let n=r.runtime_definition??r.definition,o=n.query,i=n.queryExpansion??n.query_expansion,s=n.rerank,a=C(n.name)??C(r.definition.name)??e;if(!a)return null;let d={providerName:a,...typeof o=="function"?{query:o}:{},...typeof i=="function"?{queryExpansion:i}:{},...typeof s=="function"?{rerank:s}:{}};return!d.query&&!d.queryExpansion&&!d.rerank?null:d}function ur(e){let t=C(e.search?.provider),r=Ee(t);return r?.query?{providerName:r.providerName,query:r.query}:null}function mr(e){let t=x(),r=C(e.vector_store?.adapter),n=Tn(t,r);if(!n)return null;let o=n.runtime_definition??n.definition,i=o.query;if(typeof i!="function")return null;let s=o.upsert;return{adapterName:C(o.name)??C(n.definition.name)??r??"extension",query:i,...typeof s=="function"?{upsert:s}:{}}}function fr(e,t,r){let n=Array.isArray(t)?t:t?.hits;if(!Array.isArray(n))throw new p(`Extension search provider "${e}" must return an array of hits or { hits: [...] }`,h.GENERIC_FAILURE);let o=new Set,i=[];for(let s of n){if(typeof s!="object"||s===null)continue;let a=C(s.id),d=s.score;if(!a||typeof d!="number"||!Number.isFinite(d)||o.has(a))continue;let l=r.get(a);if(!l)continue;let c=s.matched_fields,u=Array.isArray(c)&&c.every(m=>typeof m=="string")?[...new Set(c.map(m=>m.trim()).filter(m=>m.length>0))].sort((m,f)=>m.localeCompare(f)):[`provider:${e}`];o.add(a),i.push({item:l.metadata,score:d,matched_fields:u})}return i}function hr(e,t){let r=[],n=new Map;for(let o of e){if(n.has(o.id))continue;let i=t.get(o.id);i&&(n.set(o.id,o.score),r.push({item:i.metadata,score:o.score,matched_fields:["semantic"]}))}return{semanticHits:r,semanticScores:n}}function nt(e,t){let r=t.filter(l=>l.exact_id_match===!0);if(r.length===0)return e;let n=new Set(r.map(l=>l.item.id)),o=e.filter(l=>!n.has(l.item.id)),i=o.reduce((l,c)=>Math.max(l,c.score),0),s=r.sort((l,c)=>c.score-l.score),a=i+s.length+1;return[...s.map((l,c)=>({...l,score:a-c,matched_fields:["id"]})),...o]}function at(e,t,r,n,o="semantic"){let i=new Map(r.map(u=>[u.item.id,u.score])),s=new Map(r.map(u=>[u.item.id,u.matched_fields])),a=ve(t),d=ve(i),l=new Set([...t.keys(),...i.keys()]),c=1-n;return[...l].map(u=>{let m=e.get(u),f=a.get(u)??0,_=d.get(u)??0,y=f*n+_*c;if(y<=0)return null;let g=new Set;t.has(u)&&g.add(o);for(let w of s.get(u)??[])g.add(w);return{item:m.metadata,score:y,matched_fields:[...g].sort((w,v)=>w.localeCompare(v))}}).filter(u=>u!==null)}function pr(e){let t=e.configuredProvider?.trim().toLowerCase();return t==="bm25"?"explicit":t==="auto"&&!e.hasEmbeddingProvider&&!e.hasExtensionSearchProvider?"auto-fallback":null}function gr(e){let t=e.filteredDocuments.map(s=>({id:s.metadata.id,text:Ri(eo(s,{fields:e.corpusFields}))})),r=Si(t),n=xi(r,Xt(e.query),e.bm25Params),o=new Map(e.filteredDocuments.map(s=>[s.metadata.id,s]));if(e.requestedMode==="semantic"){let s=[...n].map(([a,d])=>({item:o.get(a).metadata,score:d,matched_fields:["bm25"]}));return nt(s,e.keywordHits)}let i=at(o,n,e.keywordHits,e.hybridSemanticWeight,"bm25");return nt(i,e.keywordHits)}function yr(e){let t=new Map;for(let n of e)for(let o of n){let i=t.get(o.id);(!i||o.score>i.score)&&t.set(o.id,o)}let r=[...t.values()];return r.sort((n,o)=>n.score!==o.score?o.score-n.score:n.id.localeCompare(o.id)),r}function _r(e){let t=e.metadata,r=Array.isArray(t?.tags)?t.tags.join(" "):"";return[t?.title,t?.description,t?.type,t?.status,r,e.body].map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0).join(`
4
+ `)}async function Fc(e,t){let r=e.queryExpansion.enabled?Ii(t,e.queryExpansion.max_queries):[t],n=r.length>0?r:[t];if(!e.queryExpansion.enabled)return n;if(e.queryExpansionExtension?.expand)try{let o=await Promise.resolve(e.queryExpansionExtension.expand({query:t,mode:e.requestedMode,settings:e.settings}));return Ci(n,Ai(o),e.queryExpansion.max_queries)}catch{return e.warnings.push(`search_query_expansion_provider_failed:${e.queryExpansionExtension.providerName}:using_builtin`),n}return e.queryExpansion.provider&&e.queryExpansion.provider!=="openai"&&e.queryExpansion.provider!=="ollama"&&e.warnings.push(`search_query_expansion_provider_unavailable:${e.queryExpansion.provider}:using_builtin`),n}async function Tc(e,t,r,n){if(e.extensionVectorAdapter?.query)try{return await Promise.resolve(e.extensionVectorAdapter.query({vector:t,limit:r,settings:e.settings}))}catch(o){if(!e.vectorStore)throw new p(`Extension vector adapter query failed and no built-in fallback store is configured (${o instanceof Error?o.message:String(o)})`,h.GENERIC_FAILURE);return e.warnings.push(`search_vector_adapter_failed:${e.extensionVectorAdapter.adapterName}:using_builtin`),await Et(e.vectorStore,t,r,n)}if(e.vectorStore)return await Et(e.vectorStore,t,r,n);throw new p("Semantic search requires either a configured vector store or an extension vector adapter query handler",h.USAGE)}function Pc(e,t,r){return[...e].sort((o,i)=>o.score!==i.score?i.score-o.score:o.item.id.localeCompare(i.item.id)).slice(0,r).map(o=>{let i=t.get(o.item.id);return i?{hit:o,text:_r(i)}:null}).filter(o=>o!==null)}async function Hc(e,t,r){if(!e.rerankExtension?.rerank)return null;try{let n=await Promise.resolve(e.rerankExtension.rerank({query:t,mode:"hybrid",model:e.rerank.model,top_k:e.rerank.top_k,settings:e.settings,candidates:r.map(i=>({id:i.hit.item.id,text:i.text,score:i.hit.score}))})),o=Ti(n);return o.length>0?new Map(o.map(i=>[i.id,i.score])):(e.warnings.push(`search_rerank_provider_invalid_response:${e.rerankExtension.providerName}:using_builtin`),null)}catch{return e.warnings.push(`search_rerank_provider_failed:${e.rerankExtension.providerName}:using_builtin`),null}}async function Oc(e,t,r){let n=await Hc(e,t,r);if(n)return n;let o=r.map(i=>({id:i.hit.item.id,text:i.text}));try{return await Hi(e.provider,e.rerank.model,t,o,e.embeddingTimeoutMs)}catch{return e.warnings.push("search_rerank_failed:using_hybrid_scores"),null}}function Lc(e,t){let r=new Set(t.keys()),n=e.map(o=>{let i=t.get(o.item.id);if(i===void 0)return o;let s=new Set(o.matched_fields);return s.add("rerank"),{...o,score:i,matched_fields:[...s].sort((a,d)=>a.localeCompare(d))}});return n.sort((o,i)=>{let s=r.has(o.item.id),a=r.has(i.item.id);return s!==a?s?-1:1:o.score!==i.score?i.score-o.score:o.item.id.localeCompare(i.item.id)}),n}async function jc(e,t,r,n){if(!e.rerank.enabled||r.length<=1)return r;let o=Pc(r,n,e.rerank.top_k),i=await Oc(e,t,o);return i&&i.size>0?Lc(r,i):r}async function wr(e){let t=Math.max(e.limit??e.maxResults,e.maxResults),r=e.embeddingTimeoutMs!==void 0?{timeout_ms:e.embeddingTimeoutMs}:{},n=e.vectorQueryTimeoutMs!==void 0?{timeout_ms:e.vectorQueryTimeoutMs}:{},o=e.query.trim(),i=await Fc(e,o),s=await $e(e.provider,i,r),a=await Promise.all(s.map(async _=>await Tc(e,_,t,n))),d=yr(a),l=new Map(e.filteredDocuments.map(_=>[_.metadata.id,_])),{semanticHits:c,semanticScores:u}=hr(d,l),m=u.size;if(e.requestedMode==="semantic")return{hits:nt(c,e.keywordHits),vectorMatchCount:m};let f=await jc(e,o,at(l,u,e.keywordHits,e.hybridSemanticWeight),l);return{hits:nt(f,e.keywordHits),vectorMatchCount:m}}function Di(e){let t=Ee(e.provider??void 0);return t?.queryExpansion?{providerName:t.providerName,expand:t.queryExpansion}:null}function Ni(e){let t=Ee(C(e.search?.provider));return t?.rerank?{providerName:t.providerName,rerank:t.rerank}:null}import ct from"node:fs/promises";import vr from"node:path";function Er(e){let t=(e.files??[]).map(s=>({scope:s.scope,path:s.path.trim()})),r=(e.docs??[]).map(s=>({scope:s.scope,path:s.path.trim()})),n=(e.tests??[]).filter(s=>typeof s.path=="string"&&s.path.trim().length>0).map(s=>({scope:s.scope,path:s.path.trim()})),o=[...t,...r,...n].filter(s=>s.path.length>0).sort((s,a)=>s.scope.localeCompare(a.scope)||s.path.localeCompare(a.path)),i=new Map;for(let s of o)i.set(`${s.scope}:${s.path}`,s);return[...i.values()]}async function $i(e){let t=vr.resolve(e);try{let r=await ct.realpath(t);return{resolved:t,realpath:r}}catch{return null}}async function br(e,t){let[r,n]=await Promise.all([$i(e),$i(t)]);return{projectContainmentRoot:r,globalContainmentRoot:n}}async function Sr(e,t){let r=Er(e.metadata),n=[];for(let o of r){let i=o.scope==="global"?t.globalContainmentRoot:t.projectContainmentRoot;if(!i)continue;let s=vr.resolve(i.resolved,o.path);if(!ut(i.resolved,s))continue;let a;try{a=await ct.realpath(s)}catch{continue}if(ut(i.realpath,a))try{await he({path:s,scope:o.scope}),n.push(await ct.readFile(s,"utf8"))}catch{}}return n.join(`
5
+ `)}async function xr(e,t,r,n){let o=$(x()),i=async(l,c,u)=>{let m=async(f,_)=>{await he({path:f,scope:"project"});let y=await ct.readFile(f,"utf8");return Zr(y,{format:_,schema:n,extensionFieldNames:o,onWarning:w=>s.push(w)}).body};try{return await m(c,u)}catch{let f=u==="toon"?"json_markdown":"toon",_=z(e,l.type,l.id,f,r);try{return await m(_,f)}catch{return s.push(`item_list_item_read_failed:${vr.relative(e,_)}`),""}}},s=[],a=await zn(e,t,r,s,n),d=[];if(a.length===0){let l=await Kn(e,t,r,s,n);for(let c of l){let u=z(e,c.type,c.id,t,r),m=await i(c,u,t);d.push({metadata:c,body:m})}return{documents:d,warnings:[...new Set(s)].sort((c,u)=>c.localeCompare(u))}}for(let l of a){if(typeof l.body=="string"){d.push({metadata:l.metadata,body:l.body});continue}let c=await i(l.metadata,l.item_path,l.item_format);d.push({metadata:l.metadata,body:c})}return{documents:d,warnings:[...new Set(s)].sort((l,c)=>l.localeCompare(c))}}async function Ui(e,t,r){let n=new Map;if(!e||t!=="keyword"&&t!=="hybrid")return n;let o=process.cwd(),i=await br(o,zr(o)),s=await Promise.all(r.map(async a=>[a.metadata.id,await Sr(a,i)]));for(let[a,d]of s)n.set(a,d);return n}var Gi=["tag","status","type","priority"];function Rr(e){let t={},r=[];for(let n of e.split(/\s+/).filter(o=>o.length>0)){let o=n.indexOf(":"),i=o>0?n.slice(0,o).toLowerCase():"",s=o>0?n.slice(o+1):"",a=Gi.includes(i)?i:void 0;if(a&&s.length>0&&t[a]===void 0){t[a]=s;continue}r.push(n)}return{residualQuery:r.join(" "),inlineFilters:t}}function kr(e,t,r){let n={...e};for(let o of Gi){let i=t[o];if(i!==void 0){if(Re(n[o])!==void 0){r.push(`search_inline_filter_ignored:${o}:flag_takes_precedence`);continue}n[o]=i}}return n}function Bi(e,t){let r=[],n=Rr(e),o=Object.keys(n.inlineFilters).length>0;if(o&&n.residualQuery.trim().length===0)throw new p("Inline field:value tokens consumed the entire query, leaving no search terms.",h.USAGE,{examples:["pm search auth tag:area:search","pm list --tag area:search --status open"],nextSteps:["Add keyword terms alongside the inline filters, or use pm list for pure tag/status/type/priority filtering."]});let i=o?n.residualQuery:e,s=kr(t,n.inlineFilters,r);return{query:i,options:s,inlineWarnings:r,highlight:s.highlight===!0,includeLinked:Xe(s.includeLinked),titleExact:Xe(s.titleExact),phraseExact:Xe(s.phraseExact),matchMode:_i(typeof s.matchMode=="string"?s.matchMode:void 0),minScoreOverride:wi(s.minScore),countOnly:s.count===!0,tokens:Ze(i),normalizedQuery:A(i),limit:Oe(s.limit),projection:Je(s,e),modeWasExplicit:typeof s.mode=="string"&&s.mode.trim().length>0}}function Wi(e){if(e.after!==void 0&&e.count===!0)throw new p("Search --after cannot be combined with --count.",h.USAGE)}function Ar(e,t,r,n,o,i,s,a,d,l,c,u,m,f){let _=m?{total:0,count_only:!0}:{};if(l.mode==="compact"&&n.compact===!0){let w=Y({mode:t,matchMode:r,options:n,includeLinked:o,titleExact:n.titleExact===!0,phraseExact:n.phraseExact===!0,scoreThreshold:i,hybridSemanticWeight:s,runtimeFieldFilters:u});return{query:e.trim(),mode:t,...Pr(f),items:[],count:0,..._,filters:w,...c.length>0?{warnings:c}:{}}}let g=l.mode==="full"?null:[...l.fields];return{query:e.trim(),mode:t,mode_source:f,items:[],count:0,..._,filters:Tr({effectiveMode:t,matchMode:r,options:n,includeLinked:o,titleExact:n.titleExact===!0,phraseExact:n.phraseExact===!0,scoreThreshold:i,hybridSemanticWeight:s,queryExpansion:a,rerank:d,runtimeFieldFilters:u??{}},l),projection:{mode:l.mode,fields:g},now:S(),...c.length>0?{warnings:c}:{}}}function Cr(e,t){let r=t.trim();if(r.length===0)return null;if(r==="score")return e.score;if(r==="matched_fields")return e.matched_fields;if(r.startsWith("item.")){let i=r.slice(5);return i.length===0?null:e.item[i]??null}let n=e,o=e.item;return Object.prototype.hasOwnProperty.call(o,r)?o[r]??null:Object.prototype.hasOwnProperty.call(n,r)?n[r]??null:null}function Mr(e,t){return t.mode==="full"?e.map(({matched_all_terms:r,exact_id_match:n,...o})=>o):e.map(r=>{let n={};for(let o of t.fields)n[o]=Cr(r,o);return n})}function Fr(e,t){return Ar(e.query,e.effectiveMode,e.matchMode,e.options,e.includeLinked,e.scoreThreshold,e.hybridSemanticWeight,e.queryExpansion,e.rerank,e.projection,e.warnings,e.runtimeFieldFilters,t,e.modeSource)}function zi(e,t){if(e.projection.mode==="compact"&&e.options.compact===!0)return Ir({query:e.query.trim(),mode:e.effectiveMode,...Pr(e.modeSource),items:[],count:t,total:t,count_only:!0,filters:Y({mode:e.effectiveMode,matchMode:e.matchMode,options:e.options,includeLinked:e.includeLinked,titleExact:e.titleExact,phraseExact:e.phraseExact,scoreThreshold:e.scoreThreshold,hybridSemanticWeight:e.hybridSemanticWeight,runtimeFieldFilters:e.runtimeFieldFilters})},e.warnings);let r=e.projection.mode==="full"?null:[...e.projection.fields];return Ir({query:e.query.trim(),mode:e.effectiveMode,mode_source:e.modeSource,items:[],count:t,total:t,count_only:!0,filters:Tr(e,e.projection),projection:{mode:e.projection.mode,fields:r},now:S()},e.warnings)}function Tr(e,t){let r={matchMode:e.matchMode,options:e.options,includeLinked:e.includeLinked,titleExact:e.titleExact,phraseExact:e.phraseExact,scoreThreshold:e.scoreThreshold,hybridSemanticWeight:e.hybridSemanticWeight,runtimeFieldFilters:e.runtimeFieldFilters};return t.mode==="fields"?Y({...r,mode:e.effectiveMode}):et({...r,effectiveMode:e.effectiveMode,queryExpansion:e.queryExpansion,rerank:e.rerank})}function Pr(e){return e==="settings"?{mode_source:e}:{}}function Ir(e,t){return t.length===0?e:{...e,warnings:t}}function be(e,t){return t?{...e,workspace_memory:t}:e}function Vi(e,t,r){if(!e.highlight)return{hits:r,projection:e.projection};let n=new Map(t.map(i=>[i.metadata.id,i])),o=r.map(i=>({...i,highlights:rt(n.get(i.item.id),i.matched_fields,e.tokens)}));return e.projection.mode==="full"||e.projection.fields.includes("highlights")?{hits:o,projection:e.projection}:{hits:o,projection:{mode:e.projection.mode,fields:[...e.projection.fields,"highlights"]}}}function Ki(e,t,r,n,o,i){let s=n<r?{total:r}:{};if(e.projection.mode==="compact"&&e.options.compact===!0)return Ir({query:e.query.trim(),mode:e.effectiveMode,...Pr(e.modeSource),items:t,count:t.length,...s,...i,filters:Y({mode:e.effectiveMode,matchMode:e.matchMode,options:e.options,includeLinked:e.includeLinked,titleExact:e.titleExact,phraseExact:e.phraseExact,scoreThreshold:e.scoreThreshold,hybridSemanticWeight:e.hybridSemanticWeight,runtimeFieldFilters:e.runtimeFieldFilters})},e.warnings);let a=o.mode==="full"?null:[...o.fields];return{query:e.query.trim(),mode:e.effectiveMode,mode_source:e.modeSource,items:t,count:t.length,...s,...i,filters:Tr(e,o),projection:{mode:o.mode,fields:a},now:S(),...e.warnings.length>0?{warnings:e.warnings}:{}}}var qf={applyFilters:nr,applyExactQueryFilters:rr,applyInlineQueryFilters:kr,buildHitHighlights:rt,buildVerboseSearchFilters:et,buildExplicitSemanticFallbackWarning:dr,buildCompactSearchFilterSummary:Y,buildHybridLexicalScore:cr,buildRerankCorpus:_r,buildSemanticHits:hr,classifyImplicitSemanticFallbackReason:it,collectErrorCauseCodes:ot,collectExactPhraseFields:er,collectLinkedPaths:Er,combineHybridHits:at,computeBuiltInBm25Hits:gr,computeSemanticOrHybridHits:wr,resolveBuiltInBm25Mode:pr,countOccurrences:tt,dependencyEntries:we,documentContainsExactPhrase:tr,emptySearchResult:Ar,highlightFieldSnippet:ir,loadDocuments:xr,markTokenRuns:or,parseInlineQueryFilters:Rr,maybeEmitVectorIndexStaleWarning:lr,loadLinkedCorpus:Sr,mergeVectorHitsById:yr,normalizeExtensionProviderHits:fr,normalizeScoreMap:ve,parseProjectionConfig:Je,parseTimestampWindow:Q,parseTokens:Ze,projectSearchHits:Mr,readSearchFieldValue:Cr,requireSemanticDependencies:st,resolveExtensionSearchProvider:ur,resolveExtensionSearchProviderByName:Ee,resolveExtensionVectorAdapter:mr,resolveLinkedCorpusRoots:br,scoreDocument:sr,sortHits:ar,stringArray:se,textEntries:j,validateSearchProjectionFields:Bt};async function qc(e,t){let r=k(process.cwd(),t.path);await O(r);let n=await P(r),o=$n(n).settings,i=N(o.schema),s=Z(o.schema);Bt(e.projection,s,e.query);let a=Dn(e.options,s,"search"),d=D(o,x()),l=Jn(o),c=to(o,r),u=ur(o),m=mr(o),f=yi(e.options.semanticWeight),_=Mi(o,l.active?.name??null),y=Fi(o,l.active?.model??C(o.search?.embedding_model)??"text-embedding-3-small");return{pmRoot:r,settings:o,statusRegistry:i,runtimeFieldRegistry:s,runtimeFieldFilters:a,typeRegistry:d,maxResults:Wt(o),scoreThreshold:e.minScoreOverride??Vt(o),semanticWeightProvided:e.options.semanticWeight!==void 0,semanticWeightOverride:f,hybridSemanticWeight:f??Kt(o),tuning:Qt(o),providerResolution:l,vectorResolution:c,extensionSearchProvider:u,extensionVectorAdapter:m,bm25Mode:pr({configuredProvider:C(o.search?.provider),hasEmbeddingProvider:l.active!==null,hasExtensionSearchProvider:u!==null}),queryExpansion:_,queryExpansionExtension:Di(_),rerank:y,rerankExtension:Ni(o),...Dc({requested:e.options.mode,settings:o,configuredProvider:n.search?.provider??null,providerResolution:l,vectorResolution:c,extensionSearchProvider:u,extensionVectorAdapter:m})}}function Dc(e){let r=Xn(e.providerResolution.active?.name,e.configuredProvider)==="configured"&&(e.vectorResolution.active!==null||e.extensionVectorAdapter!==null),n=e.extensionSearchProvider!==null||r,o=zt({requested:e.requested,settings:e.settings,semanticRunnable:n});return{effectiveMode:o.mode,modeSource:o.source}}async function Nc(e,t){let r=await xr(t.pmRoot,t.settings.item_format??"toon",t.typeRegistry.type_to_folder,t.settings.schema),n=He(typeof e.options.status=="string"?e.options.status:void 0,t.statusRegistry,{strict:!0}),o=We(t.statusRegistry),i=nr(r.documents,e.options,t.typeRegistry,t.runtimeFieldFilters,n,o);return{warnings:r.warnings,allDocuments:r.documents,filteredDocuments:rr(i,e.normalizedQuery,{titleExact:e.titleExact,phraseExact:e.phraseExact||e.matchMode==="exact"})}}async function $c(e,t,r){let n=await Ui(e.includeLinked,t.effectiveMode,r),o=e.matchMode==="or";return r.map(i=>cr(i,e.tokens,e.normalizedQuery,e.includeLinked,n,t.tuning,t.settings.id_prefix,o)).filter(i=>i!==null).filter(i=>e.matchMode!=="and"||i.matched_all_terms===!0)}async function Uc(e,t,r,n,o){if(t.bm25Mode===null||t.effectiveMode==="keyword")return null;let i=gr({requestedMode:t.effectiveMode,query:e.query,filteredDocuments:r,keywordHits:n,corpusFields:Zn(t.settings),bm25Params:ki(t.settings),hybridSemanticWeight:t.hybridSemanticWeight});return t.bm25Mode==="auto-fallback"&&o.push(`search_${t.effectiveMode}_offline_bm25:no_embedding_provider:using_lexical_bm25`),i}async function Gc(e,t,r,n){if(!t.extensionSearchProvider)return null;let o=t.providerResolution.active!==null&&(t.vectorResolution.active!==null||t.extensionVectorAdapter!==null);try{let i=await Promise.resolve(t.extensionSearchProvider.query({query:e.query,mode:t.effectiveMode,tokens:e.tokens,options:e.options,settings:t.settings,documents:r}));return fr(t.extensionSearchProvider.providerName,i,n)}catch(i){if(!o)throw new p(`Extension search provider "${t.extensionSearchProvider.providerName}" failed: ${i instanceof Error?i.message:String(i)}`,h.GENERIC_FAILURE);return null}}function Bc(e,t,r,n){return t.vectorMatchCount>0?t.hits:(n.push(`search_${e}_degraded:no_vector_matches:results_are_lexical`),e==="semantic"?r:t.hits)}async function Wc(e,t,r,n,o){let i=!e.extensionSearchProvider&&e.providerResolution.active!==null&&(e.vectorResolution.active!==null||e.extensionVectorAdapter!==null);o&&i&&await lr(e.pmRoot,r,n),e.extensionSearchProvider||st(t,e.providerResolution,e.vectorResolution,e.extensionVectorAdapter!==null)}async function zc(e){let{prepared:t,runtime:r,filteredDocuments:n,keywordHits:o,warnings:i,modeWasExplicit:s}=e,a=o,d=await Uc(t,r,n,o,i),l=r.effectiveMode;if(d!==null||l==="keyword")return{effectiveMode:r.effectiveMode,hits:d??a};try{if(await Wc(r,l,n,i,s),n.length===0||t.limit===0)return{effectiveMode:r.effectiveMode,hits:[]};let c=new Map(n.map(u=>[u.metadata.id,u]));if(a=await Gc(t,r,n,c)??a,a===o){let{provider:u,vectorStore:m}=st(l,r.providerResolution,r.vectorResolution,r.extensionVectorAdapter!==null),f=await wr({requestedMode:l,query:t.query,filteredDocuments:n,keywordHits:o,hybridSemanticWeight:r.hybridSemanticWeight,limit:t.limit,maxResults:r.maxResults,provider:u,vectorStore:m,extensionVectorAdapter:r.extensionVectorAdapter,queryExpansion:r.queryExpansion,queryExpansionExtension:r.queryExpansionExtension,rerank:r.rerank,rerankExtension:r.rerankExtension,warnings:i,settings:r.settings});a=Bc(l,f,o,i)}return{effectiveMode:r.effectiveMode,hits:a}}catch(c){return i.push(dr(r.effectiveMode,c)),{effectiveMode:"keyword",hits:o}}}function Qi(e){e.searchOptions.after!==void 0&&fn(e.searchOptions.after,Yt(e))}async function Yi(e,t,r){Wi(t);let n=Bi(e,t),o=await qc(n,r),i=await Nc(n,o),s=i.warnings;s.push(...n.inlineWarnings);let a=await Ho(i.allDocuments.map(E=>E.metadata),{pmRoot:o.pmRoot,statusRegistry:o.statusRegistry,now:S()});s.push(...a.warnings);let d=Oo(a,n.query);o.effectiveMode==="hybrid"&&o.semanticWeightProvided&&o.semanticWeightOverride===void 0&&s.push("search_hybrid_semantic_weight_override_invalid:using_settings_default");let l={query:n.query,modeSource:o.modeSource,matchMode:n.matchMode,options:n.options,includeLinked:n.includeLinked,titleExact:n.titleExact,phraseExact:n.phraseExact,scoreThreshold:o.scoreThreshold,hybridSemanticWeight:o.hybridSemanticWeight,queryExpansion:o.queryExpansion,rerank:o.rerank,projection:n.projection,warnings:s,runtimeFieldFilters:o.runtimeFieldFilters};if(o.effectiveMode==="keyword"&&(i.filteredDocuments.length===0||n.limit===0&&!n.countOnly))return Qi({query:n.query,mode:o.effectiveMode,searchOptions:n.options,pmRoot:o.pmRoot}),be(Fr({...l,effectiveMode:o.effectiveMode},n.countOnly),d);let c=await $c(n,o,i.filteredDocuments),u=await zc({prepared:n,runtime:o,filteredDocuments:i.filteredDocuments,keywordHits:c,warnings:s,modeWasExplicit:n.modeWasExplicit});if(u.effectiveMode!=="keyword"&&u.hits.length===0&&(i.filteredDocuments.length===0||n.limit===0&&!n.countOnly))return Qi({query:n.query,mode:u.effectiveMode,searchOptions:n.options,pmRoot:o.pmRoot}),be(Fr({...l,effectiveMode:u.effectiveMode},n.countOnly),d);let m=u.hits.filter(E=>E.exact_id_match===!0||E.score>=o.scoreThreshold),f=ar(m,o.statusRegistry),_=f.length,y=vi({pmRoot:o.pmRoot,sorted:f,query:n.query,mode:u.effectiveMode,searchOptions:n.options,limit:n.limit??o.maxResults}),g={...l,effectiveMode:u.effectiveMode};if(n.countOnly)return be(zi(g,_),d);let{hits:w,projection:v}=Vi(n,i.filteredDocuments,y.limited),b=Mr(w,v);return be(Ki(g,b,_,y.limited.length,v,y.pageExtras),d)}var Xi=["ndcg","mrr","precision","recall"];function Hr(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("Eval minimum must be an object of metric floors");let t={};for(let[r,n]of Object.entries(e)){if(!Xi.some(o=>o===r))throw new TypeError(`Unknown eval minimum metric: ${r}`);if(typeof n!="number"||!Number.isFinite(n)||n<0||n>1)throw new TypeError(`Eval minimum.${r} must be a finite number in [0, 1]`);t[r]=n}return t}function Ji(e,t){let r=Hr(t),n=[];for(let o of Xi){let i=r[o];if(i===void 0)continue;let s=e[o];!Number.isFinite(s)||s<0||s>1?n.push(`${o}:invalid`):s<i&&n.push(`${o}:${s}<${i}`)}return n}var es=10,U="https://schema.unbrained.dev/pm/eval-query-set/v1",Vc={schema:U,accepted_top_level:["array","object"],required_query_fields:["query","relevant_ids"],optional_fields:["mode","description","minimum"],modes:["keyword","semantic","hybrid"]},dt={schema:U,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},M=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},Kc=new Set(["keyword","semantic","hybrid"]);function Zi(e,t){let r=0,n=Math.min(t,e.length);for(let o=0;o<n;o+=1)r+=e[o]/Math.log2(o+2);return r}function Qc(e,t,r){if(t.size===0)return 0;let n=e.map(a=>t.has(a)?1:0),o=Zi(n,r),i=Array.from({length:t.size},()=>1),s=Zi(i,r);return s===0?0:o/s}function Yc(e,t,r){let n=Math.min(r,e.length);for(let o=0;o<n;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function Or(e,t,r){let n=Math.min(r,e.length),o=0;for(let i=0;i<n;i+=1)t.has(e[i])&&(o+=1);return o}function Xc(e,t,r){return r<=0?0:Or(e,t,r)/r}function Jc(e,t,r){return t.size===0?0:Or(e,t,r)/t.size}function ts(e,t,r){return{ndcg:Qc(e,t,r),mrr:Yc(e,t,r),precision:Xc(e,t,r),recall:Jc(e,t,r),relevant_total:t.size,retrieved_relevant:Or(e,t,r)}}function rs(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let r=e.reduce((n,o)=>({ndcg:n.ndcg+o.ndcg,mrr:n.mrr+o.mrr,precision:n.precision+o.precision,recall:n.recall+o.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:r.ndcg/t,mrr:r.mrr/t,precision:r.precision/t,recall:r.recall/t,query_count:t}}function Zc(e,t){if(typeof e!="object"||e===null)throw new M(`Eval query at index ${t} must be an object`);let r=e,n=typeof r.query=="string"?r.query.trim():"";if(n.length===0)throw new M(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(r.relevant_ids))throw new M(`Eval query at index ${t} must have a "relevant_ids" array`);if(r.relevant_ids.some(i=>typeof i!="string"))throw new M(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(r.relevant_ids.map(i=>i.trim()).filter(i=>i.length>0))];if(o.length===0)throw new M(`Eval query at index ${t} must list at least one relevant id`);if(r.mode!==void 0&&(typeof r.mode!="string"||!Kc.has(r.mode)))throw new M(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:n,relevant_ids:o,...r.minimum===void 0?{}:{minimum:Hr(r.minimum)},...r.mode!==void 0?{mode:r.mode}:{},...typeof r.description=="string"&&r.description.trim().length>0?{description:r.description.trim()}:{}}}function Lr(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==U)throw new M(`Unsupported eval query set schema; expected "${U}"`);let r=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(r))throw new M('Eval query set must be an array of queries or an object with a "queries" array');if(r.length===0)throw new M("Eval query set must contain at least one query");return{schema:U,queries:r.map((n,o)=>Zc(n,o))}}import ed from"node:fs/promises";import jr from"node:path";var td=jr.join("search","eval-queries.json"),qr={schema:U,examples:[JSON.stringify(dt)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},rd=new Set(["keyword","semantic","hybrid"]),nd=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!rd.has(t))throw new p("Eval --mode must be one of keyword|semantic|hybrid",h.USAGE);return t},od=e=>{if(e===void 0||e==="")return es;let t=ke(e);if(t===null)throw new p("Eval --k must be a positive integer",h.USAGE);return t},id=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),r=Number(t);if([t.length===0,!Number.isFinite(r),r<0,r>1].includes(!0))throw new p("Eval --fail-under must be a number in the range [0, 1]",h.USAGE);return r},G=e=>Math.round(e*1e4)/1e4,sd=async e=>{try{return await ed.readFile(e,"utf8")}catch{throw new p(`Eval query set not found at ${e}`,h.NOT_FOUND,{...qr,examples:[`echo '${JSON.stringify(dt)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},ad=(e,t)=>{try{return JSON.parse(e)}catch(r){throw new p(`Eval query set at ${t} is not valid JSON: ${r instanceof Error?r.message:String(r)}`,h.USAGE,qr)}},cd=e=>{try{return Lr(e)}catch(t){throw new p(t instanceof Error?t.message:String(t),h.USAGE,qr)}},dd=async e=>cd(ad(await sd(e),e)),ld=async(e,t,r,n)=>{let o=e.mode??t,s=(await Yi(e.query,{mode:o,limit:String(r),fields:"id"},n)).items.map(d=>d.id).filter(d=>typeof d=="string"),a=ts(s,new Set(e.relevant_ids),r);return{metrics:a,report:{query:e.query,...e.minimum===void 0?{}:{violations:Ji(a,e.minimum)},mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:G(a.ndcg),mrr:G(a.mrr),precision:G(a.precision),recall:G(a.recall)}}},ud=(e,t,r,n)=>{let o=rs(r);return{k:e,query_count:t.length,aggregate:{ndcg:G(o.ndcg),mrr:G(o.mrr),precision:G(o.precision),recall:G(o.recall)},queries:t,...n!==void 0?{fail_under:n}:{},passed:(n===void 0||o.ndcg>=n)&&t.every(i=>(i.violations?.length??0)===0)}},th=async(e,t)=>{let r=k(process.cwd(),t.path);await O(r);let n=od(e.k),o=nd(e.mode),i=id(e.failUnder),s=e.queries?jr.resolve(process.cwd(),e.queries):jr.join(r,td),a=await dd(s),d=[],l=[];for(let c of a.queries){let{report:u,metrics:m}=await ld(c,o,n,t);l.push(m),d.push(u)}return ud(n,d,l,i)};export{ws as a,Es as b,Hd as c,Od as d,el as e,tl as f,Tt as g,Vo as h,Ko as i,Qo as j,Il as k,Yl as l,Kl as m,ru as n,nu as o,ui as p,mi as q,fi as r,ha as s,Qe as t,Cu as u,Mu as v,Nu as w,Wt as x,zt as y,Vt as z,Kt as A,Qt as B,Yt as C,vi as D,Y as E,et as F,ot as G,it as H,ji as I,qi as J,qf as K,Yi as L,Xi as M,Hr as N,Ji as O,U as P,Vc as Q,dt as R,Lr as S,td as T,th as U};
6
+ //# sourceMappingURL=chunk-WWTPNIC2.js.map
@@ -0,0 +1,2 @@
1
+ import{da as g,ea as i,fa as v,ga as _}from"./chunk-YW2HBHRO.js";import{da as w}from"./chunk-FXJYZBWV.js";import u from"node:fs/promises";import c from"node:path";function f(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function b(e){return e!=="invalid"&&e!=="unreadable"}function j(e){let r=JSON.parse(e);if(typeof r!="object"||r===null||Array.isArray(r))throw new SyntaxError("Invalid settings object");let t=r.extensions;if(t===void 0)return{enabled:[],disabled:[]};if(typeof t!="object"||t===null||Array.isArray(t))throw new SyntaxError("Invalid extensions settings");let n=t;if(n.enabled!==void 0&&(!Array.isArray(n.enabled)||!n.enabled.every(a=>typeof a=="string"))||n.disabled!==void 0&&(!Array.isArray(n.disabled)||!n.disabled.every(a=>typeof a=="string")))throw new SyntaxError("Invalid extension enablement lists");return{enabled:n.enabled??[],disabled:n.disabled??[]}}async function S(e){let r;try{r=await u.readFile(e,"utf8")}catch(t){return f(t)?{status:"absent",enabled:[],disabled:[]}:{status:"unreadable",enabled:[],disabled:[],error:{code:"settings_unreadable",path:e}}}try{return{status:"ok",...j(r)}}catch{return{status:"invalid",enabled:[],disabled:[],error:{code:"settings_invalid",path:e}}}}async function A(e){let r;try{r=await u.readFile(e,"utf8")}catch(t){if(f(t))try{if((await u.stat(c.dirname(e))).isDirectory())return{status:"absent",entries:[]}}catch(n){if(f(n))return{status:"absent",entries:[]}}return{status:"unreadable",entries:[],error:{code:"managed_state_unreadable",path:e}}}try{let t=JSON.parse(r),n=_(t);if(!n||typeof t!="object"||t===null||!Array.isArray(t.entries)||n.entries.length!==t.entries.length)throw new SyntaxError("Invalid managed extension state");return{status:"ok",entries:n.entries}}catch{return{status:"invalid",entries:[],error:{code:"managed_state_invalid",path:e}}}}async function M(e){try{return{directories:(await u.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>t.localeCompare(n))}}catch(r){return f(r)?{directories:[]}:{directories:[],error:{code:"extensions_unreadable",path:e}}}}async function N(e){let r;try{r=await u.readFile(e,"utf8")}catch(t){return f(t)?{manifest:null,error:{code:"manifest_invalid",path:e}}:{manifest:null,error:{code:"manifest_unreadable",path:e}}}try{let t=v(JSON.parse(r));return t?{manifest:t}:{manifest:null,error:{code:"manifest_invalid",path:e}}}catch{return{manifest:null,error:{code:"manifest_invalid",path:e}}}}function z(e){let r=e.manifest?.name??e.directory,t=new Set(g(e.settings.enabled)),n=new Set(g(e.settings.disabled)),a=!b(e.settings.status)||!e.manifest?null:!n.has(r)&&(t.size===0||t.has(r)),o=b(e.managed.status)?e.managed.entries.some(d=>i(d.name)===i(r)||i(d.directory)===i(e.directory)):null;return{name:r,directory:e.directory,scope:e.scope,installed:!0,status:e.manifest?a===!1?"inactive":"installed":"malformed_manifest",configured_enabled:a,managed:o,runtime_active:null,...e.manifest?{version:e.manifest.version}:{}}}async function J(e){let r=e.scope??"project",t=r==="global"?w(e.cwd??process.cwd()):e.pmRoot,n=c.join(t,"extensions"),a=await S(c.join(t,"settings.json")),o=await A(c.join(n,".managed-extensions.json")),d=await M(n),l=[];for(let s of[a,o,d])s.error&&l.push(s.error);let m=e.name?.trim(),y=[];for(let s of d.directories){let x=c.join(n,s,"manifest.json"),p=await N(x);p.error&&l.push(p.error);let h=z({directory:s,scope:r,manifest:p.manifest,settings:a,managed:o});m&&![h.name,s].some(E=>i(E)===i(m))||y.push(h)}return m&&y.length===0&&l.every(s=>s.code!=="extensions_unreadable")&&y.push({name:m,directory:null,scope:r,installed:!1,status:"absent",configured_enabled:b(a.status)?!1:null,managed:b(o.status)?!1:null,runtime_active:null}),{scope:r,complete:l.length===0,settings_status:a.status,managed_state_status:o.status,extensions:y,errors:l}}export{J as a};
2
+ //# sourceMappingURL=chunk-XFADNMGD.js.map