@intentius/chant 0.70.0 → 0.71.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/dist/cli/handlers/fan-out.d.ts +45 -0
  2. package/dist/cli/handlers/fan-out.d.ts.map +1 -0
  3. package/dist/cli/handlers/lifecycle.d.ts +13 -0
  4. package/dist/cli/handlers/lifecycle.d.ts.map +1 -1
  5. package/dist/cli/handlers/operator.d.ts.map +1 -1
  6. package/dist/cli/handlers/run.d.ts +35 -0
  7. package/dist/cli/handlers/run.d.ts.map +1 -1
  8. package/dist/cli/main.d.ts.map +1 -1
  9. package/dist/cli/registry.d.ts +23 -0
  10. package/dist/cli/registry.d.ts.map +1 -1
  11. package/dist/components/deploy-units.d.ts +12 -2
  12. package/dist/components/deploy-units.d.ts.map +1 -1
  13. package/dist/components/fan-out-output.d.ts +70 -0
  14. package/dist/components/fan-out-output.d.ts.map +1 -0
  15. package/dist/components/fan-out-run.d.ts +80 -0
  16. package/dist/components/fan-out-run.d.ts.map +1 -0
  17. package/dist/components/fan-out-support.d.ts +65 -0
  18. package/dist/components/fan-out-support.d.ts.map +1 -0
  19. package/dist/components/fan-out.d.ts +194 -0
  20. package/dist/components/fan-out.d.ts.map +1 -0
  21. package/dist/components/index.d.ts +4 -0
  22. package/dist/components/index.d.ts.map +1 -1
  23. package/dist/discovery/fold-import.d.ts +96 -1
  24. package/dist/discovery/fold-import.d.ts.map +1 -1
  25. package/dist/discovery/index.d.ts.map +1 -1
  26. package/dist/fold/subset.d.ts +22 -0
  27. package/dist/fold/subset.d.ts.map +1 -1
  28. package/dist/index.d.ts +2 -0
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/lifecycle/affected.d.ts +26 -0
  31. package/dist/lifecycle/affected.d.ts.map +1 -1
  32. package/dist/op/activities/activity-contracts.d.ts +16 -1
  33. package/dist/op/activities/activity-contracts.d.ts.map +1 -1
  34. package/dist/op/activities/index.d.ts +1 -1
  35. package/dist/op/activities/index.d.ts.map +1 -1
  36. package/dist/op/activities/shell.d.ts +31 -2
  37. package/dist/op/activities/shell.d.ts.map +1 -1
  38. package/dist/op/activity-contract.d.ts +1 -1
  39. package/dist/op/activity-contract.d.ts.map +1 -1
  40. package/dist/op/activity-profiles.d.ts +19 -0
  41. package/dist/op/activity-profiles.d.ts.map +1 -1
  42. package/dist/op/builders.d.ts +21 -3
  43. package/dist/op/builders.d.ts.map +1 -1
  44. package/dist/op/gate-name.d.ts +10 -0
  45. package/dist/op/gate-name.d.ts.map +1 -1
  46. package/dist/op/step-output-ref.d.ts +25 -8
  47. package/dist/op/step-output-ref.d.ts.map +1 -1
  48. package/package.json +1 -1
  49. package/src/cli/handlers/fan-out.test.ts +394 -0
  50. package/src/cli/handlers/fan-out.ts +336 -0
  51. package/src/cli/handlers/lifecycle.test.ts +74 -1
  52. package/src/cli/handlers/lifecycle.ts +29 -1
  53. package/src/cli/handlers/operator.test.ts +22 -0
  54. package/src/cli/handlers/operator.ts +11 -3
  55. package/src/cli/handlers/run.ts +7 -1
  56. package/src/cli/main.ts +25 -3
  57. package/src/cli/registry.ts +23 -0
  58. package/src/components/deploy-units.ts +14 -4
  59. package/src/components/fan-out-output.test.ts +216 -0
  60. package/src/components/fan-out-output.ts +162 -0
  61. package/src/components/fan-out-run.test.ts +194 -0
  62. package/src/components/fan-out-run.ts +221 -0
  63. package/src/components/fan-out-support.test.ts +125 -0
  64. package/src/components/fan-out-support.ts +95 -0
  65. package/src/components/fan-out.test.ts +284 -0
  66. package/src/components/fan-out.ts +421 -0
  67. package/src/components/index.ts +33 -0
  68. package/src/discovery/fold-import.ts +195 -5
  69. package/src/discovery/index.ts +13 -5
  70. package/src/fold/subset-public-export.test.ts +31 -0
  71. package/src/fold/subset.ts +23 -0
  72. package/src/index.ts +18 -0
  73. package/src/lifecycle/affected.test.ts +118 -0
  74. package/src/lifecycle/affected.ts +118 -14
  75. package/src/op/activities/activity-contracts.ts +17 -1
  76. package/src/op/activities/index.ts +1 -1
  77. package/src/op/activities/shell.test.ts +156 -0
  78. package/src/op/activities/shell.ts +84 -9
  79. package/src/op/activity-profiles.test.ts +16 -2
  80. package/src/op/activity-profiles.ts +18 -0
  81. package/src/op/builders.ts +22 -4
  82. package/src/op/gate-name.ts +11 -0
  83. package/src/op/op-ir.test.ts +4 -1
  84. package/src/op/op.test.ts +7 -2
  85. package/src/op/step-output-ref.ts +29 -8
@@ -15,8 +15,19 @@
15
15
  * be judged from a source diff — reported as **indeterminate**, not silently
16
16
  * included or excluded.
17
17
  *
18
- * This returns the set; it does not act. Fanning `lifecycle plan` / `ApplyOp`
19
- * over it is an Op the user composes.
18
+ * ## What "stack" means here depends on the project
19
+ *
20
+ * A project that declares `stacks` in `chant.config.ts` gets each declared
21
+ * stack's own source built, and the answer names stacks. A single-root project
22
+ * has no such partition to build, so its answer names lexicon partitions, which
23
+ * is the only granularity it has. The difference matters downstream: a
24
+ * component's deploy step names a stack, so only the first kind of answer can
25
+ * be joined to components (#2420).
26
+ *
27
+ * This returns the set; it does not act. `chant components fan-out`
28
+ * (../cli/handlers/fan-out.ts) is the command that acts on it, and fanning
29
+ * `lifecycle plan` / `ApplyOp` over it by hand is still an Op the user
30
+ * composes.
20
31
  */
21
32
  import { execFile } from "node:child_process";
22
33
  import { promisify } from "node:util";
@@ -140,10 +151,92 @@ async function withWorktree<T>(repoRoot: string, ref: string, fn: (dir: string)
140
151
  }
141
152
  }
142
153
 
154
+ /** One independently-deployed stack, as `ChantConfig.stacks` declares it. */
155
+ export interface StackSource {
156
+ /** The deployed stack name — what a component's deploy step names. */
157
+ name: string;
158
+ /** Source directory to build for this stack, relative to the project root. */
159
+ src: string;
160
+ }
161
+
162
+ /**
163
+ * Build each declared stack's own source directory and key the result by
164
+ * **stack name**.
165
+ *
166
+ * Without this, one build of the project root produces a map keyed by lexicon
167
+ * partition, so an aws-only estate of fifteen stacks answers "aws changed" no
168
+ * matter which one moved. That answer cannot be joined to anything: a
169
+ * component's deploy step names a stack, not a lexicon, so
170
+ * `componentsForUnits` (../components/fan-out.ts) would claim none of it and
171
+ * a fan-out derived from it would be empty. The two halves have to speak the
172
+ * same names for either to be worth having.
173
+ *
174
+ * A stack that serializes through more than one lexicon folds its partitions
175
+ * into one artifact, because the unit being deployed is the stack.
176
+ */
177
+ async function stackArtifacts(
178
+ root: string,
179
+ serializers: Serializer[],
180
+ stacks: readonly StackSource[],
181
+ /**
182
+ * Whether a missing `src` is an error. True for the head side, where every
183
+ * declared stack must exist; false for the base side, where a stack added
184
+ * since then legitimately has no source yet and reads as an empty artifact,
185
+ * which is what makes it `changed`.
186
+ */
187
+ requireSrc: boolean,
188
+ ): Promise<{ artifacts: Map<string, string>; externalInput: string[] }> {
189
+ const artifacts = new Map<string, string>();
190
+ const externalInput: string[] = [];
191
+ for (const stack of stacks) {
192
+ const src = resolve(root, stack.src);
193
+ // `build()` on a directory that is not there returns empty outputs rather
194
+ // than throwing, so a typo in `src` would make both sides build nothing,
195
+ // match, and report the stack as unchanged forever. A silent answer of
196
+ // exactly that shape is what this whole path exists to prevent.
197
+ if (requireSrc && !existsSync(src)) {
198
+ throw new Error(
199
+ `stack "${stack.name}" declares src "${stack.src}", which does not exist under ${root}. ` +
200
+ `Fix chant.config.ts's stacks[] entry: a source directory that is not there builds to nothing, ` +
201
+ `and a stack that builds to nothing can never be reported as changed.`,
202
+ );
203
+ }
204
+ const built = await build(src, serializers);
205
+ artifacts.set(
206
+ stack.name,
207
+ [...built.outputs.entries()]
208
+ .sort(([a], [b]) => a.localeCompare(b))
209
+ .map(([lexicon, output]) => `${lexicon}\n${getPrimaryOutput(output as string)}`)
210
+ .join("\n"),
211
+ );
212
+ if (externalInputStacks(built.entities).length > 0) externalInput.push(stack.name);
213
+ }
214
+ return { artifacts, externalInput: externalInput.sort() };
215
+ }
216
+
143
217
  export interface AffectedStacksOptions {
144
218
  /** Project source directory to scope (the head/working-tree build root). */
145
219
  projectPath: string;
146
220
  serializers: Serializer[];
221
+ /**
222
+ * The project's independently-deployed stacks (`ChantConfig.stacks`). With
223
+ * them, each stack's own source is built and the answer names stacks; without
224
+ * them, one build of `projectPath` answers by lexicon partition, which is the
225
+ * only granularity a single-root project has.
226
+ *
227
+ * `dependents` is always empty in this mode, and that is not an omission: the
228
+ * build holds cross-*lexicon* edges, and the relation between two deployed
229
+ * stacks is stated by a component's `dependsOn` and `stackOutput`, which
230
+ * `chant components fan-out` walks for itself. Inventing stack edges from
231
+ * lexicon ones would be a guess dressed as a graph.
232
+ *
233
+ * Each `src` resolves against `projectPath`, so in this mode `projectPath`
234
+ * has to be the project root that `ChantConfig.stacks` is written relative
235
+ * to. A `sourceDir` that narrows the build root does not apply here: the
236
+ * stacks already say which source belongs to which of them, which is the
237
+ * narrowing, and applying both would look for `<sourceDir>/<stack.src>`.
238
+ */
239
+ stacks?: readonly StackSource[];
147
240
  /** Base git ref to diff against (built in a throwaway worktree). */
148
241
  baseRef?: string;
149
242
  /** Head git ref. Defaults to the working tree (built in place — no worktree). */
@@ -175,28 +268,39 @@ export async function affectedStacks(opts: AffectedStacksOptions): Promise<Affec
175
268
  // Head: the in-place build of the working tree, unless an explicit headRef is
176
269
  // given (then a throwaway worktree — removed before the base worktree, so at
177
270
  // most one exists at a time).
271
+ const perStack = opts.stacks && opts.stacks.length > 0 ? opts.stacks : undefined;
272
+ // No cross-stack graph in per-stack mode, by construction: see `stacks` above.
273
+ const EMPTY_GRAPH: StackGraph = { nodes: [], edges: [], order: [], waves: [], cycles: [] };
274
+ /** One build root in, its artifact map and external-input set out, at whichever granularity applies. */
275
+ const readArtifacts = async (
276
+ root: string,
277
+ isHead: boolean,
278
+ ): Promise<{ artifacts: Map<string, string>; externalInput: string[]; graph: StackGraph }> => {
279
+ if (perStack) return { ...(await stackArtifacts(root, opts.serializers, perStack, isHead)), graph: EMPTY_GRAPH };
280
+ const built = await build(root, opts.serializers);
281
+ return {
282
+ artifacts: artifactMap(built.outputs),
283
+ externalInput: externalInputStacks(built.entities),
284
+ graph: built.manifest.stackGraph,
285
+ };
286
+ };
287
+
178
288
  const head = opts.headRef
179
- ? await withWorktree(repoRoot, opts.headRef, (dir) => build(join(dir, relProject), opts.serializers))
180
- : await build(projectPath, opts.serializers);
181
- const headMap = artifactMap(head.outputs);
182
- const externalInput = externalInputStacks(head.entities);
289
+ ? await withWorktree(repoRoot, opts.headRef, (dir) => readArtifacts(join(dir, relProject), true))
290
+ : await readArtifacts(projectPath, true);
183
291
 
184
292
  // Base: caller-supplied dir (cheapest), else a single worktree at baseRef.
185
293
  let baseMap: Map<string, string>;
186
294
  if (opts.baseDir) {
187
- const baseBuild = await build(resolve(opts.baseDir), opts.serializers);
188
- baseMap = artifactMap(baseBuild.outputs);
295
+ baseMap = (await readArtifacts(resolve(opts.baseDir), false)).artifacts;
189
296
  } else if (opts.baseRef) {
190
- baseMap = await withWorktree(repoRoot, opts.baseRef, async (dir) => {
191
- const baseBuild = await build(join(dir, relProject), opts.serializers);
192
- return artifactMap(baseBuild.outputs);
193
- });
297
+ baseMap = await withWorktree(repoRoot, opts.baseRef, async (dir) => (await readArtifacts(join(dir, relProject), false)).artifacts);
194
298
  } else {
195
299
  throw new Error("affectedStacks requires either baseDir or baseRef");
196
300
  }
197
301
 
198
- return computeAffected(baseMap, headMap, head.manifest.stackGraph, {
302
+ return computeAffected(baseMap, head.artifacts, head.graph, {
199
303
  includeDependents: opts.includeDependents,
200
- externalInput,
304
+ externalInput: head.externalInput,
201
305
  });
202
306
  }
@@ -37,9 +37,25 @@ export const lifecycleDiffContract = activityContract(
37
37
  z.object({ output: z.string(), exitCode: z.number(), drifted: z.boolean() }),
38
38
  );
39
39
 
40
+ /**
41
+ * The escape hatch (#2413). `returns` is what `shellCmd` captured and used to
42
+ * throw away: the trimmed stdout, the trimmed stderr, and the exit code —
43
+ * which only ever differs from `0` when the step named that code in `okExit`,
44
+ * since anything else still rejects.
45
+ *
46
+ * Running a command chant does not model in order to discard what it produced
47
+ * is the odd case, not the normal one, so the value a later step reads through
48
+ * `sh.out.stdout` is the point of the step rather than an extra.
49
+ */
40
50
  export const shellCmdContract = activityContract(
41
51
  "shellCmd",
42
- z.strictObject({ cmd: z.string(), env: z.record(z.string(), z.string()).optional(), cwd: z.string().optional() }),
52
+ z.strictObject({
53
+ cmd: z.string(),
54
+ env: z.record(z.string(), z.string()).optional(),
55
+ cwd: z.string().optional(),
56
+ okExit: z.array(z.number()).optional(),
57
+ }),
58
+ z.object({ stdout: z.string(), stderr: z.string(), exitCode: z.number() }),
43
59
  );
44
60
 
45
61
  export const httpCheckContract = activityContract(
@@ -14,7 +14,7 @@ export type { WaitForStackArgs } from "./wait";
14
14
  // provides gitlabPipeline. The gitlabPipeline step builder stays in core.
15
15
 
16
16
  export { shellCmd } from "./shell";
17
- export type { ShellCmdArgs } from "./shell";
17
+ export type { ShellCmdArgs, ShellCmdResult } from "./shell";
18
18
 
19
19
  export { httpCheck, statusOk } from "./http-check";
20
20
  export type { HttpCheckArgs, HttpFetch } from "./http-check";
@@ -0,0 +1,156 @@
1
+ /**
2
+ * The escape hatch's safety properties (#2411, #2412) and what it publishes
3
+ * (#2413, #2414).
4
+ *
5
+ * `shellCmd` runs a command chant did not write and cannot model, which is
6
+ * what makes these different from every other activity: nothing here can know
7
+ * whether repeating the command is safe, how much it will say, or what a
8
+ * non-zero exit means.
9
+ */
10
+
11
+ import { describe, test, expect } from "vitest";
12
+ import { z } from "zod";
13
+ import { shellCmd } from "./shell";
14
+ import { shellCmdContract } from "./activity-contracts";
15
+ import { shell } from "../builders";
16
+ import { phase } from "../builders";
17
+ import { collectStepOutputRefs, stepOutput, validateStepOutputRefs } from "../step-output-ref";
18
+ import { ACTIVITY_PROFILES } from "../activity-profiles";
19
+ import { runOpLocally } from "../local-executor";
20
+ import { memoryGateLedgerPort } from "../gate";
21
+ import type { ActivityFn } from "../activity-registry";
22
+ import type { ShellCmdArgs, ShellCmdResult } from "./shell";
23
+
24
+ describe("the at-most-once default (#2411)", () => {
25
+ test("shell() asks for a profile that does not retry", () => {
26
+ const step = shell("echo hi");
27
+ expect(step.profile).toBe("atMostOnce");
28
+ expect(ACTIVITY_PROFILES.atMostOnce.retry.maximumAttempts).toBe(1);
29
+ });
30
+
31
+ test("an author who knows the command is safe to repeat can still say so", () => {
32
+ // The direction that matters: retrying is opt-in, because it is the claim
33
+ // that needs evidence about the command.
34
+ expect(shell("echo hi", { profile: "fastIdempotent" }).profile).toBe("fastIdempotent");
35
+ expect(ACTIVITY_PROFILES.fastIdempotent.retry.maximumAttempts).toBeGreaterThan(1);
36
+ });
37
+
38
+ test("the profile allows a long command, since a shell step is often a build", () => {
39
+ expect(ACTIVITY_PROFILES.atMostOnce.timeout).toBe("20m");
40
+ });
41
+ });
42
+
43
+ describe("the stdout ceiling (#2412)", () => {
44
+ test("a command producing well over 1 MiB completes instead of rejecting", async () => {
45
+ // Node's default maxBuffer is 1 MiB and this activity was the only exec
46
+ // site leaving it unset. 4 MiB is comfortably past the old ceiling and
47
+ // far short of the new one.
48
+ const bytes = 4 * 1024 * 1024;
49
+ const out = await shellCmd({ cmd: `node -e "process.stdout.write('x'.repeat(${bytes}))"` });
50
+ expect(out.stdout.length).toBe(bytes);
51
+ });
52
+
53
+ test("stdout is returned trimmed, as before", async () => {
54
+ expect((await shellCmd({ cmd: "echo hello" })).stdout).toBe("hello");
55
+ });
56
+
57
+ test("cwd and env reach the command", async () => {
58
+ const out = await shellCmd({ cmd: "pwd && echo $CHANT_SHELL_TEST", cwd: "/tmp", env: { CHANT_SHELL_TEST: "set" } });
59
+ expect(out.stdout).toContain("set");
60
+ });
61
+ });
62
+
63
+ describe("what a shell step publishes (#2413)", () => {
64
+ test("the contract declares a return schema, so a later step may reference it", () => {
65
+ const returns = shellCmdContract.returns as z.ZodTypeAny | undefined;
66
+ expect(returns).toBeDefined();
67
+ expect(returns!.parse({ stdout: "a", stderr: "b", exitCode: 0 })).toEqual({ stdout: "a", stderr: "b", exitCode: 0 });
68
+ });
69
+
70
+ test("a step reading a shell step's stdout passes OPS013", () => {
71
+ const host = shell("echo db.internal", { id: "host" });
72
+ const smoke = shell("./smoke.sh", { env: { HOST: host.out.stdout } });
73
+ const issues = validateStepOutputRefs(
74
+ { name: "deploy", phases: [phase("Go", [host, smoke])] },
75
+ new Map([["shellCmd", shellCmdContract]]),
76
+ );
77
+ expect(issues).toEqual([]);
78
+ });
79
+
80
+ test("a path the shell result does not declare is still flagged", () => {
81
+ const host = shell("echo db.internal", { id: "host" });
82
+ const smoke = shell("./smoke.sh", { env: { HOST: stepOutput(host, "stdoutt") } });
83
+ const issues = validateStepOutputRefs(
84
+ { name: "deploy", phases: [phase("Go", [host, smoke])] },
85
+ new Map([["shellCmd", shellCmdContract]]),
86
+ );
87
+ expect(issues).toHaveLength(1);
88
+ expect(issues[0].message).toContain('output path "stdoutt"');
89
+ });
90
+
91
+ test("stderr survives the call instead of being printed and dropped", async () => {
92
+ const out = await shellCmd({ cmd: `node -e "process.stderr.write('warned')"` });
93
+ expect(out).toMatchObject({ stdout: "", stderr: "warned", exitCode: 0 });
94
+ });
95
+
96
+ test("a non-zero exit still rejects, and the code is in the message", async () => {
97
+ await expect(shellCmd({ cmd: "exit 3" })).rejects.toThrow(/exited 3 \(expected 0\)/);
98
+ });
99
+
100
+ test("a code the author named resolves, carrying output and the code", async () => {
101
+ // `diff` exits 1 to report a difference. Nothing about that is a failure,
102
+ // and before this the whole step was one.
103
+ const out = await shellCmd({ cmd: `node -e "process.stdout.write('changed'); process.exit(1)"`, okExit: [0, 1] });
104
+ expect(out).toEqual({ stdout: "changed", stderr: "", exitCode: 1 });
105
+ });
106
+
107
+ test("a code the author did not name still rejects", async () => {
108
+ await expect(shellCmd({ cmd: "exit 2", okExit: [0, 1] })).rejects.toThrow(/exited 2 \(expected 0, 1\)/);
109
+ });
110
+
111
+ test("a signal kill rejects even when its code is named", async () => {
112
+ // A timeout or Ctrl-C is not an exit status the author said anything
113
+ // about, so `okExit` must not swallow it.
114
+ const ac = new AbortController();
115
+ const running = shellCmd({ cmd: "sleep 5", okExit: [0, 1, 143] }, ac.signal);
116
+ ac.abort();
117
+ await expect(running).rejects.toThrow();
118
+ });
119
+ });
120
+
121
+ describe("a reference reaching the command (#2414)", () => {
122
+ test("a reference in env typechecks, which is the whole gap", () => {
123
+ const host = shell("echo db.internal", { id: "host" });
124
+ // No `as` cast: before #2414 `WithStepRefs` was shallow, so a reference
125
+ // inside `env`'s Record<string, string> was a type error even though the
126
+ // executor resolved it and the lint rule accepted it.
127
+ const smoke = shell("./smoke.sh", { env: { HOST: host.out.stdout, MODE: "ci" } });
128
+ expect(collectStepOutputRefs(smoke.args)).toEqual([
129
+ expect.objectContaining({ step: "host", path: "stdout" }),
130
+ ]);
131
+ expect((smoke.args as { env: Record<string, string> }).env.MODE).toBe("ci");
132
+ });
133
+
134
+ test("the executor carries it into the next command's environment, end to end", async () => {
135
+ const host = shell("echo db.internal", { id: "host" });
136
+ const smoke = shell("echo reached $HOST", { env: { HOST: host.out.stdout }, id: "smoke" });
137
+
138
+ const seen: ShellCmdResult[] = [];
139
+ const spy: ActivityFn = async (args, signal) => {
140
+ const out = await shellCmd(args as unknown as ShellCmdArgs, signal);
141
+ seen.push(out);
142
+ return out;
143
+ };
144
+
145
+ const result = await runOpLocally(
146
+ { name: "deploy", overview: "", phases: [phase("Go", [host, smoke])] },
147
+ new Map([["shellCmd", spy]]),
148
+ ACTIVITY_PROFILES,
149
+ undefined,
150
+ { gates: memoryGateLedgerPort() },
151
+ );
152
+
153
+ expect(result.status).toBe("ok");
154
+ expect(seen.map((s) => s.stdout)).toEqual(["db.internal", "reached db.internal"]);
155
+ });
156
+ });
@@ -9,18 +9,93 @@ export interface ShellCmdArgs {
9
9
  env?: Record<string, string>;
10
10
  /** Working directory. Default: process.cwd(). */
11
11
  cwd?: string;
12
+ /**
13
+ * Exit codes that count as success. Default `[0]`.
14
+ *
15
+ * Without this, `exitCode` in the result could only ever be `0` (#2413):
16
+ * every other code rejects, so nothing downstream can read it. Naming the
17
+ * codes a command uses to report a result — `diff`'s 1, `grep`'s 1,
18
+ * a migration tool's "nothing to do" — turns them into a value a later
19
+ * step can branch on instead of a failed Op.
20
+ */
21
+ okExit?: number[];
22
+ }
23
+
24
+ /**
25
+ * How much stdout a command may produce, matching every other exec site in
26
+ * the tree (`../activities/apply.ts`, the terraform lexicon's activities,
27
+ * `../../components/verbs/process-runner.ts`).
28
+ *
29
+ * Node's default is 1 MiB, and this was the only exec call leaving it unset
30
+ * (#2412) — on the one activity whose output chant cannot predict, because
31
+ * the command is the author's. A verbose test run, a playbook or a wide plan
32
+ * passes 1 MiB without trying, and the overflow is a rejection rather than a
33
+ * truncation, so the step fails for a reason that has nothing to do with the
34
+ * command.
35
+ */
36
+ const MAX_STDOUT_BYTES = 64 * 1024 * 1024;
37
+
38
+ /**
39
+ * What a shell step publishes to the steps after it (#2413).
40
+ *
41
+ * `stdout` and `stderr` are trimmed, because the value an author wants from
42
+ * `echo $(terraform output -raw host)` is the host, not the host plus a
43
+ * newline, and a trailing newline in an `env` value or a gate argument is a
44
+ * bug that is very hard to see.
45
+ *
46
+ * `stderr` is here as well as on the console. It was captured and dropped
47
+ * before, so a command that reports on stderr — every tool that prints
48
+ * progress there — had no route to a later step at all.
49
+ */
50
+ export interface ShellCmdResult {
51
+ stdout: string;
52
+ stderr: string;
53
+ exitCode: number;
54
+ }
55
+
56
+ /** Node hangs the exit status off the error as `code`, and a signal kill as `signal`. */
57
+ interface ExecFailure extends Error {
58
+ code?: number | string;
59
+ signal?: string;
60
+ killed?: boolean;
61
+ stdout?: string;
62
+ stderr?: string;
12
63
  }
13
64
 
14
65
  /**
15
66
  * Run an arbitrary shell command.
16
- * Uses fastIdempotent profile — 5m timeout, 3 retries.
67
+ *
68
+ * Runs under the `atMostOnce` profile by default (#2411): one attempt, since
69
+ * nothing here can know whether repeating the author's command is safe.
17
70
  */
18
- export async function shellCmd(args: ShellCmdArgs, signal?: AbortSignal): Promise<string> {
19
- const { stdout, stderr } = await execAsync(args.cmd, {
20
- cwd: args.cwd,
21
- env: { ...process.env, ...args.env },
22
- signal,
23
- });
24
- if (stderr) console.error(stderr);
25
- return stdout.trim();
71
+ export async function shellCmd(args: ShellCmdArgs, signal?: AbortSignal): Promise<ShellCmdResult> {
72
+ const okExit = args.okExit ?? [0];
73
+ try {
74
+ const { stdout, stderr } = await execAsync(args.cmd, {
75
+ cwd: args.cwd,
76
+ env: { ...process.env, ...args.env },
77
+ maxBuffer: MAX_STDOUT_BYTES,
78
+ signal,
79
+ });
80
+ if (stderr) console.error(stderr);
81
+ return { stdout: stdout.trim(), stderr: stderr.trim(), exitCode: 0 };
82
+ } catch (err) {
83
+ const failure = err as ExecFailure;
84
+ const exitCode = typeof failure.code === "number" ? failure.code : undefined;
85
+ // A signal kill (Ctrl-C, the profile's timeout, a maxBuffer overflow) is
86
+ // not an exit status the author declared anything about, so it rethrows
87
+ // even if `okExit` happens to contain the code.
88
+ const died = failure.killed === true || typeof failure.signal === "string" || signal?.aborted === true;
89
+ if (exitCode !== undefined && !died && okExit.includes(exitCode)) {
90
+ const stderrText = (failure.stderr ?? "").trim();
91
+ if (stderrText) console.error(stderrText);
92
+ return { stdout: (failure.stdout ?? "").trim(), stderr: stderrText, exitCode };
93
+ }
94
+ if (exitCode !== undefined && !died) {
95
+ // `local-executor` records `error` as message text, so the code has to
96
+ // be in the message or it is gone (#2413).
97
+ failure.message = `command exited ${exitCode} (expected ${okExit.join(", ")}): ${failure.message}`;
98
+ }
99
+ throw failure;
100
+ }
26
101
  }
@@ -10,12 +10,26 @@ import { activity } from "./builders";
10
10
  * in an in-process step, so it did not come along.
11
11
  */
12
12
  describe("ACTIVITY_PROFILES", () => {
13
- test("carries the six named profiles", () => {
13
+ test("carries the seven named profiles", () => {
14
14
  expect(Object.keys(ACTIVITY_PROFILES).sort()).toEqual(
15
- ["argoSync", "fastIdempotent", "humanGate", "k8sWait", "longInfra", "policyCheck"],
15
+ ["argoSync", "atMostOnce", "fastIdempotent", "humanGate", "k8sWait", "longInfra", "policyCheck"],
16
16
  );
17
17
  });
18
18
 
19
+ test("atMostOnce runs once, and is the only non-gate profile that does (#2411)", () => {
20
+ expect(ACTIVITY_PROFILES.atMostOnce.retry.maximumAttempts).toBe(1);
21
+ // The two other single-attempt profiles carry semantics a shell step must
22
+ // not borrow: a gate's single attempt is about not re-asking a human, and
23
+ // a policy check's is about not re-running an evaluation. A run ledger
24
+ // that called a shell step either of those would be saying something
25
+ // false about what ran.
26
+ const singleAttempt = Object.entries(ACTIVITY_PROFILES)
27
+ .filter(([, p]) => p.retry.maximumAttempts === 1)
28
+ .map(([name]) => name)
29
+ .sort();
30
+ expect(singleAttempt).toEqual(["atMostOnce", "humanGate", "policyCheck"]);
31
+ });
32
+
19
33
  test("every profile has a timeout, and none has a worker-era field", () => {
20
34
  for (const [name, profile] of Object.entries(ACTIVITY_PROFILES)) {
21
35
  expect(typeof profile.timeout, `${name}.timeout`).toBe("string");
@@ -72,6 +72,24 @@ export const ACTIVITY_PROFILES = {
72
72
  },
73
73
  },
74
74
 
75
+ /**
76
+ * A command chant did not write and cannot know is safe to repeat (#2411).
77
+ *
78
+ * `shellCmd` is the escape hatch: its whole purpose is to run something
79
+ * outside the model, so nothing here can judge whether a second attempt is
80
+ * harmless or a second deployment. Every other activity carrying a retrying
81
+ * profile is one chant authored and knows the shape of.
82
+ *
83
+ * Twenty minutes, because a shell step is as likely to be a long build as a
84
+ * quick script, and one attempt, because retrying is the claim that needs
85
+ * evidence. An author who knows their command is idempotent names
86
+ * `fastIdempotent` or `longInfra` and gets retries back.
87
+ */
88
+ atMostOnce: {
89
+ timeout: "20m",
90
+ retry: { maximumAttempts: 1 },
91
+ },
92
+
75
93
  /**
76
94
  * Human-gate steps: waiting for an operator action (DNS delegation, approval).
77
95
  * Very long timeout, single attempt — no retry on human-gate timeouts.
@@ -306,16 +306,34 @@ export const lifecycleSnapshot = (env: string, opts?: { id?: string }): NamedAct
306
306
  activity("lifecycleSnapshot", { env } satisfies LifecycleSnapshotArgs, opts?.id ? { id: opts.id } : undefined);
307
307
 
308
308
  /**
309
- * Run an arbitrary shell command. Tag long-running commands with a `profile`
310
- * (e.g. `longInfra` for a multi-GB image push) so they get the right
311
- * start-to-close timeout on whichever runtime hosts the run.
309
+ * Run an arbitrary shell command.
310
+ *
311
+ * Defaults to the `atMostOnce` profile: twenty minutes, one attempt (#2411).
312
+ * This is the one activity chant cannot know is idempotent, because its
313
+ * purpose is to run something chant does not model, so a failed command is
314
+ * not repeated unless the author says it may be. Name `fastIdempotent` or
315
+ * `longInfra` to get retries back for a command that is safe to repeat.
316
+ *
317
+ * Give the step an `id` and later steps can read what it produced —
318
+ * `sh.out.stdout`, `sh.out.stderr`, `sh.out.exitCode` (#2413) — and a value
319
+ * from an earlier step reaches the command through `env` (#2414):
320
+ *
321
+ * ```ts
322
+ * const host = shell("terraform output -raw host", { id: "host" });
323
+ * shell("./smoke.sh", { env: { HOST: host.out.stdout } });
324
+ * ```
325
+ *
326
+ * `cmd` stays a plain `string` and takes no references. A value spliced into
327
+ * a command line is a quoting decision chant would then be making on the
328
+ * author's behalf, and `env` carries the same value into the same command
329
+ * with the shell's own rules intact.
312
330
  */
313
331
  export const shell = (
314
332
  cmd: string,
315
333
  opts?: WithStepRefs<Omit<ShellCmdArgs, "cmd">> & StepOpts,
316
334
  ): NamedActivityStep => {
317
335
  const { args, profile, id } = takeProfileAndId(opts as Record<string, unknown> | undefined);
318
- return activity("shellCmd", { cmd, ...args }, { ...(profile ? { profile } : {}), ...(id ? { id } : {}) });
336
+ return activity("shellCmd", { cmd, ...args }, { profile: profile ?? "atMostOnce", ...(id ? { id } : {}) });
319
337
  };
320
338
 
321
339
  /**
@@ -18,6 +18,17 @@
18
18
 
19
19
  import type { OpConfig, PhaseDefinition, StepDefinition } from "./types";
20
20
 
21
+ /**
22
+ * The op name a `chant components fan-out` gate is recorded under (#2420).
23
+ *
24
+ * A fan-out is a command rather than an authored `*.op.ts`, so `chant approve`
25
+ * has nothing to discover for this name and must not report that as a problem.
26
+ * It lives here, next to the other thing that decides what a gate is called,
27
+ * so both the command that records the pending fact and the command that
28
+ * answers it read one constant instead of agreeing by hand.
29
+ */
30
+ export const FAN_OUT_GATE_OP = "fan-out";
31
+
21
32
  /** Either spelling of a gate step's name. `gate` since #2202; `signalName` through 0.59.0. */
22
33
  export interface GateNamed {
23
34
  gate?: string;
@@ -123,7 +123,10 @@ describe("op.json IR", () => {
123
123
 
124
124
  expect(ir.name).toBe("full-deploy");
125
125
  const [build, approve, deploy, seed, verify] = ir.phases;
126
- expect(build.steps[0]).toMatchObject({ kind: "activity", fn: "shellCmd", profile: "fastIdempotent" });
126
+ // A shell step carries `atMostOnce` since #2411: the IR records the
127
+ // profile the builder named, and the builder names one precisely so a
128
+ // command chant cannot judge does not inherit a retrying default.
129
+ expect(build.steps[0]).toMatchObject({ kind: "activity", fn: "shellCmd", profile: "atMostOnce" });
127
130
  expect(approve.steps[0]).toMatchObject({
128
131
  kind: "gate",
129
132
  gate: "approve-deploy",
package/src/op/op.test.ts CHANGED
@@ -266,10 +266,15 @@ describe("profile routing (opts.profile sets the step profile, never leaks into
266
266
  expect("profile" in (a.args ?? {})).toBe(false);
267
267
  });
268
268
 
269
- it("shell() without profile leaves the step unprofiled (defaults apply downstream)", () => {
269
+ it("shell() without profile names atMostOnce, so the retrying default cannot apply (#2411)", () => {
270
+ // It used to leave the step unprofiled and let the executor's default
271
+ // apply, which meant the one activity chant cannot know is idempotent
272
+ // inherited three attempts by omission. The builder names its profile now,
273
+ // the way terraformPlan and terraformApply already did.
270
274
  const a = shell("echo hi", { env: { A: "1" } });
271
- expect("profile" in a).toBe(false);
275
+ expect(a.profile).toBe("atMostOnce");
272
276
  expect(a.args?.env).toEqual({ A: "1" });
277
+ expect("profile" in (a.args ?? {})).toBe(false);
273
278
  });
274
279
 
275
280
  it("build() accepts a profile override and does not leak it into args", () => {
@@ -112,15 +112,36 @@ export interface StepOutputRef {
112
112
  }
113
113
 
114
114
  /**
115
- * `T` with every own property additionally accepting a {@link StepOutputRef}
116
- * in its place (chant #1288 Stage 2) — the authoring-time counterpart of
117
- * `args` accepting a reference anywhere in the structure (#1290): a typed
118
- * step-builder wrapper whose opts type is `WithStepRefs<SomeActivityArgs>`
119
- * lets an author pass `diff.out.driftedStacks` for any field without an
120
- * `as` cast, while runtime validation of the reference itself is still
121
- * `validateStepOutputRefs`' job, not this type's.
115
+ * `V`, or a {@link StepOutputRef} in its place, at every position inside it.
116
+ *
117
+ * Recurses through arrays and plain objects — including an index signature,
118
+ * which is the case that motivated it (#2414): `shell()`'s `env` is a
119
+ * `Record<string, string>`, and a reference in one of its values resolves at
120
+ * run time (`local-executor`'s `resolveStepOutputRefs` deep-walks `args`) and
121
+ * passes OPS012 (`activity-contract.ts` skips a reference at the issue path),
122
+ * so the compiler was the only one of the three layers rejecting it.
123
+ *
124
+ * Functions are left alone rather than mapped — nothing in an activity's args
125
+ * is callable, and mapping one would silently strip its call signature.
126
+ */
127
+ type StepRefAt<V> =
128
+ | StepOutputRef
129
+ | (V extends Function ? V
130
+ : V extends readonly (infer E)[] ? (V extends unknown[] ? StepRefAt<E>[] : readonly StepRefAt<E>[])
131
+ : V extends object ? { [K in keyof V]: StepRefAt<V[K]> }
132
+ : V);
133
+
134
+ /**
135
+ * `T` with every property — at any depth — additionally accepting a {@link
136
+ * StepOutputRef} in its place (chant #1288 Stage 2, deepened in #2414) — the
137
+ * authoring-time counterpart of `args` accepting a reference anywhere in the
138
+ * structure (#1290): a typed step-builder wrapper whose opts type is
139
+ * `WithStepRefs<SomeActivityArgs>` lets an author pass
140
+ * `diff.out.driftedStacks` for any field without an `as` cast, while runtime
141
+ * validation of the reference itself is still `validateStepOutputRefs`' job,
142
+ * not this type's.
122
143
  */
123
- export type WithStepRefs<T> = { [K in keyof T]: T[K] | StepOutputRef };
144
+ export type WithStepRefs<T> = { [K in keyof T]: StepRefAt<T[K]> };
124
145
 
125
146
  /** Structural guard for a value produced by {@link stepOutput} (or `activity()`'s `.out`). */
126
147
  export function isStepOutputRef(value: unknown): value is StepOutputRef {