@intentius/chant 0.124.57 → 0.124.58

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 (121) hide show
  1. package/dist/ci-product-words.d.ts +47 -2
  2. package/dist/ci-product-words.d.ts.map +1 -1
  3. package/dist/ci-product-words.js +59 -1
  4. package/dist/ci-product.d.ts +26 -2
  5. package/dist/ci-product.d.ts.map +1 -1
  6. package/dist/ci-product.js +26 -2
  7. package/dist/cli/commands/init.d.ts +2 -0
  8. package/dist/cli/commands/init.d.ts.map +1 -1
  9. package/dist/cli/commands/init.js +1 -1
  10. package/dist/cli/handlers/build.d.ts.map +1 -1
  11. package/dist/cli/handlers/build.js +5 -1
  12. package/dist/cli/handlers/init.d.ts.map +1 -1
  13. package/dist/cli/handlers/init.js +16 -0
  14. package/dist/cli/handlers/serve.d.ts.map +1 -1
  15. package/dist/cli/handlers/serve.js +9 -0
  16. package/dist/cli/main.d.ts.map +1 -1
  17. package/dist/cli/main.js +6 -2
  18. package/dist/cli/mcp/product-tools.d.ts +40 -7
  19. package/dist/cli/mcp/product-tools.d.ts.map +1 -1
  20. package/dist/cli/mcp/product-tools.js +59 -15
  21. package/dist/cli/mcp/read-only.d.ts +2 -1
  22. package/dist/cli/mcp/read-only.d.ts.map +1 -1
  23. package/dist/cli/mcp/read-only.js +2 -1
  24. package/dist/cli/mcp/server.d.ts +11 -0
  25. package/dist/cli/mcp/server.d.ts.map +1 -1
  26. package/dist/cli/mcp/server.js +15 -3
  27. package/dist/cli/mcp-config.d.ts +4 -1
  28. package/dist/cli/mcp-config.d.ts.map +1 -1
  29. package/dist/cli/mcp-config.js +6 -2
  30. package/dist/cli/parse-args.d.ts.map +1 -1
  31. package/dist/cli/parse-args.js +9 -0
  32. package/dist/cli/registry.d.ts +8 -0
  33. package/dist/cli/registry.d.ts.map +1 -1
  34. package/dist/components/pr-pipeline.d.ts +56 -0
  35. package/dist/components/pr-pipeline.d.ts.map +1 -1
  36. package/dist/components/pr-pipeline.js +55 -2
  37. package/dist/components/product-pipeline.d.ts +18 -1
  38. package/dist/components/product-pipeline.d.ts.map +1 -1
  39. package/dist/components/product-pipeline.js +8 -2
  40. package/dist/e2e-harness/driver.d.ts.map +1 -1
  41. package/dist/e2e-harness/driver.js +97 -0
  42. package/dist/e2e-harness/forgejo.d.ts +5 -1
  43. package/dist/e2e-harness/forgejo.d.ts.map +1 -1
  44. package/dist/e2e-harness/forgejo.js +35 -0
  45. package/dist/e2e-harness/index.d.ts +7 -0
  46. package/dist/e2e-harness/index.d.ts.map +1 -1
  47. package/dist/e2e-harness/index.js +11 -1
  48. package/dist/e2e-harness/ports.d.ts +31 -0
  49. package/dist/e2e-harness/ports.d.ts.map +1 -1
  50. package/dist/e2e-harness/scenario.d.ts.map +1 -1
  51. package/dist/e2e-harness/scenario.js +9 -5
  52. package/dist/e2e-harness/schemas/e2e-scenario.schema.json +43 -3
  53. package/dist/e2e-harness/schemas/index.d.ts +22 -1
  54. package/dist/e2e-harness/schemas/index.d.ts.map +1 -1
  55. package/dist/e2e-harness/schemas/index.js +1 -1
  56. package/dist/e2e-harness/steps.d.ts.map +1 -1
  57. package/dist/e2e-harness/steps.js +4 -0
  58. package/dist/mcp/types.d.ts +9 -0
  59. package/dist/mcp/types.d.ts.map +1 -1
  60. package/dist/release-floors.d.ts +1 -1
  61. package/dist/release-floors.js +1 -1
  62. package/dist/template-request/index.d.ts +9 -0
  63. package/dist/template-request/index.d.ts.map +1 -0
  64. package/dist/template-request/index.js +8 -0
  65. package/dist/template-request/request-body.d.ts +21 -0
  66. package/dist/template-request/request-body.d.ts.map +1 -0
  67. package/dist/template-request/request-body.js +86 -0
  68. package/dist/template-request/template-request.d.ts +100 -0
  69. package/dist/template-request/template-request.d.ts.map +1 -0
  70. package/dist/template-request/template-request.js +150 -0
  71. package/dist/template-request/template-request.schema.json +100 -0
  72. package/dist/template-request/template-spec.d.ts +83 -0
  73. package/dist/template-request/template-spec.d.ts.map +1 -0
  74. package/dist/template-request/template-spec.js +146 -0
  75. package/dist/template-request/template.schema.json +114 -0
  76. package/dist/template-request/validate.d.ts +4 -0
  77. package/dist/template-request/validate.d.ts.map +1 -0
  78. package/dist/template-request/validate.js +21 -0
  79. package/dist/wave-runtime.mjs +4 -4
  80. package/package.json +8 -1
  81. package/src/ci-product-words.test.ts +23 -0
  82. package/src/ci-product-words.ts +68 -3
  83. package/src/ci-product.ts +32 -1
  84. package/src/cli/commands/init.ts +3 -1
  85. package/src/cli/handlers/build.ts +5 -1
  86. package/src/cli/handlers/init.ts +18 -0
  87. package/src/cli/handlers/serve.ts +9 -0
  88. package/src/cli/main.ts +6 -2
  89. package/src/cli/mcp/product-tools.test.ts +57 -1
  90. package/src/cli/mcp/product-tools.ts +67 -15
  91. package/src/cli/mcp/read-only.ts +2 -1
  92. package/src/cli/mcp/server.ts +20 -5
  93. package/src/cli/mcp-config.test.ts +52 -2
  94. package/src/cli/mcp-config.ts +6 -3
  95. package/src/cli/parse-args.ts +7 -0
  96. package/src/cli/registry.ts +8 -0
  97. package/src/components/pr-pipeline.ts +87 -2
  98. package/src/components/product-actions.test.ts +76 -0
  99. package/src/components/product-pipeline.ts +21 -2
  100. package/src/e2e-harness/driver.test.ts +163 -0
  101. package/src/e2e-harness/driver.ts +86 -1
  102. package/src/e2e-harness/forgejo.ts +42 -1
  103. package/src/e2e-harness/index.ts +12 -1
  104. package/src/e2e-harness/ports.ts +33 -0
  105. package/src/e2e-harness/scenario.ts +8 -6
  106. package/src/e2e-harness/schemas/README.md +11 -2
  107. package/src/e2e-harness/schemas/e2e-scenario.schema.json +43 -3
  108. package/src/e2e-harness/schemas/index.ts +5 -1
  109. package/src/e2e-harness/schemas.test.ts +44 -1
  110. package/src/e2e-harness/steps.ts +4 -0
  111. package/src/mcp/types.ts +9 -0
  112. package/src/release-floors.ts +1 -1
  113. package/src/template-request/__fixtures__/request-body.md +41 -0
  114. package/src/template-request/index.ts +8 -0
  115. package/src/template-request/request-body.ts +91 -0
  116. package/src/template-request/template-request.schema.json +100 -0
  117. package/src/template-request/template-request.test.ts +316 -0
  118. package/src/template-request/template-request.ts +235 -0
  119. package/src/template-request/template-spec.ts +176 -0
  120. package/src/template-request/template.schema.json +114 -0
  121. package/src/template-request/validate.ts +28 -0
@@ -1,4 +1,4 @@
1
- import { describe, test, expect } from "vitest";
1
+ import { describe, test, expect, vi } from "vitest";
2
2
  import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs";
3
3
  import { join } from "path";
4
4
  import { homedir } from "os";
@@ -7,7 +7,10 @@ import { initCommand } from "./commands/init";
7
7
  import { doctorCommand } from "./commands/doctor";
8
8
  import { updateCommand } from "./commands/update";
9
9
  import { parseArgs, commandRegistry } from "./main";
10
- import { MCP_CONFIG_FILENAME, MCP_SETUP_COMMAND, mcpConfigPath } from "./mcp-config";
10
+ import { generateMcpConfig, MCP_CONFIG_FILENAME, MCP_SETUP_COMMAND, mcpConfigPath } from "./mcp-config";
11
+ import { runServeMcp } from "./handlers/serve";
12
+ import { runInit } from "./handlers/init";
13
+ import type { CommandContext } from "./registry";
11
14
 
12
15
  /**
13
16
  * chant #2383. `chant init` used to write `mcp.json` into the user's home
@@ -166,3 +169,50 @@ describe("MCP config: one location, three agreeing sites (#2383)", () => {
166
169
  }
167
170
  });
168
171
  });
172
+
173
+ describe("the --propose tier on the command line (#4655)", () => {
174
+ const ctx = (argv: string[]): CommandContext => ({ args: parseArgs(argv), plugins: [], serializers: [] });
175
+
176
+ async function captured(run: () => Promise<number>): Promise<{ code: number; out: string; err: string }> {
177
+ const out: string[] = [];
178
+ const err: string[] = [];
179
+ const log = vi.spyOn(console, "log").mockImplementation((...a: unknown[]) => void out.push(a.join(" ")));
180
+ const error = vi.spyOn(console, "error").mockImplementation((...a: unknown[]) => void err.push(a.join(" ")));
181
+ try {
182
+ return { code: await run(), out: out.join("\n"), err: err.join("\n") };
183
+ } finally {
184
+ log.mockRestore();
185
+ error.mockRestore();
186
+ }
187
+ }
188
+
189
+ test("chant serve mcp --propose without --read-only exits 1 with a usage message", async () => {
190
+ const args = parseArgs(["serve", "mcp", "--propose"]);
191
+ expect(args.propose).toBe(true);
192
+ const got = await captured(() => runServeMcp(ctx(["serve", "mcp", "--propose"])));
193
+ expect(got.code).toBe(1);
194
+ expect(got.err).toMatch(/--propose needs --read-only/);
195
+ expect(got.err).toMatch(/Usage: chant serve mcp --read-only --propose/);
196
+ });
197
+
198
+ test("chant init --mcp-read-only --propose --dry-run prints the .mcp.json it would write, and writes nothing", async () => {
199
+ await withTestDir(async (dir) => {
200
+ const got = await captured(() => runInit(ctx(["init", dir, "--mcp-read-only", "--propose", "--dry-run"])));
201
+ expect(got.code).toBe(0);
202
+ expect(JSON.parse(got.out).mcpServers.chant.args).toEqual(["chant", "serve", "mcp", "--read-only", "--propose"]);
203
+ expect(existsSync(mcpConfigPath(dir))).toBe(false);
204
+ });
205
+ const refused = await captured(() => runInit(ctx(["init", "--propose", "--dry-run"])));
206
+ expect(refused.code).toBe(1);
207
+ expect(refused.err).toMatch(/--propose needs --mcp-read-only/);
208
+ });
209
+
210
+ test("init --mcp-read-only --propose registers the tier, and propose alone is refused", async () => {
211
+ await withTestDir(async (testDir) => {
212
+ await initCommand({ path: testDir, lexicon: "aws", skipInstall: true, mcpReadOnly: true, mcpPropose: true });
213
+ const config = JSON.parse(readFileSync(mcpConfigPath(testDir), "utf-8"));
214
+ expect(config.mcpServers.chant.args).toEqual(["chant", "serve", "mcp", "--read-only", "--propose"]);
215
+ });
216
+ expect(() => generateMcpConfig("npm", { propose: true })).toThrow(/--mcp-read-only --propose/);
217
+ });
218
+ });
@@ -53,14 +53,17 @@ export function detectPackageManager(dir?: string): "bun" | "npm" {
53
53
  * The MCP registration chant writes: one stdio server named `chant`. With
54
54
  * `readOnly` (`chant init --mcp-read-only`, chant#4543) it registers
55
55
  * `chant serve mcp --read-only`, which serves only the tools that change
56
- * nothing.
56
+ * nothing. With `readOnly` and `propose` (`chant init --mcp-read-only
57
+ * --propose`, chant#4655) it registers `chant serve mcp --read-only
58
+ * --propose`; `propose` without `readOnly` is refused.
57
59
  */
58
- export function generateMcpConfig(pm: "bun" | "npm", options: { readOnly?: boolean } = {}): string {
60
+ export function generateMcpConfig(pm: "bun" | "npm", options: { readOnly?: boolean; propose?: boolean } = {}): string {
61
+ if (options.propose && !options.readOnly) throw new Error("--propose is a tier of the read-only server: use --mcp-read-only --propose");
59
62
  const config = {
60
63
  mcpServers: {
61
64
  chant: {
62
65
  command: pm === "bun" ? "bunx" : "npx",
63
- args: ["chant", "serve", "mcp", ...(options.readOnly ? ["--read-only"] : [])],
66
+ args: ["chant", "serve", "mcp", ...(options.readOnly ? ["--read-only"] : []), ...(options.readOnly && options.propose ? ["--propose"] : [])],
64
67
  },
65
68
  },
66
69
  };
@@ -87,6 +87,7 @@ const BOOLEAN_FLAGS = new Set([
87
87
  "--skip-mcp",
88
88
  "--read-only",
89
89
  "--mcp-read-only",
90
+ "--propose",
90
91
  "--current",
91
92
  "--uncommitted",
92
93
  "--allow-code",
@@ -146,6 +147,7 @@ export function parseArgs(args: string[]): ParsedArgs {
146
147
  skipMcp: undefined,
147
148
  readOnly: undefined,
148
149
  mcpReadOnly: undefined,
150
+ propose: undefined,
149
151
  src: undefined,
150
152
  env: undefined,
151
153
  };
@@ -341,6 +343,8 @@ export function parseArgs(args: string[]): ParsedArgs {
341
343
  result.readOnly = true;
342
344
  } else if (arg === "--mcp-read-only") {
343
345
  result.mcpReadOnly = true;
346
+ } else if (arg === "--propose") {
347
+ result.propose = true;
344
348
  } else if (arg === "--src") {
345
349
  result.src = args[++i];
346
350
  } else if (arg === "--env") {
@@ -594,6 +598,9 @@ export function parseArgs(args: string[]): ParsedArgs {
594
598
  } else if (arg === "--apply-on-merge") {
595
599
  // `chant build --pr-loop --apply-on-merge` and `chant ci serve --apply-on-merge` (#4168): opt into applying on merge.
596
600
  result.applyOnMerge = true;
601
+ } else if (arg === "--action-job") {
602
+ // `chant build --pr-loop --action-job` (#4654): the job that answers the action comment and the action dispatch.
603
+ result.actionJob = true;
597
604
  } else if (arg === "--preview-comment") {
598
605
  // `chant build --pr-loop --preview-comment` (#4620): the job that answers `/<product> <plan word>` with a preview.
599
606
  result.previewComment = true;
@@ -137,6 +137,12 @@ export interface ParsedArgs {
137
137
  readOnly?: boolean;
138
138
  /** `chant init --mcp-read-only` (chant#4543): write `.mcp.json` registering `chant serve mcp --read-only`. */
139
139
  mcpReadOnly?: boolean;
140
+ /**
141
+ * `chant serve mcp --read-only --propose` and `chant init --mcp-read-only
142
+ * --propose` (chant#4655): the read-only server plus a product's tools that
143
+ * open pull requests (`forgeWrite`).
144
+ */
145
+ propose?: boolean;
140
146
  /** `chant import --type <ResourceType>` selector */
141
147
  selectType?: string;
142
148
  /** `chant import --name <name>` selector */
@@ -441,6 +447,8 @@ export interface ParsedArgs {
441
447
  applyBeforeMerge?: boolean;
442
448
  /** `chant build --pr-loop --preview-comment` (#4620): a job answers `/<product> <plan word>` by previewing the pull request's head again. */
443
449
  previewComment?: boolean;
450
+ /** `chant build --pr-loop --action-job` (#4654): a job answers `/<product> <action word> <member> <action>` and a dispatch with the two inputs by running the product's action verb. */
451
+ actionJob?: boolean;
444
452
  /** `chant build --pr-loop --pr-build` (#4088) — build and lint before pr-plan and pr-apply. */
445
453
  prBuild?: boolean;
446
454
  /** `chant build --pr-loop --pr-runner <stage>=<label>[,<label>...]` (#4625), repeatable: a stage's runner, plan, apply or default. */
@@ -97,7 +97,8 @@ import { layerWaves } from "../gated-waves";
97
97
  import type { DriverComponent } from "./driver";
98
98
  import type { GatedWavePipelineOptions } from "./gated-wave-pipeline";
99
99
  import type { CloudTradeSpec, PipelineCloudIdentity } from "../ci-identity";
100
- import { commentLine, resolveProductWords, type CiProductWords, type CiProductWordsInput } from "../ci-product-words";
100
+ import { commandWord, commentLine, PRODUCT_ACTION_ENV, PRODUCT_ACTION_EVENT_FLAG, resolveProductWords, type CiProductWords, type CiProductWordsInput } from "../ci-product-words";
101
+ import { CHANT_EXIT } from "../exit-codes";
101
102
  import type { ControlTarget } from "../control/dispatch";
102
103
  import { CI_RESPOND_ENV, respondList, type CiResponses } from "../ci-respond";
103
104
 
@@ -306,6 +307,15 @@ export interface PrLoopPipelineOptions {
306
307
  * Default false.
307
308
  */
308
309
  previewComment?: boolean;
310
+ /**
311
+ * The action job (#4654): `/<product> <action word> <member> <action>` on
312
+ * an issue or pull request, or a dispatch of the workflow with the two
313
+ * inputs ({@link prActionJob}), runs the product's action verb at the
314
+ * target branch's commit under its gated request. GitHub and Forgejo only.
315
+ * The words must name an `action` command and a `bin`. Set from
316
+ * `--action-job` beside `--pr-loop`. Default off.
317
+ */
318
+ actionJob?: boolean | PrActionJobOptions;
309
319
  /**
310
320
  * Where the pull request loop's jobs run (#4625), by stage: `plan` for the
311
321
  * plan and the comment preview, `apply` for the apply jobs, the record
@@ -409,7 +419,7 @@ export function prLoopRunner(options: Pick<PrLoopPipelineOptions, "runners">, st
409
419
  export function prLoopJobStage(name: string, member?: string): PrLoopRunnerStage {
410
420
  const bare = member && name.startsWith(`${member}-`) ? name.slice(member.length + 1) : name;
411
421
  if (bare === "plan" || bare === PR_COMMENT_PREVIEW_JOB) return "plan";
412
- if (bare === "apply" || bare === "record" || /^apply-wave-\d+$/.test(bare) || bare === "env-up" || bare === "env-down" || bare === "env-sweep") return "apply";
422
+ if (bare === "apply" || bare === "record" || bare === PR_ACTION_JOB || /^apply-wave-\d+$/.test(bare) || bare === "env-up" || bare === "env-down" || bare === "env-sweep") return "apply";
413
423
  return "default";
414
424
  }
415
425
 
@@ -516,6 +526,81 @@ export function prCommentLockJobs(forge: ForgeKind, options: Pick<PrLoopPipeline
516
526
  return out;
517
527
  }
518
528
 
529
+ /** The job answering the action comment and the action dispatch (#4654). */
530
+ export const PR_ACTION_JOB = "action";
531
+
532
+ /** The action job's settings (#4654). */
533
+ export interface PrActionJobOptions {
534
+ /** The dispatch inputs' names. Default the words' member noun (`stack`, `root`) and `action`. */
535
+ inputs?: { member?: string; action?: string };
536
+ }
537
+
538
+ /** The action job (#4654): what starts it, what it runs, and the values it reads. */
539
+ export interface PrActionJob {
540
+ jobName: typeof PR_ACTION_JOB;
541
+ /** The comment it answers, `/<product> <action word>`, followed by a member and an action. */
542
+ comment: string;
543
+ /** The dispatch inputs, by role: the member's input name and the action's. */
544
+ inputs: { member: string; action: string };
545
+ /**
546
+ * The command line: the product's action verb with
547
+ * {@link PRODUCT_ACTION_EVENT_FLAG}, which reads the comment or the inputs
548
+ * from {@link PRODUCT_ACTION_ENV}. A run that waits for an approval exits
549
+ * with chant's `waiting` code; {@link script} turns that into a green job.
550
+ */
551
+ command: string;
552
+ /** The step's script: the command, with chant's `waiting` exit taken as success, since a pending approval is the expected first answer. */
553
+ script: string;
554
+ /** The values it reads, as the forge spells them. */
555
+ env: Record<string, string>;
556
+ }
557
+
558
+ const INPUT_NAME = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
559
+
560
+ /**
561
+ * The action job (#4654), with `actionJob`: one job that answers the
562
+ * product's action comment and a dispatch of the workflow with a member and
563
+ * an action. It runs at the target branch's commit (an `issue_comment` run's
564
+ * checkout) or the dispatched ref, never a pull request's head, and runs the
565
+ * product's own action verb, which asks for the gated request and runs the
566
+ * action once an approval counts. The comment and the inputs reach the verb
567
+ * as variables ({@link PRODUCT_ACTION_ENV}), never as shell text.
568
+ *
569
+ * Undefined without `actionJob`. Throws on GitLab, which starts no pipeline
570
+ * on a note; for words that name no `action` command or no `bin`, since
571
+ * chant has no action verb of its own; and for input names that are not
572
+ * plain names or are the same.
573
+ */
574
+ export function prActionJob(forge: ForgeKind, options: Pick<PrLoopPipelineOptions, "actionJob" | "words"> = {}): PrActionJob | undefined {
575
+ if (!options.actionJob) return undefined;
576
+ if (forge === "gitlab") throw new Error("the action job runs on GitHub and Forgejo, whose workflows start on a comment and on a dispatch with inputs; on GitLab, run the product's action verb from a pipeline of its own");
577
+ const words = resolveProductWords(options.words);
578
+ const typed = commandWord(words, "action");
579
+ if (typed === undefined) throw new Error(`--action-job answers /${words.product} <action command>, and the words name no action command; name one in the words' commands, or drop --action-job`);
580
+ if (!words.bin) throw new Error("--action-job runs the product's action verb, and the words name no bin; chant has no action verb of its own");
581
+ const given = options.actionJob === true ? {} : options.actionJob.inputs ?? {};
582
+ const inputs = { member: given.member ?? words.noun[0], action: given.action ?? "action" };
583
+ for (const [role, name] of Object.entries(inputs)) {
584
+ if (!INPUT_NAME.test(name)) throw new Error(`the action job's ${role} input is a plain name, not ${JSON.stringify(name)}`);
585
+ }
586
+ if (inputs.member === inputs.action) throw new Error(`the action job's two inputs need two names, and both are ${inputs.action}`);
587
+ const command = withProductBin(["chant", typed, PRODUCT_ACTION_EVENT_FLAG].join(" "), words.bin);
588
+ return {
589
+ jobName: PR_ACTION_JOB,
590
+ comment: `/${words.product} ${typed}`,
591
+ inputs,
592
+ command,
593
+ script: ["set +e", command, 'code="$?"', `if [ "$code" -eq ${CHANT_EXIT.waiting} ]; then echo "The action waits for an approval."; exit 0; fi`, 'exit "$code"'].join("\n"),
594
+ env: {
595
+ [PRODUCT_ACTION_ENV.comment]: "${{ github.event.comment.body }}",
596
+ [PRODUCT_ACTION_ENV.member]: `\${{ github.event.inputs.${inputs.member} }}`,
597
+ [PRODUCT_ACTION_ENV.action]: `\${{ github.event.inputs.${inputs.action} }}`,
598
+ PR_NUMBER: "${{ github.event.issue.number }}",
599
+ GITHUB_TOKEN: GITHUB_JOB_TOKEN,
600
+ },
601
+ };
602
+ }
603
+
519
604
  /** The job answering `/<product> <plan word>` (#4620). */
520
605
  export const PR_COMMENT_PREVIEW_JOB = "comment-preview";
521
606
  /** The job that posts the comment preview's note and status (#4620). */
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Day-2 actions in the product pipeline (#4654): `actions: true` counts the
3
+ * `action` command as answered by the product's own workflow, and
4
+ * `actionJob` writes the job that answers the comment and a dispatch with a
5
+ * member and an action, running the product's action verb, which reads
6
+ * what was asked with `productActionFromEnv`.
7
+ */
8
+ import { describe, expect, test } from "vitest";
9
+ import { productPipelineJobs } from "./product-pipeline";
10
+ import { prActionJob, prLoopJobStage, PR_ACTION_JOB } from "./pr-pipeline";
11
+ import { assertProductWords, productActionFromEnv, PRODUCT_ACTION_ENV, PRODUCT_ACTION_EVENT_FLAG } from "../ci-product-words";
12
+ import { PLYWOOD, TERRAGUCCI } from "../__fixtures__/product-words";
13
+
14
+ const PW = { ...PLYWOOD, commands: { preview: "plan" as const, action: "action" as const } };
15
+ const TG = { ...TERRAGUCCI, commands: { plan: "plan" as const, action: "action" as const }, aliases: [], bin: "terragucci" };
16
+
17
+ describe("the action command in the product pipeline (#4654)", () => {
18
+ test("refused without actions, counted with it, and named among the comments", () => {
19
+ expect(() => productPipelineJobs("github", "production", { words: TG })).toThrow(/commands.action needs a action job/);
20
+ const tg = productPipelineJobs("github", "production", { words: TG, actions: true });
21
+ expect(tg.comments.action).toBe("/terragucci action");
22
+ // The product's own workflow answers it: no job here.
23
+ expect(tg.action).toBeUndefined();
24
+ });
25
+
26
+ test("actionJob writes the job, answering the comment and a dispatch with the stack and action inputs", () => {
27
+ const pw = productPipelineJobs("github", "production", { words: PW, actionJob: true });
28
+ expect(pw.comments.action).toBe("/plywood action");
29
+ expect(pw.action).toMatchObject({ jobName: PR_ACTION_JOB, comment: "/plywood action", inputs: { member: "stack", action: "action" } });
30
+ expect(pw.action!.command).toBe(`npx --no-install plywood action ${PRODUCT_ACTION_EVENT_FLAG}`);
31
+ expect(pw.action!.env).toMatchObject({
32
+ [PRODUCT_ACTION_ENV.comment]: "${{ github.event.comment.body }}",
33
+ [PRODUCT_ACTION_ENV.member]: "${{ github.event.inputs.stack }}",
34
+ [PRODUCT_ACTION_ENV.action]: "${{ github.event.inputs.action }}",
35
+ });
36
+ // A pending approval is the expected first answer, so chant's waiting exit is a green job.
37
+ expect(pw.action!.script).toContain('if [ "$code" -eq 3 ]; then');
38
+ expect(prLoopJobStage(PR_ACTION_JOB)).toBe("apply");
39
+ });
40
+
41
+ test("the inputs can be named, and the job is refused where it cannot run", () => {
42
+ expect(prActionJob("forgejo", { words: TG, actionJob: { inputs: { member: "root", action: "address" } } })!.inputs).toEqual({ member: "root", action: "address" });
43
+ expect(prActionJob("github", { words: PW })).toBeUndefined();
44
+ expect(() => prActionJob("gitlab", { words: PW, actionJob: true })).toThrow(/GitHub and Forgejo/);
45
+ expect(() => prActionJob("github", { words: { ...PW, commands: { preview: "plan" as const } }, actionJob: true })).toThrow(/name no action command/);
46
+ expect(() => prActionJob("github", { words: { ...PW, bin: undefined }, actionJob: true })).toThrow(/no bin/);
47
+ expect(() => prActionJob("github", { words: PW, actionJob: { inputs: { member: "a b" } } })).toThrow(/plain name/);
48
+ expect(() => prActionJob("github", { words: PW, actionJob: { inputs: { member: "action" } } })).toThrow(/two names/);
49
+ });
50
+ });
51
+
52
+ describe("what an action job was asked for (#4654)", () => {
53
+ const words = assertProductWords(PW, { jobs: ["plan", "action"] });
54
+
55
+ test("a comment, parsed as a comment is", () => {
56
+ expect(productActionFromEnv(words, { [PRODUCT_ACTION_ENV.comment]: "/plywood action shop/prod-us rotate" })).toEqual({ kind: "action", member: "shop/prod-us", address: "rotate", from: "comment" });
57
+ expect(productActionFromEnv(words, { [PRODUCT_ACTION_ENV.comment]: "/plywood action shop/prod-us" })).toMatchObject({ kind: "refused" });
58
+ expect(productActionFromEnv(words, { [PRODUCT_ACTION_ENV.comment]: "/plywood preview" })).toMatchObject({ kind: "refused", reason: expect.stringContaining("/plywood action <stack> <action>") });
59
+ });
60
+
61
+ test("a dispatch's two inputs, checked by the same rules", () => {
62
+ expect(productActionFromEnv(words, { [PRODUCT_ACTION_ENV.member]: "shop/prod-us", [PRODUCT_ACTION_ENV.action]: "rotate", [PRODUCT_ACTION_ENV.comment]: "" })).toEqual({
63
+ kind: "action",
64
+ member: "shop/prod-us",
65
+ address: "rotate",
66
+ from: "dispatch",
67
+ });
68
+ for (const [member, action] of [["", "rotate"], ["shop/prod-us", ""], ["../etc", "rotate"], ["shop/prod-us", "rotate; id"], ["shop/prod-us", "$(id)"], ["shop prod", "rotate"]]) {
69
+ expect(productActionFromEnv(words, { [PRODUCT_ACTION_ENV.member]: member, [PRODUCT_ACTION_ENV.action]: action })).toMatchObject({ kind: "refused" });
70
+ }
71
+ });
72
+
73
+ test("words with no action command answer no action", () => {
74
+ expect(productActionFromEnv(assertProductWords(PLYWOOD), { [PRODUCT_ACTION_ENV.member]: "s", [PRODUCT_ACTION_ENV.action]: "a" })).toMatchObject({ kind: "refused", reason: expect.stringMatching(/no action command/) });
75
+ });
76
+ });
@@ -34,7 +34,7 @@ import {
34
34
  type CiProductWords,
35
35
  type CiProductWordsInput,
36
36
  } from "../ci-product-words";
37
- import { prCommentLockJobs, prCommentPreviewJob, prLoopJobs, prLoopPostJob, prLoopRunner, prStaleJob, withProductBin, type PrCommentLockJob, type PrCommentPreviewJob, type PrLoopJob, type PrLoopPipelineOptions } from "./pr-pipeline";
37
+ import { prActionJob, prCommentLockJobs, prCommentPreviewJob, prLoopJobs, prLoopPostJob, prLoopRunner, prStaleJob, withProductBin, type PrActionJob, type PrCommentLockJob, type PrCommentPreviewJob, type PrLoopJob, type PrLoopPipelineOptions } from "./pr-pipeline";
38
38
  import type { DriverComponent } from "./driver";
39
39
  import type { ScheduledOpSpec } from "../lexicon";
40
40
  import type { CiRunner } from "../ci-jobs";
@@ -70,6 +70,15 @@ export interface ProductPipelineOptions extends Omit<PrLoopPipelineOptions, "wor
70
70
  * scheduled Ops.
71
71
  */
72
72
  agent?: boolean | ProductAgentOptions;
73
+ /**
74
+ * The product answers its `action` command (#4654) from a workflow of its
75
+ * own, such as terragucci's action workflow: `true` counts the command as
76
+ * answered, so words that map a word onto `action` are not refused, and
77
+ * `comments.action` names the comment. The pipeline writes no job for it.
78
+ * A product with no workflow of its own sets `actionJob` instead, and the
79
+ * pipeline writes the job ({@link ProductPipelineJobs.action}).
80
+ */
81
+ actions?: boolean;
73
82
  /**
74
83
  * The apply on merge from the component graph (#4588), when `waves` is
75
84
  * absent: the spec `pr-apply --wave-gate` runs, a wave per layer of
@@ -143,6 +152,12 @@ export interface ProductPipelineJobs {
143
152
  * job with the write token.
144
153
  */
145
154
  agent?: { comment: string; name: string; spec: ScheduledOpSpec };
155
+ /**
156
+ * The action job (#4654), with `actionJob`: the comment and the dispatch
157
+ * inputs it answers, and the product's action verb it runs. The GitHub and
158
+ * Forgejo lexicons render the same job.
159
+ */
160
+ action?: PrActionJob & { runner?: CiRunner };
146
161
  }
147
162
 
148
163
  /** An agent's settings as a product passes them (#4616): {@link OpAgentSpec} without the trigger, which the pipeline names. */
@@ -204,12 +219,14 @@ export function productPipelineJobs(forge: ForgeKind, env: string, options: Prod
204
219
  if (options.applyBeforeMerge || options.waves || options.componentWaves) jobs.push("apply");
205
220
  if (options.locks === "plan") jobs.push("lock", "unlock");
206
221
  if (options.agent) jobs.push("agent");
222
+ // #4654: the action command, answered by the product's own workflow (`actions`) or by the pipeline's action job.
223
+ if (options.actions || options.actionJob) jobs.push("action");
207
224
  // #4601: the note's merge sentence follows the jobs built here: waves on merge, an apply before merge, else a record for a release.
208
225
  // Words that ask for before-merge keep it when the pipeline has that job beside its waves.
209
226
  const built: CiProductApplyMode = options.waves || options.componentWaves ? "on-merge" : options.applyBeforeMerge ? "before-merge" : "release";
210
227
  const applyMode: CiProductApplyMode = options.words.applyMode === "before-merge" && options.applyBeforeMerge ? "before-merge" : built;
211
228
  const words = assertProductWords({ ...options.words, applyMode }, { jobs });
212
- const { waves: given, wavesSpecFile, member, agent: _agent, componentWaves, ...loop } = options;
229
+ const { waves: given, wavesSpecFile, member, agent: _agent, actions: _actions, componentWaves, ...loop } = options;
213
230
  const { respond } = options;
214
231
  // #4629: the pull request loop puts the responses on the apply and note jobs, as `chant build --pr-loop --respond` does.
215
232
  const prLoop: PrLoopPipelineOptions = { ...loop, words, gate: options.gate ?? words.prGate };
@@ -234,6 +251,8 @@ export function productPipelineJobs(forge: ForgeKind, env: string, options: Prod
234
251
  };
235
252
  const locks = prCommentLockJobs(forge, { locks: options.locks, words });
236
253
  if (locks.length > 0) out.locks = locks.map((job) => ({ ...job, ...defaultRunner }));
254
+ const action = prActionJob(forge, prLoop);
255
+ if (action) out.action = { ...action, ...(prLoopRunner(options, "apply") !== undefined ? { runner: prLoopRunner(options, "apply")! } : {}) };
237
256
  const stale = prStaleJob(forge, env, prLoop, member);
238
257
  if (stale) out.stale = { ...stale, ...defaultRunner };
239
258
  const preview = prCommentPreviewJob(forge, env, prLoop, member);
@@ -302,3 +302,166 @@ describe("the e2e harness's driver", () => {
302
302
  expect(run.reason).toBe("change-merge: Forgejo answered 500");
303
303
  });
304
304
  });
305
+
306
+ /**
307
+ * A product's pull request (chant#4650): the out-of-band command stands in
308
+ * for `terragucci request`, which pushes a branch and opens the pull request
309
+ * itself. The pipeline plans it as it would any other.
310
+ */
311
+ function productWorld(o: { neverOpens?: boolean; files?: string[]; staleOpen?: boolean } = {}) {
312
+ const w = world();
313
+ const pulls: Array<{ number: number; title: string; branch: string; head: string; files: string[]; open: boolean }> = [];
314
+ const posted: Array<{ pull: number; body: string; as: string }> = [];
315
+ let next = 100;
316
+ const make = async (branch: string, title: string) => {
317
+ const number = next++;
318
+ const head = `c${String(number).padStart(39, "0")}`;
319
+ pulls.push({ number, title, branch, head, files: o.files ?? ["apps/orders/main.tf"], open: true });
320
+ await w.bucket.put(
321
+ reportObjectKey(PREFIX, number, head, "plan"),
322
+ JSON.stringify({ stage: "plan", pr: number, head, op: `pr-${number}`, gate: "pr-apply", digest: `jcs1-sha256:${number}`, status: "planned", selection: { waves: [] }, members: [] }),
323
+ "application/json",
324
+ );
325
+ };
326
+ if (o.staleOpen) void make("request/bucket/orders", "Request bucket orders");
327
+ const forge: DriverPorts["forge"] = {
328
+ ...w.ports.forge,
329
+ openPulls: async () => pulls.filter((p) => p.open).map((p) => p.number),
330
+ findPull: async (branch) => {
331
+ const p = pulls.filter((x) => x.open && x.branch === branch).sort((a, b) => a.number - b.number)[0];
332
+ return p && { number: p.number, title: p.title, branch: p.branch, head: p.head };
333
+ },
334
+ pullInfo: async (n) => {
335
+ const p = pulls.find((x) => x.number === n);
336
+ return p && { number: p.number, title: p.title, branch: p.branch, head: p.head };
337
+ },
338
+ changedFiles: async (n) => pulls.find((x) => x.number === n)?.files ?? [],
339
+ postComment: async (pull, body, as) => void posted.push({ pull, body, as }),
340
+ };
341
+ const outOfBand = {
342
+ run: async (command: string[]) => {
343
+ if (!o.neverOpens) await make(command.at(-1)!, "Request bucket orders");
344
+ return 0;
345
+ },
346
+ };
347
+ return { ...w, pulls, posted, ports: { ...w.ports, forge, outOfBand } as DriverPorts };
348
+ }
349
+
350
+ function requestScenario(over: Partial<Scenario> = {}): Scenario {
351
+ return fanOut({
352
+ id: "tg-template-app",
353
+ product: "terragucci",
354
+ claim: "template/app-request",
355
+ steps: [
356
+ { id: "request", do: "out-of-band", command: ["terragucci", "request", "bucket", "orders", "request/bucket/orders"], expect: [{ exit: 0 }] },
357
+ { id: "pr", do: "await-pull", branch: "request/bucket/orders", title: "orders" },
358
+ { id: "pr-plan", do: "plan", pull: "pr", expect: [{ report: { status: "planned" } }] },
359
+ ],
360
+ ...over,
361
+ });
362
+ }
363
+
364
+ describe("a pull request a product opened", () => {
365
+ test("await-pull binds the product's pull request and its head, and plan reads the report there", async () => {
366
+ const w = productWorld();
367
+ const s = requestScenario();
368
+ expect(lintScenario(s)).toEqual([]);
369
+ const run = await runArm(s, "plain", w.ports, OPTS);
370
+ expect(run.outcome).toBe("held");
371
+ expect(verdictsOf(run, run).plain).toBe("pass");
372
+ expect(run.steps.map((x) => [x.id, x.pull, x.commit])).toEqual([
373
+ ["request", undefined, undefined],
374
+ ["pr", 100, `c${"100".padStart(39, "0")}`],
375
+ ["pr-plan", 100, `c${"100".padStart(39, "0")}`],
376
+ ]);
377
+ });
378
+
379
+ test("no pull request ever opened stalls at the await-pull limit, and is not a fail of the outcome", async () => {
380
+ const w = productWorld({ neverOpens: true });
381
+ const start = w.clock.t;
382
+ const run = await runArm(requestScenario(), "plain", w.ports, OPTS);
383
+ expect(run.outcome).toBe("stalled");
384
+ expect(run.reason).toBe("pr: no open pull request from request/bucket/orders within 300s");
385
+ expect(run.steps.at(-1)).toMatchObject({ id: "pr", stopped: { outcome: "stalled" } });
386
+ expect(w.clock.t - start).toBeGreaterThanOrEqual(300_000);
387
+ });
388
+
389
+ test("the BREAK run waits for the same branch, and never binds a pull request open before it started", async () => {
390
+ const fresh = productWorld();
391
+ const brk = await runArm(requestScenario(), "break", fresh.ports, OPTS);
392
+ expect(brk.steps.find((x) => x.id === "pr")?.pull).toBe(100);
393
+
394
+ const stale = productWorld({ staleOpen: true, neverOpens: true });
395
+ const run = await runArm(requestScenario(), "break", stale.ports, OPTS);
396
+ expect(run.outcome).toBe("stalled");
397
+ expect(run.reason).toBe("pr: pull request 100 from request/bucket/orders was open before the run started, and no new one came within 300s");
398
+ });
399
+
400
+ test("comment posts the exact body on the bound pull request, as the author unless the step says", async () => {
401
+ const w = productWorld();
402
+ const s = requestScenario();
403
+ s.steps.push(
404
+ { id: "invoke", do: "comment", pull: "pr", body: "/terragucci action orders rotate" },
405
+ { id: "again", do: "comment", pull: "pr", body: "/terragucci action orders rotate", as: "reviewer", expect: [{ pull: { title: "orders" } }] },
406
+ );
407
+ expect(lintScenario(s)).toEqual([]);
408
+ const run = await runArm(s, "plain", w.ports, OPTS);
409
+ expect(run.outcome).toBe("held");
410
+ expect(w.posted).toEqual([
411
+ { pull: 100, body: "/terragucci action orders rotate", as: "author" },
412
+ { pull: 100, body: "/terragucci action orders rotate", as: "reviewer" },
413
+ ]);
414
+ });
415
+
416
+ test("a pull outcome holds for exactly the files named, and names the extra path when there is one", async () => {
417
+ const outcome = { pull: { files: ["apps/orders/main.tf"], only: true } };
418
+ const s = () => {
419
+ const x = requestScenario();
420
+ (x.steps[1] as { expect?: unknown[] }).expect = [outcome];
421
+ return x;
422
+ };
423
+ expect(lintScenario(s())).toEqual([]);
424
+ expect((await runArm(s(), "plain", productWorld().ports, OPTS)).outcome).toBe("held");
425
+
426
+ const run = await runArm(s(), "plain", productWorld({ files: ["apps/orders/main.tf", "apps/other/main.tf"] }).ports, OPTS);
427
+ expect(run.outcome).toBe("broke");
428
+ expect(run.reason).toBe("pr: pull request 100 also changes apps/other/main.tf beyond the files named");
429
+
430
+ const missing = await runArm(s(), "plain", productWorld({ files: ["apps/other/main.tf"] }).ports, OPTS);
431
+ expect(missing.reason).toBe("pr: pull request 100 does not change apps/orders/main.tf");
432
+
433
+ const titled = requestScenario();
434
+ (titled.steps[1] as { expect?: unknown[] }).expect = [{ pull: { title: "payments" } }];
435
+ expect((await runArm(titled, "plain", productWorld().ports, OPTS)).reason).toBe('pr: pull request 100 is titled "Request bucket orders", which does not hold "payments"');
436
+ });
437
+
438
+ test("a gated outcome reads the gated requests asked since the run started: gated, then ok or failed", async () => {
439
+ const w = productWorld();
440
+ const at = (ms: number) => new Date(Date.parse("2026-10-28T10:00:00Z") + ms).toISOString();
441
+ const req = (ts: string, result?: "applied" | "failed") =>
442
+ ({
443
+ op: "tf-action",
444
+ gate: "tf-action",
445
+ digest: `d-${ts}`,
446
+ request: {},
447
+ pending: { timestamp: ts },
448
+ approvals: [],
449
+ ...(result ? { finished: { result } } : {}),
450
+ }) as unknown as import("../lifecycle/gated-request").GatedRequestRead;
451
+ const asked = [req(at(-60_000), "applied"), req(at(1000)), req(at(2000), "applied"), req(at(3000), "failed")];
452
+ const ports: DriverPorts = { ...w.ports, ledger: { runs: async () => [], gatedRequests: async (op) => (op === "tf-action" ? asked : []) } };
453
+ const s = (expect: Scenario["steps"][number]["expect"]) => fanOut({ steps: [{ id: "x", do: "out-of-band", command: ["true"], expect }] });
454
+
455
+ expect((await runArm(s([{ gated: { op: "tf-action", status: "gated", count: 1 } }, { gated: { op: "tf-action", status: "ok", count: 1 } }, { gated: { op: "tf-action", status: "failed" } }, { gated: { op: "tf-action", count: 3 } }]), "plain", ports, OPTS)).outcome).toBe("held");
456
+ expect((await runArm(s([{ gated: { op: "pulumi-stack-ops", status: "ok" } }]), "plain", ports, OPTS)).reason).toBe("x: no gated pulumi-stack-ops request ok on the ledger since the run started");
457
+ expect((await runArm(s([{ gated: { op: "tf-action", status: "ok", count: 2 } }]), "plain", ports, OPTS)).reason).toBe("x: 1 gated tf-action requests ok on the ledger, not 2");
458
+ expect((await runArm(s([{ gated: { op: "tf-action" } }]), "plain", w.ports, OPTS)).reason).toBe("x: a gated outcome needs the ledger's gated requests");
459
+ });
460
+
461
+ test("await-pull and comment stall without the forge reads they need", async () => {
462
+ const w = world();
463
+ const s = requestScenario();
464
+ const run = await runArm(s, "plain", { ...w.ports, outOfBand: { run: async () => 0 } }, OPTS);
465
+ expect(run.reason).toBe("pr: an await-pull step needs the forge's findPull");
466
+ });
467
+ });