@intentius/chant 0.124.14 → 0.124.15

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 (110) hide show
  1. package/dist/build.d.ts +6 -0
  2. package/dist/build.d.ts.map +1 -1
  3. package/dist/build.js +1 -0
  4. package/dist/change-set.d.ts +24 -2
  5. package/dist/change-set.d.ts.map +1 -1
  6. package/dist/change-set.js +50 -1
  7. package/dist/ci-jobs.d.ts +227 -0
  8. package/dist/ci-jobs.d.ts.map +1 -0
  9. package/dist/ci-jobs.js +448 -0
  10. package/dist/components/pr-pipeline.d.ts.map +1 -1
  11. package/dist/components/pr-pipeline.js +3 -2
  12. package/dist/composite.d.ts +10 -2
  13. package/dist/composite.d.ts.map +1 -1
  14. package/dist/composite.js +8 -0
  15. package/dist/discovery/collect.d.ts +2 -1
  16. package/dist/discovery/collect.d.ts.map +1 -1
  17. package/dist/discovery/collect.js +16 -1
  18. package/dist/discovery/fold-import.d.ts.map +1 -1
  19. package/dist/discovery/fold-import.js +2 -107
  20. package/dist/discovery/host-composite.d.ts +35 -0
  21. package/dist/discovery/host-composite.d.ts.map +1 -0
  22. package/dist/discovery/host-composite.js +93 -0
  23. package/dist/discovery/index.d.ts +9 -0
  24. package/dist/discovery/index.d.ts.map +1 -1
  25. package/dist/discovery/index.js +1 -1
  26. package/dist/gate-decision.d.ts +20 -9
  27. package/dist/gate-decision.d.ts.map +1 -1
  28. package/dist/gate-decision.js +72 -19
  29. package/dist/lifecycle/gate-audit.d.ts +69 -2
  30. package/dist/lifecycle/gate-audit.d.ts.map +1 -1
  31. package/dist/lifecycle/gate-audit.js +76 -2
  32. package/dist/lifecycle/gate-ledger.d.ts +24 -0
  33. package/dist/lifecycle/gate-ledger.d.ts.map +1 -1
  34. package/dist/lifecycle/gate-ledger.js +9 -1
  35. package/dist/op/activities/activity-contracts.d.ts +1 -1
  36. package/dist/op/activities/activity-contracts.js +1 -1
  37. package/dist/op/activities/change-set.d.ts +8 -3
  38. package/dist/op/activities/change-set.d.ts.map +1 -1
  39. package/dist/op/activities/change-set.js +5 -2
  40. package/dist/op/activities/reconcile.d.ts +28 -16
  41. package/dist/op/activities/reconcile.d.ts.map +1 -1
  42. package/dist/op/activities/reconcile.js +34 -20
  43. package/dist/op/builders.d.ts +1 -1
  44. package/dist/op/builders.d.ts.map +1 -1
  45. package/dist/op/builders.js +1 -1
  46. package/dist/op/op-waves-run.d.ts +1 -1
  47. package/dist/op/op-waves-run.d.ts.map +1 -1
  48. package/dist/op/op-waves-run.js +3 -3
  49. package/dist/workspace/__fixtures__/contract-repo.d.ts +7 -0
  50. package/dist/workspace/__fixtures__/contract-repo.d.ts.map +1 -1
  51. package/dist/workspace/__fixtures__/contract-repo.js +17 -1
  52. package/dist/workspace/__fixtures__/sessions.d.ts +1 -1
  53. package/dist/workspace/__fixtures__/sessions.d.ts.map +1 -1
  54. package/dist/workspace/__fixtures__/sessions.js +3 -3
  55. package/dist/workspace/change-set.schema.json +5 -3
  56. package/dist/workspace/ci-green-workflow.d.ts +3 -1
  57. package/dist/workspace/ci-green-workflow.d.ts.map +1 -1
  58. package/dist/workspace/ci-green-workflow.js +5 -2
  59. package/dist/workspace/class-data.d.ts +84 -0
  60. package/dist/workspace/class-data.d.ts.map +1 -0
  61. package/dist/workspace/class-data.js +238 -0
  62. package/dist/workspace/kinds.d.ts +3 -7
  63. package/dist/workspace/kinds.d.ts.map +1 -1
  64. package/dist/workspace/kinds.js +6 -40
  65. package/dist/workspace/principal-classes.d.ts +4 -11
  66. package/dist/workspace/principal-classes.d.ts.map +1 -1
  67. package/dist/workspace/principal-classes.js +11 -94
  68. package/package.json +1 -1
  69. package/src/build.ts +8 -0
  70. package/src/change-set.test.ts +48 -0
  71. package/src/change-set.ts +52 -2
  72. package/src/ci-jobs.test.ts +49 -0
  73. package/src/ci-jobs.ts +515 -0
  74. package/src/components/pr-pipeline.ts +3 -2
  75. package/src/composite.ts +15 -3
  76. package/src/discovery/collect.ts +15 -1
  77. package/src/discovery/fold-build-parity.test.ts +71 -0
  78. package/src/discovery/fold-import.ts +2 -113
  79. package/src/discovery/fold-project-provenance.test.ts +21 -4
  80. package/src/discovery/host-composite.ts +101 -0
  81. package/src/discovery/index.ts +11 -1
  82. package/src/gate-decision-bundle.test.ts +5 -4
  83. package/src/gate-decision-identity.test.ts +59 -6
  84. package/src/gate-decision.ts +81 -21
  85. package/src/lifecycle/gate-audit.test.ts +55 -1
  86. package/src/lifecycle/gate-audit.ts +116 -3
  87. package/src/lifecycle/gate-ledger.test.ts +20 -1
  88. package/src/lifecycle/gate-ledger.ts +33 -1
  89. package/src/op/activities/activity-contracts.ts +1 -1
  90. package/src/op/activities/change-set.ts +11 -3
  91. package/src/op/activities/lexicon-upgrade.test.ts +2 -0
  92. package/src/op/activities/reconcile.test.ts +62 -2
  93. package/src/op/activities/reconcile.ts +46 -22
  94. package/src/op/builders.ts +1 -1
  95. package/src/op/op-waves-run.ts +4 -3
  96. package/src/op/op-waves.test.ts +2 -0
  97. package/src/op/work-lease-run.test.ts +12 -4
  98. package/src/workspace/__fixtures__/contract-repo.ts +17 -1
  99. package/src/workspace/__fixtures__/sessions.ts +3 -3
  100. package/src/workspace/change-set.schema.json +5 -3
  101. package/src/workspace/ci-green-workflow.test.ts +4 -4
  102. package/src/workspace/ci-green-workflow.ts +5 -2
  103. package/src/workspace/class-data.test.ts +64 -0
  104. package/src/workspace/class-data.ts +236 -0
  105. package/src/workspace/kinds.ts +6 -35
  106. package/src/workspace/principal-classes.ts +11 -94
  107. package/src/workspace/records-formats.test.ts +7 -2
  108. package/src/workspace/records-sessions-write.test.ts +3 -3
  109. package/src/workspace/status-contract.e2e.test.ts +37 -0
  110. package/src/workspace/status-contract.test.ts +23 -21
package/src/ci-jobs.ts ADDED
@@ -0,0 +1,515 @@
1
+ /**
2
+ * The job primitives chant's three CI generators share (#3765): the scheduled
3
+ * Op pipeline (`generateOpsPipeline`), the Op waves pipeline
4
+ * (`generateOpWavesPipeline`) and the component pipeline (`chant build
5
+ * --components --generate`, with `--pr-loop`, `--wave-gate` and
6
+ * `--promote-to`). Each forge lexicon builds its documents from these, so a
7
+ * trigger, a token, a permission rule or an image default is decided once:
8
+ *
9
+ * - the image a generated job runs in, {@link CI_IMAGE};
10
+ * - the branches a trigger filters on, {@link triggerBranches};
11
+ * - the job token and secret expressions of GitHub Actions and Forgejo
12
+ * Actions, {@link GITHUB_JOB_TOKEN} and {@link githubSecret};
13
+ * - the `permissions:` a finding-mode needs and the rules for adding to it,
14
+ * {@link permissionsFor} and {@link mergePermissions};
15
+ * - the `setup` steps and `environment` a job may carry, checked once per
16
+ * forge ({@link assertSetupSteps}, {@link assertEnvironment},
17
+ * {@link gitlabSetupScript}, {@link assertGitlabEnvironment});
18
+ * - GitLab's `rules:` expressions and `id_tokens:` declaration.
19
+ *
20
+ * The Forgejo dialect (action refs, dropped `permissions:` and
21
+ * `environment:`, the header note naming what was dropped) is the forgejo
22
+ * lexicon's, in its `components/ci-jobs.ts`, since the transform it applies
23
+ * lives there.
24
+ */
25
+
26
+ import type { OpEnvironment, OpFindingMode, OpSetupStep, OpTrigger } from "./lexicon";
27
+
28
+ // ── Every forge ─────────────────────────────────────────────────────────────
29
+
30
+ /**
31
+ * The image every generated job runs in unless the caller names another. It
32
+ * carries node and npm, which `chant` needs, and git, which a job that reads
33
+ * the base commit or pushes to `chant/lifecycle` needs (#3789).
34
+ */
35
+ export const CI_IMAGE = "node:22";
36
+
37
+ /**
38
+ * The branch a `push` trigger filters on when it names none. A generator
39
+ * works from a spec, not a checkout, so it cannot read a project's real
40
+ * default branch; a project on another one names it.
41
+ */
42
+ export const DEFAULT_BRANCH = "main";
43
+
44
+ /**
45
+ * The branches a push trigger filters on: the ones given, or
46
+ * {@link DEFAULT_BRANCH} when none are. An empty list is none, on every
47
+ * forge.
48
+ */
49
+ export function pushBranches(branches: readonly string[] | undefined): string[] {
50
+ return branches && branches.length > 0 ? [...branches] : [DEFAULT_BRANCH];
51
+ }
52
+
53
+ /**
54
+ * The branches a trigger filters on: a `pull_request` trigger's list, or
55
+ * undefined for every branch; a `push` trigger's, with {@link pushBranches}'
56
+ * default; none for `cron`.
57
+ */
58
+ export function triggerBranches(trigger: OpTrigger): string[] | undefined {
59
+ switch (trigger.kind) {
60
+ case "cron":
61
+ return undefined;
62
+ case "pull_request":
63
+ return trigger.branches && trigger.branches.length > 0 ? [...trigger.branches] : undefined;
64
+ case "push":
65
+ return pushBranches(trigger.branches);
66
+ }
67
+ }
68
+
69
+ /** A job id every forge accepts, from a kebab- or camel-cased name. */
70
+ export function ciJobName(name: string): string {
71
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
72
+ }
73
+
74
+ /** A command template with each `{name}` part filled in. */
75
+ export function fillCommand(template: readonly string[], name: string): string[] {
76
+ return template.map((part) => part.replace("{name}", name));
77
+ }
78
+
79
+ /** `{ [key]: map }` when the map has an entry, else `{}`: for spreading an optional mapping into a document. */
80
+ export function nonEmpty<K extends string, V>(key: K, map: Record<string, V> | undefined): { [P in K]?: Record<string, V> } {
81
+ return map && Object.keys(map).length > 0 ? ({ [key]: map } as { [P in K]: Record<string, V> }) : {};
82
+ }
83
+
84
+ /**
85
+ * A job's `environment:` mapping. Always the mapping form, never the string
86
+ * shorthand, so adding a `url` later is a new key rather than a reshaped
87
+ * value. GitHub and GitLab read the same two keys.
88
+ */
89
+ export function environmentDoc(environment: OpEnvironment): { name: string; url?: string } {
90
+ return { name: environment.name, ...(environment.url === undefined ? {} : { url: environment.url }) };
91
+ }
92
+
93
+ /** The directory part of a relative path, `.` when there is none. */
94
+ export function dirnameOf(path: string): string {
95
+ const i = path.lastIndexOf("/");
96
+ return i <= 0 ? "." : path.slice(0, i);
97
+ }
98
+
99
+ // ── GitHub Actions and Forgejo Actions ──────────────────────────────────────
100
+
101
+ /** The runner label a generated job asks for; the Forgejo dialect rewrites it to the project's label. */
102
+ export const GITHUB_RUNNER = "ubuntu-latest";
103
+
104
+ /** The job token, which GitHub and Forgejo both mint for every run. */
105
+ export const GITHUB_JOB_TOKEN = "${{ github.token }}";
106
+
107
+ /** A repository secret, by name. */
108
+ export function githubSecret(name: string): string {
109
+ return `\${{ secrets.${name} }}`;
110
+ }
111
+
112
+ /**
113
+ * A repository secret, or the job token when the secret is unset (#3624). An
114
+ * unset secret reads as the empty string, so a workflow generated for a
115
+ * production token still runs in a fork or a fresh repository, with what the
116
+ * job token may do.
117
+ */
118
+ export function githubSecretOrJobToken(name: string): string {
119
+ return `\${{ secrets.${name} || github.token }}`;
120
+ }
121
+
122
+ /** Each name mapped from the repository secret of the same name. */
123
+ export function githubSecretEnv(names: readonly string[]): Record<string, string> {
124
+ return Object.fromEntries(names.map((n) => [n, githubSecret(n)]));
125
+ }
126
+
127
+ /**
128
+ * Least-privilege `permissions:` for a finding-mode. `report` needs no write
129
+ * access; `issue` needs only `issues: write`; `pull-request` (and
130
+ * `merge-request`, generated the same way when a GitLab-authored spec is
131
+ * targeted at github) needs `contents: write` to push the reconcile branch
132
+ * plus `pull-requests: write` to open the PR. `comment` changes nothing in
133
+ * the repository, so its whole scope is `{ contents: read, pull-requests:
134
+ * write }`.
135
+ */
136
+ export function permissionsForMode(mode: OpFindingMode): Record<string, "read" | "write"> {
137
+ switch (mode) {
138
+ case "issue":
139
+ return { contents: "read", issues: "write" };
140
+ case "comment":
141
+ return { contents: "read", "pull-requests": "write" };
142
+ case "pull-request":
143
+ case "merge-request":
144
+ return { contents: "write", "pull-requests": "write" };
145
+ case "report":
146
+ return { contents: "read" };
147
+ }
148
+ }
149
+
150
+ /**
151
+ * {@link permissionsForMode} on a trigger. A `pull_request` trigger reports
152
+ * its finding as a comment on the triggering PR itself (#2084): any mode but
153
+ * `report` posts something to act on a finding, so on that trigger every
154
+ * such mode also gets `pull-requests: write` for the comment.
155
+ */
156
+ export function permissionsFor(mode: OpFindingMode, trigger: OpTrigger): Record<string, "read" | "write"> {
157
+ const base = permissionsForMode(mode);
158
+ if (trigger.kind === "pull_request" && mode !== "report") return { ...base, "pull-requests": "write" };
159
+ return base;
160
+ }
161
+
162
+ /**
163
+ * Every scope `GITHUB_TOKEN` accepts in a workflow's `permissions:` mapping,
164
+ * kebab-cased as GitHub spells them. An additive scope outside this set is
165
+ * refused by name rather than emitted: GitHub ignores an unknown key, so
166
+ * `id_token` or `idToken` would generate a workflow that looks like it grants
167
+ * OIDC and hands the run no token at all.
168
+ */
169
+ export const GITHUB_TOKEN_SCOPES: ReadonlySet<string> = new Set([
170
+ "actions",
171
+ "attestations",
172
+ "checks",
173
+ "contents",
174
+ "deployments",
175
+ "discussions",
176
+ "id-token",
177
+ "issues",
178
+ "models",
179
+ "packages",
180
+ "pages",
181
+ "pull-requests",
182
+ "repository-projects",
183
+ "security-events",
184
+ "statuses",
185
+ ]);
186
+
187
+ /**
188
+ * Merge a spec's additive `permissions` over the finding-mode's own set
189
+ * (#2242), refusing by name anything that is not strictly additive:
190
+ *
191
+ * - a blanket `write-all`/`read-all`, in either the key or the value
192
+ * position, which is the exact thing {@link permissionsForMode} exists to
193
+ * avoid;
194
+ * - a scope GitHub does not define ({@link GITHUB_TOKEN_SCOPES}), because
195
+ * GitHub ignores the key and the run silently gets nothing;
196
+ * - a scope the mode already grants, at any value — additive means additive,
197
+ * so this can neither downgrade `contents: write` to read nor restate it.
198
+ * A mode whose set is wrong is fixed by changing the mode, where the
199
+ * scope and the behavior that spends it stay together;
200
+ * - `pull-requests: write` on a trigger with no pull request. Pull-request
201
+ * access is what the finding-modes own: `pull-request` grants it together
202
+ * with the `contents: write` needed to push the branch first, and
203
+ * `comment` grants it on the one trigger that carries a pull request to
204
+ * comment on. Adding it beside a mode that posts nothing, on a cron or
205
+ * push run, grants write access no step in the generated job can spend.
206
+ */
207
+ export function mergePermissions(
208
+ name: string,
209
+ base: Record<string, "read" | "write">,
210
+ additive: Record<string, "read" | "write">,
211
+ trigger: OpTrigger,
212
+ ): Record<string, "read" | "write"> {
213
+ const merged: Record<string, "read" | "write"> = { ...base };
214
+ for (const [rawScope, value] of Object.entries(additive)) {
215
+ const scope = rawScope.trim();
216
+ const where = `Scheduled Op "${name}" adds permission "${scope}: ${value}"`;
217
+ if (scope === "write-all" || scope === "read-all" || String(value).endsWith("-all")) {
218
+ throw new Error(
219
+ `${where}, a blanket grant. \`permissions\` on a scheduled Op is additive over the ` +
220
+ `least-privilege set its finding-mode needs, one named scope at a time. Name the scopes the ` +
221
+ `job actually spends (e.g. { "id-token": "write" }).`,
222
+ );
223
+ }
224
+ if (!GITHUB_TOKEN_SCOPES.has(scope)) {
225
+ throw new Error(
226
+ `${where}, which is not a GITHUB_TOKEN permission scope. GitHub ignores an unrecognized key, so ` +
227
+ `this would emit a workflow that reads as granted and hands the run nothing. Known scopes: ` +
228
+ `${[...GITHUB_TOKEN_SCOPES].sort().join(", ")}.`,
229
+ );
230
+ }
231
+ if (scope in base) {
232
+ throw new Error(
233
+ `${where}, but its finding-mode already grants "${scope}: ${base[scope]}". These permissions are ` +
234
+ `additive only — they never replace, widen or downgrade a scope the mode computed. Change the ` +
235
+ `Op's findingMode if that set is wrong, and add only scopes no mode grants (e.g. "id-token").`,
236
+ );
237
+ }
238
+ if (scope === "pull-requests" && trigger.kind !== "pull_request") {
239
+ throw new Error(
240
+ `${where}, but this Op's trigger is "${trigger.kind}", which carries no pull request. Pull-request ` +
241
+ `write access belongs to a finding-mode: "pull-request" grants it with the contents: write its ` +
242
+ `branch push needs, and "comment" grants it on the pull_request trigger. Set findingMode instead ` +
243
+ `of adding the scope here.`,
244
+ );
245
+ }
246
+ merged[scope] = value;
247
+ }
248
+ return merged;
249
+ }
250
+
251
+ /**
252
+ * Refs that name an action repository's own default branch. A generated
253
+ * workflow is committed once and then re-run unattended, often over a cloud
254
+ * role, so "whatever was pushed to that repo last" is not a version — the
255
+ * code that assumes the role can change between the run somebody reviewed and
256
+ * the next one. A release channel the action's author cuts deliberately (`v6`,
257
+ * `v6.2.4`, `stable`) or a commit sha is a version, and both pass.
258
+ */
259
+ const DEFAULT_BRANCH_REFS = new Set(["main", "master", "head", "default"]);
260
+
261
+ /** `owner/repo` or `owner/repo/subpath`, then `@ref`. */
262
+ const USES_PATTERN = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)((?:\/[A-Za-z0-9_.-]+)*)@([^\s@]+)$/;
263
+
264
+ /**
265
+ * Validate a `setup` list for GitHub or Forgejo Actions (#2242). A `run`
266
+ * entry needs a non-empty line and nothing else. A `uses` entry has to be a
267
+ * pinned `owner/repo[/subpath]@ref`: no bare `owner/repo`, since an unpinned
268
+ * action resolves to its default branch, and no ref in
269
+ * {@link DEFAULT_BRANCH_REFS} for the same reason spelled out loud. Local
270
+ * (`./path`) and container (`docker://`) refs are refused too — they are
271
+ * legal GitHub Actions, but the generator emits a workflow into a repository
272
+ * it has never seen, so it cannot know a local path resolves there.
273
+ */
274
+ export function assertSetupSteps(name: string, setup: OpSetupStep[]): void {
275
+ setup.forEach((step, index) => {
276
+ const where = `Scheduled Op "${name}" setup step ${index + 1}`;
277
+ if ("uses" in step) {
278
+ const ref = step.uses.trim();
279
+ const match = USES_PATTERN.exec(ref);
280
+ if (!match) {
281
+ throw new Error(
282
+ `${where} has \`uses: "${step.uses}"\`, which is not a pinned action reference. ` +
283
+ `Write it as owner/repo@ref (optionally owner/repo/subpath@ref), e.g. ` +
284
+ `"aws-actions/configure-aws-credentials@v6". A local "./path" or "docker://" ref is not ` +
285
+ `accepted here: this generator emits a workflow into a repository it cannot inspect, so it ` +
286
+ `has no way to tell whether such a ref resolves there.`,
287
+ );
288
+ }
289
+ const gitRef = match[4];
290
+ if (DEFAULT_BRANCH_REFS.has(gitRef.toLowerCase())) {
291
+ throw new Error(
292
+ `${where} pins \`uses: "${step.uses}"\` to "${gitRef}", the action repository's own default ` +
293
+ `branch, which names whatever was pushed there last rather than a version. A generated ` +
294
+ `workflow is committed once and re-run unattended, often over a cloud role, so pin a release ` +
295
+ `tag or a commit sha instead (e.g. "${match[1]}/${match[2]}@v1" or "@<40-char sha>").`,
296
+ );
297
+ }
298
+ return;
299
+ }
300
+ if (step.run.trim() === "") {
301
+ throw new Error(`${where} has an empty \`run\` line. Give it a command, or drop the entry.`);
302
+ }
303
+ });
304
+ }
305
+
306
+ /** One setup entry as a GitHub Actions step: `with:` and `env:` only when they hold something. */
307
+ export function setupStepDoc(step: OpSetupStep): Record<string, unknown> {
308
+ if ("uses" in step) {
309
+ return {
310
+ uses: step.uses,
311
+ ...nonEmpty("with", step.with),
312
+ ...nonEmpty("env", step.env),
313
+ };
314
+ }
315
+ return { run: step.run, ...nonEmpty("env", step.env) };
316
+ }
317
+
318
+ /**
319
+ * Validate an `environment` for GitHub Actions (#2257). GitHub creates an
320
+ * environment it has never seen on first use rather than failing the run,
321
+ * and an environment created that way carries no protection rules at all —
322
+ * so a job can name one and read as gated while being gated by nothing.
323
+ * Neither the generator nor GitHub can tell those apart at build time, which
324
+ * is why what is refused here is only the shape that could never bind: a
325
+ * name that is blank, and a `url` that is neither absolute nor an expression
326
+ * the forge resolves.
327
+ */
328
+ export function assertEnvironment(name: string, environment: OpEnvironment): void {
329
+ const where = `Scheduled Op "${name}" environment`;
330
+ if (environment.name.trim() === "") {
331
+ throw new Error(
332
+ `${where} has an empty \`name\`. An environment is named repository configuration — the ` +
333
+ `protection rules and reviewers live on the environment, not in this workflow — so there is ` +
334
+ `nothing for a blank name to resolve to. Give it the environment's name, or drop the option.`,
335
+ );
336
+ }
337
+ if (environment.url === undefined) return;
338
+ const url = environment.url.trim();
339
+ if (url === "") {
340
+ throw new Error(`${where} "${environment.name}" has an empty \`url\`. Omit the field rather than setting it to "".`);
341
+ }
342
+ if (!/^https?:\/\//.test(url) && !url.includes("${{")) {
343
+ throw new Error(
344
+ `${where} "${environment.name}" has \`url: "${environment.url}"\`, which is neither an absolute ` +
345
+ `http(s) URL nor a \${{ }} expression. GitHub renders this value as the deployment's own link, ` +
346
+ `so a relative path becomes a dead link on the environment page rather than an error anywhere. ` +
347
+ `Write the full URL, or an expression the run resolves to one.`,
348
+ );
349
+ }
350
+ }
351
+
352
+ // ── GitLab CI ───────────────────────────────────────────────────────────────
353
+
354
+ /** The pipeline source GitLab reports for a merge-request pipeline. */
355
+ export const GITLAB_MERGE_REQUEST_SOURCE = '$CI_PIPELINE_SOURCE == "merge_request_event"';
356
+
357
+ /** The pipeline source GitLab reports for a pipeline schedule. */
358
+ export const GITLAB_SCHEDULE_SOURCE = '$CI_PIPELINE_SOURCE == "schedule"';
359
+
360
+ /** A job variable that makes the runner clone the whole history, which a job reading the base commit needs. */
361
+ export const GITLAB_FULL_HISTORY = { GIT_DEPTH: "0" } as const;
362
+
363
+ /** The `rules:` if-expression for a push to `branch`, a quoted name or an expression such as `$CI_DEFAULT_BRANCH`. */
364
+ export function gitlabPushRule(branch: string): string {
365
+ return `$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == ${branch}`;
366
+ }
367
+
368
+ /**
369
+ * Refuse a branch name that cannot be interpolated into a `rules:`
370
+ * if-expression. The expression is a string GitLab parses, so a `"` would end
371
+ * it early and a `$` would expand as a variable — either one silently changes
372
+ * which pipelines match the job, which is worse than not generating it.
373
+ * `subject` names what filters, such as `Scheduled Op "apply"`.
374
+ */
375
+ export function assertGitlabBranch(subject: string, branch: string): void {
376
+ if (branch.trim() === "") {
377
+ throw new Error(`${subject} has an empty branch filter. Name a branch, or drop the filter.`);
378
+ }
379
+ if (/["$\\]/.test(branch)) {
380
+ throw new Error(
381
+ `${subject} filters on branch "${branch}", which carries a character this generator ` +
382
+ `cannot put in a GitLab \`rules:\` expression: a quote would end the expression early and a "$" ` +
383
+ `would expand as a CI/CD variable, either of which silently changes which pipelines run the job. ` +
384
+ `Name a branch without \`"\`, \`$\` or \`\\\`.`,
385
+ );
386
+ }
387
+ }
388
+
389
+ /**
390
+ * One `rules:` entry per branch a trigger filters on, each checked by
391
+ * {@link assertGitlabBranch}. Two or more branches are two or more entries:
392
+ * `rules:` is an OR over its list, which is how GitLab spells the alternation
393
+ * github expresses as a `branches:` array. A cron trigger is selected by
394
+ * `selector`, the CI/CD variable a pipeline schedule sets, and the Op's name.
395
+ */
396
+ export function gitlabRules(subject: string, trigger: OpTrigger, selector: { variable: string; value: string }): Array<{ if: string }> {
397
+ switch (trigger.kind) {
398
+ case "cron":
399
+ return [{ if: `${GITLAB_SCHEDULE_SOURCE} && $${selector.variable} == "${selector.value}"` }];
400
+ case "pull_request": {
401
+ const branches = triggerBranches(trigger);
402
+ if (!branches) return [{ if: GITLAB_MERGE_REQUEST_SOURCE }];
403
+ return branches.map((branch) => {
404
+ assertGitlabBranch(subject, branch);
405
+ return { if: `${GITLAB_MERGE_REQUEST_SOURCE} && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "${branch}"` };
406
+ });
407
+ }
408
+ case "push":
409
+ return pushBranches(trigger.branches).map((branch) => {
410
+ assertGitlabBranch(subject, branch);
411
+ return { if: gitlabPushRule(JSON.stringify(branch)) };
412
+ });
413
+ }
414
+ }
415
+
416
+ /**
417
+ * The `id_tokens:` entry an `id-token: write` spec gets. The name is the
418
+ * environment variable the JWT lands in, which the job's own setup line reads
419
+ * (`aws sts assume-role-with-web-identity --web-identity-token
420
+ * "$CHANT_ID_TOKEN"`, or the provider's equivalent).
421
+ *
422
+ * `$CI_SERVER_URL` as the audience is GitLab's own documented default: an
423
+ * identity provider federated to a GitLab instance is registered with that
424
+ * instance's URL as its audience, and the variable expands to exactly that on
425
+ * gitlab.com and on a self-managed instance alike.
426
+ */
427
+ export const GITLAB_ID_TOKEN_NAME = "CHANT_ID_TOKEN";
428
+ export const GITLAB_ID_TOKEN_AUDIENCE = "$CI_SERVER_URL";
429
+
430
+ /**
431
+ * Turn additive `permissions` (#2242) into the one GitLab declaration that
432
+ * carries the same meaning, refusing everything else by name.
433
+ *
434
+ * `id-token: write` is that one: GitLab's OIDC surface is `id_tokens:`, a
435
+ * per-job declaration of a JWT the job exchanges for cloud credentials
436
+ * itself. `id-token: read` is refused rather than mapped, because GitLab
437
+ * either mints the token into the job or does not. Every other scope is
438
+ * refused: GitLab has no per-job token-scope mapping at all, and a scope
439
+ * quietly dropped would emit a job that reads as granted and runs with
440
+ * nothing.
441
+ */
442
+ export function gitlabIdTokens(name: string, permissions: Record<string, "read" | "write"> | undefined): Record<string, unknown> | undefined {
443
+ let wantsIdToken = false;
444
+ for (const [rawScope, value] of Object.entries(permissions ?? {})) {
445
+ const scope = rawScope.trim();
446
+ if (scope === "id-token") {
447
+ if (value !== "write") {
448
+ throw new Error(
449
+ `Scheduled Op "${name}" adds permission "id-token: ${value}", but GitLab either mints an ` +
450
+ `OIDC token into a job or does not — there is no read-only half of an \`id_tokens:\` ` +
451
+ `declaration. Ask for { "id-token": "write" }, or drop the option.`,
452
+ );
453
+ }
454
+ wantsIdToken = true;
455
+ continue;
456
+ }
457
+ throw new Error(
458
+ `Scheduled Op "${name}" adds permission "${scope}: ${value}", but GitLab CI has no per-job ` +
459
+ `token-scope mapping — there is no \`permissions:\` key to add it to (#2242). The one scope that ` +
460
+ `does cross over is "id-token": "write", which becomes an \`id_tokens:\` declaration. Drop the ` +
461
+ `option here, or generate this Op for github.`,
462
+ );
463
+ }
464
+ return wantsIdToken ? { [GITLAB_ID_TOKEN_NAME]: { aud: GITLAB_ID_TOKEN_AUDIENCE } } : undefined;
465
+ }
466
+
467
+ /**
468
+ * A `setup` list as GitLab `script:` lines. A `uses` entry is a GitHub
469
+ * Actions marketplace action, which GitLab has no shape for, so it is refused
470
+ * by name rather than dropped. `subject` names whose setup it is, such as
471
+ * `Scheduled Op "apply"`.
472
+ */
473
+ export function gitlabSetupScript(subject: string, setup: readonly OpSetupStep[] | undefined): string[] {
474
+ return (setup ?? []).map((step, index) => {
475
+ if ("uses" in step) {
476
+ throw new Error(
477
+ `${subject} setup step ${index + 1} is \`uses: "${step.uses}"\`, a GitHub Actions ` +
478
+ `marketplace action. GitLab CI jobs run \`script\` lines only, so there is nothing to translate it ` +
479
+ `into (#2242). Express the setup as a \`{ run }\` entry, or generate it for github/forgejo.`,
480
+ );
481
+ }
482
+ return step.run;
483
+ });
484
+ }
485
+
486
+ /**
487
+ * Validate an `environment` on GitLab's own terms (#2257). A GitLab job
488
+ * naming an environment that does not exist creates an unprotected one on
489
+ * first deploy rather than failing, so the only shapes worth refusing at
490
+ * build time are the ones that could never bind: a blank name, and a `url`
491
+ * that is neither absolute nor a variable expression GitLab expands, which
492
+ * would render as a dead "View deployment" link.
493
+ */
494
+ export function assertGitlabEnvironment(name: string, environment: OpEnvironment): void {
495
+ const where = `Scheduled Op "${name}" environment`;
496
+ if (environment.name.trim() === "") {
497
+ throw new Error(
498
+ `${where} has an empty \`name\`. A GitLab environment is a project object, and its approval ` +
499
+ `rules live on that object rather than in this file, so a blank name resolves to nothing. ` +
500
+ `Give it the environment's name, or drop the option.`,
501
+ );
502
+ }
503
+ if (environment.url === undefined) return;
504
+ const url = environment.url.trim();
505
+ if (url === "") {
506
+ throw new Error(`${where} "${environment.name}" has an empty \`url\`. Omit the field rather than setting it to "".`);
507
+ }
508
+ if (!/^https?:\/\//.test(url) && !url.includes("$")) {
509
+ throw new Error(
510
+ `${where} "${environment.name}" has \`url: "${environment.url}"\`, which is neither an absolute ` +
511
+ `http(s) URL nor a variable expression GitLab expands. It becomes the environment's own link, ` +
512
+ `so a relative path is a dead link on the environment page rather than an error anywhere.`,
513
+ );
514
+ }
515
+ }
@@ -38,6 +38,7 @@
38
38
 
39
39
  import type { ForgeKind } from "../pr-forge";
40
40
  import { PR_APPLY_GATE } from "../pr-loop";
41
+ import { CI_IMAGE, GITHUB_JOB_TOKEN } from "../ci-jobs";
41
42
 
42
43
  /** Where both jobs write their reports, kept as a CI artifact. */
43
44
  export const PR_LOOP_REPORT_DIR = ".chant/pr";
@@ -55,7 +56,7 @@ export const PR_APPLY_RECORD = ".chant/pr-resume/pr-apply.json";
55
56
  * `PR_LOOP_SETUP` adds OpenTofu on top of it. A caller who sets `image`
56
57
  * brings both and gets no setup lines.
57
58
  */
58
- export const PR_LOOP_IMAGE = "node:22";
59
+ export const PR_LOOP_IMAGE = CI_IMAGE;
59
60
 
60
61
  /** Installs OpenTofu into `PR_LOOP_IMAGE`. */
61
62
  export const PR_LOOP_SETUP = [
@@ -113,7 +114,7 @@ export function prLoopJobs(forge: ForgeKind, env: string, options: PrLoopPipelin
113
114
  ...(member ? ["--member", member] : []),
114
115
  ];
115
116
  const github = forge !== "gitlab";
116
- const token: Record<string, string> = github ? { GITHUB_TOKEN: "${{ github.token }}" } : {};
117
+ const token: Record<string, string> = github ? { GITHUB_TOKEN: GITHUB_JOB_TOKEN } : {};
117
118
  return [
118
119
  {
119
120
  jobName: "plan",
package/src/composite.ts CHANGED
@@ -115,11 +115,23 @@ export class CompositeRegistry {
115
115
  * });
116
116
  * export const storage = SecureStorage({ name: "data" });
117
117
  * ```
118
+ *
119
+ * `D` (chant#3787) lets a lexicon give the definition a more precise call
120
+ * signature than `(props: P) => M`, such as a generic one whose members' types
121
+ * depend on the literal props it is called with. It is a type only: the value
122
+ * is the same definition, and `D` must still be a `CompositeDefinition<P, M>`,
123
+ * so an intersection with the precise signature first is the usual form. It
124
+ * is passed as a type argument rather than by casting the result, because the
125
+ * fold recognizes a composite by its `export const X = Composite(...)` shape.
118
126
  */
119
- export function Composite<P, M extends CompositeFactoryMembers = CompositeMembers>(
127
+ export function Composite<
128
+ P,
129
+ M extends CompositeFactoryMembers = CompositeMembers,
130
+ D extends CompositeDefinition<P, M> = CompositeDefinition<P, M>,
131
+ >(
120
132
  factory: (props: P) => M,
121
133
  name?: string,
122
- ): CompositeDefinition<P, M> {
134
+ ): D {
123
135
  const id = Symbol();
124
136
  const compositeName = name ?? "anonymous";
125
137
 
@@ -163,7 +175,7 @@ export function Composite<P, M extends CompositeFactoryMembers = CompositeMember
163
175
 
164
176
  CompositeRegistry.register(definition as CompositeDefinition<unknown>);
165
177
 
166
- return definition;
178
+ return definition as D;
167
179
  }
168
180
 
169
181
  /** Non-enumerable, symbol-keyed: invisible to serializers, spreads and comparisons, like provenance. */
@@ -4,6 +4,7 @@ import { isCompositeInstance, expandComposite, compositeOfMember } from "../comp
4
4
  import { isLexiconOutput } from "../lexicon-output";
5
5
  import { DiscoveryError } from "../errors";
6
6
  import { setProvenance, type EntityProvenance } from "../provenance";
7
+ import { expandHostComposite, hostCompositeName } from "./host-composite";
7
8
 
8
9
  /**
9
10
  * The entity key for an export. `export default` is per-module — the `Op` pattern
@@ -119,6 +120,18 @@ function enumerateEntries(
119
120
  provenance: { sourceFile: file, compositeInstance: name },
120
121
  });
121
122
  }
123
+ } else if (hostCompositeName(value) !== undefined) {
124
+ // chant#3612 — a host composite instance the fold resolved, expanded
125
+ // here rather than by one caller, so `build()` and `foldProject`
126
+ // report the same entities for it. See ./host-composite.ts.
127
+ for (const [expandedName, entity] of expandHostComposite(name, value as Record<string, unknown>)) {
128
+ entries.push({
129
+ bareKey: expandedName,
130
+ value: entity,
131
+ file,
132
+ provenance: { sourceFile: file, compositeInstance: name },
133
+ });
134
+ }
122
135
  } else if (isLexiconOutput(value)) {
123
136
  // LexiconOutput is not a Declarable but build() expects to find them in
124
137
  // the entities map so it can collect and pass them to serializers.
@@ -133,7 +146,8 @@ function enumerateEntries(
133
146
  /**
134
147
  * Collects all declarable entities from imported modules.
135
148
  * CompositeInstance exports are expanded into individual entities
136
- * with `{exportName}_{memberName}` naming.
149
+ * with `{exportName}_{memberName}` naming, and so are host composite
150
+ * instances the fold resolved (chant#3612, ./host-composite.ts).
137
151
  * LexiconOutput exports are also collected so that build() can
138
152
  * extract them and pass them to the serializer.
139
153
  *