@intentius/chant 0.124.108 → 0.124.110

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 (342) hide show
  1. package/dist/__golden__/wave-loop/fan-out-applied.json +12 -6
  2. package/dist/__golden__/wave-loop/fan-out-apply-fails.json +8 -4
  3. package/dist/__golden__/wave-loop/fan-out-gated.json +4 -2
  4. package/dist/__golden__/wave-loop/fan-out-no-members.json +16 -8
  5. package/dist/__golden__/wave-loop/fan-out-plan-fails.json +8 -4
  6. package/dist/__golden__/wave-loop/fan-out-same-root.json +4 -2
  7. package/dist/agent-facts.d.ts +130 -0
  8. package/dist/agent-facts.js +196 -0
  9. package/dist/change-risk.d.ts +216 -0
  10. package/dist/change-risk.js +304 -0
  11. package/dist/change-set.d.ts +8 -0
  12. package/dist/ci-agent-alert.d.ts +139 -0
  13. package/dist/ci-agent-alert.js +342 -0
  14. package/dist/ci-agent-triggers.d.ts +152 -0
  15. package/dist/ci-agent-triggers.js +232 -0
  16. package/dist/ci-agent-verify-failed.d.ts +149 -0
  17. package/dist/ci-agent-verify-failed.js +191 -0
  18. package/dist/ci-agent.d.ts +136 -8
  19. package/dist/ci-agent.js +353 -26
  20. package/dist/ci-comment-commands.d.ts +8 -0
  21. package/dist/ci-comment-commands.js +17 -1
  22. package/dist/ci-comment-reject.d.ts +70 -0
  23. package/dist/ci-comment-reject.js +135 -0
  24. package/dist/ci-comment-replies.d.ts +3 -1
  25. package/dist/ci-comment-replies.js +6 -0
  26. package/dist/ci-estate/delivery.d.ts +25 -3
  27. package/dist/ci-estate/delivery.js +28 -9
  28. package/dist/ci-estate/page.d.ts +7 -3
  29. package/dist/ci-estate/page.js +19 -4
  30. package/dist/ci-estate/rows.d.ts +14 -2
  31. package/dist/ci-estate/rows.js +9 -1
  32. package/dist/ci-estate.d.ts +5 -2
  33. package/dist/ci-estate.js +3 -2
  34. package/dist/ci-handover.d.ts +2 -7
  35. package/dist/ci-handover.js +3 -20
  36. package/dist/ci-jobs.d.ts +6 -0
  37. package/dist/ci-jobs.js +17 -0
  38. package/dist/ci-note-commands.d.ts +2 -0
  39. package/dist/ci-note-commands.js +12 -1
  40. package/dist/ci-product-words.d.ts +151 -1
  41. package/dist/ci-product-words.js +1390 -3
  42. package/dist/ci-product.d.ts +100 -4
  43. package/dist/ci-product.js +99 -3
  44. package/dist/ci-respond-run.d.ts +9 -0
  45. package/dist/ci-respond-run.js +35 -4
  46. package/dist/ci-respond-summary-env.d.ts +56 -0
  47. package/dist/ci-respond-summary-env.js +81 -0
  48. package/dist/ci-respond-summary.d.ts +103 -0
  49. package/dist/ci-respond-summary.js +243 -0
  50. package/dist/ci-respond.d.ts +4 -2
  51. package/dist/ci-respond.js +4 -2
  52. package/dist/cli/command-group.js +1 -1
  53. package/dist/cli/commands/lint.js +21 -3
  54. package/dist/cli/handlers/agent.js +49 -4
  55. package/dist/cli/handlers/approve.js +3 -1
  56. package/dist/cli/handlers/build.d.ts +97 -1
  57. package/dist/cli/handlers/build.js +251 -3
  58. package/dist/cli/handlers/fan-out.js +55 -0
  59. package/dist/cli/handlers/graph.d.ts +14 -0
  60. package/dist/cli/handlers/graph.js +58 -3
  61. package/dist/cli/handlers/lifecycle-health.d.ts +7 -0
  62. package/dist/cli/handlers/lifecycle-health.js +47 -9
  63. package/dist/cli/handlers/lifecycle.js +4 -1
  64. package/dist/cli/handlers/notify-relay.d.ts +2 -2
  65. package/dist/cli/handlers/notify-relay.js +67 -7
  66. package/dist/cli/handlers/pipeline-agent.d.ts +30 -0
  67. package/dist/cli/handlers/pipeline-agent.js +255 -0
  68. package/dist/cli/handlers/pipeline-artifacts.d.ts +39 -0
  69. package/dist/cli/handlers/pipeline-artifacts.js +203 -0
  70. package/dist/cli/handlers/pipeline.d.ts +16 -0
  71. package/dist/cli/handlers/pipeline.js +112 -0
  72. package/dist/cli/handlers/pr-comment.js +4 -0
  73. package/dist/cli/handlers/pr-notes.js +4 -1
  74. package/dist/cli/handlers/pr.d.ts +20 -0
  75. package/dist/cli/handlers/pr.js +114 -11
  76. package/dist/cli/handlers/promote.js +792 -47
  77. package/dist/cli/handlers/reject.d.ts +84 -0
  78. package/dist/cli/handlers/reject.js +216 -0
  79. package/dist/cli/handlers/release.js +4 -2
  80. package/dist/cli/handlers/replan.d.ts +54 -0
  81. package/dist/cli/handlers/replan.js +177 -0
  82. package/dist/cli/handlers/run-generate.d.ts +5 -0
  83. package/dist/cli/handlers/run-generate.js +31 -4
  84. package/dist/cli/handlers/run-wave.js +15 -2
  85. package/dist/cli/handlers/run.js +4 -2
  86. package/dist/cli/handlers/stage.d.ts +35 -0
  87. package/dist/cli/handlers/stage.js +90 -0
  88. package/dist/cli/lsp/server.js +4 -0
  89. package/dist/cli/main.js +88 -8
  90. package/dist/cli/parse-args.js +35 -2
  91. package/dist/cli/registry.d.ts +12 -0
  92. package/dist/components/auto-release.d.ts +2 -0
  93. package/dist/components/auto-release.js +1 -0
  94. package/dist/components/capability.d.ts +40 -0
  95. package/dist/components/cli-support.d.ts +21 -1
  96. package/dist/components/cli-support.js +28 -6
  97. package/dist/components/component.d.ts +23 -4
  98. package/dist/components/component.schema.json +28 -0
  99. package/dist/components/declared-reads.d.ts +44 -4
  100. package/dist/components/declared-reads.js +80 -3
  101. package/dist/components/discover.d.ts +8 -0
  102. package/dist/components/discover.js +1 -1
  103. package/dist/components/driver.d.ts +13 -0
  104. package/dist/components/driver.js +23 -2
  105. package/dist/components/environment-sets.d.ts +229 -0
  106. package/dist/components/environment-sets.js +338 -0
  107. package/dist/components/fan-out-canary.d.ts +47 -0
  108. package/dist/components/fan-out-canary.js +58 -0
  109. package/dist/components/fan-out-run.d.ts +17 -0
  110. package/dist/components/fan-out-run.js +14 -1
  111. package/dist/components/fan-out-support.d.ts +7 -0
  112. package/dist/components/fan-out-support.js +1 -1
  113. package/dist/components/groups.d.ts +8 -1
  114. package/dist/components/groups.js +19 -1
  115. package/dist/components/index.d.ts +5 -2
  116. package/dist/components/index.js +4 -1
  117. package/dist/components/pr-cost.d.ts +28 -0
  118. package/dist/components/pr-cost.js +53 -0
  119. package/dist/components/pr-pipeline.d.ts +33 -0
  120. package/dist/components/pr-pipeline.js +32 -5
  121. package/dist/components/pr-policy.d.ts +33 -2
  122. package/dist/components/pr-policy.js +5 -2
  123. package/dist/components/pr-risk.d.ts +42 -0
  124. package/dist/components/pr-risk.js +74 -0
  125. package/dist/components/product-pipeline.d.ts +43 -0
  126. package/dist/components/product-pipeline.js +67 -1
  127. package/dist/components/promote.d.ts +6 -0
  128. package/dist/components/promote.js +13 -0
  129. package/dist/components/release-compile.js +3 -1
  130. package/dist/components/release-gate.d.ts +6 -1
  131. package/dist/components/release-gate.js +10 -2
  132. package/dist/components/step-environments.d.ts +236 -0
  133. package/dist/components/step-environments.js +392 -0
  134. package/dist/components/upstream-replan.d.ts +201 -0
  135. package/dist/components/upstream-replan.js +249 -0
  136. package/dist/components/verify-step.d.ts +30 -0
  137. package/dist/components/verify-step.js +27 -0
  138. package/dist/components/wave-plan.js +6 -2
  139. package/dist/config-environments.d.ts +4 -2
  140. package/dist/control/dispatch.d.ts +15 -0
  141. package/dist/control/dispatch.js +28 -4
  142. package/dist/cost-estimate.d.ts +188 -0
  143. package/dist/cost-estimate.js +363 -0
  144. package/dist/drift-record.d.ts +36 -0
  145. package/dist/drift-record.js +44 -0
  146. package/dist/engine-facts.d.ts +105 -0
  147. package/dist/engine-facts.js +111 -0
  148. package/dist/exit-codes.d.ts +4 -3
  149. package/dist/exit-codes.js +4 -3
  150. package/dist/flag-params.d.ts +2 -2
  151. package/dist/flag-params.js +9 -4
  152. package/dist/floor-table.data.js +53 -0
  153. package/dist/forge-token-vars.d.ts +12 -0
  154. package/dist/forge-token-vars.js +25 -0
  155. package/dist/gate-decision.d.ts +3 -1
  156. package/dist/gate-decision.js +3 -1
  157. package/dist/gated-waves.d.ts +2 -0
  158. package/dist/gated-waves.js +1 -0
  159. package/dist/graph-ir.d.ts +30 -0
  160. package/dist/graph-ir.js +33 -1
  161. package/dist/graph-refs.d.ts +26 -0
  162. package/dist/graph-refs.js +34 -3
  163. package/dist/graph-schema/graph.schema.json +136 -0
  164. package/dist/health.d.ts +65 -0
  165. package/dist/health.js +62 -0
  166. package/dist/lexicon.d.ts +188 -1
  167. package/dist/lifecycle/disruption.d.ts +14 -1
  168. package/dist/lifecycle/disruption.js +5 -1
  169. package/dist/lifecycle/gate-change-set.d.ts +8 -0
  170. package/dist/lifecycle/gate-change-set.js +2 -1
  171. package/dist/lifecycle/gate-ledger.d.ts +26 -0
  172. package/dist/lifecycle/gate-rejection.d.ts +82 -0
  173. package/dist/lifecycle/gate-rejection.js +93 -0
  174. package/dist/lifecycle/gate-seal.d.ts +3 -3
  175. package/dist/lifecycle/gate-seal.js +5 -5
  176. package/dist/lifecycle/observe.d.ts +17 -0
  177. package/dist/lifecycle/observe.js +10 -1
  178. package/dist/lifecycle/release-cut.js +4 -0
  179. package/dist/lifecycle/release-ledger.d.ts +8 -0
  180. package/dist/lifecycle/release-risk.d.ts +137 -0
  181. package/dist/lifecycle/release-risk.js +214 -0
  182. package/dist/lifecycle/release-store.d.ts +9 -0
  183. package/dist/lifecycle/release-store.js +4 -0
  184. package/dist/lifecycle/stage-log.d.ts +85 -0
  185. package/dist/lifecycle/stage-log.js +141 -0
  186. package/dist/lint/canary-checks.d.ts +31 -0
  187. package/dist/lint/canary-checks.js +45 -0
  188. package/dist/lint/rule.d.ts +1 -0
  189. package/dist/lint/rules/evl012-pipeline-fold.d.ts +14 -0
  190. package/dist/lint/rules/evl012-pipeline-fold.js +30 -0
  191. package/dist/lint/rules/index.d.ts +1 -0
  192. package/dist/lint/rules/index.js +3 -0
  193. package/dist/notify-relay-repo.d.ts +54 -0
  194. package/dist/notify-relay-repo.js +84 -0
  195. package/dist/notify-relay.d.ts +53 -3
  196. package/dist/notify-relay.js +96 -3
  197. package/dist/notify.d.ts +57 -1
  198. package/dist/notify.js +7 -1
  199. package/dist/notify.schema.json +61 -3
  200. package/dist/observation.d.ts +34 -0
  201. package/dist/observation.js +14 -1
  202. package/dist/op/activities/review-agent.d.ts +39 -2
  203. package/dist/op/activities/review-agent.js +88 -5
  204. package/dist/op/agent-permit.d.ts +88 -0
  205. package/dist/op/agent-permit.js +97 -0
  206. package/dist/op/gate-approval-base.d.ts +8 -0
  207. package/dist/op/gate-approval-base.js +9 -0
  208. package/dist/op/gate-approval.d.ts +30 -1
  209. package/dist/op/gate-approval.js +23 -2
  210. package/dist/op/gate-quorum.d.ts +114 -8
  211. package/dist/op/gate-quorum.js +198 -21
  212. package/dist/op/gate-reject.d.ts +79 -0
  213. package/dist/op/gate-reject.js +96 -0
  214. package/dist/op/gate-summary.js +1 -1
  215. package/dist/op/gate.d.ts +28 -3
  216. package/dist/op/gate.js +55 -13
  217. package/dist/op/generate-pipeline.d.ts +15 -1
  218. package/dist/op/generate-pipeline.js +32 -5
  219. package/dist/op/index.d.ts +11 -6
  220. package/dist/op/index.js +10 -5
  221. package/dist/op/local-executor.d.ts +2 -0
  222. package/dist/op/local-executor.js +23 -4
  223. package/dist/op/op-waves-after-plan.d.ts +23 -0
  224. package/dist/op/op-waves-after-plan.js +12 -1
  225. package/dist/op/op-waves-capability-spec.d.ts +14 -0
  226. package/dist/op/op-waves-capability-spec.js +46 -6
  227. package/dist/op/op-waves-capability.d.ts +21 -13
  228. package/dist/op/op-waves-capability.js +22 -59
  229. package/dist/op/op-waves-environment-sets.d.ts +41 -0
  230. package/dist/op/op-waves-environment-sets.js +82 -0
  231. package/dist/op/op-waves-quorum-warnings.d.ts +53 -0
  232. package/dist/op/op-waves-quorum-warnings.js +90 -0
  233. package/dist/op/op-waves-release-port.d.ts +7 -0
  234. package/dist/op/op-waves-release-port.js +15 -3
  235. package/dist/op/op-waves-release.d.ts +15 -0
  236. package/dist/op/op-waves-release.js +15 -0
  237. package/dist/op/op-waves-run.d.ts +37 -3
  238. package/dist/op/op-waves-run.js +141 -18
  239. package/dist/op/op-waves-soak.d.ts +57 -0
  240. package/dist/op/op-waves-soak.js +111 -0
  241. package/dist/op/op-waves-split.d.ts +4 -0
  242. package/dist/op/op-waves-split.js +4 -0
  243. package/dist/op/op-waves.d.ts +67 -4
  244. package/dist/op/op-waves.js +71 -3
  245. package/dist/pipeline/agent-ajv.d.ts +4 -0
  246. package/dist/pipeline/agent-ajv.js +14 -0
  247. package/dist/pipeline/agent-steps.d.ts +329 -0
  248. package/dist/pipeline/agent-steps.js +602 -0
  249. package/dist/pipeline/artifacts.d.ts +264 -0
  250. package/dist/pipeline/artifacts.js +425 -0
  251. package/dist/pipeline/diff.d.ts +45 -0
  252. package/dist/pipeline/diff.js +177 -0
  253. package/dist/pipeline/fold.d.ts +43 -0
  254. package/dist/pipeline/fold.js +140 -0
  255. package/dist/pipeline/generate.d.ts +52 -0
  256. package/dist/pipeline/generate.js +120 -0
  257. package/dist/pipeline/product.d.ts +225 -0
  258. package/dist/pipeline/product.js +257 -0
  259. package/dist/pipeline/promote.d.ts +404 -0
  260. package/dist/pipeline/promote.js +694 -0
  261. package/dist/pipeline/read.d.ts +37 -0
  262. package/dist/pipeline/read.js +58 -0
  263. package/dist/pipeline/rendered.d.ts +25 -0
  264. package/dist/pipeline/rendered.js +53 -0
  265. package/dist/pipeline/soak-checks.d.ts +80 -0
  266. package/dist/pipeline/soak-checks.js +254 -0
  267. package/dist/pipeline/soak-gate.d.ts +97 -0
  268. package/dist/pipeline/soak-gate.js +176 -0
  269. package/dist/pipeline/soak-sources.d.ts +17 -0
  270. package/dist/pipeline/soak-sources.js +42 -0
  271. package/dist/pipeline/soak.d.ts +260 -0
  272. package/dist/pipeline/soak.js +378 -0
  273. package/dist/pipeline/spec.d.ts +724 -0
  274. package/dist/pipeline/spec.js +567 -0
  275. package/dist/pipeline/stage-ledger.d.ts +187 -0
  276. package/dist/pipeline/stage-ledger.js +185 -0
  277. package/dist/pipeline/stage-waves.d.ts +114 -0
  278. package/dist/pipeline/stage-waves.js +161 -0
  279. package/dist/pipeline/stages.d.ts +64 -0
  280. package/dist/pipeline/stages.js +174 -0
  281. package/dist/pipeline/verify-rollback.d.ts +277 -0
  282. package/dist/pipeline/verify-rollback.js +393 -0
  283. package/dist/pipeline.d.ts +142 -0
  284. package/dist/pipeline.js +143 -0
  285. package/dist/pr-loop.d.ts +22 -0
  286. package/dist/pr-loop.js +8 -0
  287. package/dist/pr-plan-note.d.ts +15 -1
  288. package/dist/pr-plan-note.js +8 -0
  289. package/dist/pr-post.d.ts +31 -0
  290. package/dist/pr-post.js +89 -0
  291. package/dist/release-floors.d.ts +1 -1
  292. package/dist/release-floors.js +1 -1
  293. package/dist/report-store/audit.schema.json +50 -0
  294. package/dist/report-store/dora.schema.json +331 -0
  295. package/dist/report-store/estate.schema.json +96 -0
  296. package/dist/report-store/run.schema.json +14 -0
  297. package/dist/report-store.d.ts +151 -0
  298. package/dist/report-store.js +344 -0
  299. package/dist/run-event.d.ts +7 -2
  300. package/dist/wave-runtime.mjs +458 -404
  301. package/dist/workspace/catalog-edges.js +3 -3
  302. package/dist/workspace/change-set.schema.json +4 -0
  303. package/dist/workspace/ci-cloud-identity.d.ts +4 -0
  304. package/dist/workspace/ci-cloud-identity.js +30 -0
  305. package/dist/workspace/ci-run.js +17 -2
  306. package/dist/workspace/ci-secrets.d.ts +3 -1
  307. package/dist/workspace/ci-secrets.js +7 -1
  308. package/dist/workspace/compose-graph.d.ts +1 -1
  309. package/dist/workspace/compose-graph.js +3 -1
  310. package/dist/workspace/declaration.d.ts +27 -0
  311. package/dist/workspace/declaration.js +35 -0
  312. package/dist/workspace/declaration.schema.json +56 -0
  313. package/dist/workspace/graph-cli.js +26 -0
  314. package/dist/workspace/graph.schema.json +5 -1
  315. package/dist/workspace/identity-gate-rule.d.ts +4 -0
  316. package/dist/workspace/identity-gate-rule.js +2 -2
  317. package/dist/workspace/identity-reject-rule.d.ts +14 -0
  318. package/dist/workspace/identity-reject-rule.js +24 -0
  319. package/dist/workspace/identity.d.ts +3 -0
  320. package/dist/workspace/identity.js +2 -1
  321. package/dist/workspace/nested-graph.js +2 -0
  322. package/dist/workspace/pr-report.schema.json +65 -0
  323. package/dist/workspace/promotion-order.d.ts +19 -4
  324. package/dist/workspace/promotion-order.js +26 -4
  325. package/dist/workspace/release-train.d.ts +14 -0
  326. package/dist/workspace/release-train.js +32 -0
  327. package/dist/workspace/run-event.schema.json +2 -2
  328. package/dist/workspace/stack-read-edges.d.ts +19 -0
  329. package/dist/workspace/stack-read-edges.js +54 -0
  330. package/dist/workspace/status-gates.d.ts +51 -1
  331. package/dist/workspace/status-gates.js +60 -0
  332. package/dist/workspace/status-stages.d.ts +223 -0
  333. package/dist/workspace/status-stages.js +279 -0
  334. package/dist/workspace/status.d.ts +45 -1
  335. package/dist/workspace/status.js +109 -5
  336. package/dist/workspace/status.schema.json +283 -2
  337. package/dist/workspace/train-cut.js +5 -2
  338. package/dist/workspace/train-shell.d.ts +18 -0
  339. package/dist/workspace/train-shell.js +43 -0
  340. package/dist/workspace/trust/seal.d.ts +7 -0
  341. package/dist/workspace/trust/seal.js +9 -0
  342. package/package.json +5 -1
package/dist/ci-agent.js CHANGED
@@ -5,11 +5,26 @@
5
5
  * moved here, so terragucci and plywood generate the same jobs in their own
6
6
  * words.
7
7
  *
8
- * Two triggers. `comment`: `/<product> agent <ask>` on a pull request
8
+ * Six triggers. `comment`: `/<product> agent <ask>` on a pull request
9
9
  * (`parseProductComment`), answered with a commit pushed to the pull
10
10
  * request's branch. `drift`: a scheduled Op whose run exits with chant's
11
11
  * `drift` code, answered with a pull request from the agent's own branch,
12
- * opened the first time and updated after.
12
+ * opened the first time and updated after. `alert` (#5329): a production
13
+ * alert the relay recorded as a signed fact (`./agent-facts.ts`,
14
+ * `./ci-agent-alert.ts`), answered the way drift is, from a branch per
15
+ * member. `apply-failed` and `schedule` (#5357): a failed apply's fact and
16
+ * the agent's own cron, on the same intake as alerts
17
+ * (`./ci-agent-triggers.ts`), answered the same way. `verify-failed`
18
+ * (#5339): a failed verify step or a failing soak check, which chant
19
+ * records itself as a signed fact (`./ci-agent-verify-failed.ts`),
20
+ * answered the same way.
21
+ *
22
+ * Every trigger reads the agent's settings and caps from the default
23
+ * branch (#5357): the generated command lines carry a digest of the
24
+ * settings (`--digest`), the variables must match it, and the job's commit
25
+ * must be on the default branch ({@link checkAgentBase}). A pull request
26
+ * that changes the agent's workflow, or a pipeline variable that names
27
+ * another cap, does not change the agent that runs.
13
28
  *
14
29
  * Two jobs, so the model never shares a job with a token that can write:
15
30
  *
@@ -40,9 +55,30 @@ import { CHANT_EXIT } from "./exit-codes.js";
40
55
  import { COMMENT_ALLOW_ENV, commentAllowFromEnv, commentAllowProblems, decideCommentAllow } from "./ci-comment-allow.js";
41
56
  import { parseProductComment } from "./ci-product-words.js";
42
57
  import { quoted } from "./op/activities/review-agent.js";
58
+ import { AGENT_JOIN_WINDOW_MINUTES, pendingAgentFacts, verifyAgentFact } from "./agent-facts.js";
59
+ import { agentAlertPrompt, alertOfData } from "./ci-agent-alert.js";
60
+ import { AGENT_TASK_MAX, agentApplyFailedPrompt, agentSchedulePrompt, applyFailedOfData, isScheduleFactOf, scheduleFact } from "./ci-agent-triggers.js";
61
+ import { agentVerifyFailedPrompt, verifyFailedOfData } from "./ci-agent-verify-failed.js";
62
+ import { sortedJsonReplacer } from "./sorted-json.js";
43
63
  /** The first chant with the agent job and the scheduled Op spec's `agent` and `runner` (#4616). Products feature-detect on it. */
44
64
  export const CI_AGENT_FLOOR = "0.124.55";
45
- export const AGENT_TRIGGERS = ["comment", "drift"];
65
+ export const AGENT_TRIGGERS = ["comment", "drift", "alert", "apply-failed", "schedule", "verify-failed"];
66
+ /** The triggers answered from a branch of the agent's own, with a pull request it opens and updates. */
67
+ export const AGENT_BRANCH_TRIGGERS = ["drift", "alert", "apply-failed", "schedule", "verify-failed"];
68
+ /**
69
+ * The triggers on the facts intake (#5329, #5357, #5339): the agent is a workflow
70
+ * of its own, started by hand or by its schedule, and reads its facts
71
+ * itself; facts for one member close together join one run.
72
+ */
73
+ export const AGENT_FACT_TRIGGERS = ["alert", "apply-failed", "schedule", "verify-failed"];
74
+ /** The fact triggers whose facts are read from the ledger and checked with the relay key. A schedule's fact is the run itself. */
75
+ export const AGENT_SIGNED_TRIGGERS = ["alert", "apply-failed", "verify-failed"];
76
+ /** Whether `on` reads facts: {@link AGENT_FACT_TRIGGERS}. */
77
+ export const isFactTrigger = (on) => AGENT_FACT_TRIGGERS.includes(on);
78
+ /** The variable the alert agent's jobs read the relay key from, to check the facts' signatures. */
79
+ export const AGENT_RELAY_KEY_ENV = "CHANT_RELAY_KEY";
80
+ /** How often the alert agent's workflow runs on its own, to pick up a fact whose start did not arrive. The failed-apply agent's schedule too. */
81
+ export const AGENT_ALERT_SCHEDULE = "*/15 * * * *";
46
82
  /** The Claude Code release the default agent command runs (terragucci's pin, as the review agent's). */
47
83
  export const AGENT_CLAUDE_CODE_VERSION = "2.1.290";
48
84
  /**
@@ -81,6 +117,8 @@ export const AGENT_ENV = {
81
117
  maxTurns: "CHANT_AGENT_MAX_TURNS",
82
118
  guarded: "CHANT_AGENT_GUARDED",
83
119
  branch: "CHANT_AGENT_BRANCH",
120
+ window: "CHANT_AGENT_WINDOW",
121
+ task: "CHANT_AGENT_TASK",
84
122
  env: "CHANT_AGENT_ENV",
85
123
  };
86
124
  /** GitLab starts no pipeline on a note: a pipeline of the target branch started with these runs the comment agent. */
@@ -145,17 +183,24 @@ export function resolveAgentSpec(name, spec, product = "chant") {
145
183
  if (!NAME.test(name))
146
184
  throw new AgentError(`${where}: the name is letters, digits, '.', '_' and '-'`);
147
185
  if (!AGENT_TRIGGERS.includes(spec.on))
148
- throw new AgentError(`${where}: on is "comment" or "drift"`);
186
+ throw new AgentError(`${where}: on is ${AGENT_TRIGGERS.map((t) => `"${t}"`).join(", ")}`);
149
187
  if (spec.on === "comment" && !(typeof spec.comment === "string" && /^\/[a-z][a-z0-9-]* [a-z][a-z0-9-]*$/.test(spec.comment))) {
150
188
  throw new AgentError(`${where}: on "comment" needs comment, the line it answers, such as "/${product} agent"`);
151
189
  }
152
190
  if (spec.command !== undefined && (typeof spec.command !== "string" || spec.command.trim() === ""))
153
191
  throw new AgentError(`${where}: command is a shell line`);
154
- for (const [k, v] of [["keyEnv", spec.keyEnv], ["tokenEnv", spec.tokenEnv]]) {
192
+ for (const [k, v] of [["keyEnv", spec.keyEnv], ["tokenEnv", spec.tokenEnv], ["relayKeyEnv", spec.relayKeyEnv]]) {
155
193
  if (v !== undefined && !VAR.test(v))
156
194
  throw new AgentError(`${where}: ${k} is a variable name`);
157
195
  }
158
- const branch = spec.on === "drift" ? spec.branch ?? `${product}/agent/${name}` : undefined;
196
+ const signed = AGENT_SIGNED_TRIGGERS.includes(spec.on);
197
+ if (signed && [spec.keyEnv ?? AGENT_KEY_ENV].includes(spec.relayKeyEnv ?? AGENT_RELAY_KEY_ENV))
198
+ throw new AgentError(`${where}: keyEnv and relayKeyEnv name the same variable, and the model never holds the relay key`);
199
+ if (spec.on === "schedule" && !(typeof spec.task === "string" && spec.task.trim() !== "" && spec.task.length <= AGENT_TASK_MAX)) {
200
+ throw new AgentError(`${where}: on "schedule" needs task, what the agent does on each run, in at most ${AGENT_TASK_MAX} characters`);
201
+ }
202
+ const branch = AGENT_BRANCH_TRIGGERS.includes(spec.on) ? spec.branch ?? `${product}/agent/${name}` : undefined;
203
+ const facts = isFactTrigger(spec.on);
159
204
  if (branch !== undefined && !branchOk(branch))
160
205
  throw new AgentError(`${where}: branch ${JSON.stringify(branch)} is not a branch name`);
161
206
  const guarded = spec.guarded ?? [];
@@ -185,6 +230,9 @@ export function resolveAgentSpec(name, spec, product = "chant") {
185
230
  maxTurns: spec.maxTurns === undefined ? AGENT_MAX_TURNS : intIn(`${where}: maxTurns`, spec.maxTurns, 1, 500),
186
231
  guarded: [...guarded],
187
232
  ...(branch !== undefined ? { branch } : {}),
233
+ ...(facts ? { window: spec.window === undefined ? AGENT_JOIN_WINDOW_MINUTES : intIn(`${where}: window`, spec.window, 1, 1440) } : {}),
234
+ ...(signed ? { relayKeyEnv: spec.relayKeyEnv ?? AGENT_RELAY_KEY_ENV } : {}),
235
+ ...(spec.on === "schedule" ? { task: spec.task.trim() } : {}),
188
236
  env,
189
237
  ...(spec.commentAllow !== undefined ? { commentAllow: spec.commentAllow } : {}),
190
238
  ...(spec.commentAllowTokenEnv !== undefined ? { commentAllowTokenEnv: spec.commentAllowTokenEnv } : {}),
@@ -204,6 +252,8 @@ export function agentSettingsEnv(s) {
204
252
  [AGENT_ENV.maxTurns]: String(s.maxTurns),
205
253
  ...(s.guarded.length > 0 ? { [AGENT_ENV.guarded]: JSON.stringify(s.guarded) } : {}),
206
254
  ...(s.branch ? { [AGENT_ENV.branch]: s.branch } : {}),
255
+ ...(s.window !== undefined ? { [AGENT_ENV.window]: String(s.window) } : {}),
256
+ ...(s.task !== undefined ? { [AGENT_ENV.task]: s.task } : {}),
207
257
  [AGENT_ENV.env]: s.env,
208
258
  ...(s.commentAllow ? { [COMMENT_ALLOW_ENV]: JSON.stringify(s.commentAllow) } : {}),
209
259
  };
@@ -241,6 +291,7 @@ export function agentSettingsFromEnv(env, product = "chant") {
241
291
  throw new AgentError(`${AGENT_ENV.maxCostUsd} is a number of US dollars: got ${JSON.stringify(usd)}`);
242
292
  const maxCostUsd = usd === undefined || usd === "" ? undefined : Number(usd);
243
293
  const maxTurns = num(AGENT_ENV.maxTurns);
294
+ const window = num(AGENT_ENV.window);
244
295
  const spec = {
245
296
  on: env[AGENT_ENV.on],
246
297
  ...(env[AGENT_ENV.comment] ? { comment: env[AGENT_ENV.comment] } : {}),
@@ -252,6 +303,8 @@ export function agentSettingsFromEnv(env, product = "chant") {
252
303
  ...(maxTurns !== undefined ? { maxTurns } : {}),
253
304
  ...(guarded ? { guarded } : {}),
254
305
  ...(env[AGENT_ENV.branch] ? { branch: env[AGENT_ENV.branch] } : {}),
306
+ ...(window !== undefined ? { window } : {}),
307
+ ...(env[AGENT_ENV.task] ? { task: env[AGENT_ENV.task] } : {}),
255
308
  ...(env[AGENT_ENV.env] ? { env: env[AGENT_ENV.env] } : {}),
256
309
  };
257
310
  let commentAllow;
@@ -265,6 +318,79 @@ export function agentSettingsFromEnv(env, product = "chant") {
265
318
  spec.commentAllow = commentAllow;
266
319
  return resolveAgentSpec(name, spec, product);
267
320
  }
321
+ // ── the settings are the default branch's (#5357) ──────────────────────────
322
+ /**
323
+ * The digest of an agent's settings as its jobs carry them: `sha256:` of
324
+ * {@link agentSettingsEnv}'s variables, keys sorted. The generator writes it
325
+ * on each command line (`--digest`), where a pipeline variable cannot
326
+ * replace it, and the command refuses variables that do not match it.
327
+ */
328
+ export function agentSettingsDigest(s) {
329
+ return digestOf(JSON.stringify(agentSettingsEnv(s), sortedJsonReplacer));
330
+ }
331
+ /** Undefined when the settings read from the variables are the ones the command line's digest names, else why not. */
332
+ export function agentDigestProblem(s, digest) {
333
+ if (digest === undefined)
334
+ return undefined;
335
+ if (!/^sha256:[0-9a-f]{64}$/.test(digest))
336
+ return `--digest ${JSON.stringify(digest)} is not a sha256: digest`;
337
+ return agentSettingsDigest(s) === digest
338
+ ? undefined
339
+ : "the agent's variables are not the settings its workflow on the default branch was generated with (a pipeline variable or a changed workflow names others), so the agent does not run";
340
+ }
341
+ /**
342
+ * The default branch: from the run's event on GitHub and Forgejo, else the
343
+ * `origin/HEAD` the generated checkout noted from the remote, else the
344
+ * remote itself.
345
+ */
346
+ export function agentDefaultBranch(git, env, event) {
347
+ if (env.GITLAB_CI !== "true") {
348
+ const b = event?.repository?.default_branch;
349
+ if (typeof b === "string" && branchOk(b))
350
+ return b;
351
+ }
352
+ try {
353
+ const b = git(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]).trim().replace(/^origin\//, "");
354
+ if (b && branchOk(b))
355
+ return b;
356
+ }
357
+ catch {
358
+ // Not noted: ask the remote.
359
+ }
360
+ try {
361
+ const b = /^ref: refs\/heads\/(\S+)\s+HEAD/m.exec(git(["ls-remote", "--symref", "origin", "HEAD"]))?.[1];
362
+ return b && branchOk(b) ? b : undefined;
363
+ }
364
+ catch {
365
+ return undefined;
366
+ }
367
+ }
368
+ /**
369
+ * Whether the job runs on the default branch (#5357): its commit is the
370
+ * default branch's tip or an earlier commit of it, so the workflow file the
371
+ * job's settings came from is one the default branch held. A run on a pull
372
+ * request's branch, whose workflow the pull request could have changed, is
373
+ * refused.
374
+ */
375
+ export function checkAgentBase(git, env, event) {
376
+ const branch = agentDefaultBranch(git, env, event);
377
+ if (!branch)
378
+ return { ok: false, reason: "the default branch could not be read, so the agent's settings cannot be checked against it" };
379
+ const ref = `refs/remotes/origin/${branch}`;
380
+ try {
381
+ try {
382
+ git(["rev-parse", "--verify", "-q", `${ref}^{commit}`]);
383
+ }
384
+ catch {
385
+ git(["fetch", "-q", "--no-tags", "origin", `+refs/heads/${branch}:${ref}`]);
386
+ }
387
+ git(["merge-base", "--is-ancestor", "HEAD", ref]);
388
+ return { ok: true, branch };
389
+ }
390
+ catch {
391
+ return { ok: false, reason: `the job's commit is not on ${branch}, so its workflow is not the default branch's and the agent does not run` };
392
+ }
393
+ }
268
394
  // ── what an agent may change ───────────────────────────────────────────────
269
395
  /** Directories no agent changes: CI, chant's own state, agent settings. */
270
396
  const GUARDED_DIRS = [".github/", ".forgejo/", ".gitea/", ".gitlab/", ".chant/", ".claude/", ".cursor/"];
@@ -282,7 +408,7 @@ export function agentForbiddenPaths(paths, guarded = []) {
282
408
  });
283
409
  }
284
410
  /** The guarded paths as the prompt names them. */
285
- function guardedSentence(guarded) {
411
+ export function guardedSentence(guarded) {
286
412
  return [".github/", ".forgejo/", ".gitea/", ".gitlab/", ".gitlab-ci.yml", ".chant/", "chant.workspace.json", "chant.config.ts", ...guarded, "CODEOWNERS", "CLAUDE.md, AGENTS.md, .gitattributes or .gitmodules (in any directory)", ".mcp.json", ".claude/", ".cursor/", ".cursorrules"].join(", ");
287
413
  }
288
414
  const PROMPT_TAGS = ["ask", "drift"];
@@ -381,6 +507,12 @@ export function readDecision(dir) {
381
507
  return undefined;
382
508
  if (d.branch !== undefined && !branchOk(d.branch))
383
509
  return undefined;
510
+ if (d.facts !== undefined && !(Array.isArray(d.facts) && d.facts.every((f) => typeof f === "string" && /^sha256:[0-9a-f]{64}$/.test(f))))
511
+ return undefined;
512
+ if (d.member !== undefined && !(d.member === "" || NAME.test(d.member)))
513
+ return undefined;
514
+ if (d.window !== undefined && !(typeof d.window?.from === "string" && typeof d.window?.until === "string"))
515
+ return undefined;
384
516
  return d;
385
517
  }
386
518
  catch {
@@ -499,6 +631,30 @@ export function errText(e) {
499
631
  const err = e;
500
632
  return firstLine(typeof err.stderr === "string" && err.stderr ? err.stderr : err?.message ?? String(e));
501
633
  }
634
+ /** The facts' content for the prompt and the pull request; empty when none of the facts holds what the trigger reads. */
635
+ function factContent(on, facts) {
636
+ if (on === "schedule")
637
+ return { schedule: true };
638
+ if (on === "alert") {
639
+ const alerts = facts.map((f) => alertOfData(f.data)).filter((a) => a !== undefined);
640
+ return alerts.length > 0 ? { alerts } : undefined;
641
+ }
642
+ if (on === "verify-failed") {
643
+ const verifies = facts.map((f) => verifyFailedOfData(f.data)).filter((v) => v !== undefined);
644
+ return verifies.length > 0 ? { verifies } : undefined;
645
+ }
646
+ const failures = facts.map((f) => applyFailedOfData(f.data)).filter((a) => a !== undefined);
647
+ return failures.length > 0 ? { failures } : undefined;
648
+ }
649
+ /** How a trigger names one of its facts in a reason. */
650
+ const factNoun = (on) => (on === "alert" ? "alert" : on === "apply-failed" ? "failed apply" : on === "verify-failed" ? "failed verify" : "scheduled run");
651
+ /** Whether a fact is one the run may take: signed with the relay key, or for a schedule, the fact this run makes. */
652
+ function factCheck(s, env) {
653
+ if (s.on === "schedule")
654
+ return (f) => isScheduleFactOf(f, s.name, env);
655
+ const key = env[AGENT_RELAY_KEY_ENV];
656
+ return (f) => f.trigger === s.on && verifyAgentFact(key, f);
657
+ }
502
658
  /**
503
659
  * `chant agent prepare`: decide whether the agent runs, and on what. Every
504
660
  * outcome is a decision file; a refusal is answered by the push job, which
@@ -535,16 +691,68 @@ export async function prepareAgentRun(i) {
535
691
  }
536
692
  }
537
693
  let records = [];
694
+ let runsUnread;
538
695
  try {
539
696
  records = await i.readRuns();
540
697
  }
541
698
  catch (e) {
542
- if (agentHasLimit(i.settings))
543
- return no(`the agent's runs could not be read from the ledger (${errText(e)}), so its limit cannot be checked`, ask ? { pr: ask.pr, user: ask.user } : {});
699
+ runsUnread = errText(e);
544
700
  }
701
+ // #5329, #5357: the oldest group of new facts, read and checked here; nothing the run was started with is read.
702
+ let alert;
703
+ if (isFactTrigger(i.settings.on)) {
704
+ const noun = factNoun(i.settings.on);
705
+ // Which facts are spent is on the run records, so they are read before anything else.
706
+ if (runsUnread !== undefined)
707
+ return no(`the agent's runs could not be read from the ledger (${runsUnread}), so the ${noun}s already answered are not known`);
708
+ let facts;
709
+ if (i.settings.on === "schedule") {
710
+ facts = [scheduleFact({ name: i.settings.name, env: i.env, now: i.now })];
711
+ }
712
+ else {
713
+ try {
714
+ facts = (await i.readFacts?.()) ?? [];
715
+ }
716
+ catch (e) {
717
+ return no(`the ${noun} facts could not be read from the ledger (${errText(e)})`);
718
+ }
719
+ if (!i.env[AGENT_RELAY_KEY_ENV])
720
+ return no(`${AGENT_RELAY_KEY_ENV} is not set, so no ${noun} fact can be checked`);
721
+ }
722
+ const pending = pendingAgentFacts({ facts, runs: records, relayKey: i.env[AGENT_RELAY_KEY_ENV], verify: factCheck(i.settings, i.env), now: i.now, windowMs: (i.settings.window ?? AGENT_JOIN_WINDOW_MINUTES) * 60000 });
723
+ const unsigned = pending.setAside.filter((s) => s.reason === "unsigned").length;
724
+ if (unsigned > 0)
725
+ console.error(`${i.words.product} agent: ${unsigned} ${noun} fact${unsigned === 1 ? " is" : "s are"} not signed with the relay key and start nothing`);
726
+ const group = pending.groups[0];
727
+ if (!group) {
728
+ const joined = pending.setAside.some((s) => s.reason === "joined" || s.reason === "taken");
729
+ return write({ ...base, go: false, idle: true, reason: i.settings.on === "schedule" && joined ? "a run of this schedule inside the join window answered already" : `no new ${noun}` });
730
+ }
731
+ alert = { group, content: factContent(i.settings.on, group.facts) };
732
+ }
733
+ const took = alert ? { facts: alert.group.facts.map((f) => f.id), member: alert.group.member, window: alert.group.window } : {};
734
+ if (runsUnread !== undefined && agentHasLimit(i.settings))
735
+ return no(`the agent's runs could not be read from the ledger (${runsUnread}), so its limit cannot be checked`, ask ? { pr: ask.pr, user: ask.user } : {});
545
736
  const over = overLimit(i.settings, records, i.now);
546
737
  if (over)
547
- return no(over, { stop: "stopped", ...(ask ? { pr: ask.pr, user: ask.user } : {}) });
738
+ return no(over, { stop: "stopped", ...(ask ? { pr: ask.pr, user: ask.user } : {}), ...took });
739
+ if (alert) {
740
+ const sha = i.git(["rev-parse", "HEAD"]).trim();
741
+ const c = alert.content;
742
+ if (!c)
743
+ return no(`the new ${factNoun(i.settings.on)} facts hold nothing the agent reads`, took);
744
+ const d = write({ ...base, go: true, sha, ...took });
745
+ const common = { product: i.words.product, name: i.settings.name, sha, guardedSentence: guardedSentence(i.settings.guarded) };
746
+ const prompt = "alerts" in c
747
+ ? agentAlertPrompt({ ...common, member: alert.group.member, alerts: c.alerts })
748
+ : "failures" in c
749
+ ? agentApplyFailedPrompt({ ...common, member: alert.group.member, failures: c.failures })
750
+ : "verifies" in c
751
+ ? agentVerifyFailedPrompt({ ...common, member: alert.group.member, failures: c.verifies })
752
+ : agentSchedulePrompt({ ...common, task: i.settings.task ?? "" });
753
+ writeFileSync(join(i.dir, AGENT_PROMPT_FILE), prompt);
754
+ return d;
755
+ }
548
756
  if (ask) {
549
757
  const who = { pr: ask.pr, user: ask.user };
550
758
  let fetched;
@@ -621,7 +829,7 @@ export async function runAgent(i) {
621
829
  * {@link AGENT_TRIGGERS}, a product's own word (#4817), is recorded as given.
622
830
  */
623
831
  export function agentRunRecordInput(o) {
624
- const ok = o.result === "pushed" || o.result === "opened" || o.result === "updated";
832
+ const ok = o.result === "pushed" || o.result === "opened" || o.result === "updated" || o.result === "summarized" || o.result === "answered";
625
833
  const durationMs = Math.max(0, Date.parse(o.ended) - Date.parse(o.started)) || 0;
626
834
  const outcome = {
627
835
  trigger: o.settings.on,
@@ -633,6 +841,12 @@ export function agentRunRecordInput(o) {
633
841
  ...(o.pullRequest ? { pullRequest: o.pullRequest } : {}),
634
842
  ...(o.promptDigest ? { promptDigest: o.promptDigest } : {}),
635
843
  ...(o.usage && Object.keys(o.usage).length > 0 ? { usage: o.usage } : {}),
844
+ ...(o.facts ? { facts: o.facts } : {}),
845
+ ...(o.member !== undefined ? { member: o.member } : {}),
846
+ ...(o.window ? { window: o.window } : {}),
847
+ ...(o.alerts ? { alerts: o.alerts } : {}),
848
+ ...(o.failures ? { failures: o.failures } : {}),
849
+ ...(o.verifies ? { verifies: o.verifies } : {}),
636
850
  };
637
851
  return {
638
852
  op: o.settings.name,
@@ -669,6 +883,13 @@ export async function landAgentChange(i) {
669
883
  let user;
670
884
  let ask;
671
885
  let commitSha;
886
+ // #5329, #5357: the facts this run answers, once this job has checked them against the ledger.
887
+ let took;
888
+ let alerts = [];
889
+ let failures = [];
890
+ let verifies = [];
891
+ const factual = isFactTrigger(s.on);
892
+ const noun = factNoun(s.on);
672
893
  const say = async (text) => {
673
894
  if (pr === undefined)
674
895
  return;
@@ -699,6 +920,7 @@ export async function landAgentChange(i) {
699
920
  usage,
700
921
  ...(commitSha ? { gitSha: commitSha } : {}),
701
922
  ...(i.runOrigin ? { runOrigin: i.runOrigin } : {}),
923
+ ...(took ? { facts: took.facts, member: took.member, ...(took.window ? { window: took.window } : {}), ...(took.alerts ? { alerts: took.alerts } : {}), ...(took.failures ? { failures: took.failures } : {}), ...(took.verifies ? { verifies: took.verifies } : {}) } : {}),
702
924
  }));
703
925
  }
704
926
  catch (e) {
@@ -718,6 +940,48 @@ export async function landAgentChange(i) {
718
940
  const decision = readDecision(i.dir);
719
941
  if (!decision || decision.name !== s.name || decision.on !== s.on)
720
942
  return finish({ result: "failed", reason: "the agent job left no decision this job can read" }, "the agent job left nothing to land, so nothing was pushed.");
943
+ // #5329: no new fact, so nothing ran and nothing is recorded: the scheduled run says so every few minutes.
944
+ if (factual && decision.idle && !decision.go)
945
+ return { result: "idle", reason: decision.reason ?? `no new ${noun}`, code: CHANT_EXIT.done };
946
+ if (factual && decision.facts) {
947
+ // The decision is the agent job's data: each fact it names must be on the ledger signed with the relay key (or be this
948
+ // scheduled run's own), and taken by no run yet.
949
+ let onLedger;
950
+ let runs;
951
+ try {
952
+ onLedger = s.on === "schedule" ? [scheduleFact({ name: s.name, env: i.env, now: new Date(started) })] : ((await i.readFacts?.()) ?? []);
953
+ runs = await i.readRuns();
954
+ }
955
+ catch (e) {
956
+ return finish({ result: "failed", reason: `could not read the ${noun} facts or the runs (${errText(e)})` });
957
+ }
958
+ const check = factCheck(s, i.env);
959
+ const named = decision.facts.map((id) => onLedger.find((f) => f.id === id));
960
+ if (decision.facts.length === 0 || named.some((f) => !f || !check(f) || f.member !== (decision.member ?? ""))) {
961
+ return finish({ result: "refused", reason: s.on === "schedule" ? "the decision names a fact that is not this scheduled run" : `the decision names a ${noun} fact the ledger does not hold signed with the relay key` });
962
+ }
963
+ const spent = new Set(runs.flatMap((r) => r.outcomes?.agent?.facts).filter((x) => typeof x === "string"));
964
+ if (decision.facts.some((id) => spent.has(id)))
965
+ return finish({ result: "refused", reason: `another run took these ${noun}s` });
966
+ const facts = named;
967
+ const c = factContent(s.on, facts);
968
+ alerts = c && "alerts" in c ? c.alerts : [];
969
+ failures = c && "failures" in c ? c.failures : [];
970
+ verifies = c && "verifies" in c ? c.verifies : [];
971
+ took = {
972
+ facts: decision.facts,
973
+ member: decision.member ?? "",
974
+ ...(decision.window ? { window: decision.window } : {}),
975
+ ...(s.on === "alert" ? { alerts: alerts.map((a) => ({ source: a.source, sourceId: a.sourceId })) } : {}),
976
+ ...(s.on === "apply-failed" ? { failures: failures.map((f) => ({ op: f.op, member: f.member })) } : {}),
977
+ // #5339: the stage that failed, and what failed there.
978
+ ...(s.on === "verify-failed" ? { verifies: verifies.map((v) => ({ stage: v.stage, kind: v.kind, check: v.check, member: v.member })) } : {}),
979
+ };
980
+ }
981
+ else if (factual) {
982
+ // A run that took no fact answers nothing; it fails the job, so the reason shows, and is not recorded, so it spends no run of the limit.
983
+ return { result: "failed", reason: decision.go ? `the decision names no ${noun} fact` : decision.reason ?? "the agent did not run", code: CHANT_EXIT.failed };
984
+ }
721
985
  if (!decision.go) {
722
986
  const stopped = decision.stop === "stopped";
723
987
  return finish({ result: stopped ? "stopped" : "refused", reason: decision.reason ?? "refused" }, `${decision.reason ?? "the agent did not run"}, so nothing was pushed.`);
@@ -747,9 +1011,11 @@ export async function landAgentChange(i) {
747
1011
  }
748
1012
  else {
749
1013
  sha = i.git(["rev-parse", "HEAD"]).trim();
750
- branch = s.branch;
1014
+ branch = took?.member ? `${s.branch}-${took.member}` : s.branch;
1015
+ if (!branchOk(branch))
1016
+ return finish({ result: "refused", reason: `${branch} is not a branch the agent pushes to` });
751
1017
  if (sha !== decision.sha)
752
- return finish({ result: "refused", reason: "the checkout is not the drift check's commit" }, undefined);
1018
+ return finish({ result: "refused", reason: factual ? "the checkout is not the commit the agent worked on" : "the checkout is not the drift check's commit" }, undefined);
753
1019
  }
754
1020
  }
755
1021
  catch (e) {
@@ -774,9 +1040,41 @@ export async function landAgentChange(i) {
774
1040
  if (forbidden.length > 0) {
775
1041
  return finish({ result: "refused", reason: `the change touches ${forbidden.join(", ")}`, paths }, `the agent's change touches ${forbidden.map(code).join(", ")}, which an agent may not change (CI, chant's settings and state, ${s.guarded.length ? `${s.guarded.map(code).join(", ")}, ` : ""}code owners, agent instructions and git settings), so nothing was pushed.`);
776
1042
  }
777
- const title = s.on === "comment" ? `Change asked for by ${user} on ${what} #${pr}` : `Bring the code in line with the drift ${s.name} found`;
1043
+ const alertTitle = () => {
1044
+ const first = alerts[0]?.title.replace(/[\r\n]+/g, " ").slice(0, 120) ?? "a production alert";
1045
+ return `Answer ${alerts.length > 1 ? `${alerts.length} alerts` : "the alert"}${took?.member ? ` for ${took.member}` : ""}: ${first}`;
1046
+ };
1047
+ const failedTitle = () => `Fix the failed apply${took?.member ? ` of ${took.member}` : ""}: ${(failures[0]?.label ?? "an apply").replace(/[\r\n]+/g, " ").slice(0, 120)}`;
1048
+ const verifyTitle = () => {
1049
+ const stages = [...new Set(verifies.map((v) => v.stage))].join(", ") || "a stage";
1050
+ const what = verifies.every((v) => v.kind === "soak") ? "soak" : verifies.every((v) => v.kind === "verify") ? "verify" : "verify and soak";
1051
+ return `Fix the failed ${what} in ${stages}${took?.member ? ` for ${took.member}` : ""}: ${(verifies[0]?.check ?? "a check").replace(/[\r\n]+/g, " ").slice(0, 120)}`.slice(0, 250);
1052
+ };
1053
+ const firstLineOfTask = (s.task ?? "").split("\n")[0].slice(0, 100);
1054
+ const title = s.on === "comment"
1055
+ ? `Change asked for by ${user} on ${what} #${pr}`
1056
+ : s.on === "alert"
1057
+ ? alertTitle()
1058
+ : s.on === "apply-failed"
1059
+ ? failedTitle()
1060
+ : s.on === "verify-failed"
1061
+ ? verifyTitle()
1062
+ : s.on === "schedule"
1063
+ ? `Scheduled task of ${s.name}: ${firstLineOfTask}`
1064
+ : `Bring the code in line with the drift ${s.name} found`;
778
1065
  const trailers = [...(user ? [`Requested-by: ${user}`] : []), `Agent-run: ${s.name}`];
779
- const message = [title, "", ...(ask ? [ask, ""] : s.on === "drift" ? [`Written by the agent from the drift found at ${sha.slice(0, 12)}.`, ""] : []), ...trailers, ""].join("\n");
1066
+ const fromWhat = s.on === "drift"
1067
+ ? [`Written by the agent from the drift found at ${sha.slice(0, 12)}.`, ""]
1068
+ : s.on === "alert"
1069
+ ? [`Written by the agent from ${alerts.map((a) => `${a.source} alert ${a.sourceId}`).join(", ")}.`, ""]
1070
+ : s.on === "apply-failed"
1071
+ ? [`Written by the agent from the failed apply of ${failures.map((f) => f.member || f.op).join(", ")}.`, ""]
1072
+ : s.on === "verify-failed"
1073
+ ? [`Written by the agent from the failed ${verifies.map((v) => `${v.kind} ${v.check} in ${v.stage}`).join(", ")}.`.replace(/[\r\n]+/g, " "), ""]
1074
+ : s.on === "schedule"
1075
+ ? [`Written by the agent on its schedule.`, ""]
1076
+ : [];
1077
+ const message = [title, "", ...(ask ? [ask, ""] : fromWhat), ...trailers, ""].join("\n");
780
1078
  try {
781
1079
  i.git(["-c", `user.name=${AGENT_GIT_NAME}`, "-c", `user.email=${AGENT_GIT_EMAIL}`, "-c", "commit.gpgsign=false", "commit", "-q", "-F", "-"], { cwd: i.workDir, input: message });
782
1080
  commitSha = i.git(["rev-parse", "HEAD"], { cwd: i.workDir }).trim();
@@ -812,19 +1110,44 @@ export async function landAgentChange(i) {
812
1110
  catch (e) {
813
1111
  return finish({ result: "failed", reason: `could not push to ${branch} (${errText(e)})`, commit: commitSha });
814
1112
  }
815
- const body = [
816
- `The agent changed the code to describe what is live, from the drift ${code(s.name)} found at ${code(sha.slice(0, 12))}.`,
817
- "",
818
- `It changes ${paths.map(code).join(", ")}. A person reviews it: merging keeps the change made outside the code, and the merge's apply goes through the gate like any other. Close it to undo the drift by applying the code as it is instead.`,
819
- "",
820
- "Nothing was applied, approved or merged.",
821
- ].join("\n");
1113
+ const fromFacts = (lead, items, what) => [lead, "", ...items, "", `It changes ${paths.map(code).join(", ")}. A person reviews it, and the merge's apply goes through the gate like any other. Close it to ${what}.`, "", "Nothing was applied, approved or merged."].join("\n");
1114
+ const body = s.on === "apply-failed"
1115
+ ? fromFacts(`The agent ${code(s.name)} changed the code at ${code(sha.slice(0, 12))} in answer to ${failures.length === 1 ? "this failed apply" : "these failed applies"}:`, failures.map((f) => `- ${f.label}${f.member ? `, ${code(f.member)}` : ""}${f.runUrl && /^https:\/\/\S+$/.test(f.runUrl) ? `, ${f.runUrl}` : ""}`), "leave the code as it is")
1116
+ : s.on === "verify-failed"
1117
+ ? [
1118
+ `The agent ${code(s.name)} changed the code at ${code(sha.slice(0, 12))} in answer to ${verifies.length === 1 ? "this failure" : "these failures"} after an apply:`,
1119
+ "",
1120
+ ...verifies.map((v) => `- ${v.label.replace(/[\r\n]+/g, " ")}: ${v.kind} ${code(v.check)}${v.member ? `, ${code(v.member)}` : ""}${v.runUrl && /^https:\/\/\S+$/.test(v.runUrl) ? `, ${v.runUrl}` : ""}`),
1121
+ "",
1122
+ `It changes ${paths.map(code).join(", ")}. A person reviews it, and the merge's apply goes through the gate like any other, as a new release. A rollback the stage requested stands and is decided at the stage's gate; this pull request does not replace it. Close it to leave the code as it is.`,
1123
+ "",
1124
+ "Nothing was applied, approved, merged or rolled back.",
1125
+ ].join("\n")
1126
+ : s.on === "schedule"
1127
+ ? fromFacts(`The agent ${code(s.name)} changed the code at ${code(sha.slice(0, 12))} on its schedule, for its task:`, (s.task ?? "").split("\n").map((l) => `> ${l}`), "leave the code as it is")
1128
+ : s.on === "alert"
1129
+ ? [
1130
+ `The agent ${code(s.name)} changed the code at ${code(sha.slice(0, 12))} in answer to ${alerts.length === 1 ? "this alert" : "these alerts"}:`,
1131
+ "",
1132
+ ...alerts.map((a) => `- ${a.source} ${code(a.sourceId)}${a.url && /^https:\/\/\S+$/.test(a.url) ? `, ${a.url}` : ""}`),
1133
+ "",
1134
+ `It changes ${paths.map(code).join(", ")}. A person reviews it, and the merge's apply goes through the gate like any other. Close it to leave the code as it is.`,
1135
+ "",
1136
+ "Nothing was applied, approved or merged.",
1137
+ ].join("\n")
1138
+ : [
1139
+ `The agent changed the code to describe what is live, from the drift ${code(s.name)} found at ${code(sha.slice(0, 12))}.`,
1140
+ "",
1141
+ `It changes ${paths.map(code).join(", ")}. A person reviews it: merging keeps the change made outside the code, and the merge's apply goes through the gate like any other. Close it to undo the drift by applying the code as it is instead.`,
1142
+ "",
1143
+ "Nothing was applied, approved or merged.",
1144
+ ].join("\n");
822
1145
  try {
823
1146
  const open = await i.forge.findPullRequest(branch);
824
1147
  if (open) {
825
1148
  await i.forge.editPullRequest(open.number, { title, body });
826
1149
  pr = open.number;
827
- return finish({ result: "updated", reason: `updated #${open.number} from ${branch}`, commit: commitSha, ...(open.url ? { pullRequest: open.url } : {}), paths }, `the agent replaced the change on ${code(branch)} with ${code(commitSha.slice(0, 8))} for newer drift.`);
1150
+ return finish({ result: "updated", reason: `updated #${open.number} from ${branch}`, commit: commitSha, ...(open.url ? { pullRequest: open.url } : {}), paths }, `the agent replaced the change on ${code(branch)} with ${code(commitSha.slice(0, 8))} for ${s.on === "drift" ? "newer drift" : `a newer ${noun}`}.`);
828
1151
  }
829
1152
  const made = await i.forge.openPullRequest({ head: branch, title, body });
830
1153
  pr = made.number > 0 ? made.number : undefined;
@@ -836,16 +1159,20 @@ export async function landAgentChange(i) {
836
1159
  }
837
1160
  // ── what the generated jobs run ────────────────────────────────────────────
838
1161
  /**
839
- * The three commands of the agent jobs, through the product's bin. `dir` is
1162
+ * The three commands of the agent jobs, through the product's bin, with
1163
+ * the settings' digest ({@link agentSettingsDigest}) when given. `dir` is
840
1164
  * the agent directory from the job's directory, {@link AGENT_DIR} unless a
841
1165
  * workspace member's drift Op left its output under the member's directory
842
1166
  * (#4619): GitLab keeps the artifact at its path from the repository root.
843
1167
  */
844
- export function agentCommandLines(forge, bin, dir = AGENT_DIR) {
1168
+ export function agentCommandLines(forge, bin, dir = AGENT_DIR, digest) {
845
1169
  if (!/^[A-Za-z0-9._\/-]+$/.test(dir) || dir.split("/").includes(".."))
846
1170
  throw new AgentError(`the agent directory ${JSON.stringify(dir)} is a plain path from the repository root`);
1171
+ if (digest !== undefined && !/^sha256:[0-9a-f]{64}$/.test(digest))
1172
+ throw new AgentError(`the settings digest ${JSON.stringify(digest)} is not a sha256: digest`);
847
1173
  const line = (action) => {
848
- const chant = ["chant", "agent", action, "--forge", forge, "--output", dir].join(" ");
1174
+ // #5357: the settings' digest on the line itself, which a pipeline variable cannot replace.
1175
+ const chant = ["chant", "agent", action, "--forge", forge, "--output", dir, ...(digest ? ["--digest", digest] : [])].join(" ");
849
1176
  return bin ? chant.replace(/^chant /, `${bin} `) : chant;
850
1177
  };
851
1178
  return { prepare: line("prepare"), run: line("run"), land: line("land") };
@@ -41,6 +41,11 @@
41
41
  * takes the locks of what the reach line prints at stage apply without
42
42
  * applying, and the unlock releases the pull request's locks.
43
43
  *
44
+ * - with `reject` (#5354), `/<product> reject [--stage <stage>] <reason>`:
45
+ * a rejection of the release a stage waits on, recorded under the
46
+ * author's forge identity when the stage's approval mode takes it
47
+ * (./ci-comment-reject.ts); otherwise the reply names the reject line.
48
+ *
44
49
  * - with `allow` (INTENTIUS/terragucci#1461, ./ci-comment-allow.ts), a commenter
45
50
  * a `plan`, `apply`, `lock`, `unlock` or `agent` list leaves out gets a
46
51
  * reply that names the list, whichever job runs the command. The jobs that
@@ -61,6 +66,7 @@
61
66
  * runs here.
62
67
  */
63
68
  import { type CommentAllow, type CommentAllowReads } from "./ci-comment-allow.js";
69
+ import { type CommentReject } from "./ci-comment-reject.js";
64
70
  import { type ApplyRerun, type ChantNoteJobs, type StartedRun } from "./ci-note-commands.js";
65
71
  import { type CiProductWords, type ParsedProductComment } from "./ci-product-words.js";
66
72
  import { type ForgeFetch, type PrForge } from "./pr-forge.js";
@@ -188,6 +194,8 @@ export interface AnswerCommentOptions {
188
194
  allow?: CommentAllow;
189
195
  /** What team membership is read with when `allow` names a team: the reads of a token that can read teams. Default `reads`. */
190
196
  teams?: CommentAllowReads;
197
+ /** What a reject comment is recorded with (#5354). Absent: a reject comment is answered with the reject line, and nothing is recorded. */
198
+ reject?: CommentReject;
191
199
  }
192
200
  /** What the comment job did. */
193
201
  export interface CommentOutcome {
@@ -41,6 +41,11 @@
41
41
  * takes the locks of what the reach line prints at stage apply without
42
42
  * applying, and the unlock releases the pull request's locks.
43
43
  *
44
+ * - with `reject` (#5354), `/<product> reject [--stage <stage>] <reason>`:
45
+ * a rejection of the release a stage waits on, recorded under the
46
+ * author's forge identity when the stage's approval mode takes it
47
+ * (./ci-comment-reject.ts); otherwise the reply names the reject line.
48
+ *
44
49
  * - with `allow` (INTENTIUS/terragucci#1461, ./ci-comment-allow.ts), a commenter
45
50
  * a `plan`, `apply`, `lock`, `unlock` or `agent` list leaves out gets a
46
51
  * reply that names the list, whichever job runs the command. The jobs that
@@ -61,7 +66,8 @@
61
66
  * runs here.
62
67
  */
63
68
  import { decideCommentAllow, COMMENT_ALLOW_COMMANDS } from "./ci-comment-allow.js";
64
- import { commentTerms, forkReply, memberReply, notRunReply } from "./ci-comment-replies.js";
69
+ import { commentTerms, forkReply, memberReply, notRunReply, rejectNotRecorded } from "./ci-comment-replies.js";
70
+ import { decideCommentReject } from "./ci-comment-reject.js";
65
71
  import { retryApply } from "./ci-note-commands.js";
66
72
  import { parseProductComment } from "./ci-product-words.js";
67
73
  import { ForgeApiError } from "./pr-forge.js";
@@ -134,6 +140,8 @@ export function answeredElsewhere(parsed, jobs, open) {
134
140
  return Boolean(jobs.agent);
135
141
  case "commit":
136
142
  return true;
143
+ case "reject":
144
+ return false;
137
145
  case "apply":
138
146
  // The apply before merge answers an open pull request's apply comment; a merged one's is this job's.
139
147
  return Boolean(jobs.applyBeforeMerge) && open !== false;
@@ -259,6 +267,14 @@ export async function answerProductComment(o) {
259
267
  return reply(notRunReply(o.words, parsed.kind, o.forge));
260
268
  case "commit":
261
269
  return silent("the commit job answers this comment", command);
270
+ case "reject": {
271
+ // #5354: after the write-access check above; the stage's approval mode decides whether a comment's identity counts.
272
+ if (!o.reject)
273
+ return reply(rejectNotRecorded(o.words, o.forge));
274
+ const url = typeof comment.html_url === "string" ? comment.html_url : undefined;
275
+ const done = await decideCommentReject({ reject: o.reject, words: o.words, user, reason: parsed.reason, ...(parsed.stage !== undefined ? { stage: parsed.stage } : {}), ...(url ? { url } : {}) });
276
+ return done.kind === "fail" ? broke(done.reason, command) : reply(done.text, done.kind === "recorded");
277
+ }
262
278
  case "apply":
263
279
  break;
264
280
  }