@intentius/chant 0.124.79 → 0.124.81

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 (84) hide show
  1. package/dist/ci-note-commands.d.ts +199 -0
  2. package/dist/ci-note-commands.d.ts.map +1 -0
  3. package/dist/ci-note-commands.js +372 -0
  4. package/dist/cli/handlers/build.d.ts.map +1 -1
  5. package/dist/cli/handlers/build.js +7 -1
  6. package/dist/cli/handlers/pr-notes.d.ts +13 -0
  7. package/dist/cli/handlers/pr-notes.d.ts.map +1 -0
  8. package/dist/cli/handlers/pr-notes.js +73 -0
  9. package/dist/cli/main.d.ts.map +1 -1
  10. package/dist/cli/main.js +10 -1
  11. package/dist/cli/mcp/product-tools.d.ts.map +1 -1
  12. package/dist/cli/mcp/product-tools.js +1 -2
  13. package/dist/cli/parse-args.d.ts.map +1 -1
  14. package/dist/cli/parse-args.js +10 -0
  15. package/dist/cli/registry.d.ts +4 -0
  16. package/dist/cli/registry.d.ts.map +1 -1
  17. package/dist/components/capability.d.ts +22 -0
  18. package/dist/components/capability.d.ts.map +1 -1
  19. package/dist/components/pr-pipeline.d.ts +22 -0
  20. package/dist/components/pr-pipeline.d.ts.map +1 -1
  21. package/dist/components/pr-pipeline.js +26 -0
  22. package/dist/components/product-pipeline.d.ts +12 -0
  23. package/dist/components/product-pipeline.d.ts.map +1 -1
  24. package/dist/components/product-pipeline.js +5 -1
  25. package/dist/lifecycle/release-version.d.ts.map +1 -1
  26. package/dist/lifecycle/release-version.js +1 -2
  27. package/dist/op/index.d.ts +3 -3
  28. package/dist/op/index.d.ts.map +1 -1
  29. package/dist/op/index.js +2 -2
  30. package/dist/op/op-waves-after-plan.d.ts +33 -0
  31. package/dist/op/op-waves-after-plan.d.ts.map +1 -1
  32. package/dist/op/op-waves-after-plan.js +41 -4
  33. package/dist/op/op-waves-capability.d.ts +13 -1
  34. package/dist/op/op-waves-capability.d.ts.map +1 -1
  35. package/dist/op/op-waves-capability.js +22 -14
  36. package/dist/op/op-waves-run-hooks.d.ts.map +1 -1
  37. package/dist/op/op-waves-run-hooks.js +1 -2
  38. package/dist/op/op-waves-run.d.ts.map +1 -1
  39. package/dist/op/op-waves-run.js +125 -20
  40. package/dist/op/op-waves.d.ts +9 -5
  41. package/dist/op/op-waves.d.ts.map +1 -1
  42. package/dist/parallelism.d.ts +9 -0
  43. package/dist/parallelism.d.ts.map +1 -1
  44. package/dist/parallelism.js +15 -0
  45. package/dist/pr-forge-reads.d.ts +151 -1
  46. package/dist/pr-forge-reads.d.ts.map +1 -1
  47. package/dist/pr-forge-reads.js +265 -1
  48. package/dist/release-floors.d.ts +15 -1
  49. package/dist/release-floors.d.ts.map +1 -1
  50. package/dist/release-floors.js +17 -3
  51. package/dist/wave-runtime.mjs +288 -288
  52. package/package.json +1 -1
  53. package/src/ci-note-commands.test.ts +377 -0
  54. package/src/ci-note-commands.ts +479 -0
  55. package/src/cli/handlers/build.ts +7 -1
  56. package/src/cli/handlers/pr-notes.ts +70 -0
  57. package/src/cli/main.ts +10 -1
  58. package/src/cli/mcp/product-tools.test.ts +1 -2
  59. package/src/cli/mcp/product-tools.ts +1 -2
  60. package/src/cli/parse-args.ts +8 -0
  61. package/src/cli/registry.ts +4 -0
  62. package/src/components/capability.ts +22 -0
  63. package/src/components/pr-pipeline.ts +35 -0
  64. package/src/components/product-pipeline.test.ts +14 -0
  65. package/src/components/product-pipeline.ts +13 -1
  66. package/src/lifecycle/release-version.ts +1 -2
  67. package/src/op/index.ts +3 -2
  68. package/src/op/op-waves-after-plan-wave.test.ts +2 -3
  69. package/src/op/op-waves-after-plan.ts +61 -4
  70. package/src/op/op-waves-capability.test.ts +3 -1
  71. package/src/op/op-waves-capability.ts +27 -18
  72. package/src/op/op-waves-gate-port.test.ts +231 -0
  73. package/src/op/op-waves-parallel-plans.test.ts +185 -0
  74. package/src/op/op-waves-parallelism.test.ts +5 -0
  75. package/src/op/op-waves-run-hooks.test.ts +2 -3
  76. package/src/op/op-waves-run-hooks.ts +1 -2
  77. package/src/op/op-waves-run.ts +123 -23
  78. package/src/op/op-waves-step-wave.test.ts +3 -4
  79. package/src/op/op-waves.ts +9 -5
  80. package/src/parallelism.ts +26 -0
  81. package/src/pr-forge-reads-compare.test.ts +145 -0
  82. package/src/pr-forge-reads.test.ts +203 -0
  83. package/src/pr-forge-reads.ts +398 -1
  84. package/src/release-floors.ts +24 -3
@@ -93,7 +93,7 @@ import { LifecyclePushLostError, pushLifecycleRebasing } from "../lifecycle/git"
93
93
  import { resolveCiJob } from "../lifecycle/release-ledger";
94
94
  import type { OpRunPolicyRow, OpRunRecordInput, OpRunStepRecord, OpRunWave, OpRunWavePlan, OpRunWaveTarget } from "./runtime";
95
95
  import { opWaveRunHookList, opWaveRunHooksProblems, runOpWaveAfterApply, runOpWaveBeforeApply, runOpWaveBeforePlan, type OpWaveRunHooks } from "./op-waves-run-hooks";
96
- import { foldPolicyRows, opWaveAfterPlanProblems, runOpWaveAfterPlanHooks, type OpWaveAfterPlanHook, type OpWaveAfterPlanRun, type OpWaveAfterPlanWaveOutcome } from "./op-waves-after-plan";
96
+ import { foldPolicyRows, opWaveAfterPlanProblems, runOpWaveAfterPlanHooks, type OpWaveAfterPlanHook, type OpWaveAfterPlanRun, type OpWaveAfterPlanWaveOutcome, type OpWaveAnswerApproval } from "./op-waves-after-plan";
97
97
  import { activeOtlp, RunEventTrace, type CapabilityTraceFacts, type OtlpExporter } from "../otlp";
98
98
  import { joinRunEventSinks, resolveRunEventRun, type RunEventSink } from "../run-event-stream";
99
99
  import { OpWaveRunEvents } from "./op-waves-events";
@@ -106,7 +106,7 @@ import type { LockGrain } from "../lifecycle/lock-rows";
106
106
  import type { LockLiveness } from "../lifecycle/resource-lock";
107
107
  import type { GatePolicyExec } from "../gate-policy";
108
108
  import { gitOpWaveNewerCommit, opWaveStandDownReason, tipAppliesTargets, type OpWaveNewerCommitPort } from "./op-waves-stand-down";
109
- import { mapLimited } from "../parallelism";
109
+ import { keyedSerial, mapLimited, type SerialSection } from "../parallelism";
110
110
  import {
111
111
  applyOpWaveStep,
112
112
  opWaveCosts,
@@ -127,7 +127,7 @@ import {
127
127
  type OpWaveStepPlan,
128
128
  } from "./op-waves-capability";
129
129
  import {
130
- changeInvolvement, quorumProblems, quorumRuleLine, quorumRulesFor, quorumWaiting, recordedReviewApprovals, ruleNeedsProof, samePrincipal, trustQuorumJudge,
130
+ changeInvolvement, quorumProblems, quorumRuleLine, quorumRulesFor, quorumWaiting, recordedReviewApprovals, recordedReviewOf, ruleNeedsProof, samePrincipal, trustQuorumJudge,
131
131
  type GateQuorumJudge, type GateQuorumRule, type GateQuorumRuleProgress, type QuorumJudgement,
132
132
  } from "./gate-quorum";
133
133
  import {
@@ -716,10 +716,11 @@ function quorumAtBase(spec: OpWavesSpec, where: string): Pick<OpWaveBaseRules, "
716
716
  if (bad.length > 0) return { quorumRefused: `the approval rules in ${where} cannot be read (${bad.join("; ")})` };
717
717
  extra.involved = structuredClone(a.involved as OpWavesInvolved);
718
718
  }
719
- if (raw === undefined) return {};
719
+ // terragucci issue 1303: the review ledger and the involved count without rules too.
720
+ if (raw === undefined) return extra;
720
721
  const problems = Array.isArray(raw) ? quorumProblems(raw, "approvals.quorum", { notAuthor: true }) : ["`approvals.quorum` must be a list of rules"];
721
722
  if (problems.length > 0) return { quorumRefused: `the approval rules in ${where} cannot be read (${problems.join("; ")})` };
722
- return (raw as GateQuorumRule[]).length > 0 ? { quorum: raw as GateQuorumRule[], ...extra } : {};
723
+ return (raw as GateQuorumRule[]).length > 0 ? { quorum: raw as GateQuorumRule[], ...extra } : extra;
723
724
  }
724
725
 
725
726
  /** The holds at base (#4545), or why they cannot be read. */
@@ -970,10 +971,14 @@ interface WaveContext {
970
971
  steps?: Map<string, OpWaveStepPlan>;
971
972
  /** Each run's environment from the run hooks (#4842), by target, which its plan and its apply run with. */
972
973
  runEnv?: Map<string, Record<string, string>>;
974
+ /** The wave's serial section (#4864), made when its runs plan or apply several at once and shared by its plans and applies. */
975
+ serial?: SerialSection;
973
976
  /** The plans file's change set (#4551), which a `pull-request` gate checks the pull request's approval against (#4550). */
974
977
  changeSetDoc?: ChangeSetDocument;
975
978
  /** An after-plan hook's report of the wave's plans (#4842), stored beside the pending fact. */
976
979
  report?: string;
980
+ /** The approvals the after-plan hooks settled before the gate (terragucci issue 1303), recorded at it before it is decided. */
981
+ answerApprovals?: OpWaveAnswerApproval[];
977
982
  }
978
983
 
979
984
  function planRun(opts: { spec: OpWavesSpec; wave: number; cwd: string; exec: OpWaveExec }, waveName: string, run: OpWaveRun): OpWaveMember {
@@ -1157,15 +1162,16 @@ function runHookRun(at: { spec: OpWavesSpec; k: number; wave: OpWave; cwd: strin
1157
1162
  * with the run's environment, then `afterApply`, whose files go on the
1158
1163
  * result and whose failure fails a run that applied.
1159
1164
  */
1160
- async function applyStepRun(ctx: WaveContext, registry: CapabilityRegistry, run: OpWaveRun, plan: OpWaveStepPlan): Promise<OpWaveStepApply & { files?: string[] }> {
1165
+ async function applyStepRun(ctx: WaveContext, registry: CapabilityRegistry, run: OpWaveRun, plan: OpWaveStepPlan, serial?: SerialSection): Promise<OpWaveStepApply & { files?: string[] }> {
1161
1166
  const { spec, wave, k, options } = ctx;
1162
1167
  const hooks = opWaveRunHookList(options.runHooks);
1163
1168
  const env = ctx.runEnv?.get(run.target);
1164
- if (hooks.length === 0) return applyOpWaveStep({ spec, wave, registry, ...(env ? { processEnv: env } : {}) }, run, plan);
1169
+ const at = { spec, wave, registry, cwd: ctx.cwd, ...(env ? { processEnv: env } : {}), ...(serial ? { serial } : {}) };
1170
+ if (hooks.length === 0) return applyOpWaveStep(at, run, plan);
1165
1171
  const planned = { ...runHookRun(ctx, run), planDigest: plan.planDigest, plan: opWavePlanPath(spec, k, run.target), ...(plan.artifact !== undefined ? { artifact: plan.artifact } : {}) };
1166
1172
  const stop = await runOpWaveBeforeApply(hooks, planned);
1167
1173
  if (stop !== undefined) return { outcome: "failed", reason: stop };
1168
- const got = await applyOpWaveStep({ spec, wave, registry, ...(env ? { processEnv: env } : {}) }, run, plan);
1174
+ const got = await applyOpWaveStep(at, run, plan);
1169
1175
  const after = await runOpWaveAfterApply(hooks, { ...planned, outcome: got.outcome, ...(got.outcome === "applied" ? { output: got.output } : { reason: got.reason }) });
1170
1176
  const files = after.files.length > 0 ? { files: after.files } : {};
1171
1177
  if (after.failed && got.outcome === "applied") return { outcome: "failed", reason: `applied, and then ${after.failed}`, ...(got.facts ? { facts: got.facts } : {}), ...files };
@@ -1176,10 +1182,13 @@ async function applyStepRun(ctx: WaveContext, registry: CapabilityRegistry, run:
1176
1182
  /**
1177
1183
  * Plan `runs` of wave `k` (#4545): through the spec's `step` when it names
1178
1184
  * one, each run's plan kept on `at.steps` for its apply, else with the
1179
- * commands ({@link planRuns}).
1185
+ * commands ({@link planRuns}). With the wave's `parallelism` over 1 the
1186
+ * step plans up to that many runs at once (#4864), each with the wave's
1187
+ * serial section on its context, and the members, parts and plan files come
1188
+ * out as one at a time makes them, in the wave's order.
1180
1189
  */
1181
1190
  async function planWaveRuns(
1182
- at: { spec: OpWavesSpec; k: number; wave: OpWave; cwd: string; exec: OpWaveExec; options: Pick<RunOpWaveOptions, "capabilities" | "lockGrain" | "base" | "waveExec" | "runHooks" | "decide" | "share" | "group">; steps?: Map<string, OpWaveStepPlan>; runEnv?: Map<string, Record<string, string>> },
1191
+ at: { spec: OpWavesSpec; k: number; wave: OpWave; cwd: string; exec: OpWaveExec; options: Pick<RunOpWaveOptions, "capabilities" | "lockGrain" | "base" | "waveExec" | "runHooks" | "decide" | "share" | "group">; steps?: Map<string, OpWaveStepPlan>; runEnv?: Map<string, Record<string, string>>; serial?: SerialSection },
1183
1192
  runs: readonly OpWaveRun[],
1184
1193
  discover = false,
1185
1194
  ): Promise<PlannedRuns> {
@@ -1191,7 +1200,7 @@ async function planWaveRuns(
1191
1200
  // #4613: a step's own policy engine (CrossGuard) reads its packs at the base the wave's rules were read at.
1192
1201
  const policyBase = base && base !== "HEAD" ? base : undefined;
1193
1202
  // #4842: a discovering wave's runs are the ones its step's capability finds for wave k.
1194
- const found = discover ? await discoverOpWaveStepRuns({ spec, wave, k, registry }) : undefined;
1203
+ const found = discover ? await discoverOpWaveStepRuns({ spec, wave, k, registry, cwd }) : undefined;
1195
1204
  if (found) runs = found.runs;
1196
1205
  const plans: OpWaveStepPlan[] = [];
1197
1206
  const hooks = opWaveRunHookList(at.options.runHooks);
@@ -1220,11 +1229,39 @@ async function planWaveRuns(
1220
1229
  }
1221
1230
  together = plans[0]?.group?.digest;
1222
1231
  } else {
1223
- for (const run of runs) {
1232
+ const limit = wave.parallelism ?? spec.parallelism ?? 1;
1233
+ // #4864: runs that plan beside each other share the wave's serial section, such as a turn at the provider cache for init.
1234
+ const serial = limit > 1 && runs.length > 1 ? (at.serial ??= keyedSerial()) : undefined;
1235
+ const planOne = async (run: OpWaveRun): Promise<OpWaveStepPlan> => {
1224
1236
  const before = await beforePlan(run);
1225
- const plan = await planOpWaveStep({ spec, wave, cwd, registry, planPath: opWavePlanPath(spec, k, run.target), lockGrain, ...(policyBase ? { policyBase } : {}), ...(before.env ? { processEnv: before.env } : {}), ...(before.afterInit ? { afterInit: before.afterInit } : {}) }, run);
1226
- at.steps?.set(run.target, plan);
1227
- plans.push(plan);
1237
+ return planOpWaveStep({ spec, wave, cwd, registry, planPath: opWavePlanPath(spec, k, run.target), lockGrain, ...(policyBase ? { policyBase } : {}), ...(before.env ? { processEnv: before.env } : {}), ...(before.afterInit ? { afterInit: before.afterInit } : {}), ...(serial ? { serial } : {}) }, run);
1238
+ };
1239
+ if (!serial) {
1240
+ for (const run of runs) {
1241
+ const plan = await planOne(run);
1242
+ at.steps?.set(run.target, plan);
1243
+ plans.push(plan);
1244
+ }
1245
+ } else {
1246
+ // #4864: up to `limit` plans at once, started in the wave's order. A failure starts no more, and the
1247
+ // first failing run in the wave's order fails the wave, the one a plan one at a time would have stopped at.
1248
+ let stopped = false;
1249
+ const got = await mapLimited(runs, limit, async (run): Promise<{ plan: OpWaveStepPlan } | { error: unknown } | undefined> => {
1250
+ if (stopped) return undefined;
1251
+ try {
1252
+ return { plan: await planOne(run) };
1253
+ } catch (error) {
1254
+ stopped = true;
1255
+ return { error };
1256
+ }
1257
+ });
1258
+ const failure = got.find((g) => g !== undefined && "error" in g);
1259
+ if (failure && "error" in failure) throw failure.error;
1260
+ for (const g of got) {
1261
+ if (!g || !("plan" in g)) continue;
1262
+ at.steps?.set(g.plan.target, g.plan);
1263
+ plans.push(g.plan);
1264
+ }
1228
1265
  }
1229
1266
  }
1230
1267
  const members = plans.map((p) => ({
@@ -2634,6 +2671,7 @@ async function planOpWave(options: RunOpWaveOptions, { k, pass }: WaveAttempt<Ru
2634
2671
  extras = [...(extras ?? []), ...answer.members];
2635
2672
  }
2636
2673
  if (answer?.report !== undefined) ctx.report = answer.report;
2674
+ if (answer?.approvals.length) ctx.answerApprovals = answer.approvals;
2637
2675
  if (wave.discover) {
2638
2676
  wave = { ...wave, runs: members.map((m) => ({ target: m.member, ...(m.op !== spec.op ? { op: m.op } : {}) })) };
2639
2677
  ctx.wave = wave;
@@ -2707,8 +2745,9 @@ async function decideOpWave(
2707
2745
  decision.members = members;
2708
2746
  // #4290: the rules at base whose targets glob matches one of the wave's runs.
2709
2747
  const takes = planned.rules.quorum ? quorumRulesFor(planned.rules.quorum, members.map((m) => m.member)) : [];
2710
- if (takes.length > 0) {
2711
- decision.quorum = takes;
2748
+ if (takes.length > 0) decision.quorum = takes;
2749
+ // terragucci issue 1303: a wave no rule covers still leaves the involved out, and counts a review the product recorded.
2750
+ if (takes.length > 0 || opWaveOneApprover(decision.approval, planned.rules)) {
2712
2751
  if (planned.rules.reviewLedger) decision.reviewLedger = planned.rules.reviewLedger;
2713
2752
  if (planned.rules.involved) decision.involved = planned.rules.involved;
2714
2753
  }
@@ -2751,6 +2790,8 @@ async function decideOpWave(
2751
2790
  decision.status = "approved";
2752
2791
  log(`wave ${k} (${wave.name}): planned again to the same digest, so the approval by ${was.approvedBy} still holds`);
2753
2792
  } else if (decision.status !== "refused" && (unseen || opWaveNeedsApproval(policy, members) || holds.length > 0)) {
2793
+ // terragucci issue 1303: what the product settled before the gate, recorded at it for these plans first.
2794
+ if (ctx.answerApprovals?.length) await recordAnswerApprovals(options, ctx, decision);
2754
2795
  await settleGate(options, ctx, decision);
2755
2796
  // Plans nobody previewed apply only under an approval of these very plans, whatever the gate policy says.
2756
2797
  if (unseen) refuseUnseen(ctx, decision);
@@ -3124,6 +3165,8 @@ function failed(ctx: WaveContext, line: string): RunOpWaveResult {
3124
3165
  async function settleGate(options: RunOpWaveOptions, ctx: WaveContext, decision: OpWaveDecision): Promise<void> {
3125
3166
  if (decision.point) return settlePointGate(options, ctx, decision, decision.point);
3126
3167
  if (decision.quorum?.length) return settleQuorumGate(options, ctx, decision, decision.quorum);
3168
+ // terragucci issue 1303: with no rule, `approvals.involved.exclude` and a review ledger still judge each approval, as one approver's rule does.
3169
+ if ((decision.involved?.exclude || decision.reviewLedger) && decision.approval !== "pull-request") return settleQuorumGate(options, ctx, decision, [{ count: 1 }], true);
3127
3170
  const { spec, k, wave, cwd } = ctx;
3128
3171
  const { gate, digest, approval, base, policy, members } = decision;
3129
3172
  // #4574: the run target a product's approve line names.
@@ -3279,7 +3322,7 @@ const gitCommitsBetween = (cwd: string) => (base: string, head: string): { sha:
3279
3322
  * the same pull request; with none, no approver can show they are someone
3280
3323
  * else and the rule waits.
3281
3324
  */
3282
- async function settleQuorumGate(options: RunOpWaveOptions, ctx: WaveContext, decision: OpWaveDecision, rules: GateQuorumRule[]): Promise<void> {
3325
+ async function settleQuorumGate(options: RunOpWaveOptions, ctx: WaveContext, decision: OpWaveDecision, rules: GateQuorumRule[], oneApprover = false): Promise<void> {
3283
3326
  const { spec, k, wave, cwd, log } = ctx;
3284
3327
  const { gate, digest, approval, base, policy, members } = decision;
3285
3328
  const { ledger, port } = await gatePort(options, cwd, gate, approval, base);
@@ -3384,7 +3427,11 @@ async function settleQuorumGate(options: RunOpWaveOptions, ctx: WaveContext, dec
3384
3427
  ...(reviewed ? { review: reviewed } : {}),
3385
3428
  ...(recorded.length > 0 ? { recorded } : {}),
3386
3429
  });
3387
- const judge: GateQuorumJudge = (r) => sayExcluded(judgeBase(r));
3430
+ // terragucci issue 1303: on the spec's own ledger a product's review line names every reviewer in one approver, and each reviewer counts on their own line.
3431
+ const judge: GateQuorumJudge = (r) =>
3432
+ decision.reviewLedger === spec.name && recordedReviewOf(r) !== null
3433
+ ? { proven: false, roles: [], excluded: `the review line by ${r.resolvedBy} counts each of its reviewers on their own` }
3434
+ : sayExcluded(judgeBase(r));
3388
3435
  const held = decision.heldBy?.length ? `, held by ${decision.heldBy.join(", ")}` : "";
3389
3436
  const check = await decideWaveGate(port, {
3390
3437
  op: spec.name,
@@ -3404,7 +3451,7 @@ async function settleQuorumGate(options: RunOpWaveOptions, ctx: WaveContext, dec
3404
3451
  decision.via = reviewed && check.resolution.review?.head === reviewed.head ? "pr-review" : "ledger";
3405
3452
  decision.approvedBy = by.join(", ");
3406
3453
  decision.approvedAt = check.resolution.timestamp;
3407
- log(`${label}: the approval rules at ${base.slice(0, 12)} are met by ${by.join(", ")}`);
3454
+ log(oneApprover ? `${label}: approved by ${by.join(", ")}, who had no hand in the change` : `${label}: the approval rules at ${base.slice(0, 12)} are met by ${by.join(", ")}`);
3408
3455
  return;
3409
3456
  }
3410
3457
  logRefused(log, label, check);
@@ -3412,7 +3459,8 @@ async function settleQuorumGate(options: RunOpWaveOptions, ctx: WaveContext, dec
3412
3459
  decision.recorded = check.recorded;
3413
3460
  decision.waitingSince = check.pending.timestamp;
3414
3461
  if (check.mismatch) decision.mismatch = check.mismatch;
3415
- if (check.quorum?.rules) {
3462
+ if (oneApprover) log(`${label}: no approval of ${digest} counts once the people behind the change are left out, so it waits for one`);
3463
+ else if (check.quorum?.rules) {
3416
3464
  decision.quorumProgress = check.quorum.rules;
3417
3465
  for (const p of check.quorum.rules) log(`${label}: approval rule ${quorumRuleLine(p)}`);
3418
3466
  log(`${label}: the approval rules at ${base.slice(0, 12)} are not met (${quorumWaiting(check.quorum.rules)}), so it waits for more approvals of ${digest}`);
@@ -3938,7 +3986,7 @@ async function applyStepRunsTogether(options: RunOpWaveOptions, ctx: WaveContext
3938
3986
  result.failed.push(...runs.map((r) => r.target));
3939
3987
  return;
3940
3988
  }
3941
- const got = await applyOpWaveStepGroup({ spec, wave, registry, runEnv: (target) => ctx.runEnv?.get(target) }, planned);
3989
+ const got = await applyOpWaveStepGroup({ spec, wave, registry, cwd: ctx.cwd, runEnv: (target) => ctx.runEnv?.get(target) }, planned);
3942
3990
  for (const [i, p] of planned.entries()) {
3943
3991
  let outcome = got[i]!;
3944
3992
  let files: string[] | undefined;
@@ -3976,6 +4024,8 @@ async function applyStepRunsAtOnce(options: RunOpWaveOptions, ctx: WaveContext,
3976
4024
  type Outcome = { applied: true } | { failed: true } | { moved: true } | { blockedBy: string };
3977
4025
  const order = new Map(runs.map((r, i) => [r.target, i]));
3978
4026
  const registry = await opWaveRegistry(options, ctx.cwd, options.capabilities);
4027
+ // #4864: the section the wave's plans took turns in, so an apply that inits again waits its turn too.
4028
+ const serial = runs.length > 1 ? (ctx.serial ??= keyedSerial()) : undefined;
3979
4029
  const settled = new Map<string, Promise<Outcome>>();
3980
4030
  const outcomes = await mapLimited(runs, limit, (run, i) => {
3981
4031
  const going = (async (): Promise<Outcome> => {
@@ -3994,7 +4044,7 @@ async function applyStepRunsAtOnce(options: RunOpWaveOptions, ctx: WaveContext,
3994
4044
  return { failed: true };
3995
4045
  }
3996
4046
  const startedMs = targetStarted(options, k, run.target);
3997
- const got = await applyStepRun(ctx, registry, run, plan);
4047
+ const got = await applyStepRun(ctx, registry, run, plan, serial);
3998
4048
  targetSettled(options, result, k, run.target, startedMs, got.outcome === "applied" ? "ok" : got.outcome === "moved" ? "skipped" : "failed", {
3999
4049
  ...(got.outcome !== "applied" ? { error: got.reason } : {}),
4000
4050
  ...(got.facts ? { facts: got.facts } : {}),
@@ -4252,3 +4302,53 @@ async function writeHeadPlans(plans: HeadPlans, cwd: string): Promise<void> {
4252
4302
  const pushed = await pushLifecycleRebasing({ cwd });
4253
4303
  if (!pushed.pushed) throw new Error(`the plans were recorded locally only: ${pushed.pushWarning ?? "chant/lifecycle has no remote to push to"}`);
4254
4304
  }
4305
+
4306
+ /**
4307
+ * Whether a wave no approval rule covers is still judged approver by
4308
+ * approver (terragucci issue 1303): `approvals.involved.exclude`, or a
4309
+ * review ledger under `pr-review`, at base. Not under `pull-request`, whose
4310
+ * approval is the pull request's gate.
4311
+ */
4312
+ function opWaveOneApprover(approval: GateApprovalSource, rules: Pick<OpWaveBaseRules, "involved" | "reviewLedger">): boolean {
4313
+ if (approval === "pull-request") return false;
4314
+ return rules.involved?.exclude === true || (rules.reviewLedger !== undefined && approval === "pr-review");
4315
+ }
4316
+
4317
+ /**
4318
+ * Record the approvals the after-plan hooks settled before the gate
4319
+ * (terragucci issue 1303) at the wave's gate, for the digest it decides, on
4320
+ * the spec's op. An approval already recorded for the digest by the same
4321
+ * approver with the same note is not written again. A gate that asks a
4322
+ * decision point records none: only its answer passes the wave.
4323
+ */
4324
+ async function recordAnswerApprovals(options: RunOpWaveOptions, ctx: WaveContext, decision: OpWaveDecision): Promise<void> {
4325
+ const { spec, k, wave, cwd, log } = ctx;
4326
+ const label = `wave ${k} (${wave.name})`;
4327
+ const approvals = ctx.answerApprovals ?? [];
4328
+ if (decision.point) {
4329
+ log(`${label}: the gate asks a decision point, so the ${approvals.length} approval${approvals.length === 1 ? "" : "s"} the after-plan hooks gave ${approvals.length === 1 ? "is" : "are"} not recorded`);
4330
+ return;
4331
+ }
4332
+ const ledger = options.gates ?? gitGateLedgerPort({ cwd });
4333
+ if (!ledger.appendResolution) {
4334
+ log(`${label}: the gate ledger takes no approvals, so the ones the after-plan hooks gave are not recorded`);
4335
+ return;
4336
+ }
4337
+ const now = options.now ?? new Date().toISOString();
4338
+ const had = (await ledger.read(spec.name)).resolutions.filter((r) => r.gate === decision.gate && samePlanDigest(r.planDigest, decision.digest));
4339
+ for (const a of approvals) {
4340
+ if (had.some((r) => r.resolvedBy === a.resolvedBy && r.note === a.note)) continue;
4341
+ const review = a.review ? { via: "pr-review", pr: a.review.pr, head: a.review.head, reviewers: a.review.reviewers } : {};
4342
+ await ledger.appendResolution({
4343
+ op: spec.name,
4344
+ gate: decision.gate,
4345
+ resolvedBy: a.resolvedBy,
4346
+ timestamp: now,
4347
+ planDigest: decision.digest,
4348
+ note: a.note,
4349
+ ...(a.url ? { url: a.url } : {}),
4350
+ ...(review as object),
4351
+ } as Parameters<NonNullable<GateLedgerPort["appendResolution"]>>[0]);
4352
+ log(`${label}: ${a.resolvedBy}'s approval recorded for ${decision.digest}: ${a.note}`);
4353
+ }
4354
+ }
@@ -16,7 +16,6 @@ import { CapabilityRegistry, type Capability, type CapabilityGroupOutcome, type
16
16
  import type { ChangeSetPart } from "../change-set";
17
17
  import { groupDigest } from "../components/groups";
18
18
  import { waveSetDigest } from "../wave-engine";
19
- import { NEXT_RELEASE } from "../release-floors";
20
19
  import type { OpWaveRunHooks } from "./op-waves-run-hooks";
21
20
 
22
21
  const digest = (n: string) => `sha256:${n.repeat(64)}`;
@@ -127,7 +126,7 @@ describe("a wave planned as one through a step (#4842)", () => {
127
126
  expect(result.exitCode).toBe(0);
128
127
  // The input has {op} and {wave} filled and {target} as written; the wave number is the one planned.
129
128
  expect(seen.discovered.map((d) => d.ctx)).toEqual([
130
- { env: "rest", wave: { name: "rest", number: 2 } },
129
+ { env: "rest", cwd: h.cwd, wave: { name: "rest", number: 2 } },
131
130
  ]);
132
131
  expect(seen.discovered[0]!.input).toEqual({ unit: "{target}", dir: ".", wave: "rest" });
133
132
  expect(seen.planned).toEqual(["live/c"]);
@@ -175,7 +174,7 @@ describe("a wave planned as one through a step (#4842)", () => {
175
174
  expect(result.exitCode).toBe(0);
176
175
  expect(seen.planned).toEqual([]);
177
176
  expect(seen.groups).toHaveLength(1);
178
- expect(seen.groups[0]!.ctx).toEqual({ env: "layer", components: ["live/a", "live/b"] });
177
+ expect(seen.groups[0]!.ctx).toEqual({ env: "layer", cwd: h.cwd, components: ["live/a", "live/b"] });
179
178
  expect(seen.groups[0]!.members.map((m) => m.input)).toEqual([
180
179
  { unit: "live/a", dir: ".", wave: "layer" },
181
180
  { unit: "live/b", dir: ".", wave: "layer" },
@@ -272,6 +271,6 @@ describe("a wave planned as one through a step (#4842)", () => {
272
271
 
273
272
  test("the floor is the next release", async () => {
274
273
  const entry = await import("./index");
275
- expect(entry.OP_WAVE_STEP_WAVE_FLOOR).toBe(NEXT_RELEASE);
274
+ expect(entry.OP_WAVE_STEP_WAVE_FLOOR).toBe("0.124.79");
276
275
  });
277
276
  });
@@ -412,7 +412,7 @@ export interface OpWave {
412
412
  hooks?: OpWaveHooks;
413
413
  /** Where this wave's jobs run (#3914). Default: the spec's `runner`. */
414
414
  runner?: OpWaveRunner;
415
- /** How many of the wave's runs apply at once (#4625), over the spec's `parallelism`. */
415
+ /** How many of the wave's runs plan and apply at once (#4625, #4864), over the spec's `parallelism`. */
416
416
  parallelism?: number;
417
417
  /**
418
418
  * The OIDC tokens this wave's jobs get (#3914), as `{ <variable>: <audience> }`;
@@ -513,10 +513,14 @@ export interface OpWavesSpec {
513
513
  */
514
514
  step?: OpWaveStep;
515
515
  /**
516
- * How many runs of a wave apply at once (#4625), a wave's own
517
- * `parallelism` winning. Default 1, one at a time. Over 1 it needs `step`:
518
- * a run whose wave lists one of its `dependsOn` before it waits for that
519
- * one, and is blocked when it failed, as one at a time.
516
+ * How many runs of a wave plan and apply at once (#4625, #4864), a wave's
517
+ * own `parallelism` winning. Default 1, one at a time. Over 1 it needs
518
+ * `step`: the plans start in the wave's order and the digest lists them as
519
+ * one at a time does, and a run whose wave lists one of its `dependsOn`
520
+ * before it waits for that one to apply, and is blocked when it failed, as
521
+ * one at a time. Each run's context carries the wave's serial section
522
+ * (`DeployContext.serial`), which `terraform-apply` and `terragrunt-apply`
523
+ * take their inits in when the runs share a provider cache.
520
524
  */
521
525
  parallelism?: number;
522
526
  /**
@@ -31,3 +31,29 @@ export async function mapLimited<T, R>(items: readonly T[], limit: number | unde
31
31
  await Promise.all(Array.from({ length: Math.max(1, limit) }, worker));
32
32
  return out;
33
33
  }
34
+
35
+ /**
36
+ * Run `fn` alone among the calls with the same `key` (#4864): a call waits
37
+ * for every earlier call with its key to settle, then runs, while calls
38
+ * with other keys go on beside it. A call's failure is its own; the next
39
+ * call with the key runs anyway.
40
+ */
41
+ export type SerialSection = <T>(key: string, fn: () => Promise<T>) => Promise<T>;
42
+
43
+ /** A fresh {@link SerialSection}, whose keys are its own: an op wave makes one per wave job. */
44
+ export function keyedSerial(): SerialSection {
45
+ const tails = new Map<string, Promise<unknown>>();
46
+ return <T>(key: string, fn: () => Promise<T>): Promise<T> => {
47
+ const before = tails.get(key) ?? Promise.resolve();
48
+ const mine = before.then(() => fn());
49
+ const tail = mine.then(
50
+ () => undefined,
51
+ () => undefined,
52
+ );
53
+ tails.set(key, tail);
54
+ void tail.then(() => {
55
+ if (tails.get(key) === tail) tails.delete(key);
56
+ });
57
+ return mine;
58
+ };
59
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * The forge reads of a comparison, a job and a job's artifact file (#4862),
3
+ * against a loopback fake of each forge: the calls each makes on GitHub,
4
+ * Forgejo and GitLab, and what each reads back.
5
+ */
6
+
7
+ import { afterAll, beforeAll, beforeEach, describe, expect, test } from "vitest";
8
+ import { createServer, type Server } from "node:http";
9
+ import type { AddressInfo } from "node:net";
10
+ import { forgejoReads, githubReads, gitlabReads } from "./pr-forge-reads";
11
+
12
+ const SHA = "a".repeat(40);
13
+
14
+ /** A route answers JSON, a status, or `{ raw }`, a body sent as it is. */
15
+ type Answer = unknown;
16
+ let routes: Record<string, Answer> = {};
17
+ let calls: { method: string; url: string; headers: Record<string, string | string[] | undefined> }[] = [];
18
+ let server: Server;
19
+ let origin = "";
20
+
21
+ beforeAll(async () => {
22
+ server = createServer((req, res) => {
23
+ calls.push({ method: req.method ?? "", url: req.url ?? "", headers: req.headers });
24
+ const path = new URL(req.url ?? "/", "http://x").pathname;
25
+ const found = routes[`${req.method} ${path}`];
26
+ if (found === undefined) {
27
+ res.writeHead(404, { "content-type": "application/json" });
28
+ res.end('{"message":"404 Not Found"}');
29
+ return;
30
+ }
31
+ if (typeof found === "number") {
32
+ res.writeHead(found);
33
+ res.end();
34
+ return;
35
+ }
36
+ if (typeof found === "object" && found !== null && "raw" in found) {
37
+ res.writeHead(200, { "content-type": "application/octet-stream" });
38
+ res.end(String((found as { raw: string }).raw));
39
+ return;
40
+ }
41
+ res.writeHead(200, { "content-type": "application/json" });
42
+ res.end(JSON.stringify(found));
43
+ });
44
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r()));
45
+ origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
46
+ });
47
+
48
+ afterAll(() => new Promise<void>((r) => server.close(() => r())));
49
+
50
+ beforeEach(() => {
51
+ routes = {};
52
+ calls = [];
53
+ });
54
+
55
+ const urls = () => calls.map((c) => `${c.method} ${c.url}`);
56
+ const gh = () => githubReads({ apiBase: origin, repo: "acme/infra", token: "t0k" });
57
+ const fj = () => forgejoReads({ apiBase: `${origin}/api/v1`, repo: "acme/infra", token: "t0k" });
58
+ const gl = () => gitlabReads({ apiBase: `${origin}/api/v4`, project: "acme/infra", token: "glpat" });
59
+ const P = "/api/v4/projects/acme%2Finfra";
60
+
61
+ describe("compare", () => {
62
+ test("github: the files a head changes since its merge base, a rename with its old path", async () => {
63
+ routes[`GET /repos/acme/infra/compare/main...${SHA}`] = {
64
+ behind_by: 1,
65
+ files: [{ filename: "a.tf", status: "modified" }, { filename: ".github/workflows/ci.yml", previous_filename: "ci.yml", status: "renamed" }],
66
+ };
67
+ expect(await gh().compare("main", SHA)).toEqual({ files: [{ path: "a.tf" }, { path: ".github/workflows/ci.yml", previousPath: "ci.yml" }], truncated: false });
68
+ expect(urls()).toEqual([`GET /repos/acme/infra/compare/main...${SHA}`]);
69
+ expect(calls[0]!.headers.authorization).toBe("Bearer t0k");
70
+ });
71
+
72
+ test("github: a list of 300 files is the most GitHub lists, so it says it may be cut short", async () => {
73
+ routes[`GET /repos/acme/infra/compare/release%2F1...${SHA}`] = { files: Array.from({ length: 300 }, (_, i) => ({ filename: `f${i}` })) };
74
+ const got = await gh().compare("release/1", SHA);
75
+ expect(got.files).toHaveLength(300);
76
+ expect(got.truncated).toBe(true);
77
+ });
78
+
79
+ test("forgejo: the files its commits change, once each, cut short when it lists fewer commits than it counts", async () => {
80
+ routes[`GET /api/v1/repos/acme/infra/compare/main...${SHA}`] = {
81
+ total_commits: 2,
82
+ commits: [{ sha: SHA, files: [{ filename: "a.tf", status: "modified" }, { filename: ".forgejo/workflows/ci.yml", status: "added" }] }, { sha: "b".repeat(40), files: [{ filename: "a.tf", status: "modified" }] }],
83
+ };
84
+ expect(await fj().compare("main", SHA)).toEqual({ files: [{ path: "a.tf" }, { path: ".forgejo/workflows/ci.yml" }], truncated: false });
85
+ expect(calls[0]!.headers.authorization).toBe("token t0k");
86
+ routes[`GET /api/v1/repos/acme/infra/compare/main...${SHA}`] = { total_commits: 3, commits: [{ sha: SHA, files: [{ filename: "a.tf" }] }] };
87
+ expect((await fj().compare("main", SHA)).truncated).toBe(true);
88
+ routes[`GET /api/v1/repos/acme/infra/compare/main...${SHA}`] = { total_commits: 1, commits: [{ sha: SHA }] };
89
+ expect((await fj().compare("main", SHA)).truncated).toBe(true);
90
+ });
91
+
92
+ test("gitlab: the diffs' paths from the merge base, cut short when the compare timed out", async () => {
93
+ routes[`GET ${P}/repository/compare`] = { diffs: [{ old_path: "a.tf", new_path: "a.tf" }, { old_path: "ci.yml", new_path: ".gitlab-ci.yml", renamed_file: true }], compare_timeout: false };
94
+ expect(await gl().compare("main", SHA)).toEqual({ files: [{ path: "a.tf" }, { path: ".gitlab-ci.yml", previousPath: "ci.yml" }], truncated: false });
95
+ expect(urls()).toEqual([`GET ${P}/repository/compare?from=main&to=${SHA}&straight=false`]);
96
+ expect(calls[0]!.headers["private-token"]).toBe("glpat");
97
+ routes[`GET ${P}/repository/compare`] = { diffs: [], compare_timeout: true };
98
+ expect((await gl().compare("main", SHA)).truncated).toBe(true);
99
+ });
100
+ });
101
+
102
+ describe("a job by id, and the jobs' URLs", () => {
103
+ test("github: a job with its run, branch and URL; undefined when missing", async () => {
104
+ routes["GET /repos/acme/infra/actions/jobs/5"] = { id: 5, run_id: 10, name: "review", status: "completed", conclusion: "success", head_branch: "main", html_url: "https://github.com/acme/infra/actions/runs/10/job/5" };
105
+ expect(await gh().job(5)).toEqual({ id: 5, name: "review", status: "completed", conclusion: "success", done: true, run: 10, ref: "main", url: "https://github.com/acme/infra/actions/runs/10/job/5" });
106
+ expect(await gh().job(6)).toBeUndefined();
107
+ expect(urls()).toEqual(["GET /repos/acme/infra/actions/jobs/5", "GET /repos/acme/infra/actions/jobs/6"]);
108
+ });
109
+
110
+ test("forgejo: a job by id", async () => {
111
+ routes["GET /api/v1/repos/acme/infra/actions/jobs/5"] = { id: 5, run_id: 10, name: "review", status: "running", head_branch: "main", html_url: "https://code.acme.io/acme/infra/actions/runs/3/jobs/0" };
112
+ expect(await fj().job(5)).toEqual({ id: 5, name: "review", status: "running", done: false, run: 10, ref: "main", url: "https://code.acme.io/acme/infra/actions/runs/3/jobs/0" });
113
+ });
114
+
115
+ test("gitlab: a job with its pipeline, ref, tag and URL; a pipeline's jobs with their URLs", async () => {
116
+ routes[`GET ${P}/jobs/5`] = { id: 5, name: "review", status: "success", ref: "main", tag: false, web_url: "https://gitlab.com/acme/infra/-/jobs/5", pipeline: { id: 10, sha: SHA } };
117
+ routes[`GET ${P}/jobs/6`] = { id: 6, name: "plan", status: "failed", ref: "v1", tag: true, pipeline: { id: 11 } };
118
+ expect(await gl().job(5)).toEqual({ id: 5, name: "review", status: "success", done: true, run: 10, ref: "main", tag: false, url: "https://gitlab.com/acme/infra/-/jobs/5" });
119
+ expect(await gl().job(6)).toEqual({ id: 6, name: "plan", status: "failed", done: true, run: 11, ref: "v1", tag: true });
120
+ expect(await gl().job(7)).toBeUndefined();
121
+ routes[`GET ${P}/pipelines/10/jobs`] = [{ id: 4, name: "plan", status: "success", ref: "refs/merge-requests/3/head", tag: false, web_url: "https://gitlab.com/acme/infra/-/jobs/4", pipeline: { id: 10 } }];
122
+ expect(await gl().runJobs(10)).toEqual([{ id: 4, name: "plan", status: "success", done: true, run: 10, ref: "refs/merge-requests/3/head", tag: false, url: "https://gitlab.com/acme/infra/-/jobs/4" }]);
123
+ });
124
+ });
125
+
126
+ describe("a job's artifact file", () => {
127
+ test("gitlab: one file of a job's artifacts as text, each path segment encoded; undefined when there is none", async () => {
128
+ routes[`GET ${P}/jobs/5/artifacts/terragucci-report/plan%20note.md`] = { raw: "## plan\n\nno changes\n" };
129
+ const reads = gl();
130
+ expect(await reads.artifactFile!(5, "terragucci-report/plan note.md")).toBe("## plan\n\nno changes\n");
131
+ expect(await reads.artifactFile!(5, "terragucci-report/status")).toBeUndefined();
132
+ expect(urls()).toEqual([`GET ${P}/jobs/5/artifacts/terragucci-report/plan%20note.md`, `GET ${P}/jobs/5/artifacts/terragucci-report/status`]);
133
+ expect(calls[0]!.headers["private-token"]).toBe("glpat");
134
+ });
135
+
136
+ test("gitlab: another error throws", async () => {
137
+ routes[`GET ${P}/jobs/5/artifacts/r/x`] = 500;
138
+ await expect(gl().artifactFile!(5, "r/x")).rejects.toThrow(/500/);
139
+ });
140
+
141
+ test("github and forgejo hand an artifact out as one archive, so they read no file of one", () => {
142
+ expect(gh().artifactFile).toBeUndefined();
143
+ expect(fj().artifactFile).toBeUndefined();
144
+ });
145
+ });