@unbrained/pm-cli 2026.11.22 → 2026.11.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (892) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/after-command-context-usage.js +1 -1
  3. package/dist/cli/argv-utils.js +1 -1
  4. package/dist/cli/bootstrap-args.js +1 -1
  5. package/dist/cli/bundle-integrity.js +2 -2
  6. package/dist/cli/command-namespaces.js +1 -1
  7. package/dist/cli/commander-usage.js +11 -11
  8. package/dist/cli/commands/annotations/comments.js +1 -1
  9. package/dist/cli/commands/annotations/docs.js +1 -1
  10. package/dist/cli/commands/annotations/files.js +1 -1
  11. package/dist/cli/commands/annotations/learnings.js +1 -1
  12. package/dist/cli/commands/annotations/notes.js +1 -1
  13. package/dist/cli/commands/extension/describe.js +1 -1
  14. package/dist/cli/commands/extension/extension.js +1 -1
  15. package/dist/cli/commands/extension/scaffold.js +1 -1
  16. package/dist/cli/commands/extension/shared.js +1 -1
  17. package/dist/cli/commands/governance/gc.js +1 -1
  18. package/dist/cli/commands/governance/health.js +1 -1
  19. package/dist/cli/commands/governance/telemetry.js +1 -1
  20. package/dist/cli/commands/governance/validate.js +1 -1
  21. package/dist/cli/commands/history/activity.js +1 -1
  22. package/dist/cli/commands/history/history-compact.js +1 -1
  23. package/dist/cli/commands/history/history-redact.js +1 -1
  24. package/dist/cli/commands/history/history-repair.js +1 -1
  25. package/dist/cli/commands/history/history.js +1 -1
  26. package/dist/cli/commands/history/restore.js +1 -1
  27. package/dist/cli/commands/lifecycle/append.js +1 -1
  28. package/dist/cli/commands/lifecycle/claim.js +1 -1
  29. package/dist/cli/commands/lifecycle/close-many.js +1 -1
  30. package/dist/cli/commands/lifecycle/close.js +1 -1
  31. package/dist/cli/commands/lifecycle/copy.js +1 -1
  32. package/dist/cli/commands/lifecycle/create.js +1 -1
  33. package/dist/cli/commands/lifecycle/delete.js +1 -1
  34. package/dist/cli/commands/lifecycle/focus.js +1 -1
  35. package/dist/cli/commands/lifecycle/plan.js +1 -1
  36. package/dist/cli/commands/lifecycle/update-many.js +1 -1
  37. package/dist/cli/commands/lifecycle/update.js +1 -1
  38. package/dist/cli/commands/query/aggregate.js +1 -1
  39. package/dist/cli/commands/query/context.js +1 -1
  40. package/dist/cli/commands/query/deps.js +1 -1
  41. package/dist/cli/commands/query/duplicates.js +1 -1
  42. package/dist/cli/commands/query/eval.js +1 -1
  43. package/dist/cli/commands/query/get.js +1 -1
  44. package/dist/cli/commands/query/graph.js +1 -1
  45. package/dist/cli/commands/query/list.js +1 -1
  46. package/dist/cli/commands/query/next.js +1 -1
  47. package/dist/cli/commands/query/search.js +1 -1
  48. package/dist/cli/commands/query/stats.js +1 -1
  49. package/dist/cli/commands/test/test-all.js +1 -1
  50. package/dist/cli/commands/test/test-runs.js +1 -1
  51. package/dist/cli/commands/test/test.js +1 -1
  52. package/dist/cli/commands/workspace/config.js +1 -1
  53. package/dist/cli/commands/workspace/contracts.js +1 -1
  54. package/dist/cli/commands/workspace/init.js +1 -1
  55. package/dist/cli/commands/workspace/merge.js +1 -1
  56. package/dist/cli/commands/workspace/profile.js +1 -1
  57. package/dist/cli/commands/workspace/schema.js +1 -1
  58. package/dist/cli/commands/workspace/upgrade.js +1 -1
  59. package/dist/cli/context-intent-invocation.js +1 -1
  60. package/dist/cli/description-stdin.js +1 -1
  61. package/dist/cli/error-guidance.js +5 -5
  62. package/dist/cli/expected-revisions.js +1 -1
  63. package/dist/cli/extension-command-help.js +6 -6
  64. package/dist/cli/extension-recovery.js +1 -1
  65. package/dist/cli/help-content.js +5 -5
  66. package/dist/cli/help-json-payload.js +7 -7
  67. package/dist/cli/invocation-profile.js +2 -2
  68. package/dist/cli/main.js +5 -5
  69. package/dist/cli/migration-gates.js +1 -1
  70. package/dist/cli/option-values.js +1 -1
  71. package/dist/cli/preflight-warnings.js +3 -3
  72. package/dist/cli/public.js +1 -1
  73. package/dist/cli/register-annotations.js +1 -1
  74. package/dist/cli/register-assurance.js +1 -1
  75. package/dist/cli/register-files-lookup.js +1 -1
  76. package/dist/cli/register-history-activity.js +1 -1
  77. package/dist/cli/register-history-author.js +1 -1
  78. package/dist/cli/register-history-maintenance.js +2 -2
  79. package/dist/cli/register-list-query.js +10 -10
  80. package/dist/cli/register-mutation-options.js +0 -1
  81. package/dist/cli/register-mutation.js +6 -6
  82. package/dist/cli/register-operations.js +1 -1
  83. package/dist/cli/register-setup.js +1 -1
  84. package/dist/cli/register-structured-mutation.js +1 -1
  85. package/dist/cli/registration-helpers.js +1 -1
  86. package/dist/cli/runtime/activation.js +1 -1
  87. package/dist/cli/runtime/annotation-option-retry.js +1 -1
  88. package/dist/cli/runtime/close-fields-retry.js +1 -1
  89. package/dist/cli/runtime/field-route-retry.js +1 -1
  90. package/dist/cli/runtime/invocation-options.js +1 -1
  91. package/dist/cli/runtime/invocation-rewrites.js +1 -1
  92. package/dist/cli/runtime/projection-retry.js +1 -1
  93. package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
  94. package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
  95. package/dist/cli/runtime/selection.js +1 -1
  96. package/dist/cli/runtime/telemetry-outcome.js +1 -1
  97. package/dist/cli/runtime-compatibility-boundary.js +4 -4
  98. package/dist/cli/schema/registration.js +15 -15
  99. package/dist/cli/schema-registration-helpers.js +1 -1
  100. package/dist/cli/search-refresh.js +1 -1
  101. package/dist/cli/stats-analytics-json.js +1 -1
  102. package/dist/cli/telemetry-flush.js +1 -1
  103. package/dist/cli-bundle/bundle-manifest.json +1 -1
  104. package/dist/cli-bundle/chunks/chunk-2UQU7HRR.js +9 -0
  105. package/dist/cli-bundle/chunks/chunk-5DUP4AZA.js +2 -0
  106. package/dist/cli-bundle/chunks/chunk-5WZZ5XEN.js +3 -0
  107. package/dist/cli-bundle/chunks/chunk-6H36ZHMI.js +2 -0
  108. package/dist/cli-bundle/chunks/chunk-6MYJLOSG.js +2 -0
  109. package/dist/cli-bundle/chunks/chunk-AA52P34H.js +3 -0
  110. package/dist/cli-bundle/chunks/{chunk-B76TFRO2.js → chunk-AEOHUSUI.js} +101 -101
  111. package/dist/cli-bundle/chunks/chunk-BSRIVYTM.js +8 -0
  112. package/dist/cli-bundle/chunks/chunk-CFWLQFJM.js +71 -0
  113. package/dist/cli-bundle/chunks/chunk-D6PDUKUG.js +9 -0
  114. package/dist/cli-bundle/chunks/chunk-ENKXRSFZ.js +31 -0
  115. package/dist/cli-bundle/chunks/chunk-F2Z6XLZB.js +3 -0
  116. package/dist/cli-bundle/chunks/chunk-FJOEL75F.js +2 -0
  117. package/dist/cli-bundle/chunks/chunk-GDXCAC52.js +2 -0
  118. package/dist/cli-bundle/chunks/chunk-H7JEXRIN.js +6 -0
  119. package/dist/cli-bundle/chunks/chunk-J2PDAVBC.js +2 -0
  120. package/dist/cli-bundle/chunks/chunk-KE7HMBEW.js +2 -0
  121. package/dist/cli-bundle/chunks/chunk-KZHIBEJL.js +33 -0
  122. package/dist/cli-bundle/chunks/chunk-NGJ5ERBF.js +115 -0
  123. package/dist/cli-bundle/chunks/chunk-NQ54T7T2.js +2 -0
  124. package/dist/cli-bundle/chunks/chunk-O7JHS64G.js +3 -0
  125. package/dist/cli-bundle/chunks/chunk-OKEZF7HU.js +2 -0
  126. package/dist/cli-bundle/chunks/chunk-OKIKF4FD.js +2 -0
  127. package/dist/cli-bundle/chunks/chunk-OPJF254V.js +9 -0
  128. package/dist/cli-bundle/chunks/chunk-PZA7QECY.js +1 -0
  129. package/dist/cli-bundle/chunks/chunk-RWA5YZ5X.js +2 -0
  130. package/dist/cli-bundle/chunks/chunk-S32NGRQM.js +2 -0
  131. package/dist/cli-bundle/chunks/chunk-SLFRSZK6.js +1 -0
  132. package/dist/cli-bundle/chunks/chunk-TZY5MVJF.js +125 -0
  133. package/dist/cli-bundle/chunks/chunk-YYT3MIRF.js +3 -0
  134. package/dist/cli-bundle/chunks/chunk-ZPS4B6SI.js +8 -0
  135. package/dist/cli-bundle/chunks/context-budget-recovery-M5RFUEFG.js +2 -0
  136. package/dist/cli-bundle/chunks/indexed-receipt-blobs-BPYKN5Q7.js +4 -0
  137. package/dist/cli-bundle/chunks/{item-revision-4QBMZXKX.js → item-revision-FMD4KWBB.js} +2 -2
  138. package/dist/cli-bundle/chunks/item-transaction-SEHTH7N2.js +2 -0
  139. package/dist/cli-bundle/chunks/mutation-actor-SFGYIRPW.js +2 -0
  140. package/dist/cli-bundle/chunks/mutation-admission-57LBSKQI.js +2 -0
  141. package/dist/cli-bundle/chunks/{register-list-query-RR5KACJ3.js → register-list-query-L4IBU64P.js} +11 -11
  142. package/dist/cli-bundle/chunks/register-mutation-6NUOPHZ3.js +21 -0
  143. package/dist/cli-bundle/chunks/register-operations-JGYVORNN.js +2 -0
  144. package/dist/cli-bundle/chunks/register-setup-C44SIXEH.js +2 -0
  145. package/dist/cli-bundle/chunks/settlement-hook-6MR32OOC.js +7 -0
  146. package/dist/cli-bundle/chunks/stage-PQ7AB63N.js +2 -0
  147. package/dist/cli-bundle/focused-chunks/chunk-6LKTEKHS.js +6 -0
  148. package/dist/cli-bundle/focused-chunks/chunk-6LPXMFLM.js +2 -0
  149. package/dist/cli-bundle/focused-chunks/chunk-A6VEMCRR.js +3 -0
  150. package/dist/cli-bundle/focused-chunks/chunk-AIDL2ZNT.js +3 -0
  151. package/dist/cli-bundle/focused-chunks/chunk-BKPUUW5O.js +1 -0
  152. package/dist/cli-bundle/focused-chunks/chunk-BWOVFE5B.js +2 -0
  153. package/dist/cli-bundle/focused-chunks/chunk-HMDQDRV2.js +8 -0
  154. package/dist/cli-bundle/focused-chunks/chunk-I66IKYKP.js +2 -0
  155. package/dist/cli-bundle/focused-chunks/chunk-IIP6LZ5E.js +2 -0
  156. package/dist/cli-bundle/focused-chunks/chunk-IR2J3NOT.js +2 -0
  157. package/dist/cli-bundle/focused-chunks/chunk-IROZDIDX.js +3 -0
  158. package/dist/cli-bundle/focused-chunks/chunk-ITKDHSBR.js +2 -0
  159. package/dist/cli-bundle/focused-chunks/chunk-K53OIT5J.js +2 -0
  160. package/dist/cli-bundle/focused-chunks/chunk-LQYYPXUK.js +26 -0
  161. package/dist/cli-bundle/focused-chunks/chunk-NQTEE66P.js +13 -0
  162. package/dist/cli-bundle/focused-chunks/chunk-O7Z73ALG.js +2 -0
  163. package/dist/cli-bundle/focused-chunks/chunk-OTMMOKPM.js +91 -0
  164. package/dist/cli-bundle/focused-chunks/chunk-OXOCZJC6.js +2 -0
  165. package/dist/cli-bundle/focused-chunks/chunk-QLAHEDT6.js +2 -0
  166. package/dist/cli-bundle/focused-chunks/chunk-QQIIMMFU.js +2 -0
  167. package/dist/cli-bundle/focused-chunks/chunk-RIE3SJSE.js +9 -0
  168. package/dist/cli-bundle/focused-chunks/chunk-TD544C74.js +8 -0
  169. package/dist/cli-bundle/focused-chunks/chunk-UFTUNBMY.js +27 -0
  170. package/dist/cli-bundle/focused-chunks/chunk-X6CXWWNB.js +2 -0
  171. package/dist/cli-bundle/focused-chunks/chunk-XRS3VNC6.js +44 -0
  172. package/dist/cli-bundle/focused-chunks/chunk-XYPEZGTR.js +2 -0
  173. package/dist/cli-bundle/focused-chunks/chunk-Y2ESLKCF.js +8 -0
  174. package/dist/cli-bundle/focused-chunks/chunk-YSJKQLFR.js +2 -0
  175. package/dist/cli-bundle/focused-chunks/chunk-Z2X7HH3C.js +102 -0
  176. package/dist/cli-bundle/focused-chunks/chunk-ZHWPCVQL.js +78 -0
  177. package/dist/cli-bundle/focused-chunks/context-budget-recovery-CSJV3TY3.js +2 -0
  178. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-EGEJMG3G.js +4 -0
  179. package/dist/cli-bundle/focused-chunks/{item-revision-2O6MLPEX.js → item-revision-YDACCDVY.js} +2 -2
  180. package/dist/cli-bundle/focused-chunks/item-transaction-UKEQCTKB.js +2 -0
  181. package/dist/cli-bundle/focused-chunks/mutation-actor-AS465LRX.js +2 -0
  182. package/dist/cli-bundle/focused-chunks/mutation-admission-E5UHJZFE.js +2 -0
  183. package/dist/cli-bundle/focused-chunks/settlement-hook-FMLGKG7J.js +7 -0
  184. package/dist/cli-bundle/focused-chunks/stage-36J7YLGI.js +2 -0
  185. package/dist/cli-bundle/main.js +27 -27
  186. package/dist/cli-bundle/sdk-authoring.js +1 -1
  187. package/dist/cli-bundle/sdk-contracts.js +5 -5
  188. package/dist/cli-bundle/sdk-core.js +1 -1
  189. package/dist/cli-bundle/sdk-governance.js +1 -1
  190. package/dist/cli-bundle/sdk-graph.js +1 -1
  191. package/dist/cli-bundle/sdk-merge.js +66 -66
  192. package/dist/cli-bundle/sdk-query.js +1 -1
  193. package/dist/cli-bundle/sdk-runtime.js +1 -1
  194. package/dist/cli-bundle/sdk-testing.js +1 -1
  195. package/dist/cli-bundle/sdk.js +12 -12
  196. package/dist/cli.js +1 -1
  197. package/dist/core/checkpoint/checkpoint-gc.js +1 -1
  198. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  199. package/dist/core/checkpoint/mutation-context.js +1 -1
  200. package/dist/core/config/nested-settings.js +1 -1
  201. package/dist/core/config/positional-value.js +1 -1
  202. package/dist/core/diagnostics/remediation.js +1 -1
  203. package/dist/core/extensions/activation-summary-markdown.js +2 -2
  204. package/dist/core/extensions/activation-summary.js +1 -1
  205. package/dist/core/extensions/activation-transaction.js +1 -1
  206. package/dist/core/extensions/capability-usage.js +1 -1
  207. package/dist/core/extensions/command-hook-context.js +1 -1
  208. package/dist/core/extensions/command-metadata-contract.js +1 -1
  209. package/dist/core/extensions/command-visibility-tier.js +1 -1
  210. package/dist/core/extensions/contribution-inventory.js +1 -1
  211. package/dist/core/extensions/exporter-output-contract.js +1 -1
  212. package/dist/core/extensions/extension-candidate.js +1 -1
  213. package/dist/core/extensions/extension-capability-aliases.js +1 -1
  214. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  215. package/dist/core/extensions/extension-policy.js +1 -1
  216. package/dist/core/extensions/extension-registries.js +1 -1
  217. package/dist/core/extensions/extension-runtime-helpers.js +1 -1
  218. package/dist/core/extensions/extension-types.js +1 -1
  219. package/dist/core/extensions/flag-definition-validation.js +1 -1
  220. package/dist/core/extensions/flag-value-types.js +1 -1
  221. package/dist/core/extensions/index.js +1 -1
  222. package/dist/core/extensions/item-field-types.js +1 -1
  223. package/dist/core/extensions/item-fields.js +1 -1
  224. package/dist/core/extensions/loader.js +1 -1
  225. package/dist/core/extensions/manifest-parser.js +1 -1
  226. package/dist/core/extensions/manifest-schema.js +1 -1
  227. package/dist/core/extensions/module-graph-snapshot.js +1 -1
  228. package/dist/core/extensions/mutation-actor-snapshot.js +1 -1
  229. package/dist/core/extensions/mutation-actor.js +1 -1
  230. package/dist/core/extensions/preflight-ownership.js +1 -1
  231. package/dist/core/extensions/read-output-contract.js +1 -1
  232. package/dist/core/extensions/registration-contracts.js +1 -1
  233. package/dist/core/extensions/registration-validation.js +1 -1
  234. package/dist/core/extensions/registration-values.js +1 -1
  235. package/dist/core/extensions/reserved-host-flags.js +1 -1
  236. package/dist/core/extensions/runtime-registrations.js +1 -1
  237. package/dist/core/extensions/service-ownership.js +1 -1
  238. package/dist/core/extensions/version-compat.js +1 -1
  239. package/dist/core/extensions/version-diagnostics.js +1 -1
  240. package/dist/core/fs/atomic-create.js +1 -1
  241. package/dist/core/fs/file-glob.js +1 -1
  242. package/dist/core/fs/fs-utils.js +2 -2
  243. package/dist/core/fs/host-environment-errors.js +1 -1
  244. package/dist/core/fs/index.js +1 -1
  245. package/dist/core/fs/path-utils.js +1 -1
  246. package/dist/core/governance/content-fields.js +1 -1
  247. package/dist/core/governance/issue-codes.js +1 -1
  248. package/dist/core/governance/metadata-coverage.js +1 -1
  249. package/dist/core/history/bridge.js +1 -1
  250. package/dist/core/history/digest.js +1 -1
  251. package/dist/core/history/drift-cache.js +3 -3
  252. package/dist/core/history/drift-scan.js +1 -1
  253. package/dist/core/history/event-classification.js +1 -1
  254. package/dist/core/history/event-index.js +11 -11
  255. package/dist/core/history/history-compact-bulk.js +1 -1
  256. package/dist/core/history/history-diff.js +1 -1
  257. package/dist/core/history/history-rewrite.js +1 -1
  258. package/dist/core/history/history-storage-stats.js +1 -1
  259. package/dist/core/history/history-stream-policy.js +1 -1
  260. package/dist/core/history/history.js +2 -2
  261. package/dist/core/history/identity.js +1 -1
  262. package/dist/core/history/index.js +1 -1
  263. package/dist/core/history/operation-contract.js +1 -1
  264. package/dist/core/history/projection.js +1 -1
  265. package/dist/core/history/read.js +1 -1
  266. package/dist/core/history/replay.js +2 -2
  267. package/dist/core/history/stream-summary.js +2 -2
  268. package/dist/core/history/tombstone.js +1 -1
  269. package/dist/core/history/version-address.js +1 -1
  270. package/dist/core/history/workspace-history.js +2 -2
  271. package/dist/core/io/body-file.js +1 -1
  272. package/dist/core/io/bulk-ids-input.js +2 -2
  273. package/dist/core/item/actionability.js +1 -1
  274. package/dist/core/item/deferred-fields.js +1 -1
  275. package/dist/core/item/dependency-reference.js +1 -1
  276. package/dist/core/item/id.js +1 -1
  277. package/dist/core/item/index.js +1 -1
  278. package/dist/core/item/item-format-version.js +1 -1
  279. package/dist/core/item/item-format.js +7 -7
  280. package/dist/core/item/item-record.js +1 -1
  281. package/dist/core/item/item-type-definition.js +1 -1
  282. package/dist/core/item/literal-mutation-input.js +1 -1
  283. package/dist/core/item/parent-reference-policy.js +1 -1
  284. package/dist/core/item/parse.js +8 -8
  285. package/dist/core/item/plan-lifecycle.js +1 -1
  286. package/dist/core/item/priority.js +1 -1
  287. package/dist/core/item/sprint-release-format.js +1 -1
  288. package/dist/core/item/status-filter.js +1 -1
  289. package/dist/core/item/status.js +1 -1
  290. package/dist/core/item/toon-decode.js +1 -1
  291. package/dist/core/item/type-registry.js +1 -1
  292. package/dist/core/item/type-synonyms.js +1 -1
  293. package/dist/core/lock/index.js +1 -1
  294. package/dist/core/lock/lock-confinement.js +1 -1
  295. package/dist/core/lock/lock-gc.js +1 -1
  296. package/dist/core/lock/lock-owner.js +1 -1
  297. package/dist/core/lock/lock.js +4 -4
  298. package/dist/core/output/linked-test-projection.js +5 -5
  299. package/dist/core/output/mutation-projection.js +1 -1
  300. package/dist/core/output/output-control.js +1 -1
  301. package/dist/core/output/output.js +19 -19
  302. package/dist/core/output/query-summary.js +1 -1
  303. package/dist/core/output/tabular.js +3 -3
  304. package/dist/core/packages/manifest.js +1 -1
  305. package/dist/core/packages/root.js +1 -1
  306. package/dist/core/policy/workflow-policy-schema.js +1 -1
  307. package/dist/core/policy/workflow-policy-store.js +1 -1
  308. package/dist/core/policy/workflow-policy.js +1 -1
  309. package/dist/core/profile/profile-describe.js +1 -1
  310. package/dist/core/profile/profile-lint.d.ts +1 -1
  311. package/dist/core/profile/profile-lint.js +1 -1
  312. package/dist/core/profile/profile-plan.js +1 -1
  313. package/dist/core/profile/profile-presets.js +4 -4
  314. package/dist/core/reproducibility/context.js +1 -1
  315. package/dist/core/schema/fields-file.js +2 -2
  316. package/dist/core/schema/item-types-file.js +2 -2
  317. package/dist/core/schema/runtime-field-filters.js +1 -1
  318. package/dist/core/schema/runtime-field-values.js +1 -1
  319. package/dist/core/schema/runtime-schema.js +2 -2
  320. package/dist/core/schema/status-defs-file.js +2 -2
  321. package/dist/core/schema/status-token.js +1 -1
  322. package/dist/core/schema/type-inference.js +1 -1
  323. package/dist/core/schema/type-presets.js +1 -1
  324. package/dist/core/schema/type-workflows.js +1 -1
  325. package/dist/core/search/background-refresh.js +2 -2
  326. package/dist/core/search/bm25.js +1 -1
  327. package/dist/core/search/cache.js +2 -2
  328. package/dist/core/search/corpus.js +1 -1
  329. package/dist/core/search/embedding-batches.js +1 -1
  330. package/dist/core/search/eval-thresholds.js +1 -1
  331. package/dist/core/search/eval.js +1 -1
  332. package/dist/core/search/http-client.js +1 -1
  333. package/dist/core/search/providers.js +1 -1
  334. package/dist/core/search/relevance.js +1 -1
  335. package/dist/core/search/semantic-defaults.js +1 -1
  336. package/dist/core/search/staleness.js +1 -1
  337. package/dist/core/search/vector-stores.js +2 -2
  338. package/dist/core/search/vectorization-metadata.js +1 -1
  339. package/dist/core/sentry/helpers.js +1 -1
  340. package/dist/core/sentry/instrument.js +1 -1
  341. package/dist/core/sentry/sensitive-assignments.js +1 -1
  342. package/dist/core/session/session-state.js +1 -1
  343. package/dist/core/shared/agent-session-context.js +1 -1
  344. package/dist/core/shared/author.js +5 -5
  345. package/dist/core/shared/command-line.js +1 -1
  346. package/dist/core/shared/command-types.js +0 -1
  347. package/dist/core/shared/conflict-markers.js +1 -1
  348. package/dist/core/shared/constants.js +1 -1
  349. package/dist/core/shared/error-details.js +1 -1
  350. package/dist/core/shared/errors.js +1 -1
  351. package/dist/core/shared/html-entity-decode.js +1 -1
  352. package/dist/core/shared/index.js +1 -1
  353. package/dist/core/shared/item-metadata-contract.js +1 -1
  354. package/dist/core/shared/lazy-module.js +1 -1
  355. package/dist/core/shared/levenshtein.js +1 -1
  356. package/dist/core/shared/memo.js +1 -1
  357. package/dist/core/shared/numeric-parsers.js +1 -1
  358. package/dist/core/shared/option-alias-visibility.js +1 -1
  359. package/dist/core/shared/output-unicode.js +1 -1
  360. package/dist/core/shared/primitives.js +1 -1
  361. package/dist/core/shared/process-tree.js +2 -2
  362. package/dist/core/shared/secret-rules.js +5 -5
  363. package/dist/core/shared/serial-queue.js +1 -1
  364. package/dist/core/shared/serialization.js +1 -1
  365. package/dist/core/shared/split-comma-list.js +1 -1
  366. package/dist/core/shared/text-normalization.js +1 -1
  367. package/dist/core/shared/time.js +2 -2
  368. package/dist/core/shared/url-credentials.js +1 -1
  369. package/dist/core/store/index.js +1 -1
  370. package/dist/core/store/item-format-migration.js +1 -1
  371. package/dist/core/store/item-metadata-cache.js +1 -1
  372. package/dist/core/store/item-metadata-query-index.js +11 -11
  373. package/dist/core/store/item-metadata-read-work.js +1 -1
  374. package/dist/core/store/item-mutation-precondition.js +1 -1
  375. package/dist/core/store/item-store.js +1 -1
  376. package/dist/core/store/paths.js +1 -1
  377. package/dist/core/store/settings-concurrency.js +1 -1
  378. package/dist/core/store/settings-read-cache.js +1 -1
  379. package/dist/core/store/settings-sections.js +2 -2
  380. package/dist/core/store/settings-validator.js +1 -1
  381. package/dist/core/store/settings.d.ts +3 -1
  382. package/dist/core/store/settings.js +6 -6
  383. package/dist/core/store/sqlite-runtime.js +1 -1
  384. package/dist/core/store/tracker-preflight.js +1 -1
  385. package/dist/core/store/transaction-coordinator-scope.js +1 -1
  386. package/dist/core/telemetry/consent.js +3 -3
  387. package/dist/core/telemetry/observability.js +1 -1
  388. package/dist/core/telemetry/policy.js +1 -1
  389. package/dist/core/telemetry/read-sampling.js +2 -2
  390. package/dist/core/telemetry/runtime.js +9 -9
  391. package/dist/core/test/background-runs.js +4 -4
  392. package/dist/core/test/item-test-run-tracking.js +1 -1
  393. package/dist/core/test/run-selectors.js +1 -1
  394. package/dist/core/validate/estimate-defaults.js +1 -1
  395. package/dist/core/validate/fix-planning.js +1 -1
  396. package/dist/core/validate/linked-artifact-reference.js +1 -1
  397. package/dist/core/validate/missing-by-type.js +1 -1
  398. package/dist/core/validate/missing-link-owners.js +1 -1
  399. package/dist/core/validate/stale-file-classification.js +1 -1
  400. package/dist/mcp/http-server.js +5 -5
  401. package/dist/mcp/legacy-adapter.js +1 -1
  402. package/dist/mcp/runtime-capabilities.js +1 -1
  403. package/dist/mcp/server.js +4 -4
  404. package/dist/mcp/tool-definitions.js +1 -1
  405. package/dist/sdk/actionability.js +1 -1
  406. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  407. package/dist/sdk/agent/command-recovery.js +1 -1
  408. package/dist/sdk/agent/command-suggestions.js +1 -1
  409. package/dist/sdk/agent/create-option-policy.js +1 -1
  410. package/dist/sdk/agent/identity-config.js +1 -1
  411. package/dist/sdk/agent/item-addressing.js +1 -1
  412. package/dist/sdk/agent/linked-resource-recovery.js +1 -1
  413. package/dist/sdk/agent/refusal-closure-census.js +2 -2
  414. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
  415. package/dist/sdk/agent/subcommand-recovery.js +1 -1
  416. package/dist/sdk/agent-capability-contracts.js +3 -3
  417. package/dist/sdk/agent-session-context.js +1 -1
  418. package/dist/sdk/annotations.js +1 -1
  419. package/dist/sdk/author-attribution.js +1 -1
  420. package/dist/sdk/cli-bootstrap.js +1 -1
  421. package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -5
  422. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  423. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  424. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
  425. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  426. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  427. package/dist/sdk/cli-contracts/completeness.js +1 -1
  428. package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
  429. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  430. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -2
  431. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  432. package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
  433. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  434. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
  435. package/dist/sdk/cli-contracts/string-lists.js +1 -1
  436. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  437. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  438. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  439. package/dist/sdk/cli-contracts/typed-action-inputs.js +0 -1
  440. package/dist/sdk/cli-contracts.js +1 -1
  441. package/dist/sdk/cli-program.js +1 -1
  442. package/dist/sdk/command-line.js +1 -1
  443. package/dist/sdk/comments.js +1 -1
  444. package/dist/sdk/compile-cache.js +1 -1
  445. package/dist/sdk/completion/bash.js +2 -2
  446. package/dist/sdk/completion/fish.js +72 -72
  447. package/dist/sdk/completion/shared.js +1 -1
  448. package/dist/sdk/completion/zsh.js +75 -75
  449. package/dist/sdk/completion.js +1 -1
  450. package/dist/sdk/config.js +1 -1
  451. package/dist/sdk/context/recency.js +1 -1
  452. package/dist/sdk/context/semantic-session-attribution.js +1 -1
  453. package/dist/sdk/context/usage-egress.js +1 -1
  454. package/dist/sdk/context/usage-ledger.js +6 -6
  455. package/dist/sdk/context-intent-contracts.js +1 -1
  456. package/dist/sdk/context-intent-runtime.js +1 -1
  457. package/dist/sdk/context-packing.js +1 -1
  458. package/dist/sdk/context-relevance.js +1 -1
  459. package/dist/sdk/context-signal-store.js +2 -2
  460. package/dist/sdk/context-usage.js +1 -1
  461. package/dist/sdk/dependencies/context-budget-recovery.js +1 -1
  462. package/dist/sdk/dependencies.js +1 -1
  463. package/dist/sdk/dependency-flag-validation.js +1 -1
  464. package/dist/sdk/dependency-provenance.js +1 -1
  465. package/dist/sdk/docs.js +1 -1
  466. package/dist/sdk/duplicates.js +1 -1
  467. package/dist/sdk/environment/host-environment-errors.js +1 -1
  468. package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
  469. package/dist/sdk/environment/source-context.js +1 -1
  470. package/dist/sdk/environment/tracker-preflight.js +1 -1
  471. package/dist/sdk/error-code-catalog.js +1 -1
  472. package/dist/sdk/error-runtime.js +1 -1
  473. package/dist/sdk/errors.js +1 -1
  474. package/dist/sdk/eval.js +1 -1
  475. package/dist/sdk/extension/author-manifest.js +1 -1
  476. package/dist/sdk/extension/bundled-catalog.js +1 -1
  477. package/dist/sdk/extension/command-options.js +1 -1
  478. package/dist/sdk/extension/concurrency.js +1 -1
  479. package/dist/sdk/extension/copy-scope.js +1 -1
  480. package/dist/sdk/extension/custom-field-collisions.js +1 -1
  481. package/dist/sdk/extension/describe.js +3 -3
  482. package/dist/sdk/extension/doctor.js +1 -1
  483. package/dist/sdk/extension/install-plan.js +1 -1
  484. package/dist/sdk/extension/install-receipts.js +1 -1
  485. package/dist/sdk/extension/install-runtime.js +3 -3
  486. package/dist/sdk/extension/install-snapshot.js +1 -1
  487. package/dist/sdk/extension/install-sources.js +5 -5
  488. package/dist/sdk/extension/managed-state.js +2 -2
  489. package/dist/sdk/extension/managed-update-status.js +1 -1
  490. package/dist/sdk/extension/migrations.js +2 -2
  491. package/dist/sdk/extension/native-command-options.js +1 -1
  492. package/dist/sdk/extension/output-ownership.js +1 -1
  493. package/dist/sdk/extension/runtime-summary.js +1 -1
  494. package/dist/sdk/extension/scaffold.js +11 -11
  495. package/dist/sdk/extension/shared.js +1 -1
  496. package/dist/sdk/extension/source-resolution.js +1 -1
  497. package/dist/sdk/extension/static-inventory.js +1 -1
  498. package/dist/sdk/extension/update-check.js +1 -1
  499. package/dist/sdk/extension-command-context.js +2 -2
  500. package/dist/sdk/extension-contracts.js +1 -1
  501. package/dist/sdk/extension.js +1 -1
  502. package/dist/sdk/files.js +1 -1
  503. package/dist/sdk/flag-invocation-contracts.js +1 -1
  504. package/dist/sdk/generated/error-code-catalog-rows.js +1 -1
  505. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  506. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  507. package/dist/sdk/generated-error-code-catalog.js +1 -1
  508. package/dist/sdk/governance/assurance-action-contracts.js +0 -1
  509. package/dist/sdk/governance/assurance-action.js +1 -1
  510. package/dist/sdk/governance/assurance-limits.js +1 -1
  511. package/dist/sdk/governance/assurance-mutation-error.js +1 -1
  512. package/dist/sdk/governance/assurance-presets.js +1 -1
  513. package/dist/sdk/governance/assurance-runtime.js +1 -1
  514. package/dist/sdk/governance/assurance.js +4 -4
  515. package/dist/sdk/governance/boundary-fixtures.js +1 -1
  516. package/dist/sdk/governance/closure-timestamps.js +1 -1
  517. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
  518. package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
  519. package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
  520. package/dist/sdk/governance/defect-recurrence.js +2 -2
  521. package/dist/sdk/governance/extension-host-version.js +1 -1
  522. package/dist/sdk/governance/gc.js +1 -1
  523. package/dist/sdk/governance/health/history-drift-remedies.js +1 -1
  524. package/dist/sdk/governance/health/projection.js +1 -1
  525. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  526. package/dist/sdk/governance/health.js +2 -2
  527. package/dist/sdk/governance/hierarchy-validation.js +1 -1
  528. package/dist/sdk/governance/in-progress-work-health.js +1 -1
  529. package/dist/sdk/governance/lifecycle-dependency-cycles.js +1 -1
  530. package/dist/sdk/governance/linked-file-report.js +1 -1
  531. package/dist/sdk/governance/merge-receipt-history.js +1 -1
  532. package/dist/sdk/governance/provenance-health.js +4 -4
  533. package/dist/sdk/governance/reindex.js +5 -5
  534. package/dist/sdk/governance/stale-work.js +1 -1
  535. package/dist/sdk/governance/status-role-diagnostics.js +1 -1
  536. package/dist/sdk/governance/storage-integrity.js +1 -1
  537. package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
  538. package/dist/sdk/governance/upgrade.js +2 -2
  539. package/dist/sdk/governance/validate-deferred-fields.js +1 -1
  540. package/dist/sdk/governance/validate-history-drift.js +1 -1
  541. package/dist/sdk/governance/validate-item-reader.js +1 -1
  542. package/dist/sdk/governance/validate-normalization.js +1 -1
  543. package/dist/sdk/governance/validate.js +1 -1
  544. package/dist/sdk/governance/workflow-completeness.js +1 -1
  545. package/dist/sdk/governance/workflow-policy.js +3 -3
  546. package/dist/sdk/governance/workspace-position.js +2 -2
  547. package/dist/sdk/graph/analytics.js +1 -1
  548. package/dist/sdk/graph/assembly.js +1 -1
  549. package/dist/sdk/graph/cache.js +1 -1
  550. package/dist/sdk/graph/cardinality-integrity.js +1 -1
  551. package/dist/sdk/graph/centrality.js +1 -1
  552. package/dist/sdk/graph/deadline-scheduling.js +1 -1
  553. package/dist/sdk/graph/durable-cache.js +1 -1
  554. package/dist/sdk/graph/governance-contracts.js +1 -1
  555. package/dist/sdk/graph/governance.js +1 -1
  556. package/dist/sdk/graph/hierarchy-integrity.js +1 -1
  557. package/dist/sdk/graph/lifecycle-coverage.js +1 -1
  558. package/dist/sdk/graph/mutation-advisory.js +1 -1
  559. package/dist/sdk/graph/query-contracts.js +1 -1
  560. package/dist/sdk/graph/remediation.js +1 -1
  561. package/dist/sdk/graph/run.js +1 -1
  562. package/dist/sdk/graph/scheduling.js +1 -1
  563. package/dist/sdk/graph/traversal.js +1 -1
  564. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
  565. package/dist/sdk/guide-topics.js +1 -1
  566. package/dist/sdk/guide.js +7 -7
  567. package/dist/sdk/history/append-only-repair.js +4 -4
  568. package/dist/sdk/history/attestation-command.js +2 -2
  569. package/dist/sdk/history/attestation-contract.js +1 -1
  570. package/dist/sdk/history/attestation-scan.js +1 -1
  571. package/dist/sdk/history/attestation.js +1 -1
  572. package/dist/sdk/history/maintenance.js +1 -1
  573. package/dist/sdk/history/reanchor-refusal.js +1 -1
  574. package/dist/sdk/history/reseed.js +1 -1
  575. package/dist/sdk/history/salvage.js +5 -5
  576. package/dist/sdk/history/subject.js +1 -1
  577. package/dist/sdk/history-analytics.js +1 -1
  578. package/dist/sdk/history-compact.js +1 -1
  579. package/dist/sdk/history-mcp.js +1 -1
  580. package/dist/sdk/history-provenance.js +1 -1
  581. package/dist/sdk/history-read.js +1 -1
  582. package/dist/sdk/history-redact.js +1 -1
  583. package/dist/sdk/history-repair.js +1 -1
  584. package/dist/sdk/improvement-ledger-validation.js +1 -1
  585. package/dist/sdk/improvement-ledger.js +2 -2
  586. package/dist/sdk/init-agent-guidance.js +10 -10
  587. package/dist/sdk/init.js +14 -14
  588. package/dist/sdk/invocation-author.js +1 -1
  589. package/dist/sdk/item-children.js +1 -1
  590. package/dist/sdk/item-metadata-index.js +1 -1
  591. package/dist/sdk/item-schedule.js +1 -1
  592. package/dist/sdk/item-transaction.js +1 -1
  593. package/dist/sdk/learnings.js +1 -1
  594. package/dist/sdk/lifecycle/append.js +3 -3
  595. package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
  596. package/dist/sdk/lifecycle/claim.js +1 -1
  597. package/dist/sdk/lifecycle/cli-input.js +1 -1
  598. package/dist/sdk/lifecycle/close-many.js +1 -1
  599. package/dist/sdk/lifecycle/close.js +1 -1
  600. package/dist/sdk/lifecycle/copy.js +1 -1
  601. package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
  602. package/dist/sdk/lifecycle/core-item-fields.js +1 -1
  603. package/dist/sdk/lifecycle/create-deferrals.js +1 -1
  604. package/dist/sdk/lifecycle/create.js +1 -1
  605. package/dist/sdk/lifecycle/delete.js +1 -1
  606. package/dist/sdk/lifecycle/dependency-removal.js +1 -1
  607. package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
  608. package/dist/sdk/lifecycle/focus.js +1 -1
  609. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
  610. package/dist/sdk/lifecycle/item-revision.js +1 -1
  611. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
  612. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
  613. package/dist/sdk/lifecycle/mcp-actions.js +1 -1
  614. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
  615. package/dist/sdk/lifecycle/mutation-command-options.js +0 -1
  616. package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
  617. package/dist/sdk/lifecycle/mutation-option-validation.js +1 -1
  618. package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
  619. package/dist/sdk/lifecycle/plan.js +1 -1
  620. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
  621. package/dist/sdk/lifecycle/release-handoff.js +1 -1
  622. package/dist/sdk/lifecycle/reopen.js +1 -1
  623. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -2
  624. package/dist/sdk/lifecycle/repeated-terminal-state.js +1 -1
  625. package/dist/sdk/lifecycle/restore.js +1 -1
  626. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  627. package/dist/sdk/lifecycle/start-blockers.js +1 -1
  628. package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
  629. package/dist/sdk/lifecycle/task-composition.js +1 -1
  630. package/dist/sdk/lifecycle/update-many.js +1 -1
  631. package/dist/sdk/lifecycle/update.js +2 -2
  632. package/dist/sdk/lifecycle/workflow-transition.js +1 -1
  633. package/dist/sdk/lifecycle-completion.js +1 -1
  634. package/dist/sdk/lifecycle-policy.js +1 -1
  635. package/dist/sdk/linked-artifacts.js +2 -2
  636. package/dist/sdk/mcp/apps.js +5 -5
  637. package/dist/sdk/mcp/authorization.js +1 -1
  638. package/dist/sdk/mcp/discovery.js +1 -1
  639. package/dist/sdk/mcp/executable.js +4 -4
  640. package/dist/sdk/mcp/interactions.js +1 -1
  641. package/dist/sdk/mcp/protocol.js +1 -1
  642. package/dist/sdk/mcp/skills.js +3 -3
  643. package/dist/sdk/mcp/subscriptions.js +1 -1
  644. package/dist/sdk/mcp/tasks.js +2 -2
  645. package/dist/sdk/mcp/transport.js +1 -1
  646. package/dist/sdk/merge/abandoned-receipts.js +1 -1
  647. package/dist/sdk/merge/driver.js +7 -7
  648. package/dist/sdk/merge/history-scalar-rebase.js +1 -1
  649. package/dist/sdk/merge/ignored-artifacts.js +1 -1
  650. package/dist/sdk/merge/index.js +1 -1
  651. package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
  652. package/dist/sdk/merge/install.js +6 -6
  653. package/dist/sdk/merge/receipt-file-boundary.js +1 -1
  654. package/dist/sdk/merge/receipt-operation.js +1 -1
  655. package/dist/sdk/merge/receipt-schema.js +1 -1
  656. package/dist/sdk/merge/receipts.js +4 -4
  657. package/dist/sdk/merge/reconcile.js +1 -1
  658. package/dist/sdk/merge/settlement-hook.js +4 -4
  659. package/dist/sdk/merge/stage.js +1 -1
  660. package/dist/sdk/merge/three-way.js +9 -9
  661. package/dist/sdk/merge/worktree-config.js +2 -2
  662. package/dist/sdk/merge.js +1 -1
  663. package/dist/sdk/mutation-events.js +1 -1
  664. package/dist/sdk/mutation-guard.js +1 -1
  665. package/dist/sdk/notes.js +1 -1
  666. package/dist/sdk/output/fit-envelope.js +1 -1
  667. package/dist/sdk/output/list-envelope.js +1 -1
  668. package/dist/sdk/output/table-rows.js +1 -1
  669. package/dist/sdk/output-contracts.js +1 -1
  670. package/dist/sdk/output-projection.js +1 -1
  671. package/dist/sdk/output-token-accounting.js +1 -1
  672. package/dist/sdk/output.js +2 -2
  673. package/dist/sdk/ownership-source.js +1 -1
  674. package/dist/sdk/package-import-adapters.js +1 -1
  675. package/dist/sdk/package-migrations.js +1 -1
  676. package/dist/sdk/package-runtime-options.js +1 -1
  677. package/dist/sdk/pagination.js +1 -1
  678. package/dist/sdk/profile.js +5 -5
  679. package/dist/sdk/provenance.js +1 -1
  680. package/dist/sdk/public-surface.json +1 -1
  681. package/dist/sdk/query/activity.js +1 -1
  682. package/dist/sdk/query/aggregate.js +1 -1
  683. package/dist/sdk/query/calendar.js +4 -4
  684. package/dist/sdk/query/complete-list.js +1 -1
  685. package/dist/sdk/query/context.js +2 -2
  686. package/dist/sdk/query/declared-blockers.js +1 -1
  687. package/dist/sdk/query/duplicate-candidates.js +1 -1
  688. package/dist/sdk/query/get-facet-roots.js +1 -1
  689. package/dist/sdk/query/get.js +1 -1
  690. package/dist/sdk/query/history.js +1 -1
  691. package/dist/sdk/query/item-filter-options.js +0 -1
  692. package/dist/sdk/query/light-metadata.js +1 -1
  693. package/dist/sdk/query/list-filter-shared.js +1 -1
  694. package/dist/sdk/query/list.js +1 -1
  695. package/dist/sdk/query/multi-value-filters.js +1 -1
  696. package/dist/sdk/query/next-ranking-policy.js +1 -1
  697. package/dist/sdk/query/next-ready-budget.js +1 -1
  698. package/dist/sdk/query/next.js +2 -2
  699. package/dist/sdk/query/parsers.js +1 -1
  700. package/dist/sdk/query/projection-contracts.js +1 -1
  701. package/dist/sdk/query/search/corpus.js +2 -2
  702. package/dist/sdk/query/search/filters.js +1 -1
  703. package/dist/sdk/query/search/input.js +1 -1
  704. package/dist/sdk/query/search/lexical.js +1 -1
  705. package/dist/sdk/query/search/response.js +1 -1
  706. package/dist/sdk/query/search/semantic.js +3 -3
  707. package/dist/sdk/query/search/types.js +0 -1
  708. package/dist/sdk/query/search-contracts.js +1 -1
  709. package/dist/sdk/query/search-pagination.js +1 -1
  710. package/dist/sdk/query/search-rendering.js +1 -1
  711. package/dist/sdk/query/search.js +1 -1
  712. package/dist/sdk/query/window-pagination.js +1 -1
  713. package/dist/sdk/query/workspace-contracts.js +1 -1
  714. package/dist/sdk/read-output/continuation.js +1 -1
  715. package/dist/sdk/read-output/extension.js +1 -1
  716. package/dist/sdk/read-output/options.js +1 -1
  717. package/dist/sdk/read-output/positional-rows.js +1 -1
  718. package/dist/sdk/read-output/provenance.js +1 -1
  719. package/dist/sdk/read-output/session-result.js +0 -1
  720. package/dist/sdk/read-output/surfaces.js +1 -1
  721. package/dist/sdk/read-output/tail-retention.js +1 -1
  722. package/dist/sdk/read-output-budget.js +1 -1
  723. package/dist/sdk/read-output-contracts.js +1 -1
  724. package/dist/sdk/read-output-rows.js +1 -1
  725. package/dist/sdk/read-output-session.js +1 -1
  726. package/dist/sdk/relationship-analytics.js +1 -1
  727. package/dist/sdk/relationship-context.js +1 -1
  728. package/dist/sdk/relationship-history.js +6 -6
  729. package/dist/sdk/relationship-kinds/contract.js +1 -1
  730. package/dist/sdk/relationships.js +1 -1
  731. package/dist/sdk/reproducibility/process.js +1 -1
  732. package/dist/sdk/runtime/actions.js +1 -1
  733. package/dist/sdk/runtime/context.js +1 -1
  734. package/dist/sdk/runtime/mutation-admission.js +1 -1
  735. package/dist/sdk/runtime/mutation-value-validation.js +1 -1
  736. package/dist/sdk/runtime/schema-preview.js +1 -1
  737. package/dist/sdk/runtime/schema.js +1 -1
  738. package/dist/sdk/runtime-action-aliases.js +1 -1
  739. package/dist/sdk/runtime-extended-actions.js +1 -1
  740. package/dist/sdk/runtime-input.d.ts +2 -0
  741. package/dist/sdk/runtime-input.js +1 -1
  742. package/dist/sdk/runtime-primitives.js +1 -1
  743. package/dist/sdk/runtime-public-contracts.js +0 -1
  744. package/dist/sdk/runtime-stats-options.js +1 -1
  745. package/dist/sdk/runtime.d.ts +5 -3
  746. package/dist/sdk/runtime.js +1 -1
  747. package/dist/sdk/scheduling-shortcuts.js +1 -1
  748. package/dist/sdk/schema/field-option-collisions.js +2 -0
  749. package/dist/sdk/schema-migration.js +4 -4
  750. package/dist/sdk/schema.js +7 -7
  751. package/dist/sdk/search-refresh-worker.js +1 -1
  752. package/dist/sdk/similarity-scoring.js +1 -1
  753. package/dist/sdk/similarity.js +1 -1
  754. package/dist/sdk/start-task-status.js +1 -1
  755. package/dist/sdk/stats.js +1 -1
  756. package/dist/sdk/structured-mutations.js +1 -1
  757. package/dist/sdk/telemetry-flush.js +1 -1
  758. package/dist/sdk/telemetry.js +4 -4
  759. package/dist/sdk/templates.js +3 -3
  760. package/dist/sdk/test/batch.js +2 -2
  761. package/dist/sdk/test/command-args.js +1 -1
  762. package/dist/sdk/test/command-resolution.js +2 -2
  763. package/dist/sdk/test/entry.js +2 -2
  764. package/dist/sdk/test/execution-receipts.js +2 -2
  765. package/dist/sdk/test/execution.js +5 -5
  766. package/dist/sdk/test/json-path.js +1 -1
  767. package/dist/sdk/test/linked-command-detection.js +1 -1
  768. package/dist/sdk/test/measurements.js +1 -1
  769. package/dist/sdk/test/parsers.js +1 -1
  770. package/dist/sdk/test/prerequisites.js +1 -1
  771. package/dist/sdk/test/receipt-index-snapshot.js +1 -1
  772. package/dist/sdk/test/run-phases.js +1 -1
  773. package/dist/sdk/test/runs.js +1 -1
  774. package/dist/sdk/test/trust.js +2 -2
  775. package/dist/sdk/test/update.js +1 -1
  776. package/dist/sdk/test/workspace-snapshot.js +1 -1
  777. package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
  778. package/dist/sdk/traceability/source-traceability.js +2 -2
  779. package/dist/sdk/tracker-root-discovery.js +1 -1
  780. package/dist/sdk/transactions/item-finalization.js +1 -1
  781. package/dist/sdk/workspace-contracts-cache.js +1 -1
  782. package/dist/sdk/workspace-contracts.js +1 -1
  783. package/dist/sdk/workspace-memory.js +2 -2
  784. package/dist/sdk/workspace-snapshot.js +5 -5
  785. package/dist/sdk/workspace-transaction-gc.js +1 -1
  786. package/dist/sdk/workspace-transaction.js +2 -2
  787. package/dist/sdk/workspace.js +6 -6
  788. package/dist/types/index.js +1 -1
  789. package/dist/types.js +1 -1
  790. package/docs/COMMANDS.md +1 -1
  791. package/docs/EXTENSIONS.md +1 -1
  792. package/docs/SDK.md +74 -4
  793. package/marketplace.json +1 -1
  794. package/package.json +2 -1
  795. package/packages/pm-beads/package.json +1 -1
  796. package/packages/pm-calendar/package.json +1 -1
  797. package/packages/pm-command-kit/package.json +1 -1
  798. package/packages/pm-digital-twin/package.json +1 -1
  799. package/packages/pm-governance-audit/package.json +1 -1
  800. package/packages/pm-guide-shell/package.json +1 -1
  801. package/packages/pm-kanban/package.json +1 -1
  802. package/packages/pm-lifecycle-hooks/package.json +1 -1
  803. package/packages/pm-linked-test-adapters/package.json +1 -1
  804. package/packages/pm-search-advanced/package.json +1 -1
  805. package/packages/pm-templates/package.json +1 -1
  806. package/packages/pm-todos/package.json +1 -1
  807. package/packages/pm-vcs/package.json +1 -1
  808. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  809. package/plugins/pm-claude/package.json +1 -1
  810. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  811. package/plugins/pm-codex/package.json +1 -1
  812. package/plugins/pm-codex/plugin.json +1 -1
  813. package/runtime-dependencies.json +1 -1
  814. package/scripts/finalize-build.mjs +63 -24
  815. package/scripts/prepare-build-cache.mjs +28 -1
  816. package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +0 -9
  817. package/dist/cli-bundle/chunks/chunk-4TB5D6HL.js +0 -125
  818. package/dist/cli-bundle/chunks/chunk-5ZMVLWE3.js +0 -2
  819. package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +0 -33
  820. package/dist/cli-bundle/chunks/chunk-AR4NP5HI.js +0 -3
  821. package/dist/cli-bundle/chunks/chunk-B4PPFOPY.js +0 -3
  822. package/dist/cli-bundle/chunks/chunk-CAR2L5NW.js +0 -8
  823. package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
  824. package/dist/cli-bundle/chunks/chunk-EIGUKEV6.js +0 -2
  825. package/dist/cli-bundle/chunks/chunk-GTPCAJMZ.js +0 -8
  826. package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +0 -2
  827. package/dist/cli-bundle/chunks/chunk-HC2OPETM.js +0 -2
  828. package/dist/cli-bundle/chunks/chunk-HKUV74K3.js +0 -2
  829. package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +0 -115
  830. package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +0 -2
  831. package/dist/cli-bundle/chunks/chunk-J2LABXBL.js +0 -2
  832. package/dist/cli-bundle/chunks/chunk-J52BEBSS.js +0 -2
  833. package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +0 -3
  834. package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +0 -3
  835. package/dist/cli-bundle/chunks/chunk-OJTMGDON.js +0 -31
  836. package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +0 -2
  837. package/dist/cli-bundle/chunks/chunk-TC6XLIYO.js +0 -2
  838. package/dist/cli-bundle/chunks/chunk-U7EL3AYA.js +0 -3
  839. package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +0 -6
  840. package/dist/cli-bundle/chunks/chunk-X6MIWTTT.js +0 -2
  841. package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +0 -2
  842. package/dist/cli-bundle/chunks/chunk-XFHPKXAE.js +0 -71
  843. package/dist/cli-bundle/chunks/chunk-YHVLVSEZ.js +0 -9
  844. package/dist/cli-bundle/chunks/chunk-YMUSRWV4.js +0 -9
  845. package/dist/cli-bundle/chunks/chunk-YR2KEBHP.js +0 -2
  846. package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +0 -2
  847. package/dist/cli-bundle/chunks/indexed-receipt-blobs-ITTXIN4K.js +0 -4
  848. package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +0 -2
  849. package/dist/cli-bundle/chunks/mutation-actor-FWLYWJ37.js +0 -2
  850. package/dist/cli-bundle/chunks/mutation-admission-7ZDCK3G2.js +0 -2
  851. package/dist/cli-bundle/chunks/register-mutation-57AJQWFV.js +0 -21
  852. package/dist/cli-bundle/chunks/register-operations-RKWST7CU.js +0 -2
  853. package/dist/cli-bundle/chunks/register-setup-CMI23PC5.js +0 -2
  854. package/dist/cli-bundle/chunks/settlement-hook-BXN5LEQD.js +0 -7
  855. package/dist/cli-bundle/chunks/stage-4KDVXC5Z.js +0 -2
  856. package/dist/cli-bundle/focused-chunks/chunk-2ZD7275J.js +0 -2
  857. package/dist/cli-bundle/focused-chunks/chunk-324AHXJO.js +0 -2
  858. package/dist/cli-bundle/focused-chunks/chunk-3IRCYJI5.js +0 -3
  859. package/dist/cli-bundle/focused-chunks/chunk-3V53UBHN.js +0 -9
  860. package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +0 -91
  861. package/dist/cli-bundle/focused-chunks/chunk-4JZITIJB.js +0 -2
  862. package/dist/cli-bundle/focused-chunks/chunk-4KTFKSS3.js +0 -2
  863. package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +0 -78
  864. package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +0 -2
  865. package/dist/cli-bundle/focused-chunks/chunk-BRZV7BFV.js +0 -8
  866. package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +0 -2
  867. package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +0 -3
  868. package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +0 -2
  869. package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +0 -2
  870. package/dist/cli-bundle/focused-chunks/chunk-HDEKFSOK.js +0 -2
  871. package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +0 -2
  872. package/dist/cli-bundle/focused-chunks/chunk-IWOXAUDU.js +0 -2
  873. package/dist/cli-bundle/focused-chunks/chunk-ML3JHCC6.js +0 -6
  874. package/dist/cli-bundle/focused-chunks/chunk-OPGOOP25.js +0 -2
  875. package/dist/cli-bundle/focused-chunks/chunk-RE7ZWT7D.js +0 -27
  876. package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +0 -3
  877. package/dist/cli-bundle/focused-chunks/chunk-RQ252B6V.js +0 -8
  878. package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +0 -2
  879. package/dist/cli-bundle/focused-chunks/chunk-URGHTTT3.js +0 -8
  880. package/dist/cli-bundle/focused-chunks/chunk-USPYKWQG.js +0 -13
  881. package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +0 -102
  882. package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +0 -44
  883. package/dist/cli-bundle/focused-chunks/chunk-WZWXGDYY.js +0 -26
  884. package/dist/cli-bundle/focused-chunks/chunk-YKSLZPLT.js +0 -2
  885. package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +0 -2
  886. package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +0 -2
  887. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-AF4U3F3D.js +0 -4
  888. package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +0 -2
  889. package/dist/cli-bundle/focused-chunks/mutation-actor-TCYDPUGG.js +0 -2
  890. package/dist/cli-bundle/focused-chunks/mutation-admission-LY73EJWM.js +0 -2
  891. package/dist/cli-bundle/focused-chunks/settlement-hook-ARYCZQY4.js +0 -7
  892. package/dist/cli-bundle/focused-chunks/stage-DQ7RQQ52.js +0 -2
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="846c1c5d-8a5c-56ee-832a-bfc780283e70")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{createHash,randomUUID}from"node:crypto";import{getActiveExtensionRegistrations,hasActiveOnReadHooks,runActiveOnReadHooks}from"../extensions/index.js";import{collectRegisteredItemFieldNames}from"../extensions/item-fields.js";import{parseItemDocument}from"../item/item-format.js";import{evictOldestMemoEntries}from"../shared/memo.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";import{acquireLock}from"../lock/lock.js";import{ITEM_FILE_EXTENSIONS,getItemFormatFromPath}from"./paths.js";import{rebuildItemMetadataQueryIndex,removeItemMetadataQueryIndex,updateItemMetadataQueryIndex}from"./item-metadata-query-index.js";const CACHE_VERSION=8,DEFAULT_DERIVED_INDEX_MINIMUM_ITEMS=500,DERIVED_INDEX_LOCK_ID="metadata-derived-index",CACHE_FILENAME="metadata-cache.json",BODY_CACHE_FILENAME="metadata-cache-bodies.json",COLLECTIONS_CACHE_FILENAME="metadata-cache-collections.json",DELTA_CACHE_FILENAME="metadata-cache-delta.json",MANIFEST_CACHE_FILENAME="metadata-cache-manifest.json",MAX_CACHE_CONTEXTS=4,HEAVY_METADATA_KEYS=["comments","notes","learnings","files","tests","test_runs","docs"];function resolveActiveExtensionFieldNames(){return collectRegisteredItemFieldNames(getActiveExtensionRegistrations())}function splitHeavyMetadata(metadata){const light={...metadata},heavy={};for(const key of HEAVY_METADATA_KEYS)key in light&&(heavy[key]=light[key],delete light[key]);return{light,heavy}}function mergeHeavyMetadata(light,heavy){return!heavy||Object.keys(heavy).length===0?light:{...light,...heavy}}function computeContextFingerprint(preferredFormat,typeToFolder,schema,extensionFieldNames){const hash=createHash("sha256");hash.update(`format:${preferredFormat??"default"}`);const sortedTypes=Object.entries(typeToFolder).sort(([a],[b])=>a.localeCompare(b)).map(([type,folder])=>`${type}=${folder}`).join(",");return hash.update(`|types:${sortedTypes}`),schema&&hash.update(`|schema:${JSON.stringify(schema)}`),extensionFieldNames.length>0&&hash.update(`|extension_fields:${extensionFieldNames.join(",")}`),hash.digest("hex").slice(0,16)}function getCachePath(pmRoot){return path.join(pmRoot,"runtime",CACHE_FILENAME)}function getBodyCachePath(pmRoot){return path.join(pmRoot,"runtime",BODY_CACHE_FILENAME)}function getCollectionsCachePath(pmRoot){return path.join(pmRoot,"runtime",COLLECTIONS_CACHE_FILENAME)}function getDeltaCachePath(pmRoot){return path.join(pmRoot,"runtime",DELTA_CACHE_FILENAME)}function getManifestCachePath(pmRoot){return path.join(pmRoot,"runtime",MANIFEST_CACHE_FILENAME)}function getContextCachePath(cachePath,contextFingerprint){const extension=path.extname(cachePath);return`${cachePath.slice(0,-extension.length)}.${contextFingerprint}${extension}`}const ENVELOPE_MEMO_MAX_ENTRIES=24,envelopeMemo=new Map,projectedBaseCursor=new WeakMap;function baseCursorFor(envelope){return projectedBaseCursor.get(envelope)??envelope.source_cursor}function applyMetadataDelta(envelope,delta){const baseCursor=baseCursorFor(envelope);if(!(delta.base_source_cursor!==baseCursor||envelope.source_cursor===delta.source_cursor)){projectedBaseCursor.set(envelope,baseCursor);for(const[relativePath,change]of Object.entries(delta.changes))change.entry?envelope.entries[relativePath]=change.entry:delete envelope.entries[relativePath];envelope.directory_signatures=delta.directory_signatures,envelope.source_cursor=delta.source_cursor}}function applyBodyDelta(envelope,delta){if(!envelope)return;const baseCursor=baseCursorFor(envelope);if(!(delta.base_source_cursor!==baseCursor||envelope.source_cursor===delta.source_cursor)){projectedBaseCursor.set(envelope,baseCursor);for(const[relativePath,change]of Object.entries(delta.changes))change.body?envelope.bodies[relativePath]=change.body:delete envelope.bodies[relativePath];envelope.source_cursor=delta.source_cursor}}function applyCollectionsDelta(envelope,delta){if(!envelope)return;const baseCursor=baseCursorFor(envelope);if(!(delta.base_source_cursor!==baseCursor||envelope.source_cursor===delta.source_cursor)){projectedBaseCursor.set(envelope,baseCursor);for(const[relativePath,change]of Object.entries(delta.changes))change.collections?envelope.collections[relativePath]=change.collections:delete envelope.collections[relativePath];envelope.source_cursor=delta.source_cursor}}function applyDerivedIndexDelta(metadata,bodies,collections,delta){!metadata||!delta||metadata.context_fingerprint!==delta.context_fingerprint||(applyMetadataDelta(metadata,delta),applyBodyDelta(bodies,delta),applyCollectionsDelta(collections,delta))}function memoizeEnvelope(cachePath,entry){envelopeMemo.size>=ENVELOPE_MEMO_MAX_ENTRIES&&!envelopeMemo.has(cachePath)&&evictOldestMemoEntries(envelopeMemo),envelopeMemo.set(cachePath,entry)}async function loadEnvelopeMemoized(cachePath,parse){let stat;try{stat=await fs.stat(cachePath)}catch{return envelopeMemo.delete(cachePath),null}const memoized=envelopeMemo.get(cachePath);if(memoized&&statMatches(memoized.signature,stat.mtimeMs,stat.ctimeMs,stat.size))return envelopeMemo.delete(cachePath),envelopeMemo.set(cachePath,memoized),memoized.envelope;let envelope;try{envelope=parse(await fs.readFile(cachePath,"utf8"))}catch{envelope=null}return memoizeEnvelope(cachePath,{signature:{mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size},envelope}),envelope}function clearItemMetadataEnvelopeMemo(){envelopeMemo.clear()}async function loadCache(pmRoot,contextFingerprint,diagnostics){const parse=raw=>{const parsed=JSON.parse(raw);return parsed.version!==CACHE_VERSION||typeof parsed.source_cursor!="string"||typeof parsed.entries!="object"||parsed.entries===null?null:parsed},cachePath=getCachePath(pmRoot),active=await loadEnvelopeMemoized(cachePath,parse);if(!contextFingerprint||active===null||active.context_fingerprint===contextFingerprint)return active;const retained=await loadEnvelopeMemoized(getContextCachePath(cachePath,contextFingerprint),parse);return retained===null&&appendWarning(diagnostics,`metadata_cache_context_changed:${active.context_fingerprint}->${contextFingerprint}`),retained}async function loadBodyCache(pmRoot,contextFingerprint){const parse=raw=>{const parsed=JSON.parse(raw);return parsed.version!==CACHE_VERSION||typeof parsed.source_cursor!="string"||typeof parsed.bodies!="object"||parsed.bodies===null?null:parsed},cachePath=getBodyCachePath(pmRoot),active=await loadEnvelopeMemoized(cachePath,parse);return contextFingerprint&&active?.context_fingerprint!==contextFingerprint?await loadEnvelopeMemoized(getContextCachePath(cachePath,contextFingerprint),parse):active}async function loadCollectionsCache(pmRoot,contextFingerprint){const parse=raw=>{const parsed=JSON.parse(raw);return parsed.version!==CACHE_VERSION||typeof parsed.source_cursor!="string"||typeof parsed.collections!="object"||parsed.collections===null?null:parsed},cachePath=getCollectionsCachePath(pmRoot),active=await loadEnvelopeMemoized(cachePath,parse);return contextFingerprint&&active?.context_fingerprint!==contextFingerprint?await loadEnvelopeMemoized(getContextCachePath(cachePath,contextFingerprint),parse):active}async function loadDerivedIndexDelta(pmRoot){const deltaPath=getDeltaCachePath(pmRoot),envelope=await loadEnvelopeMemoized(deltaPath,raw=>{const parsed=JSON.parse(raw);return parsed.version!==CACHE_VERSION||typeof parsed.base_source_cursor!="string"||typeof parsed.source_cursor!="string"||typeof parsed.changes!="object"||parsed.changes===null?null:parsed});if(envelope)return{envelope,invalid:!1};try{return await fs.stat(deltaPath),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function loadDerivedIndexManifest(pmRoot){const manifestPath=getManifestCachePath(pmRoot),manifest=await loadEnvelopeMemoized(manifestPath,raw=>{const parsed=JSON.parse(raw);return parsed.version!==CACHE_VERSION||typeof parsed.context_fingerprint!="string"||typeof parsed.source_cursor!="string"||!Number.isInteger(parsed.entry_count)||parsed.entry_count<0||typeof parsed.directory_signatures!="object"||parsed.directory_signatures===null?null:parsed});if(manifest)return manifest;try{await fs.stat(manifestPath),await removeDerivedIndexFiles(pmRoot)}catch{}return null}async function persistCache(cachePath,envelope){await fs.mkdir(path.dirname(cachePath),{recursive:!0}),await writeFileAtomic(cachePath,JSON.stringify(envelope));try{const stat=await fs.stat(cachePath);memoizeEnvelope(cachePath,{signature:{mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size},envelope})}catch{envelopeMemo.delete(cachePath)}const pmRoot=path.dirname(path.dirname(cachePath));if(cachePath===getCachePath(pmRoot)||cachePath===getBodyCachePath(pmRoot)||cachePath===getCollectionsCachePath(pmRoot)){const contextPath=getContextCachePath(cachePath,envelope.context_fingerprint);await writeFileAtomic(contextPath,JSON.stringify(envelope));try{const contextStat=await fs.stat(contextPath);memoizeEnvelope(contextPath,{signature:{mtime_ms:contextStat.mtimeMs,ctime_ms:contextStat.ctimeMs,size:contextStat.size},envelope})}catch{envelopeMemo.delete(contextPath)}const directory=path.dirname(cachePath),extension=path.extname(cachePath),stem=path.basename(cachePath,extension),variants=(await fs.readdir(directory,{withFileTypes:!0}).catch(()=>[])).filter(entry=>entry.isFile()&&entry.name!==path.basename(cachePath)&&entry.name.startsWith(`${stem}.`)&&entry.name.endsWith(extension)).map(entry=>path.join(directory,entry.name));if(variants.length>MAX_CACHE_CONTEXTS){const byAge=(await Promise.all(variants.map(async variantPath=>{try{return{path:variantPath,mtime:(await fs.stat(variantPath)).mtimeMs}}catch{return null}}))).filter(entry=>entry!==null);for(const stale of byAge.sort((left,right)=>left.mtime-right.mtime).slice(0,Math.max(0,byAge.length-MAX_CACHE_CONTEXTS)))await fs.rm(stale.path,{force:!0}),envelopeMemo.delete(stale.path)}}}function shouldReplaceCachedDocumentCandidate(existingFormat,candidateFormat,preferredFormat){return preferredFormat?candidateFormat===preferredFormat&&existingFormat!==preferredFormat:candidateFormat==="toon"&&existingFormat!=="toon"}function shouldRecordCachedDocumentCandidate(existingFormat,candidateFormat,preferredFormat){return existingFormat===void 0||shouldReplaceCachedDocumentCandidate(existingFormat,candidateFormat,preferredFormat)}function appendWarning(warnings,warning){warnings&&!warnings.includes(warning)&&warnings.push(warning)}function statMatches(signature,mtimeMs,ctimeMs,size){return signature.mtime_ms===mtimeMs&&signature.ctime_ms===ctimeMs&&signature.size===size}async function readItemDirectoryFiles(pmRoot,folder,warnings){const dirPath=path.join(pmRoot,folder);try{const files=await fs.readdir(dirPath);return{folder,dirPath,files}}catch(error){return typeof error=="object"&&error!==null&&"code"in error&&!isFileMissingError(error)&&appendWarning(warnings,`item_list_directory_read_failed:${folder}`),{folder,dirPath,files:[]}}}async function readDirectorySignature(pmRoot,folder){try{const stat=await fs.stat(path.join(pmRoot,folder));return[folder,{exists:!0,mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size}]}catch{return[folder,{exists:!1,mtime_ms:0,ctime_ms:0,size:0}]}}async function readDirectorySignatures(pmRoot,folders){return Object.fromEntries(await Promise.all(folders.map(async folder=>await readDirectorySignature(pmRoot,folder))))}function directorySignaturesMatch(left,right){return!left||Object.keys(left).length!==Object.keys(right).length?!1:Object.entries(right).every(([folder,signature])=>{const previous=left[folder];return previous!==void 0&&previous.exists===signature.exists&&statMatches(previous,signature.mtime_ms,signature.ctime_ms,signature.size)})}function isItemDocumentFile(file){return ITEM_FILE_EXTENSIONS.some(ext=>file.toLowerCase().endsWith(ext))}function markDocumentCacheMisses(misses,includeBody,includeCollections,metadataCached,bodyCached,collectionsCached){metadataCached||(misses.metadata=!0),includeBody&&!bodyCached&&(misses.body=!0),includeCollections&&!collectionsCached&&(misses.collections=!0)}async function dispatchCachedDocumentReadHooks(filePath,warnings,dispatchReadHooks){if(dispatchReadHooks)for(const warning of await runActiveOnReadHooks({path:filePath,scope:"project"}))appendWarning(warnings,warning)}function selectHeavyMetadata(includeCollections,collectionsCached,cachedCollections,parsedCollections){if(includeCollections)return collectionsCached&&cachedCollections?cachedCollections.collections:parsedCollections}async function readCachedDocumentParts(filePath,relativePath,context){const stat=await fs.stat(filePath),mtimeMs=stat.mtimeMs,ctimeMs=stat.ctimeMs,{size}=stat,itemFormat=getItemFormatFromPath(filePath);await dispatchCachedDocumentReadHooks(filePath,context.warnings,context.dispatchReadHooks);const cachedEntry=context.previousEntries[relativePath],metadataCached=!context.forceSourceRead&&cachedEntry!==void 0&&statMatches(cachedEntry,mtimeMs,ctimeMs,size),cachedBody=context.previousBodies[relativePath],bodyCached=!context.forceSourceRead&&cachedBody!==void 0&&statMatches(cachedBody,mtimeMs,ctimeMs,size),cachedCollections=context.previousCollections[relativePath],collectionsCached=!context.forceSourceRead&&cachedCollections!==void 0&&statMatches(cachedCollections,mtimeMs,ctimeMs,size);if(!(!metadataCached||context.includeBody&&!bodyCached||context.includeCollections&&!collectionsCached))return{mtimeMs,ctimeMs,size,itemFormat,lightMetadata:cachedEntry.metadata,heavyMetadata:selectHeavyMetadata(context.includeCollections,collectionsCached,cachedCollections,void 0),bodyLength:cachedEntry.body_length,body:context.includeBody?cachedBody.body:void 0};const raw=await fs.readFile(filePath,"utf8"),parsed=parseItemDocument(raw,{format:itemFormat,schema:context.schema,extensionFieldNames:context.extensionFieldNames,onWarning:warning=>appendWarning(context.warnings,warning)}),split=splitHeavyMetadata(parsed.metadata);return markDocumentCacheMisses(context.state.misses,context.includeBody,context.includeCollections,metadataCached,bodyCached,collectionsCached),{mtimeMs,ctimeMs,size,itemFormat,lightMetadata:metadataCached?cachedEntry.metadata:split.light,heavyMetadata:selectHeavyMetadata(context.includeCollections,collectionsCached,cachedCollections,split.heavy),bodyLength:metadataCached?cachedEntry.body_length:parsed.body.length,body:context.includeBody?parsed.body:void 0}}function recordCachedDocumentCandidate(filePath,relativePath,context,parts){context.state.newEntries[relativePath]={mtime_ms:parts.mtimeMs,ctime_ms:parts.ctimeMs,size:parts.size,metadata:parts.lightMetadata,body_length:parts.bodyLength},context.includeBody&&parts.body!==void 0&&(context.state.newBodies[relativePath]={mtime_ms:parts.mtimeMs,ctime_ms:parts.ctimeMs,size:parts.size,body:parts.body}),context.includeCollections&&parts.heavyMetadata!==void 0&&(context.state.newCollections[relativePath]={mtime_ms:parts.mtimeMs,ctime_ms:parts.ctimeMs,size:parts.size,collections:parts.heavyMetadata});const metadata=context.includeCollections?mergeHeavyMetadata(parts.lightMetadata,parts.heavyMetadata):parts.lightMetadata,existing=context.state.documentsById.get(metadata.id),candidate={metadata,body:parts.body,item_format:parts.itemFormat,item_path:filePath};shouldRecordCachedDocumentCandidate(existing?.itemFormat,parts.itemFormat,context.preferredFormat)&&context.state.documentsById.set(metadata.id,{candidate,itemFormat:parts.itemFormat})}async function processCachedDocumentFile(folder,filePath,relativePath,context){try{const parts=await readCachedDocumentParts(filePath,relativePath,context);recordCachedDocumentCandidate(filePath,relativePath,context,parts)}catch{appendWarning(context.warnings,`item_list_item_read_failed:${folder}/${path.basename(filePath)}`)}}function selectPreviousMetadataEntries(existingCache,contextFingerprint){return existingCache&&existingCache.context_fingerprint===contextFingerprint?existingCache.entries:{}}function selectPreviousBodyEntries(existingBodyCache,contextFingerprint){return existingBodyCache&&existingBodyCache.context_fingerprint===contextFingerprint?existingBodyCache.bodies:{}}function selectPreviousCollectionEntries(existingCollectionsCache,contextFingerprint){return existingCollectionsCache&&existingCollectionsCache.context_fingerprint===contextFingerprint?existingCollectionsCache.collections:{}}function createDocumentCacheMutableState(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}async function processCachedDocumentFiles(dirResults,context){const parseTasks=[];for(const{folder,dirPath,files}of dirResults)for(const file of files){if(!isItemDocumentFile(file))continue;const filePath=path.join(dirPath,file),relativePath=path.relative(context.pmRoot,filePath);parseTasks.push(processCachedDocumentFile(folder,filePath,relativePath,context)),parseTasks.length===32&&(await Promise.all(parseTasks),parseTasks.length=0)}await Promise.all(parseTasks)}async function persistMetadataCacheIfNeeded(params){if(!(!(params.state.misses.metadata||Object.keys(params.previousEntries).length!==Object.keys(params.state.newEntries).length||!directorySignaturesMatch(params.existingCache?.directory_signatures,params.directorySignatures))&&params.existingCache!==null&&params.existingCache.context_fingerprint===params.contextFingerprint))try{await persistCache(getCachePath(params.pmRoot),{version:CACHE_VERSION,context_fingerprint:params.contextFingerprint,source_cursor:params.sourceCursor,directory_signatures:params.directorySignatures,entries:params.state.newEntries}),await persistCache(getManifestCachePath(params.pmRoot),{version:CACHE_VERSION,context_fingerprint:params.contextFingerprint,source_cursor:params.sourceCursor,entry_count:Object.keys(params.state.newEntries).length,directory_signatures:params.directorySignatures});const rows=[...params.state.documentsById.values()].map(({candidate})=>({relativePath:path.relative(params.pmRoot,candidate.item_path),metadata:splitHeavyMetadata(candidate.metadata).light,linkedFiles:candidate.metadata.files??[]}));rows.length>=params.minimumIndexedItems?await rebuildItemMetadataQueryIndex({pmRoot:params.pmRoot,contextFingerprint:params.contextFingerprint,sourceCursor:params.sourceCursor,rows}):await removeItemMetadataQueryIndex(params.pmRoot)}catch{}}async function persistBodyCacheIfNeeded(params){!(params.state.misses.body||Object.keys(params.previousBodies).length!==Object.keys(params.state.newBodies).length)&&params.existingBodyCache!==null&&params.existingBodyCache.context_fingerprint===params.contextFingerprint||await persistCache(getBodyCachePath(params.pmRoot),{version:CACHE_VERSION,context_fingerprint:params.contextFingerprint,source_cursor:params.sourceCursor,bodies:params.state.newBodies}).catch(()=>{})}async function persistCollectionsCacheIfNeeded(params){!(params.state.misses.collections||Object.keys(params.previousCollections).length!==Object.keys(params.state.newCollections).length)&&params.existingCollectionsCache!==null&&params.existingCollectionsCache.context_fingerprint===params.contextFingerprint||await persistCache(getCollectionsCachePath(params.pmRoot),{version:CACHE_VERSION,context_fingerprint:params.contextFingerprint,source_cursor:params.sourceCursor,collections:params.state.newCollections}).catch(()=>{})}async function acquireItemMetadataDerivedIndexLock(pmRoot,author,options={}){const cache=await loadDerivedIndexManifest(pmRoot);return options.required!==!0&&(cache===null||cache.entry_count<DEFAULT_DERIVED_INDEX_MINIMUM_ITEMS)?async()=>{}:acquireLock(pmRoot,DERIVED_INDEX_LOCK_ID,30,author,!1,!1,3e3)}async function readItemMetadataDerivedIndexState(pmRoot,folders){const manifest=await loadDerivedIndexManifest(pmRoot);if(manifest===null)return null;const delta=await loadDerivedIndexDelta(pmRoot);if(delta.invalid)return await removeDerivedIndexFiles(pmRoot),null;const effectiveCursor=delta.envelope?.context_fingerprint===manifest.context_fingerprint&&delta.envelope.base_source_cursor===manifest.source_cursor?delta.envelope.source_cursor:manifest.source_cursor,effectiveDirectorySignatures=delta.envelope?.context_fingerprint===manifest.context_fingerprint&&delta.envelope.base_source_cursor===manifest.source_cursor?delta.envelope.directory_signatures:manifest.directory_signatures;return folders&&!directorySignaturesMatch(effectiveDirectorySignatures,await readDirectorySignatures(pmRoot,folders))?null:{source_cursor:effectiveCursor,entry_count:manifest.entry_count}}function relativeIndexPath(pmRoot,itemPath){const relative=path.relative(pmRoot,itemPath);return relative===""||relative===".."||relative.startsWith(`..${path.sep}`)||path.isAbsolute(relative)?null:relative}async function removeDerivedIndexFiles(pmRoot){await Promise.all([getCachePath(pmRoot),getBodyCachePath(pmRoot),getCollectionsCachePath(pmRoot),getDeltaCachePath(pmRoot),getManifestCachePath(pmRoot)].map(async cachePath=>{await fs.rm(cachePath,{force:!0}),envelopeMemo.delete(cachePath)})),await removeItemMetadataQueryIndex(pmRoot)}async function createDerivedIndexDeltaChange(params){if(params.mutation.document===null)return{entry:null,body:null,collections:null};const stat=await fs.stat(params.mutation.itemPath),split=splitHeavyMetadata(params.mutation.document.metadata),signature={mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size};return{entry:{...signature,metadata:split.light,body_length:params.mutation.document.body.length},body:{...signature,body:params.mutation.document.body},collections:{...signature,collections:split.heavy}}}function selectDerivedIndexDeltaChanges(delta,contextFingerprint,baseSourceCursor){return delta?.context_fingerprint===contextFingerprint&&delta.base_source_cursor===baseSourceCursor?structuredClone(delta.changes):{}}async function refreshItemMetadataDerivedIndex(mutation){const relativePath=relativeIndexPath(mutation.pmRoot,mutation.itemPath),previousRelativePath=mutation.previousItemPath?relativeIndexPath(mutation.pmRoot,mutation.previousItemPath):void 0;if(relativePath===null||previousRelativePath===null)return await removeDerivedIndexFiles(mutation.pmRoot),["metadata_derived_index_path_invalidated"];try{const contextFingerprint=computeContextFingerprint(mutation.preferredFormat,mutation.typeToFolder,mutation.schema,resolveActiveExtensionFieldNames()),existingCache=await loadDerivedIndexManifest(mutation.pmRoot);if(existingCache===null||existingCache.context_fingerprint!==contextFingerprint)return[];const baseSourceCursor=existingCache.source_cursor,delta=await loadDerivedIndexDelta(mutation.pmRoot);if(delta.invalid)return await removeDerivedIndexFiles(mutation.pmRoot),["metadata_derived_index_refresh_failed"];const changes=selectDerivedIndexDeltaChanges(delta.envelope,contextFingerprint,baseSourceCursor),expectedSourceCursor=delta.envelope?.context_fingerprint===contextFingerprint&&delta.envelope.base_source_cursor===baseSourceCursor?delta.envelope.source_cursor:baseSourceCursor;previousRelativePath!==void 0&&(changes[previousRelativePath]={entry:null,body:null,collections:null}),changes[relativePath]=await createDerivedIndexDeltaChange({mutation});const sourceCursor=randomUUID();return await persistCache(getDeltaCachePath(mutation.pmRoot),{version:CACHE_VERSION,context_fingerprint:contextFingerprint,base_source_cursor:baseSourceCursor,source_cursor:sourceCursor,directory_signatures:await readDirectorySignatures(mutation.pmRoot,[...new Set(Object.values(mutation.typeToFolder))]),changes}),await updateItemMetadataQueryIndex({pmRoot:mutation.pmRoot,contextFingerprint,expectedSourceCursor,sourceCursor,row:mutation.document===null?null:{relativePath,metadata:splitHeavyMetadata(mutation.document.metadata).light,linkedFiles:mutation.document.metadata.files},deletedRelativePaths:[...previousRelativePath===void 0?[]:[previousRelativePath],...mutation.document===null?[relativePath]:[]]})||await removeItemMetadataQueryIndex(mutation.pmRoot),[]}catch{return await removeDerivedIndexFiles(mutation.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function sortedCachedDocumentCandidates(state){return[...state.documentsById.values()].sort((left,right)=>left.candidate.metadata.id.localeCompare(right.candidate.metadata.id)).map(entry=>entry.candidate)}function cacheTierMatchesContext(envelope,contextFingerprint,sourceCursor){return envelope?.context_fingerprint===contextFingerprint&&envelope.source_cursor===sourceCursor}function hasEveryDerivedIndexPart(keys,includeBody,includeCollections,previousBodies,previousCollections){return keys.every(key=>(!includeBody||previousBodies[key]!==void 0)&&(!includeCollections||previousCollections[key]!==void 0))}function candidatesFromDerivedIndex(params){const candidatesById=new Map;for(const[relativePath,entry]of Object.entries(params.previousEntries)){const itemFormat=getItemFormatFromPath(relativePath);if(!itemFormat)continue;const metadata=params.includeCollections?mergeHeavyMetadata(entry.metadata,params.previousCollections[relativePath]?.collections):entry.metadata,existing=candidatesById.get(metadata.id);shouldRecordCachedDocumentCandidate(existing?.itemFormat,itemFormat,params.preferredFormat)&&candidatesById.set(metadata.id,{itemFormat,candidate:{metadata,body:params.includeBody?params.previousBodies[relativePath]?.body:void 0,item_format:itemFormat,item_path:path.join(params.pmRoot,relativePath)}})}return[...candidatesById.values()].sort((left,right)=>left.candidate.metadata.id.localeCompare(right.candidate.metadata.id)).map(entry=>entry.candidate)}function canUseDerivedIndex(params){return params.forceSourceScan||hasActiveOnReadHooks()||params.existingCache?.context_fingerprint!==params.contextFingerprint||params.entryKeys.length<params.minimumIndexedItems||!directorySignaturesMatch(params.existingCache?.directory_signatures,params.directorySignatures)?!1:[!params.includeBody||cacheTierMatchesContext(params.existingBodyCache,params.contextFingerprint,params.existingCache.source_cursor),!params.includeCollections||cacheTierMatchesContext(params.existingCollectionsCache,params.contextFingerprint,params.existingCache.source_cursor)].every(Boolean)&&hasEveryDerivedIndexPart(params.entryKeys,params.includeBody,params.includeCollections,params.previousBodies,params.previousCollections)}async function listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,options={}){const includeBody=options.includeBody!==!1,includeCollections=options.includeCollections!==!1,extensionFieldNames=resolveActiveExtensionFieldNames(),contextFingerprint=computeContextFingerprint(preferredFormat,typeToFolder,schema,extensionFieldNames),delta=await loadDerivedIndexDelta(pmRoot);delta.invalid&&await removeDerivedIndexFiles(pmRoot);const existingCache=await loadCache(pmRoot,contextFingerprint,options.cacheDiagnostics),existingBodyCache=includeBody?await loadBodyCache(pmRoot,contextFingerprint):null,existingCollectionsCache=includeCollections?await loadCollectionsCache(pmRoot,contextFingerprint):null;applyDerivedIndexDelta(existingCache,existingBodyCache,existingCollectionsCache,delta.envelope);const previousEntries=selectPreviousMetadataEntries(existingCache,contextFingerprint),previousBodies=selectPreviousBodyEntries(existingBodyCache,contextFingerprint),previousCollections=selectPreviousCollectionEntries(existingCollectionsCache,contextFingerprint),folders=[...new Set(Object.values(typeToFolder))],directorySignaturesBefore=await readDirectorySignatures(pmRoot,folders),entryKeys=Object.keys(previousEntries),minimumIndexedItems=Math.max(1,Math.floor(options.derivedIndexMinimumItems??DEFAULT_DERIVED_INDEX_MINIMUM_ITEMS));if(canUseDerivedIndex({forceSourceScan:options.forceSourceScan===!0,contextFingerprint,existingCache,existingBodyCache,existingCollectionsCache,directorySignatures:directorySignaturesBefore,entryKeys,minimumIndexedItems,includeBody,includeCollections,previousBodies,previousCollections}))return candidatesFromDerivedIndex({pmRoot,preferredFormat,includeBody,includeCollections,previousEntries,previousBodies,previousCollections});const dirResults=await Promise.all(folders.map(folder=>readItemDirectoryFiles(pmRoot,folder,warnings))),dispatchReadHooks=hasActiveOnReadHooks(),state=createDocumentCacheMutableState(),context={pmRoot,preferredFormat,warnings,schema,extensionFieldNames,includeBody,includeCollections,forceSourceRead:options.forceSourceScan===!0,dispatchReadHooks,previousEntries,previousBodies,previousCollections,state};await processCachedDocumentFiles(dirResults,context);const directorySignaturesAfter=await readDirectorySignatures(pmRoot,folders),stableDirectorySignatures=directorySignaturesMatch(directorySignaturesBefore,directorySignaturesAfter)?directorySignaturesAfter:{},sourceCursor=state.misses.metadata||Object.keys(previousEntries).length!==Object.keys(state.newEntries).length||!directorySignaturesMatch(existingCache?.directory_signatures,stableDirectorySignatures)||existingCache===null?randomUUID():existingCache.source_cursor;return await persistMetadataCacheIfNeeded({pmRoot,contextFingerprint,sourceCursor,existingCache,previousEntries,directorySignatures:stableDirectorySignatures,state,minimumIndexedItems}),includeBody&&await persistBodyCacheIfNeeded({pmRoot,contextFingerprint,sourceCursor,existingBodyCache,previousBodies,state}),includeCollections&&await persistCollectionsCacheIfNeeded({pmRoot,contextFingerprint,sourceCursor,existingCollectionsCache,previousCollections,state}),sortedCachedDocumentCandidates(state)}async function listAllDocumentsCached(pmRoot,preferredFormat,typeToFolder,warnings,schema){return(await listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,{includeBody:!1})).map(candidate=>({metadata:candidate.metadata,body:candidate.body??""}))}async function listAllDocumentsCachedLight(pmRoot,preferredFormat,typeToFolder,warnings,schema){return(await listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,{includeBody:!1,includeCollections:!1})).map(candidate=>({metadata:candidate.metadata,body:candidate.body??""}))}export{DEFAULT_DERIVED_INDEX_MINIMUM_ITEMS,HEAVY_METADATA_KEYS,acquireItemMetadataDerivedIndexLock,clearItemMetadataEnvelopeMemo,listAllDocumentCandidatesCached,listAllDocumentsCached,listAllDocumentsCachedLight,readItemMetadataDerivedIndexState,refreshItemMetadataDerivedIndex,shouldRecordCachedDocumentCandidate,shouldReplaceCachedDocumentCandidate};
1
+ import l from"node:fs/promises";import d from"node:path";import{createHash as me,randomUUID as K}from"node:crypto";import{getActiveExtensionRegistrations as ye,hasActiveOnReadHooks as V,runActiveOnReadHooks as _e}from"../extensions/index.js";import{collectRegisteredItemFieldNames as ge}from"../extensions/item-fields.js";import{parseItemDocument as he}from"../item/item-format.js";import{evictOldestMemoEntries as Ce}from"../shared/memo.js";import{isFileMissingError as we,writeFileAtomic as Q}from"../fs/fs-utils.js";import{acquireLock as be}from"../lock/lock.js";import{ITEM_FILE_EXTENSIONS as ve,getItemFormatFromPath as Y}from"./paths.js";import{rebuildItemMetadataQueryIndex as Me,removeItemMetadataQueryIndex as L,updateItemMetadataQueryIndex as xe}from"./item-metadata-query-index.js";const y=8,G=500,pe="metadata-derived-index",Ie="metadata-cache.json",Ee="metadata-cache-bodies.json",De="metadata-cache-collections.json",Se="metadata-cache-delta.json",je="metadata-cache-manifest.json",Z=4,Fe=["comments","notes","learnings","files","tests","test_runs","docs"];function ee(){return ge(ye())}function F(e){const n={...e},t={};for(const i of Fe)i in n&&(t[i]=n[i],delete n[i]);return{light:n,heavy:t}}function te(e,n){return!n||Object.keys(n).length===0?e:{...e,...n}}function ne(e,n,t,i){const o=me("sha256");o.update(`format:${e??"default"}`);const s=Object.entries(n).sort(([r],[u])=>r.localeCompare(u)).map(([r,u])=>`${r}=${u}`).join(",");return o.update(`|types:${s}`),t&&o.update(`|schema:${JSON.stringify(t)}`),i.length>0&&o.update(`|extension_fields:${i.join(",")}`),o.digest("hex").slice(0,16)}function O(e){return d.join(e,"runtime",Ie)}function B(e){return d.join(e,"runtime",Ee)}function A(e){return d.join(e,"runtime",De)}function T(e){return d.join(e,"runtime",Se)}function H(e){return d.join(e,"runtime",je)}function N(e,n){const t=d.extname(e);return`${e.slice(0,-t.length)}.${n}${t}`}const Oe=24,f=new Map,k=new WeakMap;function $(e){return k.get(e)??e.source_cursor}function Be(e,n){const t=$(e);if(!(n.base_source_cursor!==t||e.source_cursor===n.source_cursor)){k.set(e,t);for(const[i,o]of Object.entries(n.changes))o.entry?e.entries[i]=o.entry:delete e.entries[i];e.directory_signatures=n.directory_signatures,e.source_cursor=n.source_cursor}}function Ae(e,n){if(!e)return;const t=$(e);if(!(n.base_source_cursor!==t||e.source_cursor===n.source_cursor)){k.set(e,t);for(const[i,o]of Object.entries(n.changes))o.body?e.bodies[i]=o.body:delete e.bodies[i];e.source_cursor=n.source_cursor}}function Ne(e,n){if(!e)return;const t=$(e);if(!(n.base_source_cursor!==t||e.source_cursor===n.source_cursor)){k.set(e,t);for(const[i,o]of Object.entries(n.changes))o.collections?e.collections[i]=o.collections:delete e.collections[i];e.source_cursor=n.source_cursor}}function ke(e,n,t,i){!e||!i||e.context_fingerprint!==i.context_fingerprint||(Be(e,i),Ae(n,i),Ne(t,i))}function P(e,n){f.size>=Oe&&!f.has(e)&&Ce(f),f.set(e,n)}async function w(e,n){let t;try{t=await l.stat(e)}catch{return f.delete(e),null}const i=f.get(e);if(i&&D(i.signature,t.mtimeMs,t.ctimeMs,t.size))return f.delete(e),f.set(e,i),i.envelope;let o;try{o=n(await l.readFile(e,"utf8"))}catch{o=null}return P(e,{signature:{mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size},envelope:o}),o}function bt(){f.clear()}async function ze(e,n,t){const i=u=>{const c=JSON.parse(u);return c.version!==y||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=O(e),s=await w(o,i);if(!n||s===null||s.context_fingerprint===n)return s;const r=await w(N(o,n),i);return r===null&&E(t,`metadata_cache_context_changed:${s.context_fingerprint}->${n}`),r}async function Re(e,n){const t=s=>{const r=JSON.parse(s);return r.version!==y||typeof r.source_cursor!="string"||typeof r.bodies!="object"||r.bodies===null?null:r},i=B(e),o=await w(i,t);return n&&o?.context_fingerprint!==n?await w(N(i,n),t):o}async function Le(e,n){const t=s=>{const r=JSON.parse(s);return r.version!==y||typeof r.source_cursor!="string"||typeof r.collections!="object"||r.collections===null?null:r},i=A(e),o=await w(i,t);return n&&o?.context_fingerprint!==n?await w(N(i,n),t):o}async function J(e){const n=T(e),t=await w(n,i=>{const o=JSON.parse(i);return o.version!==y||typeof o.base_source_cursor!="string"||typeof o.source_cursor!="string"||typeof o.changes!="object"||o.changes===null?null:o});if(t)return{envelope:t,invalid:!1};try{return await l.stat(n),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function q(e){const n=H(e),t=await w(n,i=>{const o=JSON.parse(i);return o.version!==y||typeof o.context_fingerprint!="string"||typeof o.source_cursor!="string"||!Number.isInteger(o.entry_count)||o.entry_count<0||typeof o.directory_signatures!="object"||o.directory_signatures===null?null:o});if(t)return t;try{await l.stat(n),await p(e)}catch{}return null}async function I(e,n){await l.mkdir(d.dirname(e),{recursive:!0}),await Q(e,JSON.stringify(n));try{const i=await l.stat(e);P(e,{signature:{mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size},envelope:n})}catch{f.delete(e)}const t=d.dirname(d.dirname(e));if(e===O(t)||e===B(t)||e===A(t)){const i=N(e,n.context_fingerprint);await Q(i,JSON.stringify(n));try{const c=await l.stat(i);P(i,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:n})}catch{f.delete(i)}const o=d.dirname(e),s=d.extname(e),r=d.basename(e,s),u=(await l.readdir(o,{withFileTypes:!0}).catch(()=>[])).filter(c=>c.isFile()&&c.name!==d.basename(e)&&c.name.startsWith(`${r}.`)&&c.name.endsWith(s)).map(c=>d.join(o,c.name));if(u.length>Z){const c=(await Promise.all(u.map(async a=>{try{return{path:a,mtime:(await l.stat(a)).mtimeMs}}catch{return null}}))).filter(a=>a!==null);for(const a of c.sort((_,m)=>_.mtime-m.mtime).slice(0,Math.max(0,c.length-Z)))await l.rm(a.path,{force:!0}),f.delete(a.path)}}}function Te(e,n,t){return t?n===t&&e!==t:n==="toon"&&e!=="toon"}function ie(e,n,t){return e===void 0||Te(e,n,t)}function E(e,n){e&&!e.includes(n)&&e.push(n)}function D(e,n,t,i){return e.mtime_ms===n&&e.ctime_ms===t&&e.size===i}async function He(e,n,t){const i=d.join(e,n);try{const o=await l.readdir(i);return{folder:n,dirPath:i,files:o}}catch(o){return typeof o=="object"&&o!==null&&"code"in o&&!we(o)&&E(t,`item_list_directory_read_failed:${n}`),{folder:n,dirPath:i,files:[]}}}async function $e(e,n){try{const t=await l.stat(d.join(e,n));return[n,{exists:!0,mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size}]}catch{return[n,{exists:!1,mtime_ms:0,ctime_ms:0,size:0}]}}async function z(e,n){return Object.fromEntries(await Promise.all(n.map(async t=>await $e(e,t))))}function S(e,n){return!e||Object.keys(e).length!==Object.keys(n).length?!1:Object.entries(n).every(([t,i])=>{const o=e[t];return o!==void 0&&o.exists===i.exists&&D(o,i.mtime_ms,i.ctime_ms,i.size)})}function Pe(e){return ve.some(n=>e.toLowerCase().endsWith(n))}function Je(e,n,t,i,o,s){i||(e.metadata=!0),n&&!o&&(e.body=!0),t&&!s&&(e.collections=!0)}async function qe(e,n,t){if(t)for(const i of await _e({path:e,scope:"project"}))E(n,i)}function oe(e,n,t,i){if(e)return n&&t?t.collections:i}async function Ue(e,n,t){const i=await l.stat(e),o=i.mtimeMs,s=i.ctimeMs,{size:r}=i,u=Y(e);await qe(e,t.warnings,t.dispatchReadHooks);const c=t.previousEntries[n],a=!t.forceSourceRead&&c!==void 0&&D(c,o,s,r),_=t.previousBodies[n],m=!t.forceSourceRead&&_!==void 0&&D(_,o,s,r),g=t.previousCollections[n],h=!t.forceSourceRead&&g!==void 0&&D(g,o,s,r);if(!(!a||t.includeBody&&!m||t.includeCollections&&!h))return{mtimeMs:o,ctimeMs:s,size:r,itemFormat:u,lightMetadata:c.metadata,heavyMetadata:oe(t.includeCollections,h,g,void 0),bodyLength:c.body_length,body:t.includeBody?_.body:void 0};const M=await l.readFile(e,"utf8"),C=he(M,{format:u,schema:t.schema,extensionFieldNames:t.extensionFieldNames,onWarning:j=>E(t.warnings,j)}),x=F(C.metadata);return Je(t.state.misses,t.includeBody,t.includeCollections,a,m,h),{mtimeMs:o,ctimeMs:s,size:r,itemFormat:u,lightMetadata:a?c.metadata:x.light,heavyMetadata:oe(t.includeCollections,h,g,x.heavy),bodyLength:a?c.body_length:C.body.length,body:t.includeBody?C.body:void 0}}function We(e,n,t,i){t.state.newEntries[n]={mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size,metadata:i.lightMetadata,body_length:i.bodyLength},t.includeBody&&i.body!==void 0&&(t.state.newBodies[n]={mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size,body:i.body}),t.includeCollections&&i.heavyMetadata!==void 0&&(t.state.newCollections[n]={mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size,collections:i.heavyMetadata});const o=t.includeCollections?te(i.lightMetadata,i.heavyMetadata):i.lightMetadata,s=t.state.documentsById.get(o.id),r={metadata:o,body:i.body,item_format:i.itemFormat,item_path:e};ie(s?.itemFormat,i.itemFormat,t.preferredFormat)&&t.state.documentsById.set(o.id,{candidate:r,itemFormat:i.itemFormat})}async function Xe(e,n,t,i){try{const o=await Ue(n,t,i);We(n,t,i,o)}catch{E(i.warnings,`item_list_item_read_failed:${e}/${d.basename(n)}`)}}function Ke(e,n){return e&&e.context_fingerprint===n?e.entries:{}}function Ve(e,n){return e&&e.context_fingerprint===n?e.bodies:{}}function Qe(e,n){return e&&e.context_fingerprint===n?e.collections:{}}function Ye(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}async function Ge(e,n){const t=[];for(const{folder:i,dirPath:o,files:s}of e)for(const r of s){if(!Pe(r))continue;const u=d.join(o,r),c=d.relative(n.pmRoot,u);t.push(Xe(i,u,c,n)),t.length===32&&(await Promise.all(t),t.length=0)}await Promise.all(t)}async function Ze(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!S(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await I(O(e.pmRoot),{version:y,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await I(H(e.pmRoot),{version:y,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,entry_count:Object.keys(e.state.newEntries).length,directory_signatures:e.directorySignatures});const t=[...e.state.documentsById.values()].map(({candidate:i})=>({relativePath:d.relative(e.pmRoot,i.item_path),metadata:F(i.metadata).light,linkedFiles:i.metadata.files??[]}));t.length>=e.minimumIndexedItems?await Me({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:t}):await L(e.pmRoot)}catch{}}async function et(e){!(e.state.misses.body||Object.keys(e.previousBodies).length!==Object.keys(e.state.newBodies).length)&&e.existingBodyCache!==null&&e.existingBodyCache.context_fingerprint===e.contextFingerprint||await I(B(e.pmRoot),{version:y,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function tt(e){!(e.state.misses.collections||Object.keys(e.previousCollections).length!==Object.keys(e.state.newCollections).length)&&e.existingCollectionsCache!==null&&e.existingCollectionsCache.context_fingerprint===e.contextFingerprint||await I(A(e.pmRoot),{version:y,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function vt(e,n,t={}){const i=await q(e);return t.required!==!0&&(i===null||i.entry_count<G)?async()=>{}:be(e,pe,30,n,!1,!1,3e3)}async function Mt(e,n){const t=await q(e);if(t===null)return null;const i=await J(e);if(i.invalid)return await p(e),null;const o=i.envelope?.context_fingerprint===t.context_fingerprint&&i.envelope.base_source_cursor===t.source_cursor?i.envelope.source_cursor:t.source_cursor,s=i.envelope?.context_fingerprint===t.context_fingerprint&&i.envelope.base_source_cursor===t.source_cursor?i.envelope.directory_signatures:t.directory_signatures;return n&&!S(s,await z(e,n))?null:{source_cursor:o,entry_count:t.entry_count}}function re(e,n){const t=d.relative(e,n);return t===""||t===".."||t.startsWith(`..${d.sep}`)||d.isAbsolute(t)?null:t}async function p(e){await Promise.all([O(e),B(e),A(e),T(e),H(e)].map(async n=>{await l.rm(n,{force:!0}),f.delete(n)})),await L(e)}async function nt(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};const n=await l.stat(e.mutation.itemPath),t=F(e.mutation.document.metadata),i={mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size};return{entry:{...i,metadata:t.light,body_length:e.mutation.document.body.length},body:{...i,body:e.mutation.document.body},collections:{...i,collections:t.heavy}}}function it(e,n,t){return e?.context_fingerprint===n&&e.base_source_cursor===t?structuredClone(e.changes):{}}async function xt(e){const n=re(e.pmRoot,e.itemPath),t=e.previousItemPath?re(e.pmRoot,e.previousItemPath):void 0;if(n===null||t===null)return await p(e.pmRoot),["metadata_derived_index_path_invalidated"];try{const i=ne(e.preferredFormat,e.typeToFolder,e.schema,ee()),o=await q(e.pmRoot);if(o===null||o.context_fingerprint!==i)return[];const s=o.source_cursor,r=await J(e.pmRoot);if(r.invalid)return await p(e.pmRoot),["metadata_derived_index_refresh_failed"];const u=it(r.envelope,i,s),c=r.envelope?.context_fingerprint===i&&r.envelope.base_source_cursor===s?r.envelope.source_cursor:s;t!==void 0&&(u[t]={entry:null,body:null,collections:null}),u[n]=await nt({mutation:e});const a=K();return await I(T(e.pmRoot),{version:y,context_fingerprint:i,base_source_cursor:s,source_cursor:a,directory_signatures:await z(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:u}),await xe({pmRoot:e.pmRoot,contextFingerprint:i,expectedSourceCursor:c,sourceCursor:a,row:e.document===null?null:{relativePath:n,metadata:F(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...t===void 0?[]:[t],...e.document===null?[n]:[]]})||await L(e.pmRoot),[]}catch{return await p(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function ot(e){return[...e.documentsById.values()].sort((n,t)=>n.candidate.metadata.id.localeCompare(t.candidate.metadata.id)).map(n=>n.candidate)}function se(e,n,t){return e?.context_fingerprint===n&&e.source_cursor===t}function rt(e,n,t,i,o){return e.every(s=>(!n||i[s]!==void 0)&&(!t||o[s]!==void 0))}function st(e){const n=new Map;for(const[t,i]of Object.entries(e.previousEntries)){const o=Y(t);if(!o)continue;const s=e.includeCollections?te(i.metadata,e.previousCollections[t]?.collections):i.metadata,r=n.get(s.id);ie(r?.itemFormat,o,e.preferredFormat)&&n.set(s.id,{itemFormat:o,candidate:{metadata:s,body:e.includeBody?e.previousBodies[t]?.body:void 0,item_format:o,item_path:d.join(e.pmRoot,t)}})}return[...n.values()].sort((t,i)=>t.candidate.metadata.id.localeCompare(i.candidate.metadata.id)).map(t=>t.candidate)}function ct(e){return e.forceSourceScan||V()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!S(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||se(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||se(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&rt(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function ce(e,n,t,i,o,s={}){const r=s.includeBody!==!1,u=s.includeCollections!==!1,c=ee(),a=ne(n,t,o,c),_=await J(e);_.invalid&&await p(e);const m=await ze(e,a,s.cacheDiagnostics),g=r?await Re(e,a):null,h=u?await Le(e,a):null;ke(m,g,h,_.envelope);const v=Ke(m,a),M=Ve(g,a),C=Qe(h,a),x=[...new Set(Object.values(t))],j=await z(e,x),ae=Object.keys(v),U=Math.max(1,Math.floor(s.derivedIndexMinimumItems??G));if(ct({forceSourceScan:s.forceSourceScan===!0,contextFingerprint:a,existingCache:m,existingBodyCache:g,existingCollectionsCache:h,directorySignatures:j,entryKeys:ae,minimumIndexedItems:U,includeBody:r,includeCollections:u,previousBodies:M,previousCollections:C}))return st({pmRoot:e,preferredFormat:n,includeBody:r,includeCollections:u,previousEntries:v,previousBodies:M,previousCollections:C});const ue=await Promise.all(x.map(fe=>He(e,fe,i))),de=V(),b=Ye(),le={pmRoot:e,preferredFormat:n,warnings:i,schema:o,extensionFieldNames:c,includeBody:r,includeCollections:u,forceSourceRead:s.forceSourceScan===!0,dispatchReadHooks:de,previousEntries:v,previousBodies:M,previousCollections:C,state:b};await Ge(ue,le);const W=await z(e,x),X=S(j,W)?W:{},R=b.misses.metadata||Object.keys(v).length!==Object.keys(b.newEntries).length||!S(m?.directory_signatures,X)||m===null?K():m.source_cursor;return await Ze({pmRoot:e,contextFingerprint:a,sourceCursor:R,existingCache:m,previousEntries:v,directorySignatures:X,state:b,minimumIndexedItems:U}),r&&await et({pmRoot:e,contextFingerprint:a,sourceCursor:R,existingBodyCache:g,previousBodies:M,state:b}),u&&await tt({pmRoot:e,contextFingerprint:a,sourceCursor:R,existingCollectionsCache:h,previousCollections:C,state:b}),ot(b)}async function pt(e,n,t,i,o){return(await ce(e,n,t,i,o,{includeBody:!1})).map(r=>({metadata:r.metadata,body:r.body??""}))}async function It(e,n,t,i,o){return(await ce(e,n,t,i,o,{includeBody:!1,includeCollections:!1})).map(r=>({metadata:r.metadata,body:r.body??""}))}export{G as DEFAULT_DERIVED_INDEX_MINIMUM_ITEMS,Fe as HEAVY_METADATA_KEYS,vt as acquireItemMetadataDerivedIndexLock,bt as clearItemMetadataEnvelopeMemo,ce as listAllDocumentCandidatesCached,pt as listAllDocumentsCached,It as listAllDocumentsCachedLight,Mt as readItemMetadataDerivedIndexState,xt as refreshItemMetadataDerivedIndex,ie as shouldRecordCachedDocumentCandidate,Te as shouldReplaceCachedDocumentCandidate};
2
2
  //# sourceMappingURL=item-metadata-cache.js.map
@@ -1,4 +1,4 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="84a3dae8-69b6-589d-a8ec-11f77c1d103a")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{randomUUID}from"node:crypto";import{createRequire}from"node:module";import{loadDatabaseSync,loadStableDatabaseSync}from"./sqlite-runtime.js";const QUERY_INDEX_FILENAME="metadata-query-index.sqlite",QUERY_INDEX_VERSION="5";let RuntimeDatabaseSync;function resolveDatabaseSync(){return RuntimeDatabaseSync!==void 0||(RuntimeDatabaseSync=loadStableDatabaseSync(process.versions.node,createRequire(import.meta.url))),RuntimeDatabaseSync}function normalizeIndexWindowValue(value,fallback){return Math.max(0,Math.floor(value===void 0?fallback:value))}function queryIndexPath(pmRoot){return path.join(pmRoot,"runtime",QUERY_INDEX_FILENAME)}function createSchema(database){database.exec(`
1
+ import E from"node:fs/promises";import C from"node:path";import{randomUUID as w}from"node:crypto";import{createRequire as g}from"node:module";import{loadDatabaseSync as k,loadStableDatabaseSync as A}from"./sqlite-runtime.js";const F="metadata-query-index.sqlite",_="5";let m;function f(){return m!==void 0||(m=A(process.versions.node,g(import.meta.url))),m}function M(e,r){return Math.max(0,Math.floor(e===void 0?r:e))}function p(e){return C.join(e,"runtime",F)}function U(e){e.exec(`
2
2
  PRAGMA foreign_keys = ON;
3
3
  PRAGMA journal_mode = OFF;
4
4
  PRAGMA synchronous = OFF;
@@ -53,7 +53,7 @@
53
53
  tags,
54
54
  tokenize = 'unicode61'
55
55
  );
56
- `)}function writeMetadata(database,key,value){database.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(key,value)}function insertRow(database,row){const metadata=row.metadata;database.prepare(`INSERT INTO items(
56
+ `)}function S(e,r,t){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(r,t)}function x(e,r){const t=r.metadata;e.prepare(`INSERT INTO items(
57
57
  id, relative_path, metadata_json, status, type, priority,
58
58
  updated_at, created_at, parent, assignee, sprint, release
59
59
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -68,24 +68,24 @@
68
68
  parent = excluded.parent,
69
69
  assignee = excluded.assignee,
70
70
  sprint = excluded.sprint,
71
- release = excluded.release`).run(metadata.id,row.relativePath,JSON.stringify(metadata),metadata.status,metadata.type,metadata.priority,metadata.updated_at,metadata.created_at,metadata.parent??null,metadata.assignee??null,metadata.sprint??null,metadata.release??null),database.prepare("DELETE FROM item_metadata_keys WHERE item_id = ?").run(metadata.id),database.prepare("DELETE FROM item_linked_files WHERE item_id = ?").run(metadata.id),database.prepare("DELETE FROM item_search WHERE rowid = (SELECT rowid FROM items WHERE id = ?)").run(metadata.id),database.prepare("INSERT INTO item_search(rowid, id, title, description, tags) SELECT rowid, ?, ?, ?, ? FROM items WHERE id = ?").run(metadata.id,metadata.title,metadata.description,metadata.tags.join(" "),metadata.id);const insertMetadataKey=database.prepare("INSERT INTO item_metadata_keys(item_id, key) VALUES (?, ?)");for(const key of Object.keys(metadata))insertMetadataKey.run(metadata.id,key);const insertLinkedFile=database.prepare("INSERT INTO item_linked_files(item_id, path, scope, note) VALUES (?, ?, ?, ?)");for(const file of row.linkedFiles??[])insertLinkedFile.run(metadata.id,file.path,file.scope,file.note??null)}async function rebuildItemMetadataQueryIndex(options){const targetPath=queryIndexPath(options.pmRoot),Database=resolveDatabaseSync();if(!Database){await fs.rm(targetPath,{force:!0});return}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"),writeMetadata(database,"version",QUERY_INDEX_VERSION),writeMetadata(database,"context_fingerprint",options.contextFingerprint),writeMetadata(database,"source_cursor",options.sourceCursor);for(const row of options.rows)insertRow(database,row);database.exec("COMMIT"),database.close(),database=void 0,await fs.rm(targetPath,{force:!0}),await fs.rename(temporaryPath,targetPath)}catch(error){throw database?.close(),await Promise.allSettled([fs.rm(temporaryPath,{force:!0})]),error}}function readIndexMetadata(database){return Object.fromEntries(database.prepare("SELECT key, value FROM metadata").all().map(row=>[String(row.key),String(row.value)]))}async function updateItemMetadataQueryIndex(options){const Database=resolveDatabaseSync();if(!Database)return!1;const indexPath=queryIndexPath(options.pmRoot);let database;try{await fs.access(indexPath),database=new Database(indexPath),database.exec("PRAGMA foreign_keys = ON");const metadata=readIndexMetadata(database);if(metadata.version!==QUERY_INDEX_VERSION||metadata.context_fingerprint!==options.contextFingerprint||metadata.source_cursor!==options.expectedSourceCursor)return database.close(),!1;database.exec("BEGIN IMMEDIATE");const deleteByPath=database.prepare("DELETE FROM items WHERE relative_path = ?"),findRowidByPath=database.prepare("SELECT rowid FROM items WHERE relative_path = ?"),deleteSearchByRowid=database.prepare("DELETE FROM item_search WHERE rowid = ?");for(const relativePath of options.deletedRelativePaths??[]){const deleted=findRowidByPath.get(relativePath);deleteByPath.run(relativePath),deleted&&deleteSearchByRowid.run(deleted.rowid)}return options.row&&insertRow(database,options.row),writeMetadata(database,"source_cursor",options.sourceCursor),database.exec("COMMIT"),database.close(),!0}catch{try{database?.exec("ROLLBACK")}catch{}return database?.close(),!1}}function appendSetPredicate(clauses,parameters,column,values,operator){!values||values.length===0||(clauses.push(`${column} ${operator} (${values.map(()=>"?").join(", ")})`),parameters.push(...values))}function buildQueryPredicates(query){const clauses=[],parameters=[];appendSetPredicate(clauses,parameters,"status",query.statuses,"IN"),appendSetPredicate(clauses,parameters,"status",query.excludeStatuses,"NOT IN"),appendSetPredicate(clauses,parameters,"type",query.types,"IN"),appendSetPredicate(clauses,parameters,"id",query.ids,"IN");for(const metadataKey of query.metadataKeys??[])clauses.push("EXISTS (SELECT 1 FROM item_metadata_keys AS indexed_key WHERE indexed_key.item_id = items.id AND indexed_key.key = ?)"),parameters.push(metadataKey);for(const[column,value]of[["parent",query.parent],["assignee",query.assignee],["sprint",query.sprint],["release",query.release]])value!==void 0&&(clauses.push(`${column} = ?`),parameters.push(value));return query.priority!==void 0&&(clauses.push("priority = ?"),parameters.push(query.priority)),{where:clauses.length===0?"":` WHERE ${clauses.join(" AND ")}`,parameters}}async function queryItemMetadataIndex(options){const Database=resolveDatabaseSync();if(!Database)return null;const query=options.query??{},{where,parameters}=buildQueryPredicates(query);let database;try{database=new Database(queryIndexPath(options.pmRoot),{readOnly:!0});const metadata=readIndexMetadata(database);if(metadata.version!==QUERY_INDEX_VERSION||metadata.source_cursor!==options.expectedSourceCursor)return database.close(),null;const totalRow=database.prepare(`SELECT COUNT(*) AS count FROM items${where}`).get(...parameters),windowParameters=[];let window2="";query.limit!==void 0?(window2+=" LIMIT ?",windowParameters.push(Math.max(0,Math.floor(query.limit))),query.offset!==void 0&&(window2+=" OFFSET ?",windowParameters.push(Math.max(0,Math.floor(query.offset))))):query.offset!==void 0&&(window2+=" LIMIT -1 OFFSET ?",windowParameters.push(Math.max(0,Math.floor(query.offset))));const items=database.prepare(`SELECT metadata_json FROM items${where}
72
- ORDER BY ${query.terminalStatuses&&query.terminalStatuses.length>0?`CASE WHEN status IN (${query.terminalStatuses.map(()=>"?").join(", ")}) THEN 1 ELSE 0 END ASC, `:""}priority ASC, updated_at DESC, id ASC${window2}`).all(...parameters,...query.terminalStatuses??[],...windowParameters).map(row=>{const parsed=JSON.parse(String(row.metadata_json));if(!parsed.id)throw new TypeError("Indexed metadata row has no id");return parsed});return database.close(),{source_cursor:metadata.source_cursor,total:Number(totalRow.count),items}}catch{return database?.close(),null}}async function queryLinkedFileMetadataIndex(options){const Database=resolveDatabaseSync();if(!Database||options.paths.length===0)return null;let database;try{database=new Database(queryIndexPath(options.pmRoot),{readOnly:!0});const metadata=readIndexMetadata(database);if(metadata.version!==QUERY_INDEX_VERSION||metadata.source_cursor!==options.expectedSourceCursor)return database.close(),null;const pathPlaceholders=options.paths.map(()=>"?").join(", "),scopePredicate=options.scope===void 0?"":" AND scope = ?",matchParameters=[...options.paths,...options.scope===void 0?[]:[options.scope]],predicate=`path IN (${pathPlaceholders})${scopePredicate}`,totalRow=database.prepare(`SELECT COUNT(DISTINCT item_id) AS count
71
+ release = excluded.release`).run(t.id,r.relativePath,JSON.stringify(t),t.status,t.type,t.priority,t.updated_at,t.created_at,t.parent??null,t.assignee??null,t.sprint??null,t.release??null),e.prepare("DELETE FROM item_metadata_keys WHERE item_id = ?").run(t.id),e.prepare("DELETE FROM item_linked_files WHERE item_id = ?").run(t.id),e.prepare("DELETE FROM item_search WHERE rowid = (SELECT rowid FROM items WHERE id = ?)").run(t.id),e.prepare("INSERT INTO item_search(rowid, id, title, description, tags) SELECT rowid, ?, ?, ?, ? FROM items WHERE id = ?").run(t.id,t.title,t.description,t.tags.join(" "),t.id);const a=e.prepare("INSERT INTO item_metadata_keys(item_id, key) VALUES (?, ?)");for(const s of Object.keys(t))a.run(t.id,s);const i=e.prepare("INSERT INTO item_linked_files(item_id, path, scope, note) VALUES (?, ?, ?, ?)");for(const s of r.linkedFiles??[])i.run(t.id,s.path,s.scope,s.note??null)}async function b(e){const r=p(e.pmRoot),t=f();if(!t){await E.rm(r,{force:!0});return}await E.mkdir(C.dirname(r),{recursive:!0});const a=`${r}.${w()}.tmp`;let i;try{i=new t(a),U(i),i.exec("BEGIN IMMEDIATE"),S(i,"version",_),S(i,"context_fingerprint",e.contextFingerprint),S(i,"source_cursor",e.sourceCursor);for(const s of e.rows)x(i,s);i.exec("COMMIT"),i.close(),i=void 0,await E.rm(r,{force:!0}),await E.rename(a,r)}catch(s){throw i?.close(),await Promise.allSettled([E.rm(a,{force:!0})]),s}}function h(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(r=>[String(r.key),String(r.value)]))}async function W(e){const r=f();if(!r)return!1;const t=p(e.pmRoot);let a;try{await E.access(t),a=new r(t),a.exec("PRAGMA foreign_keys = ON");const i=h(a);if(i.version!==_||i.context_fingerprint!==e.contextFingerprint||i.source_cursor!==e.expectedSourceCursor)return a.close(),!1;a.exec("BEGIN IMMEDIATE");const s=a.prepare("DELETE FROM items WHERE relative_path = ?"),o=a.prepare("SELECT rowid FROM items WHERE relative_path = ?"),u=a.prepare("DELETE FROM item_search WHERE rowid = ?");for(const d of e.deletedRelativePaths??[]){const c=o.get(d);s.run(d),c&&u.run(c.rowid)}return e.row&&x(a,e.row),S(a,"source_cursor",e.sourceCursor),a.exec("COMMIT"),a.close(),!0}catch{try{a?.exec("ROLLBACK")}catch{}return a?.close(),!1}}function I(e,r,t,a,i){!a||a.length===0||(e.push(`${t} ${i} (${a.map(()=>"?").join(", ")})`),r.push(...a))}function X(e){const r=[],t=[];I(r,t,"status",e.statuses,"IN"),I(r,t,"status",e.excludeStatuses,"NOT IN"),I(r,t,"type",e.types,"IN"),I(r,t,"id",e.ids,"IN");for(const a of e.metadataKeys??[])r.push("EXISTS (SELECT 1 FROM item_metadata_keys AS indexed_key WHERE indexed_key.item_id = items.id AND indexed_key.key = ?)"),t.push(a);for(const[a,i]of[["parent",e.parent],["assignee",e.assignee],["sprint",e.sprint],["release",e.release]])i!==void 0&&(r.push(`${a} = ?`),t.push(i));return e.priority!==void 0&&(r.push("priority = ?"),t.push(e.priority)),{where:r.length===0?"":` WHERE ${r.join(" AND ")}`,parameters:t}}async function B(e){const r=f();if(!r)return null;const t=e.query??{},{where:a,parameters:i}=X(t);let s;try{s=new r(p(e.pmRoot),{readOnly:!0});const o=h(s);if(o.version!==_||o.source_cursor!==e.expectedSourceCursor)return s.close(),null;const u=s.prepare(`SELECT COUNT(*) AS count FROM items${a}`).get(...i),d=[];let c="";t.limit!==void 0?(c+=" LIMIT ?",d.push(Math.max(0,Math.floor(t.limit))),t.offset!==void 0&&(c+=" OFFSET ?",d.push(Math.max(0,Math.floor(t.offset))))):t.offset!==void 0&&(c+=" LIMIT -1 OFFSET ?",d.push(Math.max(0,Math.floor(t.offset))));const T=s.prepare(`SELECT metadata_json FROM items${a}
72
+ ORDER BY ${t.terminalStatuses&&t.terminalStatuses.length>0?`CASE WHEN status IN (${t.terminalStatuses.map(()=>"?").join(", ")}) THEN 1 ELSE 0 END ASC, `:""}priority ASC, updated_at DESC, id ASC${c}`).all(...i,...t.terminalStatuses??[],...d).map(R=>{const l=JSON.parse(String(R.metadata_json));if(!l.id)throw new TypeError("Indexed metadata row has no id");return l});return s.close(),{source_cursor:o.source_cursor,total:Number(u.count),items:T}}catch{return s?.close(),null}}async function Y(e){const r=f();if(!r||e.paths.length===0)return null;let t;try{t=new r(p(e.pmRoot),{readOnly:!0});const a=h(t);if(a.version!==_||a.source_cursor!==e.expectedSourceCursor)return t.close(),null;const i=e.paths.map(()=>"?").join(", "),s=e.scope===void 0?"":" AND scope = ?",o=[...e.paths,...e.scope===void 0?[]:[e.scope]],u=`path IN (${i})${s}`,d=t.prepare(`SELECT COUNT(DISTINCT item_id) AS count
73
73
  FROM item_linked_files
74
- WHERE ${predicate}`).get(...matchParameters),limit=normalizeIndexWindowValue(options.limit,50),offset=normalizeIndexWindowValue(options.offset,0),itemRows=database.prepare(`SELECT items.id, items.metadata_json
74
+ WHERE ${u}`).get(...o),c=M(e.limit,50),O=M(e.offset,0),T=t.prepare(`SELECT items.id, items.metadata_json
75
75
  FROM items
76
76
  WHERE EXISTS (
77
77
  SELECT 1 FROM item_linked_files
78
- WHERE item_linked_files.item_id = items.id AND ${predicate}
78
+ WHERE item_linked_files.item_id = items.id AND ${u}
79
79
  )
80
80
  ORDER BY items.priority ASC, items.updated_at DESC, items.id ASC
81
- LIMIT ? OFFSET ?`).all(...matchParameters,limit,offset),matches=[];if(itemRows.length>0){const itemIds=itemRows.map(row=>String(row.id)),linkedRows=database.prepare(`SELECT item_id, path, scope, note
81
+ LIMIT ? OFFSET ?`).all(...o,c,O),R=[];if(T.length>0){const l=T.map(n=>String(n.id)),D=t.prepare(`SELECT item_id, path, scope, note
82
82
  FROM item_linked_files
83
- WHERE item_id IN (${itemIds.map(()=>"?").join(", ")})
84
- AND ${predicate}
85
- ORDER BY path ASC, scope ASC`).all(...itemIds,...matchParameters),filesByItem=new Map(itemIds.map(itemId=>[itemId,[]]));for(const row of linkedRows){const itemId=String(row.item_id),files=filesByItem.get(itemId);files.push({path:String(row.path),scope:String(row.scope),...row.note===null?{}:{note:String(row.note)}}),filesByItem.set(itemId,files)}for(const row of itemRows){const item=JSON.parse(String(row.metadata_json));matches.push({item,files:filesByItem.get(String(row.id))})}}return database.close(),{source_cursor:metadata.source_cursor,total:Number(totalRow.count),matches}}catch{return database?.close(),null}}async function querySimilarItemMetadataIndex(options){const Database=resolveDatabaseSync();if(!Database)return null;let database;try{database=new Database(queryIndexPath(options.pmRoot),{readOnly:!0});const metadata=readIndexMetadata(database);if(metadata.version!==QUERY_INDEX_VERSION||metadata.source_cursor!==options.expectedSourceCursor)return database.close(),null;const items=database.prepare(`SELECT items.metadata_json
83
+ WHERE item_id IN (${l.map(()=>"?").join(", ")})
84
+ AND ${u}
85
+ ORDER BY path ASC, scope ASC`).all(...l,...o),y=new Map(l.map(n=>[n,[]]));for(const n of D){const N=String(n.item_id),L=y.get(N);L.push({path:String(n.path),scope:String(n.scope),...n.note===null?{}:{note:String(n.note)}}),y.set(N,L)}for(const n of T){const N=JSON.parse(String(n.metadata_json));R.push({item:N,files:y.get(String(n.id))})}}return t.close(),{source_cursor:a.source_cursor,total:Number(d.count),matches:R}}catch{return t?.close(),null}}async function G(e){const r=f();if(!r)return null;let t;try{t=new r(p(e.pmRoot),{readOnly:!0});const a=h(t);if(a.version!==_||a.source_cursor!==e.expectedSourceCursor)return t.close(),null;const s=t.prepare(`SELECT items.metadata_json
86
86
  FROM item_search
87
87
  JOIN items ON items.id = item_search.id
88
88
  WHERE item_search MATCH ?
89
89
  ORDER BY bm25(item_search), items.priority, items.updated_at DESC, items.id
90
- LIMIT ?`).all(options.query,Math.max(0,Math.floor(options.limit))).map(row=>JSON.parse(String(row.metadata_json)));return database.close(),{source_cursor:metadata.source_cursor,items}}catch{return database?.close(),null}}async function removeItemMetadataQueryIndex(pmRoot){await fs.rm(queryIndexPath(pmRoot),{force:!0})}const _testOnly={loadDatabaseSync,loadStableDatabaseSync,setDatabaseSync(databaseSync){const previous=RuntimeDatabaseSync;return RuntimeDatabaseSync=databaseSync,()=>{RuntimeDatabaseSync=previous}}};export{_testOnly,queryItemMetadataIndex,queryLinkedFileMetadataIndex,querySimilarItemMetadataIndex,rebuildItemMetadataQueryIndex,removeItemMetadataQueryIndex,updateItemMetadataQueryIndex};
90
+ LIMIT ?`).all(e.query,Math.max(0,Math.floor(e.limit))).map(o=>JSON.parse(String(o.metadata_json)));return t.close(),{source_cursor:a.source_cursor,items:s}}catch{return t?.close(),null}}async function K(e){await E.rm(p(e),{force:!0})}const Q={loadDatabaseSync:k,loadStableDatabaseSync:A,setDatabaseSync(e){const r=m;return m=e,()=>{m=r}}};export{Q as _testOnly,B as queryItemMetadataIndex,Y as queryLinkedFileMetadataIndex,G as querySimilarItemMetadataIndex,b as rebuildItemMetadataQueryIndex,K as removeItemMetadataQueryIndex,W as updateItemMetadataQueryIndex};
91
91
  //# sourceMappingURL=item-metadata-query-index.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b2b2d49a-bb8c-54d7-89d2-1dbe76879129")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{channel}from"node:diagnostics_channel";const observers=new AsyncLocalStorage,enumerations=channel("@unbrained/pm-cli/item-metadata-enumeration/v1");function recordItemMetadataEnumeration(rowCount){enumerations.publish(rowCount)}async function measureItemMetadataReadWork(operation){const work={enumeration_calls:0,metadata_rows:0},observe=message=>{observers.getStore()?.includes(work)&&(work.enumeration_calls+=1,work.metadata_rows+=message)};enumerations.subscribe(observe);try{return{result:await observers.run([...observers.getStore()??[],work],operation),work:{...work}}}finally{enumerations.unsubscribe(observe)}}export{measureItemMetadataReadWork,recordItemMetadataEnumeration};
1
+ import{AsyncLocalStorage as s}from"node:async_hooks";import{channel as i}from"node:diagnostics_channel";const r=new s,a=i("@unbrained/pm-cli/item-metadata-enumeration/v1");function m(t){a.publish(t)}async function l(t){const e={enumeration_calls:0,metadata_rows:0},n=o=>{r.getStore()?.includes(e)&&(e.enumeration_calls+=1,e.metadata_rows+=o)};a.subscribe(n);try{return{result:await r.run([...r.getStore()??[],e],t),work:{...e}}}finally{a.unsubscribe(n)}}export{l as measureItemMetadataReadWork,m as recordItemMetadataEnumeration};
2
2
  //# sourceMappingURL=item-metadata-read-work.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="bc6de6a9-454a-5dda-ab67-8f4a2f5c38d8")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{realpathSync}from"node:fs";import path from"node:path";import{hashDocument}from"../history/history.js";import{sha256Hex}from"../shared/serialization.js";import{renderPmCommand}from"../shared/command-line.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const preconditions=new AsyncLocalStorage;function runWithItemMutationPrecondition(condition,operation){return preconditions.run([...preconditions.getStore()??[],{...condition,pmRoot:path.resolve(condition.pmRoot)}],operation)}const REVISION_SCOPES_KEY=Symbol.for("@unbrained/pm-cli/item-revision-scopes"),revisionScopeRegistry=globalThis,revisionScopes=revisionScopeRegistry[REVISION_SCOPES_KEY]??=new AsyncLocalStorage;function canonicalTrackerRoot(pmRoot){const resolved=path.resolve(pmRoot);try{return realpathSync.native(resolved)}catch{return resolved}}function createItemRevisionScope(){return{entries:new Map}}function runWithItemRevisionScope(scope,operation){return revisionScopes.run([...revisionScopes.getStore()??[],scope],operation)}function bindItemRevisionScope(scope,pmRoot,expectations){const resolvedRoot=canonicalTrackerRoot(pmRoot);if(scope.pmRoot!==void 0&&scope.pmRoot!==resolvedRoot)throw new PmCliError("An expected-revision scope is already bound to another tracker.",EXIT_CODE.USAGE,{code:"expected_revision_scope_conflict",required:"Bind expected item revisions for one tracker per scope."});scope.pmRoot=resolvedRoot;for(const{id,itemHash}of expectations){const existing=scope.entries.get(id);if(existing!==void 0&&existing.declared!==itemHash)throw new PmCliError(`Item ${id} has two different expected revisions.`,EXIT_CODE.USAGE,{code:"expected_revision_duplicate",item_id:id,required:"Declare at most one expected revision per item."});scope.entries.set(id,existing??{declared:itemHash,expected:itemHash,checked:!1,committed:!1})}}function itemRevisionScopeReceipt(scope){const entries=[...scope.entries.entries()];return{checked:entries.filter(([,entry])=>entry.checked).map(([id])=>id),unchecked:entries.filter(([,entry])=>!entry.checked).map(([id])=>id)}}function matchingRevisionEntries(pmRoot,ids){const scopes=revisionScopes.getStore()??[];if(scopes.length===0)return[];const resolvedRoot=canonicalTrackerRoot(pmRoot),keys=new Set(ids.filter(id=>typeof id=="string"));return[...new Set(scopes.flatMap(scope=>scope.pmRoot===resolvedRoot?[...keys].flatMap(key=>scope.entries.get(key)??[]):[]))]}function activeItemRevisionExpectations(pmRoot){const scopes=revisionScopes.getStore()??[];if(scopes.length===0)return[];const resolvedRoot=canonicalTrackerRoot(pmRoot),expected=new Map;for(const scope of scopes)if(scope.pmRoot===resolvedRoot)for(const[id,entry]of scope.entries){if(entry.expected!==entry.declared)return;expected.set(id,(expected.get(id)??new Set).add(entry.expected))}if(![...expected.values()].some(hashes=>hashes.size>1))return[...expected].map(([id,hashes])=>`${id}=${[...hashes][0]}`)}function hasActiveItemRevisionScope(pmRoot){const resolvedRoot=canonicalTrackerRoot(pmRoot);return(revisionScopes.getStore()??[]).some(scope=>scope.pmRoot===resolvedRoot&&scope.entries.size>0)}function assertItemRevisionExpectations(pmRoot,document,targetId){const entries=matchingRevisionEntries(pmRoot,[targetId,document.metadata.id]);entries.length>0&&assertRevisionEntries(entries,targetId,hashDocument(document),!1,pmRoot)}function assertItemRevisionExpectationsOnUnreadable(pmRoot,targetId,raw){const entries=matchingRevisionEntries(pmRoot,[targetId]);entries.length>0&&assertRevisionEntries(entries,targetId,sha256Hex(raw),!0,pmRoot)}const ITEM_REVISION_CONFLICT_CHANGED_REASON="revision_changed",ITEM_REVISION_CONFLICT_UNREADABLE_REASON="document_unreadable";function itemRevisionConflictGuidance(targetId,unreadable,invocation={}){const scope=[...invocation.scopeArgs??[]],output=[...invocation.outputArgs??["--json"]],read=renderPmCommand([...scope,"get",targetId,...output]),history=renderPmCommand([...scope,"history",targetId,"--limit","5",...output]);return{required:unreadable?`Recover ${targetId} without --expect-hash (${renderPmCommand([...scope,"restore",targetId,"<version>"])}), since no declared revision describes an unreadable document.`:`Re-read ${targetId} (${read} reports item_hash), decide again against the current revision, then retry with --expect-hash <item_hash>.`,examples:[renderPmCommand([...scope,"get",targetId,"--fields","item_hash",...output]),history],nextSteps:[read,history]}}const REFUSAL_TRACKERS_KEY=Symbol.for("@unbrained/pm-cli/item-revision-refusal-trackers"),refusalTrackerRegistry=globalThis,refusalTrackers=refusalTrackerRegistry[REFUSAL_TRACKERS_KEY]??=new WeakMap,REFUSAL_CAUSE_DEPTH=8;function itemRevisionRefusalTracker(error){for(const link of refusalCauseChain(error)){const tracker=refusalTrackers.get(link);if(tracker!==void 0)return tracker}}function*refusalCauseChain(error){let current=error;for(let depth=0;depth<REFUSAL_CAUSE_DEPTH&&typeof current=="object"&&current!==null;depth+=1){yield current;try{current=current.cause}catch{return}}}function assertRevisionEntries(entries,targetId,current,unreadable,pmRoot){for(const entry of entries)if(entry.checked=!0,!(!unreadable&&entry.expected===current))throw trackRefusal(pmRoot,new PmCliError(`Item ${targetId} is no longer at the expected revision ${entry.expected.slice(0,12)}${unreadable?" (its live document cannot be read)":""}; refusing to write over a revision this decision did not see.${entry.committed?" Earlier writes by this same invocation already committed.":" Nothing was written to this item."}`,EXIT_CODE.CONFLICT,{code:"item_revision_conflict",item_id:targetId,expected_revision:entry.expected,current_revision:current,reason:unreadable?ITEM_REVISION_CONFLICT_UNREADABLE_REASON:ITEM_REVISION_CONFLICT_CHANGED_REASON,why:"The caller declared the revision its decision was based on, and another write changed the item before this locked write.",...itemRevisionConflictGuidance(targetId,unreadable)}))}function isItemRevisionRefusalFrom(error,pmRoot){const tracker=itemRevisionRefusalTracker(error);return tracker===void 0||tracker===canonicalTrackerRoot(pmRoot)}const SCOPED_REFUSALS_KEY=Symbol.for("@unbrained/pm-cli/item-revision-scoped-refusals"),scopedRefusalRegistry=globalThis,scopedRefusals=scopedRefusalRegistry[SCOPED_REFUSALS_KEY]??=new WeakSet;function isItemRevisionRefusalScoped(error){for(const link of refusalCauseChain(error))if(scopedRefusals.has(link))return!0;return!1}function markItemRevisionRefusalScoped(error){return scopedRefusals.add(error),error}function retainItemRevisionRefusalTracker(source,target){const tracker=itemRevisionRefusalTracker(source);return tracker!==void 0&&refusalTrackers.set(target,tracker),isItemRevisionRefusalScoped(source)&&scopedRefusals.add(target),target}function trackRefusal(pmRoot,error){return refusalTrackers.set(error,canonicalTrackerRoot(pmRoot)),error}function assertItemMutationPreconditions(pmRoot,document,targetId=document.metadata.id){assertItemRevisionExpectations(pmRoot,document,targetId);for(const condition of conditionsFor(pmRoot,[targetId,document.metadata.id]))condition.validate(document),condition.compensation!==void 0&&targetId===condition.id&&(condition.compensation.validated_storage_id=targetId)}function conditionsFor(pmRoot,ids){const resolvedRoot=path.resolve(pmRoot);return(preconditions.getStore()??[]).filter(condition=>condition.pmRoot===resolvedRoot&&ids.includes(condition.id))}function advanceItemMutationPreconditions(pmRoot,document,targetId=document.metadata.id,aliasIds=[],revision){const entries=matchingRevisionEntries(pmRoot,[targetId,document.metadata.id,...aliasIds]);if(entries.length>0){const committed=revision??hashDocument(document);for(const entry of entries)entry.expected=committed,entry.committed=!0}for(const condition of conditionsFor(pmRoot,[targetId,document.metadata.id,...aliasIds]))condition.committed?.(document)}function ownedTransactionCompensation(pmRoot,ids,operation){const identities=ids.filter(id=>id!==void 0);if(!identities.some(id=>id!==identities[0]))return conditionsFor(pmRoot,[identities[0]]).find(condition=>condition.compensation?.operations.includes(operation)===!0&&condition.compensation.validated_storage_id===condition.id)?.compensation}function transactionCompensationHistoryContext(pmRoot,ids,operation){const compensation=ownedTransactionCompensation(pmRoot,ids,operation);return compensation===void 0||compensation.overrides.length===0?{}:{transaction_compensation:{transaction_id:compensation.transaction_id,step_id:compensation.step_id,overridden:structuredClone(compensation.overrides)}}}function itemMutationPreconditionHistoryContext(pmRoot,ids){return Object.assign({},...conditionsFor(pmRoot,ids).map(condition=>condition.historyContext))}export{ITEM_REVISION_CONFLICT_CHANGED_REASON,ITEM_REVISION_CONFLICT_UNREADABLE_REASON,activeItemRevisionExpectations,advanceItemMutationPreconditions,assertItemMutationPreconditions,assertItemRevisionExpectationsOnUnreadable,bindItemRevisionScope,createItemRevisionScope,hasActiveItemRevisionScope,isItemRevisionRefusalFrom,isItemRevisionRefusalScoped,itemMutationPreconditionHistoryContext,itemRevisionConflictGuidance,itemRevisionRefusalTracker,itemRevisionScopeReceipt,markItemRevisionRefusalScoped,ownedTransactionCompensation,retainItemRevisionRefusalTracker,runWithItemMutationPrecondition,runWithItemRevisionScope,transactionCompensationHistoryContext};
1
+ import{AsyncLocalStorage as _}from"node:async_hooks";import{realpathSync as g}from"node:fs";import u from"node:path";import{hashDocument as S}from"../history/history.js";import{sha256Hex as k}from"../shared/serialization.js";import{renderPmCommand as d}from"../shared/command-line.js";import{EXIT_CODE as p}from"../shared/constants.js";import{PmCliError as m}from"../shared/errors.js";const l=new _;function z(t,e){return l.run([...l.getStore()??[],{...t,pmRoot:u.resolve(t.pmRoot)}],e)}const C=Symbol.for("@unbrained/pm-cli/item-revision-scopes"),b=globalThis,a=b[C]??=new _;function c(t){const e=u.resolve(t);try{return g.native(e)}catch{return e}}function B(){return{entries:new Map}}function X(t,e){return a.run([...a.getStore()??[],t],e)}function J(t,e,n){const o=c(e);if(t.pmRoot!==void 0&&t.pmRoot!==o)throw new m("An expected-revision scope is already bound to another tracker.",p.USAGE,{code:"expected_revision_scope_conflict",required:"Bind expected item revisions for one tracker per scope."});t.pmRoot=o;for(const{id:i,itemHash:r}of n){const s=t.entries.get(i);if(s!==void 0&&s.declared!==r)throw new m(`Item ${i} has two different expected revisions.`,p.USAGE,{code:"expected_revision_duplicate",item_id:i,required:"Declare at most one expected revision per item."});t.entries.set(i,s??{declared:r,expected:r,checked:!1,committed:!1})}}function Q(t){const e=[...t.entries.entries()];return{checked:e.filter(([,n])=>n.checked).map(([n])=>n),unchecked:e.filter(([,n])=>!n.checked).map(([n])=>n)}}function h(t,e){const n=a.getStore()??[];if(n.length===0)return[];const o=c(t),i=new Set(e.filter(r=>typeof r=="string"));return[...new Set(n.flatMap(r=>r.pmRoot===o?[...i].flatMap(s=>r.entries.get(s)??[]):[]))]}function Z(t){const e=a.getStore()??[];if(e.length===0)return[];const n=c(t),o=new Map;for(const i of e)if(i.pmRoot===n)for(const[r,s]of i.entries){if(s.expected!==s.declared)return;o.set(r,(o.get(r)??new Set).add(s.expected))}if(![...o.values()].some(i=>i.size>1))return[...o].map(([i,r])=>`${i}=${[...r][0]}`)}function ee(t){const e=c(t);return(a.getStore()??[]).some(n=>n.pmRoot===e&&n.entries.size>0)}function T(t,e,n){const o=h(t,[n,e.metadata.id]);o.length>0&&y(o,n,S(e),!1,t)}function te(t,e,n){const o=h(t,[e]);o.length>0&&y(o,e,k(n),!0,t)}const A="revision_changed",I="document_unreadable";function O(t,e,n={}){const o=[...n.scopeArgs??[]],i=[...n.outputArgs??["--json"]],r=d([...o,"get",t,...i]),s=d([...o,"history",t,"--limit","5",...i]);return{required:e?`Recover ${t} without --expect-hash (${d([...o,"restore",t,"<version>"])}), since no declared revision describes an unreadable document.`:`Re-read ${t} (${r} reports item_hash), decide again against the current revision, then retry with --expect-hash <item_hash>.`,examples:[d([...o,"get",t,"--fields","item_hash",...i]),s],nextSteps:[r,s]}}const M=Symbol.for("@unbrained/pm-cli/item-revision-refusal-trackers"),N=globalThis,v=N[M]??=new WeakMap,$=8;function E(t){for(const e of w(t)){const n=v.get(e);if(n!==void 0)return n}}function*w(t){let e=t;for(let n=0;n<$&&typeof e=="object"&&e!==null;n+=1){yield e;try{e=e.cause}catch{return}}}function y(t,e,n,o,i){for(const r of t)if(r.checked=!0,!(!o&&r.expected===n))throw U(i,new m(`Item ${e} is no longer at the expected revision ${r.expected.slice(0,12)}${o?" (its live document cannot be read)":""}; refusing to write over a revision this decision did not see.${r.committed?" Earlier writes by this same invocation already committed.":" Nothing was written to this item."}`,p.CONFLICT,{code:"item_revision_conflict",item_id:e,expected_revision:r.expected,current_revision:n,reason:o?I:A,why:"The caller declared the revision its decision was based on, and another write changed the item before this locked write.",...O(e,o)}))}function ne(t,e){const n=E(t);return n===void 0||n===c(e)}const P=Symbol.for("@unbrained/pm-cli/item-revision-scoped-refusals"),F=globalThis,R=F[P]??=new WeakSet;function L(t){for(const e of w(t))if(R.has(e))return!0;return!1}function oe(t){return R.add(t),t}function ie(t,e){const n=E(t);return n!==void 0&&v.set(e,n),L(t)&&R.add(e),e}function U(t,e){return v.set(e,c(t)),e}function re(t,e,n=e.metadata.id){T(t,e,n);for(const o of f(t,[n,e.metadata.id]))o.validate(e),o.compensation!==void 0&&n===o.id&&(o.compensation.validated_storage_id=n)}function f(t,e){const n=u.resolve(t);return(l.getStore()??[]).filter(o=>o.pmRoot===n&&e.includes(o.id))}function se(t,e,n=e.metadata.id,o=[],i){const r=h(t,[n,e.metadata.id,...o]);if(r.length>0){const s=i??S(e);for(const x of r)x.expected=s,x.committed=!0}for(const s of f(t,[n,e.metadata.id,...o]))s.committed?.(e)}function D(t,e,n){const o=e.filter(i=>i!==void 0);if(!o.some(i=>i!==o[0]))return f(t,[o[0]]).find(i=>i.compensation?.operations.includes(n)===!0&&i.compensation.validated_storage_id===i.id)?.compensation}function ce(t,e,n){const o=D(t,e,n);return o===void 0||o.overrides.length===0?{}:{transaction_compensation:{transaction_id:o.transaction_id,step_id:o.step_id,overridden:structuredClone(o.overrides)}}}function ae(t,e){return Object.assign({},...f(t,e).map(n=>n.historyContext))}export{A as ITEM_REVISION_CONFLICT_CHANGED_REASON,I as ITEM_REVISION_CONFLICT_UNREADABLE_REASON,Z as activeItemRevisionExpectations,se as advanceItemMutationPreconditions,re as assertItemMutationPreconditions,te as assertItemRevisionExpectationsOnUnreadable,J as bindItemRevisionScope,B as createItemRevisionScope,ee as hasActiveItemRevisionScope,ne as isItemRevisionRefusalFrom,L as isItemRevisionRefusalScoped,ae as itemMutationPreconditionHistoryContext,O as itemRevisionConflictGuidance,E as itemRevisionRefusalTracker,Q as itemRevisionScopeReceipt,oe as markItemRevisionRefusalScoped,D as ownedTransactionCompensation,ie as retainItemRevisionRefusalTracker,z as runWithItemMutationPrecondition,X as runWithItemRevisionScope,ce as transactionCompensationHistoryContext};
2
2
  //# sourceMappingURL=item-mutation-precondition.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2fda779c-a87f-517c-b71a-626c4fef98e5")}catch{}})();import fs from"node:fs/promises";import{buildDeletedItemError}from"../history/tombstone.js";import{normalizeHistoryOperationForWrite}from"../history/operation-contract.js";import{enforceWorkflowMutation}from"../policy/workflow-policy-store.js";import{recordItemMetadataEnumeration}from"./item-metadata-read-work.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,itemMutationPreconditionHistoryContext,transactionCompensationHistoryContext}from"./item-mutation-precondition.js";import{checkpointMutationHistoryContext}from"../checkpoint/mutation-context.js";import path from"node:path";import{getActiveExtensionRegistrations,projectAfterCommandItemSnapshot,recordAfterCommandAffectedItem,runActiveOnReadHooks,runActiveBeforeMutationHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{collectRegisteredItemFieldNames}from"../extensions/item-fields.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE,TYPE_TO_FOLDER}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{levenshteinDistanceWithinLimit}from"../shared/levenshtein.js";import{appendHistoryEntry,createHistoryEntry}from"../history/history.js";import{enforceHistoryStreamPolicyForItem}from"../history/history-stream-policy.js";import{canonicalDocument,parseItemDocument,serializeItemDocument}from"../item/item-format.js";import{resolveItemTypeRegistry}from"../item/type-registry.js";import{effectiveItemFormatVersion,requiredItemFormatVersion}from"../item/item-format-version.js";import{assertProjectRuntimeFormatGuard}from"../../sdk/environment/project-runtime-compatibility.js";import{acquireLockLease}from"../lock/lock.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";import{isUtf8}from"node:buffer";import{normalizeItemId,normalizeRawItemId}from"../item/id.js";import{acquireItemMetadataDerivedIndexLock,listAllDocumentCandidatesCached,listAllDocumentsCached,listAllDocumentsCachedLight,refreshItemMetadataDerivedIndex}from"./item-metadata-cache.js";import{getHistoryPath,getItemPath,ITEM_FILE_EXTENSIONS,resolveWorkspaceRoot}from"./paths.js";import{resolveGovernanceKnobs}from"./settings.js";import{assertReadableTrackerRoot}from"./tracker-preflight.js";import{resolveClaimPrincipal}from"../shared/author.js";import{pruneResolvedDeferredFields}from"../item/deferred-fields.js";import{nowIso}from"../shared/time.js";import{redactOptionalIdentityCredentials}from"../shared/url-credentials.js";async function fileExists(targetPath){try{return await fs.access(targetPath),!0}catch{return!1}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}function appendWarning(warnings,warning){warnings&&(warnings.includes(warning)||warnings.push(warning))}function resolveActiveExtensionFieldNames(explicit){return explicit??collectRegisteredItemFieldNames(getActiveExtensionRegistrations())}function resolveItemFormatSearchOrder(preferredFormat){return preferredFormat==="toon"?["toon","json_markdown"]:preferredFormat==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function locateItem(pmRoot,rawId,idPrefix="pm-",preferredFormat,typeToFolder=TYPE_TO_FOLDER){const trimmedRawId=rawId.trim(),exactRawId=trimmedRawId.startsWith("#")?trimmedRawId.slice(1):trimmedRawId;if(exactRawId.length===0)return null;const normalizedId=normalizeItemId(rawId,idPrefix),rawNormalizedId=normalizeRawItemId(rawId),candidateIds=[...new Set([exactRawId,normalizedId,rawNormalizedId])].filter(candidateId=>candidateId.length>0),entries=Object.entries(typeToFolder),searchOrder=resolveItemFormatSearchOrder(preferredFormat);for(const candidateId of candidateIds){const matches=new Map;for(const[type]of entries)for(const itemFormat of searchOrder){const itemPath=getItemPath(pmRoot,type,candidateId,itemFormat,typeToFolder);await fileExists(itemPath)&&matches.set(itemPath,matches.get(itemPath)??{id:candidateId,type,itemPath,item_format:itemFormat})}if(matches.size>1){const paths=[...matches.keys()].map(itemPath=>path.relative(pmRoot,itemPath).split(path.sep).join("/")).sort();throw new PmCliError(`Item ${candidateId} has ambiguous identity across ${paths.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,EXIT_CODE.CONFLICT,{code:"item_identity_ambiguous",item_id:candidateId,paths})}for(const match of matches.values())return match}return null}async function readLocatedItem(item,options={}){const snapshot=await readLocatedItemSnapshot(item,options);if(snapshot.error!==null)throw snapshot.error;return{raw:snapshot.raw,document:snapshot.document}}async function readLocatedItemSnapshot(item,options={}){const bytes=await fs.readFile(item.itemPath);if(!isUtf8(bytes))throw new PmCliError("Item contains invalid UTF-8; preserve a binary backup before recovering it.",EXIT_CODE.CONFLICT,{code:"item_document_encoding_invalid",item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:!1});const raw=bytes.toString("utf8");await runActiveOnReadHooks({path:item.itemPath,scope:"project"});let document;try{document=parseItemDocument(raw,{format:item.item_format,requireSupportedFormat:!0,schema:options.schema,extensionFieldNames:resolveActiveExtensionFieldNames(options.extensionFieldNames),onWarning:warning=>appendWarning(options.warnings,warning)})}catch(error){if(error instanceof PmCliError&&error.code==="item_format_version_unsupported")throw new PmCliError(`Item ${item.id}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath});if(error instanceof PmCliError&&error.code==="item_document_invalid")return{raw,document:null,error:new PmCliError(`Cannot read ${item.id} at ${item.itemPath}${bytes.length===0?" (zero-length file)":""}: ${error.message}`,error.exitCode,{...error.context,item_id:item.id,item_path:item.itemPath,byte_length:bytes.length,empty:bytes.length===0,nextSteps:[`Run pm history ${item.id} --full, then pm restore ${item.id} <version> to recover a recorded state.`]})};throw error}return{raw,document,error:null}}async function listAllItemMetadata(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCached(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataLight(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema){await assertReadableTrackerRoot(pmRoot);const documents=await listAllDocumentsCachedLight(pmRoot,preferredFormat,typeToFolder,warnings,schema);return recordItemMetadataEnumeration(documents.length),documents.map(document=>document.metadata)}async function listAllItemMetadataWithBody(pmRoot,preferredFormat,typeToFolder=TYPE_TO_FOLDER,warnings,schema,options={}){await assertReadableTrackerRoot(pmRoot);const candidates=await listAllDocumentCandidatesCached(pmRoot,preferredFormat,typeToFolder,warnings,schema,{includeBody:!0,forceSourceScan:options.forceSourceScan});return recordItemMetadataEnumeration(candidates.length),candidates.map(candidate=>({...candidate.metadata,body:candidate.body}))}function createMutationGuardSdk(params){return{async get(id){const located=await locateItem(params.pmRoot,id,params.settings.id_prefix,params.settings.item_format,params.typeToFolder);if(!located)return null;const{document}=await readLocatedItem(located,{schema:params.settings.schema});return{item:document.metadata,body:document.body}},list:()=>listAllItemMetadata(params.pmRoot,params.settings.item_format,params.typeToFolder,void 0,params.settings.schema)}}async function listKnownItemIds(pmRoot,typeToFolder){const folders=new Set(Object.values(typeToFolder)),allIds=[];return await Promise.all([...folders].map(async folder=>{try{const entries=await fs.readdir(path.join(pmRoot,folder));for(const entry of entries)for(const ext of ITEM_FILE_EXTENSIONS)if(entry.toLowerCase().endsWith(ext)){allIds.push(entry.slice(0,-ext.length));break}}catch{}})),allIds}async function buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder){const normalized=normalizeItemId(badId,idPrefix),ids=await listKnownItemIds(pmRoot,typeToFolder);if(ids.length===0)return[];const limit=Math.max(3,Math.floor(normalized.length/2));return ids.map(id=>({id,distance:levenshteinDistanceWithinLimit(id,normalized,limit)})).filter(entry=>entry.distance!==null).sort((left,right)=>left.distance-right.distance).slice(0,3).map(entry=>entry.id)}async function buildItemNotFoundError(pmRoot,badId,idPrefix,typeToFolder){const deleted=await buildDeletedItemError(pmRoot,badId,idPrefix);if(deleted)return deleted;const suggestions=await buildDidYouMeanSuggestions(pmRoot,badId,idPrefix,typeToFolder),nextSteps=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return suggestions.length>0&&nextSteps.unshift(`Did you mean one of: ${suggestions.join(", ")}?`),new PmCliError(`Item ${badId} not found`,EXIT_CODE.NOT_FOUND,{code:"item_not_found",id:badId,nextSteps})}function bypassesAssigneeConflict(op,bypassAssigneeConflict){return op==="claim"||bypassAssigneeConflict===!0&&(op==="comment_add"||op==="comment_edit"||op==="comment_delete"||op==="note_add"||op==="learning_add"||op==="release"||op==="update"||op==="update_ownership_bypass"||op==="update_audit")}async function prepareLockedItem(params){const typeToFolder=params.typeToFolder??resolveItemTypeRegistry(params.settings,getActiveExtensionRegistrations()).type_to_folder,located=await locateItem(params.pmRoot,params.id,params.settings.id_prefix,params.settings.item_format,typeToFolder);if(!located)throw await buildItemNotFoundError(params.pmRoot,params.id,params.settings.id_prefix,typeToFolder);const lease=await acquireLockLease(params.pmRoot,located.id,params.settings.locks.ttl_seconds,params.author,!!params.force,params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms,{waitPolicy:"progress"}),releaseLock=lease.release;try{const warnings=[],{raw:originalRaw,document}=await readLocatedItem(located,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames,warnings}),storedAssignee=document.metadata.assignee?.trim(),assigned=redactOptionalIdentityCredentials(storedAssignee),assignedPrincipal=document.metadata.claim_principal?.trim()||storedAssignee,callerPrincipal=resolveClaimPrincipal(params.author),governance=resolveGovernanceKnobs(params.settings);if(assigned&&assignedPrincipal!==callerPrincipal&&!params.force&&!bypassesAssigneeConflict(params.op,params.bypassAssigneeConflict)){if(governance.ownership_enforcement==="strict")throw new PmCliError(`Item ${located.id} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);governance.ownership_enforcement==="warn"&&warnings.push(`ownership_warning:assignee_conflict:${located.id}:${assigned}`)}return{typeToFolder,located,originalRaw,document,warnings,releaseLock,lease}}catch(error){throw await releaseLock(),error}}function historyContextOrUndefined(context){return Object.keys(context).length===0?void 0:context}async function commitLockedItemWrite(lease,located,originalRaw,commit){return lease.fence(async()=>{let currentRaw;try{currentRaw=await fs.readFile(located.itemPath,"utf8")}catch(error){if(!isFileMissingError(error))throw error;currentRaw=null}if(currentRaw!==originalRaw)throw new PmCliError(`Item ${located.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,EXIT_CODE.CONFLICT,{code:"stale_revision",item_id:located.id,reason:currentRaw===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return commit()})}function resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter){if(!serviceWriteOverride.handled||typeof serviceWriteOverride.result!="object"||serviceWriteOverride.result===null)return{effectiveTargetItemPath:targetItemPath,effectiveSerializedAfter:serializedAfter,skipItemWrite:!1};const overrideRecord=serviceWriteOverride.result;return{effectiveTargetItemPath:typeof overrideRecord.target_item_path=="string"&&overrideRecord.target_item_path.trim().length>0?overrideRecord.target_item_path:targetItemPath,effectiveSerializedAfter:typeof overrideRecord.contents=="string"?overrideRecord.contents:serializedAfter,skipItemWrite:overrideRecord.skip_write===!0}}async function readOverriddenCommitRevision(params){try{const located=await locateItem(params.pmRoot,params.id,params.settings.id_prefix,params.settings.item_format,params.typeToFolder);if(!located)return{document:EMPTY_CANONICAL_DOCUMENT};const document=parseItemDocument(await fs.readFile(located.itemPath,"utf8"),{format:located.item_format,requireSupportedFormat:!0,schema:params.settings.schema,extensionFieldNames:resolveActiveExtensionFieldNames(params.extensionFieldNames)});return document.metadata.id===params.embeddedId?{document}:{document:params.fallback,revision:UNREADABLE_COMMIT_REVISION}}catch{return{document:params.fallback,revision:UNREADABLE_COMMIT_REVISION}}}const UNREADABLE_COMMIT_REVISION="unreadable-after-storage-override";async function resolveItemStoreDeleteOverride(payload){const override=await runActiveServiceOverride("item_store_delete",payload),record=override.handled&&typeof override.result=="object"&&override.result!==null?override.result:{};return{effectiveItemPath:typeof record.item_path=="string"&&record.item_path.trim().length>0?record.item_path:payload.item_path,skipDelete:record.skip_delete===!0,warnings:override.warnings}}async function rollbackMutatedItemWrite(params){if(!params.skipItemWrite){if(params.effectiveTargetItemPath!==params.originalItemPath){await writeFileAtomic(params.originalItemPath,params.originalRaw),await fs.rm(params.effectiveTargetItemPath,{force:!0});return}await writeFileAtomic(params.originalItemPath,params.originalRaw)}}function recordResolvedDeferrals(document,changedFields){pruneResolvedDeferredFields(document.metadata)&&changedFields.push("deferred_fields")}async function mutateItemWithDeferredHistoryContext(params){normalizeHistoryOperationForWrite(params.op);const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:params.op,author:params.author,force:params.force,bypassAssigneeConflict:params.bypassAssigneeConflict,extensionFieldNames:params.extensionFieldNames,typeToFolder:params.typeToFolder}),{typeToFolder,located,originalRaw,document,warnings:parseWarnings,releaseLock,lease}=prepared;try{assertItemMutationPreconditions(params.pmRoot,document,located.id);const beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutableDocument=canonicalDocument(structuredClone(document),{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),mutation=await params.mutate(mutableDocument,{storageId:located.id});if(recordResolvedDeferrals(mutableDocument,mutation.changedFields),params.skipNoop===!0&&mutation.changedFields.length===0)return{item:beforeDocument.metadata,body:beforeDocument.body,changedFields:[],warnings:[...parseWarnings,...mutation.warnings??[]]};const historyContext={...params.resolveHistoryContext?.(),...checkpointMutationHistoryContext(params.pmRoot,located.id),...itemMutationPreconditionHistoryContext(params.pmRoot,[located.id,document.metadata.id])},requiredFormat=Math.max(requiredItemFormatVersion(beforeDocument.metadata),requiredItemFormatVersion(mutableDocument.metadata));assertProjectRuntimeFormatGuard(resolveWorkspaceRoot(params.pmRoot),requiredFormat),requiredFormat>effectiveItemFormatVersion(mutableDocument.metadata)&&(mutableDocument.metadata.pm_format_version=requiredFormat,mutation.changedFields.push("pm_format_version")),mutableDocument.metadata.updated_at=nowIso();const afterDocument=canonicalDocument(mutableDocument,{schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:params.op,author:params.author,before:beforeDocument,after:afterDocument});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:params.op,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields,author:params.author,sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:params.op}),targetItemFormat="toon",serializedAfter=serializeItemDocument(afterDocument,{format:targetItemFormat,schema:params.settings.schema,extensionFieldNames:params.extensionFieldNames}),targetItemPath=getItemPath(params.pmRoot,afterDocument.metadata.type,located.id,targetItemFormat,typeToFolder),historyPath=getHistoryPath(params.pmRoot,located.id),committed=await commitLockedItemWrite(lease,located,originalRaw,async()=>{const serviceWriteOverride=await runActiveServiceOverride("item_store_write",{op:params.op,pm_root:params.pmRoot,item_id:located.id,source_item_path:located.itemPath,target_item_path:targetItemPath,history_path:historyPath,item_format:targetItemFormat,before:beforeDocument,after:afterDocument,contents:serializedAfter}),{effectiveTargetItemPath:effectiveTargetItemPath2,effectiveSerializedAfter,skipItemWrite}=resolveItemStoreWriteOverride(serviceWriteOverride,targetItemPath,serializedAfter),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings2=[];try{skipItemWrite||await writeFileAtomic(effectiveTargetItemPath2,effectiveSerializedAfter),!skipItemWrite&&effectiveTargetItemPath2!==located.itemPath&&await fs.rm(located.itemPath);const entry=createHistoryEntry({nowIso:afterDocument.metadata.updated_at,author:params.author,op:params.op,before:beforeDocument,after:afterDocument,message:params.message,context:historyContextOrUndefined({...historyContext,...workflowPolicy.decisions.length===0?{}:{workflow_policies:workflowPolicy.decisions},...transactionCompensationHistoryContext(params.pmRoot,[located.id,document.metadata.id],params.op)})});try{await appendHistoryEntry(historyPath,entry)}catch(error){throw await rollbackMutatedItemWrite({skipItemWrite,effectiveTargetItemPath:effectiveTargetItemPath2,originalItemPath:located.itemPath,originalRaw}),error}skipItemWrite||(derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder,schema:params.settings.schema,itemPath:effectiveTargetItemPath2,previousItemPath:located.itemPath,document:afterDocument}))}finally{await releaseDerivedIndexLock()}const overridden=skipItemWrite||effectiveTargetItemPath2!==targetItemPath||effectiveSerializedAfter!==serializedAfter;return{derivedIndexWarnings:derivedIndexWarnings2,effectiveTargetItemPath:effectiveTargetItemPath2,overrideWarnings:serviceWriteOverride.warnings,stored:overridden?await readOverriddenCommitRevision({pmRoot:params.pmRoot,settings:params.settings,id:located.id,typeToFolder,extensionFieldNames:params.extensionFieldNames,fallback:afterDocument,embeddedId:afterDocument.metadata.id}):{document:afterDocument}}}),{derivedIndexWarnings,effectiveTargetItemPath,stored}=committed;advanceItemMutationPreconditions(params.pmRoot,stored.document,located.id,[afterDocument.metadata.id],stored.revision);const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveTargetItemPath,scope:"project",op:params.op,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${params.op}:history`,item_id:afterDocument.metadata.id,item_type:afterDocument.metadata.type,before:beforeDocument,after:afterDocument,changed_fields:mutation.changedFields})];return recordAfterCommandAffectedItem({id:afterDocument.metadata.id,op:params.op,item_type:afterDocument.metadata.type,previous_status:beforeDocument.metadata.status,status:afterDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,mutation.changedFields),current:projectAfterCommandItemSnapshot(afterDocument.metadata,mutation.changedFields),changed_fields:mutation.changedFields}),{item:afterDocument.metadata,body:afterDocument.body,changedFields:mutation.changedFields,warnings:[...parseWarnings,...mutation.warnings??[],...workflowPolicy.warnings,...historyPolicy.warnings,...committed.overrideWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}async function mutateItemWithHistoryContext(params){const{historyContext,...mutationParams}=params;return mutateItemWithDeferredHistoryContext({...mutationParams,resolveHistoryContext:()=>historyContext})}async function mutateItemWithHistoryContextResolver(params){return mutateItemWithDeferredHistoryContext(params)}async function mutateItem(params){return mutateItemWithDeferredHistoryContext(params)}const itemStoreTestOnly={appendWarning,bypassesAssigneeConflict,buildDidYouMeanSuggestions,isErrno};async function deleteItem(params){const prepared=await prepareLockedItem({pmRoot:params.pmRoot,settings:params.settings,id:params.id,op:"delete",author:params.author,force:params.force}),{located,originalRaw,document,warnings:parseWarnings,releaseLock,lease}=prepared;try{assertItemMutationPreconditions(params.pmRoot,document,located.id);const extensionFieldNames=resolveActiveExtensionFieldNames(void 0),beforeDocument=canonicalDocument(document,{schema:params.settings.schema,extensionFieldNames}),workflowPolicy=await enforceWorkflowMutation({pmRoot:params.pmRoot,settings:params.settings,operation:"delete",author:params.author,before:beforeDocument,after:null,dryRun:params.dryRun});await runActiveBeforeMutationHooks({pm_root:params.pmRoot,operation:"delete",before:beforeDocument,after:null,changed_fields:["deleted"],author:params.author,dry_run:params.dryRun===!0,sdk:createMutationGuardSdk({pmRoot:params.pmRoot,settings:params.settings,typeToFolder:prepared.typeToFolder})});const historyPolicy=await enforceHistoryStreamPolicyForItem({pmRoot:params.pmRoot,settings:params.settings,itemId:located.id,commandLabel:"delete"}),deletionTimestamp=nowIso(),tombstoneDocument=EMPTY_CANONICAL_DOCUMENT,historyEntry=createHistoryEntry({nowIso:deletionTimestamp,author:params.author,op:"delete",before:beforeDocument,after:tombstoneDocument,message:params.message,context:historyContextOrUndefined({...workflowPolicy.decisions.length===0?{}:{workflow_policies:workflowPolicy.decisions},...transactionCompensationHistoryContext(params.pmRoot,[located.id,document.metadata.id],"delete")})}),historyPath=getHistoryPath(params.pmRoot,located.id),runDeleteOverride=()=>resolveItemStoreDeleteOverride({op:"delete",pm_root:params.pmRoot,item_id:located.id,item_path:located.itemPath,history_path:historyPath,before:beforeDocument});if(params.dryRun===!0){const preview=await runDeleteOverride();return{item:beforeDocument.metadata,changedFields:["deleted"],targetPath:preview.effectiveItemPath,warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...preview.warnings]}}const committed=await commitLockedItemWrite(lease,located,originalRaw,async()=>{const{effectiveItemPath:effectiveItemPath2,skipDelete,warnings}=await runDeleteOverride(),releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author);let derivedIndexWarnings2=[];try{skipDelete||await fs.rm(effectiveItemPath2);try{await appendHistoryEntry(historyPath,historyEntry)}catch(error){throw skipDelete||await writeFileAtomic(effectiveItemPath2,originalRaw),error}skipDelete||(derivedIndexWarnings2=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder:prepared.typeToFolder,schema:params.settings.schema,itemPath:effectiveItemPath2,document:null}))}finally{await releaseDerivedIndexLock()}return{derivedIndexWarnings:derivedIndexWarnings2,effectiveItemPath:effectiveItemPath2,overrideWarnings:warnings,stored:skipDelete||effectiveItemPath2!==located.itemPath?await readOverriddenCommitRevision({pmRoot:params.pmRoot,settings:params.settings,id:located.id,typeToFolder:prepared.typeToFolder,fallback:tombstoneDocument,embeddedId:document.metadata.id}):{document:tombstoneDocument}}}),{derivedIndexWarnings,effectiveItemPath,stored}=committed;advanceItemMutationPreconditions(params.pmRoot,stored.document,located.id,[document.metadata.id],stored.revision);const hookWarnings=[...await runActiveOnWriteHooks({path:effectiveItemPath,scope:"project",op:"delete",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]}),...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"delete:history",item_id:beforeDocument.metadata.id,item_type:beforeDocument.metadata.type,before:beforeDocument,after:tombstoneDocument,changed_fields:["deleted"]})];return recordAfterCommandAffectedItem({id:beforeDocument.metadata.id,op:"delete",item_type:beforeDocument.metadata.type,previous_status:beforeDocument.metadata.status,previous:projectAfterCommandItemSnapshot(beforeDocument.metadata,Object.keys(beforeDocument.metadata)),changed_fields:["deleted"]}),{item:beforeDocument.metadata,changedFields:["deleted"],warnings:[...parseWarnings,...workflowPolicy.warnings,...historyPolicy.warnings,...committed.overrideWarnings,...derivedIndexWarnings,...hookWarnings]}}finally{await releaseLock()}}export{buildItemNotFoundError,createMutationGuardSdk,deleteItem,itemStoreTestOnly,listAllItemMetadata,listAllItemMetadataLight,listAllItemMetadataWithBody,locateItem,mutateItem,mutateItemWithHistoryContext,mutateItemWithHistoryContextResolver,readLocatedItem,readLocatedItemSnapshot};
1
+ import I from"node:fs/promises";import{buildDeletedItemError as bt}from"../history/tombstone.js";import{normalizeHistoryOperationForWrite as Pt}from"../history/operation-contract.js";import{enforceWorkflowMutation as B}from"../policy/workflow-policy-store.js";import{recordItemMetadataEnumeration as L}from"./item-metadata-read-work.js";import{advanceItemMutationPreconditions as G,assertItemMutationPreconditions as V,itemMutationPreconditionHistoryContext as kt,transactionCompensationHistoryContext as Y}from"./item-mutation-precondition.js";import{checkpointMutationHistoryContext as Ct}from"../checkpoint/mutation-context.js";import M from"node:path";import{getActiveExtensionRegistrations as K,projectAfterCommandItemSnapshot as E,recordAfterCommandAffectedItem as X,runActiveOnReadHooks as Nt,runActiveBeforeMutationHooks as J,runActiveOnWriteHooks as D,runActiveServiceOverride as Q}from"../extensions/index.js";import{collectRegisteredItemFieldNames as Tt}from"../extensions/item-fields.js";import{EMPTY_CANONICAL_DOCUMENT as Z,EXIT_CODE as C,TYPE_TO_FOLDER as O}from"../shared/constants.js";import{PmCliError as y}from"../shared/errors.js";import{levenshteinDistanceWithinLimit as Dt}from"../shared/levenshtein.js";import{appendHistoryEntry as tt,createHistoryEntry as et}from"../history/history.js";import{enforceHistoryStreamPolicyForItem as ot}from"../history/history-stream-policy.js";import{canonicalDocument as W,parseItemDocument as it,serializeItemDocument as Ot}from"../item/item-format.js";import{resolveItemTypeRegistry as Wt}from"../item/type-registry.js";import{effectiveItemFormatVersion as At,requiredItemFormatVersion as nt}from"../item/item-format-version.js";import{assertProjectRuntimeFormatGuard as St}from"../../sdk/environment/project-runtime-compatibility.js";import{acquireLockLease as Lt}from"../lock/lock.js";import{isFileMissingError as Mt,writeFileAtomic as A}from"../fs/fs-utils.js";import{isUtf8 as Et}from"node:buffer";import{normalizeItemId as rt,normalizeRawItemId as jt}from"../item/id.js";import{acquireItemMetadataDerivedIndexLock as at,listAllDocumentCandidatesCached as $t,listAllDocumentsCached as Ht,listAllDocumentsCachedLight as zt,refreshItemMetadataDerivedIndex as st}from"./item-metadata-cache.js";import{getHistoryPath as dt,getItemPath as ct,ITEM_FILE_EXTENSIONS as qt,resolveWorkspaceRoot as Ut}from"./paths.js";import{resolveGovernanceKnobs as Bt}from"./settings.js";import{assertReadableTrackerRoot as j}from"./tracker-preflight.js";import{resolveClaimPrincipal as Gt}from"../shared/author.js";import{pruneResolvedDeferredFields as Vt}from"../item/deferred-fields.js";import{nowIso as mt}from"../shared/time.js";import{redactOptionalIdentityCredentials as Yt}from"../shared/url-credentials.js";async function Kt(t){try{return await I.access(t),!0}catch{return!1}}function Xt(t,o){return typeof t=="object"&&t!==null&&"code"in t&&t.code===o}function lt(t,o){t&&(t.includes(o)||t.push(o))}function $(t){return t??Tt(K())}function Jt(t){return t==="toon"?["toon","json_markdown"]:t==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function H(t,o,e="pm-",i,a=O){const n=o.trim(),d=n.startsWith("#")?n.slice(1):n;if(d.length===0)return null;const l=rt(o,e),m=jt(o),r=[...new Set([d,l,m])].filter(h=>h.length>0),f=Object.entries(a),c=Jt(i);for(const h of r){const u=new Map;for(const[s]of f)for(const g of c){const p=ct(t,s,h,g,a);await Kt(p)&&u.set(p,u.get(p)??{id:h,type:s,itemPath:p,item_format:g})}if(u.size>1){const s=[...u.keys()].map(g=>M.relative(t,g).split(M.sep).join("/")).sort();throw new y(`Item ${h} has ambiguous identity across ${s.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,C.CONFLICT,{code:"item_identity_ambiguous",item_id:h,paths:s})}for(const s of u.values())return s}return null}async function ft(t,o={}){const e=await Qt(t,o);if(e.error!==null)throw e.error;return{raw:e.raw,document:e.document}}async function Qt(t,o={}){const e=await I.readFile(t.itemPath);if(!Et(e))throw new y("Item contains invalid UTF-8; preserve a binary backup before recovering it.",C.CONFLICT,{code:"item_document_encoding_invalid",item_id:t.id,item_path:t.itemPath,byte_length:e.length,empty:!1});const i=e.toString("utf8");await Nt({path:t.itemPath,scope:"project"});let a;try{a=it(i,{format:t.item_format,requireSupportedFormat:!0,schema:o.schema,extensionFieldNames:$(o.extensionFieldNames),onWarning:n=>lt(o.warnings,n)})}catch(n){if(n instanceof y&&n.code==="item_format_version_unsupported")throw new y(`Item ${t.id}: ${n.message}`,n.exitCode,{...n.context,item_id:t.id,item_path:t.itemPath});if(n instanceof y&&n.code==="item_document_invalid")return{raw:i,document:null,error:new y(`Cannot read ${t.id} at ${t.itemPath}${e.length===0?" (zero-length file)":""}: ${n.message}`,n.exitCode,{...n.context,item_id:t.id,item_path:t.itemPath,byte_length:e.length,empty:e.length===0,nextSteps:[`Run pm history ${t.id} --full, then pm restore ${t.id} <version> to recover a recorded state.`]})};throw n}return{raw:i,document:a,error:null}}async function Zt(t,o,e=O,i,a){await j(t);const n=await Ht(t,o,e,i,a);return L(n.length),n.map(d=>d.metadata)}async function Me(t,o,e=O,i,a){await j(t);const n=await zt(t,o,e,i,a);return L(n.length),n.map(d=>d.metadata)}async function Ee(t,o,e=O,i,a,n={}){await j(t);const d=await $t(t,o,e,i,a,{includeBody:!0,forceSourceScan:n.forceSourceScan});return L(d.length),d.map(l=>({...l.metadata,body:l.body}))}function ut(t){return{async get(o){const e=await H(t.pmRoot,o,t.settings.id_prefix,t.settings.item_format,t.typeToFolder);if(!e)return null;const{document:i}=await ft(e,{schema:t.settings.schema});return{item:i.metadata,body:i.body}},list:()=>Zt(t.pmRoot,t.settings.item_format,t.typeToFolder,void 0,t.settings.schema)}}async function te(t,o){const e=new Set(Object.values(o)),i=[];return await Promise.all([...e].map(async a=>{try{const n=await I.readdir(M.join(t,a));for(const d of n)for(const l of qt)if(d.toLowerCase().endsWith(l)){i.push(d.slice(0,-l.length));break}}catch{}})),i}async function ht(t,o,e,i){const a=rt(o,e),n=await te(t,i);if(n.length===0)return[];const d=Math.max(3,Math.floor(a.length/2));return n.map(m=>({id:m,distance:Dt(m,a,d)})).filter(m=>m.distance!==null).sort((m,r)=>m.distance-r.distance).slice(0,3).map(m=>m.id)}async function ee(t,o,e,i){const a=await bt(t,o,e);if(a)return a;const n=await ht(t,o,e,i),d=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return n.length>0&&d.unshift(`Did you mean one of: ${n.join(", ")}?`),new y(`Item ${o} not found`,C.NOT_FOUND,{code:"item_not_found",id:o,nextSteps:d})}function gt(t,o){return t==="claim"||o===!0&&(t==="comment_add"||t==="comment_edit"||t==="comment_delete"||t==="note_add"||t==="learning_add"||t==="release"||t==="update"||t==="update_ownership_bypass"||t==="update_audit")}async function wt(t){const o=t.typeToFolder??Wt(t.settings,K()).type_to_folder,e=await H(t.pmRoot,t.id,t.settings.id_prefix,t.settings.item_format,o);if(!e)throw await ee(t.pmRoot,t.id,t.settings.id_prefix,o);const i=await Lt(t.pmRoot,e.id,t.settings.locks.ttl_seconds,t.author,!!t.force,t.settings.governance.force_required_for_stale_lock,t.settings.locks.wait_ms,{waitPolicy:"progress"}),a=i.release;try{const n=[],{raw:d,document:l}=await ft(e,{schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames,warnings:n}),m=l.metadata.assignee?.trim(),r=Yt(m),f=l.metadata.claim_principal?.trim()||m,c=Gt(t.author),h=Bt(t.settings);if(r&&f!==c&&!t.force&&!gt(t.op,t.bypassAssigneeConflict)){if(h.ownership_enforcement==="strict")throw new y(`Item ${e.id} is assigned to ${r}. Use --force to override.`,C.CONFLICT);h.ownership_enforcement==="warn"&&n.push(`ownership_warning:assignee_conflict:${e.id}:${r}`)}return{typeToFolder:o,located:e,originalRaw:d,document:l,warnings:n,releaseLock:a,lease:i}}catch(n){throw await a(),n}}function pt(t){return Object.keys(t).length===0?void 0:t}async function yt(t,o,e,i){return t.fence(async()=>{let a;try{a=await I.readFile(o.itemPath,"utf8")}catch(n){if(!Mt(n))throw n;a=null}if(a!==e)throw new y(`Item ${o.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,C.CONFLICT,{code:"stale_revision",item_id:o.id,reason:a===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return i()})}function oe(t,o,e){if(!t.handled||typeof t.result!="object"||t.result===null)return{effectiveTargetItemPath:o,effectiveSerializedAfter:e,skipItemWrite:!1};const i=t.result;return{effectiveTargetItemPath:typeof i.target_item_path=="string"&&i.target_item_path.trim().length>0?i.target_item_path:o,effectiveSerializedAfter:typeof i.contents=="string"?i.contents:e,skipItemWrite:i.skip_write===!0}}async function _t(t){try{const o=await H(t.pmRoot,t.id,t.settings.id_prefix,t.settings.item_format,t.typeToFolder);if(!o)return{document:Z};const e=it(await I.readFile(o.itemPath,"utf8"),{format:o.item_format,requireSupportedFormat:!0,schema:t.settings.schema,extensionFieldNames:$(t.extensionFieldNames)});return e.metadata.id===t.embeddedId?{document:e}:{document:t.fallback,revision:It}}catch{return{document:t.fallback,revision:It}}}const It="unreadable-after-storage-override";async function ie(t){const o=await Q("item_store_delete",t),e=o.handled&&typeof o.result=="object"&&o.result!==null?o.result:{};return{effectiveItemPath:typeof e.item_path=="string"&&e.item_path.trim().length>0?e.item_path:t.item_path,skipDelete:e.skip_delete===!0,warnings:o.warnings}}async function ne(t){if(!t.skipItemWrite){if(t.effectiveTargetItemPath!==t.originalItemPath){await A(t.originalItemPath,t.originalRaw),await I.rm(t.effectiveTargetItemPath,{force:!0});return}await A(t.originalItemPath,t.originalRaw)}}function re(t,o){Vt(t.metadata)&&o.push("deferred_fields")}async function z(t){Pt(t.op);const o=await wt({pmRoot:t.pmRoot,settings:t.settings,id:t.id,op:t.op,author:t.author,force:t.force,bypassAssigneeConflict:t.bypassAssigneeConflict,extensionFieldNames:t.extensionFieldNames,typeToFolder:t.typeToFolder}),{typeToFolder:e,located:i,originalRaw:a,document:n,warnings:d,releaseLock:l,lease:m}=o;try{V(t.pmRoot,n,i.id);const r=W(n,{schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames}),f=W(structuredClone(n),{schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames}),c=await t.mutate(f,{storageId:i.id});if(re(f,c.changedFields),t.skipNoop===!0&&c.changedFields.length===0)return{item:r.metadata,body:r.body,changedFields:[],warnings:[...d,...c.warnings??[]]};const h={...t.resolveHistoryContext?.(),...Ct(t.pmRoot,i.id),...kt(t.pmRoot,[i.id,n.metadata.id])},u=Math.max(nt(r.metadata),nt(f.metadata));St(Ut(t.pmRoot),u),u>At(f.metadata)&&(f.metadata.pm_format_version=u,c.changedFields.push("pm_format_version")),f.metadata.updated_at=mt();const s=W(f,{schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames}),g=await B({pmRoot:t.pmRoot,settings:t.settings,operation:t.op,author:t.author,before:r,after:s});await J({pm_root:t.pmRoot,operation:t.op,before:r,after:s,changed_fields:c.changedFields,author:t.author,sdk:ut({pmRoot:t.pmRoot,settings:t.settings,typeToFolder:e})});const p=await ot({pmRoot:t.pmRoot,settings:t.settings,itemId:i.id,commandLabel:t.op}),v="toon",x=Ot(s,{format:v,schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames}),b=ct(t.pmRoot,s.metadata.type,i.id,v,e),F=dt(t.pmRoot,i.id),N=await yt(m,i,a,async()=>{const P=await Q("item_store_write",{op:t.op,pm_root:t.pmRoot,item_id:i.id,source_item_path:i.itemPath,target_item_path:b,history_path:F,item_format:v,before:r,after:s,contents:x}),{effectiveTargetItemPath:_,effectiveSerializedAfter:q,skipItemWrite:k}=oe(P,b,x),vt=await at(t.pmRoot,t.author);let U=[];try{k||await A(_,q),!k&&_!==i.itemPath&&await I.rm(i.itemPath);const Rt=et({nowIso:s.metadata.updated_at,author:t.author,op:t.op,before:r,after:s,message:t.message,context:pt({...h,...g.decisions.length===0?{}:{workflow_policies:g.decisions},...Y(t.pmRoot,[i.id,n.metadata.id],t.op)})});try{await tt(F,Rt)}catch(xt){throw await ne({skipItemWrite:k,effectiveTargetItemPath:_,originalItemPath:i.itemPath,originalRaw:a}),xt}k||(U=await st({pmRoot:t.pmRoot,preferredFormat:t.settings.item_format,typeToFolder:e,schema:t.settings.schema,itemPath:_,previousItemPath:i.itemPath,document:s}))}finally{await vt()}const Ft=k||_!==b||q!==x;return{derivedIndexWarnings:U,effectiveTargetItemPath:_,overrideWarnings:P.warnings,stored:Ft?await _t({pmRoot:t.pmRoot,settings:t.settings,id:i.id,typeToFolder:e,extensionFieldNames:t.extensionFieldNames,fallback:s,embeddedId:s.metadata.id}):{document:s}}}),{derivedIndexWarnings:w,effectiveTargetItemPath:R,stored:T}=N;G(t.pmRoot,T.document,i.id,[s.metadata.id],T.revision);const S=[...await D({path:R,scope:"project",op:t.op,item_id:s.metadata.id,item_type:s.metadata.type,before:r,after:s,changed_fields:c.changedFields}),...await D({path:F,scope:"project",op:`${t.op}:history`,item_id:s.metadata.id,item_type:s.metadata.type,before:r,after:s,changed_fields:c.changedFields})];return X({id:s.metadata.id,op:t.op,item_type:s.metadata.type,previous_status:r.metadata.status,status:s.metadata.status,previous:E(r.metadata,c.changedFields),current:E(s.metadata,c.changedFields),changed_fields:c.changedFields}),{item:s.metadata,body:s.body,changedFields:c.changedFields,warnings:[...d,...c.warnings??[],...g.warnings,...p.warnings,...N.overrideWarnings,...w,...S]}}finally{await l()}}async function je(t){const{historyContext:o,...e}=t;return z({...e,resolveHistoryContext:()=>o})}async function $e(t){return z(t)}async function He(t){return z(t)}const ze={appendWarning:lt,bypassesAssigneeConflict:gt,buildDidYouMeanSuggestions:ht,isErrno:Xt};async function qe(t){const o=await wt({pmRoot:t.pmRoot,settings:t.settings,id:t.id,op:"delete",author:t.author,force:t.force}),{located:e,originalRaw:i,document:a,warnings:n,releaseLock:d,lease:l}=o;try{V(t.pmRoot,a,e.id);const m=$(void 0),r=W(a,{schema:t.settings.schema,extensionFieldNames:m}),f=await B({pmRoot:t.pmRoot,settings:t.settings,operation:"delete",author:t.author,before:r,after:null,dryRun:t.dryRun});await J({pm_root:t.pmRoot,operation:"delete",before:r,after:null,changed_fields:["deleted"],author:t.author,dry_run:t.dryRun===!0,sdk:ut({pmRoot:t.pmRoot,settings:t.settings,typeToFolder:o.typeToFolder})});const c=await ot({pmRoot:t.pmRoot,settings:t.settings,itemId:e.id,commandLabel:"delete"}),h=mt(),u=Z,s=et({nowIso:h,author:t.author,op:"delete",before:r,after:u,message:t.message,context:pt({...f.decisions.length===0?{}:{workflow_policies:f.decisions},...Y(t.pmRoot,[e.id,a.metadata.id],"delete")})}),g=dt(t.pmRoot,e.id),p=()=>ie({op:"delete",pm_root:t.pmRoot,item_id:e.id,item_path:e.itemPath,history_path:g,before:r});if(t.dryRun===!0){const w=await p();return{item:r.metadata,changedFields:["deleted"],targetPath:w.effectiveItemPath,warnings:[...n,...f.warnings,...c.warnings,...w.warnings]}}const v=await yt(l,e,i,async()=>{const{effectiveItemPath:w,skipDelete:R,warnings:T}=await p(),S=await at(t.pmRoot,t.author);let P=[];try{R||await I.rm(w);try{await tt(g,s)}catch(_){throw R||await A(w,i),_}R||(P=await st({pmRoot:t.pmRoot,preferredFormat:t.settings.item_format,typeToFolder:o.typeToFolder,schema:t.settings.schema,itemPath:w,document:null}))}finally{await S()}return{derivedIndexWarnings:P,effectiveItemPath:w,overrideWarnings:T,stored:R||w!==e.itemPath?await _t({pmRoot:t.pmRoot,settings:t.settings,id:e.id,typeToFolder:o.typeToFolder,fallback:u,embeddedId:a.metadata.id}):{document:u}}}),{derivedIndexWarnings:x,effectiveItemPath:b,stored:F}=v;G(t.pmRoot,F.document,e.id,[a.metadata.id],F.revision);const N=[...await D({path:b,scope:"project",op:"delete",item_id:r.metadata.id,item_type:r.metadata.type,before:r,after:u,changed_fields:["deleted"]}),...await D({path:g,scope:"project",op:"delete:history",item_id:r.metadata.id,item_type:r.metadata.type,before:r,after:u,changed_fields:["deleted"]})];return X({id:r.metadata.id,op:"delete",item_type:r.metadata.type,previous_status:r.metadata.status,previous:E(r.metadata,Object.keys(r.metadata)),changed_fields:["deleted"]}),{item:r.metadata,changedFields:["deleted"],warnings:[...n,...f.warnings,...c.warnings,...v.overrideWarnings,...x,...N]}}finally{await d()}}export{ee as buildItemNotFoundError,ut as createMutationGuardSdk,qe as deleteItem,ze as itemStoreTestOnly,Zt as listAllItemMetadata,Me as listAllItemMetadataLight,Ee as listAllItemMetadataWithBody,H as locateItem,He as mutateItem,je as mutateItemWithHistoryContext,$e as mutateItemWithHistoryContextResolver,ft as readLocatedItem,Qt as readLocatedItemSnapshot};
2
2
  //# sourceMappingURL=item-store.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7f4b8abe-997c-549c-9791-87c78506c8b5")}catch{}})();import{readFileSync,readdirSync,realpathSync,statSync}from"node:fs";import os from"node:os";import path from"node:path";import{PM_DIRNAME,EXIT_CODE,SETTINGS_FILENAME,TYPE_TO_FOLDER}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{isFileAbsentError}from"../fs/fs-utils.js";import{toDefaultFolder}from"../item/type-registry.js";const ITEM_FILE_EXTENSION_BY_FORMAT={json_markdown:".md",toon:".toon"},ITEM_FORMAT_BY_EXTENSION={".md":"json_markdown",".toon":"toon"},NEARBY_TRACKER_SCAN_IGNORED_DIRECTORIES=new Set([".git","coverage","dist","node_modules"]),ITEM_FILE_EXTENSIONS=[".md",".toon"];function pathExists(pathValue){try{return statSync(pathValue),!0}catch{return!1}}function physicalDiscoveryStart(cwd){let ancestor=path.resolve(cwd);const missing=[];for(;path.dirname(ancestor)!==ancestor;)try{return path.join(realpathSync(ancestor),...missing)}catch(error){if(!isFileAbsentError(error))throw error;missing.unshift(path.basename(ancestor)),ancestor=path.dirname(ancestor)}return path.join(realpathSync(ancestor),...missing)}function repositoryBoundaryExists(marker){try{return statSync(marker),!0}catch(error){if(isFileAbsentError(error))return!1;throw error}}function isPmSettingsFile(settingsPath){try{const parsed=JSON.parse(readFileSync(settingsPath,"utf8"));return typeof parsed!="object"||parsed===null||Array.isArray(parsed)?!1:"id_prefix"in parsed||"item_format"in parsed}catch{return!1}}function discoverPmRootFromAncestors(cwd){let current=physicalDiscoveryStart(cwd);for(;;){const candidateRoot=path.join(current,PM_DIRNAME),candidateSettingsPath=path.join(candidateRoot,SETTINGS_FILENAME);if(pathExists(candidateSettingsPath))return candidateRoot;const rootLayoutSettingsPath=path.join(current,SETTINGS_FILENAME);if(pathExists(rootLayoutSettingsPath)&&isPmSettingsFile(rootLayoutSettingsPath))return current;if(repositoryBoundaryExists(path.join(current,".git")))return candidateRoot;const parent=path.dirname(current);if(parent===current)return;current=parent}}function resolveImplicitPmRoot(cwd){return discoverPmRootFromAncestors(cwd)??path.resolve(cwd,PM_DIRNAME)}function discoverNearbyPmRoot(cwd,excludedRoot){const normalizedExcluded=excludedRoot?path.resolve(excludedRoot):void 0;try{return readdirSync(path.resolve(cwd),{withFileTypes:!0}).filter(entry=>entry.isDirectory()&&!NEARBY_TRACKER_SCAN_IGNORED_DIRECTORIES.has(entry.name)).map(entry=>path.join(path.resolve(cwd),entry.name)).filter(candidate=>candidate!==normalizedExcluded).filter(candidate=>pathExists(getSettingsPath(candidate))).filter(candidate=>isPmSettingsFile(getSettingsPath(candidate))).sort((left,right)=>left.localeCompare(right))[0]}catch{return}}function resolvePmRoot(cwd,cliPath){const envPath=process.env.PM_PATH,explicitPath=cliPath?.trim()||envPath?.trim();if(explicitPath){const resolved=path.resolve(cwd,explicitPath);if(!pathExists(getSettingsPath(resolved))){const nestedRoot=path.join(resolved,PM_DIRNAME);if(pathExists(getSettingsPath(nestedRoot)))return nestedRoot}return resolved}return resolveImplicitPmRoot(cwd)}function resolveWorkspaceRoot(pmRoot){const normalizedRoot=path.resolve(pmRoot),parent=path.dirname(normalizedRoot);return path.basename(normalizedRoot)==="pm"&&path.basename(parent)===".agents"?path.dirname(parent):normalizedRoot}function resolveGlobalPmRoot(cwd){const envPath=process.env.PM_GLOBAL_PATH?.trim(),selected=envPath&&envPath.length>0?envPath:path.join(os.homedir(),".pm-cli");return path.resolve(cwd,selected)}function getSettingsPath(pmRoot){return path.join(pmRoot,SETTINGS_FILENAME)}function getTypeDirPath(pmRoot,type,typeToFolder=TYPE_TO_FOLDER){const folder=typeToFolder[type]??toDefaultFolder(type);return path.join(pmRoot,folder)}function getItemPath(pmRoot,type,id,itemFormat="toon",typeToFolder=TYPE_TO_FOLDER){return path.join(getTypeDirPath(pmRoot,type,typeToFolder),`${id}${ITEM_FILE_EXTENSION_BY_FORMAT[itemFormat]}`)}function getItemFormatFromPath(itemPath){const normalizedItemPath=itemPath.replaceAll("\\","/"),extension=path.posix.extname(normalizedItemPath).toLowerCase();return ITEM_FORMAT_BY_EXTENSION[extension]??null}function getHistoryPath(pmRoot,id){if(!/^(?!\.{1,2}$)[^/\\:\0]+$/.test(id))throw new PmCliError("Invalid history item id: expected a single filename.",EXIT_CODE.USAGE);return path.join(pmRoot,"history",`${id}.jsonl`)}function getLockPath(pmRoot,id){return path.join(pmRoot,"locks",`${id}.lock`)}function getRuntimePath(pmRoot){return path.join(pmRoot,"runtime")}function getTestRunsPath(pmRoot){return path.join(getRuntimePath(pmRoot),"test-runs")}function getTestRunsRecordsPath(pmRoot){return path.join(getTestRunsPath(pmRoot),"runs")}function getTestRunRecordPath(pmRoot,runId){return path.join(getTestRunsRecordsPath(pmRoot),`${runId}.json`)}function getTestRunsStdoutPath(pmRoot){return path.join(getTestRunsPath(pmRoot),"stdout")}function getTestRunsStderrPath(pmRoot){return path.join(getTestRunsPath(pmRoot),"stderr")}function getTestRunStdoutPath(pmRoot,runId){return path.join(getTestRunsStdoutPath(pmRoot),`${runId}.log`)}function getTestRunStderrPath(pmRoot,runId){return path.join(getTestRunsStderrPath(pmRoot),`${runId}.log`)}function getTestRunsResultsPath(pmRoot){return path.join(getTestRunsPath(pmRoot),"results")}function getTestRunResultPath(pmRoot,runId){return path.join(getTestRunsResultsPath(pmRoot),`${runId}.json`)}export{ITEM_FILE_EXTENSIONS,ITEM_FILE_EXTENSION_BY_FORMAT,discoverNearbyPmRoot,getHistoryPath,getItemFormatFromPath,getItemPath,getLockPath,getRuntimePath,getSettingsPath,getTestRunRecordPath,getTestRunResultPath,getTestRunStderrPath,getTestRunStdoutPath,getTestRunsPath,getTestRunsRecordsPath,getTestRunsResultsPath,getTestRunsStderrPath,getTestRunsStdoutPath,getTypeDirPath,resolveGlobalPmRoot,resolveImplicitPmRoot,resolvePmRoot,resolveWorkspaceRoot};
1
+ import{readFileSync as R,readdirSync as x,realpathSync as m,statSync as p}from"node:fs";import j from"node:os";import r from"node:path";import{PM_DIRNAME as l,EXIT_CODE as E,SETTINGS_FILENAME as f,TYPE_TO_FOLDER as d}from"../shared/constants.js";import{PmCliError as g}from"../shared/errors.js";import{isFileAbsentError as h}from"../fs/fs-utils.js";import{toDefaultFolder as T}from"../item/type-registry.js";const _={json_markdown:".md",toon:".toon"},S={".md":"json_markdown",".toon":"toon"},v=new Set([".git","coverage","dist","node_modules"]),Y=[".md",".toon"];function u(e){try{return p(e),!0}catch{return!1}}function y(e){let t=r.resolve(e);const o=[];for(;r.dirname(t)!==t;)try{return r.join(m(t),...o)}catch(n){if(!h(n))throw n;o.unshift(r.basename(t)),t=r.dirname(t)}return r.join(m(t),...o)}function I(e){try{return p(e),!0}catch(t){if(h(t))return!1;throw t}}function P(e){try{const t=JSON.parse(R(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function A(e){let t=y(e);for(;;){const o=r.join(t,l),n=r.join(o,f);if(u(n))return o;const i=r.join(t,f);if(u(i)&&P(i))return t;if(I(r.join(t,".git")))return o;const s=r.dirname(t);if(s===t)return;t=s}}function F(e){return A(e)??r.resolve(e,l)}function z(e,t){const o=t?r.resolve(t):void 0;try{return x(r.resolve(e),{withFileTypes:!0}).filter(n=>n.isDirectory()&&!v.has(n.name)).map(n=>r.join(r.resolve(e),n.name)).filter(n=>n!==o).filter(n=>u(a(n))).filter(n=>P(a(n))).sort((n,i)=>n.localeCompare(i))[0]}catch{return}}function H(e,t){const o=process.env.PM_PATH,n=t?.trim()||o?.trim();if(n){const i=r.resolve(e,n);if(!u(a(i))){const s=r.join(i,l);if(u(a(s)))return s}return i}return F(e)}function J(e){const t=r.resolve(e),o=r.dirname(t);return r.basename(t)==="pm"&&r.basename(o)===".agents"?r.dirname(o):t}function K(e){const t=process.env.PM_GLOBAL_PATH?.trim(),o=t&&t.length>0?t:r.join(j.homedir(),".pm-cli");return r.resolve(e,o)}function a(e){return r.join(e,f)}function N(e,t,o=d){const n=o[t]??T(t);return r.join(e,n)}function U(e,t,o,n="toon",i=d){return r.join(N(e,t,i),`${o}${_[n]}`)}function W(e){const t=e.replaceAll("\\","/"),o=r.posix.extname(t).toLowerCase();return S[o]??null}function q(e,t){if(!/^(?!\.{1,2}$)[^/\\:\0]+$/.test(t))throw new g("Invalid history item id: expected a single filename.",E.USAGE);return r.join(e,"history",`${t}.jsonl`)}function Q(e,t){return r.join(e,"locks",`${t}.lock`)}function O(e){return r.join(e,"runtime")}function c(e){return r.join(O(e),"test-runs")}function M(e){return r.join(c(e),"runs")}function V(e,t){return r.join(M(e),`${t}.json`)}function $(e){return r.join(c(e),"stdout")}function D(e){return r.join(c(e),"stderr")}function Z(e,t){return r.join($(e),`${t}.log`)}function tt(e,t){return r.join(D(e),`${t}.log`)}function L(e){return r.join(c(e),"results")}function et(e,t){return r.join(L(e),`${t}.json`)}export{Y as ITEM_FILE_EXTENSIONS,_ as ITEM_FILE_EXTENSION_BY_FORMAT,z as discoverNearbyPmRoot,q as getHistoryPath,W as getItemFormatFromPath,U as getItemPath,Q as getLockPath,O as getRuntimePath,a as getSettingsPath,V as getTestRunRecordPath,et as getTestRunResultPath,tt as getTestRunStderrPath,Z as getTestRunStdoutPath,c as getTestRunsPath,M as getTestRunsRecordsPath,L as getTestRunsResultsPath,D as getTestRunsStderrPath,$ as getTestRunsStdoutPath,N as getTypeDirPath,K as resolveGlobalPmRoot,F as resolveImplicitPmRoot,H as resolvePmRoot,J as resolveWorkspaceRoot};
2
2
  //# sourceMappingURL=paths.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a0ca9902-540c-50fe-a4e2-9c234c4a01f3")}catch{}})();import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{stableValueEquals}from"../shared/serialization.js";function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function reconcileSettingsSnapshot(baseline,proposed,current,segments=[]){if(stableValueEquals(baseline,proposed)&&(segments.length>0||isRecord(current)))return current;if(stableValueEquals(baseline,current)||stableValueEquals(proposed,current))return proposed;if((baseline===void 0||isRecord(baseline))&&isRecord(proposed)&&isRecord(current)){const before=baseline??{},keys=new Set([...Object.keys(before),...Object.keys(proposed),...Object.keys(current)]);return Object.fromEntries([...keys].flatMap(key=>{const merged=reconcileSettingsSnapshot(Object.hasOwn(before,key)?before[key]:void 0,Object.hasOwn(proposed,key)?proposed[key]:void 0,Object.hasOwn(current,key)?current[key]:void 0,[...segments,key]);return merged===void 0?[]:[[key,merged]]}))}throw new PmCliError(`Settings changed concurrently at ${segments.join(".")||"<root>"}; read the latest settings and reapply the intended change.`,EXIT_CODE.CONFLICT,{reason:"stale_settings_snapshot",required:"Read a fresh settings snapshot and reapply the intended change.",why:"Another writer changed the same setting after this snapshot was read.",examples:["pm config project export --json"],nextSteps:["Read the current settings, then retry the original config operation."]})}export{reconcileSettingsSnapshot};
1
+ import{EXIT_CODE as c}from"../shared/constants.js";import{PmCliError as d}from"../shared/errors.js";import{stableValueEquals as o}from"../shared/serialization.js";function i(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function g(t,r,e,a=[]){if(o(t,r)&&(a.length>0||i(e)))return e;if(o(t,e)||o(r,e))return r;if((t===void 0||i(t))&&i(r)&&i(e)){const s=t??{},f=new Set([...Object.keys(s),...Object.keys(r),...Object.keys(e)]);return Object.fromEntries([...f].flatMap(n=>{const h=g(Object.hasOwn(s,n)?s[n]:void 0,Object.hasOwn(r,n)?r[n]:void 0,Object.hasOwn(e,n)?e[n]:void 0,[...a,n]);return h===void 0?[]:[[n,h]]}))}throw new d(`Settings changed concurrently at ${a.join(".")||"<root>"}; read the latest settings and reapply the intended change.`,c.CONFLICT,{reason:"stale_settings_snapshot",required:"Read a fresh settings snapshot and reapply the intended change.",why:"Another writer changed the same setting after this snapshot was read.",examples:["pm config project export --json"],nextSteps:["Read the current settings, then retry the original config operation."]})}export{g as reconcileSettingsSnapshot};
2
2
  //# sourceMappingURL=settings-concurrency.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="78c79deb-5cf0-54fe-b98c-a0d5b3671ab2")}catch{}})();import{stat}from"node:fs/promises";const settingsReadCacheByRoot=new Map;function normalizeTrackedPaths(paths){return[...new Set(paths.map(pathValue=>pathValue.trim()).filter(pathValue=>pathValue.length>0))].sort((left,right)=>left.localeCompare(right))}async function readPathSignature(targetPath){try{const targetStats=await stat(targetPath);return{path:targetPath,mtime_ms:targetStats.mtimeMs,size:targetStats.size}}catch{return{path:targetPath,mtime_ms:null,size:null}}}async function collectSettingsReadCacheSignatures(paths){const normalizedPaths=normalizeTrackedPaths(paths),signatures=await Promise.all(normalizedPaths.map(targetPath=>readPathSignature(targetPath)));return signatures.sort((left,right)=>left.path.localeCompare(right.path)),signatures}function settingsReadCacheSignaturesEqual(left,right){if(left.length!==right.length)return!1;for(let index=0;index<left.length;index+=1){const leftEntry=left[index],rightEntry=right[index];if(leftEntry.path!==rightEntry.path||leftEntry.mtime_ms!==rightEntry.mtime_ms||leftEntry.size!==rightEntry.size)return!1}return!0}function getSettingsReadCacheEntry(pmRoot){return settingsReadCacheByRoot.get(pmRoot)}function setSettingsReadCacheEntry(pmRoot,entry){const normalizedTrackedPaths=normalizeTrackedPaths(entry.tracked_paths),normalizedSignatures=[...entry.signatures].map(signature=>({path:signature.path,mtime_ms:signature.mtime_ms,size:signature.size})).sort((left,right)=>left.path.localeCompare(right.path));settingsReadCacheByRoot.set(pmRoot,{tracked_paths:normalizedTrackedPaths,signatures:normalizedSignatures,value:entry.value})}function clearSettingsReadCache(pmRoot){if(pmRoot){settingsReadCacheByRoot.delete(pmRoot);return}settingsReadCacheByRoot.clear()}export{clearSettingsReadCache,collectSettingsReadCacheSignatures,getSettingsReadCacheEntry,setSettingsReadCacheEntry,settingsReadCacheSignaturesEqual};
1
+ import{stat as c}from"node:fs/promises";const s=new Map;function i(t){return[...new Set(t.map(e=>e.trim()).filter(e=>e.length>0))].sort((e,a)=>e.localeCompare(a))}async function m(t){try{const e=await c(t);return{path:t,mtime_ms:e.mtimeMs,size:e.size}}catch{return{path:t,mtime_ms:null,size:null}}}async function u(t){const e=i(t),a=await Promise.all(e.map(r=>m(r)));return a.sort((r,n)=>r.path.localeCompare(n.path)),a}function h(t,e){if(t.length!==e.length)return!1;for(let a=0;a<t.length;a+=1){const r=t[a],n=e[a];if(r.path!==n.path||r.mtime_ms!==n.mtime_ms||r.size!==n.size)return!1}return!0}function p(t){return s.get(t)}function d(t,e){const a=i(e.tracked_paths),r=[...e.signatures].map(n=>({path:n.path,mtime_ms:n.mtime_ms,size:n.size})).sort((n,o)=>n.path.localeCompare(o.path));s.set(t,{tracked_paths:a,signatures:r,value:e.value})}function g(t){if(t){s.delete(t);return}s.clear()}export{g as clearSettingsReadCache,u as collectSettingsReadCacheSignatures,p as getSettingsReadCacheEntry,d as setSettingsReadCacheEntry,h as settingsReadCacheSignaturesEqual};
2
2
  //# sourceMappingURL=settings-read-cache.js.map
@@ -1,3 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7cbbb50d-e9bc-5940-9ae6-6270e9c2fcbf")}catch{}})();import{createHash}from"node:crypto";import{readFileIfExists}from"../fs/fs-utils.js";import{runActiveOnReadHooks,runActiveOnWriteHooks}from"../extensions/index.js";import{mutateWorkspaceJsonWithHistory}from"../history/workspace-history.js";import{resolveAuthor}from"../shared/author.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{toErrorMessage}from"../shared/primitives.js";import{stableValueEquals}from"../shared/serialization.js";import{getSettingsPath}from"./paths.js";import{readSettings}from"./settings.js";import{clearSettingsReadCache}from"./settings-read-cache.js";import{CORE_SETTINGS_SECTION_KEYS}from"./settings-validator.js";const SETTINGS_SECTION_NAME_PATTERN=/^[a-z][a-z0-9_-]{0,63}$/u,RESERVED_SECTION_NAMES=new Set(["constructor","prototype"]),SETTINGS_SECTION_WRITE_OP="settings:section:write",MAX_VALIDATION_MESSAGE_LENGTH=240;function settingsSectionRevision(value){return`sha256:${createHash("sha256").update(canonicalSectionJson(value)).digest("hex")}`}function canonicalSectionJson(value){return Array.isArray(value)?`[${value.map(entry=>canonicalSectionJson(entry)).join(",")}]`:typeof value=="object"&&value!==null?`{${Object.keys(value).sort().map(key=>`${JSON.stringify(key)}:${canonicalSectionJson(Object.getOwnPropertyDescriptor(value,key)?.value)}`).join(",")}}`:String(JSON.stringify(value))}function assertSettingsSectionName(section){if(!SETTINGS_SECTION_NAME_PATTERN.test(section)||RESERVED_SECTION_NAMES.has(section))throw new PmCliError(`Invalid settings section name "${section.slice(0,80)}". Use 1-64 lowercase letters, digits, underscores or hyphens, starting with a letter.`,EXIT_CODE.USAGE,{code:"settings_section_name_invalid",field:"section",required:"Name the section after the package, for example lint or jev."});if(CORE_SETTINGS_SECTION_KEYS.includes(section))throw new PmCliError(`Settings section "${section}" is owned by core settings; extension sections must use another name.`,EXIT_CODE.USAGE,{code:"settings_section_reserved",field:"section",value:section,required:"Read core settings with readSettings and change them with writeSettings or pm config."})}function parseSettingsDocument(raw){let parsed;try{parsed=JSON.parse(raw)}catch{parsed=void 0}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new PmCliError("settings.json is not a JSON object, so no settings section can be read or written.",EXIT_CODE.USAGE,{code:"settings_section_document_malformed",reason:parsed===void 0?"settings_json_malformed":"settings_json_not_object",nextSteps:["Repair .agents/pm/settings.json so it is a JSON object, then retry.","Run pm health to confirm the settings warning has cleared."]});return parsed}function validateSectionValue(section,raw,validate){let value;try{value=validate===void 0?raw:validate(raw)}catch(error){throw new PmCliError(`Settings section "${section}" is invalid: ${toErrorMessage(error).slice(0,MAX_VALIDATION_MESSAGE_LENGTH)}`,EXIT_CODE.USAGE,{code:"settings_section_invalid",field:section,required:`Fix the "${section}" section of .agents/pm/settings.json so the owning package accepts it, then retry.`})}return value}function hasJsonHook(value){return typeof Reflect.get(value,"toJSON")=="function"}function describeJsonPath(segments){return segments.length===0?"the value":segments.join(".")}function hasOnlyDataProperties(value,requireEnumerable){return Object.values(Object.getOwnPropertyDescriptors(value)).every(descriptor=>"value"in descriptor&&(!requireEnumerable||descriptor.enumerable===!0))}function isPlainJsonArray(value){if(Object.getPrototypeOf(value)!==Array.prototype||!hasOnlyDataProperties(value,!1))return!1;const keys=Object.keys(value);return keys.length===value.length&&keys.every((key,index)=>key===String(index))&&Object.getOwnPropertyNames(value).length===value.length+1&&Object.getOwnPropertySymbols(value).length===0&&!hasJsonHook(value)}function isPlainJsonObject(value){const prototype=Object.getPrototypeOf(value);return(prototype===Object.prototype||prototype===null)&&hasOnlyDataProperties(value,!0)&&Object.getOwnPropertySymbols(value).length===0&&!hasJsonHook(value)}function findScalarDrift(value,segments){if(value===null||typeof value=="string"||typeof value=="boolean")return null;const where=describeJsonPath(segments);return typeof value=="number"?Number.isFinite(value)?null:{detail:`${where} is a non-finite number`,representable:!0}:{detail:`${where} is ${typeof value}`,representable:typeof value!="bigint"&&segments.length>0}}function findJsonDrift(value,segments=[],ancestors=new Set){if(typeof value!="object"||value===null)return findScalarDrift(value,segments);const where=describeJsonPath(segments);if(ancestors.has(value))return{detail:`${where} is a circular reference`,representable:!1};if(!(Array.isArray(value)?isPlainJsonArray(value):isPlainJsonObject(value)))return{detail:`${where} is not a plain JSON ${Array.isArray(value)?"array":"object"}`,representable:!0};ancestors.add(value);for(const[key,entry]of Object.entries(value)){const drift=findJsonDrift(entry,[...segments,key],ancestors);if(drift!==null)return drift}return ancestors.delete(value),null}function findReservedJsonKey(value,segments=[]){if(typeof value!="object"||value===null)return null;for(const[key,entry]of Object.entries(value)){const keyPath=[...segments,key];if(key==="__proto__"||key==="prototype"&&segments.at(-1)==="constructor")return describeJsonPath(keyPath);const nested=findReservedJsonKey(entry,keyPath);if(nested!==null)return nested}return null}function refuseSectionValue(section,value,reason){return validateSectionValue(section,value,()=>{throw new Error(reason)})}function toStoredSectionValue(section,value){const drift=findJsonDrift(value);if(drift!==null){const reason=drift.representable?`the value would change when stored as JSON: ${drift.detail}`:`the value is not representable as JSON: ${drift.detail}`;return refuseSectionValue(section,value,reason)}const reserved=findReservedJsonKey(value);return reserved!==null?refuseSectionValue(section,value,`${reserved} is a reserved key that settings history cannot record`):JSON.parse(JSON.stringify(value))}function readSectionEntry(document,section){return Object.hasOwn(document,section)?document[section]:void 0}async function readSettingsSection(pmRoot,section,options={}){assertSettingsSectionName(section);const settingsPath=getSettingsPath(pmRoot);await runActiveOnReadHooks({path:settingsPath,scope:"project"});const raw=await readFileIfExists(settingsPath),stored=raw===null?void 0:readSectionEntry(parseSettingsDocument(raw),section);if(stored===void 0)return{section,source:"default",value:options.defaultValue,revision:null};const revision=settingsSectionRevision(stored);return{section,source:"stored",value:validateSectionValue(section,structuredClone(stored),options.validate),revision}}async function writeSettingsSection(pmRoot,section,value,options={}){assertSettingsSectionName(section);const next=value===void 0?void 0:toStoredSectionValue(section,validateSectionValue(section,value,options.validate)),settingsPath=getSettingsPath(pmRoot),settings=await readSettings(pmRoot);try{const mutation=await mutateWorkspaceJsonWithHistory({pmRoot,filePath:settingsPath,op:SETTINGS_SECTION_WRITE_OP,author:resolveAuthor(options.author,settings.author_default),lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms,recordCreation:!1,mutate:beforeRaw=>{if(beforeRaw===null)throw new PmCliError("settings.json does not exist, so no settings section can be written.",EXIT_CODE.NOT_FOUND,{code:"settings_section_document_missing",required:"Initialize the tracker with pm init, then retry."});const document=parseSettingsDocument(beforeRaw),current=readSectionEntry(document,section),previousRevision=current===void 0?null:settingsSectionRevision(current);if(options.expectedRevision!==void 0&&options.expectedRevision!==previousRevision)throw new PmCliError(`Settings section "${section}" changed since it was read; read it again and reapply the change.`,EXIT_CODE.CONFLICT,{code:"settings_section_revision_conflict",field:section,expected_revision:options.expectedRevision,current_revision:previousRevision,required:"Read the section again with readSettingsSection, then retry with its current revision."});const receipt={section,changed:!1,previous_revision:previousRevision,revision:next===void 0?null:settingsSectionRevision(next)};return stableValueEquals(current,next)?{raw:beforeRaw,result:receipt}:(next===void 0?delete document[section]:document[section]=next,{raw:`${JSON.stringify(document,null,2)}
2
- `,result:{...receipt,changed:!0}})}});return mutation.changed&&await runActiveOnWriteHooks({path:settingsPath,scope:"project",op:SETTINGS_SECTION_WRITE_OP}),mutation.result}finally{clearSettingsReadCache(pmRoot)}}export{readSettingsSection,settingsSectionRevision,writeSettingsSection};
1
+ import{createHash as P}from"node:crypto";import{readFileIfExists as T}from"../fs/fs-utils.js";import{runActiveOnReadHooks as k,runActiveOnWriteHooks as x}from"../extensions/index.js";import{mutateWorkspaceJsonWithHistory as I}from"../history/workspace-history.js";import{resolveAuthor as R}from"../shared/author.js";import{EXIT_CODE as c}from"../shared/constants.js";import{PmCliError as a}from"../shared/errors.js";import{toErrorMessage as C}from"../shared/primitives.js";import{stableValueEquals as D}from"../shared/serialization.js";import{getSettingsPath as O}from"./paths.js";import{readSettings as G}from"./settings.js";import{clearSettingsReadCache as V}from"./settings-read-cache.js";import{CORE_SETTINGS_SECTION_KEYS as q}from"./settings-validator.js";const H=/^[a-z][a-z0-9_-]{0,63}$/u,M=new Set(["constructor","prototype"]),w="settings:section:write",U=240;function h(e){return`sha256:${P("sha256").update(g(e)).digest("hex")}`}function g(e){return Array.isArray(e)?`[${e.map(t=>g(t)).join(",")}]`:typeof e=="object"&&e!==null?`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${g(Object.getOwnPropertyDescriptor(e,n)?.value)}`).join(",")}}`:String(JSON.stringify(e))}function _(e){if(!H.test(e)||M.has(e))throw new a(`Invalid settings section name "${e.slice(0,80)}". Use 1-64 lowercase letters, digits, underscores or hyphens, starting with a letter.`,c.USAGE,{code:"settings_section_name_invalid",field:"section",required:"Name the section after the package, for example lint or jev."});if(q.includes(e))throw new a(`Settings section "${e}" is owned by core settings; extension sections must use another name.`,c.USAGE,{code:"settings_section_reserved",field:"section",value:e,required:"Read core settings with readSettings and change them with writeSettings or pm config."})}function b(e){let t;try{t=JSON.parse(e)}catch{t=void 0}if(typeof t!="object"||t===null||Array.isArray(t))throw new a("settings.json is not a JSON object, so no settings section can be read or written.",c.USAGE,{code:"settings_section_document_malformed",reason:t===void 0?"settings_json_malformed":"settings_json_not_object",nextSteps:["Repair .agents/pm/settings.json so it is a JSON object, then retry.","Run pm health to confirm the settings warning has cleared."]});return t}function y(e,t,n){let r;try{r=n===void 0?t:n(t)}catch(i){throw new a(`Settings section "${e}" is invalid: ${C(i).slice(0,U)}`,c.USAGE,{code:"settings_section_invalid",field:e,required:`Fix the "${e}" section of .agents/pm/settings.json so the owning package accepts it, then retry.`})}return r}function j(e){return typeof Reflect.get(e,"toJSON")=="function"}function S(e){return e.length===0?"the value":e.join(".")}function E(e,t){return Object.values(Object.getOwnPropertyDescriptors(e)).every(n=>"value"in n&&(!t||n.enumerable===!0))}function F(e){if(Object.getPrototypeOf(e)!==Array.prototype||!E(e,!1))return!1;const t=Object.keys(e);return t.length===e.length&&t.every((n,r)=>n===String(r))&&Object.getOwnPropertyNames(e).length===e.length+1&&Object.getOwnPropertySymbols(e).length===0&&!j(e)}function W(e){const t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&E(e,!0)&&Object.getOwnPropertySymbols(e).length===0&&!j(e)}function z(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return null;const n=S(t);return typeof e=="number"?Number.isFinite(e)?null:{detail:`${n} is a non-finite number`,representable:!0}:{detail:`${n} is ${typeof e}`,representable:typeof e!="bigint"&&t.length>0}}function N(e,t=[],n=new Set){if(typeof e!="object"||e===null)return z(e,t);const r=S(t);if(n.has(e))return{detail:`${r} is a circular reference`,representable:!1};if(!(Array.isArray(e)?F(e):W(e)))return{detail:`${r} is not a plain JSON ${Array.isArray(e)?"array":"object"}`,representable:!0};n.add(e);for(const[o,s]of Object.entries(e)){const f=N(s,[...t,o],n);if(f!==null)return f}return n.delete(e),null}function A(e,t=[]){if(typeof e!="object"||e===null)return null;for(const[n,r]of Object.entries(e)){const i=[...t,n];if(n==="__proto__"||n==="prototype"&&t.at(-1)==="constructor")return S(i);const o=A(r,i);if(o!==null)return o}return null}function $(e,t,n){return y(e,t,()=>{throw new Error(n)})}function L(e,t){const n=N(t);if(n!==null){const i=n.representable?`the value would change when stored as JSON: ${n.detail}`:`the value is not representable as JSON: ${n.detail}`;return $(e,t,i)}const r=A(t);return r!==null?$(e,t,`${r} is a reserved key that settings history cannot record`):JSON.parse(JSON.stringify(t))}function J(e,t){return Object.hasOwn(e,t)?e[t]:void 0}async function se(e,t,n={}){_(t);const r=O(e);await k({path:r,scope:"project"});const i=await T(r),o=i===null?void 0:J(b(i),t);if(o===void 0)return{section:t,source:"default",value:n.defaultValue,revision:null};const s=h(o);return{section:t,source:"stored",value:y(t,structuredClone(o),n.validate),revision:s}}async function ce(e,t,n,r={}){_(t);const i=n===void 0?void 0:L(t,y(t,n,r.validate)),o=O(e),s=await G(e);try{const f=await I({pmRoot:e,filePath:o,op:w,author:R(r.author,s.author_default),lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms,recordCreation:!1,mutate:d=>{if(d===null)throw new a("settings.json does not exist, so no settings section can be written.",c.NOT_FOUND,{code:"settings_section_document_missing",required:"Initialize the tracker with pm init, then retry."});const u=b(d),l=J(u,t),p=l===void 0?null:h(l);if(r.expectedRevision!==void 0&&r.expectedRevision!==p)throw new a(`Settings section "${t}" changed since it was read; read it again and reapply the change.`,c.CONFLICT,{code:"settings_section_revision_conflict",field:t,expected_revision:r.expectedRevision,current_revision:p,required:"Read the section again with readSettingsSection, then retry with its current revision."});const m={section:t,changed:!1,previous_revision:p,revision:i===void 0?null:h(i)};return D(l,i)?{raw:d,result:m}:(i===void 0?delete u[t]:u[t]=i,{raw:`${JSON.stringify(u,null,2)}
2
+ `,result:{...m,changed:!0}})}});return f.changed&&await x({path:o,scope:"project",op:w}),f.result}finally{V(e)}}export{se as readSettingsSection,h as settingsSectionRevision,ce as writeSettingsSection};
3
3
  //# sourceMappingURL=settings-sections.js.map