@codeyam-editor/codeyam-editor 0.1.0-staging.gac4ca32 → 0.1.0-staging.gc0a93f0

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 (79) hide show
  1. package/npm/cloud.js +1758 -175
  2. package/npm/codesign-plan.js +68 -0
  3. package/npm/compose-conflict.js +59 -0
  4. package/npm/editor-dev.js +24 -2
  5. package/npm/editor.js +15 -5
  6. package/npm/empty-project-dir.js +92 -7
  7. package/npm/fleet-add-failure.js +742 -0
  8. package/npm/fleet-auth-health.js +121 -5
  9. package/npm/fleet-branch.js +124 -1
  10. package/npm/fleet-build-data.js +62 -4
  11. package/npm/fleet-cleanup.js +302 -1
  12. package/npm/fleet-datastore-health.js +107 -0
  13. package/npm/fleet-destroy-safety.js +230 -13
  14. package/npm/fleet-early-roster.js +87 -0
  15. package/npm/fleet-effect-poll.js +110 -0
  16. package/npm/fleet-env.js +86 -0
  17. package/npm/fleet-ghcr-secret.js +129 -0
  18. package/npm/fleet-git-maintenance.js +142 -0
  19. package/npm/fleet-host-op-limiter.js +68 -0
  20. package/npm/fleet-iap-token.js +165 -0
  21. package/npm/fleet-job-badge.js +28 -12
  22. package/npm/fleet-memory.js +306 -8
  23. package/npm/fleet-plans.js +81 -3
  24. package/npm/fleet-pool.js +75 -16
  25. package/npm/fleet-prewarm.js +87 -11
  26. package/npm/fleet-probe-transport.js +155 -0
  27. package/npm/fleet-project-drift.js +58 -0
  28. package/npm/fleet-public-url.js +127 -7
  29. package/npm/fleet-queue.js +199 -1
  30. package/npm/fleet-reachability.js +80 -0
  31. package/npm/fleet-revision.js +212 -0
  32. package/npm/fleet-run-setup.js +66 -0
  33. package/npm/fleet-running-plan.js +37 -7
  34. package/npm/fleet-session-activity.js +162 -0
  35. package/npm/fleet-session-token-cache.js +65 -0
  36. package/npm/fleet-status-refs.js +96 -0
  37. package/npm/fleet-strand.js +39 -8
  38. package/npm/fleet-vm-access.js +276 -7
  39. package/npm/fleet-vm-probe-target.js +282 -0
  40. package/npm/fleet-vm-readiness.js +78 -20
  41. package/npm/ingress-invoke.js +272 -10
  42. package/npm/launch-config.js +404 -8
  43. package/npm/scenario-check.js +1013 -34
  44. package/npm/scenario-handlers.js +103 -27
  45. package/npm/scenario-interactivity.js +612 -19
  46. package/npm/scenario-issues.js +85 -1
  47. package/npm/scenario-mocks.js +340 -31
  48. package/npm/scenario-playwright.js +461 -42
  49. package/npm/utils.js +298 -24
  50. package/package.json +5 -5
  51. package/ui/dist/assets/{ContainerInspector-urDZ9zOC.js → ContainerInspector-C7I9wctz.js} +1 -1
  52. package/ui/dist/assets/EditorShell-9aYMeOdZ.js +330 -0
  53. package/ui/dist/assets/EditorShell-CE8iG_EM.css +1 -0
  54. package/ui/dist/assets/{Markdown-BoLHHFXH.js → Markdown-Chgdf3PW.js} +1 -1
  55. package/ui/dist/assets/ProjectLauncherScreen-E0NYYiwy.js +1 -0
  56. package/ui/dist/assets/ScenarioDataPanel-CLwkrex0.js +18 -0
  57. package/ui/dist/assets/{ScenarioDataPanelFullPage-DlAIUrnk.js → ScenarioDataPanelFullPage-DT0TZC4M.js} +1 -1
  58. package/ui/dist/assets/ScenarioRenderer-Bsarhcrl.js +21 -0
  59. package/ui/dist/assets/{StepsSimulator-BFldWyoX.js → StepsSimulator-CymGgfbu.js} +1 -1
  60. package/ui/dist/assets/index-BRoAenc1.css +1 -0
  61. package/ui/dist/assets/index-iMR5siiG.js +27 -0
  62. package/ui/dist/assets/{markdown-v0F0UEt3.js → markdown-C9tbsVHX.js} +1 -1
  63. package/ui/dist/assets/react-nrLBr15I.js +28 -0
  64. package/ui/dist/assets/{useEvents-DHkLJZR4.js → useEvents-S3Qk1Y_d.js} +1 -1
  65. package/ui/dist/assets/useServerIdentity-CVuHTzjg.js +1 -0
  66. package/ui/dist/index.html +4 -4
  67. package/ui/dist/open-source/codeyam-counter.png +0 -0
  68. package/ui/dist/open-source/el-carot.png +0 -0
  69. package/ui/dist/open-source/tabcommand.png +0 -0
  70. package/ui/dist/preview-subdir-demo/index.html +62 -0
  71. package/ui/dist/preview-subdir-demo/sibling.html +48 -0
  72. package/ui/dist/assets/EditorShell-D7wGyetm.css +0 -1
  73. package/ui/dist/assets/EditorShell-eZm_8CsG.js +0 -230
  74. package/ui/dist/assets/ProjectLauncherScreen-Bq8CJo9M.js +0 -1
  75. package/ui/dist/assets/ScenarioDataPanel-DuU3_hdh.js +0 -5
  76. package/ui/dist/assets/ScenarioRenderer-od1vF8-p.js +0 -21
  77. package/ui/dist/assets/index-B7_KRKaQ.js +0 -27
  78. package/ui/dist/assets/index-D3csSagX.css +0 -1
  79. package/ui/dist/assets/react-CSS0HapR.js +0 -28
package/npm/cloud.js CHANGED
@@ -11,6 +11,7 @@
11
11
 
12
12
  const { spawn, spawnSync } = require("child_process");
13
13
  const fs = require("fs");
14
+ const https = require("https");
14
15
  const os = require("os");
15
16
  const path = require("path");
16
17
  const readline = require("readline");
@@ -58,6 +59,7 @@ const {
58
59
  normalizePrincipal,
59
60
  resolveDefaultOperator,
60
61
  withDefaultOperator,
62
+ unauthorizableAddRefusal,
61
63
  accessFor,
62
64
  setAccess,
63
65
  addAccess,
@@ -75,9 +77,11 @@ const {
75
77
  regionFromZone,
76
78
  vmIngressInvocation,
77
79
  vmIngressStatusInvocation,
80
+ vmIngressGrantAccessInvocation,
78
81
  parseIngressStatusVerdict,
79
82
  parseIngressTeardownVerdict,
80
83
  selectIngressReconcileTargets,
84
+ selectIngressGrantOnlyTargets,
81
85
  selectOrphanIngressTargets,
82
86
  classifyOrphanDownResult,
83
87
  backendServicesListInvocation,
@@ -90,6 +94,11 @@ const {
90
94
  iapAccessInvocation,
91
95
  sharedIngressInvocation,
92
96
  backendServiceTimeoutInvocation,
97
+ FLEET_FIREWALL_RULE_NAMES,
98
+ fleetFirewallDescribeInvocation,
99
+ fleetFirewallConvergeInvocation,
100
+ firewallNeedsConverge,
101
+ firewallAdmitsPort,
93
102
  } = require("./ingress-invoke");
94
103
  // Shared fleet-roster writer/reader. `cloud:up` rosters the VM it just
95
104
  // provisioned so the dashboard, the cloudflared-monitor tunnel publisher, and
@@ -97,6 +106,10 @@ const {
97
106
  // edit (the invisible-VM gap improve38 closes). `readRoster` enumerates the
98
107
  // fleet for `reconcile-ingress`.
99
108
  const { addToRoster, readRoster } = require("./fleet-roster");
109
+ // Tells a docker container-name conflict (a concurrent run already started this
110
+ // container) apart from a real `docker compose up -d` failure, so the abort path
111
+ // can converge instead of escalating to instance deletion.
112
+ const { classifyComposeUpFailure } = require("./compose-conflict");
100
113
 
101
114
  // =============================================================================
102
115
  // Pure helpers — every export here is unit-tested in cloud.test.js without
@@ -159,14 +172,34 @@ const KNOWN_FLAGS = [
159
172
  // default is loud — a tokenless VM cannot sync plan claims and must never
160
173
  // report healthy silently. Use only when push genuinely isn't wanted.
161
174
  "allow-no-git-credentials",
175
+ // Provision the VM in admin mode: forward CODEYAM_ADMIN=1 into the container
176
+ // so the Home-tab Setup door renders. Equivalent to `CODEYAM_ADMIN=1 npm run
177
+ // cloud:up …`; absent = strict non-admin (the safe default). Survives
178
+ // re-provision because it rides the compose-render substitution, unlike a
179
+ // manual VM compose edit.
180
+ "admin",
181
+ // GCE machine type for the VM (e.g. n2-standard-4, e2-standard-4). Persisted
182
+ // in cloud.json so a later bare `cloud:up` keeps it. Defaults to
183
+ // DEFAULT_FLEET_MACHINE_TYPE. The whole point of exposing this is fleet
184
+ // scale-out: the region's E2_CPUS quota (72 in us-central1) caps the fleet at
185
+ // ~14 e2-standard-4 VMs, while N2_CPUS/N2D_CPUS (200, unused) leave room for
186
+ // 30 — so the fleet defaults to N2 and this flag lets a caller override.
187
+ "machine-type",
162
188
  ];
163
189
 
164
190
  // Flags that take no value (presence = true). parseFlags must not demand a
165
191
  // value for these or `--no-tunnel` would error "requires a value".
166
- const BOOLEAN_FLAGS = ["no-tunnel", "skip-setup", "list", "allow-no-git-credentials"];
192
+ const BOOLEAN_FLAGS = ["no-tunnel", "skip-setup", "list", "allow-no-git-credentials", "admin"];
167
193
 
168
194
  const FIREWALL_RULE_NAME = "codeyam-editor-iap-ssh";
169
195
  const INSTANCE_TAG = "codeyam-editor";
196
+ // Default GCE machine type for fleet VMs. N2 (not E2) because the fleet must
197
+ // reach 30 VMs: us-central1 E2_CPUS quota is 72, so 30 × e2-standard-4 (120
198
+ // vCPU) + the operator host exceed it and cap the fleet at ~14 regardless of
199
+ // code — while N2_CPUS/N2D_CPUS are 200 and unused, leaving headroom for 30 ×
200
+ // n2-standard-4. Override per-VM with `--machine-type`. See the vm--scale-
201
+ // fleet-to-30-vms plan for the measured quota rationale.
202
+ const DEFAULT_FLEET_MACHINE_TYPE = "n2-standard-4";
170
203
  const EDITOR_PORT = 14199;
171
204
  const VITE_PORT = 5173;
172
205
 
@@ -481,6 +514,28 @@ function previewSameOriginSafeFromStack(stackJson) {
481
514
  return typeof flag === "boolean" ? flag : true;
482
515
  }
483
516
 
517
+ /** Resolve the sameOriginSafe flag a seed should ACT on, given the static
518
+ * `stack.json` reading and the running editor's own `/api/config` verdict.
519
+ *
520
+ * Precedence: a BOOLEAN effective verdict wins; anything else (`null`,
521
+ * `undefined`, a non-boolean) defers to the static flag. The type check is the
522
+ * whole rule — `null` means "no server was up to ask", which is the
523
+ * pre-container seed and must leave the static read in charge, NOT "the server
524
+ * said same-origin is fine". Collapsing the two would put the static flag back
525
+ * in control on exactly the path that needs the override.
526
+ *
527
+ * Extracted from `seedPreviewOrigin` because that function's inputs arrive over
528
+ * gcloud SSH, so this rule was only reachable through heavy mocking — while
529
+ * being precisely where the defect lived. `stack.json` cannot express the state
530
+ * that matters here: a project escalates off the same-origin subpath at RUNTIME
531
+ * after a hydration failure, and the adaptive-default stacks that happens to
532
+ * (Next.js) deliberately omit the key. So a seeder that re-derives the flag
533
+ * from the file writes back the same-origin sentinel that just failed, and the
534
+ * project sits at `previewDedicatedOriginUnavailable: true` forever. Pure. */
535
+ function resolveEffectiveSameOriginSafe(staticFlag, effectiveVerdict) {
536
+ return typeof effectiveVerdict === "boolean" ? effectiveVerdict : staticFlag;
537
+ }
538
+
484
539
  // Matches an absolute cloudflared quick-tunnel origin
485
540
  // (`https://<sub>.trycloudflare.com`, optionally with a port/path/query). These
486
541
  // URLs ROTATE on every tunnel respawn, which is exactly why a frozen one rots.
@@ -550,6 +605,32 @@ function isWrongModePreviewOrigin(localJson, sameOriginSafe) {
550
605
  return LOOPBACK_ORIGIN_RE.test(origin);
551
606
  }
552
607
 
608
+ /** Decide whether a VM is presenting as HEALTHY while its Live Preview is
609
+ * silently dead — the VM-9 failure mode. The heal
610
+ * (`reconcilePreviewOriginToSlugHost`) fixes the mechanism; this predicate is
611
+ * the smoke detector that catches a FUTURE mechanism gap (a new stack shape, a
612
+ * new provisioning path) by observation instead of by a user noticing a blank
613
+ * iframe days later.
614
+ *
615
+ * Input is the editor's own `/api/config` payload — the effective truth table
616
+ * (`previewSameOriginSafe` + the resolved `previewOrigin`), not a
617
+ * re-derivation from stack.json over ssh. True iff the stack is NOT
618
+ * same-origin-safe AND its effective previewOrigin is one a remote browser can
619
+ * never load (the `/__codeyam_preview` sentinel, any relative path, or a
620
+ * loopback origin) — i.e. exactly `isWrongModePreviewOrigin`'s wrong-mode
621
+ * condition, evaluated against the live config rather than editor.local.json.
622
+ * Composing the two keeps ONE definition of "wrong-mode origin" in this file.
623
+ *
624
+ * Deliberately conservative: a missing/unparseable payload, an absent
625
+ * `previewSameOriginSafe`, or a legitimate same-origin-safe stack on the
626
+ * subpath all return false. Absence of evidence is never a false alarm — the
627
+ * caller renders "unknown" instead. Pure. */
628
+ function isSilentlyBrokenPreview(apiConfig) {
629
+ if (!apiConfig || typeof apiConfig !== "object") return false;
630
+ if (apiConfig.previewSameOriginSafe !== false) return false;
631
+ return isWrongModePreviewOrigin(apiConfig, false);
632
+ }
633
+
553
634
  /** Read the operator-laptop cloudflared-urls.json sidecar. Missing/unparseable
554
635
  * → {} (the monitor may not have run yet; the seed falls back to localhost). */
555
636
  function readCloudflaredUrls() {
@@ -747,6 +828,28 @@ function buildEditorLocalEnvPatch(localEnv, agent) {
747
828
  return { provider: agent, env: { [varName]: value } };
748
829
  }
749
830
 
831
+ /** Build the editor.local.json patch that seeds a GREENFIELD project's
832
+ * `projectTitle` so its live identity resolves to the real project name from
833
+ * first boot. A greenfield project (`--new-project <name>`, no clientRepo) has
834
+ * no origin remote and is bind-mounted at /workspace on the VM, so the editor's
835
+ * identity resolver would otherwise fall back to the bare mount basename
836
+ * "workspace" — which the fleet dashboard then reads as a permanent false
837
+ * project-dir-drift. Seeding `projectTitle` (deep-merged over editor.json on the
838
+ * VM) makes `project_identity::read` prefer the real name.
839
+ *
840
+ * Returns `null` for a clone (a repo Add already labels from its origin
841
+ * basename, and re-seeding a clone's title would be wrong) or when no
842
+ * greenfield name is available, so the caller can no-op without an SSH round
843
+ * trip. Pure — mirrors buildEditorLocalEnvPatch so the decision is unit-tested
844
+ * without a live VM. */
845
+ function buildGreenfieldTitlePatch(cfg = {}) {
846
+ const p = resolveProject(cfg);
847
+ if (!p.greenfield) return null;
848
+ const name = typeof p.name === 'string' ? p.name.trim() : '';
849
+ if (!name) return null;
850
+ return { projectTitle: name };
851
+ }
852
+
750
853
  /** Parse `docker compose ps --format json` (compose v2 — one JSON object per
751
854
  * line) and return the editor service's `State` string, or null when the
752
855
  * service is absent / output is unparseable. Two callers shared an identical
@@ -769,6 +872,79 @@ function parseEditorComposeState(stdout) {
769
872
  return null;
770
873
  }
771
874
 
875
+ /** Decide whether `cloud:up`'s abort handler may delete the instance it is
876
+ * unwinding. Pure `{ createdThisRun, containerUp, rostered, probeInconclusive }
877
+ * → 'delete' | 'keep'`, matching the `reapVerdict` / `reattachVerdict` /
878
+ * `reconcileRosteredVm` pattern in npm/fleet-cleanup.js, so the whole matrix is
879
+ * exhaustively testable without a VM.
880
+ *
881
+ * `createdThisRun` stays a NECESSARY condition — never delete an instance this
882
+ * run did not create — but 2026-08-07 proved it is not SUFFICIENT. It answers
883
+ * "did I create this?", not "is it safe to destroy?", and in a concurrent
884
+ * provision race the losing run legitimately owns the flag while the winner has
885
+ * already brought the VM up and rostered it. Deleting there destroyed VM-4 and
886
+ * VM-5. So authorization also requires CURRENT-STATE evidence that the VM is
887
+ * out of service:
888
+ *
889
+ * - `containerUp` — the editor container is running (per the compose-ps probe).
890
+ * A VM serving an editor is in use by definition.
891
+ * - `rostered` — the VM is in the fleet roster, the operator-visible source of
892
+ * truth. Note this is true whether the winning run or THIS run rostered it;
893
+ * either way the VM is visible in the dashboard and removable in one command,
894
+ * so it is not the silent orphan teardown exists to prevent.
895
+ * - `probeInconclusive` — liveness could not be determined. This must fail
896
+ * SAFE: a failing probe is how we reach the abort handler in the first place,
897
+ * so it can never count as evidence the VM is dead. An orphan costs one
898
+ * `npm run cloud:destroy`; a wrong delete costs a 15-40 minute rebuild plus
899
+ * any unpushed work on the VM. */
900
+ function abortTeardownDecision({ createdThisRun, containerUp, rostered, probeInconclusive } = {}) {
901
+ if (!createdThisRun) return "keep";
902
+ if (probeInconclusive) return "keep";
903
+ if (containerUp) return "keep";
904
+ if (rostered) return "keep";
905
+ return "delete";
906
+ }
907
+
908
+ /** Gather the CURRENT-STATE inputs {@link abortTeardownDecision} needs, so the
909
+ * abort handler reads gather → decide → act instead of inlining probes among
910
+ * the delete calls.
911
+ *
912
+ * Only runs the probes when `createdThisRun` is true — the decision is `keep`
913
+ * regardless otherwise, and an abort path should not spend SSH round trips
914
+ * proving something it already knows. In that case it returns the
915
+ * probe-inconclusive shape, which is the safe default at every layer.
916
+ *
917
+ * Both lookups are wrapped: a throwing probe or an unreadable roster must fail
918
+ * SAFE (toward `keep`), never take a second exception path into the delete.
919
+ * `deps` is injectable so the matrix is unit-tested without a VM. */
920
+ function probeAbortTeardownState(cfg, createdThisRun, deps = {}) {
921
+ if (!createdThisRun) {
922
+ return { containerUp: false, rostered: false, probeInconclusive: true };
923
+ }
924
+ const probe = deps.probeEditorComposeState || probeEditorComposeState;
925
+ const roster = deps.readRoster || readRoster;
926
+ const resolveVm = deps.resolveFleetVmNumber || resolveFleetVmNumber;
927
+ const log = deps.log || ((m) => console.error(m));
928
+
929
+ let liveness = { state: null, inconclusive: true };
930
+ try {
931
+ liveness = probe(cfg);
932
+ } catch (e) {
933
+ log(` (liveness probe failed: ${e && e.message})`);
934
+ }
935
+ let rostered = false;
936
+ try {
937
+ const vm = resolveVm(cfg.instanceName);
938
+ rostered = vm != null && (roster() || []).includes(vm);
939
+ } catch { /* unreadable roster — treated as not-rostered; liveness still guards */ }
940
+
941
+ return {
942
+ containerUp: liveness.state === "running",
943
+ rostered,
944
+ probeInconclusive: liveness.inconclusive,
945
+ };
946
+ }
947
+
772
948
  /** Translate one of the wrapper's verbs into the exact `gcloud` argv. The
773
949
  * switch's job is to keep every per-verb command shape in one reviewable
774
950
  * place — tests assert the arrays without ever spawning a process. */
@@ -789,7 +965,7 @@ function buildGcloudArgs(verb, cfg = {}, extras = {}) {
789
965
  return [
790
966
  "compute", "instances", "create", instanceName,
791
967
  "--project", project, "--zone", zone,
792
- "--machine-type=e2-standard-4",
968
+ `--machine-type=${cfg.machineType || DEFAULT_FLEET_MACHINE_TYPE}`,
793
969
  "--image-family=debian-12",
794
970
  "--image-project=debian-cloud",
795
971
  "--boot-disk-size=100GB",
@@ -804,6 +980,19 @@ function buildGcloudArgs(verb, cfg = {}, extras = {}) {
804
980
  return ["compute", "instances", "delete", instanceName, "--project", project, "--zone", zone, "--quiet"];
805
981
  case "instances-describe":
806
982
  return ["compute", "instances", "describe", instanceName, "--project", project, "--zone", zone, "--format=json"];
983
+ // Outstanding (not-yet-DONE) zone operations targeting this instance. Used to
984
+ // tell a normal transient PROVISIONING from a wedged insert: GCE can accept an
985
+ // insert and then never finish it, leaving an operation parked at RUNNING/0%
986
+ // that holds the instance name forever. The status filter is what makes this
987
+ // cheap and unambiguous — a DONE operation is history and says nothing about
988
+ // whether the slot is currently blocked.
989
+ case "operations-list-pending":
990
+ return [
991
+ "compute", "operations", "list",
992
+ "--project", project,
993
+ "--filter", `zone:(${zone}) AND targetLink~${instanceName}$ AND status!=DONE`,
994
+ "--format=json",
995
+ ];
807
996
  case "instances-list-tagged":
808
997
  return [
809
998
  "compute", "instances", "list",
@@ -889,11 +1078,94 @@ function buildGcloudArgs(verb, cfg = {}, extras = {}) {
889
1078
  // real use. Unit tests pin their exports so a refactor cannot drop them.
890
1079
  // =============================================================================
891
1080
 
1081
+ // Per-call wall-clock budget for a single gcloud / SSH invocation. A hung
1082
+ // `gcloud describe` (metadata / IAP hiccup) used to block the whole
1083
+ // `cloud:reconcile-ingress` sweep forever — the only timeout in the reconcile
1084
+ // path was the outer 10-minute exec budget in the dashboard, and that never
1085
+ // cascaded to the orphaned descendants. Bounding every per-call spawn well under
1086
+ // that outer budget means a single hang trips HERE first: the call returns a
1087
+ // timed-out result (formatGcloudFailure renders it), the sweep skips that VM,
1088
+ // and no descendant is left hanging to pile up. Shared by runGcloud and the two
1089
+ // reconcile spawnSync sites (status probe, per-BES timeout converge) so all three
1090
+ // reference one value. 2 min is generous for any single describe/update/SSH probe
1091
+ // yet comfortably under the 600000 ms outer reconcile budget.
1092
+ //
1093
+ // It is a PROBE budget, and provisioning is exempt — see
1094
+ // GCLOUD_PROVISION_TIMEOUT_MS below. Do not re-collapse the two: raising this
1095
+ // constant to accommodate a slow create would un-bound the reconcile sweep,
1096
+ // which is the exact orphan-cascade this value exists to stop.
1097
+ const GCLOUD_CALL_TIMEOUT_MS = 120000;
1098
+
1099
+ // `instances create` / `instances start` are NOT probes: each blocks until GCE's
1100
+ // insert (or start) operation reaches a terminal state, which routinely outruns
1101
+ // the probe budget under zonal contention. Inheriting GCLOUD_CALL_TIMEOUT_MS
1102
+ // SIGTERMd gcloud mid-insert; `spawnSync` then returned `status: null`, which
1103
+ // `!== 0`, so a local kill was indistinguishable from a remote rejection and the
1104
+ // caller threw a bare `Failed to create instance <name>` with no cause in it.
1105
+ // That mattered downstream: every arm of classifyAddFailure keys on a transcript
1106
+ // signature, so a causeless log fell through to the optimistic `verifying`
1107
+ // fallback and told the operator to WAIT on a VM GCE had already wedged
1108
+ // (observed 2026-09-04 on VM-8: insert 14:29:50Z, add errored 14:32:26Z — the
1109
+ // 120s budget plus teardown).
1110
+ //
1111
+ // Deliberately above the 600000 ms outer reconcile budget, on the same reasoning
1112
+ // as PROJECT_BOOTSTRAP_TIMEOUT_MS: ensureInstance is only ever reached from the
1113
+ // add path, never from the reconcile sweep, so the sweep-relative ceiling that
1114
+ // governs GCLOUD_CALL_TIMEOUT_MS does not apply. A create still running at 10
1115
+ // minutes is wedged, not slow.
1116
+ const GCLOUD_PROVISION_TIMEOUT_MS = 10 * 60 * 1000;
1117
+
1118
+ /** The per-call spawn budget a given wrapper verb should run under. Provisioning
1119
+ * verbs get GCLOUD_PROVISION_TIMEOUT_MS; everything else keeps the probe budget.
1120
+ * Pure — the mapping is asserted directly, without spawning a process. */
1121
+ function gcloudCallTimeoutMs(verb) {
1122
+ return verb === "instances-create" || verb === "instances-start"
1123
+ ? GCLOUD_PROVISION_TIMEOUT_MS
1124
+ : GCLOUD_CALL_TIMEOUT_MS;
1125
+ }
1126
+
1127
+ // The project bootstrap is NOT a probe: it runs `git clone` + `npm install` in
1128
+ // the repo root and every `apps[].dir`, each package's `postinstall`, then
1129
+ // `npm run setup` — minutes of remote work on a heavy repo. It once ran as ONE
1130
+ // blocking `runGcloud("ssh-script")` call, so it inherited GCLOUD_CALL_TIMEOUT_MS
1131
+ // (a budget whose own comment scopes it to "any single describe/update/SSH
1132
+ // probe"). That SIGTERMd the gcloud child mid-clone; `spawnSync` then returned
1133
+ // `status: null`, which `!== 0`, so the timeout was indistinguishable from a
1134
+ // genuine remote failure and the caller's abort path DELETED A COMPLETELY
1135
+ // HEALTHY VM.
1136
+ //
1137
+ // Observed twice: 2026-07-28 on client repo `lets-go-compost-portal` (a root
1138
+ // postinstall of `playwright install chromium`, ~293 MB), and 2026-07-29
1139
+ // provisioning six self-host `codeyam-editor` VMs, whose clone alone exceeds the
1140
+ // probe budget — all six were built, torn down mid-clone, and reported as
1141
+ // "scripts/gcp-project-bootstrap.sh failed on the VM".
1142
+ //
1143
+ // The install is now DETACHED (projectBootstrapLaunchCommand + a re-attaching
1144
+ // follow loop, outcome read from VM-side state), so no single call carries the
1145
+ // whole install any more. This constant is therefore the OVERALL deadline across
1146
+ // re-attaches — the point at which we stop waiting on a still-healthy VM and say
1147
+ // exactly that. Deliberately well above the outer reconcile budget: a long remote
1148
+ // install is not a step in a sweep, so the sweep-relative ceiling that governs
1149
+ // GCLOUD_CALL_TIMEOUT_MS does not apply to it.
1150
+ const PROJECT_BOOTSTRAP_TIMEOUT_MS = 40 * 60 * 1000;
1151
+
1152
+ /** Whether a `spawnSync` result is a LOCAL timeout kill rather than a remote
1153
+ * failure. `spawnSync` reports a timeout as `status: null` plus an ETIMEDOUT
1154
+ * error, so a bare `status !== 0` check conflates the two — which is what made
1155
+ * a timed-out bootstrap look like a broken one. Pure. */
1156
+ function isSpawnTimeout(result) {
1157
+ if (!result) return false;
1158
+ if (result.status !== null && result.status !== undefined) return false;
1159
+ const code = result.error && result.error.code;
1160
+ return code === "ETIMEDOUT" || result.signal === "SIGTERM";
1161
+ }
1162
+
892
1163
  function runGcloud(args, opts = {}) {
893
1164
  return spawnSync("gcloud", args, {
894
1165
  stdio: opts.stdio || "inherit",
895
1166
  input: opts.input,
896
1167
  encoding: opts.encoding || "utf8",
1168
+ timeout: opts.timeout != null ? opts.timeout : GCLOUD_CALL_TIMEOUT_MS,
897
1169
  });
898
1170
  }
899
1171
 
@@ -924,6 +1196,66 @@ function formatGcloudFailure(result) {
924
1196
  return "(no output captured from gcloud)";
925
1197
  }
926
1198
 
1199
+ /** The thrown message for a failed `instances create` / `instances start`.
1200
+ *
1201
+ * Splits the two outcomes the old bare `Failed to create instance <name>`
1202
+ * collapsed, because they are different operator actions: a LOCAL timeout means
1203
+ * GCE may still be working the operation and it should be checked, while a
1204
+ * remote rejection means GCE said no and its own stderr is the answer. Both
1205
+ * arms put a cause in the transcript — classifyAddFailure keys on transcript
1206
+ * text, so a causeless message is what lands an add on the optimistic
1207
+ * `verifying` fallback. Pure: result in, string out.
1208
+ *
1209
+ * `verb` is the operator-facing word ("create" / "start"), not a wrapper verb. */
1210
+ /** Operator-facing copy for a create GCE accepted and then abandoned, kept
1211
+ * separate from the guard that detects it for the same reason
1212
+ * provisionFailureMessage is: the decision of WHEN to refuse and the wording of
1213
+ * WHAT to say are different concerns, and only the wording needs asserting.
1214
+ * Extracting it is what lets the copy be tested without a live gcloud — and on
1215
+ * this feature the copy IS the fix, since the bug was a message that told the
1216
+ * operator to wait for a VM that would never arrive.
1217
+ *
1218
+ * Every field is rendered defensively because this runs on a degraded path: the
1219
+ * operations read that produced `pending` is best-effort, so a partial record
1220
+ * must still yield a message that names the problem rather than printing
1221
+ * "undefined" at the operator. */
1222
+ function wedgedOperationMessage(instanceName, pending = {}) {
1223
+ const detail = [
1224
+ `${pending.name || "unnamed"}: ${pending.operationType || "unknown type"}`,
1225
+ `status ${pending.status || "unknown"}`,
1226
+ `progress ${pending.progress == null ? "unknown" : `${pending.progress}%`}`,
1227
+ `error ${pending.errorCode || "unknown"}${pending.errorMessage ? `: ${pending.errorMessage}` : ""}`,
1228
+ ].join(", ");
1229
+ return (
1230
+ `Instance ${instanceName} is stuck in PROVISIONING behind a wedged create operation (${detail}). ` +
1231
+ "GCE accepted the create and never finished it, so this slot cannot be re-added and a delete will queue " +
1232
+ "behind the wedged operation rather than clear it. This needs GCE-side resolution — open a Google Cloud " +
1233
+ "Support case citing that error. Use a different VM number if you need a box now."
1234
+ );
1235
+ }
1236
+
1237
+ function provisionFailureMessage(verb, instanceName, result) {
1238
+ if (isSpawnTimeout(result)) {
1239
+ const minutes = Math.round(GCLOUD_PROVISION_TIMEOUT_MS / 60000);
1240
+ // A SIGTERMd child legitimately often captured nothing, and appending
1241
+ // formatGcloudFailure's "(no output captured)" placeholder to a message that
1242
+ // already states the cause is noise. Append it only when it is real output.
1243
+ const detail = formatGcloudFailure(result);
1244
+ const captured = detail === "(no output captured from gcloud)" ? "" : `\n${detail}`;
1245
+ return (
1246
+ `Failed to ${verb} instance ${instanceName}: the gcloud call exceeded the local ` +
1247
+ `${minutes}-minute provisioning budget and was SIGTERMd locally. GCE may still be ` +
1248
+ `working the operation — check it with \`gcloud compute operations list\` before ` +
1249
+ `retrying, and delete the half-built instance if one exists.` +
1250
+ captured
1251
+ );
1252
+ }
1253
+ return (
1254
+ `Failed to ${verb} instance ${instanceName} (gcloud exit ${result && result.status}).\n` +
1255
+ formatGcloudFailure(result)
1256
+ );
1257
+ }
1258
+
927
1259
  // A bounded, pure classifier that keys on status === 255 (gcloud-ssh's exit
928
1260
  // for an ssh failure) and a signature match against known transient strings.
929
1261
  function isTransientSshFailure(result) {
@@ -999,6 +1331,38 @@ function fetchInstanceState(cfg) {
999
1331
  }
1000
1332
  }
1001
1333
 
1334
+ /** Read the instance's outstanding (not-DONE) zone operations and summarize the
1335
+ * first one, or null when there are none / the call failed. Shaped as
1336
+ * { name, operationType, status, progress, errorCode, errorMessage } — the fields
1337
+ * the wedged-insert refusal message and the fleet classifier both need.
1338
+ *
1339
+ * Returning null on a failed or unparseable call is deliberate: this is a
1340
+ * DIAGNOSTIC read used to make a refusal more informative, so it must never turn
1341
+ * a working provision into a failing one just because the operations API hiccuped. */
1342
+ function fetchPendingOperation(cfg) {
1343
+ const result = runGcloud(buildGcloudArgs("operations-list-pending", cfg), {
1344
+ stdio: ["ignore", "pipe", "ignore"],
1345
+ });
1346
+ if (result.status !== 0) return null;
1347
+ let ops;
1348
+ try {
1349
+ ops = JSON.parse(result.stdout);
1350
+ } catch {
1351
+ return null;
1352
+ }
1353
+ if (!Array.isArray(ops) || ops.length === 0) return null;
1354
+ const op = ops[0];
1355
+ const err = op && op.error && Array.isArray(op.error.errors) ? op.error.errors[0] : null;
1356
+ return {
1357
+ name: op.name || null,
1358
+ operationType: op.operationType || null,
1359
+ status: op.status || null,
1360
+ progress: typeof op.progress === "number" ? op.progress : null,
1361
+ errorCode: (err && err.code) || null,
1362
+ errorMessage: (err && err.message) || null,
1363
+ };
1364
+ }
1365
+
1002
1366
  function loadOrInitCloudConfig(projectDir, flags) {
1003
1367
  const existing = loadCloudConfig(projectDir);
1004
1368
  // noTunnel is a per-invocation behavior, never persisted — else a later manual
@@ -1080,7 +1444,11 @@ async function ensureFirewallRule(cfg) {
1080
1444
  }
1081
1445
  }
1082
1446
 
1083
- async function ensureInstance(cfg) {
1447
+ // `sleepFn` is injectable so the 60-iteration wait loop can be driven with a
1448
+ // no-op instead of burning 2 real minutes of clock — the same seam
1449
+ // runGcloudSshWithRetry / waitForEditorComposeRunning already expose.
1450
+ async function ensureInstance(cfg, { sleepFn } = {}) {
1451
+ const sleep = sleepFn || ((ms) => new Promise((r) => setTimeout(r, ms)));
1084
1452
  console.error(`Checking instance ${cfg.instanceName}...`);
1085
1453
  const initialState = fetchInstanceState(cfg);
1086
1454
  const createdThisRun = initialState === null;
@@ -1091,29 +1459,59 @@ async function ensureInstance(cfg) {
1091
1459
  }
1092
1460
  if (initialState === "TERMINATED") {
1093
1461
  console.error(` ${cfg.instanceName} is TERMINATED — starting...`);
1094
- const start = runGcloud(buildGcloudArgs("instances-start", cfg));
1462
+ const start = runGcloud(buildGcloudArgs("instances-start", cfg), {
1463
+ timeout: gcloudCallTimeoutMs("instances-start"),
1464
+ });
1095
1465
  if (start.status !== 0) {
1096
- throw new Error(`Failed to start instance ${cfg.instanceName}`);
1466
+ throw new Error(provisionFailureMessage("start", cfg.instanceName, start));
1097
1467
  }
1098
1468
  } else if (initialState === null) {
1099
1469
  console.error(` ${cfg.instanceName} not found — creating...`);
1100
- const create = runGcloud(buildGcloudArgs("instances-create", cfg));
1470
+ const create = runGcloud(buildGcloudArgs("instances-create", cfg), {
1471
+ timeout: gcloudCallTimeoutMs("instances-create"),
1472
+ });
1101
1473
  if (create.status !== 0) {
1102
- throw new Error(`Failed to create instance ${cfg.instanceName}`);
1474
+ throw new Error(provisionFailureMessage("create", cfg.instanceName, create));
1103
1475
  }
1104
1476
  } else {
1477
+ // A slot found in PROVISIONING is ambiguous, and the two readings need
1478
+ // opposite handling. On a normal add it is a transient the poll loop below
1479
+ // resolves in seconds. But GCE can also accept an insert and then never
1480
+ // finish it (2026-09-04, VM-8): the operation parks at RUNNING/0%, eventually
1481
+ // attaches an INTERNAL_ERROR without ever reaching DONE, and holds the
1482
+ // instance name indefinitely — a delete queues behind it rather than clearing
1483
+ // it. Polling that for 2 minutes only rediscovers, slowly and with a message
1484
+ // naming neither the operation nor the wedge, a state the first describe
1485
+ // already showed. Read the outstanding operation instead and fail immediately
1486
+ // when it carries a terminal error, so the transcript carries the signature
1487
+ // fleet-add-failure.js's wedged-insert arm keys on.
1488
+ if (initialState === "PROVISIONING") {
1489
+ const pending = fetchPendingOperation(cfg);
1490
+ if (pending && pending.errorCode) {
1491
+ throw new Error(wedgedOperationMessage(cfg.instanceName, pending));
1492
+ }
1493
+ }
1105
1494
  console.error(` ${cfg.instanceName} is ${initialState}; waiting...`);
1106
1495
  }
1107
1496
 
1497
+ let lastState = initialState;
1108
1498
  for (let i = 0; i < 60; i++) {
1109
- if (fetchInstanceState(cfg) === "RUNNING") {
1499
+ lastState = fetchInstanceState(cfg);
1500
+ if (lastState === "RUNNING") {
1110
1501
  console.error(` ✓ ${cfg.instanceName} is RUNNING`);
1111
1502
  await waitForIapReady(cfg);
1112
1503
  return { createdThisRun };
1113
1504
  }
1114
- await new Promise((r) => setTimeout(r, 2000));
1505
+ await sleep(2000);
1115
1506
  }
1116
- throw new Error(`Instance ${cfg.instanceName} did not reach RUNNING within 2 minutes`);
1507
+ // Name the state it was actually stuck in. An instance parked in PROVISIONING
1508
+ // is a different operator action from one that stopped answering describe at
1509
+ // all, and the old message ("did not reach RUNNING") distinguished neither.
1510
+ throw new Error(
1511
+ `Instance ${cfg.instanceName} did not reach RUNNING within 2 minutes ` +
1512
+ `(last observed state: ${lastState || "unknown — describe returned no state"}` +
1513
+ `${createdThisRun ? "; a create was issued this run" : ""}).`,
1514
+ );
1117
1515
  }
1118
1516
 
1119
1517
  /** GCE reports the instance as RUNNING the moment the boot disk is attached,
@@ -1496,7 +1894,320 @@ function bootstrapLogTail(cfg, lines = 40) {
1496
1894
  return String(r.stdout || "").trim() || "(log unavailable)";
1497
1895
  }
1498
1896
 
1499
- async function ensureProjectBootstrapped(cfg) {
1897
+ // ─── Detached PROJECT bootstrap ──────────────────────────────────────────────
1898
+ //
1899
+ // The VM bootstrap above solved a problem the PROJECT bootstrap still had: read
1900
+ // success and failure from VM-SIDE STATE, never from the SSH exit code, so a
1901
+ // dropped follow-session over a healthy VM is not misreported as "failed on the
1902
+ // VM". The project bootstrap ran instead as ONE blocking ssh-script call, so a
1903
+ // local budget elapsing (or an SSH pipe breaking) was indistinguishable from a
1904
+ // genuine remote failure and the caller's abort path DELETED A HEALTHY VM.
1905
+ // Raising the budget alone just moves the cliff; these helpers remove it by
1906
+ // mirroring the VM-bootstrap contract — detached launch, re-attaching follow
1907
+ // loop, VM-side outcome probe.
1908
+ //
1909
+ // All VM-side paths are keyed by repo name so two projects on one VM never
1910
+ // collide, and they sit beside the `.done` marker projectBootstrapDoneMarker
1911
+ // already defines. Pure string builders (like their VM-bootstrap counterparts)
1912
+ // so the whole grammar is unit-testable without a live VM.
1913
+ function projectBootstrapScriptPath(repoName) {
1914
+ return `$HOME/.codeyam-project-bootstrap-${repoName}.sh`;
1915
+ }
1916
+ function projectBootstrapRunnerPath(repoName) {
1917
+ return `$HOME/.codeyam-project-bootstrap-${repoName}-run.sh`;
1918
+ }
1919
+ function projectBootstrapLogPath(repoName) {
1920
+ return `$HOME/.codeyam-project-bootstrap-${repoName}.log`;
1921
+ }
1922
+ function projectBootstrapPidPath(repoName) {
1923
+ return `$HOME/.codeyam-project-bootstrap-${repoName}.pid`;
1924
+ }
1925
+ // The runner's recorded EXIT STATUS. Deliberately `.status`, NOT `.done`:
1926
+ // `.done` is already taken by scripts/gcp-project-bootstrap.sh's own terminal
1927
+ // SUCCESS marker (a timestamp, written only after `set -euo pipefail` carried
1928
+ // every step through — see projectBootstrapDoneMarker). Reusing `.done` for an
1929
+ // exit code would overwrite the success signal that both improve40's false-skip
1930
+ // fix and the follow loop below depend on. Two files, two distinct meanings:
1931
+ // `.done` = "the script reached its last line", `.status` = "the runner exited,
1932
+ // here is its code".
1933
+ function projectBootstrapStatusPath(repoName) {
1934
+ return `$HOME/.codeyam-project-bootstrap-${repoName}.status`;
1935
+ }
1936
+ const PROJECT_BOOTSTRAP_LAUNCHED_MARKER = "CODEYAM_PROJECT_BOOTSTRAP_LAUNCHED";
1937
+ const PROJECT_BOOTSTRAP_STATUS_MARKER = "CYPROJ";
1938
+ // One follow session caps at 15 min; the overall wait caps at
1939
+ // PROJECT_BOOTSTRAP_TIMEOUT_MS across re-attaches before we bail loudly with
1940
+ // the VM-side log location. Unlike the VM-bootstrap follow loop — whose follow
1941
+ // calls inherit the 120 s probe budget and so re-attach every two minutes over
1942
+ // a ~14-min build — the project follow call below is given an explicit local
1943
+ // budget just above this remote deadline, so a long install streams in one
1944
+ // session instead of churning re-attaches.
1945
+ const PROJECT_BOOTSTRAP_FOLLOW_SECS = 900;
1946
+ const PROJECT_BOOTSTRAP_FOLLOW_TIMEOUT_MS = (PROJECT_BOOTSTRAP_FOLLOW_SECS + 60) * 1000;
1947
+
1948
+ // The tiny VM-side wrapper the detached launch execs: run the real bootstrap,
1949
+ // redirect all output to the per-repo log, and record the exit status in the
1950
+ // `.status` sentinel — the single source of truth for "did the runner exit, and
1951
+ // with what?" once the SSH follow-session is gone. Contains NO secrets (tokens
1952
+ // arrive via the launch env prefix, never written to disk).
1953
+ function projectBootstrapRunnerScript(repoName) {
1954
+ return [
1955
+ "#!/usr/bin/env bash",
1956
+ "# Detached project-bootstrap runner (written by npm/cloud.js",
1957
+ "# ensureProjectBootstrapped). Survives SSH disconnect: the laptop only",
1958
+ "# *follows* the log below; this process keeps running under its own session",
1959
+ "# if the follow drops. Records its own PID so the status probe can check",
1960
+ "# liveness via `kill -0` (a `pgrep` on the script path would also match the",
1961
+ "# probe command itself).",
1962
+ `echo "$$" > "${projectBootstrapPidPath(repoName)}"`,
1963
+ `bash "${projectBootstrapScriptPath(repoName)}" "$@" > "${projectBootstrapLogPath(repoName)}" 2>&1`,
1964
+ "status=$?",
1965
+ `echo "$status" > "${projectBootstrapStatusPath(repoName)}"`,
1966
+ `rm -f "${projectBootstrapPidPath(repoName)}"`,
1967
+ "",
1968
+ ].join("\n");
1969
+ }
1970
+
1971
+ // Build the remote command that (1) materializes the bootstrap script + runner
1972
+ // on the VM, (2) clears the stale sentinels, (3) launches the runner DETACHED
1973
+ // (`nohup setsid`, new session, stdio to /dev/null) so it outlives the SSH
1974
+ // session, and (4) prints a launched marker. The detach is the durable fix: the
1975
+ // install no longer dies when the laptop's SSH pipe breaks, and the VM is no
1976
+ // longer torn down because it did.
1977
+ //
1978
+ // BOTH sentinels are cleared, `.status` and `.done`. Clearing `.done` is what
1979
+ // makes the outcome probe honest: after a launch, a present `.done` can only
1980
+ // mean THIS run's script reached its terminal line, never a leftover from a
1981
+ // previous half-wired attempt.
1982
+ function projectBootstrapLaunchCommand(scriptBody, scriptArgs = [], envVars = {}, repoName, libFiles = {}) {
1983
+ const scriptB64 = Buffer.from(scriptBody, "utf8").toString("base64");
1984
+ const runnerB64 = Buffer.from(projectBootstrapRunnerScript(repoName), "utf8").toString("base64");
1985
+ const argsString = scriptArgs.map(shQuote).join(" ");
1986
+ const envPrefix = envAssignmentPrefix(envVars);
1987
+ // The bootstrap script is written STANDALONE to $HOME, so any `source`/`.` it
1988
+ // does relative to its own directory resolves against $HOME — not against the
1989
+ // repo layout it was authored in. `libFiles` carries those siblings, keyed by
1990
+ // the $HOME-relative path the script will look for them at (e.g.
1991
+ // "lib/npm-pin.sh"). Their directories do not exist on a fresh VM, hence the
1992
+ // mkdir. Omitting a sourced library is not a soft failure: the script aborts
1993
+ // under `set -euo pipefail` and cloud:up tears the new VM down, which is the
1994
+ // 2026-09-04 fleet-wide add outage.
1995
+ const libWrites = Object.entries(libFiles).flatMap(([relPath, body]) => {
1996
+ const b64 = Buffer.from(body, "utf8").toString("base64");
1997
+ const dir = path.posix.dirname(relPath);
1998
+ const mkdir = dir && dir !== "." ? [`mkdir -p $HOME/${dir}`] : [];
1999
+ return [...mkdir, `echo '${b64}' | base64 -d > $HOME/${relPath}`];
2000
+ });
2001
+ // Writes run synchronously (fast, before any backgrounding) so a decode error
2002
+ // aborts before launch; then the runner is detached. The env prefix is on the
2003
+ // setsid command so the tokens are inherited through nohup→setsid→bash but
2004
+ // never appear in any argv. `& echo MARKER` (no `;` before echo) keeps the
2005
+ // launch in the background while still confirming it fired.
2006
+ const writes = [
2007
+ ...libWrites,
2008
+ `echo '${scriptB64}' | base64 -d > ${projectBootstrapScriptPath(repoName)}`,
2009
+ `echo '${runnerB64}' | base64 -d > ${projectBootstrapRunnerPath(repoName)}`,
2010
+ `rm -f ${projectBootstrapStatusPath(repoName)} ${projectBootstrapDoneMarker(repoName)}`,
2011
+ ].join(" && ");
2012
+ const launch =
2013
+ `${envPrefix}nohup setsid bash ${projectBootstrapRunnerPath(repoName)} ${argsString}`.trimEnd() +
2014
+ ` </dev/null >/dev/null 2>&1 &`;
2015
+ return `${writes}; ${launch} echo ${PROJECT_BOOTSTRAP_LAUNCHED_MARKER}`;
2016
+ }
2017
+
2018
+ // Build the remote command that FOLLOWS the detached install: tail the log live
2019
+ // for the operator, polling for the `.status` sentinel, and exit when the runner
2020
+ // finishes OR a per-session deadline elapses. If the SSH session drops
2021
+ // mid-follow this command dies but the detached install keeps going — the caller
2022
+ // then re-attaches.
2023
+ function projectBootstrapFollowCommand(repoName, deadlineSecs = PROJECT_BOOTSTRAP_FOLLOW_SECS) {
2024
+ const log = projectBootstrapLogPath(repoName);
2025
+ const status = projectBootstrapStatusPath(repoName);
2026
+ return [
2027
+ `touch ${log}`,
2028
+ `tail -n +1 -F ${log} 2>/dev/null & TP=$!`,
2029
+ `waited=0`,
2030
+ `while [ ! -f ${status} ]; do ` +
2031
+ `sleep 3; waited=$((waited+3)); ` +
2032
+ `if [ "$waited" -ge ${deadlineSecs} ]; then kill "$TP" 2>/dev/null; exit 0; fi; ` +
2033
+ `done`,
2034
+ `sleep 1`,
2035
+ `kill "$TP" 2>/dev/null`,
2036
+ ].join("; ");
2037
+ }
2038
+
2039
+ // Build the remote command that reports terminal VM state in one parseable
2040
+ // line: whether the script's terminal `.done` marker exists, the runner's
2041
+ // recorded exit status (or `none`), and whether the runner is still alive.
2042
+ // Cheap — runs over ssh-probe.
2043
+ function projectBootstrapStatusCommand(repoName) {
2044
+ const pid = projectBootstrapPidPath(repoName);
2045
+ const status = projectBootstrapStatusPath(repoName);
2046
+ // Liveness via the runner's PID file + `kill -0`, NOT pgrep: the status
2047
+ // command's own argv contains the bootstrap path, so a `pgrep -f` on it would
2048
+ // match this very probe and always report running. A stale PID file from a
2049
+ // killed runner reads as not-running because `kill -0` fails.
2050
+ return [
2051
+ `done=no; [ -f ${projectBootstrapDoneMarker(repoName)} ] && done=yes`,
2052
+ `st=none; [ -f ${status} ] && st=$(cat ${status} 2>/dev/null)`,
2053
+ `run=no; if [ -f ${pid} ]; then p=$(cat ${pid} 2>/dev/null); ` +
2054
+ `{ [ -n "$p" ] && kill -0 "$p" 2>/dev/null; } && run=yes; fi`,
2055
+ `echo "${PROJECT_BOOTSTRAP_STATUS_MARKER} done=$done status=$st running=$run"`,
2056
+ ].join("; ");
2057
+ }
2058
+
2059
+ // Parse the single status line emitted by projectBootstrapStatusCommand.
2060
+ // Returns `{ done, status, running }` or null when no status line is present
2061
+ // (e.g. the probe ssh itself failed and produced no stdout).
2062
+ function parseProjectBootstrapStatus(stdout) {
2063
+ const m = String(stdout || "").match(
2064
+ new RegExp(`${PROJECT_BOOTSTRAP_STATUS_MARKER} done=(\\S+) status=(\\S+) running=(\\S+)`),
2065
+ );
2066
+ if (!m) return null;
2067
+ return { done: m[1], status: m[2], running: m[3] };
2068
+ }
2069
+
2070
+ // Decide the project-bootstrap outcome from VM-side state alone — never the SSH
2071
+ // exit code. The `.done` marker is the real artifact (the script writes it only
2072
+ // after `set -euo pipefail` carried every step to success), so its presence is
2073
+ // success regardless of how the follow session ended — the same reasoning that
2074
+ // makes the docker image authoritative for the VM bootstrap. A live runner means
2075
+ // "re-attach". A recorded exit status without the marker means the install ran
2076
+ // and failed. Nothing at all means it was never started (or the probe could not
2077
+ // see it).
2078
+ function decideProjectBootstrapOutcome(status) {
2079
+ if (!status) return "absent";
2080
+ const { done, status: exitStatus, running } = status;
2081
+ if (done === "yes") return "success";
2082
+ if (running === "yes") return "running";
2083
+ if (exitStatus && exitStatus !== "none") return "failed";
2084
+ return "absent";
2085
+ }
2086
+
2087
+ // Reduce one follow-loop iteration to an action: "success" | "failed" |
2088
+ // "timeout" | "reattach". Extracted as a pure function because its PRECEDENCE is
2089
+ // load-bearing — it decides whether an operator is told a VM is broken:
2090
+ //
2091
+ // • success and failed outrank the deadline. Otherwise the final poll of a
2092
+ // slow-but-successful bootstrap reports a timeout, and the operator is sent
2093
+ // to reconcile a VM that actually finished.
2094
+ // • a still-running install past the deadline is a TIMEOUT, never a failure.
2095
+ // That is the VM-8 case: healthy VM, still installing, and saying so is what
2096
+ // gets the add classified retryable instead of destroyed.
2097
+ // • an unseen runner ("absent") before the deadline re-attaches rather than
2098
+ // failing — "I could not see it" is not "it broke" — but is still bounded by
2099
+ // the deadline so the loop cannot spin forever.
2100
+ function decideProjectBootstrapFollowAction({ outcome, now, deadline } = {}) {
2101
+ if (outcome === "success") return "success";
2102
+ if (outcome === "failed") return "failed";
2103
+ if (now >= deadline) return "timeout";
2104
+ return "reattach";
2105
+ }
2106
+
2107
+ // Probe the VM for the detached project bootstrap's terminal state and reduce it
2108
+ // to a single outcome string ("success" | "failed" | "running" | "absent").
2109
+ // Used both for the idempotent re-attach decision and after each follow session.
2110
+ function probeProjectBootstrapOutcome(cfg, repoName) {
2111
+ const r = runGcloud(
2112
+ buildGcloudArgs("ssh-probe", cfg, { command: projectBootstrapStatusCommand(repoName) }),
2113
+ { stdio: ["ignore", "pipe", "pipe"] },
2114
+ );
2115
+ return decideProjectBootstrapOutcome(parseProjectBootstrapStatus(r.stdout));
2116
+ }
2117
+
2118
+ /** Assemble the env forwarded into the project-bootstrap shell on the VM.
2119
+ * Extracted from ensureProjectBootstrapped so its CONDITIONAL keys are testable
2120
+ * without a VM — previously you could not assert "FLEET_DOMAIN is omitted for a
2121
+ * non-fleet project" or "a re-provision without --admin stays non-admin"
2122
+ * without invoking the whole gcloud-touching bootstrap.
2123
+ *
2124
+ * Keys, and why each is here:
2125
+ * GITHUB_TOKEN — clone a private client repo.
2126
+ * CY_GIT_USER_{NAME,EMAIL} — rendered into the compose file, then written
2127
+ * to `git config --global` by the entrypoint so
2128
+ * plan_claim_refs::create_claim's commit-tree
2129
+ * call succeeds. Empty is legitimate (a CI
2130
+ * runner with no author); the entrypoint warns
2131
+ * and proceeds, so the keys stay present.
2132
+ * FLEET_DOMAIN — ONLY for a numbered fleet VM with a domain
2133
+ * configured, so the compose render publishes
2134
+ * on 0.0.0.0 for the LB NEG. Omitted entirely
2135
+ * otherwise, preserving the loopback-only
2136
+ * publish a plain client project expects.
2137
+ * <forwarded launch-form keys> — DATABASE_URL et al, whitelisted by the
2138
+ * dashboard via CY_FORWARD_ENV_KEYS, so the
2139
+ * bootstrap-time `npm run setup` sees them on
2140
+ * the first try. Empty on plain `cloud:up`.
2141
+ * CODEYAM_ADMIN — the Home-tab Setup door. Defaults to the
2142
+ * strict non-admin "".
2143
+ *
2144
+ * Later spreads win, matching the original inline assembly exactly. `deps` lets
2145
+ * a test supply the token and git identity instead of reading the real
2146
+ * environment and shelling out to git. */
2147
+ function projectBootstrapEnv(cfg = {}, { env = process.env, githubToken, gitIdentity } = {}) {
2148
+ const git = gitIdentity || resolveLaptopGitIdentity();
2149
+ const out = {
2150
+ GITHUB_TOKEN: githubToken !== undefined ? githubToken : resolveGithubToken(),
2151
+ CY_GIT_USER_NAME: git.name,
2152
+ CY_GIT_USER_EMAIL: git.email,
2153
+ };
2154
+ const ingressPlan = ingressWiringPlan(cfg, env);
2155
+ if (ingressPlan.wire) out.FLEET_DOMAIN = ingressPlan.domain;
2156
+ Object.assign(out, resolveSetupForwardEnv(env));
2157
+ Object.assign(out, buildProvisionEnv(env, cfg));
2158
+ return out;
2159
+ }
2160
+
2161
+ // Fetch the tail of the VM-side project-bootstrap log for an actionable failure
2162
+ // message — the operator sees WHY the install failed, not a bare exit code.
2163
+ function projectBootstrapLogTail(cfg, repoName, lines = 40) {
2164
+ const r = runGcloud(
2165
+ buildGcloudArgs("ssh-probe", cfg, {
2166
+ command: `tail -n ${lines} ${projectBootstrapLogPath(repoName)} 2>/dev/null`,
2167
+ }),
2168
+ { stdio: ["ignore", "pipe", "pipe"] },
2169
+ );
2170
+ return String(r.stdout || "").trim() || "(log unavailable)";
2171
+ }
2172
+
2173
+ /** Assemble the extra provision-time env forwarded into the bootstrap shell,
2174
+ * where it feeds the compose-render substitution. Currently just the admin
2175
+ * toggle: CODEYAM_ADMIN gates the Home-tab Setup door and is read from the
2176
+ * editor-server process env (handlers.rs::admin_enabled, strict literal "1").
2177
+ * The operator opts in with `CODEYAM_ADMIN=1 npm run cloud:up …` or `--admin`
2178
+ * (which lands as cfg.admin); anything else forwards "" so a normal launch —
2179
+ * and a re-provision without the flag — is strict non-admin. Pure over its
2180
+ * inputs so cloud.test.js can pin it without touching gcloud. */
2181
+ function buildProvisionEnv(env = process.env, flags = {}) {
2182
+ const admin = flags.admin === true || env.CODEYAM_ADMIN === "1";
2183
+ return { CODEYAM_ADMIN: admin ? "1" : "" };
2184
+ }
2185
+
2186
+ /** Build the one-shot SSH shell command that reconciles a running VM's admin
2187
+ * mode without a full re-provision: rewrite the rendered compose's
2188
+ * CODEYAM_ADMIN line to `value` — or insert it under `environment:` on a legacy
2189
+ * VM whose compose predates the placeholder — then recreate the editor service
2190
+ * so admin_enabled() re-reads it. `value` is always "1" or "" (the caller
2191
+ * normalizes), so inlining it into sed is safe. Pure/string-only so
2192
+ * cloud.test.js can assert its shape without SSHing. */
2193
+ function buildReconcileAdminCommand(repoName, value) {
2194
+ const f = "docker-compose.cloud.yml";
2195
+ const entry = ` - CODEYAM_ADMIN=${value}`;
2196
+ // Capture only the leading indentation (\1) and re-emit the literal key, so a
2197
+ // value that starts with a digit (e.g. "1") never lands right after the
2198
+ // backreference — `\11` would be read by sed as group 11, not `\1` + "1".
2199
+ return (
2200
+ `cd ~/projects/${repoName} && ` +
2201
+ `if grep -qE '^[[:space:]]*- CODEYAM_ADMIN=' ${f}; then ` +
2202
+ `sed -i -E 's#^([[:space:]]*)- CODEYAM_ADMIN=.*#\\1- CODEYAM_ADMIN=${value}#' ${f}; ` +
2203
+ `else ` +
2204
+ `sed -i -E 's#^([[:space:]]*environment:[[:space:]]*)$#\\1\\n${entry}#' ${f}; ` +
2205
+ `fi && ` +
2206
+ `docker compose -f ${f} up -d editor`
2207
+ );
2208
+ }
2209
+
2210
+ async function ensureProjectBootstrapped(cfg, { sleepFn } = {}) {
1500
2211
  const repoName = resolveProject(cfg).name;
1501
2212
  console.error(`Checking project bootstrap state for ${repoName}...`);
1502
2213
  // Gate on the TERMINAL completion marker the script writes as its very last
@@ -1525,44 +2236,162 @@ async function ensureProjectBootstrapped(cfg) {
1525
2236
  console.error(` streaming scripts/gcp-project-bootstrap.sh to VM for ${cfg.repo}...`);
1526
2237
  const scriptPath = path.join(rootDir, "scripts", "gcp-project-bootstrap.sh");
1527
2238
  const scriptBody = readStreamedScript(scriptPath, cfg);
2239
+ // gcp-project-bootstrap.sh sources lib/npm-pin.sh relative to its own
2240
+ // directory. Read it through readStreamedScript too, so the library is subject
2241
+ // to the same drift guard as the script that sources it — streaming a reviewed
2242
+ // remote script beside a stale on-disk library would defeat the guard.
2243
+ const bootstrapLibs = {
2244
+ "lib/npm-pin.sh": readStreamedScript(path.join(rootDir, "scripts", "lib", "npm-pin.sh"), cfg),
2245
+ };
1528
2246
  const scriptArgs = clientProjectBootstrapArgs(cfg);
1529
- // Forward the laptop's git author identity so the rendered compose file
1530
- // carries CY_GIT_USER_{NAME,EMAIL} → the entrypoint writes them to
1531
- // `git config --global` → plan_claim_refs::create_claim's commit-tree call
1532
- // succeeds. Empty strings are fine (laptop has no identity, e.g. a CI
1533
- // runner); the entrypoint warns and proceeds.
1534
- const laptopGit = resolveLaptopGitIdentity();
1535
- // Forward the operator's launch-form env keys (DATABASE_URL, etc.) into the
1536
- // bootstrap shell so the bootstrap-time `npm run setup` sees them on the
1537
- // first try — without this, Prisma `db:push`/`db:seed` fail for lack of
1538
- // env and the bootstrap's fail-soft branch leaves the app schema-less until
1539
- // the post-add `reapplyVmEnv` re-fires setup. See
1540
- // `improve37-launch-form-env-injected-into-cloud-up-bootstrap-not-just-applied-after`.
1541
- // Whitelisted by the dashboard via CY_FORWARD_ENV_KEYS — empty on the
1542
- // standalone `cloud:up` path, so that flow is unchanged.
1543
- const forwardEnv = resolveSetupForwardEnv();
1544
- // Forward the fleet domain so the bootstrap's compose render publishes the
1545
- // editor/app ports on 0.0.0.0 (the LB NEG reaches them on the VM's internal
1546
- // IP) instead of loopback-only. Only when a fleet domain is configured AND
1547
- // this is a numbered fleet VM — a non-fleet client project keeps the
1548
- // loopback-only publish (legacy parity). Absent ⇒ key omitted entirely.
1549
- const ingressEnv = {};
1550
- const ingressPlan = ingressWiringPlan(cfg);
1551
- if (ingressPlan.wire) ingressEnv.FLEET_DOMAIN = ingressPlan.domain;
1552
- const command = sshScriptCommand(scriptBody, scriptArgs, {
1553
- GITHUB_TOKEN: resolveGithubToken(),
1554
- CY_GIT_USER_NAME: laptopGit.name,
1555
- CY_GIT_USER_EMAIL: laptopGit.email,
1556
- ...ingressEnv,
1557
- ...forwardEnv,
1558
- });
1559
- const result = runGcloud(
1560
- buildGcloudArgs("ssh-script", cfg, { command }),
1561
- { stdio: "inherit" },
2247
+ // Git identity, forwarded launch-form keys, fleet-domain ingress and the admin
2248
+ // toggle — see projectBootstrapEnv for what each key is for and when it is
2249
+ // omitted. Extracted so those conditionals are testable without a VM.
2250
+ const bootstrapEnv = projectBootstrapEnv(cfg);
2251
+
2252
+ // Idempotent re-attach: a prior cloud:up whose follow-session dropped may have
2253
+ // left a detached install still running. Converge on it instead of starting a
2254
+ // second `npm install` on top of the first.
2255
+ //
2256
+ // NOTE the deliberate asymmetry with ensureBootstrapped, which DOES return
2257
+ // early on an outcome of "success". There, the done-probe and the outcome probe
2258
+ // read the same artifact (the docker image), so they always agree. Here the
2259
+ // done-probe above is a strictly STRONGER three-way AND (`.done` marker +
2260
+ // ~/projects/<repo>/.codeyam + docker-compose.cloud.yml) than this probe's
2261
+ // `.done`-alone success, and it has already said no. Honoring a bare `.done`
2262
+ // here would re-open the improve40 VM-7 false-skip from the other side, so only
2263
+ // "running" short-circuits the launch.
2264
+ const initial = probeProjectBootstrapOutcome(cfg, repoName);
2265
+ if (initial === "running") {
2266
+ console.error(" ↺ a detached project bootstrap is already in progress — re-attaching to its log...");
2267
+ } else {
2268
+ // "absent" (never started), "failed" (a prior run died), or "success" (a bare
2269
+ // marker the stricter done-probe rejected) → (re)launch a fresh detached
2270
+ // install that will survive an SSH disconnect. Every step of
2271
+ // gcp-project-bootstrap.sh is skip-on-exists, so re-entering is cheap.
2272
+ console.error(" launching detached project bootstrap on the VM (survives SSH disconnect)...");
2273
+ const launch = projectBootstrapLaunchCommand(scriptBody, scriptArgs, bootstrapEnv, repoName, bootstrapLibs);
2274
+ const launched = await runGcloudSshWithRetry(
2275
+ "ssh-script",
2276
+ cfg,
2277
+ { command: launch },
2278
+ { stdio: ["ignore", "pipe", "pipe"], label: "project bootstrap launch", sleepFn },
2279
+ );
2280
+ if (isSpawnTimeout(launched)) {
2281
+ // The LOCAL budget elapsed and we SIGTERMd the gcloud child. Say so:
2282
+ // the launch is a short write-and-detach, so this is an SSH-reachability
2283
+ // problem, NOT a broken bootstrap script — and the VM may be perfectly
2284
+ // healthy. Conflating the two is what destroyed VM-8.
2285
+ throw new Error(
2286
+ `launching the detached project bootstrap exceeded the local gcloud call budget ` +
2287
+ `and was SIGTERMd locally — the VM may be healthy and simply unreachable over SSH ` +
2288
+ `right now. Re-run to re-attach (each bootstrap step is skip-on-exists).`,
2289
+ );
2290
+ }
2291
+ if (launched.status !== 0) {
2292
+ throw new Error(
2293
+ `failed to launch the detached project bootstrap on the VM (gcloud ssh exit ${launched.status}).\n` +
2294
+ formatGcloudFailure(launched),
2295
+ );
2296
+ }
2297
+ }
2298
+
2299
+ // Follow the live log, re-attaching across any follow-session drops, until the
2300
+ // VM reports a terminal state or the overall deadline elapses. Success and
2301
+ // failure are read from VM state (the `.done` marker + the `.status` sentinel),
2302
+ // never the SSH exit code — so "my laptop's SSH dropped" or "a heavy npm
2303
+ // install outran a local budget" no longer masquerades as a broken bootstrap
2304
+ // and no longer gets a healthy VM deleted.
2305
+ const deadline = Date.now() + PROJECT_BOOTSTRAP_TIMEOUT_MS;
2306
+ for (;;) {
2307
+ runGcloud(
2308
+ buildGcloudArgs("ssh-script", cfg, { command: projectBootstrapFollowCommand(repoName) }),
2309
+ { stdio: "inherit", timeout: PROJECT_BOOTSTRAP_FOLLOW_TIMEOUT_MS },
2310
+ );
2311
+ const outcome = probeProjectBootstrapOutcome(cfg, repoName);
2312
+ const action = decideProjectBootstrapFollowAction({
2313
+ outcome,
2314
+ now: Date.now(),
2315
+ deadline,
2316
+ });
2317
+ if (action === "success") {
2318
+ console.error(` ✓ ${repoName} bootstrap complete`);
2319
+ return;
2320
+ }
2321
+ if (action === "failed") {
2322
+ const tail = projectBootstrapLogTail(cfg, repoName);
2323
+ throw new Error(
2324
+ "scripts/gcp-project-bootstrap.sh failed on the VM. " +
2325
+ `Last lines of ${projectBootstrapLogPath(repoName)}:\n${tail}`,
2326
+ );
2327
+ }
2328
+ if (action === "timeout") {
2329
+ // The install is STILL RUNNING on a healthy VM and we simply stopped
2330
+ // waiting. This message is the signature npm/fleet-add-failure.js keys on
2331
+ // to classify the add as `project-bootstrap-timeout` (retryable) instead of
2332
+ // the non-retryable generic cloud-up-failed that tore down VM-8.
2333
+ throw new Error(
2334
+ `project bootstrap exceeded the local ${Math.round(PROJECT_BOOTSTRAP_TIMEOUT_MS / 60000)}-minute budget ` +
2335
+ `— the VM and its detached bootstrap may be healthy and still running. ` +
2336
+ `Re-run to re-attach (each bootstrap step is skip-on-exists), or inspect ` +
2337
+ `${projectBootstrapLogPath(repoName)} on the VM.`,
2338
+ );
2339
+ }
2340
+ // action === "reattach": the follow session ended but the install is alive
2341
+ // (or the probe could not see it yet). Re-attach to its log.
2342
+ console.error(" ↺ follow session ended but the project bootstrap is still running — re-attaching...");
2343
+ }
2344
+ }
2345
+
2346
+ /** Run the compose-ps liveness probe over SSH and report BOTH the editor
2347
+ * service's state and whether the probe itself could be trusted.
2348
+ *
2349
+ * The `|| true` keeps the remote pipeline's exit status 0 whenever SSH itself
2350
+ * worked, so a non-zero `status` means the transport failed (auth/SSH/IAP) —
2351
+ * not that the container is down. Callers that must fail safe (the abort
2352
+ * teardown) need that distinction; `parseEditorComposeState` alone collapses
2353
+ * "no container" and "could not ask" into the same `null`.
2354
+ *
2355
+ * Returns `{ state, inconclusive }` where `state` is the compose `State` string
2356
+ * (`"running"`, `"exited"`, …) or null when the service is absent, and
2357
+ * `inconclusive` is true only for a transport failure. */
2358
+ function probeEditorComposeState(cfg) {
2359
+ const repoName = resolveProject(cfg).name;
2360
+ const composeCmd = `docker compose -f docker-compose.cloud.yml`;
2361
+ const probe = runGcloud(
2362
+ buildGcloudArgs("ssh-probe", cfg, {
2363
+ command: `cd ~/projects/${repoName} 2>/dev/null && ${composeCmd} ps --format json 2>/dev/null || true`,
2364
+ }),
2365
+ { stdio: ["ignore", "pipe", "ignore"] },
1562
2366
  );
1563
- if (result.status !== 0) {
1564
- throw new Error("scripts/gcp-project-bootstrap.sh failed on the VM");
2367
+ if (probe.status !== 0) {
2368
+ return { state: null, inconclusive: true };
1565
2369
  }
2370
+ return { state: parseEditorComposeState(probe.stdout), inconclusive: false };
2371
+ }
2372
+
2373
+ /** Poll {@link probeEditorComposeState} until the editor service reads
2374
+ * `running`, returning true as soon as it does. Used to close the TOCTOU window
2375
+ * after a container-name conflict: the winning run may still be inside
2376
+ * `Creating`/`Created` when the conflict surfaces, so a single immediate probe
2377
+ * can under-read and report a healthy container as absent.
2378
+ *
2379
+ * Deliberately short (default ~30s): this is not the multi-minute first-boot
2380
+ * budget `waitForContainerRunning` grants, it is the tail of a start that
2381
+ * another process has already begun. `sleepFn` and `probeFn` are injectable so
2382
+ * a unit test drives the whole loop with neither wall-clock delay nor a VM. */
2383
+ async function waitForEditorComposeRunning(cfg, { attempts = 6, delayMs = 5000, sleepFn, probeFn } = {}) {
2384
+ const sleep = sleepFn || ((ms) => new Promise((r) => setTimeout(r, ms)));
2385
+ const probe = probeFn || probeEditorComposeState;
2386
+ for (let i = 0; i < attempts; i++) {
2387
+ if (probe(cfg).state === "running") {
2388
+ return true;
2389
+ }
2390
+ if (i < attempts - 1) {
2391
+ await sleep(delayMs);
2392
+ }
2393
+ }
2394
+ return false;
1566
2395
  }
1567
2396
 
1568
2397
  async function ensureEditorContainerUp(cfg) {
@@ -1572,13 +2401,7 @@ async function ensureEditorContainerUp(cfg) {
1572
2401
  // cloud variant when self-hosting (see gcp-project-bootstrap.sh).
1573
2402
  const composeCmd = `docker compose -f docker-compose.cloud.yml`;
1574
2403
  console.error("Checking editor container state...");
1575
- const probe = runGcloud(
1576
- buildGcloudArgs("ssh-probe", cfg, {
1577
- command: `cd ~/projects/${repoName} && ${composeCmd} ps --format json 2>/dev/null || true`,
1578
- }),
1579
- { stdio: ["ignore", "pipe", "ignore"] },
1580
- );
1581
- if (probe.status === 0 && parseEditorComposeState(probe.stdout) === "running") {
2404
+ if (probeEditorComposeState(cfg).state === "running") {
1582
2405
  console.error(" ✓ editor container is already running");
1583
2406
  // containerStarted: the container is confirmed up, so the CLI install runs
1584
2407
  // its POST-start path with no wait — see the precondition on ensureAgentCliInstalled.
@@ -1586,14 +2409,47 @@ async function ensureEditorContainerUp(cfg) {
1586
2409
  return;
1587
2410
  }
1588
2411
  console.error(" starting editor container (docker compose up -d)...");
2412
+ // CAPTURE rather than `stdio: "inherit"`: the daemon writes its container-name
2413
+ // conflict to stderr, and with "inherit" that text went straight to our parent
2414
+ // and was never observable here — so the conflict could not be told apart from
2415
+ // a real failure (the 2026-08-07 VM-4/VM-5 delete). spawnSync cannot both
2416
+ // stream and capture, so the operator's view is preserved by echoing the
2417
+ // captured streams immediately below instead of live. Do NOT revert this to
2418
+ // "inherit"; classification depends on it.
1589
2419
  const up = runGcloud(
1590
2420
  buildGcloudArgs("ssh-probe", cfg, {
1591
2421
  command: `cd ~/projects/${repoName} && ${composeCmd} up -d`,
1592
2422
  }),
1593
- { stdio: "inherit" },
2423
+ { stdio: ["ignore", "pipe", "pipe"] },
1594
2424
  );
2425
+ if (up.stdout) process.stderr.write(up.stdout);
2426
+ if (up.stderr) process.stderr.write(up.stderr);
1595
2427
  if (up.status !== 0) {
1596
- throw new Error("docker compose up -d failed on the VM");
2428
+ const verdict = classifyComposeUpFailure({ status: up.status, stderr: `${up.stderr || ""}\n${up.stdout || ""}` });
2429
+ if (verdict !== "name-conflict") {
2430
+ throw new Error("docker compose up -d failed on the VM");
2431
+ }
2432
+ // A name conflict means a concurrent run already created this container —
2433
+ // the goal we were about to pursue is being reached by someone else. Confirm
2434
+ // that positively before converging: a conflict whose container never
2435
+ // reaches `running` (e.g. a stale STOPPED container squatting the name) is a
2436
+ // genuine problem and must still fail loudly, or convergence becomes a
2437
+ // catch-all that papers over real breakage.
2438
+ console.error(
2439
+ " a concurrent run already created the editor container — confirming it reaches running...",
2440
+ );
2441
+ if (!(await waitForEditorComposeRunning(cfg))) {
2442
+ throw new Error(
2443
+ "docker compose up -d hit a container-name conflict on the VM, but the conflicting " +
2444
+ "container never reached running (a stale stopped container may be holding the name). " +
2445
+ `Inspect with: gcloud compute ssh ${cfg.instanceName} --command 'cd ~/projects/${repoName} && ${composeCmd} ps -a'`,
2446
+ );
2447
+ }
2448
+ console.error(" ✓ editor container is running (started by a concurrent run)");
2449
+ // containerStarted: the container is confirmed up — same post-start contract
2450
+ // as the already-running short-circuit above.
2451
+ await ensureAgentCliInstalled(cfg, { containerStarted: true });
2452
+ return;
1597
2453
  }
1598
2454
  // containerStarted: `up -d` returned 0, so the CLI install is legitimately a
1599
2455
  // post-start step. A brief wait-for-running here (slow boot settling) is
@@ -1609,18 +2465,10 @@ async function ensureEditorContainerUp(cfg) {
1609
2465
  // success. This throws (non-zero exit) when the editor service isn't
1610
2466
  // `running`, converting a silent partial provision into a loud, actionable
1611
2467
  // failure the operator (and the dashboard's fail-fast-on-nonzero path) can act
1612
- // on. The `|| true` keeps the probe's exit status 0 so the real signal is the
1613
- // parsed compose state, not the SSH/cd exit code.
2468
+ // on. An inconclusive probe is not "running" here — a terminal gate must have
2469
+ // positive evidence, and the caller's job is to fail loudly without it.
1614
2470
  async function assertEditorContainerRunning(cfg) {
1615
- const repoName = resolveProject(cfg).name;
1616
- const composeCmd = `docker compose -f docker-compose.cloud.yml`;
1617
- const probe = runGcloud(
1618
- buildGcloudArgs("ssh-probe", cfg, {
1619
- command: `cd ~/projects/${repoName} 2>/dev/null && ${composeCmd} ps --format json 2>/dev/null || true`,
1620
- }),
1621
- { stdio: ["ignore", "pipe", "ignore"] },
1622
- );
1623
- if (!(probe.status === 0 && parseEditorComposeState(probe.stdout) === "running")) {
2471
+ if (probeEditorComposeState(cfg).state !== "running") {
1624
2472
  throw new Error(
1625
2473
  `provisioning incomplete: editor container is not running on ${cfg.instanceName} ` +
1626
2474
  `(no /workspace or container). Re-run: npm run cloud:up -- --instance-name ${cfg.instanceName}`,
@@ -1763,49 +2611,113 @@ function resolveGhcrPushToken() {
1763
2611
  return process.env.CODEYAM_GHCR_PUSH_TOKEN || "";
1764
2612
  }
1765
2613
 
2614
+ // Registry manifest media types we accept when probing image presence over the
2615
+ // GHCR HTTP API — Docker v2 + manifest lists and their OCI equivalents, so a
2616
+ // multi-arch index answers 200 the same as a single-arch manifest.
2617
+ const MANIFEST_ACCEPT = [
2618
+ "application/vnd.docker.distribution.manifest.v2+json",
2619
+ "application/vnd.docker.distribution.manifest.list.v2+json",
2620
+ "application/vnd.oci.image.manifest.v1+json",
2621
+ "application/vnd.oci.image.index.v1+json",
2622
+ ].join(", ");
2623
+ const GHCR_PROBE_TIMEOUT_MS = 15000;
2624
+
2625
+ /** Default HTTPS client for the registry probe: a GET that resolves to
2626
+ * `{ statusCode }` and NEVER rejects — any socket / DNS / timeout error resolves
2627
+ * to `statusCode: 0` (the probe reads that as "undetermined"). Injected as the
2628
+ * `httpImpl` option so probeUsableEditorImage is unit-testable with no network
2629
+ * (and no Docker daemon). `requestImpl` (defaulting to `https.request`) is
2630
+ * injectable so the response / error / timeout mapping is itself unit-testable
2631
+ * without a real socket. */
2632
+ function httpsManifestGet({ hostname, path: reqPath, headers }, requestImpl = https.request) {
2633
+ return new Promise((resolve) => {
2634
+ const req = requestImpl(
2635
+ { hostname, path: reqPath, method: "GET", headers },
2636
+ (res) => {
2637
+ res.resume(); // drain the body so the socket is freed
2638
+ res.on("end", () => resolve({ statusCode: res.statusCode }));
2639
+ },
2640
+ );
2641
+ req.on("error", () => resolve({ statusCode: 0 }));
2642
+ req.setTimeout(GHCR_PROBE_TIMEOUT_MS, () => req.destroy());
2643
+ req.end();
2644
+ });
2645
+ }
2646
+
2647
+ /** Probe ONE fully-qualified image ref (`host/repo:tag`) over the registry HTTP
2648
+ * API — no docker daemon, so a docker-less operator host can still determine
2649
+ * presence. Returns true (200 present), false (404 absent), or null (auth /
2650
+ * network / malformed-ref → can't tell absent from forbidden). */
2651
+ async function probeManifestRef(fullRef, bearer, httpGet) {
2652
+ const colon = fullRef.lastIndexOf(":");
2653
+ if (colon < 0) return null;
2654
+ const ref = fullRef.slice(0, colon); // host/repo
2655
+ const tag = fullRef.slice(colon + 1); // slug-latest
2656
+ const slash = ref.indexOf("/");
2657
+ if (slash < 0) return null;
2658
+ const hostname = ref.slice(0, slash); // ghcr.io
2659
+ const repo = ref.slice(slash + 1); // codeyam-ai/codeyam-editor-cloud-smoke
2660
+ let res;
2661
+ try {
2662
+ res = await httpGet({
2663
+ hostname,
2664
+ path: `/v2/${repo}/manifests/${encodeURIComponent(tag)}`,
2665
+ headers: { Authorization: `Bearer ${bearer}`, Accept: MANIFEST_ACCEPT },
2666
+ });
2667
+ } catch (_e) {
2668
+ return null;
2669
+ }
2670
+ const code = res && res.statusCode;
2671
+ if (code === 200) return true;
2672
+ if (code === 404) return false;
2673
+ return null; // 401 / 403 / 5xx / 0 (network) → undetermined
2674
+ }
2675
+
1766
2676
  /** Read-only probe: does a usable prebuilt editor image already exist on the
1767
2677
  * registry for `branch`? Used by the fleet dashboard BEFORE a concurrent batch
1768
2678
  * add to decide whether to pace one VM ahead of the rest (see
1769
- * npm/fleet-prewarm.js::decideBatchPrewarm). A `docker manifest inspect` is a
1770
- * HEAD-equivalent — it reads the manifest without pulling the (multi-GB) image.
2679
+ * npm/fleet-prewarm.js::decideBatchPrewarm).
2680
+ *
2681
+ * Queries the registry over its HTTP API (`GET /v2/<repo>/manifests/<tag>`, a
2682
+ * HEAD-equivalent that reads the manifest without pulling the multi-GB image)
2683
+ * instead of `docker login` / `docker manifest inspect`. This is the root fix
2684
+ * for the docker-less GCE operator host: the old docker path errored on the
2685
+ * first `docker login` spawn (the control plane has no docker daemon) and so
2686
+ * returned `null` forever, which decideBatchPrewarm read as "fan out" — the
2687
+ * image was therefore never published and every cold add source-built. Over
2688
+ * HTTP the probe returns a DEFINITIVE verdict with no daemon.
1771
2689
  *
1772
2690
  * Returns:
1773
2691
  * true — at least one of the usable tags exists (a cold add can pull; no pacer)
1774
2692
  * false — every tag was checked and none exists (known-absent; pacing pays)
1775
- * null — undetermined: no read token, docker missing, or a probe error that
1776
- * can't be distinguished from "absent". The caller treats null as
1777
- * "fan out" (today's behavior, never worse) rather than risk a
1778
- * 10-min serialization that might buy nothing.
2693
+ * null — undetermined: no read token, or an auth/network error that can't be
2694
+ * distinguished from "absent".
1779
2695
  *
1780
- * The private packages require auth, so we `docker login` with the read token
1781
- * first; without a token we can't tell absent from forbidden, so → null.
1782
- * `spawnImpl` is injectable for unit tests. */
1783
- function probeUsableEditorImage({ branch, registry, token, spawnImpl } = {}) {
2696
+ * GHCR's private packages require auth; without a read token we can't tell
2697
+ * absent from forbidden, so → null. The read token is sent as the registry
2698
+ * bearer (GHCR accepts a base64-encoded PAT directly — no separate token-
2699
+ * exchange round-trip). `httpImpl` is injectable for unit tests; a legacy
2700
+ * `spawnImpl` option is still accepted (and ignored) for backward-compat — the
2701
+ * HTTP happy path needs no spawn. */
2702
+ async function probeUsableEditorImage({ branch, registry, token, httpImpl } = {}) {
1784
2703
  const fp = require("./fleet-prewarm");
1785
- const spawn = spawnImpl || spawnSync;
1786
2704
  const reg = registry || process.env.CODEYAM_REGISTRY || "ghcr.io/codeyam-ai";
1787
2705
  const readToken = token || resolveGhcrToken();
1788
2706
  if (!readToken) return null; // can't auth → can't distinguish absent from forbidden
1789
- const host = String(reg).split("/")[0];
1790
- const login = spawn(
1791
- "docker",
1792
- ["login", host, "-u", process.env.CODEYAM_GHCR_USER || "codeyam", "--password-stdin"],
1793
- { input: readToken, encoding: "utf8" },
1794
- );
1795
- // spawn error (docker missing) or a non-zero login → undetermined.
1796
- if (!login || login.error || login.status !== 0) return null;
2707
+ const httpGet = httpImpl || httpsManifestGet;
2708
+ // GHCR accepts a base64-encoded PAT as the registry bearer — no token-exchange
2709
+ // round-trip needed.
2710
+ const bearer = Buffer.from(readToken).toString("base64");
1797
2711
  const tags = fp.usableImageTags({ registry: reg, branch });
1798
2712
  let allClean = true;
1799
- for (const tag of tags) {
1800
- const res = spawn("docker", ["manifest", "inspect", tag], { encoding: "utf8" });
1801
- if (!res || res.error) {
1802
- allClean = false; // probe itself failed to run — can't claim "absent"
1803
- continue;
1804
- }
1805
- if (res.status === 0) return true; // a usable image exists
1806
- }
1807
- // Every tag inspected cleanly and none existed → definitively absent. If any
1808
- // probe failed to run, we can't be sure → undetermined.
2713
+ for (const fullRef of tags) {
2714
+ const verdict = await probeManifestRef(fullRef, bearer, httpGet);
2715
+ if (verdict === true) return true; // a usable image exists
2716
+ if (verdict === null) allClean = false; // this tag's probe was inconclusive
2717
+ // verdict === false → this tag is absent; keep checking the rest
2718
+ }
2719
+ // Every tag probed cleanly and none existed → definitively absent. If any probe
2720
+ // was inconclusive we can't claim absence → undetermined.
1809
2721
  return allClean ? false : null;
1810
2722
  }
1811
2723
 
@@ -1842,6 +2754,15 @@ function classifyGitRemoteError(stderr) {
1842
2754
  ) {
1843
2755
  return "network";
1844
2756
  }
2757
+ // A greenfield project (`--new-project` scaffold) has no origin remote and an
2758
+ // unborn `main`, so `git ls-remote origin` fails with "does not appear to be a
2759
+ // git repository". No token would fix this — there is simply nothing to push
2760
+ // yet — so it is neither `credential` nor `network` nor `git-spawn`. Keep the
2761
+ // match narrow: `repository not found` is a genuine access failure against a
2762
+ // real remote and must NOT be swallowed here.
2763
+ if (lower.includes("does not appear to be a git repository")) {
2764
+ return "no-remote";
2765
+ }
1845
2766
  return "other";
1846
2767
  }
1847
2768
 
@@ -1879,6 +2800,14 @@ function decideCredentialHeal({ stagingEmpty, lsRemoteOk, lsRemoteStderr }) {
1879
2800
  reason: "git binary failed to launch — not a credential gap, not re-seeding",
1880
2801
  };
1881
2802
  }
2803
+ if (category === "no-remote") {
2804
+ return {
2805
+ heal: false,
2806
+ category,
2807
+ reason:
2808
+ "no git remote configured — greenfield project, nothing to push yet (not a credential gap)",
2809
+ };
2810
+ }
1882
2811
  return {
1883
2812
  heal: true,
1884
2813
  category,
@@ -1896,6 +2825,16 @@ function decideCredentialHeal({ stagingEmpty, lsRemoteOk, lsRemoteStderr }) {
1896
2825
  };
1897
2826
  }
1898
2827
 
2828
+ /** The single GitHub credential line format shared by every seed path: the
2829
+ * host staging file, the durable on-disk `store` fallback, and the live
2830
+ * cache-daemon approve all expect `https://x-access-token:<token>@github.com`
2831
+ * (git's credential-URL form, matched by both the entrypoint parser and
2832
+ * git-credential-store). Centralized so the `x-access-token` shape has one
2833
+ * source of truth instead of being re-typed at each call site. */
2834
+ function githubCredentialLine(token) {
2835
+ return `https://x-access-token:${token}@github.com`;
2836
+ }
2837
+
1899
2838
  /** Write the laptop's GitHub token into ~/.codeyam-cloud-git-credentials on
1900
2839
  * the VM so the cloud compose can mount it into /root/.git-credentials —
1901
2840
  * without this, claude / codex / gemini inside the container can clone the
@@ -1921,21 +2860,28 @@ async function seedGithubCredentials(cfg, opts = {}) {
1921
2860
  console.error(
1922
2861
  `Writing GitHub token (from ${source}) into ~/.codeyam-cloud-git-credentials on the VM...`,
1923
2862
  );
1924
- const credLine = `https://x-access-token:${token}@github.com`;
2863
+ const credLine = githubCredentialLine(token);
1925
2864
  // Quote the token through one shell layer (gcloud ssh --command); the
1926
2865
  // value is base64'd to keep it out of the shell history.
1927
2866
  const b64 = Buffer.from(`${credLine}\n`).toString("base64");
1928
- // Verify-before-move: decode into a chmod-600 temp, assert it is non-empty
1929
- // (`[ -s ]`), and only THEN move it over the live staging file. An empty or
2867
+ // Verify-before-write: decode into a chmod-600 temp, assert it is non-empty
2868
+ // (`[ -s ]`), and only THEN copy it over the live staging file. An empty or
1930
2869
  // unreadable decode must never clobber an existing good file — the entrypoint
1931
2870
  // reads this file on every boot, and a silent empty write is exactly how a
1932
2871
  // reprovision lands a VM that "could not read Username for github.com". The
1933
- // trailing `echo OK` runs only on the move, so an empty write can't mask
2872
+ // trailing `echo OK` runs only on success, so an empty write can't mask
1934
2873
  // success with a `&& echo` (the failure shape seen on the Claude creds sinks).
2874
+ //
2875
+ // Use `cat "$t" > "$f"` (in-place truncate), NOT `mv`: the staging file is
2876
+ // bind-mounted read-only into the running container, and `mv` mints a NEW
2877
+ // inode that the live `:ro` mount does not follow — so a `mv`-based re-seed
2878
+ // never reached the running container until a full recreate. Truncating the
2879
+ // existing file in place keeps its inode, so the durable write is visible to
2880
+ // the container immediately. Then remove the temp.
1935
2881
  const remoteCmd =
1936
2882
  `f=$HOME/.codeyam-cloud-git-credentials && t="$f.tmp.$$" && ` +
1937
2883
  `echo ${b64} | base64 -d > "$t" && chmod 600 "$t" && ` +
1938
- `if [ -s "$t" ]; then mv "$t" "$f" && echo OK; ` +
2884
+ `if [ -s "$t" ]; then cat "$t" > "$f" && chmod 600 "$f" && rm -f "$t" && echo OK; ` +
1939
2885
  `else rm -f "$t"; echo EMPTY-WRITE-REFUSED >&2; exit 1; fi`;
1940
2886
  const result = runGcloud(
1941
2887
  buildGcloudArgs("ssh-probe", cfg, { command: remoteCmd }),
@@ -1946,26 +2892,76 @@ async function seedGithubCredentials(cfg, opts = {}) {
1946
2892
  }
1947
2893
  }
1948
2894
 
2895
+ /** Sentinel the remote read prints when it cannot find an `editor.json` under
2896
+ * any `~/projects/*` directory. Distinguishes "this VM has no scaffolded
2897
+ * project" (a real miss worth warning about) from "the project is scaffolded
2898
+ * but declares no port" (legitimately a `VITE_PORT` default). Without the
2899
+ * distinction both collapse to `{}` and the miss is silent. */
2900
+ const VM_APP_PORT_NO_CONFIG = "<<<NOCONFIG>>>";
2901
+
2902
+ /** Build the remote shell command that locates the project's `.codeyam` dir and
2903
+ * cats its two config files in one round-trip.
2904
+ *
2905
+ * Resolution is glob-based rather than `~/projects/<repoName>` alone: the host
2906
+ * directory is not guaranteed to be named after the repo (a renamed repo, a
2907
+ * manually-cloned dir, a fleet slug), and when the guess missed, the old code
2908
+ * silently returned `VITE_PORT` and forwarded the wrong port. The repo-named
2909
+ * path is still tried FIRST so a multi-project VM resolves deterministically;
2910
+ * the glob is the fallback. When nothing matches, print the sentinel so the
2911
+ * caller can warn instead of guessing. Pure string builder; no I/O. */
2912
+ function buildVmAppPortReadCommand(repoName) {
2913
+ return (
2914
+ `d=""; ` +
2915
+ `for c in ~/projects/${repoName}/.codeyam ~/projects/*/.codeyam; do ` +
2916
+ `if [ -f "$c/editor.json" ]; then d="$c"; break; fi; done; ` +
2917
+ `if [ -z "$d" ]; then echo '${VM_APP_PORT_NO_CONFIG}'; else ` +
2918
+ `cat "$d/editor.json" 2>/dev/null || echo '{}'; ` +
2919
+ `echo '<<<LOCAL>>>'; ` +
2920
+ `cat "$d/editor.local.json" 2>/dev/null || echo '{}'; fi`
2921
+ );
2922
+ }
2923
+
1949
2924
  /** Best-effort read of the VM's resolved app dev-server port so cloud:up's
1950
2925
  * laptop `-L` forward, readiness probe, and previewOrigin seed all target the
1951
2926
  * port the app actually serves on instead of a hardcoded 5173. Cats the VM's
1952
2927
  * editor.json and editor.local.json in one SSH round-trip and resolves via
1953
- * `resolveConfiguredAppPort`. Any failure (SSH error, missing/corrupt JSON)
1954
- * falls back to `VITE_PORT` — the same default `resolved_port()` lands on for
1955
- * a portless config, so a 5173/greenfield project sees no behavior change. */
2928
+ * `resolveConfiguredAppPort`.
2929
+ *
2930
+ * Falls back to `VITE_PORT` on any failure — but fails LOUD, not silent. A
2931
+ * wrong port here is not a cosmetic default: it forwards the wrong `-L` port,
2932
+ * and if the preview ends up on a dedicated origin the viewer gets
2933
+ * "localhost refused to connect" with nothing pointing at the cause. So an SSH
2934
+ * failure or a VM with no scaffolded project warns on stderr naming that
2935
+ * symptom. A scaffolded project that simply declares no port is NOT a miss —
2936
+ * `VITE_PORT` is genuinely correct there (it is what `resolved_port()` lands
2937
+ * on) and stays quiet. */
1956
2938
  async function readVmAppPort(cfg) {
1957
2939
  const repoName = resolveProject(cfg).name;
1958
- const base = `~/projects/${repoName}/.codeyam`;
1959
2940
  const read = runGcloud(
1960
2941
  buildGcloudArgs("ssh-probe", cfg, {
1961
- command:
1962
- `cat ${base}/editor.json 2>/dev/null || echo '{}'; ` +
1963
- `echo '<<<LOCAL>>>'; ` +
1964
- `cat ${base}/editor.local.json 2>/dev/null || echo '{}'`,
2942
+ command: buildVmAppPortReadCommand(repoName),
1965
2943
  }),
1966
2944
  { stdio: ["ignore", "pipe", "ignore"] },
1967
2945
  );
1968
- if (read.status !== 0 || typeof read.stdout !== "string") return VITE_PORT;
2946
+ if (read.status !== 0 || typeof read.stdout !== "string") {
2947
+ console.error(
2948
+ `[cloud] WARNING: could not read the VM's app port over SSH — ` +
2949
+ `falling back to ${VITE_PORT}. If the app does not serve on ` +
2950
+ `${VITE_PORT}, the laptop port-forward targets the wrong port and the ` +
2951
+ `Live Preview will show "localhost refused to connect".`,
2952
+ );
2953
+ return VITE_PORT;
2954
+ }
2955
+ if (read.stdout.includes(VM_APP_PORT_NO_CONFIG)) {
2956
+ console.error(
2957
+ `[cloud] WARNING: no .codeyam/editor.json found under ~/projects on the ` +
2958
+ `VM (looked for '${repoName}', then any project dir) — falling back to ` +
2959
+ `${VITE_PORT}. If the project is scaffolded under a different name and ` +
2960
+ `serves on another port, the port-forward targets the wrong port and ` +
2961
+ `the Live Preview will show "localhost refused to connect".`,
2962
+ );
2963
+ return VITE_PORT;
2964
+ }
1969
2965
  const parse = (s) => {
1970
2966
  try {
1971
2967
  const v = JSON.parse(s);
@@ -2025,8 +3021,30 @@ function buildEditorLocalSeedWriteCommand({ repoName, remotePath, b64 }) {
2025
3021
  * `_managedPreviewOrigin` sentinel). We stamp the sentinel here too so the
2026
3022
  * monitor doesn't mistake the cloud:up seed for a user pin. The
2027
3023
  * skip-on-already-set guard stays: a non-empty previewOrigin (whether a user
2028
- * pin or a monitor write) is left untouched on every `cloud:up`. */
2029
- async function seedPreviewOrigin(cfg, appPort = VITE_PORT) {
3024
+ * pin or a monitor write) is left untouched on every `cloud:up`.
3025
+ *
3026
+ * `effectiveSameOriginSafe` is the RUNNING editor's own verdict
3027
+ * (`/api/config`'s `previewSameOriginSafe`), supplied by a caller that has
3028
+ * already fetched it. When it is a boolean it WINS over the static
3029
+ * `stack.json` read; `null`/absent leaves the static read in charge.
3030
+ *
3031
+ * That parameter exists because this function had two sources of truth for one
3032
+ * flag, and they disagreed exactly where the adaptive default lives. A
3033
+ * subpath hydration failure escalates a project off `/__codeyam_preview` at
3034
+ * RUNTIME even when `stack.json` never declared `sameOriginSafe: false` — which
3035
+ * is the documented Next.js scaffold shape (a static `false` broke every
3036
+ * SSH-forward VM, so the key is deliberately absent). `healPreviewOriginAtReady`
3037
+ * decided WHETHER to heal from that runtime verdict and was right, then called
3038
+ * this function, which recomputed WHAT to write from the static flag and wrote
3039
+ * the very same-origin sentinel that had just failed. The project then sat
3040
+ * permanently at `previewDedicatedOriginUnavailable: true` — the editor knowing
3041
+ * it must leave the subpath and having nowhere to go — beside a preview host
3042
+ * that was already provisioned, LB-routed, HEALTHY and unused. */
3043
+ async function seedPreviewOrigin(
3044
+ cfg,
3045
+ appPort = VITE_PORT,
3046
+ effectiveSameOriginSafe = null,
3047
+ ) {
2030
3048
  const repoName = resolveProject(cfg).name;
2031
3049
  const remotePath = `~/projects/${repoName}/.codeyam/editor.local.json`;
2032
3050
  const stackPath = `~/projects/${repoName}/.codeyam/stack.json`;
@@ -2062,6 +3080,12 @@ async function seedPreviewOrigin(cfg, appPort = VITE_PORT) {
2062
3080
  current = parseObj(localJson);
2063
3081
  sameOriginSafe = previewSameOriginSafeFromStack(parseObj(stackJson));
2064
3082
  }
3083
+ // The running editor's verdict overrides the static file — see
3084
+ // `resolveEffectiveSameOriginSafe` for why only a boolean counts.
3085
+ sameOriginSafe = resolveEffectiveSameOriginSafe(
3086
+ sameOriginSafe,
3087
+ effectiveSameOriginSafe,
3088
+ );
2065
3089
 
2066
3090
  // Resolve this VM's custom slug (if any) so a dedicated-origin seed uses the
2067
3091
  // slug host. The slug rides on cfg at Add time (the --vm-slug flag, validated
@@ -2095,6 +3119,12 @@ async function seedPreviewOrigin(cfg, appPort = VITE_PORT) {
2095
3119
  // `sameOriginSafe: true`, and seeded `/__codeyam_preview` — which a
2096
3120
  // remote browser then loads as `127.0.0.1 refused to connect`). Once
2097
3121
  // stack.json exists, heal it forward to the dedicated origin.
3122
+ // `sameOriginSafe` here is the EFFECTIVE verdict, so this exception also
3123
+ // covers the case stack.json can never report: a project whose static
3124
+ // flag is legitimately absent (the Next.js scaffold default) that
3125
+ // escalated off the subpath at runtime after a hydration failure. The
3126
+ // caller passes the editor's own answer; without it this predicate read
3127
+ // `true` and declined to heal the one shape it was needed for.
2098
3128
  // Because every dashboard action (Reset / Update / Add / bootstrap-recovery)
2099
3129
  // re-runs this seed over cloud:up, either heal reaches every touch-point the
2100
3130
  // moment stack.json is present — closing the race without re-ordering
@@ -2190,11 +3220,14 @@ async function healPreviewOriginAtReady(cfg, appPort = VITE_PORT) {
2190
3220
  `READY auto-heal: ${cfg.instanceName} reports a not-same-origin-safe stack ` +
2191
3221
  `but a wrong-mode previewOrigin (${config.previewOrigin}); re-seeding...`,
2192
3222
  );
2193
- // Re-run the seed: stack.json is now readable, so the wrong-mode heal writes
2194
- // the dedicated origin into editor.local.json (a published `<N>-preview`
2195
- // tunnel URL, else the localhost bootstrap for the window before the monitor's
2196
- // first tick).
2197
- await seedPreviewOrigin(cfg, appPort);
3223
+ // Re-run the seed with the verdict we just read, so WHETHER to heal and WHAT
3224
+ // to write come from the same source. Passing it is what makes this heal reach
3225
+ // the adaptive-default stacks it exists for: on a Next.js project whose
3226
+ // `stack.json` omits `sameOriginSafe` (the scaffolded shape), the static read
3227
+ // inside the seed answers `true` and re-writes the same-origin sentinel that
3228
+ // just failed to hydrate. We got here precisely BECAUSE the editor said
3229
+ // `false`, so `false` is the answer the seed must use.
3230
+ await seedPreviewOrigin(cfg, appPort, false);
2198
3231
  // Tell the running server to re-read editor.local.json — no restart (the
2199
3232
  // footgun that killed VM7's live Claude session).
2200
3233
  const reload = runGcloud(
@@ -2289,6 +3322,66 @@ async function seedAgentApiKey(cfg) {
2289
3322
  // vm--no-cli-install-before-container-started removed; do not re-add it.
2290
3323
  }
2291
3324
 
3325
+ /** Pure: deep-merge `patch` over the VM's current editor.local.json content and
3326
+ * return the base64 of the pretty-printed result, ready for
3327
+ * buildEditorLocalSeedWriteCommand. `currentRaw` is the raw `cat` output of the
3328
+ * remote file (may be undefined, empty, or corrupt) — anything that doesn't
3329
+ * parse to a plain object is treated as `{}`, because overwriting a corrupt
3330
+ * override file with a known-good one is safer than refusing to seed. Extracted
3331
+ * so seedGreenfieldProjectTitle stays a thin I/O passthrough and the
3332
+ * parse+merge+encode is unit-tested without a live VM. */
3333
+ function mergeEditorLocalPatchB64(currentRaw, patch) {
3334
+ let current = {};
3335
+ try {
3336
+ const parsed = JSON.parse(currentRaw);
3337
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
3338
+ current = parsed;
3339
+ }
3340
+ } catch {
3341
+ // Unparseable / missing remote content → start from {}.
3342
+ }
3343
+ const merged = deepMergeJson(current, patch);
3344
+ return Buffer.from(JSON.stringify(merged, null, 2), "utf8").toString("base64");
3345
+ }
3346
+
3347
+ /** Seed a GREENFIELD project's `projectTitle` into the VM's editor.local.json
3348
+ * BEFORE compose up, so the editor caches the real project name at startup and
3349
+ * the fleet dashboard renders the correct card label with no false
3350
+ * project-dir-drift. Like seedAgentApiKey, this MUST run before
3351
+ * ensureEditorContainerUp — the editor reads its config once at startup.
3352
+ *
3353
+ * No-op for a clone (buildGreenfieldTitlePatch returns null): a repo Add labels
3354
+ * from its origin basename, so there is nothing to seed and no SSH round-trip
3355
+ * is spent. Runs on every cloud:up, so a reconfigure re-seeds the title,
3356
+ * converging a VM provisioned before this fix onto the correct identity without
3357
+ * a destroy. Thin I/O passthrough: the parse+merge+encode lives in the pure
3358
+ * mergeEditorLocalPatchB64 helper. */
3359
+ async function seedGreenfieldProjectTitle(cfg) {
3360
+ const patch = buildGreenfieldTitlePatch(cfg);
3361
+ if (!patch) return; // clone (or no greenfield name) — nothing to seed
3362
+
3363
+ const repoName = resolveProject(cfg).name;
3364
+ const remotePath = `~/projects/${repoName}/.codeyam/editor.local.json`;
3365
+ console.error(`Seeding projectTitle='${patch.projectTitle}' into ${remotePath}...`);
3366
+
3367
+ const read = runGcloud(
3368
+ buildGcloudArgs("ssh-probe", cfg, {
3369
+ command: `cat ${remotePath} 2>/dev/null || echo '{}'`,
3370
+ }),
3371
+ { stdio: ["ignore", "pipe", "ignore"] },
3372
+ );
3373
+ const b64 = mergeEditorLocalPatchB64(read.stdout, patch);
3374
+ const write = runGcloud(
3375
+ buildGcloudArgs("ssh-probe", cfg, {
3376
+ command: buildEditorLocalSeedWriteCommand({ repoName, remotePath, b64 }),
3377
+ }),
3378
+ { stdio: ["ignore", "inherit", "inherit"] },
3379
+ );
3380
+ if (write.status !== 0) {
3381
+ throw new Error(`Failed to write ${remotePath} on VM`);
3382
+ }
3383
+ }
3384
+
2292
3385
  /** Tri-state probe of the editor container's running state on the VM host.
2293
3386
  * One ssh round-trip; returns `"running"`, `"not-running"`, or `"unknown"`.
2294
3387
  *
@@ -2532,7 +3625,16 @@ function promptForInstanceName(expected) {
2532
3625
  });
2533
3626
  }
2534
3627
 
2535
- const STREAMED_SCRIPTS = ["scripts/gcp-bootstrap.sh", "scripts/gcp-project-bootstrap.sh"];
3628
+ // Every file streamed to a VM, and therefore every file the drift guard must
3629
+ // compare against the reviewed remote tip. `scripts/lib/npm-pin.sh` is here
3630
+ // because gcp-project-bootstrap.sh SOURCES it: a library that reaches the VM is
3631
+ // as much streamed content as the script that sources it, and leaving it out
3632
+ // meant the drift guard silently vouched for only half of what was shipped.
3633
+ const STREAMED_SCRIPTS = [
3634
+ "scripts/gcp-bootstrap.sh",
3635
+ "scripts/gcp-project-bootstrap.sh",
3636
+ "scripts/lib/npm-pin.sh",
3637
+ ];
2536
3638
 
2537
3639
  /** The configured editor branch to compare/stream streamed scripts against.
2538
3640
  * Resolved from config (`resolveEditorConfig` → `editorBranch`, itself derived
@@ -2551,6 +3653,42 @@ function streamedScriptMergeBase(editorBranch) {
2551
3653
  return mbResult.status === 0 ? mbResult.stdout.trim() : null;
2552
3654
  }
2553
3655
 
3656
+ /** Fetch `editorBranch` from origin into a REAL remote-tracking ref
3657
+ * (`refs/remotes/origin/<branch>`) rather than only into `FETCH_HEAD`.
3658
+ *
3659
+ * Operator hosts are commonly shallow, single-branch clones that track only
3660
+ * `+refs/heads/main`, so `origin/<some-feature-branch>` is not a local ref and
3661
+ * every `git show origin/<branch>:<path>` against it fails. Fetching through an
3662
+ * explicit refspec creates the ref, which keeps the drift verdict and the bytes
3663
+ * actually streamed derived from the same object. Falls back to a plain fetch
3664
+ * (FETCH_HEAD only) when the refspec form is rejected — `readRemoteScriptBlob`
3665
+ * can still read through FETCH_HEAD in that case. */
3666
+ function fetchStreamedScriptRef(editorBranch) {
3667
+ const refspec = `${editorBranch}:refs/remotes/origin/${editorBranch}`;
3668
+ const withRef = spawnSync("git", ["fetch", "--force", "origin", refspec], { encoding: "utf8" });
3669
+ if (withRef.status === 0) return { ok: true, stderr: "" };
3670
+
3671
+ const plain = spawnSync("git", ["fetch", "origin", editorBranch], { encoding: "utf8" });
3672
+ if (plain.status === 0) return { ok: true, stderr: "" };
3673
+ return { ok: false, stderr: (plain.stderr || withRef.stderr || "").trim() };
3674
+ }
3675
+
3676
+ /** Resolve one revision of a streamed script from the fetched remote, trying the
3677
+ * remote-tracking ref first and `FETCH_HEAD` second. `gitArg` is the git verb
3678
+ * (`rev-parse` for the blob hash, `show` for the bytes) so the drift facts and the
3679
+ * streamed bytes resolve through the SAME ref-preference order — a verdict of
3680
+ * "stream remote" can therefore never disagree with what actually got streamed.
3681
+ * Returns `{ ok: false }` only when the blob is unreadable through both refs. */
3682
+ function resolveRemoteScriptRev(gitArg, relPath, editorBranch) {
3683
+ for (const ref of [`origin/${editorBranch}`, "FETCH_HEAD"]) {
3684
+ const result = spawnSync("git", [gitArg, `${ref}:${relPath}`], { encoding: "utf8" });
3685
+ if (result.status === 0 && typeof result.stdout === "string") {
3686
+ return { ok: true, stdout: result.stdout, ref };
3687
+ }
3688
+ }
3689
+ return { ok: false, stdout: "", ref: null };
3690
+ }
3691
+
2554
3692
  /** Gather the drift facts for one streamed script relative to `origin/<editorBranch>`:
2555
3693
  * its local (working-tree) blob hash, the remote-tip blob hash, the merge-base blob
2556
3694
  * hash, and whether the working tree is dirty. Any git failure yields a null hash,
@@ -2562,11 +3700,8 @@ function gatherScriptDriftFacts(relPath, editorBranch, mergeBase) {
2562
3700
  const localHashResult = spawnSync("git", ["hash-object", relPath], { encoding: "utf8" });
2563
3701
  const localHash = localHashResult.status === 0 ? localHashResult.stdout.trim() : null;
2564
3702
 
2565
- let remoteHash = null;
2566
- const remoteHashResult = spawnSync("git", ["rev-parse", `origin/${editorBranch}:${relPath}`], { encoding: "utf8" });
2567
- if (remoteHashResult.status === 0) {
2568
- remoteHash = remoteHashResult.stdout.trim();
2569
- }
3703
+ const remoteRev = resolveRemoteScriptRev("rev-parse", relPath, editorBranch);
3704
+ const remoteHash = remoteRev.ok ? remoteRev.stdout.trim() : null;
2570
3705
 
2571
3706
  let baseHash = null;
2572
3707
  if (mergeBase) {
@@ -2589,7 +3724,15 @@ function gatherScriptDriftFacts(relPath, editorBranch, mergeBase) {
2589
3724
  * un-pulled dashboard can't add VMs" failure. Streams the on-disk copy instead
2590
3725
  * when the operator authored local content the remote tip lacks (dirty edit or a
2591
3726
  * committed local-ahead change — developer mode) or when the remote is unreachable
2592
- * (offline fallback). `absScriptPath` is an absolute path under the repo root. */
3727
+ * (offline fallback — `remoteHash === null`, the only sanctioned on-disk path).
3728
+ *
3729
+ * A "remote" verdict NEVER falls back to the on-disk copy. On a clean-but-behind
3730
+ * checkout the on-disk bytes are precisely the stale bytes the drift guard exists
3731
+ * to keep off the VM, so substituting them silently defeats the guard: the verdict
3732
+ * said "stream the reviewed remote tip" and the VM would instead receive the old
3733
+ * script, with only a `[Warning]` to show for it. When the remote blob cannot be
3734
+ * read through either ref this throws, aborting the add.
3735
+ * `absScriptPath` is an absolute path under the repo root. */
2593
3736
  function readStreamedScript(absScriptPath, cfg = {}) {
2594
3737
  const relPath = path.relative(rootDir, absScriptPath) || absScriptPath;
2595
3738
  const editorBranch = streamedScriptEditorBranch(cfg);
@@ -2598,15 +3741,18 @@ function readStreamedScript(absScriptPath, cfg = {}) {
2598
3741
 
2599
3742
  const { streamedScriptSource } = require("./script-drift");
2600
3743
  if (streamedScriptSource(facts) === "remote") {
2601
- const remote = spawnSync("git", ["show", `origin/${editorBranch}:${relPath}`], { encoding: "utf8" });
2602
- if (remote.status === 0 && typeof remote.stdout === "string") {
2603
- console.error(` streaming canonical ${relPath} from origin/${editorBranch} (checkout behind remote is fine)`);
3744
+ const remote = resolveRemoteScriptRev("show", relPath, editorBranch);
3745
+ if (remote.ok) {
3746
+ console.error(` streaming canonical ${relPath} from ${remote.ref} (checkout behind remote is fine)`);
2604
3747
  return remote.stdout;
2605
3748
  }
2606
- // Remote read failed unexpectedly (raced fetch, ref pruned): fall through to disk.
2607
- console.error(
2608
- ` [Warning] Could not read ${relPath} from origin/${editorBranch} ` +
2609
- `(${(remote.stderr || "").trim() || "unavailable"}). Falling back to the on-disk copy.`,
3749
+ // The facts said "the remote tip is the canonical source" but its bytes are
3750
+ // unreadable. Streaming the on-disk copy here would provision unreviewed stale
3751
+ // bytes under the banner of a successful add — fail loud instead.
3752
+ throw new Error(
3753
+ `could not read ${relPath} from origin/${editorBranch} (or FETCH_HEAD); ` +
3754
+ `refusing to stream a possibly-stale on-disk copy. ` +
3755
+ `Fetch the branch first: git fetch origin ${editorBranch}:refs/remotes/origin/${editorBranch}`,
2610
3756
  );
2611
3757
  }
2612
3758
  return fs.readFileSync(absScriptPath, "utf8");
@@ -2628,10 +3774,11 @@ function checkScriptDrift(cfg) {
2628
3774
 
2629
3775
  console.error(`Checking streamed-script drift against origin/${editorBranch}...`);
2630
3776
 
2631
- // 1. git fetch origin <editorBranch>
2632
- const fetchResult = spawnSync("git", ["fetch", "origin", editorBranch], { encoding: "utf8" });
2633
- if (fetchResult.status !== 0) {
2634
- console.error(` [Warning] Failed to fetch origin ${editorBranch} (${(fetchResult.stderr || "").trim() || "unknown error"}). Skipping drift check.`);
3777
+ // 1. Fetch into refs/remotes/origin/<editorBranch> so the ref resolves even on a
3778
+ // single-branch clone that tracks only +refs/heads/main.
3779
+ const fetchResult = fetchStreamedScriptRef(editorBranch);
3780
+ if (!fetchResult.ok) {
3781
+ console.error(` [Warning] Failed to fetch origin ${editorBranch} (${fetchResult.stderr || "unknown error"}). Skipping drift check.`);
2635
3782
  return;
2636
3783
  }
2637
3784
 
@@ -2724,8 +3871,9 @@ function fleetInstancePrefix() {
2724
3871
  * scripts/gcp/vm-ingress.sh with the resolved coordinates. Returns the spawnSync
2725
3872
  * result so callers decide fatality — Add treats a non-zero as a loud warning
2726
3873
  * (the VM is provisioned; ingress can be re-wired), Destroy likewise warns so a
2727
- * teardown still removes the instance. */
2728
- function runVmIngress(cfg, action, vmNumber, domain, appPort, slug) {
3874
+ * teardown still removes the instance. `vmAccess` (up only) is the Add's intended
3875
+ * principal set, which the script's grant step uses in place of its sidecar read. */
3876
+ function runVmIngress(cfg, action, vmNumber, domain, appPort, slug, vmAccess) {
2729
3877
  const scriptPath = path.join(rootDir, "scripts", "gcp", "vm-ingress.sh");
2730
3878
  const inv = vmIngressInvocation({
2731
3879
  scriptPath,
@@ -2737,6 +3885,7 @@ function runVmIngress(cfg, action, vmNumber, domain, appPort, slug) {
2737
3885
  appPort,
2738
3886
  instancePrefix: fleetInstancePrefix(),
2739
3887
  slug,
3888
+ vmAccess,
2740
3889
  });
2741
3890
  return spawnSync(inv.command, inv.args, {
2742
3891
  stdio: "inherit",
@@ -2744,17 +3893,100 @@ function runVmIngress(cfg, action, vmNumber, domain, appPort, slug) {
2744
3893
  });
2745
3894
  }
2746
3895
 
3896
+ /** Grant-only pass: (re-)apply one VM's default IAP access grant by spawning
3897
+ * `scripts/gcp/vm-ingress.sh <N> grant-access` — the churn-free action that runs
3898
+ * `apply_default_iap_access` without touching any NEG/BES/host-rule resource.
3899
+ * Reconcile uses this for already-`wired` VMs its re-wire loop skips, so a healed
3900
+ * VM whose backends already exist still (re-)grants the automation SA the IAP
3901
+ * accessor. Returns the spawnSync result so the caller logs granted vs failed;
3902
+ * best-effort + loud, never fatal. */
3903
+ function runVmIngressGrantAccess(cfg, vmNumber, domain, slug) {
3904
+ const scriptPath = path.join(rootDir, "scripts", "gcp", "vm-ingress.sh");
3905
+ const inv = vmIngressGrantAccessInvocation({
3906
+ scriptPath,
3907
+ vmNumber,
3908
+ domain,
3909
+ project: cfg.project,
3910
+ zone: cfg.zone,
3911
+ slug,
3912
+ });
3913
+ return spawnSync(inv.command, inv.args, {
3914
+ stdio: "inherit",
3915
+ env: { ...process.env, ...inv.env },
3916
+ });
3917
+ }
3918
+
3919
+ /** THE principal set that must have IAP access to this VM after the Add: the
3920
+ * explicit `cfg.vmAccess` collaborators unioned with the resolved default
3921
+ * operator. Both add-time access paths consume this ONE function —
3922
+ * `wireVmIngressOnAdd` (which hands it to vm-ingress.sh's grant) and
3923
+ * `applyVmAccessOnAdd` (which grants it and subtracts it from the stale-revoke
3924
+ * set). They used to decide independently, and that is precisely how one path
3925
+ * granted `user:jared@codeyam.com` at 00:09:31 and the other revoked the same
3926
+ * principal 18 seconds later as a "stale prior tenant" (VMs 4/5/6, 2026-08-09):
3927
+ * the ingress path read the SIDECAR (still holding the prior tenant) while
3928
+ * `applyVmAccessOnAdd` resolved an empty operator. One source of truth removes
3929
+ * the whole class of disagreement. `env` is injectable for tests; the only I/O
3930
+ * is `resolveDefaultOperator`'s config/gcloud read. */
3931
+ function intendedVmPrincipals(cfg = {}, env = process.env) {
3932
+ return withDefaultOperator(
3933
+ normalizeAccessList(cfg.vmAccess || []),
3934
+ resolveDefaultOperator({ env }),
3935
+ );
3936
+ }
3937
+
3938
+ /** Add preflight: throw — BEFORE any GCE instance exists — when this Add would
3939
+ * come up on an IAP-gated public URL that authorizes NOBODY. The whole condition
3940
+ * is env + config (`intendedVmPrincipals` needs no GCP state), which is why it
3941
+ * belongs beside cmdUp's other cheap boundary validations rather than after a
3942
+ * machine has been provisioned: checking later means a half-provisioned VM to
3943
+ * clean up. On 2026-08-09 the un-refused version of this Add reported `done` for
3944
+ * VMs 4/5/6, left three unreachable URLs, and revoked each slot's prior tenant on
3945
+ * the way.
3946
+ *
3947
+ * Only fires in LB mode on a numbered fleet VM with nothing to grant; an explicit
3948
+ * `--vm-access` satisfies it with no default operator configured, so the
3949
+ * collaborator flow is unaffected, as is every legacy quick-tunnel Add. The
3950
+ * refusal text (and its `Next valid action:` remedy naming all three config
3951
+ * tiers) is the pure `unauthorizableAddRefusal`; this function is the composition
3952
+ * and the throw. */
3953
+ function assertAddCanAuthorizeSomeone(cfg, env = process.env) {
3954
+ let plan;
3955
+ try {
3956
+ plan = ingressWiringPlan(cfg, env);
3957
+ } catch {
3958
+ // A malformed domain is `resolveIngressDomain`'s error to raise on the wiring
3959
+ // path; it must not masquerade here as an authorization refusal.
3960
+ plan = { wire: false };
3961
+ }
3962
+ const refusal = unauthorizableAddRefusal({
3963
+ lbMode: !!plan.wire,
3964
+ vmNumber: plan.wire ? plan.vmNumber : null,
3965
+ intendedCount: plan.wire ? intendedVmPrincipals(cfg, env).length : null,
3966
+ });
3967
+ if (refusal) throw new Error(refusal);
3968
+ }
3969
+
2747
3970
  /** Add-time hook: wire VM-N onto the shared LB when a fleet domain is set.
2748
3971
  * Best-effort + loud — a wiring hiccup must never abort an otherwise-green Add
2749
3972
  * (the VM is reachable operator-side over SSH regardless), so on failure it
2750
3973
  * prints the exact re-run command rather than throwing. No-op (and silent) in
2751
- * legacy quick-tunnel mode or for a non-fleet client project. */
3974
+ * legacy quick-tunnel mode or for a non-fleet client project.
3975
+ *
3976
+ * RETURNS the principals this call granted (`intendedVmPrincipals`), or [] when
3977
+ * it did not wire — the explicit dataflow `applyVmAccessOnAdd` needs to know what
3978
+ * the Add has already granted before it computes a stale-revoke. Returned on the
3979
+ * FAILURE path too: a non-zero `vm-ingress.sh up` may still have completed its
3980
+ * grant step, and a principal that was possibly granted must never be revoked. */
2752
3981
  function wireVmIngressOnAdd(cfg, appPort, env = process.env) {
2753
3982
  const plan = ingressWiringPlan(cfg, env);
2754
- if (!plan.wire) return;
3983
+ if (!plan.wire) return [];
2755
3984
  const label = plan.slug || `vm-${plan.vmNumber}`;
3985
+ // Hand the intended set to the script so its `apply_default_iap_access` grants
3986
+ // THIS Add's principals instead of reading the sidecar's prior tenant.
3987
+ const vmAccess = intendedVmPrincipals(cfg, env);
2756
3988
  console.error(` wiring LB ingress for VM-${plan.vmNumber} on ${plan.domain}...`);
2757
- const res = runVmIngress(cfg, "up", plan.vmNumber, plan.domain, appPort, plan.slug);
3989
+ const res = runVmIngress(cfg, "up", plan.vmNumber, plan.domain, appPort, plan.slug, vmAccess);
2758
3990
  if (res.status === 0) {
2759
3991
  console.error(` ✓ LB ingress wired: https://${label}.editor.${plan.domain}`);
2760
3992
  } else {
@@ -2776,6 +4008,7 @@ function wireVmIngressOnAdd(cfg, appPort, env = process.env) {
2776
4008
  `(vm-ingress.sh up exited ${res.status == null ? "abnormally" : res.status}). Re-wire: ${rewire}`,
2777
4009
  );
2778
4010
  }
4011
+ return vmAccess;
2779
4012
  }
2780
4013
 
2781
4014
  /** Destroy-time hook: unwire VM-N's LB backends before the instance is deleted,
@@ -2844,8 +4077,15 @@ function runIapAccess(cfg, vmNumber, action, principals) {
2844
4077
  * a revoke/grant hiccup (e.g. the SA missing IAP-admin) prints the exact re-run
2845
4078
  * command rather than aborting an otherwise-green Add. `cfg.vmAccess` is the
2846
4079
  * array (or comma-separated string) cmdUp validated; absent ⇒ an empty desired
2847
- * list (the clean-slate case). */
2848
- function applyVmAccessOnAdd(cfg, env = process.env) {
4080
+ * list (the clean-slate case).
4081
+ *
4082
+ * `grantedThisRun` is what an EARLIER step of this same Add already granted —
4083
+ * `wireVmIngressOnAdd`'s return value. It is subtracted from the stale-revoke
4084
+ * set, so a principal this Add just authorized can never be revoked moments later
4085
+ * as a prior tenant. That is a second, cheaper guard than the shared
4086
+ * `intendedVmPrincipals` resolver above: it holds even if the two paths drift
4087
+ * apart again, which is exactly how VMs 4/5/6 broke on 2026-08-09. */
4088
+ function applyVmAccessOnAdd(cfg, env = process.env, { grantedThisRun = [] } = {}) {
2849
4089
  const desired = normalizeAccessList(cfg.vmAccess || []);
2850
4090
  let plan;
2851
4091
  try {
@@ -2862,11 +4102,15 @@ function applyVmAccessOnAdd(cfg, env = process.env) {
2862
4102
  // never inaccessible-by-default (the Error-51 footgun). The default operator is
2863
4103
  // NOT persisted to the sidecar (it's a standing grant, not a per-VM
2864
4104
  // collaborator), so `desired` alone drives the sidecar + stale-revoke below.
2865
- const toGrant = withDefaultOperator(desired, resolveDefaultOperator({ env }));
4105
+ const toGrant = intendedVmPrincipals(cfg, env);
2866
4106
  const stale = accessFor(vmNumber);
2867
4107
  // Never revoke a principal we're about to (re-)grant — a prior tenant who was
2868
- // also the default operator must not be revoked-then-regranted for nothing.
2869
- const staleOnly = stale.filter((p) => !toGrant.includes(p));
4108
+ // also the default operator must not be revoked-then-regranted for nothing —
4109
+ // NOR one an earlier step of this same Add already granted. `toGrant` alone
4110
+ // protected nothing when it was empty: the ingress step had granted the operator
4111
+ // seconds earlier and this revoke took it straight back off (VMs 4/5/6).
4112
+ const grantedAlready = new Set([...toGrant, ...normalizeAccessList(grantedThisRun || [])]);
4113
+ const staleOnly = stale.filter((p) => !grantedAlready.has(p));
2870
4114
 
2871
4115
  if (plan.wire) {
2872
4116
  if (staleOnly.length > 0) {
@@ -2983,12 +4227,23 @@ async function convergeVmIngressOnAdd(cfg, appPort, env = process.env, deps = {}
2983
4227
  }
2984
4228
  if (!plan.wire) {
2985
4229
  // Nothing to converge — the no-op wire keeps the clean-slate invariant.
2986
- wireVmIngressOnAdd(cfg, appPort, env);
2987
- return { wired: true, reason: "no-wire" };
2988
- }
2989
-
4230
+ const granted = wireVmIngressOnAdd(cfg, appPort, env);
4231
+ return { wired: true, reason: "no-wire", grantedThisRun: granted };
4232
+ }
4233
+
4234
+ // The intended set, resolved ONCE and handed to every `up` attempt so each
4235
+ // converge iteration grants the same principals — and reported back to the
4236
+ // caller as `grantedThisRun` so the access reconcile that follows cannot revoke
4237
+ // them. Every `up` runs the script's grant step, so these are granted whether
4238
+ // the loop converges or hits its deadline. Injectable via `deps` like the rest
4239
+ // of this loop's slow I/O: the resolve spawns `gcloud config get-value account`
4240
+ // on its last tier, and a unit test must never depend on the gcloud identity
4241
+ // that happens to be active on the machine running it.
4242
+ const grantedThisRun =
4243
+ deps.grantedThisRun != null ? deps.grantedThisRun : intendedVmPrincipals(cfg, env);
2990
4244
  const runUp =
2991
- deps.runUp || ((p) => runVmIngress(cfg, "up", p.vmNumber, p.domain, appPort, p.slug));
4245
+ deps.runUp
4246
+ || ((p) => runVmIngress(cfg, "up", p.vmNumber, p.domain, appPort, p.slug, grantedThisRun));
2992
4247
  const probeVerdict = deps.probeVerdict || ((p) => probeVmIngressVerdict(cfg, p));
2993
4248
  const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
2994
4249
  const now = deps.now || (() => Date.now());
@@ -3031,7 +4286,7 @@ async function convergeVmIngressOnAdd(cfg, appPort, env = process.env, deps = {}
3031
4286
  if (decision.done) {
3032
4287
  if (decision.wired) {
3033
4288
  console.error(` ✓ LB ingress wired: https://${label}.editor.${plan.domain}`);
3034
- return { wired: true, reason: "wired", attempts: attempt + 1 };
4289
+ return { wired: true, reason: "wired", attempts: attempt + 1, grantedThisRun };
3035
4290
  }
3036
4291
  const rewire =
3037
4292
  `FLEET_DOMAIN=${plan.domain}${plan.slug ? ` VM_SLUG=${plan.slug}` : ""} ` +
@@ -3048,7 +4303,7 @@ async function convergeVmIngressOnAdd(cfg, appPort, env = process.env, deps = {}
3048
4303
  `CY_DEGRADED ingress-wiring-failed: VM-${plan.vmNumber} public URL did not wire ` +
3049
4304
  `within the add window (last verdict=${verdict || "unknown"}). Re-wire: ${rewire}`,
3050
4305
  );
3051
- return { wired: false, reason: "deadline", attempts: attempt + 1 };
4306
+ return { wired: false, reason: "deadline", attempts: attempt + 1, grantedThisRun };
3052
4307
  }
3053
4308
  attempt += 1;
3054
4309
  await sleep(decision.delayMs);
@@ -3077,8 +4332,8 @@ function startDetachedAddWiring(cfg, appPort, env = process.env) {
3077
4332
  if (!plan.wire) {
3078
4333
  // Nothing slow to detach: wiring is a no-op and the access reconcile is a cheap
3079
4334
  // sidecar write. Run them inline so the clean-slate invariant still holds.
3080
- wireVmIngressOnAdd(cfg, appPort, env);
3081
- applyVmAccessOnAdd(cfg, env);
4335
+ const grantedThisRun = wireVmIngressOnAdd(cfg, appPort, env);
4336
+ applyVmAccessOnAdd(cfg, env, { grantedThisRun });
3082
4337
  return;
3083
4338
  }
3084
4339
  const marker = ingressInflightMarkerPath(INGRESS_INFLIGHT_DIR, plan.vmNumber);
@@ -3110,8 +4365,8 @@ function startDetachedAddWiring(cfg, appPort, env = process.env) {
3110
4365
  `running it inline instead.`,
3111
4366
  );
3112
4367
  try { fs.unlinkSync(marker); } catch { /* marker may not exist */ }
3113
- wireVmIngressOnAdd(cfg, appPort, env);
3114
- applyVmAccessOnAdd(cfg, env);
4368
+ const grantedThisRun = wireVmIngressOnAdd(cfg, appPort, env);
4369
+ applyVmAccessOnAdd(cfg, env, { grantedThisRun });
3115
4370
  }
3116
4371
  }
3117
4372
 
@@ -3143,8 +4398,11 @@ async function cmdWireAddTail() {
3143
4398
  // Converge the URL to `verdict=wired` (retry-until-wired), not a single-shot
3144
4399
  // `up` left to the slow reconcile sweep — then the IAP access grant, in the
3145
4400
  // SAME order cmdUp ran them inline.
3146
- await convergeVmIngressOnAdd(cfg, appPort);
3147
- applyVmAccessOnAdd(cfg);
4401
+ // Carry what the converge granted into the access reconcile, so the revoke
4402
+ // step cannot take back a principal this same Add just authorized — the exact
4403
+ // grant-then-revoke-18s-later sequence `/tmp/cy-wire-add-vm-4.log` recorded.
4404
+ const { grantedThisRun } = await convergeVmIngressOnAdd(cfg, appPort);
4405
+ applyVmAccessOnAdd(cfg, process.env, { grantedThisRun });
3148
4406
  } finally {
3149
4407
  if (marker) {
3150
4408
  try { fs.unlinkSync(marker); } catch { /* already gone — fine */ }
@@ -3206,6 +4464,75 @@ function releaseVmSlugOnDestroy(cfg) {
3206
4464
  return vmNumber;
3207
4465
  }
3208
4466
 
4467
+ /** Does `branch` still exist on `repo`? Answered with a single
4468
+ * `git ls-remote --heads` — about a second, and no cloud resource touched.
4469
+ *
4470
+ * Tri-state on purpose, and the third state is the load-bearing one:
4471
+ * true — the ref resolved.
4472
+ * false — the remote answered and the ref is NOT there. Provably gone.
4473
+ * null — we could not get an answer (no network, no credentials, git
4474
+ * missing, timeout). NOT evidence of a deleted branch.
4475
+ * Only `false` refuses an add. Collapsing `null` into `false` would turn every
4476
+ * transient GitHub blip into a fleet-wide add outage, which is a far worse
4477
+ * failure than the one this preflight exists to prevent — and the classifier
4478
+ * arm downstream still catches a genuinely dead ref, just later and dearer.
4479
+ *
4480
+ * A private repo needs credentials, so the token is inlined into the URL the
4481
+ * same way clone_editor_repo does it on the VM side (x-access-token), and for
4482
+ * the same reason: the plain URL 401s. The token is confined to this argv and
4483
+ * never logged — the caller prints `repo` (the un-inlined form) instead. */
4484
+ function gitBranchRefExists({ repo, branch }) {
4485
+ if (!repo || !branch) return null;
4486
+ let url = repo;
4487
+ const token = resolveGithubToken();
4488
+ if (token && /^https:\/\/github\.com\//.test(repo)) {
4489
+ url = repo.replace("https://", `https://x-access-token:${token}@`);
4490
+ }
4491
+ const res = spawnSync("git", ["ls-remote", "--heads", url, branch], {
4492
+ encoding: "utf8",
4493
+ timeout: 30000,
4494
+ });
4495
+ // A non-zero exit is an unreachable/unauthorized remote, not an absent branch:
4496
+ // git exits 0 and prints nothing for "connected fine, no such head".
4497
+ if (res.error || res.status !== 0) return null;
4498
+ return String(res.stdout || "").trim().length > 0;
4499
+ }
4500
+
4501
+ /** Refuse an add whose stored branch has been deleted from origin, BEFORE the
4502
+ * first gcloud call.
4503
+ *
4504
+ * Without this the failure lands as late and as expensively as it possibly can:
4505
+ * on 2026-08-25 four fleet VMs each created a real GCE instance, booted it,
4506
+ * installed npm and cloned 13,226 files before `git fetch` inside the VM said
4507
+ * `fatal: couldn't find remote ref editor-improvements-75` — a branch pruned
4508
+ * from origin hours earlier when it merged. One `git ls-remote` establishes the
4509
+ * same fact in about a second, for free. This repo prunes branches on merge, so
4510
+ * ANY stored feature-branch name expires silently; that makes this a recurring
4511
+ * condition, not a one-off.
4512
+ *
4513
+ * Placed beside checkScriptDrift and assertVariantProvisionable — the other
4514
+ * "fail loud before creating a GCE instance" guards — because it is only worth
4515
+ * anything ahead of ensureInstance. It cannot live in scripts/gcp-bootstrap.sh,
4516
+ * which already runs ON the provisioned box and never sees the client branch.
4517
+ *
4518
+ * Throws with the field, the branch and the repo named. Never throws for a ref
4519
+ * it could not check (see gitBranchRefExists). */
4520
+ function assertBranchRefsExist(cfg, { refExists = gitBranchRefExists } = {}) {
4521
+ // Lazy require: launch-config.js requires THIS module at load time, so a
4522
+ // top-level require here would close the cycle. Same pattern as the
4523
+ // isPlaceholderProject call sites above.
4524
+ const lc = require("./launch-config");
4525
+ const { editorRepo, editorBranch } = resolveEditorConfig(cfg);
4526
+ const targets = lc.branchRefTargets(
4527
+ { clientRepo: cfg.repo, clientBranch: cfg.branch, editorBranch },
4528
+ { editorRepo },
4529
+ );
4530
+ if (!targets.length) return;
4531
+ console.error("Checking that the requested branches still exist on origin...");
4532
+ const missing = lc.missingBranchRefs(targets, refExists);
4533
+ if (missing.length) throw new Error(lc.missingBranchRefMessage(missing));
4534
+ }
4535
+
3209
4536
  async function cmdUp(args, projectDir = rootDir) {
3210
4537
  ensureGcloud();
3211
4538
  const flags = parseFlags(args);
@@ -3256,8 +4583,14 @@ async function cmdUp(args, projectDir = rootDir) {
3256
4583
  }
3257
4584
  }
3258
4585
 
4586
+ assertAddCanAuthorizeSomeone(cfg);
4587
+
3259
4588
  checkScriptDrift(cfg);
3260
4589
 
4590
+ // Last of the pre-instance guards: a deleted branch ref is checkable in ~1s
4591
+ // and otherwise costs a full instance + boot + 13k-file clone to discover.
4592
+ assertBranchRefsExist(cfg);
4593
+
3261
4594
  await ensureFirewallRule(cfg);
3262
4595
  const { createdThisRun } = await ensureInstance(cfg);
3263
4596
 
@@ -3287,6 +4620,10 @@ async function cmdUp(args, projectDir = rootDir) {
3287
4620
  }
3288
4621
  }
3289
4622
  await seedAgentApiKey(cfg);
4623
+ // Greenfield only (no-op for a clone): seed projectTitle so the editor
4624
+ // resolves its identity to the real project name instead of the bare
4625
+ // /workspace mount basename — the source of the false project-dir-drift.
4626
+ await seedGreenfieldProjectTitle(cfg);
3290
4627
  await ensureEditorContainerUp(cfg);
3291
4628
  // Provision contract: a just-provisioned VM must actually reach GitHub.
3292
4629
  // Verify in-container git auth now that the container (and its credential
@@ -3358,7 +4695,27 @@ async function cmdUp(args, projectDir = rootDir) {
3358
4695
  );
3359
4696
  }
3360
4697
  } catch (err) {
3361
- if (createdThisRun) {
4698
+ // `createdThisRun` alone MUST NOT authorize deletion. Gather what state the
4699
+ // VM is in right now, then let the pure decision rule — see
4700
+ // abortTeardownDecision's doc comment for why each input is load-bearing.
4701
+ const state = probeAbortTeardownState(cfg, createdThisRun);
4702
+ const verdict = abortTeardownDecision({ createdThisRun, ...state });
4703
+ if (createdThisRun && verdict === "keep") {
4704
+ // Deliberately loud and specific. The old blanket "tearing down the VM
4705
+ // cloud:up created this run (no orphan left behind)" was actively
4706
+ // misleading here — it asserted no orphan while deleting a working VM.
4707
+ const why = state.probeInconclusive
4708
+ ? "its liveness could not be confirmed (probe failed), and an unconfirmed VM is never deleted"
4709
+ : state.containerUp
4710
+ ? "its editor container is RUNNING — another run brought it up"
4711
+ : "it is in the fleet roster and visible to the dashboard";
4712
+ console.error(
4713
+ `✗ provisioning aborted — the VM ${cfg.instanceName} was LEFT IN PLACE because ${why}.\n` +
4714
+ ` This run created the instance, but that alone does not authorize deleting a VM that is in service.\n` +
4715
+ ` If it really should go, remove it deliberately: npm run cloud:destroy`,
4716
+ );
4717
+ }
4718
+ if (verdict === "delete") {
3362
4719
  console.error(
3363
4720
  `✗ provisioning aborted — tearing down the VM cloud:up created this run (no orphan left behind)`,
3364
4721
  );
@@ -3540,14 +4897,7 @@ async function cmdStatus(args, projectDir = rootDir) {
3540
4897
  const imgStatus = String(imgProbe.stdout || "").trim() || "?";
3541
4898
  console.error(` image: ${imgStatus}`);
3542
4899
 
3543
- const repoName = resolveProject(cfg).name;
3544
- const containerProbe = runGcloud(
3545
- buildGcloudArgs("ssh-probe", cfg, {
3546
- command: `cd ~/projects/${repoName} 2>/dev/null && docker compose -f docker-compose.cloud.yml ps --format json 2>/dev/null || echo`,
3547
- }),
3548
- { stdio: ["ignore", "pipe", "ignore"] },
3549
- );
3550
- const containerStatus = parseEditorComposeState(containerProbe.stdout) || "missing";
4900
+ const containerStatus = probeEditorComposeState(cfg).state || "missing";
3551
4901
  console.error(` editor container: ${containerStatus}`);
3552
4902
 
3553
4903
  const appPort = await readVmAppPort(cfg);
@@ -3641,17 +4991,40 @@ async function cmdReconcileIngress(args, projectDir = rootDir) {
3641
4991
  zone: cfg.zone,
3642
4992
  slug,
3643
4993
  });
4994
+ // Bound the per-VM status probe: a hung `bash vm-ingress.sh <N> status`
4995
+ // (its gcloud describes stalling on an IAP/metadata hiccup) must not stall the
4996
+ // whole sweep. On timeout res.stdout is empty, so parseIngressStatusVerdict
4997
+ // returns null → an `unknown` verdict → selectIngressReconcileTargets SKIPS
4998
+ // this VM and the sweep continues to the next one.
3644
4999
  const res = spawnSync(inv.command, inv.args, {
3645
5000
  env: { ...process.env, ...inv.env },
3646
5001
  encoding: "utf8",
5002
+ timeout: GCLOUD_CALL_TIMEOUT_MS,
3647
5003
  });
3648
5004
  return { vmNumber: n, slug, verdict: parseIngressStatusVerdict(res.stdout || "") };
3649
5005
  });
3650
5006
  const targets = selectIngressReconcileTargets(statuses);
3651
5007
  const targetNums = new Set(targets.map((t) => t.vmNumber));
5008
+ // The complement of the re-wire loop: `wired` VMs whose backends already exist
5009
+ // so the re-wire loop skips them, yet still need the SA-accessor (re-)granted —
5010
+ // `up` is the only path that grants it, and it never runs for a wired VM. This
5011
+ // closes the VM-8 heal-path gap (a wired VM whose backends predate the SA-grant
5012
+ // fix would otherwise stay 403 forever). Disjoint from `targets` by construction.
5013
+ const grantOnlyNums = new Set(
5014
+ selectIngressGrantOnlyTargets(statuses).map((g) => g.vmNumber),
5015
+ );
3652
5016
  for (const s of statuses) {
3653
- if (!targetNums.has(s.vmNumber)) {
3654
- const label = s.slug || `vm-${s.vmNumber}`;
5017
+ if (targetNums.has(s.vmNumber)) continue;
5018
+ const label = s.slug || `vm-${s.vmNumber}`;
5019
+ if (grantOnlyNums.has(s.vmNumber)) {
5020
+ // Churn-free grant-only pass: (re-)grant the accessor without re-wiring any
5021
+ // NEG/BES/host-rule resource. Idempotent (a no-op when the SA is already
5022
+ // bound) and best-effort-but-loud — a grant hiccup logs, never aborts.
5023
+ const gres = runVmIngressGrantAccess(cfg, s.vmNumber, domain, s.slug);
5024
+ console.error(
5025
+ ` VM-${s.vmNumber} ${label}: wired → ok (accessor ${gres.status === 0 ? "granted" : "grant FAILED"})`,
5026
+ );
5027
+ } else {
3655
5028
  console.error(` VM-${s.vmNumber} ${label}: ${s.verdict || "unknown"} → ok`);
3656
5029
  }
3657
5030
  }
@@ -3681,7 +5054,13 @@ async function cmdReconcileIngress(args, projectDir = rootDir) {
3681
5054
  for (const surface of gi.SURFACES) {
3682
5055
  const bes = gi.backendServiceName(n, surface);
3683
5056
  const inv = backendServiceTimeoutInvocation({ bes, project: cfg.project });
3684
- const res = spawnSync(inv.command, inv.args, { encoding: "utf8" });
5057
+ // Bound the per-BES converge too: a hung `gcloud backend-services update`
5058
+ // returns a non-zero (timed-out) result, so it falls into the skip branch
5059
+ // below and the sweep moves on to the next BES rather than stalling.
5060
+ const res = spawnSync(inv.command, inv.args, {
5061
+ encoding: "utf8",
5062
+ timeout: GCLOUD_CALL_TIMEOUT_MS,
5063
+ });
3685
5064
  if (res.status === 0) {
3686
5065
  console.error(` ${bes}: timeout → 86400`);
3687
5066
  } else {
@@ -3691,6 +5070,12 @@ async function cmdReconcileIngress(args, projectDir = rootDir) {
3691
5070
  }
3692
5071
  }
3693
5072
 
5073
+ // Converge the shared fleet firewall, then surface any app port it still fails to
5074
+ // admit. Both ride this same boot + periodic cadence so the running fleet
5075
+ // self-heals without a hand-run bootstrap.
5076
+ const firewallState = convergeFleetFirewall({ cfg });
5077
+ await reportFirewallPortGaps({ cfg, roster, firewallState });
5078
+
3694
5079
  // Auto-clean orphaned LB ingress (vm--auto-clean-orphaned-lb-ingress): any
3695
5080
  // backend service whose VM number is gone from the roster is a destroyed VM's
3696
5081
  // leftover — cleaned here automatically with the verified `down`, so the
@@ -3720,6 +5105,106 @@ async function cmdReconcileIngress(args, projectDir = rootDir) {
3720
5105
  * summary (null when the backend-service enumeration itself failed) — the same
3721
5106
  * shape it prints — so the flow is directly assertable. `deps` is injectable so
3722
5107
  * the enumerate → select → down flow is testable without gcloud. */
5108
+ /** Converge the shared fleet firewall rule to all-tcp so the LB reaches whatever
5109
+ * port a project's app actually serves.
5110
+ *
5111
+ * A rule pinned to a hardcoded port list (`tcp:14199,tcp:5173,tcp:3000`) drops
5112
+ * LB→VM traffic for any VM serving outside it — the VM-6-on-8080 Live Preview
5113
+ * outage — while the preview backend service still reads HEALTHY, because its
5114
+ * health check runs on the always-admitted editor port. The failure is therefore
5115
+ * invisible until someone opens the preview. Converging here (not only in the
5116
+ * hand-run google-ingress.sh bootstrap) is what makes a drifted rule self-heal on
5117
+ * the running fleet.
5118
+ *
5119
+ * All-tcp is the right exposure, not a per-stack port list: the rule stays scoped
5120
+ * to Google's LB + health-check source ranges and the fleet instance tag either
5121
+ * way, so it admits any app port (Vite 5173, Next 3000, Astro 4321, Go 8080, …)
5122
+ * without enumeration. EVERY candidate name in FLEET_FIREWALL_RULE_NAMES is
5123
+ * converged: describing only one silently no-ops on a fleet wired under the other.
5124
+ *
5125
+ * Scope-safe by construction — `update --rules=tcp` rewrites only the allowed
5126
+ * protocols/ports, never a rule's source ranges or target tags, so this can never
5127
+ * change who the rule applies to. Best-effort throughout: a describe/update
5128
+ * failure logs and continues, never aborting the rest of the reconcile.
5129
+ *
5130
+ * Returns `[{ ruleName, rules, converged }]` for every rule that exists — `rules`
5131
+ * is the post-converge allowed value — so the flow is assertable without gcloud.
5132
+ * `deps.spawnSync` is injectable for the same reason.
5133
+ * See plan vm--self-healing-app-port-agnostic-fleet-lb-firewall. */
5134
+ function convergeFleetFirewall({ cfg } = {}, deps = {}) {
5135
+ const run = deps.spawnSync || spawnSync;
5136
+ const project = cfg && cfg.project;
5137
+ const state = [];
5138
+ for (const ruleName of FLEET_FIREWALL_RULE_NAMES) {
5139
+ const dinv = fleetFirewallDescribeInvocation({ ruleName, project });
5140
+ const dres = run(dinv.command, dinv.args, { encoding: "utf8" });
5141
+ // A non-zero describe means no rule under this name — expected, not an error:
5142
+ // only one of the candidate names is deployed on any given fleet.
5143
+ if (!dres || dres.status !== 0) continue;
5144
+ const current = ((dres.stdout || "") + "").trim();
5145
+ if (!firewallNeedsConverge(current)) {
5146
+ console.error(` firewall ${ruleName}: already all-tcp → ok`);
5147
+ state.push({ ruleName, rules: "tcp", converged: false });
5148
+ continue;
5149
+ }
5150
+ const cinv = fleetFirewallConvergeInvocation({ ruleName, project });
5151
+ const cres = run(cinv.command, cinv.args, { encoding: "utf8" });
5152
+ if (cres && cres.status === 0) {
5153
+ console.error(` firewall ${ruleName}: rules '${current}' → tcp (all-tcp)`);
5154
+ state.push({ ruleName, rules: "tcp", converged: true });
5155
+ } else {
5156
+ const tail = (
5157
+ (cres && (cres.stderr || (cres.error && cres.error.message))) || ""
5158
+ ).toString().trim().split("\n").pop() || "error";
5159
+ console.error(` firewall ${ruleName}: converge skipped (${tail})`);
5160
+ state.push({ ruleName, rules: current, converged: false });
5161
+ }
5162
+ }
5163
+ if (!state.length) {
5164
+ console.error(
5165
+ ` firewall: no rule found under ${FLEET_FIREWALL_RULE_NAMES.join(" / ")} —` +
5166
+ " LB→VM traffic may be blocked; run scripts/gcp/google-ingress.sh",
5167
+ );
5168
+ }
5169
+ return state;
5170
+ }
5171
+
5172
+ /** Surface any rostered VM whose app port the fleet firewall does not admit — the
5173
+ * tripwire for a masked "HEALTHY but unreachable" preview.
5174
+ *
5175
+ * The preview backend service health-checks the fixed editor port, so a rule that
5176
+ * admits that port but not the app's real one reads HEALTHY while every real
5177
+ * request is dropped. That masking is what made the VM-6 outage invisible. Emits a
5178
+ * machine-readable `CY_FIREWALL_PORT_GAP <json>` line per gap, mirroring the
5179
+ * `CY_ORPHAN_SWEEP` marker convention the dashboard already parses.
5180
+ *
5181
+ * Only runs when a rule is still port-pinned: a converged all-tcp rule admits every
5182
+ * port, so the healthy path cannot produce a gap and skipping it avoids an SSH
5183
+ * round-trip per rostered VM for a check that cannot fail. In practice this fires
5184
+ * only if the converge itself failed (e.g. a permissions regression).
5185
+ *
5186
+ * Returns the emitted `[{ vmNumber, appPort, rule, allowed }]` gaps — the same
5187
+ * shape it prints — so the marker contract is directly assertable.
5188
+ * `deps.readVmAppPort` is injectable so tests never reach for SSH. */
5189
+ async function reportFirewallPortGaps({ cfg, roster, firewallState } = {}, deps = {}) {
5190
+ const readPort = deps.readVmAppPort || readVmAppPort;
5191
+ const pinned = (firewallState || []).filter((f) => firewallNeedsConverge(f.rules));
5192
+ const gaps = [];
5193
+ if (!pinned.length) return gaps;
5194
+ for (const n of roster || []) {
5195
+ const perVmCfg = { ...cfg, instanceName: `${fleetInstancePrefix()}${n}` };
5196
+ const appPort = await readPort(perVmCfg);
5197
+ for (const f of pinned) {
5198
+ if (firewallAdmitsPort(f.rules, appPort)) continue;
5199
+ const gap = { vmNumber: n, appPort, rule: f.ruleName, allowed: f.rules };
5200
+ console.error(` VM-${n}: app port ${appPort} NOT admitted by ${f.ruleName}`);
5201
+ console.log(`CY_FIREWALL_PORT_GAP ${JSON.stringify(gap)}`);
5202
+ gaps.push(gap);
5203
+ }
5204
+ }
5205
+ return gaps;
5206
+ }
5207
+
3723
5208
  function sweepOrphanIngress({ cfg, domain, roster, projectDir = rootDir } = {}, deps = {}) {
3724
5209
  const gi = deps.googleIngress || require("./google-ingress.js");
3725
5210
  const fcl = deps.fleetCleanup || require("./fleet-cleanup.js");
@@ -3820,7 +5305,14 @@ function sweepOrphanIngress({ cfg, domain, roster, projectDir = rootDir } = {},
3820
5305
  });
3821
5306
  const res = run(inv.command, inv.args, { encoding: "utf8", env: { ...process.env, ...inv.env } });
3822
5307
  const verdict = parseIngressTeardownVerdict((res && res.stdout) || "");
3823
- const outcome = classifyOrphanDownResult({ verdict, status: res ? res.status : null });
5308
+ // Pass `signal` too: a teardown the caller's group-kill reaped has a NULL
5309
+ // status, which the classifier would otherwise report as `spawn-failed`
5310
+ // rather than the truthful `killed=SIGKILL`.
5311
+ const outcome = classifyOrphanDownResult({
5312
+ verdict,
5313
+ status: res ? res.status : null,
5314
+ signal: res ? res.signal : null,
5315
+ });
3824
5316
  if (outcome.cleaned) {
3825
5317
  summary.cleaned.push(n);
3826
5318
  console.error(` VM-${n}: orphaned ingress → auto-cleaned (verified clean)`);
@@ -3889,20 +5381,33 @@ async function probeGitCredentials(cfg) {
3889
5381
  /** Seed the LIVE in-memory git credential-cache daemon over its socket — the
3890
5382
  * same `git credential approve` shape the entrypoint uses
3891
5383
  * (scripts/cloud-editor-entrypoint.sh) — so push works immediately with no
3892
- * container restart. base64 keeps the token out of the shell history across
3893
- * the gcloud-ssh → docker layers. Throws if the approve fails. Shared by
3894
- * {@link cmdReconcileCredentials} and {@link assertGitPushCredentials}. */
5384
+ * container restart. ALSO writes the container-local on-disk `store` fallback
5385
+ * file (the fill-only second helper baked into the image) directly, so a
5386
+ * reconcile leaves the VM durable against the cache daemon dying mid-life, not
5387
+ * just healthy for the moment. base64 keeps the token out of the shell history
5388
+ * across the gcloud-ssh → docker layers, and the store write is an in-place
5389
+ * `cat > file` truncate (chmod 600), never touched by git's approve path.
5390
+ * Throws if either write fails. Shared by {@link cmdReconcileCredentials} and
5391
+ * {@link assertGitPushCredentials}. */
3895
5392
  async function seedLiveCredentialCache(cfg, token) {
3896
5393
  const repoName = resolveProject(cfg).name;
3897
5394
  const projectCd = `cd ~/projects/${repoName}`;
3898
5395
  const composeExec = `docker compose -f docker-compose.cloud.yml exec -T editor`;
3899
5396
  const socket = "/run/codeyam/git-credential-cache.socket";
5397
+ const store = "/run/codeyam/git-credentials-store";
3900
5398
  const approveStdin = `protocol=https\nhost=github.com\nusername=x-access-token\npassword=${token}\n\n`;
3901
5399
  const b64 = Buffer.from(approveStdin).toString("base64");
5400
+ // The store-file line is the same one-URL-per-line format as the host staging
5401
+ // file; the image's fill-only `store` helper reads it on a cache miss.
5402
+ const storeB64 = Buffer.from(`${githubCredentialLine(token)}\n`).toString("base64");
3902
5403
  const seedCmd =
3903
- `${projectCd} && echo ${b64} | base64 -d | ${composeExec} ` +
5404
+ `${projectCd} && ` +
5405
+ `echo ${b64} | base64 -d | ${composeExec} ` +
3904
5406
  `git -c 'credential.helper=cache --timeout=31536000 --socket=${socket}' ` +
3905
- `credential approve && echo APPROVED`;
5407
+ `credential approve && ` +
5408
+ `echo ${storeB64} | base64 -d | ${composeExec} ` +
5409
+ `bash -c 'cat > ${store} && chmod 600 ${store}' && ` +
5410
+ `echo APPROVED`;
3906
5411
  const seed = runGcloud(
3907
5412
  buildGcloudArgs("ssh-probe", cfg, { command: seedCmd }),
3908
5413
  { stdio: ["ignore", "pipe", "inherit"] },
@@ -3941,6 +5446,39 @@ async function cmdReconcileCredentials(args, projectDir = rootDir) {
3941
5446
  );
3942
5447
  }
3943
5448
 
5449
+ /** `cloud:reconcile-admin` — flip admin mode on/off for an already-running VM
5450
+ * WITHOUT a full re-provision. Resolves the desired value from this invocation
5451
+ * (`--admin` / `CODEYAM_ADMIN`, else off), rewrites the rendered compose's
5452
+ * CODEYAM_ADMIN line, and recreates the editor service — matching what a manual
5453
+ * compose edit + `docker compose up -d editor` does today, so the durable admin
5454
+ * setting no longer requires a full re-provision to change. */
5455
+ async function cmdReconcileAdmin(args, projectDir = rootDir) {
5456
+ ensureGcloud();
5457
+ const flags = parseFlags(args);
5458
+ const cfg = loadCloudConfig(projectDir);
5459
+ if (!cfg) {
5460
+ throw new Error("No .codeyam/cloud.json found. Run `npm run cloud:up` first.");
5461
+ }
5462
+ const desired =
5463
+ buildProvisionEnv(process.env, flags).CODEYAM_ADMIN === "1" ? "1" : "";
5464
+ const repoName = resolveProject(cfg).name;
5465
+ console.error(
5466
+ `Reconciling admin mode to ${desired === "1" ? "ON" : "off"} on ${cfg.instanceName}...`,
5467
+ );
5468
+ const result = runGcloud(
5469
+ buildGcloudArgs("ssh-probe", cfg, {
5470
+ command: buildReconcileAdminCommand(repoName, desired),
5471
+ }),
5472
+ { stdio: "inherit" },
5473
+ );
5474
+ if (result.status !== 0) {
5475
+ throw new Error(`Failed to reconcile admin mode on ${cfg.instanceName}.`);
5476
+ }
5477
+ console.error(
5478
+ ` ✓ editor service recreated; /api/config now reports admin=${desired === "1" ? "true" : "false"}.`,
5479
+ );
5480
+ }
5481
+
3944
5482
  /** Provision-time guarantee that a just-provisioned VM can actually reach
3945
5483
  * GitHub. Probes the staging file + in-container `git ls-remote origin` and
3946
5484
  * routes the outcome through the SAME {@link decideCredentialHeal} classifier
@@ -4072,6 +5610,7 @@ const HANDLERS = {
4072
5610
  "reconcile-ingress": cmdReconcileIngress,
4073
5611
  "wire-add-tail": cmdWireAddTail,
4074
5612
  "reconcile-credentials": cmdReconcileCredentials,
5613
+ "reconcile-admin": cmdReconcileAdmin,
4075
5614
  access: cmdAccess,
4076
5615
  };
4077
5616
 
@@ -4094,6 +5633,10 @@ async function cloudMain() {
4094
5633
 
4095
5634
  module.exports = {
4096
5635
  // pure helpers
5636
+ isSpawnTimeout,
5637
+ gcloudCallTimeoutMs,
5638
+ provisionFailureMessage,
5639
+ GCLOUD_PROVISION_TIMEOUT_MS,
4097
5640
  agentEnvVarName,
4098
5641
  agentNpmPackage,
4099
5642
  AGENT_ENV_VARS,
@@ -4104,11 +5647,15 @@ module.exports = {
4104
5647
  assertAgentCliInstalled,
4105
5648
  probeContainerRunning,
4106
5649
  probeContainerState,
5650
+ waitForEditorComposeRunning,
5651
+ abortTeardownDecision,
5652
+ probeAbortTeardownState,
4107
5653
  probeAgentBinaryInstalled,
4108
5654
  waitForContainerRunning,
4109
5655
  KNOWN_FLAGS,
4110
5656
  FIREWALL_RULE_NAME,
4111
5657
  INSTANCE_TAG,
5658
+ DEFAULT_FLEET_MACHINE_TYPE,
4112
5659
  EDITOR_PORT,
4113
5660
  VITE_PORT,
4114
5661
  parseFlags,
@@ -4125,8 +5672,10 @@ module.exports = {
4125
5672
  resolveConfiguredAppPort,
4126
5673
  resolveSeedPreviewOrigin,
4127
5674
  previewSameOriginSafeFromStack,
5675
+ resolveEffectiveSameOriginSafe,
4128
5676
  isRottedManagedPreviewOrigin,
4129
5677
  isWrongModePreviewOrigin,
5678
+ isSilentlyBrokenPreview,
4130
5679
  resolveEditorConfig,
4131
5680
  validateEditorVariant,
4132
5681
  assertVariantProvisionable,
@@ -4135,13 +5684,19 @@ module.exports = {
4135
5684
  resolveGhcrToken,
4136
5685
  resolveGhcrPushToken,
4137
5686
  probeUsableEditorImage,
5687
+ httpsManifestGet,
4138
5688
  resolveProject,
4139
5689
  clientProjectBootstrapArgs,
4140
5690
  cloudConfigPath,
4141
5691
  loadCloudConfig,
4142
5692
  saveCloudConfig,
4143
5693
  loadOrInitCloudConfig,
5694
+ buildProvisionEnv,
5695
+ buildReconcileAdminCommand,
5696
+ cmdReconcileAdmin,
4144
5697
  buildEditorLocalEnvPatch,
5698
+ buildGreenfieldTitlePatch,
5699
+ mergeEditorLocalPatchB64,
4145
5700
  buildEditorLocalSeedWriteCommand,
4146
5701
  seedPreviewOrigin,
4147
5702
  healPreviewOriginAtReady,
@@ -4155,11 +5710,29 @@ module.exports = {
4155
5710
  decideBootstrapOutcome,
4156
5711
  projectBootstrapDoneMarker,
4157
5712
  projectBootstrapDoneProbeCommand,
5713
+ projectBootstrapScriptPath,
5714
+ projectBootstrapRunnerPath,
5715
+ projectBootstrapLogPath,
5716
+ projectBootstrapPidPath,
5717
+ projectBootstrapStatusPath,
5718
+ projectBootstrapRunnerScript,
5719
+ projectBootstrapLaunchCommand,
5720
+ projectBootstrapFollowCommand,
5721
+ projectBootstrapStatusCommand,
5722
+ parseProjectBootstrapStatus,
5723
+ decideProjectBootstrapOutcome,
5724
+ decideProjectBootstrapFollowAction,
5725
+ projectBootstrapEnv,
5726
+ PROJECT_BOOTSTRAP_LAUNCHED_MARKER,
5727
+ PROJECT_BOOTSTRAP_FOLLOW_SECS,
5728
+ ensureProjectBootstrapped,
4158
5729
  SSH_KEEPALIVE_FLAGS,
4159
5730
  resolveSetupForwardEnv,
4160
5731
  FORWARD_ENV_KEYS_ENV,
4161
5732
  parseEditorComposeState,
4162
5733
  fetchInstanceState,
5734
+ fetchPendingOperation,
5735
+ wedgedOperationMessage,
4163
5736
  formatGcloudFailure,
4164
5737
  isTransientSshFailure,
4165
5738
  runGcloudSshWithRetry,
@@ -4169,6 +5742,8 @@ module.exports = {
4169
5742
  checkScriptDrift,
4170
5743
  streamedScriptEditorBranch,
4171
5744
  streamedScriptMergeBase,
5745
+ fetchStreamedScriptRef,
5746
+ resolveRemoteScriptRev,
4172
5747
  gatherScriptDriftFacts,
4173
5748
  readStreamedScript,
4174
5749
  STREAMED_SCRIPTS,
@@ -4177,6 +5752,8 @@ module.exports = {
4177
5752
  ingressWiringPlan,
4178
5753
  fleetInstancePrefix,
4179
5754
  runVmIngress,
5755
+ intendedVmPrincipals,
5756
+ assertAddCanAuthorizeSomeone,
4180
5757
  wireVmIngressOnAdd,
4181
5758
  probeVmIngressVerdict,
4182
5759
  convergeVmIngressOnAdd,
@@ -4195,6 +5772,8 @@ module.exports = {
4195
5772
  cmdIngressUp,
4196
5773
  cmdReconcileIngress,
4197
5774
  sweepOrphanIngress,
5775
+ convergeFleetFirewall,
5776
+ reportFirewallPortGaps,
4198
5777
  cmdReconcileCredentials,
4199
5778
  cmdAccess,
4200
5779
  cloudMain,
@@ -4202,13 +5781,17 @@ module.exports = {
4202
5781
  seedLiveCredentialCache,
4203
5782
  assertGitPushCredentials,
4204
5783
  seedGithubCredentials,
5784
+ githubCredentialLine,
4205
5785
  resolveGithubToken,
4206
5786
  resolveGithubTokenWithSource,
4207
5787
  MissingGitPushCredentialsError,
4208
5788
  classifyGitRemoteError,
4209
5789
  decideCredentialHeal,
4210
5790
  readVmAppPort,
5791
+ buildVmAppPortReadCommand,
4211
5792
  resolveLaptopGitIdentity,
5793
+ gitBranchRefExists,
5794
+ assertBranchRefsExist,
4212
5795
  };
4213
5796
 
4214
5797
  if (require.main === module) {