@unbrained/pm-cli 2026.10.3 → 2026.10.5

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 (742) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +28 -2
  3. package/dist/cli/after-command-context-usage.js +1 -1
  4. package/dist/cli/argv-utils.js +1 -1
  5. package/dist/cli/bootstrap-args.js +1 -1
  6. package/dist/cli/bundle-integrity.js +2 -2
  7. package/dist/cli/command-namespaces.js +1 -1
  8. package/dist/cli/commander-usage.d.ts +1 -1
  9. package/dist/cli/commander-usage.js +7 -4
  10. package/dist/cli/commands/annotations/comments.js +1 -1
  11. package/dist/cli/commands/annotations/docs.js +1 -1
  12. package/dist/cli/commands/annotations/files.js +1 -1
  13. package/dist/cli/commands/annotations/learnings.js +1 -1
  14. package/dist/cli/commands/annotations/notes.js +1 -1
  15. package/dist/cli/commands/extension/describe.js +1 -1
  16. package/dist/cli/commands/extension/extension.js +1 -1
  17. package/dist/cli/commands/extension/scaffold.js +1 -1
  18. package/dist/cli/commands/extension/shared.js +1 -1
  19. package/dist/cli/commands/governance/gc.js +1 -1
  20. package/dist/cli/commands/governance/health.js +1 -1
  21. package/dist/cli/commands/governance/telemetry.js +1 -1
  22. package/dist/cli/commands/governance/validate.js +1 -1
  23. package/dist/cli/commands/history/activity.js +1 -1
  24. package/dist/cli/commands/history/history-compact.js +1 -1
  25. package/dist/cli/commands/history/history-redact.js +1 -1
  26. package/dist/cli/commands/history/history-repair.js +1 -1
  27. package/dist/cli/commands/history/history.js +1 -1
  28. package/dist/cli/commands/history/restore.js +1 -1
  29. package/dist/cli/commands/lifecycle/append.js +1 -1
  30. package/dist/cli/commands/lifecycle/claim.js +1 -1
  31. package/dist/cli/commands/lifecycle/close-many.js +1 -1
  32. package/dist/cli/commands/lifecycle/close.js +1 -1
  33. package/dist/cli/commands/lifecycle/copy.js +1 -1
  34. package/dist/cli/commands/lifecycle/create.js +1 -1
  35. package/dist/cli/commands/lifecycle/delete.js +1 -1
  36. package/dist/cli/commands/lifecycle/focus.js +1 -1
  37. package/dist/cli/commands/lifecycle/plan.js +1 -1
  38. package/dist/cli/commands/lifecycle/update-many.js +1 -1
  39. package/dist/cli/commands/lifecycle/update.js +1 -1
  40. package/dist/cli/commands/query/aggregate.js +1 -1
  41. package/dist/cli/commands/query/context.js +1 -1
  42. package/dist/cli/commands/query/deps.js +1 -1
  43. package/dist/cli/commands/query/duplicates.js +1 -1
  44. package/dist/cli/commands/query/eval.js +1 -1
  45. package/dist/cli/commands/query/get.js +1 -1
  46. package/dist/cli/commands/query/graph.js +1 -1
  47. package/dist/cli/commands/query/list.js +1 -1
  48. package/dist/cli/commands/query/next.js +1 -1
  49. package/dist/cli/commands/query/search.js +1 -1
  50. package/dist/cli/commands/query/stats.js +1 -1
  51. package/dist/cli/commands/test/test-all.js +1 -1
  52. package/dist/cli/commands/test/test-runs.js +1 -1
  53. package/dist/cli/commands/test/test.js +1 -1
  54. package/dist/cli/commands/workspace/config.js +1 -1
  55. package/dist/cli/commands/workspace/contracts.js +1 -1
  56. package/dist/cli/commands/workspace/init.js +1 -1
  57. package/dist/cli/commands/workspace/merge.js +1 -1
  58. package/dist/cli/commands/workspace/profile.js +1 -1
  59. package/dist/cli/commands/workspace/schema.js +1 -1
  60. package/dist/cli/commands/workspace/upgrade.js +1 -1
  61. package/dist/cli/context-intent-invocation.js +1 -1
  62. package/dist/cli/description-stdin.js +1 -1
  63. package/dist/cli/error-guidance.js +3 -1
  64. package/dist/cli/extension-command-help.js +5 -3
  65. package/dist/cli/extension-command-options.js +1 -1
  66. package/dist/cli/extension-recovery.js +1 -1
  67. package/dist/cli/help-content.js +5 -2
  68. package/dist/cli/help-json-payload.js +6 -3
  69. package/dist/cli/invocation-profile.js +2 -2
  70. package/dist/cli/main.js +5 -5
  71. package/dist/cli/migration-gates.js +1 -1
  72. package/dist/cli/option-values.js +1 -1
  73. package/dist/cli/public.js +1 -1
  74. package/dist/cli/register-annotations.js +1 -1
  75. package/dist/cli/register-assurance.js +1 -1
  76. package/dist/cli/register-files-lookup.js +1 -1
  77. package/dist/cli/register-history-activity.js +1 -1
  78. package/dist/cli/register-history-author.js +1 -1
  79. package/dist/cli/register-history-maintenance.js +2 -2
  80. package/dist/cli/register-list-query.js +10 -10
  81. package/dist/cli/register-mutation-options.js +1 -1
  82. package/dist/cli/register-mutation.js +2 -2
  83. package/dist/cli/register-operations.js +1 -1
  84. package/dist/cli/register-setup.js +1 -1
  85. package/dist/cli/register-structured-mutation.js +1 -1
  86. package/dist/cli/registration-helpers.js +1 -1
  87. package/dist/cli/runtime/activation.js +1 -1
  88. package/dist/cli/runtime/invocation-options.js +1 -1
  89. package/dist/cli/runtime/projection-retry.js +1 -1
  90. package/dist/cli/runtime/selection.js +1 -1
  91. package/dist/cli/runtime/telemetry-outcome.js +1 -1
  92. package/dist/cli/runtime-compatibility-boundary.d.ts +1 -1
  93. package/dist/cli/runtime-compatibility-boundary.js +4 -4
  94. package/dist/cli/schema/registration.js +2 -2
  95. package/dist/cli/schema-registration-helpers.js +1 -1
  96. package/dist/cli/search-refresh.js +1 -1
  97. package/dist/cli/stats-analytics-json.js +1 -1
  98. package/dist/cli/telemetry-flush.js +1 -1
  99. package/dist/cli-bundle/bundle-manifest.json +162 -162
  100. package/dist/cli-bundle/chunks/chunk-3CYOBJUK.js +3 -0
  101. package/dist/cli-bundle/chunks/chunk-5MNOWZPN.js +3 -0
  102. package/dist/cli-bundle/chunks/chunk-AJ7H6XUF.js +20 -0
  103. package/dist/cli-bundle/chunks/chunk-D332RXZ7.js +80 -0
  104. package/dist/cli-bundle/chunks/chunk-HRJ6G6ZG.js +31 -0
  105. package/dist/cli-bundle/chunks/chunk-KRVI56QE.js +6 -0
  106. package/dist/cli-bundle/chunks/chunk-N4YGSG6F.js +238 -0
  107. package/dist/cli-bundle/chunks/chunk-OOLYASYJ.js +2 -0
  108. package/dist/cli-bundle/chunks/chunk-R7CG2DB7.js +2 -0
  109. package/dist/cli-bundle/chunks/chunk-TGMONGWX.js +2 -0
  110. package/dist/cli-bundle/chunks/chunk-UZ7BIUCI.js +2 -0
  111. package/dist/cli-bundle/chunks/{chunk-44UGMMQ6.js → chunk-VZ63DEVJ.js} +3 -3
  112. package/dist/cli-bundle/chunks/chunk-WFZ4UEOB.js +2 -0
  113. package/dist/cli-bundle/chunks/chunk-YVBRASXO.js +8 -0
  114. package/dist/cli-bundle/chunks/{chunk-5XKF5SQV.js → chunk-Z66DWDAU.js} +91 -91
  115. package/dist/cli-bundle/chunks/{register-list-query-DYCGUQEW.js → register-list-query-75QXHIFH.js} +11 -11
  116. package/dist/cli-bundle/chunks/register-mutation-YS54SCHG.js +20 -0
  117. package/dist/cli-bundle/chunks/register-operations-6KHZQSYJ.js +2 -0
  118. package/dist/cli-bundle/chunks/register-setup-RTATEN2M.js +2 -0
  119. package/dist/cli-bundle/focused-chunks/{chunk-3BIYG72P.js → chunk-2CVX3KR3.js} +2 -2
  120. package/dist/cli-bundle/focused-chunks/chunk-5C3IDDW7.js +2 -0
  121. package/dist/cli-bundle/focused-chunks/{chunk-DBD4W4QP.js → chunk-ABV67XCC.js} +3 -3
  122. package/dist/cli-bundle/focused-chunks/chunk-B5RSLVE6.js +3 -0
  123. package/dist/cli-bundle/focused-chunks/chunk-C224METM.js +20 -0
  124. package/dist/cli-bundle/focused-chunks/chunk-CLDPTMQY.js +6 -0
  125. package/dist/cli-bundle/focused-chunks/chunk-DDRN42PB.js +8 -0
  126. package/dist/cli-bundle/focused-chunks/{chunk-EJN7DY3B.js → chunk-DOVTUKJQ.js} +2 -2
  127. package/dist/cli-bundle/focused-chunks/chunk-ECBOPEJE.js +75 -0
  128. package/dist/cli-bundle/focused-chunks/chunk-GITOYRUW.js +165 -0
  129. package/dist/cli-bundle/focused-chunks/chunk-GUIF3WVC.js +30 -0
  130. package/dist/cli-bundle/focused-chunks/chunk-LE4JUCRR.js +3 -0
  131. package/dist/cli-bundle/focused-chunks/{chunk-HFAW3FJQ.js → chunk-PSXFFQFT.js} +2 -2
  132. package/dist/cli-bundle/focused-chunks/chunk-RHIH6XIW.js +12 -0
  133. package/dist/cli-bundle/focused-chunks/chunk-UDYRVBOZ.js +2 -0
  134. package/dist/cli-bundle/focused-chunks/chunk-XV5RV4ZT.js +2 -0
  135. package/dist/cli-bundle/focused-chunks/{chunk-XRSCIYHR.js → chunk-YMU42COG.js} +2 -2
  136. package/dist/cli-bundle/main.js +28 -28
  137. package/dist/cli-bundle/sdk-authoring.js +1 -1
  138. package/dist/cli-bundle/sdk-contracts.js +2 -2
  139. package/dist/cli-bundle/sdk-core.js +32 -32
  140. package/dist/cli-bundle/sdk-governance.js +1 -1
  141. package/dist/cli-bundle/sdk-graph.js +1 -1
  142. package/dist/cli-bundle/sdk-merge.js +55 -55
  143. package/dist/cli-bundle/sdk-query.js +1 -1
  144. package/dist/cli-bundle/sdk-runtime.js +1 -1
  145. package/dist/cli-bundle/sdk-testing.js +1 -1
  146. package/dist/cli-bundle/sdk.js +10 -10
  147. package/dist/cli.js +1 -1
  148. package/dist/core/checkpoint/checkpoint-gc.js +1 -1
  149. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  150. package/dist/core/config/nested-settings.js +1 -1
  151. package/dist/core/config/positional-value.js +1 -1
  152. package/dist/core/diagnostics/remediation.js +1 -1
  153. package/dist/core/extensions/activation-summary-markdown.js +2 -1
  154. package/dist/core/extensions/activation-summary.js +1 -1
  155. package/dist/core/extensions/activation-transaction.js +1 -1
  156. package/dist/core/extensions/capability-usage.js +1 -1
  157. package/dist/core/extensions/command-hook-context.js +1 -1
  158. package/dist/core/extensions/command-metadata-contract.js +1 -1
  159. package/dist/core/extensions/command-visibility-tier.js +1 -1
  160. package/dist/core/extensions/contribution-inventory.js +1 -1
  161. package/dist/core/extensions/exporter-output-contract.js +1 -1
  162. package/dist/core/extensions/extension-candidate.js +1 -1
  163. package/dist/core/extensions/extension-capability-aliases.js +1 -1
  164. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  165. package/dist/core/extensions/extension-policy.js +1 -1
  166. package/dist/core/extensions/extension-registries.js +1 -1
  167. package/dist/core/extensions/extension-runtime-helpers.js +1 -1
  168. package/dist/core/extensions/extension-types.d.ts +8 -1
  169. package/dist/core/extensions/extension-types.js +1 -1
  170. package/dist/core/extensions/flag-definition-validation.js +1 -1
  171. package/dist/core/extensions/flag-value-types.js +1 -1
  172. package/dist/core/extensions/index.js +1 -1
  173. package/dist/core/extensions/item-field-types.js +1 -1
  174. package/dist/core/extensions/item-fields.js +1 -1
  175. package/dist/core/extensions/loader.js +1 -1
  176. package/dist/core/extensions/manifest-parser.js +1 -1
  177. package/dist/core/extensions/manifest-schema.js +1 -1
  178. package/dist/core/extensions/module-graph-snapshot.js +1 -1
  179. package/dist/core/extensions/preflight-ownership.js +1 -1
  180. package/dist/core/extensions/registration-contracts.js +1 -1
  181. package/dist/core/extensions/registration-validation.js +1 -1
  182. package/dist/core/extensions/registration-values.js +1 -1
  183. package/dist/core/extensions/reserved-host-flags.js +1 -1
  184. package/dist/core/extensions/runtime-registrations.js +1 -1
  185. package/dist/core/extensions/service-ownership.js +1 -1
  186. package/dist/core/extensions/version-compat.js +1 -1
  187. package/dist/core/fs/atomic-create.js +1 -1
  188. package/dist/core/fs/fs-utils.js +2 -2
  189. package/dist/core/fs/host-environment-errors.js +1 -1
  190. package/dist/core/fs/index.js +1 -1
  191. package/dist/core/fs/path-utils.js +1 -1
  192. package/dist/core/governance/content-fields.js +1 -1
  193. package/dist/core/governance/issue-codes.js +1 -1
  194. package/dist/core/governance/metadata-coverage.js +1 -1
  195. package/dist/core/history/digest.js +1 -1
  196. package/dist/core/history/drift-cache.js +3 -3
  197. package/dist/core/history/drift-scan.d.ts +4 -0
  198. package/dist/core/history/drift-scan.js +1 -1
  199. package/dist/core/history/event-classification.js +1 -1
  200. package/dist/core/history/event-index.js +8 -7
  201. package/dist/core/history/history-compact-bulk.js +1 -1
  202. package/dist/core/history/history-diff.js +1 -1
  203. package/dist/core/history/history-rewrite.js +1 -1
  204. package/dist/core/history/history-storage-stats.js +1 -1
  205. package/dist/core/history/history-stream-policy.js +1 -1
  206. package/dist/core/history/history.js +2 -2
  207. package/dist/core/history/identity.js +1 -1
  208. package/dist/core/history/index.js +1 -1
  209. package/dist/core/history/operation-contract.js +1 -1
  210. package/dist/core/history/projection.js +1 -1
  211. package/dist/core/history/read.js +1 -1
  212. package/dist/core/history/replay.js +2 -1
  213. package/dist/core/history/tombstone.js +1 -1
  214. package/dist/core/history/version-address.js +1 -1
  215. package/dist/core/history/workspace-history.js +2 -2
  216. package/dist/core/io/body-file.js +1 -1
  217. package/dist/core/io/bulk-ids-input.js +2 -1
  218. package/dist/core/item/actionability.js +1 -1
  219. package/dist/core/item/dependency-reference.js +1 -1
  220. package/dist/core/item/id.js +1 -1
  221. package/dist/core/item/index.js +1 -1
  222. package/dist/core/item/item-format-version.js +1 -1
  223. package/dist/core/item/item-format.js +6 -4
  224. package/dist/core/item/item-record.js +1 -1
  225. package/dist/core/item/item-type-definition.js +1 -1
  226. package/dist/core/item/parent-reference-policy.js +1 -1
  227. package/dist/core/item/parse.js +8 -2
  228. package/dist/core/item/plan-lifecycle.js +1 -1
  229. package/dist/core/item/priority.js +1 -1
  230. package/dist/core/item/sprint-release-format.js +1 -1
  231. package/dist/core/item/status-filter.js +1 -1
  232. package/dist/core/item/status.js +1 -1
  233. package/dist/core/item/toon-decode.js +1 -1
  234. package/dist/core/item/type-registry.js +1 -1
  235. package/dist/core/item/type-synonyms.js +1 -1
  236. package/dist/core/lock/index.js +1 -1
  237. package/dist/core/lock/lock-gc.js +1 -1
  238. package/dist/core/lock/lock.js +3 -3
  239. package/dist/core/output/mutation-projection.js +1 -1
  240. package/dist/core/output/output-control.js +1 -1
  241. package/dist/core/output/output.js +22 -10
  242. package/dist/core/output/query-summary.js +1 -1
  243. package/dist/core/output/tabular.js +3 -1
  244. package/dist/core/packages/manifest.js +1 -1
  245. package/dist/core/packages/root.js +1 -1
  246. package/dist/core/policy/workflow-policy-schema.js +1 -1
  247. package/dist/core/policy/workflow-policy-store.js +1 -1
  248. package/dist/core/policy/workflow-policy.js +1 -1
  249. package/dist/core/profile/profile-describe.js +1 -1
  250. package/dist/core/profile/profile-lint.js +1 -1
  251. package/dist/core/profile/profile-plan.js +1 -1
  252. package/dist/core/profile/profile-presets.js +25 -1
  253. package/dist/core/reproducibility/context.js +1 -1
  254. package/dist/core/schema/fields-file.js +2 -2
  255. package/dist/core/schema/item-types-file.js +2 -2
  256. package/dist/core/schema/runtime-field-filters.js +1 -1
  257. package/dist/core/schema/runtime-field-values.js +1 -1
  258. package/dist/core/schema/runtime-schema.js +2 -2
  259. package/dist/core/schema/status-defs-file.js +2 -2
  260. package/dist/core/schema/status-token.js +1 -1
  261. package/dist/core/schema/type-inference.js +1 -1
  262. package/dist/core/schema/type-presets.js +1 -1
  263. package/dist/core/schema/type-workflows.js +1 -1
  264. package/dist/core/search/background-refresh.js +2 -2
  265. package/dist/core/search/bm25.js +1 -1
  266. package/dist/core/search/cache.js +2 -2
  267. package/dist/core/search/corpus.js +1 -1
  268. package/dist/core/search/embedding-batches.js +1 -1
  269. package/dist/core/search/eval-thresholds.js +1 -1
  270. package/dist/core/search/eval.js +1 -1
  271. package/dist/core/search/http-client.js +1 -1
  272. package/dist/core/search/providers.js +1 -1
  273. package/dist/core/search/relevance.js +1 -1
  274. package/dist/core/search/semantic-defaults.js +1 -1
  275. package/dist/core/search/staleness.js +1 -1
  276. package/dist/core/search/vector-stores.js +2 -2
  277. package/dist/core/search/vectorization-metadata.js +1 -1
  278. package/dist/core/sentry/helpers.js +1 -1
  279. package/dist/core/sentry/instrument.js +1 -1
  280. package/dist/core/session/session-state.js +1 -1
  281. package/dist/core/shared/agent-session-context.js +1 -1
  282. package/dist/core/shared/author.js +5 -1
  283. package/dist/core/shared/command-line.js +1 -1
  284. package/dist/core/shared/command-types.js +1 -1
  285. package/dist/core/shared/conflict-markers.js +1 -1
  286. package/dist/core/shared/constants.js +1 -1
  287. package/dist/core/shared/errors.js +1 -1
  288. package/dist/core/shared/html-entity-decode.js +1 -1
  289. package/dist/core/shared/index.js +1 -1
  290. package/dist/core/shared/item-metadata-contract.js +1 -1
  291. package/dist/core/shared/lazy-module.js +1 -1
  292. package/dist/core/shared/levenshtein.js +1 -1
  293. package/dist/core/shared/memo.js +1 -1
  294. package/dist/core/shared/numeric-parsers.js +1 -1
  295. package/dist/core/shared/option-alias-visibility.js +1 -1
  296. package/dist/core/shared/primitives.js +1 -1
  297. package/dist/core/shared/secret-rules.js +1 -1
  298. package/dist/core/shared/serial-queue.js +1 -1
  299. package/dist/core/shared/serialization.js +1 -1
  300. package/dist/core/shared/split-comma-list.js +1 -1
  301. package/dist/core/shared/text-normalization.js +1 -1
  302. package/dist/core/shared/time.js +2 -1
  303. package/dist/core/store/index.js +1 -1
  304. package/dist/core/store/item-format-migration.js +1 -1
  305. package/dist/core/store/item-metadata-cache.js +1 -1
  306. package/dist/core/store/item-metadata-query-index.js +7 -7
  307. package/dist/core/store/item-metadata-read-work.js +1 -1
  308. package/dist/core/store/item-store.js +1 -1
  309. package/dist/core/store/paths.js +1 -1
  310. package/dist/core/store/settings-concurrency.js +1 -1
  311. package/dist/core/store/settings-read-cache.js +1 -1
  312. package/dist/core/store/settings-validator.js +1 -1
  313. package/dist/core/store/settings.d.ts +11 -2
  314. package/dist/core/store/settings.js +3 -3
  315. package/dist/core/store/tracker-preflight.js +1 -1
  316. package/dist/core/telemetry/consent.js +2 -2
  317. package/dist/core/telemetry/observability.js +1 -1
  318. package/dist/core/telemetry/policy.js +1 -1
  319. package/dist/core/telemetry/read-sampling.js +2 -2
  320. package/dist/core/telemetry/runtime.js +9 -5
  321. package/dist/core/test/background-runs.js +3 -3
  322. package/dist/core/test/item-test-run-tracking.js +1 -1
  323. package/dist/core/test/run-selectors.js +1 -1
  324. package/dist/core/validate/estimate-defaults.js +1 -1
  325. package/dist/core/validate/fix-planning.js +1 -1
  326. package/dist/core/validate/linked-artifact-reference.js +1 -1
  327. package/dist/core/validate/missing-by-type.js +1 -1
  328. package/dist/core/validate/missing-link-owners.js +1 -1
  329. package/dist/core/validate/stale-file-classification.js +1 -1
  330. package/dist/mcp/http-server.js +6 -4
  331. package/dist/mcp/legacy-adapter.js +1 -1
  332. package/dist/mcp/runtime-capabilities.js +1 -1
  333. package/dist/mcp/server.js +4 -4
  334. package/dist/mcp/tool-definitions.js +1 -1
  335. package/dist/sdk/actionability.js +1 -1
  336. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  337. package/dist/sdk/agent/command-recovery.js +1 -1
  338. package/dist/sdk/agent/command-suggestions.js +1 -1
  339. package/dist/sdk/agent/create-option-policy.js +1 -1
  340. package/dist/sdk/agent/identity-config.js +1 -1
  341. package/dist/sdk/agent/item-addressing.js +1 -1
  342. package/dist/sdk/agent/refusal-closure-census.js +2 -1
  343. package/dist/sdk/agent/refusal-closure.js +1 -1
  344. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
  345. package/dist/sdk/agent/refusal-reachability.js +3 -1
  346. package/dist/sdk/agent/subcommand-recovery.js +1 -1
  347. package/dist/sdk/agent/task-transcript-contracts.js +1 -1
  348. package/dist/sdk/agent/tracker-preflight-contracts.js +1 -1
  349. package/dist/sdk/agent-capability-contracts.js +3 -1
  350. package/dist/sdk/agent-session-context.js +1 -1
  351. package/dist/sdk/annotations.js +1 -1
  352. package/dist/sdk/author-attribution.js +1 -1
  353. package/dist/sdk/authoring.js +1 -1
  354. package/dist/sdk/cli-bootstrap.js +1 -1
  355. package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -3
  356. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  357. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  358. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
  359. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  360. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  361. package/dist/sdk/cli-contracts/completeness.js +1 -1
  362. package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
  363. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  364. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -1
  365. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  366. package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
  367. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  368. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
  369. package/dist/sdk/cli-contracts/string-lists.js +1 -1
  370. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  371. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  372. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  373. package/dist/sdk/cli-contracts/typed-action-inputs.js +1 -1
  374. package/dist/sdk/cli-contracts.js +1 -1
  375. package/dist/sdk/cli-program.js +1 -1
  376. package/dist/sdk/command-line.js +1 -1
  377. package/dist/sdk/comments.js +1 -1
  378. package/dist/sdk/compile-cache.js +1 -1
  379. package/dist/sdk/completion/bash.js +2 -1
  380. package/dist/sdk/completion/fish.js +13 -7
  381. package/dist/sdk/completion/shared.js +1 -1
  382. package/dist/sdk/completion/zsh.js +14 -8
  383. package/dist/sdk/completion.js +1 -1
  384. package/dist/sdk/compose.js +1 -1
  385. package/dist/sdk/config.js +1 -1
  386. package/dist/sdk/context/recency.js +1 -1
  387. package/dist/sdk/context/semantic-session-attribution.js +1 -1
  388. package/dist/sdk/context/usage-egress.js +1 -1
  389. package/dist/sdk/context/usage-ledger.js +6 -3
  390. package/dist/sdk/context-intent-contracts.js +1 -1
  391. package/dist/sdk/context-intent-runtime.js +1 -1
  392. package/dist/sdk/context-packing.js +1 -1
  393. package/dist/sdk/context-relevance.js +1 -1
  394. package/dist/sdk/context-signal-store.js +2 -2
  395. package/dist/sdk/context-usage.js +1 -1
  396. package/dist/sdk/contracts.js +1 -1
  397. package/dist/sdk/core-governance.js +1 -1
  398. package/dist/sdk/core.js +1 -1
  399. package/dist/sdk/corpus-shape.js +1 -1
  400. package/dist/sdk/define.js +1 -1
  401. package/dist/sdk/dependencies.js +1 -1
  402. package/dist/sdk/dependency-flag-validation.js +1 -1
  403. package/dist/sdk/dependency-provenance.js +1 -1
  404. package/dist/sdk/docs.js +1 -1
  405. package/dist/sdk/duplicates.js +1 -1
  406. package/dist/sdk/environment/agent-environment.js +1 -1
  407. package/dist/sdk/environment/host-environment-errors.js +1 -1
  408. package/dist/sdk/environment/project-runtime-compatibility.js +2 -1
  409. package/dist/sdk/environment/source-context.js +1 -1
  410. package/dist/sdk/environment/tracker-preflight.js +1 -1
  411. package/dist/sdk/error-code-catalog.js +1 -1
  412. package/dist/sdk/error-runtime.js +1 -1
  413. package/dist/sdk/errors.js +1 -1
  414. package/dist/sdk/eval.js +1 -1
  415. package/dist/sdk/extension/author-manifest.js +1 -1
  416. package/dist/sdk/extension/bundled-catalog.js +1 -1
  417. package/dist/sdk/extension/concurrency.js +1 -1
  418. package/dist/sdk/extension/copy-scope.js +1 -1
  419. package/dist/sdk/extension/custom-field-collisions.js +1 -1
  420. package/dist/sdk/extension/describe.js +4 -2
  421. package/dist/sdk/extension/doctor.js +1 -1
  422. package/dist/sdk/extension/install-plan.js +1 -1
  423. package/dist/sdk/extension/install-receipts.js +1 -1
  424. package/dist/sdk/extension/install-runtime.js +3 -3
  425. package/dist/sdk/extension/install-snapshot.js +1 -1
  426. package/dist/sdk/extension/install-sources.js +5 -5
  427. package/dist/sdk/extension/managed-state.js +2 -2
  428. package/dist/sdk/extension/migrations.js +2 -2
  429. package/dist/sdk/extension/output-ownership.js +1 -1
  430. package/dist/sdk/extension/runtime-summary.js +1 -1
  431. package/dist/sdk/extension/scaffold.js +11 -4
  432. package/dist/sdk/extension/shared.js +1 -1
  433. package/dist/sdk/extension/source-resolution.js +1 -1
  434. package/dist/sdk/extension/static-inventory.js +1 -1
  435. package/dist/sdk/extension/update-check.js +1 -1
  436. package/dist/sdk/extension-command-context.js +1 -1
  437. package/dist/sdk/extension-contracts.js +1 -1
  438. package/dist/sdk/extension.js +1 -1
  439. package/dist/sdk/files.js +1 -1
  440. package/dist/sdk/flag-invocation-contracts.js +1 -1
  441. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  442. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  443. package/dist/sdk/generated-error-code-catalog.js +1 -1
  444. package/dist/sdk/governance/assurance-action-contracts.js +1 -1
  445. package/dist/sdk/governance/assurance-action.js +1 -1
  446. package/dist/sdk/governance/assurance-limits.js +1 -1
  447. package/dist/sdk/governance/assurance-mutation-error.js +1 -1
  448. package/dist/sdk/governance/assurance-presets.js +1 -1
  449. package/dist/sdk/governance/assurance-runtime.js +1 -1
  450. package/dist/sdk/governance/assurance.js +4 -4
  451. package/dist/sdk/governance/boundary-fixtures.js +1 -1
  452. package/dist/sdk/governance/closure-timestamps.js +1 -1
  453. package/dist/sdk/governance/coverage-assurance.js +1 -1
  454. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
  455. package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
  456. package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
  457. package/dist/sdk/governance/defect-recurrence.js +1 -1
  458. package/dist/sdk/governance/extension-host-version.js +1 -1
  459. package/dist/sdk/governance/gc.js +1 -1
  460. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  461. package/dist/sdk/governance/health.js +2 -1
  462. package/dist/sdk/governance/hierarchy-validation.js +1 -1
  463. package/dist/sdk/governance/linked-file-report.js +1 -1
  464. package/dist/sdk/governance/merge-receipt-history.js +1 -1
  465. package/dist/sdk/governance/provenance-health.js +4 -1
  466. package/dist/sdk/governance/reindex.js +5 -4
  467. package/dist/sdk/governance/stale-work.js +1 -1
  468. package/dist/sdk/governance/status-role-diagnostics.js +1 -1
  469. package/dist/sdk/governance/storage-integrity.js +1 -1
  470. package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
  471. package/dist/sdk/governance/upgrade.js +2 -2
  472. package/dist/sdk/governance/validate-history-drift.js +1 -1
  473. package/dist/sdk/governance/validate-item-reader.js +1 -1
  474. package/dist/sdk/governance/validate-normalization.js +1 -1
  475. package/dist/sdk/governance/validate.js +1 -1
  476. package/dist/sdk/governance/workflow-completeness.js +1 -1
  477. package/dist/sdk/governance/workflow-policy.js +3 -3
  478. package/dist/sdk/governance/workspace-position.js +2 -1
  479. package/dist/sdk/governance.js +1 -1
  480. package/dist/sdk/graph/adapter.js +1 -1
  481. package/dist/sdk/graph/analytics.js +1 -1
  482. package/dist/sdk/graph/assembly.js +1 -1
  483. package/dist/sdk/graph/cache.js +1 -1
  484. package/dist/sdk/graph/centrality.js +1 -1
  485. package/dist/sdk/graph/conformance.js +1 -1
  486. package/dist/sdk/graph/deadline-scheduling.js +1 -1
  487. package/dist/sdk/graph/durable-cache.js +1 -1
  488. package/dist/sdk/graph/governance-contracts.js +1 -1
  489. package/dist/sdk/graph/governance.js +1 -1
  490. package/dist/sdk/graph/hierarchy-integrity.js +1 -1
  491. package/dist/sdk/graph/index.js +1 -1
  492. package/dist/sdk/graph/lifecycle-coverage.js +1 -1
  493. package/dist/sdk/graph/mutation-advisory.js +1 -1
  494. package/dist/sdk/graph/query-contracts.js +1 -1
  495. package/dist/sdk/graph/remediation.js +1 -1
  496. package/dist/sdk/graph/run.js +1 -1
  497. package/dist/sdk/graph/scheduling.js +1 -1
  498. package/dist/sdk/graph/traversal.js +1 -1
  499. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
  500. package/dist/sdk/graph.js +1 -1
  501. package/dist/sdk/guide-topics.js +1 -1
  502. package/dist/sdk/guide.js +8 -1
  503. package/dist/sdk/history/attestation-command.js +1 -1
  504. package/dist/sdk/history/attestation-contract.js +1 -1
  505. package/dist/sdk/history/attestation-scan.js +1 -1
  506. package/dist/sdk/history/attestation.js +1 -1
  507. package/dist/sdk/history/maintenance.js +1 -1
  508. package/dist/sdk/history/salvage.js +3 -2
  509. package/dist/sdk/history/subject.js +1 -1
  510. package/dist/sdk/history-analytics.js +1 -1
  511. package/dist/sdk/history-compact.js +1 -1
  512. package/dist/sdk/history-mcp.js +1 -1
  513. package/dist/sdk/history-provenance.js +1 -1
  514. package/dist/sdk/history-read.js +1 -1
  515. package/dist/sdk/history-redact.js +1 -1
  516. package/dist/sdk/history-repair.js +1 -1
  517. package/dist/sdk/improvement-ledger-validation.js +1 -1
  518. package/dist/sdk/improvement-ledger.js +2 -2
  519. package/dist/sdk/index.js +1 -1
  520. package/dist/sdk/init-agent-guidance.js +16 -2
  521. package/dist/sdk/init.js +16 -2
  522. package/dist/sdk/invocation-author.js +1 -1
  523. package/dist/sdk/item-children.js +1 -1
  524. package/dist/sdk/item-metadata-index.js +1 -1
  525. package/dist/sdk/item-schedule.js +1 -1
  526. package/dist/sdk/item-transaction.js +1 -1
  527. package/dist/sdk/learnings.js +1 -1
  528. package/dist/sdk/lifecycle/append.js +4 -2
  529. package/dist/sdk/lifecycle/claim.js +1 -1
  530. package/dist/sdk/lifecycle/close-many.js +1 -1
  531. package/dist/sdk/lifecycle/close.js +1 -1
  532. package/dist/sdk/lifecycle/copy.js +1 -1
  533. package/dist/sdk/lifecycle/create.js +1 -1
  534. package/dist/sdk/lifecycle/delete.js +1 -1
  535. package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
  536. package/dist/sdk/lifecycle/focus.js +1 -1
  537. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
  538. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
  539. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
  540. package/dist/sdk/lifecycle/mcp-actions.js +1 -1
  541. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
  542. package/dist/sdk/lifecycle/mutation-command-options.js +1 -1
  543. package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
  544. package/dist/sdk/lifecycle/plan.js +1 -1
  545. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
  546. package/dist/sdk/lifecycle/reopen.js +1 -1
  547. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -1
  548. package/dist/sdk/lifecycle/restore.js +1 -1
  549. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  550. package/dist/sdk/lifecycle/task-composition.js +1 -1
  551. package/dist/sdk/lifecycle/update-many.js +1 -1
  552. package/dist/sdk/lifecycle/update.js +2 -1
  553. package/dist/sdk/lifecycle-completion.js +1 -1
  554. package/dist/sdk/lifecycle-policy.js +1 -1
  555. package/dist/sdk/linked-artifacts.js +2 -1
  556. package/dist/sdk/mcp/apps.js +1 -1
  557. package/dist/sdk/mcp/authorization.js +1 -1
  558. package/dist/sdk/mcp/discovery.js +1 -1
  559. package/dist/sdk/mcp/interactions.js +1 -1
  560. package/dist/sdk/mcp/protocol.js +1 -1
  561. package/dist/sdk/mcp/skills.js +3 -1
  562. package/dist/sdk/mcp/subscriptions.js +1 -1
  563. package/dist/sdk/mcp/tasks.js +2 -2
  564. package/dist/sdk/mcp/transport.js +1 -1
  565. package/dist/sdk/merge/abandoned-receipts.js +1 -1
  566. package/dist/sdk/merge/driver.js +1 -1
  567. package/dist/sdk/merge/index.js +1 -1
  568. package/dist/sdk/merge/install.js +4 -2
  569. package/dist/sdk/merge/receipt-file-boundary.js +1 -1
  570. package/dist/sdk/merge/receipt-operation.js +1 -1
  571. package/dist/sdk/merge/receipt-schema.js +1 -1
  572. package/dist/sdk/merge/receipts.js +4 -4
  573. package/dist/sdk/merge/reconcile.js +1 -1
  574. package/dist/sdk/merge/three-way.js +3 -2
  575. package/dist/sdk/merge/worktree-config.js +1 -1
  576. package/dist/sdk/merge.js +1 -1
  577. package/dist/sdk/mutation-events.js +1 -1
  578. package/dist/sdk/mutation-guard.js +1 -1
  579. package/dist/sdk/notes.js +1 -1
  580. package/dist/sdk/output-contracts.js +1 -1
  581. package/dist/sdk/output-projection.js +1 -1
  582. package/dist/sdk/output-token-accounting.js +1 -1
  583. package/dist/sdk/output.js +2 -1
  584. package/dist/sdk/ownership-source.js +1 -1
  585. package/dist/sdk/package-import-adapters.js +1 -1
  586. package/dist/sdk/package-migrations.js +1 -1
  587. package/dist/sdk/package-runtime-options.js +1 -1
  588. package/dist/sdk/pagination.js +1 -1
  589. package/dist/sdk/profile.js +5 -1
  590. package/dist/sdk/provenance.js +1 -1
  591. package/dist/sdk/public-surface.json +1 -1
  592. package/dist/sdk/query/activity.js +1 -1
  593. package/dist/sdk/query/aggregate.js +1 -1
  594. package/dist/sdk/query/calendar.js +4 -1
  595. package/dist/sdk/query/complete-list.js +1 -1
  596. package/dist/sdk/query/context.js +2 -1
  597. package/dist/sdk/query/duplicate-candidates.js +1 -1
  598. package/dist/sdk/query/get.d.ts +14 -2
  599. package/dist/sdk/query/get.js +1 -1
  600. package/dist/sdk/query/history.js +1 -1
  601. package/dist/sdk/query/item-filter-options.js +1 -1
  602. package/dist/sdk/query/light-metadata.js +1 -1
  603. package/dist/sdk/query/list-filter-shared.js +1 -1
  604. package/dist/sdk/query/list.js +1 -1
  605. package/dist/sdk/query/multi-value-filters.js +1 -1
  606. package/dist/sdk/query/next-ready-budget.js +1 -1
  607. package/dist/sdk/query/next.js +2 -1
  608. package/dist/sdk/query/parsers.js +1 -1
  609. package/dist/sdk/query/projection-contracts.js +1 -1
  610. package/dist/sdk/query/search/corpus.js +2 -1
  611. package/dist/sdk/query/search/filters.js +1 -1
  612. package/dist/sdk/query/search/input.js +1 -1
  613. package/dist/sdk/query/search/lexical.js +1 -1
  614. package/dist/sdk/query/search/response.js +1 -1
  615. package/dist/sdk/query/search/semantic.js +3 -2
  616. package/dist/sdk/query/search/types.js +1 -1
  617. package/dist/sdk/query/search-contracts.js +1 -1
  618. package/dist/sdk/query/search-pagination.d.ts +1 -1
  619. package/dist/sdk/query/search-pagination.js +1 -1
  620. package/dist/sdk/query/search-rendering.js +1 -1
  621. package/dist/sdk/query/search.js +1 -1
  622. package/dist/sdk/query/workspace-contracts.js +1 -1
  623. package/dist/sdk/query.js +1 -1
  624. package/dist/sdk/read-output/continuation.js +1 -1
  625. package/dist/sdk/read-output/options.js +1 -1
  626. package/dist/sdk/read-output/provenance.js +1 -1
  627. package/dist/sdk/read-output-budget.js +1 -1
  628. package/dist/sdk/read-output-contracts.js +1 -1
  629. package/dist/sdk/read-output-rows.js +1 -1
  630. package/dist/sdk/read-output-session.js +1 -1
  631. package/dist/sdk/relationship-analytics.js +1 -1
  632. package/dist/sdk/relationship-context.js +1 -1
  633. package/dist/sdk/relationship-history.js +7 -4
  634. package/dist/sdk/relationship-kinds/contract.js +1 -1
  635. package/dist/sdk/relationship-migration.js +1 -1
  636. package/dist/sdk/relationships.js +1 -1
  637. package/dist/sdk/reproducibility/process.js +1 -1
  638. package/dist/sdk/runtime/actions.js +1 -1
  639. package/dist/sdk/runtime/context.js +1 -1
  640. package/dist/sdk/runtime/schema-preview.js +1 -1
  641. package/dist/sdk/runtime/schema.js +1 -1
  642. package/dist/sdk/runtime-action-aliases.js +1 -1
  643. package/dist/sdk/runtime-extended-actions.js +1 -1
  644. package/dist/sdk/runtime-input.js +1 -1
  645. package/dist/sdk/runtime-primitives.js +1 -1
  646. package/dist/sdk/runtime-public-contracts.js +1 -1
  647. package/dist/sdk/runtime-stats-options.js +1 -1
  648. package/dist/sdk/runtime.js +1 -1
  649. package/dist/sdk/scheduling-shortcuts.js +1 -1
  650. package/dist/sdk/schema-migration.js +4 -3
  651. package/dist/sdk/schema.js +7 -1
  652. package/dist/sdk/search-refresh-worker.js +1 -1
  653. package/dist/sdk/similarity-scoring.js +1 -1
  654. package/dist/sdk/similarity.js +1 -1
  655. package/dist/sdk/start-task-status.js +1 -1
  656. package/dist/sdk/stats.js +1 -1
  657. package/dist/sdk/structured-mutations.js +1 -1
  658. package/dist/sdk/telemetry-flush.js +1 -1
  659. package/dist/sdk/telemetry.js +4 -3
  660. package/dist/sdk/templates.js +26 -2
  661. package/dist/sdk/test/batch.js +2 -2
  662. package/dist/sdk/test/entry.js +1 -1
  663. package/dist/sdk/test/execution.js +6 -5
  664. package/dist/sdk/test/json-path.js +1 -1
  665. package/dist/sdk/test/linked-command-detection.js +1 -1
  666. package/dist/sdk/test/measurements.js +1 -1
  667. package/dist/sdk/test/parsers.js +1 -1
  668. package/dist/sdk/test/runs.js +1 -1
  669. package/dist/sdk/test/trust.js +2 -2
  670. package/dist/sdk/test/workspace-snapshot.js +1 -1
  671. package/dist/sdk/testing.js +7 -4
  672. package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
  673. package/dist/sdk/traceability/source-traceability.js +2 -1
  674. package/dist/sdk/tracker-root-discovery.js +1 -1
  675. package/dist/sdk/workspace-contracts-cache.js +1 -1
  676. package/dist/sdk/workspace-contracts.js +1 -1
  677. package/dist/sdk/workspace-memory.js +2 -2
  678. package/dist/sdk/workspace-recipe.js +1 -1
  679. package/dist/sdk/workspace-snapshot.js +5 -4
  680. package/dist/sdk/workspace-transaction-gc.js +1 -1
  681. package/dist/sdk/workspace-transaction.js +2 -2
  682. package/dist/sdk/workspace.js +3 -2
  683. package/dist/types/index.js +1 -1
  684. package/dist/types.js +1 -1
  685. package/docs/AGENT_EVIDENCE_CONSISTENCY.md +88 -0
  686. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +25 -0
  687. package/docs/GET_READ_EVIDENCE.md +68 -0
  688. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +23 -0
  689. package/docs/README.md +2 -0
  690. package/docs/SDK_AUDITED_MUTATIONS.md +35 -0
  691. package/docs/TESTING.md +8 -0
  692. package/docs/ecosystem-review-2026-09-28.json +2864 -3157
  693. package/marketplace.json +2 -2
  694. package/package.json +1 -1
  695. package/packages/pm-beads/package.json +1 -1
  696. package/packages/pm-calendar/package.json +1 -1
  697. package/packages/pm-command-kit/package.json +1 -1
  698. package/packages/pm-digital-twin/package.json +1 -1
  699. package/packages/pm-governance-audit/package.json +1 -1
  700. package/packages/pm-guide-shell/package.json +1 -1
  701. package/packages/pm-kanban/package.json +1 -1
  702. package/packages/pm-lifecycle-hooks/package.json +1 -1
  703. package/packages/pm-linked-test-adapters/package.json +1 -1
  704. package/packages/pm-search-advanced/package.json +1 -1
  705. package/packages/pm-templates/package.json +1 -1
  706. package/packages/pm-todos/package.json +1 -1
  707. package/packages/pm-vcs/extensions/vcs/index.ts +4 -2
  708. package/packages/pm-vcs/package.json +1 -1
  709. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  710. package/plugins/pm-claude/package.json +2 -2
  711. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  712. package/plugins/pm-codex/package.json +2 -2
  713. package/plugins/pm-codex/plugin.json +1 -1
  714. package/scripts/finalize-build.mjs +3 -2
  715. package/dist/cli-bundle/chunks/chunk-3AF2R3Y6.js +0 -6
  716. package/dist/cli-bundle/chunks/chunk-6ST3SCQ6.js +0 -2
  717. package/dist/cli-bundle/chunks/chunk-6Z4IV2MC.js +0 -8
  718. package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
  719. package/dist/cli-bundle/chunks/chunk-FW5LJXQY.js +0 -31
  720. package/dist/cli-bundle/chunks/chunk-H2DZW6I6.js +0 -3
  721. package/dist/cli-bundle/chunks/chunk-H7CXQBGQ.js +0 -2
  722. package/dist/cli-bundle/chunks/chunk-KP7NBQK3.js +0 -80
  723. package/dist/cli-bundle/chunks/chunk-MKXBCBAN.js +0 -20
  724. package/dist/cli-bundle/chunks/chunk-QPKQKSQU.js +0 -238
  725. package/dist/cli-bundle/chunks/chunk-SGFQQXFD.js +0 -2
  726. package/dist/cli-bundle/chunks/chunk-YCBGZF3T.js +0 -2
  727. package/dist/cli-bundle/chunks/chunk-YDWKGUQU.js +0 -3
  728. package/dist/cli-bundle/chunks/register-mutation-5PT3NW3A.js +0 -20
  729. package/dist/cli-bundle/chunks/register-operations-QDDQOAAV.js +0 -2
  730. package/dist/cli-bundle/chunks/register-setup-BBX67YMA.js +0 -2
  731. package/dist/cli-bundle/focused-chunks/chunk-4FFPGNCJ.js +0 -6
  732. package/dist/cli-bundle/focused-chunks/chunk-73DA7ISY.js +0 -75
  733. package/dist/cli-bundle/focused-chunks/chunk-E754JDLY.js +0 -2
  734. package/dist/cli-bundle/focused-chunks/chunk-FKK2HI3S.js +0 -2
  735. package/dist/cli-bundle/focused-chunks/chunk-GMYUNHST.js +0 -3
  736. package/dist/cli-bundle/focused-chunks/chunk-HIA2ZF64.js +0 -12
  737. package/dist/cli-bundle/focused-chunks/chunk-UTRSM3ZK.js +0 -8
  738. package/dist/cli-bundle/focused-chunks/chunk-VVWYI2X7.js +0 -2
  739. package/dist/cli-bundle/focused-chunks/chunk-WAJNX4RN.js +0 -20
  740. package/dist/cli-bundle/focused-chunks/chunk-WCY6HRZO.js +0 -30
  741. package/dist/cli-bundle/focused-chunks/chunk-YC32ZSLS.js +0 -165
  742. package/dist/cli-bundle/focused-chunks/chunk-ZIXFMIUL.js +0 -3
@@ -1,3 +1,3 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a69b18ac-4f93-5b12-ba74-764405961966")}catch(e2){}})();import*as fs from"node:fs/promises";import{constants}from"node:fs";import path from"node:path";import crypto from"node:crypto";const WINDOWS_RENAME_RETRY_DELAYS_MS=[10,25,50,100];async function ensureDir(dirPath){await fs.mkdir(dirPath,{recursive:true})}async function pathExists(targetPath){try{await fs.access(targetPath);return true}catch{return false}}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,rejectionMessage){const handle=await fs.open(targetPath,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{if(!(await handle.stat()).isFile())throw new TypeError(rejectionMessage);return await handle.readFile("utf8")}finally{await handle.close()}}async function writeFileAtomic(targetPath,contents){const dirPath=path.dirname(targetPath);await ensureDir(dirPath);const tempPath=path.join(dirPath,`.${path.basename(targetPath)}.${process.pid}.${Date.now()}.${crypto.randomBytes(4).toString("hex")}.tmp`);await fs.writeFile(tempPath,contents,"utf8");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){lastError=retryError;if(!isErrno(retryError,"EPERM")&&!isErrno(retryError,"EBUSY")){break}}}try{await fs.unlink(tempPath)}catch{}throw lastError}if(isErrno(error,"EXDEV")){try{await fs.copyFile(tempPath,targetPath)}finally{try{await fs.unlink(tempPath)}catch{}}return}try{await fs.unlink(tempPath)}catch{}throw 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,writeFileAtomic};
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]="937f3049-08a1-5d60-8005-05441dc1c0b6")}catch{}})();import*as fs from"node:fs/promises";import{constants}from"node:fs";import path from"node:path";import crypto from"node:crypto";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,rejectionMessage){const handle=await fs.open(targetPath,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{if(!(await handle.stat()).isFile())throw new TypeError(rejectionMessage);return await handle.readFile("utf8")}finally{await handle.close()}}async function writeFileAtomic(targetPath,contents){const dirPath=path.dirname(targetPath);await ensureDir(dirPath);const tempPath=path.join(dirPath,`.${path.basename(targetPath)}.${process.pid}.${Date.now()}.${crypto.randomBytes(4).toString("hex")}.tmp`);await fs.writeFile(tempPath,contents,"utf8");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}}try{await fs.unlink(tempPath)}catch{}throw lastError}if(isErrno(error,"EXDEV")){try{await fs.copyFile(tempPath,targetPath)}finally{try{await fs.unlink(tempPath)}catch{}}return}try{await fs.unlink(tempPath)}catch{}throw 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,writeFileAtomic};
3
3
  //# sourceMappingURL=fs-utils.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="aaf1c6ce-1bc9-5974-a38f-7daf8e4e63cc")}catch(e2){}})();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"}]]);const OPERATION_PATTERN=/^[a-z][a-z0-9_]{0,63}$/u;const 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)));const 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;if(typeof errorRecord.code==="string"&&HOST_ENVIRONMENT_FAULTS.has(errorRecord.code)){return errorRecord.code}if(typeof errorRecord.errno!=="number"||!Number.isInteger(errorRecord.errno)){return null}return 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
+ (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};
2
2
  //# sourceMappingURL=host-environment-errors.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c24aeefc-5ee2-5a06-9a16-941d89b10cd7")}catch(e2){}})();export*from"./fs-utils.js";
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";
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="83a29a06-1b0b-52e6-9617-2fc03861cb18")}catch(e2){}})();import path from"path";function isPathWithinDirectory(directory,targetPath){const relative=path.relative(directory,targetPath);if(relative.length===0){return true}return!relative.startsWith("..")&&!path.isAbsolute(relative)}export{isPathWithinDirectory};
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};
2
2
  //# sourceMappingURL=path-utils.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2e200f74-0e6c-58ac-ab8c-da49071465ff")}catch(e2){}})();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){if(!Array.isArray(tests)){return false}return tests.some(entry=>{if(typeof entry!=="object"||entry===null){return false}const command=entry.command;return typeof command==="string"&&command.trim().length>0})}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){return false}if(selection==="absent"&&present){return false}}return true}function filterByContentFields(items,filters){if(!hasContentFieldFilter(filters)){return[...items]}return items.filter(item=>itemMatchesContentFilters(item,filters))}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){if(total===0){return 100}return 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();const total=items.length;for(const item of items){for(const field of CONTENT_FIELD_ORDER){if(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;const emptyBodyCount=total-bodyPopulated.present;const 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
+ (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};
2
2
  //# sourceMappingURL=content-fields.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3b09b58f-2ec7-523e-87f3-8d828deb8480")}catch(e2){}})();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];const normalized=rawCode.toUpperCase();const rawPrefix=rawCode.slice(0,rawCode.lastIndexOf("-"));const configured=new Set((options.configuredPrefixes??[]).map(prefix=>prefix.trim().replace(/-+$/u,"").toUpperCase()));const remainder=trimmed.slice(rawCode.length);const evidence=options.evidenceText?.toUpperCase()??"";const hasExplicitBodyEvidence=evidence.includes(`ISSUE CODE: ${normalized}`)||evidence.includes(`ISSUE CODE \`${normalized}\``)||evidence.includes(`\`${normalized}\``)||evidence.includes(`[${normalized}]`);const structurallyQualified=rawPrefix===rawPrefix.toUpperCase()||/^\s*(?::|—|–|\])/u.test(remainder)||configured.has(rawPrefix.toUpperCase())||hasExplicitBodyEvidence;return structurallyQualified?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()));const prerequisites=new Map;const dependents=new Map;for(const entry of entries){const id=entry.id.toLowerCase();const 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 roots=[...prerequisites].filter(([,targets])=>targets.size===0).map(([id])=>id);const queue=[...roots];const 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]);if(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"){continue}if(isNonEmptyIdReference(item.duplicate_of)){continue}const code=extractIssueCode(item.title,{...options,evidenceText:item.body});if(code===null){continue}let entries=byCode.get(code);if(!entries){entries=[];byCode.set(code,entries)}if(!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
+ (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};
2
2
  //# sourceMappingURL=issue-codes.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="81a10252-4fa3-5c14-878d-7d78717419a4")}catch(e2){}})();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);if(registry.terminal_canceled_statuses.has(id)){return"canceled"}if(registry.terminal_statuses.has(id)){return"closed"}if(registry.blocked_statuses.has(id)){return"blocked"}if(registry.draft_statuses.has(id)){return"draft"}if(id===registry.open_status){return"open"}if(registry.active_statuses.has(id)){return"in_progress"}return"other"}}}function isAcMissing(item){return toNonEmptyStringOrUndefined(item.acceptance_criteria)===void 0}function isEstimateMissing(item){return!Number.isFinite(item.estimated_minutes)}function isResolutionMissing(item,classifier){if(!classifier.isTerminal(item.status)){return false}return toNonEmptyStringOrUndefined(item.resolution)===void 0}function isReviewerMissing(item){return toNonEmptyStringOrUndefined(item.reviewer)===void 0}function isRiskMissing(item){return toNonEmptyStringOrUndefined(item.risk)===void 0}function isConfidenceMissing(item){if(typeof item.confidence==="number"){return!Number.isFinite(item.confidence)}return 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 Boolean(filters.acMissing||filters.estimatesMissing||filters.resolutionMissing||filters.reviewerMissing||filters.riskMissing||filters.confidenceMissing||filters.sprintMissing||filters.releaseMissing||filters.metadataMissing)}function itemMatchesSpecificMetadataFilters(item,filters,classifier){const checks=[[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)]];return checks.every(([requested,matched])=>requested!==true||matched)}function itemMatchesCoreMetadataMissingUnion(item,classifier){return isAcMissing(item)||isEstimateMissing(item)||isResolutionMissing(item,classifier)}function itemMatchesMissingMetadata(item,filters,classifier){if(!hasMissingMetadataFilter(filters)){return true}if(!itemMatchesSpecificMetadataFilters(item,filters,classifier)){return false}if(filters.metadataMissing&&!itemMatchesCoreMetadataMissingUnion(item,classifier)){return false}return true}function filterMissingMetadata(items,filters,classifier){if(!hasMissingMetadataFilter(filters)){return[...items]}return items.filter(item=>itemMatchesMissingMetadata(item,filters,classifier))}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){if(field==="resolution"){return classifier.isTerminal(item.status)}return true}function roundPercent(present,applicable){if(applicable===0){return 100}return 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;if(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();const 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();const tags=Array.isArray(item.tags)?item.tags:[];const matching=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);if(!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)=>{if(right.total!==left.total){return right.total-left.total}if(left.key===null){return 1}if(right.key===null){return-1}return 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
+ (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};
2
2
  //# sourceMappingURL=metadata-coverage.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1e3cba21-c5a4-541a-9841-484cfbb70f4e")}catch(e2){}})();import{createHash}from"node:crypto";const HISTORY_HASH_ALGORITHMS=["sha256","sha512"];const LEGACY_HISTORY_HASH_ALGORITHM="sha256";const 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
+ (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};
2
2
  //# sourceMappingURL=digest.js.map
@@ -1,4 +1,4 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="979782f5-f4ee-5df5-a68a-0c51ab0548ae")}catch(e2){}})();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");const 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=false;let 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:true})}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));if(path.basename(historyDirectory)!=="history"){return}await invalidateHistoryDriftCache(path.dirname(historyDirectory))}export{invalidateHistoryDriftCache,invalidateHistoryDriftCacheForPath};
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};
4
4
  //# sourceMappingURL=drift-cache.js.map
@@ -32,6 +32,10 @@ export interface DriftScanOptions {
32
32
  /** Value that configures or reports cache hit verification for this contract. */
33
33
  cacheHitVerification?: DriftCacheHitVerification;
34
34
  }
35
+ /** Strictly verify one item using the shared stream verifier without reading or writing the corpus cache or inspecting workspace histories and documents. */
36
+ export declare function scanItemHistoryDrift(pmRoot: string, item: ItemMetadata & {
37
+ body: string;
38
+ }): Promise<DriftScanResult>;
35
39
  /**
36
40
  * Scan every item's history stream for drift (missing/unreadable streams, broken
37
41
  * hash chains, and item/history hash mismatches).
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d876d1ab-2de0-5c32-b999-721038adafcd")}catch(e2){}})();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,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]);const DRIFT_CACHE_VERSION=11;const 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");const parsed=JSON.parse(raw);if(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!==true||entry.chain_ok&&entry.version_skew!==true&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)&&!entry.latest_hash_comparable)){return null}return parsed}catch{return null}}async function scanWorkspaceHistory(pmRoot,previousEntries,nextEntries,verifyCacheHitByContent,accumulator){const historyPath=getWorkspaceHistoryPath(pmRoot);let stat;try{stat=await fs.stat(historyPath)}catch(error){if(isFileMissingError(error))return false;accumulator.unreadableStreams.push(WORKSPACE_HISTORY_ID);return false}const missingCount=accumulator.missingStreams.length;const resolved=await resolveStreamVerification({itemId:WORKSPACE_HISTORY_ID,historyPath,stat,cached:previousEntries[WORKSPACE_HISTORY_ID],verifyCacheHitByContent,accumulator});if(!resolved.verification){accumulator.missingStreams.splice(missingCount);return resolved.cacheDirty}if(resolved.verification.versionSkew){accumulator.versionSkews.push(WORKSPACE_HISTORY_ID)}if(!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};return resolved.cacheDirty}function hashContent(raw){return createHash("sha256").update(raw).digest("hex")}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)}async function verifyHistoryStream(historyPath){const raw=await fs.readFile(historyPath,"utf8");const contentHash=hashContent(raw);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);const versionSkew=entries.some(hasUnsupportedHistoryCapability);const latestEntry=entries[entries.length-1];const algorithmSupported=READABLE_HISTORY_HASH_ALGORITHMS.has(latestEntry.hash_algorithm);const latestExplicitVersion=latestEntry.item_hash_version;const latestExplicitVersionSupported=latestExplicitVersion!==void 0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(latestExplicitVersion);const 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{const loaded=await verifyHistoryStream(historyPath);if(!loaded){accumulator.missingStreams.push(itemId);return null}return loaded}catch{accumulator.unreadableStreams.push(itemId);return 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===true)&&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;const canUseCache=cacheMetadataMatches(params.cached,params.stat)&&cachedContentHash!==void 0;if(!canUseCache||!params.cached||!params.cached.chain_ok){return{verification:await loadFreshStreamVerification(params.itemId,params.historyPath,params.accumulator),cacheDirty:true}}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===true,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:false}}async function scanItemHistory(pmRoot,item,cache,accumulator){let historyPath;let stat;try{historyPath=getHistoryPath(pmRoot,item.id);stat=await fs.stat(historyPath)}catch(error){(isFileMissingError(error)?accumulator.missingStreams:accumulator.unreadableStreams).push(item.id);return false}const resolved=await resolveStreamVerification({itemId:item.id,historyPath,stat,cached:cache.previousEntries[item.id],verifyCacheHitByContent:cache.verifyCacheHitByContent,accumulator});if(!resolved.verification)return resolved.cacheDirty;if(resolved.verification.identityDiscontinuities.length>0){(accumulator.identityDiscontinuities??=[]).push(...resolved.verification.identityDiscontinuities.map(finding=>({...finding,item_id:item.id})))}if(resolved.verification.versionSkew){accumulator.versionSkews.push(item.id)}if(!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;if(!resolved.verification.latestHashComparable)return resolved.cacheDirty;const currentHashes=hashDocumentVerificationCandidates({metadata:itemMetadata,body},resolved.verification.itemHashVersion,resolved.verification.hashAlgorithm);if(!currentHashes.includes(resolved.verification.latestAfterHash))accumulator.hashMismatches.push(item.id);return 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))return;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 scanHistoryDrift(pmRoot,items,options={}){const accumulator={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]};const cache=await loadDriftCache(pmRoot);const previousEntries=cache?.entries??{};const nextEntries={};let cacheDirty=false;const verifyCacheHitByContent=options.cacheHitVerification!=="metadata";const cacheState={previousEntries,nextEntries,verifyCacheHitByContent};for(const item of items){if(await scanItemHistory(pmRoot,item,cacheState,accumulator))cacheDirty=true}const workspaceCacheDirty=await scanWorkspaceHistory(pmRoot,previousEntries,nextEntries,verifyCacheHitByContent,accumulator);cacheDirty||=workspaceCacheDirty;await scanWorkspaceStateAgreement(pmRoot,accumulator);if(cacheDirty||Object.keys(previousEntries).length!==Object.keys(nextEntries).length){const cachePath=getDriftCachePath(pmRoot);try{await fs.mkdir(path.dirname(cachePath),{recursive:true});await writeFileAtomic(cachePath,JSON.stringify({version:DRIFT_CACHE_VERSION,history_item_hash_version:CURRENT_HISTORY_ITEM_HASH_VERSION,entries:nextEntries}))}catch{}}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}}export{scanHistoryDrift};
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]="97537e2a-b8cb-559e-82bc-3c98b0c51db1")}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,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=11,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)}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};
2
2
  //# sourceMappingURL=drift-scan.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="9d5caf29-c1f2-5120-bc0b-c64a0bdd19ff")}catch(e2){}})();const HISTORY_EVENT_CLASSIFICATION_VERSION=1;const 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","update_audit","update_ownership_bypass"];const SUBSTANTIVE_HISTORY_OPERATIONS=["append","cancel","claim","close","comment_add","create","learning_add","note_add","reopen"];const MAINTENANCE_OPERATIONS=new Set(MAINTENANCE_HISTORY_OPERATIONS);const SUBSTANTIVE_OPERATIONS=new Set(SUBSTANTIVE_HISTORY_OPERATIONS);const 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);if(segments[0]==="metadata"||segments[0]==="front_matter"){return segments[1]}return segments[0]==="body"?"body":void 0}function classifyHistoryEvent(entry){if(entry.event_class==="substantive"||entry.event_class==="maintenance"){return entry.event_class}if(MAINTENANCE_OPERATIONS.has(entry.op))return"maintenance";if(SUBSTANTIVE_OPERATIONS.has(entry.op))return"substantive";if(entry.op!=="update")return"substantive";return 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
+ (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]="7d6d435b-b83a-53df-80c5-211437214161")}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","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};
2
2
  //# sourceMappingURL=event-classification.js.map
@@ -1,4 +1,5 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="542d77d0-7bb8-5ed0-a1da-09de33d3767f")}catch(e2){}})();import fs from"node:fs/promises";import path from"node:path";import{randomUUID}from"node:crypto";import{createRequire}from"node:module";import{isFileMissingError}from"../fs/fs-utils.js";import{acquireLock,captureProcessIdentity,isProcessIdentityAlive}from"../lock/lock.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{isMillisecondPrecisionRfc3339DateTime}from"../shared/time.js";import{readHistoryEntries}from"./read.js";import{classifyHistoryEvent}from"./event-classification.js";const EVENT_INDEX_FILENAME="history-event-index.sqlite";const EVENT_INDEX_VERSION="5";const AUTHORITATIVE_HISTORY_CACHE_LIMIT=8;const HISTORY_EVENT_INDEX_LOCK_ID="history-event-index";const HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS=300;const HISTORY_EVENT_INDEX_LOCK_WAIT_MS=3e4;const HISTORY_EVENT_INDEX_INVALIDATION_LOCK_ID="history-event-index-invalidation";const HISTORY_EVENT_INDEX_INVALIDATION_DIRECTORY="history-event-index-invalidations";const HISTORY_EVENT_INDEX_INVALIDATION_MAX_UNVERIFIED_AGE_MS=HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS*2*1e3;const HISTORY_INDEX_LOCK_CONTENDED=Symbol("history-index-lock-contended");const authoritativeHistoryCaches=new Map;function eventIndexPath(pmRoot){return path.join(pmRoot,"runtime",EVENT_INDEX_FILENAME)}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);const 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}}await fs.rm(path.join(historyEventIndexInvalidationDirectory(pmRoot),name),{force:true});return null}))).filter(name=>name!==null);return{pending,committed:invalidations.committed}}async function withHistoryEventIndexInvalidationLock(pmRoot,operation){const release=await acquireLock(pmRoot,HISTORY_EVENT_INDEX_INVALIDATION_LOCK_ID,HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS,`history-event-index-invalidation:${process.pid}`,false,false,HISTORY_EVENT_INDEX_LOCK_WAIT_MS);try{return await operation()}finally{await release()}}async function beginHistoryEventIndexInvalidation(pmRoot){const directory=historyEventIndexInvalidationDirectory(pmRoot);await fs.mkdir(directory,{recursive:true});const token=randomUUID();const processIdentity=await captureProcessIdentity();const pendingPath=path.join(directory,`${processIdentity.pid}-${processIdentity.process_start_identity??"unknown"}-${Date.now()}-${token}.pending`);await fs.writeFile(pendingPath,"pending\n",{flag:"wx"});return{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:true})}catch{}}async function withHistoryEventIndexLock(pmRoot,operation){const release=await acquireLock(pmRoot,HISTORY_EVENT_INDEX_LOCK_ID,HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS,`history-event-index:${process.pid}`,false,false,HISTORY_EVENT_INDEX_LOCK_WAIT_MS);try{return await operation()}finally{await release()}}async function readAuthoritativeHistorySnapshot(pmRoot){const historyRoot=path.join(pmRoot,"history");const entries=await fs.readdir(historyRoot,{withFileTypes:true}).catch(error=>{if(typeof error==="object"&&error!==null&&"code"in error&&error.code==="ENOENT"){return[]}throw error});const cached=authoritativeHistoryCaches.get(pmRoot)??{streams:new Map,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,-".jsonl".length);presentStreams.add(streamId);const historyPath=path.join(historyRoot,historyFile.name);const stats=await fs.stat(historyPath,{bigint:true});const signature=[stats.dev,stats.ino,stats.size,stats.mtimeNs,stats.ctimeNs].join(":");if(cached.streams.get(streamId)?.signature===signature)continue;const history=await readIndexableHistoryEntries(historyPath,streamId);cached.streams.set(streamId,{signature,byte_size:Number(stats.size),events:history.map((entry,streamOffset)=>({stream_id:streamId,stream_offset:streamOffset,entry}))});changed=true}for(const streamId of cached.streams.keys()){if(!presentStreams.has(streamId)){cached.streams.delete(streamId);changed=true}}if(changed){cached.ordered_events=[...cached.streams.values()].flatMap(stream=>stream.events).sort(compareHistoryEventPosition)}authoritativeHistoryCaches.delete(pmRoot);authoritativeHistoryCaches.set(pmRoot,cached);if(authoritativeHistoryCaches.size>AUTHORITATIVE_HISTORY_CACHE_LIMIT){const oldestRoot=authoritativeHistoryCaches.keys().next().value;authoritativeHistoryCaches.delete(oldestRoot)}return{events:cached.ordered_events,stream_byte_sizes:new Map([...cached.streams].map(([streamId,stream])=>[streamId,stream.byte_size]))}}async function readIndexableHistoryEntries(historyPath,streamId){const entries=await readHistoryEntries(historyPath,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()}))}async function readAuthoritativeHistoryEvents(pmRoot){return(await readAuthoritativeHistorySnapshot(pmRoot)).events}function loadDatabaseSync(loadModule){try{const loaded=loadModule(["node","sqlite"].join(":"));return loaded.DatabaseSync??null}catch{return null}}function loadStableDatabaseSync(nodeVersion,loadModule){const nodeMajor=Number.parseInt(nodeVersion,10);return Number.isFinite(nodeMajor)&&nodeMajor>=22?loadDatabaseSync(loadModule):null}let RuntimeDatabaseSync;function resolveDatabaseSync(){if(RuntimeDatabaseSync!==void 0)return RuntimeDatabaseSync;RuntimeDatabaseSync=loadStableDatabaseSync(process.versions.node,createRequire(import.meta.url));return RuntimeDatabaseSync}function createSchema(database){database.exec(`
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]="a70d2ff9-9664-5cad-9657-ab9c54422bc2")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{randomUUID}from"node:crypto";import{createRequire}from"node:module";import{isFileMissingError}from"../fs/fs-utils.js";import{acquireLock,captureProcessIdentity,isProcessIdentityAlive}from"../lock/lock.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{isMillisecondPrecisionRfc3339DateTime}from"../shared/time.js";import{readHistoryEntries}from"./read.js";import{classifyHistoryEvent}from"./event-classification.js";const EVENT_INDEX_FILENAME="history-event-index.sqlite",EVENT_INDEX_VERSION="5",AUTHORITATIVE_HISTORY_CACHE_LIMIT=8,HISTORY_EVENT_INDEX_LOCK_ID="history-event-index",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_LOCK_CONTENDED=Symbol("history-index-lock-contended"),authoritativeHistoryCaches=new Map;function eventIndexPath(pmRoot){return path.join(pmRoot,"runtime",EVENT_INDEX_FILENAME)}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){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,HISTORY_EVENT_INDEX_LOCK_WAIT_MS);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
2
+ `,{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 withHistoryEventIndexLock(pmRoot,operation){const release=await acquireLock(pmRoot,HISTORY_EVENT_INDEX_LOCK_ID,HISTORY_EVENT_INDEX_LOCK_TTL_SECONDS,`history-event-index:${process.pid}`,!1,!1,HISTORY_EVENT_INDEX_LOCK_WAIT_MS);try{return await operation()}finally{await release()}}async function readAuthoritativeHistorySnapshot(pmRoot){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}),cached=authoritativeHistoryCaches.get(pmRoot)??{streams:new Map,ordered_events:[]},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),stats=await fs.stat(historyPath,{bigint:!0}),signature=[stats.dev,stats.ino,stats.size,stats.mtimeNs,stats.ctimeNs].join(":");if(cached.streams.get(streamId)?.signature===signature)continue;const history=await readIndexableHistoryEntries(historyPath,streamId);cached.streams.set(streamId,{signature,byte_size:Number(stats.size),events:history.map((entry,streamOffset)=>({stream_id:streamId,stream_offset:streamOffset,entry}))}),changed=!0}for(const streamId of cached.streams.keys())presentStreams.has(streamId)||(cached.streams.delete(streamId),changed=!0);if(changed&&(cached.ordered_events=[...cached.streams.values()].flatMap(stream=>stream.events).sort(compareHistoryEventPosition)),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,stream_byte_sizes:new Map([...cached.streams].map(([streamId,stream])=>[streamId,stream.byte_size]))}}async function readIndexableHistoryEntries(historyPath,streamId){const entries=await readHistoryEntries(historyPath,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()}))}async function readAuthoritativeHistoryEvents(pmRoot){return(await readAuthoritativeHistorySnapshot(pmRoot)).events}function loadDatabaseSync(loadModule){try{return loadModule(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}function loadStableDatabaseSync(nodeVersion,loadModule){const nodeMajor=Number.parseInt(nodeVersion,10);return Number.isFinite(nodeMajor)&&nodeMajor>=22?loadDatabaseSync(loadModule):null}let RuntimeDatabaseSync;function resolveDatabaseSync(){return RuntimeDatabaseSync!==void 0||(RuntimeDatabaseSync=loadStableDatabaseSync(process.versions.node,createRequire(import.meta.url))),RuntimeDatabaseSync}function createSchema(database){database.exec(`
2
3
  PRAGMA journal_mode = OFF;
3
4
  PRAGMA synchronous = OFF;
4
5
  CREATE TABLE metadata (
@@ -33,15 +34,15 @@
33
34
  ON events(agent_harness, ts, stream_id, stream_offset);
34
35
  CREATE INDEX events_instance_order
35
36
  ON events(agent_instance, ts, stream_id, stream_offset);
36
- `);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(
37
+ `),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(
37
38
  stream_id, stream_offset, ts, author, agent_harness,
38
39
  agent_instance, op, event_class, entry_json
39
- ) 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));if(typeof entry.ts!=="string"||!isMillisecondPrecisionRfc3339DateTime(entry.ts.trim())){return null}return{stream_id:String(row.stream_id),stream_offset:Number(row.stream_offset),entry:{...entry,ts:new Date(entry.ts.trim()).toISOString()}}}function upsertStreamByteSize(database,streamId,byteSize){database.prepare(`INSERT INTO streams(stream_id, byte_size) VALUES (?, ?)
40
- ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size`).run(streamId,byteSize)}async function rebuildHistoryEventIndex(pmRoot){const Database=resolveDatabaseSync();if(!Database)return false;return withHistoryEventIndexLock(pmRoot,async()=>{let invalidations;try{invalidations=await withHistoryEventIndexInvalidationLock(pmRoot,()=>recoverAbandonedHistoryEventIndexInvalidations(pmRoot))}catch(error){if(error instanceof PmCliError&&error.code==="lock_conflict"){return false}throw error}if(invalidations.pending.length>0)return false;const targetPath=eventIndexPath(pmRoot);await fs.mkdir(path.dirname(targetPath),{recursive:true});const temporaryPath=`${targetPath}.${randomUUID()}.tmp`;let database;try{database=new Database(temporaryPath);createSchema(database);database.exec("BEGIN IMMEDIATE");const authoritative=await readAuthoritativeHistorySnapshot(pmRoot);for(const event of authoritative.events){insertEvent(database,event)}for(const[streamId,byteSize]of authoritative.stream_byte_sizes){upsertStreamByteSize(database,streamId,byteSize)}database.exec("COMMIT");database.close();database=void 0;const published=await withHistoryEventIndexInvalidationLock(pmRoot,async()=>{const current=await recoverAbandonedHistoryEventIndexInvalidations(pmRoot);if(current.pending.length>0||!sameInvalidationNames(invalidations.committed,current.committed)){return false}await fs.rm(targetPath,{force:true});await fs.rename(temporaryPath,targetPath);await Promise.all(invalidations.committed.map(name=>fs.rm(path.join(historyEventIndexInvalidationDirectory(pmRoot),name),{force:true})));return true});if(!published)await fs.rm(temporaryPath,{force:true});return published}catch(error){database?.close();await fs.rm(temporaryPath,{force:true});throw error}})}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 false}}else if(query.since_ts!==void 0&&event.entry.ts<canonicalHistoryQueryTimestamp(query.since_ts)){return false}return true}function matchesHistoryEventHarness(event,query){if(!query.harnesses||query.harnesses.length===0)return true;if(query.harnesses.includes(event.entry.agent_harness??""))return true;return event.entry.agent_harness===void 0&&(query.harness_alias_authors??[]).includes(event.entry.author)}function matchesHistoryEventQuery(event,query){if(!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)){return false}return(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));const rows=(await readAuthoritativeHistoryEvents(pmRoot)).filter(event=>matchesHistoryEventQuery(event,query)).slice(0,limit+1);return{events:rows.slice(0,query.limit),has_more:rows.length>query.limit}}async function appendHistoryEntryWithEventIndex(historyPath,entry,append){const pmRoot=path.dirname(path.dirname(historyPath));const Database=resolveDatabaseSync();if(!Database){await append();return}let authoritativeAppendCommitted=false;try{await withHistoryEventIndexLock(pmRoot,async()=>{const targetPath=eventIndexPath(pmRoot);try{await fs.access(targetPath)}catch{await append();return}let database;try{database=new Database(targetPath);const version=database.prepare("SELECT value FROM metadata WHERE key = 'version'").get();if(version?.value!==EVENT_INDEX_VERSION){throw new TypeError("Unsupported history event index version")}}catch{database?.close();await fs.rm(targetPath,{force:true});await append();return}try{database.exec("PRAGMA busy_timeout = 5000");database.exec("BEGIN IMMEDIATE")}catch(error){database.close();throw error}let appended=false;try{await append();appended=true;authoritativeAppendCommitted=true;const streamId=path.basename(historyPath,".jsonl");const 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});upsertStreamByteSize(database,streamId,(await fs.stat(historyPath)).size);database.exec("COMMIT");database.close()}catch(error){database?.close();if(!appended)throw error;await invalidateHistoryEventIndex(pmRoot)}})}catch(error){if(authoritativeAppendCommitted){await invalidateHistoryEventIndex(pmRoot);return}if(!(error instanceof PmCliError)||error.code!=="lock_conflict"){throw error}let pendingMarkerPath;try{await withHistoryEventIndexInvalidationLock(pmRoot,async()=>{const marker=await beginHistoryEventIndexInvalidation(pmRoot);pendingMarkerPath=marker.pendingPath;try{await append();authoritativeAppendCommitted=true}catch(appendError){await fs.rm(marker.pendingPath,{force:true});throw appendError}await fs.rename(marker.pendingPath,marker.committedPath);await invalidateHistoryEventIndex(pmRoot)})}catch(fallbackError){if(authoritativeAppendCommitted){await invalidateHistoryEventIndex(pmRoot);try{await fs.rm(pendingMarkerPath,{force:true})}catch{}return}throw fallbackError}}}async function removeHistoryEventIndexForHistoryPath(historyPath){await fs.rm(eventIndexPath(path.dirname(path.dirname(historyPath))),{force:true})}function appendSetPredicate(clauses,parameters,column,values){if(!values||values.length===0)return;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(", ");const 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 openSettledHistoryEventIndex(pmRoot,Database){const invalidations=await recoverAbandonedHistoryEventIndexInvalidations(pmRoot);if(invalidations.pending.length>0||invalidations.committed.length>0){return void 0}const database=new Database(eventIndexPath(pmRoot),{readOnly:true});try{const version=database.prepare("SELECT value FROM metadata WHERE key = 'version'").get();if(version?.value===EVENT_INDEX_VERSION)return database}catch(error){database.close();throw error}database.close();return void 0}async function queryHistoryEventIndex(pmRoot,query){const Database=resolveDatabaseSync();if(!Database)return null;const clauses=[];const 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 if(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 ")}`;let database;try{return await withHistoryEventIndexLock(pmRoot,async()=>{return withHistoryEventIndexInvalidationLock(pmRoot,async()=>{database=await openSettledHistoryEventIndex(pmRoot,Database);if(!database)return null;const validationStreamIds=await historyIndexValidationStreamIds(database,pmRoot,query.stream_ids);if(!await historyIndexMatchesStreamSizes(database,pmRoot,validationStreamIds)){database.close();database=void 0;return null}const rows=database.prepare(`SELECT stream_id, stream_offset, entry_json
40
+ ) 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 upsertStreamByteSize(database,streamId,byteSize){database.prepare(`INSERT INTO streams(stream_id, byte_size) VALUES (?, ?)
41
+ ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size`).run(streamId,byteSize)}async function rebuildHistoryEventIndex(pmRoot){const Database=resolveDatabaseSync();return Database?withHistoryEventIndexLock(pmRoot,async()=>{let invalidations;try{invalidations=await withHistoryEventIndexInvalidationLock(pmRoot,()=>recoverAbandonedHistoryEventIndexInvalidations(pmRoot))}catch(error){if(error instanceof PmCliError&&error.code==="lock_conflict")return!1;throw error}if(invalidations.pending.length>0)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);for(const event of authoritative.events)insertEvent(database,event);for(const[streamId,byteSize]of authoritative.stream_byte_sizes)upsertStreamByteSize(database,streamId,byteSize);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)?!1:(await fs.rm(targetPath,{force:!0}),await fs.rename(temporaryPath,targetPath),await Promise.all(invalidations.committed.map(name=>fs.rm(path.join(historyEventIndexInvalidationDirectory(pmRoot),name),{force:!0}))),!0)});return published||await fs.rm(temporaryPath,{force:!0}),published}catch(error){throw database?.close(),await fs.rm(temporaryPath,{force:!0}),error}}):!1}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)),rows=(await readAuthoritativeHistoryEvents(pmRoot)).filter(event=>matchesHistoryEventQuery(event,query)).slice(0,limit+1);return{events:rows.slice(0,query.limit),has_more:rows.length>query.limit}}async function appendHistoryEntryWithEventIndex(historyPath,entry,append){const pmRoot=path.dirname(path.dirname(historyPath)),Database=resolveDatabaseSync();if(!Database){await append();return}let authoritativeAppendCommitted=!1;try{await withHistoryEventIndexLock(pmRoot,async()=>{const targetPath=eventIndexPath(pmRoot);try{await fs.access(targetPath)}catch{await append();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")}catch{database?.close(),await fs.rm(targetPath,{force:!0}),await append();return}try{database.exec("PRAGMA busy_timeout = 5000"),database.exec("BEGIN IMMEDIATE")}catch(error){throw database.close(),error}let appended=!1;try{await append(),appended=!0,authoritativeAppendCommitted=!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}),upsertStreamByteSize(database,streamId,(await fs.stat(historyPath)).size),database.exec("COMMIT"),database.close()}catch(error){if(database?.close(),!appended)throw error;await invalidateHistoryEventIndex(pmRoot)}})}catch(error){if(authoritativeAppendCommitted){await invalidateHistoryEventIndex(pmRoot);return}if(!(error instanceof PmCliError)||error.code!=="lock_conflict")throw error;let pendingMarkerPath;try{await withHistoryEventIndexInvalidationLock(pmRoot,async()=>{const 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,marker.committedPath),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 openSettledHistoryEventIndex(pmRoot,Database){const invalidations=await recoverAbandonedHistoryEventIndexInvalidations(pmRoot);if(invalidations.pending.length>0||invalidations.committed.length>0)return;const database=new Database(eventIndexPath(pmRoot),{readOnly:!0});try{if(database.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value===EVENT_INDEX_VERSION)return database}catch(error){throw database.close(),error}database.close()}async function queryHistoryEventIndex(pmRoot,query){const Database=resolveDatabaseSync();if(!Database)return null;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 ")}`;let database;try{return await withHistoryEventIndexLock(pmRoot,async()=>withHistoryEventIndexInvalidationLock(pmRoot,async()=>{if(database=await openSettledHistoryEventIndex(pmRoot,Database),!database)return null;const validationStreamIds=await historyIndexValidationStreamIds(database,pmRoot,query.stream_ids);if(!await historyIndexMatchesStreamSizes(database,pmRoot,validationStreamIds))return database.close(),database=void 0,null;const rows=database.prepare(`SELECT stream_id, stream_offset, entry_json
41
42
  FROM events${where}
42
43
  ORDER BY ts, stream_id, stream_offset
43
- LIMIT ?`).all(...parameters,Math.max(0,Math.floor(query.limit))+1);const events=rows.slice(0,query.limit).map(parseIndexedHistoryEvent);database.close();database=void 0;return events.includes(null)?null:{events,has_more:rows.length>query.limit}})})}catch{database?.close();return null}}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];if(current===void 0||compareHistoryEventPosition(current,event)<0){latest[event.stream_id]=event}}return latest}async function readHistoryStreamByteSize(pmRoot,streamId){if(path.basename(streamId)!==streamId)return null;try{return(await fs.stat(path.join(pmRoot,"history",`${streamId}.jsonl`))).size}catch(error){if(isFileMissingError(error))return 0;throw error}}async function historyIndexMatchesStreamSizes(database,pmRoot,streamIds){for(let start=0;start<streamIds.length;start+=500){const chunk=streamIds.slice(start,start+500);const storedSizes=new Map(database.prepare(`SELECT stream_id, byte_size FROM streams
44
- WHERE stream_id IN (${chunk.map(()=>"?").join(", ")})`).all(...chunk).map(row=>[String(row.stream_id),Number(row.byte_size)]));const currentSizes=await Promise.all(chunk.map(streamId=>readHistoryStreamByteSize(pmRoot,streamId)));for(const[index,currentSize]of currentSizes.entries()){if(currentSize===null)return false;const streamId=chunk[index];const storedSize=storedSizes.get(streamId);if(currentSize===0&&storedSize===void 0)continue;if(currentSize!==storedSize)return false}}return true}async function historyIndexValidationStreamIds(database,pmRoot,requestedStreamIds){if(requestedStreamIds&&requestedStreamIds.length>0){return[...new Set(requestedStreamIds.filter(streamId=>streamId.trim().length>0))]}const indexed=database.prepare("SELECT stream_id FROM streams").all().map(row=>String(row.stream_id));const authoritative=await fs.readdir(path.join(pmRoot,"history"),{withFileTypes:true}).then(entries=>entries.filter(entry=>entry.isFile()&&entry.name.endsWith(".jsonl")).map(entry=>entry.name.slice(0,-".jsonl".length))).catch(error=>{if(isFileMissingError(error))return[];throw error});return[...new Set([...indexed,...authoritative])]}async function readIndexedLatestSubstantiveEvents(Database,pmRoot,streamIds,requested){if(!Database)return null;let database;try{return await withHistoryEventIndexLock(pmRoot,async()=>{return withHistoryEventIndexInvalidationLock(pmRoot,async()=>{database=await openSettledHistoryEventIndex(pmRoot,Database);if(!database)return null;if(!await historyIndexMatchesStreamSizes(database,pmRoot,streamIds)){database.close();database=void 0;return null}const indexed=[];for(let start=0;start<streamIds.length;start+=500){const chunk=streamIds.slice(start,start+500);const rows=database.prepare(`SELECT stream_id, stream_offset, entry_json
44
+ LIMIT ?`).all(...parameters,Math.max(0,Math.floor(query.limit))+1),events=rows.slice(0,query.limit).map(parseIndexedHistoryEvent);return database.close(),database=void 0,events.includes(null)?null:{events,has_more:rows.length>query.limit}}))}catch{return database?.close(),null}}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 readHistoryStreamByteSize(pmRoot,streamId){if(path.basename(streamId)!==streamId)return null;try{return(await fs.stat(path.join(pmRoot,"history",`${streamId}.jsonl`))).size}catch(error){if(isFileMissingError(error))return 0;throw error}}async function historyIndexMatchesStreamSizes(database,pmRoot,streamIds){for(let start=0;start<streamIds.length;start+=500){const chunk=streamIds.slice(start,start+500),storedSizes=new Map(database.prepare(`SELECT stream_id, byte_size FROM streams
45
+ WHERE stream_id IN (${chunk.map(()=>"?").join(", ")})`).all(...chunk).map(row=>[String(row.stream_id),Number(row.byte_size)])),currentSizes=await Promise.all(chunk.map(streamId=>readHistoryStreamByteSize(pmRoot,streamId)));for(const[index,currentSize]of currentSizes.entries()){if(currentSize===null)return!1;const streamId=chunk[index],storedSize=storedSizes.get(streamId);if(!(currentSize===0&&storedSize===void 0)&&currentSize!==storedSize)return!1}}return!0}async function historyIndexValidationStreamIds(database,pmRoot,requestedStreamIds){if(requestedStreamIds&&requestedStreamIds.length>0)return[...new Set(requestedStreamIds.filter(streamId=>streamId.trim().length>0))];const indexed=database.prepare("SELECT stream_id FROM streams").all().map(row=>String(row.stream_id)),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){if(!Database)return null;let database;try{return await withHistoryEventIndexLock(pmRoot,async()=>withHistoryEventIndexInvalidationLock(pmRoot,async()=>{if(database=await openSettledHistoryEventIndex(pmRoot,Database),!database)return null;if(!await historyIndexMatchesStreamSizes(database,pmRoot,streamIds))return database.close(),database=void 0,null;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
45
46
  FROM (
46
47
  SELECT stream_id, stream_offset, entry_json,
47
48
  ROW_NUMBER() OVER (
@@ -52,5 +53,5 @@
52
53
  WHERE event_class = 'substantive'
53
54
  AND stream_id IN (${chunk.map(()=>"?").join(", ")})
54
55
  )
55
- WHERE recency_rank = 1`).all(...chunk);const parsed=rows.map(parseIndexedHistoryEvent);if(parsed.includes(null)){database.close();database=void 0;return null}indexed.push(...parsed)}database.close();database=void 0;return collectLatestSubstantiveEvents(indexed,requested)})})}catch(error){database?.close();if(error instanceof PmCliError&&error.code==="lock_conflict"){return HISTORY_INDEX_LOCK_CONTENDED}return 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);const Database=resolveDatabaseSync();const indexed=await readIndexedLatestSubstantiveEvents(Database,pmRoot,uniqueIds,requested);if(indexed!==null&&indexed!==HISTORY_INDEX_LOCK_CONTENDED){return indexed}if(Database&&indexed!==HISTORY_INDEX_LOCK_CONTENDED){try{if(await rebuildHistoryEventIndex(pmRoot)){const rebuilt=await readIndexedLatestSubstantiveEvents(Database,pmRoot,uniqueIds,requested);if(rebuilt!==null&&rebuilt!==HISTORY_INDEX_LOCK_CONTENDED){return rebuilt}}}catch{}}const authoritative=[];await Promise.all(uniqueIds.map(async streamId=>{const historyPath=path.join(pmRoot,"history",`${streamId}.jsonl`);const entries=await readIndexableHistoryEntries(historyPath,streamId).catch(error=>{if(error instanceof PmCliError&&error.code==="history_timestamp_invalid"){return[]}throw error});entries.forEach((entry,streamOffset)=>{authoritative.push({stream_id:streamId,stream_offset:streamOffset,entry})})}));return collectLatestSubstantiveEvents(authoritative,requested)}const _testOnly={collectLatestSubstantiveEvents,loadDatabaseSync,loadStableDatabaseSync,setDatabaseSync(databaseSync){const previous=RuntimeDatabaseSync;RuntimeDatabaseSync=databaseSync;return()=>{RuntimeDatabaseSync=previous}}};export{_testOnly,appendHistoryEntryWithEventIndex,queryHistoryEventIndex,queryHistoryEventStreams,readLatestSubstantiveHistoryEvents,rebuildHistoryEventIndex,removeHistoryEventIndexForHistoryPath};
56
+ WHERE recency_rank = 1`).all(...chunk).map(parseIndexedHistoryEvent);if(parsed.includes(null))return database.close(),database=void 0,null;indexed.push(...parsed)}return database.close(),database=void 0,collectLatestSubstantiveEvents(indexed,requested)}))}catch(error){return database?.close(),error instanceof PmCliError&&error.code==="lock_conflict"?HISTORY_INDEX_LOCK_CONTENDED: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_LOCK_CONTENDED)return indexed;if(Database&&indexed!==HISTORY_INDEX_LOCK_CONTENDED)try{if(await rebuildHistoryEventIndex(pmRoot)){const rebuilt=await readIndexedLatestSubstantiveEvents(Database,pmRoot,uniqueIds,requested);if(rebuilt!==null&&rebuilt!==HISTORY_INDEX_LOCK_CONTENDED)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,readLatestSubstantiveHistoryEvents,rebuildHistoryEventIndex,removeHistoryEventIndexForHistoryPath};
56
57
  //# sourceMappingURL=event-index.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d51da34a-9f37-5441-91f0-15a16b601709")}catch(e2){}})();function selectIdsMode(ids,byId,minEntries){const seen=new Set;const 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:false,skip_reason:"no_stream"});continue}if(candidate.entries<=minEntries){rows.push({id,entries:candidate.entries,selected:false,skip_reason:"already_compact"});continue}rows.push({id,entries:candidate.entries,selected:true,skip_reason:null})}return rows}function selectScanMode(candidates,criteria){const ordered=[...candidates].sort((a,b)=>b.entries-a.entries||a.id.localeCompare(b.id));const rows=[];for(const candidate of ordered){if(criteria.scope==="closed"&&candidate.bucket!=="closed"){rows.push({id:candidate.id,entries:candidate.entries,selected:false,skip_reason:"scope_mismatch"});continue}if(candidate.entries<=criteria.minEntries){rows.push({id:candidate.id,entries:candidate.entries,selected:false,skip_reason:"already_compact"});continue}if(criteria.allOver!==void 0&&candidate.entries<=criteria.allOver){rows.push({id:candidate.id,entries:candidate.entries,selected:false,skip_reason:"below_threshold"});continue}rows.push({id:candidate.id,entries:candidate.entries,selected:true,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(){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};
2
2
  //# sourceMappingURL=history-compact-bulk.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="44d1db57-ab29-540d-b337-443d382d0d9b")}catch(e2){}})();import{cloneEmptyReplayDocument,tryApplyReplayPatch}from"./replay.js";function decodeJsonPointerSegment(segment){return segment.replaceAll("~1","/").replaceAll("~0","~")}function patchPathToChangedField(path){if(path==="/body"||path.startsWith("/body/"))return"body";if(path==="/metadata"||path.startsWith("/metadata/")||path==="/front_matter"||path.startsWith("/front_matter/")){const segment2=path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];if(!segment2)return"metadata";return decodeJsonPointerSegment(segment2)}const segment=path.replace(/^\//,"").split("/")[0];return segment?decodeJsonPointerSegment(segment):"root"}function readFieldValue(doc,field){if(field==="body")return doc.body;if(field==="metadata")return doc.metadata;if(field==="root")return doc;return doc.metadata[field]}function computeHistoryDiff(fullEntries,options){const windowStartIndex=options?.windowStartIndex??0;const fieldFilter=options?.field;if(fullEntries.length===0||windowStartIndex>=fullEntries.length){return[]}let current=cloneEmptyReplayDocument();const result=[];for(let p=0;p<fullEntries.length;p+=1){const entry=fullEntries[p];const beforeDoc=current;const applied=tryApplyReplayPatch(current,entry.patch);let afterDoc;if(applied.ok){afterDoc=applied.document;current=afterDoc}else{afterDoc=beforeDoc}const changedFieldSet=new Set;for(const patchOp of entry.patch){changedFieldSet.add(patchPathToChangedField(patchOp.path));if(patchOp.from!==void 0){changedFieldSet.add(patchPathToChangedField(patchOp.from))}}const sortedFields=[...changedFieldSet].sort((a,b)=>a.localeCompare(b));if(p>=windowStartIndex){if(fieldFilter!==void 0){if(!changedFieldSet.has(fieldFilter)){continue}const change={field:fieldFilter,before:readFieldValue(beforeDoc,fieldFilter),after:readFieldValue(afterDoc,fieldFilter)};result.push({index:p+1,ts:entry.ts,op:entry.op,author:entry.author,patch_ops:entry.patch.length,changed_fields:[fieldFilter],changes:[change]})}else{const changes=sortedFields.map(field=>({field,before:readFieldValue(beforeDoc,field),after:readFieldValue(afterDoc,field)}));result.push({index:p+1,ts:entry.ts,op:entry.op,author:entry.author,patch_ops:entry.patch.length,changed_fields:sortedFields,changes})}}}return result}export{computeHistoryDiff,patchPathToChangedField};
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]="1dcf0d72-10da-51b6-b9f6-ab47bebcbf64")}catch{}})();import{cloneEmptyReplayDocument,tryApplyReplayPatch}from"./replay.js";function decodeJsonPointerSegment(segment){return segment.replaceAll("~1","/").replaceAll("~0","~")}function patchPathToChangedField(path){if(path==="/body"||path.startsWith("/body/"))return"body";if(path==="/metadata"||path.startsWith("/metadata/")||path==="/front_matter"||path.startsWith("/front_matter/")){const segment2=path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];return segment2?decodeJsonPointerSegment(segment2):"metadata"}const segment=path.replace(/^\//,"").split("/")[0];return segment?decodeJsonPointerSegment(segment):"root"}function readFieldValue(doc,field){return field==="body"?doc.body:field==="metadata"?doc.metadata:field==="root"?doc:doc.metadata[field]}function computeHistoryDiff(fullEntries,options){const windowStartIndex=options?.windowStartIndex??0,fieldFilter=options?.field;if(fullEntries.length===0||windowStartIndex>=fullEntries.length)return[];let current=cloneEmptyReplayDocument();const result=[];for(let p=0;p<fullEntries.length;p+=1){const entry=fullEntries[p],beforeDoc=current,applied=tryApplyReplayPatch(current,entry.patch);let afterDoc;applied.ok?(afterDoc=applied.document,current=afterDoc):afterDoc=beforeDoc;const changedFieldSet=new Set;for(const patchOp of entry.patch)changedFieldSet.add(patchPathToChangedField(patchOp.path)),patchOp.from!==void 0&&changedFieldSet.add(patchPathToChangedField(patchOp.from));const sortedFields=[...changedFieldSet].sort((a,b)=>a.localeCompare(b));if(p>=windowStartIndex)if(fieldFilter!==void 0){if(!changedFieldSet.has(fieldFilter))continue;const change={field:fieldFilter,before:readFieldValue(beforeDoc,fieldFilter),after:readFieldValue(afterDoc,fieldFilter)};result.push({index:p+1,ts:entry.ts,op:entry.op,author:entry.author,patch_ops:entry.patch.length,changed_fields:[fieldFilter],changes:[change]})}else{const changes=sortedFields.map(field=>({field,before:readFieldValue(beforeDoc,field),after:readFieldValue(afterDoc,field)}));result.push({index:p+1,ts:entry.ts,op:entry.op,author:entry.author,patch_ops:entry.patch.length,changed_fields:sortedFields,changes})}}return result}export{computeHistoryDiff,patchPathToChangedField};
2
2
  //# sourceMappingURL=history-diff.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="cd8981b8-f6f7-5911-9951-799e68cecb9b")}catch(e2){}})();import fs from"node:fs/promises";import{readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{acquireLock}from"../lock/lock.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{locateItem,readLocatedItem}from"../store/item-store.js";import{resolveGovernanceKnobs}from"../store/settings.js";import{invalidateHistoryDriftCacheForPath}from"./drift-cache.js";function checkHistoryRewriteOwnership(params){if(!params.itemDocument)return[];const assigned=params.itemDocument.metadata?.assignee?.trim();if(!assigned||assigned===params.author||params.force)return[];const governance=resolveGovernanceKnobs(params.settings);if(governance.ownership_enforcement==="strict"){throw new PmCliError(`Item ${params.subjectId} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT)}if(governance.ownership_enforcement==="warn"){return[`ownership_warning:assignee_conflict:${params.subjectId}:${assigned}`]}return[]}async function verifyHistoryRewriteNoDrift(params){const historyRawUnderLock=await readFileIfExists(params.subject.historyPath);if(historyRawUnderLock!==params.historyRawBeforeLock){throw new PmCliError(`History for ${params.subject.id} changed while waiting for lock; retry ${params.operation}.`,EXIT_CODE.CONFLICT)}const locatedUnderLock=await locateItem(params.pmRoot,params.subject.id,params.settings.id_prefix,params.settings.item_format,params.typeRegistry.type_to_folder);const loadedItemUnderLock=locatedUnderLock?params.readItem?await params.readItem(locatedUnderLock):await readLocatedItem(locatedUnderLock,{schema:params.settings.schema}):null;if((loadedItemUnderLock?.raw??null)!==(params.currentItemRawBeforeLock??null)){throw new PmCliError(`Item ${params.subject.id} changed while waiting for lock; retry ${params.operation}.`,EXIT_CODE.CONFLICT)}return{historyRawUnderLock,locatedUnderLock,loadedItemUnderLock}}async function writeHistoryRawWithRollback(params){const writeHistoryRaw=params.writeHistoryRaw??writeFileAtomic;try{await writeHistoryRaw(params.historyPath,params.nextHistoryRaw);await invalidateHistoryDriftCacheForPath(params.historyPath)}catch(error){try{if(params.historyRawUnderLock===null){await fs.rm(params.historyPath,{force:true})}else{await writeHistoryRaw(params.historyPath,params.historyRawUnderLock)}await invalidateHistoryDriftCacheForPath(params.historyPath)}catch(rollbackError){throw new AggregateError([error,rollbackError],`History rewrite failed and rollback also failed: ${String(error)}`)}throw error}}async function executeHistoryRewrite(params){const warnings=[...checkHistoryRewriteOwnership({itemDocument:params.itemDocument,subjectId:params.subject.id,author:params.author,force:params.force,settings:params.settings})];const releaseLock=await acquireLock(params.pmRoot,params.subject.id,params.settings.locks.ttl_seconds,params.author,Boolean(params.force),params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms);try{const verified=await verifyHistoryRewriteNoDrift({pmRoot:params.pmRoot,subject:params.subject,settings:params.settings,typeRegistry:params.typeRegistry,historyRawBeforeLock:params.historyRawBeforeLock,currentItemRawBeforeLock:params.currentItemRawBeforeLock,operation:params.operation});await params.applyRewrite(verified);if(params.applyPostRewrite){warnings.push(...await params.applyPostRewrite(verified))}return warnings}finally{await releaseLock()}}export{checkHistoryRewriteOwnership,executeHistoryRewrite,verifyHistoryRewriteNoDrift,writeHistoryRawWithRollback};
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]="eeaf2318-5964-5d98-ad90-9faa7fc69975")}catch{}})();import fs from"node:fs/promises";import{readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{acquireLock}from"../lock/lock.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{locateItem,readLocatedItem}from"../store/item-store.js";import{resolveGovernanceKnobs}from"../store/settings.js";import{invalidateHistoryDriftCacheForPath}from"./drift-cache.js";function checkHistoryRewriteOwnership(params){if(!params.itemDocument)return[];const assigned=params.itemDocument.metadata?.assignee?.trim();if(!assigned||assigned===params.author||params.force)return[];const governance=resolveGovernanceKnobs(params.settings);if(governance.ownership_enforcement==="strict")throw new PmCliError(`Item ${params.subjectId} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);return governance.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${params.subjectId}:${assigned}`]:[]}async function verifyHistoryRewriteNoDrift(params){const historyRawUnderLock=await readFileIfExists(params.subject.historyPath);if(historyRawUnderLock!==params.historyRawBeforeLock)throw new PmCliError(`History for ${params.subject.id} changed while waiting for lock; retry ${params.operation}.`,EXIT_CODE.CONFLICT);const locatedUnderLock=await locateItem(params.pmRoot,params.subject.id,params.settings.id_prefix,params.settings.item_format,params.typeRegistry.type_to_folder),loadedItemUnderLock=locatedUnderLock?params.readItem?await params.readItem(locatedUnderLock):await readLocatedItem(locatedUnderLock,{schema:params.settings.schema}):null;if((loadedItemUnderLock?.raw??null)!==(params.currentItemRawBeforeLock??null))throw new PmCliError(`Item ${params.subject.id} changed while waiting for lock; retry ${params.operation}.`,EXIT_CODE.CONFLICT);return{historyRawUnderLock,locatedUnderLock,loadedItemUnderLock}}async function writeHistoryRawWithRollback(params){const writeHistoryRaw=params.writeHistoryRaw??writeFileAtomic;try{await writeHistoryRaw(params.historyPath,params.nextHistoryRaw),await invalidateHistoryDriftCacheForPath(params.historyPath)}catch(error){try{params.historyRawUnderLock===null?await fs.rm(params.historyPath,{force:!0}):await writeHistoryRaw(params.historyPath,params.historyRawUnderLock),await invalidateHistoryDriftCacheForPath(params.historyPath)}catch(rollbackError){throw new AggregateError([error,rollbackError],`History rewrite failed and rollback also failed: ${String(error)}`)}throw error}}async function executeHistoryRewrite(params){const warnings=[...checkHistoryRewriteOwnership({itemDocument:params.itemDocument,subjectId:params.subject.id,author:params.author,force:params.force,settings:params.settings})],releaseLock=await acquireLock(params.pmRoot,params.subject.id,params.settings.locks.ttl_seconds,params.author,!!params.force,params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms);try{const verified=await verifyHistoryRewriteNoDrift({pmRoot:params.pmRoot,subject:params.subject,settings:params.settings,typeRegistry:params.typeRegistry,historyRawBeforeLock:params.historyRawBeforeLock,currentItemRawBeforeLock:params.currentItemRawBeforeLock,operation:params.operation});return await params.applyRewrite(verified),params.applyPostRewrite&&warnings.push(...await params.applyPostRewrite(verified)),warnings}finally{await releaseLock()}}export{checkHistoryRewriteOwnership,executeHistoryRewrite,verifyHistoryRewriteNoDrift,writeHistoryRawWithRollback};
2
2
  //# sourceMappingURL=history-rewrite.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="60090339-2f94-5f22-be47-518498838b92")}catch(e2){}})();function shouldReplaceExtreme(candidate,current,candidateTieBreaker,currentTieBreaker,direction,tieDirection="min"){const comparison=direction==="min"?candidate-current:current-candidate;const tieComparison=tieDirection==="min"?candidateTieBreaker.localeCompare(currentTieBreaker??candidateTieBreaker):(currentTieBreaker??candidateTieBreaker).localeCompare(candidateTieBreaker);return comparison<0||comparison===0&&currentTieBreaker!==null&&tieComparison<0}function parseStreamStat(id,raw){const bytes=Buffer.byteLength(raw,"utf8");let lines=0;let oldestTs=null;let newestTs=null;let oldestMs=Number.POSITIVE_INFINITY;let newestMs=Number.NEGATIVE_INFINITY;for(const rawLine of raw.split(/\r?\n/)){const trimmed=rawLine.trim();if(trimmed===""){continue}lines+=1;let parsed;try{parsed=JSON.parse(trimmed)}catch{continue}if(parsed===null||typeof parsed!=="object"||!("ts"in parsed)||typeof parsed["ts"]!=="string"){continue}const ts=parsed["ts"];const ms=Date.parse(ts);if(Number.isNaN(ms)){continue}if(shouldReplaceExtreme(ms,oldestMs,ts,oldestTs,"min")){oldestMs=ms;oldestTs=ts}if(shouldReplaceExtreme(ms,newestMs,ts,newestTs,"max","max")){newestMs=ms;newestTs=ts}}return{id,bytes,lines,oldest_ts:oldestTs,newest_ts:newestTs}}function computeHistoryStorageStats(streams,options){const rawTopN=options?.topN??5;const topN=Math.max(0,Math.floor(rawTopN));const stats=streams.map(({id,raw})=>parseStreamStat(id,raw));let totalLines=0;let totalBytes=0;let oldestEntry=null;let newestEntry=null;let globalOldestMs=Number.POSITIVE_INFINITY;let globalNewestMs=Number.NEGATIVE_INFINITY;for(const stat of stats){totalLines+=stat.lines;totalBytes+=stat.bytes;if(stat.oldest_ts!==null){const ms=Date.parse(stat.oldest_ts);if(shouldReplaceExtreme(ms,globalOldestMs,stat.id,oldestEntry?.id??null,"min")){globalOldestMs=ms;oldestEntry={id:stat.id,ts:stat.oldest_ts}}}if(stat.newest_ts!==null){const ms=Date.parse(stat.newest_ts);if(shouldReplaceExtreme(ms,globalNewestMs,stat.id,newestEntry?.id??null,"max")){globalNewestMs=ms;newestEntry={id:stat.id,ts:stat.newest_ts}}}}const largestByBytes=topN===0?[]:[...stats].sort((a,b)=>b.bytes-a.bytes||a.id.localeCompare(b.id)).slice(0,topN);const deepestByLines=topN===0?[]:[...stats].sort((a,b)=>b.lines-a.lines||a.id.localeCompare(b.id)).slice(0,topN);return{total_streams:streams.length,total_lines:totalLines,total_bytes:totalBytes,largest_by_bytes:largestByBytes,deepest_by_lines:deepestByLines,oldest_entry:oldestEntry,newest_entry:newestEntry}}export{computeHistoryStorageStats};
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]="9cd23db4-2411-5c95-a6a0-fa30dd3a9a18")}catch{}})();function shouldReplaceExtreme(candidate,current,candidateTieBreaker,currentTieBreaker,direction,tieDirection="min"){const comparison=direction==="min"?candidate-current:current-candidate,tieComparison=tieDirection==="min"?candidateTieBreaker.localeCompare(currentTieBreaker??candidateTieBreaker):(currentTieBreaker??candidateTieBreaker).localeCompare(candidateTieBreaker);return comparison<0||comparison===0&&currentTieBreaker!==null&&tieComparison<0}function parseStreamStat(id,raw){const bytes=Buffer.byteLength(raw,"utf8");let lines=0,oldestTs=null,newestTs=null,oldestMs=Number.POSITIVE_INFINITY,newestMs=Number.NEGATIVE_INFINITY;for(const rawLine of raw.split(/\r?\n/)){const trimmed=rawLine.trim();if(trimmed==="")continue;lines+=1;let parsed;try{parsed=JSON.parse(trimmed)}catch{continue}if(parsed===null||typeof parsed!="object"||!("ts"in parsed)||typeof parsed.ts!="string")continue;const ts=parsed.ts,ms=Date.parse(ts);Number.isNaN(ms)||(shouldReplaceExtreme(ms,oldestMs,ts,oldestTs,"min")&&(oldestMs=ms,oldestTs=ts),shouldReplaceExtreme(ms,newestMs,ts,newestTs,"max","max")&&(newestMs=ms,newestTs=ts))}return{id,bytes,lines,oldest_ts:oldestTs,newest_ts:newestTs}}function computeHistoryStorageStats(streams,options){const rawTopN=options?.topN??5,topN=Math.max(0,Math.floor(rawTopN)),stats=streams.map(({id,raw})=>parseStreamStat(id,raw));let totalLines=0,totalBytes=0,oldestEntry=null,newestEntry=null,globalOldestMs=Number.POSITIVE_INFINITY,globalNewestMs=Number.NEGATIVE_INFINITY;for(const stat of stats){if(totalLines+=stat.lines,totalBytes+=stat.bytes,stat.oldest_ts!==null){const ms=Date.parse(stat.oldest_ts);shouldReplaceExtreme(ms,globalOldestMs,stat.id,oldestEntry?.id??null,"min")&&(globalOldestMs=ms,oldestEntry={id:stat.id,ts:stat.oldest_ts})}if(stat.newest_ts!==null){const ms=Date.parse(stat.newest_ts);shouldReplaceExtreme(ms,globalNewestMs,stat.id,newestEntry?.id??null,"max")&&(globalNewestMs=ms,newestEntry={id:stat.id,ts:stat.newest_ts})}}const largestByBytes=topN===0?[]:[...stats].sort((a,b)=>b.bytes-a.bytes||a.id.localeCompare(b.id)).slice(0,topN),deepestByLines=topN===0?[]:[...stats].sort((a,b)=>b.lines-a.lines||a.id.localeCompare(b.id)).slice(0,topN);return{total_streams:streams.length,total_lines:totalLines,total_bytes:totalBytes,largest_by_bytes:largestByBytes,deepest_by_lines:deepestByLines,oldest_entry:oldestEntry,newest_entry:newestEntry}}export{computeHistoryStorageStats};
2
2
  //# sourceMappingURL=history-storage-stats.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="99eadab1-5338-5d75-b600-fa0463053375")}catch(e2){}})();import fs from"node:fs/promises";import path from"node:path";import{runActiveOnWriteHooks}from"../extensions/index.js";import{ensureDir,pathExists}from"../fs/fs-utils.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{getHistoryPath}from"../store/paths.js";function toSortedUniqueItemIds(itemIds){return[...new Set(itemIds.filter(value=>value.trim().length>0))].sort((left,right)=>left.localeCompare(right))}function strictMissingStreamError(itemId,commandLabel){return new PmCliError(`Missing history stream for ${itemId}. ${commandLabel} requires history streams when settings.history.missing_stream is strict_error.`,EXIT_CODE.NOT_FOUND)}async function createStream(historyPath,commandLabel){await ensureDir(path.dirname(historyPath));const handle=await fs.open(historyPath,"a");await handle.close();return runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${commandLabel}:history:auto_create`})}async function enforceHistoryStreamPolicyForItem(params){return enforceHistoryStreamPolicyForItems({pmRoot:params.pmRoot,settings:params.settings,itemIds:[params.itemId],commandLabel:params.commandLabel})}async function enforceHistoryStreamPolicyForItems(params){const ids=toSortedUniqueItemIds(params.itemIds);const autoCreated=[];const warnings=[];for(const itemId of ids){const historyPath=getHistoryPath(params.pmRoot,itemId);if(await pathExists(historyPath)){continue}if(params.settings.history.missing_stream==="strict_error"){throw strictMissingStreamError(itemId,params.commandLabel)}warnings.push(...await createStream(historyPath,params.commandLabel));warnings.push(`history_stream_auto_created:${itemId}`);autoCreated.push(itemId)}return{auto_created_ids:autoCreated,warnings}}export{enforceHistoryStreamPolicyForItem,enforceHistoryStreamPolicyForItems};
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]="1d746e4d-ff6c-54ec-a94f-4ec4cb8f77b5")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{runActiveOnWriteHooks}from"../extensions/index.js";import{ensureDir,pathExists}from"../fs/fs-utils.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{getHistoryPath}from"../store/paths.js";function toSortedUniqueItemIds(itemIds){return[...new Set(itemIds.filter(value=>value.trim().length>0))].sort((left,right)=>left.localeCompare(right))}function strictMissingStreamError(itemId,commandLabel){return new PmCliError(`Missing history stream for ${itemId}. ${commandLabel} requires history streams when settings.history.missing_stream is strict_error.`,EXIT_CODE.NOT_FOUND)}async function createStream(historyPath,commandLabel){return await ensureDir(path.dirname(historyPath)),await(await fs.open(historyPath,"a")).close(),runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${commandLabel}:history:auto_create`})}async function enforceHistoryStreamPolicyForItem(params){return enforceHistoryStreamPolicyForItems({pmRoot:params.pmRoot,settings:params.settings,itemIds:[params.itemId],commandLabel:params.commandLabel})}async function enforceHistoryStreamPolicyForItems(params){const ids=toSortedUniqueItemIds(params.itemIds),autoCreated=[],warnings=[];for(const itemId of ids){const historyPath=getHistoryPath(params.pmRoot,itemId);if(!await pathExists(historyPath)){if(params.settings.history.missing_stream==="strict_error")throw strictMissingStreamError(itemId,params.commandLabel);warnings.push(...await createStream(historyPath,params.commandLabel)),warnings.push(`history_stream_auto_created:${itemId}`),autoCreated.push(itemId)}}return{auto_created_ids:autoCreated,warnings}}export{enforceHistoryStreamPolicyForItem,enforceHistoryStreamPolicyForItems};
2
2
  //# sourceMappingURL=history-stream-policy.js.map