@unbrained/pm-cli 2026.11.21 → 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 (943) hide show
  1. package/.agents/skills/pm-developer/SKILL.md +1 -1
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/dist/cli/after-command-context-usage.js +1 -1
  4. package/dist/cli/argv-utils.js +1 -1
  5. package/dist/cli/bootstrap-args.js +1 -1
  6. package/dist/cli/bundle-integrity.js +2 -2
  7. package/dist/cli/command-namespaces.js +1 -1
  8. package/dist/cli/commander-usage.js +11 -11
  9. package/dist/cli/commands/annotations/comments.js +1 -1
  10. package/dist/cli/commands/annotations/docs.js +1 -1
  11. package/dist/cli/commands/annotations/files.js +1 -1
  12. package/dist/cli/commands/annotations/learnings.js +1 -1
  13. package/dist/cli/commands/annotations/notes.js +1 -1
  14. package/dist/cli/commands/extension/describe.js +1 -1
  15. package/dist/cli/commands/extension/extension.js +1 -1
  16. package/dist/cli/commands/extension/scaffold.js +1 -1
  17. package/dist/cli/commands/extension/shared.js +1 -1
  18. package/dist/cli/commands/governance/gc.js +1 -1
  19. package/dist/cli/commands/governance/health.js +1 -1
  20. package/dist/cli/commands/governance/telemetry.js +1 -1
  21. package/dist/cli/commands/governance/validate.js +1 -1
  22. package/dist/cli/commands/history/activity.js +1 -1
  23. package/dist/cli/commands/history/history-compact.js +1 -1
  24. package/dist/cli/commands/history/history-redact.js +1 -1
  25. package/dist/cli/commands/history/history-repair.js +1 -1
  26. package/dist/cli/commands/history/history.js +1 -1
  27. package/dist/cli/commands/history/restore.js +1 -1
  28. package/dist/cli/commands/lifecycle/append.js +1 -1
  29. package/dist/cli/commands/lifecycle/claim.js +1 -1
  30. package/dist/cli/commands/lifecycle/close-many.js +1 -1
  31. package/dist/cli/commands/lifecycle/close.js +1 -1
  32. package/dist/cli/commands/lifecycle/copy.js +1 -1
  33. package/dist/cli/commands/lifecycle/create.js +1 -1
  34. package/dist/cli/commands/lifecycle/delete.js +1 -1
  35. package/dist/cli/commands/lifecycle/focus.js +1 -1
  36. package/dist/cli/commands/lifecycle/plan.js +1 -1
  37. package/dist/cli/commands/lifecycle/update-many.js +1 -1
  38. package/dist/cli/commands/lifecycle/update.js +1 -1
  39. package/dist/cli/commands/query/aggregate.js +1 -1
  40. package/dist/cli/commands/query/context.js +1 -1
  41. package/dist/cli/commands/query/deps.js +1 -1
  42. package/dist/cli/commands/query/duplicates.js +1 -1
  43. package/dist/cli/commands/query/eval.js +1 -1
  44. package/dist/cli/commands/query/get.js +1 -1
  45. package/dist/cli/commands/query/graph.js +1 -1
  46. package/dist/cli/commands/query/list.js +1 -1
  47. package/dist/cli/commands/query/next.js +1 -1
  48. package/dist/cli/commands/query/search.js +1 -1
  49. package/dist/cli/commands/query/stats.js +1 -1
  50. package/dist/cli/commands/test/test-all.js +1 -1
  51. package/dist/cli/commands/test/test-runs.js +1 -1
  52. package/dist/cli/commands/test/test.js +1 -1
  53. package/dist/cli/commands/workspace/config.js +1 -1
  54. package/dist/cli/commands/workspace/contracts.js +1 -1
  55. package/dist/cli/commands/workspace/init.js +1 -1
  56. package/dist/cli/commands/workspace/merge.js +1 -1
  57. package/dist/cli/commands/workspace/profile.js +1 -1
  58. package/dist/cli/commands/workspace/schema.js +1 -1
  59. package/dist/cli/commands/workspace/upgrade.js +1 -1
  60. package/dist/cli/context-intent-invocation.js +1 -1
  61. package/dist/cli/description-stdin.js +1 -1
  62. package/dist/cli/error-guidance.js +5 -5
  63. package/dist/cli/expected-revisions.js +1 -1
  64. package/dist/cli/extension-command-help.js +6 -6
  65. package/dist/cli/extension-recovery.js +1 -1
  66. package/dist/cli/help-content.js +5 -5
  67. package/dist/cli/help-json-payload.js +7 -7
  68. package/dist/cli/invocation-profile.js +2 -2
  69. package/dist/cli/main.js +5 -5
  70. package/dist/cli/migration-gates.js +1 -1
  71. package/dist/cli/option-values.js +1 -1
  72. package/dist/cli/preflight-warnings.js +3 -3
  73. package/dist/cli/public.js +1 -1
  74. package/dist/cli/register-annotations.js +1 -1
  75. package/dist/cli/register-assurance.js +1 -1
  76. package/dist/cli/register-files-lookup.js +1 -1
  77. package/dist/cli/register-history-activity.js +1 -1
  78. package/dist/cli/register-history-author.js +1 -1
  79. package/dist/cli/register-history-maintenance.js +2 -2
  80. package/dist/cli/register-list-query.js +10 -10
  81. package/dist/cli/register-mutation-options.js +0 -1
  82. package/dist/cli/register-mutation.js +6 -6
  83. package/dist/cli/register-operations.js +1 -1
  84. package/dist/cli/register-setup.js +1 -1
  85. package/dist/cli/register-structured-mutation.js +1 -1
  86. package/dist/cli/registration-helpers.js +1 -1
  87. package/dist/cli/runtime/activation.js +1 -1
  88. package/dist/cli/runtime/annotation-option-retry.js +1 -1
  89. package/dist/cli/runtime/close-fields-retry.js +1 -1
  90. package/dist/cli/runtime/field-route-retry.js +1 -1
  91. package/dist/cli/runtime/invocation-options.js +1 -1
  92. package/dist/cli/runtime/invocation-rewrites.js +1 -1
  93. package/dist/cli/runtime/projection-retry.js +1 -1
  94. package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
  95. package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
  96. package/dist/cli/runtime/selection.js +1 -1
  97. package/dist/cli/runtime/telemetry-outcome.js +1 -1
  98. package/dist/cli/runtime-compatibility-boundary.js +4 -4
  99. package/dist/cli/schema/registration.js +15 -15
  100. package/dist/cli/schema-registration-helpers.js +1 -1
  101. package/dist/cli/search-refresh.js +1 -1
  102. package/dist/cli/stats-analytics-json.js +1 -1
  103. package/dist/cli/telemetry-flush.js +1 -1
  104. package/dist/cli-bundle/bundle-manifest.json +1 -1
  105. package/dist/cli-bundle/chunks/chunk-2UQU7HRR.js +9 -0
  106. package/dist/cli-bundle/chunks/chunk-5DUP4AZA.js +2 -0
  107. package/dist/cli-bundle/chunks/chunk-5WZZ5XEN.js +3 -0
  108. package/dist/cli-bundle/chunks/chunk-6H36ZHMI.js +2 -0
  109. package/dist/cli-bundle/chunks/chunk-6MYJLOSG.js +2 -0
  110. package/dist/cli-bundle/chunks/chunk-AA52P34H.js +3 -0
  111. package/dist/cli-bundle/chunks/chunk-AEOHUSUI.js +2289 -0
  112. package/dist/cli-bundle/chunks/chunk-BSRIVYTM.js +8 -0
  113. package/dist/cli-bundle/chunks/chunk-CFWLQFJM.js +71 -0
  114. package/dist/cli-bundle/chunks/chunk-D6PDUKUG.js +9 -0
  115. package/dist/cli-bundle/chunks/chunk-ENKXRSFZ.js +31 -0
  116. package/dist/cli-bundle/chunks/chunk-F2Z6XLZB.js +3 -0
  117. package/dist/cli-bundle/chunks/chunk-FJOEL75F.js +2 -0
  118. package/dist/cli-bundle/chunks/chunk-GDXCAC52.js +2 -0
  119. package/dist/cli-bundle/chunks/chunk-H7JEXRIN.js +6 -0
  120. package/dist/cli-bundle/chunks/chunk-J2PDAVBC.js +2 -0
  121. package/dist/cli-bundle/chunks/chunk-KE7HMBEW.js +2 -0
  122. package/dist/cli-bundle/chunks/chunk-KZHIBEJL.js +33 -0
  123. package/dist/cli-bundle/chunks/chunk-NGJ5ERBF.js +115 -0
  124. package/dist/cli-bundle/chunks/chunk-NQ54T7T2.js +2 -0
  125. package/dist/cli-bundle/chunks/chunk-O7JHS64G.js +3 -0
  126. package/dist/cli-bundle/chunks/chunk-OKEZF7HU.js +2 -0
  127. package/dist/cli-bundle/chunks/chunk-OKIKF4FD.js +2 -0
  128. package/dist/cli-bundle/chunks/chunk-OPJF254V.js +9 -0
  129. package/dist/cli-bundle/chunks/chunk-PZA7QECY.js +1 -0
  130. package/dist/cli-bundle/chunks/chunk-RWA5YZ5X.js +2 -0
  131. package/dist/cli-bundle/chunks/chunk-S32NGRQM.js +2 -0
  132. package/dist/cli-bundle/chunks/chunk-SLFRSZK6.js +1 -0
  133. package/dist/cli-bundle/chunks/chunk-TZY5MVJF.js +125 -0
  134. package/dist/cli-bundle/chunks/chunk-YYT3MIRF.js +3 -0
  135. package/dist/cli-bundle/chunks/chunk-ZPS4B6SI.js +8 -0
  136. package/dist/cli-bundle/chunks/context-budget-recovery-M5RFUEFG.js +2 -0
  137. package/dist/cli-bundle/chunks/indexed-receipt-blobs-BPYKN5Q7.js +4 -0
  138. package/dist/cli-bundle/chunks/{item-revision-R5SZPJZ5.js → item-revision-FMD4KWBB.js} +2 -2
  139. package/dist/cli-bundle/chunks/item-transaction-SEHTH7N2.js +2 -0
  140. package/dist/cli-bundle/chunks/mutation-actor-SFGYIRPW.js +2 -0
  141. package/dist/cli-bundle/chunks/mutation-admission-57LBSKQI.js +2 -0
  142. package/dist/cli-bundle/chunks/{register-list-query-SPGPS3OS.js → register-list-query-L4IBU64P.js} +11 -11
  143. package/dist/cli-bundle/chunks/register-mutation-6NUOPHZ3.js +21 -0
  144. package/dist/cli-bundle/chunks/register-operations-JGYVORNN.js +2 -0
  145. package/dist/cli-bundle/chunks/register-setup-C44SIXEH.js +2 -0
  146. package/dist/cli-bundle/chunks/settlement-hook-6MR32OOC.js +7 -0
  147. package/dist/cli-bundle/chunks/stage-PQ7AB63N.js +2 -0
  148. package/dist/cli-bundle/focused-chunks/chunk-6LKTEKHS.js +6 -0
  149. package/dist/cli-bundle/focused-chunks/chunk-6LPXMFLM.js +2 -0
  150. package/dist/cli-bundle/focused-chunks/chunk-A6VEMCRR.js +3 -0
  151. package/dist/cli-bundle/focused-chunks/chunk-AIDL2ZNT.js +3 -0
  152. package/dist/cli-bundle/focused-chunks/chunk-BKPUUW5O.js +1 -0
  153. package/dist/cli-bundle/focused-chunks/chunk-BWOVFE5B.js +2 -0
  154. package/dist/cli-bundle/focused-chunks/chunk-HMDQDRV2.js +8 -0
  155. package/dist/cli-bundle/focused-chunks/chunk-I66IKYKP.js +2 -0
  156. package/dist/cli-bundle/focused-chunks/chunk-IIP6LZ5E.js +2 -0
  157. package/dist/cli-bundle/focused-chunks/chunk-IR2J3NOT.js +2 -0
  158. package/dist/cli-bundle/focused-chunks/chunk-IROZDIDX.js +3 -0
  159. package/dist/cli-bundle/focused-chunks/chunk-ITKDHSBR.js +2 -0
  160. package/dist/cli-bundle/focused-chunks/chunk-K53OIT5J.js +2 -0
  161. package/dist/cli-bundle/focused-chunks/chunk-LQYYPXUK.js +26 -0
  162. package/dist/cli-bundle/focused-chunks/chunk-NQTEE66P.js +13 -0
  163. package/dist/cli-bundle/focused-chunks/chunk-O7Z73ALG.js +2 -0
  164. package/dist/cli-bundle/focused-chunks/chunk-OTMMOKPM.js +91 -0
  165. package/dist/cli-bundle/focused-chunks/chunk-OXOCZJC6.js +2 -0
  166. package/dist/cli-bundle/focused-chunks/chunk-QLAHEDT6.js +2 -0
  167. package/dist/cli-bundle/focused-chunks/chunk-QQIIMMFU.js +2 -0
  168. package/dist/cli-bundle/focused-chunks/chunk-RIE3SJSE.js +9 -0
  169. package/dist/cli-bundle/focused-chunks/chunk-TD544C74.js +8 -0
  170. package/dist/cli-bundle/focused-chunks/chunk-UFTUNBMY.js +27 -0
  171. package/dist/cli-bundle/focused-chunks/chunk-X6CXWWNB.js +2 -0
  172. package/dist/cli-bundle/focused-chunks/chunk-XRS3VNC6.js +44 -0
  173. package/dist/cli-bundle/focused-chunks/chunk-XYPEZGTR.js +2 -0
  174. package/dist/cli-bundle/focused-chunks/chunk-Y2ESLKCF.js +8 -0
  175. package/dist/cli-bundle/focused-chunks/chunk-YSJKQLFR.js +2 -0
  176. package/dist/cli-bundle/focused-chunks/chunk-Z2X7HH3C.js +102 -0
  177. package/dist/cli-bundle/focused-chunks/chunk-ZHWPCVQL.js +78 -0
  178. package/dist/cli-bundle/focused-chunks/context-budget-recovery-CSJV3TY3.js +2 -0
  179. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-EGEJMG3G.js +4 -0
  180. package/dist/cli-bundle/focused-chunks/{item-revision-3V3UIP5X.js → item-revision-YDACCDVY.js} +2 -2
  181. package/dist/cli-bundle/focused-chunks/item-transaction-UKEQCTKB.js +2 -0
  182. package/dist/cli-bundle/focused-chunks/mutation-actor-AS465LRX.js +2 -0
  183. package/dist/cli-bundle/focused-chunks/mutation-admission-E5UHJZFE.js +2 -0
  184. package/dist/cli-bundle/focused-chunks/settlement-hook-FMLGKG7J.js +7 -0
  185. package/dist/cli-bundle/focused-chunks/stage-36J7YLGI.js +2 -0
  186. package/dist/cli-bundle/main.js +27 -27
  187. package/dist/cli-bundle/sdk-authoring.js +1 -1
  188. package/dist/cli-bundle/sdk-contracts.js +5 -5
  189. package/dist/cli-bundle/sdk-core.js +1 -1
  190. package/dist/cli-bundle/sdk-governance.js +1 -1
  191. package/dist/cli-bundle/sdk-graph.js +1 -1
  192. package/dist/cli-bundle/sdk-merge.js +72 -60
  193. package/dist/cli-bundle/sdk-query.js +1 -1
  194. package/dist/cli-bundle/sdk-runtime.js +1 -1
  195. package/dist/cli-bundle/sdk-testing.js +1 -1
  196. package/dist/cli-bundle/sdk.js +13 -13
  197. package/dist/cli.js +1 -1
  198. package/dist/core/checkpoint/checkpoint-gc.js +1 -1
  199. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  200. package/dist/core/checkpoint/mutation-context.js +1 -1
  201. package/dist/core/config/nested-settings.js +1 -1
  202. package/dist/core/config/positional-value.js +1 -1
  203. package/dist/core/diagnostics/remediation.js +1 -1
  204. package/dist/core/extensions/activation-summary-markdown.js +2 -2
  205. package/dist/core/extensions/activation-summary.js +1 -1
  206. package/dist/core/extensions/activation-transaction.js +1 -1
  207. package/dist/core/extensions/capability-usage.js +1 -1
  208. package/dist/core/extensions/command-hook-context.js +1 -1
  209. package/dist/core/extensions/command-metadata-contract.js +1 -1
  210. package/dist/core/extensions/command-visibility-tier.js +1 -1
  211. package/dist/core/extensions/contribution-inventory.js +1 -1
  212. package/dist/core/extensions/exporter-output-contract.js +1 -1
  213. package/dist/core/extensions/extension-candidate.js +1 -1
  214. package/dist/core/extensions/extension-capability-aliases.js +1 -1
  215. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  216. package/dist/core/extensions/extension-policy.js +1 -1
  217. package/dist/core/extensions/extension-registries.js +1 -1
  218. package/dist/core/extensions/extension-runtime-helpers.js +1 -1
  219. package/dist/core/extensions/extension-types.js +1 -1
  220. package/dist/core/extensions/flag-definition-validation.js +1 -1
  221. package/dist/core/extensions/flag-value-types.js +1 -1
  222. package/dist/core/extensions/index.js +1 -1
  223. package/dist/core/extensions/item-field-types.js +1 -1
  224. package/dist/core/extensions/item-fields.js +1 -1
  225. package/dist/core/extensions/loader.js +1 -1
  226. package/dist/core/extensions/manifest-parser.js +1 -1
  227. package/dist/core/extensions/manifest-schema.js +1 -1
  228. package/dist/core/extensions/module-graph-snapshot.js +1 -1
  229. package/dist/core/extensions/mutation-actor-snapshot.js +1 -1
  230. package/dist/core/extensions/mutation-actor.js +1 -1
  231. package/dist/core/extensions/preflight-ownership.js +1 -1
  232. package/dist/core/extensions/read-output-contract.js +1 -1
  233. package/dist/core/extensions/registration-contracts.js +1 -1
  234. package/dist/core/extensions/registration-validation.js +1 -1
  235. package/dist/core/extensions/registration-values.js +1 -1
  236. package/dist/core/extensions/reserved-host-flags.js +1 -1
  237. package/dist/core/extensions/runtime-registrations.js +1 -1
  238. package/dist/core/extensions/service-ownership.js +1 -1
  239. package/dist/core/extensions/version-compat.js +1 -1
  240. package/dist/core/extensions/version-diagnostics.js +1 -1
  241. package/dist/core/fs/atomic-create.js +1 -1
  242. package/dist/core/fs/file-glob.js +1 -1
  243. package/dist/core/fs/fs-utils.js +2 -2
  244. package/dist/core/fs/host-environment-errors.js +1 -1
  245. package/dist/core/fs/index.js +1 -1
  246. package/dist/core/fs/path-utils.js +1 -1
  247. package/dist/core/governance/content-fields.js +1 -1
  248. package/dist/core/governance/issue-codes.js +1 -1
  249. package/dist/core/governance/metadata-coverage.js +1 -1
  250. package/dist/core/history/bridge.js +2 -0
  251. package/dist/core/history/digest.js +1 -1
  252. package/dist/core/history/drift-cache.js +3 -3
  253. package/dist/core/history/drift-scan.js +1 -1
  254. package/dist/core/history/event-classification.js +1 -1
  255. package/dist/core/history/event-index.js +11 -11
  256. package/dist/core/history/history-compact-bulk.js +1 -1
  257. package/dist/core/history/history-diff.js +1 -1
  258. package/dist/core/history/history-rewrite.js +1 -1
  259. package/dist/core/history/history-storage-stats.js +1 -1
  260. package/dist/core/history/history-stream-policy.js +1 -1
  261. package/dist/core/history/history.d.ts +12 -0
  262. package/dist/core/history/history.js +2 -2
  263. package/dist/core/history/identity.js +1 -1
  264. package/dist/core/history/index.js +1 -1
  265. package/dist/core/history/operation-contract.js +1 -1
  266. package/dist/core/history/projection.js +1 -1
  267. package/dist/core/history/read.d.ts +9 -0
  268. package/dist/core/history/read.js +1 -1
  269. package/dist/core/history/replay.d.ts +46 -5
  270. package/dist/core/history/replay.js +2 -2
  271. package/dist/core/history/stream-summary.js +2 -2
  272. package/dist/core/history/tombstone.js +1 -1
  273. package/dist/core/history/version-address.js +1 -1
  274. package/dist/core/history/workspace-history.js +2 -2
  275. package/dist/core/io/body-file.js +1 -1
  276. package/dist/core/io/bulk-ids-input.js +2 -2
  277. package/dist/core/item/actionability.js +1 -1
  278. package/dist/core/item/deferred-fields.js +1 -1
  279. package/dist/core/item/dependency-reference.js +1 -1
  280. package/dist/core/item/id.js +1 -1
  281. package/dist/core/item/index.js +1 -1
  282. package/dist/core/item/item-format-version.js +1 -1
  283. package/dist/core/item/item-format.js +7 -7
  284. package/dist/core/item/item-record.js +1 -1
  285. package/dist/core/item/item-type-definition.js +1 -1
  286. package/dist/core/item/literal-mutation-input.js +1 -1
  287. package/dist/core/item/parent-reference-policy.js +1 -1
  288. package/dist/core/item/parse.js +8 -8
  289. package/dist/core/item/plan-lifecycle.js +1 -1
  290. package/dist/core/item/priority.js +1 -1
  291. package/dist/core/item/sprint-release-format.js +1 -1
  292. package/dist/core/item/status-filter.js +1 -1
  293. package/dist/core/item/status.js +1 -1
  294. package/dist/core/item/toon-decode.js +1 -1
  295. package/dist/core/item/type-registry.js +1 -1
  296. package/dist/core/item/type-synonyms.js +1 -1
  297. package/dist/core/lock/index.js +1 -1
  298. package/dist/core/lock/lock-confinement.js +1 -1
  299. package/dist/core/lock/lock-gc.js +1 -1
  300. package/dist/core/lock/lock-owner.js +1 -1
  301. package/dist/core/lock/lock.js +4 -4
  302. package/dist/core/output/linked-test-projection.js +5 -5
  303. package/dist/core/output/mutation-projection.js +1 -1
  304. package/dist/core/output/output-control.js +1 -1
  305. package/dist/core/output/output.js +19 -19
  306. package/dist/core/output/query-summary.js +1 -1
  307. package/dist/core/output/tabular.js +3 -3
  308. package/dist/core/packages/manifest.js +1 -1
  309. package/dist/core/packages/root.js +1 -1
  310. package/dist/core/policy/workflow-policy-schema.js +1 -1
  311. package/dist/core/policy/workflow-policy-store.js +1 -1
  312. package/dist/core/policy/workflow-policy.js +1 -1
  313. package/dist/core/profile/profile-describe.js +1 -1
  314. package/dist/core/profile/profile-lint.d.ts +1 -1
  315. package/dist/core/profile/profile-lint.js +1 -1
  316. package/dist/core/profile/profile-plan.js +1 -1
  317. package/dist/core/profile/profile-presets.js +4 -4
  318. package/dist/core/reproducibility/context.js +1 -1
  319. package/dist/core/schema/fields-file.js +2 -2
  320. package/dist/core/schema/item-types-file.js +2 -2
  321. package/dist/core/schema/runtime-field-filters.js +1 -1
  322. package/dist/core/schema/runtime-field-values.js +1 -1
  323. package/dist/core/schema/runtime-schema.js +2 -2
  324. package/dist/core/schema/status-defs-file.js +2 -2
  325. package/dist/core/schema/status-token.js +1 -1
  326. package/dist/core/schema/type-inference.js +1 -1
  327. package/dist/core/schema/type-presets.js +1 -1
  328. package/dist/core/schema/type-workflows.js +1 -1
  329. package/dist/core/search/background-refresh.js +2 -2
  330. package/dist/core/search/bm25.js +1 -1
  331. package/dist/core/search/cache.js +2 -2
  332. package/dist/core/search/corpus.js +1 -1
  333. package/dist/core/search/embedding-batches.js +1 -1
  334. package/dist/core/search/eval-thresholds.js +1 -1
  335. package/dist/core/search/eval.js +1 -1
  336. package/dist/core/search/http-client.js +1 -1
  337. package/dist/core/search/providers.js +1 -1
  338. package/dist/core/search/relevance.js +1 -1
  339. package/dist/core/search/semantic-defaults.js +1 -1
  340. package/dist/core/search/staleness.js +1 -1
  341. package/dist/core/search/vector-stores.js +2 -2
  342. package/dist/core/search/vectorization-metadata.js +1 -1
  343. package/dist/core/sentry/helpers.js +1 -1
  344. package/dist/core/sentry/instrument.js +1 -1
  345. package/dist/core/sentry/sensitive-assignments.js +1 -1
  346. package/dist/core/session/session-state.js +1 -1
  347. package/dist/core/shared/agent-session-context.js +1 -1
  348. package/dist/core/shared/author.js +5 -5
  349. package/dist/core/shared/command-line.js +1 -1
  350. package/dist/core/shared/command-types.js +0 -1
  351. package/dist/core/shared/conflict-markers.js +1 -1
  352. package/dist/core/shared/constants.js +1 -1
  353. package/dist/core/shared/error-details.js +1 -1
  354. package/dist/core/shared/errors.js +1 -1
  355. package/dist/core/shared/html-entity-decode.js +1 -1
  356. package/dist/core/shared/index.js +1 -1
  357. package/dist/core/shared/item-metadata-contract.js +1 -1
  358. package/dist/core/shared/lazy-module.js +1 -1
  359. package/dist/core/shared/levenshtein.js +1 -1
  360. package/dist/core/shared/memo.js +1 -1
  361. package/dist/core/shared/numeric-parsers.js +1 -1
  362. package/dist/core/shared/option-alias-visibility.js +1 -1
  363. package/dist/core/shared/output-unicode.js +1 -1
  364. package/dist/core/shared/primitives.js +1 -1
  365. package/dist/core/shared/process-tree.js +2 -2
  366. package/dist/core/shared/secret-rules.js +5 -5
  367. package/dist/core/shared/serial-queue.js +1 -1
  368. package/dist/core/shared/serialization.js +1 -1
  369. package/dist/core/shared/split-comma-list.js +1 -1
  370. package/dist/core/shared/text-normalization.js +1 -1
  371. package/dist/core/shared/time.js +2 -2
  372. package/dist/core/shared/url-credentials.js +1 -1
  373. package/dist/core/store/index.js +1 -1
  374. package/dist/core/store/item-format-migration.js +1 -1
  375. package/dist/core/store/item-metadata-cache.js +1 -1
  376. package/dist/core/store/item-metadata-query-index.js +11 -11
  377. package/dist/core/store/item-metadata-read-work.js +1 -1
  378. package/dist/core/store/item-mutation-precondition.js +1 -1
  379. package/dist/core/store/item-store.js +1 -1
  380. package/dist/core/store/paths.js +1 -1
  381. package/dist/core/store/settings-concurrency.js +1 -1
  382. package/dist/core/store/settings-read-cache.js +1 -1
  383. package/dist/core/store/settings-sections.js +2 -2
  384. package/dist/core/store/settings-validator.js +1 -1
  385. package/dist/core/store/settings.d.ts +3 -1
  386. package/dist/core/store/settings.js +6 -6
  387. package/dist/core/store/sqlite-runtime.js +1 -1
  388. package/dist/core/store/tracker-preflight.js +1 -1
  389. package/dist/core/store/transaction-coordinator-scope.js +1 -1
  390. package/dist/core/telemetry/consent.js +3 -3
  391. package/dist/core/telemetry/observability.js +1 -1
  392. package/dist/core/telemetry/policy.js +1 -1
  393. package/dist/core/telemetry/read-sampling.js +2 -2
  394. package/dist/core/telemetry/runtime.js +9 -9
  395. package/dist/core/test/background-runs.js +4 -4
  396. package/dist/core/test/item-test-run-tracking.js +1 -1
  397. package/dist/core/test/run-selectors.js +1 -1
  398. package/dist/core/validate/estimate-defaults.js +1 -1
  399. package/dist/core/validate/fix-planning.js +1 -1
  400. package/dist/core/validate/linked-artifact-reference.js +1 -1
  401. package/dist/core/validate/missing-by-type.js +1 -1
  402. package/dist/core/validate/missing-link-owners.js +1 -1
  403. package/dist/core/validate/stale-file-classification.js +1 -1
  404. package/dist/mcp/http-server.js +5 -5
  405. package/dist/mcp/legacy-adapter.js +1 -1
  406. package/dist/mcp/runtime-capabilities.js +1 -1
  407. package/dist/mcp/server.js +4 -4
  408. package/dist/mcp/tool-definitions.js +1 -1
  409. package/dist/sdk/actionability.js +1 -1
  410. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  411. package/dist/sdk/agent/command-recovery.js +1 -1
  412. package/dist/sdk/agent/command-suggestions.js +1 -1
  413. package/dist/sdk/agent/create-option-policy.js +1 -1
  414. package/dist/sdk/agent/identity-config.js +1 -1
  415. package/dist/sdk/agent/item-addressing.js +1 -1
  416. package/dist/sdk/agent/linked-resource-recovery.js +1 -1
  417. package/dist/sdk/agent/refusal-closure-census.js +2 -2
  418. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
  419. package/dist/sdk/agent/subcommand-recovery.js +1 -1
  420. package/dist/sdk/agent-capability-contracts.js +3 -3
  421. package/dist/sdk/agent-session-context.js +1 -1
  422. package/dist/sdk/annotations.js +1 -1
  423. package/dist/sdk/author-attribution.js +1 -1
  424. package/dist/sdk/cli-bootstrap.js +1 -1
  425. package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -5
  426. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  427. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  428. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
  429. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  430. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  431. package/dist/sdk/cli-contracts/completeness.js +1 -1
  432. package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
  433. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  434. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -2
  435. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  436. package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
  437. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  438. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
  439. package/dist/sdk/cli-contracts/string-lists.js +1 -1
  440. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  441. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  442. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  443. package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +2 -2
  444. package/dist/sdk/cli-contracts/typed-action-inputs.js +0 -1
  445. package/dist/sdk/cli-contracts.js +1 -1
  446. package/dist/sdk/cli-program.js +1 -1
  447. package/dist/sdk/command-line.js +1 -1
  448. package/dist/sdk/comments.js +1 -1
  449. package/dist/sdk/compile-cache.js +1 -1
  450. package/dist/sdk/completion/bash.js +2 -2
  451. package/dist/sdk/completion/fish.js +74 -73
  452. package/dist/sdk/completion/shared.js +1 -1
  453. package/dist/sdk/completion/zsh.js +77 -76
  454. package/dist/sdk/completion.js +1 -1
  455. package/dist/sdk/config.js +1 -1
  456. package/dist/sdk/context/recency.js +1 -1
  457. package/dist/sdk/context/semantic-session-attribution.js +1 -1
  458. package/dist/sdk/context/usage-egress.js +1 -1
  459. package/dist/sdk/context/usage-ledger.js +6 -6
  460. package/dist/sdk/context-intent-contracts.js +1 -1
  461. package/dist/sdk/context-intent-runtime.js +1 -1
  462. package/dist/sdk/context-packing.js +1 -1
  463. package/dist/sdk/context-relevance.js +1 -1
  464. package/dist/sdk/context-signal-store.js +2 -2
  465. package/dist/sdk/context-usage.js +1 -1
  466. package/dist/sdk/dependencies/context-budget-recovery.js +1 -1
  467. package/dist/sdk/dependencies.js +1 -1
  468. package/dist/sdk/dependency-flag-validation.js +1 -1
  469. package/dist/sdk/dependency-provenance.js +1 -1
  470. package/dist/sdk/docs.js +1 -1
  471. package/dist/sdk/duplicates.js +1 -1
  472. package/dist/sdk/environment/host-environment-errors.js +1 -1
  473. package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
  474. package/dist/sdk/environment/source-context.js +1 -1
  475. package/dist/sdk/environment/tracker-preflight.js +1 -1
  476. package/dist/sdk/error-code-catalog.js +1 -1
  477. package/dist/sdk/error-runtime.js +1 -1
  478. package/dist/sdk/errors.js +1 -1
  479. package/dist/sdk/eval.js +1 -1
  480. package/dist/sdk/extension/author-manifest.js +1 -1
  481. package/dist/sdk/extension/bundled-catalog.js +1 -1
  482. package/dist/sdk/extension/command-options.js +1 -1
  483. package/dist/sdk/extension/concurrency.js +1 -1
  484. package/dist/sdk/extension/copy-scope.js +1 -1
  485. package/dist/sdk/extension/custom-field-collisions.js +1 -1
  486. package/dist/sdk/extension/describe.js +3 -3
  487. package/dist/sdk/extension/doctor.js +1 -1
  488. package/dist/sdk/extension/install-plan.js +1 -1
  489. package/dist/sdk/extension/install-receipts.js +1 -1
  490. package/dist/sdk/extension/install-runtime.js +3 -3
  491. package/dist/sdk/extension/install-snapshot.js +1 -1
  492. package/dist/sdk/extension/install-sources.js +5 -5
  493. package/dist/sdk/extension/managed-state.js +2 -2
  494. package/dist/sdk/extension/managed-update-status.js +1 -1
  495. package/dist/sdk/extension/migrations.js +2 -2
  496. package/dist/sdk/extension/native-command-options.js +1 -1
  497. package/dist/sdk/extension/output-ownership.js +1 -1
  498. package/dist/sdk/extension/runtime-summary.js +1 -1
  499. package/dist/sdk/extension/scaffold.js +11 -11
  500. package/dist/sdk/extension/shared.js +1 -1
  501. package/dist/sdk/extension/source-resolution.js +1 -1
  502. package/dist/sdk/extension/static-inventory.js +1 -1
  503. package/dist/sdk/extension/update-check.js +1 -1
  504. package/dist/sdk/extension-command-context.js +2 -2
  505. package/dist/sdk/extension-contracts.js +1 -1
  506. package/dist/sdk/extension.js +1 -1
  507. package/dist/sdk/files.js +1 -1
  508. package/dist/sdk/flag-invocation-contracts.js +1 -1
  509. package/dist/sdk/generated/error-code-catalog-rows.js +1 -1
  510. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  511. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  512. package/dist/sdk/generated-error-code-catalog.js +1 -1
  513. package/dist/sdk/governance/assurance-action-contracts.js +0 -1
  514. package/dist/sdk/governance/assurance-action.js +1 -1
  515. package/dist/sdk/governance/assurance-limits.js +1 -1
  516. package/dist/sdk/governance/assurance-mutation-error.js +1 -1
  517. package/dist/sdk/governance/assurance-presets.js +1 -1
  518. package/dist/sdk/governance/assurance-runtime.js +1 -1
  519. package/dist/sdk/governance/assurance.js +4 -4
  520. package/dist/sdk/governance/boundary-fixtures.js +1 -1
  521. package/dist/sdk/governance/closure-timestamps.js +1 -1
  522. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
  523. package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
  524. package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
  525. package/dist/sdk/governance/defect-recurrence.js +2 -2
  526. package/dist/sdk/governance/extension-host-version.js +1 -1
  527. package/dist/sdk/governance/gc.js +1 -1
  528. package/dist/sdk/governance/health/history-drift-remedies.js +2 -0
  529. package/dist/sdk/governance/health/projection.js +1 -1
  530. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  531. package/dist/sdk/governance/health.js +2 -2
  532. package/dist/sdk/governance/hierarchy-validation.js +1 -1
  533. package/dist/sdk/governance/in-progress-work-health.js +1 -1
  534. package/dist/sdk/governance/lifecycle-dependency-cycles.js +1 -1
  535. package/dist/sdk/governance/linked-file-report.js +1 -1
  536. package/dist/sdk/governance/merge-receipt-history.js +1 -1
  537. package/dist/sdk/governance/provenance-health.js +4 -4
  538. package/dist/sdk/governance/reindex.js +5 -5
  539. package/dist/sdk/governance/stale-work.js +1 -1
  540. package/dist/sdk/governance/status-role-diagnostics.js +1 -1
  541. package/dist/sdk/governance/storage-integrity.js +1 -1
  542. package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
  543. package/dist/sdk/governance/upgrade.js +2 -2
  544. package/dist/sdk/governance/validate-deferred-fields.js +1 -1
  545. package/dist/sdk/governance/validate-history-drift.js +1 -1
  546. package/dist/sdk/governance/validate-item-reader.js +1 -1
  547. package/dist/sdk/governance/validate-normalization.js +1 -1
  548. package/dist/sdk/governance/validate.js +1 -1
  549. package/dist/sdk/governance/workflow-completeness.js +1 -1
  550. package/dist/sdk/governance/workflow-policy.js +3 -3
  551. package/dist/sdk/governance/workspace-position.js +2 -2
  552. package/dist/sdk/graph/analytics.js +1 -1
  553. package/dist/sdk/graph/assembly.js +1 -1
  554. package/dist/sdk/graph/cache.js +1 -1
  555. package/dist/sdk/graph/cardinality-integrity.js +1 -1
  556. package/dist/sdk/graph/centrality.js +1 -1
  557. package/dist/sdk/graph/deadline-scheduling.js +1 -1
  558. package/dist/sdk/graph/durable-cache.js +1 -1
  559. package/dist/sdk/graph/governance-contracts.js +1 -1
  560. package/dist/sdk/graph/governance.js +1 -1
  561. package/dist/sdk/graph/hierarchy-integrity.js +1 -1
  562. package/dist/sdk/graph/lifecycle-coverage.js +1 -1
  563. package/dist/sdk/graph/mutation-advisory.js +1 -1
  564. package/dist/sdk/graph/query-contracts.js +1 -1
  565. package/dist/sdk/graph/remediation.js +1 -1
  566. package/dist/sdk/graph/run.js +1 -1
  567. package/dist/sdk/graph/scheduling.js +1 -1
  568. package/dist/sdk/graph/traversal.js +1 -1
  569. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
  570. package/dist/sdk/guide-topics.js +1 -1
  571. package/dist/sdk/guide.js +7 -7
  572. package/dist/sdk/history/append-only-repair.d.ts +30 -0
  573. package/dist/sdk/history/append-only-repair.js +6 -0
  574. package/dist/sdk/history/attestation-command.js +2 -2
  575. package/dist/sdk/history/attestation-contract.js +1 -1
  576. package/dist/sdk/history/attestation-scan.js +1 -1
  577. package/dist/sdk/history/attestation.js +1 -1
  578. package/dist/sdk/history/maintenance.d.ts +8 -2
  579. package/dist/sdk/history/maintenance.js +1 -1
  580. package/dist/sdk/history/reanchor-refusal.js +2 -0
  581. package/dist/sdk/history/reseed.d.ts +15 -0
  582. package/dist/sdk/history/reseed.js +2 -0
  583. package/dist/sdk/history/salvage.d.ts +19 -8
  584. package/dist/sdk/history/salvage.js +5 -3
  585. package/dist/sdk/history/subject.js +1 -1
  586. package/dist/sdk/history-analytics.js +1 -1
  587. package/dist/sdk/history-compact.js +1 -1
  588. package/dist/sdk/history-mcp.js +1 -1
  589. package/dist/sdk/history-provenance.js +1 -1
  590. package/dist/sdk/history-read.js +1 -1
  591. package/dist/sdk/history-redact.js +1 -1
  592. package/dist/sdk/history-repair.d.ts +8 -2
  593. package/dist/sdk/history-repair.js +1 -1
  594. package/dist/sdk/improvement-ledger-validation.js +1 -1
  595. package/dist/sdk/improvement-ledger.js +2 -2
  596. package/dist/sdk/index.d.ts +1 -1
  597. package/dist/sdk/init-agent-guidance.js +10 -10
  598. package/dist/sdk/init.js +14 -14
  599. package/dist/sdk/invocation-author.js +1 -1
  600. package/dist/sdk/item-children.js +1 -1
  601. package/dist/sdk/item-metadata-index.js +1 -1
  602. package/dist/sdk/item-schedule.js +1 -1
  603. package/dist/sdk/item-transaction.d.ts +33 -1
  604. package/dist/sdk/item-transaction.js +1 -1
  605. package/dist/sdk/learnings.js +1 -1
  606. package/dist/sdk/lifecycle/append.js +3 -3
  607. package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
  608. package/dist/sdk/lifecycle/claim.js +1 -1
  609. package/dist/sdk/lifecycle/cli-input.js +1 -1
  610. package/dist/sdk/lifecycle/close-many.js +1 -1
  611. package/dist/sdk/lifecycle/close.js +1 -1
  612. package/dist/sdk/lifecycle/copy.js +1 -1
  613. package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
  614. package/dist/sdk/lifecycle/core-item-fields.js +1 -1
  615. package/dist/sdk/lifecycle/create-deferrals.js +1 -1
  616. package/dist/sdk/lifecycle/create.js +1 -1
  617. package/dist/sdk/lifecycle/delete.js +1 -1
  618. package/dist/sdk/lifecycle/dependency-removal.js +1 -1
  619. package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
  620. package/dist/sdk/lifecycle/focus.js +1 -1
  621. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
  622. package/dist/sdk/lifecycle/item-revision.js +1 -1
  623. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
  624. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
  625. package/dist/sdk/lifecycle/mcp-actions.js +1 -1
  626. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
  627. package/dist/sdk/lifecycle/mutation-command-options.js +0 -1
  628. package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
  629. package/dist/sdk/lifecycle/mutation-option-validation.js +1 -1
  630. package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
  631. package/dist/sdk/lifecycle/plan.js +1 -1
  632. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
  633. package/dist/sdk/lifecycle/release-handoff.js +1 -1
  634. package/dist/sdk/lifecycle/reopen.js +1 -1
  635. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -2
  636. package/dist/sdk/lifecycle/repeated-terminal-state.js +1 -1
  637. package/dist/sdk/lifecycle/restore.js +1 -1
  638. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  639. package/dist/sdk/lifecycle/start-blockers.js +1 -1
  640. package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
  641. package/dist/sdk/lifecycle/task-composition.js +1 -1
  642. package/dist/sdk/lifecycle/update-many.js +1 -1
  643. package/dist/sdk/lifecycle/update.js +2 -2
  644. package/dist/sdk/lifecycle/workflow-transition.js +1 -1
  645. package/dist/sdk/lifecycle-completion.js +1 -1
  646. package/dist/sdk/lifecycle-policy.js +1 -1
  647. package/dist/sdk/linked-artifacts.js +2 -2
  648. package/dist/sdk/mcp/apps.js +5 -5
  649. package/dist/sdk/mcp/authorization.js +1 -1
  650. package/dist/sdk/mcp/discovery.js +1 -1
  651. package/dist/sdk/mcp/executable.js +4 -4
  652. package/dist/sdk/mcp/interactions.js +1 -1
  653. package/dist/sdk/mcp/protocol.js +1 -1
  654. package/dist/sdk/mcp/skills.js +3 -3
  655. package/dist/sdk/mcp/subscriptions.js +1 -1
  656. package/dist/sdk/mcp/tasks.js +2 -2
  657. package/dist/sdk/mcp/transport.js +1 -1
  658. package/dist/sdk/merge/abandoned-receipts.js +1 -1
  659. package/dist/sdk/merge/driver.js +7 -7
  660. package/dist/sdk/merge/history-scalar-rebase.js +1 -1
  661. package/dist/sdk/merge/ignored-artifacts.js +1 -1
  662. package/dist/sdk/merge/index.js +1 -1
  663. package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
  664. package/dist/sdk/merge/install.js +6 -6
  665. package/dist/sdk/merge/receipt-file-boundary.js +1 -1
  666. package/dist/sdk/merge/receipt-operation.js +1 -1
  667. package/dist/sdk/merge/receipt-schema.js +1 -1
  668. package/dist/sdk/merge/receipts.js +4 -4
  669. package/dist/sdk/merge/reconcile.js +1 -1
  670. package/dist/sdk/merge/settlement-hook.js +4 -4
  671. package/dist/sdk/merge/stage.js +1 -1
  672. package/dist/sdk/merge/three-way.d.ts +22 -3
  673. package/dist/sdk/merge/three-way.js +9 -3
  674. package/dist/sdk/merge/worktree-config.js +2 -2
  675. package/dist/sdk/merge.js +1 -1
  676. package/dist/sdk/mutation-events.js +1 -1
  677. package/dist/sdk/mutation-guard.js +1 -1
  678. package/dist/sdk/notes.js +1 -1
  679. package/dist/sdk/output/fit-envelope.js +1 -1
  680. package/dist/sdk/output/list-envelope.js +1 -1
  681. package/dist/sdk/output/table-rows.js +1 -1
  682. package/dist/sdk/output-contracts.js +1 -1
  683. package/dist/sdk/output-projection.js +1 -1
  684. package/dist/sdk/output-token-accounting.js +1 -1
  685. package/dist/sdk/output.js +2 -2
  686. package/dist/sdk/ownership-source.js +1 -1
  687. package/dist/sdk/package-import-adapters.js +1 -1
  688. package/dist/sdk/package-migrations.js +1 -1
  689. package/dist/sdk/package-runtime-options.js +1 -1
  690. package/dist/sdk/pagination.js +1 -1
  691. package/dist/sdk/profile.js +5 -5
  692. package/dist/sdk/provenance.js +1 -1
  693. package/dist/sdk/public-surface.json +1 -1
  694. package/dist/sdk/query/activity.js +1 -1
  695. package/dist/sdk/query/aggregate.js +1 -1
  696. package/dist/sdk/query/calendar.js +4 -4
  697. package/dist/sdk/query/complete-list.js +1 -1
  698. package/dist/sdk/query/context.js +2 -2
  699. package/dist/sdk/query/declared-blockers.js +1 -1
  700. package/dist/sdk/query/duplicate-candidates.js +1 -1
  701. package/dist/sdk/query/get-facet-roots.js +1 -1
  702. package/dist/sdk/query/get.js +1 -1
  703. package/dist/sdk/query/history.js +1 -1
  704. package/dist/sdk/query/item-filter-options.js +0 -1
  705. package/dist/sdk/query/light-metadata.js +1 -1
  706. package/dist/sdk/query/list-filter-shared.js +1 -1
  707. package/dist/sdk/query/list.js +1 -1
  708. package/dist/sdk/query/multi-value-filters.js +1 -1
  709. package/dist/sdk/query/next-ranking-policy.js +1 -1
  710. package/dist/sdk/query/next-ready-budget.js +1 -1
  711. package/dist/sdk/query/next.js +2 -2
  712. package/dist/sdk/query/parsers.js +1 -1
  713. package/dist/sdk/query/projection-contracts.js +1 -1
  714. package/dist/sdk/query/search/corpus.js +2 -2
  715. package/dist/sdk/query/search/filters.js +1 -1
  716. package/dist/sdk/query/search/input.js +1 -1
  717. package/dist/sdk/query/search/lexical.js +1 -1
  718. package/dist/sdk/query/search/response.js +1 -1
  719. package/dist/sdk/query/search/semantic.js +3 -3
  720. package/dist/sdk/query/search/types.js +0 -1
  721. package/dist/sdk/query/search-contracts.js +1 -1
  722. package/dist/sdk/query/search-pagination.js +1 -1
  723. package/dist/sdk/query/search-rendering.js +1 -1
  724. package/dist/sdk/query/search.js +1 -1
  725. package/dist/sdk/query/window-pagination.js +1 -1
  726. package/dist/sdk/query/workspace-contracts.js +1 -1
  727. package/dist/sdk/read-output/continuation.js +1 -1
  728. package/dist/sdk/read-output/extension.js +1 -1
  729. package/dist/sdk/read-output/options.js +1 -1
  730. package/dist/sdk/read-output/positional-rows.js +1 -1
  731. package/dist/sdk/read-output/provenance.js +1 -1
  732. package/dist/sdk/read-output/session-result.js +0 -1
  733. package/dist/sdk/read-output/surfaces.js +1 -1
  734. package/dist/sdk/read-output/tail-retention.js +1 -1
  735. package/dist/sdk/read-output-budget.js +1 -1
  736. package/dist/sdk/read-output-contracts.js +1 -1
  737. package/dist/sdk/read-output-rows.js +1 -1
  738. package/dist/sdk/read-output-session.js +1 -1
  739. package/dist/sdk/relationship-analytics.js +1 -1
  740. package/dist/sdk/relationship-context.js +1 -1
  741. package/dist/sdk/relationship-history.js +6 -6
  742. package/dist/sdk/relationship-kinds/contract.js +1 -1
  743. package/dist/sdk/relationships.js +1 -1
  744. package/dist/sdk/reproducibility/process.js +1 -1
  745. package/dist/sdk/runtime/actions.js +1 -1
  746. package/dist/sdk/runtime/context.js +1 -1
  747. package/dist/sdk/runtime/mutation-admission.js +1 -1
  748. package/dist/sdk/runtime/mutation-value-validation.js +1 -1
  749. package/dist/sdk/runtime/schema-preview.js +1 -1
  750. package/dist/sdk/runtime/schema.js +1 -1
  751. package/dist/sdk/runtime-action-aliases.js +1 -1
  752. package/dist/sdk/runtime-extended-actions.js +1 -1
  753. package/dist/sdk/runtime-input.d.ts +8 -2
  754. package/dist/sdk/runtime-input.js +1 -1
  755. package/dist/sdk/runtime-primitives.d.ts +1 -1
  756. package/dist/sdk/runtime-primitives.js +1 -1
  757. package/dist/sdk/runtime-public-contracts.js +0 -1
  758. package/dist/sdk/runtime-stats-options.js +1 -1
  759. package/dist/sdk/runtime.d.ts +9 -0
  760. package/dist/sdk/runtime.js +1 -1
  761. package/dist/sdk/scheduling-shortcuts.js +1 -1
  762. package/dist/sdk/schema/field-option-collisions.js +2 -0
  763. package/dist/sdk/schema-migration.js +4 -4
  764. package/dist/sdk/schema.js +7 -7
  765. package/dist/sdk/search-refresh-worker.js +1 -1
  766. package/dist/sdk/similarity-scoring.js +1 -1
  767. package/dist/sdk/similarity.js +1 -1
  768. package/dist/sdk/start-task-status.js +1 -1
  769. package/dist/sdk/stats.js +1 -1
  770. package/dist/sdk/structured-mutations.d.ts +5 -5
  771. package/dist/sdk/structured-mutations.js +1 -1
  772. package/dist/sdk/telemetry-flush.js +1 -1
  773. package/dist/sdk/telemetry.js +4 -4
  774. package/dist/sdk/templates.js +3 -3
  775. package/dist/sdk/test/batch.js +2 -2
  776. package/dist/sdk/test/command-args.js +1 -1
  777. package/dist/sdk/test/command-resolution.js +2 -2
  778. package/dist/sdk/test/entry.js +2 -2
  779. package/dist/sdk/test/execution-receipts.js +2 -2
  780. package/dist/sdk/test/execution.js +5 -5
  781. package/dist/sdk/test/json-path.js +1 -1
  782. package/dist/sdk/test/linked-command-detection.js +1 -1
  783. package/dist/sdk/test/measurements.js +1 -1
  784. package/dist/sdk/test/parsers.js +1 -1
  785. package/dist/sdk/test/prerequisites.js +1 -1
  786. package/dist/sdk/test/receipt-index-snapshot.js +1 -1
  787. package/dist/sdk/test/run-phases.js +1 -1
  788. package/dist/sdk/test/runs.js +1 -1
  789. package/dist/sdk/test/trust.js +2 -2
  790. package/dist/sdk/test/update.js +1 -1
  791. package/dist/sdk/test/workspace-snapshot.js +1 -1
  792. package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
  793. package/dist/sdk/traceability/source-traceability.js +2 -2
  794. package/dist/sdk/tracker-root-discovery.js +1 -1
  795. package/dist/sdk/transactions/item-finalization.js +2 -0
  796. package/dist/sdk/workspace-contracts-cache.js +1 -1
  797. package/dist/sdk/workspace-contracts.js +1 -1
  798. package/dist/sdk/workspace-memory.js +2 -2
  799. package/dist/sdk/workspace-snapshot.js +5 -5
  800. package/dist/sdk/workspace-transaction-gc.js +1 -1
  801. package/dist/sdk/workspace-transaction.js +2 -2
  802. package/dist/sdk/workspace.js +6 -6
  803. package/dist/types/index.js +1 -1
  804. package/dist/types.d.ts +20 -0
  805. package/dist/types.js +1 -1
  806. package/docs/AGENT_GUIDE.md +1 -1
  807. package/docs/AGENT_RUNTIME_PRIMITIVES.md +1 -1
  808. package/docs/COMMANDS.md +7 -3
  809. package/docs/EXTENSIONS.md +1 -1
  810. package/docs/HISTORY_RECOVERY.md +229 -5
  811. package/docs/README.md +2 -2
  812. package/docs/SDK.md +174 -5
  813. package/docs/SDK_CONTEXT_COORDINATION.md +3 -2
  814. package/marketplace.json +1 -1
  815. package/node_modules/tar/package.json +2 -3
  816. package/package.json +31 -2
  817. package/packages/pm-beads/package.json +1 -1
  818. package/packages/pm-calendar/package.json +1 -1
  819. package/packages/pm-command-kit/package.json +1 -1
  820. package/packages/pm-digital-twin/package.json +1 -1
  821. package/packages/pm-governance-audit/package.json +1 -1
  822. package/packages/pm-guide-shell/package.json +1 -1
  823. package/packages/pm-kanban/package.json +1 -1
  824. package/packages/pm-lifecycle-hooks/package.json +1 -1
  825. package/packages/pm-linked-test-adapters/package.json +1 -1
  826. package/packages/pm-search-advanced/package.json +1 -1
  827. package/packages/pm-templates/package.json +1 -1
  828. package/packages/pm-todos/package.json +1 -1
  829. package/packages/pm-vcs/package.json +1 -1
  830. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  831. package/plugins/pm-claude/package.json +1 -1
  832. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  833. package/plugins/pm-codex/package.json +1 -1
  834. package/plugins/pm-codex/plugin.json +1 -1
  835. package/runtime-dependencies.json +1 -1
  836. package/scripts/finalize-build.mjs +63 -24
  837. package/scripts/prepare-build-cache.mjs +28 -1
  838. package/dist/cli-bundle/chunks/chunk-2DXRTIC6.js +0 -21
  839. package/dist/cli-bundle/chunks/chunk-5647LU3A.js +0 -2287
  840. package/dist/cli-bundle/chunks/chunk-6QLEXRUG.js +0 -9
  841. package/dist/cli-bundle/chunks/chunk-AHQB7W2H.js +0 -3
  842. package/dist/cli-bundle/chunks/chunk-BKSVHOWI.js +0 -2
  843. package/dist/cli-bundle/chunks/chunk-CASX6SFI.js +0 -2
  844. package/dist/cli-bundle/chunks/chunk-CIKGG34F.js +0 -2
  845. package/dist/cli-bundle/chunks/chunk-D6ILFXZY.js +0 -2
  846. package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
  847. package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +0 -2
  848. package/dist/cli-bundle/chunks/chunk-IUIOTAF6.js +0 -9
  849. package/dist/cli-bundle/chunks/chunk-JVGRFU5H.js +0 -3
  850. package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +0 -3
  851. package/dist/cli-bundle/chunks/chunk-KVBIMFUG.js +0 -6
  852. package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +0 -3
  853. package/dist/cli-bundle/chunks/chunk-NCFCBKIP.js +0 -2
  854. package/dist/cli-bundle/chunks/chunk-NT5AKFE5.js +0 -31
  855. package/dist/cli-bundle/chunks/chunk-PJXKA4QU.js +0 -125
  856. package/dist/cli-bundle/chunks/chunk-RMIRNYRG.js +0 -71
  857. package/dist/cli-bundle/chunks/chunk-RULHZRFN.js +0 -2
  858. package/dist/cli-bundle/chunks/chunk-S6HB3WL2.js +0 -2
  859. package/dist/cli-bundle/chunks/chunk-SA4BNP3Q.js +0 -2
  860. package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +0 -2
  861. package/dist/cli-bundle/chunks/chunk-SRVTCYAU.js +0 -2
  862. package/dist/cli-bundle/chunks/chunk-WELSVDPU.js +0 -2
  863. package/dist/cli-bundle/chunks/chunk-XHJ3H5PL.js +0 -3
  864. package/dist/cli-bundle/chunks/chunk-XWHJIRNV.js +0 -8
  865. package/dist/cli-bundle/chunks/chunk-YJEBK7HU.js +0 -8
  866. package/dist/cli-bundle/chunks/chunk-YKJKQ7DM.js +0 -115
  867. package/dist/cli-bundle/chunks/chunk-YMUSRWV4.js +0 -9
  868. package/dist/cli-bundle/chunks/chunk-YR2KEBHP.js +0 -2
  869. package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +0 -2
  870. package/dist/cli-bundle/chunks/indexed-receipt-blobs-ITTXIN4K.js +0 -4
  871. package/dist/cli-bundle/chunks/item-transaction-7DFCG73I.js +0 -2
  872. package/dist/cli-bundle/chunks/mutation-actor-3TG636XG.js +0 -2
  873. package/dist/cli-bundle/chunks/mutation-admission-LICSDNNO.js +0 -2
  874. package/dist/cli-bundle/chunks/register-mutation-WWVECKFQ.js +0 -21
  875. package/dist/cli-bundle/chunks/register-operations-L6HFJNWD.js +0 -2
  876. package/dist/cli-bundle/chunks/register-setup-K7UFG5TD.js +0 -2
  877. package/dist/cli-bundle/chunks/settlement-hook-BXN5LEQD.js +0 -7
  878. package/dist/cli-bundle/chunks/stage-57KH3KAC.js +0 -2
  879. package/dist/cli-bundle/focused-chunks/chunk-3IRCYJI5.js +0 -3
  880. package/dist/cli-bundle/focused-chunks/chunk-3V53UBHN.js +0 -9
  881. package/dist/cli-bundle/focused-chunks/chunk-532WZV65.js +0 -2
  882. package/dist/cli-bundle/focused-chunks/chunk-7A4QWNZX.js +0 -8
  883. package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +0 -2
  884. package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +0 -3
  885. package/dist/cli-bundle/focused-chunks/chunk-CU2BRAOX.js +0 -2
  886. package/dist/cli-bundle/focused-chunks/chunk-CWWKRI5P.js +0 -2
  887. package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +0 -2
  888. package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +0 -2
  889. package/dist/cli-bundle/focused-chunks/chunk-HGFNL5XI.js +0 -2
  890. package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +0 -2
  891. package/dist/cli-bundle/focused-chunks/chunk-IQK5NPMG.js +0 -13
  892. package/dist/cli-bundle/focused-chunks/chunk-J63D6QST.js +0 -6
  893. package/dist/cli-bundle/focused-chunks/chunk-JMQJBZQ5.js +0 -2
  894. package/dist/cli-bundle/focused-chunks/chunk-LNHUE4VV.js +0 -2
  895. package/dist/cli-bundle/focused-chunks/chunk-MKM5NKD7.js +0 -8
  896. package/dist/cli-bundle/focused-chunks/chunk-NP72ZDXE.js +0 -2
  897. package/dist/cli-bundle/focused-chunks/chunk-OSLQD5VH.js +0 -102
  898. package/dist/cli-bundle/focused-chunks/chunk-QGKLRXP7.js +0 -2
  899. package/dist/cli-bundle/focused-chunks/chunk-QSJW6NSQ.js +0 -66
  900. package/dist/cli-bundle/focused-chunks/chunk-RPE6IX26.js +0 -2
  901. package/dist/cli-bundle/focused-chunks/chunk-SRDQSA6M.js +0 -91
  902. package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +0 -2
  903. package/dist/cli-bundle/focused-chunks/chunk-UOC6257J.js +0 -26
  904. package/dist/cli-bundle/focused-chunks/chunk-URJ2E6AS.js +0 -3
  905. package/dist/cli-bundle/focused-chunks/chunk-WXMI4AV5.js +0 -8
  906. package/dist/cli-bundle/focused-chunks/chunk-XCJSHNXK.js +0 -27
  907. package/dist/cli-bundle/focused-chunks/chunk-XQQSSKJI.js +0 -44
  908. package/dist/cli-bundle/focused-chunks/chunk-YOAYY3HE.js +0 -2
  909. package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +0 -2
  910. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-AF4U3F3D.js +0 -4
  911. package/dist/cli-bundle/focused-chunks/item-transaction-HLBW7B3J.js +0 -2
  912. package/dist/cli-bundle/focused-chunks/mutation-actor-62HKR5IO.js +0 -2
  913. package/dist/cli-bundle/focused-chunks/mutation-admission-X4PF2SG3.js +0 -2
  914. package/dist/cli-bundle/focused-chunks/settlement-hook-ARYCZQY4.js +0 -7
  915. package/dist/cli-bundle/focused-chunks/stage-O7T7CXBB.js +0 -2
  916. package/dist/sdk/agent/refusal-closure.js +0 -2
  917. package/dist/sdk/agent/refusal-reachability.js +0 -4
  918. package/dist/sdk/agent/task-transcript-contracts.js +0 -2
  919. package/dist/sdk/agent/tracker-preflight-contracts.js +0 -2
  920. package/dist/sdk/authoring.js +0 -2
  921. package/dist/sdk/compose.js +0 -2
  922. package/dist/sdk/contracts.js +0 -2
  923. package/dist/sdk/core-governance.js +0 -2
  924. package/dist/sdk/core.js +0 -2
  925. package/dist/sdk/corpus-shape.js +0 -2
  926. package/dist/sdk/define.js +0 -2
  927. package/dist/sdk/environment/agent-environment.js +0 -2
  928. package/dist/sdk/governance/artifact-ledgers.js +0 -2
  929. package/dist/sdk/governance/coverage-assurance.js +0 -2
  930. package/dist/sdk/governance/reliability.js +0 -2
  931. package/dist/sdk/governance.js +0 -2
  932. package/dist/sdk/graph/adapter.js +0 -2
  933. package/dist/sdk/graph/conformance.js +0 -2
  934. package/dist/sdk/graph/index.js +0 -2
  935. package/dist/sdk/graph.js +0 -2
  936. package/dist/sdk/index.js +0 -2
  937. package/dist/sdk/query.js +0 -2
  938. package/dist/sdk/relationship-migration.js +0 -2
  939. package/dist/sdk/testing.js +0 -8
  940. package/dist/sdk/workspace-recipe.js +0 -2
  941. package/docs/AGENT_PROVENANCE_ADR.md +0 -206
  942. package/docs/DEFECT_RECURRENCE.md +0 -257
  943. package/docs/PERFORMANCE.md +0 -204
@@ -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]="8e9a2374-d190-52e1-8afd-14e1954863f0")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import os from"node:os";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{readAuthorEnvironment}from"../../core/shared/author.js";import{getBackgroundTestRunStatus,listBackgroundTestRuns,readBackgroundTestRunLogs,resumeBackgroundTestRun,runBackgroundTestRunWorker,spawnBackgroundTestRunWorker,startBackgroundTestRun,stopBackgroundTestRun}from"../../core/test/background-runs.js";import{resolveGlobalPmRoot,resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{parseLimit}from"../../core/shared/numeric-parsers.js";const BACKGROUND_STATUS_VALUES=["queued","running","passed","failed","stopped","canceled"],BACKGROUND_STREAM_VALUES=["stdout","stderr","both"];function normalizeStatus(value){if(value===void 0)return;const normalized=value.trim().toLowerCase();if(BACKGROUND_STATUS_VALUES.includes(normalized))return normalized;throw new PmCliError(`Invalid --status value "${value}"`,EXIT_CODE.USAGE)}function normalizeStream(value){if(value===void 0||value.trim().length===0)return"stderr";const normalized=value.trim().toLowerCase();if(BACKGROUND_STREAM_VALUES.includes(normalized))return normalized;throw new PmCliError(`Invalid --stream value "${value}"`,EXIT_CODE.USAGE)}function resolveWhoamiFallback(){try{const username=os.userInfo().username.trim();if(username.length>0)return username}catch{}}function resolveRequestedBy(author,fallback){const candidates=[author,readAuthorEnvironment(),fallback,process.env.USER,process.env.LOGNAME,process.env.USERNAME,resolveWhoamiFallback()];for(const candidate of candidates){if(typeof candidate!="string")continue;const trimmed=candidate.trim();if(trimmed.length>0)return trimmed}return"unknown"}async function ensureInitialized(pmRoot){await assertInitializedTracker(pmRoot)}async function runStartBackgroundRun(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),globalPmRoot=resolveGlobalPmRoot(process.cwd());await ensureInitialized(pmRoot);const settings=await readSettings(pmRoot),requestedBy=resolveRequestedBy(options.author,settings.author_default),started=await startBackgroundTestRun({pmRoot,globalPmRoot,kind:options.kind,commandArgs:options.commandArgs,requestedBy,targetId:options.targetId,statusFilter:options.statusFilter});return started.started?{started:!0,run:await spawnBackgroundTestRunWorker({pmRoot,runId:started.run.id,noExtensions:options.noExtensions===!0})}:{started:!1,duplicate_of:started.duplicate_of,run:started.run}}async function runTestRunsList(options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await ensureInitialized(pmRoot);const status=normalizeStatus(options.status),limit=parseLimit(options.limit,"limit"),runs=await listBackgroundTestRuns(pmRoot,{status,limit});return{runs,count:runs.length,filters:{status,limit}}}async function runTestRunsStatus(runId,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await ensureInitialized(pmRoot);const status=await getBackgroundTestRunStatus(pmRoot,runId);return{run:status.run,health:status.health}}async function runTestRunsLogs(runId,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await ensureInitialized(pmRoot);const stream=normalizeStream(options.stream),tail=parseLimit(options.tail,"tail"),logs=await readBackgroundTestRunLogs(pmRoot,runId,stream,tail);return{run:logs.run,stream:logs.stream,tail:logs.tail,stdout:logs.stdout,stderr:logs.stderr}}async function runTestRunsStop(runId,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await ensureInitialized(pmRoot);const stopped=await stopBackgroundTestRun(pmRoot,runId,options.force===!0);return{run:stopped.run,signal_sent:stopped.signal_sent}}async function runTestRunsResume(runId,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await ensureInitialized(pmRoot);const settings=await readSettings(pmRoot),requestedBy=resolveRequestedBy(options.author,settings.author_default),resumed=await resumeBackgroundTestRun(pmRoot,runId,requestedBy,options.noExtensions===!0);return{resumed_from:runId,run:resumed}}async function runTestRunsWorker(runId,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await ensureInitialized(pmRoot);const finished=await runBackgroundTestRunWorker(pmRoot,runId,global2.noExtensions===!0);return{id:finished.id,status:finished.status,exit_code:finished.exit_code}}export{runStartBackgroundRun,runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop,runTestRunsWorker};
1
+ import{assertInitializedTracker as l}from"../environment/tracker-preflight.js";import w from"node:os";import{EXIT_CODE as c}from"../../core/shared/constants.js";import{PmCliError as d}from"../../core/shared/errors.js";import{readAuthorEnvironment as R}from"../../core/shared/author.js";import{getBackgroundTestRunStatus as g,listBackgroundTestRuns as h,readBackgroundTestRunLogs as T,resumeBackgroundTestRun as k,runBackgroundTestRunWorker as E,spawnBackgroundTestRunWorker as S,startBackgroundTestRun as B,stopBackgroundTestRun as _}from"../../core/test/background-runs.js";import{resolveGlobalPmRoot as x,resolvePmRoot as u}from"../../core/store/paths.js";import{readSettings as m}from"../../core/store/settings.js";import{parseLimit as f}from"../../core/shared/numeric-parsers.js";const y=["queued","running","passed","failed","stopped","canceled"],A=["stdout","stderr","both"];function L(t){if(t===void 0)return;const n=t.trim().toLowerCase();if(y.includes(n))return n;throw new d(`Invalid --status value "${t}"`,c.USAGE)}function U(t){if(t===void 0||t.trim().length===0)return"stderr";const n=t.trim().toLowerCase();if(A.includes(n))return n;throw new d(`Invalid --stream value "${t}"`,c.USAGE)}function I(){try{const t=w.userInfo().username.trim();if(t.length>0)return t}catch{}}function p(t,n){const e=[t,R(),n,process.env.USER,process.env.LOGNAME,process.env.USERNAME,I()];for(const r of e){if(typeof r!="string")continue;const s=r.trim();if(s.length>0)return s}return"unknown"}async function i(t){await l(t)}async function D(t,n){const e=u(process.cwd(),n.path),r=x(process.cwd());await i(e);const s=await m(e),a=p(t.author,s.author_default),o=await B({pmRoot:e,globalPmRoot:r,kind:t.kind,commandArgs:t.commandArgs,requestedBy:a,targetId:t.targetId,statusFilter:t.statusFilter});return o.started?{started:!0,run:await S({pmRoot:e,runId:o.run.id,noExtensions:t.noExtensions===!0})}:{started:!1,duplicate_of:o.duplicate_of,run:o.run}}async function F(t,n){const e=u(process.cwd(),n.path);await i(e);const r=L(t.status),s=f(t.limit,"limit"),a=await h(e,{status:r,limit:s});return{runs:a,count:a.length,filters:{status:r,limit:s}}}async function M(t,n){const e=u(process.cwd(),n.path);await i(e);const r=await g(e,t);return{run:r.run,health:r.health}}async function K(t,n,e){const r=u(process.cwd(),e.path);await i(r);const s=U(n.stream),a=f(n.tail,"tail"),o=await T(r,t,s,a);return{run:o.run,stream:o.stream,tail:o.tail,stdout:o.stdout,stderr:o.stderr}}async function V(t,n,e){const r=u(process.cwd(),e.path);await i(r);const s=await _(r,t,n.force===!0);return{run:s.run,signal_sent:s.signal_sent}}async function $(t,n,e){const r=u(process.cwd(),e.path);await i(r);const s=await m(r),a=p(n.author,s.author_default),o=await k(r,t,a,n.noExtensions===!0);return{resumed_from:t,run:o}}async function X(t,n){const e=u(process.cwd(),n.path);await i(e);const r=await E(e,t,n.noExtensions===!0);return{id:r.id,status:r.status,exit_code:r.exit_code}}export{D as runStartBackgroundRun,F as runTestRunsList,K as runTestRunsLogs,$ as runTestRunsResume,M as runTestRunsStatus,V as runTestRunsStop,X as runTestRunsWorker};
2
2
  //# sourceMappingURL=runs.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]="8f1a3301-8938-5208-9177-72ee29f3d174")}catch{}})();import{execFile}from"node:child_process";import{readFile}from"node:fs/promises";import path from"node:path";import{promisify}from"node:util";import{ensureDir,writeFileAtomic}from"../../core/fs/fs-utils.js";import{sha256Hex,stableStringify}from"../../core/shared/serialization.js";import{isTimestampLiteral}from"../../core/shared/time.js";import{getRuntimePath}from"../../core/store/paths.js";import{assertLinkedTestContext}from"./entry.js";const execFileAsync=promisify(execFile),LINKED_TEST_TRUST_LEDGER_VERSION=1,LINKED_TEST_TRUST_LEDGER_FILE="linked-test-trust.json";function trustLedgerPath(pmRoot){return path.join(getRuntimePath(pmRoot),LINKED_TEST_TRUST_LEDGER_FILE)}function emptyTrustLedger(){return{version:LINKED_TEST_TRUST_LEDGER_VERSION,acknowledged:{}}}async function readTrustLedger(pmRoot){try{const parsed=JSON.parse(await readFile(trustLedgerPath(pmRoot),"utf8"));return parsed.version!==LINKED_TEST_TRUST_LEDGER_VERSION||typeof parsed.acknowledged!="object"||parsed.acknowledged===null||Array.isArray(parsed.acknowledged)?emptyTrustLedger():{version:LINKED_TEST_TRUST_LEDGER_VERSION,acknowledged:parsed.acknowledged}}catch{return emptyTrustLedger()}}async function resolveLinkedTestSourceRef(cwd=process.cwd()){const hostedRef=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(hostedRef&&hostedRef!=="merge")return hostedRef;try{const{stdout}=await execFileAsync("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd,encoding:"utf8",windowsHide:!0,timeout:1e4}),ref=stdout.trim();return ref.length===0?void 0:ref}catch{return}}function resolveLinkedTestSourceWorkspaceRoot(cwd=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||cwd}function hasValidLinkedTestProvenance(provenance){return provenance===null||typeof provenance!="object"?!1:typeof provenance.author=="string"&&provenance.author.trim().length>0&&typeof provenance.created_at=="string"&&isTimestampLiteral(provenance.created_at)&&(provenance.source_kind==="local_mutation"||provenance.source_kind==="merge_union")}function linkedTestTrustRefs(sourceRef,currentSourceRef){return{...sourceRef?{source_ref:sourceRef}:{},...currentSourceRef?{current_source_ref:currentSourceRef}:{}}}function attachLinkedTestProvenance(tests,author,createdAt,sourceRef){return tests?.map(test=>test.command&&!test.provenance?{...test,provenance:{author,created_at:createdAt,source_kind:"local_mutation",...sourceRef?{source_ref:sourceRef}:{}}}:test)}async function attachLinkedTestMutationProvenance(tests,author,createdAt){if(!tests||tests.length===0)return tests;for(const test of tests)assertLinkedTestContext(test);const sourceWorkspaceRoot=resolveLinkedTestSourceWorkspaceRoot();return attachLinkedTestProvenance(tests,author,createdAt,await resolveLinkedTestSourceRef(sourceWorkspaceRoot))}function linkedTestTrustFingerprint(test){return sha256Hex(stableStringify({command:test.command??null,path:test.path??null,scope:test.scope,pm_context_mode:test.pm_context_mode??null,workspace_context_mode:test.workspace_context_mode??null,env_set:test.env_set??null,env_clear:test.env_clear??null,shared_host_safe:test.shared_host_safe??null,provenance:test.provenance??null,provenance_invalid:test.provenance_invalid??null}))}async function resolveLinkedTestTrust(pmRoot,test,currentSourceRef){const ledger=await readTrustLedger(pmRoot);return resolveLinkedTestTrustFromLedger(test,currentSourceRef,ledger)}function resolveLinkedTestTrustFromLedger(test,currentSourceRef,ledger){const fingerprint=linkedTestTrustFingerprint(test),sourceRef=test.provenance?.source_ref;if(test.provenance===void 0&&test.provenance_invalid!==!0)return{fingerprint,trusted:!0,reason:"legacy"};const acknowledged=Object.hasOwn(ledger.acknowledged,fingerprint);return test.provenance_invalid===!0||!hasValidLinkedTestProvenance(test.provenance)?acknowledged?{fingerprint,trusted:!0,reason:"acknowledged",...linkedTestTrustRefs(void 0,currentSourceRef)}:{fingerprint,trusted:!1,reason:"invalid_provenance",...linkedTestTrustRefs(void 0,currentSourceRef)}:test.provenance.source_kind==="local_mutation"&&sourceRef===void 0?{fingerprint,trusted:!0,reason:"local_mutation",...linkedTestTrustRefs(void 0,currentSourceRef)}:test.provenance.source_kind==="local_mutation"&&sourceRef!==void 0&&sourceRef===currentSourceRef?{fingerprint,trusted:!0,reason:"local_source_ref",source_ref:sourceRef,current_source_ref:currentSourceRef}:acknowledged?{fingerprint,trusted:!0,reason:"acknowledged",...linkedTestTrustRefs(sourceRef,currentSourceRef)}:{fingerprint,trusted:!1,reason:"foreign_source_ref",...linkedTestTrustRefs(sourceRef,currentSourceRef)}}async function resolveLinkedTestTrustBatch(pmRoot,tests,currentSourceRef){const ledger=await readTrustLedger(pmRoot);return tests.map(test=>resolveLinkedTestTrustFromLedger(test,currentSourceRef,ledger))}async function acknowledgeLinkedTests(pmRoot,tests,acknowledgedAt){const ledger=await readTrustLedger(pmRoot),fingerprints=tests.filter(test=>typeof test.command=="string"&&test.command.length>0).map(linkedTestTrustFingerprint);for(const fingerprint of fingerprints)ledger.acknowledged[fingerprint]={acknowledged_at:acknowledgedAt};return await ensureDir(path.dirname(trustLedgerPath(pmRoot))),await writeFileAtomic(trustLedgerPath(pmRoot),`${JSON.stringify(ledger,null,2)}
2
- `),{acknowledged:fingerprints.length,fingerprints}}export{acknowledgeLinkedTests,attachLinkedTestMutationProvenance,attachLinkedTestProvenance,linkedTestTrustFingerprint,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust,resolveLinkedTestTrustBatch};
1
+ import{execFile as m}from"node:child_process";import{readFile as p}from"node:fs/promises";import u from"node:path";import{promisify as g}from"node:util";import{ensureDir as k,writeFileAtomic as T}from"../../core/fs/fs-utils.js";import{sha256Hex as v,stableStringify as w}from"../../core/shared/serialization.js";import{isTimestampLiteral as h}from"../../core/shared/time.js";import{getRuntimePath as y}from"../../core/store/paths.js";import{assertLinkedTestContext as L}from"./entry.js";const E=g(m),c=1,x="linked-test-trust.json";function s(e){return u.join(y(e),x)}function l(){return{version:c,acknowledged:{}}}async function d(e){try{const n=JSON.parse(await p(s(e),"utf8"));return n.version!==c||typeof n.acknowledged!="object"||n.acknowledged===null||Array.isArray(n.acknowledged)?l():{version:c,acknowledged:n.acknowledged}}catch{return l()}}async function F(e=process.cwd()){const n=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(n&&n!=="merge")return n;try{const{stdout:o}=await E("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=o.trim();return r.length===0?void 0:r}catch{return}}function O(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function A(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&h(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function a(e,n){return{...e?{source_ref:e}:{},...n?{current_source_ref:n}:{}}}function D(e,n,o,r){return e?.map(t=>t.command&&!t.provenance?{...t,provenance:{author:n,created_at:o,source_kind:"local_mutation",...r?{source_ref:r}:{}}}:t)}async function G(e,n,o){if(!e||e.length===0)return e;for(const t of e)L(t);const r=O();return D(e,n,o,await F(r))}function f(e){return v(w({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function B(e,n,o){const r=await d(e);return _(n,o,r)}function _(e,n,o){const r=f(e),t=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};const i=Object.hasOwn(o.acknowledged,r);return e.provenance_invalid===!0||!A(e.provenance)?i?{fingerprint:r,trusted:!0,reason:"acknowledged",...a(void 0,n)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...a(void 0,n)}:e.provenance.source_kind==="local_mutation"&&t===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...a(void 0,n)}:e.provenance.source_kind==="local_mutation"&&t!==void 0&&t===n?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:t,current_source_ref:n}:i?{fingerprint:r,trusted:!0,reason:"acknowledged",...a(t,n)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...a(t,n)}}async function C(e,n,o){const r=await d(e);return n.map(t=>_(t,o,r))}async function K(e,n,o){const r=await d(e),t=n.filter(i=>typeof i.command=="string"&&i.command.length>0).map(f);for(const i of t)r.acknowledged[i]={acknowledged_at:o};return await k(u.dirname(s(e))),await T(s(e),`${JSON.stringify(r,null,2)}
2
+ `),{acknowledged:t.length,fingerprints:t}}export{K as acknowledgeLinkedTests,G as attachLinkedTestMutationProvenance,D as attachLinkedTestProvenance,f as linkedTestTrustFingerprint,F as resolveLinkedTestSourceRef,O as resolveLinkedTestSourceWorkspaceRoot,B as resolveLinkedTestTrust,C as resolveLinkedTestTrustBatch};
3
3
  //# sourceMappingURL=trust.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]="f75d72fe-b7f5-576d-b6c1-1cd94e3288b3")}catch{}})();import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{normalizeLinkedTest}from"../../core/item/item-format.js";import{parseOnlyIndexValue}from"../../core/test/run-selectors.js";import{resolveAuthor}from"../../core/shared/author.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{stableValueEquals}from"../../core/shared/serialization.js";import{nowIso}from"../../core/shared/time.js";import{mutateItemWithHistoryContextResolver}from"../../core/store/item-store.js";import{resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{renderPmCommand,resolvePmCommandScopeArgs}from"../command-line.js";import{assertLinkedTestContext,linkedTestsHaveSameIdentity,STRUCTURED_LINKED_TEST_KEYS}from"./entry.js";import{parseLinkedTestJsonEntries}from"./parsers.js";import{assertNoRecursiveTestAllCommand}from"./linked-command-detection.js";const COMMAND_IDENTITY_KEYS=["command","cmd"],EDITABLE_LINKED_TEST_KEYS=Object.freeze(STRUCTURED_LINKED_TEST_KEYS.filter(key=>!["command","cmd","timeout"].includes(key)));function parseLinkedTestUpdateOptions(options){if(options.update===void 0&&options.updateIndex===void 0&&options.setJson===void 0)return;if(options.update===void 0==(options.updateIndex===void 0)||options.setJson===void 0)throw new PmCliError("Use exactly one --update or --update-index with --set-json",EXIT_CODE.USAGE);let patch;try{patch=JSON.parse(options.setJson)}catch{throw new PmCliError("--set-json must contain a JSON object with explicit linked-test metadata fields",EXIT_CODE.USAGE)}if(options.updateIndex!==void 0)return{selector:{index:parseOnlyIndexValue(options.updateIndex,"--update-index")},patch};const value=options.update,prefix=/^(command|path)=/u.exec(value);return{selector:prefix?.[1]==="path"?{path:value.slice(prefix[0].length)}:{command:prefix?value.slice(prefix[0].length):value},patch}}function assertLinkedTestEditUsage(options){if([options.list,options.run,options.progress,options.timeout!==void 0,options.acknowledgeLinkedTests,options.metricBelow!==void 0,options.metricDiff!==void 0,(options.add?.length??0)>0,(options.addJson?.length??0)>0,(options.remove?.length??0)>0,(options.removeIndex?.length??0)>0].some(Boolean))throw new PmCliError("Edit linked-test metadata separately from listing, additions, removals, execution options, metric filters and trust acknowledgement",EXIT_CODE.USAGE)}function selectIndex(tests,selector){if(typeof selector!="object"||selector===null||Array.isArray(selector))throw new PmCliError("Select one linked test by index, command, or path",EXIT_CODE.USAGE);const keys=Object.keys(selector);if(keys.length!==1||!["index","command","path"].includes(keys[0]))throw new PmCliError("Select one linked test by index, command, or path",EXIT_CODE.USAGE);if("index"in selector){const index=parseOnlyIndexValue(selector.index,"--update-index");if(index<=tests.length)return index-1}else{const key="command"in selector?"command":"path",value="command"in selector?selector.command:selector.path;if(typeof value!="string"||value.trim().length===0)throw new PmCliError("Linked-test selector must be a non-empty command or path",EXIT_CODE.USAGE);const matches=tests.flatMap((test,index)=>test[key]===value?[index]:[]);if(matches.length===1)return matches[0];if(matches.length>1)throw new PmCliError(`Linked-test selector is ambiguous; matching indexes: ${matches.map(index=>index+1).join(", ")}`,EXIT_CODE.USAGE,{code:"linked_test_update_ambiguous",required:"List linked tests and select one current --update-index."})}throw new PmCliError("No linked test matched the update selector",EXIT_CODE.NOT_FOUND,{code:"linked_test_update_no_match",required:"List linked tests and select a current command, path, or --update-index."})}function assertEditablePatchFields(patch,allowEmpty){const keys=Object.keys(patch),unsupported=keys.filter(key=>!EDITABLE_LINKED_TEST_KEYS.includes(key));if(keys.length===0&&!allowEmpty||unsupported.length>0)throw new PmCliError("Patch explicit linked-test metadata fields; command, aliases and provenance cannot be edited",EXIT_CODE.USAGE,{code:"linked_test_patch_fields_unsupported",changed:!1,...unsupported.length>0?{field:unsupported[0]}:{},required:`Patch at least one editable field: ${EDITABLE_LINKED_TEST_KEYS.join(", ")}.`,recovery:{allowed_values:[...EDITABLE_LINKED_TEST_KEYS]},...unsupported.length>0?{nextSteps:[`Remove unsupported field(s) from --set-json: ${unsupported.join(", ")}.`]}:{}});if(patch.scope===null)throw new PmCliError("scope is required and cannot be cleared",EXIT_CODE.USAGE)}function buildReplacementEntry(test,patch,command){const entry={};for(const key of EDITABLE_LINKED_TEST_KEYS){const value=patch[key]!==void 0?patch[key]:test[key];value!=null&&(entry[key]=value)}return{command,...entry}}function commandImmutableContext(identityKey){return{field:identityKey,changed:!1,required:"Replace the entry instead: remove the selected linked test and add the new command in one pm test invocation, which records fresh provenance."}}function resolveRequestedCommand(record,identityKey,current){const spellings=COMMAND_IDENTITY_KEYS.filter(key=>Object.hasOwn(record,key)).map(key=>record[key]),requested=typeof record[identityKey]=="string"?record[identityKey].trim():"";if(spellings.length>1&&spellings.some(spelling=>typeof spelling!="string"||spelling.trim()!==requested))throw new PmCliError("--set-json sets command and cmd to different values; send one command",EXIT_CODE.USAGE,{code:"linked_test_command_immutable",...commandImmutableContext(identityKey),nextSteps:["Send the replacement command once, as command."]});if(requested.length===0||requested===current.command)throw new PmCliError(requested.length===0?`--set-json cannot set ${identityKey}: a linked test's command is its immutable identity`:`--set-json ${identityKey} repeats the selected entry's command; omit it to edit only metadata`,EXIT_CODE.USAGE,{code:"linked_test_command_immutable",...commandImmutableContext(identityKey),nextSteps:[`Patch only editable fields: ${EDITABLE_LINKED_TEST_KEYS.join(", ")}.`]});return assertNoRecursiveTestAllCommand(requested),requested}function admitReplacementEntry(params){const{id,tests,index,identityKey,otherFields,requested,global:global2}=params;assertEditablePatchFields(otherFields,!0);const entry=buildReplacementEntry(tests[index],otherFields,requested),candidate=parseLinkedTestJsonEntries(JSON.stringify(entry),"--add-json")[0];assertLinkedTestContext(candidate);const collision=tests.findIndex((test,position)=>position!==index&&linkedTestsHaveSameIdentity(test,candidate));if(collision>=0)throw new PmCliError(`--set-json cannot change ${identityKey}: linked test ${collision+1} already has the requested identity, so a replacement would merge into it`,EXIT_CODE.USAGE,{code:"linked_test_command_immutable",...commandImmutableContext(identityKey),nextSteps:[`Edit linked test ${collision+1} instead: ${renderPmCommand([...resolvePmCommandScopeArgs(global2),"test",id,"--update-index",String(collision+1),"--set-json","<editable fields>"])}`,`Or drop the selected entry: ${renderPmCommand([...resolvePmCommandScopeArgs(global2),"test",id,"--remove-index",String(index+1)])}`]});return entry}function replacementControlArgs(controls){return[...controls.author!==void 0?["--author",controls.author]:[],...controls.message!==void 0?["--message",controls.message]:[],...controls.force===!0?["--force"]:[]]}function assertCommandIdentityUnchanged(params){const{id,tests,index,patch,global:global2,controls}=params;if(typeof patch!="object"||patch===null||Array.isArray(patch))return;const record=patch,identityKey=COMMAND_IDENTITY_KEYS.find(key=>Object.hasOwn(record,key));if(identityKey===void 0)return;const current=tests[index],requested=resolveRequestedCommand(record,identityKey,current),otherFields=Object.fromEntries(Object.entries(record).filter(([key])=>!COMMAND_IDENTITY_KEYS.includes(key))),entry=admitReplacementEntry({id,tests,index,identityKey,otherFields,requested,global:global2}),removal=current.command!==void 0&&tests.filter(test=>test.command===current.command).length===1?["--remove",`command=${current.command}`]:["--remove-index",String(index+1)],retryArgs=[...resolvePmCommandScopeArgs(global2),"test",id,...removal,"--add-json",JSON.stringify(entry),...replacementControlArgs(controls)];throw new PmCliError(`--set-json cannot change ${identityKey}: a linked test's command is its immutable identity; replace the entry instead`,EXIT_CODE.USAGE,{code:"linked_test_command_immutable",...commandImmutableContext(identityKey),recovery:{suggested_retry:renderPmCommand(retryArgs),suggested_retry_args:retryArgs},nextSteps:["Run the suggested retry: it removes the selected entry and adds the new command in one history-recorded write. It selects the entry by its current command or list position, so list the linked tests again first if another writer may have changed them.",`SDK: runTest(${JSON.stringify(id)}, { ${removal[0]==="--remove"?"remove":"removeIndex"}: [...], addJson: [...] }, { path: <the same tracker root> }) with the same values.`]})}function applyPatch(test,patch){if(typeof patch!="object"||patch===null||Array.isArray(patch))throw new PmCliError("Linked-test metadata patch must be a JSON object",EXIT_CODE.USAGE);const keys=Object.keys(patch);assertEditablePatchFields(patch,!1);const metadata=Object.fromEntries(Object.entries(test).filter(([key])=>STRUCTURED_LINKED_TEST_KEYS.includes(key))),parsed=normalizeLinkedTest(parseLinkedTestJsonEntries(JSON.stringify({...metadata,command:test.command??"legacy-path-only",...Object.fromEntries(Object.entries(patch).map(([key,value])=>[key,value===null?void 0:value]))}),"--set-json")[0]);assertLinkedTestContext(parsed);const fields=keys.filter(key=>!stableValueEquals(test[key],parsed[key])),next={...test};for(const key of fields){const value=parsed[key];Object.assign(next,{[key]:value}),value===void 0&&delete next[key]}if(!next.command?.trim()&&!next.path?.trim())throw new PmCliError("Linked-test entry must retain a command or path",EXIT_CODE.USAGE);return{test:next,fields}}async function updateLinkedTest(id,options,global2={}){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),author=resolveAuthor(options.author,settings.author_default),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());let updatedIndex=0,updatedFields=[];const result=await mutateItemWithHistoryContextResolver({pmRoot,settings,id,author,op:"tests_update",message:options.message,force:options.force,skipNoop:!0,typeToFolder:typeRegistry.type_to_folder,resolveHistoryContext:()=>({linked_test_update:{index:updatedIndex,fields:updatedFields}}),mutate(document){const tests2=document.metadata.tests??[],index=selectIndex(tests2,options.selector);assertCommandIdentityUnchanged({id:document.metadata.id,tests:tests2,index,patch:options.patch,global:global2,controls:options});const patch=applyPatch(tests2[index],options.patch);return updatedIndex=index+1,updatedFields=patch.fields,patch.fields.length===0?{changedFields:[]}:(document.metadata.tests=tests2.map((test,position)=>position===index?{...patch.test,updated_by:author,updated_at:nowIso()}:test),{changedFields:["tests"]})}}),tests=result.item.tests;return{ok:!0,id:result.item.id,tests,count:tests.length,changed:result.changedFields.length>0,updated_index:updatedIndex,updated_fields:updatedFields}}export{EDITABLE_LINKED_TEST_KEYS,assertLinkedTestEditUsage,parseLinkedTestUpdateOptions,updateLinkedTest};
1
+ import{getActiveExtensionRegistrations as I}from"../../core/extensions/index.js";import{resolveItemTypeRegistry as T}from"../../core/item/type-registry.js";import{normalizeLinkedTest as U}from"../../core/item/item-format.js";import{parseOnlyIndexValue as b}from"../../core/test/run-selectors.js";import{resolveAuthor as L}from"../../core/shared/author.js";import{EXIT_CODE as o}from"../../core/shared/constants.js";import{PmCliError as m}from"../../core/shared/errors.js";import{stableValueEquals as N}from"../../core/shared/serialization.js";import{nowIso as G}from"../../core/shared/time.js";import{mutateItemWithHistoryContextResolver as R}from"../../core/store/item-store.js";import{resolvePmRoot as $}from"../../core/store/paths.js";import{readSettings as C}from"../../core/store/settings.js";import{assertInitializedTracker as J}from"../environment/tracker-preflight.js";import{renderPmCommand as k,resolvePmCommandScopeArgs as _}from"../command-line.js";import{assertLinkedTestContext as E,linkedTestsHaveSameIdentity as q,STRUCTURED_LINKED_TEST_KEYS as v}from"./entry.js";import{parseLinkedTestJsonEntries as j}from"./parsers.js";import{assertNoRecursiveTestAllCommand as D}from"./linked-command-detection.js";const S=["command","cmd"],w=Object.freeze(v.filter(e=>!["command","cmd","timeout"].includes(e)));function le(e){if(e.update===void 0&&e.updateIndex===void 0&&e.setJson===void 0)return;if(e.update===void 0==(e.updateIndex===void 0)||e.setJson===void 0)throw new m("Use exactly one --update or --update-index with --set-json",o.USAGE);let t;try{t=JSON.parse(e.setJson)}catch{throw new m("--set-json must contain a JSON object with explicit linked-test metadata fields",o.USAGE)}if(e.updateIndex!==void 0)return{selector:{index:b(e.updateIndex,"--update-index")},patch:t};const a=e.update,n=/^(command|path)=/u.exec(a);return{selector:n?.[1]==="path"?{path:a.slice(n[0].length)}:{command:n?a.slice(n[0].length):a},patch:t}}function ue(e){if([e.list,e.run,e.progress,e.timeout!==void 0,e.acknowledgeLinkedTests,e.metricBelow!==void 0,e.metricDiff!==void 0,(e.add?.length??0)>0,(e.addJson?.length??0)>0,(e.remove?.length??0)>0,(e.removeIndex?.length??0)>0].some(Boolean))throw new m("Edit linked-test metadata separately from listing, additions, removals, execution options, metric filters and trust acknowledgement",o.USAGE)}function F(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new m("Select one linked test by index, command, or path",o.USAGE);const a=Object.keys(t);if(a.length!==1||!["index","command","path"].includes(a[0]))throw new m("Select one linked test by index, command, or path",o.USAGE);if("index"in t){const n=b(t.index,"--update-index");if(n<=e.length)return n-1}else{const n="command"in t?"command":"path",d="command"in t?t.command:t.path;if(typeof d!="string"||d.trim().length===0)throw new m("Linked-test selector must be a non-empty command or path",o.USAGE);const s=e.flatMap((c,i)=>c[n]===d?[i]:[]);if(s.length===1)return s[0];if(s.length>1)throw new m(`Linked-test selector is ambiguous; matching indexes: ${s.map(c=>c+1).join(", ")}`,o.USAGE,{code:"linked_test_update_ambiguous",required:"List linked tests and select one current --update-index."})}throw new m("No linked test matched the update selector",o.NOT_FOUND,{code:"linked_test_update_no_match",required:"List linked tests and select a current command, path, or --update-index."})}function A(e,t){const a=Object.keys(e),n=a.filter(d=>!w.includes(d));if(a.length===0&&!t||n.length>0)throw new m("Patch explicit linked-test metadata fields; command, aliases and provenance cannot be edited",o.USAGE,{code:"linked_test_patch_fields_unsupported",changed:!1,...n.length>0?{field:n[0]}:{},required:`Patch at least one editable field: ${w.join(", ")}.`,recovery:{allowed_values:[...w]},...n.length>0?{nextSteps:[`Remove unsupported field(s) from --set-json: ${n.join(", ")}.`]}:{}});if(e.scope===null)throw new m("scope is required and cannot be cleared",o.USAGE)}function P(e,t,a){const n={};for(const d of w){const s=t[d]!==void 0?t[d]:e[d];s!=null&&(n[d]=s)}return{command:a,...n}}function x(e){return{field:e,changed:!1,required:"Replace the entry instead: remove the selected linked test and add the new command in one pm test invocation, which records fresh provenance."}}function Y(e,t,a){const n=S.filter(s=>Object.hasOwn(e,s)).map(s=>e[s]),d=typeof e[t]=="string"?e[t].trim():"";if(n.length>1&&n.some(s=>typeof s!="string"||s.trim()!==d))throw new m("--set-json sets command and cmd to different values; send one command",o.USAGE,{code:"linked_test_command_immutable",...x(t),nextSteps:["Send the replacement command once, as command."]});if(d.length===0||d===a.command)throw new m(d.length===0?`--set-json cannot set ${t}: a linked test's command is its immutable identity`:`--set-json ${t} repeats the selected entry's command; omit it to edit only metadata`,o.USAGE,{code:"linked_test_command_immutable",...x(t),nextSteps:[`Patch only editable fields: ${w.join(", ")}.`]});return D(d),d}function z(e){const{id:t,tests:a,index:n,identityKey:d,otherFields:s,requested:c,global:i}=e;A(s,!0);const r=P(a[n],s,c),l=j(JSON.stringify(r),"--add-json")[0];E(l);const u=a.findIndex((h,f)=>f!==n&&q(h,l));if(u>=0)throw new m(`--set-json cannot change ${d}: linked test ${u+1} already has the requested identity, so a replacement would merge into it`,o.USAGE,{code:"linked_test_command_immutable",...x(d),nextSteps:[`Edit linked test ${u+1} instead: ${k([..._(i),"test",t,"--update-index",String(u+1),"--set-json","<editable fields>"])}`,`Or drop the selected entry: ${k([..._(i),"test",t,"--remove-index",String(n+1)])}`]});return r}function B(e){return[...e.author!==void 0?["--author",e.author]:[],...e.message!==void 0?["--message",e.message]:[],...e.force===!0?["--force"]:[]]}function H(e){const{id:t,tests:a,index:n,patch:d,global:s,controls:c}=e;if(typeof d!="object"||d===null||Array.isArray(d))return;const i=d,r=S.find(g=>Object.hasOwn(i,g));if(r===void 0)return;const l=a[n],u=Y(i,r,l),h=Object.fromEntries(Object.entries(i).filter(([g])=>!S.includes(g))),f=z({id:t,tests:a,index:n,identityKey:r,otherFields:h,requested:u,global:s}),p=l.command!==void 0&&a.filter(g=>g.command===l.command).length===1?["--remove",`command=${l.command}`]:["--remove-index",String(n+1)],y=[..._(s),"test",t,...p,"--add-json",JSON.stringify(f),...B(c)];throw new m(`--set-json cannot change ${r}: a linked test's command is its immutable identity; replace the entry instead`,o.USAGE,{code:"linked_test_command_immutable",...x(r),recovery:{suggested_retry:k(y),suggested_retry_args:y},nextSteps:["Run the suggested retry: it removes the selected entry and adds the new command in one history-recorded write. It selects the entry by its current command or list position, so list the linked tests again first if another writer may have changed them.",`SDK: runTest(${JSON.stringify(t)}, { ${p[0]==="--remove"?"remove":"removeIndex"}: [...], addJson: [...] }, { path: <the same tracker root> }) with the same values.`]})}function K(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new m("Linked-test metadata patch must be a JSON object",o.USAGE);const a=Object.keys(t);A(t,!1);const n=Object.fromEntries(Object.entries(e).filter(([i])=>v.includes(i))),d=U(j(JSON.stringify({...n,command:e.command??"legacy-path-only",...Object.fromEntries(Object.entries(t).map(([i,r])=>[i,r===null?void 0:r]))}),"--set-json")[0]);E(d);const s=a.filter(i=>!N(e[i],d[i])),c={...e};for(const i of s){const r=d[i];Object.assign(c,{[i]:r}),r===void 0&&delete c[i]}if(!c.command?.trim()&&!c.path?.trim())throw new m("Linked-test entry must retain a command or path",o.USAGE);return{test:c,fields:s}}async function fe(e,t,a={}){const n=$(process.cwd(),a.path);await J(n);const d=await C(n),s=L(t.author,d.author_default),c=T(d,I());let i=0,r=[];const l=await R({pmRoot:n,settings:d,id:e,author:s,op:"tests_update",message:t.message,force:t.force,skipNoop:!0,typeToFolder:c.type_to_folder,resolveHistoryContext:()=>({linked_test_update:{index:i,fields:r}}),mutate(h){const f=h.metadata.tests??[],p=F(f,t.selector);H({id:h.metadata.id,tests:f,index:p,patch:t.patch,global:a,controls:t});const y=K(f[p],t.patch);return i=p+1,r=y.fields,y.fields.length===0?{changedFields:[]}:(h.metadata.tests=f.map((g,O)=>O===p?{...y.test,updated_by:s,updated_at:G()}:g),{changedFields:["tests"]})}}),u=l.item.tests;return{ok:!0,id:l.item.id,tests:u,count:u.length,changed:l.changedFields.length>0,updated_index:i,updated_fields:r}}export{w as EDITABLE_LINKED_TEST_KEYS,ue as assertLinkedTestEditUsage,le as parseLinkedTestUpdateOptions,fe as updateLinkedTest};
2
2
  //# sourceMappingURL=update.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]="6638f21c-6cf5-5dec-a0d9-91ae323afce3")}catch{}})();import{cp,lstat,mkdir,readlink,realpath,stat,symlink}from"node:fs/promises";import{execFile}from"node:child_process";import path from"node:path";import{promisify}from"node:util";import{seedSnapshotReceiptIndex}from"./receipt-index-snapshot.js";import{isFileMissingError}from"../../core/fs/fs-utils.js";const EXCLUDED_SEGMENTS=new Set([".agents",".git",".nyc_output",".turbo","coverage"]),execFileAsync=promisify(execFile);async function seedSnapshotGitIdentity(sourceRoot,snapshotRoot){const marker=await statSnapshotTarget(path.join(sourceRoot,".git"));if(!marker||marker.isDirectory()&&!await statSnapshotTarget(path.join(sourceRoot,".git/HEAD")))return!1;const env=Object.fromEntries(Object.entries(process.env).filter(([key])=>!key.toUpperCase().startsWith("GIT_")));await execFileAsync("git",["clone","--no-local","--no-checkout","--template=","--origin=origin","--",sourceRoot,snapshotRoot],{env,timeout:12e4,maxBuffer:1024*1024,windowsHide:!0}),await execFileAsync("git",["-C",snapshotRoot,"remote","remove","origin"],{env,timeout:1e4,windowsHide:!0});try{await execFileAsync("git",["-C",snapshotRoot,"rev-parse","--verify","--quiet","HEAD"],{env,timeout:1e4,windowsHide:!0})}catch(error){if(error.code===1)return!0;throw error}return await execFileAsync("git",["-C",snapshotRoot,"read-tree","HEAD"],{env,timeout:1e4,windowsHide:!0}),!0}async function seedSnapshotGitAuthority(sourceRoot,snapshotRoot,sourcePmRoot,includeTrackerData){await seedSnapshotGitIdentity(sourceRoot,snapshotRoot)&&sourcePmRoot&&includeTrackerData!==!1&&await seedSnapshotReceiptIndex(sourceRoot,snapshotRoot,sourcePmRoot)}function hasExcludedSegment(relative){return relative.split(path.sep).some(segment=>EXCLUDED_SEGMENTS.has(segment.toLowerCase()))}function isOutsideWorkspace(relative){return relative===".."||relative.startsWith(`..${path.sep}`)||path.isAbsolute(relative)}async function statSnapshotTarget(source){try{return await stat(source)}catch(error){if(!isFileMissingError(error))throw error;return}}async function resolveLinkTarget(target){const missing=[];let ancestor=target;for(;path.dirname(ancestor)!==ancestor;)try{return path.join(await realpath(ancestor),...missing)}catch(error){if(!isFileMissingError(error))throw error;missing.unshift(path.basename(ancestor)),ancestor=path.dirname(ancestor)}return path.join(await realpath(ancestor),...missing)}async function resolveSnapshotTarget(target,sourceRoot,dependencyRoots){const relative=path.relative(sourceRoot,await resolveLinkTarget(target));if(!isOutsideWorkspace(relative))return relative;const suffix=[];let ancestor=target;for(;path.dirname(ancestor)!==ancestor;){const physicalAncestor=await resolveLinkTarget(ancestor),dependency=dependencyRoots.find(([,root])=>root===physicalAncestor);if(dependency)return path.join(dependency[0],...suffix);suffix.unshift(path.basename(ancestor)),ancestor=path.dirname(ancestor)}return relative}async function seedLinkedTestWorkspaceSnapshot(sourceRoot,snapshotRoot,sourcePmRoot,includeTrackerData){const dependencyRoots=[],sourceLinks=[],resolvedSourceRoot=await realpath(sourceRoot),resolvedSnapshotRoot=await resolveLinkTarget(path.resolve(snapshotRoot));if(![path.relative(resolvedSourceRoot,resolvedSnapshotRoot),path.relative(resolvedSnapshotRoot,resolvedSourceRoot)].every(isOutsideWorkspace))throw new Error("Snapshot destination must be disjoint from the source workspace; choose a temporary root outside the checkout.");await mkdir(path.dirname(snapshotRoot),{recursive:!0}),await seedSnapshotGitAuthority(resolvedSourceRoot,snapshotRoot,sourcePmRoot,includeTrackerData),await cp(resolvedSourceRoot,snapshotRoot,{recursive:!0,force:!0,async filter(source){const relative=path.relative(resolvedSourceRoot,source);if(!relative)return!0;if(hasExcludedSegment(relative))return!1;if(path.basename(source).toLowerCase()==="node_modules"){if((await statSnapshotTarget(source))?.isDirectory()){const target=await resolveLinkTarget(source),targetRelative=path.relative(resolvedSourceRoot,target);if(!isOutsideWorkspace(path.relative(target,resolvedSourceRoot))||!isOutsideWorkspace(targetRelative)&&(hasExcludedSegment(targetRelative)||!targetRelative.split(path.sep).some(segment=>segment.toLowerCase()==="node_modules")))throw new Error(`Dependency symlink must target an included dependency directory or external installation: ${relative}`);dependencyRoots.push([relative,target])}return!1}return(await lstat(source)).isSymbolicLink()?(sourceLinks.push([relative,path.resolve(path.dirname(source),await readlink(source)),(await statSnapshotTarget(source))?.isDirectory()?"junction":"file"]),!1):!0}});for(const[relative]of dependencyRoots)await symlink(path.resolve(resolvedSourceRoot,relative),path.join(snapshotRoot,relative),"junction");for(const[relative,target,type]of sourceLinks){const targetRelative=await resolveSnapshotTarget(target,resolvedSourceRoot,dependencyRoots);if(isOutsideWorkspace(targetRelative)||hasExcludedSegment(targetRelative))throw new Error(`Source symlink must target included workspace source: ${relative}`);await symlink(path.resolve(snapshotRoot,targetRelative),path.join(snapshotRoot,relative),type)}}export{seedLinkedTestWorkspaceSnapshot};
1
+ import{cp as E,lstat as j,mkdir as b,readlink as D,realpath as v,stat as _,symlink as g}from"node:fs/promises";import{execFile as x}from"node:child_process";import e from"node:path";import{promisify as C}from"node:util";import{seedSnapshotReceiptIndex as L}from"./receipt-index-snapshot.js";import{isFileMissingError as k}from"../../core/fs/fs-utils.js";const A=new Set([".agents",".git",".nyc_output",".turbo","coverage"]),m=C(x);async function H(i,t){const r=await p(e.join(i,".git"));if(!r||r.isDirectory()&&!await p(e.join(i,".git/HEAD")))return!1;const a=Object.fromEntries(Object.entries(process.env).filter(([o])=>!o.toUpperCase().startsWith("GIT_")));await m("git",["clone","--no-local","--no-checkout","--template=","--origin=origin","--",i,t],{env:a,timeout:12e4,maxBuffer:1024*1024,windowsHide:!0}),await m("git",["-C",t,"remote","remove","origin"],{env:a,timeout:1e4,windowsHide:!0});try{await m("git",["-C",t,"rev-parse","--verify","--quiet","HEAD"],{env:a,timeout:1e4,windowsHide:!0})}catch(o){if(o.code===1)return!0;throw o}return await m("git",["-C",t,"read-tree","HEAD"],{env:a,timeout:1e4,windowsHide:!0}),!0}async function T(i,t,r,a){await H(i,t)&&r&&a!==!1&&await L(i,t,r)}function h(i){return i.split(e.sep).some(t=>A.has(t.toLowerCase()))}function w(i){return i===".."||i.startsWith(`..${e.sep}`)||e.isAbsolute(i)}async function p(i){try{return await _(i)}catch(t){if(!k(t))throw t;return}}async function y(i){const t=[];let r=i;for(;e.dirname(r)!==r;)try{return e.join(await v(r),...t)}catch(a){if(!k(a))throw a;t.unshift(e.basename(r)),r=e.dirname(r)}return e.join(await v(r),...t)}async function I(i,t,r){const a=e.relative(t,await y(i));if(!w(a))return a;const o=[];let c=i;for(;e.dirname(c)!==c;){const s=await y(c),d=r.find(([,n])=>n===s);if(d)return e.join(d[0],...o);o.unshift(e.basename(c)),c=e.dirname(c)}return a}async function U(i,t,r,a){const o=[],c=[],s=await v(i),d=await y(e.resolve(t));if(![e.relative(s,d),e.relative(d,s)].every(w))throw new Error("Snapshot destination must be disjoint from the source workspace; choose a temporary root outside the checkout.");await b(e.dirname(t),{recursive:!0}),await T(s,t,r,a),await E(s,t,{recursive:!0,force:!0,async filter(n){const u=e.relative(s,n);if(!u)return!0;if(h(u))return!1;if(e.basename(n).toLowerCase()==="node_modules"){if((await p(n))?.isDirectory()){const f=await y(n),l=e.relative(s,f);if(!w(e.relative(f,s))||!w(l)&&(h(l)||!l.split(e.sep).some(S=>S.toLowerCase()==="node_modules")))throw new Error(`Dependency symlink must target an included dependency directory or external installation: ${u}`);o.push([u,f])}return!1}return(await j(n)).isSymbolicLink()?(c.push([u,e.resolve(e.dirname(n),await D(n)),(await p(n))?.isDirectory()?"junction":"file"]),!1):!0}});for(const[n]of o)await g(e.resolve(s,n),e.join(t,n),"junction");for(const[n,u,f]of c){const l=await I(u,s,o);if(w(l)||h(l))throw new Error(`Source symlink must target included workspace source: ${n}`);await g(e.resolve(t,l),e.join(t,n),f)}}export{U as seedLinkedTestWorkspaceSnapshot};
2
2
  //# sourceMappingURL=workspace-snapshot.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]="920b5725-710a-5839-86e3-dbdbc8a602a8")}catch{}})();import{parseSourceLineRange}from"./source-traceability.js";function runtimeFilesLookupOptions(options,paths,parseInteger){let lineRange;if(typeof options.lines=="string")lineRange=parseSourceLineRange(options.lines);else if(options.lineRange!==void 0){if(options.lineRange===null||typeof options.lineRange!="object"||Array.isArray(options.lineRange))throw new RangeError("Source line range must be an object with numeric start and end values.");lineRange=parseSourceLineRange(`${String(Reflect.get(options.lineRange,"start"))}:${String(Reflect.get(options.lineRange,"end"))}`)}return{paths,scope:options.scope==="project"||options.scope==="global"?options.scope:void 0,limit:parseInteger(options.limit,"files lookup limit"),offset:parseInteger(options.offset,"files lookup offset"),noTruncate:options.noTruncate===!0,strictRead:options.strictRead===!0,explain:options.explain===!0,lineRange,decisionDepth:parseInteger(options.decisionDepth,"files lookup decision depth")}}export{runtimeFilesLookupOptions};
1
+ import{parseSourceLineRange as i}from"./source-traceability.js";function a(e,r,l){let n;if(typeof e.lines=="string")n=i(e.lines);else if(e.lineRange!==void 0){if(e.lineRange===null||typeof e.lineRange!="object"||Array.isArray(e.lineRange))throw new RangeError("Source line range must be an object with numeric start and end values.");n=i(`${String(Reflect.get(e.lineRange,"start"))}:${String(Reflect.get(e.lineRange,"end"))}`)}return{paths:r,scope:e.scope==="project"||e.scope==="global"?e.scope:void 0,limit:l(e.limit,"files lookup limit"),offset:l(e.offset,"files lookup offset"),noTruncate:e.noTruncate===!0,strictRead:e.strictRead===!0,explain:e.explain===!0,lineRange:n,decisionDepth:l(e.decisionDepth,"files lookup decision depth")}}export{a as runtimeFilesLookupOptions};
2
2
  //# sourceMappingURL=runtime-files-lookup.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]="15749905-177d-5ae0-b475-668733f41e8a")}catch{}})();import{execFile}from"node:child_process";import path from"node:path";import{assembleWorkspaceRelationshipGraph}from"../graph/assembly.js";function runGit(workspaceRoot,args){return new Promise((resolve,reject)=>{execFile("git",[...args],{cwd:workspaceRoot,encoding:"utf8",maxBuffer:4*1024*1024},(error,stdout)=>{error?reject(error):resolve(stdout)})})}function validateLineRange(range){if(range&&(!Number.isSafeInteger(range.start)||!Number.isSafeInteger(range.end)||range.start<1||range.end<range.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function parseSourceLineRange(value){const match=/^(\d+):(\d+)$/u.exec(value.trim()),range=match?{start:Number(match[1]),end:Number(match[2])}:void 0;if(validateLineRange(range),!range)throw new RangeError("Source line range must use start:end.");return range}function parseBlameCommits(output){const lines=new Map;for(const row of output.split(`
2
- `)){const commit=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(row)?.[1];commit&&lines.set(commit,(lines.get(commit)??0)+1)}return lines}function parseCommitItemReferences(output){const fields=output.split("\0"),references=new Map;for(let index=0;index+1<fields.length;index+=2){const commit=fields[index]?.trim();if(!commit)continue;const ids=[...new Set(fields[index+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((left,right)=>left.localeCompare(right));references.set(commit,ids)}return references}async function readGitAttribution(params){const relativePath=path.relative(params.workspaceRoot,path.resolve(params.workspaceRoot,params.sourcePath)),blame=await runGit(params.workspaceRoot,["blame","--line-porcelain","-L",`${params.lineRange.start},${params.lineRange.end}`,"--",relativePath]),log=await runGit(params.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",relativePath]);return{commitLines:parseBlameCommits(blame),commitItems:parseCommitItemReferences(log),available:!0}}function expandDecisionPath(params){const tail=params.current.nodes.at(-1),nextDepth=params.current.kinds.length+1;let foundDepth;for(const edge of params.graph.incidentEdges(tail)){const outgoing=edge.source===tail,next=outgoing?edge.target:edge.source;if((params.visitedDepth.get(next)??Number.POSITIVE_INFINITY)<nextDepth)continue;params.visitedDepth.set(next,nextDepth);const definition=params.graph.registry().require(edge.kind),nextPath={nodes:[...params.current.nodes,next],kinds:[...params.current.kinds,outgoing?edge.kind:definition.inverse??edge.kind]};params.details.get(next)?.type?.toLowerCase()==="decision"?(foundDepth=nextDepth,params.found.push(nextPath)):params.queue.push(nextPath)}return foundDepth}function collectDecisionPaths(params){const queue=[{nodes:[params.itemId],kinds:[]}],visitedDepth=new Map([[params.itemId,0]]),found=[];let foundDepth;for(;queue.length>0;){const current=queue.shift(),depth=current.kinds.length;foundDepth!==void 0&&depth>=foundDepth||depth>=params.maxDepth||(foundDepth=expandDecisionPath({current,graph:params.graph,details:params.details,visitedDepth,queue,found})??foundDepth)}return found.sort((left,right)=>left.nodes.join("\0").localeCompare(right.nodes.join("\0"))),found}function shortestDecisionPath(itemId,corpus,maxDepth){const assembly=assembleWorkspaceRelationshipGraph(corpus);if(!assembly.graph.hasNode(itemId))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};const found=collectDecisionPaths({itemId,maxDepth,graph:assembly.graph,details:new Map(assembly.details.map(detail=>[detail.id,detail]))}),selected=found[0];if(!selected)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};const decisionIds=[...new Set(found.map(entry=>entry.nodes.at(-1)))];return{status:decisionIds.length===1?"found":"ambiguous",nodes:selected.nodes,kinds:selected.kinds,alternative_decision_ids:decisionIds.slice(1)}}async function resolveGitAttribution(params){if(!params.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await readGitAttribution({workspaceRoot:params.workspaceRoot,sourcePath:params.paths[0],lineRange:params.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function sourceAmbiguities(params){const ambiguities=[];return params.hasLineRange&&!params.attributionAvailable&&ambiguities.push("git_attribution_unavailable"),params.hasLineRange&&params.contributionLines===0&&ambiguities.push("line_attribution_unmapped"),params.decisionStatus==="ambiguous"&&ambiguities.push("multiple_governing_decisions"),params.decisionStatus==="not_found"&&ambiguities.push("governing_decision_not_found"),ambiguities}function mappedBlamedCommits(attribution){return[...attribution.commitLines.keys()].filter(commit=>(attribution.commitItems.get(commit)?.length??0)>0)}async function explainSourceTraceability(params){validateLineRange(params.lineRange);const decisionDepth=params.decisionDepth??8;if(!Number.isSafeInteger(decisionDepth)||decisionDepth<1||decisionDepth>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");const attribution=await resolveGitAttribution(params),mappedCommits=mappedBlamedCommits(attribution),explanations=new Map;for(const candidate of params.candidates){const attributedCommits=[...attribution.commitLines.entries()].filter(([commit])=>attribution.commitItems.get(commit)?.includes(candidate.item.id)),contributionLines=attributedCommits.reduce((total,[,lines])=>total+lines,0),decisionPath=shortestDecisionPath(candidate.item.id,params.corpus,decisionDepth),ambiguities=sourceAmbiguities({hasLineRange:params.lineRange!==void 0,attributionAvailable:attribution.available,contributionLines,decisionStatus:decisionPath.status});explanations.set(candidate.item.id,{score:contributionLines*100+candidate.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(candidate.item.updated_at))/(720*60*60*1e3))),contribution_lines:contributionLines,evidence:[...candidate.files.map(file=>({kind:"linked_file",reference:file.path})),...attributedCommits.map(([commit,lines])=>({kind:"git_commit",reference:commit.slice(0,12),contribution_lines:lines}))],rationale:{value:candidate.item.value?.trim()||null,why_now:candidate.item.why_now?.trim()||null,outcome:candidate.item.outcome?.trim()||null,objective:candidate.item.objective?.trim()||null},decision_path:decisionPath,ambiguities})}return{explanations,receipt:{line_range:params.lineRange??null,blamed_commit_count:attribution.commitLines.size,mapped_commit_count:mappedCommits.length,unmapped_commit_count:attribution.commitLines.size-mappedCommits.length,decision_depth:decisionDepth}}}const _testOnlySourceTraceability={mappedBlamedCommits,parseBlameCommits,parseCommitItemReferences,shortestDecisionPath};export{_testOnlySourceTraceability,explainSourceTraceability,parseSourceLineRange};
1
+ import{execFile as _}from"node:child_process";import l from"node:path";import{assembleWorkspaceRelationshipGraph as v}from"../graph/assembly.js";function m(e,t){return new Promise((n,i)=>{_("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(s,o)=>{s?i(s):n(o)})})}function f(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function M(e){const t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(f(n),!n)throw new RangeError("Source line range must use start:end.");return n}function h(e){const t=new Map;for(const n of e.split(`
2
+ `)){const i=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];i&&t.set(i,(t.get(i)??0)+1)}return t}function g(e){const t=e.split("\0"),n=new Map;for(let i=0;i+1<t.length;i+=2){const s=t[i]?.trim();if(!s)continue;const o=[...new Set(t[i+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((c,r)=>c.localeCompare(r));n.set(s,o)}return n}async function R(e){const t=l.relative(e.workspaceRoot,l.resolve(e.workspaceRoot,e.sourcePath)),n=await m(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),i=await m(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:h(n),commitItems:g(i),available:!0}}function k(e){const t=e.current.nodes.at(-1),n=e.current.kinds.length+1;let i;for(const s of e.graph.incidentEdges(t)){const o=s.source===t,c=o?s.target:s.source;if((e.visitedDepth.get(c)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(c,n);const r=e.graph.registry().require(s.kind),a={nodes:[...e.current.nodes,c],kinds:[...e.current.kinds,o?s.kind:r.inverse??s.kind]};e.details.get(c)?.type?.toLowerCase()==="decision"?(i=n,e.found.push(a)):e.queue.push(a)}return i}function x(e){const t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),i=[];let s;for(;t.length>0;){const o=t.shift(),c=o.kinds.length;s!==void 0&&c>=s||c>=e.maxDepth||(s=k({current:o,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:i})??s)}return i.sort((o,c)=>o.nodes.join("\0").localeCompare(c.nodes.join("\0"))),i}function p(e,t,n){const i=v(t);if(!i.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};const s=x({itemId:e,maxDepth:n,graph:i.graph,details:new Map(i.details.map(r=>[r.id,r]))}),o=s[0];if(!o)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};const c=[...new Set(s.map(r=>r.nodes.at(-1)))];return{status:c.length===1?"found":"ambiguous",nodes:o.nodes,kinds:o.kinds,alternative_decision_ids:c.slice(1)}}async function I(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await R({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function L(e){const t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function b(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function P(e){f(e.lineRange);const t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");const n=await I(e),i=b(n),s=new Map;for(const o of e.candidates){const c=[...n.commitLines.entries()].filter(([u])=>n.commitItems.get(u)?.includes(o.item.id)),r=c.reduce((u,[,d])=>u+d,0),a=p(o.item.id,e.corpus,t),w=L({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:r,decisionStatus:a.status});s.set(o.item.id,{score:r*100+o.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(o.item.updated_at))/(720*60*60*1e3))),contribution_lines:r,evidence:[...o.files.map(u=>({kind:"linked_file",reference:u.path})),...c.map(([u,d])=>({kind:"git_commit",reference:u.slice(0,12),contribution_lines:d}))],rationale:{value:o.item.value?.trim()||null,why_now:o.item.why_now?.trim()||null,outcome:o.item.outcome?.trim()||null,objective:o.item.objective?.trim()||null},decision_path:a,ambiguities:w})}return{explanations:s,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:i.length,unmapped_commit_count:n.commitLines.size-i.length,decision_depth:t}}}const N={mappedBlamedCommits:b,parseBlameCommits:h,parseCommitItemReferences:g,shortestDecisionPath:p};export{N as _testOnlySourceTraceability,P as explainSourceTraceability,M as parseSourceLineRange};
3
3
  //# sourceMappingURL=source-traceability.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]="bd9a8d3b-bc6f-5309-a3fb-7e5f41ef9dab")}catch{}})();import{discoverNearbyPmRoot}from"../core/store/paths.js";export{discoverNearbyPmRoot};
1
+ import{discoverNearbyPmRoot as e}from"../core/store/paths.js";export{e as discoverNearbyPmRoot};
2
2
  //# sourceMappingURL=tracker-root-discovery.js.map
@@ -0,0 +1,2 @@
1
+ import{getActiveExtensionRegistrations as E}from"../../core/extensions/index.js";import{collectRegisteredItemFieldNames as _}from"../../core/extensions/item-fields.js";import{canonicalDocument as l,parseItemDocument as $,serializeItemDocument as F}from"../../core/item/item-format.js";import{EXIT_CODE as O}from"../../core/shared/constants.js";import{PmCliError as b}from"../../core/shared/errors.js";import{stableStringify as m}from"../../core/shared/serialization.js";import{pruneResolvedDeferredFields as A}from"../../core/item/deferred-fields.js";import{mutateItem as I}from"../../core/store/item-store.js";import{readSettings as T}from"../../core/store/settings.js";const j=["id","updated_at","pm_format_version","type"],S="import";function p(e,t){if(typeof e!="string"||!/^[A-Za-z][A-Za-z0-9_]*$/u.test(e)||e in Object.prototype)throw new TypeError(`${t} names an invalid field ${JSON.stringify(e)}; use a front-matter field name of letters, digits and underscores`);if(j.includes(e))throw new TypeError(`${t} cannot change "${e}"; the item writer derives it, or an update row owns it`)}function u(e){return Array.isArray(e)?`array of ${e.length}`:typeof e}const z=["__proto__","constructor","prototype"];function y(e){return e!==null&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype}function h(e){return e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?Array.from(e).every(h):y(e)?Object.entries(e).every(([t,o])=>!z.includes(t)&&h(o)):!1}function N(e,t){const{set:o,unset:d}=e;if(o!==void 0&&!y(o))throw new TypeError(`${t} set must be a plain object of front-matter fields`);if(d!==void 0&&!Array.isArray(d))throw new TypeError(`${t} unset must be an array of front-matter field names`);const i=Object.keys(o??{}),s=d??[];if(i.length+s.length===0)throw new TypeError(`${t} requires at least one field in set or unset`);for(const n of i)if(p(n,t),o[n]===null||!h(o[n]))throw new TypeError(`${t} set "${n}" must be a non-null JSON value (no undefined, non-finite number, sparse array, class instance, or __proto__/constructor/prototype key); remove a field with unset`);for(const n of s){if(p(n,t),n==="body"||n==="front_matter")throw new TypeError(`${t} cannot unset "${n}"; the item format reserves that name`);if(i.includes(n))throw new TypeError(`${t} both sets and unsets "${n}"`)}if(new Set(s).size!==s.length)throw new TypeError(`${t} unset repeats a field`)}async function J(e){N(e,`Finalization of ${e.id}`);const t=await T(e.pmRoot),o={schema:t.schema,extensionFieldNames:_(E())},d=await I({pmRoot:e.pmRoot,settings:t,id:e.id,op:S,author:e.author,message:e.message,force:e.force===!0,extensionFieldNames:o.extensionFieldNames,mutate:i=>{const s=structuredClone(i.metadata),n=i.metadata;for(const[r,c]of Object.entries(e.set??{}))n[r]=structuredClone(c);for(const r of e.unset??[])delete n[r];let a;try{A(i.metadata);const r=l(i,o),c=l($(F(r,o),o),o);if(m(c)!==m(r))throw new TypeError("the stored item reads back as a different document; a set field collides with a name the item format reserves");a=r.metadata;const f=Object.entries(e.set??{}).find(([w,g])=>u(a[w])!==u(g));if(f!==void 0)throw new TypeError(`set "${f[0]}" is not stored as declared (${u(f[1])} normalizes to ${a[f[0]]===void 0?"an absent field":u(a[f[0]])})`)}catch(r){throw new b(`Finalization of ${e.id} would not store a readable item with the declared fields: ${r.message}`,O.USAGE,{code:"finalization_invalid_document",item_id:e.id,required:"Declare set and unset fields that leave a valid item under the workspace schema, with each set value in the shape its field stores.",why:"A finalization writes front-matter fields exactly, so the patched document is read back through the item reader, and each declared value is checked against what would be stored, before anything is written.",nextSteps:[`Run pm get ${e.id} --json to compare the current fields with the finalization, then correct the patch and retry the transaction.`]})}return{changedFields:[...new Set([...Object.keys(s),...Object.keys(a)])].filter(r=>Object.hasOwn(s,r)!==Object.hasOwn(a,r)||m(s[r])!==m(a[r])).sort((r,c)=>r.localeCompare(c))}}});return{item:d.item,changedFields:d.changedFields}}export{S as FINALIZATION_HISTORY_OPERATION,j as FINALIZATION_RESERVED_FIELDS,J as applyItemFinalization,N as assertValidItemFinalization,h as isJournalValue};
2
+ //# sourceMappingURL=item-finalization.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]="96234a42-d25c-5221-a12b-a992925a13ba")}catch{}})();const WORKSPACE_CONTRACTS_CACHE_LIMIT=50,workspaceExtensionRegistrationsCache=new Map;function clearWorkspaceContractsCache(){workspaceExtensionRegistrationsCache.clear()}function memoizeWorkspaceExtensionRegistrations(cacheKey,loadRegistrations){const cached=workspaceExtensionRegistrationsCache.get(cacheKey);if(cached!==void 0)return cached;if(workspaceExtensionRegistrationsCache.size>=50){const oldestKey=workspaceExtensionRegistrationsCache.keys().next().value;workspaceExtensionRegistrationsCache.delete(oldestKey)}const registrations=loadRegistrations().catch(error=>{throw workspaceExtensionRegistrationsCache.get(cacheKey)===registrations&&workspaceExtensionRegistrationsCache.delete(cacheKey),error});return workspaceExtensionRegistrationsCache.set(cacheKey,registrations),registrations}export{clearWorkspaceContractsCache,memoizeWorkspaceExtensionRegistrations};
1
+ const i=50,e=new Map;function c(){e.clear()}function C(t,r){const s=e.get(t);if(s!==void 0)return s;if(e.size>=50){const o=e.keys().next().value;e.delete(o)}const n=r().catch(o=>{throw e.get(t)===n&&e.delete(t),o});return e.set(t,n),n}export{c as clearWorkspaceContractsCache,C as memoizeWorkspaceExtensionRegistrations};
2
2
  //# sourceMappingURL=workspace-contracts-cache.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="69f9c792-7ee1-5e4b-9900-38e1c887c4d4")}catch{}})();import{runtimeFieldOptionTarget}from"../core/schema/runtime-schema.js";function buildWorkspaceFieldContracts(definitions){return definitions.map(definition=>({key:definition.key,optionName:runtimeFieldOptionTarget(definition),metadataKey:definition.metadata_key,type:definition.type,commands:[...definition.commands],repeatable:definition.repeatable,requiredOnCreate:definition.required_on_create,...definition.description?{description:definition.description}:{}}))}function buildWorkspaceExtensionCommandContracts(definitions){return definitions.map(definition=>({command:definition.command,action:definition.action,arguments:definition.arguments.map(argument=>({name:argument.name,required:argument.required===!0,variadic:argument.variadic===!0,description:argument.description})),description:definition.description,tier:definition.tier??"standard",family:definition.family??"extensions"}))}export{buildWorkspaceExtensionCommandContracts,buildWorkspaceFieldContracts};
1
+ import{runtimeFieldOptionTarget as t}from"../core/schema/runtime-schema.js";function m(a){return a.map(e=>({key:e.key,optionName:t(e),metadataKey:e.metadata_key,type:e.type,commands:[...e.commands],repeatable:e.repeatable,requiredOnCreate:e.required_on_create,...e.description?{description:e.description}:{}}))}function p(a){return a.map(e=>({command:e.command,action:e.action,arguments:e.arguments.map(r=>({name:r.name,required:r.required===!0,variadic:r.variadic===!0,description:r.description})),description:e.description,tier:e.tier??"standard",family:e.family??"extensions"}))}export{p as buildWorkspaceExtensionCommandContracts,m as buildWorkspaceFieldContracts};
2
2
  //# sourceMappingURL=workspace-contracts.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]="df753f1d-cfc1-555e-a411-e1417eab0b53")}catch{}})();import path from"node:path";import{createHash}from"node:crypto";import{isFileAbsentError,writeFileAtomic}from"../core/fs/fs-utils.js";import{normalizeStatusForRegistry}from"../core/item/status.js";import{stableStringify}from"../core/shared/serialization.js";import{readItemMetadataDerivedIndexState}from"../core/store/item-metadata-cache.js";import{resolveCompletionTimestamp}from"./lifecycle-completion.js";import fs from"node:fs/promises";const WORKSPACE_MEMORY_FORMAT_VERSION=1,DEFAULT_WORKSPACE_MEMORY_MINIMUM_ITEMS=1e4,DEFAULT_ROLLUP_LIMIT=12;function quarterKey(timestamp){const date=new Date(timestamp);return`${date.getUTCFullYear()}-Q${Math.floor(date.getUTCMonth()/3)+1}`}function nearestEpic(item,itemsById){const visited=new Set;let parentId=item.parent;for(;parentId&&!visited.has(parentId);){visited.add(parentId);const parent=itemsById.get(parentId);if(!parent)return;if(parent.type.toLowerCase()==="epic")return parent;parentId=parent.parent}}function finalizeRollup(rollup){const ordered=[...rollup.items].sort((left,right)=>right.completion.timestamp.localeCompare(left.completion.timestamp)||left.item.id.localeCompare(right.item.id)),outcomes=new Set;let knowledgeEntries=0;for(const{item}of ordered){const outcome=item.resolution??item.close_reason;outcome?.trim()&&outcomes.add(outcome.trim()),knowledgeEntries+=(item.notes?.length??0)+(item.learnings?.length??0)}return{kind:rollup.kind,key:rollup.key,label:rollup.label,item_count:ordered.length,first_closed_at:ordered.at(-1).completion.timestamp,last_closed_at:ordered[0].completion.timestamp,representative_items:ordered.slice(0,5).map(({item:{id,title}})=>({id,title})),outcomes:[...outcomes].sort().slice(0,5),knowledge_entries:knowledgeEntries}}function buildWorkspaceMemorySnapshot(items,options){if(!options.sourceCursor.trim())throw new TypeError("Workspace memory source cursor must be non-empty");if(!Number.isFinite(Date.parse(options.now)))throw new TypeError("Workspace memory clock must be a valid timestamp");const completed=items.filter(item=>options.statusRegistry.terminal_done_statuses.has(normalizeStatusForRegistry(item.status,options.statusRegistry))).map(item=>{const completion=resolveCompletionTimestamp(item);if(!completion.resolved)throw new TypeError(`Completed item ${item.id} has no reporting timestamp`);return{item,completion}}),itemsById=new Map(items.map(item=>[item.id,item])),groups=new Map;for(const completedItem of completed){const{item,completion}=completedItem,epoch=quarterKey(completion.timestamp),epochKey=`epoch:${epoch}`,epochRollup=groups.get(epochKey)??{kind:"epoch",key:epoch,label:epoch,items:[]};epochRollup.items.push(completedItem),groups.set(epochKey,epochRollup);const epic=nearestEpic(item,itemsById);if(epic){const epicKey=`epic:${epic.id}`,epicRollup=groups.get(epicKey)??{kind:"epic",key:epic.id,label:epic.title,items:[]};epicRollup.items.push(completedItem),groups.set(epicKey,epicRollup)}}return{format_version:WORKSPACE_MEMORY_FORMAT_VERSION,source_cursor:options.sourceCursor,source_item_count:items.length,generated_at:options.now,completion_time_sources:completed.reduce((counts,{completion})=>(counts[completion.source]+=1,counts),{completed_at:0,closed_at:0,updated_at:0}),rollups:[...groups.values()].map(finalizeRollup).sort((left,right)=>right.last_closed_at.localeCompare(left.last_closed_at)||left.kind.localeCompare(right.kind)||left.key.localeCompare(right.key))}}function isWorkspaceMemoryItemReference(value){return typeof value=="object"&&value!==null&&"id"in value&&typeof value.id=="string"&&value.id.length>0&&"title"in value&&typeof value.title=="string"}function isWorkspaceMemoryRollup(value){if(typeof value!="object"||value===null)return!1;const rollup=value,textFields=[rollup.key,rollup.label].every(field=>typeof field=="string"&&field.length>0),timestamps=[rollup.first_closed_at,rollup.last_closed_at].every(timestamp=>typeof timestamp=="string"&&Number.isFinite(Date.parse(timestamp)));return(rollup.kind==="epoch"||rollup.kind==="epic")&&textFields&&Number.isSafeInteger(rollup.item_count)&&rollup.item_count>0&&timestamps&&Array.isArray(rollup.representative_items)&&rollup.representative_items.every(isWorkspaceMemoryItemReference)&&Array.isArray(rollup.outcomes)&&rollup.outcomes.every(outcome=>typeof outcome=="string")&&Number.isSafeInteger(rollup.knowledge_entries)&&rollup.knowledge_entries>=0}function parseWorkspaceMemorySnapshot(value){if(typeof value!="object"||value===null||Array.isArray(value))return null;const snapshot=value;return snapshot.format_version!==WORKSPACE_MEMORY_FORMAT_VERSION||typeof snapshot.source_cursor!="string"||!snapshot.source_cursor.trim()||!Number.isSafeInteger(snapshot.source_item_count)||snapshot.source_item_count<0||typeof snapshot.generated_at!="string"||!Number.isFinite(Date.parse(snapshot.generated_at))||!Array.isArray(snapshot.rollups)?null:snapshot.rollups.every(isWorkspaceMemoryRollup)?snapshot:null}function fallbackSourceCursor(items){return`scan:${createHash("sha256").update(stableStringify(items.map(item=>[item.id,item.updated_at,item.status,item.parent]).sort(([left],[right])=>String(left).localeCompare(String(right))))).digest("hex")}`}async function resolveWorkspaceMemorySourceCursor(items,pmRoot,explicitCursor){return explicitCursor!==void 0?explicitCursor:(await readItemMetadataDerivedIndexState(pmRoot))?.source_cursor??fallbackSourceCursor(items)}async function readPersistedWorkspaceMemory(filePath){try{const snapshot=parseWorkspaceMemorySnapshot(JSON.parse(await fs.readFile(filePath,"utf8")));return{snapshot,invalid:snapshot===null}}catch(error){return{snapshot:null,invalid:!(typeof error=="object"&&error!==null&&"code"in error&&isFileAbsentError(error))}}}async function readWorkspaceMemory(items,options){const minimumItems=Math.max(1,Math.floor(options.minimumItems??DEFAULT_WORKSPACE_MEMORY_MINIMUM_ITEMS));if(items.length<minimumItems)return{snapshot:null,cache_status:"skipped",warnings:[]};const sourceCursor=await resolveWorkspaceMemorySourceCursor(items,options.pmRoot,options.sourceCursor),filePath=path.join(options.pmRoot,"runtime","workspace-memory.json"),warnings=[],persisted=await readPersistedWorkspaceMemory(filePath),parsed=persisted.snapshot;if(persisted.invalid&&warnings.push("workspace_memory_invalid"),parsed?.source_cursor===sourceCursor&&parsed.source_item_count===items.length)return{snapshot:parsed,cache_status:"fresh",warnings};parsed&&warnings.push("workspace_memory_stale");const snapshot=buildWorkspaceMemorySnapshot(items,{statusRegistry:options.statusRegistry,sourceCursor,now:options.now});try{await writeFileAtomic(filePath,`${JSON.stringify(snapshot)}
2
- `)}catch{warnings.push("workspace_memory_write_failed")}return{snapshot,cache_status:"rebuilt",warnings}}function selectWorkspaceMemoryRollups(snapshot,tokenBudget,limit=DEFAULT_ROLLUP_LIMIT){const boundedBudget=Math.max(0,Math.floor(tokenBudget));let consumed=0;const selected=[];for(const rollup of snapshot.rollups){if(selected.length>=Math.max(0,Math.floor(limit)))break;const tokens=Math.ceil(JSON.stringify(rollup).length/4);consumed+tokens>boundedBudget||(selected.push(rollup),consumed+=tokens)}return selected}function selectWorkspaceMemory(memory,tokenBudget,limit=DEFAULT_ROLLUP_LIMIT){if(memory.snapshot===null)return;const rollups=selectWorkspaceMemoryRollups(memory.snapshot,tokenBudget,limit);if(rollups.length!==0)return{cache_status:memory.cache_status==="fresh"?"fresh":"rebuilt",source_cursor:memory.snapshot.source_cursor,...memory.snapshot.completion_time_sources?{completion_time_sources:{...memory.snapshot.completion_time_sources}}:{},rollups}}function searchWorkspaceMemory(snapshot,query,limit=5){if(snapshot===null)return[];const tokens=query.trim().toLowerCase().split(/\s+/u).filter(Boolean);return tokens.length===0?[]:snapshot.rollups.map(rollup=>({rollup,score:tokens.filter(token=>[rollup.key,rollup.label,...rollup.outcomes,...rollup.representative_items.flatMap(item=>[item.id,item.title])].join(" ").toLowerCase().includes(token)).length})).filter(({score})=>score>0).sort((left,right)=>right.score-left.score||right.rollup.last_closed_at.localeCompare(left.rollup.last_closed_at)||left.rollup.key.localeCompare(right.rollup.key)).slice(0,Math.max(0,Math.floor(limit))).map(({rollup})=>rollup)}function searchWorkspaceMemoryReadResult(memory,query,limit=5){const matches=searchWorkspaceMemory(memory.snapshot,query,limit);if(matches.length!==0)return{cache_status:memory.cache_status==="fresh"?"fresh":"rebuilt",matches}}export{DEFAULT_WORKSPACE_MEMORY_MINIMUM_ITEMS,buildWorkspaceMemorySnapshot,readWorkspaceMemory,searchWorkspaceMemory,searchWorkspaceMemoryReadResult,selectWorkspaceMemory,selectWorkspaceMemoryRollups};
1
+ import h from"node:path";import{createHash as y}from"node:crypto";import{isFileAbsentError as g,writeFileAtomic as k}from"../core/fs/fs-utils.js";import{normalizeStatusForRegistry as w}from"../core/item/status.js";import{stableStringify as M}from"../core/shared/serialization.js";import{readItemMetadataDerivedIndexState as b}from"../core/store/item-metadata-cache.js";import{resolveCompletionTimestamp as S}from"./lifecycle-completion.js";import C from"node:fs/promises";const f=1,R=1e4,_=12;function I(t){const e=new Date(t);return`${e.getUTCFullYear()}-Q${Math.floor(e.getUTCMonth()/3)+1}`}function x(t,e){const s=new Set;let n=t.parent;for(;n&&!s.has(n);){s.add(n);const r=e.get(n);if(!r)return;if(r.type.toLowerCase()==="epic")return r;n=r.parent}}function A(t){const e=[...t.items].sort((r,o)=>o.completion.timestamp.localeCompare(r.completion.timestamp)||r.item.id.localeCompare(o.item.id)),s=new Set;let n=0;for(const{item:r}of e){const o=r.resolution??r.close_reason;o?.trim()&&s.add(o.trim()),n+=(r.notes?.length??0)+(r.learnings?.length??0)}return{kind:t.kind,key:t.key,label:t.label,item_count:e.length,first_closed_at:e.at(-1).completion.timestamp,last_closed_at:e[0].completion.timestamp,representative_items:e.slice(0,5).map(({item:{id:r,title:o}})=>({id:r,title:o})),outcomes:[...s].sort().slice(0,5),knowledge_entries:n}}function W(t,e){if(!e.sourceCursor.trim())throw new TypeError("Workspace memory source cursor must be non-empty");if(!Number.isFinite(Date.parse(e.now)))throw new TypeError("Workspace memory clock must be a valid timestamp");const s=t.filter(o=>e.statusRegistry.terminal_done_statuses.has(w(o.status,e.statusRegistry))).map(o=>{const a=S(o);if(!a.resolved)throw new TypeError(`Completed item ${o.id} has no reporting timestamp`);return{item:o,completion:a}}),n=new Map(t.map(o=>[o.id,o])),r=new Map;for(const o of s){const{item:a,completion:i}=o,c=I(i.timestamp),u=`epoch:${c}`,p=r.get(u)??{kind:"epoch",key:c,label:c,items:[]};p.items.push(o),r.set(u,p);const l=x(a,n);if(l){const m=`epic:${l.id}`,d=r.get(m)??{kind:"epic",key:l.id,label:l.title,items:[]};d.items.push(o),r.set(m,d)}}return{format_version:f,source_cursor:e.sourceCursor,source_item_count:t.length,generated_at:e.now,completion_time_sources:s.reduce((o,{completion:a})=>(o[a.source]+=1,o),{completed_at:0,closed_at:0,updated_at:0}),rollups:[...r.values()].map(A).sort((o,a)=>a.last_closed_at.localeCompare(o.last_closed_at)||o.kind.localeCompare(a.kind)||o.key.localeCompare(a.key))}}function E(t){return typeof t=="object"&&t!==null&&"id"in t&&typeof t.id=="string"&&t.id.length>0&&"title"in t&&typeof t.title=="string"}function v(t){if(typeof t!="object"||t===null)return!1;const e=t,s=[e.key,e.label].every(r=>typeof r=="string"&&r.length>0),n=[e.first_closed_at,e.last_closed_at].every(r=>typeof r=="string"&&Number.isFinite(Date.parse(r)));return(e.kind==="epoch"||e.kind==="epic")&&s&&Number.isSafeInteger(e.item_count)&&e.item_count>0&&n&&Array.isArray(e.representative_items)&&e.representative_items.every(E)&&Array.isArray(e.outcomes)&&e.outcomes.every(r=>typeof r=="string")&&Number.isSafeInteger(e.knowledge_entries)&&e.knowledge_entries>=0}function F(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;const e=t;return e.format_version!==f||typeof e.source_cursor!="string"||!e.source_cursor.trim()||!Number.isSafeInteger(e.source_item_count)||e.source_item_count<0||typeof e.generated_at!="string"||!Number.isFinite(Date.parse(e.generated_at))||!Array.isArray(e.rollups)?null:e.rollups.every(v)?e:null}function O(t){return`scan:${y("sha256").update(M(t.map(e=>[e.id,e.updated_at,e.status,e.parent]).sort(([e],[s])=>String(e).localeCompare(String(s))))).digest("hex")}`}async function N(t,e,s){return s!==void 0?s:(await b(e))?.source_cursor??O(t)}async function T(t){try{const e=F(JSON.parse(await C.readFile(t,"utf8")));return{snapshot:e,invalid:e===null}}catch(e){return{snapshot:null,invalid:!(typeof e=="object"&&e!==null&&"code"in e&&g(e))}}}async function z(t,e){const s=Math.max(1,Math.floor(e.minimumItems??R));if(t.length<s)return{snapshot:null,cache_status:"skipped",warnings:[]};const n=await N(t,e.pmRoot,e.sourceCursor),r=h.join(e.pmRoot,"runtime","workspace-memory.json"),o=[],a=await T(r),i=a.snapshot;if(a.invalid&&o.push("workspace_memory_invalid"),i?.source_cursor===n&&i.source_item_count===t.length)return{snapshot:i,cache_status:"fresh",warnings:o};i&&o.push("workspace_memory_stale");const c=W(t,{statusRegistry:e.statusRegistry,sourceCursor:n,now:e.now});try{await k(r,`${JSON.stringify(c)}
2
+ `)}catch{o.push("workspace_memory_write_failed")}return{snapshot:c,cache_status:"rebuilt",warnings:o}}function L(t,e,s=_){const n=Math.max(0,Math.floor(e));let r=0;const o=[];for(const a of t.rollups){if(o.length>=Math.max(0,Math.floor(s)))break;const i=Math.ceil(JSON.stringify(a).length/4);r+i>n||(o.push(a),r+=i)}return o}function q(t,e,s=_){if(t.snapshot===null)return;const n=L(t.snapshot,e,s);if(n.length!==0)return{cache_status:t.cache_status==="fresh"?"fresh":"rebuilt",source_cursor:t.snapshot.source_cursor,...t.snapshot.completion_time_sources?{completion_time_sources:{...t.snapshot.completion_time_sources}}:{},rollups:n}}function j(t,e,s=5){if(t===null)return[];const n=e.trim().toLowerCase().split(/\s+/u).filter(Boolean);return n.length===0?[]:t.rollups.map(r=>({rollup:r,score:n.filter(o=>[r.key,r.label,...r.outcomes,...r.representative_items.flatMap(a=>[a.id,a.title])].join(" ").toLowerCase().includes(o)).length})).filter(({score:r})=>r>0).sort((r,o)=>o.score-r.score||o.rollup.last_closed_at.localeCompare(r.rollup.last_closed_at)||r.rollup.key.localeCompare(o.rollup.key)).slice(0,Math.max(0,Math.floor(s))).map(({rollup:r})=>r)}function H(t,e,s=5){const n=j(t.snapshot,e,s);if(n.length!==0)return{cache_status:t.cache_status==="fresh"?"fresh":"rebuilt",matches:n}}export{R as DEFAULT_WORKSPACE_MEMORY_MINIMUM_ITEMS,W as buildWorkspaceMemorySnapshot,z as readWorkspaceMemory,j as searchWorkspaceMemory,H as searchWorkspaceMemoryReadResult,q as selectWorkspaceMemory,L as selectWorkspaceMemoryRollups};
3
3
  //# sourceMappingURL=workspace-memory.js.map
@@ -1,6 +1,6 @@
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]="66cb8c82-3760-5628-a1de-69e417cf0292")}catch{}})();import crypto from"node:crypto";import{cp,lstat,mkdir,readFile,readdir,rename,rm,writeFile}from"node:fs/promises";import path from"node:path";import{isFileMissingError,writeFileAtomic}from"../core/fs/fs-utils.js";import{appendWorkspaceAuditEvent}from"../core/history/workspace-history.js";import{acquireLockLease,waitForStaleCleanupGate}from"../core/lock/lock.js";import{getLockPath}from"../core/store/paths.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{withHostEnvironmentBoundary}from"./environment/host-environment-errors.js";const SNAPSHOT_SCHEMA="https://schema.unbrained.dev/pm/workspace-snapshot/v1",WORKSPACE_SNAPSHOT_ACTIONS=["create","list","inspect","restore","delete"],SNAPSHOT_RUNTIME_PATH=path.join("runtime","workspace-snapshots"),EXCLUDED_ROOT_NAMES=new Set(["checkpoints","locks","runtime","search","transactions"]),SNAPSHOT_TARGET_PATTERN=/^[a-z0-9][a-z0-9._-]*$/,WORKSPACE_WRITER_LOCK_ID="sdk-workspace-transaction",SNAPSHOT_HOST_FAULT_CODES={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},DEFAULT_ATOMIC_OPERATIONS={renameEntry:rename,removeEntry:async target=>{await rm(target,{recursive:!0,force:!0})}};class WorkspaceLockHeartbeat{lockPath;owner;intervalMs;timer;refresh;failure;constructor(lockPath,owner,ttlSeconds){this.lockPath=lockPath,this.owner=owner,this.intervalMs=Math.max(10,Math.floor(ttlSeconds*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(error=>{this.failure=error}).finally(()=>{this.refresh=void 0}))}async renew(){const releaseGate=await waitForStaleCleanupGate(this.lockPath,WORKSPACE_WRITER_LOCK_ID);if(releaseGate===null)throw new Error("Workspace writer lock cleanup gate stayed held");try{const parsed=JSON.parse(await readFile(this.lockPath,"utf8"));if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error("Workspace writer lock has invalid structure");const lock=parsed;if(lock.id!==WORKSPACE_WRITER_LOCK_ID||lock.owner!==this.owner||lock.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await writeFileAtomic(this.lockPath,`${JSON.stringify({...lock,created_at:new Date().toISOString()},null,2)}
2
- `)}finally{await releaseGate()}}}const _testOnlyWorkspaceSnapshot={WorkspaceLockHeartbeat,withSnapshotFilesystemGuard};async function collectAuthoritativeFiles(root,relative=""){const entries=await readdir(path.join(root,relative),{withFileTypes:!0}),files=[];for(const entry of entries.sort((left,right)=>left.name.localeCompare(right.name))){if(relative.length===0&&EXCLUDED_ROOT_NAMES.has(entry.name))continue;const entryRelative=path.posix.join(relative.replaceAll(path.sep,"/"),entry.name);if(entry.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${entryRelative}`);if(entry.isDirectory())files.push(...await collectAuthoritativeFiles(root,entryRelative));else if(entry.isFile())files.push(entryRelative);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${entryRelative}`)}return files}async function buildManifest(pmRoot){const files=await collectAuthoritativeFiles(pmRoot),hash=crypto.createHash("sha256"),contents=[];let bytes=0;for(const file of files){const content=await readFile(path.join(pmRoot,file));contents.push(content),bytes+=content.byteLength,hash.update(file),hash.update("\0"),hash.update(String(content.byteLength)),hash.update("\0"),hash.update(content)}const fingerprint=hash.digest("hex");return{manifest:{schema:SNAPSHOT_SCHEMA,fingerprint,files,bytes},contents}}function lineCount(content){return content===void 0||content.byteLength===0?0:content.toString("utf8").split(`
3
- `).filter(line=>line.trim().length>0).length}async function snapshotContents(root,files){const contents=new Map;for(let offset=0;offset<files.length;offset+=32){const batch=files.slice(offset,offset+32),entries=await Promise.all(batch.map(async file=>[file,await readFile(path.join(root,file))]));for(const[file,content]of entries)contents.set(file,content)}return contents}function validateSnapshotTarget(target){if(!SNAPSHOT_TARGET_PATTERN.test(target))throw new PmCliError("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",EXIT_CODE.USAGE,{code:"invalid_workspace_snapshot_target",required:"Provide a non-empty lowercase snapshot name or 64-character hexadecimal fingerprint.",why:"Snapshot targets are used as portable reference filenames and content identities.",examples:["pm workspace snapshot list --json","pm workspace snapshot inspect baseline --json"],nextSteps:["List available snapshots, then retry with a returned name or fingerprint."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function withSnapshotFilesystemGuard(operation,run){return withHostEnvironmentBoundary(`workspace_snapshot_${operation}`,run,{codes:{capacity:SNAPSHOT_HOST_FAULT_CODES.capacity.code,permission:SNAPSHOT_HOST_FAULT_CODES.permission.code,resource:SNAPSHOT_HOST_FAULT_CODES.resource.code},why:"Snapshot create and restore copy authoritative tracker state before activation, so the stage needs capacity and write access up front.",nextSteps:["Reclaim rebuildable tracker cache space with pm gc, then retry."],suggestedRetry:"pm gc --json"})}function snapshotStore(pmRoot){return path.join(pmRoot,SNAPSHOT_RUNTIME_PATH)}function workspaceSnapshotNotFound(target){return new PmCliError(`Unknown workspace snapshot: ${target}`,EXIT_CODE.NOT_FOUND,{code:"workspace_snapshot_not_found",required:"Use a snapshot name or fingerprint returned by snapshot list.",why:"The requested reference or immutable snapshot object does not exist.",examples:["pm workspace snapshot list --json"],nextSteps:["List available snapshots and retry with an exact target."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function readSnapshotJson(file,target){try{return JSON.parse(await readFile(file,"utf8"))}catch(error){throw isFileMissingError(error)?workspaceSnapshotNotFound(target):error}}async function removeSnapshotEntry(entry,target,recursive){try{await rm(entry,{recursive})}catch(error){throw isFileMissingError(error)?workspaceSnapshotNotFound(target):error}}async function publishWorkspaceSnapshotObject(temporaryRoot,objectRoot,operations=DEFAULT_ATOMIC_OPERATIONS){try{return await operations.renameEntry(temporaryRoot,objectRoot),!1}catch(error){if(!(error instanceof Error&&"code"in error&&(error.code==="EEXIST"||error.code==="ENOTEMPTY")))throw error;return await operations.removeEntry(temporaryRoot),!0}}async function swapWorkspaceSnapshotRootWithActivation(staging,pmRoot,backup,operations,afterActivation){await operations.renameEntry(pmRoot,backup);try{await operations.renameEntry(staging,pmRoot),await afterActivation?.()}catch(error){throw await operations.renameEntry(backup,pmRoot),await operations.removeEntry(staging),error}await operations.removeEntry(backup)}async function swapWorkspaceSnapshotRoot(staging,pmRoot,backup,operations=DEFAULT_ATOMIC_OPERATIONS){await swapWorkspaceSnapshotRootWithActivation(staging,pmRoot,backup,operations)}async function resolveSnapshotFingerprint(pmRoot,target){return validateSnapshotTarget(target),/^[a-f0-9]{64}$/.test(target)?target:(await readSnapshotJson(path.join(snapshotStore(pmRoot),"refs",`${target}.json`),target)).fingerprint}async function createWorkspaceSnapshot(pmRoot,options={}){if(options.name!==void 0&&(validateSnapshotTarget(options.name),/^[a-f0-9]{64}$/.test(options.name)))throw new PmCliError("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",EXIT_CODE.USAGE,{code:"workspace_snapshot_name_reserved_fingerprint",required:"Choose a human-readable reference name that cannot be mistaken for a content fingerprint.",why:"Exact 64-character hexadecimal values address immutable objects.",examples:["pm workspace snapshot create baseline --json"],nextSteps:["Retry with a shorter descriptive snapshot name."]});const{manifest,contents}=await buildManifest(pmRoot),store=snapshotStore(pmRoot),objectRoot=path.join(store,"objects",manifest.fingerprint);let deduplicated=!1;try{deduplicated=(await lstat(objectRoot)).isDirectory()}catch(error){if(!(error instanceof Error&&"code"in error&&isFileMissingError(error)))throw error}if(!deduplicated){const temporaryRoot=path.join(store,"objects",`.create-${process.pid}-${crypto.randomUUID()}`);await withSnapshotFilesystemGuard("create_object",async()=>{await mkdir(path.join(temporaryRoot,"files"),{recursive:!0});for(const[index,file]of manifest.files.entries()){const target=path.join(temporaryRoot,"files",file);await mkdir(path.dirname(target),{recursive:!0}),await writeFile(target,contents[index])}await writeFile(path.join(temporaryRoot,"manifest.json"),`${JSON.stringify(manifest,null,2)}
4
- `,"utf8"),await mkdir(path.dirname(objectRoot),{recursive:!0})}),deduplicated=await publishWorkspaceSnapshotObject(temporaryRoot,objectRoot)}if(options.name!==void 0){const reference={name:options.name,fingerprint:manifest.fingerprint},refsRoot=path.join(store,"refs");await mkdir(refsRoot,{recursive:!0});const temporaryRef=path.join(refsRoot,`.ref-${process.pid}-${crypto.randomUUID()}`);await writeFile(temporaryRef,`${JSON.stringify(reference,null,2)}
5
- `,"utf8"),await rename(temporaryRef,path.join(refsRoot,`${options.name}.json`))}return{manifest,...options.name===void 0?{}:{name:options.name},deduplicated}}async function inspectWorkspaceSnapshot(pmRoot,target){const fingerprint=await resolveSnapshotFingerprint(pmRoot,target),manifest=await readSnapshotJson(path.join(snapshotStore(pmRoot),"objects",fingerprint,"manifest.json"),target);if(manifest.schema!==SNAPSHOT_SCHEMA||manifest.fingerprint!==fingerprint)throw new PmCliError(`Snapshot manifest identity mismatch: ${target}`,EXIT_CODE.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return manifest}async function listWorkspaceSnapshots(pmRoot){const store=snapshotStore(pmRoot),objectNames=await readdir(path.join(store,"objects")).catch(error=>{if(error instanceof Error&&"code"in error&&isFileMissingError(error))return[];throw error}),referenceNames=await readdir(path.join(store,"refs")).catch(error=>{if(error instanceof Error&&"code"in error&&isFileMissingError(error))return[];throw error});return{objects:await Promise.all(objectNames.filter(name=>/^[a-f0-9]{64}$/.test(name)).sort().map(name=>inspectWorkspaceSnapshot(pmRoot,name))),references:await Promise.all(referenceNames.filter(name=>name.endsWith(".json")).sort().map(async name=>JSON.parse(await readFile(path.join(store,"refs",name),"utf8"))))}}async function planWorkspaceSnapshotRestore(pmRoot,target){const targetManifest=await inspectWorkspaceSnapshot(pmRoot,target),{manifest:currentManifest,contents:currentContentList}=await buildManifest(pmRoot),currentContents=new Map(currentManifest.files.map((file,index)=>[file,currentContentList[index]])),targetContents=await snapshotContents(path.join(snapshotStore(pmRoot),"objects",targetManifest.fingerprint,"files"),targetManifest.files),currentFiles=new Set(currentManifest.files),targetFiles=new Set(targetManifest.files),changedFiles=new Set([...currentFiles,...targetFiles]);for(const file of changedFiles){const currentContent=currentContents.get(file),targetContent=targetContents.get(file);currentContent!==void 0&&targetContent!==void 0&&currentContent.equals(targetContent)&&changedFiles.delete(file)}const affectedHistoryStreams=currentManifest.files.filter(file=>file.startsWith("history/")&&file.endsWith(".jsonl")).map(file=>{const currentEntries=lineCount(currentContents.get(file)),targetEntries=lineCount(targetContents.get(file));return{path:file,current_entries:currentEntries,target_entries:targetEntries,removed_entries:Math.max(0,currentEntries-targetEntries)}}).filter(entry=>entry.removed_entries>0).sort((left,right)=>left.path.localeCompare(right.path));return{target_fingerprint:targetManifest.fingerprint,current_fingerprint:currentManifest.fingerprint,changed_file_count:changedFiles.size,removed_file_count:[...currentFiles].filter(file=>!targetFiles.has(file)).length,added_file_count:[...targetFiles].filter(file=>!currentFiles.has(file)).length,removed_item_count:[...currentFiles].filter(file=>file.endsWith(".toon")&&!targetFiles.has(file)).length,affected_history_stream_count:affectedHistoryStreams.length,removed_history_entry_count:affectedHistoryStreams.reduce((total,entry)=>total+entry.removed_entries,0),affected_history_streams:affectedHistoryStreams,changes_authoritative_state:currentManifest.fingerprint!==targetManifest.fingerprint}}async function restoreWorkspaceSnapshotWithRecovery(pmRoot,target,options={}){if(options.force!==!0)throw new PmCliError("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",EXIT_CODE.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${target} --dry-run --json`,`pm workspace snapshot restore ${target} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${target} --dry-run --json`}});const author=options.author?.trim()||"pm-sdk",lockTtlSeconds=options.lockTtlSeconds??60,lockWaitMs=options.lockWaitMs??5e3,workspaceLease=await acquireLockLease(pmRoot,WORKSPACE_WRITER_LOCK_ID,lockTtlSeconds,author,!1,!1,lockWaitMs),releaseWorkspaceLock=workspaceLease.release,heartbeat=new WorkspaceLockHeartbeat(getLockPath(pmRoot,WORKSPACE_WRITER_LOCK_ID),author,lockTtlSeconds);heartbeat.start(),await heartbeat.refreshNow();let staging,swapStarted=!1,heartbeatStopped=!1;try{const plan=await planWorkspaceSnapshotRestore(pmRoot,target),manifest=await inspectWorkspaceSnapshot(pmRoot,target),recovery=await createWorkspaceSnapshot(pmRoot),fingerprint=manifest.fingerprint,store=snapshotStore(pmRoot),source=path.join(store,"objects",fingerprint,"files"),parent=path.dirname(pmRoot),base=path.basename(pmRoot);staging=path.join(parent,`.${base}.restore-${crypto.randomUUID()}`);const backup=path.join(parent,`.${base}.backup-${crypto.randomUUID()}`);await withSnapshotFilesystemGuard("restore_stage",async()=>{await mkdir(staging,{recursive:!0}),await cp(source,staging,{recursive:!0,force:!1}),await mkdir(path.join(staging,"runtime"),{recursive:!0}),await cp(store,path.join(staging,SNAPSHOT_RUNTIME_PATH),{recursive:!0,force:!1})});const audit=await appendWorkspaceAuditEvent({pmRoot:staging,op:"workspace_snapshot_restore",author,message:options.message??`Restore workspace snapshot ${fingerprint}; recovery snapshot ${recovery.manifest.fingerprint}`,context:{target_fingerprint:fingerprint,pre_restore_fingerprint:recovery.manifest.fingerprint,changed_file_count:plan.changed_file_count,removed_file_count:plan.removed_file_count,removed_item_count:plan.removed_item_count,affected_history_stream_count:plan.affected_history_stream_count,removed_history_entry_count:plan.removed_history_entry_count},lockTtlSeconds,lockWaitMs}),auditHistoryPath=path.relative(staging,audit.historyPath).replaceAll("\\","/");await heartbeat.stop(),heartbeatStopped=!0;const stagedWorkspaceLock=getLockPath(staging,WORKSPACE_WRITER_LOCK_ID),stagedRoot=staging;return await workspaceLease.fence(async()=>{await mkdir(path.dirname(stagedWorkspaceLock),{recursive:!0}),await writeFile(stagedWorkspaceLock,await readFile(getLockPath(pmRoot,WORKSPACE_WRITER_LOCK_ID)),{flag:"wx"}),swapStarted=!0,await swapWorkspaceSnapshotRootWithActivation(stagedRoot,pmRoot,backup,DEFAULT_ATOMIC_OPERATIONS,async()=>{heartbeat.start(),heartbeatStopped=!1,await heartbeat.refreshNow()})}),await heartbeat.stop(),heartbeatStopped=!0,{manifest,plan,recovery_fingerprint:recovery.manifest.fingerprint,audit_history_path:auditHistoryPath,audit_operation:"workspace_snapshot_restore"}}catch(error){throw staging!==void 0&&!swapStarted&&await Promise.allSettled([rm(staging,{recursive:!0,force:!0})]),error}finally{try{heartbeatStopped||await heartbeat.stop()}catch{}finally{await releaseWorkspaceLock()}}}async function restoreWorkspaceSnapshot(pmRoot,target){return(await restoreWorkspaceSnapshotWithRecovery(pmRoot,target,{force:!0,message:"Restore requested through the compatibility SDK signature"})).manifest}async function deleteWorkspaceSnapshot(pmRoot,target){validateSnapshotTarget(target);const store=snapshotStore(pmRoot);if(!/^[a-f0-9]{64}$/.test(target))return await removeSnapshotEntry(path.join(store,"refs",`${target}.json`),target,!1),{deleted:"reference",target};const{references}=await listWorkspaceSnapshots(pmRoot);if(references.some(reference=>reference.fingerprint===target))throw new Error(`Snapshot object ${target} is still referenced`);return await removeSnapshotEntry(path.join(store,"objects",target),target,!0),{deleted:"object",target}}export{SNAPSHOT_SCHEMA,WORKSPACE_SNAPSHOT_ACTIONS,_testOnlyWorkspaceSnapshot,createWorkspaceSnapshot,deleteWorkspaceSnapshot,inspectWorkspaceSnapshot,listWorkspaceSnapshots,planWorkspaceSnapshotRestore,publishWorkspaceSnapshotObject,restoreWorkspaceSnapshot,restoreWorkspaceSnapshotWithRecovery,swapWorkspaceSnapshotRoot};
1
+ import k from"node:crypto";import{cp as F,lstat as te,mkdir as d,readFile as y,readdir as x,rename as I,rm as W,writeFile as v}from"node:fs/promises";import a from"node:path";import{isFileMissingError as g,writeFileAtomic as re}from"../core/fs/fs-utils.js";import{appendWorkspaceAuditEvent as se}from"../core/history/workspace-history.js";import{acquireLockLease as ne,waitForStaleCleanupGate as ae}from"../core/lock/lock.js";import{getLockPath as O}from"../core/store/paths.js";import{EXIT_CODE as S}from"../core/shared/constants.js";import{PmCliError as j}from"../core/shared/errors.js";import{withHostEnvironmentBoundary as oe}from"./environment/host-environment-errors.js";const H="https://schema.unbrained.dev/pm/workspace-snapshot/v1",xe=["create","list","inspect","restore","delete"],D=a.join("runtime","workspace-snapshots"),ie=new Set(["checkpoints","locks","runtime","search","transactions"]),ce=/^[a-z0-9][a-z0-9._-]*$/,_="sdk-workspace-transaction",T={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},$={renameEntry:I,removeEntry:async t=>{await W(t,{recursive:!0,force:!0})}};class R{lockPath;owner;intervalMs;timer;refresh;failure;constructor(e,r,s){this.lockPath=e,this.owner=r,this.intervalMs=Math.max(10,Math.floor(s*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(e=>{this.failure=e}).finally(()=>{this.refresh=void 0}))}async renew(){const e=await ae(this.lockPath,_);if(e===null)throw new Error("Workspace writer lock cleanup gate stayed held");try{const r=JSON.parse(await y(this.lockPath,"utf8"));if(typeof r!="object"||r===null||Array.isArray(r))throw new Error("Workspace writer lock has invalid structure");const s=r;if(s.id!==_||s.owner!==this.owner||s.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await re(this.lockPath,`${JSON.stringify({...s,created_at:new Date().toISOString()},null,2)}
2
+ `)}finally{await e()}}}const We={WorkspaceLockHeartbeat:R,withSnapshotFilesystemGuard:N};async function q(t,e=""){const r=await x(a.join(t,e),{withFileTypes:!0}),s=[];for(const n of r.sort((c,h)=>c.name.localeCompare(h.name))){if(e.length===0&&ie.has(n.name))continue;const c=a.posix.join(e.replaceAll(a.sep,"/"),n.name);if(n.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${c}`);if(n.isDirectory())s.push(...await q(t,c));else if(n.isFile())s.push(c);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${c}`)}return s}async function G(t){const e=await q(t),r=k.createHash("sha256"),s=[];let n=0;for(const h of e){const i=await y(a.join(t,h));s.push(i),n+=i.byteLength,r.update(h),r.update("\0"),r.update(String(i.byteLength)),r.update("\0"),r.update(i)}const c=r.digest("hex");return{manifest:{schema:H,fingerprint:c,files:e,bytes:n},contents:s}}function J(t){return t===void 0||t.byteLength===0?0:t.toString("utf8").split(`
3
+ `).filter(e=>e.trim().length>0).length}async function he(t,e){const r=new Map;for(let s=0;s<e.length;s+=32){const n=e.slice(s,s+32),c=await Promise.all(n.map(async h=>[h,await y(a.join(t,h))]));for(const[h,i]of c)r.set(h,i)}return r}function A(t){if(!ce.test(t))throw new j("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",S.USAGE,{code:"invalid_workspace_snapshot_target",required:"Provide a non-empty lowercase snapshot name or 64-character hexadecimal fingerprint.",why:"Snapshot targets are used as portable reference filenames and content identities.",examples:["pm workspace snapshot list --json","pm workspace snapshot inspect baseline --json"],nextSteps:["List available snapshots, then retry with a returned name or fingerprint."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function N(t,e){return oe(`workspace_snapshot_${t}`,e,{codes:{capacity:T.capacity.code,permission:T.permission.code,resource:T.resource.code},why:"Snapshot create and restore copy authoritative tracker state before activation, so the stage needs capacity and write access up front.",nextSteps:["Reclaim rebuildable tracker cache space with pm gc, then retry."],suggestedRetry:"pm gc --json"})}function m(t){return a.join(t,D)}function K(t){return new j(`Unknown workspace snapshot: ${t}`,S.NOT_FOUND,{code:"workspace_snapshot_not_found",required:"Use a snapshot name or fingerprint returned by snapshot list.",why:"The requested reference or immutable snapshot object does not exist.",examples:["pm workspace snapshot list --json"],nextSteps:["List available snapshots and retry with an exact target."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function z(t,e){try{return JSON.parse(await y(t,"utf8"))}catch(r){throw g(r)?K(e):r}}async function X(t,e,r){try{await W(t,{recursive:r})}catch(s){throw g(s)?K(e):s}}async function pe(t,e,r=$){try{return await r.renameEntry(t,e),!1}catch(s){if(!(s instanceof Error&&"code"in s&&(s.code==="EEXIST"||s.code==="ENOTEMPTY")))throw s;return await r.removeEntry(t),!0}}async function B(t,e,r,s,n){await s.renameEntry(e,r);try{await s.renameEntry(t,e),await n?.()}catch(c){throw await s.renameEntry(r,e),await s.removeEntry(t),c}await s.removeEntry(r)}async function Oe(t,e,r,s=$){await B(t,e,r,s)}async function fe(t,e){return A(e),/^[a-f0-9]{64}$/.test(e)?e:(await z(a.join(m(t),"refs",`${e}.json`),e)).fingerprint}async function le(t,e={}){if(e.name!==void 0&&(A(e.name),/^[a-f0-9]{64}$/.test(e.name)))throw new j("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",S.USAGE,{code:"workspace_snapshot_name_reserved_fingerprint",required:"Choose a human-readable reference name that cannot be mistaken for a content fingerprint.",why:"Exact 64-character hexadecimal values address immutable objects.",examples:["pm workspace snapshot create baseline --json"],nextSteps:["Retry with a shorter descriptive snapshot name."]});const{manifest:r,contents:s}=await G(t),n=m(t),c=a.join(n,"objects",r.fingerprint);let h=!1;try{h=(await te(c)).isDirectory()}catch(i){if(!(i instanceof Error&&"code"in i&&g(i)))throw i}if(!h){const i=a.join(n,"objects",`.create-${process.pid}-${k.randomUUID()}`);await N("create_object",async()=>{await d(a.join(i,"files"),{recursive:!0});for(const[l,p]of r.files.entries()){const u=a.join(i,"files",p);await d(a.dirname(u),{recursive:!0}),await v(u,s[l])}await v(a.join(i,"manifest.json"),`${JSON.stringify(r,null,2)}
4
+ `,"utf8"),await d(a.dirname(c),{recursive:!0})}),h=await pe(i,c)}if(e.name!==void 0){const i={name:e.name,fingerprint:r.fingerprint},l=a.join(n,"refs");await d(l,{recursive:!0});const p=a.join(l,`.ref-${process.pid}-${k.randomUUID()}`);await v(p,`${JSON.stringify(i,null,2)}
5
+ `,"utf8"),await I(p,a.join(l,`${e.name}.json`))}return{manifest:r,...e.name===void 0?{}:{name:e.name},deduplicated:h}}async function P(t,e){const r=await fe(t,e),s=await z(a.join(m(t),"objects",r,"manifest.json"),e);if(s.schema!==H||s.fingerprint!==r)throw new j(`Snapshot manifest identity mismatch: ${e}`,S.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return s}async function ue(t){const e=m(t),r=await x(a.join(e,"objects")).catch(n=>{if(n instanceof Error&&"code"in n&&g(n))return[];throw n}),s=await x(a.join(e,"refs")).catch(n=>{if(n instanceof Error&&"code"in n&&g(n))return[];throw n});return{objects:await Promise.all(r.filter(n=>/^[a-f0-9]{64}$/.test(n)).sort().map(n=>P(t,n))),references:await Promise.all(s.filter(n=>n.endsWith(".json")).sort().map(async n=>JSON.parse(await y(a.join(e,"refs",n),"utf8"))))}}async function we(t,e){const r=await P(t,e),{manifest:s,contents:n}=await G(t),c=new Map(s.files.map((o,f)=>[o,n[f]])),h=await he(a.join(m(t),"objects",r.fingerprint,"files"),r.files),i=new Set(s.files),l=new Set(r.files),p=new Set([...i,...l]);for(const o of p){const f=c.get(o),w=h.get(o);f!==void 0&&w!==void 0&&f.equals(w)&&p.delete(o)}const u=s.files.filter(o=>o.startsWith("history/")&&o.endsWith(".jsonl")).map(o=>{const f=J(c.get(o)),w=J(h.get(o));return{path:o,current_entries:f,target_entries:w,removed_entries:Math.max(0,f-w)}}).filter(o=>o.removed_entries>0).sort((o,f)=>o.path.localeCompare(f.path));return{target_fingerprint:r.fingerprint,current_fingerprint:s.fingerprint,changed_file_count:p.size,removed_file_count:[...i].filter(o=>!l.has(o)).length,added_file_count:[...l].filter(o=>!i.has(o)).length,removed_item_count:[...i].filter(o=>o.endsWith(".toon")&&!l.has(o)).length,affected_history_stream_count:u.length,removed_history_entry_count:u.reduce((o,f)=>o+f.removed_entries,0),affected_history_streams:u,changes_authoritative_state:s.fingerprint!==r.fingerprint}}async function de(t,e,r={}){if(r.force!==!0)throw new j("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",S.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${e} --dry-run --json`,`pm workspace snapshot restore ${e} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${e} --dry-run --json`}});const s=r.author?.trim()||"pm-sdk",n=r.lockTtlSeconds??60,c=r.lockWaitMs??5e3,h=await ne(t,_,n,s,!1,!1,c),i=h.release,l=new R(O(t,_),s,n);l.start(),await l.refreshNow();let p,u=!1,o=!1;try{const f=await we(t,e),w=await P(t,e),b=await le(t),E=w.fingerprint,C=m(t),Y=a.join(C,"objects",E,"files"),L=a.dirname(t),M=a.basename(t);p=a.join(L,`.${M}.restore-${k.randomUUID()}`);const Q=a.join(L,`.${M}.backup-${k.randomUUID()}`);await N("restore_stage",async()=>{await d(p,{recursive:!0}),await F(Y,p,{recursive:!0,force:!1}),await d(a.join(p,"runtime"),{recursive:!0}),await F(C,a.join(p,D),{recursive:!0,force:!1})});const V=await se({pmRoot:p,op:"workspace_snapshot_restore",author:s,message:r.message??`Restore workspace snapshot ${E}; recovery snapshot ${b.manifest.fingerprint}`,context:{target_fingerprint:E,pre_restore_fingerprint:b.manifest.fingerprint,changed_file_count:f.changed_file_count,removed_file_count:f.removed_file_count,removed_item_count:f.removed_item_count,affected_history_stream_count:f.affected_history_stream_count,removed_history_entry_count:f.removed_history_entry_count},lockTtlSeconds:n,lockWaitMs:c}),Z=a.relative(p,V.historyPath).replaceAll("\\","/");await l.stop(),o=!0;const U=O(p,_),ee=p;return await h.fence(async()=>{await d(a.dirname(U),{recursive:!0}),await v(U,await y(O(t,_)),{flag:"wx"}),u=!0,await B(ee,t,Q,$,async()=>{l.start(),o=!1,await l.refreshNow()})}),await l.stop(),o=!0,{manifest:w,plan:f,recovery_fingerprint:b.manifest.fingerprint,audit_history_path:Z,audit_operation:"workspace_snapshot_restore"}}catch(f){throw p!==void 0&&!u&&await Promise.allSettled([W(p,{recursive:!0,force:!0})]),f}finally{try{o||await l.stop()}catch{}finally{await i()}}}async function Te(t,e){return(await de(t,e,{force:!0,message:"Restore requested through the compatibility SDK signature"})).manifest}async function $e(t,e){A(e);const r=m(t);if(!/^[a-f0-9]{64}$/.test(e))return await X(a.join(r,"refs",`${e}.json`),e,!1),{deleted:"reference",target:e};const{references:s}=await ue(t);if(s.some(n=>n.fingerprint===e))throw new Error(`Snapshot object ${e} is still referenced`);return await X(a.join(r,"objects",e),e,!0),{deleted:"object",target:e}}export{H as SNAPSHOT_SCHEMA,xe as WORKSPACE_SNAPSHOT_ACTIONS,We as _testOnlyWorkspaceSnapshot,le as createWorkspaceSnapshot,$e as deleteWorkspaceSnapshot,P as inspectWorkspaceSnapshot,ue as listWorkspaceSnapshots,we as planWorkspaceSnapshotRestore,pe as publishWorkspaceSnapshotObject,Te as restoreWorkspaceSnapshot,de as restoreWorkspaceSnapshotWithRecovery,Oe as swapWorkspaceSnapshotRoot};
6
6
  //# sourceMappingURL=workspace-snapshot.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]="ff5e2370-3b70-5f71-9492-72906f642c85")}catch{}})();import{isFileMissingError}from"../core/fs/fs-utils.js";import fs from"node:fs/promises";import path from"node:path";const MILLISECONDS_PER_DAY=1440*60*1e3,TERMINAL_JOURNAL_STATUSES=new Set(["committed","compensated"]);function readJournalStatusAndTimestamp(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return{status:null,updatedAt:null}}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return{status:null,updatedAt:null};const record=parsed;return{status:record.abandonment!==void 0?"abandoned":typeof record.status=="string"?record.status:null,updatedAt:typeof record.updatedAt=="string"?record.updatedAt:null}}function classifyWorkspaceTransactionJournal(file,status,updatedAt,nowMs,retentionMs){const updatedAtMs=updatedAt===null?Number.NaN:Date.parse(updatedAt);if(status===null||!Number.isFinite(updatedAtMs))return{entry:{file,status,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};const ageMs=nowMs-updatedAtMs;return TERMINAL_JOURNAL_STATUSES.has(status)?ageMs>retentionMs?{entry:{file,status,age_seconds:Math.floor(ageMs/1e3),stale:!0},remove:!0}:{entry:{file,status,age_seconds:Math.floor(ageMs/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file,status,age_seconds:Math.floor(ageMs/1e3),stale:!1,reason:"active"},remove:!1}}async function processWorkspaceTransactionJournal(absolutePath,relativePath,fileName,options){const warnings=options.hooks?.onRead?await options.hooks.onRead(absolutePath):[],journal=readJournalStatusAndTimestamp(await fs.readFile(absolutePath,"utf8")),decision=classifyWorkspaceTransactionJournal(relativePath,journal.status,journal.updatedAt,options.nowMs,options.retentionMs);return decision.entry.reason==="unparseable"&&warnings.push(`transaction_journal_unparseable:${fileName}`),decision.remove&&!options.dryRun&&(await fs.rm(absolutePath,{force:!0}),options.hooks?.onWrite&&warnings.push(...await options.hooks.onWrite(absolutePath))),{decision,warnings}}async function runWorkspaceTransactionGc(pmRoot,options){const{dryRun,hooks}=options,nowMs=options.now??Date.now(),retentionMs=Math.max(0,options.retentionDays)*MILLISECONDS_PER_DAY,journalsDir=path.join(pmRoot,"transactions","sdk"),result={scanned:0,removed:[],retained:[],warnings:[],entries:[]};let files;try{files=(await fs.readdir(journalsDir)).filter(file=>file.endsWith(".json")).sort((left,right)=>left.localeCompare(right))}catch(error){if(isFileMissingError(error))return result;throw error}for(const file of files){const absPath=path.join(journalsDir,file),relPath=`transactions/sdk/${file}`,fileResult=await processWorkspaceTransactionJournal(absPath,relPath,file,{dryRun,hooks,nowMs,retentionMs});result.warnings.push(...fileResult.warnings),result.scanned+=1;const{decision}=fileResult;if(!decision.remove){result.retained.push(relPath),result.entries.push(decision.entry);continue}result.removed.push(relPath),result.entries.push(decision.entry)}return result}export{runWorkspaceTransactionGc};
1
+ import{isFileMissingError as y}from"../core/fs/fs-utils.js";import f from"node:fs/promises";import h from"node:path";const w=1440*60*1e3,A=new Set(["committed","compensated"]);function M(n){let e;try{e=JSON.parse(n)}catch{return{status:null,updatedAt:null}}if(typeof e!="object"||e===null||Array.isArray(e))return{status:null,updatedAt:null};const r=e;return{status:r.abandonment!==void 0?"abandoned":typeof r.status=="string"?r.status:null,updatedAt:typeof r.updatedAt=="string"?r.updatedAt:null}}function g(n,e,r,t,i){const u=r===null?Number.NaN:Date.parse(r);if(e===null||!Number.isFinite(u))return{entry:{file:n,status:e,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};const s=t-u;return A.has(e)?s>i?{entry:{file:n,status:e,age_seconds:Math.floor(s/1e3),stale:!0},remove:!0}:{entry:{file:n,status:e,age_seconds:Math.floor(s/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:n,status:e,age_seconds:Math.floor(s/1e3),stale:!1,reason:"active"},remove:!1}}async function k(n,e,r,t){const i=t.hooks?.onRead?await t.hooks.onRead(n):[],u=M(await f.readFile(n,"utf8")),s=g(e,u.status,u.updatedAt,t.nowMs,t.retentionMs);return s.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${r}`),s.remove&&!t.dryRun&&(await f.rm(n,{force:!0}),t.hooks?.onWrite&&i.push(...await t.hooks.onWrite(n))),{decision:s,warnings:i}}async function R(n,e){const{dryRun:r,hooks:t}=e,i=e.now??Date.now(),u=Math.max(0,e.retentionDays)*w,s=h.join(n,"transactions","sdk"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]};let p;try{p=(await f.readdir(s)).filter(a=>a.endsWith(".json")).sort((a,c)=>a.localeCompare(c))}catch(a){if(y(a))return o;throw a}for(const a of p){const c=h.join(s,a),l=`transactions/sdk/${a}`,m=await k(c,l,a,{dryRun:r,hooks:t,nowMs:i,retentionMs:u});o.warnings.push(...m.warnings),o.scanned+=1;const{decision:d}=m;if(!d.remove){o.retained.push(l),o.entries.push(d.entry);continue}o.removed.push(l),o.entries.push(d.entry)}return o}export{R as runWorkspaceTransactionGc};
2
2
  //# sourceMappingURL=workspace-transaction-gc.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]="f100554a-d0e9-54c1-9dca-7ea5b79b0dc2")}catch{}})();import{mkdir,readFile}from"node:fs/promises";import path from"node:path";import{createHash}from"node:crypto";import{appendWorkspaceAuditEvent,getWorkspaceHistoryPath,WORKSPACE_HISTORY_ID}from"../core/history/workspace-history.js";import{readHistoryEntries}from"./history-read.js";import{acquireLock}from"../core/lock/lock.js";import{isFileMissingError,writeFileAtomic}from"../core/fs/fs-utils.js";import{nowIso}from"../core/shared/time.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{runAsCoordinatorCompensation}from"../core/store/transaction-coordinator-scope.js";class WorkspaceTransactionInterruptedError extends Error{constructor(message="Workspace transaction interrupted"){super(message),this.name="WorkspaceTransactionInterruptedError"}}const WORKSPACE_TRANSACTION_LOCK_ID="sdk-workspace-transaction",TRANSACTION_ID_PATTERN=/^[a-zA-Z0-9._-]+$/,DEFAULT_LOCK_TTL_SECONDS=30,DEFAULT_LOCK_WAIT_MS=3e3;function requiredIdentifier(value,label){if(typeof value!="string")throw new TypeError(`${label} must be a string`);const normalized=value.trim();if(!normalized||!TRANSACTION_ID_PATTERN.test(normalized))throw new TypeError(`${label} must match [a-zA-Z0-9._-]+`);return normalized}function requiredText(value,label){if(typeof value!="string")throw new TypeError(`${label} must be a string`);const normalized=value.trim();if(!normalized)throw new TypeError(`${label} must be non-empty`);return normalized}function validateWorkspaceTransactionIdentity(options){return{pmRoot:requiredText(options.pmRoot,"Transaction pmRoot"),transactionId:requiredIdentifier(options.transactionId,"Transaction id"),author:requiredText(options.author,"Transaction author")}}function positiveInteger(value,fallback,label){const resolved=value??fallback;if(!Number.isInteger(resolved)||resolved<=0)throw new TypeError(`${label} must be a positive integer`);return resolved}function journalPath(pmRoot,transactionId){return path.join(pmRoot,"transactions","sdk",`${transactionId}.json`)}async function writeJournal(pmRoot,journal){journal.updatedAt=nowIso();const target=journalPath(pmRoot,journal.transactionId);await mkdir(path.dirname(target),{recursive:!0}),await writeFileAtomic(target,`${JSON.stringify(journal,null,2)}
2
- `)}function hasValidJournalMetadata(journal){return Number.isInteger(journal.attempt)&&typeof journal.author=="string"&&typeof journal.createdAt=="string"&&typeof journal.updatedAt=="string"&&hasValidAbandonment(journal)}function hasValidAbandonment(journal){const retirement=journal.abandonment;return retirement===void 0?journal.schemaVersion===1&&journal.status!=="abandoned":journal.schemaVersion!==2||retirement===null||typeof retirement!="object"||journal.status==="committed"?!1:typeof retirement.reason=="string"&&retirement.reason.trim().length>0&&typeof retirement.author=="string"&&retirement.author.trim().length>0&&(retirement.supersededBy===void 0||typeof retirement.supersededBy=="string"&&TRANSACTION_ID_PATTERN.test(retirement.supersededBy)&&retirement.supersededBy!==journal.transactionId)}function createResultMap(source){return Object.assign(Object.create(null),source)}function cloneJournalValue(value,label){try{const serialized=JSON.stringify(value,(_key,nestedValue)=>{if(typeof nestedValue=="number"&&!Number.isFinite(nestedValue))throw new TypeError(`${label} contains a non-finite number`);if(nestedValue===void 0||typeof nestedValue=="function"||typeof nestedValue=="symbol")throw new TypeError(`${label} contains a non-JSON value`);return nestedValue});return JSON.parse(serialized)}catch(error){throw new TypeError(`${label} must be JSON serializable`,{cause:error})}}function cloneOptionalJournalValue(value,label){return value===void 0?void 0:cloneJournalValue(value,label)}function setJournalEntry(target,stepId,value,label){const cloned=cloneOptionalJournalValue(value,label);cloned===void 0?delete target[stepId]:target[stepId]=cloned}function isJournalMap(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function hasUniqueKnownStepIds(value,stepIds){return Array.isArray(value)&&new Set(value).size===value.length&&value.every(stepId=>typeof stepId=="string"&&stepIds.includes(stepId))}function hasValidJournalLifecycle(journal,stepIds){if(!hasUniqueKnownStepIds(journal.startedStepIds,stepIds)||!hasUniqueKnownStepIds(journal.completedStepIds,stepIds)||!isJournalMap(journal.results)||!isJournalMap(journal.compensationData))return!1;const startedStepIds=journal.startedStepIds,started=new Set(startedStepIds),completedStepIds=journal.completedStepIds,completed=new Set(completedStepIds);return Object.keys(journal.compensationData).some(stepId=>!started.has(stepId))||Object.keys(journal.results).some(stepId=>!completed.has(stepId))?!1:journal.status==="committed"?stepIds.every(stepId=>completed.has(stepId)):!["compensated","abandoned"].includes(journal.status??"")||completed.size===0&&started.size===0}function invalidJournal(transactionId,detail){return new PmCliError(`Workspace transaction ${transactionId} journal is invalid (${detail})`,EXIT_CODE.CONFLICT,{code:"transaction_journal_invalid",required:"A valid durable journal is required before transaction recovery can continue.",why:"Corrupt journal data cannot establish which steps applied or still require compensation.",nextSteps:["Preserve the journal and inspect its integrity or restore a verified backup before retrying.","Do not switch to a new transaction id to bypass an unreadable journal; previously applied work may remain."]})}function journalPlanMismatch(transactionId){return new PmCliError(`Workspace transaction ${transactionId} journal does not match the supplied plan`,EXIT_CODE.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the original plan or safely abandon the interrupted transaction before replacing it.",why:"A journal records the plan it is resuming; applying a different plan under the same id could skip or duplicate steps.",nextSteps:["Re-run with the original document to resume or replay it.","For item batches use client.itemTransactions.status(transactionId), then client.itemTransactions.abandon(transactionId, { reason }) before committing a changed plan with a new transactionId.","Run pm ops gc --scope transactions --dry-run to inspect retention; active and explicitly abandoned journals remain protected."]})}function matchesJournalSteps(journal,recorded,requested){return requested===void 0||journal.abandonment!==void 0||journal.status==="compensated"||recorded.length===requested.length&&recorded.every((id,index)=>id===requested[index])}function parseJournal(raw,transactionId,stepIds){let parsed;try{parsed=JSON.parse(raw)}catch{throw invalidJournal(transactionId,"invalid JSON")}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw invalidJournal(transactionId,"expected an object");const journal=parsed;if(!((journal.schemaVersion===1||journal.schemaVersion===2)&&journal.transactionId===transactionId))throw invalidJournal(transactionId,"schema version or transaction id does not match the journal file");const recordedStepIds=journal.stepIds;if(!Array.isArray(recordedStepIds)||!hasUniqueKnownStepIds(recordedStepIds,recordedStepIds)||!hasValidJournalLifecycle(journal,recordedStepIds)||!hasValidJournalMetadata(journal)||typeof journal.status!="string"||!["applying","compensating","compensated","committed","abandoned"].includes(journal.status))throw invalidJournal(transactionId,"invalid lifecycle, metadata, status or step ids");if(!matchesJournalSteps(journal,recordedStepIds,stepIds))throw journalPlanMismatch(transactionId);return{...journal,results:createResultMap(journal.results),compensationData:createResultMap(journal.compensationData)}}async function prepareJournalForApply(options,transactionId,author,stepIds,existing){let journal=existing;const recovered=journal!==void 0;if(journal?.status==="compensating"&&await compensateAppliedSteps(options,journal),journal===void 0||journal.status==="compensated"){const timestamp=nowIso();journal={schemaVersion:1,transactionId,author,status:"applying",attempt:(journal?.attempt??0)+1,createdAt:journal?.createdAt??timestamp,updatedAt:timestamp,stepIds,startedStepIds:[],completedStepIds:[],results:createResultMap(),compensationData:createResultMap(),...options.recoveryData===void 0?{}:{recoveryData:cloneJournalValue(options.recoveryData,"Transaction recovery data")}},await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"prepared")}return{journal,recovered}}async function applyPreparedTransaction(options,journal,recovered){try{await discoverAppliedSteps(journal,options.steps),await writeJournal(options.pmRoot,journal);const completed=new Set(journal.completedStepIds),started=new Set(journal.startedStepIds);for(const step of options.steps){if(completed.has(step.id))continue;const inspection=await step.inspect();let result=cloneOptionalJournalValue(inspection.result,`Step ${step.id} result`);if(inspection.state!=="applied"){const compensationData=await step.prepareCompensation?.();setJournalEntry(journal.compensationData,step.id,compensationData,`Step ${step.id} compensation data`),started.add(step.id),journal.startedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>started.has(stepId)),await writeJournal(options.pmRoot,journal);const appliedResult=await step.apply();result=cloneOptionalJournalValue(appliedResult,`Step ${step.id} result`)}await emitTransition(options,journal,"step_applied",step.id),completed.add(step.id),journal.completedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>completed.has(stepId)),setJournalEntry(journal.results,step.id,result,`Step ${step.id} result`),await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"step_recorded",step.id)}return await emitTransition(options,journal,"committing"),journal.status="committed",await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"committed"),{transactionId:journal.transactionId,status:"committed",recovered,results:createResultMap(journal.results)}}catch(error){if(error instanceof WorkspaceTransactionInterruptedError||journal.status==="committed")throw error;try{await compensateAppliedSteps(options,journal)}catch(compensationError){throw new AggregateError([error,compensationError],`Workspace transaction failed and compensation failed: ${String(compensationError)}`,{cause:compensationError})}throw error}}async function loadJournal(pmRoot,transactionId,stepIds){try{return parseJournal(await readFile(journalPath(pmRoot,transactionId),"utf8"),transactionId,stepIds)}catch(error){if(error!==null&&typeof error=="object"&&"code"in error&&isFileMissingError(error))return;throw error}}async function emitTransition(options,journal,transition,stepId){await options.onTransition?.({transactionId:journal.transactionId,attempt:journal.attempt,transition,...stepId===void 0?{}:{stepId}})}async function discoverAppliedSteps(journal,steps){const completed=new Set,results=createResultMap();for(const step of steps){const inspection=await step.inspect();inspection.state==="applied"&&(completed.add(step.id),setJournalEntry(results,step.id,inspection.result,`Step ${step.id} result`))}journal.results=results,journal.completedStepIds=steps.map(step=>step.id).filter(stepId=>completed.has(stepId))}async function compensateAppliedSteps(options,journal){journal.status="compensating",await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"compensating");const completed=new Set(journal.completedStepIds),started=new Set(journal.startedStepIds);for(const step of[...options.steps].reverse()){if(!started.has(step.id)&&!completed.has(step.id))continue;let shouldCompensate;try{const state=(await step.inspect()).state;shouldCompensate=started.has(step.id)&&(state==="applied"||state==="pending"&&step.compensatePending===!0)}catch{shouldCompensate=started.has(step.id)}shouldCompensate&&(await emitTransition(options,journal,"step_compensating",step.id),await runAsCoordinatorCompensation({pmRoot:options.pmRoot,transactionId:journal.transactionId,step},()=>step.compensate(journal.compensationData[step.id]))),completed.delete(step.id),started.delete(step.id),journal.completedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>completed.has(stepId)),journal.startedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>started.has(stepId)),delete journal.results[step.id],delete journal.compensationData[step.id],await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"step_compensated",step.id)}journal.status="compensated",await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"compensated")}async function commitWorkspaceTransaction(options){const{pmRoot,transactionId,author}=validateWorkspaceTransactionIdentity(options),lockTtlSeconds=positiveInteger(options.lockTtlSeconds,DEFAULT_LOCK_TTL_SECONDS,"Transaction lock TTL"),lockWaitMs=positiveInteger(options.lockWaitMs,DEFAULT_LOCK_WAIT_MS,"Transaction lock wait"),steps=[...options.steps];if(steps.length===0)throw new TypeError("Workspace transaction requires at least one step");const stepIds=steps.map(step=>{const stepId=requiredIdentifier(step.id,"Transaction step id");if(stepId!==step.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return stepId});if(new Set(stepIds).size!==stepIds.length)throw new TypeError("Workspace transaction step ids must be unique");const stableOptions={...options,pmRoot,transactionId,author,steps,lockTtlSeconds,lockWaitMs},release=await acquireLock(pmRoot,WORKSPACE_TRANSACTION_LOCK_ID,lockTtlSeconds,author,!1,!1,lockWaitMs);try{const existing=await loadJournal(pmRoot,transactionId,stepIds);if(existing?.status==="abandoned"||existing?.abandonment!==void 0)throw retiredTransaction(existing);const recovered=existing!==void 0;if(existing?.status==="committed")return{transactionId,status:"committed",recovered:!0,results:createResultMap(existing.results)};const prepared=await prepareJournalForApply(stableOptions,transactionId,author,stepIds,existing);return await applyPreparedTransaction(stableOptions,prepared.journal,recovered||prepared.recovered)}finally{await release()}}function retiredTransaction(journal){const pending=journal.status!=="abandoned",supersededBy=journal.abandonment.supersededBy,retry=supersededBy===void 0?`Retry abandonment without supersededBy to finish retirement of ${JSON.stringify(journal.transactionId)}.`:`Retry abandonment with supersededBy ${JSON.stringify(supersededBy)} to finish retirement of ${JSON.stringify(journal.transactionId)}.`;return new PmCliError(pending?`Transaction ${journal.transactionId} retirement is incomplete`:`Transaction ${journal.transactionId} has been abandoned`,EXIT_CODE.CONFLICT,{code:"transaction_abandoned",required:pending?retry:"Use a new transactionId for the replacement plan.",why:pending?"Forward replay is fenced, but the recorded retirement has not finished. Preserve its replacement identity.":"An explicitly retired transaction identity cannot be resumed.",...pending?{retirement:{state:"pending",superseded_by:supersededBy??null},nextSteps:[retry]}:{}})}async function readWorkspaceTransaction(pmRoot,transactionId){const identity=validateWorkspaceTransactionIdentity({pmRoot,transactionId,author:"reader"});return loadJournal(identity.pmRoot,identity.transactionId)}function workspaceTransactionPlanDigest(journal){return createHash("sha256").update(JSON.stringify(journal.stepIds)).digest("hex")}async function abandonWorkspaceTransaction(options){const identity=validateWorkspaceTransactionIdentity(options),reason=requiredText(options.reason,"Abandonment reason"),supersededBy=options.supersededBy===void 0?void 0:requiredIdentifier(options.supersededBy,"Replacement transaction id");if(supersededBy===identity.transactionId)throw new TypeError("Replacement transaction id must differ from the abandoned id");const lockTtlSeconds=positiveInteger(options.lockTtlSeconds,DEFAULT_LOCK_TTL_SECONDS,"Transaction lock TTL"),lockWaitMs=positiveInteger(options.lockWaitMs,DEFAULT_LOCK_WAIT_MS,"Transaction lock wait"),release=await acquireLock(identity.pmRoot,WORKSPACE_TRANSACTION_LOCK_ID,lockTtlSeconds,identity.author,!1,!1,lockWaitMs);try{const journal=await loadJournal(identity.pmRoot,identity.transactionId);if(journal===void 0)throw new PmCliError(`Transaction ${identity.transactionId} was not found`,EXIT_CODE.NOT_FOUND);if(journal.status==="committed")throw new PmCliError(`Transaction ${identity.transactionId} is committed and cannot be abandoned`,EXIT_CODE.CONFLICT,{code:"transaction_committed",required:"Plan a separate explicit corrective mutation.",why:"Recovery cannot silently undo committed work."});if(journal.abandonment!==void 0&&journal.abandonment.supersededBy!==supersededBy)throw retiredTransaction(journal);if(journal.status==="abandoned")return journal;const steps=options.resolveSteps(structuredClone(journal));if(JSON.stringify(steps.map(step=>step.id))!==JSON.stringify(journal.stepIds))throw journalPlanMismatch(identity.transactionId);if(journal.abandonment===void 0){if(supersededBy!==void 0&&await loadJournal(identity.pmRoot,supersededBy)!==void 0)throw new PmCliError(`Replacement transaction ${supersededBy} already exists`,EXIT_CODE.CONFLICT);journal.schemaVersion=2,journal.abandonment={reason,author:identity.author,...supersededBy===void 0?{}:{supersededBy}},await writeJournal(identity.pmRoot,journal)}return journal.status!=="compensated"&&await compensateAppliedSteps({...options,...identity,steps},journal),await auditTransactionAbandonment(journal,identity.pmRoot,lockTtlSeconds,lockWaitMs),journal.status="abandoned",await writeJournal(identity.pmRoot,journal),journal}finally{await release()}}async function auditTransactionAbandonment(journal,pmRoot,lockTtlSeconds,lockWaitMs){const planDigest=workspaceTransactionPlanDigest(journal);if((await readHistoryEntries(getWorkspaceHistoryPath(pmRoot),WORKSPACE_HISTORY_ID)).some(entry=>entry.op==="transaction_abandon"&&entry.context?.transaction_id===journal.transactionId&&entry.context?.attempt===journal.attempt&&entry.context?.plan_digest===planDigest))return;const abandonment=journal.abandonment;await appendWorkspaceAuditEvent({pmRoot,author:abandonment.author,lockTtlSeconds,lockWaitMs,op:"transaction_abandon",message:abandonment.reason,context:{transaction_id:journal.transactionId,attempt:journal.attempt,plan_digest:planDigest,...abandonment.supersededBy===void 0?{}:{superseded_by:abandonment.supersededBy}}})}export{WorkspaceTransactionInterruptedError,abandonWorkspaceTransaction,commitWorkspaceTransaction,readWorkspaceTransaction,validateWorkspaceTransactionIdentity,workspaceTransactionPlanDigest};
1
+ import{mkdir as M,readFile as P}from"node:fs/promises";import E from"node:path";import{createHash as q}from"node:crypto";import{appendWorkspaceAuditEvent as z,getWorkspaceHistoryPath as K,WORKSPACE_HISTORY_ID as V}from"../core/history/workspace-history.js";import{readHistoryEntries as U}from"./history-read.js";import{acquireLock as N}from"../core/lock/lock.js";import{isFileMissingError as H,writeFileAtomic as Z}from"../core/fs/fs-utils.js";import{nowIso as v}from"../core/shared/time.js";import{EXIT_CODE as f}from"../core/shared/constants.js";import{PmCliError as l}from"../core/shared/errors.js";import{runAsCoordinatorCompensation as X}from"../core/store/transaction-coordinator-scope.js";class Y extends Error{constructor(e="Workspace transaction interrupted"){super(e),this.name="WorkspaceTransactionInterruptedError"}}const $="sdk-workspace-transaction",C=/^[a-zA-Z0-9._-]+$/,J=30,D=3e3;function b(t,e){if(typeof t!="string")throw new TypeError(`${e} must be a string`);const s=t.trim();if(!s||!C.test(s))throw new TypeError(`${e} must match [a-zA-Z0-9._-]+`);return s}function S(t,e){if(typeof t!="string")throw new TypeError(`${e} must be a string`);const s=t.trim();if(!s)throw new TypeError(`${e} must be non-empty`);return s}function I(t){return{pmRoot:S(t.pmRoot,"Transaction pmRoot"),transactionId:b(t.transactionId,"Transaction id"),author:S(t.author,"Transaction author")}}function w(t,e,s){const a=t??e;if(!Number.isInteger(a)||a<=0)throw new TypeError(`${s} must be a positive integer`);return a}function x(t,e){return E.join(t,"transactions","sdk",`${e}.json`)}async function p(t,e){e.updatedAt=v();const s=x(t,e.transactionId);await M(E.dirname(s),{recursive:!0}),await Z(s,`${JSON.stringify(e,null,2)}
2
+ `)}function G(t){return Number.isInteger(t.attempt)&&typeof t.author=="string"&&typeof t.createdAt=="string"&&typeof t.updatedAt=="string"&&Q(t)}function Q(t){const e=t.abandonment;return e===void 0?t.schemaVersion===1&&t.status!=="abandoned":t.schemaVersion!==2||e===null||typeof e!="object"||t.status==="committed"?!1:typeof e.reason=="string"&&e.reason.trim().length>0&&typeof e.author=="string"&&e.author.trim().length>0&&(e.supersededBy===void 0||typeof e.supersededBy=="string"&&C.test(e.supersededBy)&&e.supersededBy!==t.transactionId)}function u(t){return Object.assign(Object.create(null),t)}function W(t,e){try{const s=JSON.stringify(t,(a,n)=>{if(typeof n=="number"&&!Number.isFinite(n))throw new TypeError(`${e} contains a non-finite number`);if(n===void 0||typeof n=="function"||typeof n=="symbol")throw new TypeError(`${e} contains a non-JSON value`);return n});return JSON.parse(s)}catch(s){throw new TypeError(`${e} must be JSON serializable`,{cause:s})}}function k(t,e){return t===void 0?void 0:W(t,e)}function A(t,e,s,a){const n=k(s,a);n===void 0?delete t[e]:t[e]=n}function F(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function R(t,e){return Array.isArray(t)&&new Set(t).size===t.length&&t.every(s=>typeof s=="string"&&e.includes(s))}function j(t,e){if(!R(t.startedStepIds,e)||!R(t.completedStepIds,e)||!F(t.results)||!F(t.compensationData))return!1;const s=t.startedStepIds,a=new Set(s),n=t.completedStepIds,r=new Set(n);return Object.keys(t.compensationData).some(i=>!a.has(i))||Object.keys(t.results).some(i=>!r.has(i))?!1:t.status==="committed"?e.every(i=>r.has(i)):!["compensated","abandoned"].includes(t.status??"")||r.size===0&&a.size===0}function g(t,e){return new l(`Workspace transaction ${t} journal is invalid (${e})`,f.CONFLICT,{code:"transaction_journal_invalid",required:"A valid durable journal is required before transaction recovery can continue.",why:"Corrupt journal data cannot establish which steps applied or still require compensation.",nextSteps:["Preserve the journal and inspect its integrity or restore a verified backup before retrying.","Do not switch to a new transaction id to bypass an unreadable journal; previously applied work may remain."]})}function L(t){return new l(`Workspace transaction ${t} journal does not match the supplied plan`,f.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the original plan or safely abandon the interrupted transaction before replacing it.",why:"A journal records the plan it is resuming; applying a different plan under the same id could skip or duplicate steps.",nextSteps:["Re-run with the original document to resume or replay it.","For item batches use client.itemTransactions.status(transactionId), then client.itemTransactions.abandon(transactionId, { reason }) before committing a changed plan with a new transactionId.","Run pm ops gc --scope transactions --dry-run to inspect retention; active and explicitly abandoned journals remain protected."]})}function tt(t,e,s){return s===void 0||t.abandonment!==void 0||t.status==="compensated"||e.length===s.length&&e.every((a,n)=>a===s[n])}function et(t,e,s){let a;try{a=JSON.parse(t)}catch{throw g(e,"invalid JSON")}if(!a||typeof a!="object"||Array.isArray(a))throw g(e,"expected an object");const n=a;if(!((n.schemaVersion===1||n.schemaVersion===2)&&n.transactionId===e))throw g(e,"schema version or transaction id does not match the journal file");const i=n.stepIds;if(!Array.isArray(i)||!R(i,i)||!j(n,i)||!G(n)||typeof n.status!="string"||!["applying","compensating","compensated","committed","abandoned"].includes(n.status))throw g(e,"invalid lifecycle, metadata, status or step ids");if(!tt(n,i,s))throw L(e);return{...n,results:u(n.results),compensationData:u(n.compensationData)}}async function nt(t,e,s,a,n){let r=n;const i=r!==void 0;if(r?.status==="compensating"&&await _(t,r),r===void 0||r.status==="compensated"){const o=v();r={schemaVersion:1,transactionId:e,author:s,status:"applying",attempt:(r?.attempt??0)+1,createdAt:r?.createdAt??o,updatedAt:o,stepIds:a,startedStepIds:[],completedStepIds:[],results:u(),compensationData:u(),...t.recoveryData===void 0?{}:{recoveryData:W(t.recoveryData,"Transaction recovery data")}},await p(t.pmRoot,r),await m(t,r,"prepared")}return{journal:r,recovered:i}}async function at(t,e,s){try{await st(e,t.steps),await p(t.pmRoot,e);const a=new Set(e.completedStepIds),n=new Set(e.startedStepIds);for(const r of t.steps){if(a.has(r.id))continue;const i=await r.inspect();let o=k(i.result,`Step ${r.id} result`);if(i.state!=="applied"){const d=await r.prepareCompensation?.();A(e.compensationData,r.id,d,`Step ${r.id} compensation data`),n.add(r.id),e.startedStepIds=t.steps.map(c=>c.id).filter(c=>n.has(c)),await p(t.pmRoot,e);const y=await r.apply();o=k(y,`Step ${r.id} result`)}await m(t,e,"step_applied",r.id),a.add(r.id),e.completedStepIds=t.steps.map(d=>d.id).filter(d=>a.has(d)),A(e.results,r.id,o,`Step ${r.id} result`),await p(t.pmRoot,e),await m(t,e,"step_recorded",r.id)}return await m(t,e,"committing"),e.status="committed",await p(t.pmRoot,e),await m(t,e,"committed"),{transactionId:e.transactionId,status:"committed",recovered:s,results:u(e.results)}}catch(a){if(a instanceof Y||e.status==="committed")throw a;try{await _(t,e)}catch(n){throw new AggregateError([a,n],`Workspace transaction failed and compensation failed: ${String(n)}`,{cause:n})}throw a}}async function T(t,e,s){try{return et(await P(x(t,e),"utf8"),e,s)}catch(a){if(a!==null&&typeof a=="object"&&"code"in a&&H(a))return;throw a}}async function m(t,e,s,a){await t.onTransition?.({transactionId:e.transactionId,attempt:e.attempt,transition:s,...a===void 0?{}:{stepId:a}})}async function st(t,e){const s=new Set,a=u();for(const n of e){const r=await n.inspect();r.state==="applied"&&(s.add(n.id),A(a,n.id,r.result,`Step ${n.id} result`))}t.results=a,t.completedStepIds=e.map(n=>n.id).filter(n=>s.has(n))}async function _(t,e){e.status="compensating",await p(t.pmRoot,e),await m(t,e,"compensating");const s=new Set(e.completedStepIds),a=new Set(e.startedStepIds);for(const n of[...t.steps].reverse()){if(!a.has(n.id)&&!s.has(n.id))continue;let r;try{const i=(await n.inspect()).state;r=a.has(n.id)&&(i==="applied"||i==="pending"&&n.compensatePending===!0)}catch{r=a.has(n.id)}r&&(await m(t,e,"step_compensating",n.id),await X({pmRoot:t.pmRoot,transactionId:e.transactionId,step:n},()=>n.compensate(e.compensationData[n.id]))),s.delete(n.id),a.delete(n.id),e.completedStepIds=t.steps.map(i=>i.id).filter(i=>s.has(i)),e.startedStepIds=t.steps.map(i=>i.id).filter(i=>a.has(i)),delete e.results[n.id],delete e.compensationData[n.id],await p(t.pmRoot,e),await m(t,e,"step_compensated",n.id)}e.status="compensated",await p(t.pmRoot,e),await m(t,e,"compensated")}async function gt(t){const{pmRoot:e,transactionId:s,author:a}=I(t),n=w(t.lockTtlSeconds,J,"Transaction lock TTL"),r=w(t.lockWaitMs,D,"Transaction lock wait"),i=[...t.steps];if(i.length===0)throw new TypeError("Workspace transaction requires at least one step");const o=i.map(c=>{const h=b(c.id,"Transaction step id");if(h!==c.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return h});if(new Set(o).size!==o.length)throw new TypeError("Workspace transaction step ids must be unique");const d={...t,pmRoot:e,transactionId:s,author:a,steps:i,lockTtlSeconds:n,lockWaitMs:r},y=await N(e,$,n,a,!1,!1,r);try{const c=await T(e,s,o);if(c?.status==="abandoned"||c?.abandonment!==void 0)throw B(c);const h=c!==void 0;if(c?.status==="committed")return{transactionId:s,status:"committed",recovered:!0,results:u(c.results)};const O=await nt(d,s,a,o,c);return await at(d,O.journal,h||O.recovered)}finally{await y()}}function B(t){const e=t.status!=="abandoned",s=t.abandonment.supersededBy,a=s===void 0?`Retry abandonment without supersededBy to finish retirement of ${JSON.stringify(t.transactionId)}.`:`Retry abandonment with supersededBy ${JSON.stringify(s)} to finish retirement of ${JSON.stringify(t.transactionId)}.`;return new l(e?`Transaction ${t.transactionId} retirement is incomplete`:`Transaction ${t.transactionId} has been abandoned`,f.CONFLICT,{code:"transaction_abandoned",required:e?a:"Use a new transactionId for the replacement plan.",why:e?"Forward replay is fenced, but the recorded retirement has not finished. Preserve its replacement identity.":"An explicitly retired transaction identity cannot be resumed.",...e?{retirement:{state:"pending",superseded_by:s??null},nextSteps:[a]}:{}})}async function Tt(t,e){const s=I({pmRoot:t,transactionId:e,author:"reader"});return T(s.pmRoot,s.transactionId)}function rt(t){return q("sha256").update(JSON.stringify(t.stepIds)).digest("hex")}async function bt(t){const e=I(t),s=S(t.reason,"Abandonment reason"),a=t.supersededBy===void 0?void 0:b(t.supersededBy,"Replacement transaction id");if(a===e.transactionId)throw new TypeError("Replacement transaction id must differ from the abandoned id");const n=w(t.lockTtlSeconds,J,"Transaction lock TTL"),r=w(t.lockWaitMs,D,"Transaction lock wait"),i=await N(e.pmRoot,$,n,e.author,!1,!1,r);try{const o=await T(e.pmRoot,e.transactionId);if(o===void 0)throw new l(`Transaction ${e.transactionId} was not found`,f.NOT_FOUND);if(o.status==="committed")throw new l(`Transaction ${e.transactionId} is committed and cannot be abandoned`,f.CONFLICT,{code:"transaction_committed",required:"Plan a separate explicit corrective mutation.",why:"Recovery cannot silently undo committed work."});if(o.abandonment!==void 0&&o.abandonment.supersededBy!==a)throw B(o);if(o.status==="abandoned")return o;const d=t.resolveSteps(structuredClone(o));if(JSON.stringify(d.map(y=>y.id))!==JSON.stringify(o.stepIds))throw L(e.transactionId);if(o.abandonment===void 0){if(a!==void 0&&await T(e.pmRoot,a)!==void 0)throw new l(`Replacement transaction ${a} already exists`,f.CONFLICT);o.schemaVersion=2,o.abandonment={reason:s,author:e.author,...a===void 0?{}:{supersededBy:a}},await p(e.pmRoot,o)}return o.status!=="compensated"&&await _({...t,...e,steps:d},o),await it(o,e.pmRoot,n,r),o.status="abandoned",await p(e.pmRoot,o),o}finally{await i()}}async function it(t,e,s,a){const n=rt(t);if((await U(K(e),V)).some(o=>o.op==="transaction_abandon"&&o.context?.transaction_id===t.transactionId&&o.context?.attempt===t.attempt&&o.context?.plan_digest===n))return;const i=t.abandonment;await z({pmRoot:e,author:i.author,lockTtlSeconds:s,lockWaitMs:a,op:"transaction_abandon",message:i.reason,context:{transaction_id:t.transactionId,attempt:t.attempt,plan_digest:n,...i.supersededBy===void 0?{}:{superseded_by:i.supersededBy}}})}export{Y as WorkspaceTransactionInterruptedError,bt as abandonWorkspaceTransaction,gt as commitWorkspaceTransaction,Tt as readWorkspaceTransaction,I as validateWorkspaceTransactionIdentity,rt as workspaceTransactionPlanDigest};
3
3
  //# sourceMappingURL=workspace-transaction.js.map