@intentius/chant-lexicon-terraform 0.124.79 → 0.124.80

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.
@@ -119,6 +119,11 @@
119
119
  * yet makes the member a hole naming it, so the root is never planned on a
120
120
  * stand-in.
121
121
  *
122
+ * - `workspace`: the workspace the root runs in (chant#4854). `init` runs in
123
+ * `default`, then `workspace select -or-create=true` selects it, creating
124
+ * it when the backend does not list it yet, and the plan, apply and
125
+ * output run in it. Such a root plans with `plan`, never as a one-root set.
126
+ *
122
127
  * A wave's run hooks in the product's process (chant#4842) reach the step
123
128
  * through its context. `processEnv` goes to every command for the root (a
124
129
  * role's credentials, values from a secret store), and `afterInit` is
@@ -183,7 +188,7 @@ export interface TerraformApplyStepInput {
183
188
  root: string;
184
189
  /** Input variables, after the root's var files. See `TerraformPlanArgs.vars`. */
185
190
  vars?: Record<string, unknown>;
186
- /** Where the `chant.config.*` search starts. Default: the current directory. */
191
+ /** Where the `chant.config.*` search starts. Default: the directory the caller runs the step in (`DeployContext.cwd`, an op wave's `cwd`, chant#4854), else the current directory. */
187
192
  cwd?: string;
188
193
  /** The root's files from here instead of its entry's `dir` (#4542): a promote under a release sets it to the recorded copy. */
189
194
  dir?: string;
@@ -193,6 +198,49 @@ export interface TerraformApplyStepInput {
193
198
  cone?: string;
194
199
  /** Vars read from other roots' outputs (#4545), Atmos's `!terraform.state`. The step's `vars` win over them. */
195
200
  reads?: TerraformStateRead[];
201
+ /**
202
+ * The workspace the root plans and applies in (chant#4854), such as an
203
+ * Atmos instance's. `init` runs in `default`, then `workspace select
204
+ * -or-create=true` selects it, creating it when the backend does not list
205
+ * it yet, and plan, apply and output run with `TF_WORKSPACE` set to it.
206
+ * Absent: the entry's `workspace`, or the run's environment, as before.
207
+ */
208
+ workspace?: string;
209
+ /**
210
+ * The binary the root runs, a name on `PATH` or a path, in place of
211
+ * `terraform.binary` (terragucci issue 1303): a root that pins its own
212
+ * terraform or tofu release. A product's {@link TerraformRootResolver}
213
+ * sets it per root. Absent: `terraform.binary`, as before.
214
+ */
215
+ binary?: string;
216
+ }
217
+
218
+ /** What a root runs in place of the step's (terragucci issue 1303). An unset field runs the step's. */
219
+ export interface TerraformRootTools {
220
+ /** The binary, a name on `PATH` or a path. See {@link TerraformApplyStepInput.binary}. */
221
+ binary?: string;
222
+ /**
223
+ * The environment a read of this root's state runs with over the job's,
224
+ * when another root's `reads` name it as their upstream (terragucci issue
225
+ * 1303): its role's credentials, never the reader's. The root's own plan
226
+ * and apply take theirs from the run hooks (`DeployContext.processEnv`).
227
+ */
228
+ readEnv?: Record<string, string>;
229
+ }
230
+
231
+ /**
232
+ * What a root runs (terragucci issue 1303), asked once per plan and per
233
+ * apply with the root and the step's input, as `terragrunt-apply`'s
234
+ * `resolveUnit` is asked per unit. A product passes its own, which installs
235
+ * a pinned release and checks its version, so a root runs what it plans
236
+ * with whatever `chant.config.ts` names.
237
+ */
238
+ export type TerraformRootResolver = (root: string, input: TerraformApplyStepInput) => TerraformRootTools | Promise<TerraformRootTools>;
239
+
240
+ /** What {@link terraformApplyCapabilityWith} takes. */
241
+ export interface TerraformApplyDeps {
242
+ /** What each root runs. Default: the step's `binary`, else `terraform.binary`. */
243
+ resolveRoot?: TerraformRootResolver;
196
244
  }
197
245
 
198
246
  /** What `terraform-apply` returns. `outputs` is what a dependent's `stackOutput()` reads. */
@@ -230,13 +278,22 @@ function lockTimeoutOf(input: TerraformApplyStepInput): { lockTimeout?: string }
230
278
  * read once, the values under the step's own `vars`. `waiting` when an
231
279
  * upstream has no such output yet. Throws when a state cannot be read.
232
280
  */
233
- async function withReads(input: TerraformApplyStepInput): Promise<{ input: TerraformApplyStepInput } | { waiting: string; upstreams: string[] }> {
281
+ async function withReads(input: TerraformApplyStepInput, resolveRoot?: TerraformRootResolver): Promise<{ input: TerraformApplyStepInput } | { waiting: string; upstreams: string[] }> {
234
282
  const reads = input.reads ?? [];
235
283
  if (reads.length === 0) return { input };
236
284
  const problems = stateReadsProblems(reads);
237
285
  if (problems.length > 0) throw new Error(`terraform-apply: root "${input.root}": ${problems.join("; ")}`);
238
- const filled = await fillStateReads(reads, async (root) => {
239
- const at = { root, ...(input.cwd ? { cwd: input.cwd } : {}) };
286
+ const filled = await fillStateReads(reads, async (root, read) => {
287
+ // terragucci issue 1303: the upstream's own directory, workspace, binary and environment, as terragucci's upstreamOutputs reads it.
288
+ const tools = resolveRoot ? await resolveRoot(root, { root, ...(input.cwd ? { cwd: input.cwd } : {}), ...(read.dir ? { dir: read.dir } : {}), ...(read.workspace ? { workspace: read.workspace } : {}) }) : undefined;
289
+ const at = {
290
+ root,
291
+ ...(input.cwd ? { cwd: input.cwd } : {}),
292
+ ...(read.dir ? { dir: read.dir } : {}),
293
+ ...(read.workspace ? { workspace: read.workspace } : {}),
294
+ ...(tools?.binary ? { binary: tools.binary } : {}),
295
+ ...(tools?.readEnv ? { env: tools.readEnv } : {}),
296
+ };
240
297
  await terraformInit(at);
241
298
  return terraformOutputs(at);
242
299
  });
@@ -258,12 +315,25 @@ function waitingOnReads(ctx: DeployContext, input: TerraformApplyStepInput, wait
258
315
  /** A run hook's environment (chant#4842, `DeployContext.processEnv`), which every command for the root runs with. */
259
316
  type RunEnv = Record<string, string> | undefined;
260
317
 
261
- const rootArgs = (input: TerraformApplyStepInput, env?: RunEnv) => ({ root: input.root, ...(input.cwd ? { cwd: input.cwd } : {}), ...(input.dir ? { dir: input.dir } : {}), ...(env ? { env } : {}) });
318
+ const rootArgs = (input: TerraformApplyStepInput, env?: RunEnv) => ({
319
+ root: input.root,
320
+ ...(input.cwd ? { cwd: input.cwd } : {}),
321
+ ...(input.dir ? { dir: input.dir } : {}),
322
+ ...(env ? { env } : {}),
323
+ ...(input.workspace ? { workspace: input.workspace } : {}),
324
+ ...(input.binary ? { binary: input.binary } : {}),
325
+ });
262
326
 
263
327
  function requireRoot(input: TerraformApplyStepInput): void {
264
328
  if (typeof input.root !== "string" || input.root === "") {
265
329
  throw new Error('terraform-apply: "root" is required and names an entry in terraform.roots');
266
330
  }
331
+ if (input.workspace !== undefined && (typeof input.workspace !== "string" || input.workspace.trim() === "")) {
332
+ throw new Error(`terraform-apply: root "${input.root}": workspace must name a workspace`);
333
+ }
334
+ if (input.binary !== undefined && (typeof input.binary !== "string" || input.binary.trim() === "")) {
335
+ throw new Error(`terraform-apply: root "${input.root}": binary must name a binary or its path`);
336
+ }
267
337
  }
268
338
 
269
339
  async function planRoot(input: TerraformApplyStepInput, targets?: string[], at: { env?: RunEnv; afterInit?: () => Promise<void> } = {}): Promise<PlannedRoot & { changeSet?: ChangeSetPart; json?: unknown }> {
@@ -399,8 +469,41 @@ function isShapeArtifact(value: unknown): value is TerraformShapeArtifact {
399
469
  return v?.kind === "terraform-apply-shape" && typeof v.digest === "string" && typeof v.shape === "object" && v.shape !== null;
400
470
  }
401
471
 
472
+ /** Each step input core passed, as it was filled (chant#4854, terragucci issue 1303), for the methods core calls with the input alone. */
473
+ const filledInputs = new WeakMap<object, TerraformApplyStepInput>();
474
+
475
+ /**
476
+ * The step's input with `cwd` set to the caller's directory when it names
477
+ * none (chant#4854, `DeployContext.cwd`): an op wave run in process for
478
+ * another directory finds that directory's `chant.config.*`, not the
479
+ * process's. The input core passed is remembered, so `defaultLockGrain`,
480
+ * `lockGrainRefusal` and `traceFacts`, which get the input alone, read the
481
+ * same config.
482
+ */
483
+ export function withContextCwd(ctx: { cwd?: string } | undefined, input: TerraformApplyStepInput): TerraformApplyStepInput {
484
+ if (!input || typeof input !== "object" || input.cwd !== undefined || ctx?.cwd === undefined) return input;
485
+ const filled = { ...input, cwd: ctx.cwd };
486
+ filledInputs.set(input, { ...filledInputs.get(input), ...filled });
487
+ return filled;
488
+ }
489
+
490
+ /** The step's input with `cwd` from the context and what `resolveRoot` answers for the root (terragucci issue 1303), remembered for the input core passed. */
491
+ async function filledInput(resolveRoot: TerraformRootResolver | undefined, ctx: { cwd?: string } | undefined, input: TerraformApplyStepInput): Promise<TerraformApplyStepInput> {
492
+ const at = withContextCwd(ctx, input);
493
+ if (!resolveRoot || !at || typeof at !== "object" || typeof at.root !== "string" || at.root === "") return at;
494
+ const tools = await resolveRoot(at.root, at);
495
+ if (tools?.binary !== undefined && (typeof tools.binary !== "string" || tools.binary.trim() === "")) {
496
+ throw new Error(`terraform-apply: root "${at.root}": the product's resolveRoot answered a binary that names nothing`);
497
+ }
498
+ if (!tools?.binary) return at;
499
+ const filled = { ...at, binary: tools.binary };
500
+ filledInputs.set(input, filled);
501
+ return filled;
502
+ }
503
+
402
504
  /** The root's directory, as `terraform.roots` names it from the nearest `chant.config.*`, and the configured binary. */
403
- async function rootDir(input: TerraformApplyStepInput): Promise<{ dir: string; binary?: string } | undefined> {
505
+ async function rootDir(given: TerraformApplyStepInput): Promise<{ dir: string; binary?: string } | undefined> {
506
+ const input = filledInputs.get(given) ?? given;
404
507
  const start = resolve(input.cwd ?? process.cwd());
405
508
  const { config, configPath } = await loadChantConfigUpward(start);
406
509
  const terraform = (config as { terraform?: TerraformConfig }).terraform;
@@ -408,7 +511,8 @@ async function rootDir(input: TerraformApplyStepInput): Promise<{ dir: string; b
408
511
  const declared = terraform?.roots?.[input.root]?.dir ?? input.dir;
409
512
  if (declared === undefined) return undefined;
410
513
  const dir = input.dir ?? declared;
411
- return { dir: resolve(configPath ? dirname(configPath) : start, dir), ...(terraform?.binary ? { binary: terraform.binary } : {}) };
514
+ const binary = input.binary ?? terraform?.binary;
515
+ return { dir: resolve(configPath ? dirname(configPath) : start, dir), ...(binary ? { binary } : {}) };
412
516
  }
413
517
 
414
518
  const firstLines = (err: unknown): string => {
@@ -541,8 +645,8 @@ async function runChoudoufuWave(
541
645
  }
542
646
 
543
647
  /** The input a `run` that plans for itself plans with (#4545): its reads filled, or an error naming the upstream to apply first. */
544
- async function readsForRun(input: TerraformApplyStepInput): Promise<TerraformApplyStepInput> {
545
- const read = await withReads(input);
648
+ async function readsForRun(input: TerraformApplyStepInput, resolveRoot?: TerraformRootResolver): Promise<TerraformApplyStepInput> {
649
+ const read = await withReads(input, resolveRoot);
546
650
  if ("waiting" in read) throw new Error(`terraform-apply: root "${input.root}": ${read.waiting}`);
547
651
  return read.input;
548
652
  }
@@ -555,132 +659,154 @@ async function plannerOf(input: TerraformApplyStepInput, plan?: CapabilityPlan):
555
659
  return planner === "terraform" || planner === "tofu" || planner === "choudoufu" ? planner : "terraform";
556
660
  }
557
661
 
558
- export const terraformApplyCapability: Capability<TerraformApplyStepInput, TerraformApplyStepOutput> = {
559
- kind: "terraform-apply",
560
- // A root's apply has no undo short of applying the previous configuration,
561
- // which is a change of its own. COMP003 asks the component to say so.
562
- rollbackPolicy: "needs-opt-out",
563
- // #4300: `--target` passes through as `-target`, and the saved plan holds those addresses alone.
564
- targets: "accept",
565
- // #4627: `plan` refreshes the root's state before it plans unless told `-refresh=false`, which chant never passes,
566
- // so `--refresh` asks for what every plan does and the digest still binds it. `-target` plans a resource with what it
567
- // depends on and never what depends on it, so `--target-dependents` has nothing to map onto.
568
- planFlags: {
569
- refresh: "accept",
570
- targetDependents: { refuse: "terraform and tofu plan a -target with what it depends on, never what depends on it, so there is no flag to widen it to its dependents; name each dependent with --target" },
571
- },
572
- async plan(ctx: DeployContext, given: TerraformApplyStepInput): Promise<CapabilityPlan> {
573
- requireRoot(given);
574
- // #4545: a root reading an upstream's output that is not there yet is a hole naming the upstream.
575
- const read = await withReads(given);
576
- if ("waiting" in read) return waitingOnReads(ctx, given, read);
577
- const { input } = read;
578
- const unresolved = [...(ctx.unresolvedInputs ?? [])].sort();
579
- const targets = ctx.targets && ctx.targets.length > 0 ? ctx.targets : undefined;
580
- if (unresolved.length > 0) return previewRoot(ctx, input, unresolved, targets);
581
- // A targeted root plans with `plan -target`, and a cone plan with `plan -cone` (#4545), never as a choudoufu one-root set.
582
- const env = ctx.processEnv;
583
- const wave = targets || input.cone ? { wave: false } : await choudoufuWaveRoot({ ...rootArgs(input, env), ...(input.vars ? { vars: input.vars } : {}) });
584
- if (wave.wave) {
585
- // chant#4842: live-plan-set inits and plans in one command, so the run hook's check comes before it.
586
- await ctx.afterInit?.();
587
- const set = await choudoufuPlanSet(rootArgs(input, env));
588
- const artifact: ChoudoufuWavePlannedRoot = {
589
- planDigest: set.planDigest,
590
- choudoufu: { planSetFile: set.planSetFile, setDigest: set.setDigest },
591
- lockRows: terraformLockRows(input.root, set.changeSet.member.scope, set.json),
662
+ /**
663
+ * `terraform-apply` with `deps` in place of the defaults (terragucci issue
664
+ * 1303). `resolveRoot` answers what each root runs, so a product whose roots
665
+ * pin their own releases passes its resolver, as it passes `resolveUnit` to
666
+ * `terragruntApplyCapability`. A composed group (`together`) runs the
667
+ * project's binary, as before.
668
+ */
669
+ export function terraformApplyCapabilityWith(deps: TerraformApplyDeps = {}): Capability<TerraformApplyStepInput, TerraformApplyStepOutput> {
670
+ return {
671
+ kind: "terraform-apply",
672
+ // A root's apply has no undo short of applying the previous configuration,
673
+ // which is a change of its own. COMP003 asks the component to say so.
674
+ rollbackPolicy: "needs-opt-out",
675
+ // #4300: `--target` passes through as `-target`, and the saved plan holds those addresses alone.
676
+ targets: "accept",
677
+ // #4627: `plan` refreshes the root's state before it plans unless told `-refresh=false`, which chant never passes,
678
+ // so `--refresh` asks for what every plan does and the digest still binds it. `-target` plans a resource with what it
679
+ // depends on and never what depends on it, so `--target-dependents` has nothing to map onto.
680
+ planFlags: {
681
+ refresh: "accept",
682
+ targetDependents: { refuse: "terraform and tofu plan a -target with what it depends on, never what depends on it, so there is no flag to widen it to its dependents; name each dependent with --target" },
683
+ },
684
+ async plan(ctx: DeployContext, step: TerraformApplyStepInput): Promise<CapabilityPlan> {
685
+ const given = await filledInput(deps.resolveRoot, ctx, step);
686
+ requireRoot(given);
687
+ // #4545: a root reading an upstream's output that is not there yet is a hole naming the upstream.
688
+ const read = await withReads(given, deps.resolveRoot);
689
+ if ("waiting" in read) return waitingOnReads(ctx, given, read);
690
+ const { input } = read;
691
+ const unresolved = [...(ctx.unresolvedInputs ?? [])].sort();
692
+ const targets = ctx.targets && ctx.targets.length > 0 ? ctx.targets : undefined;
693
+ if (unresolved.length > 0) return previewRoot(ctx, input, unresolved, targets);
694
+ // A targeted root plans with `plan -target`, and a cone plan with `plan -cone` (#4545), never as a choudoufu one-root set.
695
+ const env = ctx.processEnv;
696
+ const wave = targets || input.cone ? { wave: false } : await choudoufuWaveRoot({ ...rootArgs(input, env), ...(input.vars ? { vars: input.vars } : {}) });
697
+ if (wave.wave) {
698
+ // chant#4842: live-plan-set inits and plans in one command, so the run hook's check comes before it.
699
+ await ctx.afterInit?.();
700
+ const set = await choudoufuPlanSet(rootArgs(input, env));
701
+ const artifact: ChoudoufuWavePlannedRoot = {
702
+ planDigest: set.planDigest,
703
+ choudoufu: { planSetFile: set.planSetFile, setDigest: set.setDigest },
704
+ lockRows: terraformLockRows(input.root, set.changeSet.member.scope, set.json),
705
+ };
706
+ return { member: input.root, planDigest: set.planDigest, artifact, changeSet: set.changeSet, outputs: terraformPlannedOutputs(set.json), shape: terraformPlanShape(set.json, input.root) };
707
+ }
708
+ const { changeSet, json, ...planned } = await planRoot(input, targets, { env, ...(ctx.afterInit ? { afterInit: ctx.afterInit } : {}) });
709
+ // #4552: a choudoufu root's rows, keyed from the plan document while it is at hand.
710
+ const lockRows = changeSet?.member.planner === "choudoufu" ? terraformLockRows(input.root, changeSet.member.scope, json) : undefined;
711
+ return {
712
+ member: input.root,
713
+ planDigest: planned.planDigest,
714
+ artifact: { ...planned, ...(lockRows ? { lockRows } : {}) },
715
+ ...(changeSet ? { changeSet } : {}),
716
+ // plywood#55: each changed resource's own digest, which a merged wave compares with the pull request's per resource.
717
+ resourceDigests: terraformResourceDigests(json),
718
+ outputs: terraformPlannedOutputs(json),
719
+ shape: terraformPlanShape(json, input.root),
720
+ ...(targets ? { targets } : {}),
592
721
  };
593
- return { member: input.root, planDigest: set.planDigest, artifact, changeSet: set.changeSet, outputs: terraformPlannedOutputs(set.json), shape: terraformPlanShape(set.json, input.root) };
594
- }
595
- const { changeSet, json, ...planned } = await planRoot(input, targets, { env, ...(ctx.afterInit ? { afterInit: ctx.afterInit } : {}) });
596
- // #4552: a choudoufu root's rows, keyed from the plan document while it is at hand.
597
- const lockRows = changeSet?.member.planner === "choudoufu" ? terraformLockRows(input.root, changeSet.member.scope, json) : undefined;
598
- return {
599
- member: input.root,
600
- planDigest: planned.planDigest,
601
- artifact: { ...planned, ...(lockRows ? { lockRows } : {}) },
602
- ...(changeSet ? { changeSet } : {}),
603
- // plywood#55: each changed resource's own digest, which a merged wave compares with the pull request's per resource.
604
- resourceDigests: terraformResourceDigests(json),
605
- outputs: terraformPlannedOutputs(json),
606
- shape: terraformPlanShape(json, input.root),
607
- ...(targets ? { targets } : {}),
608
- };
609
- },
610
- // The root's outputs as its state holds them now (#3183): what a dependent
611
- // planned before this root applies reads through `stackOutput()`.
612
- async outputs(ctx: DeployContext, input: TerraformApplyStepInput): Promise<Record<string, unknown>> {
613
- requireRoot(input);
614
- await terraformInit(rootArgs(input, ctx.processEnv));
615
- return terraformOutputs(rootArgs(input, ctx.processEnv));
616
- },
617
- // #4447 (ws-107): a group core forms of components that read each other plans and applies as one composed run
618
- // when `terraform.compose.enabled` is set (./compose-group.ts). Delegates, so the methods are read when called.
619
- groupReads: (ctx, members) => terraformComposeGroup.groupReads(ctx, members),
620
- // #4542: a member pointed at a release's recorded copy plans alone, since a composition reads the declared roots.
621
- groupFallback: async (ctx, members) =>
622
- members.some((m) => typeof m.step.dir === "string")
623
- ? { kind: "release-copy", reason: "a member deploys a release's recorded copy of its root, which a composition does not read" }
624
- : terraformComposeGroup.groupFallback(ctx, members),
625
- // #4542: the root's files, which a release cut records and a promote under it plans.
626
- releaseInputs: (input, ctx) => terraformReleaseInputs(input, ctx),
627
- // #4552: resource under choudoufu, the root under Terraform, tofu and Terragrunt, which refuse resource by name.
628
- async defaultLockGrain(input, plan) {
629
- return terraformDefaultLockGrain(await plannerOf(input, plan));
630
- },
631
- async lockGrainRefusal(input, grain, plan) {
632
- if (grain !== "resource") return undefined;
633
- const binary = (await rootDir(input).catch(() => undefined))?.binary;
634
- return terraformLockGrainRefusal(grain, await plannerOf(input, plan), binary);
635
- },
636
- // The ruling for ci-products (2026-10-28): a Terraform, tofu or Terragrunt root waits for its root row on the ledger in place of
637
- // the backend's lock. A choudoufu root stays on the resource grain and never asks for this row.
638
- targetLockRow(input) {
639
- return typeof input?.root === "string" && input.root !== "" ? { key: rootRowKey(input.root), target: input.root, address: input.root } : undefined;
640
- },
641
- lockRows(input, plan) {
642
- const kept = (plan.artifact as { lockRows?: LockRow[] } | undefined)?.lockRows;
643
- if (Array.isArray(kept)) return kept;
644
- return plan.changeSet ? terraformLockRowsFromPart(input.root, plan.changeSet) : [];
645
- },
646
- // #4555: the root and the binary, for the step's span and run record.
647
- traceFacts: async (input, outcome) => terraformTraceFacts(input, outcome, (await rootDir(input).catch(() => undefined))?.binary),
648
- planGroup: (ctx, members) => terraformComposeGroup.planGroup(ctx, members),
649
- runGroup: (ctx, run, members) => terraformComposeGroup.runGroup(ctx, run, members),
650
- async run(ctx: DeployContext, input: TerraformApplyStepInput): Promise<TerraformApplyStepOutput> {
651
- const fromWave = ctx.plans?.[input.root];
652
- if (isChoudoufuWavePlan(fromWave)) return runChoudoufuWave(ctx, input, fromWave);
653
- if (isShapeArtifact(fromWave)) {
654
- // A root previewed with stand-ins (#4463): plan it now with the real
655
- // values, and apply that plan only when it is within the preview's shape.
656
- const fresh = await planRoot(await readsForRun(input), ctx.targets, { env: ctx.processEnv });
657
- const differences = planShapeDifferences(fromWave.shape, terraformPlanShape(fresh.json, input.root));
658
- if (differences.length > 0) throw new PlanShapeMovedError(input.root, differences);
659
- const applied = await terraformApply({ ...rootArgs(input, ctx.processEnv), planFile: fresh.planFile, ...lockTimeoutOf(input) });
722
+ },
723
+ // The root's outputs as its state holds them now (#3183): what a dependent
724
+ // planned before this root applies reads through `stackOutput()`.
725
+ async outputs(ctx: DeployContext, step: TerraformApplyStepInput): Promise<Record<string, unknown>> {
726
+ const input = await filledInput(deps.resolveRoot, ctx, step);
727
+ requireRoot(input);
728
+ await terraformInit(rootArgs(input, ctx.processEnv));
729
+ return terraformOutputs(rootArgs(input, ctx.processEnv));
730
+ },
731
+ // #4447 (ws-107): a group core forms of components that read each other plans and applies as one composed run
732
+ // when `terraform.compose.enabled` is set (./compose-group.ts). Delegates, so the methods are read when called.
733
+ groupReads: (ctx, members) => terraformComposeGroup.groupReads(ctx, members),
734
+ // #4542: a member pointed at a release's recorded copy plans alone, since a composition reads the declared roots.
735
+ groupFallback: async (ctx, members) =>
736
+ members.some((m) => typeof m.step.dir === "string")
737
+ ? { kind: "release-copy", reason: "a member deploys a release's recorded copy of its root, which a composition does not read" }
738
+ : terraformComposeGroup.groupFallback(ctx, members),
739
+ // #4542: the root's files, which a release cut records and a promote under it plans.
740
+ releaseInputs: (input, ctx) => terraformReleaseInputs(input, ctx),
741
+ // #4552: resource under choudoufu, the root under Terraform, tofu and Terragrunt, which refuse resource by name.
742
+ async defaultLockGrain(input, plan) {
743
+ return terraformDefaultLockGrain(await plannerOf(input, plan));
744
+ },
745
+ async lockGrainRefusal(input, grain, plan) {
746
+ if (grain !== "resource") return undefined;
747
+ const binary = (await rootDir(input).catch(() => undefined))?.binary;
748
+ return terraformLockGrainRefusal(grain, await plannerOf(input, plan), binary);
749
+ },
750
+ // The ruling for ci-products (2026-10-28): a Terraform, tofu or Terragrunt root waits for its root row on the ledger in place of
751
+ // the backend's lock. A choudoufu root stays on the resource grain and never asks for this row.
752
+ targetLockRow(input) {
753
+ return typeof input?.root === "string" && input.root !== "" ? { key: rootRowKey(input.root), target: input.root, address: input.root } : undefined;
754
+ },
755
+ lockRows(input, plan) {
756
+ const kept = (plan.artifact as { lockRows?: LockRow[] } | undefined)?.lockRows;
757
+ if (Array.isArray(kept)) return kept;
758
+ return plan.changeSet ? terraformLockRowsFromPart(input.root, plan.changeSet) : [];
759
+ },
760
+ // #4555: the root and the binary, for the step's span and run record.
761
+ traceFacts: async (input, outcome) => terraformTraceFacts(input, outcome, (await rootDir(input).catch(() => undefined))?.binary),
762
+ planGroup: (ctx, members) => {
763
+ // chant#4854: each member's lock grain reads the config at the wave's directory too.
764
+ for (const m of members) if (m.input) withContextCwd(m.ctx ?? ctx, m.input);
765
+ return terraformComposeGroup.planGroup(ctx, members);
766
+ },
767
+ runGroup: (ctx, run, members) => {
768
+ for (const m of members) if (m.input) withContextCwd(m.ctx ?? ctx, m.input);
769
+ return terraformComposeGroup.runGroup(ctx, run, members);
770
+ },
771
+ async run(ctx: DeployContext, step: TerraformApplyStepInput): Promise<TerraformApplyStepOutput> {
772
+ const input = await filledInput(deps.resolveRoot, ctx, step);
773
+ const fromWave = ctx.plans?.[input.root];
774
+ if (isChoudoufuWavePlan(fromWave)) return runChoudoufuWave(ctx, input, fromWave);
775
+ if (isShapeArtifact(fromWave)) {
776
+ // A root previewed with stand-ins (#4463): plan it now with the real
777
+ // values, and apply that plan only when it is within the preview's shape.
778
+ const fresh = await planRoot(await readsForRun(input, deps.resolveRoot), ctx.targets, { env: ctx.processEnv });
779
+ const differences = planShapeDifferences(fromWave.shape, terraformPlanShape(fresh.json, input.root));
780
+ if (differences.length > 0) throw new PlanShapeMovedError(input.root, differences);
781
+ const applied = await terraformApply({ ...rootArgs(input, ctx.processEnv), planFile: fresh.planFile, ...lockTimeoutOf(input) });
782
+ if (!applied.applied) {
783
+ throw new Error(`terraform-apply: root "${input.root}" refused the plan it was given (${applied.refused ?? "refused"}). ${applied.refusal ?? ""}`);
784
+ }
785
+ const outputs = await terraformOutputs(rootArgs(input, ctx.processEnv));
786
+ return { root: input.root, planDigest: fresh.planDigest, fromWavePlan: false, outputs };
787
+ }
788
+ const planned: PlannedRoot = isPlannedRoot(fromWave)
789
+ ? fromWave
790
+ : await planRoot(await readsForRun(input, deps.resolveRoot), ctx.targets, { env: ctx.processEnv }).then(({ planFile, planDigest }) => ({ planFile, planDigest }));
791
+ const applied = await terraformApply({ ...rootArgs(input, ctx.processEnv), planFile: planned.planFile, ...lockTimeoutOf(input) });
660
792
  if (!applied.applied) {
661
- throw new Error(`terraform-apply: root "${input.root}" refused the plan it was given (${applied.refused ?? "refused"}). ${applied.refusal ?? ""}`);
793
+ const message =
794
+ `terraform-apply: root "${input.root}" refused the plan it was given (${applied.refused ?? "refused"}). ` +
795
+ (applied.refusal ?? "");
796
+ // A plan the wave approved that choudoufu refuses as no longer matching
797
+ // moved since the approval (#4553: one made against another estate is a
798
+ // failure). One this run made itself is planned afresh by the next run.
799
+ if (applied.refused === "approval-mismatch" && isPlannedRoot(fromWave)) throw new TerraformPlanMovedError(input.root, message);
800
+ throw new Error(message);
662
801
  }
663
802
  const outputs = await terraformOutputs(rootArgs(input, ctx.processEnv));
664
- return { root: input.root, planDigest: fresh.planDigest, fromWavePlan: false, outputs };
665
- }
666
- const planned: PlannedRoot = isPlannedRoot(fromWave)
667
- ? fromWave
668
- : await planRoot(await readsForRun(input), ctx.targets, { env: ctx.processEnv }).then(({ planFile, planDigest }) => ({ planFile, planDigest }));
669
- const applied = await terraformApply({ ...rootArgs(input, ctx.processEnv), planFile: planned.planFile, ...lockTimeoutOf(input) });
670
- if (!applied.applied) {
671
- const message =
672
- `terraform-apply: root "${input.root}" refused the plan it was given (${applied.refused ?? "refused"}). ` +
673
- (applied.refusal ?? "");
674
- // A plan the wave approved that choudoufu refuses as no longer matching
675
- // moved since the approval (#4553: one made against another estate is a
676
- // failure). One this run made itself is planned afresh by the next run.
677
- if (applied.refused === "approval-mismatch" && isPlannedRoot(fromWave)) throw new TerraformPlanMovedError(input.root, message);
678
- throw new Error(message);
679
- }
680
- const outputs = await terraformOutputs(rootArgs(input, ctx.processEnv));
681
- return { root: input.root, planDigest: planned.planDigest, fromWavePlan: isPlannedRoot(fromWave), outputs };
682
- },
683
- };
803
+ return { root: input.root, planDigest: planned.planDigest, fromWavePlan: isPlannedRoot(fromWave), outputs };
804
+ },
805
+ };
806
+ }
807
+
808
+ /** `terraform-apply` with each root on the step's `binary`, else `terraform.binary`. */
809
+ export const terraformApplyCapability: Capability<TerraformApplyStepInput, TerraformApplyStepOutput> = terraformApplyCapabilityWith();
684
810
 
685
811
  export const TERRAFORM_VERB_FAMILIES = {
686
812
  apply: ["terraform-apply"],
@@ -103,7 +103,8 @@ interface ComposedArtifact {
103
103
  /** What the group methods use, each replaceable in a test. */
104
104
  export interface ComposeGroupDeps {
105
105
  /** The project's config. Default: `loadChantConfigUpward` from the current directory. */
106
- project?: () => Promise<ComposeProject>;
106
+ /** The project at the group's directory (`GroupContext.cwd`, chant#4854), else at `process.cwd()`. */
107
+ project?: (cwd?: string) => Promise<ComposeProject>;
107
108
  /** The run for a composition. Default: `EstateRun` when `estate` is set, else `ComposedRun`. */
108
109
  runner?: (o: GroupRunnerOptions) => ComposedRunner;
109
110
  /**
@@ -128,8 +129,8 @@ export interface ComposeGroupMethods {
128
129
  runGroup(ctx: GroupContext, run: GroupRun, members: readonly GroupMember<StepInput>[]): Promise<CapabilityGroupOutcome>;
129
130
  }
130
131
 
131
- async function loadProject(): Promise<ComposeProject> {
132
- const start = resolve(process.cwd());
132
+ async function loadProject(cwd?: string): Promise<ComposeProject> {
133
+ const start = resolve(cwd ?? process.cwd());
133
134
  const { config, configPath } = await loadChantConfigUpward(start);
134
135
  const projectRoot = configPath ? dirname(configPath) : start;
135
136
  const terraform = (config as { terraform?: TerraformConfig }).terraform;
@@ -369,7 +370,7 @@ export function composeGroup(deps: ComposeGroupDeps = {}): ComposeGroupMethods {
369
370
 
370
371
  /** The composition the group plans as, or throws when it does not compose. */
371
372
  async function composed(ctx: GroupContext, members: readonly GroupMember<StepInput>[]): Promise<{ p: ComposeProject; c: Composition }> {
372
- const p = await project();
373
+ const p = await project(ctx.cwd);
373
374
  const off = composeOff(p.terraform);
374
375
  if (off) throw new Error(off.reason);
375
376
  const c = await compositionOf(ctx, p, members);
@@ -403,14 +404,14 @@ export function composeGroup(deps: ComposeGroupDeps = {}): ComposeGroupMethods {
403
404
  }
404
405
 
405
406
  return {
406
- async groupReads(_ctx, members) {
407
- const p = await project();
407
+ async groupReads(ctx, members) {
408
+ const p = await project(ctx.cwd);
408
409
  if (composeOff(p.terraform)) return [];
409
410
  return hclGroupReads(p, members);
410
411
  },
411
412
 
412
413
  async groupFallback(ctx, members) {
413
- const p = await project();
414
+ const p = await project(ctx.cwd);
414
415
  const off = composeOff(p.terraform);
415
416
  if (off) return { kind: off.kind, reason: off.reason };
416
417
  const c = await compositionOf(ctx, p, members);