@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]="975b7c1d-e398-586a-bd50-b3bf0528d24a")}catch{}})();import{unicodeSafePrefix}from"../shared/text-normalization.js";const CHANGED_FIELDS_KEY="changed_fields",CHANGED_FIELD_COUNT_KEY="changed_field_count",ROWS_KEY="rows",UPDATE_MANY_MUTATION_MODES=new Set(["apply","rollback"]),DELETE_OUTCOMES=new Set(["deleted","would_delete"]),COMPACT_RECURRENCE_TEXT_LIMIT=256,COMPOUND_MUTATION_STEPS={start_task:["claim","update"],pause_task:["update","release"],close_task:["close","release"]};function projectCompoundMutation(result,options){if(!isPlainObject(result)||typeof result.action!="string"||typeof result.id!="string"||result.id.length===0)return null;const steps=Object.hasOwn(COMPOUND_MUTATION_STEPS,result.action)?COMPOUND_MUTATION_STEPS[result.action]:void 0;if(!steps||!steps.every(step=>{const value=result[step];return isPlainObject(value)&&isPlainObject(value.item)&&value.item.id===result.id&&Array.isArray(value.changed_fields)&&value.changed_fields.every(field=>typeof field=="string")}))return null;const final=result[steps.at(-1)],identity=projectIdOnlyResult(final);return options.idOnly?identity:!options.compactEnvelope&&options.changedFields!=="compact"?null:{...result,...options.compactEnvelope?{...identity,changed_field_count:new Set(steps.flatMap(step=>result[step].changed_fields)).size}:{},...Object.fromEntries(steps.map(step=>[step,projectMutationResult(result[step],options)]))}}function truncateCompactRecurrenceText(value){return typeof value!="string"||value.length<=COMPACT_RECURRENCE_TEXT_LIMIT?value:`${unicodeSafePrefix(value,COMPACT_RECURRENCE_TEXT_LIMIT-1)}\u2026`}function projectCompactRecurrence(value){if(!isPlainObject(value))return null;const recurrence={...value};return recurrence.reason=truncateCompactRecurrenceText(recurrence.reason),isPlainObject(recurrence.previous_terminal)&&(recurrence.previous_terminal=Object.fromEntries(Object.entries(recurrence.previous_terminal).map(([key,entry])=>[key,truncateCompactRecurrenceText(entry)]))),recurrence}function isPlainObject(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;const proto=Object.getPrototypeOf(value);return proto===null||proto===Object.prototype}function compactOwnChangedFields(envelope){const changedFields=envelope[CHANGED_FIELDS_KEY];if(!Array.isArray(changedFields))return null;const projected=Object.getPrototypeOf(envelope)===null?Object.create(null):{};for(const[key,value]of Object.entries(envelope))key!==CHANGED_FIELDS_KEY&&(projected[key]=value);return projected[CHANGED_FIELD_COUNT_KEY]=changedFields.length,projected}function isMutationEnvelope(value){return"item"in value&&Array.isArray(value[CHANGED_FIELDS_KEY])}function isUpdateManyMutationEnvelope(value){return typeof value.mode=="string"&&UPDATE_MANY_MUTATION_MODES.has(value.mode)&&Array.isArray(value[ROWS_KEY])}function replaceRows(envelope,rows){const projected=Object.getPrototypeOf(envelope)===null?Object.create(null):{};return Object.assign(projected,envelope),projected[ROWS_KEY]=rows,projected}function projectIdOnlyResult(result){if(!isPlainObject(result))return null;const subject=isPlainObject(result.item)?result.item:isPlainObject(result.plan)?result.plan:null;if(subject===null)return null;const id=typeof subject.id=="string"?subject.id:void 0,status=typeof result.outcome=="string"&&DELETE_OUTCOMES.has(result.outcome)?result.outcome:typeof subject.status=="string"?subject.status:void 0;return id?status?{id,status,...typeof result.deleted=="boolean"?{deleted:result.deleted}:{}}:{id}:null}function projectCompactMutationEnvelope(result,includeItem){if(!isPlainObject(result))return null;if(isPlainObject(result.plan)&&isPlainObject(result.mutation_receipt)&&result.mutation_receipt.kind==="plan_mutation"&&result.mutation_receipt.id===result.plan.id&&result.mutation_receipt.action===result.action)return result.mutation_receipt;if(!includeItem||!isPlainObject(result.item)||typeof result.item.id!="string")return null;const changedFields=result[CHANGED_FIELDS_KEY];if(!Array.isArray(changedFields))return null;const compact={id:result.item.id,...typeof result.outcome=="string"&&DELETE_OUTCOMES.has(result.outcome)?{status:result.outcome}:typeof result.item.status=="string"?{status:result.item.status}:{},...typeof result.deleted=="boolean"?{deleted:result.deleted}:{},...typeof result.previous_status=="string"?{previous_status:result.previous_status}:{},changed_field_count:changedFields.length};return appendCompactMutationEvidence(result,result.item,compact),compact}function appendCompactMutationEvidence(result,item,compact){const closeReason=typeof result.close_reason=="string"?result.close_reason:typeof item.close_reason=="string"?item.close_reason:void 0;closeReason!==void 0&&(compact.close_reason=closeReason);const recurrence=projectCompactRecurrence(result.recurrence);recurrence!==null&&(compact.recurrence=recurrence),Array.isArray(result.warnings)&&result.warnings.length>0&&(compact.warnings=result.warnings);for(const key of["recovery","follow_up","handoff","completion","start","takeover"])isPlainObject(result[key])&&(compact[key]=result[key]);if(typeof result.claimed_by=="string"||typeof result.released_by=="string")for(const key of["claimed_by","released_by","previous_assignee","forced","skipped","available","attempts","start_refused","suggestions"])Object.hasOwn(result,key)&&(compact[key]=result[key])}function compactUpdateManyRows(envelope){const rows=isUpdateManyMutationEnvelope(envelope)?envelope[ROWS_KEY]:void 0;if(!Array.isArray(rows))return{projected:envelope,changed:!1};let rowsChanged=!1;const nextRows=rows.map(row=>{if(!isPlainObject(row))return row;const compactedRow=compactOwnChangedFields(row);return compactedRow?(rowsChanged=!0,compactedRow):row});return rowsChanged?{projected:replaceRows(envelope,nextRows),changed:!0}:{projected:envelope,changed:!1}}function projectMutationResult(result,options={}){const compound=projectCompoundMutation(result,options);if(compound!==null)return compound;if(options.idOnly===!0){const idOnly=projectIdOnlyResult(result);if(idOnly!==null)return idOnly}if(options.compactEnvelope===!0||options.changedFields==="compact"){const compact=projectCompactMutationEnvelope(result,options.compactEnvelope===!0);if(compact!==null)return compact}if((options.changedFields??"full")==="full"||!isPlainObject(result))return result;let changed=!1,projected=result;const compactedTop=isMutationEnvelope(result)?compactOwnChangedFields(result):null;compactedTop!==null&&(projected=compactedTop,changed=!0);const rowProjection=compactUpdateManyRows(projected);return rowProjection.changed&&(projected=rowProjection.projected,changed=!0),changed?projected:result}export{projectMutationResult};
1
+ import{unicodeSafePrefix as O}from"../shared/text-normalization.js";const s="changed_fields",h="changed_field_count",p="rows",j=new Set(["apply","rollback"]),u=new Set(["deleted","would_delete"]),l=256,y={start_task:["claim","update"],pause_task:["update","release"],close_task:["close","release"]};function E(e,n){if(!r(e)||typeof e.action!="string"||typeof e.id!="string"||e.id.length===0)return null;const t=Object.hasOwn(y,e.action)?y[e.action]:void 0;if(!t||!t.every(o=>{const a=e[o];return r(a)&&r(a.item)&&a.item.id===e.id&&Array.isArray(a.changed_fields)&&a.changed_fields.every(f=>typeof f=="string")}))return null;const i=e[t.at(-1)],c=g(i);return n.idOnly?c:!n.compactEnvelope&&n.changedFields!=="compact"?null:{...e,...n.compactEnvelope?{...c,changed_field_count:new Set(t.flatMap(o=>e[o].changed_fields)).size}:{},...Object.fromEntries(t.map(o=>[o,k(e[o],n)]))}}function m(e){return typeof e!="string"||e.length<=l?e:`${O(e,l-1)}\u2026`}function b(e){if(!r(e))return null;const n={...e};return n.reason=m(n.reason),r(n.previous_terminal)&&(n.previous_terminal=Object.fromEntries(Object.entries(n.previous_terminal).map(([t,i])=>[t,m(i)]))),n}function r(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const n=Object.getPrototypeOf(e);return n===null||n===Object.prototype}function _(e){const n=e[s];if(!Array.isArray(n))return null;const t=Object.getPrototypeOf(e)===null?Object.create(null):{};for(const[i,c]of Object.entries(e))i!==s&&(t[i]=c);return t[h]=n.length,t}function A(e){return"item"in e&&Array.isArray(e[s])}function w(e){return typeof e.mode=="string"&&j.has(e.mode)&&Array.isArray(e[p])}function M(e,n){const t=Object.getPrototypeOf(e)===null?Object.create(null):{};return Object.assign(t,e),t[p]=n,t}function g(e){if(!r(e))return null;const n=r(e.item)?e.item:r(e.plan)?e.plan:null;if(n===null)return null;const t=typeof n.id=="string"?n.id:void 0,i=typeof e.outcome=="string"&&u.has(e.outcome)?e.outcome:typeof n.status=="string"?n.status:void 0;return t?i?{id:t,status:i,...typeof e.deleted=="boolean"?{deleted:e.deleted}:{}}:{id:t}:null}function C(e,n){if(!r(e))return null;if(r(e.plan)&&r(e.mutation_receipt)&&e.mutation_receipt.kind==="plan_mutation"&&e.mutation_receipt.id===e.plan.id&&e.mutation_receipt.action===e.action)return e.mutation_receipt;if(!n||!r(e.item)||typeof e.item.id!="string")return null;const t=e[s];if(!Array.isArray(t))return null;const i={id:e.item.id,...typeof e.outcome=="string"&&u.has(e.outcome)?{status:e.outcome}:typeof e.item.status=="string"?{status:e.item.status}:{},...typeof e.deleted=="boolean"?{deleted:e.deleted}:{},...typeof e.previous_status=="string"?{previous_status:e.previous_status}:{},changed_field_count:t.length};return T(e,e.item,i),i}function T(e,n,t){const i=typeof e.close_reason=="string"?e.close_reason:typeof n.close_reason=="string"?n.close_reason:void 0;i!==void 0&&(t.close_reason=i);const c=b(e.recurrence);c!==null&&(t.recurrence=c),Array.isArray(e.warnings)&&e.warnings.length>0&&(t.warnings=e.warnings);for(const o of["recovery","follow_up","handoff","completion","start","takeover"])r(e[o])&&(t[o]=e[o]);if(typeof e.claimed_by=="string"||typeof e.released_by=="string")for(const o of["claimed_by","released_by","previous_assignee","forced","skipped","available","attempts","start_refused","suggestions"])Object.hasOwn(e,o)&&(t[o]=e[o])}function R(e){const n=w(e)?e[p]:void 0;if(!Array.isArray(n))return{projected:e,changed:!1};let t=!1;const i=n.map(c=>{if(!r(c))return c;const o=_(c);return o?(t=!0,o):c});return t?{projected:M(e,i),changed:!0}:{projected:e,changed:!1}}function k(e,n={}){const t=E(e,n);if(t!==null)return t;if(n.idOnly===!0){const d=g(e);if(d!==null)return d}if(n.compactEnvelope===!0||n.changedFields==="compact"){const d=C(e,n.compactEnvelope===!0);if(d!==null)return d}if((n.changedFields??"full")==="full"||!r(e))return e;let c=!1,o=e;const a=A(e)?_(e):null;a!==null&&(o=a,c=!0);const f=R(o);return f.changed&&(o=f.projected,c=!0),c?o:e}export{k as projectMutationResult};
2
2
  //# sourceMappingURL=mutation-projection.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]="32aa20df-edf7-543d-b733-841130466f00")}catch{}})();const SUPPRESS_HOST_OUTPUT_KEY="__pm_suppress_host_output",SUPPRESS_HOST_OUTPUT_MARKER="@unbrained/pm-cli:suppress-host-output:v1";function suppressHostOutput(result){return result===void 0?{__pm_suppress_host_output:SUPPRESS_HOST_OUTPUT_MARKER}:{__pm_suppress_host_output:SUPPRESS_HOST_OUTPUT_MARKER,result}}function isHostOutputSuppressed(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&value[SUPPRESS_HOST_OUTPUT_KEY]===SUPPRESS_HOST_OUTPUT_MARKER}export{SUPPRESS_HOST_OUTPUT_MARKER,isHostOutputSuppressed,suppressHostOutput};
1
+ const s="__pm_suppress_host_output",p="@unbrained/pm-cli:suppress-host-output:v1";function u(t){return t===void 0?{__pm_suppress_host_output:p}:{__pm_suppress_host_output:p,result:t}}function _(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&t[s]===p}export{p as SUPPRESS_HOST_OUTPUT_MARKER,_ as isHostOutputSuppressed,u as suppressHostOutput};
2
2
  //# sourceMappingURL=output-control.js.map
@@ -1,22 +1,22 @@
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]="f33393ac-6b72-5e46-92a5-f276d1fbfff1")}catch{}})();import{getActiveCommandContext,runActiveCommandOverride,runActiveRendererOverride,runActiveServiceOverrideSync,setActiveCommandResult}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{isHostOutputSuppressed}from"./output-control.js";import{projectMutationResult}from"./mutation-projection.js";import{projectLinkedTestReply}from"./linked-test-projection.js";import{attachReadOutputContracts}from"../../sdk/context-intent-contracts.js";import{attachOutputTokenAccounting}from"../../sdk/output-token-accounting.js";import{propagateContextUsageServingReceipt}from"../../sdk/context-usage.js";import{isReadResultOmittedForBudget,resolveReadOutputEncoding,resolveReadOutputSurface}from"../../sdk/read-output-contracts.js";import{readOutputPositionalRowPaths}from"../../sdk/read-output/positional-rows.js";import{GET_FACET_ROOTS}from"../../sdk/query/get-facet-roots.js";import{withDeliveredOutputRenderer}from"../../sdk/read-output-budget.js";import{encode as encodeToon}from"@toon-format/toon";import{encodePmTableRows,projectPmTableEncodingForToon}from"../../sdk/output/table-rows.js";import{projectPmBriefListEnvelope,projectPmBriefSearchEnvelope}from"../../sdk/output/list-envelope.js";import{prepareWellFormedOutputText}from"../shared/output-unicode.js";const DECLARED_PROCESS_EXIT_CODES=new Set(Object.values(EXIT_CODE)),COLLECTION_COUNT_ALIASES=new Map([["notes_count","notes"],["tests_count","tests"]]),NATIVE_OUTPUT_MARKER="__pm_native_output";let streamErrorHandlersInstalled=!1;function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function setActiveCommandResultOmitted(source){const omitted={read_output:{result_omitted:!0}};propagateContextUsageServingReceipt(source,omitted),setActiveCommandResult(omitted)}function setActiveCommandDeliveryResult(result,receiptSource,structuredDeliveryPreserved){if(structuredDeliveryPreserved){setActiveCommandResult(result);return}setActiveCommandResultOmitted(receiptSource)}function stripNativeOutputMarker(result){if(!isPlainObject(result)||result[NATIVE_OUTPUT_MARKER]!==!0)return result;const{[NATIVE_OUTPUT_MARKER]:_marker,...rest}=result;return rest}function isBrokenPipeError(error){return typeof error=="object"&&error!==null&&error.code==="EPIPE"}function markStdoutBrokenPipeExitCode(){(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=EXIT_CODE.SUCCESS)}function markStderrBrokenPipeExitCode(){(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE)}function markBrokenPipeExitCode(target){if(target==="stdout"){markStdoutBrokenPipeExitCode();return}markStderrBrokenPipeExitCode()}function handleUnhandledStreamError(error){const unhandled=error instanceof Error?error:new Error(String(error));setImmediate(()=>{throw unhandled})}function installStreamErrorHandlers(){streamErrorHandlersInstalled||(streamErrorHandlersInstalled=!0,process.stdout.on("error",error=>{if(isBrokenPipeError(error)){markBrokenPipeExitCode("stdout");return}handleUnhandledStreamError(error)}),process.stderr.on("error",error=>{if(isBrokenPipeError(error)){markBrokenPipeExitCode("stderr");return}handleUnhandledStreamError(error)}))}function writeToStream(target,text){installStreamErrorHandlers();try{return target==="stdout"?process.stdout.write(text):process.stderr.write(text),!0}catch(error){if(isBrokenPipeError(error))return markBrokenPipeExitCode(target),!1;throw error}}function writeStdout(text){return writeToStream("stdout",text)}function writeStderr(text){return writeToStream("stderr",text)}function renderScalar(value){return typeof value=="string"?JSON.stringify(value):typeof value=="number"||typeof value=="boolean"?String(value):value===null?"null":JSON.stringify(value)}function indentToon(encoded,depth){const indent=" ".repeat(depth);return encoded.split(`
2
- `).map(line=>`${indent}${line}`).join(`
3
- `)}function isNestedTableCandidateBounded(rows){const columns=new Set;let presentCells=0;for(const row of rows){const keys=Object.keys(row);presentCells+=keys.length;for(const key of keys)columns.add(key)}return rows.length*columns.size<=presentCells*2}function renderToonObjectEntry(key,entry,depth,allowNestedTable){const indent=" ".repeat(depth);if(!isPlainObject(entry)&&!Array.isArray(entry))return`${indent}${key}: ${renderScalar(entry)}`;const receipt=key==="omission_receipt"?renderToonOmissionReceipt(entry,depth):void 0;if(receipt!==void 0)return receipt;if(Array.isArray(entry)){if(entry.length===0)return`${indent}${key}: []`;const expanded=indentToon(encodeToon({[key]:entry}),depth);return allowNestedTable&&entry.length>=1&&entry.every(isPlainObject)&&isNestedTableCandidateBounded(entry)?[!1,!0].map(compact=>{const table=encodePmTableRows(entry,{compact});return indentToon(encodeToon({[key]:table.rows,[`${key}_encoding`]:projectPmTableEncodingForToon(table.encoding)}),depth)}).reduce((smallest,candidate)=>Buffer.byteLength(candidate)<Buffer.byteLength(smallest)?candidate:smallest,expanded):expanded}return isPlainObject(entry)&&Object.keys(entry).length===0?`${indent}${key}: {}`:`${indent}${key}:
4
- ${renderToonValue(entry,depth+1)}`}function renderToonOmissionReceipt(entry,depth){const indent=" ".repeat(depth);if(isCompleteOmissionReceipt(entry))return`${indent}omission_receipt: complete`;const named=isPlainObject(entry)?projectDerivableOmissionReceipt(entry):void 0;if(named===void 0)return;const rowsText=`${indent}omission_receipt:
5
- ${renderToonValue(entry,depth+1)}`,namedText=`${indent}omission_receipt:
6
- ${renderToonValue(named,depth+1)}`;return Buffer.byteLength(namedText)<Buffer.byteLength(rowsText)?namedText:rowsText}function projectDerivableOmissionReceipt(receipt){const groups=receipt.omitted_field_groups;if(!Array.isArray(groups)||groups.length===0||Object.hasOwn(receipt,"restore_with"))return;const names=[];let prefix;for(const group of groups){if(!isPlainObject(group)||Object.keys(group).length!==2)return;const{name,restore_with:restoreWith}=group;if(typeof name!="string"||name.length===0||typeof restoreWith!="string"||!restoreWith.endsWith(name))return;const groupPrefix=restoreWith.slice(0,restoreWith.length-name.length);if(prefix!==void 0&&groupPrefix!==prefix)return;prefix=groupPrefix,names.push(name)}return Object.fromEntries(Object.entries(receipt).flatMap(([key,value])=>key==="omitted_field_groups"?[[key,names],["restore_with",`${prefix}<name>`]]:[[key,value]]))}function compactToonArray(values,policy,preserveEmpty){const compactedEntries=values.map(entry=>compactToonValue(entry,policy,preserveEmpty||policy.preserveRowFacts&&isPlainObject(entry))).filter(entry=>entry!==void 0);return compactedEntries.length>0||preserveEmpty?compactedEntries:void 0}function compactToonValue(value,policy={omitDuplicateCountAliases:!0,preserveRowFacts:!0},preserveEmpty=!1){if(value===null)return preserveEmpty?null:void 0;if(Array.isArray(value))return compactToonArray(value,policy,preserveEmpty);if(isPlainObject(value)){const compacted=[],entries=Object.entries(value).filter(([key,entry])=>{const canonicalCount=COLLECTION_COUNT_ALIASES.get(key);return!policy.omitDuplicateCountAliases||canonicalCount===void 0||!isPlainObject(value.collection_counts)||entry!==value.collection_counts[canonicalCount]});for(const[key,entry]of entries){if(key==="omitted_field_groups"&&Array.isArray(entry)&&entry.length===0){compacted.push([key,[]]);continue}const compactedEntry=compactToonValue(entry,policy,preserveEmpty);compactedEntry!==void 0&&compacted.push([key,compactedEntry])}return compacted.length>0||preserveEmpty?Object.fromEntries(compacted):void 0}return value}function renderToonValue(value,depth){const indent=" ".repeat(depth);if(Array.isArray(value))return value.length===0?"[]":indentToon(encodeToon(value),depth);if(isPlainObject(value)){const entries=Object.entries(value);return entries.length===0?"{}":entries.map(([key,entry])=>renderToonObjectEntry(key,entry,depth,!Object.hasOwn(value,`${key}_encoding`)&&!(key==="checks"&&isPlainObject(value.verdict)&&value.verdict.authority==="ok"))).join(`
7
- `)}return`${indent}${renderScalar(value)}`}function renderDefaultMarkdownResult(value){if(!isPlainObject(value)||value.output_default!=="markdown"||typeof value.view!="string"||!Array.isArray(value.events)||!Array.isArray(value.days))return null;const lines=[`# pm calendar (${value.view})`,""],summary=isPlainObject(value.summary)?value.summary:{};if(lines.push(`- events: ${String(summary.events??0)}`),lines.push(""),value.events.length===0)return lines.push("No calendar events matched the selected filters."),`${lines.join(`
1
+ import{getActiveCommandContext as V,runActiveCommandOverride as G,runActiveRendererOverride as H,runActiveServiceOverrideSync as v,setActiveCommandResult as A}from"../extensions/index.js";import{EXIT_CODE as a}from"../shared/constants.js";import{isHostOutputSuppressed as K}from"./output-control.js";import{projectMutationResult as j}from"./mutation-projection.js";import{projectLinkedTestReply as X}from"./linked-test-projection.js";import{attachReadOutputContracts as k}from"../../sdk/context-intent-contracts.js";import{attachOutputTokenAccounting as Y}from"../../sdk/output-token-accounting.js";import{propagateContextUsageServingReceipt as I}from"../../sdk/context-usage.js";import{isReadResultOmittedForBudget as C,resolveReadOutputEncoding as z,resolveReadOutputSurface as Q}from"../../sdk/read-output-contracts.js";import{readOutputPositionalRowPaths as Z}from"../../sdk/read-output/positional-rows.js";import{GET_FACET_ROOTS as ee}from"../../sdk/query/get-facet-roots.js";import{withDeliveredOutputRenderer as S}from"../../sdk/read-output-budget.js";import{encode as b}from"@toon-format/toon";import{encodePmTableRows as te,projectPmTableEncodingForToon as ne}from"../../sdk/output/table-rows.js";import{projectPmBriefListEnvelope as re,projectPmBriefSearchEnvelope as oe}from"../../sdk/output/list-envelope.js";import{prepareWellFormedOutputText as ie}from"../shared/output-unicode.js";const se=new Set(Object.values(a)),ue=new Map([["notes_count","notes"],["tests_count","tests"]]),x="__pm_native_output";let L=!1;function c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function R(e){const t={read_output:{result_omitted:!0}};I(e,t),A(t)}function w(e,t,n){if(n){A(e);return}R(t)}function ce(e){if(!c(e)||e[x]!==!0)return e;const{[x]:t,...n}=e;return n}function y(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function de(){(process.exitCode===void 0||process.exitCode===a.SUCCESS)&&(process.exitCode=a.SUCCESS)}function fe(){(process.exitCode===void 0||process.exitCode===a.SUCCESS)&&(process.exitCode=a.GENERIC_FAILURE)}function T(e){if(e==="stdout"){de();return}fe()}function F(e){const t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function ae(){L||(L=!0,process.stdout.on("error",e=>{if(y(e)){T("stdout");return}F(e)}),process.stderr.on("error",e=>{if(y(e)){T("stderr");return}F(e)}))}function B(e,t){ae();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(y(n))return T(e),!1;throw n}}function le(e){return B("stdout",e)}function M(e){return B("stderr",e)}function U(e){return typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":JSON.stringify(e)}function $(e,t){const n=" ".repeat(t);return e.split(`
2
+ `).map(r=>`${n}${r}`).join(`
3
+ `)}function me(e){const t=new Set;let n=0;for(const r of e){const o=Object.keys(r);n+=o.length;for(const i of o)t.add(i)}return e.length*t.size<=n*2}function pe(e,t,n,r){const o=" ".repeat(n);if(!c(t)&&!Array.isArray(t))return`${o}${e}: ${U(t)}`;const i=e==="omission_receipt"?Oe(t,n):void 0;if(i!==void 0)return i;if(Array.isArray(t)){if(t.length===0)return`${o}${e}: []`;const s=$(b({[e]:t}),n);return r&&t.length>=1&&t.every(c)&&me(t)?[!1,!0].map(d=>{const f=te(t,{compact:d});return $(b({[e]:f.rows,[`${e}_encoding`]:ne(f.encoding)}),n)}).reduce((d,f)=>Buffer.byteLength(f)<Buffer.byteLength(d)?f:d,s):s}return c(t)&&Object.keys(t).length===0?`${o}${e}: {}`:`${o}${e}:
4
+ ${_(t,n+1)}`}function Oe(e,t){const n=" ".repeat(t);if(Re(e))return`${n}omission_receipt: complete`;const r=c(e)?ge(e):void 0;if(r===void 0)return;const o=`${n}omission_receipt:
5
+ ${_(e,t+1)}`,i=`${n}omission_receipt:
6
+ ${_(r,t+1)}`;return Buffer.byteLength(i)<Buffer.byteLength(o)?i:o}function ge(e){const t=e.omitted_field_groups;if(!Array.isArray(t)||t.length===0||Object.hasOwn(e,"restore_with"))return;const n=[];let r;for(const o of t){if(!c(o)||Object.keys(o).length!==2)return;const{name:i,restore_with:s}=o;if(typeof i!="string"||i.length===0||typeof s!="string"||!s.endsWith(i))return;const u=s.slice(0,s.length-i.length);if(r!==void 0&&u!==r)return;r=u,n.push(i)}return Object.fromEntries(Object.entries(e).flatMap(([o,i])=>o==="omitted_field_groups"?[[o,n],["restore_with",`${r}<name>`]]:[[o,i]]))}function _e(e,t,n){const r=e.map(o=>l(o,t,n||t.preserveRowFacts&&c(o))).filter(o=>o!==void 0);return r.length>0||n?r:void 0}function l(e,t={omitDuplicateCountAliases:!0,preserveRowFacts:!0},n=!1){if(e===null)return n?null:void 0;if(Array.isArray(e))return _e(e,t,n);if(c(e)){const r=[],o=Object.entries(e).filter(([i,s])=>{const u=ue.get(i);return!t.omitDuplicateCountAliases||u===void 0||!c(e.collection_counts)||s!==e.collection_counts[u]});for(const[i,s]of o){if(i==="omitted_field_groups"&&Array.isArray(s)&&s.length===0){r.push([i,[]]);continue}const u=l(s,t,n);u!==void 0&&r.push([i,u])}return r.length>0||n?Object.fromEntries(r):void 0}return e}function _(e,t){const n=" ".repeat(t);if(Array.isArray(e))return e.length===0?"[]":$(b(e),t);if(c(e)){const r=Object.entries(e);return r.length===0?"{}":r.map(([o,i])=>pe(o,i,t,!Object.hasOwn(e,`${o}_encoding`)&&!(o==="checks"&&c(e.verdict)&&e.verdict.authority==="ok"))).join(`
7
+ `)}return`${n}${U(e)}`}function he(e){if(!c(e)||e.output_default!=="markdown"||typeof e.view!="string"||!Array.isArray(e.events)||!Array.isArray(e.days))return null;const t=[`# pm calendar (${e.view})`,""],n=c(e.summary)?e.summary:{};if(t.push(`- events: ${String(n.events??0)}`),t.push(""),e.events.length===0)return t.push("No calendar events matched the selected filters."),`${t.join(`
8
8
  `)}
9
- `;for(const event of value.events){if(!isPlainObject(event))continue;const kind=typeof event.kind=="string"?event.kind:"event",title=typeof event.item_title=="string"?event.item_title:"",itemId=typeof event.item_id=="string"?event.item_id:"",reminderText=typeof event.reminder_text=="string"&&event.reminder_text.length>0?` ${event.reminder_text}`:"";lines.push(`- [${kind}] ${itemId} ${title}${reminderText}`.trim())}return`${lines.join(`
9
+ `;for(const r of e.events){if(!c(r))continue;const o=typeof r.kind=="string"?r.kind:"event",i=typeof r.item_title=="string"?r.item_title:"",s=typeof r.item_id=="string"?r.item_id:"",u=typeof r.reminder_text=="string"&&r.reminder_text.length>0?` ${r.reminder_text}`:"";t.push(`- [${o}] ${s} ${i}${u}`.trim())}return`${t.join(`
10
10
  `)}
11
- `}const LEAN_READ_ENVELOPE_ECHO_KEYS=new Set(["filters","now","projection","sorting"]);function projectLeanJsonValue(value){const compacted=compactToonValue(value,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!isPlainObject(compacted)||!Array.isArray(compacted.items))return compacted??null;const projected=Object.fromEntries(Object.entries(compacted).filter(([key])=>!LEAN_READ_ENVELOPE_ECHO_KEYS.has(key)));return projected.has_more!==!0&&delete projected.next_cursor,projected}function projectEmptyCheckDetails(value){return!isPlainObject(value)||value.ok!==!0||!isPlainObject(value.verdict)||value.verdict.authority!=="ok"||!Array.isArray(value.checks)?value:{...value,checks:value.checks.map(omitEmptySuccessfulCheckDetails)}}function omitEmptySuccessfulCheckDetails(check){if(!isPlainObject(check)||check.ok!==!0||!isPlainObject(check.details)||Object.keys(check.details).length!==0)return check;const{details:_details,...rest}=check;return rest}function formatBuiltInOutput(result,format,lean=!1,toon={}){if(result=prepareWellFormedOutputText(result),format==="json"){const value=lean?projectLeanJsonValue(result):result,briefList=isPlainObject(result)&&isPlainObject(result.projection)&&result.projection.mode==="brief"&&Array.isArray(result.items);return`${JSON.stringify(value,null,briefList?void 0:2)}
12
- `}const compactedToon=restorePositionalRows(result,restoreRequestedEmptyCollections(result,compactToonValue(projectEmptyCheckDetails(projectPmBriefSearchEnvelope(projectPmBriefListEnvelope(result))),TOON_COMPACTION_POLICY),toon.preserveEmptyItemCollections===!0),toon.positionalRowPaths??[]);return compactedToon===void 0?`{}
13
- `:`${renderToonValue(compactedToon,0)}
14
- `}const TOON_COMPACTION_POLICY={omitDuplicateCountAliases:!0,preserveRowFacts:!0};function restoreEmptyCollections(source,compacted,preserveEmpty=!1){if(Array.isArray(source)){if(source.length===0)return[];const kept2=Array.isArray(compacted)?compacted:[],aligned=kept2.length===source.length;let next=0;const rows=source.flatMap(row=>{const rowPreservesEmpty=preserveEmpty||isPlainObject(row),dropped=!aligned&&compactToonValue(row,TOON_COMPACTION_POLICY,rowPreservesEmpty)===void 0,restored=restoreEmptyCollections(row,dropped?void 0:kept2[next++],rowPreservesEmpty);return restored===void 0?[]:[restored]});return rows.length>0?rows:compacted}if(!isPlainObject(source))return compacted;const kept=isPlainObject(compacted)?compacted:{},entries=Object.entries(source).flatMap(([key,value])=>{const restored=restoreEmptyCollections(value,Object.hasOwn(kept,key)?kept[key]:void 0,preserveEmpty);return restored===void 0?[]:[[key,restored]]});return entries.length>0||Object.keys(source).length===0?Object.fromEntries(entries):compacted}function restoreRequestedEmptyCollections(source,compacted,preserve){if(!preserve||!isPlainObject(source))return compacted;const base=isPlainObject(compacted)?compacted:{},restored=new Map(Object.keys(source).filter(key=>key==="item"||GET_FACET_ROOTS.has(key)).map(key=>[key,restoreEmptyCollections(source[key],base[key])]));return mergeRestoredEntries(source,base,restored)}function mergeRestoredEntries(source,base,restored){const entries=Object.entries(base).map(([key,value])=>[key,restored.has(key)?restored.get(key):value]),sourceKeys=Object.keys(source);for(const[key,value]of restored){if(Object.hasOwn(base,key)||value===void 0)continue;const later=new Set(sourceKeys.slice(sourceKeys.indexOf(key)+1)),position=entries.findIndex(([entryKey])=>later.has(entryKey));entries.splice(position===-1?entries.length:position,0,[key,value])}return Object.fromEntries(entries)}function restorePositionalRows(source,compacted,paths){if(!isPlainObject(source))return compacted;const restorable=paths.filter(path=>{const rows=source[path];return Array.isArray(rows)&&rows.some(row=>compactToonValue(row,TOON_COMPACTION_POLICY,isPlainObject(row))===void 0)});if(restorable.length===0)return compacted;const base=isPlainObject(compacted)?compacted:{},restored=new Map(restorable.map(path=>[path,source[path].map(row=>compactToonValue(row,TOON_COMPACTION_POLICY,!0))]));return mergeRestoredEntries(source,base,restored)}const COMPLETE_OMISSION_RECEIPT=JSON.stringify({has_omissions:!1,omitted_field_group_count:0,omitted_field_groups:[]});function isCompleteOmissionReceipt(value){const entries=Object.entries(Object(value)).sort(([left],[right])=>left.localeCompare(right));return JSON.stringify(Object.fromEntries(entries))===COMPLETE_OMISSION_RECEIPT}function resolveOutputService(effectiveResult,nativeOutput,options,format){const serviceOverride=nativeOutput?{handled:!1,result:effectiveResult,warnings:[]}:runActiveServiceOverrideSync("output_format",{command:options.command,args:options.commandArgs,command_options:options.commandOptions,global:{...options},pm_root:options.pmRoot,format,options:{...options},result:effectiveResult}),legacyPayloadEchoWarning=serviceOverride.warnings.find(warning=>warning.startsWith("extension_output_format_payload_echo_deprecated:"));return legacyPayloadEchoWarning!==void 0&&writeStderr(`Warning: ${legacyPayloadEchoWarning}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
15
- `),serviceOverride.handled&&typeof serviceOverride.result=="string"?{result:serviceOverride.result,rendered:serviceOverride.result.endsWith(`
16
- `)?serviceOverride.result:`${serviceOverride.result}
17
- `,structuredDeliveryPreserved:!1}:{result:serviceOverride.handled?serviceOverride.result:effectiveResult,rendered:null,structuredDeliveryPreserved:!serviceOverride.handled||isPlainObject(serviceOverride.result)}}function formatEffectiveOutput(effectiveResult,nativeOutput,options,defaultFormat){const activeCommandContext=getActiveCommandContext(),command=options.command??activeCommandContext?.command,commandOptions={...activeCommandContext?.options,...options.commandOptions,...Object.fromEntries([["outputInclude",options.outputInclude],["outputLimit",options.outputLimit],["outputBudget",options.outputBudget],["outputFormat",options.outputFormat],["outputSession",options.outputSession],["outputCursor",options.outputCursor],["outputRowContract",options.outputRowContract]].filter(entry=>entry[1]!==void 0))},format=resolveReadOutputEncoding(command??"",commandOptions)??defaultFormat,resolvedCommandOptions={...commandOptions,resolvedOutputFormat:format},effectiveOptions={...options,command,commandOptions:resolvedCommandOptions},service=resolveOutputService(effectiveResult,nativeOutput,effectiveOptions,format),renderNative=nativeRenderer(format,command,resolvedCommandOptions,options.lean===!0);if(service.rendered!==null)return deliverServiceRendering(service.rendered,{format,renderNative,contract:()=>attachReadOutputContracts(command,resolvedCommandOptions,effectiveResult),effectiveResult,quiet:options.quiet===!0});const outputResult=service.result;propagateContextUsageServingReceipt(effectiveResult,outputResult);const projectedOutputResult=projectLinkedTestReply(command,outputResult,{lean:options.lean===!0,fullContext:commandOptions.checkContext===!0,fullOutput:commandOptions.fullOutput===!0});let nativeFallback=!1;return deliverContractedRead({format,contract:()=>attachReadOutputContracts(command,resolvedCommandOptions,projectedOutputResult),renderDelivered:value=>{if(format==="toon"){const markdownDefault=renderDefaultMarkdownResult(value);if(markdownDefault!==null)return{text:markdownDefault,custom:!1}}const rendererOverride=nativeOutput||nativeFallback||isReadResultOmittedForBudget(value)?{rendered:null}:runActiveRendererOverride(format,value);return rendererOverride.rendered!==null?{text:rendererOverride.rendered.endsWith(`
18
- `)?rendererOverride.rendered:`${rendererOverride.rendered}
19
- `,custom:!0}:{text:renderNative(value),custom:!1}},renderNative,useNativeRendering:()=>{nativeFallback=!0},structuredDeliveryPreserved:service.structuredDeliveryPreserved,tokenAccounting:options.tokenAccounting===!0,quiet:options.quiet===!0,effectiveResult})}function nativeRenderer(format,command,commandOptions,lean){if(format==="json")return value=>formatBuiltInOutput(value,"json",lean);const selectedFields=commandOptions.fields,preserveEmptyItemCollections=command==="get"&&typeof selectedFields=="string"&&selectedFields.trim().length>0,positionalRowPaths=readOutputPositionalRowPaths(command===void 0?void 0:resolveReadOutputSurface(command,commandOptions));return value=>formatBuiltInOutput(value,"toon",!1,{preserveEmptyItemCollections,positionalRowPaths})}function deliverServiceRendering(serviceRendered,delivery){const audited=withDeliveredOutputRenderer(delivery.format,value=>isReadResultOmittedForBudget(value)?delivery.renderNative(value):serviceRendered,delivery.contract);return isReadResultOmittedForBudget(audited)?(process.exitCode||=EXIT_CODE.USAGE,setActiveCommandDeliveryResult(audited,delivery.effectiveResult,!delivery.quiet),delivery.renderNative(audited)):(setActiveCommandResultOmitted(delivery.effectiveResult),serviceRendered)}function deliverContractedRead(delivery){let contracted=withDeliveredOutputRenderer(delivery.format,value=>delivery.renderDelivered(value).text,delivery.contract),unaccounted=delivery.renderDelivered(contracted);unaccounted.custom&&receiptsUnderstateDelivery(contracted,unaccounted.text)&&(delivery.useNativeRendering(),contracted=withDeliveredOutputRenderer(delivery.format,delivery.renderNative,delivery.contract),unaccounted={text:delivery.renderNative(contracted),custom:!1}),isReadResultOmittedForBudget(contracted)&&(process.exitCode||=EXIT_CODE.USAGE);let structuredDeliveryPreserved=delivery.structuredDeliveryPreserved&&!unaccounted.custom;if(!delivery.tokenAccounting)return setActiveCommandDeliveryResult(contracted,delivery.effectiveResult,!delivery.quiet&&structuredDeliveryPreserved),unaccounted.text;const renderResolvedOutput=value=>{const delivered=delivery.renderDelivered(value);return delivered.custom&&(structuredDeliveryPreserved=!1),delivered.text},accountedOutputResult=attachOutputTokenAccounting(contracted,renderResolvedOutput),rendered=renderResolvedOutput(accountedOutputResult);return setActiveCommandDeliveryResult(accountedOutputResult,delivery.effectiveResult,!delivery.quiet&&structuredDeliveryPreserved),rendered}const DELIVERED_TOKEN_RECEIPTS=[["read_output","estimated_tokens"],["context_intent","estimated_tokens"],["read_session","spent_this_call_tokens"]];function receiptsUnderstateDelivery(value,text){const deliveredTokens=Math.ceil(Buffer.byteLength(text,"utf8")/4),record=Object(value);return DELIVERED_TOKEN_RECEIPTS.some(([receipt,field])=>{const section=record[receipt],estimate=isPlainObject(section)?section[field]:void 0;return typeof estimate=="number"&&estimate<deliveredTokens})}function formatOutput(result,options){const commandOverride=runActiveCommandOverride(result),suppressedOutput=isHostOutputSuppressed(commandOverride.result)?commandOverride.result:null,nativeResult=commandOverride.result,nativeOutput=isPlainObject(nativeResult)&&nativeResult[NATIVE_OUTPUT_MARKER]===!0,effectiveResult=suppressedOutput?suppressedOutput.result:stripNativeOutputMarker(commandOverride.result);return setActiveCommandResult(effectiveResult),suppressedOutput?(setActiveCommandResultOmitted(effectiveResult),""):formatEffectiveOutput(effectiveResult,nativeOutput,options,resolveDefaultOutputFormat(options))}function resolveDefaultOutputFormat(options){return options.json===!0||options.json===void 0&&options.defaultOutputFormat==="json"?"json":"toon"}function projectPrintedResult(result,options){return options.idOnly?projectMutationResult(result,{idOnly:!0}):options.fullChangedFields?result:options.noChangedFields?projectMutationResult(result,{changedFields:"compact"}):projectMutationResult(result,{compactEnvelope:!0})}function printResult(result,options){isPlainObject(result)&&Number.isInteger(result.exit_code)&&DECLARED_PROCESS_EXIT_CODES.has(Number(result.exit_code))&&(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=Number(result.exit_code));const rendered=formatOutput(projectPrintedResult(result,options),options);options.quiet||writeStdout(rendered)}function printError(message){const override=runActiveServiceOverrideSync("error_format",{message}),rendered=override.handled&&typeof override.result=="string"?override.result:message;writeStderr(rendered.endsWith(`
20
- `)?rendered:`${rendered}
21
- `)}const outputTestOnly={compactToonValue,renderToonValue};export{formatBuiltInOutput,formatOutput,outputTestOnly,printError,printResult,projectPrintedResult,writeStderr,writeStdout};
11
+ `}const Ce=new Set(["filters","now","projection","sorting"]);function Ee(e){const t=l(e,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!c(t)||!Array.isArray(t.items))return t??null;const n=Object.fromEntries(Object.entries(t).filter(([r])=>!Ce.has(r)));return n.has_more!==!0&&delete n.next_cursor,n}function Ae(e){return!c(e)||e.ok!==!0||!c(e.verdict)||e.verdict.authority!=="ok"||!Array.isArray(e.checks)?e:{...e,checks:e.checks.map(je)}}function je(e){if(!c(e)||e.ok!==!0||!c(e.details)||Object.keys(e.details).length!==0)return e;const{details:t,...n}=e;return n}function q(e,t,n=!1,r={}){if(e=ie(e),t==="json"){const i=n?Ee(e):e,s=c(e)&&c(e.projection)&&e.projection.mode==="brief"&&Array.isArray(e.items);return`${JSON.stringify(i,null,s?void 0:2)}
12
+ `}const o=be(e,Se(e,l(Ae(oe(re(e))),E),r.preserveEmptyItemCollections===!0),r.positionalRowPaths??[]);return o===void 0?`{}
13
+ `:`${_(o,0)}
14
+ `}const E={omitDuplicateCountAliases:!0,preserveRowFacts:!0};function P(e,t,n=!1){if(Array.isArray(e)){if(e.length===0)return[];const i=Array.isArray(t)?t:[],s=i.length===e.length;let u=0;const d=e.flatMap(f=>{const m=n||c(f),O=!s&&l(f,E,m)===void 0,g=P(f,O?void 0:i[u++],m);return g===void 0?[]:[g]});return d.length>0?d:t}if(!c(e))return t;const r=c(t)?t:{},o=Object.entries(e).flatMap(([i,s])=>{const u=P(s,Object.hasOwn(r,i)?r[i]:void 0,n);return u===void 0?[]:[[i,u]]});return o.length>0||Object.keys(e).length===0?Object.fromEntries(o):t}function Se(e,t,n){if(!n||!c(e))return t;const r=c(t)?t:{},o=new Map(Object.keys(e).filter(i=>i==="item"||ee.has(i)).map(i=>[i,P(e[i],r[i])]));return W(e,r,o)}function W(e,t,n){const r=Object.entries(t).map(([i,s])=>[i,n.has(i)?n.get(i):s]),o=Object.keys(e);for(const[i,s]of n){if(Object.hasOwn(t,i)||s===void 0)continue;const u=new Set(o.slice(o.indexOf(i)+1)),d=r.findIndex(([f])=>u.has(f));r.splice(d===-1?r.length:d,0,[i,s])}return Object.fromEntries(r)}function be(e,t,n){if(!c(e))return t;const r=n.filter(s=>{const u=e[s];return Array.isArray(u)&&u.some(d=>l(d,E,c(d))===void 0)});if(r.length===0)return t;const o=c(t)?t:{},i=new Map(r.map(s=>[s,e[s].map(u=>l(u,E,!0))]));return W(e,o,i)}const xe=JSON.stringify({has_omissions:!1,omitted_field_group_count:0,omitted_field_groups:[]});function Re(e){const t=Object.entries(Object(e)).sort(([n],[r])=>n.localeCompare(r));return JSON.stringify(Object.fromEntries(t))===xe}function we(e,t,n,r){const o=t?{handled:!1,result:e,warnings:[]}:v("output_format",{command:n.command,args:n.commandArgs,command_options:n.commandOptions,global:{...n},pm_root:n.pmRoot,format:r,options:{...n},result:e}),i=o.warnings.find(s=>s.startsWith("extension_output_format_payload_echo_deprecated:"));return i!==void 0&&M(`Warning: ${i}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
15
+ `),o.handled&&typeof o.result=="string"?{result:o.result,rendered:o.result.endsWith(`
16
+ `)?o.result:`${o.result}
17
+ `,structuredDeliveryPreserved:!1}:{result:o.handled?o.result:e,rendered:null,structuredDeliveryPreserved:!o.handled||c(o.result)}}function ye(e,t,n,r){const o=V(),i=n.command??o?.command,s={...o?.options,...n.commandOptions,...Object.fromEntries([["outputInclude",n.outputInclude],["outputLimit",n.outputLimit],["outputBudget",n.outputBudget],["outputFormat",n.outputFormat],["outputSession",n.outputSession],["outputCursor",n.outputCursor],["outputRowContract",n.outputRowContract]].filter(p=>p[1]!==void 0))},u=z(i??"",s)??r,d={...s,resolvedOutputFormat:u},f={...n,command:i,commandOptions:d},m=we(e,t,f,u),O=Te(u,i,d,n.lean===!0);if(m.rendered!==null)return $e(m.rendered,{format:u,renderNative:O,contract:()=>k(i,d,e),effectiveResult:e,quiet:n.quiet===!0});const g=m.result;I(e,g);const J=X(i,g,{lean:n.lean===!0,fullContext:s.checkContext===!0,fullOutput:s.fullOutput===!0});let D=!1;return Pe({format:u,contract:()=>k(i,d,J),renderDelivered:p=>{if(u==="toon"){const N=he(p);if(N!==null)return{text:N,custom:!1}}const h=t||D||C(p)?{rendered:null}:H(u,p);return h.rendered!==null?{text:h.rendered.endsWith(`
18
+ `)?h.rendered:`${h.rendered}
19
+ `,custom:!0}:{text:O(p),custom:!1}},renderNative:O,useNativeRendering:()=>{D=!0},structuredDeliveryPreserved:m.structuredDeliveryPreserved,tokenAccounting:n.tokenAccounting===!0,quiet:n.quiet===!0,effectiveResult:e})}function Te(e,t,n,r){if(e==="json")return u=>q(u,"json",r);const o=n.fields,i=t==="get"&&typeof o=="string"&&o.trim().length>0,s=Z(t===void 0?void 0:Q(t,n));return u=>q(u,"toon",!1,{preserveEmptyItemCollections:i,positionalRowPaths:s})}function $e(e,t){const n=S(t.format,r=>C(r)?t.renderNative(r):e,t.contract);return C(n)?(process.exitCode||=a.USAGE,w(n,t.effectiveResult,!t.quiet),t.renderNative(n)):(R(t.effectiveResult),e)}function Pe(e){let t=S(e.format,u=>e.renderDelivered(u).text,e.contract),n=e.renderDelivered(t);n.custom&&Ne(t,n.text)&&(e.useNativeRendering(),t=S(e.format,e.renderNative,e.contract),n={text:e.renderNative(t),custom:!1}),C(t)&&(process.exitCode||=a.USAGE);let r=e.structuredDeliveryPreserved&&!n.custom;if(!e.tokenAccounting)return w(t,e.effectiveResult,!e.quiet&&r),n.text;const o=u=>{const d=e.renderDelivered(u);return d.custom&&(r=!1),d.text},i=Y(t,o),s=o(i);return w(i,e.effectiveResult,!e.quiet&&r),s}const De=[["read_output","estimated_tokens"],["context_intent","estimated_tokens"],["read_session","spent_this_call_tokens"]];function Ne(e,t){const n=Math.ceil(Buffer.byteLength(t,"utf8")/4),r=Object(e);return De.some(([o,i])=>{const s=r[o],u=c(s)?s[i]:void 0;return typeof u=="number"&&u<n})}function ve(e,t){const n=G(e),r=K(n.result)?n.result:null,o=n.result,i=c(o)&&o[x]===!0,s=r?r.result:ce(n.result);return A(s),r?(R(s),""):ye(s,i,t,ke(t))}function ke(e){return e.json===!0||e.json===void 0&&e.defaultOutputFormat==="json"?"json":"toon"}function Ie(e,t){return t.idOnly?j(e,{idOnly:!0}):t.fullChangedFields?e:t.noChangedFields?j(e,{changedFields:"compact"}):j(e,{compactEnvelope:!0})}function et(e,t){c(e)&&Number.isInteger(e.exit_code)&&se.has(Number(e.exit_code))&&(process.exitCode===void 0||process.exitCode===a.SUCCESS)&&(process.exitCode=Number(e.exit_code));const n=ve(Ie(e,t),t);t.quiet||le(n)}function tt(e){const t=v("error_format",{message:e}),n=t.handled&&typeof t.result=="string"?t.result:e;M(n.endsWith(`
20
+ `)?n:`${n}
21
+ `)}const nt={compactToonValue:l,renderToonValue:_};export{q as formatBuiltInOutput,ve as formatOutput,nt as outputTestOnly,tt as printError,et as printResult,Ie as projectPrintedResult,M as writeStderr,le as writeStdout};
22
22
  //# sourceMappingURL=output.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]="baa27a48-c538-574c-9d05-1f1c0f4f429c")}catch{}})();function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function resolveQueryProjectionLabel(options){return options.brief===!0?"brief":typeof options.fields=="string"&&options.fields.trim().length>0||Array.isArray(options.fields)&&options.fields.length>0?"fields":options.compact===!0?"compact":"full"}function withQuerySummary(result,options){const requestedLabel=resolveQueryProjectionLabel(options),projection=requestedLabel==="brief"?requestedLabel:isRecord(result.projection)&&typeof result.projection.mode=="string"?result.projection.mode:requestedLabel;return{...result,query_summary:{filters:isRecord(result.filters)?result.filters:{},projection}}}export{resolveQueryProjectionLabel,withQuerySummary};
1
+ function t(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function n(r){return r.brief===!0?"brief":typeof r.fields=="string"&&r.fields.trim().length>0||Array.isArray(r.fields)&&r.fields.length>0?"fields":r.compact===!0?"compact":"full"}function o(r,i){const e=n(i),f=e==="brief"?e:t(r.projection)&&typeof r.projection.mode=="string"?r.projection.mode:e;return{...r,query_summary:{filters:t(r.filters)?r.filters:{},projection:f}}}export{n as resolveQueryProjectionLabel,o as withQuerySummary};
2
2
  //# sourceMappingURL=query-summary.js.map
@@ -1,4 +1,4 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c628dcf9-d98f-566e-9f93-cc81e737691c")}catch{}})();function resolveColumns(rows){const columns=[],seen=new Set;for(const row of rows)for(const key of Object.keys(row))seen.has(key)||(seen.add(key),columns.push(key));return columns}function renderCell(value){return value==null?"":Array.isArray(value)?value.map(entry=>renderCell(entry)).join(";"):typeof value=="object"?JSON.stringify(value):String(value)}function escapeCsvField(value){return/[",\r\n]/.test(value)?`"${value.replace(/"/g,'""')}"`:value}function renderRowsAsCsv(rows){if(rows.length===0)return"";const columns=resolveColumns(rows),lines=[columns.map(column=>escapeCsvField(column)).join(",")];for(const row of rows)lines.push(columns.map(column=>escapeCsvField(renderCell(row[column]))).join(","));return lines.join(`
2
- `)}function renderRowsAsTable(rows){if(rows.length===0)return"";const columns=resolveColumns(rows),cells=rows.map(row=>columns.map(column=>renderCell(row[column]))),widths=columns.map((column,index)=>Math.max(column.length,...cells.map(rowCells=>rowCells[index].length))),pad=(value,index)=>value.padEnd(widths[index]),lines=[columns.map((column,index)=>pad(column,index)).join(" | ")];lines.push(widths.map(width=>"-".repeat(width)).join("-+-"));for(const rowCells of cells)lines.push(rowCells.map((value,index)=>pad(value,index)).join(" | "));return lines.join(`
3
- `)}export{renderRowsAsCsv,renderRowsAsTable};
1
+ function u(n){const t=[],e=new Set;for(const s of n)for(const i of Object.keys(s))e.has(i)||(e.add(i),t.push(i));return t}function p(n){return n==null?"":Array.isArray(n)?n.map(t=>p(t)).join(";"):typeof n=="object"?JSON.stringify(n):String(n)}function m(n){return/[",\r\n]/.test(n)?`"${n.replace(/"/g,'""')}"`:n}function a(n){if(n.length===0)return"";const t=u(n),e=[t.map(s=>m(s)).join(",")];for(const s of n)e.push(t.map(i=>m(p(s[i]))).join(","));return e.join(`
2
+ `)}function l(n){if(n.length===0)return"";const t=u(n),e=n.map(o=>t.map(r=>p(o[r]))),s=t.map((o,r)=>Math.max(o.length,...e.map(f=>f[r].length))),i=(o,r)=>o.padEnd(s[r]),c=[t.map((o,r)=>i(o,r)).join(" | ")];c.push(s.map(o=>"-".repeat(o)).join("-+-"));for(const o of e)c.push(o.map((r,f)=>i(r,f)).join(" | "));return c.join(`
3
+ `)}export{a as renderRowsAsCsv,l as renderRowsAsTable};
4
4
  //# sourceMappingURL=tabular.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]="74b72dd8-0877-55a4-9c80-d043f19e1f96")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{pathExists}from"../fs/fs-utils.js";import{isPathWithinDirectory}from"../fs/path-utils.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const PM_PACKAGE_RESOURCE_KINDS=["extensions","docs","examples","assets","prompts"],PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS=Object.freeze({extensions:Object.freeze([".agents/pm/extensions","extensions",".custom/pm-extensions",".custom/pm-extension"]),docs:Object.freeze(["docs","documentation"]),examples:Object.freeze(["examples","docs/examples"]),assets:Object.freeze(["assets",".agents/pm/assets"]),prompts:Object.freeze(["prompts",".agents/pm/prompts"])});function isKnownPackageResourceKind(value){return PM_PACKAGE_RESOURCE_KINDS.includes(value)}function normalizePackageResourceEntries(kind,raw){if(raw==null)return[];const entries=Array.isArray(raw)?raw:[raw],normalized=[];for(const entry of entries){if(typeof entry!="string"||entry.trim().length===0)throw new PmCliError(`Package manifest field pm.${kind} must contain string paths.`,EXIT_CODE.USAGE);normalized.push(entry.trim())}return[...new Set(normalized)].sort((left,right)=>left.localeCompare(right))}function normalizePackageResourceMap(raw){if(raw==null)return{};if(typeof raw!="object"||Array.isArray(raw))throw new PmCliError("Package manifest field pm must be an object.",EXIT_CODE.USAGE);const resources={},candidate=raw;for(const[key,value]of Object.entries(candidate)){if(!isKnownPackageResourceKind(key))continue;const entries=normalizePackageResourceEntries(key,value);entries.length>0&&(resources[key]=entries)}return resources}function readStringField(source,key){const value=source[key];return typeof value=="string"&&value.trim().length>0?value.trim():void 0}function normalizeStringArray(raw){if(!Array.isArray(raw))return;const values=raw.map(value=>typeof value=="string"?value.trim():"").filter(value=>value.length>0);return values.length>0?[...new Set(values)].sort((left,right)=>left.localeCompare(right)):void 0}function readUrlLikeField(raw){if(typeof raw=="string"&&raw.trim().length>0)return raw.trim();if(typeof raw=="object"&&raw!==null&&!Array.isArray(raw)){const value=raw.url;return typeof value=="string"&&value.trim().length>0?value.trim():void 0}}function normalizeCatalogLinks(raw){if(typeof raw!="object"||raw===null||Array.isArray(raw))return;const source=raw,links={docs:readStringField(source,"docs"),npm:readStringField(source,"npm"),repository:readStringField(source,"repository"),report:readStringField(source,"report")};return Object.values(links).some(value=>typeof value=="string")?links:void 0}function normalizeCatalogMedia(raw){if(typeof raw!="object"||raw===null||Array.isArray(raw))return;const source=raw,media={image:readStringField(source,"image"),video:readStringField(source,"video")};return Object.values(media).some(value=>typeof value=="string")?media:void 0}function normalizePackageCatalogMetadata(raw){if(typeof raw!="object"||raw===null||Array.isArray(raw))return;const source=raw,catalog={display_name:readStringField(source,"display_name")??readStringField(source,"displayName"),category:readStringField(source,"category"),summary:readStringField(source,"summary"),links:normalizeCatalogLinks(source.links),media:normalizeCatalogMedia(source.media),tags:normalizeStringArray(source.tags)};return Object.values(catalog).some(value=>value!==void 0)?catalog:void 0}async function readPmPackageManifest(packageRoot){const packageJsonPath=path.join(packageRoot,"package.json");if(!await pathExists(packageJsonPath))return{source:"convention",resources:{}};let parsed;try{parsed=JSON.parse(await fs.readFile(packageJsonPath,"utf8"))}catch(error){throw new PmCliError(`Failed to parse package manifest at "${packageJsonPath}": ${String(error)}`,EXIT_CODE.USAGE)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new PmCliError(`Package manifest at "${packageJsonPath}" must be a JSON object.`,EXIT_CODE.USAGE);const packageJson=parsed,pmManifest=packageJson.pm,hasPmManifest=pmManifest!=null,pmManifestRecord=typeof pmManifest=="object"&&pmManifest!==null&&!Array.isArray(pmManifest)?pmManifest:{};return{source:hasPmManifest?"pm":"convention",package_json_path:packageJsonPath,package_name:typeof packageJson.name=="string"?packageJson.name:void 0,package_version:typeof packageJson.version=="string"?packageJson.version:void 0,package_private:packageJson.private===!0,package_description:typeof packageJson.description=="string"?packageJson.description:void 0,package_keywords:normalizeStringArray(packageJson.keywords),package_homepage:typeof packageJson.homepage=="string"?packageJson.homepage:void 0,package_repository_url:readUrlLikeField(packageJson.repository),package_bugs_url:readUrlLikeField(packageJson.bugs),aliases:normalizeStringArray(pmManifestRecord.aliases),resources:normalizePackageResourceMap(pmManifest),catalog:normalizePackageCatalogMetadata(pmManifestRecord.catalog)}}async function listExtensionManifestDirectories(parentDirectory){if(!await pathExists(parentDirectory))return[];const entries=await fs.readdir(parentDirectory,{withFileTypes:!0}),candidates=[];for(const entry of entries){if(!entry.isDirectory())continue;const directory=path.join(parentDirectory,entry.name);await pathExists(path.join(directory,"manifest.json"))&&candidates.push(directory)}return candidates.sort((left,right)=>left.localeCompare(right))}async function collectPackageExtensionDirectories(packageRoot){if(await pathExists(path.join(packageRoot,"manifest.json")))return[packageRoot];const manifestEntries=(await readPmPackageManifest(packageRoot)).resources.extensions??[],discovered=new Set;for(const entry of manifestEntries){if(entry.includes("*")||entry.startsWith("!"))throw new PmCliError(`Package extension entry "${entry}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,EXIT_CODE.USAGE);const absolute=path.resolve(packageRoot,entry);if(!isPathWithinDirectory(packageRoot,absolute))throw new PmCliError(`Package extension entry "${entry}" resolves outside package root.`,EXIT_CODE.USAGE);if(await pathExists(path.join(absolute,"manifest.json"))){discovered.add(absolute);continue}for(const child of await listExtensionManifestDirectories(absolute))discovered.add(child)}if(manifestEntries.length===0)for(const root of PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS.extensions)for(const child of await listExtensionManifestDirectories(path.join(packageRoot,root)))discovered.add(child);return[...discovered].sort((left,right)=>left.localeCompare(right))}export{PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,PM_PACKAGE_RESOURCE_KINDS,collectPackageExtensionDirectories,readPmPackageManifest};
1
+ import d from"node:fs/promises";import a from"node:path";import{pathExists as u}from"../fs/fs-utils.js";import{isPathWithinDirectory as h}from"../fs/path-utils.js";import{EXIT_CODE as c}from"../shared/constants.js";import{PmCliError as f}from"../shared/errors.js";const j=["extensions","docs","examples","assets","prompts"],A=Object.freeze({extensions:Object.freeze([".agents/pm/extensions","extensions",".custom/pm-extensions",".custom/pm-extension"]),docs:Object.freeze(["docs","documentation"]),examples:Object.freeze(["examples","docs/examples"]),assets:Object.freeze(["assets",".agents/pm/assets"]),prompts:Object.freeze(["prompts",".agents/pm/prompts"])});function k(e){return j.includes(e)}function b(e,t){if(t==null)return[];const o=Array.isArray(t)?t:[t],n=[];for(const r of o){if(typeof r!="string"||r.trim().length===0)throw new f(`Package manifest field pm.${e} must contain string paths.`,c.USAGE);n.push(r.trim())}return[...new Set(n)].sort((r,s)=>r.localeCompare(s))}function x(e){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new f("Package manifest field pm must be an object.",c.USAGE);const t={},o=e;for(const[n,r]of Object.entries(o)){if(!k(n))continue;const s=b(n,r);s.length>0&&(t[n]=s)}return t}function i(e,t){const o=e[t];return typeof o=="string"&&o.trim().length>0?o.trim():void 0}function m(e){if(!Array.isArray(e))return;const t=e.map(o=>typeof o=="string"?o.trim():"").filter(o=>o.length>0);return t.length>0?[...new Set(t)].sort((o,n)=>o.localeCompare(n)):void 0}function l(e){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(typeof e=="object"&&e!==null&&!Array.isArray(e)){const t=e.url;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}}function _(e){if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e,o={docs:i(t,"docs"),npm:i(t,"npm"),repository:i(t,"repository"),report:i(t,"report")};return Object.values(o).some(n=>typeof n=="string")?o:void 0}function E(e){if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e,o={image:i(t,"image"),video:i(t,"video")};return Object.values(o).some(n=>typeof n=="string")?o:void 0}function P(e){if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e,o={display_name:i(t,"display_name")??i(t,"displayName"),category:i(t,"category"),summary:i(t,"summary"),links:_(t.links),media:E(t.media),tags:m(t.tags)};return Object.values(o).some(n=>n!==void 0)?o:void 0}async function O(e){const t=a.join(e,"package.json");if(!await u(t))return{source:"convention",resources:{}};let o;try{o=JSON.parse(await d.readFile(t,"utf8"))}catch(y){throw new f(`Failed to parse package manifest at "${t}": ${String(y)}`,c.USAGE)}if(typeof o!="object"||o===null||Array.isArray(o))throw new f(`Package manifest at "${t}" must be a JSON object.`,c.USAGE);const n=o,r=n.pm,s=r!=null,p=typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{};return{source:s?"pm":"convention",package_json_path:t,package_name:typeof n.name=="string"?n.name:void 0,package_version:typeof n.version=="string"?n.version:void 0,package_private:n.private===!0,package_description:typeof n.description=="string"?n.description:void 0,package_keywords:m(n.keywords),package_homepage:typeof n.homepage=="string"?n.homepage:void 0,package_repository_url:l(n.repository),package_bugs_url:l(n.bugs),aliases:m(p.aliases),resources:x(r),catalog:P(p.catalog)}}async function g(e){if(!await u(e))return[];const t=await d.readdir(e,{withFileTypes:!0}),o=[];for(const n of t){if(!n.isDirectory())continue;const r=a.join(e,n.name);await u(a.join(r,"manifest.json"))&&o.push(r)}return o.sort((n,r)=>n.localeCompare(r))}async function G(e){if(await u(a.join(e,"manifest.json")))return[e];const o=(await O(e)).resources.extensions??[],n=new Set;for(const r of o){if(r.includes("*")||r.startsWith("!"))throw new f(`Package extension entry "${r}" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,c.USAGE);const s=a.resolve(e,r);if(!h(e,s))throw new f(`Package extension entry "${r}" resolves outside package root.`,c.USAGE);if(await u(a.join(s,"manifest.json"))){n.add(s);continue}for(const p of await g(s))n.add(p)}if(o.length===0)for(const r of A.extensions)for(const s of await g(a.join(e,r)))n.add(s);return[...n].sort((r,s)=>r.localeCompare(s))}export{A as PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,j as PM_PACKAGE_RESOURCE_KINDS,G as collectPackageExtensionDirectories,O as readPmPackageManifest};
2
2
  //# sourceMappingURL=manifest.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]="efea1aa1-1ad1-5f53-a3a5-b83803d9deb1")}catch{}})();import fs from"node:fs";import path from"node:path";import{fileURLToPath}from"node:url";const PM_CLI_PACKAGE_NAME="@unbrained/pm-cli";function packageJsonNamesPmCli(packageJsonPath){try{return JSON.parse(fs.readFileSync(packageJsonPath,"utf8")).name===PM_CLI_PACKAGE_NAME}catch{return!1}}function findPmPackageRootFromPath(startPath){let current=fs.existsSync(startPath)&&fs.statSync(startPath).isDirectory()?path.resolve(startPath):path.dirname(path.resolve(startPath));for(;;){const packageJsonPath=path.join(current,"package.json");if(fs.existsSync(packageJsonPath)&&packageJsonNamesPmCli(packageJsonPath))return current;const parent=path.dirname(current);if(parent===current)return;current=parent}}function resolvePmPackageRootFromModule(metaUrl,fallbackRelativeSegments=[]){const modulePath=fileURLToPath(metaUrl);return findPmPackageRootFromPath(modulePath)||path.resolve(path.dirname(modulePath),...fallbackRelativeSegments)}function resolvePmCliVersion(metaUrl,fallbackRelativeSegments=[]){try{const packageJsonPath=path.join(resolvePmPackageRootFromModule(metaUrl,fallbackRelativeSegments),"package.json");if(!fs.existsSync(packageJsonPath))return;const parsed=JSON.parse(fs.readFileSync(packageJsonPath,"utf8"));return typeof parsed.version=="string"&&parsed.version.trim().length>0?parsed.version:void 0}catch{return}}function resolveConfiguredPmPackageRoot(env=process.env,envName="PM_CLI_PACKAGE_ROOT",metaUrl,fallbackRelativeSegments=[]){const envRoot=env[envName];return typeof envRoot=="string"&&envRoot.trim().length>0?path.resolve(envRoot.trim()):metaUrl?resolvePmPackageRootFromModule(metaUrl,fallbackRelativeSegments):process.cwd()}export{findPmPackageRootFromPath,resolveConfiguredPmPackageRoot,resolvePmCliVersion,resolvePmPackageRootFromModule};
1
+ import i from"node:fs";import t from"node:path";import{fileURLToPath as a}from"node:url";const u="@unbrained/pm-cli";function f(e){try{return JSON.parse(i.readFileSync(e,"utf8")).name===u}catch{return!1}}function d(e){let n=i.existsSync(e)&&i.statSync(e).isDirectory()?t.resolve(e):t.dirname(t.resolve(e));for(;;){const r=t.join(n,"package.json");if(i.existsSync(r)&&f(r))return n;const o=t.dirname(n);if(o===n)return;n=o}}function c(e,n=[]){const r=a(e),o=d(r);return o||t.resolve(t.dirname(r),...n)}function P(e,n=[]){try{const r=t.join(c(e,n),"package.json");if(!i.existsSync(r))return;const o=JSON.parse(i.readFileSync(r,"utf8"));return typeof o.version=="string"&&o.version.trim().length>0?o.version:void 0}catch{return}}function g(e=process.env,n="PM_CLI_PACKAGE_ROOT",r,o=[]){const s=e[n];return typeof s=="string"&&s.trim().length>0?t.resolve(s.trim()):r?c(r,o):process.cwd()}export{d as findPmPackageRootFromPath,g as resolveConfiguredPmPackageRoot,P as resolvePmCliVersion,c as resolvePmPackageRootFromModule};
2
2
  //# sourceMappingURL=root.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]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();import{MAX_WORKFLOW_POLICIES,MAX_WORKFLOW_POLICY_TERMS}from"./workflow-policy.js";const text={type:"string",minLength:1,maxLength:128,pattern:"\\S"},terms={type:"array",minItems:1,maxItems:MAX_WORKFLOW_POLICY_TERMS,items:text},fields={...terms,items:{...text,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},WORKFLOW_POLICY_SCHEMA={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(key=>[key,terms])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:text,id:text}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:terms}},...["field_writers","approval"].map(kind=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:kind},fields,authors:terms}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:MAX_WORKFLOW_POLICY_TERMS,items:{type:"array",minItems:2,maxItems:2,items:text}}}}]}}},WORKFLOW_POLICY_DOCUMENT_SCHEMA={$schema:"https://json-schema.org/draft/2020-12/schema",title:"pm workflow policy registry",type:"object",additionalProperties:!1,required:["version","policies"],properties:{version:{const:1},enforcement:{enum:["advise","refuse"],default:"advise"},policies:{type:"array",maxItems:MAX_WORKFLOW_POLICIES,items:WORKFLOW_POLICY_SCHEMA}}};export{WORKFLOW_POLICY_DOCUMENT_SCHEMA,WORKFLOW_POLICY_SCHEMA};
1
+ import{MAX_WORKFLOW_POLICIES as o,MAX_WORKFLOW_POLICY_TERMS as i}from"./workflow-policy.js";const e={type:"string",minLength:1,maxLength:128,pattern:"\\S"},t={type:"array",minItems:1,maxItems:i,items:e},s={...t,items:{...e,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},a={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(r=>[r,t])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:e,id:e}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:s}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:t}},...["field_writers","approval"].map(r=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:r},fields:s,authors:t}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:i,items:{type:"array",minItems:2,maxItems:2,items:e}}}}]}}},p={$schema:"https://json-schema.org/draft/2020-12/schema",title:"pm workflow policy registry",type:"object",additionalProperties:!1,required:["version","policies"],properties:{version:{const:1},enforcement:{enum:["advise","refuse"],default:"advise"},policies:{type:"array",maxItems:o,items:a}}};export{p as WORKFLOW_POLICY_DOCUMENT_SCHEMA,a as WORKFLOW_POLICY_SCHEMA};
2
2
  //# sourceMappingURL=workflow-policy-schema.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]="9fa43d4b-3e4e-5d96-a256-0ce743f52372")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{renderPmCommand}from"../shared/command-line.js";import{canonicalizeCommandOptionKey,commandOptionFlagLabel}from"../item/type-registry.js";import{isUtf8}from"node:buffer";import{isFileMissingError}from"../fs/fs-utils.js";import{appendWorkspaceAuditEvent}from"../history/workspace-history.js";import{verifyHistoryChain}from"../history/replay.js";import{PmCliError}from"../shared/errors.js";import{EXIT_CODE}from"../shared/constants.js";import{getHistoryPath}from"../store/paths.js";import{ownedTransactionCompensation}from"../store/item-mutation-precondition.js";import{evaluateWorkflowPolicies,parseWorkflowPolicyDocument,workflowPolicyApplies}from"./workflow-policy.js";const MAX_WORKFLOW_POLICY_BYTES=1048576,MAX_WORKFLOW_APPROVAL_HISTORY_BYTES=4194304;async function readBoundedPolicyFile(file,maxBytes){let ancestor=path.dirname(file);for(;ancestor!==path.parse(file).root;){const stats=await fs.stat(ancestor).catch(error=>{if(isFileMissingError(error))return null;throw error});if(stats!==null){if(!stats.isDirectory())throw new PmCliError("Workflow policy storage ancestor must be a directory.",EXIT_CODE.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Restore the policy or approval history directory before retrying."]});break}ancestor=path.dirname(ancestor)}const handle=await fs.open(file,"r").catch(error=>{if(isFileMissingError(error))return null;throw error});if(handle===null)return null;try{const size=(await handle.stat()).size,buffer=Buffer.alloc(Math.min(maxBytes,size)+1);let offset=0;for(;offset<buffer.length;){const read=await handle.read(buffer,offset,buffer.length-offset,offset);if(read.bytesRead===0)break;offset+=read.bytesRead}if(offset===buffer.length||!isUtf8(buffer.subarray(0,offset)))throw new PmCliError("Workflow policy input exceeds its byte bound or is not valid UTF-8.",EXIT_CODE.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Inspect the policy and approval history; reduce the declaration or use verified history compaction before retrying."]});return buffer.toString("utf8",0,offset)}finally{await handle.close()}}function decodeWorkflowPolicyDocument(raw){if(raw===null)return{version:1,enforcement:"advise",policies:[]};let value;try{value=JSON.parse(raw)}catch{throw new PmCliError("schema/policies.json must contain valid JSON.",EXIT_CODE.CONFLICT,{code:"workflow_policy_registry_invalid",nextSteps:["Restore valid policy JSON before retrying the mutation."]})}return parseWorkflowPolicyDocument(value)}async function readWorkflowPolicies(pmRoot){return decodeWorkflowPolicyDocument(await readBoundedPolicyFile(path.join(pmRoot,"schema","policies.json"),MAX_WORKFLOW_POLICY_BYTES))}async function readWorkflowApprovals(pmRoot,id){const raw=await readBoundedPolicyFile(getHistoryPath(pmRoot,id),MAX_WORKFLOW_APPROVAL_HISTORY_BYTES);if(raw===null)return[];let entries;try{if(entries=raw.split(/\r?\n/).filter(line=>line.trim()).map(line=>JSON.parse(line)),!verifyHistoryChain(entries).ok)throw new Error("invalid chain")}catch{throw new PmCliError("Approval evidence requires a valid item history chain.",EXIT_CODE.CONFLICT,{code:"workflow_policy_approval_history_invalid",nextSteps:[`Run pm history ${id} --verify before recording or using an approval.`]})}return entries.flatMap(entry=>{const approval=entry.context?.workflow_approval;if(entry.op!=="policy_approve"||entry.record_hash_version!==1||typeof entry.record_hash!="string"||typeof approval!="object"||approval===null)return[];const record=approval;return typeof record.policy_fingerprint!="string"||typeof record.content_fingerprint!="string"?[]:[{policy_fingerprint:record.policy_fingerprint,content_fingerprint:record.content_fingerprint,author:entry.author}]})}async function evaluateWorkspacePolicies(pmRoot,document,input){const needsApproval=input.before?.status!==input.after?.status&&document.policies.some(policy=>policy.rule.kind==="approval"&&workflowPolicyApplies(policy,input)),id=input.before?.id??input.after?.id,approvals=needsApproval&&typeof id=="string"?await readWorkflowApprovals(pmRoot,id):[];return evaluateWorkflowPolicies(document,{...input,approvals})}function recordCompensationOverrides(params,refused){if(params.dryRun===!0)return!1;const compensation=ownedTransactionCompensation(params.pmRoot,[params.before?.metadata.id,params.after?.metadata.id],params.operation);return compensation===void 0?!1:(compensation.overrides.push(...refused.map(decision=>({source:"workflow_policy",policy_id:decision.policy_id,rule:decision.rule}))),!0)}async function enforceWorkflowMutation(params){const document=await readWorkflowPolicies(params.pmRoot),result=await evaluateWorkspacePolicies(params.pmRoot,document,{operation:params.operation,author:params.author,before:params.before?{...params.before.metadata,body:params.before.body}:null,after:params.after?{...params.after.metadata,body:params.after.body}:null});if(result.allowed)return result;const refused=result.decisions.filter(decision=>!decision.satisfied&&decision.effect==="refuse");return recordCompensationOverrides(params,refused)?result:refuseWorkflowMutation(params,document,result,refused)}async function refuseWorkflowMutation(params,document,result,refused){const sideEffects=[];let auditNotice="";if(!params.dryRun)try{const audit=await appendWorkspaceAuditEvent({pmRoot:params.pmRoot,op:"policy_refused",author:params.author,context:{item_id:params.after?.metadata.id??params.before?.metadata.id,operation:params.operation,workflow_policies:result.decisions},message:"Workflow policy refused a proposed item mutation.",lockTtlSeconds:params.settings.locks.ttl_seconds,lockWaitMs:params.settings.locks.wait_ms});sideEffects.push({path:"history/_workspace.jsonl",op:"policy_refused",record_hash:audit.entry.record_hash}),auditNotice=" Audit appended to tracker-relative history/_workspace.jsonl; retain it with the workspace changes. Each refused attempt records its own audit event."}catch(cause){const error=new PmCliError("Workflow policy refusal could not be recorded in workspace history.",EXIT_CODE.CONFLICT,{code:"workflow_policy_audit_failed",nextSteps:["Resolve workspace-history lock or storage failures, then retry the refused mutation; no item changes were written."]});throw error.cause=cause,error}const violations=refused.slice(0,3).map(decision=>({policy_id:decision.policy_id,rule:decision.rule,description:document.policies.find(policy=>policy.id===decision.policy_id).description,missing_fields:decision.missing_fields})),missing=[...new Set(violations.flatMap(decision=>decision.missing_fields))],summary=violations.map(decision=>`${decision.policy_id} (${decision.rule})`).join(", "),remaining=refused.length>3?` and ${refused.length-3} more`:"",itemId=params.after?.metadata.id??params.before.metadata.id,fieldSteps=missing.map(field=>{if(params.before===null)return`Supply ${field} in the original ${params.operation} request, then retry; the item was not created.`;const option=canonicalizeCommandOptionKey("update",field);return option===void 0?`Supply ${field} using its declared SDK or package mutation contract, then retry.`:renderPmCommand(["update",itemId,commandOptionFlagLabel("update",option),`<${field}>`,"--pm-path",path.resolve(params.pmRoot)])});throw new PmCliError(`Workflow policy refused ${params.operation}: ${summary}${remaining}.${missing.length?` Missing: ${missing.join(", ")}.`:""}${auditNotice}`,EXIT_CODE.CONFLICT,{code:"workflow_policy_refused",side_effects:sideEffects,reason:violations.map(decision=>decision.policy_id).join(","),policy_violations:violations,policy_violation_count:refused.length,required:missing.length?`Supply missing fields: ${missing.join(", ")}, then retry the refused mutation.`:"Satisfy the declared workflow policy before retrying.",why:violations.map(decision=>decision.description).filter(Boolean).join(" ")||void 0,recovery:{missing_required_fields:missing},nextSteps:[...fieldSteps,...new Set(refused.slice(0,3).filter(decision=>decision.missing_fields.length===0).map(decision=>decision.remediation)),...refused.length>3?[`Inspect all policies with pm schema policies before retrying ${params.operation}.`]:[]]})}export{MAX_WORKFLOW_APPROVAL_HISTORY_BYTES,MAX_WORKFLOW_POLICY_BYTES,decodeWorkflowPolicyDocument,enforceWorkflowMutation,evaluateWorkspacePolicies,readWorkflowApprovals,readWorkflowPolicies};
1
+ import u from"node:fs/promises";import d from"node:path";import{renderPmCommand as k}from"../shared/command-line.js";import{canonicalizeCommandOptionKey as v,commandOptionFlagLabel as b}from"../item/type-registry.js";import{isUtf8 as S}from"node:buffer";import{isFileMissingError as y}from"../fs/fs-utils.js";import{appendWorkspaceAuditEvent as O}from"../history/workspace-history.js";import{verifyHistoryChain as C}from"../history/replay.js";import{PmCliError as p}from"../shared/errors.js";import{EXIT_CODE as f}from"../shared/constants.js";import{getHistoryPath as W}from"../store/paths.js";import{ownedTransactionCompensation as R}from"../store/item-mutation-precondition.js";import{evaluateWorkflowPolicies as x,parseWorkflowPolicyDocument as $,workflowPolicyApplies as P}from"./workflow-policy.js";const T=1048576,F=4194304;async function h(e,l){let r=d.dirname(e);for(;r!==d.parse(e).root;){const o=await u.stat(r).catch(a=>{if(y(a))return null;throw a});if(o!==null){if(!o.isDirectory())throw new p("Workflow policy storage ancestor must be a directory.",f.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Restore the policy or approval history directory before retrying."]});break}r=d.dirname(r)}const i=await u.open(e,"r").catch(o=>{if(y(o))return null;throw o});if(i===null)return null;try{const o=(await i.stat()).size,a=Buffer.alloc(Math.min(l,o)+1);let n=0;for(;n<a.length;){const s=await i.read(a,n,a.length-n,n);if(s.bytesRead===0)break;n+=s.bytesRead}if(n===a.length||!S(a.subarray(0,n)))throw new p("Workflow policy input exceeds its byte bound or is not valid UTF-8.",f.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Inspect the policy and approval history; reduce the declaration or use verified history compaction before retrying."]});return a.toString("utf8",0,n)}finally{await i.close()}}function I(e){if(e===null)return{version:1,enforcement:"advise",policies:[]};let l;try{l=JSON.parse(e)}catch{throw new p("schema/policies.json must contain valid JSON.",f.CONFLICT,{code:"workflow_policy_registry_invalid",nextSteps:["Restore valid policy JSON before retrying the mutation."]})}return $(l)}async function j(e){return I(await h(d.join(e,"schema","policies.json"),T))}async function L(e,l){const r=await h(W(e,l),F);if(r===null)return[];let i;try{if(i=r.split(/\r?\n/).filter(o=>o.trim()).map(o=>JSON.parse(o)),!C(i).ok)throw new Error("invalid chain")}catch{throw new p("Approval evidence requires a valid item history chain.",f.CONFLICT,{code:"workflow_policy_approval_history_invalid",nextSteps:[`Run pm history ${l} --verify before recording or using an approval.`]})}return i.flatMap(o=>{const a=o.context?.workflow_approval;if(o.op!=="policy_approve"||o.record_hash_version!==1||typeof o.record_hash!="string"||typeof a!="object"||a===null)return[];const n=a;return typeof n.policy_fingerprint!="string"||typeof n.content_fingerprint!="string"?[]:[{policy_fingerprint:n.policy_fingerprint,content_fingerprint:n.content_fingerprint,author:o.author}]})}async function N(e,l,r){const i=r.before?.status!==r.after?.status&&l.policies.some(n=>n.rule.kind==="approval"&&P(n,r)),o=r.before?.id??r.after?.id,a=i&&typeof o=="string"?await L(e,o):[];return x(l,{...r,approvals:a})}function A(e,l){if(e.dryRun===!0)return!1;const r=R(e.pmRoot,[e.before?.metadata.id,e.after?.metadata.id],e.operation);return r===void 0?!1:(r.overrides.push(...l.map(i=>({source:"workflow_policy",policy_id:i.policy_id,rule:i.rule}))),!0)}async function Q(e){const l=await j(e.pmRoot),r=await N(e.pmRoot,l,{operation:e.operation,author:e.author,before:e.before?{...e.before.metadata,body:e.before.body}:null,after:e.after?{...e.after.metadata,body:e.after.body}:null});if(r.allowed)return r;const i=r.decisions.filter(o=>!o.satisfied&&o.effect==="refuse");return A(e,i)?r:E(e,l,r,i)}async function E(e,l,r,i){const o=[];let a="";if(!e.dryRun)try{const t=await O({pmRoot:e.pmRoot,op:"policy_refused",author:e.author,context:{item_id:e.after?.metadata.id??e.before?.metadata.id,operation:e.operation,workflow_policies:r.decisions},message:"Workflow policy refused a proposed item mutation.",lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms});o.push({path:"history/_workspace.jsonl",op:"policy_refused",record_hash:t.entry.record_hash}),a=" Audit appended to tracker-relative history/_workspace.jsonl; retain it with the workspace changes. Each refused attempt records its own audit event."}catch(t){const c=new p("Workflow policy refusal could not be recorded in workspace history.",f.CONFLICT,{code:"workflow_policy_audit_failed",nextSteps:["Resolve workspace-history lock or storage failures, then retry the refused mutation; no item changes were written."]});throw c.cause=t,c}const n=i.slice(0,3).map(t=>({policy_id:t.policy_id,rule:t.rule,description:l.policies.find(c=>c.id===t.policy_id).description,missing_fields:t.missing_fields})),s=[...new Set(n.flatMap(t=>t.missing_fields))],w=n.map(t=>`${t.policy_id} (${t.rule})`).join(", "),m=i.length>3?` and ${i.length-3} more`:"",_=e.after?.metadata.id??e.before.metadata.id,g=s.map(t=>{if(e.before===null)return`Supply ${t} in the original ${e.operation} request, then retry; the item was not created.`;const c=v("update",t);return c===void 0?`Supply ${t} using its declared SDK or package mutation contract, then retry.`:k(["update",_,b("update",c),`<${t}>`,"--pm-path",d.resolve(e.pmRoot)])});throw new p(`Workflow policy refused ${e.operation}: ${w}${m}.${s.length?` Missing: ${s.join(", ")}.`:""}${a}`,f.CONFLICT,{code:"workflow_policy_refused",side_effects:o,reason:n.map(t=>t.policy_id).join(","),policy_violations:n,policy_violation_count:i.length,required:s.length?`Supply missing fields: ${s.join(", ")}, then retry the refused mutation.`:"Satisfy the declared workflow policy before retrying.",why:n.map(t=>t.description).filter(Boolean).join(" ")||void 0,recovery:{missing_required_fields:s},nextSteps:[...g,...new Set(i.slice(0,3).filter(t=>t.missing_fields.length===0).map(t=>t.remediation)),...i.length>3?[`Inspect all policies with pm schema policies before retrying ${e.operation}.`]:[]]})}export{F as MAX_WORKFLOW_APPROVAL_HISTORY_BYTES,T as MAX_WORKFLOW_POLICY_BYTES,I as decodeWorkflowPolicyDocument,Q as enforceWorkflowMutation,N as evaluateWorkspacePolicies,L as readWorkflowApprovals,j as readWorkflowPolicies};
2
2
  //# sourceMappingURL=workflow-policy-store.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f675993f-c483-5751-baed-d968b4fd24c0")}catch{}})();import{createHash}from"node:crypto";import{stableStringify,stableValueEquals}from"../shared/serialization.js";import{PmCliError}from"../shared/errors.js";import{EXIT_CODE}from"../shared/constants.js";const WORKFLOW_POLICY_ACTIONS=["policies","policy-put","policy-remove","policy-mode","policy-check","policy-approve","policy-presets"],MAX_WORKFLOW_POLICIES=256,MAX_WORKFLOW_POLICY_TERMS=64;function invalidPolicy(detail){throw new PmCliError(`Invalid workflow policy: ${detail}`,EXIT_CODE.USAGE,{code:"workflow_policy_invalid",nextSteps:["Inspect pm schema policies and correct the declaration using pm schema policy-put."]})}function policyObject(value,keys,label){if(typeof value!="object"||value===null||Array.isArray(value))return invalidPolicy(`${label} must be an object`);const record=value;return Object.keys(record).some(key=>!keys.includes(key))?invalidPolicy(`${label} contains an unknown key`):record}function policyText(value,label,max=128){return typeof value!="string"||!value.trim()||value.length>max?invalidPolicy(`${label} must be nonempty text of at most ${max} characters`):value.trim()}function policyTerms(value,label){if(!Array.isArray(value)||value.length===0||value.length>MAX_WORKFLOW_POLICY_TERMS)return invalidPolicy(`${label} requires 1-${MAX_WORKFLOW_POLICY_TERMS} terms`);const terms=value.map(entry=>policyText(entry,label));return label==="fields"&&terms.some(term=>!/^[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$/.test(term)||term.split(".").some(part=>["__proto__","constructor","prototype"].includes(part)))?invalidPolicy("fields must be safe metadata paths of at most eight segments"):[...new Set(terms)]}function parsePolicyRule(value){const common=policyObject(value,["kind","fields","authors","allowed"],"rule");return common.kind==="transition"?(policyObject(common,["kind","allowed"],"transition rule"),!Array.isArray(common.allowed)||common.allowed.length>MAX_WORKFLOW_POLICY_TERMS?invalidPolicy("transition.allowed must be a bounded array"):{kind:"transition",allowed:common.allowed.map(pair=>!Array.isArray(pair)||pair.length!==2?invalidPolicy("transition pairs need two statuses"):[policyText(pair[0],"from"),policyText(pair[1],"to")])}):common.kind==="authors"?(policyObject(common,["kind","authors"],"authors rule"),{kind:"authors",authors:policyTerms(common.authors,"authors")}):common.kind==="require_fields"?(policyObject(common,["kind","fields"],"require_fields rule"),{kind:"require_fields",fields:policyTerms(common.fields,"fields")}):common.kind==="field_writers"||common.kind==="approval"?(policyObject(common,["kind","fields","authors"],"field rule"),{kind:common.kind,fields:policyTerms(common.fields,"fields"),authors:policyTerms(common.authors,"authors")}):invalidPolicy("unknown rule kind")}function parsePolicySubject(value){const subject={},source=policyObject(value,["types","tags","statuses","operations","parents","dependency"],"subject");for(const key of["types","tags","statuses","operations","parents"])source[key]!==void 0&&(subject[key]=policyTerms(source[key],key));if(source.dependency!==void 0){const edge=policyObject(source.dependency,["kind","id"],"dependency");subject.dependency={kind:policyText(edge.kind,"dependency kind"),...edge.id===void 0?{}:{id:policyText(edge.id,"dependency id")}}}return subject}function parseWorkflowPolicy(value){const raw=policyObject(value,["id","description","subject","effect","rule"],"policy"),id=policyText(raw.id,"id");return/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(id)?raw.effect!==void 0&&(typeof raw.effect!="string"||!["advise","warn","refuse"].includes(raw.effect))?invalidPolicy("effect must be advise, warn, or refuse"):{id,rule:parsePolicyRule(raw.rule),...raw.subject===void 0?{}:{subject:parsePolicySubject(raw.subject)},...raw.description===void 0?{}:{description:policyText(raw.description,"description",500)},...raw.effect===void 0?{}:{effect:raw.effect}}:invalidPolicy("id must be a stable token")}function parseWorkflowPolicyDocument(value){const raw=policyObject(value,["version","enforcement","policies"],"document");if(raw.version!==1)return invalidPolicy("unsupported version");if(raw.enforcement!==void 0&&raw.enforcement!=="advise"&&raw.enforcement!=="refuse")return invalidPolicy("enforcement must be advise or refuse");if(!Array.isArray(raw.policies)||raw.policies.length>MAX_WORKFLOW_POLICIES)return invalidPolicy(`policies must contain at most ${MAX_WORKFLOW_POLICIES} declarations`);const policies=raw.policies.map(parseWorkflowPolicy);return new Set(policies.map(policy=>policy.id)).size!==policies.length?invalidPolicy("duplicate policy id"):{version:1,enforcement:raw.enforcement??"advise",policies}}function readWorkflowPolicyField(record,field){let value=record;for(const key of field.split(".")){if(typeof value!="object"||value===null||!Object.hasOwn(value,key))return;value=value[key]}return value}function hasPolicyValue(value){return value==null?!1:typeof value=="string"?value.trim().length>0:typeof value=="number"?Number.isFinite(value):Array.isArray(value)?value.length>0:typeof value=="object"?Object.keys(value).length>0:!0}function workflowPolicyFingerprint(policy){return createHash("sha256").update(stableStringify(policy)).digest("hex")}function workflowApprovalFingerprint(policy,record){const fields=policy.rule.kind==="approval"?policy.rule.fields:[];return createHash("sha256").update(stableStringify({id:record.id,fields:fields.map(field=>[field,readWorkflowPolicyField(record,field)])})).digest("hex")}function matchesPolicyDependency(expected,dependencies){return Array.isArray(dependencies)&&dependencies.some(edge=>typeof edge=="object"&&edge!==null&&"kind"in edge&&edge.kind===expected.kind&&(expected.id===void 0||"id"in edge&&edge.id===expected.id))}function matchesPolicySubject(subject,record,operation){return!(subject.types&&!subject.types.some(type=>type.toLowerCase()===String(record.type).toLowerCase())||subject.statuses&&!subject.statuses.includes(String(record.status))||subject.operations&&!subject.operations.includes(operation)||subject.parents&&!subject.parents.includes(String(record.parent))||subject.tags&&(!Array.isArray(record.tags)||!subject.tags.some(tag=>record.tags.includes(tag)))||subject.dependency&&!matchesPolicyDependency(subject.dependency,record.dependencies))}function workflowPolicyApplies(policy,input){if(input.completeness_only&&(policy.rule.kind!=="require_fields"||policy.subject?.operations!==void 0)||policy.rule.kind==="approval"&&input.before===null)return!1;const subject=policy.subject??{},status=input.after?.status??input.before?.status;return[input.before,input.after].some(record=>record!==null&&matchesPolicySubject(subject,{...record,status},input.operation))}function missingRequiredPolicyFields(fields,input,changedStatus,fieldsChanged){const scopeChanged=["type","tags","parent","dependencies"].some(field=>!stableValueEquals(input.before?.[field],input.after?.[field]));return input.after&&(input.completeness_only||changedStatus||fieldsChanged||scopeChanged)?fields.filter(field=>!hasPolicyValue(readWorkflowPolicyField(input.after,field))):[]}function hasMatchingWorkflowApproval(policy,input,authors,policyFingerprint){const record=input.after??input.before,contentFingerprint=workflowApprovalFingerprint(policy,record);return input.approvals?.some(approval=>approval.policy_fingerprint===policyFingerprint&&approval.content_fingerprint===contentFingerprint&&approval.author!==input.author&&authors.includes(approval.author))??!1}function evaluatePolicyRule(policy,input,policyFingerprint){const rule=policy.rule,changedStatus=input.before?.status!==input.after?.status,fieldsChanged="fields"in rule&&rule.fields.some(field=>!stableValueEquals(readWorkflowPolicyField(input.before,field),readWorkflowPolicyField(input.after,field)));switch(rule.kind){case"require_fields":{const missing=missingRequiredPolicyFields(rule.fields,input,changedStatus,fieldsChanged);return{satisfied:missing.length===0,missing_fields:missing,remediation:"Supply the declared required fields before this lifecycle transition."}}case"transition":return{satisfied:!changedStatus||rule.allowed.some(([from,to])=>from===String(input.before?.status??"$create")&&to===String(input.after?.status??"$delete")),missing_fields:[],remediation:"Choose a declared allowed transition; inspect pm schema policies."};case"authors":return{satisfied:rule.authors.includes(input.author),missing_fields:[],remediation:"Have a declared workflow actor perform this operation."};case"field_writers":return{satisfied:!fieldsChanged||rule.authors.includes(input.author),missing_fields:[],remediation:"Have a declared field writer change the protected fields."};case"approval":return{satisfied:!changedStatus||hasMatchingWorkflowApproval(policy,input,rule.authors,policyFingerprint),missing_fields:[],remediation:`Record an independent approval with pm schema policy-approve <item-id> --policy ${policy.id} after preparing the reviewed fields.`}}}function evaluateWorkflowPolicySnapshot(document,input,fingerprint){const decisions=document.policies.filter(policy=>workflowPolicyApplies(policy,input)).map(policy=>{const requested=policy.effect??"advise",policyFingerprint=fingerprint(policy);return{policy_id:policy.id,policy_fingerprint:policyFingerprint,rule:policy.rule.kind,effect:requested==="refuse"&&document.enforcement!=="refuse"?"warn":requested,...evaluatePolicyRule(policy,input,policyFingerprint)}});return{allowed:!decisions.some(decision=>!decision.satisfied&&decision.effect==="refuse"),decisions,warnings:decisions.filter(decision=>!decision.satisfied).map(decision=>`workflow_policy:${decision.effect}:${decision.policy_id}:${decision.rule}`)}}function evaluateWorkflowPolicies(document,input){return evaluateWorkflowPolicySnapshot(document,input,workflowPolicyFingerprint)}function createWorkflowPolicyEvaluator(document){const snapshot=parseWorkflowPolicyDocument(document),fingerprints=new Map(snapshot.policies.map(policy=>[policy,workflowPolicyFingerprint(policy)]));return input=>evaluateWorkflowPolicySnapshot(snapshot,input,policy=>fingerprints.get(policy))}export{MAX_WORKFLOW_POLICIES,MAX_WORKFLOW_POLICY_TERMS,WORKFLOW_POLICY_ACTIONS,createWorkflowPolicyEvaluator,evaluateWorkflowPolicies,parseWorkflowPolicy,parseWorkflowPolicyDocument,readWorkflowPolicyField,workflowApprovalFingerprint,workflowPolicyApplies,workflowPolicyFingerprint};
1
+ import{createHash as p}from"node:crypto";import{stableStringify as m,stableValueEquals as y}from"../shared/serialization.js";import{PmCliError as _}from"../shared/errors.js";import{EXIT_CODE as A}from"../shared/constants.js";const z=["policies","policy-put","policy-remove","policy-mode","policy-check","policy-approve","policy-presets"],h=256,u=64;function o(r){throw new _(`Invalid workflow policy: ${r}`,A.USAGE,{code:"workflow_policy_invalid",nextSteps:["Inspect pm schema policies and correct the declaration using pm schema policy-put."]})}function a(r,e,t){if(typeof r!="object"||r===null||Array.isArray(r))return o(`${t} must be an object`);const n=r;return Object.keys(n).some(i=>!e.includes(i))?o(`${t} contains an unknown key`):n}function d(r,e,t=128){return typeof r!="string"||!r.trim()||r.length>t?o(`${e} must be nonempty text of at most ${t} characters`):r.trim()}function c(r,e){if(!Array.isArray(r)||r.length===0||r.length>u)return o(`${e} requires 1-${u} terms`);const t=r.map(n=>d(n,e));return e==="fields"&&t.some(n=>!/^[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$/.test(n)||n.split(".").some(i=>["__proto__","constructor","prototype"].includes(i)))?o("fields must be safe metadata paths of at most eight segments"):[...new Set(t)]}function b(r){const e=a(r,["kind","fields","authors","allowed"],"rule");return e.kind==="transition"?(a(e,["kind","allowed"],"transition rule"),!Array.isArray(e.allowed)||e.allowed.length>u?o("transition.allowed must be a bounded array"):{kind:"transition",allowed:e.allowed.map(t=>!Array.isArray(t)||t.length!==2?o("transition pairs need two statuses"):[d(t[0],"from"),d(t[1],"to")])}):e.kind==="authors"?(a(e,["kind","authors"],"authors rule"),{kind:"authors",authors:c(e.authors,"authors")}):e.kind==="require_fields"?(a(e,["kind","fields"],"require_fields rule"),{kind:"require_fields",fields:c(e.fields,"fields")}):e.kind==="field_writers"||e.kind==="approval"?(a(e,["kind","fields","authors"],"field rule"),{kind:e.kind,fields:c(e.fields,"fields"),authors:c(e.authors,"authors")}):o("unknown rule kind")}function P(r){const e={},t=a(r,["types","tags","statuses","operations","parents","dependency"],"subject");for(const n of["types","tags","statuses","operations","parents"])t[n]!==void 0&&(e[n]=c(t[n],n));if(t.dependency!==void 0){const n=a(t.dependency,["kind","id"],"dependency");e.dependency={kind:d(n.kind,"dependency kind"),...n.id===void 0?{}:{id:d(n.id,"dependency id")}}}return e}function S(r){const e=a(r,["id","description","subject","effect","rule"],"policy"),t=d(e.id,"id");return/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(t)?e.effect!==void 0&&(typeof e.effect!="string"||!["advise","warn","refuse"].includes(e.effect))?o("effect must be advise, warn, or refuse"):{id:t,rule:b(e.rule),...e.subject===void 0?{}:{subject:P(e.subject)},...e.description===void 0?{}:{description:d(e.description,"description",500)},...e.effect===void 0?{}:{effect:e.effect}}:o("id must be a stable token")}function O(r){const e=a(r,["version","enforcement","policies"],"document");if(e.version!==1)return o("unsupported version");if(e.enforcement!==void 0&&e.enforcement!=="advise"&&e.enforcement!=="refuse")return o("enforcement must be advise or refuse");if(!Array.isArray(e.policies)||e.policies.length>h)return o(`policies must contain at most ${h} declarations`);const t=e.policies.map(S);return new Set(t.map(n=>n.id)).size!==t.length?o("duplicate policy id"):{version:1,enforcement:e.enforcement??"advise",policies:t}}function l(r,e){let t=r;for(const n of e.split(".")){if(typeof t!="object"||t===null||!Object.hasOwn(t,n))return;t=t[n]}return t}function $(r){return r==null?!1:typeof r=="string"?r.trim().length>0:typeof r=="number"?Number.isFinite(r):Array.isArray(r)?r.length>0:typeof r=="object"?Object.keys(r).length>0:!0}function w(r){return p("sha256").update(m(r)).digest("hex")}function x(r,e){const t=r.rule.kind==="approval"?r.rule.fields:[];return p("sha256").update(m({id:e.id,fields:t.map(n=>[n,l(e,n)])})).digest("hex")}function W(r,e){return Array.isArray(e)&&e.some(t=>typeof t=="object"&&t!==null&&"kind"in t&&t.kind===r.kind&&(r.id===void 0||"id"in t&&t.id===r.id))}function v(r,e,t){return!(r.types&&!r.types.some(n=>n.toLowerCase()===String(e.type).toLowerCase())||r.statuses&&!r.statuses.includes(String(e.status))||r.operations&&!r.operations.includes(t)||r.parents&&!r.parents.includes(String(e.parent))||r.tags&&(!Array.isArray(e.tags)||!r.tags.some(n=>e.tags.includes(n)))||r.dependency&&!W(r.dependency,e.dependencies))}function C(r,e){if(e.completeness_only&&(r.rule.kind!=="require_fields"||r.subject?.operations!==void 0)||r.rule.kind==="approval"&&e.before===null)return!1;const t=r.subject??{},n=e.after?.status??e.before?.status;return[e.before,e.after].some(i=>i!==null&&v(t,{...i,status:n},e.operation))}function q(r,e,t,n){const i=["type","tags","parent","dependencies"].some(s=>!y(e.before?.[s],e.after?.[s]));return e.after&&(e.completeness_only||t||n||i)?r.filter(s=>!$(l(e.after,s))):[]}function F(r,e,t,n){const i=e.after??e.before,f=x(r,i);return e.approvals?.some(s=>s.policy_fingerprint===n&&s.content_fingerprint===f&&s.author!==e.author&&t.includes(s.author))??!1}function j(r,e,t){const n=r.rule,i=e.before?.status!==e.after?.status,f="fields"in n&&n.fields.some(s=>!y(l(e.before,s),l(e.after,s)));switch(n.kind){case"require_fields":{const s=q(n.fields,e,i,f);return{satisfied:s.length===0,missing_fields:s,remediation:"Supply the declared required fields before this lifecycle transition."}}case"transition":return{satisfied:!i||n.allowed.some(([s,k])=>s===String(e.before?.status??"$create")&&k===String(e.after?.status??"$delete")),missing_fields:[],remediation:"Choose a declared allowed transition; inspect pm schema policies."};case"authors":return{satisfied:n.authors.includes(e.author),missing_fields:[],remediation:"Have a declared workflow actor perform this operation."};case"field_writers":return{satisfied:!f||n.authors.includes(e.author),missing_fields:[],remediation:"Have a declared field writer change the protected fields."};case"approval":return{satisfied:!i||F(r,e,n.authors,t),missing_fields:[],remediation:`Record an independent approval with pm schema policy-approve <item-id> --policy ${r.id} after preparing the reviewed fields.`}}}function g(r,e,t){const n=r.policies.filter(i=>C(i,e)).map(i=>{const f=i.effect??"advise",s=t(i);return{policy_id:i.id,policy_fingerprint:s,rule:i.rule.kind,effect:f==="refuse"&&r.enforcement!=="refuse"?"warn":f,...j(i,e,s)}});return{allowed:!n.some(i=>!i.satisfied&&i.effect==="refuse"),decisions:n,warnings:n.filter(i=>!i.satisfied).map(i=>`workflow_policy:${i.effect}:${i.policy_id}:${i.rule}`)}}function Z(r,e){return g(r,e,w)}function M(r){const e=O(r),t=new Map(e.policies.map(n=>[n,w(n)]));return n=>g(e,n,i=>t.get(i))}export{h as MAX_WORKFLOW_POLICIES,u as MAX_WORKFLOW_POLICY_TERMS,z as WORKFLOW_POLICY_ACTIONS,M as createWorkflowPolicyEvaluator,Z as evaluateWorkflowPolicies,S as parseWorkflowPolicy,O as parseWorkflowPolicyDocument,l as readWorkflowPolicyField,x as workflowApprovalFingerprint,C as workflowPolicyApplies,w as workflowPolicyFingerprint};
2
2
  //# sourceMappingURL=workflow-policy.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]="ab26bcb3-fb2a-5f2f-96e7-7965787b924e")}catch{}})();import{normalizeAddFieldInput}from"../schema/fields-file.js";import{normalizeAddStatusInput}from"../schema/status-defs-file.js";import{normalizeAddTypeInput}from"../schema/item-types-file.js";function describeProfileComposition(profile){return{types:profile.types.length,statuses:profile.statuses.length,fields:profile.fields.length,workflows:profile.workflows.length,config:profile.config.length,templates:profile.templates.length,packages:profile.packages.length}}function describeProjectProfile(profile){return{name:profile.name,title:profile.title,summary:profile.summary,composition:describeProfileComposition(profile),types:profile.types.map(type=>lenientIdentifier(()=>normalizeAddTypeInput(type).name,()=>String(type.name??""))),statuses:profile.statuses.map(status=>lenientIdentifier(()=>normalizeAddStatusInput(status).id,()=>String(status.id??""))),fields:profile.fields.map(field=>lenientIdentifier(()=>normalizeAddFieldInput(field).key,()=>String(field.key??""))),workflows:profile.workflows.map(workflow=>workflow.type),config:profile.config.map(entry=>`${entry.key}=${entry.value}`),templates:profile.templates.map(template=>template.name),packages:profile.packages.map(recommendation=>({spec:recommendation.spec,reason:recommendation.reason}))}}function lenientIdentifier(normalize,raw){try{return normalize()}catch{return raw()}}export{describeProfileComposition,describeProjectProfile};
1
+ import{normalizeAddFieldInput as n}from"../schema/fields-file.js";import{normalizeAddStatusInput as a}from"../schema/status-defs-file.js";import{normalizeAddTypeInput as m}from"../schema/item-types-file.js";function o(t){return{types:t.types.length,statuses:t.statuses.length,fields:t.fields.length,workflows:t.workflows.length,config:t.config.length,templates:t.templates.length,packages:t.packages.length}}function i(t){return{name:t.name,title:t.title,summary:t.summary,composition:o(t),types:t.types.map(e=>s(()=>m(e).name,()=>String(e.name??""))),statuses:t.statuses.map(e=>s(()=>a(e).id,()=>String(e.id??""))),fields:t.fields.map(e=>s(()=>n(e).key,()=>String(e.key??""))),workflows:t.workflows.map(e=>e.type),config:t.config.map(e=>`${e.key}=${e.value}`),templates:t.templates.map(e=>e.name),packages:t.packages.map(e=>({spec:e.spec,reason:e.reason}))}}function s(t,e){try{return t()}catch{return e()}}export{o as describeProfileComposition,i as describeProjectProfile};
2
2
  //# sourceMappingURL=profile-describe.js.map
@@ -6,7 +6,7 @@ export declare const PROFILE_LINT_DIMENSIONS:readonly["profile","types","statuse
6
6
  /** Restricts profile lint dimension values accepted by command, SDK, and storage contracts. */
7
7
  export type ProfileLintDimension=(typeof PROFILE_LINT_DIMENSIONS)[number];
8
8
  /** Stable machine-readable codes every {@link ProjectProfileLintFinding} carries. */
9
- export declare const PROFILE_LINT_CODES:readonly["profile_name_empty","profile_name_not_normalized","profile_title_empty","profile_summary_empty","type_invalid","type_duplicate","status_invalid","status_duplicate","field_invalid","field_duplicate","field_mcp_input_collision","workflow_type_empty","workflow_type_unknown","workflow_duplicate_type","workflow_transition_malformed","workflow_status_unknown","config_key_unknown","config_value_invalid","config_duplicate","template_type_unknown","package_spec_empty"];
9
+ export declare const PROFILE_LINT_CODES:readonly["profile_name_empty","profile_name_not_normalized","profile_title_empty","profile_summary_empty","type_invalid","type_duplicate","status_invalid","status_duplicate","field_invalid","field_duplicate","field_mcp_input_collision","field_option_collision","workflow_type_empty","workflow_type_unknown","workflow_duplicate_type","workflow_transition_malformed","workflow_status_unknown","config_key_unknown","config_value_invalid","config_duplicate","template_type_unknown","package_spec_empty"];
10
10
  /** Restricts profile lint code values accepted by command, SDK, and storage contracts. */
11
11
  export type ProfileLintCode=(typeof PROFILE_LINT_CODES)[number];
12
12
  /** A single graded consistency finding produced by {@link lintProjectProfile}. */
@@ -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]="0b04624c-2096-55dc-9dde-b8c76ead72d6")}catch{}})();import{BUILTIN_ITEM_TYPE_VALUES}from"../../types/index.js";import{parseNestedSettingValue,resolveNestedSettingDescriptor}from"../config/nested-settings.js";import{normalizeAddFieldInput}from"../schema/fields-file.js";import{normalizeAddStatusInput}from"../schema/status-defs-file.js";import{normalizeAddTypeInput}from"../schema/item-types-file.js";import{normalizeStatusToken}from"../schema/type-workflows.js";import{DEFAULT_RUNTIME_STATUS_DEFINITIONS}from"../schema/runtime-schema.js";import{toErrorMessage}from"../shared/primitives.js";import{resolvePmToolCustomFieldCollision}from"../../sdk/cli-contracts/tool-schema.js";import{normalizeProfileLookupKey}from"./profile-presets.js";const PROFILE_LINT_DIMENSIONS=["profile","types","statuses","fields","workflows","config","templates","packages"],PROFILE_LINT_CODES=["profile_name_empty","profile_name_not_normalized","profile_title_empty","profile_summary_empty","type_invalid","type_duplicate","status_invalid","status_duplicate","field_invalid","field_duplicate","field_mcp_input_collision","workflow_type_empty","workflow_type_unknown","workflow_duplicate_type","workflow_transition_malformed","workflow_status_unknown","config_key_unknown","config_value_invalid","config_duplicate","template_type_unknown","package_spec_empty"],BUILTIN_STATUS_TOKENS=new Set(DEFAULT_RUNTIME_STATUS_DEFINITIONS.flatMap(definition=>[normalizeStatusToken(definition.id),...(definition.aliases??[]).map(alias=>normalizeStatusToken(alias))]).filter(token=>token.length>0)),BUILTIN_TYPE_KEYS=new Set(BUILTIN_ITEM_TYPE_VALUES.map(name=>name.toLowerCase()));function lintProfileIdentity(profile,findings){profile.name.trim().length===0?findings.push({severity:"error",code:"profile_name_empty",dimension:"profile",message:"Profile name must not be empty; profile resolution requires a non-blank name."}):profile.name!==normalizeProfileLookupKey(profile.name)&&findings.push({severity:"warning",code:"profile_name_not_normalized",dimension:"profile",target:profile.name,message:`Profile name "${profile.name}" is not in canonical form; resolution folds it to "${normalizeProfileLookupKey(profile.name)}" (lowercase, hyphens as underscores).`}),profile.title.trim().length===0&&findings.push({severity:"warning",code:"profile_title_empty",dimension:"profile",message:"Profile title is empty; list and show surfaces will render a blank title."}),profile.summary.trim().length===0&&findings.push({severity:"warning",code:"profile_summary_empty",dimension:"profile",message:"Profile summary is empty; list and show surfaces will render a blank archetype description."})}function lintTypes(profile,findings){const declared=new Set,seen=new Set;for(const[index,type]of profile.types.entries()){let name;try{name=normalizeAddTypeInput(type).name}catch(error){findings.push({severity:"error",code:"type_invalid",dimension:"types",target:typeof type.name=="string"?type.name:`#${index}`,message:toErrorMessage(error)});continue}const key=name.toLowerCase();if(seen.has(key)){findings.push({severity:"error",code:"type_duplicate",dimension:"types",target:name,message:`Item type "${name}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}seen.add(key),declared.add(key)}return declared}function lintStatuses(profile,findings){const declared=new Set,seen=new Set;for(const[index,status]of profile.statuses.entries()){let normalized;try{normalized=normalizeAddStatusInput(status)}catch(error){findings.push({severity:"error",code:"status_invalid",dimension:"statuses",target:typeof status.id=="string"?status.id:`#${index}`,message:toErrorMessage(error)});continue}if(seen.has(normalized.id)){findings.push({severity:"error",code:"status_duplicate",dimension:"statuses",target:normalized.id,message:`Status "${normalized.id}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}seen.add(normalized.id),declared.add(normalized.id);for(const alias of normalized.aliases??[])declared.add(normalizeStatusToken(alias))}return declared}function lintFields(profile,findings){const seen=new Set;for(const[index,field]of profile.fields.entries()){let key;try{key=normalizeAddFieldInput(field).key}catch(error){findings.push({severity:"error",code:"field_invalid",dimension:"fields",target:typeof field.key=="string"?field.key:`#${index}`,message:toErrorMessage(error)});continue}if(seen.has(key)){findings.push({severity:"error",code:"field_duplicate",dimension:"fields",target:key,message:`Field "${key}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}seen.add(key);const collision=resolvePmToolCustomFieldCollision(key);collision&&findings.push({severity:"warning",code:"field_mcp_input_collision",dimension:"fields",target:key,message:`Field "${key}" collides with canonical MCP property "${collision.property}" owned by ${collision.owner}; callers must pass the custom value through ${collision.nested_path}.`})}}function lintWorkflows(profile,declaredTypes,declaredStatuses,findings){const seenTypes=new Set;for(const[index,workflow]of profile.workflows.entries()){const typeKey=workflow.type.trim().toLowerCase();if(typeKey.length===0){findings.push({severity:"error",code:"workflow_type_empty",dimension:"workflows",target:`#${index}`,message:"Workflow has an empty type; the workflow resolver drops entries without a type."});continue}const duplicate=seenTypes.has(typeKey);seenTypes.add(typeKey),duplicate?findings.push({severity:"warning",code:"workflow_duplicate_type",dimension:"workflows",target:workflow.type,message:`Workflow type "${workflow.type}" is declared more than once; the later transition set wins.`}):!BUILTIN_TYPE_KEYS.has(typeKey)&&!declaredTypes.has(typeKey)&&findings.push({severity:"warning",code:"workflow_type_unknown",dimension:"workflows",target:workflow.type,message:`Workflow governs type "${workflow.type}" which is neither a built-in type nor declared by this profile; it has no effect unless that type already exists.`});const reportedUnknownStatuses=new Set;for(const pair of workflow.allowed_transitions){const from=normalizeStatusToken(pair[0]),to=normalizeStatusToken(pair[1]);if(from.length===0||to.length===0){findings.push({severity:"error",code:"workflow_transition_malformed",dimension:"workflows",target:workflow.type,message:`Workflow "${workflow.type}" has a transition with an empty status; the workflow resolver silently drops it.`});continue}for(const token of[from,to])BUILTIN_STATUS_TOKENS.has(token)||declaredStatuses.has(token)||reportedUnknownStatuses.has(token)||(reportedUnknownStatuses.add(token),findings.push({severity:"warning",code:"workflow_status_unknown",dimension:"workflows",target:token,message:`Workflow "${workflow.type}" references status "${token}" which is neither a built-in status nor declared by this profile; transitions to or from it are unreachable.`}))}}}function lintConfig(profile,findings){const seen=new Set;for(const entry of profile.config){const descriptor=resolveNestedSettingDescriptor(entry.key);if(descriptor===void 0){findings.push({severity:"error",code:"config_key_unknown",dimension:"config",target:entry.key,message:`Config knob "${entry.key}" is not a recognized setting; apply rejects it with a usage error.`});continue}seen.has(descriptor.key)?findings.push({severity:"error",code:"config_duplicate",dimension:"config",target:descriptor.key,message:`Config knob "${descriptor.key}" is set more than once; the later value silently overwrites the earlier one.`}):seen.add(descriptor.key);const parsed=parseNestedSettingValue(descriptor,entry.value);parsed.ok||findings.push({severity:"error",code:"config_value_invalid",dimension:"config",target:entry.key,message:parsed.error.message})}}function lintTemplates(profile,declaredTypes,findings){for(const template of profile.templates){const typeOption=template.options.type;if(typeof typeOption!="string"||typeOption.trim().length===0)continue;const typeKey=typeOption.trim().toLowerCase();!BUILTIN_TYPE_KEYS.has(typeKey)&&!declaredTypes.has(typeKey)&&findings.push({severity:"warning",code:"template_type_unknown",dimension:"templates",target:template.name,message:`Template "${template.name}" creates type "${typeOption}" which is neither a built-in type nor declared by this profile.`})}}function lintPackages(profile,findings){for(const[index,recommendation]of profile.packages.entries())recommendation.spec.trim().length===0&&findings.push({severity:"warning",code:"package_spec_empty",dimension:"packages",target:`#${index}`,message:"Package recommendation has an empty spec; it cannot be surfaced as an install hint."})}function lintProjectProfile(profile){const findings=[];lintProfileIdentity(profile,findings);const declaredTypes=lintTypes(profile,findings),declaredStatuses=lintStatuses(profile,findings);lintFields(profile,findings),lintWorkflows(profile,declaredTypes,declaredStatuses,findings),lintConfig(profile,findings),lintTemplates(profile,declaredTypes,findings),lintPackages(profile,findings);const errorCount=findings.filter(finding=>finding.severity==="error").length,warningCount=findings.length-errorCount;return{profile:profile.name,ok:errorCount===0,findings,errorCount,warningCount}}export{PROFILE_LINT_CODES,PROFILE_LINT_DIMENSIONS,lintProjectProfile};
1
+ import{BUILTIN_ITEM_TYPE_VALUES as _}from"../../types/index.js";import{parseNestedSettingValue as g,resolveNestedSettingDescriptor as k}from"../config/nested-settings.js";import{normalizeAddFieldInput as v}from"../schema/fields-file.js";import{normalizeAddStatusInput as S}from"../schema/status-defs-file.js";import{normalizeAddTypeInput as $}from"../schema/item-types-file.js";import{normalizeStatusToken as d}from"../schema/type-workflows.js";import{DEFAULT_RUNTIME_STATUS_DEFINITIONS as T}from"../schema/runtime-schema.js";import{toErrorMessage as m}from"../shared/primitives.js";import{resolvePmToolCustomFieldCollision as I}from"../../sdk/cli-contracts/tool-schema.js";import{describeFieldOptionCollision as b,resolveAddFieldOptionCollisions as C}from"../../sdk/schema/field-option-collisions.js";import{normalizeProfileLookupKey as w}from"./profile-presets.js";const G=["profile","types","statuses","fields","workflows","config","templates","packages"],H=["profile_name_empty","profile_name_not_normalized","profile_title_empty","profile_summary_empty","type_invalid","type_duplicate","status_invalid","status_duplicate","field_invalid","field_duplicate","field_mcp_input_collision","field_option_collision","workflow_type_empty","workflow_type_unknown","workflow_duplicate_type","workflow_transition_malformed","workflow_status_unknown","config_key_unknown","config_value_invalid","config_duplicate","template_type_unknown","package_spec_empty"],P=new Set(T.flatMap(e=>[d(e.id),...(e.aliases??[]).map(t=>d(t))]).filter(e=>e.length>0)),h=new Set(_.map(e=>e.toLowerCase()));function E(e,t){e.name.trim().length===0?t.push({severity:"error",code:"profile_name_empty",dimension:"profile",message:"Profile name must not be empty; profile resolution requires a non-blank name."}):e.name!==w(e.name)&&t.push({severity:"warning",code:"profile_name_not_normalized",dimension:"profile",target:e.name,message:`Profile name "${e.name}" is not in canonical form; resolution folds it to "${w(e.name)}" (lowercase, hyphens as underscores).`}),e.title.trim().length===0&&t.push({severity:"warning",code:"profile_title_empty",dimension:"profile",message:"Profile title is empty; list and show surfaces will render a blank title."}),e.summary.trim().length===0&&t.push({severity:"warning",code:"profile_summary_empty",dimension:"profile",message:"Profile summary is empty; list and show surfaces will render a blank archetype description."})}function L(e,t){const r=new Set,s=new Set;for(const[i,o]of e.types.entries()){let n;try{n=$(o).name}catch(l){t.push({severity:"error",code:"type_invalid",dimension:"types",target:typeof o.name=="string"?o.name:`#${i}`,message:m(l)});continue}const a=n.toLowerCase();if(s.has(a)){t.push({severity:"error",code:"type_duplicate",dimension:"types",target:n,message:`Item type "${n}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}s.add(a),r.add(a)}return r}function N(e,t){const r=new Set,s=new Set;for(const[i,o]of e.statuses.entries()){let n;try{n=S(o)}catch(a){t.push({severity:"error",code:"status_invalid",dimension:"statuses",target:typeof o.id=="string"?o.id:`#${i}`,message:m(a)});continue}if(s.has(n.id)){t.push({severity:"error",code:"status_duplicate",dimension:"statuses",target:n.id,message:`Status "${n.id}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}s.add(n.id),r.add(n.id);for(const a of n.aliases??[])r.add(d(a))}return r}function F(e,t){const r=new Set;for(const[s,i]of e.fields.entries()){let o,n;try{n=v(i),o=n.key}catch(p){t.push({severity:"error",code:"field_invalid",dimension:"fields",target:typeof i.key=="string"?i.key:`#${s}`,message:m(p)});continue}if(r.has(o)){t.push({severity:"error",code:"field_duplicate",dimension:"fields",target:o,message:`Field "${o}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}r.add(o);const a=C(n);a.length>0&&t.push({severity:"error",code:"field_option_collision",dimension:"fields",target:o,message:`Field "${o}" would disable a built-in option: ${a.map(b).join("; ")}. Rename the field or narrow its commands.`});const l=I(o);l&&t.push({severity:"warning",code:"field_mcp_input_collision",dimension:"fields",target:o,message:`Field "${o}" collides with canonical MCP property "${l.property}" owned by ${l.owner}; callers must pass the custom value through ${l.nested_path}.`})}}function z(e,t,r,s){const i=new Set;for(const[o,n]of e.workflows.entries()){const a=n.type.trim().toLowerCase();if(a.length===0){s.push({severity:"error",code:"workflow_type_empty",dimension:"workflows",target:`#${o}`,message:"Workflow has an empty type; the workflow resolver drops entries without a type."});continue}const l=i.has(a);i.add(a),l?s.push({severity:"warning",code:"workflow_duplicate_type",dimension:"workflows",target:n.type,message:`Workflow type "${n.type}" is declared more than once; the later transition set wins.`}):!h.has(a)&&!t.has(a)&&s.push({severity:"warning",code:"workflow_type_unknown",dimension:"workflows",target:n.type,message:`Workflow governs type "${n.type}" which is neither a built-in type nor declared by this profile; it has no effect unless that type already exists.`});const p=new Set;for(const f of n.allowed_transitions){const u=d(f[0]),y=d(f[1]);if(u.length===0||y.length===0){s.push({severity:"error",code:"workflow_transition_malformed",dimension:"workflows",target:n.type,message:`Workflow "${n.type}" has a transition with an empty status; the workflow resolver silently drops it.`});continue}for(const c of[u,y])P.has(c)||r.has(c)||p.has(c)||(p.add(c),s.push({severity:"warning",code:"workflow_status_unknown",dimension:"workflows",target:c,message:`Workflow "${n.type}" references status "${c}" which is neither a built-in status nor declared by this profile; transitions to or from it are unreachable.`}))}}}function x(e,t){const r=new Set;for(const s of e.config){const i=k(s.key);if(i===void 0){t.push({severity:"error",code:"config_key_unknown",dimension:"config",target:s.key,message:`Config knob "${s.key}" is not a recognized setting; apply rejects it with a usage error.`});continue}r.has(i.key)?t.push({severity:"error",code:"config_duplicate",dimension:"config",target:i.key,message:`Config knob "${i.key}" is set more than once; the later value silently overwrites the earlier one.`}):r.add(i.key);const o=g(i,s.value);o.ok||t.push({severity:"error",code:"config_value_invalid",dimension:"config",target:s.key,message:o.error.message})}}function O(e,t,r){for(const s of e.templates){const i=s.options.type;if(typeof i!="string"||i.trim().length===0)continue;const o=i.trim().toLowerCase();!h.has(o)&&!t.has(o)&&r.push({severity:"warning",code:"template_type_unknown",dimension:"templates",target:s.name,message:`Template "${s.name}" creates type "${i}" which is neither a built-in type nor declared by this profile.`})}}function U(e,t){for(const[r,s]of e.packages.entries())s.spec.trim().length===0&&t.push({severity:"warning",code:"package_spec_empty",dimension:"packages",target:`#${r}`,message:"Package recommendation has an empty spec; it cannot be surfaced as an install hint."})}function J(e){const t=[];E(e,t);const r=L(e,t),s=N(e,t);F(e,t),z(e,r,s,t),x(e,t),O(e,r,t),U(e,t);const i=t.filter(n=>n.severity==="error").length,o=t.length-i;return{profile:e.name,ok:i===0,findings:t,errorCount:i,warningCount:o}}export{H as PROFILE_LINT_CODES,G as PROFILE_LINT_DIMENSIONS,J as lintProjectProfile};
2
2
  //# sourceMappingURL=profile-lint.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]="be2b507d-2797-570c-b211-46d950edcbde")}catch{}})();import{normalizeAddTypeInput,parseItemTypesFile,serializeItemTypesFile,upsertItemType}from"../schema/item-types-file.js";import{normalizeAddStatusInput,parseStatusDefsFile,serializeStatusDefsFile,upsertStatusDef}from"../schema/status-defs-file.js";import{normalizeAddFieldInput,parseFieldsFile,serializeFieldsFile,upsertField}from"../schema/fields-file.js";import{parseNestedSettingValue,readNestedSettingValue,resolveNestedSettingDescriptor}from"../config/nested-settings.js";function planSchemaComponent(initialFile,inputs,keyOf,serialize,upsert){let file=initialFile;const changes=[];for(const input of inputs){const before=serialize(file),result=upsert(file,input),after=serialize(result.file);file=result.file;const status=before===after?"unchanged":result.replaced?"update":"add";changes.push({key:keyOf(input),status})}return{file,changes,changed:changes.some(change=>change.status!=="unchanged")}}function canonicalTransitions(transitions){return JSON.stringify(transitions.map(pair=>pair.join("\0")).sort())}function planWorkflows(current,desired){const result=current.map(entry=>({...entry})),changes=[];for(const workflow of desired){const index=result.findIndex(entry=>entry.type===workflow.type),next={type:workflow.type,allowed_transitions:workflow.allowed_transitions};index<0?(result.push(next),changes.push({type:workflow.type,status:"add"})):canonicalTransitions(result[index].allowed_transitions)===canonicalTransitions(workflow.allowed_transitions)?changes.push({type:workflow.type,status:"unchanged"}):(result[index]=next,changes.push({type:workflow.type,status:"update"}))}return{changes,result,changed:changes.some(change=>change.status!=="unchanged")}}function planConfig(profile,settings){const changes=[];for(const entry of profile.config){const descriptor=resolveNestedSettingDescriptor(entry.key);if(descriptor===void 0)throw new Error(`Profile "${profile.name}" references unknown config key "${entry.key}".`);const parsed=parseNestedSettingValue(descriptor,entry.value);if(!parsed.ok)throw new Error(`Profile "${profile.name}" config ${entry.key}: ${parsed.error.message}`);const current=readNestedSettingValue(settings,descriptor),status=current===null?"add":current===parsed.parsed.value?"unchanged":"update";changes.push({key:descriptor.key,path:descriptor.path,value:parsed.parsed.value,status})}return{changes,changed:changes.some(change=>change.status!=="unchanged")}}function canonicalTemplateOptions(options){const sorted=Object.entries(options).sort(([left],[right])=>left.localeCompare(right));return JSON.stringify(sorted)}function planTemplates(profile,existing){const changes=[];for(const template of profile.templates){const current=existing.get(template.name);let status;current===void 0?status="add":canonicalTemplateOptions(current)===canonicalTemplateOptions(template.options)?status="unchanged":status="update",changes.push({name:template.name,options:template.options,status})}return{changes,changed:changes.some(change=>change.status!=="unchanged")}}function planProfileApplication(profile,current){const types=planSchemaComponent(parseItemTypesFile(current.typesRaw),profile.types,input=>normalizeAddTypeInput(input).name,serializeItemTypesFile,(file,input)=>upsertItemType(file,normalizeAddTypeInput(input))),statuses=planSchemaComponent(parseStatusDefsFile(current.statusesRaw),profile.statuses,input=>normalizeAddStatusInput(input).id,serializeStatusDefsFile,(file,input)=>upsertStatusDef(file,normalizeAddStatusInput(input))),fields=planSchemaComponent(parseFieldsFile(current.fieldsRaw),profile.fields,input=>normalizeAddFieldInput(input).key,serializeFieldsFile,(file,input)=>upsertField(file,normalizeAddFieldInput(input))),workflows=planWorkflows(current.workflows,profile.workflows),config=planConfig(profile,current.settings),templates=planTemplates(profile,current.templates),packages=profile.packages.map(recommendation=>({spec:recommendation.spec,reason:recommendation.reason,status:current.installedPackages.has(recommendation.spec)?"installed":"recommended"})),changed=types.changed||statuses.changed||fields.changed||workflows.changed||config.changed||templates.changed;return{profile:{name:profile.name,title:profile.title,summary:profile.summary},types,statuses,fields,workflows,config,templates,packages,changed}}export{planProfileApplication};
1
+ import{normalizeAddTypeInput as f,parseItemTypesFile as w,serializeItemTypesFile as k,upsertItemType as F}from"../schema/item-types-file.js";import{normalizeAddStatusInput as m,parseStatusDefsFile as S,serializeStatusDefsFile as I,upsertStatusDef as T}from"../schema/status-defs-file.js";import{normalizeAddFieldInput as g,parseFieldsFile as v,serializeFieldsFile as z,upsertField as N}from"../schema/fields-file.js";import{parseNestedSettingValue as $,readNestedSettingValue as x,resolveNestedSettingDescriptor as A}from"../config/nested-settings.js";function l(s,o,a,e,t){let n=s;const i=[];for(const r of o){const u=e(n),d=t(n,r),c=e(d.file);n=d.file;const p=u===c?"unchanged":d.replaced?"update":"add";i.push({key:a(r),status:p})}return{file:n,changes:i,changed:i.some(r=>r.status!=="unchanged")}}function h(s){return JSON.stringify(s.map(o=>o.join("\0")).sort())}function D(s,o){const a=s.map(t=>({...t})),e=[];for(const t of o){const n=a.findIndex(r=>r.type===t.type),i={type:t.type,allowed_transitions:t.allowed_transitions};n<0?(a.push(i),e.push({type:t.type,status:"add"})):h(a[n].allowed_transitions)===h(t.allowed_transitions)?e.push({type:t.type,status:"unchanged"}):(a[n]=i,e.push({type:t.type,status:"update"}))}return{changes:e,result:a,changed:e.some(t=>t.status!=="unchanged")}}function O(s,o){const a=[];for(const e of s.config){const t=A(e.key);if(t===void 0)throw new Error(`Profile "${s.name}" references unknown config key "${e.key}".`);const n=$(t,e.value);if(!n.ok)throw new Error(`Profile "${s.name}" config ${e.key}: ${n.error.message}`);const i=x(o,t),r=i===null?"add":i===n.parsed.value?"unchanged":"update";a.push({key:t.key,path:t.path,value:n.parsed.value,status:r})}return{changes:a,changed:a.some(e=>e.status!=="unchanged")}}function y(s){const o=Object.entries(s).sort(([a],[e])=>a.localeCompare(e));return JSON.stringify(o)}function P(s,o){const a=[];for(const e of s.templates){const t=o.get(e.name);let n;t===void 0?n="add":y(t)===y(e.options)?n="unchanged":n="update",a.push({name:e.name,options:e.options,status:n})}return{changes:a,changed:a.some(e=>e.status!=="unchanged")}}function j(s,o){const a=l(w(o.typesRaw),s.types,c=>f(c).name,k,(c,p)=>F(c,f(p))),e=l(S(o.statusesRaw),s.statuses,c=>m(c).id,I,(c,p)=>T(c,m(p))),t=l(v(o.fieldsRaw),s.fields,c=>g(c).key,z,(c,p)=>N(c,g(p))),n=D(o.workflows,s.workflows),i=O(s,o.settings),r=P(s,o.templates),u=s.packages.map(c=>({spec:c.spec,reason:c.reason,status:o.installedPackages.has(c.spec)?"installed":"recommended"})),d=a.changed||e.changed||t.changed||n.changed||i.changed||r.changed;return{profile:{name:s.name,title:s.title,summary:s.summary},types:a,statuses:e,fields:t,workflows:n,config:i,templates:r,packages:u,changed:d}}export{j as planProfileApplication};
2
2
  //# sourceMappingURL=profile-plan.js.map