@intentius/chant 0.124.39 → 0.124.41

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 (337) hide show
  1. package/dist/__fixtures__/oidc-emulator.d.ts +49 -0
  2. package/dist/__fixtures__/oidc-emulator.d.ts.map +1 -0
  3. package/dist/__fixtures__/oidc-emulator.js +89 -0
  4. package/dist/ci-handover.d.ts +117 -0
  5. package/dist/ci-handover.d.ts.map +1 -0
  6. package/dist/ci-handover.js +217 -0
  7. package/dist/ci-identity.d.ts +190 -0
  8. package/dist/ci-identity.d.ts.map +1 -0
  9. package/dist/ci-identity.js +219 -0
  10. package/dist/cli/component-endpoint.d.ts +20 -0
  11. package/dist/cli/component-endpoint.d.ts.map +1 -0
  12. package/dist/cli/component-endpoint.js +36 -0
  13. package/dist/cli/handlers/approve.d.ts +2 -1
  14. package/dist/cli/handlers/approve.d.ts.map +1 -1
  15. package/dist/cli/handlers/approve.js +20 -6
  16. package/dist/cli/handlers/build.d.ts.map +1 -1
  17. package/dist/cli/handlers/build.js +15 -1
  18. package/dist/cli/handlers/fan-out.d.ts.map +1 -1
  19. package/dist/cli/handlers/fan-out.js +26 -4
  20. package/dist/cli/handlers/gate-resume.d.ts +3 -0
  21. package/dist/cli/handlers/gate-resume.d.ts.map +1 -1
  22. package/dist/cli/handlers/gate-resume.js +15 -2
  23. package/dist/cli/handlers/lock.d.ts +8 -0
  24. package/dist/cli/handlers/lock.d.ts.map +1 -0
  25. package/dist/cli/handlers/lock.js +197 -0
  26. package/dist/cli/handlers/pr-env.d.ts +34 -0
  27. package/dist/cli/handlers/pr-env.d.ts.map +1 -0
  28. package/dist/cli/handlers/pr-env.js +436 -0
  29. package/dist/cli/handlers/pr.d.ts +74 -0
  30. package/dist/cli/handlers/pr.d.ts.map +1 -1
  31. package/dist/cli/handlers/pr.js +514 -58
  32. package/dist/cli/handlers/promote.d.ts.map +1 -1
  33. package/dist/cli/handlers/promote.js +16 -2
  34. package/dist/cli/handlers/query.d.ts +6 -0
  35. package/dist/cli/handlers/query.d.ts.map +1 -0
  36. package/dist/cli/handlers/query.js +80 -0
  37. package/dist/cli/handlers/run.d.ts +4 -1
  38. package/dist/cli/handlers/run.d.ts.map +1 -1
  39. package/dist/cli/handlers/run.js +17 -6
  40. package/dist/cli/main.d.ts.map +1 -1
  41. package/dist/cli/main.js +41 -2
  42. package/dist/cli/parse-args.d.ts.map +1 -1
  43. package/dist/cli/parse-args.js +31 -2
  44. package/dist/cli/registry.d.ts +12 -2
  45. package/dist/cli/registry.d.ts.map +1 -1
  46. package/dist/components/auto-release.d.ts +35 -3
  47. package/dist/components/auto-release.d.ts.map +1 -1
  48. package/dist/components/auto-release.js +29 -2
  49. package/dist/components/cli-support.d.ts +2 -0
  50. package/dist/components/cli-support.d.ts.map +1 -1
  51. package/dist/components/cli-support.js +2 -0
  52. package/dist/components/deploy-units.d.ts.map +1 -1
  53. package/dist/components/deploy-units.js +5 -0
  54. package/dist/components/fan-out-run.d.ts +28 -0
  55. package/dist/components/fan-out-run.d.ts.map +1 -1
  56. package/dist/components/fan-out-run.js +27 -3
  57. package/dist/components/pr-environment.d.ts +298 -0
  58. package/dist/components/pr-environment.d.ts.map +1 -0
  59. package/dist/components/pr-environment.js +406 -0
  60. package/dist/components/pr-hooks.d.ts +66 -0
  61. package/dist/components/pr-hooks.d.ts.map +1 -0
  62. package/dist/components/pr-hooks.js +119 -0
  63. package/dist/components/pr-pipeline.d.ts +72 -2
  64. package/dist/components/pr-pipeline.d.ts.map +1 -1
  65. package/dist/components/pr-pipeline.js +96 -5
  66. package/dist/components/pr-policy.d.ts +109 -0
  67. package/dist/components/pr-policy.d.ts.map +1 -0
  68. package/dist/components/pr-policy.js +150 -0
  69. package/dist/components/pr-run.d.ts.map +1 -1
  70. package/dist/components/pr-run.js +5 -3
  71. package/dist/components/promote.d.ts.map +1 -1
  72. package/dist/components/promote.js +39 -16
  73. package/dist/gate-decision.d.ts +15 -2
  74. package/dist/gate-decision.d.ts.map +1 -1
  75. package/dist/gate-decision.js +17 -2
  76. package/dist/gate-policy.d.ts +140 -0
  77. package/dist/gate-policy.d.ts.map +1 -0
  78. package/dist/gate-policy.js +242 -0
  79. package/dist/lifecycle/__fixtures__/publish-fakes.d.ts.map +1 -1
  80. package/dist/lifecycle/__fixtures__/publish-fakes.js +6 -1
  81. package/dist/lifecycle/gate-checkpoint.d.ts +1 -1
  82. package/dist/lifecycle/gate-checkpoint.js +1 -1
  83. package/dist/{workspace/trust → lifecycle}/gate-seal.d.ts +1 -1
  84. package/dist/lifecycle/gate-seal.d.ts.map +1 -0
  85. package/dist/lifecycle/publish-declaration.d.ts.map +1 -1
  86. package/dist/lifecycle/publish-declaration.js +4 -3
  87. package/dist/lifecycle/publish-npm.d.ts +2 -2
  88. package/dist/lifecycle/publish-npm.d.ts.map +1 -1
  89. package/dist/lifecycle/publish-npm.js +31 -8
  90. package/dist/lifecycle/query.d.ts +68 -0
  91. package/dist/lifecycle/query.d.ts.map +1 -0
  92. package/dist/lifecycle/query.js +246 -0
  93. package/dist/lifecycle/release-ledger.d.ts +31 -0
  94. package/dist/lifecycle/release-ledger.d.ts.map +1 -1
  95. package/dist/lifecycle/release-ledger.js +19 -1
  96. package/dist/lifecycle/run-ledger.d.ts +13 -0
  97. package/dist/lifecycle/run-ledger.d.ts.map +1 -1
  98. package/dist/lifecycle/run-ledger.js +16 -0
  99. package/dist/lifecycle/status.d.ts +5 -1
  100. package/dist/lifecycle/status.d.ts.map +1 -1
  101. package/dist/lifecycle/status.js +10 -5
  102. package/dist/lifecycle/target-lock.d.ts +97 -0
  103. package/dist/lifecycle/target-lock.d.ts.map +1 -0
  104. package/dist/lifecycle/target-lock.js +286 -0
  105. package/dist/live-endpoint.d.ts +18 -0
  106. package/dist/live-endpoint.d.ts.map +1 -1
  107. package/dist/live-endpoint.js +27 -0
  108. package/dist/op/activities/activity-contracts.d.ts +30 -0
  109. package/dist/op/activities/activity-contracts.d.ts.map +1 -1
  110. package/dist/op/activities/activity-contracts.js +26 -0
  111. package/dist/op/activities/index.d.ts +2 -0
  112. package/dist/op/activities/index.d.ts.map +1 -1
  113. package/dist/op/activities/index.js +4 -0
  114. package/dist/op/activities/review-agent.d.ts +137 -0
  115. package/dist/op/activities/review-agent.d.ts.map +1 -0
  116. package/dist/op/activities/review-agent.js +266 -0
  117. package/dist/op/builders.d.ts +9 -0
  118. package/dist/op/builders.d.ts.map +1 -1
  119. package/dist/op/builders.js +11 -0
  120. package/dist/op/cron.d.ts +8 -0
  121. package/dist/op/cron.d.ts.map +1 -1
  122. package/dist/op/cron.js +51 -0
  123. package/dist/op/gate-approval.d.ts +20 -13
  124. package/dist/op/gate-approval.d.ts.map +1 -1
  125. package/dist/op/gate-approval.js +13 -18
  126. package/dist/op/gate-quorum.d.ts +131 -0
  127. package/dist/op/gate-quorum.d.ts.map +1 -0
  128. package/dist/op/gate-quorum.js +183 -0
  129. package/dist/op/gate-resume.d.ts +4 -2
  130. package/dist/op/gate-resume.d.ts.map +1 -1
  131. package/dist/op/gate-resume.js +5 -4
  132. package/dist/op/gate-review.js +1 -1
  133. package/dist/op/gate.d.ts +32 -4
  134. package/dist/op/gate.d.ts.map +1 -1
  135. package/dist/op/gate.js +40 -24
  136. package/dist/op/index.d.ts +6 -4
  137. package/dist/op/index.d.ts.map +1 -1
  138. package/dist/op/index.js +4 -3
  139. package/dist/op/local-executor.d.ts.map +1 -1
  140. package/dist/op/local-executor.js +9 -3
  141. package/dist/op/op-waves-run.d.ts +62 -1
  142. package/dist/op/op-waves-run.d.ts.map +1 -1
  143. package/dist/op/op-waves-run.js +190 -11
  144. package/dist/op/op-waves.d.ts +55 -3
  145. package/dist/op/op-waves.d.ts.map +1 -1
  146. package/dist/op/op-waves.js +63 -8
  147. package/dist/op/schedule-overdue.d.ts +57 -0
  148. package/dist/op/schedule-overdue.d.ts.map +1 -0
  149. package/dist/op/schedule-overdue.js +138 -0
  150. package/dist/override-gate.d.ts +2 -2
  151. package/dist/override-gate.d.ts.map +1 -1
  152. package/dist/override-gate.js +1 -1
  153. package/dist/pr-forge.d.ts +36 -0
  154. package/dist/pr-forge.d.ts.map +1 -1
  155. package/dist/pr-forge.js +82 -0
  156. package/dist/pr-loop.d.ts +90 -1
  157. package/dist/pr-loop.d.ts.map +1 -1
  158. package/dist/pr-loop.js +77 -3
  159. package/dist/pr-post.d.ts +72 -0
  160. package/dist/pr-post.d.ts.map +1 -0
  161. package/dist/pr-post.js +134 -0
  162. package/dist/wave-blocked.d.ts +79 -0
  163. package/dist/wave-blocked.d.ts.map +1 -0
  164. package/dist/wave-blocked.js +245 -0
  165. package/dist/wave-engine.d.ts +6 -0
  166. package/dist/wave-engine.d.ts.map +1 -1
  167. package/dist/wave-engine.js +2 -0
  168. package/dist/wave-runtime.mjs +239 -239
  169. package/dist/workspace/__fixtures__/two-member-workspace.d.ts +1 -0
  170. package/dist/workspace/__fixtures__/two-member-workspace.d.ts.map +1 -1
  171. package/dist/workspace/__fixtures__/two-member-workspace.js +1 -1
  172. package/dist/workspace/ci-branches.d.ts +51 -0
  173. package/dist/workspace/ci-branches.d.ts.map +1 -0
  174. package/dist/workspace/ci-branches.js +69 -0
  175. package/dist/workspace/ci-cloud-identity.d.ts +11 -0
  176. package/dist/workspace/ci-cloud-identity.d.ts.map +1 -0
  177. package/dist/workspace/ci-cloud-identity.js +24 -0
  178. package/dist/workspace/ci-locks.d.ts +12 -0
  179. package/dist/workspace/ci-locks.d.ts.map +1 -0
  180. package/dist/workspace/ci-locks.js +6 -0
  181. package/dist/workspace/ci-run.d.ts +24 -1
  182. package/dist/workspace/ci-run.d.ts.map +1 -1
  183. package/dist/workspace/ci-run.js +85 -6
  184. package/dist/workspace/declaration.d.ts +63 -0
  185. package/dist/workspace/declaration.d.ts.map +1 -1
  186. package/dist/workspace/declaration.js +72 -1
  187. package/dist/workspace/declaration.schema.json +147 -0
  188. package/dist/workspace/identity-gate-rule.d.ts +1 -1
  189. package/dist/workspace/identity-gate-rule.d.ts.map +1 -1
  190. package/dist/workspace/identity-gate-rule.js +1 -1
  191. package/dist/workspace/identity.d.ts +1 -1
  192. package/dist/workspace/identity.d.ts.map +1 -1
  193. package/dist/workspace/lineage-upgrade.d.ts.map +1 -1
  194. package/dist/workspace/lineage-upgrade.js +8 -5
  195. package/dist/workspace/member-pipeline.d.ts +6 -0
  196. package/dist/workspace/member-pipeline.d.ts.map +1 -1
  197. package/dist/workspace/member-pipeline.js +23 -0
  198. package/dist/workspace/pr-report.schema.json +73 -2
  199. package/dist/workspace/security.d.ts.map +1 -1
  200. package/dist/workspace/security.js +4 -0
  201. package/dist/workspace/status-gates.d.ts +3 -2
  202. package/dist/workspace/status-gates.d.ts.map +1 -1
  203. package/dist/workspace/status-gates.js +8 -7
  204. package/dist/workspace/status.d.ts +3 -1
  205. package/dist/workspace/status.d.ts.map +1 -1
  206. package/dist/workspace/status.js +7 -3
  207. package/dist/workspace/status.schema.json +1 -0
  208. package/dist/workspace/trust/seal.d.ts +2 -2
  209. package/dist/workspace/trust/seal.d.ts.map +1 -1
  210. package/dist/workspace/trust/seal.js +2 -2
  211. package/package.json +1 -1
  212. package/src/__fixtures__/oidc-emulator.ts +118 -0
  213. package/src/ci-handover.test.ts +209 -0
  214. package/src/ci-handover.ts +237 -0
  215. package/src/ci-identity.test.ts +201 -0
  216. package/src/ci-identity.ts +310 -0
  217. package/src/cli/component-endpoint.ts +43 -0
  218. package/src/cli/handlers/approve.ts +18 -5
  219. package/src/cli/handlers/build.ts +15 -1
  220. package/src/cli/handlers/fan-out.test.ts +10 -0
  221. package/src/cli/handlers/fan-out.ts +29 -4
  222. package/src/cli/handlers/gate-resume.ts +16 -2
  223. package/src/cli/handlers/lock.test.ts +98 -0
  224. package/src/cli/handlers/lock.ts +202 -0
  225. package/src/cli/handlers/operator.test.ts +3 -1
  226. package/src/cli/handlers/pr-endpoint.test.ts +169 -0
  227. package/src/cli/handlers/pr-env.ts +462 -0
  228. package/src/cli/handlers/pr-waves-blocked.test.ts +247 -0
  229. package/src/cli/handlers/pr.test.ts +184 -0
  230. package/src/cli/handlers/pr.ts +508 -64
  231. package/src/cli/handlers/promote.ts +25 -2
  232. package/src/cli/handlers/query.ts +78 -0
  233. package/src/cli/handlers/run.test.ts +2 -1
  234. package/src/cli/handlers/run.ts +16 -5
  235. package/src/cli/main.ts +41 -2
  236. package/src/cli/parse-args.ts +23 -2
  237. package/src/cli/registry.ts +12 -2
  238. package/src/components/auto-release-infra.test.ts +131 -0
  239. package/src/components/auto-release.test.ts +40 -1
  240. package/src/components/auto-release.ts +50 -4
  241. package/src/components/cli-support.ts +4 -0
  242. package/src/components/deploy-units.ts +5 -0
  243. package/src/components/fan-out-run.ts +39 -2
  244. package/src/components/fan-out-waves.test.ts +45 -1
  245. package/src/components/pr-environment.test.ts +249 -0
  246. package/src/components/pr-environment.ts +538 -0
  247. package/src/components/pr-hooks.test.ts +118 -0
  248. package/src/components/pr-hooks.ts +157 -0
  249. package/src/components/pr-pipeline.ts +130 -5
  250. package/src/components/pr-policy.test.ts +145 -0
  251. package/src/components/pr-policy.ts +211 -0
  252. package/src/components/pr-run.ts +5 -2
  253. package/src/components/promote.test.ts +39 -0
  254. package/src/components/promote.ts +38 -14
  255. package/src/gate-decision-bundle.test.ts +4 -3
  256. package/src/gate-decision.ts +39 -2
  257. package/src/gate-policy-bundle.test.ts +28 -0
  258. package/src/gate-policy.test.ts +162 -0
  259. package/src/gate-policy.ts +298 -0
  260. package/src/lifecycle/__fixtures__/publish-fakes.ts +6 -1
  261. package/src/lifecycle/gate-checkpoint.ts +1 -1
  262. package/src/{workspace/trust → lifecycle}/gate-seal.ts +1 -1
  263. package/src/lifecycle/publish-declaration.ts +4 -3
  264. package/src/lifecycle/publish-npm.ts +33 -8
  265. package/src/lifecycle/publish-targets.test.ts +36 -3
  266. package/src/lifecycle/query.test.ts +91 -0
  267. package/src/lifecycle/query.ts +315 -0
  268. package/src/lifecycle/release-ledger.ts +42 -1
  269. package/src/lifecycle/run-ledger.ts +18 -0
  270. package/src/lifecycle/status.test.ts +19 -0
  271. package/src/lifecycle/status.ts +14 -6
  272. package/src/lifecycle/target-lock.test.ts +195 -0
  273. package/src/lifecycle/target-lock.ts +347 -0
  274. package/src/live-endpoint.ts +31 -0
  275. package/src/op/activities/activity-contracts.ts +31 -0
  276. package/src/op/activities/index.ts +6 -0
  277. package/src/op/activities/review-agent.test.ts +240 -0
  278. package/src/op/activities/review-agent.ts +355 -0
  279. package/src/op/builders.ts +13 -0
  280. package/src/op/cron.ts +44 -0
  281. package/src/op/gate-alias.test.ts +2 -2
  282. package/src/op/gate-approval.test.ts +30 -9
  283. package/src/op/gate-approval.ts +23 -26
  284. package/src/op/gate-quorum.test.ts +139 -0
  285. package/src/op/gate-quorum.ts +248 -0
  286. package/src/op/gate-resume.ts +6 -3
  287. package/src/op/gate-review.ts +1 -1
  288. package/src/op/gate.ts +64 -23
  289. package/src/op/index.ts +13 -1
  290. package/src/op/local-executor.ts +9 -2
  291. package/src/op/op-waves-hook-targets.test.ts +126 -0
  292. package/src/op/op-waves-policy-hold.test.ts +66 -0
  293. package/src/op/op-waves-quorum.test.ts +101 -0
  294. package/src/op/op-waves-run.ts +233 -11
  295. package/src/op/op-waves.ts +83 -10
  296. package/src/op/schedule-overdue.test.ts +220 -0
  297. package/src/op/schedule-overdue.ts +161 -0
  298. package/src/override-gate-bundle.test.ts +1 -1
  299. package/src/override-gate.ts +2 -2
  300. package/src/pr-forge-bundle.test.ts +2 -2
  301. package/src/pr-forge.test.ts +33 -0
  302. package/src/pr-forge.ts +114 -0
  303. package/src/pr-loop-bundle.test.ts +2 -2
  304. package/src/pr-loop.test.ts +58 -0
  305. package/src/pr-loop.ts +146 -4
  306. package/src/pr-post.test.ts +141 -0
  307. package/src/pr-post.ts +159 -0
  308. package/src/wave-blocked-bundle.test.ts +25 -0
  309. package/src/wave-blocked.test.ts +146 -0
  310. package/src/wave-blocked.ts +271 -0
  311. package/src/wave-engine.ts +8 -0
  312. package/src/workspace/__fixtures__/two-member-workspace.ts +2 -2
  313. package/src/workspace/ci-branches.test.ts +62 -0
  314. package/src/workspace/ci-branches.ts +79 -0
  315. package/src/workspace/ci-cloud-identity.test.ts +53 -0
  316. package/src/workspace/ci-cloud-identity.ts +23 -0
  317. package/src/workspace/ci-locks.ts +16 -0
  318. package/src/workspace/ci-run-index.test.ts +2 -1
  319. package/src/workspace/ci-run.test.ts +133 -8
  320. package/src/workspace/ci-run.ts +92 -7
  321. package/src/workspace/declaration.schema.json +147 -0
  322. package/src/workspace/declaration.test.ts +76 -0
  323. package/src/workspace/declaration.ts +134 -2
  324. package/src/workspace/identity-gate-rule.ts +1 -1
  325. package/src/workspace/identity.ts +1 -1
  326. package/src/workspace/lineage-upgrade.ts +11 -8
  327. package/src/workspace/member-pipeline.test.ts +29 -0
  328. package/src/workspace/member-pipeline.ts +30 -0
  329. package/src/workspace/pr-report.schema.json +73 -2
  330. package/src/workspace/security.ts +4 -0
  331. package/src/workspace/status-gates.ts +9 -6
  332. package/src/workspace/status.schema.json +1 -0
  333. package/src/workspace/status.ts +11 -4
  334. package/src/workspace/trust/gate-seal.test.ts +1 -1
  335. package/src/workspace/trust/seal.ts +2 -2
  336. package/dist/workspace/trust/gate-seal.d.ts.map +0 -1
  337. /package/dist/{workspace/trust → lifecycle}/gate-seal.js +0 -0
@@ -0,0 +1,195 @@
1
+ /**
2
+ * #4293: target locks a pull request holds, `_locks/<gate>.json` on
3
+ * `chant/lifecycle`, in one clone and across clones through a bare remote.
4
+ */
5
+ import { afterAll, describe, expect, test } from "vitest";
6
+ import { execFileSync } from "node:child_process";
7
+ import { chmodSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import {
11
+ describeHeldTargetLocks,
12
+ heldTargetLocks,
13
+ parseTargetLocks,
14
+ readTargetLocks,
15
+ releaseTargetLocks,
16
+ renderTargetLocks,
17
+ takeTargetLocks,
18
+ targetLockGateProblem,
19
+ targetLockPath,
20
+ type TargetLock,
21
+ } from "./target-lock";
22
+
23
+ const dirs: string[] = [];
24
+ afterAll(() => {
25
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
26
+ });
27
+
28
+ function tmp(prefix: string): string {
29
+ const d = realpathSync(mkdtempSync(join(tmpdir(), prefix)));
30
+ dirs.push(d);
31
+ return d;
32
+ }
33
+
34
+ function git(cwd: string, ...args: string[]): string {
35
+ return execFileSync("git", args, { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }).trim();
36
+ }
37
+
38
+ function configure(dir: string): void {
39
+ git(dir, "config", "user.email", "test@chant.dev");
40
+ git(dir, "config", "user.name", "Test");
41
+ git(dir, "config", "commit.gpgsign", "false");
42
+ }
43
+
44
+ function initRepo(): string {
45
+ const dir = tmp("chant-target-lock-");
46
+ git(dir, "init", "-q", "-b", "main");
47
+ configure(dir);
48
+ writeFileSync(join(dir, "README.md"), "# t\n");
49
+ git(dir, "add", "README.md");
50
+ git(dir, "commit", "-q", "-m", "init");
51
+ return dir;
52
+ }
53
+
54
+ const holder = (pr: number, stage: TargetLock["stage"], by = "alice"): TargetLock => ({ pr, by, at: "2026-10-22T10:00:00.000Z", stage, head: "a".repeat(40) });
55
+
56
+ describe("the lock file", () => {
57
+ test("parses a version 1 file and drops malformed entries; anything else holds no locks", () => {
58
+ const text = JSON.stringify({ version: 1, locks: { web: holder(1, "plan"), bad: { pr: "x" }, api: { pr: 2, by: "b", at: "t", stage: "nope" } } });
59
+ expect(parseTargetLocks(text)).toEqual({ version: 1, locks: { web: holder(1, "plan") } });
60
+ expect(parseTargetLocks("not json")).toEqual({ version: 1, locks: {} });
61
+ expect(parseTargetLocks(JSON.stringify({ version: 2, locks: {} }))).toEqual({ version: 1, locks: {} });
62
+ expect(parseTargetLocks(null)).toEqual({ version: 1, locks: {} });
63
+ });
64
+
65
+ test("renders targets sorted, so the same locks are the same blob", () => {
66
+ const a = renderTargetLocks({ version: 1, locks: { web: holder(1, "plan"), api: holder(2, "lock") } });
67
+ const b = renderTargetLocks({ version: 1, locks: { api: holder(2, "lock"), web: holder(1, "plan") } });
68
+ expect(a).toBe(b);
69
+ expect(Object.keys(JSON.parse(a).locks)).toEqual(["api", "web"]);
70
+ });
71
+
72
+ test("the path is _locks/<gate>.json under the member prefix, and a gate name must be a file name", () => {
73
+ expect(targetLockPath("pr-apply")).toBe("_locks/pr-apply.json");
74
+ expect(targetLockPath("pr-apply", "_members/api/")).toBe("_members/api/_locks/pr-apply.json");
75
+ expect(targetLockGateProblem("pr-apply")).toBeNull();
76
+ expect(targetLockGateProblem("../x")).toMatch(/not a lock file name/);
77
+ });
78
+
79
+ test("describes held locks by pull request, with how they were taken", () => {
80
+ const text = describeHeldTargetLocks([
81
+ { target: "api", ...holder(7, "plan", "bob") },
82
+ { target: "web", ...holder(7, "plan", "bob") },
83
+ { target: "db", ...holder(9, "lock", "carol") },
84
+ ], (n) => `merge request !${n}`);
85
+ expect(text).toBe("api, web are locked by merge request !7 (planned by bob); db is locked by merge request !9 (locked with chant lock by carol)");
86
+ });
87
+ });
88
+
89
+ describe("target locks in one clone", () => {
90
+ test("a pull request takes free targets; another is refused with the holder named; unlock frees them", async () => {
91
+ const cwd = initRepo();
92
+ const first = await takeTargetLocks("pr-apply", ["web", "api"], holder(1, "plan"), { cwd });
93
+ expect(first).toEqual({ ok: true, taken: ["api", "web"], released: [], expired: [], pushed: false });
94
+ expect(JSON.parse(git(cwd, "show", "chant/lifecycle:_locks/pr-apply.json")).locks.web.pr).toBe(1);
95
+
96
+ const second = await takeTargetLocks("pr-apply", ["web", "db"], holder(2, "plan", "bob"), { cwd });
97
+ expect(second).toEqual({ ok: false, held: [{ target: "web", ...holder(1, "plan") }] });
98
+ // Nothing of the refused pull request was written.
99
+ expect(Object.keys((await readTargetLocks("pr-apply", { cwd })).locks)).toEqual(["api", "web"]);
100
+
101
+ expect(await heldTargetLocks("pr-apply", ["web", "db"], 2, { cwd })).toHaveLength(1);
102
+ expect(await heldTargetLocks("pr-apply", ["web", "db"], 1, { cwd })).toEqual([]);
103
+ expect(await heldTargetLocks("pr-apply", ["web"], null, { cwd })).toHaveLength(1);
104
+
105
+ expect(await releaseTargetLocks("pr-apply", 1, { cwd, targets: ["api"] })).toEqual({ released: ["api"], pushed: false });
106
+ expect(await releaseTargetLocks("pr-apply", 1, { cwd })).toEqual({ released: ["web"], pushed: false });
107
+ expect(await releaseTargetLocks("pr-apply", 1, { cwd })).toEqual({ released: [], pushed: false });
108
+ expect(await takeTargetLocks("pr-apply", ["web", "db"], holder(2, "plan", "bob"), { cwd })).toMatchObject({ ok: true, taken: ["db", "web"] });
109
+ });
110
+
111
+ test("a lock whose pull request merged or closed is taken over and dropped", async () => {
112
+ const cwd = initRepo();
113
+ await takeTargetLocks("pr-apply", ["web", "api"], holder(1, "plan"), { cwd });
114
+ const isOpen = async (pr: number) => pr !== 1;
115
+ const taken = await takeTargetLocks("pr-apply", ["web"], holder(2, "lock", "bob"), { cwd, isOpen });
116
+ expect(taken).toMatchObject({ ok: true, taken: ["web"], expired: ["api", "web"] });
117
+ expect((await readTargetLocks("pr-apply", { cwd })).locks).toEqual({ web: holder(2, "lock", "bob") });
118
+ expect(await heldTargetLocks("pr-apply", ["web"], 3, { cwd, isOpen: async () => false })).toEqual([]);
119
+ });
120
+
121
+ test("a plan keeps the pull request's own lock and apply locks; an apply takes over its plan locks", async () => {
122
+ const cwd = initRepo();
123
+ await takeTargetLocks("pr-apply", ["web"], holder(1, "lock"), { cwd });
124
+ await takeTargetLocks("pr-apply", ["web", "api"], holder(1, "plan"), { cwd });
125
+ let locks = (await readTargetLocks("pr-apply", { cwd })).locks;
126
+ expect(locks.web.stage).toBe("lock");
127
+ expect(locks.api.stage).toBe("plan");
128
+ await takeTargetLocks("pr-apply", ["api"], holder(1, "apply"), { cwd });
129
+ locks = (await readTargetLocks("pr-apply", { cwd })).locks;
130
+ expect(locks.api.stage).toBe("apply");
131
+ });
132
+
133
+ test("a plan with releaseStalePlan drops its plan locks on targets the head no longer reaches", async () => {
134
+ const cwd = initRepo();
135
+ await takeTargetLocks("pr-apply", ["web", "api"], holder(1, "plan"), { cwd });
136
+ await takeTargetLocks("pr-apply", ["db"], holder(1, "lock"), { cwd });
137
+ const again = await takeTargetLocks("pr-apply", ["web"], holder(1, "plan"), { cwd, releaseStalePlan: true });
138
+ expect(again).toMatchObject({ ok: true, taken: ["web"], released: ["api"] });
139
+ expect(Object.keys((await readTargetLocks("pr-apply", { cwd })).locks)).toEqual(["db", "web"]);
140
+ });
141
+
142
+ test("each gate keeps its own file", async () => {
143
+ const cwd = initRepo();
144
+ await takeTargetLocks("pr-apply", ["web"], holder(1, "plan"), { cwd });
145
+ expect(await takeTargetLocks("staging-apply", ["web"], holder(2, "plan"), { cwd })).toMatchObject({ ok: true });
146
+ expect(git(cwd, "ls-tree", "--name-only", "chant/lifecycle", "_locks/").split("\n").sort()).toEqual(["_locks/pr-apply.json", "_locks/staging-apply.json"]);
147
+ });
148
+ });
149
+
150
+ describe("target locks across clones, through a bare remote", () => {
151
+ function setup(): { root: string; remote: string; a: string; b: string } {
152
+ const root = tmp("chant-target-lock-remote-");
153
+ const remote = join(root, "remote.git");
154
+ git(root, "init", "-q", "--bare", "-b", "main", remote);
155
+ const a = join(root, "a");
156
+ git(root, "clone", "-q", remote, a);
157
+ configure(a);
158
+ writeFileSync(join(a, "README.md"), "# t\n");
159
+ git(a, "add", "README.md");
160
+ git(a, "commit", "-q", "-m", "init");
161
+ git(a, "push", "-q", "origin", "main");
162
+ const b = join(root, "b");
163
+ git(root, "clone", "-q", remote, b);
164
+ configure(b);
165
+ return { root, remote, a, b };
166
+ }
167
+
168
+ test("a lock reaches the remote, the other clone is refused, and an unlock there frees it", async () => {
169
+ const { remote, a, b } = setup();
170
+ expect(await takeTargetLocks("pr-apply", ["web"], holder(1, "plan"), { cwd: a })).toMatchObject({ ok: true, pushed: true });
171
+ expect(JSON.parse(git(remote, "show", "chant/lifecycle:_locks/pr-apply.json")).locks.web.pr).toBe(1);
172
+ expect(await takeTargetLocks("pr-apply", ["web"], holder(2, "plan"), { cwd: b })).toMatchObject({ ok: false, held: [{ target: "web", pr: 1 }] });
173
+ expect(await releaseTargetLocks("pr-apply", 1, { cwd: b })).toEqual({ released: ["web"], pushed: true });
174
+ expect(await takeTargetLocks("pr-apply", ["web"], holder(2, "plan"), { cwd: a })).toMatchObject({ ok: true, taken: ["web"], pushed: true });
175
+ });
176
+
177
+ test("a push the remote refuses is dropped and decided again: two clones can't both lock one target", async () => {
178
+ const { root, remote, a, b } = setup();
179
+ // A writes its lock locally only, with no remote, then pushes it from B's pre-push hook,
180
+ // so B's first push lands after A's and is refused.
181
+ git(a, "remote", "remove", "origin");
182
+ expect(await takeTargetLocks("pr-apply", ["web"], holder(1, "plan"), { cwd: a })).toMatchObject({ ok: true, pushed: false });
183
+ git(a, "remote", "add", "origin", remote);
184
+ const marker = join(root, "raced");
185
+ const hook = join(b, ".git", "hooks", "pre-push");
186
+ writeFileSync(hook, `#!/bin/sh\nif [ ! -e "${marker}" ]; then touch "${marker}"; git -C "${a}" push -q origin chant/lifecycle:chant/lifecycle; fi\nexit 0\n`);
187
+ chmodSync(hook, 0o755);
188
+
189
+ const lost = await takeTargetLocks("pr-apply", ["web", "api"], holder(2, "plan", "bob"), { cwd: b });
190
+ expect(lost).toEqual({ ok: false, held: [{ target: "web", ...holder(1, "plan") }] });
191
+ // B's refused commit is gone: its branch is the remote's, which holds only A's lock.
192
+ expect(git(b, "rev-parse", "chant/lifecycle")).toBe(git(remote, "rev-parse", "chant/lifecycle"));
193
+ expect(Object.keys(JSON.parse(git(remote, "show", "chant/lifecycle:_locks/pr-apply.json")).locks)).toEqual(["web"]);
194
+ });
195
+ });
@@ -0,0 +1,347 @@
1
+ /**
2
+ * Target locks (#4293): a pull request holds a lock on each target its
3
+ * change reaches, so no other pull request applies or locks those targets
4
+ * until it merges or closes, or someone runs `chant unlock` on it.
5
+ *
6
+ * A target is a name the caller picks: a component, a workspace member, or
7
+ * a lexicon's own unit such as a Terraform root. The locks of one gate live
8
+ * in one file, `_locks/<gate>.json` on `chant/lifecycle`, under the member's
9
+ * ledger prefix in a workspace member (./git.ts `ledgerDir`). The gate is
10
+ * the pull-request loop's, `pr-apply` unless the pipeline names another, so
11
+ * two pipelines with their own gates keep their own locks.
12
+ *
13
+ * Every change is a new commit on the branch, written with the read-then-CAS
14
+ * the other ledgers use and then pushed. A lock counts only once the remote
15
+ * has it: when the push is refused because another writer moved the branch,
16
+ * the local commit is dropped, the branch is read again and the decision is
17
+ * made again. So two jobs that lock the same target at once cannot both win.
18
+ * A repository with no remote is one machine, and the local write decides.
19
+ *
20
+ * A lock held by a pull request that is no longer open is released: the
21
+ * holder merged or closed. The caller says which pull requests are open
22
+ * (`isOpen`, from the forge). Without it every lock counts as held, and only
23
+ * `chant unlock` releases one.
24
+ *
25
+ * The file is coordination, not a record of work. ws-074 holds: the
26
+ * repository is the database, and the file is one more ledger on the
27
+ * branch, so any clone can read who holds what.
28
+ */
29
+ import { getRuntime } from "../runtime-adapter";
30
+ import {
31
+ fetchLifecycleStatus,
32
+ pushLifecycleStatus,
33
+ readBlobBySha,
34
+ readPathSha,
35
+ RefCASConflictError,
36
+ writeBlobToPath,
37
+ } from "./git";
38
+ import { resolveMemberLedger } from "./member-ledger";
39
+
40
+ /** The directory on `chant/lifecycle` that holds the lock files. */
41
+ export const LOCKS_DIR = "_locks";
42
+
43
+ const STATE_BRANCH = "chant/lifecycle";
44
+ /** A scratch ref this module owns, for reading the remote tip after a refused push. */
45
+ const PROBE_REF = "refs/chant/target-lock-probe";
46
+ const ATTEMPTS = 5;
47
+
48
+ /**
49
+ * How a lock was taken. `plan`: the pull request's plan took it (`ci.locks:
50
+ * plan`). `apply`: its apply took it. `lock`: someone ran `chant lock`.
51
+ */
52
+ export type TargetLockStage = "plan" | "apply" | "lock";
53
+
54
+ export const TARGET_LOCK_STAGES = ["plan", "apply", "lock"] as const satisfies readonly TargetLockStage[];
55
+
56
+ /** One target's lock: the pull request that holds it, who took it, when, how, and the head it took it at. */
57
+ export interface TargetLock {
58
+ pr: number;
59
+ by: string;
60
+ at: string;
61
+ stage: TargetLockStage;
62
+ /** The pull request's head commit when the lock was taken. Absent when the caller did not say. */
63
+ head?: string;
64
+ }
65
+
66
+ /** `_locks/<gate>.json`. */
67
+ export interface TargetLockFile {
68
+ version: 1;
69
+ locks: Record<string, TargetLock>;
70
+ }
71
+
72
+ /** A lock another open pull request holds on a target the caller needs. */
73
+ export interface HeldTargetLock extends TargetLock {
74
+ target: string;
75
+ }
76
+
77
+ /** Says whether pull request `pr` is still open. */
78
+ export type PullRequestOpen = (pr: number) => Promise<boolean>;
79
+
80
+ export interface TargetLockOptions {
81
+ cwd?: string;
82
+ /** Whether a holder is still open. Absent: every holder counts as open. */
83
+ isOpen?: PullRequestOpen;
84
+ }
85
+
86
+ export type TakeTargetLocksResult =
87
+ | {
88
+ ok: true;
89
+ /** The targets now locked, sorted. */
90
+ taken: string[];
91
+ /** Plan locks of the same pull request on targets it no longer reaches, released (`releaseStalePlan`). */
92
+ released: string[];
93
+ /** Locks of merged or closed pull requests that this write dropped. */
94
+ expired: string[];
95
+ /** Whether the remote has the write. False with no remote, or when recording is off. */
96
+ pushed: boolean;
97
+ }
98
+ | { ok: false; held: HeldTargetLock[] };
99
+
100
+ /** The path of `gate`'s lock file on `chant/lifecycle`, under a member's prefix when it has one. */
101
+ export function targetLockPath(gate: string, memberPrefix = ""): string {
102
+ return `${memberPrefix}${LOCKS_DIR}/${gate}.json`;
103
+ }
104
+
105
+ /** A gate name that is safe as a file name. */
106
+ export function targetLockGateProblem(gate: string): string | null {
107
+ return /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(gate) ? null : `the gate name ${JSON.stringify(gate)} is not a lock file name: letters, digits, '.', '_' and '-', starting with a letter or digit`;
108
+ }
109
+
110
+ const isStage = (v: unknown): v is TargetLockStage => typeof v === "string" && (TARGET_LOCK_STAGES as readonly string[]).includes(v);
111
+
112
+ /** Parse a lock file. Anything that is not a version 1 file with a map of locks reads as no locks; a malformed entry is dropped. */
113
+ export function parseTargetLocks(text: string | null): TargetLockFile {
114
+ if (!text) return { version: 1, locks: {} };
115
+ try {
116
+ const doc = JSON.parse(text) as { version?: unknown; locks?: unknown };
117
+ if (doc?.version === 1 && doc.locks && typeof doc.locks === "object" && !Array.isArray(doc.locks)) {
118
+ const locks: Record<string, TargetLock> = {};
119
+ for (const [target, raw] of Object.entries(doc.locks as Record<string, Record<string, unknown>>)) {
120
+ if (!raw || !Number.isInteger(raw.pr) || typeof raw.by !== "string" || typeof raw.at !== "string" || !isStage(raw.stage)) continue;
121
+ locks[target] = { pr: raw.pr as number, by: raw.by, at: raw.at, stage: raw.stage, ...(typeof raw.head === "string" ? { head: raw.head } : {}) };
122
+ }
123
+ return { version: 1, locks };
124
+ }
125
+ } catch {
126
+ // An unreadable file holds no locks.
127
+ }
128
+ return { version: 1, locks: {} };
129
+ }
130
+
131
+ /** The file's text: targets sorted, so two writes of the same locks are the same blob. */
132
+ export function renderTargetLocks(file: TargetLockFile): string {
133
+ const locks = Object.fromEntries(Object.keys(file.locks).sort().map((t) => [t, file.locks[t]]));
134
+ return `${JSON.stringify({ version: 1, locks }, null, 2)}\n`;
135
+ }
136
+
137
+ /** Fetch `chant/lifecycle`, refusing a ledger this checkout cannot read: a lock decided on a stale branch is no lock. */
138
+ async function fetchForLocks(cwd?: string): Promise<void> {
139
+ const fetched = await fetchLifecycleStatus({ cwd });
140
+ if (fetched.status === "diverged") throw new Error(`the local ${STATE_BRANCH} has forked from ${fetched.remote}'s, so the locks cannot be read: ${fetched.stderr}`);
141
+ if (fetched.status === "unreachable") throw new Error(`cannot fetch ${STATE_BRANCH} from ${fetched.remote}, so the locks cannot be read${fetched.stderr ? `: ${fetched.stderr}` : ""}`);
142
+ }
143
+
144
+ async function readCurrent(gate: string, cwd?: string): Promise<{ sha: string | null; file: TargetLockFile }> {
145
+ const sha = await readPathSha(LOCKS_DIR, `${gate}.json`, { cwd });
146
+ return { sha, file: parseTargetLocks(sha ? await readBlobBySha(sha, { cwd }) : null) };
147
+ }
148
+
149
+ /** The locks of `gate` as the remote holds them now, fetched first. */
150
+ export async function readTargetLocks(gate: string, opts: { cwd?: string } = {}): Promise<TargetLockFile> {
151
+ const problem = targetLockGateProblem(gate);
152
+ if (problem) throw new Error(problem);
153
+ await fetchForLocks(opts.cwd);
154
+ return (await readCurrent(gate, opts.cwd)).file;
155
+ }
156
+
157
+ /** A memo of `isOpen`, so one decision asks the forge about each pull request once. */
158
+ function openMemo(isOpen?: PullRequestOpen): PullRequestOpen {
159
+ const seen = new Map<number, Promise<boolean>>();
160
+ return (pr) => {
161
+ if (!isOpen) return Promise.resolve(true);
162
+ if (!seen.has(pr)) seen.set(pr, isOpen(pr));
163
+ return seen.get(pr)!;
164
+ };
165
+ }
166
+
167
+ /** The locks on `targets` that an open pull request other than `pr` holds, by target. */
168
+ async function heldIn(file: TargetLockFile, targets: readonly string[], pr: number | null, open: PullRequestOpen): Promise<HeldTargetLock[]> {
169
+ const held: HeldTargetLock[] = [];
170
+ for (const target of [...new Set(targets)].sort()) {
171
+ const l = file.locks[target];
172
+ if (l && l.pr !== pr && (await open(l.pr))) held.push({ target, ...l });
173
+ }
174
+ return held;
175
+ }
176
+
177
+ /**
178
+ * The locks on `targets` that an open pull request other than `pr` holds.
179
+ * Reads only: an apply calls this to refuse a target another pull request
180
+ * holds. `pr` null (an apply of a green commit) counts every open holder.
181
+ */
182
+ export async function heldTargetLocks(gate: string, targets: readonly string[], pr: number | null, opts: TargetLockOptions = {}): Promise<HeldTargetLock[]> {
183
+ if (targets.length === 0) return [];
184
+ const file = await readTargetLocks(gate, opts);
185
+ return heldIn(file, targets, pr, openMemo(opts.isOpen));
186
+ }
187
+
188
+ /** The local tip of `chant/lifecycle`, or "" when there is none. */
189
+ async function localTip(cwd?: string): Promise<string> {
190
+ const out = await getRuntime().spawn(["git", "rev-parse", "--verify", "--quiet", `refs/heads/${STATE_BRANCH}`], { cwd });
191
+ return out.exitCode === 0 ? out.stdout.trim() : "";
192
+ }
193
+
194
+ /**
195
+ * After a refused push: drop the lock commit `ours` from the local branch by
196
+ * moving it to the remote's tip, so the next attempt reads what the other
197
+ * writer pushed. Done only when `parent`, the tip before the write, is in
198
+ * the remote's history, so no other local commit is lost. Throws otherwise.
199
+ */
200
+ async function dropRefusedWrite(remote: string, ours: string, parent: string, cwd?: string): Promise<void> {
201
+ const rt = getRuntime();
202
+ const env = { LC_ALL: "C", LANGUAGE: "" };
203
+ const probe = await rt.spawn(["git", "fetch", "--force", remote, `${STATE_BRANCH}:${PROBE_REF}`], { cwd, env });
204
+ if (probe.exitCode !== 0) throw new Error(`the push of the locks was refused and ${STATE_BRANCH} could not be read again from ${remote}: ${probe.stderr.trim()}`);
205
+ try {
206
+ if (parent) {
207
+ const contains = await rt.spawn(["git", "merge-base", "--is-ancestor", parent, PROBE_REF], { cwd, env });
208
+ if (contains.exitCode !== 0) throw new Error(`the push of the locks was refused, and the local ${STATE_BRANCH} holds commits ${remote} does not; push or fetch ${STATE_BRANCH} and lock again`);
209
+ }
210
+ const tip = (await rt.spawn(["git", "rev-parse", "--verify", PROBE_REF], { cwd, env })).stdout.trim();
211
+ const moved = await rt.spawn(["git", "update-ref", `refs/heads/${STATE_BRANCH}`, tip, ours], { cwd, env });
212
+ if (moved.exitCode !== 0) throw new Error(`could not drop the refused lock commit from ${STATE_BRANCH}: ${moved.stderr.trim()}`);
213
+ await rt.spawn(["git", "update-ref", `refs/remotes/${remote}/${STATE_BRANCH}`, tip], { cwd, env });
214
+ } finally {
215
+ await rt.spawn(["git", "update-ref", "-d", PROBE_REF], { cwd, env });
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Write `next` over the file read at `sha`, then push. Returns null when the
221
+ * branch moved under the write (locally or on the remote), so the caller
222
+ * reads and decides again.
223
+ */
224
+ async function writeAndPush(gate: string, sha: string | null, next: TargetLockFile, message: string, cwd?: string): Promise<{ pushed: boolean } | null> {
225
+ const parent = await localTip(cwd);
226
+ let commit: string;
227
+ try {
228
+ commit = await writeBlobToPath(LOCKS_DIR, `${gate}.json`, renderTargetLocks(next), message, { cwd, expectPriorPathSha: sha });
229
+ } catch (err) {
230
+ if (err instanceof RefCASConflictError) return null;
231
+ throw err;
232
+ }
233
+ const push = await pushLifecycleStatus({ cwd });
234
+ switch (push.status) {
235
+ case "pushed":
236
+ return { pushed: true };
237
+ case "no-remote":
238
+ case "not-recorded":
239
+ return { pushed: false };
240
+ case "stale":
241
+ await dropRefusedWrite(push.remote, commit, parent, cwd);
242
+ await fetchForLocks(cwd);
243
+ return null;
244
+ case "failed":
245
+ throw new Error(`the locks were written but the push of ${STATE_BRANCH} to ${push.remote} failed, so they do not count yet: ${push.stderr}`);
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Lock `targets` for pull request `holder.pr`. A target locked by another
251
+ * pull request that is still open is held, and nothing is locked. A target
252
+ * locked by one that merged or closed is taken over, and its lock dropped.
253
+ * Targets this pull request already holds stay its own, with the new head.
254
+ * An apply or a `chant lock` takes over the pull request's own plan locks;
255
+ * a plan keeps its own apply and `chant lock` locks as they are. With
256
+ * `releaseStalePlan`, the pull request's plan locks on targets it no longer
257
+ * reaches are released.
258
+ */
259
+ export async function takeTargetLocks(
260
+ gate: string,
261
+ targets: readonly string[],
262
+ holder: TargetLock,
263
+ opts: TargetLockOptions & { releaseStalePlan?: boolean } = {},
264
+ ): Promise<TakeTargetLocksResult> {
265
+ const problem = targetLockGateProblem(gate);
266
+ if (problem) throw new Error(problem);
267
+ for (const t of targets) if (t.trim() === "") throw new Error("a lock target is a non-empty name");
268
+ const wanted = [...new Set(targets)].sort();
269
+ const open = openMemo(opts.isOpen);
270
+ await fetchForLocks(opts.cwd);
271
+ for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {
272
+ const { sha, file } = await readCurrent(gate, opts.cwd);
273
+ const held = await heldIn(file, wanted, holder.pr, open);
274
+ if (held.length > 0) return { ok: false, held };
275
+
276
+ const next: TargetLockFile = { version: 1, locks: {} };
277
+ const released: string[] = [];
278
+ const expired: string[] = [];
279
+ for (const [target, l] of Object.entries(file.locks)) {
280
+ if (l.pr === holder.pr) {
281
+ if (opts.releaseStalePlan && l.stage === "plan" && !wanted.includes(target)) {
282
+ released.push(target);
283
+ continue;
284
+ }
285
+ } else if (opts.isOpen && !(await open(l.pr))) {
286
+ expired.push(target);
287
+ continue;
288
+ }
289
+ next.locks[target] = l;
290
+ }
291
+ for (const target of wanted) {
292
+ const own = file.locks[target];
293
+ next.locks[target] = holder.stage === "plan" && own?.pr === holder.pr && own.stage !== "plan" ? own : holder;
294
+ }
295
+ const done = { ok: true as const, taken: wanted, released: released.sort(), expired: expired.sort() };
296
+ if (renderTargetLocks(next) === renderTargetLocks(file) && sha !== null) return { ...done, pushed: false };
297
+ if (wanted.length === 0 && released.length === 0 && expired.length === 0) return { ...done, pushed: false };
298
+ const wrote = await writeAndPush(gate, sha, next, `Lock ${wanted.length} target${wanted.length === 1 ? "" : "s"} of ${gate} for pull request ${holder.pr} (${holder.stage})`, opts.cwd);
299
+ if (wrote) return { ...done, pushed: wrote.pushed };
300
+ }
301
+ throw new Error(`could not write the locks of ${gate}: ${STATE_BRANCH} kept moving; lock again`);
302
+ }
303
+
304
+ /**
305
+ * Release the locks pull request `pr` holds on `gate`: every one, or only
306
+ * those on `targets`. Returns the targets released, sorted.
307
+ */
308
+ export async function releaseTargetLocks(
309
+ gate: string,
310
+ pr: number,
311
+ opts: { cwd?: string; targets?: readonly string[] } = {},
312
+ ): Promise<{ released: string[]; pushed: boolean }> {
313
+ const problem = targetLockGateProblem(gate);
314
+ if (problem) throw new Error(problem);
315
+ await fetchForLocks(opts.cwd);
316
+ for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {
317
+ const { sha, file } = await readCurrent(gate, opts.cwd);
318
+ const mine = Object.keys(file.locks)
319
+ .filter((t) => file.locks[t].pr === pr && (!opts.targets || opts.targets.includes(t)))
320
+ .sort();
321
+ if (mine.length === 0) return { released: [], pushed: false };
322
+ const next: TargetLockFile = { version: 1, locks: Object.fromEntries(Object.entries(file.locks).filter(([t]) => !mine.includes(t))) };
323
+ const wrote = await writeAndPush(gate, sha, next, `Unlock ${mine.length} target${mine.length === 1 ? "" : "s"} of ${gate} held by pull request ${pr}`, opts.cwd);
324
+ if (wrote) return { released: mine, pushed: wrote.pushed };
325
+ }
326
+ throw new Error(`could not write the locks of ${gate}: ${STATE_BRANCH} kept moving; unlock again`);
327
+ }
328
+
329
+ /** The lock file's path for the project at `cwd`, for messages. */
330
+ export async function targetLockPathAt(gate: string, cwd?: string): Promise<string> {
331
+ const { prefix } = await resolveMemberLedger(cwd ?? process.cwd());
332
+ return targetLockPath(gate, prefix);
333
+ }
334
+
335
+ const STAGE_WORDS: Record<TargetLockStage, string> = { plan: "planned", apply: "applied", lock: "locked with chant lock" };
336
+
337
+ /**
338
+ * One line naming the targets others hold, for a refusal or a note.
339
+ * `name` says how the forge names a holder (GitLab: `merge request !7`).
340
+ */
341
+ export function describeHeldTargetLocks(held: readonly HeldTargetLock[], name: (pr: number) => string = (pr) => `pull request ${pr}`): string {
342
+ const byPr = new Map<number, HeldTargetLock[]>();
343
+ for (const h of held) byPr.set(h.pr, [...(byPr.get(h.pr) ?? []), h]);
344
+ return [...byPr]
345
+ .map(([pr, hs]) => `${hs.map((h) => h.target).join(", ")} ${hs.length === 1 ? "is" : "are"} locked by ${name(pr)} (${STAGE_WORDS[hs[0].stage]} by ${hs[0].by})`)
346
+ .join("; ");
347
+ }
@@ -145,3 +145,34 @@ export function zeroResourcesWarning(
145
145
  if (Object.keys(observed.unobserved).length > 0) return undefined;
146
146
  return `${lexicon}: 0 live resources for env "${environment}" (${declaredCount} declared) — check the endpoint/credentials`;
147
147
  }
148
+
149
+ /**
150
+ * Run `run` with `environment`'s declared endpoint applied, as
151
+ * {@link applyLiveEndpoint} applies it to a `--live` read, and restored after
152
+ * (#4281). The component plan and apply paths (`components pr-plan`,
153
+ * `pr-apply`, `pr-record`, `fan-out`, `promote`, `rollback`, `redeploy` and
154
+ * `chant run --components`) run capabilities that honor the same ambient vars:
155
+ * azure's `arm-deploy` reads `AZURE_ENDPOINT_URL`, gcp's `gcp-apply`
156
+ * `GCP_ENDPOINT_URL`, aws's `cfn-deploy` `AWS_ENDPOINT_URL`. Without this, a
157
+ * plan for an environment declared against an emulator went to the real cloud
158
+ * unless the shell exported the var by hand.
159
+ *
160
+ * `lexicons` is called only when the environment declares an endpoint, so a
161
+ * caller that has to load its plugins pays for that only then.
162
+ */
163
+ export async function withEnvironmentEndpoint<T>(
164
+ environments: EnvironmentDeclaration[] | undefined,
165
+ environment: string,
166
+ lexicons: () => Promise<readonly EndpointLexicon[]> | readonly EndpointLexicon[],
167
+ run: () => Promise<T>,
168
+ options: { warn?: (message: string) => void; env?: NodeJS.ProcessEnv } = {},
169
+ ): Promise<T> {
170
+ if (!environmentEndpoint(environments, environment)) return run();
171
+ const applied = applyLiveEndpoint(environments, environment, await lexicons(), options.env);
172
+ if (applied.notice) options.warn?.(applied.notice);
173
+ try {
174
+ return await run();
175
+ } finally {
176
+ applied.restore();
177
+ }
178
+ }
@@ -141,6 +141,37 @@ export const behaviourFindingContract = activityContract(
141
141
  }),
142
142
  );
143
143
 
144
+ /**
145
+ * The review agent (#4299). `changeSet` is `composeChangeSet`'s document,
146
+ * checked only for the fields the prompt reads. `returns` names what a later
147
+ * step may read; no gate reads it.
148
+ */
149
+ export const reviewAgentContract = activityContract(
150
+ "reviewAgent",
151
+ z.strictObject({
152
+ op: z.string(),
153
+ changeSet: z.object({ digest: z.string(), entries: z.array(z.unknown()) }).passthrough().optional(),
154
+ changeSetFile: z.string().optional(),
155
+ mode: z.enum(["comment", "report"]).optional(),
156
+ title: z.string().optional(),
157
+ description: z.string().optional(),
158
+ base: z.string().optional(),
159
+ instructions: z.string().optional(),
160
+ command: z.string().optional(),
161
+ keyEnv: z.string().optional(),
162
+ timeout: z.number().positive().optional(),
163
+ }),
164
+ z.object({
165
+ mode: z.enum(["comment", "report"]),
166
+ risk: z.enum(["low", "medium", "high", "unknown"]),
167
+ exitCode: z.number().nullable(),
168
+ summary: z.string(),
169
+ commentUrl: z.string().optional(),
170
+ pullRequest: z.string().optional(),
171
+ mergeRequest: z.string().optional(),
172
+ }),
173
+ );
174
+
144
175
  /**
145
176
  * The propose-only template upgrade (#2550, ws-032). `args` mirrors
146
177
  * `ProposeWorkspaceUpgradeArgs` without its test hooks. `returns` names what
@@ -161,6 +161,12 @@ export type {
161
161
  BaseCheckout,
162
162
  } from "./predict-behaviour";
163
163
 
164
+ // The review agent (#4299): a model reviews the change set against the pull
165
+ // request's own text and posts one sticky note. Only the activity and its
166
+ // marker are re-exported, since the registry collects every exported function.
167
+ export { reviewAgent, reviewMarker } from "./review-agent";
168
+ export type { ReviewAgentArgs, ReviewAgentResult, ReviewAgentMode, ReviewRisk } from "./review-agent";
169
+
164
170
  // The propose-only template upgrade (#2550). Loads the workspace code on first
165
171
  // call only, so importing this module loads nothing under `workspace/`.
166
172
  export { proposeWorkspaceUpgrade } from "./propose-upgrade";