@lightdash-tools/mcp 0.8.0 → 0.11.0

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 (339) hide show
  1. package/README.md +112 -236
  2. package/dist/audit/server-profile.d.ts +13 -0
  3. package/dist/audit/server-profile.js +28 -0
  4. package/dist/audit/server-profile.test.js +21 -0
  5. package/dist/auth/oauth-broker/pending-store.d.ts +6 -7
  6. package/dist/auth/oauth-broker/pending-store.js +3 -4
  7. package/dist/auth/oauth-broker/pending-store.test.d.ts +2 -3
  8. package/dist/auth/oauth-broker/pending-store.test.js +2 -39
  9. package/dist/auth/oauth-broker/routes.d.ts +1 -1
  10. package/dist/auth/oauth-broker/routes.js +3 -3
  11. package/dist/auth/oauth-broker/routes.test.js +1 -1
  12. package/dist/auth/request-state-key.d.ts +19 -0
  13. package/dist/auth/request-state-key.js +49 -0
  14. package/dist/auth/resource-server/lightdash-oauth-middleware.d.ts +1 -3
  15. package/dist/auth/resource-server/lightdash-oauth-middleware.js +1 -20
  16. package/dist/auth/resource-server/lightdash-oauth-middleware.test.js +14 -14
  17. package/dist/auth/resource-server/oauth-protected-resource.d.ts +6 -6
  18. package/dist/auth/resource-server/oauth-protected-resource.js +8 -8
  19. package/dist/auth/resource-server/token-scopes.d.ts +1 -1
  20. package/dist/auth/resource-server/token-scopes.js +1 -1
  21. package/dist/auth/resource-server/www-authenticate.test.js +11 -13
  22. package/dist/bin.js +54 -51
  23. package/dist/config/env.d.ts +8 -16
  24. package/dist/config/env.js +9 -17
  25. package/dist/config/load-mcp-config.d.ts +0 -4
  26. package/dist/config/load-mcp-config.js +9 -38
  27. package/dist/config/load-mcp-config.test.js +8 -2
  28. package/dist/config/normalize-url.d.ts +1 -1
  29. package/dist/config/normalize-url.js +1 -1
  30. package/dist/config/normalize-url.test.js +16 -13
  31. package/dist/config/obsolete-env.d.ts +5 -0
  32. package/dist/config/obsolete-env.js +48 -0
  33. package/dist/config/obsolete-env.test.js +22 -0
  34. package/dist/config/runtime.d.ts +3 -3
  35. package/dist/config/runtime.js +19 -23
  36. package/dist/config/runtime.test.js +23 -9
  37. package/dist/config/test-mcp-http-config.js +1 -1
  38. package/dist/destructive/content-promote.js +7 -1
  39. package/dist/destructive/promote-contract.test.js +106 -47
  40. package/dist/destructive/register-destructive-tool.js +6 -24
  41. package/dist/destructive/request-state.d.ts +2 -6
  42. package/dist/destructive/request-state.js +3 -38
  43. package/dist/destructive/types.d.ts +2 -1
  44. package/dist/governance/available-projects.d.ts +37 -0
  45. package/dist/governance/available-projects.js +132 -0
  46. package/dist/governance/available-projects.test.d.ts +4 -0
  47. package/dist/governance/available-projects.test.js +107 -0
  48. package/dist/governance/mcp-client-session.d.ts +3 -2
  49. package/dist/governance/mcp-client-session.js +3 -2
  50. package/dist/governance/mcp-post-factory-context.d.ts +15 -0
  51. package/dist/governance/mcp-post-factory-context.js +22 -0
  52. package/dist/governance/mcp-post-factory-context.test.js +34 -0
  53. package/dist/governance/project-scope.d.ts +8 -22
  54. package/dist/governance/project-scope.js +36 -44
  55. package/dist/governance/project-scope.test.d.ts +1 -1
  56. package/dist/governance/project-scope.test.js +21 -44
  57. package/dist/governance/promote-allowlist.d.ts +18 -0
  58. package/dist/governance/promote-allowlist.js +66 -0
  59. package/dist/governance/promote-allowlist.test.d.ts +4 -0
  60. package/dist/governance/promote-allowlist.test.js +87 -0
  61. package/dist/http.integration.test.js +116 -265
  62. package/dist/http.test.js +0 -12
  63. package/dist/index.d.ts +5 -1
  64. package/dist/index.integration.test.js +0 -4
  65. package/dist/index.js +31 -16
  66. package/dist/policy/content-developer.d.ts +3 -3
  67. package/dist/policy/content-developer.js +3 -3
  68. package/dist/policy/content-developer.test.js +10 -4
  69. package/dist/policy/content-reader.d.ts +15 -6
  70. package/dist/policy/content-reader.js +39 -10
  71. package/dist/policy/content-reader.test.js +5 -3
  72. package/dist/policy/envelope.d.ts +4 -2
  73. package/dist/policy/envelope.js +2 -2
  74. package/dist/policy/envelope.test.js +28 -0
  75. package/dist/policy/preview-ledger-fault.test.js +101 -426
  76. package/dist/policy/preview-ledger.d.ts +38 -74
  77. package/dist/policy/preview-ledger.js +108 -186
  78. package/dist/policy/preview-ledger.test.js +237 -111
  79. package/dist/policy/result-limits.d.ts +6 -1
  80. package/dist/policy/result-limits.js +28 -29
  81. package/dist/policy/result-limits.test.js +10 -1
  82. package/dist/profiles/ai-agent-ops/v1/index.d.ts +6 -0
  83. package/dist/profiles/ai-agent-ops/v1/index.js +20 -0
  84. package/dist/profiles/ai-agent-ops/v1/prompts.d.ts +5 -0
  85. package/dist/profiles/ai-agent-ops/v1/prompts.js +141 -0
  86. package/dist/profiles/ai-agent-ops/v1/prompts.test.d.ts +4 -0
  87. package/dist/profiles/ai-agent-ops/v1/prompts.test.js +26 -0
  88. package/dist/profiles/ai-agent-ops/v1/resources/playbooks/core.md +39 -0
  89. package/dist/profiles/ai-agent-ops/v1/resources/playbooks/evaluation.md +25 -0
  90. package/dist/profiles/ai-agent-ops/v1/resources/playbooks/index.md +14 -0
  91. package/dist/profiles/ai-agent-ops/v1/resources/playbooks/loop-engineering.md +28 -0
  92. package/dist/profiles/ai-agent-ops/v1/resources/playbooks/release-gate.md +22 -0
  93. package/dist/profiles/ai-agent-ops/v1/resources/playbooks.d.ts +10 -0
  94. package/dist/profiles/ai-agent-ops/v1/resources/playbooks.js +41 -0
  95. package/dist/profiles/content-developer/v1/index.d.ts +8 -0
  96. package/dist/profiles/content-developer/v1/index.js +22 -0
  97. package/dist/{personas → profiles}/content-developer/v1/prompts.d.ts +3 -0
  98. package/dist/profiles/content-developer/v1/prompts.js +157 -0
  99. package/dist/profiles/content-developer/v1/prompts.test.js +286 -0
  100. package/dist/profiles/content-developer/v1/resources/playbooks/chart-types.md +138 -0
  101. package/dist/profiles/content-developer/v1/resources/playbooks/content-move.md +22 -0
  102. package/dist/profiles/content-developer/v1/resources/playbooks/core.md +109 -0
  103. package/dist/profiles/content-developer/v1/resources/playbooks/dashboard-design.md +153 -0
  104. package/dist/profiles/content-developer/v1/resources/playbooks/dashboards.md +108 -0
  105. package/dist/profiles/content-developer/v1/resources/playbooks/index.md +15 -0
  106. package/dist/{personas → profiles}/content-developer/v1/resources/playbooks.d.ts +1 -1
  107. package/dist/profiles/content-developer/v1/resources/playbooks.js +65 -0
  108. package/dist/profiles/content-governance/v1/index.d.ts +7 -0
  109. package/dist/profiles/content-governance/v1/index.js +21 -0
  110. package/dist/{personas → profiles}/content-governance/v1/prompts.test.js +2 -2
  111. package/dist/{personas → profiles}/content-governance/v1/resources/playbooks/core.md +3 -3
  112. package/dist/{personas → profiles}/content-governance/v1/resources/playbooks/dashboards.md +1 -1
  113. package/dist/{personas → profiles}/content-governance/v1/resources/playbooks.js +4 -4
  114. package/dist/profiles/content-reader/v1/index.d.ts +6 -0
  115. package/dist/profiles/content-reader/v1/index.js +20 -0
  116. package/dist/profiles/content-reader/v1/prompts.js +162 -0
  117. package/dist/{personas → profiles}/content-reader/v1/prompts.test.js +2 -2
  118. package/dist/profiles/content-reader/v1/resources/playbooks/compare.md +36 -0
  119. package/dist/profiles/content-reader/v1/resources/playbooks/core.md +67 -0
  120. package/dist/profiles/content-reader/v1/resources/playbooks/discover.md +35 -0
  121. package/dist/profiles/content-reader/v1/resources/playbooks/explain-run.md +49 -0
  122. package/dist/profiles/content-reader/v1/resources/playbooks/index.md +14 -0
  123. package/dist/{personas → profiles}/content-reader/v1/resources/playbooks.js +4 -4
  124. package/dist/profiles/data-analyst/v1/index.d.ts +6 -0
  125. package/dist/profiles/data-analyst/v1/index.js +20 -0
  126. package/dist/profiles/data-analyst/v1/prompts.d.ts +5 -0
  127. package/dist/profiles/data-analyst/v1/prompts.js +41 -0
  128. package/dist/profiles/data-analyst/v1/prompts.test.d.ts +4 -0
  129. package/dist/profiles/data-analyst/v1/prompts.test.js +26 -0
  130. package/dist/profiles/data-analyst/v1/resources/playbooks/core.md +41 -0
  131. package/dist/profiles/data-analyst/v1/resources/playbooks/explore.md +26 -0
  132. package/dist/profiles/data-analyst/v1/resources/playbooks/index.md +8 -0
  133. package/dist/profiles/data-analyst/v1/resources/playbooks.d.ts +10 -0
  134. package/dist/profiles/data-analyst/v1/resources/playbooks.js +33 -0
  135. package/dist/profiles/index.d.ts +24 -0
  136. package/dist/profiles/index.js +73 -0
  137. package/dist/profiles/index.test.js +121 -0
  138. package/dist/{personas → profiles}/lib/playbook-resources.d.ts +12 -10
  139. package/dist/{personas → profiles}/lib/playbook-resources.js +28 -24
  140. package/dist/profiles/organization-audit/v1/index.d.ts +6 -0
  141. package/dist/profiles/organization-audit/v1/index.js +20 -0
  142. package/dist/profiles/organization-audit/v1/prompts.js +124 -0
  143. package/dist/{personas → profiles}/organization-audit/v1/prompts.test.js +2 -2
  144. package/dist/profiles/organization-audit/v1/resources/playbooks/access.md +21 -0
  145. package/dist/profiles/organization-audit/v1/resources/playbooks/content.md +19 -0
  146. package/dist/profiles/organization-audit/v1/resources/playbooks/core.md +69 -0
  147. package/dist/profiles/organization-audit/v1/resources/playbooks/deliveries.md +14 -0
  148. package/dist/profiles/organization-audit/v1/resources/playbooks/index.md +14 -0
  149. package/dist/{personas → profiles}/organization-audit/v1/resources/playbooks.js +3 -3
  150. package/dist/profiles/profile.membership.test.js +36 -0
  151. package/dist/profiles/semantic-layer/v1/index.d.ts +6 -0
  152. package/dist/profiles/semantic-layer/v1/index.js +19 -0
  153. package/dist/profiles/semantic-layer/v1/prompts.js +96 -0
  154. package/dist/{personas → profiles}/semantic-layer/v1/prompts.test.js +2 -2
  155. package/dist/profiles/semantic-layer/v1/resources/playbooks/compose-compile.md +60 -0
  156. package/dist/profiles/semantic-layer/v1/resources/playbooks/core.md +71 -0
  157. package/dist/profiles/semantic-layer/v1/resources/playbooks/explore.md +79 -0
  158. package/dist/profiles/semantic-layer/v1/resources/playbooks/index.md +13 -0
  159. package/dist/{personas → profiles}/semantic-layer/v1/resources/playbooks.js +4 -4
  160. package/dist/{personas → profiles}/types.d.ts +6 -7
  161. package/dist/{personas → profiles}/types.js +1 -1
  162. package/dist/protocol-contract.test.js +48 -3
  163. package/dist/server/capabilities.d.ts +6 -6
  164. package/dist/server/capabilities.js +11 -8
  165. package/dist/server/capabilities.test.js +8 -7
  166. package/dist/server/server.js +17 -13
  167. package/dist/server/upstream-errors.d.ts +17 -0
  168. package/dist/server/upstream-errors.js +60 -0
  169. package/dist/server/upstream-errors.test.js +50 -0
  170. package/dist/stdio.process.test.js +65 -9
  171. package/dist/tools/ai-agents/agents.d.ts +7 -0
  172. package/dist/tools/ai-agents/agents.js +32 -0
  173. package/dist/tools/ai-agents/agents.test.d.ts +1 -0
  174. package/dist/tools/ai-agents/agents.test.js +176 -0
  175. package/dist/tools/ai-agents/discovery.d.ts +9 -0
  176. package/dist/tools/ai-agents/discovery.js +73 -0
  177. package/dist/tools/ai-agents/evaluations.d.ts +14 -0
  178. package/dist/tools/ai-agents/evaluations.js +177 -0
  179. package/dist/tools/ai-agents/helpers.d.ts +63 -0
  180. package/dist/tools/ai-agents/helpers.js +321 -0
  181. package/dist/tools/ai-agents/threads.d.ts +7 -0
  182. package/dist/tools/ai-agents/threads.js +40 -0
  183. package/dist/tools/composition/explain-content.js +3 -1
  184. package/dist/tools/index.d.ts +1 -1
  185. package/dist/tools/index.js +1 -1
  186. package/dist/tools/index.test.js +16 -10
  187. package/dist/tools/lib/schema-fields.d.ts +2 -0
  188. package/dist/tools/lib/schema-fields.js +4 -1
  189. package/dist/tools/lib/stable-stringify.d.ts +1 -1
  190. package/dist/tools/lib/stable-stringify.js +1 -1
  191. package/dist/tools/organization/invariants.test.d.ts +1 -1
  192. package/dist/tools/organization/invariants.test.js +5 -5
  193. package/dist/tools/organization/inventory.js +2 -1
  194. package/dist/tools/project/content.js +5 -1
  195. package/dist/tools/project/developer-content-preview.d.ts +3 -2
  196. package/dist/tools/project/developer-content-preview.js +41 -36
  197. package/dist/tools/project/developer-content-shared.d.ts +9 -3
  198. package/dist/tools/project/developer-content-shared.js +8 -4
  199. package/dist/tools/project/developer-content.d.ts +7 -8
  200. package/dist/tools/project/developer-content.js +72 -67
  201. package/dist/tools/project/developer-get-chart-as-code.d.ts +9 -0
  202. package/dist/tools/project/developer-get-chart-as-code.js +39 -0
  203. package/dist/tools/project/developer-get-chart-as-code.test.d.ts +4 -0
  204. package/dist/tools/project/developer-get-chart-as-code.test.js +70 -0
  205. package/dist/tools/project/developer-helpers.d.ts +1 -1
  206. package/dist/tools/project/developer-helpers.js +1 -1
  207. package/dist/tools/project/get-dashboard-promote-diff.js +12 -2
  208. package/dist/tools/project/invariants.test.d.ts +1 -1
  209. package/dist/tools/project/invariants.test.js +12 -10
  210. package/dist/tools/project/parameters.js +8 -3
  211. package/dist/tools/project/projects.d.ts +1 -4
  212. package/dist/tools/project/projects.js +37 -15
  213. package/dist/tools/project/projects.test.js +70 -8
  214. package/dist/tools/project/reader-content.js +6 -3
  215. package/dist/tools/project/reader-execution.js +4 -2
  216. package/dist/tools/project/reader-export-chart-image.d.ts +6 -0
  217. package/dist/tools/project/reader-export-chart-image.js +78 -0
  218. package/dist/tools/project/reader-export-chart-image.test.d.ts +4 -0
  219. package/dist/tools/project/reader-export-chart-image.test.js +149 -0
  220. package/dist/tools/project/spaces.js +12 -4
  221. package/dist/tools/project/spaces.test.d.ts +1 -0
  222. package/dist/tools/project/spaces.test.js +47 -0
  223. package/dist/tools/query/bounded-saved-query.d.ts +4 -3
  224. package/dist/tools/query/bounded-saved-query.js +4 -6
  225. package/dist/tools/query/lifecycle.d.ts +1 -1
  226. package/dist/tools/query/lifecycle.js +25 -31
  227. package/dist/tools/query/query-ledger.d.ts +17 -9
  228. package/dist/tools/query/query-ledger.js +21 -15
  229. package/dist/tools/query/query-ledger.test.js +13 -11
  230. package/dist/tools/query/reader-tool-helpers.d.ts +4 -2
  231. package/dist/tools/query/reader-tool-helpers.js +11 -8
  232. package/dist/tools/query/reader-tool-helpers.test.js +8 -4
  233. package/dist/tools/query/run-metric-query.d.ts +6 -0
  234. package/dist/tools/query/run-metric-query.js +94 -0
  235. package/dist/tools/query/run-metric-query.test.d.ts +4 -0
  236. package/dist/tools/query/run-metric-query.test.js +116 -0
  237. package/dist/tools/registry.d.ts +71 -8
  238. package/dist/tools/registry.js +36 -6
  239. package/dist/tools/semantic/explores.js +43 -17
  240. package/dist/tools/semantic/metrics.js +22 -8
  241. package/dist/tools/semantic/query.js +25 -17
  242. package/dist/tools/shared.d.ts +28 -9
  243. package/dist/tools/shared.js +62 -29
  244. package/dist/tools/shared.test.js +100 -4
  245. package/dist/transports/streamable-http.js +75 -223
  246. package/dist/transports/streamable-http.test.js +19 -12
  247. package/package.json +5 -6
  248. package/dist/destructive/confirmation-claim.d.ts +0 -21
  249. package/dist/destructive/confirmation-claim.js +0 -87
  250. package/dist/destructive/confirmation-claim.test.js +0 -50
  251. package/dist/personas/content-developer/v1/index.d.ts +0 -10
  252. package/dist/personas/content-developer/v1/index.js +0 -51
  253. package/dist/personas/content-developer/v1/prompts.js +0 -138
  254. package/dist/personas/content-developer/v1/prompts.test.js +0 -75
  255. package/dist/personas/content-developer/v1/resources/playbooks/content-move.md +0 -15
  256. package/dist/personas/content-developer/v1/resources/playbooks/core.md +0 -63
  257. package/dist/personas/content-developer/v1/resources/playbooks/dashboards.md +0 -55
  258. package/dist/personas/content-developer/v1/resources/playbooks/index.md +0 -13
  259. package/dist/personas/content-developer/v1/resources/playbooks.js +0 -44
  260. package/dist/personas/content-governance/v1/index.d.ts +0 -9
  261. package/dist/personas/content-governance/v1/index.js +0 -29
  262. package/dist/personas/content-reader/v1/index.d.ts +0 -8
  263. package/dist/personas/content-reader/v1/index.js +0 -37
  264. package/dist/personas/content-reader/v1/prompts.js +0 -128
  265. package/dist/personas/content-reader/v1/resources/playbooks/compare.md +0 -21
  266. package/dist/personas/content-reader/v1/resources/playbooks/core.md +0 -40
  267. package/dist/personas/content-reader/v1/resources/playbooks/discover.md +0 -13
  268. package/dist/personas/content-reader/v1/resources/playbooks/explain-run.md +0 -19
  269. package/dist/personas/content-reader/v1/resources/playbooks/index.md +0 -14
  270. package/dist/personas/index.d.ts +0 -22
  271. package/dist/personas/index.js +0 -73
  272. package/dist/personas/index.test.js +0 -109
  273. package/dist/personas/organization-audit/v1/index.d.ts +0 -8
  274. package/dist/personas/organization-audit/v1/index.js +0 -42
  275. package/dist/personas/organization-audit/v1/prompts.js +0 -92
  276. package/dist/personas/organization-audit/v1/resources/playbooks/access.md +0 -13
  277. package/dist/personas/organization-audit/v1/resources/playbooks/content.md +0 -9
  278. package/dist/personas/organization-audit/v1/resources/playbooks/core.md +0 -36
  279. package/dist/personas/organization-audit/v1/resources/playbooks/deliveries.md +0 -9
  280. package/dist/personas/organization-audit/v1/resources/playbooks/index.md +0 -14
  281. package/dist/personas/persona.parity.test.js +0 -26
  282. package/dist/personas/semantic-layer/v1/index.d.ts +0 -8
  283. package/dist/personas/semantic-layer/v1/index.js +0 -32
  284. package/dist/personas/semantic-layer/v1/prompts.js +0 -85
  285. package/dist/personas/semantic-layer/v1/resources/playbooks/compose-compile.md +0 -55
  286. package/dist/personas/semantic-layer/v1/resources/playbooks/core.md +0 -39
  287. package/dist/personas/semantic-layer/v1/resources/playbooks/explore.md +0 -76
  288. package/dist/personas/semantic-layer/v1/resources/playbooks/index.md +0 -13
  289. package/dist/store/config.d.ts +0 -11
  290. package/dist/store/config.js +0 -50
  291. package/dist/store/config.test.js +0 -56
  292. package/dist/store/create-oauth-broker-store.d.ts +0 -6
  293. package/dist/store/create-oauth-broker-store.js +0 -16
  294. package/dist/store/create-preview-store.d.ts +0 -10
  295. package/dist/store/create-preview-store.js +0 -30
  296. package/dist/store/create-session-store.d.ts +0 -19
  297. package/dist/store/create-session-store.js +0 -24
  298. package/dist/store/in-memory-preview-store.d.ts +0 -17
  299. package/dist/store/in-memory-preview-store.js +0 -72
  300. package/dist/store/redis-client.d.ts +0 -11
  301. package/dist/store/redis-client.js +0 -48
  302. package/dist/store/redis-oauth-broker-store.d.ts +0 -42
  303. package/dist/store/redis-oauth-broker-store.js +0 -167
  304. package/dist/store/redis-oauth-broker-store.test.js +0 -80
  305. package/dist/store/redis-preview-store.d.ts +0 -23
  306. package/dist/store/redis-preview-store.js +0 -94
  307. package/dist/store/redis-preview-store.test.js +0 -39
  308. package/dist/store/redis-session-index.d.ts +0 -33
  309. package/dist/store/redis-session-index.js +0 -49
  310. package/dist/store/types.d.ts +0 -13
  311. package/dist/store/types.js +0 -8
  312. package/dist/transports/http-request-utils.d.ts +0 -2
  313. package/dist/transports/http-request-utils.js +0 -13
  314. package/dist/transports/session-store.d.ts +0 -72
  315. package/dist/transports/session-store.js +0 -143
  316. package/dist/transports/session-store.test.js +0 -111
  317. /package/dist/{destructive/confirmation-claim.test.d.ts → audit/server-profile.test.d.ts} +0 -0
  318. /package/dist/{personas/index.test.d.ts → config/obsolete-env.test.d.ts} +0 -0
  319. /package/dist/{personas/persona.parity.test.d.ts → governance/mcp-post-factory-context.test.d.ts} +0 -0
  320. /package/dist/{store/config.test.d.ts → policy/envelope.test.d.ts} +0 -0
  321. /package/dist/{personas → profiles}/content-developer/v1/prompts.test.d.ts +0 -0
  322. /package/dist/{personas → profiles}/content-governance/v1/prompts.d.ts +0 -0
  323. /package/dist/{personas → profiles}/content-governance/v1/prompts.js +0 -0
  324. /package/dist/{personas → profiles}/content-governance/v1/prompts.test.d.ts +0 -0
  325. /package/dist/{personas → profiles}/content-governance/v1/resources/playbooks/charts.md +0 -0
  326. /package/dist/{personas → profiles}/content-governance/v1/resources/playbooks/index.md +0 -0
  327. /package/dist/{personas → profiles}/content-governance/v1/resources/playbooks.d.ts +0 -0
  328. /package/dist/{personas → profiles}/content-reader/v1/prompts.d.ts +0 -0
  329. /package/dist/{personas → profiles}/content-reader/v1/prompts.test.d.ts +0 -0
  330. /package/dist/{personas → profiles}/content-reader/v1/resources/playbooks.d.ts +0 -0
  331. /package/dist/{store/redis-oauth-broker-store.test.d.ts → profiles/index.test.d.ts} +0 -0
  332. /package/dist/{personas → profiles}/organization-audit/v1/prompts.d.ts +0 -0
  333. /package/dist/{personas → profiles}/organization-audit/v1/prompts.test.d.ts +0 -0
  334. /package/dist/{personas → profiles}/organization-audit/v1/resources/playbooks.d.ts +0 -0
  335. /package/dist/{store/redis-preview-store.test.d.ts → profiles/profile.membership.test.d.ts} +0 -0
  336. /package/dist/{personas → profiles}/semantic-layer/v1/prompts.d.ts +0 -0
  337. /package/dist/{personas → profiles}/semantic-layer/v1/prompts.test.d.ts +0 -0
  338. /package/dist/{personas → profiles}/semantic-layer/v1/resources/playbooks.d.ts +0 -0
  339. /package/dist/{transports/session-store.test.d.ts → server/upstream-errors.test.d.ts} +0 -0
@@ -1,118 +1,82 @@
1
1
  /**
2
- * Session-scoped preview ledger for content-developer (ADR-0014 / ADR-0016).
2
+ * HMAC-signed preview tokens for content-developer (ADR-0014 / ADR-0019).
3
3
  *
4
- * Hard gate: every SAFE_WRITE tool requires a session-owned, validated, unexpired
5
- * `previewId` whose `contentHash` matches the exact payload being applied.
6
- *
7
- * Apply path: claim (`validated` → `applying` via CAS) → mutate → mark applied or
8
- * release/reconcile. Never delete-before-I/O as the sole path.
4
+ * Hard gate: every SAFE_WRITE requires a validated, unexpired `previewToken` whose
5
+ * `contentHash` matches `{ proposed, baseline }`. Tokens are client-carried (no server
6
+ * ledger). confirm_preview mints a validated token; apply verifies + re-sends proposed.
9
7
  */
8
+ import type { ServerContext } from '@modelcontextprotocol/server';
10
9
  export declare const PREVIEW_RESOURCE_KINDS: readonly ["chart", "content-move", "dashboard"];
11
10
  export type PreviewResourceKind = (typeof PREVIEW_RESOURCE_KINDS)[number];
12
- export type PreviewStatus = 'applying' | 'draft' | 'reconciliation_required' | 'validated';
11
+ export type PreviewStatus = 'draft' | 'validated';
13
12
  /** Snapshot identity captured when the preview was issued (for update stale detection). */
14
13
  export type PreviewBaseline = {
15
14
  updatedAt?: string;
16
15
  uuid?: string;
17
16
  slug?: string;
18
17
  };
19
- export type PreviewLedgerEntry = {
18
+ /** Compact claims embedded in the HMAC-signed previewToken (no proposed body). */
19
+ export type PreviewTokenClaims = {
20
20
  previewId: string;
21
- sessionId: string;
21
+ subject: string;
22
22
  projectUuid: string;
23
23
  resourceKind: PreviewResourceKind;
24
- /** Primary uuid/slug/'new'/joined item keys identifying the resource being previewed. */
25
24
  resourceKey: string;
26
- /**
27
- * Alternate identifiers accepted for validate/consume matching (e.g. chart UUID and
28
- * upsert slug). Always includes `resourceKey`.
29
- */
30
25
  resourceAliases: readonly string[];
31
- /** sha256 of the canonical JSON of `{ proposed, baseline }`. */
32
26
  contentHash: string;
33
27
  status: PreviewStatus;
34
- proposed: unknown;
35
28
  baseline?: PreviewBaseline;
36
29
  createdAt: string;
37
30
  expiresAt: string;
38
31
  };
39
- /** Pluggable persistence for preview ledger entries (ADR-0016). */
40
- export interface PreviewStore {
41
- get(previewId: string): Promise<PreviewLedgerEntry | undefined>;
42
- put(entry: PreviewLedgerEntry): Promise<void>;
43
- /** Atomic status transition; returns false if expected status mismatch / missing */
44
- compareAndSwap(previewId: string, expectedStatus: PreviewStatus, next: PreviewLedgerEntry): Promise<boolean>;
45
- /** Atomic delete when current status matches; returns false on mismatch / missing */
46
- compareAndDelete(previewId: string, expectedStatus: PreviewStatus): Promise<boolean>;
47
- delete(previewId: string): Promise<void>;
48
- }
49
32
  export declare class PreviewLedgerError extends Error {
50
- readonly code: 'PREVIEW_EXPIRED' | 'PREVIEW_NOT_OWNED' | 'PREVIEW_NOT_VALIDATED' | 'PREVIEW_RECONCILIATION_REQUIRED' | 'PREVIEW_REQUIRED' | 'PREVIEW_STALE';
33
+ readonly code: 'PREVIEW_NOT_OWNED' | 'PREVIEW_NOT_VALIDATED' | 'PREVIEW_REQUIRED' | 'PREVIEW_STALE';
51
34
  constructor(code: PreviewLedgerError['code'], message: string);
52
35
  }
53
36
  /** Default preview lifetime; short enough to discourage stale multi-step drift. */
54
37
  export declare const DEFAULT_PREVIEW_TTL_MS: number;
55
- /** sha256 hex digest of the stable JSON form of `value`. */
38
+ /** Minimal ServerContext for unit tests that mint/verify without a live MCP request. */
39
+ export declare const EMPTY_SERVER_CONTEXT: ServerContext;
40
+ /** Reset codec (tests only). */
41
+ export declare function resetPreviewLedgerForTests(): void;
42
+ /** sha256 hex digest of the stable JSON form of `value` (preview binding hash). */
56
43
  export declare function hashPreviewContent(value: unknown): string;
57
44
  export declare function uniqueResourceKeys(...keys: Array<string | null | undefined>): string[];
58
- /**
59
- * Classify upstream mutation failures for release vs reconcile.
60
- * HTTP 4xx (except 408/429) prove no successful mutation → release to validated.
61
- * Timeouts / 5xx / network / rate-limit → reconciliation_required.
62
- */
63
- export declare function classifyMutationFailure(err: unknown): 'reconcile' | 'release';
64
- export declare function addPreviewLedgerEntry(input: {
65
- sessionId: string;
45
+ /** Mint a draft previewToken (opaque HMAC blob). Does not store proposed on the server. */
46
+ export declare function mintDraftPreviewToken(input: {
47
+ subject: string;
66
48
  projectUuid: string;
67
49
  resourceKind: PreviewResourceKind;
68
50
  resourceKey: string;
69
- /** Extra aliases (uuid/slug) accepted for validate/consume. */
70
51
  resourceAliases?: readonly string[];
71
52
  proposed: unknown;
72
53
  baseline?: PreviewBaseline;
73
- ttlMs?: number;
74
- }): Promise<PreviewLedgerEntry>;
75
- /** Look up a preview by id, enforcing session/project ownership and expiry. */
76
- export declare function getOwnedPreview(input: {
77
- previewId: string;
78
- sessionId: string;
54
+ serverContext?: ServerContext;
55
+ }): Promise<{
56
+ previewToken: string;
57
+ claims: PreviewTokenClaims;
58
+ }>;
59
+ /** Confirm a draft token: verify bindings and mint a validated token (no server write). */
60
+ export declare function confirmPreviewToken(input: {
61
+ previewToken: string;
62
+ subject: string;
79
63
  projectUuid: string;
80
- }): Promise<PreviewLedgerEntry>;
81
- /**
82
- * Mark a draft preview validated after a successful confirm_preview call.
83
- * `expected` binds validation to the resource it was actually run against.
84
- */
85
- export declare function markPreviewValidated(previewId: string, sessionId: string, projectUuid: string, expected: {
86
64
  resourceKind: PreviewResourceKind;
87
65
  resourceKey: string;
88
- }): Promise<PreviewLedgerEntry>;
89
- export type ClaimPreviewForApplyInput = {
90
- previewId: string;
91
- sessionId: string;
66
+ serverContext?: ServerContext;
67
+ }): Promise<{
68
+ previewToken: string;
69
+ claims: PreviewTokenClaims;
70
+ }>;
71
+ export type ApplyPreviewTokenInput = {
72
+ previewToken: string;
73
+ subject: string;
92
74
  projectUuid: string;
93
75
  resourceKind: PreviewResourceKind;
94
76
  resourceKey: string;
95
77
  proposed: unknown;
96
- /** Fresh resource snapshot for baseline stale detection (update and create races). */
97
78
  currentBaseline?: PreviewBaseline;
79
+ serverContext?: ServerContext;
98
80
  };
99
- /**
100
- * Claim a validated preview for apply (`validated` → `applying` via CAS).
101
- * Same kind/key/hash/baseline checks as the former consume path, but does not delete.
102
- */
103
- export declare function claimPreviewForApply(input: ClaimPreviewForApplyInput): Promise<PreviewLedgerEntry>;
104
- /** Delete a claimed preview when still `applying` (single-use completion). */
105
- export declare function markPreviewApplied(previewId: string): Promise<void>;
106
- /**
107
- * After a failed mutation: known no-write failures return to `validated`;
108
- * uncertain outcomes move to `reconciliation_required`.
109
- */
110
- export declare function releaseOrReconcilePreview(previewId: string, err: unknown): Promise<void>;
111
- /**
112
- * Claim → run mutation → mark applied; on mutation failure release/reconcile and rethrow.
113
- * After a successful mutation, never release/reconcile if mark-applied fails (would invite
114
- * double-apply); log and return the mutation result instead.
115
- */
116
- export declare function withClaimedPreviewApply<T>(claimInput: ClaimPreviewForApplyInput, fn: (entry: PreviewLedgerEntry) => Promise<T>): Promise<T>;
117
- /** Test helper: reset to a fresh in-memory store. */
118
- export declare function resetPreviewLedgerForTests(): void;
81
+ /** Verify validated token then run mutation (ADR-0019: no server-side claim/release). */
82
+ export declare function withValidatedPreviewApply<T>(input: ApplyPreviewTokenInput, fn: (claims: PreviewTokenClaims) => Promise<T>): Promise<T>;
@@ -1,30 +1,22 @@
1
1
  "use strict";
2
2
  /**
3
- * Session-scoped preview ledger for content-developer (ADR-0014 / ADR-0016).
3
+ * HMAC-signed preview tokens for content-developer (ADR-0014 / ADR-0019).
4
4
  *
5
- * Hard gate: every SAFE_WRITE tool requires a session-owned, validated, unexpired
6
- * `previewId` whose `contentHash` matches the exact payload being applied.
7
- *
8
- * Apply path: claim (`validated` → `applying` via CAS) → mutate → mark applied or
9
- * release/reconcile. Never delete-before-I/O as the sole path.
5
+ * Hard gate: every SAFE_WRITE requires a validated, unexpired `previewToken` whose
6
+ * `contentHash` matches `{ proposed, baseline }`. Tokens are client-carried (no server
7
+ * ledger). confirm_preview mints a validated token; apply verifies + re-sends proposed.
10
8
  */
11
9
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.DEFAULT_PREVIEW_TTL_MS = exports.PreviewLedgerError = exports.PREVIEW_RESOURCE_KINDS = void 0;
10
+ exports.EMPTY_SERVER_CONTEXT = exports.DEFAULT_PREVIEW_TTL_MS = exports.PreviewLedgerError = exports.PREVIEW_RESOURCE_KINDS = void 0;
11
+ exports.resetPreviewLedgerForTests = resetPreviewLedgerForTests;
13
12
  exports.hashPreviewContent = hashPreviewContent;
14
13
  exports.uniqueResourceKeys = uniqueResourceKeys;
15
- exports.classifyMutationFailure = classifyMutationFailure;
16
- exports.addPreviewLedgerEntry = addPreviewLedgerEntry;
17
- exports.getOwnedPreview = getOwnedPreview;
18
- exports.markPreviewValidated = markPreviewValidated;
19
- exports.claimPreviewForApply = claimPreviewForApply;
20
- exports.markPreviewApplied = markPreviewApplied;
21
- exports.releaseOrReconcilePreview = releaseOrReconcilePreview;
22
- exports.withClaimedPreviewApply = withClaimedPreviewApply;
23
- exports.resetPreviewLedgerForTests = resetPreviewLedgerForTests;
14
+ exports.mintDraftPreviewToken = mintDraftPreviewToken;
15
+ exports.confirmPreviewToken = confirmPreviewToken;
16
+ exports.withValidatedPreviewApply = withValidatedPreviewApply;
24
17
  const node_crypto_1 = require("node:crypto");
25
- const client_1 = require("@lightdash-tools/client");
26
- const create_preview_store_js_1 = require("../store/create-preview-store.js");
27
- const in_memory_preview_store_js_1 = require("../store/in-memory-preview-store.js");
18
+ const server_1 = require("@modelcontextprotocol/server");
19
+ const request_state_key_js_1 = require("../auth/request-state-key.js");
28
20
  const stable_stringify_js_1 = require("../tools/lib/stable-stringify.js");
29
21
  exports.PREVIEW_RESOURCE_KINDS = ['chart', 'content-move', 'dashboard'];
30
22
  class PreviewLedgerError extends Error {
@@ -37,7 +29,24 @@ class PreviewLedgerError extends Error {
37
29
  exports.PreviewLedgerError = PreviewLedgerError;
38
30
  /** Default preview lifetime; short enough to discourage stale multi-step drift. */
39
31
  exports.DEFAULT_PREVIEW_TTL_MS = 10 * 60000;
40
- /** sha256 hex digest of the stable JSON form of `value`. */
32
+ const TTL_SECONDS = exports.DEFAULT_PREVIEW_TTL_MS / 1000;
33
+ /** Minimal ServerContext for unit tests that mint/verify without a live MCP request. */
34
+ exports.EMPTY_SERVER_CONTEXT = { mcpReq: {} };
35
+ let codec;
36
+ function getPreviewTokenCodec() {
37
+ if (!codec) {
38
+ codec = (0, server_1.createRequestStateCodec)({
39
+ key: (0, request_state_key_js_1.resolveRequestStateKey)(request_state_key_js_1.PREVIEW_TOKEN_KEY_PURPOSE),
40
+ ttlSeconds: TTL_SECONDS,
41
+ });
42
+ }
43
+ return codec;
44
+ }
45
+ /** Reset codec (tests only). */
46
+ function resetPreviewLedgerForTests() {
47
+ codec = undefined;
48
+ }
49
+ /** sha256 hex digest of the stable JSON form of `value` (preview binding hash). */
41
50
  function hashPreviewContent(value) {
42
51
  return (0, stable_stringify_js_1.hashStableValue)(value);
43
52
  }
@@ -50,194 +59,107 @@ function uniqueResourceKeys(...keys) {
50
59
  }
51
60
  return out;
52
61
  }
53
- /**
54
- * Classify upstream mutation failures for release vs reconcile.
55
- * HTTP 4xx (except 408/429) prove no successful mutation → release to validated.
56
- * Timeouts / 5xx / network / rate-limit → reconciliation_required.
57
- */
58
- function classifyMutationFailure(err) {
59
- if (err instanceof client_1.RateLimitError) {
60
- return 'reconcile';
61
- }
62
- if (err instanceof client_1.NetworkError) {
63
- return 'reconcile';
62
+ function hashPreviewBinding(proposed, baseline) {
63
+ return (0, stable_stringify_js_1.hashStableValue)({ proposed, baseline: baseline !== null && baseline !== void 0 ? baseline : null });
64
+ }
65
+ function resourceKeyMatches(claims, resourceKey) {
66
+ return claims.resourceKey === resourceKey || claims.resourceAliases.includes(resourceKey);
67
+ }
68
+ /** Update drift or create-target appearance → PREVIEW_STALE. */
69
+ function assertBaselineStillValid(previewId, claims, currentBaseline) {
70
+ var _a;
71
+ const previewedUpdatedAt = (_a = claims.baseline) === null || _a === void 0 ? void 0 : _a.updatedAt;
72
+ if (previewedUpdatedAt != null &&
73
+ previewedUpdatedAt !== '' &&
74
+ (currentBaseline === null || currentBaseline === void 0 ? void 0 : currentBaseline.updatedAt) !== previewedUpdatedAt) {
75
+ throw new PreviewLedgerError('PREVIEW_STALE', `Preview '${previewId}' baseline changed (resource was updated after preview); re-run preview -> confirm`);
64
76
  }
65
- if (err instanceof client_1.LightdashApiError) {
66
- const status = err.statusCode;
67
- if (status === 408 || status === 429) {
68
- return 'reconcile';
69
- }
70
- if (status >= 400 && status < 500) {
71
- return 'release';
72
- }
73
- return 'reconcile';
77
+ if (claims.baseline == null &&
78
+ (((currentBaseline === null || currentBaseline === void 0 ? void 0 : currentBaseline.uuid) != null && currentBaseline.uuid !== '') ||
79
+ ((currentBaseline === null || currentBaseline === void 0 ? void 0 : currentBaseline.updatedAt) != null && currentBaseline.updatedAt !== ''))) {
80
+ throw new PreviewLedgerError('PREVIEW_STALE', `Preview '${previewId}' targeted a non-existent resource that now exists; re-run preview -> confirm`);
74
81
  }
75
- return 'reconcile';
76
82
  }
77
- function hashPreviewBinding(proposed, baseline) {
78
- return hashPreviewContent({ proposed, baseline: baseline !== null && baseline !== void 0 ? baseline : null });
83
+ function resolveServerContext(serverContext) {
84
+ return serverContext !== null && serverContext !== void 0 ? serverContext : exports.EMPTY_SERVER_CONTEXT;
79
85
  }
80
- function resourceKeyMatches(entry, resourceKey) {
81
- return entry.resourceKey === resourceKey || entry.resourceAliases.includes(resourceKey);
86
+ function assertResourceBinding(claims, expected) {
87
+ if (claims.resourceKind !== expected.resourceKind ||
88
+ !resourceKeyMatches(claims, expected.resourceKey)) {
89
+ throw new PreviewLedgerError('PREVIEW_STALE', `Preview '${claims.previewId}' was created for '${claims.resourceKind}:${claims.resourceKey}', not the requested '${expected.resourceKind}:${expected.resourceKey}'`);
90
+ }
82
91
  }
83
- function store() {
84
- return (0, create_preview_store_js_1.getPreviewStore)();
92
+ async function mintClaims(claims, serverContext) {
93
+ return getPreviewTokenCodec().mint(claims, resolveServerContext(serverContext));
85
94
  }
86
- async function assertOwnedEntry(input) {
87
- const entry = await store().get(input.previewId);
88
- if (!entry) {
89
- throw new PreviewLedgerError('PREVIEW_REQUIRED', `Preview '${input.previewId}' was not found; call the matching preview_* tool first`);
95
+ async function verifyClaims(previewToken, serverContext) {
96
+ if (previewToken.length === 0) {
97
+ throw new PreviewLedgerError('PREVIEW_REQUIRED', 'previewToken is required; call the matching preview_* tool first');
90
98
  }
91
- if (entry.sessionId !== input.sessionId || entry.projectUuid !== input.projectUuid) {
92
- throw new PreviewLedgerError('PREVIEW_NOT_OWNED', `Preview '${input.previewId}' is not owned by this session/project`);
99
+ try {
100
+ const claims = await getPreviewTokenCodec().verify(previewToken, resolveServerContext(serverContext));
101
+ if (Date.parse(claims.expiresAt) < Date.now()) {
102
+ throw new PreviewLedgerError('PREVIEW_REQUIRED', 'previewToken is invalid or expired; call the matching preview_* tool first');
103
+ }
104
+ return claims;
93
105
  }
94
- if (Date.parse(entry.expiresAt) < Date.now()) {
95
- await store().delete(input.previewId);
96
- throw new PreviewLedgerError('PREVIEW_EXPIRED', `Preview '${input.previewId}' has expired`);
106
+ catch (err) {
107
+ if (err instanceof PreviewLedgerError) {
108
+ throw err;
109
+ }
110
+ throw new PreviewLedgerError('PREVIEW_REQUIRED', 'previewToken is invalid or expired; call the matching preview_* tool first');
97
111
  }
98
- if (entry.status === 'reconciliation_required') {
99
- throw new PreviewLedgerError('PREVIEW_RECONCILIATION_REQUIRED', `Preview '${input.previewId}' needs reconciliation after an uncertain apply failure; inspect the resource and re-run preview -> confirm`);
112
+ }
113
+ function assertSubjectAndProject(claims, subject, projectUuid) {
114
+ if (claims.subject !== subject || claims.projectUuid !== projectUuid) {
115
+ throw new PreviewLedgerError('PREVIEW_NOT_OWNED', `Preview '${claims.previewId}' is not owned by this subject/project`);
100
116
  }
101
- return entry;
102
117
  }
103
- async function addPreviewLedgerEntry(input) {
104
- var _a, _b;
118
+ /** Mint a draft previewToken (opaque HMAC blob). Does not store proposed on the server. */
119
+ async function mintDraftPreviewToken(input) {
120
+ var _a;
105
121
  const now = Date.now();
106
- const ttl = (_a = input.ttlMs) !== null && _a !== void 0 ? _a : exports.DEFAULT_PREVIEW_TTL_MS;
107
- const resourceAliases = uniqueResourceKeys(input.resourceKey, ...((_b = input.resourceAliases) !== null && _b !== void 0 ? _b : []));
108
- const entry = {
122
+ const resourceAliases = uniqueResourceKeys(input.resourceKey, ...((_a = input.resourceAliases) !== null && _a !== void 0 ? _a : []));
123
+ const claims = {
109
124
  previewId: (0, node_crypto_1.randomUUID)(),
110
- sessionId: input.sessionId,
125
+ subject: input.subject,
111
126
  projectUuid: input.projectUuid,
112
127
  resourceKind: input.resourceKind,
113
128
  resourceKey: input.resourceKey,
114
129
  resourceAliases,
115
130
  contentHash: hashPreviewBinding(input.proposed, input.baseline),
116
131
  status: 'draft',
117
- proposed: input.proposed,
118
132
  baseline: input.baseline,
119
133
  createdAt: new Date(now).toISOString(),
120
- expiresAt: new Date(now + ttl).toISOString(),
134
+ expiresAt: new Date(now + exports.DEFAULT_PREVIEW_TTL_MS).toISOString(),
121
135
  };
122
- await store().put(entry);
123
- return entry;
124
- }
125
- /** Look up a preview by id, enforcing session/project ownership and expiry. */
126
- async function getOwnedPreview(input) {
127
- return assertOwnedEntry(input);
136
+ const previewToken = await mintClaims(claims, input.serverContext);
137
+ return { previewToken, claims };
128
138
  }
129
- /**
130
- * Mark a draft preview validated after a successful confirm_preview call.
131
- * `expected` binds validation to the resource it was actually run against.
132
- */
133
- async function markPreviewValidated(previewId, sessionId, projectUuid, expected) {
134
- const entry = await assertOwnedEntry({ previewId, sessionId, projectUuid });
135
- if (entry.resourceKind !== expected.resourceKind ||
136
- !resourceKeyMatches(entry, expected.resourceKey)) {
137
- throw new PreviewLedgerError('PREVIEW_STALE', `Preview '${previewId}' was created for '${entry.resourceKind}:${entry.resourceKey}', not the requested '${expected.resourceKind}:${expected.resourceKey}'`);
138
- }
139
- if (entry.status !== 'draft') {
140
- throw new PreviewLedgerError('PREVIEW_NOT_VALIDATED', `Preview '${previewId}' cannot be confirmed from status '${entry.status}'`);
141
- }
142
- const validated = Object.assign(Object.assign({}, entry), { status: 'validated' });
143
- const swapped = await store().compareAndSwap(previewId, 'draft', validated);
144
- if (!swapped) {
145
- throw new PreviewLedgerError('PREVIEW_NOT_VALIDATED', `Preview '${previewId}' could not be marked validated (status raced)`);
139
+ /** Confirm a draft token: verify bindings and mint a validated token (no server write). */
140
+ async function confirmPreviewToken(input) {
141
+ const claims = await verifyClaims(input.previewToken, input.serverContext);
142
+ assertSubjectAndProject(claims, input.subject, input.projectUuid);
143
+ assertResourceBinding(claims, input);
144
+ if (claims.status !== 'draft') {
145
+ throw new PreviewLedgerError('PREVIEW_NOT_VALIDATED', `Preview '${claims.previewId}' cannot be confirmed from status '${claims.status}'`);
146
146
  }
147
- return validated;
148
- }
149
- function hasNonEmpty(value) {
150
- return value != null && value !== '';
151
- }
152
- /** Update drift or create-target appearance → PREVIEW_STALE. */
153
- function assertBaselineStillValid(previewId, entry, currentBaseline) {
154
- var _a;
155
- const previewedUpdatedAt = (_a = entry.baseline) === null || _a === void 0 ? void 0 : _a.updatedAt;
156
- if (hasNonEmpty(previewedUpdatedAt) && (currentBaseline === null || currentBaseline === void 0 ? void 0 : currentBaseline.updatedAt) !== previewedUpdatedAt) {
157
- throw new PreviewLedgerError('PREVIEW_STALE', `Preview '${previewId}' baseline changed (resource was updated after preview); re-run preview -> confirm`);
158
- }
159
- if (entry.baseline == null &&
160
- (hasNonEmpty(currentBaseline === null || currentBaseline === void 0 ? void 0 : currentBaseline.uuid) || hasNonEmpty(currentBaseline === null || currentBaseline === void 0 ? void 0 : currentBaseline.updatedAt))) {
161
- throw new PreviewLedgerError('PREVIEW_STALE', `Preview '${previewId}' targeted a non-existent resource that now exists; re-run preview -> confirm`);
162
- }
163
- }
164
- function assertClaimBindings(entry, input) {
165
- if (entry.status !== 'validated') {
166
- throw new PreviewLedgerError('PREVIEW_NOT_VALIDATED', `Preview '${input.previewId}' has not been validated`);
167
- }
168
- if (entry.resourceKind !== input.resourceKind || !resourceKeyMatches(entry, input.resourceKey)) {
169
- throw new PreviewLedgerError('PREVIEW_STALE', `Preview '${input.previewId}' does not match the target resource ('${input.resourceKind}:${input.resourceKey}')`);
170
- }
171
- if (hashPreviewBinding(input.proposed, entry.baseline) !== entry.contentHash) {
172
- throw new PreviewLedgerError('PREVIEW_STALE', `Preview '${input.previewId}' content hash does not match the applied payload; re-run preview -> confirm`);
173
- }
174
- assertBaselineStillValid(input.previewId, entry, input.currentBaseline);
175
- }
176
- /**
177
- * Claim a validated preview for apply (`validated` → `applying` via CAS).
178
- * Same kind/key/hash/baseline checks as the former consume path, but does not delete.
179
- */
180
- async function claimPreviewForApply(input) {
181
- const entry = await assertOwnedEntry({
182
- previewId: input.previewId,
183
- sessionId: input.sessionId,
184
- projectUuid: input.projectUuid,
185
- });
186
- assertClaimBindings(entry, input);
187
- const applying = Object.assign(Object.assign({}, entry), { status: 'applying' });
188
- const swapped = await store().compareAndSwap(input.previewId, 'validated', applying);
189
- if (!swapped) {
190
- throw new PreviewLedgerError('PREVIEW_NOT_VALIDATED', `Preview '${input.previewId}' could not be claimed for apply (already claimed or status raced)`);
191
- }
192
- return applying;
193
- }
194
- /** Delete a claimed preview when still `applying` (single-use completion). */
195
- async function markPreviewApplied(previewId) {
196
- await store().compareAndDelete(previewId, 'applying');
197
- }
198
- /**
199
- * After a failed mutation: known no-write failures return to `validated`;
200
- * uncertain outcomes move to `reconciliation_required`.
201
- */
202
- async function releaseOrReconcilePreview(previewId, err) {
203
- const entry = await store().get(previewId);
204
- if (!entry || entry.status !== 'applying') {
205
- return;
206
- }
207
- const action = classifyMutationFailure(err);
208
- if (action === 'release') {
209
- const released = Object.assign(Object.assign({}, entry), { status: 'validated' });
210
- await store().compareAndSwap(previewId, 'applying', released);
211
- return;
212
- }
213
- const reconciling = Object.assign(Object.assign({}, entry), { status: 'reconciliation_required' });
214
- await store().compareAndSwap(previewId, 'applying', reconciling);
215
- }
216
- /**
217
- * Claim → run mutation → mark applied; on mutation failure release/reconcile and rethrow.
218
- * After a successful mutation, never release/reconcile if mark-applied fails (would invite
219
- * double-apply); log and return the mutation result instead.
220
- */
221
- async function withClaimedPreviewApply(claimInput, fn) {
222
- const entry = await claimPreviewForApply(claimInput);
223
- let result;
224
- try {
225
- result = await fn(entry);
226
- }
227
- catch (err) {
228
- await releaseOrReconcilePreview(entry.previewId, err);
229
- throw err;
230
- }
231
- try {
232
- await markPreviewApplied(entry.previewId);
233
- }
234
- catch (err) {
235
- // Mutation already succeeded — never release/reconcile (would invite double-apply).
236
- console.error(`[preview-ledger] markPreviewApplied failed after successful mutation (previewId=${entry.previewId})`, err);
237
- }
238
- return result;
239
- }
240
- /** Test helper: reset to a fresh in-memory store. */
241
- function resetPreviewLedgerForTests() {
242
- (0, create_preview_store_js_1.setPreviewStoreForTests)(new in_memory_preview_store_js_1.InMemoryPreviewStore());
147
+ const now = Date.now();
148
+ const validated = Object.assign(Object.assign({}, claims), { status: 'validated', createdAt: new Date(now).toISOString(), expiresAt: new Date(now + exports.DEFAULT_PREVIEW_TTL_MS).toISOString() });
149
+ const previewToken = await mintClaims(validated, input.serverContext);
150
+ return { previewToken, claims: validated };
151
+ }
152
+ /** Verify validated token then run mutation (ADR-0019: no server-side claim/release). */
153
+ async function withValidatedPreviewApply(input, fn) {
154
+ const claims = await verifyClaims(input.previewToken, input.serverContext);
155
+ assertSubjectAndProject(claims, input.subject, input.projectUuid);
156
+ if (claims.status !== 'validated') {
157
+ throw new PreviewLedgerError('PREVIEW_NOT_VALIDATED', `Preview '${claims.previewId}' has not been validated`);
158
+ }
159
+ assertResourceBinding(claims, input);
160
+ if (hashPreviewBinding(input.proposed, claims.baseline) !== claims.contentHash) {
161
+ throw new PreviewLedgerError('PREVIEW_STALE', `Preview '${claims.previewId}' content hash does not match the applied payload; re-run preview -> confirm`);
162
+ }
163
+ assertBaselineStillValid(claims.previewId, claims, input.currentBaseline);
164
+ return fn(claims);
243
165
  }