@unbrained/pm-cli 2026.11.22 → 2026.11.23

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 (892) 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-2UQU7HRR.js +9 -0
  105. package/dist/cli-bundle/chunks/chunk-5DUP4AZA.js +2 -0
  106. package/dist/cli-bundle/chunks/chunk-5WZZ5XEN.js +3 -0
  107. package/dist/cli-bundle/chunks/chunk-6H36ZHMI.js +2 -0
  108. package/dist/cli-bundle/chunks/chunk-6MYJLOSG.js +2 -0
  109. package/dist/cli-bundle/chunks/chunk-AA52P34H.js +3 -0
  110. package/dist/cli-bundle/chunks/{chunk-B76TFRO2.js → chunk-AEOHUSUI.js} +101 -101
  111. package/dist/cli-bundle/chunks/chunk-BSRIVYTM.js +8 -0
  112. package/dist/cli-bundle/chunks/chunk-CFWLQFJM.js +71 -0
  113. package/dist/cli-bundle/chunks/chunk-D6PDUKUG.js +9 -0
  114. package/dist/cli-bundle/chunks/chunk-ENKXRSFZ.js +31 -0
  115. package/dist/cli-bundle/chunks/chunk-F2Z6XLZB.js +3 -0
  116. package/dist/cli-bundle/chunks/chunk-FJOEL75F.js +2 -0
  117. package/dist/cli-bundle/chunks/chunk-GDXCAC52.js +2 -0
  118. package/dist/cli-bundle/chunks/chunk-H7JEXRIN.js +6 -0
  119. package/dist/cli-bundle/chunks/chunk-J2PDAVBC.js +2 -0
  120. package/dist/cli-bundle/chunks/chunk-KE7HMBEW.js +2 -0
  121. package/dist/cli-bundle/chunks/chunk-KZHIBEJL.js +33 -0
  122. package/dist/cli-bundle/chunks/chunk-NGJ5ERBF.js +115 -0
  123. package/dist/cli-bundle/chunks/chunk-NQ54T7T2.js +2 -0
  124. package/dist/cli-bundle/chunks/chunk-O7JHS64G.js +3 -0
  125. package/dist/cli-bundle/chunks/chunk-OKEZF7HU.js +2 -0
  126. package/dist/cli-bundle/chunks/chunk-OKIKF4FD.js +2 -0
  127. package/dist/cli-bundle/chunks/chunk-OPJF254V.js +9 -0
  128. package/dist/cli-bundle/chunks/chunk-PZA7QECY.js +1 -0
  129. package/dist/cli-bundle/chunks/chunk-RWA5YZ5X.js +2 -0
  130. package/dist/cli-bundle/chunks/chunk-S32NGRQM.js +2 -0
  131. package/dist/cli-bundle/chunks/chunk-SLFRSZK6.js +1 -0
  132. package/dist/cli-bundle/chunks/chunk-TZY5MVJF.js +125 -0
  133. package/dist/cli-bundle/chunks/chunk-YYT3MIRF.js +3 -0
  134. package/dist/cli-bundle/chunks/chunk-ZPS4B6SI.js +8 -0
  135. package/dist/cli-bundle/chunks/context-budget-recovery-M5RFUEFG.js +2 -0
  136. package/dist/cli-bundle/chunks/indexed-receipt-blobs-BPYKN5Q7.js +4 -0
  137. package/dist/cli-bundle/chunks/{item-revision-4QBMZXKX.js → item-revision-FMD4KWBB.js} +2 -2
  138. package/dist/cli-bundle/chunks/item-transaction-SEHTH7N2.js +2 -0
  139. package/dist/cli-bundle/chunks/mutation-actor-SFGYIRPW.js +2 -0
  140. package/dist/cli-bundle/chunks/mutation-admission-57LBSKQI.js +2 -0
  141. package/dist/cli-bundle/chunks/{register-list-query-RR5KACJ3.js → register-list-query-L4IBU64P.js} +11 -11
  142. package/dist/cli-bundle/chunks/register-mutation-6NUOPHZ3.js +21 -0
  143. package/dist/cli-bundle/chunks/register-operations-JGYVORNN.js +2 -0
  144. package/dist/cli-bundle/chunks/register-setup-C44SIXEH.js +2 -0
  145. package/dist/cli-bundle/chunks/settlement-hook-6MR32OOC.js +7 -0
  146. package/dist/cli-bundle/chunks/stage-PQ7AB63N.js +2 -0
  147. package/dist/cli-bundle/focused-chunks/chunk-6LKTEKHS.js +6 -0
  148. package/dist/cli-bundle/focused-chunks/chunk-6LPXMFLM.js +2 -0
  149. package/dist/cli-bundle/focused-chunks/chunk-A6VEMCRR.js +3 -0
  150. package/dist/cli-bundle/focused-chunks/chunk-AIDL2ZNT.js +3 -0
  151. package/dist/cli-bundle/focused-chunks/chunk-BKPUUW5O.js +1 -0
  152. package/dist/cli-bundle/focused-chunks/chunk-BWOVFE5B.js +2 -0
  153. package/dist/cli-bundle/focused-chunks/chunk-HMDQDRV2.js +8 -0
  154. package/dist/cli-bundle/focused-chunks/chunk-I66IKYKP.js +2 -0
  155. package/dist/cli-bundle/focused-chunks/chunk-IIP6LZ5E.js +2 -0
  156. package/dist/cli-bundle/focused-chunks/chunk-IR2J3NOT.js +2 -0
  157. package/dist/cli-bundle/focused-chunks/chunk-IROZDIDX.js +3 -0
  158. package/dist/cli-bundle/focused-chunks/chunk-ITKDHSBR.js +2 -0
  159. package/dist/cli-bundle/focused-chunks/chunk-K53OIT5J.js +2 -0
  160. package/dist/cli-bundle/focused-chunks/chunk-LQYYPXUK.js +26 -0
  161. package/dist/cli-bundle/focused-chunks/chunk-NQTEE66P.js +13 -0
  162. package/dist/cli-bundle/focused-chunks/chunk-O7Z73ALG.js +2 -0
  163. package/dist/cli-bundle/focused-chunks/chunk-OTMMOKPM.js +91 -0
  164. package/dist/cli-bundle/focused-chunks/chunk-OXOCZJC6.js +2 -0
  165. package/dist/cli-bundle/focused-chunks/chunk-QLAHEDT6.js +2 -0
  166. package/dist/cli-bundle/focused-chunks/chunk-QQIIMMFU.js +2 -0
  167. package/dist/cli-bundle/focused-chunks/chunk-RIE3SJSE.js +9 -0
  168. package/dist/cli-bundle/focused-chunks/chunk-TD544C74.js +8 -0
  169. package/dist/cli-bundle/focused-chunks/chunk-UFTUNBMY.js +27 -0
  170. package/dist/cli-bundle/focused-chunks/chunk-X6CXWWNB.js +2 -0
  171. package/dist/cli-bundle/focused-chunks/chunk-XRS3VNC6.js +44 -0
  172. package/dist/cli-bundle/focused-chunks/chunk-XYPEZGTR.js +2 -0
  173. package/dist/cli-bundle/focused-chunks/chunk-Y2ESLKCF.js +8 -0
  174. package/dist/cli-bundle/focused-chunks/chunk-YSJKQLFR.js +2 -0
  175. package/dist/cli-bundle/focused-chunks/chunk-Z2X7HH3C.js +102 -0
  176. package/dist/cli-bundle/focused-chunks/chunk-ZHWPCVQL.js +78 -0
  177. package/dist/cli-bundle/focused-chunks/context-budget-recovery-CSJV3TY3.js +2 -0
  178. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-EGEJMG3G.js +4 -0
  179. package/dist/cli-bundle/focused-chunks/{item-revision-2O6MLPEX.js → item-revision-YDACCDVY.js} +2 -2
  180. package/dist/cli-bundle/focused-chunks/item-transaction-UKEQCTKB.js +2 -0
  181. package/dist/cli-bundle/focused-chunks/mutation-actor-AS465LRX.js +2 -0
  182. package/dist/cli-bundle/focused-chunks/mutation-admission-E5UHJZFE.js +2 -0
  183. package/dist/cli-bundle/focused-chunks/settlement-hook-FMLGKG7J.js +7 -0
  184. package/dist/cli-bundle/focused-chunks/stage-36J7YLGI.js +2 -0
  185. package/dist/cli-bundle/main.js +27 -27
  186. package/dist/cli-bundle/sdk-authoring.js +1 -1
  187. package/dist/cli-bundle/sdk-contracts.js +5 -5
  188. package/dist/cli-bundle/sdk-core.js +1 -1
  189. package/dist/cli-bundle/sdk-governance.js +1 -1
  190. package/dist/cli-bundle/sdk-graph.js +1 -1
  191. package/dist/cli-bundle/sdk-merge.js +66 -66
  192. package/dist/cli-bundle/sdk-query.js +1 -1
  193. package/dist/cli-bundle/sdk-runtime.js +1 -1
  194. package/dist/cli-bundle/sdk-testing.js +1 -1
  195. package/dist/cli-bundle/sdk.js +12 -12
  196. package/dist/cli.js +1 -1
  197. package/dist/core/checkpoint/checkpoint-gc.js +1 -1
  198. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  199. package/dist/core/checkpoint/mutation-context.js +1 -1
  200. package/dist/core/config/nested-settings.js +1 -1
  201. package/dist/core/config/positional-value.js +1 -1
  202. package/dist/core/diagnostics/remediation.js +1 -1
  203. package/dist/core/extensions/activation-summary-markdown.js +2 -2
  204. package/dist/core/extensions/activation-summary.js +1 -1
  205. package/dist/core/extensions/activation-transaction.js +1 -1
  206. package/dist/core/extensions/capability-usage.js +1 -1
  207. package/dist/core/extensions/command-hook-context.js +1 -1
  208. package/dist/core/extensions/command-metadata-contract.js +1 -1
  209. package/dist/core/extensions/command-visibility-tier.js +1 -1
  210. package/dist/core/extensions/contribution-inventory.js +1 -1
  211. package/dist/core/extensions/exporter-output-contract.js +1 -1
  212. package/dist/core/extensions/extension-candidate.js +1 -1
  213. package/dist/core/extensions/extension-capability-aliases.js +1 -1
  214. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  215. package/dist/core/extensions/extension-policy.js +1 -1
  216. package/dist/core/extensions/extension-registries.js +1 -1
  217. package/dist/core/extensions/extension-runtime-helpers.js +1 -1
  218. package/dist/core/extensions/extension-types.js +1 -1
  219. package/dist/core/extensions/flag-definition-validation.js +1 -1
  220. package/dist/core/extensions/flag-value-types.js +1 -1
  221. package/dist/core/extensions/index.js +1 -1
  222. package/dist/core/extensions/item-field-types.js +1 -1
  223. package/dist/core/extensions/item-fields.js +1 -1
  224. package/dist/core/extensions/loader.js +1 -1
  225. package/dist/core/extensions/manifest-parser.js +1 -1
  226. package/dist/core/extensions/manifest-schema.js +1 -1
  227. package/dist/core/extensions/module-graph-snapshot.js +1 -1
  228. package/dist/core/extensions/mutation-actor-snapshot.js +1 -1
  229. package/dist/core/extensions/mutation-actor.js +1 -1
  230. package/dist/core/extensions/preflight-ownership.js +1 -1
  231. package/dist/core/extensions/read-output-contract.js +1 -1
  232. package/dist/core/extensions/registration-contracts.js +1 -1
  233. package/dist/core/extensions/registration-validation.js +1 -1
  234. package/dist/core/extensions/registration-values.js +1 -1
  235. package/dist/core/extensions/reserved-host-flags.js +1 -1
  236. package/dist/core/extensions/runtime-registrations.js +1 -1
  237. package/dist/core/extensions/service-ownership.js +1 -1
  238. package/dist/core/extensions/version-compat.js +1 -1
  239. package/dist/core/extensions/version-diagnostics.js +1 -1
  240. package/dist/core/fs/atomic-create.js +1 -1
  241. package/dist/core/fs/file-glob.js +1 -1
  242. package/dist/core/fs/fs-utils.js +2 -2
  243. package/dist/core/fs/host-environment-errors.js +1 -1
  244. package/dist/core/fs/index.js +1 -1
  245. package/dist/core/fs/path-utils.js +1 -1
  246. package/dist/core/governance/content-fields.js +1 -1
  247. package/dist/core/governance/issue-codes.js +1 -1
  248. package/dist/core/governance/metadata-coverage.js +1 -1
  249. package/dist/core/history/bridge.js +1 -1
  250. package/dist/core/history/digest.js +1 -1
  251. package/dist/core/history/drift-cache.js +3 -3
  252. package/dist/core/history/drift-scan.js +1 -1
  253. package/dist/core/history/event-classification.js +1 -1
  254. package/dist/core/history/event-index.js +11 -11
  255. package/dist/core/history/history-compact-bulk.js +1 -1
  256. package/dist/core/history/history-diff.js +1 -1
  257. package/dist/core/history/history-rewrite.js +1 -1
  258. package/dist/core/history/history-storage-stats.js +1 -1
  259. package/dist/core/history/history-stream-policy.js +1 -1
  260. package/dist/core/history/history.js +2 -2
  261. package/dist/core/history/identity.js +1 -1
  262. package/dist/core/history/index.js +1 -1
  263. package/dist/core/history/operation-contract.js +1 -1
  264. package/dist/core/history/projection.js +1 -1
  265. package/dist/core/history/read.js +1 -1
  266. package/dist/core/history/replay.js +2 -2
  267. package/dist/core/history/stream-summary.js +2 -2
  268. package/dist/core/history/tombstone.js +1 -1
  269. package/dist/core/history/version-address.js +1 -1
  270. package/dist/core/history/workspace-history.js +2 -2
  271. package/dist/core/io/body-file.js +1 -1
  272. package/dist/core/io/bulk-ids-input.js +2 -2
  273. package/dist/core/item/actionability.js +1 -1
  274. package/dist/core/item/deferred-fields.js +1 -1
  275. package/dist/core/item/dependency-reference.js +1 -1
  276. package/dist/core/item/id.js +1 -1
  277. package/dist/core/item/index.js +1 -1
  278. package/dist/core/item/item-format-version.js +1 -1
  279. package/dist/core/item/item-format.js +7 -7
  280. package/dist/core/item/item-record.js +1 -1
  281. package/dist/core/item/item-type-definition.js +1 -1
  282. package/dist/core/item/literal-mutation-input.js +1 -1
  283. package/dist/core/item/parent-reference-policy.js +1 -1
  284. package/dist/core/item/parse.js +8 -8
  285. package/dist/core/item/plan-lifecycle.js +1 -1
  286. package/dist/core/item/priority.js +1 -1
  287. package/dist/core/item/sprint-release-format.js +1 -1
  288. package/dist/core/item/status-filter.js +1 -1
  289. package/dist/core/item/status.js +1 -1
  290. package/dist/core/item/toon-decode.js +1 -1
  291. package/dist/core/item/type-registry.js +1 -1
  292. package/dist/core/item/type-synonyms.js +1 -1
  293. package/dist/core/lock/index.js +1 -1
  294. package/dist/core/lock/lock-confinement.js +1 -1
  295. package/dist/core/lock/lock-gc.js +1 -1
  296. package/dist/core/lock/lock-owner.js +1 -1
  297. package/dist/core/lock/lock.js +4 -4
  298. package/dist/core/output/linked-test-projection.js +5 -5
  299. package/dist/core/output/mutation-projection.js +1 -1
  300. package/dist/core/output/output-control.js +1 -1
  301. package/dist/core/output/output.js +19 -19
  302. package/dist/core/output/query-summary.js +1 -1
  303. package/dist/core/output/tabular.js +3 -3
  304. package/dist/core/packages/manifest.js +1 -1
  305. package/dist/core/packages/root.js +1 -1
  306. package/dist/core/policy/workflow-policy-schema.js +1 -1
  307. package/dist/core/policy/workflow-policy-store.js +1 -1
  308. package/dist/core/policy/workflow-policy.js +1 -1
  309. package/dist/core/profile/profile-describe.js +1 -1
  310. package/dist/core/profile/profile-lint.d.ts +1 -1
  311. package/dist/core/profile/profile-lint.js +1 -1
  312. package/dist/core/profile/profile-plan.js +1 -1
  313. package/dist/core/profile/profile-presets.js +4 -4
  314. package/dist/core/reproducibility/context.js +1 -1
  315. package/dist/core/schema/fields-file.js +2 -2
  316. package/dist/core/schema/item-types-file.js +2 -2
  317. package/dist/core/schema/runtime-field-filters.js +1 -1
  318. package/dist/core/schema/runtime-field-values.js +1 -1
  319. package/dist/core/schema/runtime-schema.js +2 -2
  320. package/dist/core/schema/status-defs-file.js +2 -2
  321. package/dist/core/schema/status-token.js +1 -1
  322. package/dist/core/schema/type-inference.js +1 -1
  323. package/dist/core/schema/type-presets.js +1 -1
  324. package/dist/core/schema/type-workflows.js +1 -1
  325. package/dist/core/search/background-refresh.js +2 -2
  326. package/dist/core/search/bm25.js +1 -1
  327. package/dist/core/search/cache.js +2 -2
  328. package/dist/core/search/corpus.js +1 -1
  329. package/dist/core/search/embedding-batches.js +1 -1
  330. package/dist/core/search/eval-thresholds.js +1 -1
  331. package/dist/core/search/eval.js +1 -1
  332. package/dist/core/search/http-client.js +1 -1
  333. package/dist/core/search/providers.js +1 -1
  334. package/dist/core/search/relevance.js +1 -1
  335. package/dist/core/search/semantic-defaults.js +1 -1
  336. package/dist/core/search/staleness.js +1 -1
  337. package/dist/core/search/vector-stores.js +2 -2
  338. package/dist/core/search/vectorization-metadata.js +1 -1
  339. package/dist/core/sentry/helpers.js +1 -1
  340. package/dist/core/sentry/instrument.js +1 -1
  341. package/dist/core/sentry/sensitive-assignments.js +1 -1
  342. package/dist/core/session/session-state.js +1 -1
  343. package/dist/core/shared/agent-session-context.js +1 -1
  344. package/dist/core/shared/author.js +5 -5
  345. package/dist/core/shared/command-line.js +1 -1
  346. package/dist/core/shared/command-types.js +0 -1
  347. package/dist/core/shared/conflict-markers.js +1 -1
  348. package/dist/core/shared/constants.js +1 -1
  349. package/dist/core/shared/error-details.js +1 -1
  350. package/dist/core/shared/errors.js +1 -1
  351. package/dist/core/shared/html-entity-decode.js +1 -1
  352. package/dist/core/shared/index.js +1 -1
  353. package/dist/core/shared/item-metadata-contract.js +1 -1
  354. package/dist/core/shared/lazy-module.js +1 -1
  355. package/dist/core/shared/levenshtein.js +1 -1
  356. package/dist/core/shared/memo.js +1 -1
  357. package/dist/core/shared/numeric-parsers.js +1 -1
  358. package/dist/core/shared/option-alias-visibility.js +1 -1
  359. package/dist/core/shared/output-unicode.js +1 -1
  360. package/dist/core/shared/primitives.js +1 -1
  361. package/dist/core/shared/process-tree.js +2 -2
  362. package/dist/core/shared/secret-rules.js +5 -5
  363. package/dist/core/shared/serial-queue.js +1 -1
  364. package/dist/core/shared/serialization.js +1 -1
  365. package/dist/core/shared/split-comma-list.js +1 -1
  366. package/dist/core/shared/text-normalization.js +1 -1
  367. package/dist/core/shared/time.js +2 -2
  368. package/dist/core/shared/url-credentials.js +1 -1
  369. package/dist/core/store/index.js +1 -1
  370. package/dist/core/store/item-format-migration.js +1 -1
  371. package/dist/core/store/item-metadata-cache.js +1 -1
  372. package/dist/core/store/item-metadata-query-index.js +11 -11
  373. package/dist/core/store/item-metadata-read-work.js +1 -1
  374. package/dist/core/store/item-mutation-precondition.js +1 -1
  375. package/dist/core/store/item-store.js +1 -1
  376. package/dist/core/store/paths.js +1 -1
  377. package/dist/core/store/settings-concurrency.js +1 -1
  378. package/dist/core/store/settings-read-cache.js +1 -1
  379. package/dist/core/store/settings-sections.js +2 -2
  380. package/dist/core/store/settings-validator.js +1 -1
  381. package/dist/core/store/settings.d.ts +3 -1
  382. package/dist/core/store/settings.js +6 -6
  383. package/dist/core/store/sqlite-runtime.js +1 -1
  384. package/dist/core/store/tracker-preflight.js +1 -1
  385. package/dist/core/store/transaction-coordinator-scope.js +1 -1
  386. package/dist/core/telemetry/consent.js +3 -3
  387. package/dist/core/telemetry/observability.js +1 -1
  388. package/dist/core/telemetry/policy.js +1 -1
  389. package/dist/core/telemetry/read-sampling.js +2 -2
  390. package/dist/core/telemetry/runtime.js +9 -9
  391. package/dist/core/test/background-runs.js +4 -4
  392. package/dist/core/test/item-test-run-tracking.js +1 -1
  393. package/dist/core/test/run-selectors.js +1 -1
  394. package/dist/core/validate/estimate-defaults.js +1 -1
  395. package/dist/core/validate/fix-planning.js +1 -1
  396. package/dist/core/validate/linked-artifact-reference.js +1 -1
  397. package/dist/core/validate/missing-by-type.js +1 -1
  398. package/dist/core/validate/missing-link-owners.js +1 -1
  399. package/dist/core/validate/stale-file-classification.js +1 -1
  400. package/dist/mcp/http-server.js +5 -5
  401. package/dist/mcp/legacy-adapter.js +1 -1
  402. package/dist/mcp/runtime-capabilities.js +1 -1
  403. package/dist/mcp/server.js +4 -4
  404. package/dist/mcp/tool-definitions.js +1 -1
  405. package/dist/sdk/actionability.js +1 -1
  406. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  407. package/dist/sdk/agent/command-recovery.js +1 -1
  408. package/dist/sdk/agent/command-suggestions.js +1 -1
  409. package/dist/sdk/agent/create-option-policy.js +1 -1
  410. package/dist/sdk/agent/identity-config.js +1 -1
  411. package/dist/sdk/agent/item-addressing.js +1 -1
  412. package/dist/sdk/agent/linked-resource-recovery.js +1 -1
  413. package/dist/sdk/agent/refusal-closure-census.js +2 -2
  414. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
  415. package/dist/sdk/agent/subcommand-recovery.js +1 -1
  416. package/dist/sdk/agent-capability-contracts.js +3 -3
  417. package/dist/sdk/agent-session-context.js +1 -1
  418. package/dist/sdk/annotations.js +1 -1
  419. package/dist/sdk/author-attribution.js +1 -1
  420. package/dist/sdk/cli-bootstrap.js +1 -1
  421. package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -5
  422. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  423. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  424. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
  425. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  426. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  427. package/dist/sdk/cli-contracts/completeness.js +1 -1
  428. package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
  429. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  430. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -2
  431. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  432. package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
  433. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  434. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
  435. package/dist/sdk/cli-contracts/string-lists.js +1 -1
  436. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  437. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  438. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  439. package/dist/sdk/cli-contracts/typed-action-inputs.js +0 -1
  440. package/dist/sdk/cli-contracts.js +1 -1
  441. package/dist/sdk/cli-program.js +1 -1
  442. package/dist/sdk/command-line.js +1 -1
  443. package/dist/sdk/comments.js +1 -1
  444. package/dist/sdk/compile-cache.js +1 -1
  445. package/dist/sdk/completion/bash.js +2 -2
  446. package/dist/sdk/completion/fish.js +72 -72
  447. package/dist/sdk/completion/shared.js +1 -1
  448. package/dist/sdk/completion/zsh.js +75 -75
  449. package/dist/sdk/completion.js +1 -1
  450. package/dist/sdk/config.js +1 -1
  451. package/dist/sdk/context/recency.js +1 -1
  452. package/dist/sdk/context/semantic-session-attribution.js +1 -1
  453. package/dist/sdk/context/usage-egress.js +1 -1
  454. package/dist/sdk/context/usage-ledger.js +6 -6
  455. package/dist/sdk/context-intent-contracts.js +1 -1
  456. package/dist/sdk/context-intent-runtime.js +1 -1
  457. package/dist/sdk/context-packing.js +1 -1
  458. package/dist/sdk/context-relevance.js +1 -1
  459. package/dist/sdk/context-signal-store.js +2 -2
  460. package/dist/sdk/context-usage.js +1 -1
  461. package/dist/sdk/dependencies/context-budget-recovery.js +1 -1
  462. package/dist/sdk/dependencies.js +1 -1
  463. package/dist/sdk/dependency-flag-validation.js +1 -1
  464. package/dist/sdk/dependency-provenance.js +1 -1
  465. package/dist/sdk/docs.js +1 -1
  466. package/dist/sdk/duplicates.js +1 -1
  467. package/dist/sdk/environment/host-environment-errors.js +1 -1
  468. package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
  469. package/dist/sdk/environment/source-context.js +1 -1
  470. package/dist/sdk/environment/tracker-preflight.js +1 -1
  471. package/dist/sdk/error-code-catalog.js +1 -1
  472. package/dist/sdk/error-runtime.js +1 -1
  473. package/dist/sdk/errors.js +1 -1
  474. package/dist/sdk/eval.js +1 -1
  475. package/dist/sdk/extension/author-manifest.js +1 -1
  476. package/dist/sdk/extension/bundled-catalog.js +1 -1
  477. package/dist/sdk/extension/command-options.js +1 -1
  478. package/dist/sdk/extension/concurrency.js +1 -1
  479. package/dist/sdk/extension/copy-scope.js +1 -1
  480. package/dist/sdk/extension/custom-field-collisions.js +1 -1
  481. package/dist/sdk/extension/describe.js +3 -3
  482. package/dist/sdk/extension/doctor.js +1 -1
  483. package/dist/sdk/extension/install-plan.js +1 -1
  484. package/dist/sdk/extension/install-receipts.js +1 -1
  485. package/dist/sdk/extension/install-runtime.js +3 -3
  486. package/dist/sdk/extension/install-snapshot.js +1 -1
  487. package/dist/sdk/extension/install-sources.js +5 -5
  488. package/dist/sdk/extension/managed-state.js +2 -2
  489. package/dist/sdk/extension/managed-update-status.js +1 -1
  490. package/dist/sdk/extension/migrations.js +2 -2
  491. package/dist/sdk/extension/native-command-options.js +1 -1
  492. package/dist/sdk/extension/output-ownership.js +1 -1
  493. package/dist/sdk/extension/runtime-summary.js +1 -1
  494. package/dist/sdk/extension/scaffold.js +11 -11
  495. package/dist/sdk/extension/shared.js +1 -1
  496. package/dist/sdk/extension/source-resolution.js +1 -1
  497. package/dist/sdk/extension/static-inventory.js +1 -1
  498. package/dist/sdk/extension/update-check.js +1 -1
  499. package/dist/sdk/extension-command-context.js +2 -2
  500. package/dist/sdk/extension-contracts.js +1 -1
  501. package/dist/sdk/extension.js +1 -1
  502. package/dist/sdk/files.js +1 -1
  503. package/dist/sdk/flag-invocation-contracts.js +1 -1
  504. package/dist/sdk/generated/error-code-catalog-rows.js +1 -1
  505. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  506. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  507. package/dist/sdk/generated-error-code-catalog.js +1 -1
  508. package/dist/sdk/governance/assurance-action-contracts.js +0 -1
  509. package/dist/sdk/governance/assurance-action.js +1 -1
  510. package/dist/sdk/governance/assurance-limits.js +1 -1
  511. package/dist/sdk/governance/assurance-mutation-error.js +1 -1
  512. package/dist/sdk/governance/assurance-presets.js +1 -1
  513. package/dist/sdk/governance/assurance-runtime.js +1 -1
  514. package/dist/sdk/governance/assurance.js +4 -4
  515. package/dist/sdk/governance/boundary-fixtures.js +1 -1
  516. package/dist/sdk/governance/closure-timestamps.js +1 -1
  517. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
  518. package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
  519. package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
  520. package/dist/sdk/governance/defect-recurrence.js +2 -2
  521. package/dist/sdk/governance/extension-host-version.js +1 -1
  522. package/dist/sdk/governance/gc.js +1 -1
  523. package/dist/sdk/governance/health/history-drift-remedies.js +1 -1
  524. package/dist/sdk/governance/health/projection.js +1 -1
  525. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  526. package/dist/sdk/governance/health.js +2 -2
  527. package/dist/sdk/governance/hierarchy-validation.js +1 -1
  528. package/dist/sdk/governance/in-progress-work-health.js +1 -1
  529. package/dist/sdk/governance/lifecycle-dependency-cycles.js +1 -1
  530. package/dist/sdk/governance/linked-file-report.js +1 -1
  531. package/dist/sdk/governance/merge-receipt-history.js +1 -1
  532. package/dist/sdk/governance/provenance-health.js +4 -4
  533. package/dist/sdk/governance/reindex.js +5 -5
  534. package/dist/sdk/governance/stale-work.js +1 -1
  535. package/dist/sdk/governance/status-role-diagnostics.js +1 -1
  536. package/dist/sdk/governance/storage-integrity.js +1 -1
  537. package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
  538. package/dist/sdk/governance/upgrade.js +2 -2
  539. package/dist/sdk/governance/validate-deferred-fields.js +1 -1
  540. package/dist/sdk/governance/validate-history-drift.js +1 -1
  541. package/dist/sdk/governance/validate-item-reader.js +1 -1
  542. package/dist/sdk/governance/validate-normalization.js +1 -1
  543. package/dist/sdk/governance/validate.js +1 -1
  544. package/dist/sdk/governance/workflow-completeness.js +1 -1
  545. package/dist/sdk/governance/workflow-policy.js +3 -3
  546. package/dist/sdk/governance/workspace-position.js +2 -2
  547. package/dist/sdk/graph/analytics.js +1 -1
  548. package/dist/sdk/graph/assembly.js +1 -1
  549. package/dist/sdk/graph/cache.js +1 -1
  550. package/dist/sdk/graph/cardinality-integrity.js +1 -1
  551. package/dist/sdk/graph/centrality.js +1 -1
  552. package/dist/sdk/graph/deadline-scheduling.js +1 -1
  553. package/dist/sdk/graph/durable-cache.js +1 -1
  554. package/dist/sdk/graph/governance-contracts.js +1 -1
  555. package/dist/sdk/graph/governance.js +1 -1
  556. package/dist/sdk/graph/hierarchy-integrity.js +1 -1
  557. package/dist/sdk/graph/lifecycle-coverage.js +1 -1
  558. package/dist/sdk/graph/mutation-advisory.js +1 -1
  559. package/dist/sdk/graph/query-contracts.js +1 -1
  560. package/dist/sdk/graph/remediation.js +1 -1
  561. package/dist/sdk/graph/run.js +1 -1
  562. package/dist/sdk/graph/scheduling.js +1 -1
  563. package/dist/sdk/graph/traversal.js +1 -1
  564. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
  565. package/dist/sdk/guide-topics.js +1 -1
  566. package/dist/sdk/guide.js +7 -7
  567. package/dist/sdk/history/append-only-repair.js +4 -4
  568. package/dist/sdk/history/attestation-command.js +2 -2
  569. package/dist/sdk/history/attestation-contract.js +1 -1
  570. package/dist/sdk/history/attestation-scan.js +1 -1
  571. package/dist/sdk/history/attestation.js +1 -1
  572. package/dist/sdk/history/maintenance.js +1 -1
  573. package/dist/sdk/history/reanchor-refusal.js +1 -1
  574. package/dist/sdk/history/reseed.js +1 -1
  575. package/dist/sdk/history/salvage.js +5 -5
  576. package/dist/sdk/history/subject.js +1 -1
  577. package/dist/sdk/history-analytics.js +1 -1
  578. package/dist/sdk/history-compact.js +1 -1
  579. package/dist/sdk/history-mcp.js +1 -1
  580. package/dist/sdk/history-provenance.js +1 -1
  581. package/dist/sdk/history-read.js +1 -1
  582. package/dist/sdk/history-redact.js +1 -1
  583. package/dist/sdk/history-repair.js +1 -1
  584. package/dist/sdk/improvement-ledger-validation.js +1 -1
  585. package/dist/sdk/improvement-ledger.js +2 -2
  586. package/dist/sdk/init-agent-guidance.js +10 -10
  587. package/dist/sdk/init.js +14 -14
  588. package/dist/sdk/invocation-author.js +1 -1
  589. package/dist/sdk/item-children.js +1 -1
  590. package/dist/sdk/item-metadata-index.js +1 -1
  591. package/dist/sdk/item-schedule.js +1 -1
  592. package/dist/sdk/item-transaction.js +1 -1
  593. package/dist/sdk/learnings.js +1 -1
  594. package/dist/sdk/lifecycle/append.js +3 -3
  595. package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
  596. package/dist/sdk/lifecycle/claim.js +1 -1
  597. package/dist/sdk/lifecycle/cli-input.js +1 -1
  598. package/dist/sdk/lifecycle/close-many.js +1 -1
  599. package/dist/sdk/lifecycle/close.js +1 -1
  600. package/dist/sdk/lifecycle/copy.js +1 -1
  601. package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
  602. package/dist/sdk/lifecycle/core-item-fields.js +1 -1
  603. package/dist/sdk/lifecycle/create-deferrals.js +1 -1
  604. package/dist/sdk/lifecycle/create.js +1 -1
  605. package/dist/sdk/lifecycle/delete.js +1 -1
  606. package/dist/sdk/lifecycle/dependency-removal.js +1 -1
  607. package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
  608. package/dist/sdk/lifecycle/focus.js +1 -1
  609. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
  610. package/dist/sdk/lifecycle/item-revision.js +1 -1
  611. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
  612. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
  613. package/dist/sdk/lifecycle/mcp-actions.js +1 -1
  614. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
  615. package/dist/sdk/lifecycle/mutation-command-options.js +0 -1
  616. package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
  617. package/dist/sdk/lifecycle/mutation-option-validation.js +1 -1
  618. package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
  619. package/dist/sdk/lifecycle/plan.js +1 -1
  620. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
  621. package/dist/sdk/lifecycle/release-handoff.js +1 -1
  622. package/dist/sdk/lifecycle/reopen.js +1 -1
  623. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -2
  624. package/dist/sdk/lifecycle/repeated-terminal-state.js +1 -1
  625. package/dist/sdk/lifecycle/restore.js +1 -1
  626. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  627. package/dist/sdk/lifecycle/start-blockers.js +1 -1
  628. package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
  629. package/dist/sdk/lifecycle/task-composition.js +1 -1
  630. package/dist/sdk/lifecycle/update-many.js +1 -1
  631. package/dist/sdk/lifecycle/update.js +2 -2
  632. package/dist/sdk/lifecycle/workflow-transition.js +1 -1
  633. package/dist/sdk/lifecycle-completion.js +1 -1
  634. package/dist/sdk/lifecycle-policy.js +1 -1
  635. package/dist/sdk/linked-artifacts.js +2 -2
  636. package/dist/sdk/mcp/apps.js +5 -5
  637. package/dist/sdk/mcp/authorization.js +1 -1
  638. package/dist/sdk/mcp/discovery.js +1 -1
  639. package/dist/sdk/mcp/executable.js +4 -4
  640. package/dist/sdk/mcp/interactions.js +1 -1
  641. package/dist/sdk/mcp/protocol.js +1 -1
  642. package/dist/sdk/mcp/skills.js +3 -3
  643. package/dist/sdk/mcp/subscriptions.js +1 -1
  644. package/dist/sdk/mcp/tasks.js +2 -2
  645. package/dist/sdk/mcp/transport.js +1 -1
  646. package/dist/sdk/merge/abandoned-receipts.js +1 -1
  647. package/dist/sdk/merge/driver.js +7 -7
  648. package/dist/sdk/merge/history-scalar-rebase.js +1 -1
  649. package/dist/sdk/merge/ignored-artifacts.js +1 -1
  650. package/dist/sdk/merge/index.js +1 -1
  651. package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
  652. package/dist/sdk/merge/install.js +6 -6
  653. package/dist/sdk/merge/receipt-file-boundary.js +1 -1
  654. package/dist/sdk/merge/receipt-operation.js +1 -1
  655. package/dist/sdk/merge/receipt-schema.js +1 -1
  656. package/dist/sdk/merge/receipts.js +4 -4
  657. package/dist/sdk/merge/reconcile.js +1 -1
  658. package/dist/sdk/merge/settlement-hook.js +4 -4
  659. package/dist/sdk/merge/stage.js +1 -1
  660. package/dist/sdk/merge/three-way.js +9 -9
  661. package/dist/sdk/merge/worktree-config.js +2 -2
  662. package/dist/sdk/merge.js +1 -1
  663. package/dist/sdk/mutation-events.js +1 -1
  664. package/dist/sdk/mutation-guard.js +1 -1
  665. package/dist/sdk/notes.js +1 -1
  666. package/dist/sdk/output/fit-envelope.js +1 -1
  667. package/dist/sdk/output/list-envelope.js +1 -1
  668. package/dist/sdk/output/table-rows.js +1 -1
  669. package/dist/sdk/output-contracts.js +1 -1
  670. package/dist/sdk/output-projection.js +1 -1
  671. package/dist/sdk/output-token-accounting.js +1 -1
  672. package/dist/sdk/output.js +2 -2
  673. package/dist/sdk/ownership-source.js +1 -1
  674. package/dist/sdk/package-import-adapters.js +1 -1
  675. package/dist/sdk/package-migrations.js +1 -1
  676. package/dist/sdk/package-runtime-options.js +1 -1
  677. package/dist/sdk/pagination.js +1 -1
  678. package/dist/sdk/profile.js +5 -5
  679. package/dist/sdk/provenance.js +1 -1
  680. package/dist/sdk/public-surface.json +1 -1
  681. package/dist/sdk/query/activity.js +1 -1
  682. package/dist/sdk/query/aggregate.js +1 -1
  683. package/dist/sdk/query/calendar.js +4 -4
  684. package/dist/sdk/query/complete-list.js +1 -1
  685. package/dist/sdk/query/context.js +2 -2
  686. package/dist/sdk/query/declared-blockers.js +1 -1
  687. package/dist/sdk/query/duplicate-candidates.js +1 -1
  688. package/dist/sdk/query/get-facet-roots.js +1 -1
  689. package/dist/sdk/query/get.js +1 -1
  690. package/dist/sdk/query/history.js +1 -1
  691. package/dist/sdk/query/item-filter-options.js +0 -1
  692. package/dist/sdk/query/light-metadata.js +1 -1
  693. package/dist/sdk/query/list-filter-shared.js +1 -1
  694. package/dist/sdk/query/list.js +1 -1
  695. package/dist/sdk/query/multi-value-filters.js +1 -1
  696. package/dist/sdk/query/next-ranking-policy.js +1 -1
  697. package/dist/sdk/query/next-ready-budget.js +1 -1
  698. package/dist/sdk/query/next.js +2 -2
  699. package/dist/sdk/query/parsers.js +1 -1
  700. package/dist/sdk/query/projection-contracts.js +1 -1
  701. package/dist/sdk/query/search/corpus.js +2 -2
  702. package/dist/sdk/query/search/filters.js +1 -1
  703. package/dist/sdk/query/search/input.js +1 -1
  704. package/dist/sdk/query/search/lexical.js +1 -1
  705. package/dist/sdk/query/search/response.js +1 -1
  706. package/dist/sdk/query/search/semantic.js +3 -3
  707. package/dist/sdk/query/search/types.js +0 -1
  708. package/dist/sdk/query/search-contracts.js +1 -1
  709. package/dist/sdk/query/search-pagination.js +1 -1
  710. package/dist/sdk/query/search-rendering.js +1 -1
  711. package/dist/sdk/query/search.js +1 -1
  712. package/dist/sdk/query/window-pagination.js +1 -1
  713. package/dist/sdk/query/workspace-contracts.js +1 -1
  714. package/dist/sdk/read-output/continuation.js +1 -1
  715. package/dist/sdk/read-output/extension.js +1 -1
  716. package/dist/sdk/read-output/options.js +1 -1
  717. package/dist/sdk/read-output/positional-rows.js +1 -1
  718. package/dist/sdk/read-output/provenance.js +1 -1
  719. package/dist/sdk/read-output/session-result.js +0 -1
  720. package/dist/sdk/read-output/surfaces.js +1 -1
  721. package/dist/sdk/read-output/tail-retention.js +1 -1
  722. package/dist/sdk/read-output-budget.js +1 -1
  723. package/dist/sdk/read-output-contracts.js +1 -1
  724. package/dist/sdk/read-output-rows.js +1 -1
  725. package/dist/sdk/read-output-session.js +1 -1
  726. package/dist/sdk/relationship-analytics.js +1 -1
  727. package/dist/sdk/relationship-context.js +1 -1
  728. package/dist/sdk/relationship-history.js +6 -6
  729. package/dist/sdk/relationship-kinds/contract.js +1 -1
  730. package/dist/sdk/relationships.js +1 -1
  731. package/dist/sdk/reproducibility/process.js +1 -1
  732. package/dist/sdk/runtime/actions.js +1 -1
  733. package/dist/sdk/runtime/context.js +1 -1
  734. package/dist/sdk/runtime/mutation-admission.js +1 -1
  735. package/dist/sdk/runtime/mutation-value-validation.js +1 -1
  736. package/dist/sdk/runtime/schema-preview.js +1 -1
  737. package/dist/sdk/runtime/schema.js +1 -1
  738. package/dist/sdk/runtime-action-aliases.js +1 -1
  739. package/dist/sdk/runtime-extended-actions.js +1 -1
  740. package/dist/sdk/runtime-input.d.ts +2 -0
  741. package/dist/sdk/runtime-input.js +1 -1
  742. package/dist/sdk/runtime-primitives.js +1 -1
  743. package/dist/sdk/runtime-public-contracts.js +0 -1
  744. package/dist/sdk/runtime-stats-options.js +1 -1
  745. package/dist/sdk/runtime.d.ts +5 -3
  746. package/dist/sdk/runtime.js +1 -1
  747. package/dist/sdk/scheduling-shortcuts.js +1 -1
  748. package/dist/sdk/schema/field-option-collisions.js +2 -0
  749. package/dist/sdk/schema-migration.js +4 -4
  750. package/dist/sdk/schema.js +7 -7
  751. package/dist/sdk/search-refresh-worker.js +1 -1
  752. package/dist/sdk/similarity-scoring.js +1 -1
  753. package/dist/sdk/similarity.js +1 -1
  754. package/dist/sdk/start-task-status.js +1 -1
  755. package/dist/sdk/stats.js +1 -1
  756. package/dist/sdk/structured-mutations.js +1 -1
  757. package/dist/sdk/telemetry-flush.js +1 -1
  758. package/dist/sdk/telemetry.js +4 -4
  759. package/dist/sdk/templates.js +3 -3
  760. package/dist/sdk/test/batch.js +2 -2
  761. package/dist/sdk/test/command-args.js +1 -1
  762. package/dist/sdk/test/command-resolution.js +2 -2
  763. package/dist/sdk/test/entry.js +2 -2
  764. package/dist/sdk/test/execution-receipts.js +2 -2
  765. package/dist/sdk/test/execution.js +5 -5
  766. package/dist/sdk/test/json-path.js +1 -1
  767. package/dist/sdk/test/linked-command-detection.js +1 -1
  768. package/dist/sdk/test/measurements.js +1 -1
  769. package/dist/sdk/test/parsers.js +1 -1
  770. package/dist/sdk/test/prerequisites.js +1 -1
  771. package/dist/sdk/test/receipt-index-snapshot.js +1 -1
  772. package/dist/sdk/test/run-phases.js +1 -1
  773. package/dist/sdk/test/runs.js +1 -1
  774. package/dist/sdk/test/trust.js +2 -2
  775. package/dist/sdk/test/update.js +1 -1
  776. package/dist/sdk/test/workspace-snapshot.js +1 -1
  777. package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
  778. package/dist/sdk/traceability/source-traceability.js +2 -2
  779. package/dist/sdk/tracker-root-discovery.js +1 -1
  780. package/dist/sdk/transactions/item-finalization.js +1 -1
  781. package/dist/sdk/workspace-contracts-cache.js +1 -1
  782. package/dist/sdk/workspace-contracts.js +1 -1
  783. package/dist/sdk/workspace-memory.js +2 -2
  784. package/dist/sdk/workspace-snapshot.js +5 -5
  785. package/dist/sdk/workspace-transaction-gc.js +1 -1
  786. package/dist/sdk/workspace-transaction.js +2 -2
  787. package/dist/sdk/workspace.js +6 -6
  788. package/dist/types/index.js +1 -1
  789. package/dist/types.js +1 -1
  790. package/docs/COMMANDS.md +1 -1
  791. package/docs/EXTENSIONS.md +1 -1
  792. package/docs/SDK.md +74 -4
  793. package/marketplace.json +1 -1
  794. package/package.json +2 -1
  795. package/packages/pm-beads/package.json +1 -1
  796. package/packages/pm-calendar/package.json +1 -1
  797. package/packages/pm-command-kit/package.json +1 -1
  798. package/packages/pm-digital-twin/package.json +1 -1
  799. package/packages/pm-governance-audit/package.json +1 -1
  800. package/packages/pm-guide-shell/package.json +1 -1
  801. package/packages/pm-kanban/package.json +1 -1
  802. package/packages/pm-lifecycle-hooks/package.json +1 -1
  803. package/packages/pm-linked-test-adapters/package.json +1 -1
  804. package/packages/pm-search-advanced/package.json +1 -1
  805. package/packages/pm-templates/package.json +1 -1
  806. package/packages/pm-todos/package.json +1 -1
  807. package/packages/pm-vcs/package.json +1 -1
  808. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  809. package/plugins/pm-claude/package.json +1 -1
  810. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  811. package/plugins/pm-codex/package.json +1 -1
  812. package/plugins/pm-codex/plugin.json +1 -1
  813. package/runtime-dependencies.json +1 -1
  814. package/scripts/finalize-build.mjs +63 -24
  815. package/scripts/prepare-build-cache.mjs +28 -1
  816. package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +0 -9
  817. package/dist/cli-bundle/chunks/chunk-4TB5D6HL.js +0 -125
  818. package/dist/cli-bundle/chunks/chunk-5ZMVLWE3.js +0 -2
  819. package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +0 -33
  820. package/dist/cli-bundle/chunks/chunk-AR4NP5HI.js +0 -3
  821. package/dist/cli-bundle/chunks/chunk-B4PPFOPY.js +0 -3
  822. package/dist/cli-bundle/chunks/chunk-CAR2L5NW.js +0 -8
  823. package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
  824. package/dist/cli-bundle/chunks/chunk-EIGUKEV6.js +0 -2
  825. package/dist/cli-bundle/chunks/chunk-GTPCAJMZ.js +0 -8
  826. package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +0 -2
  827. package/dist/cli-bundle/chunks/chunk-HC2OPETM.js +0 -2
  828. package/dist/cli-bundle/chunks/chunk-HKUV74K3.js +0 -2
  829. package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +0 -115
  830. package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +0 -2
  831. package/dist/cli-bundle/chunks/chunk-J2LABXBL.js +0 -2
  832. package/dist/cli-bundle/chunks/chunk-J52BEBSS.js +0 -2
  833. package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +0 -3
  834. package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +0 -3
  835. package/dist/cli-bundle/chunks/chunk-OJTMGDON.js +0 -31
  836. package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +0 -2
  837. package/dist/cli-bundle/chunks/chunk-TC6XLIYO.js +0 -2
  838. package/dist/cli-bundle/chunks/chunk-U7EL3AYA.js +0 -3
  839. package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +0 -6
  840. package/dist/cli-bundle/chunks/chunk-X6MIWTTT.js +0 -2
  841. package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +0 -2
  842. package/dist/cli-bundle/chunks/chunk-XFHPKXAE.js +0 -71
  843. package/dist/cli-bundle/chunks/chunk-YHVLVSEZ.js +0 -9
  844. package/dist/cli-bundle/chunks/chunk-YMUSRWV4.js +0 -9
  845. package/dist/cli-bundle/chunks/chunk-YR2KEBHP.js +0 -2
  846. package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +0 -2
  847. package/dist/cli-bundle/chunks/indexed-receipt-blobs-ITTXIN4K.js +0 -4
  848. package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +0 -2
  849. package/dist/cli-bundle/chunks/mutation-actor-FWLYWJ37.js +0 -2
  850. package/dist/cli-bundle/chunks/mutation-admission-7ZDCK3G2.js +0 -2
  851. package/dist/cli-bundle/chunks/register-mutation-57AJQWFV.js +0 -21
  852. package/dist/cli-bundle/chunks/register-operations-RKWST7CU.js +0 -2
  853. package/dist/cli-bundle/chunks/register-setup-CMI23PC5.js +0 -2
  854. package/dist/cli-bundle/chunks/settlement-hook-BXN5LEQD.js +0 -7
  855. package/dist/cli-bundle/chunks/stage-4KDVXC5Z.js +0 -2
  856. package/dist/cli-bundle/focused-chunks/chunk-2ZD7275J.js +0 -2
  857. package/dist/cli-bundle/focused-chunks/chunk-324AHXJO.js +0 -2
  858. package/dist/cli-bundle/focused-chunks/chunk-3IRCYJI5.js +0 -3
  859. package/dist/cli-bundle/focused-chunks/chunk-3V53UBHN.js +0 -9
  860. package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +0 -91
  861. package/dist/cli-bundle/focused-chunks/chunk-4JZITIJB.js +0 -2
  862. package/dist/cli-bundle/focused-chunks/chunk-4KTFKSS3.js +0 -2
  863. package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +0 -78
  864. package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +0 -2
  865. package/dist/cli-bundle/focused-chunks/chunk-BRZV7BFV.js +0 -8
  866. package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +0 -2
  867. package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +0 -3
  868. package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +0 -2
  869. package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +0 -2
  870. package/dist/cli-bundle/focused-chunks/chunk-HDEKFSOK.js +0 -2
  871. package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +0 -2
  872. package/dist/cli-bundle/focused-chunks/chunk-IWOXAUDU.js +0 -2
  873. package/dist/cli-bundle/focused-chunks/chunk-ML3JHCC6.js +0 -6
  874. package/dist/cli-bundle/focused-chunks/chunk-OPGOOP25.js +0 -2
  875. package/dist/cli-bundle/focused-chunks/chunk-RE7ZWT7D.js +0 -27
  876. package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +0 -3
  877. package/dist/cli-bundle/focused-chunks/chunk-RQ252B6V.js +0 -8
  878. package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +0 -2
  879. package/dist/cli-bundle/focused-chunks/chunk-URGHTTT3.js +0 -8
  880. package/dist/cli-bundle/focused-chunks/chunk-USPYKWQG.js +0 -13
  881. package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +0 -102
  882. package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +0 -44
  883. package/dist/cli-bundle/focused-chunks/chunk-WZWXGDYY.js +0 -26
  884. package/dist/cli-bundle/focused-chunks/chunk-YKSLZPLT.js +0 -2
  885. package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +0 -2
  886. package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +0 -2
  887. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-AF4U3F3D.js +0 -4
  888. package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +0 -2
  889. package/dist/cli-bundle/focused-chunks/mutation-actor-TCYDPUGG.js +0 -2
  890. package/dist/cli-bundle/focused-chunks/mutation-admission-LY73EJWM.js +0 -2
  891. package/dist/cli-bundle/focused-chunks/settlement-hook-ARYCZQY4.js +0 -7
  892. package/dist/cli-bundle/focused-chunks/stage-DQ7RQQ52.js +0 -2
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="427dd932-a013-557c-b3d8-5d7bb042e88c")}catch{}})();import{readdir,realpath,stat}from"node:fs/promises";import path from"node:path";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const MAX_PATTERN_LENGTH=4096,MAX_NESTING=32,MAX_RANGE_SIZE=1e3,MAX_STATES=5e4,DFA_LIMITS={nodes:1e4,edges:4e4,stateIds:2e6},SLASH=47;class GlobTooComplex extends Error{}const POSIX_CLASSES=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function negationRefusal(){return new PmCliError("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",EXIT_CODE.USAGE)}function bracketEnd(chars,start){let index=start+1;for((chars[index]==="!"||chars[index]==="^")&&(index+=1),chars[index]==="]"&&(index+=1);index<chars.length;){const char=chars[index];if(char==="\\")index+=2;else if(char==="["&&chars[index+1]===":"){const close=chars.indexOf(":",index+2);close===-1||chars[close+1]!=="]"?index+=1:index=close+2}else{if(char==="]")return index+1;index+=1}}return-1}function openerAt(chars,index,open){const char=chars[index];if(char==="{")return{index,kind:"{"};if(char!=="(")return;const operator=chars[index-1];return operator!==void 0&&"@?*+!".includes(operator)&&!isEscaped(chars,index-1)?{index:index-1,kind:"("}:open.some(opener=>opener.kind==="(")?{index,kind:"plain"}:void 0}function closeAt(chars,index,open,closers,groups){const char=chars[index],top=open.at(-1);if(char===")"&&top?.kind==="plain"){open.pop(),groups.set(top.index,index);return}const kind=char==="}"?"{":char===")"?"(":void 0;if(!(kind===void 0||top?.kind!==kind)&&(open.pop(),closers.set(top.index,index),chars[top.index]==="!"))throw negationRefusal()}function pairConstructs(chars){const closers=new Map,brackets=new Map,groups=new Map,open=[];let index=0;for(;index<chars.length;){if(chars[index]==="\\"){index+=2;continue}const end=chars[index]==="["?bracketEnd(chars,index):-1;if(end!==-1){brackets.set(index,end),index=end;continue}const opener=openerAt(chars,index,open);if(opener!==void 0?open.push(opener):closeAt(chars,index,open,closers,groups),open.length>MAX_NESTING)throw new GlobTooComplex;index+=1}return{closers,brackets,groups}}function isEscaped(chars,index){let count=0;for(let cursor=index-1;cursor>=0&&chars[cursor]==="\\";cursor-=1)count+=1;return count%2===1}function literalNodes(text){return Array.from(text,char=>({kind:"char",value:char.codePointAt(0)}))}function braceRange(content){const numeric=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(content),alphabetic=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(content);if(numeric===null&&alphabetic===null)return;const[from,to]=numeric!==null?[Number(numeric[1]),Number(numeric[2])]:[alphabetic[1].codePointAt(0),alphabetic[2].codePointAt(0)];if(Math.abs(to-from)+1>MAX_RANGE_SIZE)throw new GlobTooComplex;const step=from<=to?1:-1,values=[];for(let value=from;value!==to+step;value+=step)values.push(numeric!==null?String(value):String.fromCodePoint(value));return values}function posixClassAt(chars,index){if(chars[index]!=="["||chars[index+1]!==":")return;const colon=chars.indexOf(":",index+2);if(!(colon===-1||chars[colon+1]!=="]"))return{ranges:POSIX_CLASSES.get(chars.slice(index+2,colon).join(""))??[],next:colon+2}}function memberAt(chars,index,close){const escaped=chars[index]==="\\"&&index+1<close;return{codePoint:chars[escaped?index+1:index].codePointAt(0),next:index+(escaped?2:1)}}function bracketLiteral(chars,start,end){const literal=[];for(let cursor=start;cursor<end;cursor+=1)chars[cursor]==="\\"&&cursor+1<end&&(cursor+=1),literal.push(chars[cursor].codePointAt(0));return literal}function parseClass(chars,start,end){let index=start+1;const negated=chars[index]==="!"||chars[index]==="^";negated&&(index+=1);const ranges=[],close=end-1;for(;index<close;){const posix=posixClassAt(chars,index);if(posix!==void 0){ranges.push(...posix.ranges),index=posix.next;continue}const low=memberAt(chars,index,close);if(index=low.next,chars[index]!=="-"||index+1>=close){ranges.push([low.codePoint,low.codePoint]);continue}const high=memberAt(chars,index+1,close);index=high.next,low.codePoint<=high.codePoint&&ranges.push([low.codePoint,high.codePoint])}return{kind:"class",negated,ranges,literal:bracketLiteral(chars,start,end)}}class Parser{chars;closers;brackets;groups;constructor(chars,pairs){this.chars=chars,this.closers=pairs.closers,this.brackets=pairs.brackets,this.groups=pairs.groups}alternatives(start,end,separator){const options=[];let cursor=start;for(;;){const{nodes,stop}=this.sequence(cursor,end,separator);if(options.push(nodes),stop>=end)return options;cursor=stop+1}}sequence(start,end,separator){const nodes=[];let index=start;for(;index<end;){if(this.chars[index]===separator)return{nodes,stop:index};const token=this.token(index,end);nodes.push(...token.nodes),index=token.next}return{nodes,stop:end}}token(index,end){const char=this.chars[index];if(char==="\\")return{nodes:literalNodes(index+1<end?this.chars[index+1]:"\\"),next:index+2};const closer=this.closers.get(index);if(closer!==void 0)return{nodes:char==="{"?this.brace(index,closer):this.extglob(char,index,closer),next:closer+1};const group=this.groups.get(index);if(group!==void 0)return{nodes:[...literalNodes("("),...this.sequence(index+1,group,void 0).nodes,...literalNodes(")")],next:group+1};const bracket=this.brackets.get(index);return bracket!==void 0?{nodes:[parseClass(this.chars,index,bracket)],next:bracket}:char==="*"?this.stars(index,end):{nodes:char==="?"?[{kind:"any"}]:literalNodes(char),next:index+1}}extglob(operator,index,closer){const options=this.alternatives(index+2,closer,"|");return[operator==="@"?{kind:"alt",options}:{kind:"repeat",optional:operator!=="+",many:operator!=="?",options}]}brace(index,closer){const options=this.alternatives(index+1,closer,",");if(options.length>1)return[{kind:"alt",options}];const range=braceRange(this.chars.slice(index+1,closer).join(""));return range!==void 0?[{kind:"alt",options:range.map(literalNodes)}]:[...literalNodes("{"),...options[0],...literalNodes("}")]}stars(index,end){let run=1;for(;this.chars[index+run]==="*"&&index+run<end&&!this.closers.has(index+run);)run+=1;if(run!==2)return{nodes:[{kind:"star"}],next:index+run};const slash=index+run<end&&this.chars[index+run]==="/";return{nodes:[{kind:"globstar",slash}],next:index+run+(slash?1:0)}}}const END_KINDS=["segment","inside"],ANY={kind:"any"};function entriesOf(ends){return END_KINDS.flatMap(kind=>ends[kind]===void 0?[]:[ends[kind]])}class Nfa{states=[];add(){if(this.states.length>=MAX_STATES)throw new GlobTooComplex;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(from,to,syntactic=!0){this.states[from].epsilon.push(to),syntactic&&this.states[from].syntactic.push(to)}consume(from,test,kind){const to=this.add();for(const entry of entriesOf(from))this.states[entry].edges.push({test,to});return{[kind]:to}}join(parts){const joined={};for(const kind of END_KINDS){const states=parts.flatMap(part=>part[kind]===void 0?[]:[part[kind]]);if(states.length===1&&(joined[kind]=states[0]),states.length>1){const merged=this.add();for(const state of states)this.epsilon(state,merged);joined[kind]=merged}}return joined}feed(ends,loop){for(const kind of END_KINDS)ends[kind]!==void 0&&this.epsilon(ends[kind],loop[kind])}build(nodes,from){let current=from;for(const node of nodes)current=this.node(node,current);return current}alternation(options,from){return this.join(options.map(option=>this.build(option,from)))}star(from){const loop=this.add();for(const entry of entriesOf(from))this.epsilon(entry,loop,!1);return this.states[loop].edges.push({test:ANY,to:loop}),{inside:loop}}segments(from){const between=this.add();this.epsilon(from,between,!1);const inside=this.add();return this.states[between].edges.push({test:ANY,to:inside}),this.states[inside].edges.push({test:ANY,to:inside},{test:{kind:"char",value:SLASH},to:between}),between}globstar(from,slash){if(slash){const parts=[];return from.segment!==void 0&&parts.push({segment:this.segments(from.segment)}),from.inside!==void 0&&parts.push(this.consume(this.star({inside:from.inside}),{kind:"char",value:SLASH},"segment")),this.join(parts)}const star=this.star(from);return from.segment!==void 0&&this.globstars.push({continuation:star.inside,entry:from.segment}),star}globstars=[];syntacticClosure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.states[stack.pop()].syntactic)seen.has(next)||(seen.add(next),stack.push(next));return seen}resolveGlobstars(accept){for(const{continuation,entry}of this.globstars){const reachable=this.syntacticClosure([continuation]);if(reachable.has(accept)){const rest=this.add();this.epsilon(entry,rest,!1),this.states[rest].edges.push({test:{kind:"all"},to:rest}),this.epsilon(rest,accept,!1)}const targets=new Set;for(const state of reachable)for(const{test,to}of this.states[state].edges)accepts(test,SLASH)&&targets.add(to);if(targets.size===0)continue;const segments=this.segments(entry);for(const target of targets)this.epsilon(segments,target,!1)}}repeat(node,from){if(!node.many)return this.join([from,this.alternation(node.options,from)]);const loop={segment:this.add(),inside:this.add()};return this.feed(node.optional?from:this.alternation(node.options,from),loop),this.feed(this.alternation(node.options,loop),loop),loop}node(node,from){switch(node.kind){case"char":return this.consume(from,{kind:"char",value:node.value},node.value===SLASH?"segment":"inside");case"any":return this.consume(from,ANY,"inside");case"star":return this.star(from);case"globstar":return this.globstar(from,node.slash);case"class":return this.join([this.consume(from,{kind:"class",negated:node.negated,ranges:node.ranges},"inside"),this.build(node.literal.map(value=>({kind:"char",value})),from)]);case"alt":return this.alternation(node.options,from);case"repeat":return this.repeat(node,from)}}}function accepts(test,codePoint){switch(test.kind){case"char":return test.value===codePoint;case"any":return codePoint!==SLASH;case"all":return!0;case"class":return codePoint!==SLASH&&test.ranges.some(([low,high])=>codePoint>=low&&codePoint<=high)!==test.negated}}class PathMatcher{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(nfa,startState,acceptState,limits){this.nfa=nfa,this.acceptState=acceptState,this.limits=limits,this.start=this.node(this.closure([startState]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.nfa.states[stack.pop()].epsilon)seen.has(next)||(seen.add(next),stack.push(next));return[...seen].sort((left,right)=>left-right)}node(states){const key=states.join(","),cached=this.nodes.get(key);if(cached!==void 0)return cached;(this.nodes.size>=this.limits.nodes||this.stateIds+states.length>this.limits.stateIds)&&this.reset();const created={id:this.nextId,generation:this.generation,states,accepting:states.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(key,created),this.stateIds+=states.length,created}step(from,codePoint){const key=`${from.id}:${codePoint}`,known=from.generation===this.generation?this.edges.get(key):void 0;if(known!==void 0)return known;const reached=[];for(const state of from.states)for(const{test,to}of this.nfa.states[state].edges)accepts(test,codePoint)&&reached.push(to);const next=this.node(this.closure(reached));return this.edges.size>=this.limits.edges&&this.reset(),from.generation===this.generation&&this.edges.set(key,next),next}advance(from,text){let node=from;for(const char of text){if(node.states.length===0)return node;node=this.step(node,char.codePointAt(0))}return node}}function compile(text,limits=DFA_LIMITS){const chars=Array.from(text),nodes=new Parser(chars,pairConstructs(chars)).sequence(0,chars.length,void 0).nodes,nfa=new Nfa,start=nfa.add(),accept=nfa.add();for(const end of entriesOf(nfa.build(nodes,{segment:start})))nfa.epsilon(end,accept);return nfa.resolveGlobstars(accept),new PathMatcher(nfa,start,accept,limits)}function isStaticSegment(segment){return!/[*?[\]{}()!@+\\]/u.test(segment)}function kindOf(entry){return entry.isFile()?"file":entry.isDirectory()?"directory":"other"}async function resolveEntry(directory,real,entry){if(!entry.isSymbolicLink())return{kind:kindOf(entry),real:path.join(real,entry.name)};try{const target=await realpath(path.join(directory,entry.name));return{kind:kindOf(await stat(target)),real:target}}catch{return}}async function walk(matcher,directory,real,prefix,node,ancestors,out){let entries;try{entries=await readdir(directory,{withFileTypes:!0})}catch{return}for(const entry of entries){const afterName=matcher.advance(node,entry.name);if(afterName.states.length===0)continue;const resolved=await resolveEntry(directory,real,entry);if(resolved===void 0)continue;const relative=path.posix.join(prefix,entry.name);if(resolved.kind==="file"&&afterName.accepting&&out.push(relative),resolved.kind!=="directory")continue;const afterSlash=matcher.step(afterName,SLASH);afterSlash.states.length===0||ancestors.has(resolved.real)||(ancestors.add(resolved.real),await walk(matcher,path.join(directory,entry.name),resolved.real,relative,afterSlash,ancestors,out),ancestors.delete(resolved.real))}}function normalizePattern(pattern){const normalized=path.posix.normalize(pattern);return/^\/\/[^/]/u.test(pattern)?`/${normalized}`:normalized}function trimTrailingSeparators(pattern){let text=pattern;for(;text.length>1&&text.endsWith("/")&&!isEscaped(text,text.length-1);)text=text.slice(0,-1);return text}async function listed(directory,name){return(await readdir(directory).catch(()=>[])).includes(name)}async function exactCase(cwd,segments){let directory=cwd,index=0;for(;segments[index]==="..";)directory=path.dirname(directory),index+=1;for(;index<segments.length;index+=1){if(!await listed(directory,segments[index]))return!1;directory=path.join(directory,segments[index])}return!0}function isAbsolutePattern(text,platform=process.platform){return text.startsWith("/")||platform==="win32"&&/^[A-Za-z]:\//u.test(text)}async function literalMatch(text,cwd){const target=path.resolve(cwd,text),found=await stat(target).catch(()=>{});if(found===void 0||!found.isFile())return[];const absolute=isAbsolutePattern(text);return(absolute?await listed(path.dirname(target),path.basename(target)):await exactCase(cwd,text.split("/")))?[absolute?target.replaceAll("\\","/"):path.posix.normalize(text)]:[]}function splitStatic(text,cwd){const segments=text.split("/");let count=0;for(;count<segments.length&&isStaticSegment(segments[count]);)count+=1;if(count===segments.length)return;const prefix=count===0?"":`${segments.slice(0,count).join("/")}/`,root=path.resolve(cwd,prefix),rest=segments.slice(count).join("/");if(isAbsolutePattern(text))return{root,base:root.replaceAll("\\","/"),rest,prefix:[]};const relative=path.posix.normalize(prefix===""?".":prefix).replace(/\/$/u,"");return{root,base:relative==="."?"":relative,rest,prefix:segments.slice(0,count)}}function compileWithinBounds(text){try{return compile(text)}catch(error){if(error instanceof GlobTooComplex)return;throw error}}async function expandFileGlob(pattern,cwd){if(pattern.startsWith("!"))throw negationRefusal();if(Array.from(pattern).length>MAX_PATTERN_LENGTH)return[];const text=trimTrailingSeparators(normalizePattern(pattern)),parts=splitStatic(text,cwd);if(parts===void 0)return literalMatch(text,cwd);const matcher=compileWithinBounds(parts.rest);if(matcher===void 0||!await exactCase(cwd,parts.prefix))return[];const real=await realpath(parts.root).catch(()=>{});if(real===void 0)return[];const out=[];return await walk(matcher,parts.root,real,"",matcher.start,new Set([real]),out),out.map(relative=>joinOutput(parts.base,relative))}function joinOutput(base,relative){return base.startsWith("//")?`/${path.posix.join(base.slice(1),relative)}`:path.posix.join(base,relative)}const _testOnly={compile,isAbsolutePattern,joinOutput,normalizePattern};export{_testOnly,expandFileGlob};
1
+ import{readdir as A,realpath as S,stat as v}from"node:fs/promises";import c from"node:path";import{EXIT_CODE as O}from"../shared/constants.js";import{PmCliError as G}from"../shared/errors.js";const $=4096,L=32,X=1e3,D=5e4,F={nodes:1e4,edges:4e4,stateIds:2e6},h=47;class p extends Error{}const W=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function j(){return new G("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",O.USAGE)}function q(i,t){let e=t+1;for((i[e]==="!"||i[e]==="^")&&(e+=1),i[e]==="]"&&(e+=1);e<i.length;){const n=i[e];if(n==="\\")e+=2;else if(n==="["&&i[e+1]===":"){const s=i.indexOf(":",e+2);s===-1||i[s+1]!=="]"?e+=1:e=s+2}else{if(n==="]")return e+1;e+=1}}return-1}function R(i,t,e){const n=i[t];if(n==="{")return{index:t,kind:"{"};if(n!=="(")return;const s=i[t-1];return s!==void 0&&"@?*+!".includes(s)&&!x(i,t-1)?{index:t-1,kind:"("}:e.some(o=>o.kind==="(")?{index:t,kind:"plain"}:void 0}function Z(i,t,e,n,s){const o=i[t],r=e.at(-1);if(o===")"&&r?.kind==="plain"){e.pop(),s.set(r.index,t);return}const a=o==="}"?"{":o===")"?"(":void 0;if(!(a===void 0||r?.kind!==a)&&(e.pop(),n.set(r.index,t),i[r.index]==="!"))throw j()}function H(i){const t=new Map,e=new Map,n=new Map,s=[];let o=0;for(;o<i.length;){if(i[o]==="\\"){o+=2;continue}const r=i[o]==="["?q(i,o):-1;if(r!==-1){e.set(o,r),o=r;continue}const a=R(i,o,s);if(a!==void 0?s.push(a):Z(i,o,s,t,n),s.length>L)throw new p;o+=1}return{closers:t,brackets:e,groups:n}}function x(i,t){let e=0;for(let n=t-1;n>=0&&i[n]==="\\";n-=1)e+=1;return e%2===1}function f(i){return Array.from(i,t=>({kind:"char",value:t.codePointAt(0)}))}function B(i){const t=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(i),e=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(i);if(t===null&&e===null)return;const[n,s]=t!==null?[Number(t[1]),Number(t[2])]:[e[1].codePointAt(0),e[2].codePointAt(0)];if(Math.abs(s-n)+1>X)throw new p;const o=n<=s?1:-1,r=[];for(let a=n;a!==s+o;a+=o)r.push(t!==null?String(a):String.fromCodePoint(a));return r}function K(i,t){if(i[t]!=="["||i[t+1]!==":")return;const e=i.indexOf(":",t+2);if(!(e===-1||i[e+1]!=="]"))return{ranges:W.get(i.slice(t+2,e).join(""))??[],next:e+2}}function I(i,t,e){const n=i[t]==="\\"&&t+1<e;return{codePoint:i[n?t+1:t].codePointAt(0),next:t+(n?2:1)}}function U(i,t,e){const n=[];for(let s=t;s<e;s+=1)i[s]==="\\"&&s+1<e&&(s+=1),n.push(i[s].codePointAt(0));return n}function Y(i,t,e){let n=t+1;const s=i[n]==="!"||i[n]==="^";s&&(n+=1);const o=[],r=e-1;for(;n<r;){const a=K(i,n);if(a!==void 0){o.push(...a.ranges),n=a.next;continue}const u=I(i,n,r);if(n=u.next,i[n]!=="-"||n+1>=r){o.push([u.codePoint,u.codePoint]);continue}const l=I(i,n+1,r);n=l.next,u.codePoint<=l.codePoint&&o.push([u.codePoint,l.codePoint])}return{kind:"class",negated:s,ranges:o,literal:U(i,t,e)}}class J{chars;closers;brackets;groups;constructor(t,e){this.chars=t,this.closers=e.closers,this.brackets=e.brackets,this.groups=e.groups}alternatives(t,e,n){const s=[];let o=t;for(;;){const{nodes:r,stop:a}=this.sequence(o,e,n);if(s.push(r),a>=e)return s;o=a+1}}sequence(t,e,n){const s=[];let o=t;for(;o<e;){if(this.chars[o]===n)return{nodes:s,stop:o};const r=this.token(o,e);s.push(...r.nodes),o=r.next}return{nodes:s,stop:e}}token(t,e){const n=this.chars[t];if(n==="\\")return{nodes:f(t+1<e?this.chars[t+1]:"\\"),next:t+2};const s=this.closers.get(t);if(s!==void 0)return{nodes:n==="{"?this.brace(t,s):this.extglob(n,t,s),next:s+1};const o=this.groups.get(t);if(o!==void 0)return{nodes:[...f("("),...this.sequence(t+1,o,void 0).nodes,...f(")")],next:o+1};const r=this.brackets.get(t);return r!==void 0?{nodes:[Y(this.chars,t,r)],next:r}:n==="*"?this.stars(t,e):{nodes:n==="?"?[{kind:"any"}]:f(n),next:t+1}}extglob(t,e,n){const s=this.alternatives(e+2,n,"|");return[t==="@"?{kind:"alt",options:s}:{kind:"repeat",optional:t!=="+",many:t!=="?",options:s}]}brace(t,e){const n=this.alternatives(t+1,e,",");if(n.length>1)return[{kind:"alt",options:n}];const s=B(this.chars.slice(t+1,e).join(""));return s!==void 0?[{kind:"alt",options:s.map(f)}]:[...f("{"),...n[0],...f("}")]}stars(t,e){let n=1;for(;this.chars[t+n]==="*"&&t+n<e&&!this.closers.has(t+n);)n+=1;if(n!==2)return{nodes:[{kind:"star"}],next:t+n};const s=t+n<e&&this.chars[t+n]==="/";return{nodes:[{kind:"globstar",slash:s}],next:t+n+(s?1:0)}}}const w=["segment","inside"],g={kind:"any"};function m(i){return w.flatMap(t=>i[t]===void 0?[]:[i[t]])}class Q{states=[];add(){if(this.states.length>=D)throw new p;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(t,e,n=!0){this.states[t].epsilon.push(e),n&&this.states[t].syntactic.push(e)}consume(t,e,n){const s=this.add();for(const o of m(t))this.states[o].edges.push({test:e,to:s});return{[n]:s}}join(t){const e={};for(const n of w){const s=t.flatMap(o=>o[n]===void 0?[]:[o[n]]);if(s.length===1&&(e[n]=s[0]),s.length>1){const o=this.add();for(const r of s)this.epsilon(r,o);e[n]=o}}return e}feed(t,e){for(const n of w)t[n]!==void 0&&this.epsilon(t[n],e[n])}build(t,e){let n=e;for(const s of t)n=this.node(s,n);return n}alternation(t,e){return this.join(t.map(n=>this.build(n,e)))}star(t){const e=this.add();for(const n of m(t))this.epsilon(n,e,!1);return this.states[e].edges.push({test:g,to:e}),{inside:e}}segments(t){const e=this.add();this.epsilon(t,e,!1);const n=this.add();return this.states[e].edges.push({test:g,to:n}),this.states[n].edges.push({test:g,to:n},{test:{kind:"char",value:h},to:e}),e}globstar(t,e){if(e){const s=[];return t.segment!==void 0&&s.push({segment:this.segments(t.segment)}),t.inside!==void 0&&s.push(this.consume(this.star({inside:t.inside}),{kind:"char",value:h},"segment")),this.join(s)}const n=this.star(t);return t.segment!==void 0&&this.globstars.push({continuation:n.inside,entry:t.segment}),n}globstars=[];syntacticClosure(t){const e=new Set(t),n=[...t];for(;n.length>0;)for(const s of this.states[n.pop()].syntactic)e.has(s)||(e.add(s),n.push(s));return e}resolveGlobstars(t){for(const{continuation:e,entry:n}of this.globstars){const s=this.syntacticClosure([e]);if(s.has(t)){const a=this.add();this.epsilon(n,a,!1),this.states[a].edges.push({test:{kind:"all"},to:a}),this.epsilon(a,t,!1)}const o=new Set;for(const a of s)for(const{test:u,to:l}of this.states[a].edges)M(u,h)&&o.add(l);if(o.size===0)continue;const r=this.segments(n);for(const a of o)this.epsilon(r,a,!1)}}repeat(t,e){if(!t.many)return this.join([e,this.alternation(t.options,e)]);const n={segment:this.add(),inside:this.add()};return this.feed(t.optional?e:this.alternation(t.options,e),n),this.feed(this.alternation(t.options,n),n),n}node(t,e){switch(t.kind){case"char":return this.consume(e,{kind:"char",value:t.value},t.value===h?"segment":"inside");case"any":return this.consume(e,g,"inside");case"star":return this.star(e);case"globstar":return this.globstar(e,t.slash);case"class":return this.join([this.consume(e,{kind:"class",negated:t.negated,ranges:t.ranges},"inside"),this.build(t.literal.map(n=>({kind:"char",value:n})),e)]);case"alt":return this.alternation(t.options,e);case"repeat":return this.repeat(t,e)}}}function M(i,t){switch(i.kind){case"char":return i.value===t;case"any":return t!==h;case"all":return!0;case"class":return t!==h&&i.ranges.some(([e,n])=>t>=e&&t<=n)!==i.negated}}class V{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(t,e,n,s){this.nfa=t,this.acceptState=n,this.limits=s,this.start=this.node(this.closure([e]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(t){const e=new Set(t),n=[...t];for(;n.length>0;)for(const s of this.nfa.states[n.pop()].epsilon)e.has(s)||(e.add(s),n.push(s));return[...e].sort((s,o)=>s-o)}node(t){const e=t.join(","),n=this.nodes.get(e);if(n!==void 0)return n;(this.nodes.size>=this.limits.nodes||this.stateIds+t.length>this.limits.stateIds)&&this.reset();const s={id:this.nextId,generation:this.generation,states:t,accepting:t.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(e,s),this.stateIds+=t.length,s}step(t,e){const n=`${t.id}:${e}`,s=t.generation===this.generation?this.edges.get(n):void 0;if(s!==void 0)return s;const o=[];for(const a of t.states)for(const{test:u,to:l}of this.nfa.states[a].edges)M(u,e)&&o.push(l);const r=this.node(this.closure(o));return this.edges.size>=this.limits.edges&&this.reset(),t.generation===this.generation&&this.edges.set(n,r),r}advance(t,e){let n=t;for(const s of e){if(n.states.length===0)return n;n=this.step(n,s.codePointAt(0))}return n}}function E(i,t=F){const e=Array.from(i),n=new J(e,H(e)).sequence(0,e.length,void 0).nodes,s=new Q,o=s.add(),r=s.add();for(const a of m(s.build(n,{segment:o})))s.epsilon(a,r);return s.resolveGlobstars(r),new V(s,o,r,t)}function tt(i){return!/[*?[\]{}()!@+\\]/u.test(i)}function P(i){return i.isFile()?"file":i.isDirectory()?"directory":"other"}async function et(i,t,e){if(!e.isSymbolicLink())return{kind:P(e),real:c.join(t,e.name)};try{const n=await S(c.join(i,e.name));return{kind:P(await v(n)),real:n}}catch{return}}async function _(i,t,e,n,s,o,r){let a;try{a=await A(t,{withFileTypes:!0})}catch{return}for(const u of a){const l=i.advance(s,u.name);if(l.states.length===0)continue;const d=await et(t,e,u);if(d===void 0)continue;const b=c.posix.join(n,u.name);if(d.kind==="file"&&l.accepting&&r.push(b),d.kind!=="directory")continue;const y=i.step(l,h);y.states.length===0||o.has(d.real)||(o.add(d.real),await _(i,c.join(t,u.name),d.real,b,y,o,r),o.delete(d.real))}}function z(i){const t=c.posix.normalize(i);return/^\/\/[^/]/u.test(i)?`/${t}`:t}function nt(i){let t=i;for(;t.length>1&&t.endsWith("/")&&!x(t,t.length-1);)t=t.slice(0,-1);return t}async function N(i,t){return(await A(i).catch(()=>[])).includes(t)}async function C(i,t){let e=i,n=0;for(;t[n]==="..";)e=c.dirname(e),n+=1;for(;n<t.length;n+=1){if(!await N(e,t[n]))return!1;e=c.join(e,t[n])}return!0}function k(i,t=process.platform){return i.startsWith("/")||t==="win32"&&/^[A-Za-z]:\//u.test(i)}async function st(i,t){const e=c.resolve(t,i),n=await v(e).catch(()=>{});if(n===void 0||!n.isFile())return[];const s=k(i);return(s?await N(c.dirname(e),c.basename(e)):await C(t,i.split("/")))?[s?e.replaceAll("\\","/"):c.posix.normalize(i)]:[]}function it(i,t){const e=i.split("/");let n=0;for(;n<e.length&&tt(e[n]);)n+=1;if(n===e.length)return;const s=n===0?"":`${e.slice(0,n).join("/")}/`,o=c.resolve(t,s),r=e.slice(n).join("/");if(k(i))return{root:o,base:o.replaceAll("\\","/"),rest:r,prefix:[]};const a=c.posix.normalize(s===""?".":s).replace(/\/$/u,"");return{root:o,base:a==="."?"":a,rest:r,prefix:e.slice(0,n)}}function ot(i){try{return E(i)}catch(t){if(t instanceof p)return;throw t}}async function lt(i,t){if(i.startsWith("!"))throw j();if(Array.from(i).length>$)return[];const e=nt(z(i)),n=it(e,t);if(n===void 0)return st(e,t);const s=ot(n.rest);if(s===void 0||!await C(t,n.prefix))return[];const o=await S(n.root).catch(()=>{});if(o===void 0)return[];const r=[];return await _(s,n.root,o,"",s.start,new Set([o]),r),r.map(a=>T(n.base,a))}function T(i,t){return i.startsWith("//")?`/${c.posix.join(i.slice(1),t)}`:c.posix.join(i,t)}const dt={compile:E,isAbsolutePattern:k,joinOutput:T,normalizePattern:z};export{dt as _testOnly,lt as expandFileGlob};
2
2
  //# sourceMappingURL=file-glob.js.map
@@ -1,3 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="af07b34f-9e45-561f-aa8c-2415ee4a46b9")}catch{}})();import*as fs from"node:fs/promises";import{constants}from"node:fs";import path from"node:path";import crypto from"node:crypto";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const WINDOWS_RENAME_RETRY_DELAYS_MS=[10,25,50,100];async function ensureDir(dirPath){await fs.mkdir(dirPath,{recursive:!0})}async function pathExists(targetPath){try{return await fs.access(targetPath),!0}catch{return!1}}function isFileAbsentError(error){return isFileMissingError(error)||isErrno(error,"ENOTDIR")}function isFileMissingError(error){return isErrno(error,"ENOENT")}async function readFileIfExists(targetPath){try{return await fs.readFile(targetPath,"utf8")}catch(error){if(isFileAbsentError(error))return null;throw error}}async function readRegularFile(targetPath,rejectionError){const handle=await fs.open(targetPath,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{if(!(await handle.stat()).isFile())throw rejectionError;return await handle.readFile("utf8")}finally{await handle.close()}}function transactionPreviewNonRegularFileError(relativePath){const relative=relativePath?.replaceAll(path.sep,"/"),contained=relative!==void 0&&!path.posix.isAbsolute(relative)&&!path.win32.isAbsolute(relative)&&!relative.split("/").includes(".."),first=contained?relative.split("/")[0]:void 0,areas={"settings.json":"settings",runtime:"runtime",schema:"schema",history:"history",transactions:"transactions"},area=first===void 0?"tracker_storage":Object.hasOwn(areas,first)?areas[first]:"tracker_storage",safe=contained&&relative.length>0&&relative.length<=160&&relative.split("/").every(part=>part!=="."&&/^[a-zA-Z0-9_.-]+$/u.test(part)),location=safe?relative:`${area} (entry name redacted)`;return new PmCliError(`Transaction preview requires regular files and directories. Inspect ${location} relative to the selected tracker root.`,EXIT_CODE.USAGE,{code:"transaction_preview_non_regular_file",preview_storage:{storage_area:area,...safe?{relative_entry:relative}:{},entry_redacted:!safe},required:"regular files and directories within the configured tracker storage",why:"Preview does not follow linked entries or read special files.",nextSteps:[`Inspect ${location} within the selected tracker for links, directories used as files, or special files; do not follow link targets.`,"Restore the intended regular files and directories, then retry the original dry-run command."]})}async function unlinkQuietly(filePath){try{await fs.unlink(filePath)}catch{}}async function writeFileAtomic(targetPath,contents,options={}){const dirPath=path.dirname(targetPath);options.createParentDirectories!==!1&&await ensureDir(dirPath);const tempPath=path.join(dirPath,`.${path.basename(targetPath)}.${process.pid}.${Date.now()}.${crypto.randomBytes(4).toString("hex")}.tmp`);try{await fs.writeFile(tempPath,contents,options.mode===void 0?"utf8":{encoding:"utf8",mode:options.mode})}catch(error){throw await unlinkQuietly(tempPath),error}try{await fs.rename(tempPath,targetPath)}catch(error){if(process.platform==="win32"&&(isErrno(error,"EPERM")||isErrno(error,"EBUSY"))){let lastError=error;for(const delayMs of WINDOWS_RENAME_RETRY_DELAYS_MS){await new Promise(resolve=>setTimeout(resolve,delayMs));try{await fs.rename(tempPath,targetPath);return}catch(retryError){if(lastError=retryError,!isErrno(retryError,"EPERM")&&!isErrno(retryError,"EBUSY"))break}}throw await unlinkQuietly(tempPath),lastError}if(isErrno(error,"EXDEV")){try{await fs.copyFile(tempPath,targetPath)}finally{await unlinkQuietly(tempPath)}return}throw await unlinkQuietly(tempPath),error}}async function appendLineAtomic(targetPath,line){const dirPath=path.dirname(targetPath);await ensureDir(dirPath);const handle=await fs.open(targetPath,"a");try{await handle.writeFile(`${line}
2
- `,"utf8")}finally{await handle.close()}}async function removeFileIfExists(targetPath){try{await fs.unlink(targetPath)}catch(error){if(!isFileAbsentError(error))throw error}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}export{appendLineAtomic,ensureDir,isFileAbsentError,isFileMissingError,pathExists,readFileIfExists,readRegularFile,removeFileIfExists,transactionPreviewNonRegularFileError,writeFileAtomic};
1
+ import*as n from"node:fs/promises";import{constants as w}from"node:fs";import c from"node:path";import y from"node:crypto";import{EXIT_CODE as h}from"../shared/constants.js";import{PmCliError as E}from"../shared/errors.js";const _=[10,25,50,100];async function p(e){await n.mkdir(e,{recursive:!0})}async function A(e){try{return await n.access(e),!0}catch{return!1}}function m(e){return g(e)||l(e,"ENOTDIR")}function g(e){return l(e,"ENOENT")}async function N(e){try{return await n.readFile(e,"utf8")}catch(t){if(m(t))return null;throw t}}async function R(e,t){const r=await n.open(e,w.O_RDONLY|w.O_NOFOLLOW|w.O_NONBLOCK);try{if(!(await r.stat()).isFile())throw t;return await r.readFile("utf8")}finally{await r.close()}}function D(e){const t=e?.replaceAll(c.sep,"/"),r=t!==void 0&&!c.posix.isAbsolute(t)&&!c.win32.isAbsolute(t)&&!t.split("/").includes(".."),o=r?t.split("/")[0]:void 0,i={"settings.json":"settings",runtime:"runtime",schema:"schema",history:"history",transactions:"transactions"},a=o===void 0?"tracker_storage":Object.hasOwn(i,o)?i[o]:"tracker_storage",u=r&&t.length>0&&t.length<=160&&t.split("/").every(s=>s!=="."&&/^[a-zA-Z0-9_.-]+$/u.test(s)),f=u?t:`${a} (entry name redacted)`;return new E(`Transaction preview requires regular files and directories. Inspect ${f} relative to the selected tracker root.`,h.USAGE,{code:"transaction_preview_non_regular_file",preview_storage:{storage_area:a,...u?{relative_entry:t}:{},entry_redacted:!u},required:"regular files and directories within the configured tracker storage",why:"Preview does not follow linked entries or read special files.",nextSteps:[`Inspect ${f} within the selected tracker for links, directories used as files, or special files; do not follow link targets.`,"Restore the intended regular files and directories, then retry the original dry-run command."]})}async function d(e){try{await n.unlink(e)}catch{}}async function $(e,t,r={}){const o=c.dirname(e);r.createParentDirectories!==!1&&await p(o);const i=c.join(o,`.${c.basename(e)}.${process.pid}.${Date.now()}.${y.randomBytes(4).toString("hex")}.tmp`);try{await n.writeFile(i,t,r.mode===void 0?"utf8":{encoding:"utf8",mode:r.mode})}catch(a){throw await d(i),a}try{await n.rename(i,e)}catch(a){if(process.platform==="win32"&&(l(a,"EPERM")||l(a,"EBUSY"))){let u=a;for(const f of _){await new Promise(s=>setTimeout(s,f));try{await n.rename(i,e);return}catch(s){if(u=s,!l(s,"EPERM")&&!l(s,"EBUSY"))break}}throw await d(i),u}if(l(a,"EXDEV")){try{await n.copyFile(i,e)}finally{await d(i)}return}throw await d(i),a}}async function S(e,t){const r=c.dirname(e);await p(r);const o=await n.open(e,"a");try{await o.writeFile(`${t}
2
+ `,"utf8")}finally{await o.close()}}async function b(e){try{await n.unlink(e)}catch(t){if(!m(t))throw t}}function l(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}export{S as appendLineAtomic,p as ensureDir,m as isFileAbsentError,g as isFileMissingError,A as pathExists,N as readFileIfExists,R as readRegularFile,b as removeFileIfExists,D as transactionPreviewNonRegularFileError,$ as writeFileAtomic};
3
3
  //# sourceMappingURL=fs-utils.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="151124a3-cefa-55d3-bf4f-bd8f2553ad72")}catch{}})();import{constants as osConstants}from"node:os";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const HOST_ENVIRONMENT_FAULTS=new Map([["EACCES",{summary:"was denied filesystem permission",recovery:"Grant the required filesystem access, then retry.",category:"permission"}],["EDQUOT",{summary:"exceeded the filesystem quota",recovery:"Raise or reclaim the filesystem quota, then retry.",category:"capacity"}],["EMFILE",{summary:"exhausted the process file-descriptor limit",recovery:"Close unused file handles or raise the process limit, then retry.",category:"resource"}],["ENFILE",{summary:"exhausted the host file-descriptor limit",recovery:"Free host file descriptors or raise the host limit, then retry.",category:"resource"}],["ENOMEM",{summary:"ran out of available memory",recovery:"Free memory or reduce concurrent work, then retry.",category:"resource"}],["ENOSPC",{summary:"ran out of storage space",recovery:"Free storage on the filesystem holding the project, then retry.",category:"capacity"}],["EPERM",{summary:"was denied by the host permission policy",recovery:"Grant the required filesystem permission, then retry.",category:"permission"}],["EROFS",{summary:"targeted a read-only filesystem",recovery:"Use a writable project filesystem or remount it read-write, then retry.",category:"permission"}]]),OPERATION_PATTERN=/^[a-z][a-z0-9_]{0,63}$/u,HOST_ENVIRONMENT_ERRNO_NAMES=new Map([[osConstants.errno.EACCES,"EACCES"],[osConstants.errno.EDQUOT,"EDQUOT"],[osConstants.errno.EMFILE,"EMFILE"],[osConstants.errno.ENFILE,"ENFILE"],[osConstants.errno.ENOMEM,"ENOMEM"],[osConstants.errno.ENOSPC,"ENOSPC"],[osConstants.errno.EPERM,"EPERM"],[osConstants.errno.EROFS,"EROFS"]].filter(([errno])=>Number.isInteger(errno))),HOST_ENVIRONMENT_FAULT_CODES={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function classifyHostEnvironmentFault(error){if(typeof error!="object"||error===null)return null;const errorRecord=error;return typeof errorRecord.code=="string"&&HOST_ENVIRONMENT_FAULTS.has(errorRecord.code)?errorRecord.code:typeof errorRecord.errno!="number"||!Number.isInteger(errorRecord.errno)?null:HOST_ENVIRONMENT_ERRNO_NAMES.get(Math.abs(errorRecord.errno))??null}function translateHostEnvironmentFault(error,operation,options={}){const errno=classifyHostEnvironmentFault(error);if(errno===null)return null;if(!OPERATION_PATTERN.test(operation))throw new PmCliError("Host environment operation labels must be bounded identifiers.",EXIT_CODE.USAGE,{code:"host_environment_operation_invalid",field:"operation"});const fault=HOST_ENVIRONMENT_FAULTS.get(errno);return new PmCliError(`Host filesystem operation ${operation} ${fault.summary}.`,EXIT_CODE.GENERIC_FAILURE,{code:options.codes?.[fault.category]??HOST_ENVIRONMENT_FAULT_CODES[fault.category].code,reason:errno,required:fault.recovery,why:options.why??"The operating system refused a required project filesystem operation.",nextSteps:[fault.recovery,...options.nextSteps??[]],...options.suggestedRetry?{recovery:{suggested_retry:options.suggestedRetry}}:{}})}async function withHostEnvironmentBoundary(operation,run,options={}){try{return await run()}catch(error){throw translateHostEnvironmentFault(error,operation,options)??error}}export{classifyHostEnvironmentFault,translateHostEnvironmentFault,withHostEnvironmentBoundary};
1
+ import{constants as t}from"node:os";import{EXIT_CODE as i}from"../shared/constants.js";import{PmCliError as a}from"../shared/errors.js";const c=new Map([["EACCES",{summary:"was denied filesystem permission",recovery:"Grant the required filesystem access, then retry.",category:"permission"}],["EDQUOT",{summary:"exceeded the filesystem quota",recovery:"Raise or reclaim the filesystem quota, then retry.",category:"capacity"}],["EMFILE",{summary:"exhausted the process file-descriptor limit",recovery:"Close unused file handles or raise the process limit, then retry.",category:"resource"}],["ENFILE",{summary:"exhausted the host file-descriptor limit",recovery:"Free host file descriptors or raise the host limit, then retry.",category:"resource"}],["ENOMEM",{summary:"ran out of available memory",recovery:"Free memory or reduce concurrent work, then retry.",category:"resource"}],["ENOSPC",{summary:"ran out of storage space",recovery:"Free storage on the filesystem holding the project, then retry.",category:"capacity"}],["EPERM",{summary:"was denied by the host permission policy",recovery:"Grant the required filesystem permission, then retry.",category:"permission"}],["EROFS",{summary:"targeted a read-only filesystem",recovery:"Use a writable project filesystem or remount it read-write, then retry.",category:"permission"}]]),y=/^[a-z][a-z0-9_]{0,63}$/u,m=new Map([[t.errno.EACCES,"EACCES"],[t.errno.EDQUOT,"EDQUOT"],[t.errno.EMFILE,"EMFILE"],[t.errno.ENFILE,"ENFILE"],[t.errno.ENOMEM,"ENOMEM"],[t.errno.ENOSPC,"ENOSPC"],[t.errno.EPERM,"EPERM"],[t.errno.EROFS,"EROFS"]].filter(([r])=>Number.isInteger(r))),u={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function E(r){if(typeof r!="object"||r===null)return null;const e=r;return typeof e.code=="string"&&c.has(e.code)?e.code:typeof e.errno!="number"||!Number.isInteger(e.errno)?null:m.get(Math.abs(e.errno))??null}function l(r,e,o={}){const s=E(r);if(s===null)return null;if(!y.test(e))throw new a("Host environment operation labels must be bounded identifiers.",i.USAGE,{code:"host_environment_operation_invalid",field:"operation"});const n=c.get(s);return new a(`Host filesystem operation ${e} ${n.summary}.`,i.GENERIC_FAILURE,{code:o.codes?.[n.category]??u[n.category].code,reason:s,required:n.recovery,why:o.why??"The operating system refused a required project filesystem operation.",nextSteps:[n.recovery,...o.nextSteps??[]],...o.suggestedRetry?{recovery:{suggested_retry:o.suggestedRetry}}:{}})}async function p(r,e,o={}){try{return await e()}catch(s){throw l(s,r,o)??s}}export{E as classifyHostEnvironmentFault,l as translateHostEnvironmentFault,p as withHostEnvironmentBoundary};
2
2
  //# sourceMappingURL=host-environment-errors.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c24aeefc-5ee2-5a06-9a16-941d89b10cd7")}catch{}})();export*from"./fs-utils.js";
1
+ export*from"./fs-utils.js";
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="01422574-583a-5fd1-bc00-f61f430073cd")}catch{}})();import path from"path";function isPathWithinDirectory(directory,targetPath){const relative=path.relative(directory,targetPath);return relative.length===0?!0:!relative.startsWith("..")&&!path.isAbsolute(relative)}export{isPathWithinDirectory};
1
+ import r from"path";function o(e,i){const t=r.relative(e,i);return t.length===0?!0:!t.startsWith("..")&&!r.isAbsolute(t)}export{o as isPathWithinDirectory};
2
2
  //# sourceMappingURL=path-utils.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="67f9184e-08b6-5f21-9f92-e60974adbf1e")}catch{}})();const CONTENT_FIELD_ORDER=["notes","learnings","files","docs","tests","comments","deps","body","linked_command"];function hasEntries(value){return Array.isArray(value)&&value.length>0}function hasBody(body){return typeof body=="string"&&body.trim().length>0}function hasLinkedCommand(tests){return Array.isArray(tests)?tests.some(entry=>{if(typeof entry!="object"||entry===null)return!1;const command=entry.command;return typeof command=="string"&&command.trim().length>0}):!1}function isContentFieldPresent(item,field){switch(field){case"notes":return hasEntries(item.notes);case"learnings":return hasEntries(item.learnings);case"files":return hasEntries(item.files);case"docs":return hasEntries(item.docs);case"tests":return hasEntries(item.tests);case"comments":return hasEntries(item.comments);case"deps":return hasEntries(item.dependencies);case"body":return hasBody(item.body);case"linked_command":return hasLinkedCommand(item.tests)}}function hasContentFieldFilter(filters){return CONTENT_FIELD_ORDER.some(field=>filters[field]!==void 0)}function itemMatchesContentFilters(item,filters){for(const field of CONTENT_FIELD_ORDER){const selection=filters[field];if(selection===void 0)continue;const present=isContentFieldPresent(item,field);if(selection==="present"&&!present||selection==="absent"&&present)return!1}return!0}function filterByContentFields(items,filters){return hasContentFieldFilter(filters)?items.filter(item=>itemMatchesContentFilters(item,filters)):[...items]}function contentFiltersNeedCollections(filters){return CONTENT_FIELD_ORDER.some(field=>field!=="body"&&filters[field]!==void 0)}function contentFiltersNeedBody(filters){return filters.body!==void 0}function roundPercent(present,total){return total===0?100:Math.round(present/total*1e3)/10}function emptyUtilizationFields(){const record={};for(const field of CONTENT_FIELD_ORDER)record[field]={present:0,total:0,percent:100};return record}function computeContentFieldUtilization(items){const fields=emptyUtilizationFields(),total=items.length;for(const item of items)for(const field of CONTENT_FIELD_ORDER)isContentFieldPresent(item,field)&&(fields[field].present+=1);for(const field of CONTENT_FIELD_ORDER)fields[field].total=total,fields[field].percent=roundPercent(fields[field].present,total);const bodyPopulated=fields.body,emptyBodyCount=total-bodyPopulated.present,emptyBody={present:emptyBodyCount,total,percent:roundPercent(emptyBodyCount,total)};return{total_items:total,fields,body_populated:bodyPopulated,empty_body:emptyBody}}export{CONTENT_FIELD_ORDER,computeContentFieldUtilization,contentFiltersNeedBody,contentFiltersNeedCollections,filterByContentFields,hasContentFieldFilter,isContentFieldPresent,itemMatchesContentFilters};
1
+ const s=["notes","learnings","files","docs","tests","comments","deps","body","linked_command"];function r(e){return Array.isArray(e)&&e.length>0}function a(e){return typeof e=="string"&&e.trim().length>0}function p(e){return Array.isArray(e)?e.some(n=>{if(typeof n!="object"||n===null)return!1;const t=n.command;return typeof t=="string"&&t.trim().length>0}):!1}function u(e,n){switch(n){case"notes":return r(e.notes);case"learnings":return r(e.learnings);case"files":return r(e.files);case"docs":return r(e.docs);case"tests":return r(e.tests);case"comments":return r(e.comments);case"deps":return r(e.dependencies);case"body":return a(e.body);case"linked_command":return p(e.tests)}}function y(e){return s.some(n=>e[n]!==void 0)}function m(e,n){for(const t of s){const o=n[t];if(o===void 0)continue;const c=u(e,t);if(o==="present"&&!c||o==="absent"&&c)return!1}return!0}function b(e,n){return y(n)?e.filter(t=>m(t,n)):[...e]}function F(e){return s.some(n=>n!=="body"&&e[n]!==void 0)}function g(e){return e.body!==void 0}function f(e,n){return n===0?100:Math.round(e/n*1e3)/10}function h(){const e={};for(const n of s)e[n]={present:0,total:0,percent:100};return e}function C(e){const n=h(),t=e.length;for(const i of e)for(const d of s)u(i,d)&&(n[d].present+=1);for(const i of s)n[i].total=t,n[i].percent=f(n[i].present,t);const o=n.body,c=t-o.present,l={present:c,total:t,percent:f(c,t)};return{total_items:t,fields:n,body_populated:o,empty_body:l}}export{s as CONTENT_FIELD_ORDER,C as computeContentFieldUtilization,g as contentFiltersNeedBody,F as contentFiltersNeedCollections,b as filterByContentFields,y as hasContentFieldFilter,u as isContentFieldPresent,m as itemMatchesContentFilters};
2
2
  //# sourceMappingURL=content-fields.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e93db1eb-e524-58bf-af2e-cb5f22f3047b")}catch{}})();const ISSUE_CODE_PATTERN=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function extractIssueCode(title,options={}){if(typeof title!="string")return null;const trimmed=title.trim();if(trimmed.length===0)return null;const match=ISSUE_CODE_PATTERN.exec(trimmed);if(!match)return null;const rawCode=match[1],normalized=rawCode.toUpperCase(),rawPrefix=rawCode.slice(0,rawCode.lastIndexOf("-")),configured=new Set((options.configuredPrefixes??[]).map(prefix=>prefix.trim().replace(/-+$/u,"").toUpperCase())),remainder=trimmed.slice(rawCode.length),evidence=options.evidenceText?.toUpperCase()??"",hasExplicitBodyEvidence=evidence.includes(`ISSUE CODE: ${normalized}`)||evidence.includes(`ISSUE CODE \`${normalized}\``)||evidence.includes(`\`${normalized}\``)||evidence.includes(`[${normalized}]`);return rawPrefix===rawPrefix.toUpperCase()||/^\s*(?::|—|–|\])/u.test(remainder)||configured.has(rawPrefix.toUpperCase())||hasExplicitBodyEvidence?normalized:null}function isNonEmptyIdReference(value){return typeof value=="string"&&value.trim().length>0}function findCodeCollisionEntries(entries){const idsInGroup=new Set(entries.map(entry=>entry.id.toLowerCase())),prerequisites=new Map,dependents=new Map;for(const entry of entries){const id=entry.id.toLowerCase(),targets=new Set([...entry.parent===null?[]:[entry.parent.toLowerCase()],...entry.derivations].filter(target=>target!==id&&idsInGroup.has(target)));prerequisites.set(id,targets);for(const target of targets){const successors=dependents.get(target)??[];successors.push(id),dependents.set(target,successors)}}const queue=[...[...prerequisites].filter(([,targets])=>targets.size===0).map(([id])=>id)],derived=new Set;for(let index=0;index<queue.length;index+=1)for(const successor of dependents.get(queue[index])??[]){const targets=prerequisites.get(successor);targets.delete(queue[index]),targets.size===0&&(derived.add(successor),queue.push(successor))}return entries.filter(entry=>!derived.has(entry.id.toLowerCase()))}function findDuplicateIssueCodes(items,options={}){const byCode=new Map;for(const item of items){if(typeof item.title!="string"||isNonEmptyIdReference(item.duplicate_of))continue;const code=extractIssueCode(item.title,{...options,evidenceText:item.body});if(code===null)continue;let entries=byCode.get(code);entries||(entries=[],byCode.set(code,entries)),entries.some(entry=>entry.id===item.id)||entries.push({id:item.id,title:item.title,parent:isNonEmptyIdReference(item.parent)?item.parent.trim():null,derivations:(item.dependencies??[]).filter(edge=>["discovered_from","supersedes","incident_from"].includes(edge.kind)).map(edge=>edge.id.trim().toLowerCase()).filter(id=>id!==item.id.toLowerCase())})}const duplicates=[];for(const[code,entries]of byCode){if(entries.length<2)continue;const collisionEntries=findCodeCollisionEntries(entries);if(collisionEntries.length<2)continue;const sorted=[...collisionEntries].sort((left,right)=>left.id.localeCompare(right.id));duplicates.push({code,count:sorted.length,ids:sorted.map(entry=>entry.id),titles:sorted.map(entry=>entry.title)})}return duplicates.sort((left,right)=>left.code.localeCompare(right.code))}export{extractIssueCode,findDuplicateIssueCodes};
1
+ const m=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function C(r,u={}){if(typeof r!="string")return null;const c=r.trim();if(c.length===0)return null;const d=m.exec(c);if(!d)return null;const t=d[1],n=t.toUpperCase(),o=t.slice(0,t.lastIndexOf("-")),e=new Set((u.configuredPrefixes??[]).map(p=>p.trim().replace(/-+$/u,"").toUpperCase())),s=c.slice(t.length),i=u.evidenceText?.toUpperCase()??"",l=i.includes(`ISSUE CODE: ${n}`)||i.includes(`ISSUE CODE \`${n}\``)||i.includes(`\`${n}\``)||i.includes(`[${n}]`);return o===o.toUpperCase()||/^\s*(?::|—|–|\])/u.test(s)||e.has(o.toUpperCase())||l?n:null}function f(r){return typeof r=="string"&&r.trim().length>0}function g(r){const u=new Set(r.map(e=>e.id.toLowerCase())),c=new Map,d=new Map;for(const e of r){const s=e.id.toLowerCase(),i=new Set([...e.parent===null?[]:[e.parent.toLowerCase()],...e.derivations].filter(l=>l!==s&&u.has(l)));c.set(s,i);for(const l of i){const a=d.get(l)??[];a.push(s),d.set(l,a)}}const n=[...[...c].filter(([,e])=>e.size===0).map(([e])=>e)],o=new Set;for(let e=0;e<n.length;e+=1)for(const s of d.get(n[e])??[]){const i=c.get(s);i.delete(n[e]),i.size===0&&(o.add(s),n.push(s))}return r.filter(e=>!o.has(e.id.toLowerCase()))}function h(r,u={}){const c=new Map;for(const t of r){if(typeof t.title!="string"||f(t.duplicate_of))continue;const n=C(t.title,{...u,evidenceText:t.body});if(n===null)continue;let o=c.get(n);o||(o=[],c.set(n,o)),o.some(e=>e.id===t.id)||o.push({id:t.id,title:t.title,parent:f(t.parent)?t.parent.trim():null,derivations:(t.dependencies??[]).filter(e=>["discovered_from","supersedes","incident_from"].includes(e.kind)).map(e=>e.id.trim().toLowerCase()).filter(e=>e!==t.id.toLowerCase())})}const d=[];for(const[t,n]of c){if(n.length<2)continue;const o=g(n);if(o.length<2)continue;const e=[...o].sort((s,i)=>s.id.localeCompare(i.id));d.push({code:t,count:e.length,ids:e.map(s=>s.id),titles:e.map(s=>s.title)})}return d.sort((t,n)=>t.code.localeCompare(n.code))}export{C as extractIssueCode,h as findDuplicateIssueCodes};
2
2
  //# sourceMappingURL=issue-codes.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f9d73d74-7c4e-5ea9-b34c-c984b4c15ab3")}catch{}})();import{toNonEmptyStringOrUndefined}from"../shared/primitives.js";const LIFECYCLE_BUCKET_ORDER=["open","in_progress","blocked","draft","closed","canceled","other"];function normalizeStatus(status,registry){const trimmed=status.trim().toLowerCase();return registry.alias_to_id.get(trimmed)??trimmed}function lifecycleClassifierFromStatusRegistry(registry){return{isTerminal(status){return registry.terminal_statuses.has(normalizeStatus(status,registry))},classify(status){const id=normalizeStatus(status,registry);return registry.terminal_canceled_statuses.has(id)?"canceled":registry.terminal_statuses.has(id)?"closed":registry.blocked_statuses.has(id)?"blocked":registry.draft_statuses.has(id)?"draft":id===registry.open_status?"open":registry.active_statuses.has(id)?"in_progress":"other"}}}function isAcMissing(item){return toNonEmptyStringOrUndefined(item.acceptance_criteria)===void 0}function isEstimateMissing(item){return!Number.isFinite(item.estimated_minutes)}function isResolutionMissing(item,classifier){return classifier.isTerminal(item.status)?toNonEmptyStringOrUndefined(item.resolution)===void 0:!1}function isReviewerMissing(item){return toNonEmptyStringOrUndefined(item.reviewer)===void 0}function isRiskMissing(item){return toNonEmptyStringOrUndefined(item.risk)===void 0}function isConfidenceMissing(item){return typeof item.confidence=="number"?!Number.isFinite(item.confidence):toNonEmptyStringOrUndefined(item.confidence)===void 0}function isSprintMissing(item){return toNonEmptyStringOrUndefined(item.sprint)===void 0}function isReleaseMissing(item){return toNonEmptyStringOrUndefined(item.release)===void 0}function hasMissingMetadataFilter(filters){return!!(filters.acMissing||filters.estimatesMissing||filters.resolutionMissing||filters.reviewerMissing||filters.riskMissing||filters.confidenceMissing||filters.sprintMissing||filters.releaseMissing||filters.metadataMissing)}function itemMatchesSpecificMetadataFilters(item,filters,classifier){return[[filters.acMissing,isAcMissing(item)],[filters.estimatesMissing,isEstimateMissing(item)],[filters.resolutionMissing,isResolutionMissing(item,classifier)],[filters.reviewerMissing,isReviewerMissing(item)],[filters.riskMissing,isRiskMissing(item)],[filters.confidenceMissing,isConfidenceMissing(item)],[filters.sprintMissing,isSprintMissing(item)],[filters.releaseMissing,isReleaseMissing(item)]].every(([requested,matched])=>requested!==!0||matched)}function itemMatchesCoreMetadataMissingUnion(item,classifier){return isAcMissing(item)||isEstimateMissing(item)||isResolutionMissing(item,classifier)}function itemMatchesMissingMetadata(item,filters,classifier){return hasMissingMetadataFilter(filters)?!(!itemMatchesSpecificMetadataFilters(item,filters,classifier)||filters.metadataMissing&&!itemMatchesCoreMetadataMissingUnion(item,classifier)):!0}function filterMissingMetadata(items,filters,classifier){return hasMissingMetadataFilter(filters)?items.filter(item=>itemMatchesMissingMetadata(item,filters,classifier)):[...items]}const COVERAGE_FIELD_ORDER=["acceptance_criteria","estimated_minutes","resolution","tags","parent"];function isFieldPresent(item,field){switch(field){case"acceptance_criteria":return!isAcMissing(item);case"estimated_minutes":return!isEstimateMissing(item);case"resolution":return toNonEmptyStringOrUndefined(item.resolution)!==void 0;case"tags":return Array.isArray(item.tags)&&item.tags.length>0;default:return toNonEmptyStringOrUndefined(item.parent)!==void 0}}function isFieldApplicable(item,field,classifier){return field==="resolution"?classifier.isTerminal(item.status):!0}function roundPercent(present,applicable){return applicable===0?100:Math.round(present/applicable*1e3)/10}function emptyFieldCoverage(){const record={};for(const field of COVERAGE_FIELD_ORDER)record[field]={present:0,applicable:0,percent:100};return record}function accumulateCoverage(target,item,classifier){for(const field of COVERAGE_FIELD_ORDER){if(!isFieldApplicable(item,field,classifier))continue;const entry=target[field];entry.applicable+=1,isFieldPresent(item,field)&&(entry.present+=1)}}function finalizePercentages(record){for(const field of COVERAGE_FIELD_ORDER){const entry=record[field];entry.percent=roundPercent(entry.present,entry.applicable)}}function computeMetadataCoverage(items,classifier){const overall=emptyFieldCoverage(),byType={};for(const item of items){accumulateCoverage(overall,item,classifier);const typeRecord=byType[item.type]??(byType[item.type]=emptyFieldCoverage());accumulateCoverage(typeRecord,item,classifier)}finalizePercentages(overall);for(const typeRecord of Object.values(byType))finalizePercentages(typeRecord);return{overall,by_type:byType}}const EMPTY_GROUP_LABELS={assignee:"(unassigned)",priority:"(no priority)",tag:"(untagged)",parent:"(unparented)",type:"(untyped)",status:"(no status)"};function emptyGroupLabel(dimension){return EMPTY_GROUP_LABELS[dimension]}function emptyBuckets(){return{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}function groupKeysForItem(item,dimension,options){switch(dimension){case"assignee":return[toNonEmptyStringOrUndefined(item.assignee)??null];case"parent":return[toNonEmptyStringOrUndefined(item.parent)??null];case"type":return[toNonEmptyStringOrUndefined(item.type)??null];case"status":return[toNonEmptyStringOrUndefined(item.status)??null];case"priority":return[typeof item.priority=="number"?`P${item.priority}`:null];default:{const prefix=options.tagPrefix?.trim(),matching=(Array.isArray(item.tags)?item.tags:[]).filter(tag=>typeof tag=="string"&&tag.length>0&&(!prefix||tag.startsWith(prefix)));return matching.length>0?matching:[null]}}}function groupItemsByDimension(items,dimension,classifier,options={}){const rows=new Map;let totalItems=0;for(const item of items){totalItems+=1;const bucket=classifier.classify(item.status);for(const key of groupKeysForItem(item,dimension,options)){const mapKey=key??"\0empty";let row=rows.get(mapKey);row||(row={label:key??emptyGroupLabel(dimension),key,buckets:emptyBuckets(),total:0},rows.set(mapKey,row)),row.buckets[bucket]+=1,row.total+=1}}const sorted=[...rows.values()].sort((left,right)=>right.total!==left.total?right.total-left.total:left.key===null?1:right.key===null?-1:left.label.localeCompare(right.label));return{dimension,rows:sorted,total_items:totalItems}}function computeLifecycleDistribution(items,classifier){const buckets=emptyBuckets();for(const item of items)buckets[classifier.classify(item.status)]+=1;return buckets}export{COVERAGE_FIELD_ORDER,LIFECYCLE_BUCKET_ORDER,computeLifecycleDistribution,computeMetadataCoverage,emptyGroupLabel,filterMissingMetadata,groupItemsByDimension,hasMissingMetadataFilter,isAcMissing,isConfidenceMissing,isEstimateMissing,isReleaseMissing,isResolutionMissing,isReviewerMissing,isRiskMissing,isSprintMissing,itemMatchesMissingMetadata,lifecycleClassifierFromStatusRegistry};
1
+ import{toNonEmptyStringOrUndefined as i}from"../shared/primitives.js";const U=["open","in_progress","blocked","draft","closed","canceled","other"];function y(e,t){const n=e.trim().toLowerCase();return t.alias_to_id.get(n)??n}function G(e){return{isTerminal(t){return e.terminal_statuses.has(y(t,e))},classify(t){const n=y(t,e);return e.terminal_canceled_statuses.has(n)?"canceled":e.terminal_statuses.has(n)?"closed":e.blocked_statuses.has(n)?"blocked":e.draft_statuses.has(n)?"draft":n===e.open_status?"open":e.active_statuses.has(n)?"in_progress":"other"}}}function l(e){return i(e.acceptance_criteria)===void 0}function d(e){return!Number.isFinite(e.estimated_minutes)}function _(e,t){return t.isTerminal(e.status)?i(e.resolution)===void 0:!1}function R(e){return i(e.reviewer)===void 0}function v(e){return i(e.risk)===void 0}function C(e){return typeof e.confidence=="number"?!Number.isFinite(e.confidence):i(e.confidence)===void 0}function E(e){return i(e.sprint)===void 0}function w(e){return i(e.release)===void 0}function b(e){return!!(e.acMissing||e.estimatesMissing||e.resolutionMissing||e.reviewerMissing||e.riskMissing||e.confidenceMissing||e.sprintMissing||e.releaseMissing||e.metadataMissing)}function F(e,t,n){return[[t.acMissing,l(e)],[t.estimatesMissing,d(e)],[t.resolutionMissing,_(e,n)],[t.reviewerMissing,R(e)],[t.riskMissing,v(e)],[t.confidenceMissing,C(e)],[t.sprintMissing,E(e)],[t.releaseMissing,w(e)]].every(([s,o])=>s!==!0||o)}function A(e,t){return l(e)||d(e)||_(e,t)}function L(e,t,n){return b(t)?!(!F(e,t,n)||t.metadataMissing&&!A(e,n)):!0}function K(e,t,n){return b(t)?e.filter(r=>L(r,t,n)):[...e]}const g=["acceptance_criteria","estimated_minutes","resolution","tags","parent"];function P(e,t){switch(t){case"acceptance_criteria":return!l(e);case"estimated_minutes":return!d(e);case"resolution":return i(e.resolution)!==void 0;case"tags":return Array.isArray(e.tags)&&e.tags.length>0;default:return i(e.parent)!==void 0}}function O(e,t,n){return t==="resolution"?n.isTerminal(e.status):!0}function S(e,t){return t===0?100:Math.round(e/t*1e3)/10}function m(){const e={};for(const t of g)e[t]={present:0,applicable:0,percent:100};return e}function h(e,t,n){for(const r of g){if(!O(t,r,n))continue;const s=e[r];s.applicable+=1,P(t,r)&&(s.present+=1)}}function x(e){for(const t of g){const n=e[t];n.percent=S(n.present,n.applicable)}}function N(e,t){const n=m(),r={};for(const s of e){h(n,s,t);const o=r[s.type]??(r[s.type]=m());h(o,s,t)}x(n);for(const s of Object.values(r))x(s);return{overall:n,by_type:r}}const T={assignee:"(unassigned)",priority:"(no priority)",tag:"(untagged)",parent:"(unparented)",type:"(untyped)",status:"(no status)"};function B(e){return T[e]}function k(){return{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}function D(e,t,n){switch(t){case"assignee":return[i(e.assignee)??null];case"parent":return[i(e.parent)??null];case"type":return[i(e.type)??null];case"status":return[i(e.status)??null];case"priority":return[typeof e.priority=="number"?`P${e.priority}`:null];default:{const r=n.tagPrefix?.trim(),o=(Array.isArray(e.tags)?e.tags:[]).filter(c=>typeof c=="string"&&c.length>0&&(!r||c.startsWith(r)));return o.length>0?o:[null]}}}function z(e,t,n,r={}){const s=new Map;let o=0;for(const a of e){o+=1;const u=n.classify(a.status);for(const p of D(a,t,r)){const M=p??"\0empty";let f=s.get(M);f||(f={label:p??B(t),key:p,buckets:k(),total:0},s.set(M,f)),f.buckets[u]+=1,f.total+=1}}const c=[...s.values()].sort((a,u)=>u.total!==a.total?u.total-a.total:a.key===null?1:u.key===null?-1:a.label.localeCompare(u.label));return{dimension:t,rows:c,total_items:o}}function Y(e,t){const n=k();for(const r of e)n[t.classify(r.status)]+=1;return n}export{g as COVERAGE_FIELD_ORDER,U as LIFECYCLE_BUCKET_ORDER,Y as computeLifecycleDistribution,N as computeMetadataCoverage,B as emptyGroupLabel,K as filterMissingMetadata,z as groupItemsByDimension,b as hasMissingMetadataFilter,l as isAcMissing,C as isConfidenceMissing,d as isEstimateMissing,w as isReleaseMissing,_ as isResolutionMissing,R as isReviewerMissing,v as isRiskMissing,E as isSprintMissing,L as itemMatchesMissingMetadata,G as lifecycleClassifierFromStatusRegistry};
2
2
  //# sourceMappingURL=metadata-coverage.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="01a75358-2a0c-531d-bf79-ff353e1990c9")}catch{}})();import{historyDigest,resolveHistoryHashAlgorithm}from"./digest.js";const HISTORY_BRIDGE_VERSION=1;function isHistoryBridgeBreak(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;const candidate=value;return Object.keys(candidate).length===3&&typeof candidate.gap_from=="string"&&typeof candidate.gap_to=="string"&&candidate.gap_from!==candidate.gap_to&&(candidate.record_hash===null||typeof candidate.record_hash=="string")}function readHistoryBridge(entry){if(!Object.hasOwn(entry,"bridge"))return;const bridge=entry.bridge;if(entry.op!=="history_repair"||typeof entry.record_hash!="string"||typeof bridge!="object"||bridge===null||Array.isArray(bridge))return"invalid";const candidate=bridge;return candidate.version===HISTORY_BRIDGE_VERSION&&Object.keys(candidate).length===3&&typeof candidate.segment_digest=="string"&&Array.isArray(candidate.breaks)&&candidate.breaks.length>0&&[...candidate.breaks].every(isHistoryBridgeBreak)?candidate:"invalid"}function describeHistoryBreak(previous,entry){return{gap_from:previous.after_hash,gap_to:entry.before_hash,record_hash:entry.record_hash??null}}function matchesHistoryBreak(descriptor,previous,entry){return descriptor!==void 0&&descriptor.gap_from===previous.after_hash&&descriptor.gap_to===entry.before_hash&&descriptor.record_hash===(entry.record_hash??null)}function digestBridgedSegment(segment,bridge){return historyDigest(canonicalBridgeJson(segment),resolveHistoryHashAlgorithm(bridge.hash_algorithm))}const ARRAY_INDEX_KEY=/^(?:0|[1-9]\d*)$/u,isArrayIndexKey=key=>ARRAY_INDEX_KEY.test(key)&&Number(key)<2**32-1;function canonicalBridgeJson(value){if(Array.isArray(value))return`[${value.map(item=>canonicalBridgeJson(item??null)).join(",")}]`;if(value===null||typeof value!="object")return JSON.stringify(value);const record=value,keys=Object.keys(record).filter(key=>record[key]!==void 0);return`{${[...keys.filter(isArrayIndexKey),...keys.filter(key=>!isArrayIndexKey(key)).sort()].map(key=>`${JSON.stringify(key)}:${canonicalBridgeJson(record[key])}`).join(",")}}`}function findNextHistoryBridge(entries,index){for(let candidate=index+1;candidate<entries.length;candidate+=1)if(Object.hasOwn(entries[candidate],"bridge"))return candidate;return-1}function safeSegmentDigest(segment,bridge){try{return digestBridgedSegment(segment,bridge)}catch{return null}}function findBridgedSegmentStart(entries,bridge,floor,end){const first=bridge.breaks[0];let materialized=-1;for(let start=Math.max(1,floor);start<end;start+=1){const entry=entries[start],anchored=entries[start-1].after_hash===first.gap_from&&entry.before_hash===first.gap_to,named=first.record_hash!==null&&entry.record_hash===first.record_hash;if(!anchored&&!named)continue;const covered=entries.slice(start,end);if(safeSegmentDigest(covered,entries[end])===bridge.segment_digest)return{start,digest:!0};materialized<0&&anchored&&covered.every(record=>record.replay_inexact===!0)&&(materialized=start)}return{start:materialized,digest:!1}}function locateBridgedSegments(entries){const located={segments:[],unlocated:[],undigested:[]};let floor=1;return entries.forEach((entry,index)=>{if(!Object.hasOwn(entry,"bridge"))return;const bridge=readHistoryBridge(entry),found=typeof bridge=="object"?findBridgedSegmentStart(entries,bridge,floor,index):{start:-1,digest:!1},start=found.start;start<0?located.unlocated.push(index):found.digest||located.undigested.push(index),located.segments.push({start:start<0?floor:start,end:index,exact:start>=0}),start>=0&&(floor=index+1)}),located}export{HISTORY_BRIDGE_VERSION,describeHistoryBreak,digestBridgedSegment,findNextHistoryBridge,locateBridgedSegments,matchesHistoryBreak,readHistoryBridge};
1
+ import{historyDigest as l,resolveHistoryHashAlgorithm as _}from"./digest.js";const p=1;function y(r){if(typeof r!="object"||r===null||Array.isArray(r))return!1;const t=r;return Object.keys(t).length===3&&typeof t.gap_from=="string"&&typeof t.gap_to=="string"&&t.gap_from!==t.gap_to&&(t.record_hash===null||typeof t.record_hash=="string")}function m(r){if(!Object.hasOwn(r,"bridge"))return;const t=r.bridge;if(r.op!=="history_repair"||typeof r.record_hash!="string"||typeof t!="object"||t===null||Array.isArray(t))return"invalid";const e=t;return e.version===p&&Object.keys(e).length===3&&typeof e.segment_digest=="string"&&Array.isArray(e.breaks)&&e.breaks.length>0&&[...e.breaks].every(y)?e:"invalid"}function k(r,t){return{gap_from:r.after_hash,gap_to:t.before_hash,record_hash:t.record_hash??null}}function S(r,t,e){return r!==void 0&&r.gap_from===t.after_hash&&r.gap_to===e.before_hash&&r.record_hash===(e.record_hash??null)}function b(r,t){return l(c(r),_(t.hash_algorithm))}const O=/^(?:0|[1-9]\d*)$/u,g=r=>O.test(r)&&Number(r)<2**32-1;function c(r){if(Array.isArray(r))return`[${r.map(n=>c(n??null)).join(",")}]`;if(r===null||typeof r!="object")return JSON.stringify(r);const t=r,e=Object.keys(t).filter(n=>t[n]!==void 0);return`{${[...e.filter(g),...e.filter(n=>!g(n)).sort()].map(n=>`${JSON.stringify(n)}:${c(t[n])}`).join(",")}}`}function x(r,t){for(let e=t+1;e<r.length;e+=1)if(Object.hasOwn(r[e],"bridge"))return e;return-1}function j(r,t){try{return b(r,t)}catch{return null}}function A(r,t,e,i){const n=t.breaks[0];let a=-1;for(let s=Math.max(1,e);s<i;s+=1){const o=r[s],f=r[s-1].after_hash===n.gap_from&&o.before_hash===n.gap_to,h=n.record_hash!==null&&o.record_hash===n.record_hash;if(!f&&!h)continue;const d=r.slice(s,i);if(j(d,r[i])===t.segment_digest)return{start:s,digest:!0};a<0&&f&&d.every(u=>u.replay_inexact===!0)&&(a=s)}return{start:a,digest:!1}}function H(r){const t={segments:[],unlocated:[],undigested:[]};let e=1;return r.forEach((i,n)=>{if(!Object.hasOwn(i,"bridge"))return;const a=m(i),s=typeof a=="object"?A(r,a,e,n):{start:-1,digest:!1},o=s.start;o<0?t.unlocated.push(n):s.digest||t.undigested.push(n),t.segments.push({start:o<0?e:o,end:n,exact:o>=0}),o>=0&&(e=n+1)}),t}export{p as HISTORY_BRIDGE_VERSION,k as describeHistoryBreak,b as digestBridgedSegment,x as findNextHistoryBridge,H as locateBridgedSegments,S as matchesHistoryBreak,m as readHistoryBridge};
2
2
  //# sourceMappingURL=bridge.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="ca5b60a5-80a7-5e7d-917f-4c7649bcbab6")}catch{}})();import{createHash}from"node:crypto";const HISTORY_HASH_ALGORITHMS=["sha256","sha512"],LEGACY_HISTORY_HASH_ALGORITHM="sha256",CURRENT_HISTORY_HASH_ALGORITHM="sha256";function resolveHistoryHashAlgorithm(value){if(value===void 0)return LEGACY_HISTORY_HASH_ALGORITHM;if(value==="sha256"||value==="sha512")return value;throw new TypeError(`unsupported_history_hash_algorithm:${String(value)}`)}function historyDigest(value,algorithm){return createHash(resolveHistoryHashAlgorithm(algorithm)).update(value,"utf8").digest("hex")}export{CURRENT_HISTORY_HASH_ALGORITHM,HISTORY_HASH_ALGORITHMS,LEGACY_HISTORY_HASH_ALGORITHM,historyDigest,resolveHistoryHashAlgorithm};
1
+ import{createHash as o}from"node:crypto";const n=["sha256","sha512"],s="sha256",H="sha256";function e(t){if(t===void 0)return s;if(t==="sha256"||t==="sha512")return t;throw new TypeError(`unsupported_history_hash_algorithm:${String(t)}`)}function i(t,r){return o(e(r)).update(t,"utf8").digest("hex")}export{H as CURRENT_HISTORY_HASH_ALGORITHM,n as HISTORY_HASH_ALGORITHMS,s as LEGACY_HISTORY_HASH_ALGORITHM,i as historyDigest,e as resolveHistoryHashAlgorithm};
2
2
  //# sourceMappingURL=digest.js.map
@@ -1,4 +1,4 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="687cbe24-6d5c-5322-962d-455048eb84b5")}catch{}})();import{isFileMissingError}from"../fs/fs-utils.js";import fs from"node:fs/promises";import path from"node:path";import{writeStderr}from"../output/output.js";const DRIFT_CACHE_RELATIVE_PATH=path.join("runtime","history-drift-cache.json"),DRIFT_CACHE_ERROR_CODES={EINVAL:"invalid_cache_path",EISDIR:"cache_path_is_directory",ENOENT:"invalid_cache_path",ENOTDIR:"invalid_cache_path",ERR_FS_EISDIR:"cache_path_is_directory"};function getFilesystemErrorCode(error){return typeof error=="object"&&error!==null&&"code"in error&&typeof error.code=="string"?error.code:void 0}async function invalidateHistoryDriftCache(pmRoot){const cachePath=path.join(pmRoot,DRIFT_CACHE_RELATIVE_PATH);let pmRootIsDirectory=!1,rootFailureCode="invalid_cache_path";try{pmRootIsDirectory=(await fs.stat(await fs.realpath(pmRoot))).isDirectory()}catch(error){const errorCode=getFilesystemErrorCode(error);rootFailureCode=errorCode===void 0?"unknown":DRIFT_CACHE_ERROR_CODES[errorCode]??"filesystem_error"}if(!pmRootIsDirectory){writeStderr(`[pm] warning: history_drift_cache_invalidation_failed:${rootFailureCode}
2
- `);return}try{await fs.rm(cachePath,{force:!0})}catch(error){const errorCode=getFilesystemErrorCode(error);if(isFileMissingError(error))return;const code=errorCode===void 0?"unknown":DRIFT_CACHE_ERROR_CODES[errorCode]??"filesystem_error";writeStderr(`[pm] warning: history_drift_cache_invalidation_failed:${code}
3
- `)}}async function invalidateHistoryDriftCacheForPath(historyPath){const historyDirectory=path.dirname(path.resolve(historyPath));path.basename(historyDirectory)==="history"&&await invalidateHistoryDriftCache(path.dirname(historyDirectory))}export{invalidateHistoryDriftCache,invalidateHistoryDriftCacheForPath};
1
+ import{isFileMissingError as f}from"../fs/fs-utils.js";import a from"node:fs/promises";import i from"node:path";import{writeStderr as s}from"../output/output.js";const l=i.join("runtime","history-drift-cache.json"),d={EINVAL:"invalid_cache_path",EISDIR:"cache_path_is_directory",ENOENT:"invalid_cache_path",ENOTDIR:"invalid_cache_path",ERR_FS_EISDIR:"cache_path_is_directory"};function _(t){return typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:void 0}async function y(t){const e=i.join(t,l);let n=!1,c="invalid_cache_path";try{n=(await a.stat(await a.realpath(t))).isDirectory()}catch(o){const r=_(o);c=r===void 0?"unknown":d[r]??"filesystem_error"}if(!n){s(`[pm] warning: history_drift_cache_invalidation_failed:${c}
2
+ `);return}try{await a.rm(e,{force:!0})}catch(o){const r=_(o);if(f(o))return;const h=r===void 0?"unknown":d[r]??"filesystem_error";s(`[pm] warning: history_drift_cache_invalidation_failed:${h}
3
+ `)}}async function C(t){const e=i.dirname(i.resolve(t));i.basename(e)==="history"&&await y(i.dirname(e))}export{y as invalidateHistoryDriftCache,C as invalidateHistoryDriftCacheForPath};
4
4
  //# sourceMappingURL=drift-cache.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a535e1be-f99b-5898-af76-0c9d5b8a681d")}catch{}})();import{HISTORY_HASH_ALGORITHMS,resolveHistoryHashAlgorithm}from"./digest.js";import fs from"node:fs/promises";import{createHash}from"node:crypto";import path from"node:path";import{getHistoryPath}from"../store/paths.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";import{CURRENT_HISTORY_ITEM_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,hasNewerRecordSealFormat,hashDocumentVerificationCandidates}from"./history.js";import{verifyHistoryChainWithVersion}from"./replay.js";import{findHistoryIdentityDiscontinuities}from"./identity.js";import{getWorkspaceHistoryPath,inspectWorkspaceHistoryState,WORKSPACE_HISTORY_ID}from"./workspace-history.js";const READABLE_HISTORY_HASH_ALGORITHMS=new Set([void 0,...HISTORY_HASH_ALGORITHMS]),DRIFT_CACHE_VERSION=13,DRIFT_CACHE_FILENAME="history-drift-cache.json";function getDriftCachePath(pmRoot){return path.join(pmRoot,"runtime",DRIFT_CACHE_FILENAME)}async function loadDriftCache(pmRoot){try{const raw=await fs.readFile(getDriftCachePath(pmRoot),"utf8"),parsed=JSON.parse(raw);return parsed.version!==DRIFT_CACHE_VERSION||parsed.history_item_hash_version!==CURRENT_HISTORY_ITEM_HASH_VERSION||typeof parsed.entries!="object"||parsed.entries===null||Object.values(parsed.entries).some(entry=>typeof entry.chain_ok!="boolean"||typeof entry.latest_hash_comparable!="boolean"||!READABLE_HISTORY_HASH_ALGORITHMS.has(entry.hash_algorithm)||!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)&&entry.version_skew!==!0||entry.chain_ok&&entry.version_skew!==!0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)&&!entry.latest_hash_comparable)?null:parsed}catch{return null}}function createDriftScanAccumulator(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function buildDriftScanResult(accumulator){const driftedItems=[...new Set([...accumulator.missingStreams,...accumulator.unreadableStreams,...accumulator.hashMismatches,...accumulator.chainMismatches,...accumulator.versionSkews,...accumulator.workspaceStateMismatches.length>0||accumulator.workspaceStateMissing.length>0||accumulator.workspaceStateUnreadable.length>0?[WORKSPACE_HISTORY_ID]:[]])].sort((a,b)=>a.localeCompare(b));return{...accumulator,driftedItems}}async function scanWorkspaceHistory(pmRoot,previousEntries,nextEntries,verifyCacheHitByContent,accumulator){const historyPath=getWorkspaceHistoryPath(pmRoot);let stat;try{stat=await fs.stat(historyPath)}catch(error){return isFileMissingError(error)||accumulator.unreadableStreams.push(WORKSPACE_HISTORY_ID),!1}const missingCount=accumulator.missingStreams.length,resolved=await resolveStreamVerification({itemId:WORKSPACE_HISTORY_ID,historyPath,stat,cached:previousEntries[WORKSPACE_HISTORY_ID],verifyCacheHitByContent,accumulator});return resolved.verification?(resolved.verification.versionSkew&&accumulator.versionSkews.push(WORKSPACE_HISTORY_ID),resolved.verification.chainOk||accumulator.chainMismatches.push(WORKSPACE_HISTORY_ID),nextEntries[WORKSPACE_HISTORY_ID]={mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size,content_hash:resolved.verification.contentHash,latest_after_hash:resolved.verification.latestAfterHash,chain_ok:resolved.verification.chainOk,version_skew:resolved.verification.versionSkew,latest_hash_comparable:resolved.verification.latestHashComparable,item_hash_version:resolved.verification.itemHashVersion,hash_algorithm:resolved.verification.hashAlgorithm},resolved.cacheDirty):(accumulator.missingStreams.splice(missingCount),resolved.cacheDirty)}function hasUnsupportedHistoryCapability(entry){return!READABLE_HISTORY_HASH_ALGORITHMS.has(entry.hash_algorithm)||entry.item_hash_version!==void 0&&!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)||hasNewerRecordSealFormat(entry)}async function verifyHistoryStream(historyPath){const raw=await fs.readFile(historyPath,"utf8"),contentHash=createHash("sha256").update(raw).digest("hex");if(raw.trim().length===0)return null;const entries=[];let latestAfterHash=null;for(const line of raw.split(/\r?\n/)){const trimmed=line.trim();if(trimmed.length===0)continue;const parsed=JSON.parse(trimmed);if(typeof parsed.after_hash!="string"||parsed.after_hash.trim().length===0)throw new Error("missing after_hash");entries.push(parsed),latestAfterHash=parsed.after_hash}if(!latestAfterHash)return null;const verification=verifyHistoryChainWithVersion(entries),versionSkew=entries.some(hasUnsupportedHistoryCapability),latestEntry=entries[entries.length-1],algorithmSupported=READABLE_HISTORY_HASH_ALGORITHMS.has(latestEntry.hash_algorithm),latestExplicitVersion=latestEntry.item_hash_version,latestExplicitVersionSupported=latestExplicitVersion!==void 0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(latestExplicitVersion),latestHashVersion=latestExplicitVersionSupported?latestExplicitVersion:verification.item_hash_version;return{latestAfterHash,hashAlgorithm:algorithmSupported?resolveHistoryHashAlgorithm(latestEntry.hash_algorithm):void 0,identityDiscontinuities:findHistoryIdentityDiscontinuities(entries),chainOk:verification.ok,versionSkew,latestHashComparable:algorithmSupported&&latestHashVersion!==void 0&&(!versionSkew||latestExplicitVersionSupported||latestExplicitVersion===void 0),contentHash,itemHashVersion:latestHashVersion??CURRENT_HISTORY_ITEM_HASH_VERSION}}function cacheMetadataMatches(cached,stat){return cached!==void 0&&cached.mtime_ms===stat.mtimeMs&&cached.ctime_ms===stat.ctimeMs&&cached.size===stat.size}async function loadFreshStreamVerification(itemId,historyPath,accumulator){try{return await verifyHistoryStream(historyPath)||(accumulator.missingStreams.push(itemId),null)}catch{return accumulator.unreadableStreams.push(itemId),null}}function matchesCachedVerification(verification,cached){return verification!==null&&verification.contentHash===cached.content_hash&&verification.latestAfterHash===cached.latest_after_hash&&verification.chainOk===cached.chain_ok&&verification.versionSkew===(cached.version_skew===!0)&&verification.latestHashComparable===cached.latest_hash_comparable&&verification.itemHashVersion===cached.item_hash_version&&verification.hashAlgorithm===cached.hash_algorithm}async function resolveStreamVerification(params){const cachedContentHash=typeof params.cached?.content_hash=="string"&&params.cached.content_hash.length>0?params.cached.content_hash:void 0;if(!(cacheMetadataMatches(params.cached,params.stat)&&cachedContentHash!==void 0)||!params.cached||!params.cached.chain_ok)return{verification:await loadFreshStreamVerification(params.itemId,params.historyPath,params.accumulator),cacheDirty:!0};if(params.verifyCacheHitByContent){const verification=await loadFreshStreamVerification(params.itemId,params.historyPath,params.accumulator);return{verification,cacheDirty:!matchesCachedVerification(verification,params.cached)}}return{verification:{identityDiscontinuities:[],latestAfterHash:params.cached.latest_after_hash,chainOk:params.cached.chain_ok,versionSkew:params.cached.version_skew===!0,latestHashComparable:params.cached.latest_hash_comparable&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(params.cached.item_hash_version),contentHash:cachedContentHash,itemHashVersion:params.cached.item_hash_version,hashAlgorithm:params.cached.hash_algorithm},cacheDirty:!1}}async function scanItemHistory(pmRoot,item,cache,accumulator){let historyPath,stat;try{historyPath=getHistoryPath(pmRoot,item.id),stat=await fs.stat(historyPath)}catch(error){return(isFileMissingError(error)?accumulator.missingStreams:accumulator.unreadableStreams).push(item.id),!1}const resolved=await resolveStreamVerification({itemId:item.id,historyPath,stat,cached:cache.previousEntries[item.id],verifyCacheHitByContent:cache.verifyCacheHitByContent,accumulator});if(!resolved.verification)return resolved.cacheDirty;resolved.verification.identityDiscontinuities.length>0&&(accumulator.identityDiscontinuities??=[]).push(...resolved.verification.identityDiscontinuities.map(finding=>({...finding,item_id:item.id}))),resolved.verification.versionSkew&&accumulator.versionSkews.push(item.id),resolved.verification.chainOk||accumulator.chainMismatches.push(item.id),cache.nextEntries[item.id]={mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size,content_hash:resolved.verification.contentHash,latest_after_hash:resolved.verification.latestAfterHash,chain_ok:resolved.verification.chainOk,version_skew:resolved.verification.versionSkew,latest_hash_comparable:resolved.verification.latestHashComparable,item_hash_version:resolved.verification.itemHashVersion,hash_algorithm:resolved.verification.hashAlgorithm};const{body,...itemMetadata}=item;return resolved.verification.latestHashComparable&&(hashDocumentVerificationCandidates({metadata:itemMetadata,body},resolved.verification.itemHashVersion,resolved.verification.hashAlgorithm).includes(resolved.verification.latestAfterHash)||accumulator.hashMismatches.push(item.id)),resolved.cacheDirty}async function scanWorkspaceStateAgreement(pmRoot,accumulator){if(!(accumulator.unreadableStreams.includes(WORKSPACE_HISTORY_ID)||accumulator.chainMismatches.includes(WORKSPACE_HISTORY_ID)||accumulator.versionSkews.includes(WORKSPACE_HISTORY_ID)))try{const agreement=await inspectWorkspaceHistoryState(pmRoot);accumulator.workspaceStateMismatches.push(...agreement.mismatched_documents),accumulator.workspaceStateMissing.push(...agreement.missing_documents),accumulator.workspaceStateUnreadable.push(...agreement.unreadable_documents)}catch{accumulator.unreadableStreams.push(WORKSPACE_HISTORY_ID)}}async function scanItemHistoryDrift(pmRoot,item){const accumulator=createDriftScanAccumulator();return await scanItemHistory(pmRoot,item,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},accumulator),buildDriftScanResult(accumulator)}async function scanHistoryDrift(pmRoot,items,options={}){const accumulator=createDriftScanAccumulator(),previousEntries=(await loadDriftCache(pmRoot))?.entries??{},nextEntries={};let cacheDirty=!1;const verifyCacheHitByContent=options.cacheHitVerification!=="metadata",cacheState={previousEntries,nextEntries,verifyCacheHitByContent};for(const item of items)await scanItemHistory(pmRoot,item,cacheState,accumulator)&&(cacheDirty=!0);const workspaceCacheDirty=await scanWorkspaceHistory(pmRoot,previousEntries,nextEntries,verifyCacheHitByContent,accumulator);if(cacheDirty||=workspaceCacheDirty,await scanWorkspaceStateAgreement(pmRoot,accumulator),cacheDirty||Object.keys(previousEntries).length!==Object.keys(nextEntries).length){const cachePath=getDriftCachePath(pmRoot);try{await fs.mkdir(path.dirname(cachePath),{recursive:!0}),await writeFileAtomic(cachePath,JSON.stringify({version:DRIFT_CACHE_VERSION,history_item_hash_version:CURRENT_HISTORY_ITEM_HASH_VERSION,entries:nextEntries}))}catch{}}return buildDriftScanResult(accumulator)}export{scanHistoryDrift,scanItemHistoryDrift};
1
+ import{HISTORY_HASH_ALGORITHMS as E,resolveHistoryHashAlgorithm as O}from"./digest.js";import m from"node:fs/promises";import{createHash as I}from"node:crypto";import y from"node:path";import{getHistoryPath as V}from"../store/paths.js";import{isFileMissingError as p,writeFileAtomic as R}from"../fs/fs-utils.js";import{CURRENT_HISTORY_ITEM_HASH_VERSION as v,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS as d,hasNewerRecordSealFormat as T,hashDocumentVerificationCandidates as P}from"./history.js";import{verifyHistoryChainWithVersion as F}from"./replay.js";import{findHistoryIdentityDiscontinuities as N}from"./identity.js";import{getWorkspaceHistoryPath as x,inspectWorkspaceHistoryState as U,WORKSPACE_HISTORY_ID as c}from"./workspace-history.js";const S=new Set([void 0,...E]),w=13,j="history-drift-cache.json";function g(e){return y.join(e,"runtime",j)}async function z(e){try{const t=await m.readFile(g(e),"utf8"),n=JSON.parse(t);return n.version!==w||n.history_item_hash_version!==v||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(i=>typeof i.chain_ok!="boolean"||typeof i.latest_hash_comparable!="boolean"||!S.has(i.hash_algorithm)||!d.includes(i.item_hash_version)&&i.version_skew!==!0||i.chain_ok&&i.version_skew!==!0&&d.includes(i.item_hash_version)&&!i.latest_hash_comparable)?null:n}catch{return null}}function k(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function C(e){const t=[...new Set([...e.missingStreams,...e.unreadableStreams,...e.hashMismatches,...e.chainMismatches,...e.versionSkews,...e.workspaceStateMismatches.length>0||e.workspaceStateMissing.length>0||e.workspaceStateUnreadable.length>0?[c]:[]])].sort((n,i)=>n.localeCompare(i));return{...e,driftedItems:t}}async function B(e,t,n,i,r){const h=x(e);let s;try{s=await m.stat(h)}catch(f){return p(f)||r.unreadableStreams.push(c),!1}const o=r.missingStreams.length,a=await M({itemId:c,historyPath:h,stat:s,cached:t[c],verifyCacheHitByContent:i,accumulator:r});return a.verification?(a.verification.versionSkew&&r.versionSkews.push(c),a.verification.chainOk||r.chainMismatches.push(c),n[c]={mtime_ms:s.mtimeMs,ctime_ms:s.ctimeMs,size:s.size,content_hash:a.verification.contentHash,latest_after_hash:a.verification.latestAfterHash,chain_ok:a.verification.chainOk,version_skew:a.verification.versionSkew,latest_hash_comparable:a.verification.latestHashComparable,item_hash_version:a.verification.itemHashVersion,hash_algorithm:a.verification.hashAlgorithm},a.cacheDirty):(r.missingStreams.splice(o),a.cacheDirty)}function W(e){return!S.has(e.hash_algorithm)||e.item_hash_version!==void 0&&!d.includes(e.item_hash_version)||T(e)}async function Y(e){const t=await m.readFile(e,"utf8"),n=I("sha256").update(t).digest("hex");if(t.trim().length===0)return null;const i=[];let r=null;for(const D of t.split(/\r?\n/)){const H=D.trim();if(H.length===0)continue;const u=JSON.parse(H);if(typeof u.after_hash!="string"||u.after_hash.trim().length===0)throw new Error("missing after_hash");i.push(u),r=u.after_hash}if(!r)return null;const h=F(i),s=i.some(W),o=i[i.length-1],a=S.has(o.hash_algorithm),f=o.item_hash_version,l=f!==void 0&&d.includes(f),_=l?f:h.item_hash_version;return{latestAfterHash:r,hashAlgorithm:a?O(o.hash_algorithm):void 0,identityDiscontinuities:N(i),chainOk:h.ok,versionSkew:s,latestHashComparable:a&&_!==void 0&&(!s||l||f===void 0),contentHash:n,itemHashVersion:_??v}}function L(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function b(e,t,n){try{const i=await Y(t);return i||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}function J(e,t){return e!==null&&e.contentHash===t.content_hash&&e.latestAfterHash===t.latest_after_hash&&e.chainOk===t.chain_ok&&e.versionSkew===(t.version_skew===!0)&&e.latestHashComparable===t.latest_hash_comparable&&e.itemHashVersion===t.item_hash_version&&e.hashAlgorithm===t.hash_algorithm}async function M(e){const t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(L(e.cached,e.stat)&&t!==void 0)||!e.cached||!e.cached.chain_ok)return{verification:await b(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){const i=await b(e.itemId,e.historyPath,e.accumulator);return{verification:i,cacheDirty:!J(i,e.cached)}}return{verification:{identityDiscontinuities:[],latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,versionSkew:e.cached.version_skew===!0,latestHashComparable:e.cached.latest_hash_comparable&&d.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version,hashAlgorithm:e.cached.hash_algorithm},cacheDirty:!1}}async function A(e,t,n,i){let r,h;try{r=V(e,t.id),h=await m.stat(r)}catch(l){return(p(l)?i.missingStreams:i.unreadableStreams).push(t.id),!1}const s=await M({itemId:t.id,historyPath:r,stat:h,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:i});if(!s.verification)return s.cacheDirty;s.verification.identityDiscontinuities.length>0&&(i.identityDiscontinuities??=[]).push(...s.verification.identityDiscontinuities.map(l=>({...l,item_id:t.id}))),s.verification.versionSkew&&i.versionSkews.push(t.id),s.verification.chainOk||i.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:h.mtimeMs,ctime_ms:h.ctimeMs,size:h.size,content_hash:s.verification.contentHash,latest_after_hash:s.verification.latestAfterHash,chain_ok:s.verification.chainOk,version_skew:s.verification.versionSkew,latest_hash_comparable:s.verification.latestHashComparable,item_hash_version:s.verification.itemHashVersion,hash_algorithm:s.verification.hashAlgorithm};const{body:o,...a}=t;return s.verification.latestHashComparable&&(P({metadata:a,body:o},s.verification.itemHashVersion,s.verification.hashAlgorithm).includes(s.verification.latestAfterHash)||i.hashMismatches.push(t.id)),s.cacheDirty}async function G(e,t){if(!(t.unreadableStreams.includes(c)||t.chainMismatches.includes(c)||t.versionSkews.includes(c)))try{const n=await U(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(c)}}async function ne(e,t){const n=k();return await A(e,t,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},n),C(n)}async function ae(e,t,n={}){const i=k(),h=(await z(e))?.entries??{},s={};let o=!1;const a=n.cacheHitVerification!=="metadata",f={previousEntries:h,nextEntries:s,verifyCacheHitByContent:a};for(const _ of t)await A(e,_,f,i)&&(o=!0);const l=await B(e,h,s,a,i);if(o||=l,await G(e,i),o||Object.keys(h).length!==Object.keys(s).length){const _=g(e);try{await m.mkdir(y.dirname(_),{recursive:!0}),await R(_,JSON.stringify({version:w,history_item_hash_version:v,entries:s}))}catch{}}return C(i)}export{ae as scanHistoryDrift,ne as scanItemHistoryDrift};
2
2
  //# sourceMappingURL=drift-scan.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3c2c29c0-0034-54d4-9dbd-2e9af047784e")}catch{}})();const HISTORY_EVENT_CLASSIFICATION_VERSION=1,MAINTENANCE_HISTORY_OPERATIONS=["docs_add","files_add","history:author-acknowledge","history_author_acknowledge","history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","normalize","release","test_run_track","tests_add","tests_remove","tests_update","update_audit","update_ownership_bypass"],SUBSTANTIVE_HISTORY_OPERATIONS=["append","cancel","claim","close","comment_add","create","learning_add","note_add","reopen"],MAINTENANCE_OPERATIONS=new Set(MAINTENANCE_HISTORY_OPERATIONS),SUBSTANTIVE_OPERATIONS=new Set(SUBSTANTIVE_HISTORY_OPERATIONS),MAINTENANCE_UPDATE_FIELDS=new Set(["actual_result","affected_version","assignee","blocked_by","blocked_reason","close_reason","confidence","customer_impact","definition_of_ready","dependencies","docs","environment","expected_result","files","fixed_version","goal","impact","learnings","notes","objective","order","outcome","parent","release","reminders","reporter","repro_steps","resolution","reviewer","severity","sprint","tests","test_runs","unblock_note","updated_at","value","why_now"]);function topLevelPatchField(operation){const segments=operation.path.split("/").filter(Boolean);return segments[0]==="metadata"||segments[0]==="front_matter"?segments[1]:segments[0]==="body"?"body":void 0}function classifyHistoryEvent(entry){return entry.event_class==="substantive"||entry.event_class==="maintenance"?entry.event_class:MAINTENANCE_OPERATIONS.has(entry.op)?"maintenance":SUBSTANTIVE_OPERATIONS.has(entry.op)||entry.op!=="update"?"substantive":Array.isArray(entry.patch)&&entry.patch.length>0&&entry.patch.every(operation=>{const field=topLevelPatchField(operation);return field!==void 0&&MAINTENANCE_UPDATE_FIELDS.has(field)})?"maintenance":"substantive"}export{HISTORY_EVENT_CLASSIFICATION_VERSION,MAINTENANCE_HISTORY_OPERATIONS,SUBSTANTIVE_HISTORY_OPERATIONS,classifyHistoryEvent};
1
+ const _=1,n=["docs_add","files_add","history:author-acknowledge","history_author_acknowledge","history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","normalize","release","test_run_track","tests_add","tests_remove","tests_update","update_audit","update_ownership_bypass"],a=["append","cancel","claim","close","comment_add","create","learning_add","note_add","reopen"],o=new Set(n),r=new Set(a),i=new Set(["actual_result","affected_version","assignee","blocked_by","blocked_reason","close_reason","confidence","customer_impact","definition_of_ready","dependencies","docs","environment","expected_result","files","fixed_version","goal","impact","learnings","notes","objective","order","outcome","parent","release","reminders","reporter","repro_steps","resolution","reviewer","severity","sprint","tests","test_runs","unblock_note","updated_at","value","why_now"]);function c(e){const t=e.path.split("/").filter(Boolean);return t[0]==="metadata"||t[0]==="front_matter"?t[1]:t[0]==="body"?"body":void 0}function d(e){return e.event_class==="substantive"||e.event_class==="maintenance"?e.event_class:o.has(e.op)?"maintenance":r.has(e.op)||e.op!=="update"?"substantive":Array.isArray(e.patch)&&e.patch.length>0&&e.patch.every(t=>{const s=c(t);return s!==void 0&&i.has(s)})?"maintenance":"substantive"}export{_ as HISTORY_EVENT_CLASSIFICATION_VERSION,n as MAINTENANCE_HISTORY_OPERATIONS,a as SUBSTANTIVE_HISTORY_OPERATIONS,d as classifyHistoryEvent};
2
2
  //# sourceMappingURL=event-classification.js.map
@@ -1,7 +1,7 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c5f096f6-4af4-568e-89ef-1aa0a8718973")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{createHash,randomUUID}from"node:crypto";import{createRequire}from"node:module";import{setImmediate as yieldToEventLoop}from"node:timers/promises";import{isFileMissingError}from"../fs/fs-utils.js";import{acquireLock,captureProcessIdentity,isProcessIdentityAlive,hasUnexpiredLockOwner}from"../lock/lock.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{isMillisecondPrecisionRfc3339DateTime}from"../shared/time.js";import{readHistorySnapshot}from"./read.js";import{verifyHistoryChainWithVersion}from"./replay.js";import{classifyHistoryEvent}from"./event-classification.js";import{loadDatabaseSync,loadStableDatabaseSync}from"../store/sqlite-runtime.js";const EVENT_INDEX_FILENAME="history-event-index.sqlite",EVENT_INDEX_VERSION="7",AUTHORITATIVE_HISTORY_CACHE_LIMIT=8,HISTORY_STREAM_CONTENT_READ_CONCURRENCY=32,HISTORY_EVENT_INDEX_LOCK_ID="history-event-index",HISTORY_EVENT_INDEX_APPEND_OWNER_PREFIX="history-event-index:append:",HISTORY_EVENT_INDEX_REPAIR_COOLDOWN_MS=5e3,HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS=300,HISTORY_EVENT_INDEX_LOCK_WAIT_MS=3e4,HISTORY_EVENT_INDEX_INVALIDATION_LOCK_ID="history-event-index-invalidation",HISTORY_EVENT_INDEX_INVALIDATION_DIRECTORY="history-event-index-invalidations",HISTORY_EVENT_INDEX_INVALIDATION_MAX_UNVERIFIED_AGE_MS=HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS*2*1e3,HISTORY_INDEX_CHANGED=Symbol("history-index-changed"),authoritativeHistoryCaches=new Map;function eventIndexPath(pmRoot){return path.join(pmRoot,"runtime",EVENT_INDEX_FILENAME)}function refusedHistoryRepairPath(pmRoot){return path.join(pmRoot,"runtime","history-event-index-repair-deferred")}async function hasRecentRefusedHistoryRepair(pmRoot){try{const deferredAt=Number(await fs.readFile(refusedHistoryRepairPath(pmRoot),"utf8")),age=Date.now()-deferredAt;return age>=0&&age<HISTORY_EVENT_INDEX_REPAIR_COOLDOWN_MS}catch{return!1}}async function deferAutomaticHistoryRepair(pmRoot){try{await fs.writeFile(refusedHistoryRepairPath(pmRoot),`${Date.now()}
2
- `)}catch{}}function historyEventIndexInvalidationDirectory(pmRoot){return path.join(pmRoot,"runtime",HISTORY_EVENT_INDEX_INVALIDATION_DIRECTORY)}async function listHistoryEventIndexInvalidations(pmRoot){const entries=await fs.readdir(historyEventIndexInvalidationDirectory(pmRoot)).catch(error=>{if(isFileMissingError(error))return[];throw error});return{pending:entries.filter(name=>name.endsWith(".pending")).sort(),committed:entries.filter(name=>name.endsWith(".committed")).sort()}}async function recoverAbandonedHistoryEventIndexInvalidations(pmRoot){const invalidations=await listHistoryEventIndexInvalidations(pmRoot);return{pending:(await Promise.all(invalidations.pending.map(async name=>{const owner=/^(\d+)-(unknown|\d+)-(\d+)-.+\.pending$/u.exec(name);if(owner!==null){const processStartIdentity=owner[2];if(await isProcessIdentityAlive({pid:Number(owner[1]),...processStartIdentity==="unknown"?{}:{process_start_identity:processStartIdentity}},Math.max(0,Date.now()-Number(owner[3])),HISTORY_EVENT_INDEX_INVALIDATION_MAX_UNVERIFIED_AGE_MS))return name}return await fs.rm(path.join(historyEventIndexInvalidationDirectory(pmRoot),name),{force:!0}),null}))).filter(name=>name!==null),committed:invalidations.committed}}async function withHistoryEventIndexInvalidationLock(pmRoot,operation,waitMs=HISTORY_EVENT_INDEX_LOCK_WAIT_MS){const release=await acquireLock(pmRoot,HISTORY_EVENT_INDEX_INVALIDATION_LOCK_ID,HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS,`history-event-index-invalidation:${process.pid}`,!1,!1,waitMs,waitMs===0?{maxWaitMs:0}:void 0);try{return await operation()}finally{await release()}}async function beginHistoryEventIndexInvalidation(pmRoot){const directory=historyEventIndexInvalidationDirectory(pmRoot);await fs.mkdir(directory,{recursive:!0});const token=randomUUID(),processIdentity=await captureProcessIdentity(),pendingPath=path.join(directory,`${processIdentity.pid}-${processIdentity.process_start_identity??"unknown"}-${Date.now()}-${token}.pending`);return await fs.writeFile(pendingPath,`pending
3
- `,{flag:"wx"}),{pendingPath,committedPath:path.join(directory,`${token}.committed`)}}function sameInvalidationNames(left,right){return left.length===right.length&&left.every((name,index)=>name===right[index])}async function invalidateHistoryEventIndex(pmRoot){try{await fs.rm(eventIndexPath(pmRoot),{force:!0})}catch{}}async function recordHistoryEventIndexInvalidation(pmRoot,retainCache){const directory=historyEventIndexInvalidationDirectory(pmRoot);await fs.mkdir(directory,{recursive:!0}),await fs.writeFile(path.join(directory,`${randomUUID()}${retainCache?".contended":""}.committed`),`committed
4
- `,{flag:"wx"}),retainCache||await invalidateHistoryEventIndex(pmRoot)}function hasContendedHistoryEventIndexInvalidation(invalidations){return invalidations.committed.some(name=>name.endsWith(".contended.committed"))}function hasNativeHistoryEventIndexContention(pmRoot,Database){let database;try{return database=new Database(eventIndexPath(pmRoot)),database.exec("PRAGMA busy_timeout = 0"),database.exec("BEGIN EXCLUSIVE"),!1}catch(error){return isHistoryIndexSqliteContention(error)}finally{database?.close()}}async function historyEventIndexAppendIsActive(pmRoot,invalidations){return invalidations.pending.length>0||await hasUnexpiredLockOwner(pmRoot,HISTORY_EVENT_INDEX_LOCK_ID,HISTORY_EVENT_INDEX_APPEND_OWNER_PREFIX)}async function withHistoryEventIndexLock(pmRoot,operation,waitMs=HISTORY_EVENT_INDEX_LOCK_WAIT_MS,purpose="rebuild"){const release=await acquireLock(pmRoot,HISTORY_EVENT_INDEX_LOCK_ID,HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS,`history-event-index:${purpose}:${process.pid}`,!1,!1,waitMs,waitMs===0?{maxWaitMs:0}:void 0);try{return await operation()}finally{await release()}}async function readAuthoritativeHistorySnapshot(pmRoot,requestedStreamIds,verify=!1){const historyRoot=path.join(pmRoot,"history"),entries=await fs.readdir(historyRoot,{withFileTypes:!0}).catch(error=>{if(typeof error=="object"&&error!==null&&"code"in error&&error.code==="ENOENT")return[];throw error}),base=authoritativeHistoryCaches.get(pmRoot)??{streams:new Map,ordered_events:[]},streams=new Map(base.streams);let orderedEvents=base.ordered_events;const presentStreams=new Set;let changed=!authoritativeHistoryCaches.has(pmRoot);for(const historyFile of entries.filter(entry=>entry.isFile()&&entry.name.endsWith(".jsonl")).sort((left,right)=>left.name.localeCompare(right.name))){const streamId=historyFile.name.slice(0,-6);presentStreams.add(streamId);const historyPath=path.join(historyRoot,historyFile.name);if(!historyStreamIsSelected(streamId,requestedStreamIds))continue;const stream=await readChangedHistoryStream(historyPath,streamId,streams.get(streamId),verify);stream!==void 0&&(streams.set(streamId,stream),changed=!0)}for(const streamId of streams.keys())presentStreams.has(streamId)||(streams.delete(streamId),changed=!0);changed&&(orderedEvents=[...streams.values()].flatMap(stream=>stream.events).sort(compareHistoryEventPosition));const cached={streams,ordered_events:orderedEvents};if(authoritativeHistoryCaches.delete(pmRoot),authoritativeHistoryCaches.set(pmRoot,cached),authoritativeHistoryCaches.size>AUTHORITATIVE_HISTORY_CACHE_LIMIT){const oldestRoot=authoritativeHistoryCaches.keys().next().value;authoritativeHistoryCaches.delete(oldestRoot)}return{events:cached.ordered_events.filter(event=>historyStreamIsSelected(event.stream_id,requestedStreamIds)).map(event=>projectRecordedHistoryEvent(event,verify)),stream_receipts:new Map([...cached.streams].filter(([streamId])=>historyStreamIsSelected(streamId,requestedStreamIds)).map(([streamId,stream])=>[streamId,{byte_size:stream.byte_size,content_hash:stream.signature}]))}}function projectRecordedHistoryEvent(event,verify){return verify||event.recorded_entry===void 0?event:{stream_id:event.stream_id,stream_offset:event.stream_offset,entry:event.entry}}function historyStreamIsSelected(streamId,requested){return!requested?.length||requested.includes(streamId)}async function readChangedHistoryStream(historyPath,streamId,previous,verify){if(!verify&&previous!==void 0&&previous.byte_size===(await fs.stat(historyPath)).size){const signature=createHash("sha256").update(await fs.readFile(historyPath)).digest("hex");if(previous.signature===signature)return}return readIndexableHistoryStream(historyPath,streamId,verify)}async function readIndexableHistoryStream(historyPath,streamId,verify){const snapshot=await readHistorySnapshot(historyPath,streamId);if(verify){const result=verifyHistoryChainWithVersion(snapshot.entries);if(!result.ok)throw new PmCliError(`Authoritative history integrity verification failed for ${streamId}.`,EXIT_CODE.GENERIC_FAILURE,{code:"event_history_integrity_failed",why:result.errors.join(", "),nextSteps:[`Run pm history ${streamId} --verify to inspect the authoritative chain before retrying.`]})}const raw=snapshot.raw_bytes??new Uint8Array;return{signature:createHash("sha256").update(raw).digest("hex"),byte_size:raw.byteLength,events:normalizeIndexableHistoryEntries(snapshot.entries,streamId).map((entry,streamOffset)=>({stream_id:streamId,stream_offset:streamOffset,entry,...verify?{recorded_entry:snapshot.entries[streamOffset]}:{}}))}}async function readIndexableHistoryEntries(historyPath,streamId){return normalizeIndexableHistoryEntries((await readHistorySnapshot(historyPath,streamId)).entries,streamId)}function normalizeIndexableHistoryEntries(entries,streamId){for(const[index,entry]of entries.entries())if(typeof entry.ts!="string"||!isMillisecondPrecisionRfc3339DateTime(entry.ts.trim()))throw new PmCliError(`History for ${streamId} contains an invalid or sub-millisecond timestamp at line ${index+1}. Repair or restore the history stream and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_timestamp_invalid"});return entries.map(entry=>({...entry,ts:new Date(entry.ts.trim()).toISOString()}))}let RuntimeDatabaseSync;function resolveDatabaseSync(){return RuntimeDatabaseSync!==void 0||(RuntimeDatabaseSync=loadStableDatabaseSync(process.versions.node,createRequire(import.meta.url))),RuntimeDatabaseSync}function createSchema(database){database.exec(`
1
+ import l from"node:fs/promises";import _ from"node:path";import{createHash as N,randomUUID as C}from"node:crypto";import{createRequire as mt}from"node:module";import{setImmediate as U}from"node:timers/promises";import{isFileMissingError as g}from"../fs/fs-utils.js";import{acquireLock as W,captureProcessIdentity as ht,isProcessIdentityAlive as Et,hasUnexpiredLockOwner as yt}from"../lock/lock.js";import{EXIT_CODE as V}from"../shared/constants.js";import{PmCliError as I}from"../shared/errors.js";import{isMillisecondPrecisionRfc3339DateTime as Y}from"../shared/time.js";import{readHistorySnapshot as G}from"./read.js";import{verifyHistoryChainWithVersion as pt}from"./replay.js";import{classifyHistoryEvent as B}from"./event-classification.js";import{loadDatabaseSync as wt,loadStableDatabaseSync as K}from"../store/sqlite-runtime.js";const vt="history-event-index.sqlite",L="7",It=8,Q=32,J="history-event-index",Tt="history-event-index:append:",Nt=5e3,D=300,Z=3e4,gt="history-event-index-invalidation",St="history-event-index-invalidations",Ot=D*2*1e3,h=Symbol("history-index-changed"),E=new Map;function y(t){return _.join(t,"runtime",vt)}function q(t){return _.join(t,"runtime","history-event-index-repair-deferred")}async function tt(t){try{const e=Number(await l.readFile(q(t),"utf8")),n=Date.now()-e;return n>=0&&n<Nt}catch{return!1}}async function et(t){try{await l.writeFile(q(t),`${Date.now()}
2
+ `)}catch{}}function T(t){return _.join(t,"runtime",St)}async function S(t){const e=await l.readdir(T(t)).catch(n=>{if(g(n))return[];throw n});return{pending:e.filter(n=>n.endsWith(".pending")).sort(),committed:e.filter(n=>n.endsWith(".committed")).sort()}}async function nt(t){const e=await S(t);return{pending:(await Promise.all(e.pending.map(async r=>{const s=/^(\d+)-(unknown|\d+)-(\d+)-.+\.pending$/u.exec(r);if(s!==null){const i=s[2];if(await Et({pid:Number(s[1]),...i==="unknown"?{}:{process_start_identity:i}},Math.max(0,Date.now()-Number(s[3])),Ot))return r}return await l.rm(_.join(T(t),r),{force:!0}),null}))).filter(r=>r!==null),committed:e.committed}}async function M(t,e,n=Z){const r=await W(t,gt,D,`history-event-index-invalidation:${process.pid}`,!1,!1,n,n===0?{maxWaitMs:0}:void 0);try{return await e()}finally{await r()}}async function xt(t){const e=T(t);await l.mkdir(e,{recursive:!0});const n=C(),r=await ht(),s=_.join(e,`${r.pid}-${r.process_start_identity??"unknown"}-${Date.now()}-${n}.pending`);return await l.writeFile(s,`pending
3
+ `,{flag:"wx"}),{pendingPath:s,committedPath:_.join(e,`${n}.committed`)}}function bt(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}async function O(t){try{await l.rm(y(t),{force:!0})}catch{}}async function j(t,e){const n=T(t);await l.mkdir(n,{recursive:!0}),await l.writeFile(_.join(n,`${C()}${e?".contended":""}.committed`),`committed
4
+ `,{flag:"wx"}),e||await O(t)}function x(t){return t.committed.some(e=>e.endsWith(".contended.committed"))}function z(t,e){let n;try{return n=new e(y(t)),n.exec("PRAGMA busy_timeout = 0"),n.exec("BEGIN EXCLUSIVE"),!1}catch(r){return w(r)}finally{n?.close()}}async function rt(t,e){return e.pending.length>0||await yt(t,J,Tt)}async function st(t,e,n=Z,r="rebuild"){const s=await W(t,J,D,`history-event-index:${r}:${process.pid}`,!1,!1,n,n===0?{maxWaitMs:0}:void 0);try{return await e()}finally{await s()}}async function it(t,e,n=!1){const r=_.join(t,"history"),s=await l.readdir(r,{withFileTypes:!0}).catch(d=>{if(typeof d=="object"&&d!==null&&"code"in d&&d.code==="ENOENT")return[];throw d}),i=E.get(t)??{streams:new Map,ordered_events:[]},a=new Map(i.streams);let o=i.ordered_events;const c=new Set;let u=!E.has(t);for(const d of s.filter(m=>m.isFile()&&m.name.endsWith(".jsonl")).sort((m,v)=>m.name.localeCompare(v.name))){const m=d.name.slice(0,-6);c.add(m);const v=_.join(r,d.name);if(!P(m,e))continue;const $=await Ht(v,m,a.get(m),n);$!==void 0&&(a.set(m,$),u=!0)}for(const d of a.keys())c.has(d)||(a.delete(d),u=!0);u&&(o=[...a.values()].flatMap(d=>d.events).sort(X));const f={streams:a,ordered_events:o};if(E.delete(t),E.set(t,f),E.size>It){const d=E.keys().next().value;E.delete(d)}return{events:f.ordered_events.filter(d=>P(d.stream_id,e)).map(d=>At(d,n)),stream_receipts:new Map([...f.streams].filter(([d])=>P(d,e)).map(([d,m])=>[d,{byte_size:m.byte_size,content_hash:m.signature}]))}}function At(t,e){return e||t.recorded_entry===void 0?t:{stream_id:t.stream_id,stream_offset:t.stream_offset,entry:t.entry}}function P(t,e){return!e?.length||e.includes(t)}async function Ht(t,e,n,r){if(!r&&n!==void 0&&n.byte_size===(await l.stat(t)).size){const s=N("sha256").update(await l.readFile(t)).digest("hex");if(n.signature===s)return}return Rt(t,e,r)}async function Rt(t,e,n){const r=await G(t,e);if(n){const i=pt(r.entries);if(!i.ok)throw new I(`Authoritative history integrity verification failed for ${e}.`,V.GENERIC_FAILURE,{code:"event_history_integrity_failed",why:i.errors.join(", "),nextSteps:[`Run pm history ${e} --verify to inspect the authoritative chain before retrying.`]})}const s=r.raw_bytes??new Uint8Array;return{signature:N("sha256").update(s).digest("hex"),byte_size:s.byteLength,events:at(r.entries,e).map((i,a)=>({stream_id:e,stream_offset:a,entry:i,...n?{recorded_entry:r.entries[a]}:{}}))}}async function Ct(t,e){return at((await G(t,e)).entries,e)}function at(t,e){for(const[n,r]of t.entries())if(typeof r.ts!="string"||!Y(r.ts.trim()))throw new I(`History for ${e} contains an invalid or sub-millisecond timestamp at line ${n+1}. Repair or restore the history stream and retry.`,V.GENERIC_FAILURE,{code:"history_timestamp_invalid"});return t.map(n=>({...n,ts:new Date(n.ts.trim()).toISOString()}))}let p;function b(){return p!==void 0||(p=K(process.versions.node,mt(import.meta.url))),p}function Lt(t){t.exec(`
5
5
  PRAGMA journal_mode = OFF;
6
6
  PRAGMA synchronous = OFF;
7
7
  CREATE TABLE metadata (
@@ -37,14 +37,14 @@
37
37
  ON events(agent_harness, ts, stream_id, stream_offset);
38
38
  CREATE INDEX events_instance_order
39
39
  ON events(agent_instance, ts, stream_id, stream_offset);
40
- `),database.prepare("INSERT INTO metadata(key, value) VALUES ('version', ?)").run(EVENT_INDEX_VERSION)}function insertEvent(database,event){const entry={...event.entry,ts:new Date(event.entry.ts.trim()).toISOString()};database.prepare(`INSERT INTO events(
40
+ `),t.prepare("INSERT INTO metadata(key, value) VALUES ('version', ?)").run(L)}function ot(t,e){const n={...e.entry,ts:new Date(e.entry.ts.trim()).toISOString()};t.prepare(`INSERT INTO events(
41
41
  stream_id, stream_offset, ts, author, agent_harness,
42
42
  agent_instance, op, event_class, entry_json
43
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(event.stream_id,event.stream_offset,entry.ts,entry.author,entry.agent_harness??null,entry.agent_instance??null,entry.op,classifyHistoryEvent(entry),JSON.stringify(entry))}function parseIndexedHistoryEvent(row){const entry=JSON.parse(String(row.entry_json));return typeof entry.ts!="string"||!isMillisecondPrecisionRfc3339DateTime(entry.ts.trim())?null:{stream_id:String(row.stream_id),stream_offset:Number(row.stream_offset),entry:{...entry,ts:new Date(entry.ts.trim()).toISOString()}}}function upsertStreamContentReceipt(database,streamId,receipt){database.prepare(`INSERT INTO streams(stream_id, byte_size, content_hash) VALUES (?, ?, ?)
44
- ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size, content_hash = excluded.content_hash`).run(streamId,receipt.byte_size,receipt.content_hash)}async function rebuildHistoryEventIndex(pmRoot,options={}){const Database=resolveDatabaseSync();return Database?withHistoryEventIndexLock(pmRoot,async()=>{let invalidations;try{invalidations=await withHistoryEventIndexInvalidationLock(pmRoot,()=>recoverAbandonedHistoryEventIndexInvalidations(pmRoot),options.lockWaitMs)}catch(error){if(error instanceof PmCliError&&error.code==="lock_conflict")return!1;throw error}if(invalidations.pending.length>0||hasContendedHistoryEventIndexInvalidation(invalidations)&&hasNativeHistoryEventIndexContention(pmRoot,Database))return!1;const targetPath=eventIndexPath(pmRoot);await fs.mkdir(path.dirname(targetPath),{recursive:!0});const temporaryPath=`${targetPath}.${randomUUID()}.tmp`;let database;try{database=new Database(temporaryPath),createSchema(database),database.exec("BEGIN IMMEDIATE");const authoritative=await readAuthoritativeHistorySnapshot(pmRoot);await populateHistoryEventIndex(database,authoritative),database.exec("COMMIT"),database.close(),database=void 0;const published=await withHistoryEventIndexInvalidationLock(pmRoot,async()=>{const current=await recoverAbandonedHistoryEventIndexInvalidations(pmRoot);return current.pending.length>0||!sameInvalidationNames(invalidations.committed,current.committed)||hasContendedHistoryEventIndexInvalidation(current)&&hasNativeHistoryEventIndexContention(pmRoot,Database)?!1:(await fs.rm(targetPath,{force:!0}),await fs.rename(temporaryPath,targetPath),!0)},options.lockWaitMs);return published&&await Promise.all(invalidations.committed.map(name=>fs.rm(path.join(historyEventIndexInvalidationDirectory(pmRoot),name),{force:!0}))),published||(await deferAutomaticHistoryRepair(pmRoot),await fs.rm(temporaryPath,{force:!0})),published}catch(error){throw await deferAutomaticHistoryRepair(pmRoot),database?.close(),await fs.rm(temporaryPath,{force:!0}),error}},options.lockWaitMs):!1}async function populateHistoryEventIndex(database,snapshot){let inserted=0;for(const event of snapshot.events)insertEvent(database,event),++inserted%500===0&&await yieldToEventLoop();for(const[streamId,receipt]of snapshot.stream_receipts)upsertStreamContentReceipt(database,streamId,receipt),++inserted%500===0&&await yieldToEventLoop()}function matchesSet(value,accepted){return!accepted||accepted.length===0||accepted.includes(value)}function compareHistoryEventPosition(left,right){return left.entry.ts.localeCompare(right.entry.ts)||left.stream_id.localeCompare(right.stream_id)||left.stream_offset-right.stream_offset}function canonicalHistoryQueryTimestamp(value){const milliseconds=Date.parse(value);return Number.isFinite(milliseconds)?new Date(milliseconds).toISOString():value}function isInsideHistoryEventWindow(event,query){if(query.after_ts!==void 0&&query.after_stream_id!==void 0&&query.after_stream_offset!==void 0){if(compareHistoryEventPosition(event,{stream_id:query.after_stream_id,stream_offset:query.after_stream_offset,entry:{...event.entry,ts:canonicalHistoryQueryTimestamp(query.after_ts)}})<=0)return!1}else if(query.since_ts!==void 0&&event.entry.ts<canonicalHistoryQueryTimestamp(query.since_ts))return!1;return!0}function matchesHistoryEventHarness(event,query){return!query.harnesses||query.harnesses.length===0||query.harnesses.includes(event.entry.agent_harness??"")?!0:event.entry.agent_harness===void 0&&(query.harness_alias_authors??[]).includes(event.entry.author)}function matchesHistoryEventQuery(event,query){return!isInsideHistoryEventWindow(event,query)||!matchesSet(event.entry.op,query.ops)||!matchesSet(event.entry.author,query.authors)||!matchesSet(event.entry.agent_instance??"",query.agent_instances)||!matchesSet(event.stream_id,query.stream_ids)||!matchesHistoryEventHarness(event,query)?!1:(query.provenance??[]).every(predicate=>{const value=event.entry.agent_provenance?.[predicate.dimension]?.value;return value!==void 0&&predicate.values.includes(value)})}async function queryHistoryEventStreams(pmRoot,query){const limit=Math.max(0,Math.floor(query.limit)),snapshot=await readAuthoritativeHistorySnapshot(pmRoot,query.stream_ids,query.verify),rows=snapshot.events.filter(event=>matchesHistoryEventQuery(event,query)).slice(0,limit+1);return{events:rows.slice(0,query.limit),has_more:rows.length>query.limit,...query.verify?{verified_streams:snapshot.stream_receipts.size}:{}}}async function historyEventIndexHasAppendBase(database,historyPath){const stored=database.prepare("SELECT byte_size, content_hash FROM streams WHERE stream_id = ?").get(path.basename(historyPath,".jsonl"));let actualSize=0;try{actualSize=(await fs.stat(historyPath)).size}catch(error){if(!isFileMissingError(error))throw error}if(Number(stored?.byte_size??0)!==actualSize)return!1;const current=await readHistoryStreamContentReceipt(path.dirname(path.dirname(historyPath)),path.basename(historyPath,".jsonl"));return stored===void 0?current?.byte_size===0:current?.content_hash===stored.content_hash}async function appendHistoryEntryWithEventIndex(historyPath,entry,append){const pmRoot=path.dirname(path.dirname(historyPath)),Database=resolveDatabaseSync();let authoritativeAppendCommitted=!1;const appendAuthoritative=async()=>{await append(),authoritativeAppendCommitted=!0};if(!Database){await appendUnindexedHistory(pmRoot,appendAuthoritative);return}try{await withHistoryEventIndexLock(pmRoot,async()=>{const targetPath=eventIndexPath(pmRoot);try{await fs.access(targetPath)}catch{await appendAuthoritative();return}let database;try{if(database=new Database(targetPath),database.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==EVENT_INDEX_VERSION)throw new TypeError("Unsupported history event index version");if(!await historyEventIndexHasAppendBase(database,historyPath))throw new TypeError("Stale history event index append base")}catch(error){if(database?.close(),isHistoryIndexSqliteContention(error))throw error;await recordHistoryEventIndexInvalidation(pmRoot,!0),await appendAuthoritative();return}try{database.exec("PRAGMA busy_timeout = 0"),database.exec("BEGIN IMMEDIATE")}catch(error){if(database.close(),isHistoryIndexSqliteContention(error)||!(error instanceof Error)||error.code!=="ERR_SQLITE_ERROR")throw error;await recordHistoryEventIndexInvalidation(pmRoot,!1),await appendAuthoritative();return}let appended=!1;try{await appendAuthoritative(),appended=!0;const streamId=path.basename(historyPath,".jsonl"),offset=database.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(streamId);insertEvent(database,{stream_id:streamId,stream_offset:Number(offset.value),entry}),upsertStreamContentReceipt(database,streamId,await readHistoryStreamContentReceipt(pmRoot,streamId)),database.exec("COMMIT"),database.close()}catch(error){if(database?.close(),!appended)throw error;await recordHistoryEventIndexInvalidation(pmRoot,isHistoryIndexSqliteContention(error))}},0,"append")}catch(error){if(authoritativeAppendCommitted){await invalidateHistoryEventIndex(pmRoot);return}if(!isHistoryIndexWriteContention(error))throw error;await appendUnindexedHistory(pmRoot,appendAuthoritative,isHistoryIndexSqliteContention(error))}}async function appendUnindexedHistory(pmRoot,append,nativeContention=!1){let authoritativeAppendCommitted=!1,pendingMarkerPath;try{await withHistoryEventIndexInvalidationLock(pmRoot,async()=>{const contended=nativeContention||hasContendedHistoryEventIndexInvalidation(await listHistoryEventIndexInvalidations(pmRoot)),marker=await beginHistoryEventIndexInvalidation(pmRoot);pendingMarkerPath=marker.pendingPath;try{await append(),authoritativeAppendCommitted=!0}catch(appendError){throw await fs.rm(marker.pendingPath,{force:!0}),appendError}await fs.rename(marker.pendingPath,contended?marker.committedPath.replace(/\.committed$/u,".contended.committed"):marker.committedPath),contended||await invalidateHistoryEventIndex(pmRoot)})}catch(fallbackError){if(authoritativeAppendCommitted){await invalidateHistoryEventIndex(pmRoot);try{await fs.rm(pendingMarkerPath,{force:!0})}catch{}return}throw fallbackError}}async function removeHistoryEventIndexForHistoryPath(historyPath){await fs.rm(eventIndexPath(path.dirname(path.dirname(historyPath))),{force:!0})}function appendSetPredicate(clauses,parameters,column,values){!values||values.length===0||(clauses.push(`${column} IN (${values.map(()=>"?").join(", ")})`),parameters.push(...values))}function appendHarnessPredicate(clauses,parameters,harnesses,aliasAuthors){if(!harnesses||harnesses.length===0)return;const harnessPlaceholders=harnesses.map(()=>"?").join(", "),aliases=aliasAuthors??[];if(aliases.length>0){clauses.push(`(agent_harness IN (${harnessPlaceholders}) OR (agent_harness IS NULL AND author IN (${aliases.map(()=>"?").join(", ")})))`),parameters.push(...harnesses,...aliases);return}clauses.push(`agent_harness IN (${harnessPlaceholders})`),parameters.push(...harnesses)}async function readHistoryEventIndexSnapshot(pmRoot,Database,requestedStreamIds,read){let database;try{const invalidations=await listHistoryEventIndexInvalidations(pmRoot);if(await historyEventIndexAppendIsActive(pmRoot,invalidations))return HISTORY_INDEX_CHANGED;const before=await historyEventIndexSignature(pmRoot);if(invalidations.committed.length>0)return hasContendedHistoryEventIndexInvalidation(invalidations)&&hasNativeHistoryEventIndexContention(pmRoot,Database)?HISTORY_INDEX_CHANGED:null;if(database=new Database(eventIndexPath(pmRoot),{readOnly:!0}),database.exec("BEGIN"),database.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==EVENT_INDEX_VERSION)return null;const result=read(database);if(result===null)return null;const storedSizes=readHistoryEventIndexStreamReceipts(database,requestedStreamIds),completed=database;database=void 0,completed.close();const streamIds=await historyIndexValidationStreamIds([...storedSizes.keys()],pmRoot,requestedStreamIds),sizesMatch=await historyIndexMatchesStreamContents(storedSizes,pmRoot,streamIds),current=await listHistoryEventIndexInvalidations(pmRoot);return current.committed.length>0||await historyEventIndexAppendIsActive(pmRoot,current)||before!==await historyEventIndexSignature(pmRoot)?HISTORY_INDEX_CHANGED:sizesMatch?result:null}catch(error){return isHistoryIndexSqliteContention(error)?HISTORY_INDEX_CHANGED:null}finally{database?.close()}}function isHistoryIndexSqliteContention(error){return typeof error=="object"&&error!==null&&"errcode"in error&&[5,6].includes(error.errcode)}function isHistoryIndexWriteContention(error){return isHistoryIndexSqliteContention(error)||error instanceof PmCliError&&error.code==="lock_conflict"}function readHistoryEventIndexStreamReceipts(database,requestedStreamIds){const storedSizes=new Map,ids=requestedStreamIds&&requestedStreamIds.length>0?[...new Set(requestedStreamIds)]:void 0;if(ids===void 0)for(const row of database.prepare("SELECT stream_id, byte_size, content_hash FROM streams").all())storedSizes.set(String(row.stream_id),{byte_size:Number(row.byte_size),content_hash:String(row.content_hash)});else for(let start=0;start<ids.length;start+=500){const chunk=ids.slice(start,start+500);for(const row of database.prepare(`SELECT stream_id, byte_size, content_hash FROM streams WHERE stream_id IN (${chunk.map(()=>"?").join(", ")})`).all(...chunk))storedSizes.set(String(row.stream_id),{byte_size:Number(row.byte_size),content_hash:String(row.content_hash)})}return storedSizes}async function historyEventIndexSignature(pmRoot){const stats=await fs.stat(eventIndexPath(pmRoot),{bigint:!0});return[stats.dev,stats.ino,stats.size,stats.mtimeNs,stats.ctimeNs].join(":")}async function readHistoryEventIndexPage(pmRoot,query){if(query.verify)return{result:await queryHistoryEventStreams(pmRoot,query),repair_needed:!1};const Database=resolveDatabaseSync();if(!Database)return{result:null,repair_needed:!1};const clauses=[],parameters=[];if(query.after_ts!==void 0&&query.after_stream_id!==void 0&&query.after_stream_offset!==void 0){clauses.push("(ts > ? OR (ts = ? AND stream_id > ?) OR (ts = ? AND stream_id = ? AND stream_offset > ?))");const afterTimestamp=canonicalHistoryQueryTimestamp(query.after_ts);parameters.push(afterTimestamp,afterTimestamp,query.after_stream_id,afterTimestamp,query.after_stream_id,query.after_stream_offset)}else query.since_ts!==void 0&&(clauses.push("ts >= ?"),parameters.push(canonicalHistoryQueryTimestamp(query.since_ts)));appendSetPredicate(clauses,parameters,"op",query.ops),appendSetPredicate(clauses,parameters,"author",query.authors),appendHarnessPredicate(clauses,parameters,query.harnesses,query.harness_alias_authors),appendSetPredicate(clauses,parameters,"agent_instance",query.agent_instances);for(const predicate of query.provenance??[])clauses.push(`json_extract(entry_json, '$.agent_provenance.${predicate.dimension}.value') IN (${predicate.values.map(()=>"?").join(", ")})`),parameters.push(...predicate.values);appendSetPredicate(clauses,parameters,"stream_id",query.stream_ids);const where=clauses.length===0?"":` WHERE ${clauses.join(" AND ")}`,attempt=await readHistoryEventIndexSnapshot(pmRoot,Database,query.stream_ids,database=>{const rows=database.prepare(`SELECT stream_id, stream_offset, entry_json
45
- FROM events${where}
43
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.stream_id,e.stream_offset,n.ts,n.author,n.agent_harness??null,n.agent_instance??null,n.op,B(n),JSON.stringify(n))}function ct(t){const e=JSON.parse(String(t.entry_json));return typeof e.ts!="string"||!Y(e.ts.trim())?null:{stream_id:String(t.stream_id),stream_offset:Number(t.stream_offset),entry:{...e,ts:new Date(e.ts.trim()).toISOString()}}}function dt(t,e,n){t.prepare(`INSERT INTO streams(stream_id, byte_size, content_hash) VALUES (?, ?, ?)
44
+ ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size, content_hash = excluded.content_hash`).run(e,n.byte_size,n.content_hash)}async function Dt(t,e={}){const n=b();return n?st(t,async()=>{let r;try{r=await M(t,()=>nt(t),e.lockWaitMs)}catch(o){if(o instanceof I&&o.code==="lock_conflict")return!1;throw o}if(r.pending.length>0||x(r)&&z(t,n))return!1;const s=y(t);await l.mkdir(_.dirname(s),{recursive:!0});const i=`${s}.${C()}.tmp`;let a;try{a=new n(i),Lt(a),a.exec("BEGIN IMMEDIATE");const o=await it(t);await Mt(a,o),a.exec("COMMIT"),a.close(),a=void 0;const c=await M(t,async()=>{const u=await nt(t);return u.pending.length>0||!bt(r.committed,u.committed)||x(u)&&z(t,n)?!1:(await l.rm(s,{force:!0}),await l.rename(i,s),!0)},e.lockWaitMs);return c&&await Promise.all(r.committed.map(u=>l.rm(_.join(T(t),u),{force:!0}))),c||(await et(t),await l.rm(i,{force:!0})),c}catch(o){throw await et(t),a?.close(),await l.rm(i,{force:!0}),o}},e.lockWaitMs):!1}async function Mt(t,e){let n=0;for(const r of e.events)ot(t,r),++n%500===0&&await U();for(const[r,s]of e.stream_receipts)dt(t,r,s),++n%500===0&&await U()}function A(t,e){return!e||e.length===0||e.includes(t)}function X(t,e){return t.entry.ts.localeCompare(e.entry.ts)||t.stream_id.localeCompare(e.stream_id)||t.stream_offset-e.stream_offset}function H(t){const e=Date.parse(t);return Number.isFinite(e)?new Date(e).toISOString():t}function jt(t,e){if(e.after_ts!==void 0&&e.after_stream_id!==void 0&&e.after_stream_offset!==void 0){if(X(t,{stream_id:e.after_stream_id,stream_offset:e.after_stream_offset,entry:{...t.entry,ts:H(e.after_ts)}})<=0)return!1}else if(e.since_ts!==void 0&&t.entry.ts<H(e.since_ts))return!1;return!0}function zt(t,e){return!e.harnesses||e.harnesses.length===0||e.harnesses.includes(t.entry.agent_harness??"")?!0:t.entry.agent_harness===void 0&&(e.harness_alias_authors??[]).includes(t.entry.author)}function Pt(t,e){return!jt(t,e)||!A(t.entry.op,e.ops)||!A(t.entry.author,e.authors)||!A(t.entry.agent_instance??"",e.agent_instances)||!A(t.stream_id,e.stream_ids)||!zt(t,e)?!1:(e.provenance??[]).every(n=>{const r=t.entry.agent_provenance?.[n.dimension]?.value;return r!==void 0&&n.values.includes(r)})}async function Xt(t,e){const n=Math.max(0,Math.floor(e.limit)),r=await it(t,e.stream_ids,e.verify),s=r.events.filter(i=>Pt(i,e)).slice(0,n+1);return{events:s.slice(0,e.limit),has_more:s.length>e.limit,...e.verify?{verified_streams:r.stream_receipts.size}:{}}}async function kt(t,e){const n=t.prepare("SELECT byte_size, content_hash FROM streams WHERE stream_id = ?").get(_.basename(e,".jsonl"));let r=0;try{r=(await l.stat(e)).size}catch(i){if(!g(i))throw i}if(Number(n?.byte_size??0)!==r)return!1;const s=await F(_.dirname(_.dirname(e)),_.basename(e,".jsonl"));return n===void 0?s?.byte_size===0:s?.content_hash===n.content_hash}async function oe(t,e,n){const r=_.dirname(_.dirname(t)),s=b();let i=!1;const a=async()=>{await n(),i=!0};if(!s){await ft(r,a);return}try{await st(r,async()=>{const o=y(r);try{await l.access(o)}catch{await a();return}let c;try{if(c=new s(o),c.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==L)throw new TypeError("Unsupported history event index version");if(!await kt(c,t))throw new TypeError("Stale history event index append base")}catch(f){if(c?.close(),w(f))throw f;await j(r,!0),await a();return}try{c.exec("PRAGMA busy_timeout = 0"),c.exec("BEGIN IMMEDIATE")}catch(f){if(c.close(),w(f)||!(f instanceof Error)||f.code!=="ERR_SQLITE_ERROR")throw f;await j(r,!1),await a();return}let u=!1;try{await a(),u=!0;const f=_.basename(t,".jsonl"),d=c.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(f);ot(c,{stream_id:f,stream_offset:Number(d.value),entry:e}),dt(c,f,await F(r,f)),c.exec("COMMIT"),c.close()}catch(f){if(c?.close(),!u)throw f;await j(r,w(f))}},0,"append")}catch(o){if(i){await O(r);return}if(!$t(o))throw o;await ft(r,a,w(o))}}async function ft(t,e,n=!1){let r=!1,s;try{await M(t,async()=>{const i=n||x(await S(t)),a=await xt(t);s=a.pendingPath;try{await e(),r=!0}catch(o){throw await l.rm(a.pendingPath,{force:!0}),o}await l.rename(a.pendingPath,i?a.committedPath.replace(/\.committed$/u,".contended.committed"):a.committedPath),i||await O(t)})}catch(i){if(r){await O(t);try{await l.rm(s,{force:!0})}catch{}return}throw i}}async function ce(t){await l.rm(y(_.dirname(_.dirname(t))),{force:!0})}function R(t,e,n,r){!r||r.length===0||(t.push(`${n} IN (${r.map(()=>"?").join(", ")})`),e.push(...r))}function Ft(t,e,n,r){if(!n||n.length===0)return;const s=n.map(()=>"?").join(", "),i=r??[];if(i.length>0){t.push(`(agent_harness IN (${s}) OR (agent_harness IS NULL AND author IN (${i.map(()=>"?").join(", ")})))`),e.push(...n,...i);return}t.push(`agent_harness IN (${s})`),e.push(...n)}async function lt(t,e,n,r){let s;try{const i=await S(t);if(await rt(t,i))return h;const a=await ut(t);if(i.committed.length>0)return x(i)&&z(t,e)?h:null;if(s=new e(y(t),{readOnly:!0}),s.exec("BEGIN"),s.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==L)return null;const c=r(s);if(c===null)return null;const u=Ut(s,n),f=s;s=void 0,f.close();const d=await Yt([...u.keys()],t,n),m=await Vt(u,t,d),v=await S(t);return v.committed.length>0||await rt(t,v)||a!==await ut(t)?h:m?c:null}catch(i){return w(i)?h:null}finally{s?.close()}}function w(t){return typeof t=="object"&&t!==null&&"errcode"in t&&[5,6].includes(t.errcode)}function $t(t){return w(t)||t instanceof I&&t.code==="lock_conflict"}function Ut(t,e){const n=new Map,r=e&&e.length>0?[...new Set(e)]:void 0;if(r===void 0)for(const s of t.prepare("SELECT stream_id, byte_size, content_hash FROM streams").all())n.set(String(s.stream_id),{byte_size:Number(s.byte_size),content_hash:String(s.content_hash)});else for(let s=0;s<r.length;s+=500){const i=r.slice(s,s+500);for(const a of t.prepare(`SELECT stream_id, byte_size, content_hash FROM streams WHERE stream_id IN (${i.map(()=>"?").join(", ")})`).all(...i))n.set(String(a.stream_id),{byte_size:Number(a.byte_size),content_hash:String(a.content_hash)})}return n}async function ut(t){const e=await l.stat(y(t),{bigint:!0});return[e.dev,e.ino,e.size,e.mtimeNs,e.ctimeNs].join(":")}async function Wt(t,e){if(e.verify)return{result:await Xt(t,e),repair_needed:!1};const n=b();if(!n)return{result:null,repair_needed:!1};const r=[],s=[];if(e.after_ts!==void 0&&e.after_stream_id!==void 0&&e.after_stream_offset!==void 0){r.push("(ts > ? OR (ts = ? AND stream_id > ?) OR (ts = ? AND stream_id = ? AND stream_offset > ?))");const o=H(e.after_ts);s.push(o,o,e.after_stream_id,o,e.after_stream_id,e.after_stream_offset)}else e.since_ts!==void 0&&(r.push("ts >= ?"),s.push(H(e.since_ts)));R(r,s,"op",e.ops),R(r,s,"author",e.authors),Ft(r,s,e.harnesses,e.harness_alias_authors),R(r,s,"agent_instance",e.agent_instances);for(const o of e.provenance??[])r.push(`json_extract(entry_json, '$.agent_provenance.${o.dimension}.value') IN (${o.values.map(()=>"?").join(", ")})`),s.push(...o.values);R(r,s,"stream_id",e.stream_ids);const i=r.length===0?"":` WHERE ${r.join(" AND ")}`,a=await lt(t,n,e.stream_ids,o=>{const c=o.prepare(`SELECT stream_id, stream_offset, entry_json
45
+ FROM events${i}
46
46
  ORDER BY ts, stream_id, stream_offset
47
- LIMIT ?`).all(...parameters,Math.max(0,Math.floor(query.limit))+1),events=rows.slice(0,query.limit).map(parseIndexedHistoryEvent);return events.includes(null)?null:{events,has_more:rows.length>query.limit}});return{result:attempt===HISTORY_INDEX_CHANGED?null:attempt,repair_needed:attempt===null&&!await hasRecentRefusedHistoryRepair(pmRoot)}}async function queryHistoryEventIndex(pmRoot,query){return(await readHistoryEventIndexPage(pmRoot,query)).result}function collectLatestSubstantiveEvents(events,requested){const latest=Object.create(null);for(const event of events){if(!requested.has(event.stream_id)||classifyHistoryEvent(event.entry)!=="substantive")continue;const current=latest[event.stream_id];(current===void 0||compareHistoryEventPosition(current,event)<0)&&(latest[event.stream_id]=event)}return latest}async function readHistoryStreamContentReceipt(pmRoot,streamId){if(path.basename(streamId)!==streamId)return null;try{const historyPath=path.join(pmRoot,"history",`${streamId}.jsonl`),stats=await fs.stat(historyPath),raw=await fs.readFile(historyPath);return stats.size!==raw.length?null:{byte_size:raw.length,content_hash:createHash("sha256").update(raw).digest("hex")}}catch(error){if(isFileMissingError(error))return{byte_size:0,content_hash:createHash("sha256").digest("hex")};throw error}}async function historyIndexMatchesStreamContents(storedSizes,pmRoot,streamIds){for(let start=0;start<streamIds.length;start+=HISTORY_STREAM_CONTENT_READ_CONCURRENCY){const chunk=streamIds.slice(start,start+HISTORY_STREAM_CONTENT_READ_CONCURRENCY),currentSizes=await Promise.all(chunk.map(streamId=>readHistoryStreamContentReceipt(pmRoot,streamId)));for(const[index,currentSize]of currentSizes.entries()){if(currentSize===null)return!1;const streamId=chunk[index],storedSize=storedSizes.get(streamId);if(!(currentSize.byte_size===0&&storedSize===void 0)&&(currentSize.byte_size!==storedSize?.byte_size||currentSize.content_hash!==storedSize.content_hash))return!1}}return!0}async function historyIndexValidationStreamIds(indexed,pmRoot,requestedStreamIds){if(requestedStreamIds&&requestedStreamIds.length>0)return[...new Set(requestedStreamIds.filter(streamId=>streamId.trim().length>0))];const authoritative=await fs.readdir(path.join(pmRoot,"history"),{withFileTypes:!0}).then(entries=>entries.filter(entry=>entry.isFile()&&entry.name.endsWith(".jsonl")).map(entry=>entry.name.slice(0,-6))).catch(error=>{if(isFileMissingError(error))return[];throw error});return[...new Set([...indexed,...authoritative])]}async function readIndexedLatestSubstantiveEvents(Database,pmRoot,streamIds,requested){return Database?readHistoryEventIndexSnapshot(pmRoot,Database,streamIds,database=>{const indexed=[];for(let start=0;start<streamIds.length;start+=500){const chunk=streamIds.slice(start,start+500),parsed=database.prepare(`SELECT stream_id, stream_offset, entry_json
47
+ LIMIT ?`).all(...s,Math.max(0,Math.floor(e.limit))+1),u=c.slice(0,e.limit).map(ct);return u.includes(null)?null:{events:u,has_more:c.length>e.limit}});return{result:a===h?null:a,repair_needed:a===null&&!await tt(t)}}async function de(t,e){return(await Wt(t,e)).result}function k(t,e){const n=Object.create(null);for(const r of t){if(!e.has(r.stream_id)||B(r.entry)!=="substantive")continue;const s=n[r.stream_id];(s===void 0||X(s,r)<0)&&(n[r.stream_id]=r)}return n}async function F(t,e){if(_.basename(e)!==e)return null;try{const n=_.join(t,"history",`${e}.jsonl`),r=await l.stat(n),s=await l.readFile(n);return r.size!==s.length?null:{byte_size:s.length,content_hash:N("sha256").update(s).digest("hex")}}catch(n){if(g(n))return{byte_size:0,content_hash:N("sha256").digest("hex")};throw n}}async function Vt(t,e,n){for(let r=0;r<n.length;r+=Q){const s=n.slice(r,r+Q),i=await Promise.all(s.map(a=>F(e,a)));for(const[a,o]of i.entries()){if(o===null)return!1;const c=s[a],u=t.get(c);if(!(o.byte_size===0&&u===void 0)&&(o.byte_size!==u?.byte_size||o.content_hash!==u.content_hash))return!1}}return!0}async function Yt(t,e,n){if(n&&n.length>0)return[...new Set(n.filter(s=>s.trim().length>0))];const r=await l.readdir(_.join(e,"history"),{withFileTypes:!0}).then(s=>s.filter(i=>i.isFile()&&i.name.endsWith(".jsonl")).map(i=>i.name.slice(0,-6))).catch(s=>{if(g(s))return[];throw s});return[...new Set([...t,...r])]}async function _t(t,e,n,r){return t?lt(e,t,n,s=>{const i=[];for(let a=0;a<n.length;a+=500){const o=n.slice(a,a+500),u=s.prepare(`SELECT stream_id, stream_offset, entry_json
48
48
  FROM (
49
49
  SELECT stream_id, stream_offset, entry_json,
50
50
  ROW_NUMBER() OVER (
@@ -53,7 +53,7 @@
53
53
  ) AS recency_rank
54
54
  FROM events
55
55
  WHERE event_class = 'substantive'
56
- AND stream_id IN (${chunk.map(()=>"?").join(", ")})
56
+ AND stream_id IN (${o.map(()=>"?").join(", ")})
57
57
  )
58
- WHERE recency_rank = 1`).all(...chunk).map(parseIndexedHistoryEvent);if(parsed.includes(null))return null;indexed.push(...parsed)}return collectLatestSubstantiveEvents(indexed,requested)}):null}async function readLatestSubstantiveHistoryEvents(pmRoot,streamIds){const uniqueIds=[...new Set(streamIds.filter(id=>id.trim().length>0&&path.basename(id)===id))];if(uniqueIds.length===0)return{};const requested=new Set(uniqueIds),Database=resolveDatabaseSync(),indexed=await readIndexedLatestSubstantiveEvents(Database,pmRoot,uniqueIds,requested);if(indexed!==null&&indexed!==HISTORY_INDEX_CHANGED)return indexed;if(Database&&indexed!==HISTORY_INDEX_CHANGED&&!await hasRecentRefusedHistoryRepair(pmRoot))try{if(await rebuildHistoryEventIndex(pmRoot,{lockWaitMs:0})){const rebuilt=await readIndexedLatestSubstantiveEvents(Database,pmRoot,uniqueIds,requested);if(rebuilt!==null&&rebuilt!==HISTORY_INDEX_CHANGED)return rebuilt}}catch{}const authoritative=[];return await Promise.all(uniqueIds.map(async streamId=>{const historyPath=path.join(pmRoot,"history",`${streamId}.jsonl`);(await readIndexableHistoryEntries(historyPath,streamId).catch(error=>{if(error instanceof PmCliError&&error.code==="history_timestamp_invalid")return[];throw error})).forEach((entry,streamOffset)=>{authoritative.push({stream_id:streamId,stream_offset:streamOffset,entry})})})),collectLatestSubstantiveEvents(authoritative,requested)}const _testOnly={collectLatestSubstantiveEvents,loadDatabaseSync,loadStableDatabaseSync,setDatabaseSync(databaseSync){const previous=RuntimeDatabaseSync;return RuntimeDatabaseSync=databaseSync,()=>{RuntimeDatabaseSync=previous}}};export{_testOnly,appendHistoryEntryWithEventIndex,queryHistoryEventIndex,queryHistoryEventStreams,readHistoryEventIndexPage,readLatestSubstantiveHistoryEvents,rebuildHistoryEventIndex,removeHistoryEventIndexForHistoryPath};
58
+ WHERE recency_rank = 1`).all(...o).map(ct);if(u.includes(null))return null;i.push(...u)}return k(i,r)}):null}async function fe(t,e){const n=[...new Set(e.filter(o=>o.trim().length>0&&_.basename(o)===o))];if(n.length===0)return{};const r=new Set(n),s=b(),i=await _t(s,t,n,r);if(i!==null&&i!==h)return i;if(s&&i!==h&&!await tt(t))try{if(await Dt(t,{lockWaitMs:0})){const o=await _t(s,t,n,r);if(o!==null&&o!==h)return o}}catch{}const a=[];return await Promise.all(n.map(async o=>{const c=_.join(t,"history",`${o}.jsonl`);(await Ct(c,o).catch(f=>{if(f instanceof I&&f.code==="history_timestamp_invalid")return[];throw f})).forEach((f,d)=>{a.push({stream_id:o,stream_offset:d,entry:f})})})),k(a,r)}const le={collectLatestSubstantiveEvents:k,loadDatabaseSync:wt,loadStableDatabaseSync:K,setDatabaseSync(t){const e=p;return p=t,()=>{p=e}}};export{le as _testOnly,oe as appendHistoryEntryWithEventIndex,de as queryHistoryEventIndex,Xt as queryHistoryEventStreams,Wt as readHistoryEventIndexPage,fe as readLatestSubstantiveHistoryEvents,Dt as rebuildHistoryEventIndex,ce as removeHistoryEventIndexForHistoryPath};
59
59
  //# sourceMappingURL=event-index.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f3603dce-8aeb-5409-80f4-ad3367e35eb9")}catch{}})();function selectIdsMode(ids,byId,minEntries){const seen=new Set,rows=[];for(const rawId of ids){const id=rawId.trim();if(id.length===0||seen.has(id))continue;seen.add(id);const candidate=byId.get(id);if(candidate===void 0){rows.push({id,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(candidate.entries<=minEntries){rows.push({id,entries:candidate.entries,selected:!1,skip_reason:"already_compact"});continue}rows.push({id,entries:candidate.entries,selected:!0,skip_reason:null})}return rows}function selectScanMode(candidates,criteria){const ordered=[...candidates].sort((a,b)=>b.entries-a.entries||a.id.localeCompare(b.id)),rows=[];for(const candidate of ordered){if(criteria.scope==="closed"&&candidate.bucket!=="closed"){rows.push({id:candidate.id,entries:candidate.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(candidate.entries<=criteria.minEntries){rows.push({id:candidate.id,entries:candidate.entries,selected:!1,skip_reason:"already_compact"});continue}if(criteria.allOver!==void 0&&candidate.entries<=criteria.allOver){rows.push({id:candidate.id,entries:candidate.entries,selected:!1,skip_reason:"below_threshold"});continue}rows.push({id:candidate.id,entries:candidate.entries,selected:!0,skip_reason:null})}return rows}function selectHistoryCompactBulkTargets(candidates,criteria){if(criteria.ids!==void 0&&criteria.ids.length>0){const byId=new Map(candidates.map(candidate=>[candidate.id,candidate]));return selectIdsMode(criteria.ids,byId,criteria.minEntries)}return selectScanMode(candidates,criteria)}export{selectHistoryCompactBulkTargets};
1
+ function c(i,s,o){const n=new Set,e=[];for(const d of i){const t=d.trim();if(t.length===0||n.has(t))continue;n.add(t);const r=s.get(t);if(r===void 0){e.push({id:t,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(r.entries<=o){e.push({id:t,entries:r.entries,selected:!1,skip_reason:"already_compact"});continue}e.push({id:t,entries:r.entries,selected:!0,skip_reason:null})}return e}function l(i,s){const o=[...i].sort((e,d)=>d.entries-e.entries||e.id.localeCompare(d.id)),n=[];for(const e of o){if(s.scope==="closed"&&e.bucket!=="closed"){n.push({id:e.id,entries:e.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(e.entries<=s.minEntries){n.push({id:e.id,entries:e.entries,selected:!1,skip_reason:"already_compact"});continue}if(s.allOver!==void 0&&e.entries<=s.allOver){n.push({id:e.id,entries:e.entries,selected:!1,skip_reason:"below_threshold"});continue}n.push({id:e.id,entries:e.entries,selected:!0,skip_reason:null})}return n}function u(i,s){if(s.ids!==void 0&&s.ids.length>0){const o=new Map(i.map(n=>[n.id,n]));return c(s.ids,o,s.minEntries)}return l(i,s)}export{u as selectHistoryCompactBulkTargets};
2
2
  //# sourceMappingURL=history-compact-bulk.js.map