@caelo-cms/provisioning 0.12.16 → 0.12.18

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 (74) hide show
  1. package/dist/adopt-existing.d.ts +18 -0
  2. package/dist/adopt-existing.d.ts.map +1 -1
  3. package/dist/adopt-existing.js +46 -1
  4. package/dist/adopt-existing.js.map +1 -1
  5. package/dist/agent-db.js +1522 -101
  6. package/dist/audit-job-setup.d.ts +0 -9
  7. package/dist/audit-job-setup.d.ts.map +1 -1
  8. package/dist/audit-job-setup.js +17 -27
  9. package/dist/audit-job-setup.js.map +1 -1
  10. package/dist/converge-job-gcp.d.ts +0 -7
  11. package/dist/converge-job-gcp.d.ts.map +1 -1
  12. package/dist/converge-job-gcp.js +1 -36
  13. package/dist/converge-job-gcp.js.map +1 -1
  14. package/dist/infra-contract.d.ts +1 -1
  15. package/dist/infra-contract.d.ts.map +1 -1
  16. package/dist/infra-contract.js +11 -1
  17. package/dist/infra-contract.js.map +1 -1
  18. package/dist/operator-access.d.ts +23 -0
  19. package/dist/operator-access.d.ts.map +1 -1
  20. package/dist/operator-access.js +62 -2
  21. package/dist/operator-access.js.map +1 -1
  22. package/dist/owner-email.d.ts +79 -0
  23. package/dist/owner-email.d.ts.map +1 -0
  24. package/dist/owner-email.js +170 -0
  25. package/dist/owner-email.js.map +1 -0
  26. package/dist/reporting-job-catalog.d.ts.map +1 -1
  27. package/dist/reporting-job-catalog.js +3 -2
  28. package/dist/reporting-job-catalog.js.map +1 -1
  29. package/dist/stack-contract.d.ts +12 -7
  30. package/dist/stack-contract.d.ts.map +1 -1
  31. package/dist/stack-contract.js +24 -6
  32. package/dist/stack-contract.js.map +1 -1
  33. package/dist/wizard.d.ts.map +1 -1
  34. package/dist/wizard.js +30 -12
  35. package/dist/wizard.js.map +1 -1
  36. package/dist/wizards/gcp-cost.d.ts.map +1 -1
  37. package/dist/wizards/gcp-cost.js +7 -2
  38. package/dist/wizards/gcp-cost.js.map +1 -1
  39. package/dist/wizards/gcp-install-job.d.ts +24 -0
  40. package/dist/wizards/gcp-install-job.d.ts.map +1 -1
  41. package/dist/wizards/gcp-install-job.js +119 -13
  42. package/dist/wizards/gcp-install-job.js.map +1 -1
  43. package/dist/wizards/gcp-pulumi.d.ts +0 -6
  44. package/dist/wizards/gcp-pulumi.d.ts.map +1 -1
  45. package/dist/wizards/gcp-pulumi.js +0 -7
  46. package/dist/wizards/gcp-pulumi.js.map +1 -1
  47. package/dist/wizards/gcp.js +0 -1
  48. package/dist/wizards/gcp.js.map +1 -1
  49. package/package.json +2 -2
  50. package/src/admin-memory.test.ts +49 -11
  51. package/src/adopt-existing.test.ts +190 -0
  52. package/src/adopt-existing.ts +56 -1
  53. package/src/audit-job-setup.test.ts +14 -39
  54. package/src/audit-job-setup.ts +17 -35
  55. package/src/converge-job-gcp.test.ts +2 -5
  56. package/src/converge-job-gcp.ts +1 -46
  57. package/src/infra-contract.test.ts +4 -3
  58. package/src/infra-contract.ts +11 -1
  59. package/src/operator-access.ts +81 -2
  60. package/src/owner-email.test.ts +302 -0
  61. package/src/owner-email.ts +214 -0
  62. package/src/reporting-job-catalog.ts +3 -2
  63. package/src/reporting-job-setup.test.ts +1 -1
  64. package/src/stack-contract.ts +25 -7
  65. package/src/stack-converge.test.ts +43 -2
  66. package/src/wizard.ts +30 -10
  67. package/src/wizards/gcp-cost.ts +8 -2
  68. package/src/wizards/gcp-install-job.test.ts +180 -0
  69. package/src/wizards/gcp-install-job.ts +130 -12
  70. package/src/wizards/gcp-pulumi.ts +0 -7
  71. package/src/wizards/gcp.ts +0 -1
  72. package/stacks/azure/index.ts +4 -0
  73. package/stacks/gcp/index.ts +11 -0
  74. package/stacks/gcp-firebase/index.ts +11 -0
@@ -1790,6 +1790,19 @@ const GCP_COMMON: readonly IamInvariant[] = [
1790
1790
  onFailure: "warn",
1791
1791
  why: "staging's visitor-AI key is stored for the staging gateway; without it only storing the key fails",
1792
1792
  },
1793
+ {
1794
+ // #1764 — read-only: the services the project enables and their quotas.
1795
+ // The admin reads the Cloud Run CPU quota at every job start and sizes
1796
+ // the quality check's Lighthouse runs and a search index's tasks from it
1797
+ // (admin-core reporting-jobs/run-capacity.ts); a fixed width stopped
1798
+ // fresh installs on a new project's 20 vCPU.
1799
+ stackResource: "run-quota-viewer",
1800
+ role: "roles/serviceusage.serviceUsageViewer",
1801
+ member: "run-sa",
1802
+ target: { kind: "project" },
1803
+ onFailure: "abort",
1804
+ why: "the admin sizes the quality check and search index jobs from the project's Cloud Run CPU quota; without it every Stage audit and large index fails to start",
1805
+ },
1793
1806
  ];
1794
1807
 
1795
1808
  /** v0.6.6 — a custom runtime SA gets no telemetry roles implicitly. */
@@ -2201,13 +2214,18 @@ export const ADMIN_MEMORY_DEFAULT = "2Gi";
2201
2214
  /**
2202
2215
  * Epic #1644 (#1649) — the live and the staging gateway's memory. Search,
2203
2216
  * suggest and read answer from collection index files the gateway keeps
2204
- * parsed in memory (`CAELO_COLLECTIONS_CACHE_MB`, 256 MiB by default, plus
2205
- * the release being opened), next to its visitor handlers: 512 MiB left no
2206
- * room for that. AWS (1024 MB Fargate tasks) and Azure (1.0Gi apps) already
2207
- * run every service at 1 GiB; `upgrade` raises a Google Cloud gateway below
2208
- * it (never lowers a larger value, stack-converge.ts planServiceMemory).
2209
- */
2210
- export const GATEWAY_MEMORY_DEFAULT = "1Gi";
2217
+ * parsed in memory (`CAELO_COLLECTIONS_CACHE_MB`,
2218
+ * COLLECTIONS_CACHE_MB_DEFAULT), and a search by meaning embeds the query
2219
+ * with a model the gateway loads itself: GATEWAY_PEAK_WITH_MODEL_MIB
2220
+ * (@caelo-cms/shared gateway-memory.ts) measured on Cloud Run. 1 GiB held
2221
+ * the model only just and the cache not at all: on 2026-11-26 (#1745) a searchVIU
2222
+ * gateway was lost in the middle of its first semantic search. 2 GiB holds
2223
+ * both; `upgrade` raises a Google Cloud gateway below it (never lowers a
2224
+ * larger value, stack-converge.ts planServiceMemory), the Azure stack sizes
2225
+ * its gateway app from it, and the AWS stack defines no gateway task yet
2226
+ * (#749). Request-billed, so it costs memory only while a request runs.
2227
+ */
2228
+ export const GATEWAY_MEMORY_DEFAULT = "2Gi";
2211
2229
 
2212
2230
  /** The memory upgrade raises each Cloud Run service to (null: the stacks' alone). */
2213
2231
  export const SERVICE_MEMORY_FLOOR: Readonly<Record<CloudRunSlug, string | null>> = {
@@ -72,6 +72,8 @@ const GW_TELEMETRY = [
72
72
  { role: "roles/monitoring.metricWriter", members: [GW_SA, STG_SA] },
73
73
  ];
74
74
  const IAP_AGENT = "serviceAccount:service-42@gcp-sa-iap.iam.gserviceaccount.com";
75
+ /** #1764 — the admin reads the project's Cloud Run CPU quota. */
76
+ const RUN_QUOTA = { role: "roles/serviceusage.serviceUsageViewer", members: [RUN_SA] };
75
77
 
76
78
  const firebase: InstallTarget = {
77
79
  provider: "gcp-firebase",
@@ -573,6 +575,7 @@ describe("ensureStackInvariants", () => {
573
575
  { role: "roles/firebasehosting.admin", members: [RUN_SA] },
574
576
  { role: "roles/logging.logWriter", members: [RUN_SA] },
575
577
  { role: "roles/monitoring.metricWriter", members: [RUN_SA] },
578
+ RUN_QUOTA,
576
579
  ...GW_TELEMETRY,
577
580
  ]),
578
581
  ],
@@ -725,7 +728,11 @@ describe("ensureStackInvariants", () => {
725
728
  it("regression A5: adds the gateway run.viewer + telemetry roles an older install lacks", async () => {
726
729
  const answers = fullFirebase();
727
730
  answers["projects get-iam-policy"] = [
728
- policy([{ role: "roles/firebasehosting.admin", members: [RUN_SA] }, ...GW_TELEMETRY]),
731
+ policy([
732
+ { role: "roles/firebasehosting.admin", members: [RUN_SA] },
733
+ RUN_QUOTA,
734
+ ...GW_TELEMETRY,
735
+ ]),
729
736
  ];
730
737
  answers["run services get-iam-policy caelo-production-data-gateway"] = [
731
738
  policy([{ role: "roles/run.invoker", members: ["allUsers"] }]),
@@ -779,10 +786,42 @@ describe("ensureStackInvariants", () => {
779
786
  expect(failed?.error).toContain("Re-run the installer");
780
787
  });
781
788
 
789
+ it("#1764 — gives an older install's admin the quota read, and aborts when it cannot", async () => {
790
+ const without = () => {
791
+ const answers = fullFirebase();
792
+ answers["projects get-iam-policy"] = [
793
+ policy([
794
+ { role: "roles/firebasehosting.admin", members: [RUN_SA] },
795
+ { role: "roles/logging.logWriter", members: [RUN_SA] },
796
+ { role: "roles/monitoring.metricWriter", members: [RUN_SA] },
797
+ ...GW_TELEMETRY,
798
+ ]),
799
+ ];
800
+ return answers;
801
+ };
802
+ const added = fakeGcloud(without());
803
+ const report = await ensureStackInvariants(firebase, { run: added.run, sleep: async () => {} });
804
+ expect(report.mustAbort).toBe(false);
805
+ expect(added.calls).toContain(
806
+ `projects add-iam-policy-binding acme --member=${RUN_SA} --role=roles/serviceusage.serviceUsageViewer --condition=None --quiet --format=none`,
807
+ );
808
+
809
+ const refused = without();
810
+ refused["projects add-iam-policy-binding"] = [fail("PERMISSION_DENIED: setIamPolicy")];
811
+ const r = fakeGcloud(refused);
812
+ const aborted = await ensureStackInvariants(firebase, { run: r.run, sleep: async () => {} });
813
+ // Without it every Stage audit and large index build fails to start.
814
+ expect(aborted.mustAbort).toBe(true);
815
+ });
816
+
782
817
  it("only warns when a telemetry role can't be added", async () => {
783
818
  const answers = fullFirebase();
784
819
  answers["projects get-iam-policy"] = [
785
- policy([{ role: "roles/firebasehosting.admin", members: [RUN_SA] }, ...GW_TELEMETRY]),
820
+ policy([
821
+ { role: "roles/firebasehosting.admin", members: [RUN_SA] },
822
+ RUN_QUOTA,
823
+ ...GW_TELEMETRY,
824
+ ]),
786
825
  ];
787
826
  answers["projects add-iam-policy-binding"] = [fail("PERMISSION_DENIED: setIamPolicy")];
788
827
  const { run } = fakeGcloud(answers);
@@ -797,6 +836,7 @@ describe("ensureStackInvariants", () => {
797
836
  policy([
798
837
  { role: "roles/firebasehosting.admin", members: [RUN_SA] },
799
838
  { role: "roles/monitoring.metricWriter", members: [RUN_SA] },
839
+ RUN_QUOTA,
800
840
  ...GW_TELEMETRY,
801
841
  ]),
802
842
  ];
@@ -833,6 +873,7 @@ describe("ensureStackInvariants", () => {
833
873
  policy([
834
874
  { role: "roles/logging.logWriter", members: [RUN_SA] },
835
875
  { role: "roles/monitoring.metricWriter", members: [RUN_SA] },
876
+ RUN_QUOTA,
836
877
  ...GW_TELEMETRY,
837
878
  ]),
838
879
  ],
package/src/wizard.ts CHANGED
@@ -45,6 +45,7 @@ import {
45
45
  scrubInstallProgress,
46
46
  writeMetadata,
47
47
  } from "./install-state.js";
48
+ import { ownerEmailProblem, settleResumedOwnerEmail } from "./owner-email.js";
48
49
  import type { RunMode } from "./run-mode.js";
49
50
  import { selfCommand } from "./self-command.js";
50
51
  import { runGcpWizard } from "./wizards/gcp.js";
@@ -104,8 +105,9 @@ export async function runWizard(opts: WizardOptions = {}): Promise<void> {
104
105
 
105
106
  // 1. Resume-existing-install fast path. Before prompting for anything,
106
107
  // scan ~/.caelo-* for installs and offer them as "resume X" options.
107
- // Picking an existing install carries domain + owner + projectId
108
- // over and skips re-prompting; "new install" falls through to the
108
+ // Picking an existing install carries domain + projectId over and
109
+ // asks only for the Owner email, prefilled (a typo there locks the
110
+ // Owner out, owner-email.ts); "new install" falls through to the
109
111
  // fresh-flow below.
110
112
  //
111
113
  // v0.3.18 — previously the wizard re-asked for provider + domain +
@@ -136,6 +138,10 @@ export async function runWizard(opts: WizardOptions = {}): Promise<void> {
136
138
  ...(opts.projectId ? { projectId: opts.projectId } : {}),
137
139
  ...(opts.version ? { version: opts.version } : {}),
138
140
  ...(opts.billingAccountId ? { billingAccountId: opts.billingAccountId } : {}),
141
+ // An existing install's Owner email is settled there: a change decides
142
+ // whether its job runs again.
143
+ ...(opts.ownerEmail ? { ownerEmail: opts.ownerEmail } : {}),
144
+ nonInteractive: opts.nonInteractive ?? false,
139
145
  });
140
146
  if (prep.kind === "handled") {
141
147
  outro(bold("Done."));
@@ -164,10 +170,15 @@ export async function runWizard(opts: WizardOptions = {}): Promise<void> {
164
170
  if (resumeChoice) {
165
171
  provider = resumeChoice.provider;
166
172
  domain = resumeChoice.domain;
167
- ownerEmail = resumeChoice.ownerEmail;
168
173
  projectIdHint = resumeChoice.projectId;
169
174
  installId = resumeChoice.installId;
170
175
  ensureInstallDir(installId);
176
+ // A resumed install may correct its Owner email (owner-email.ts). Job
177
+ // mode settled it in prepareJobModeInstall already; the picker is only
178
+ // offered without --owner-email, so here it is asked for, prefilled.
179
+ ownerEmail = jobModeExisting
180
+ ? resumeChoice.ownerEmail
181
+ : await settleResumedOwnerEmail(resumeChoice, { nonInteractive: false });
171
182
  } else {
172
183
  provider = jobModeProvider ?? opts.provider ?? (await pickProvider());
173
184
  domain = opts.domain ?? (await promptDomain());
@@ -193,13 +204,26 @@ export async function runWizard(opts: WizardOptions = {}): Promise<void> {
193
204
  cancel(`Aborted. Run with a different domain or remove ~/.caelo-${installId}/ first.`);
194
205
  process.exit(0);
195
206
  }
207
+ // The address typed (or passed) above is the one to continue with.
208
+ ownerEmail = await settleResumedOwnerEmail(existingForId, {
209
+ requested: ownerEmail,
210
+ nonInteractive: false,
211
+ });
196
212
  } else if (existingForId) {
197
213
  // Non-interactive re-run of an existing install: resume it. Keep its
198
214
  // metadata (createdAt, region, the recorded release in imageDigests)
199
215
  // so the re-run converges infrastructure instead of looking like a
200
216
  // new install that deploys `:latest`.
217
+ ownerEmail = await settleResumedOwnerEmail(existingForId, {
218
+ requested: ownerEmail,
219
+ nonInteractive: true,
220
+ });
201
221
  writeMetadata(installId, {
202
- ...resumedMetadata(existingForId, { domain, ownerEmail, projectId: projectIdHint }),
222
+ ...resumedMetadata(readMetadata(installId) ?? existingForId, {
223
+ domain,
224
+ ownerEmail,
225
+ projectId: projectIdHint,
226
+ }),
203
227
  ...(opts.stagingDomain ? { stagingDomain } : {}),
204
228
  });
205
229
  } else {
@@ -463,17 +487,13 @@ async function promptOwnerEmail(): Promise<string> {
463
487
  const value = await text({
464
488
  message: "Owner email (you'll be the IAP allowlisted Owner; can add more later)",
465
489
  placeholder: "you@example.com",
466
- validate: (v) => {
467
- if (!v || v.length === 0) return "Email is required";
468
- if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) return "Looks like an invalid email";
469
- return undefined;
470
- },
490
+ validate: (v) => ownerEmailProblem(v ?? ""),
471
491
  });
472
492
  if (isCancel(value)) {
473
493
  cancel("Cancelled.");
474
494
  process.exit(0);
475
495
  }
476
- return value as string;
496
+ return (value as string).trim();
477
497
  }
478
498
 
479
499
  // Re-export the spinner factory so per-provider wizards use a consistent UX.
@@ -175,6 +175,9 @@ export function estimateGcpCost(inputs: CostEstimateInputs): {
175
175
  // An always-on instance is priced at 1 GiB (the $15 line); extra memory
176
176
  // is billed per GiB-second (~$6.50 per GiB-month).
177
177
  const perMinInstanceUsd = 15 + Math.max(0, adminGiB - 1) * 6.5;
178
+ // The gateway's always-on instance, priced the same way.
179
+ const gatewayGiB = (memoryQuantityMiB(GATEWAY_MEMORY_DEFAULT) as number) / 1024;
180
+ const perGatewayMinInstanceUsd = 15 + Math.max(0, gatewayGiB - 1) * 6.5;
178
181
 
179
182
  const lines: CostLine[] = [
180
183
  {
@@ -202,7 +205,7 @@ export function estimateGcpCost(inputs: CostEstimateInputs): {
202
205
  name: "Quality checks (Cloud Run audit job)",
203
206
  monthlyUsd: 2,
204
207
  notes:
205
- "one container per Lighthouse run, all in parallel (up to 5 pages x 3 runs, ~90 s at 2 vCPU each; a page whose runs disagree gets 2 more): ~$0.05 per audited Stage, at most ~$0.08, partly in the free tier; results bucket ~$0",
208
+ "Lighthouse runs of 2 vCPU in containers of their own (up to 5 pages x 3 runs, ~90 s each; a page whose runs disagree gets 2 more), as many at once as the project's Cloud Run CPU quota allows (all 15 from 40 vCPU; a new project's 20 vCPU run 5 at a time, the same cost in more time): ~$0.05 per audited Stage, at most ~$0.08, partly in the free tier; results bucket ~$0",
206
209
  },
207
210
  {
208
211
  // #1359 — the whole audit of a Stage runs in its own job, not on the
@@ -250,7 +253,10 @@ export function estimateGcpCost(inputs: CostEstimateInputs): {
250
253
  // #1328 — on gcp-firebase the visitor gateway is the new
251
254
  // `caelo-<env>-data-gateway` service; same billing either way.
252
255
  name: provider === "gcp" ? "Cloud Run gateway" : "Cloud Run data gateway",
253
- monthlyUsd: inputs.gatewayMinInstances === 0 ? 1 : 1 + inputs.gatewayMinInstances * 15,
256
+ monthlyUsd:
257
+ inputs.gatewayMinInstances === 0
258
+ ? 1
259
+ : Math.round(1 + inputs.gatewayMinInstances * perGatewayMinInstanceUsd),
254
260
  notes:
255
261
  inputs.gatewayMinInstances === 0
256
262
  ? `scale-to-zero, ${GATEWAY_MEMORY_DEFAULT} (search indexes cached in memory, #1644); ~$1/mo light traffic`
@@ -0,0 +1,180 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * The launcher's decision for an install that has a job (gcp-install-job.ts
5
+ * decideInstallRun): a finished install whose Owner email was corrected on a
6
+ * re-run runs the job again, which applies it, against fake gcloud runners.
7
+ * Before, a finished install was shown as done with the address it was
8
+ * installed with, and a wrong one could not be corrected in job mode at all.
9
+ */
10
+
11
+ import { describe, expect, it } from "bun:test";
12
+ import { readFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import type { GcloudResult } from "../gcloud.js";
15
+ import type { GcloudRunner } from "../gcloud-retry.js";
16
+ import { INSTALL_SETUP_LINK_SECRET, type InstallJobStatus } from "../install-job.js";
17
+ import { opsBucketName } from "../state-backend.js";
18
+ import type { SyncGcloud } from "../state-store.js";
19
+ import { decideInstallRun } from "./gcp-install-job.js";
20
+
21
+ const PROJECT = "acme-site";
22
+ const REGION = "europe-west1";
23
+ const JOB = "caelo-production-operator-access-sync";
24
+ const ok = (stdout = ""): GcloudResult => ({ ok: true, stdout, stderr: "", exitCode: 0 });
25
+ const fail = (stderr: string): GcloudResult => ({ ok: false, stdout: "", stderr, exitCode: 1 });
26
+
27
+ const status = (state: InstallJobStatus["state"]): InstallJobStatus => ({
28
+ statusVersion: 1,
29
+ installId: "gcp-acme-site",
30
+ execution: "caelo-install-x7k2p",
31
+ state,
32
+ phase: state === "succeeded" ? "Done" : "Provisioning the infrastructure (pulumi up, 8-15 min)",
33
+ caeloVersion: "0.12.16",
34
+ startedAt: "2026-11-26T10:00:00.000Z",
35
+ updatedAt: "2026-11-26T11:00:00.000Z",
36
+ });
37
+
38
+ /** The operator-access job as `gcloud run jobs describe --format=json` shows it. */
39
+ const accessJob = (members: string) =>
40
+ JSON.stringify({
41
+ spec: {
42
+ template: {
43
+ spec: {
44
+ template: {
45
+ spec: {
46
+ containers: [
47
+ { env: [{ name: "CAELO_OPERATOR_ACCESS_STATIC_MEMBERS", value: members }] },
48
+ ],
49
+ },
50
+ },
51
+ },
52
+ },
53
+ },
54
+ });
55
+
56
+ /**
57
+ * The bucket's install-job.json, and gcloud for a project whose setup link
58
+ * is stored and whose operator-access job admits `admits` (or answers
59
+ * `accessJob` when given); every gcloud call recorded.
60
+ */
61
+ function fakeProject(opts: {
62
+ readonly job: InstallJobStatus;
63
+ readonly admits?: string;
64
+ readonly accessJob?: GcloudResult;
65
+ readonly execution?: "running" | "finished";
66
+ }) {
67
+ const calls: string[][] = [];
68
+ const syncRun: SyncGcloud = (args) =>
69
+ args.join(" ") === `storage cat gs://${opsBucketName(PROJECT)}/install/install-job.json`
70
+ ? ok(JSON.stringify(opts.job))
71
+ : fail(`unexpected gcloud ${args.join(" ")}`);
72
+ const run: GcloudRunner = async (args) => {
73
+ calls.push(args);
74
+ const line = args.join(" ");
75
+ if (line.startsWith(`secrets versions access latest --secret=${INSTALL_SETUP_LINK_SECRET}`)) {
76
+ return ok("https://caelo-production-admin-abc-ew.a.run.app/setup?token=t0k3n");
77
+ }
78
+ if (line.startsWith(`run jobs describe ${JOB} --region=${REGION} --project=${PROJECT}`)) {
79
+ return opts.accessJob ?? ok(accessJob(opts.admits ?? ""));
80
+ }
81
+ if (line.startsWith("run jobs executions describe")) {
82
+ return ok(
83
+ JSON.stringify({ status: opts.execution === "finished" ? { completionTime: "x" } : {} }),
84
+ );
85
+ }
86
+ return fail(`unexpected gcloud ${line}`);
87
+ };
88
+ return { run, syncRun, calls };
89
+ }
90
+
91
+ const target = (ownerEmail: string) => ({ projectId: PROJECT, region: REGION, ownerEmail });
92
+
93
+ describe("decideInstallRun — the Owner email of a finished install", () => {
94
+ it("a finished install runs again when its corrected Owner email is not applied yet", async () => {
95
+ const p = fakeProject({ job: status("succeeded"), admits: "user:owner@acme.exmaple" });
96
+ const decision = await decideInstallRun(p.run, p.syncRun, target("owner@acme.example"));
97
+ expect(decision.kind).toBe("start");
98
+ if (decision.kind !== "start") throw new Error("unreachable");
99
+ expect(decision.previous?.state).toBe("succeeded");
100
+ expect(decision.why).toBe(
101
+ "the Owner email owner@acme.example is not applied yet (the admin admits user:owner@acme.exmaple, the records would make it user:owner@acme.example); a new run applies it",
102
+ );
103
+ });
104
+
105
+ it("a finished install whose operator-access job admits the recorded address is done", async () => {
106
+ const p = fakeProject({ job: status("succeeded"), admits: "user:owner@acme.example" });
107
+ const decision = await decideInstallRun(p.run, p.syncRun, target("Owner@Acme.example"));
108
+ expect(decision.kind).toBe("done");
109
+ });
110
+
111
+ it("a finished install without its operator-access job runs again", async () => {
112
+ const p = fakeProject({
113
+ job: status("succeeded"),
114
+ accessJob: fail(`ERROR: (gcloud.run.jobs.describe) Cannot find job [${JOB}].`),
115
+ });
116
+ const decision = await decideInstallRun(p.run, p.syncRun, target("owner@acme.example"));
117
+ expect(decision.kind).toBe("start");
118
+ if (decision.kind === "start") expect(decision.why).toContain(`${JOB} does not exist`);
119
+ });
120
+
121
+ it("an operator-access job that cannot be read stops the launcher with the next step", async () => {
122
+ const p = fakeProject({
123
+ job: status("succeeded"),
124
+ accessJob: fail("ERROR: (gcloud.run.jobs.describe) PERMISSION_DENIED: run.jobs.get"),
125
+ });
126
+ await expect(decideInstallRun(p.run, p.syncRun, target("owner@acme.example"))).rejects.toThrow(
127
+ `Could not read the operator-access job ${JOB} in ${PROJECT}: ERROR: (gcloud.run.jobs.describe) PERMISSION_DENIED: run.jobs.get. Check that gcloud is signed in as an Owner of the project`,
128
+ );
129
+ });
130
+
131
+ it("a running job is followed: its Owner email is not looked at", async () => {
132
+ const p = fakeProject({ job: status("running"), execution: "running" });
133
+ const decision = await decideInstallRun(p.run, p.syncRun, target("someone@else.example"));
134
+ expect(decision.kind).toBe("attach");
135
+ expect(p.calls.some((a) => a.includes(JOB))).toBe(false);
136
+ });
137
+
138
+ it("an unfinished install starts again without asking about access", async () => {
139
+ const p = fakeProject({ job: status("failed") });
140
+ const decision = await decideInstallRun(p.run, p.syncRun, target("owner@acme.example"));
141
+ expect(decision.kind).toBe("start");
142
+ expect(p.calls).toEqual([]);
143
+ });
144
+ });
145
+
146
+ describe("prepareJobModeInstall — a resumed install's Owner email", () => {
147
+ // The function runs gcloud and prompts, so its order is pinned on the
148
+ // source, like the billing check's (gcp-billing.test.ts).
149
+ const source = readFileSync(join(import.meta.dir, "gcp-install-job.ts"), "utf8");
150
+ const prep = source.slice(
151
+ source.indexOf("export async function prepareJobModeInstall("),
152
+ source.indexOf("function refuseOwnerChangeDuringRun("),
153
+ );
154
+
155
+ it("asks for it, and records a change, before it shows a finished install", () => {
156
+ const afterAttach = prep.indexOf('if (decision.kind === "attach") {');
157
+ const ask = prep.indexOf("await resolveResumedOwnerEmail(meta, owner)", afterAttach);
158
+ expect(afterAttach).toBeGreaterThan(-1);
159
+ expect(ask).toBeGreaterThan(afterAttach);
160
+ expect(ask).toBeLessThan(prep.indexOf("await recordOwnerEmailForJob("));
161
+ expect(prep.indexOf("await recordOwnerEmailForJob(")).toBeLessThan(
162
+ prep.indexOf("await showResult("),
163
+ );
164
+ });
165
+
166
+ it("refuses a change before it follows a running job", () => {
167
+ expect(prep.indexOf("refuseOwnerChangeDuringRun(")).toBeGreaterThan(-1);
168
+ expect(prep.indexOf("refuseOwnerChangeDuringRun(")).toBeLessThan(
169
+ prep.indexOf("await followToTheEnd("),
170
+ );
171
+ });
172
+
173
+ it("hands the flag and the run mode's interactivity over from the wizard", () => {
174
+ const wizard = readFileSync(join(import.meta.dir, "..", "wizard.ts"), "utf8");
175
+ const call = wizard.slice(wizard.indexOf("await prepareJobModeInstall({"));
176
+ const args = call.slice(0, call.indexOf("});"));
177
+ expect(args).toContain("ownerEmail: opts.ownerEmail");
178
+ expect(args).toContain("nonInteractive: opts.nonInteractive");
179
+ });
180
+ });