` source is read from the connection
+ # the build is bound to, so the provider must be one the manifest
+ # requires — the platform's parser refuses it otherwise.
+ sources_known = ("repo.name", "repo.owner", "repo.fullName",
+ "connection.cloudflare.workersSubdomain")
+ src = field.get("from")
+ if src is not None and src not in sources_known:
+ B(f"inputs[{key}].from is {src!r} — must be one of {', '.join(sources_known)}")
+ if isinstance(src, str) and src.startswith("connection."):
+ provider = src.split(".")[1]
+ if provider not in ((spec.get("requires") or {}).get("integrations") or []):
+ B(f"inputs[{key}].from is {src!r} but spec.requires.integrations "
+ f"does not list {provider} — there is no connection to read it from")
+
+ # ── secrets: BOTH or NEITHER, checked both ways ───────────────────────
+ declared = {s.get("key"): (s.get("provider"), s.get("template")) for s in (spec.get("secrets") or [])}
+ if bp is None:
+ if declared:
+ B(f"declares {len(declared)} secret(s) but the repo has no "
+ f"repo-blueprint.yaml to mint them")
+ elif not blueprint_secrets:
+ if declared:
+ B(f"declares {len(declared)} secret(s) and repo-blueprint.yaml has no "
+ f"orun.integrations/reconcile@v1 hook to mint any")
+ else:
+ if "secrets" not in spec:
+ B("repo-blueprint.yaml mints keys and the manifest declares no secrets")
+ for k in sorted(set(blueprint_secrets) - set(declared)):
+ B(f"repo-blueprint.yaml mints {k} and the manifest does not declare it")
+ for k in sorted(set(declared) - set(blueprint_secrets)):
+ B(f"declares secret {k} and repo-blueprint.yaml never mints it")
+ for k in sorted(set(blueprint_secrets) & set(declared)):
+ if blueprint_secrets[k] != declared[k]:
+ B(f"{k}: manifest says provider/template {declared[k]}, "
+ f"repo-blueprint.yaml mints it as {blueprint_secrets[k]}")
+
+ # ── bootstrap: what is left of it, and what BE4 removed ───────────────
+ #
+ # `umbrella` and `agentBrief` named two files BE4 deleted. orun-cloud
+ # BE-K1c made both OPTIONAL in the manifest contract for exactly this, so
+ # this file no longer declares them — and must not, because a path that
+ # does not exist is the drift this whole test is about.
+ boot = spec.get("bootstrap") or {}
+ for field in ("umbrella", "agentBrief"):
+ rel = boot.get(field)
+ if rel is None:
+ continue
+ B(f"bootstrap.{field} is back, naming {rel}. The shell layer is gone "
+ f"(BE4): every phase is declared in repo-blueprint.yaml and orun runs "
+ f"it, so there is no umbrella to name and no session to brief.")
+ if not boot.get("expectedMinutes"):
+ B("bootstrap.expectedMinutes is missing — the console renders it")
+
+ # ── …and what BE-K1e added in their place ─────────────────────────────
+ #
+ # With no umbrella and no brief, `blueprint` is the ONLY entry point: it
+ # names the document whose phases a runner places after fetching this repo
+ # at its pinned tag. The registry row's `manifestPath` names the console
+ # CARD — this file — so without this key a runner has nothing to run.
+ #
+ # Checked the way everything else here is checked: against the thing that
+ # does the work, not against another copy of the claim. The file must
+ # exist, and it must be the one that actually declares the phases — a path
+ # to some other YAML would satisfy a mere existence check and fail a real
+ # bootstrap at the only moment that matters.
+ build = boot.get("blueprint")
+ if not build:
+ B("bootstrap.blueprint is missing. This baseline has no umbrella and "
+ "no agentBrief (BE4), so nothing else names the document a runner "
+ "places — a fetch at the pinned tag would find no entry point.")
+ else:
+ target = root / build
+ if not target.is_file():
+ B(f"bootstrap.blueprint names {build}, which does not exist")
+ else:
+ try:
+ doc = yaml.safe_load(target.read_text()) or {}
+ except yaml.YAMLError as exc:
+ doc = {}
+ B(f"bootstrap.blueprint names {build}, which does not parse: {exc}")
+ if doc and not (doc.get("phases") or (doc.get("spec") or {}).get("phases")):
+ B(f"bootstrap.blueprint names {build}, which declares no phases. "
+ f"A runner would fetch it and place nothing.")
+ if doc and doc.get("kind") != "Blueprint":
+ B(f"bootstrap.blueprint names {build}, whose kind is "
+ f"{doc.get('kind')!r} rather than Blueprint")
+
+ # ── every declared input is one the BLUEPRINT accepts ─────────────────
+ #
+ # This used to check the manifest's keys against the UMBRELLA's inputs,
+ # because a flow was what consumed them and orun's flow engine fails closed
+ # on an undeclared `--set`. The blueprint is what consumes them now, and it
+ # fails closed the same way:
+ #
+ # ✕ unknown input "reponame" (not declared in blueprint inputs)
+ #
+ # That equivalence is why open question 10 had to be settled in the same
+ # commit that deleted the flows: the umbrella's lowercase input names were
+ # the ONLY thing translating this file's keys into the blueprint's
+ # camelCase ones, so deleting it without renaming would have left every key
+ # refused.
+ #
+ # ONE DIRECTION ONLY. The blueprint declares more than this file does —
+ # `githuborg`, `epicSlug`, `domain`, `orunWorkspace` and the identity
+ # defaults are how a BUILD is driven, not what a product is configured
+ # with. What must hold is that nothing this file declares arrives at an
+ # engine that cannot take it.
+ if bp is not None:
+ bp_inputs = set((bp.get("inputs") or {}).keys())
+ if not bp_inputs:
+ B("repo-blueprint.yaml declares no inputs — this check has gone blind")
+ for key in [f.get("key") for f in (spec.get("inputs") or [])]:
+ if key and key not in bp_inputs:
+ B(f"inputs[{key}] is not an input of repo-blueprint.yaml — the "
+ f"console would resolve it and the engine would refuse it "
+ f"(orun fails closed on an undeclared --set)")
+
+ # ── …AND THE OTHER DIRECTION, for REQUIRED inputs only ───────────────
+ #
+ # The check above is one-directional on purpose: the blueprint declares
+ # more than this card does, because `epicSlug`, `domain` and the identity
+ # defaults are how a BUILD is driven rather than what a product is
+ # configured with. That tolerance had no floor, and `githuborg` fell
+ # through it — `required: true` in the blueprint, absent from this card,
+ # so a platform build resolved the card's inputs, handed them to the
+ # runner and died on its first step:
+ #
+ # ✕ input "githuborg" is required
+ #
+ # An input the blueprint REQUIRES and gives no default to is one somebody
+ # must supply, and the only things that supply inputs to a hosted build
+ # are this card's fields and its `from`/`derive` sources. So "more" may
+ # not include one of those.
+ #
+ # Defaulted inputs stay out of it: a default IS the supply.
+ if bp is not None:
+ for key, spec_in in (bp.get("inputs") or {}).items():
+ if not isinstance(spec_in, dict):
+ continue
+ if not spec_in.get("required"):
+ continue
+ if "default" in spec_in:
+ continue
+ if key not in input_keys:
+ B(f"repo-blueprint.yaml requires input {key!r} and gives it no "
+ f"default, and this card does not declare it — a hosted build "
+ f"would collect every field it shows and still die with "
+ f'\'input "{key}" is required\'')
+
+ # ── programme: BOTH or NEITHER, against the blueprint's own hooks ─────
+ #
+ # A milestone is what a phase CLUBS ITS TASK UNDER, which the phase states
+ # as `orun.task/ensure@v1`'s `milestone:`, which is why a phase that is
+ # the second landing of one unit of work would name its predecessor's
+ # milestone rather than one of its own (`04-workers-restore` did, before
+ # the bootstrap folded it into `05-edge`).
+ #
+ # Distinct, in phase order. The old check grepped the umbrella's
+ # `ensure-milestone` lines for the same list.
+ ensured, seen = [], set()
+ for phase in bp_phases:
+ for hook in uses(phase, "orun.task/ensure@v1"):
+ # Not `name`: that is the manifest's file name, which the summary
+ # line below prints (it printed the last milestone instead).
+ ms_name = ((hook.get("with") or {}).get("milestone") or "")
+ ms_name = ms_name.replace("{{ .phase.name }}", phase.get("name", "")).strip()
+ if ms_name and ms_name not in seen:
+ seen.add(ms_name)
+ ensured.append(ms_name)
+
+ # A phase's `when:` is what made a milestone conditional; the umbrella
+ # carried the same fact as a shell `[ != "true" ] ||` guard.
+ conditional = {
+ p_["name"] for p_ in bp_phases
+ if p_.get("when") and p_.get("name") in seen
+ }
+
+ prog = spec.get("programme")
+ if not ensured:
+ if prog:
+ B("declares a programme but repo-blueprint.yaml opens no milestones")
+ else:
+ if not prog:
+ B(f"repo-blueprint.yaml opens {len(ensured)} milestone(s) and the "
+ f"manifest declares no programme")
+ else:
+ ms = prog.get("milestones") or []
+ if any(not isinstance(m, dict) or "name" not in m for m in ms):
+ B("every programme.milestones entry must be a mapping with a `name` "
+ "(so a conditional one can carry its `when`)")
+ else:
+ names = [m["name"] for m in ms]
+ dcond = {m["name"] for m in ms if m.get("when")}
+ if names != ensured:
+ B(f"programme.milestones {names} != repo-blueprint.yaml's {ensured}")
+ if dcond != conditional:
+ B(f"conditional milestones disagree: manifest says {sorted(dcond) or '[]'}, "
+ f"the blueprint guards {sorted(conditional) or '[]'}")
+ slug = ((bp.get("inputs") or {}).get("epicSlug") or {}).get("default")
+ if slug and prog.get("epicSlug") != slug:
+ B(f"programme.epicSlug {prog.get('epicSlug')!r} != the blueprint's "
+ f"default {slug!r}")
+
+ # ── verify is optional, but must not name an input that is not there ──
+ input_keys = {f.get("key") for f in (spec.get("inputs") or [])} | {"env"}
+ for url in ((spec.get("verify") or {}).get("urls") or []):
+ for ph in re.findall(r"\{([a-zA-Z0-9_]+)\}", url):
+ if ph not in input_keys:
+ B(f"verify url interpolates {{{ph}}}, which is not an input")
+
+ checked.append((name, len(declared), len((prog or {}).get("milestones") or [])))
+
+if problems:
+ print("FAIL: a manifest and the blueprint disagree:", file=sys.stderr)
+ for p in problems:
+ print(f" - {p}", file=sys.stderr)
+ sys.exit(1)
+
+for name, ns, nm in checked:
+ print(f" {name}: {ns} secret(s), {nm} milestone(s) agree with repo-blueprint.yaml")
+PY
+
+echo "manifest.test.sh: ok"
diff --git a/testing/phases.test.sh b/testing/phases.test.sh
new file mode 100755
index 0000000..7449a24
--- /dev/null
+++ b/testing/phases.test.sh
@@ -0,0 +1,492 @@
+#!/usr/bin/env bash
+# The phases in `repo-blueprint.yaml` must be the phases the bootstrap runs,
+# placing what they are meant to place, in the order their hooks must run,
+# saying what they are, and naming only what the engine can resolve.
+#
+# TWO PHASES, ONE LANDING THAT DEPLOYS. `01-product` places every module the
+# blueprint declares — root files, workflows, tooling, the Supabase and
+# Hyperdrive roots, the migrations, the app and the tests — and lands them as
+# ONE pull request; the convergence after that merge provisions and deploys it
+# all, the order carried by the components' enforced `dependsOn` (placement
+# proves it on the product's own plan). `02-docs` places nothing: it records
+# the deployment and restores what 01-product deferred.
+#
+# The partition is written down a second time below on purpose: a module that
+# drifts out of 01-product, or a phase that grows back between the two, is a
+# change to how a product is built and has to be argued in the diff that edits
+# both places. The hook ORDER is written down too: every step of the identity
+# chain depends on the one before it (rebrand reads `git ls-files`, the verify
+# reads the restaged tree, the credentials are minted after the link and
+# before the landing whose convergence uses them), and a reorder fails live.
+#
+# What the applies publish is not checked by a separate await: every key is
+# resolved in the convergence, when a job starts, by a component that waits
+# for its publisher on main — so a green convergence says the key is there,
+# from the place every later run looks. This file holds that for each key,
+# and asks for an `orun.secrets/exists@v1` await for any key nothing reads.
+#
+# And the shape that keeps a bootstrap fast (orun >= v2.88.0): the run-level
+# task set-up runs in the background, each phase finds its task just before
+# its landing, each landing checks its commit here (`checks: local`), and the
+# convergence watch reads every few seconds.
+#
+# Adapted from sourceplane/cirrus-baseline's testing/phases.test.sh: the
+# narration rules and the hook-only rule are Cirrus's, unchanged.
+#
+# bash + python3 + PyYAML. No network, no fakes, no credential.
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+root="$(cd "$here/.." && pwd)"
+
+echo "── repo-blueprint.yaml phases against what the bootstrap runs"
+python3 - "$root" <<'PY'
+import pathlib, re, sys
+
+try:
+ import yaml
+except ImportError:
+ sys.exit("PyYAML is required for the phase contract test (pip install pyyaml)")
+
+root = pathlib.Path(sys.argv[1])
+problems = []
+def bad(m): problems.append(m)
+
+bp = yaml.safe_load((root / "repo-blueprint.yaml").read_text())
+phases = bp.get("phases") or []
+if not phases:
+ sys.exit("repo-blueprint.yaml declares no phases — this check has gone blind")
+
+PRODUCT = ["ai-deployment", "ai-operations", "cloudflare-hyperdrive", "db", "db-migrate",
+ "db-tests", "github-workflows", "rebrand-values", "root-gitignore", "root-intent",
+ "root-package-json", "root-pnpm-lock",
+ "root-pnpm-workspace", "root-readme", "root-turbo", "supabase", "tooling-eslint",
+ "tooling-migrations", "tooling-tsconfig", "tooling-wire", "vscode", "web",
+ "web-tests"]
+PARTITION = {"01-product": PRODUCT, "02-docs": []}
+HOOK_ONLY = {"02-docs"}
+# The phase that DEPLOYS, and so must give a re-run something to land.
+DEPLOYS = {"01-product"}
+
+# No phase has a `pre` hook: the task is found in `post`, just before the
+# landing, so that everything before it runs beside the background task
+# set-up.
+PRE = {"01-product": [], "02-docs": []}
+# The post hooks, in the order they must run (the brief's chain): the
+# re-run marker and the git index; the rebrand and the re-tenant; the three
+# rewrites a product needs before it lands; the restage and the verify; the
+# repository and its link; one brokered `secrets` reconcile per provider
+# (checked below); the task, then the landing.
+POST_ORDER = {
+ "01-product": ["retouch", "git-init", "stage", "rebrand", "orun-workspace",
+ "work-tree", "promotion", "dev-lanes", "restage", "rebrand-verify",
+ "repo", "link", "secrets-cloudflare", "secrets-supabase", "task", "land"],
+ "02-docs": ["promotion", "dev-lanes", "render", "task", "land"],
+}
+# The scripts behind the run: hooks that rewrite intent.yaml, with the mode
+# each must be called in.
+RUNS = {
+ ("01-product", "work-tree"): ("tooling/bootstrap/work-tree.mjs", "--strip"),
+ ("01-product", "promotion"): ("tooling/bootstrap/promotion.mjs", "--defer"),
+ ("01-product", "dev-lanes"): ("tooling/bootstrap/dev-lanes.mjs", "--defer"),
+ ("02-docs", "promotion"): ("tooling/bootstrap/promotion.mjs", "--restore"),
+ ("02-docs", "dev-lanes"): ("tooling/bootstrap/dev-lanes.mjs", "--restore"),
+ ("02-docs", "render"): ("hooks/render-deployment-docs.sh", None),
+}
+# 01-product watches its convergence and probes the app; it awaits nothing
+# the convergence already proved (below — a published key nothing reads puts
+# an `orun.secrets/exists@` between the two). 02-docs awaits nothing: its
+# render probes as it writes, and its landing redeploys nothing.
+AWAIT_ORDER = {"01-product": ["orun.run/watch@", "orun.http/probe@"],
+ "02-docs": []}
+
+by_name = {p["name"]: p for p in phases}
+names = [p["name"] for p in phases]
+
+# ── the order IS the execution order ──────────────────────────────────────
+if names != sorted(names):
+ bad(f"phases are not in execution order: {names}. The numbered name IS the "
+ f"order; a phase out of sequence is a barrier in the wrong place.")
+if names != list(PARTITION):
+ bad(f"phases are {names}; the bootstrap runs {list(PARTITION)}")
+
+# ── the partition has not drifted ─────────────────────────────────────────
+for name, want in PARTITION.items():
+ if name not in by_name:
+ continue
+ now = sorted(by_name[name].get("modules") or [])
+ if now != sorted(want):
+ bad(f"phase {name} no longer places what it placed: gained "
+ f"{sorted(set(now) - set(want)) or '[]'}, lost {sorted(set(want) - set(now)) or '[]'}")
+declared = {m["name"] for m in bp.get("modules") or []}
+placed = {m for p in phases for m in (p.get("modules") or [])}
+for m in sorted(declared - placed):
+ bad(f"module {m} is declared and no phase places it")
+for m in sorted(declared - set(PRODUCT)):
+ bad(f"module {m} is declared and 01-product does not place it — every module lands in the one landing")
+for name in HOOK_ONLY:
+ if by_name.get(name, {}).get("modules"):
+ bad(f"phase {name} places modules — it is declared as hooks only")
+
+# ── nothing may GATE on a phase the tree cannot answer for ────────────────
+for p in phases:
+ for need in ((p.get("requires") or {}).get("phases") or []):
+ if need in HOOK_ONLY:
+ bad(f"phase {p['name']} requires {need}, which places no files — require "
+ f"its predecessor instead")
+ if need not in by_name or names.index(need) >= names.index(p["name"]):
+ bad(f"phase {p['name']} requires {need}, which does not run before it")
+
+# ── 01-product asks for every connection it mints from, before it creates anything
+probe = ((by_name.get("01-product") or {}).get("requires") or {}).get("probe") or []
+doctor = [h for h in probe if (h.get("uses") or "").startswith("orun.doctor/check@")]
+want_providers = {"github", "cloudflare", "supabase"}
+if not doctor or set((doctor[0].get("with") or {}).get("providers") or []) != want_providers:
+ bad(f"01-product must probe {sorted(want_providers)} with orun.doctor/check@v1 before it places")
+elif (doctor[0].get("with") or {}).get("githubOwner") != "{{ .inputs.githuborg }}":
+ bad("01-product's doctor probe must wait for the GitHub App on the repository's owner")
+
+# ── every phase says what it is and what to budget ────────────────────────
+for p in phases:
+ for field in ("title", "expectedMinutes"):
+ if not p.get(field):
+ bad(f"phase {p['name']} declares no {field} — an operator reads both")
+ if not (p.get("hooks") or {}):
+ bad(f"phase {p['name']} declares no hooks — a phase that only places files "
+ f"still has to land them")
+
+def hooks_of(p):
+ h = p.get("hooks") or {}
+ if isinstance(h, list):
+ return list(h)
+ return [x for slot in ("pre", "post", "await") for x in (h.get(slot) or [])]
+
+run_hooks = list((bp.get("hooks") or {}).get("preInstantiate") or [])
+
+# ── the hook chain, in order ──────────────────────────────────────────────
+for name, want in PRE.items():
+ got = [h.get("id") for h in ((by_name.get(name, {}).get("hooks") or {}).get("pre") or [])]
+ if got != want:
+ bad(f"phase {name}'s pre hooks are {got}; want {want} — a task found in `pre` waits "
+ f"for the background task set-up before the phase has done anything")
+for name, want in POST_ORDER.items():
+ p = by_name.get(name)
+ if not p:
+ continue
+ post = (p.get("hooks") or {}).get("post") or []
+ ids = [h.get("id") for h in post]
+ if ids != want:
+ bad(f"phase {name}'s post hooks run {ids}; the chain is {want}")
+ # THE BROKERED KEYS, ONE `secrets` RECONCILE PER PROVIDER (orun >= v2.87.0):
+ # each key under its own scope template, the connections and the existing
+ # secrets read once per hook, the missing keys created side by side. A
+ # reconcile reads one connection, so two providers are two hooks; two
+ # hooks whose other parameters are the same are one hook written twice.
+ shared = {}
+ for h in post:
+ if (h.get("id") or "").startswith("secrets") and not (h.get("uses") or "").startswith("orun.integrations/reconcile@"):
+ bad(f"phase {name} hook {h.get('id')} is not an orun.integrations/reconcile@v1")
+ if not (h.get("uses") or "").startswith("orun.integrations/reconcile@"):
+ continue
+ w = h.get("with") or {}
+ if "keys" in w or "template" in w or not w.get("secrets"):
+ bad(f"phase {name} hook {h.get('id')} does not use the `secrets: [{{key, template}}]` form — "
+ f"one template per hook reads the connections and the secrets once per key")
+ if h.get("id") != f"secrets-{w.get('provider')}":
+ bad(f"phase {name} hook {h.get('id')} mints from {w.get('provider')}; name it secrets-{w.get('provider')}")
+ same = tuple(sorted((k, str(v)) for k, v in w.items() if k != "secrets"))
+ if same in shared:
+ bad(f"phase {name} hooks {shared[same]} and {h.get('id')} take the same parameters {dict(same)} — "
+ f"merge them into one `secrets` list")
+ shared.setdefault(same, h.get("id"))
+ for (ph, hid), (script, mode) in RUNS.items():
+ if ph != name:
+ continue
+ hook = next((h for h in post if h.get("id") == hid), None)
+ argv = " ".join((hook or {}).get("run") or [])
+ if script not in argv or (mode and mode not in argv):
+ bad(f"phase {name} hook {hid} must run {script} {mode or ''}".rstrip())
+
+# ── what the infrastructure publishes is read in the convergence ──────────
+# Each infra component's `secretOutputs` is what its apply lease-publishes to
+# the project's stage and prod rungs. A key is PROVED by the convergence when
+# a component resolves it from that place as its job starts (a `secretEnv`
+# reference, fail-closed: a missing document fails the lane) and waits for
+# the publisher on a merge to main (`mode: enforced`, advisory on a pull
+# request), on both stage and prod. Such a key needs no await; a key nothing
+# reads that way must be awaited with `orun.secrets/exists@v1` on stage and
+# prod in 01-product — and a key the convergence already proves must not be,
+# because that await is a platform round trip that can only agree.
+comps = {}
+for f in root.rglob("component.yaml"):
+ if "node_modules" in f.parts:
+ continue
+ d = yaml.safe_load(f.read_text()) or {}
+ comps[(d.get("metadata") or {}).get("name")] = (f.relative_to(root).as_posix(), d.get("spec") or {})
+def enforced_on_main(spec, target):
+ edge = next((d for d in spec.get("dependsOn") or [] if d.get("component") == target), None)
+ rules = (edge or {}).get("modeRules") or []
+ return bool(edge) and edge.get("mode") == "enforced" and any(
+ r.get("mode") == "advisory" and (r.get("when") or {}).get("triggerRef") == "github-pull-request"
+ for r in rules)
+published = {}
+for name, (rel, spec) in comps.items():
+ for pair in str((spec.get("parameters") or {}).get("secretOutputs") or "").split(","):
+ if "=" in pair:
+ published[pair.split("=", 1)[0].strip()] = name
+if not published:
+ bad("no infra component declares secretOutputs — this check has gone blind")
+proved, readers_of = set(), {}
+for key, pub in sorted(published.items()):
+ covered = set()
+ for name, (rel, spec) in comps.items():
+ if name == pub:
+ continue
+ subscribed = {e.get("name") for e in ((spec.get("subscribe") or {}).get("environments") or [])}
+ for ref in (spec.get("secretEnv") or {}).values():
+ m = re.fullmatch(r"secret://[^/]+/[^/]+/([^/]+)/([A-Z0-9_]+)", str(ref))
+ if not m or m.group(2) != key:
+ continue
+ readers_of.setdefault(key, set()).add(name)
+ if not enforced_on_main(spec, pub):
+ bad(f"{rel} resolves {key} and does not wait for {pub} on a merge to main — declare "
+ f"dependsOn {pub} with mode: enforced and a modeRules advisory on github-pull-request")
+ continue
+ env = m.group(1)
+ on = subscribed & {"stage", "prod"}
+ covered |= on if "{{" in env else ({env} if on and env in ("stage", "prod") else set())
+ if covered >= {"stage", "prod"}:
+ proved.add(key)
+awaits = ((by_name.get("01-product") or {}).get("hooks") or {}).get("await") or []
+exists = [h for h in awaits if (h.get("uses") or "").startswith("orun.secrets/exists@")]
+awaited = {k for h in exists for k in ((h.get("with") or {}).get("keys") or [])}
+if set(published) - proved - awaited:
+ bad(f"01-product neither reads nor awaits {sorted(set(published) - proved - awaited)} — nothing in "
+ f"the convergence resolves it on stage and prod, so await it with orun.secrets/exists@v1")
+if awaited & proved:
+ bad(f"01-product awaits {sorted(awaited & proved)}, which the convergence already resolves "
+ f"({', '.join(sorted({r for k in awaited & proved for r in readers_of.get(k, ())}))}) — drop them")
+for h in exists:
+ w = h.get("with") or {}
+ if sorted(w.get("environments") or []) != ["prod", "stage"]:
+ bad(f"01-product awaits the published secrets on {w.get('environments')}, not stage and prod")
+ if w.get("project") != "{{ .inputs.reponame }}":
+ bad("01-product awaits the published secrets in another project than the product's")
+# A key nothing reads is awaited between the watch and the probe.
+if set(published) - proved:
+ AWAIT_ORDER["01-product"] = ["orun.run/watch@", "orun.secrets/exists@", "orun.http/probe@"]
+for name, want in AWAIT_ORDER.items():
+ awaits = ((by_name.get(name) or {}).get("hooks") or {}).get("await") or []
+ got = [h.get("uses") or "" for h in awaits]
+ if len(got) != len(want) or not all(g.startswith(w) for g, w in zip(got, want)):
+ bad(f"phase {name}'s await hooks are {got}; they must be {want} (in that order)")
+for name in names:
+ for h in ((by_name[name].get("hooks") or {}).get("await") or []):
+ if (h.get("uses") or "").startswith("orun.http/probe@"):
+ urls = (h.get("with") or {}).get("urls") or []
+ for env in ("stage", "prod"):
+ base = f"https://{{{{ .inputs.reponame }}}}-web-{env}.{{{{ .inputs.subdomain }}}}.workers.dev"
+ for want in (base, base + "/api/health"):
+ if want not in urls:
+ bad(f"phase {name}'s probe does not ask {want}")
+
+# ── every phase lands, and every landing is bound to its task ─────────────
+for p in phases:
+ ids = [h.get("id") for h in hooks_of(p)]
+ lands = [h for h in hooks_of(p) if (h.get("uses") or "").startswith("orun.pr/land@")]
+ if len(lands) != 1:
+ bad(f"phase {p['name']} has {len(lands)} landing(s); a phase is ONE pull request")
+ continue
+ w = lands[0].get("with") or {}
+ if w.get("task") != "{{ .phase.hooks.task.outputs.key }}":
+ bad(f"phase {p['name']} lands without binding the PR to its task key")
+ if "task" not in ids or ids.index("task") > ids.index(lands[0].get("id")):
+ bad(f"phase {p['name']} must ensure its task before it lands")
+ if p["name"] in DEPLOYS:
+ if not any("retouch.mjs" in " ".join(h.get("run") or []) for h in hooks_of(p)):
+ bad(f"phase {p['name']} deploys and has no retouch hook — a re-run after a "
+ f"failed convergence would land an empty diff and redeploy nothing")
+ awaits = (p.get("hooks") or {}).get("await") or []
+ watch = [h for h in awaits if (h.get("uses") or "").startswith("orun.run/watch@")]
+ if not watch or (watch[0].get("with") or {}).get("sha") != "{{ .phase.hooks.land.outputs.mergeSha }}":
+ bad(f"phase {p['name']} deploys and does not watch the convergence of the "
+ f"commit it merged (orun.run/watch@v1 with sha: mergeSha)")
+
+# ── THE FAST SHAPE (orun >= v2.88.0) ──────────────────────────────────────
+# The run-level list is the task set-up, all of it in the background: the
+# first phase's provider check, placement, rebrand, repository and secrets
+# run while it opens the epic, the milestones and the tasks.
+for h in run_hooks:
+ if not h.get("background"):
+ bad(f"hooks.preInstantiate {h.get('id')} is not `background: true` — the first phase "
+ f"waits for it before doing anything, though nothing before its landing reads it")
+# No phase reaches the task plane in `pre`: that waits for the background at
+# once, before the phase has placed a file — the old order.
+for p in phases:
+ for h in ((p.get("hooks") or {}).get("pre") or []):
+ if (h.get("uses") or "").startswith(("orun.task/", "orun.pr/")):
+ bad(f"phase {p['name']} pre hook {h.get('id')} uses {h['uses']} — find the task in "
+ f"`post`, just before the landing")
+# Every landing checks its commit here and merges, instead of waiting ~25 s
+# for a runner to plan the tree this box just wrote.
+for p in phases:
+ for h in hooks_of(p):
+ if (h.get("uses") or "").startswith("orun.pr/land@") and (h.get("with") or {}).get("checks") != "local":
+ bad(f"phase {p['name']} lands with checks {(h.get('with') or {}).get('checks', 'ci')!r}, "
+ f"not 'local' — it waits for a runner to plan a tree that is here")
+# The convergence watch reads every few seconds, not the action's default 40.
+for p in phases:
+ for h in ((p.get("hooks") or {}).get("await") or []):
+ if (h.get("uses") or "").startswith("orun.run/watch@"):
+ every = (h.get("with") or {}).get("pollSeconds")
+ if not isinstance(every, int) or every > 10:
+ bad(f"phase {p['name']} watches its convergence every {every or 40} s; at most 10 — "
+ f"the build goes on that much after the run is green")
+# The shipped lockfile is installed frozen by the lanes and by the baseline's
+# e2e tier; a hook re-resolving it is a minute of network for nothing.
+for p in phases:
+ for h in hooks_of(p):
+ if "--lockfile-only" in (h.get("run") or []):
+ bad(f"phase {p['name']} hook {h.get('id')} re-resolves the lockfile the baseline ships")
+
+# ── every phase's task is one the run-level list opens, in the same order ─
+def task_names(hooks):
+ return [(h.get("with") or {}).get("name") for h in hooks
+ if (h.get("uses") or "").startswith("orun.task/ensure@")
+ and (h.get("with") or {}).get("kind") == "task"]
+opened = task_names(run_hooks)
+per_phase = [n for p in phases for n in task_names(hooks_of(p))]
+if opened != per_phase:
+ bad(f"the run-level list opens tasks {opened}; the phases ensure {per_phase} — "
+ f"a task is found by its title, so the two must be the same words")
+milestones = [(h.get("with") or {}).get("name") for h in run_hooks
+ if (h.get("with") or {}).get("kind") == "milestone"]
+if milestones != names:
+ bad(f"the run-level list opens milestones {milestones}; the phases are {names}")
+for h in run_hooks + [x for p in phases for x in hooks_of(p)]:
+ if (h.get("with") or {}).get("prefix") not in (None, "BASE"):
+ bad(f"hook {h.get('id')} files its task under prefix {h['with']['prefix']}, not BASE")
+
+# ── every contract a hook names exists, beside the blueprint ──────────────
+for h in run_hooks + [x for p in phases for x in hooks_of(p)]:
+ rel = (h.get("with") or {}).get("contract")
+ if rel and not (root / rel).exists():
+ bad(f"hook {h.get('id')} names contract {rel}, which does not exist")
+ if rel and not rel.startswith(".baseline/tasks/"):
+ bad(f"hook {h.get('id')} names contract {rel} outside .baseline/tasks/ — "
+ f"`tasks/` is this repository's own work tree, where an unkeyed "
+ f"contract is an error")
+for p in phases:
+ for h in hooks_of(p):
+ argv = " ".join(h.get("run") or [])
+ for ref in re.findall(r"\{\{ \.baseline\.dir \}\}/(\S+?)(?:\"|'|\s|$)", argv + " "):
+ if not (root / ref).exists():
+ bad(f"phase {p['name']} hook {h.get('id')} runs {ref}, which this "
+ f"repository does not have")
+
+# ── every phase has a documentation page, and every page a phase ──────────
+docs_dir = root / "docs" / "phases"
+pages = {f.stem for f in docs_dir.glob("*.md")} - {"README"}
+for n in names:
+ if n not in pages:
+ bad(f"phase {n} has no page at docs/phases/{n}.md")
+for page in sorted(pages - set(names)):
+ bad(f"docs/phases/{page}.md documents a phase repo-blueprint.yaml does not declare")
+
+# ── narration: authored here, printed from state (Cirrus's rules) ─────────
+META_AT = {
+ "start": {"files", "expectedMinutes"},
+ "await": {"files", "expectedMinutes"},
+ "failed": {"files", "expectedMinutes"},
+ "done": {"files", "expectedMinutes", "elapsed", "next"},
+}
+STATE_WORDS = {"done", "failed", "complete", "completed", "succeeded", "skipped"}
+PHASE_KEYS = {"name", "title"}
+input_keys = set((bp.get("inputs") or {}).keys())
+
+ws_input = (bp.get("inputs") or {}).get("orunWorkspace") or {}
+if ws_input.get("from") != "workspace":
+ bad("inputs.orunWorkspace must declare `from: workspace` — a console build has no other way to say it")
+
+def strip_expressions(line):
+ return re.sub(r"\{\{.*?\}\}", "", line, flags=re.S)
+
+def refs(line):
+ found = []
+ for expr in re.findall(r"\{\{(.*?)\}\}", line, re.S):
+ found += re.findall(r"\.([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*)", expr)
+ return found
+
+def check_line(where, line, slot, hook_ids):
+ prose = strip_expressions(line).lower()
+ for w in STATE_WORDS:
+ if re.search(rf"\b{w}\b", prose):
+ bad(f"{where} asserts {w!r} — `state` is the truth and narration is the "
+ f"caption. Describe the world, not the run.")
+ for ref in refs(line):
+ parts = ref.split(".")
+ head = parts[0]
+ if head == "phase":
+ if len(parts) != 2 or parts[1] not in PHASE_KEYS:
+ bad(f"{where} names .{ref}; a phase carries {sorted(PHASE_KEYS)}")
+ elif head == "inputs":
+ if len(parts) != 2 or parts[1] not in input_keys:
+ bad(f"{where} names .{ref}, which is not a declared input")
+ elif head == "meta":
+ allowed = META_AT.get(slot, META_AT["start"])
+ if len(parts) != 2 or parts[1] not in allowed:
+ bad(f"{where} names .{ref}; the {slot} event carries {sorted(allowed)}")
+ elif head == "hooks":
+ if len(parts) < 2 or parts[1] not in hook_ids:
+ bad(f"{where} names .{ref}; this phase has no such hook")
+ else:
+ bad(f"{where} names .{ref}; narration may reference phase, inputs, meta and hooks")
+
+for p in phases:
+ n = p.get("narrate") or {}
+ ids = {h.get("id") for h in hooks_of(p)}
+ awaits = bool((p.get("hooks") or {}).get("await"))
+ for slot in ("start", "await", "done", "failed"):
+ line = n.get(slot)
+ if slot == "await" and not awaits:
+ # A phase that waits on nothing never says its await line.
+ if line:
+ bad(f"phase {p['name']} declares narrate.await and has no await hooks — "
+ f"nobody would ever read it")
+ continue
+ if not line:
+ bad(f"phase {p['name']} declares no narrate.{slot}")
+ continue
+ check_line(f"phase {p['name']} narrate.{slot}", line, slot, ids)
+ for h in ((p.get("hooks") or {}).get("await") or []):
+ line = h.get("narrate")
+ if not line:
+ bad(f"phase {p['name']} await hook {h.get('id')} declares no narrate — a "
+ f"wait with no words reads as a stalled build")
+ continue
+ check_line(f"phase {p['name']} hook {h.get('id')} narrate", line, "done", ids)
+ for slot in ("pre", "post"):
+ for h in ((p.get("hooks") or {}).get(slot) or []):
+ if h.get("narrate"):
+ check_line(f"phase {p['name']} hook {h.get('id')} narrate", h["narrate"], "start", ids)
+
+# ── what a baseline of this shape never grows back ────────────────────────
+if (root / "flows").exists():
+ bad("flows/ exists — the bootstrap is the blueprint; every mechanism is a typed orun action")
+
+if problems:
+ print("FAIL: the blueprint's phases and the bootstrap disagree:", file=sys.stderr)
+ for p in problems:
+ print(f" - {p}", file=sys.stderr)
+ sys.exit(1)
+
+placed_n = sum(len(p.get("modules") or []) for p in phases)
+narrated = sum(len(p.get("narrate") or {}) for p in phases)
+narrated += sum(1 for p in phases for h in hooks_of(p) if h.get("narrate"))
+print(f" {len(phases)} phases, {placed_n} modules (all in 01-product), {len(HOOK_ONLY)} hook-only — in execution order")
+print(f" the hook chain in order; the convergence resolves {sorted(proved)} on stage and prod, "
+ f"each from a job that waits for its publisher" + (f"; 01-product awaits {sorted(awaited)}" if awaited else ""))
+print(f" the fast shape: the task set-up in the background, no `pre` hook, every landing checks: local")
+print(f" {narrated} authored narration lines, every reference resolving")
+PY
+
+echo "phases.test.sh: ok"
diff --git a/testing/placement.test.sh b/testing/placement.test.sh
new file mode 100755
index 0000000..55d7621
--- /dev/null
+++ b/testing/placement.test.sh
@@ -0,0 +1,426 @@
+#!/usr/bin/env bash
+# TIER 1 — the tree is placed, branded, and made to answer.
+#
+# A real bootstrap is `orun new --run-hooks --resume` against a workspace: it
+# places each phase, runs that phase's hooks, lands a pull request and watches
+# the convergence. Everything in that sentence except the platform can run
+# here, offline, and this file runs it:
+#
+# 1. the whole blueprint placed in one go — orun runs `validate` and
+# `plan --dry-run` inside the produced tree and says so; asserted, because
+# a future orun that stopped running them would weaken this tier in silence;
+# 2. THE OFFLINE BOOTSTRAP (testing/lib/bootstrap.sh) — both phases placed in
+# order, each finished by the blueprint's OWN `run:` hooks (the retouch
+# marker, rebrand, re-tenant, work-tree strip, the deferrals and their
+# restore, the deployment record), each landing a commit;
+# 3. the product it ends with: branded with no residue, carrying nothing of
+# the factory and naming none of it, re-tenanted, its gates restored, its
+# record rendered, its wrangler config committed;
+# 4. what the product's own CI does with the 01-product merge: `orun plan
+# --trigger github-push-main` over exactly that commit. Per environment:
+# supabase → cloudflare-hyperdrive → db-migrate → web, every edge
+# ENFORCED, read off the plan's own dependency graph; stage and prod side
+# by side; nothing on dev; every brokered key the plan resolves minted by
+# the blueprint, and every other the infrastructure publishes. The same
+# commit planned as a pull request: every one of those edges advisory;
+# 5. after 02-docs: prod waits on stage again and dev verifies main again;
+# 6. a `--resume` over the finished product places nothing and un-brands
+# nothing.
+#
+# testing/e2e.test.sh goes on from here: it installs, migrates, builds and
+# serves the product, and proves the page reads and writes its database.
+#
+# Needs: orun, node, pnpm, python3 (+PyYAML), git. No credential. The
+# deployment-record probes reach the network if they can, and pass without it.
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+root="$(cd "$here/.." && pwd)"
+# shellcheck source=lib/bootstrap.sh
+source "$here/lib/bootstrap.sh"
+
+for bin in orun node pnpm python3 git; do
+ command -v "$bin" >/dev/null || { echo "placement.test.sh needs $bin on PATH" >&2; exit 1; }
+done
+
+scratch="$(mktemp -d)"
+trap 'rm -rf "$scratch"' EXIT
+fails=0
+fail() { echo " ✕ $*" >&2; fails=$((fails + 1)); }
+values="$here/fixtures/acme.json"
+repo="$(python3 -c "import json,sys;print(json.load(open(sys.argv[1]))['reponame'])" "$values")"
+
+sets=()
+while IFS=$'\t' read -r k v; do sets+=( --set "$k=$v" ); done < <(
+ python3 - "$values" <<'PY'
+import json, sys
+for k, v in json.load(open(sys.argv[1])).items():
+ if not k.startswith("_"):
+ print(f"{k}\t{'true' if v is True else 'false' if v is False else v}")
+PY
+)
+
+# ── 1. the whole blueprint, one placement ──────────────────────────────────
+echo "── placing the whole blueprint at once (offline, no credential)"
+whole="$scratch/whole"
+mkdir -p "$whole"
+if ! orun new --blueprint "$root/repo-blueprint.yaml" --out "$whole" "${sets[@]}" > "$scratch/whole.log" 2>&1; then
+ echo "FAIL: the placement did not run" >&2; tail -20 "$scratch/whole.log" >&2; exit 1
+fi
+# The line's wording moved between orun releases (v2.58: `repo gate: validate +
+# plan --dry-run passed`; v2.79: `Verified intent valid · N components …`).
+grep -Eq "repo gate: validate \+ plan --dry-run passed|Verified +intent valid" "$scratch/whole.log" \
+ || fail "the placement did not report the repo-scale gate (orun validate + plan --dry-run inside the tree)"
+n="$(find "$whole" -type f -not -path '*/.orun/*' | wc -l | tr -d ' ')"
+[ "$n" -ge 100 ] || fail "only $n files placed — that is not a product"
+[ "$fails" -eq 0 ] && echo " $n files placed into an empty directory; the repo-scale gate ran"
+
+# ── 2. the offline bootstrap ───────────────────────────────────────────────
+echo "── the offline bootstrap: both phases, their own hooks, a landing each"
+tree="$scratch/$repo" # named as the repository is: orun names the project after it
+bootstrap_offline "$root" "$tree" "$values" "$scratch/logs" > "$scratch/bootstrap.log" 2>&1 || {
+ echo "FAIL: the offline bootstrap stopped" >&2; tail -40 "$scratch/bootstrap.log" >&2; exit 1; }
+grep -E '^── ' "$scratch/bootstrap.log" | sed 's/^/ /'
+commits="$(git -C "$tree" rev-list --count HEAD)"
+[ "$commits" = 2 ] || fail "the bootstrap landed $commits commits, not one per phase (2)"
+
+# ── 3. the product it ends with ────────────────────────────────────────────
+echo "── the product it produced"
+(cd "$tree" && node "$root/tooling/rebrand/rebrand.mjs" --verify --values .rebrand/values.json) > "$scratch/verify.log" 2>&1 \
+ || { fail "rebrand --verify found the baseline's identity in the product:"; sed 's/^/ /' "$scratch/verify.log" >&2; }
+
+python3 - "$tree" "$values" "$root" <<'PY' || fails=$((fails + 1))
+import json, pathlib, re, subprocess, sys
+import yaml
+tree, values, root = pathlib.Path(sys.argv[1]), json.load(open(sys.argv[2])), pathlib.Path(sys.argv[3])
+problems = []
+def bad(m): problems.append(m)
+repo, org, name, sub, ws = (values[k] for k in ("reponame", "githuborg", "productname", "subdomain", "orunWorkspace"))
+
+tracked = subprocess.run(["git", "ls-files"], cwd=tree, capture_output=True, text=True, check=True).stdout.split()
+
+# Nothing of the factory, nothing local, exactly the two context pages.
+NEVER = (".baseline/", "specs/", "tasks/", "testing/", "hooks/", "docs/phases/",
+ "tooling/rebrand/", "tooling/bootstrap/", ".github/workflows/baseline.yml",
+ ".github/workflows/tag.yml", "BOOTSTRAP.md", "repo-blueprint.yaml", "blueprint.yaml")
+for p in tracked:
+ if any(p == n or p.startswith(n) for n in NEVER):
+ bad(f"{p} is in the product — it is the factory")
+ if re.search(r"(^|/)(\.env(\.local)?|\.dev\.vars|node_modules|\.orun|\.next|\.open-next|\.terraform)(/|$)", p):
+ bad(f"{p} is in the product — a local or built file")
+ai = {p for p in tracked if p.startswith("ai/")}
+if ai != {"ai/context/deployment.md", "ai/context/operations.md"}:
+ bad(f"ai/ in the product is {sorted(ai)}")
+
+# …and no tracked file names one of the factory's paths.
+FACTORY_PATH = re.compile(r"repo-blueprint|(? "$scratch/validate.log" 2>&1 \
+ || { fail "orun validate refused the product's intent at 01-product"; tail -10 "$scratch/validate.log" >&2; }
+# The merge is the repository's first content: every file is new, so the
+# push's `--changed` set is every component — the full plan.
+(cd "$at01" && orun plan --intent intent.yaml --trigger github-push-main --output "$scratch/plan-main.json") > "$scratch/plan-main.log" 2>&1 \
+ || { fail "orun plan (push to main) failed in the product at 01-product"; tail -15 "$scratch/plan-main.log" >&2; }
+(cd "$at01" && orun plan --intent intent.yaml --trigger github-pull-request --base empty --head HEAD \
+ --output "$scratch/plan-pr.json") > "$scratch/plan-pr.log" 2>&1 \
+ || { fail "orun plan (pull request) failed in the product at 01-product"; tail -15 "$scratch/plan-pr.log" >&2; }
+
+# The PRODUCT's CI plans with its own lane pin (ci.yml), not with the orun
+# that places the blueprint: per-edge `modeRules` — advisory on a pull
+# request — are read by that pin, and an orun older than it (v2.58.11, the
+# bootstrap's floor before v2.88.0) plans them enforced everywhere. So the
+# pull-request half below holds only when this orun is at least the
+# product's pin — which the floor now is; e2e.test.sh asserts it again.
+lane_pin="$(sed -n 's/^ *version: *v\([0-9.]*\) *$/\1/p' "$tree/.github/workflows/ci.yml" | head -1)"
+this_orun="$(orun --version | sed -n 's/.*version v\{0,1\}\([0-9.]*\).*/\1/p' | head -1)"
+
+python3 - "$scratch/plan-main.json" "$scratch/plan-pr.json" "$values" "$root" "$at01" "$this_orun" "$lane_pin" <<'PLAN' || fails=$((fails + 1))
+import json, pathlib, sys
+import yaml
+plan, pr = json.load(open(sys.argv[1])), json.load(open(sys.argv[2]))
+values, root, tree = json.load(open(sys.argv[3])), pathlib.Path(sys.argv[4]), pathlib.Path(sys.argv[5])
+this_orun, lane_pin = (tuple(int(x) for x in v.split(".")) for v in sys.argv[6:8])
+repo, sub, ws = values["reponame"], values["subdomain"], values["orunWorkspace"]
+problems = []
+def bad(m): problems.append(m)
+jobs = {(j["component"], j["environment"]): j for j in plan["jobs"]}
+ids = {j["id"]: j for j in plan["jobs"]}
+
+CHAIN = ["supabase", "cloudflare-hyperdrive", "db-migrate", "web"]
+PROFILE = {"supabase": "terraform.apply", "cloudflare-hyperdrive": "terraform.apply",
+ "db-migrate": "db-migrate.apply", "web": "cloudflare-workers-assets-turbo.deploy",
+ "db": "turbo-package.quick-check"}
+want = {(c, e) for c in PROFILE for e in ("stage", "prod")}
+if set(jobs) != want:
+ bad(f"the 01-product merge plans {sorted(jobs)}; it must plan {sorted(want)} — and nothing on dev")
+for (comp, env), j in jobs.items():
+ if comp in PROFILE and j["profile"] != PROFILE[comp]:
+ bad(f"{comp}@{env} plans {j['profile']}, not {PROFILE[comp]}")
+ if j.get("dependencyMode") != "enforced":
+ bad(f"{j['id']} plans dependencyMode {j.get('dependencyMode')}, not enforced")
+ for dep in j.get("dependsOn") or []:
+ if ids[dep]["environment"] != j["environment"]:
+ bad(f"{j['id']} waits on {dep} — during the bootstrap stage and prod run side by side")
+
+# THE ORDER, read off the plan's own graph: each link of the chain is an
+# ENFORCED edge (`dependsOn`, not `advisoryDependsOn`), and the depth of each
+# job — the longest chain of enforced edges into it — puts the four on four
+# different levels, in order.
+depth = {}
+def level(jid):
+ if jid not in depth:
+ depth[jid] = 1 + max((level(d) for d in ids[jid].get("dependsOn") or []), default=-1)
+ return depth[jid]
+for env in ("stage", "prod"):
+ by = {c: jobs.get((c, env)) for c in CHAIN}
+ if not all(by.values()):
+ continue
+ for a, b in zip(CHAIN, CHAIN[1:]):
+ if by[a]["id"] not in (by[b].get("dependsOn") or []):
+ bad(f"{b}@{env} does not wait on {a}@{env} — the order is {' → '.join(CHAIN)}")
+ for dep in ("cloudflare-hyperdrive", "db-migrate"):
+ if by[dep]["id"] not in (by["web"].get("dependsOn") or []):
+ bad(f"web@{env} reads {dep}'s output and does not wait on it")
+ order = sorted(CHAIN, key=lambda c: level(by[c]["id"]))
+ levels = [level(by[c]["id"]) for c in order]
+ if order != CHAIN or len(set(levels)) != len(levels):
+ bad(f"{env} converges {order} at levels {levels}; it must be {' → '.join(CHAIN)}, one after another")
+ else:
+ print(f" {env}, enforced: " + " → ".join(order))
+
+# …and on a pull request every one of those edges is ADVISORY: nothing is
+# applied or deployed there, so nothing waits.
+prj = {(j["component"], j["environment"]): j for j in pr["jobs"]}
+pr_edges = this_orun >= lane_pin
+for env in ("stage", "prod"):
+ for a, b in zip(CHAIN, CHAIN[1:]) if pr_edges else ():
+ jb, ja = prj.get((b, env)), prj.get((a, env))
+ if not ja or not jb:
+ bad(f"the pull-request plan has no {a}@{env} or {b}@{env}")
+ continue
+ if ja["id"] in (jb.get("dependsOn") or []):
+ bad(f"on a pull request {b}@{env} still waits on {a}@{env} — the edge must be advisory there")
+ if ja["id"] not in (jb.get("advisoryDependsOn") or []):
+ bad(f"on a pull request {b}@{env} does not name {a}@{env} as advisory")
+ for comp, prof in (("supabase", "plan-only"), ("cloudflare-hyperdrive", "plan-only"),
+ ("db-migrate", "plan"), ("web", "verify")):
+ j = prj.get((comp, env))
+ if j and not j["profile"].endswith("." + prof):
+ bad(f"on a pull request {comp}@{env} plans {j['profile']}, which may mutate")
+if pr_edges:
+ print(" pull request: the same edges, advisory; plan-only, plan and verify — nothing applied")
+else:
+ print(f" pull request: plan-only, plan and verify — nothing applied (the edges' advisory mode is "
+ f"read by the product's lane pin v{'.'.join(map(str, lane_pin))}; this orun is "
+ f"v{'.'.join(map(str, this_orun))} — not checked here)")
+
+# Every brokered key the plan resolves is one the blueprint mints, and every
+# other key it resolves is one an apply publishes — nothing else. Derived
+# from the product's own plan (component secretEnv AND the compositions'
+# bindings), the blueprint's reconcile hooks and the components' secretOutputs.
+bp = yaml.safe_load((root / "repo-blueprint.yaml").read_text())
+# Either form a reconcile takes: `secrets: [{key, template}]`, or `keys`.
+minted = {k for p in bp["phases"] for slot in (p.get("hooks") or {}).values() for h in slot
+ if (h.get("uses") or "").startswith("orun.integrations/reconcile@")
+ for k in [s["key"] for s in h["with"].get("secrets") or []] + list(h["with"].get("keys") or [])}
+published = set()
+for comp in tree.glob("infra/**/component.yaml"):
+ so = str(((yaml.safe_load(comp.read_text()) or {}).get("spec") or {}).get("parameters", {}).get("secretOutputs") or "")
+ published |= {pair.split("=", 1)[0] for pair in so.split(",") if "=" in pair}
+resolved = set()
+for (comp, env), j in jobs.items():
+ for r in j.get("secretRefs") or []:
+ ref = r["ref"]
+ resolved.add(ref.rsplit("/", 1)[1])
+ if not ref.startswith(f"secret://{ws}/"):
+ bad(f"{comp}@{env} resolves {r['asEnv']} from {ref} — not the product's workspace")
+ if f"/{repo}/" not in ref and f"project:{repo}/" not in ref:
+ bad(f"{comp}@{env} resolves {r['asEnv']} from {ref} — not the product's project")
+if resolved - published != minted:
+ bad(f"the plan resolves brokered keys {sorted(resolved - published)}; the blueprint mints {sorted(minted)}")
+if not published <= resolved:
+ bad(f"the infrastructure publishes {sorted(published - resolved)} and nothing reads it")
+print(f" the plan resolves exactly the {len(minted)} keys the blueprint mints, "
+ f"and reads all {len(published)} the applies publish")
+
+# The deploy itself: the structure check, the live wiring render, the
+# Worker's name, the smoke.
+for env in ("stage", "prod"):
+ j = jobs.get(("web", env))
+ if not j:
+ continue
+ steps = {s["id"]: s.get("run") or "" for s in j["steps"]}
+ for need in ("verify-app-structure", "build-app", "deploy", "smoke"):
+ if need not in steps:
+ bad(f"web@{env} has no {need} step")
+ if 'test -f "wrangler.jsonc"' not in steps.get("verify-app-structure", ""):
+ bad(f"web@{env} checks another config before the build: {steps.get('verify-app-structure','').strip()}")
+ if "tooling/wire/live.mjs" not in steps.get("build-app", "") or "cloudflare-hyperdrive" not in steps.get("build-app", ""):
+ bad(f"web@{env} does not render its wrangler config from the Hyperdrive wiring before it builds")
+ if f'EFFECTIVE_WORKER_NAME="{repo}-web-{env}"' not in steps.get("deploy", ""):
+ bad(f"web@{env} deploys a Worker not named {repo}-web-{env}")
+ if "/api/health" not in steps.get("smoke", "") or f'export WORKERS_DEV_SUBDOMAIN="{sub}"' not in steps.get("smoke", ""):
+ bad(f"web@{env}'s smoke does not check the product's own /api/health")
+
+if problems:
+ for p in problems:
+ print(f" ✕ {p}", file=sys.stderr)
+ sys.exit(1)
+print(" stage and prod side by side; nothing on dev; the Worker, its wiring render and its smoke the product's own")
+PLAN
+
+# ── 5. after the record: the gates are back ────────────────────────────────
+echo "── orun plan in the finished product: prod waits on stage, dev verifies main"
+(cd "$tree" && orun plan --intent intent.yaml --trigger github-push-main --output "$scratch/plan-after.json") > "$scratch/plan-after.log" 2>&1 \
+ || { fail "orun plan failed in the finished product"; tail -15 "$scratch/plan-after.log" >&2; }
+python3 - "$scratch/plan-after.json" <<'AFTER' || fails=$((fails + 1))
+import json, sys
+plan = json.load(open(sys.argv[1]))
+jobs = {(j["component"], j["environment"]): j for j in plan["jobs"]}
+problems = []
+for comp in ("supabase", "cloudflare-hyperdrive", "db-migrate", "web"):
+ prod, stage = jobs.get((comp, "prod")), jobs.get((comp, "stage"))
+ if not prod or not stage or stage["id"] not in (prod.get("dependsOn") or []):
+ problems.append(f"{comp}@prod does not wait on {comp}@stage — the promotion gate is not back")
+dev = sorted(c for (c, e) in jobs if e == "dev")
+if dev != ["db", "db-tests", "web", "web-tests"]:
+ problems.append(f"dev verifies {dev} on a push to main; it must verify db, db-tests, web and web-tests")
+for p in problems:
+ print(f" ✕ {p}", file=sys.stderr)
+if problems:
+ sys.exit(1)
+print(" prod waits on stage for every component; dev verifies db, db-tests, web and web-tests")
+AFTER
+
+# ── 6. a resume over the finished product ─────────────────────────────────
+echo "── --resume over the finished product"
+before="$(git -C "$tree" status --porcelain; git -C "$tree" rev-parse HEAD)"
+orun new --blueprint "$root/repo-blueprint.yaml" --out "$tree" --resume "${sets[@]}" > "$scratch/resume.log" 2>&1 \
+ || { fail "--resume did not run"; tail -10 "$scratch/resume.log" >&2; }
+after="$(git -C "$tree" status --porcelain; git -C "$tree" rev-parse HEAD)"
+[ "$before" = "$after" ] || { fail "--resume changed the finished product:"; git -C "$tree" status --short | head -10 >&2; }
+grep -q "SITE_NAME = \"Sam's Profiles & Co\"" "$tree/apps/web/lib/site.ts" \
+ || fail "--resume reverted the product's identity"
+[ "$fails" -eq 0 ] && echo " nothing placed again, nothing un-branded"
+
+[ "$fails" -eq 0 ] || { echo "placement.test.sh: $fails failure(s)" >&2; exit 1; }
+echo "placement.test.sh: ok"
diff --git a/testing/rebrand.test.sh b/testing/rebrand.test.sh
new file mode 100755
index 0000000..dd0eca4
--- /dev/null
+++ b/testing/rebrand.test.sh
@@ -0,0 +1,184 @@
+#!/usr/bin/env bash
+# THE REBRAND WRITES EACH VALUE ONCE, AND WHAT IT WROTE STAYS WRITTEN.
+#
+# Drives the real tooling/rebrand/rebrand.mjs over one-file trees and compares
+# the file. Each case is a shape this baseline's identity actually takes in the
+# tree — the name seam, the worker name, the Worker's own origin, the
+# placeholder domain, a secret ref, the `repo` the Supabase project is named
+# after — and each runs through as many passes as a bootstrap might make, so a
+# value written once must survive every later pass unchanged. Two things must
+# NOT be renamed: the upstream template's own links (its name is this
+# baseline's slug minus `-starter`), and a migration (its checksum is in the
+# manifest and in every database it was applied to), even where it spells the
+# slug.
+#
+# The identity is PINNED (fixtures/baseline-identity.postgres-kysely.json) rather
+# than read from .baseline/identity.json: what this tests is the engine, and
+# its fixtures spell the identity out literally.
+#
+# Needs: node, git. No network.
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+rebrand="$here/../tooling/rebrand/rebrand.mjs"
+identity="$here/fixtures/baseline-identity.postgres-kysely.json"
+
+fail=0
+# check NAME VALUES-JSON FILE CONTENT WANT [PASSES]
+check() {
+ local name="$1" values="$2" file="$3" content="$4" want="$5" passes="${6:-1}"
+ local tmp got out i
+ tmp="$(mktemp -d)"
+ git -C "$tmp" init -q
+ mkdir -p "$tmp/$(dirname "$file")" "$tmp/.rebrand"
+ printf '%s\n' "$content" > "$tmp/$file"
+ printf '%s\n' "$values" > "$tmp/.rebrand/values.json"
+ for ((i = 1; i <= passes; i++)); do
+ git -C "$tmp" add -A
+ if ! out="$(cd "$tmp" && node "$rebrand" --baseline-identity "$identity" --values .rebrand/values.json --allow-dirty 2>&1)"; then
+ echo " ✕ $name: rebrand pass $i failed:" >&2
+ printf '%s\n' "$out" | sed 's/^/ /' >&2
+ fail=1
+ rm -rf "$tmp"
+ return
+ fi
+ done
+ got="$(cat "$tmp/$file")"
+ rm -rf "$tmp"
+ if [ "$got" = "$want" ]; then
+ echo " ok $name"
+ else
+ echo " ✕ $name:" >&2
+ echo " got: $got" >&2
+ echo " want: $want" >&2
+ fail=1
+ fi
+}
+
+acme='{"reponame":"acme-postgres","productname":"Acme Cloud","productdomain":"acme.dev","githuborg":"acme-inc","subdomain":"acme","orunWorkspace":"ws_79BDXAZQ"}'
+
+echo "── rebrand: the product's own identity"
+check "the name seam takes the product's name" \
+ "$acme" apps/web/lib/site.ts 'export const SITE_NAME = "Postgres on Cloudflare"' \
+ 'export const SITE_NAME = "Acme Cloud"'
+check "…and stays a valid string for a name with an apostrophe and an ampersand" \
+ '{"reponame":"sams-profiles","productname":"Sam'"'"'s Profiles & Co","productdomain":"sam.dev"}' \
+ apps/web/lib/site.ts 'export const SITE_NAME = "Postgres on Cloudflare"' \
+ 'export const SITE_NAME = "Sam'"'"'s Profiles & Co"'
+check "the display name elsewhere is content, and is left alone" \
+ "$acme" apps/web/app/x.tsx 'Welcome to Postgres on Cloudflare.
' \
+ 'Welcome to Postgres on Cloudflare.
'
+check "the worker name is re-prefixed, the environment suffix kept" \
+ "$acme" apps/web/component.yaml 'workerName: postgres-kysely-web' \
+ 'workerName: acme-postgres-web'
+check "the Worker's own origin (the site URL the build bakes in): worker name and subdomain" \
+ "$acme" apps/web/component.yaml \
+ 'buildCommand: NEXT_PUBLIC_SITE_URL="${SITE_URL:-https://postgres-kysely-web-${ORUN_ENVIRONMENT}.your-workers-subdomain.workers.dev}" pnpm build' \
+ 'buildCommand: NEXT_PUBLIC_SITE_URL="${SITE_URL:-https://acme-postgres-web-${ORUN_ENVIRONMENT}.acme.workers.dev}" pnpm build'
+check "the placeholder domain is the product's domain, not a renamed slug" \
+ "$acme" intent.yaml ' BASE_DOMAIN: postgres-kysely.example.com' \
+ ' BASE_DOMAIN: acme.dev'
+check "no domain given: the reserved placeholder, for an owner to replace later" \
+ '{"reponame":"acme-postgres","productname":"Acme Cloud","githuborg":"acme-inc","subdomain":"acme"}' \
+ intent.yaml ' BASE_DOMAIN: postgres-kysely.example.com' \
+ ' BASE_DOMAIN: acme-postgres.example.com'
+check "an empty domain is no domain" \
+ '{"reponame":"acme-postgres","productname":"Acme Cloud","productdomain":""}' \
+ intent.yaml ' BASE_DOMAIN: postgres-kysely.example.com' \
+ ' BASE_DOMAIN: acme-postgres.example.com'
+check "the repo slug" \
+ "$acme" package.json ' "name": "postgres-kysely",' \
+ ' "name": "acme-postgres",'
+check "the repo Terraform names the Supabase project and Hyperdrive config after" \
+ "$acme" intent.yaml ' repo: postgres-kysely' \
+ ' repo: acme-postgres'
+check "…and the one db-migrate carries" \
+ "$acme" infra/db-migrate/component.yaml ' repo: postgres-kysely' \
+ ' repo: acme-postgres'
+check "the fixture's Hyperdrive name follows it" \
+ "$acme" apps/web/wiring.fixture.json ' "hyperdrive_name": "stg-postgres-kysely-stage"' \
+ ' "hyperdrive_name": "stg-acme-postgres-stage"'
+check "a secret ref names the product's workspace and project" \
+ "$acme" infra/db-migrate/component.yaml \
+ ' SUPABASE_ACCESS_TOKEN: "secret://postgres-kysely/postgres-kysely/{{ .environment }}/SUPABASE_ACCESS_TOKEN"' \
+ ' SUPABASE_ACCESS_TOKEN: "secret://ws_79BDXAZQ/acme-postgres/{{ .environment }}/SUPABASE_ACCESS_TOKEN"'
+check "this repository's source link names the product's owner and repository" \
+ "$acme" apps/web/app/page.tsx 'href="https://github.com/sourceplane/postgres-kysely"' \
+ 'href="https://github.com/acme-inc/acme-postgres"'
+check "org-owned identity is not renamed" \
+ "$acme" intent.yaml 'apiVersion: sourceplane.io/v1 # mail ops@sourceplane.ai' \
+ 'apiVersion: sourceplane.io/v1 # mail ops@sourceplane.ai'
+
+echo "── rebrand: what is upstream's, or must never change"
+check "the upstream template's directory is upstream's" \
+ "$acme" apps/web/app/page.tsx 'href="https://github.com/vercel/examples/tree/main/storage/postgres-kysely"' \
+ 'href="https://github.com/vercel/examples/tree/main/storage/postgres-kysely"'
+check "…and so is its demo" \
+ "$acme" apps/web/README.md 'https://postgres-kysely.vercel.app/' \
+ 'https://postgres-kysely.vercel.app/'
+check "a migration is never rewritten (its checksum is in the manifest)" \
+ "$acme" packages/db/src/migrations/030_x/up.sql '-- postgres-kysely: a comment the checksum covers' \
+ '-- postgres-kysely: a comment the checksum covers'
+
+echo "── rebrand: a written value is not rewritten, in any later pass"
+contains='{"reponame":"postgres-kysely-2","productname":"Postgres on Cloudflare 2","productdomain":"postgres-kysely.example.com.au","githuborg":"sourceplane","subdomain":"your-workers-subdomain-2"}'
+check "a repo slug containing the baseline's slug survives three passes" \
+ "$contains" package.json ' "name": "postgres-kysely",' \
+ ' "name": "postgres-kysely-2",' 3
+check "a worker name built on it survives three passes" \
+ "$contains" apps/web/component.yaml 'workerName: postgres-kysely-web' \
+ 'workerName: postgres-kysely-2-web' 3
+check "a domain containing the baseline's domain survives three passes" \
+ "$contains" intent.yaml 'BASE_DOMAIN: postgres-kysely.example.com' \
+ 'BASE_DOMAIN: postgres-kysely.example.com.au' 3
+check "a subdomain containing the placeholder survives three passes" \
+ "$contains" apps/web/component.yaml 'workersDevSubdomain: your-workers-subdomain' \
+ 'workersDevSubdomain: your-workers-subdomain-2' 3
+check "a name containing the baseline's name survives three passes" \
+ "$contains" apps/web/lib/site.ts 'export const SITE_NAME = "Postgres on Cloudflare"' \
+ 'export const SITE_NAME = "Postgres on Cloudflare 2"' 3
+
+# --verify runs after every rebrand. Without the product's values it cannot
+# tell the product's own identity from a leftover; with them it can. A real
+# leftover must fail it either way.
+verify() { # NAME VALUES FILE CONTENT WANT(pass|fail) [--values]
+ local name="$1" values="$2" file="$3" content="$4" want="$5" withvalues="${6:-}" tmp got
+ tmp="$(mktemp -d)"
+ git -C "$tmp" init -q
+ mkdir -p "$tmp/$(dirname "$file")" "$tmp/.rebrand"
+ printf '%s\n' "$content" > "$tmp/$file"
+ printf '%s\n' "$values" > "$tmp/.rebrand/values.json"
+ git -C "$tmp" add -A
+ if (cd "$tmp" && node "$rebrand" --baseline-identity "$identity" --verify ${withvalues:+--values .rebrand/values.json} >/dev/null 2>&1); then got=pass; else got=fail; fi
+ rm -rf "$tmp"
+ if [ "$got" = "$want" ]; then echo " ok $name"; else echo " ✕ $name: --verify ${got}ed, want $want" >&2; fail=1; fi
+}
+echo "── rebrand --verify: the product's own identity is not residue"
+verify "given the values, a slug containing the baseline's passes" \
+ "$contains" package.json '"name": "postgres-kysely-2"' pass --values
+verify "without them it cannot know, and fails" \
+ "$contains" package.json '"name": "postgres-kysely-2"' fail
+verify "given the values, a real leftover still fails" \
+ "$acme" package.json '"name": "postgres-kysely"' fail --values
+verify "a leftover worker name fails" \
+ "$acme" apps/web/component.yaml 'workerName: postgres-kysely-web' fail --values
+verify "a leftover code identifier fails (no rule renames it — so nothing may spell it)" \
+ "$acme" apps/web/app/x.ts 'export class PostgresKysely {}' fail --values
+verify "the upstream template's links are not residue" \
+ "$acme" apps/web/app/page.tsx 'href="https://github.com/vercel/examples/tree/main/storage/postgres-kysely"' pass --values
+verify "a clean product passes" \
+ "$acme" package.json '"name": "acme-postgres"' pass --values
+
+echo "── rebrand: a residue it cannot rename fails the rebrand itself"
+tmp="$(mktemp -d)"; git -C "$tmp" init -q; mkdir -p "$tmp/.rebrand" "$tmp/apps/web"
+printf '%s\n' "$acme" > "$tmp/.rebrand/values.json"
+printf 'const x = "POSTGRES_KYSELY_TOKEN"\n' > "$tmp/apps/web/x.ts"
+git -C "$tmp" add -A
+if (cd "$tmp" && node "$rebrand" --baseline-identity "$identity" --values .rebrand/values.json --allow-dirty >/dev/null 2>&1); then
+ echo " ✕ an unrenamable env-var prefix passed the rebrand" >&2; fail=1
+else
+ echo " ok an unrenamable env-var prefix fails the rebrand, naming the file"
+fi
+rm -rf "$tmp"
+
+[ "$fail" -eq 0 ] || exit 1
+echo "rebrand.test.sh: ok"
diff --git a/testing/retouch.test.sh b/testing/retouch.test.sh
new file mode 100755
index 0000000..1ef5d69
--- /dev/null
+++ b/testing/retouch.test.sh
@@ -0,0 +1,199 @@
+#!/usr/bin/env bash
+# A RE-RUN PHASE HAS SOMETHING TO LAND.
+#
+# A phase's convergence can fail AFTER its PR merged, and the merge has already
+# put every file the phase places on main. orun derives phase state from the
+# files, so a retried build sees the phase placed and a forced re-run of it
+# lands an EMPTY diff — and the product's CI plans `--changed`, so a component
+# whose files did not change in the push does not deploy. The phase's `retouch`
+# hook (tooling/bootstrap/retouch.mjs) is what breaks that: one marker line at
+# the end of each affected component.yaml,
+#
+# # orun: redeploy
+#
+# replaced rather than accumulated, so the landing has a diff and exactly the
+# phase's components are in the changed set. The marker is a deploy trigger and
+# nothing reads it back; phase state stays derived, never stored.
+#
+# This drives the real retouch.mjs over a two-component tree, then checks that
+# every component the blueprint's retouch hooks name resolves in THIS tree —
+# the layout a product is placed with.
+# Needs: node. No network.
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+root="$(cd "$here/.." && pwd)"
+retouch="$root/tooling/bootstrap/retouch.mjs"
+
+command -v node >/dev/null || { echo "retouch.test.sh needs node" >&2; exit 1; }
+
+fail=0
+ok() { echo " ok $*"; }
+bad() { echo " ✕ $*" >&2; fail=1; }
+
+tmp="$(mktemp -d)"
+trap 'rm -rf "$tmp"' EXIT
+
+# A product tree with two components in two of the lanes the blueprint places
+# into, a test package that shares a directory name with the first (as
+# tests/ does with apps/) and must NOT be touched, and the
+# hand-written re-trigger line the fleet carried before this tool existed.
+mkdir -p "$tmp/apps/alpha" "$tmp/infra/beta" "$tmp/tests/alpha" "$tmp/node_modules/x"
+cat > "$tmp/apps/alpha/component.yaml" <<'Y'
+apiVersion: sourceplane.io/v1
+kind: Component
+metadata:
+ name: alpha
+spec:
+ type: cloudflare-worker-turbo
+ labels:
+ team: platform
+# ci: re-trigger deploy (batch A — runner-starvation recovery 20260622T115650Z)
+Y
+# No trailing newline on purpose: the tool must add one, and only one.
+printf 'apiVersion: sourceplane.io/v1\nkind: Component\nmetadata:\n name: beta\nspec:\n type: terraform' > "$tmp/infra/beta/component.yaml"
+printf 'kind: Component\nmetadata:\n name: alpha-tests\n' > "$tmp/tests/alpha/component.yaml"
+printf 'kind: Component\nmetadata:\n name: alpha\n' > "$tmp/node_modules/x/component.yaml"
+cp "$tmp/apps/alpha/component.yaml" "$tmp/alpha.orig"
+cp "$tmp/infra/beta/component.yaml" "$tmp/beta.orig"
+
+markers() { grep -c '^# orun: redeploy ' "$1" || true; }
+
+echo "── retouch: one marker, last, replaced not appended"
+(cd "$tmp" && ORUN_RUN_ID=run-one node "$retouch" --phase 04-workers --components alpha,beta) > "$tmp/one.log" 2>&1 \
+ || { bad "first run failed:"; sed 's/^/ /' "$tmp/one.log" >&2; }
+for f in apps/alpha infra/beta; do
+ [ "$(markers "$tmp/$f/component.yaml")" = 1 ] || bad "$f: $(markers "$tmp/$f/component.yaml") marker lines after one run, want 1"
+ [ "$(tail -n1 "$tmp/$f/component.yaml")" = "# orun: redeploy 04-workers run-one" ] \
+ || bad "$f: last line is '$(tail -n1 "$tmp/$f/component.yaml")'"
+done
+[ "$(tail -c1 "$tmp/infra/beta/component.yaml" | od -An -c | tr -d ' ')" = '\n' ] \
+ || bad "infra/beta: no trailing newline after retouch"
+ok "both components carry the marker as their last line"
+
+(cd "$tmp" && ORUN_RUN_ID=run-two node "$retouch" --phase 04-workers-restore --components alpha,beta) > "$tmp/two.log" 2>&1 \
+ || { bad "second run failed:"; sed 's/^/ /' "$tmp/two.log" >&2; }
+for f in apps/alpha infra/beta; do
+ [ "$(markers "$tmp/$f/component.yaml")" = 1 ] || bad "$f: $(markers "$tmp/$f/component.yaml") marker lines after two runs — the marker accumulated"
+ [ "$(tail -n1 "$tmp/$f/component.yaml")" = "# orun: redeploy 04-workers-restore run-two" ] \
+ || bad "$f: second run did not replace the marker: '$(tail -n1 "$tmp/$f/component.yaml")'"
+done
+grep -q 'replace marker' "$tmp/two.log" || bad "second run did not report a replacement"
+ok "a second run replaces the marker (a different phase's too) rather than appending"
+
+echo "── retouch: every other byte is as it was"
+if [ "$(head -n -1 "$tmp/apps/alpha/component.yaml" | cksum)" = "$(cksum < "$tmp/alpha.orig")" ]; then
+ ok "apps/alpha: the file above the marker is byte-for-byte the original"
+else
+ bad "apps/alpha: bytes above the marker changed"
+ diff <(head -n -1 "$tmp/apps/alpha/component.yaml") "$tmp/alpha.orig" >&2 || true
+fi
+if [ "$(head -n -1 "$tmp/infra/beta/component.yaml" | cksum)" = "$(printf '%s\n' "$(cat "$tmp/beta.orig")" | cksum)" ]; then
+ ok "infra/beta: only a newline was added before the marker"
+else
+ bad "infra/beta: bytes above the marker changed"
+fi
+grep -q '^# ci: re-trigger deploy' "$tmp/apps/alpha/component.yaml" \
+ && ok "the hand-written re-trigger line is left alone" \
+ || bad "the hand-written re-trigger line was removed"
+[ "$(cat "$tmp/tests/alpha/component.yaml")" = "$(printf 'kind: Component\nmetadata:\n name: alpha-tests\n')" ] \
+ && ok "tests/alpha (alpha-tests) was not touched — components resolve by metadata.name" \
+ || bad "tests/alpha was touched: a component is its metadata.name, not its directory name"
+
+echo "── retouch: the same stamp twice is a no-op"
+(cd "$tmp" && ORUN_RUN_ID=run-two node "$retouch" --phase 04-workers-restore --components alpha,beta) > "$tmp/again.log" 2>&1 \
+ || bad "idempotent re-run failed"
+grep -q 'nothing to do' "$tmp/again.log" && ok "re-running with the same stamp reports nothing to do" \
+ || bad "re-running with the same stamp did not report a no-op: $(tail -1 "$tmp/again.log")"
+
+echo "── retouch: the stamp"
+(cd "$tmp" && env -u ORUN_RUN_ID ORUN_SESSION_ID=sess-9 node "$retouch" --phase p --components beta) >/dev/null 2>&1
+[ "$(tail -n1 "$tmp/infra/beta/component.yaml")" = "# orun: redeploy p sess-9" ] \
+ && ok "ORUN_SESSION_ID stamps when ORUN_RUN_ID is unset" \
+ || bad "ORUN_SESSION_ID was not used: '$(tail -n1 "$tmp/infra/beta/component.yaml")'"
+(cd "$tmp" && env -u ORUN_RUN_ID -u ORUN_SESSION_ID node "$retouch" --phase p --components beta) >/dev/null 2>&1
+tail -n1 "$tmp/infra/beta/component.yaml" | grep -Eq '^# orun: redeploy p [0-9]{8}T[0-9]{6}Z$' \
+ && ok "with neither, a UTC timestamp" \
+ || bad "no timestamp stamp: '$(tail -n1 "$tmp/infra/beta/component.yaml")'"
+
+echo "── retouch: --dry-run writes nothing, --check names what is missing"
+before="$(cksum < "$tmp/apps/alpha/component.yaml")"
+(cd "$tmp" && ORUN_RUN_ID=dry node "$retouch" --phase p --components alpha --dry-run) > "$tmp/dry.log" 2>&1 \
+ || bad "--dry-run failed"
+[ "$before" = "$(cksum < "$tmp/apps/alpha/component.yaml")" ] && grep -q 'would replace marker' "$tmp/dry.log" \
+ && ok "--dry-run reports the change and leaves the file alone" \
+ || bad "--dry-run wrote, or did not say what it would do"
+
+if (cd "$tmp" && node "$retouch" --phase p --components alpha,gamma --check) > "$tmp/check.log" 2>&1; then
+ bad "--check passed with gamma absent"
+else
+ grep -q 'gamma' "$tmp/check.log" && ok "--check fails and names gamma" \
+ || bad "--check failed without naming the missing component: $(cat "$tmp/check.log")"
+fi
+if (cd "$tmp" && ORUN_RUN_ID=x node "$retouch" --phase p --components alpha,gamma) > "$tmp/miss.log" 2>&1; then
+ bad "a run with a missing component succeeded"
+else
+ [ "$(tail -n1 "$tmp/apps/alpha/component.yaml")" != "# orun: redeploy p x" ] \
+ && ok "a missing component refuses the whole run before any file is written" \
+ || bad "a missing component still wrote the components that exist"
+fi
+(cd "$tmp" && node "$retouch" --phase p --components alpha,beta --check) >/dev/null 2>&1 \
+ && ok "--check passes when every component resolves" || bad "--check failed on a complete set"
+
+echo "── retouch: --affects reads a task contract"
+cat > "$tmp/contract.yaml" <<'Y'
+# A contract, as .baseline/tasks/*.TaskContract.yaml are written.
+apiVersion: orun.io/v1
+kind: TaskContract
+spec:
+ goal: Two components converge
+ affects:
+ - alpha
+ # a comment between items
+ - beta
+ doneWhen:
+ - convergence green
+ gates: []
+Y
+(cd "$tmp" && ORUN_RUN_ID=via-contract node "$retouch" --phase 05-edge --affects contract.yaml) > "$tmp/aff.log" 2>&1 \
+ || { bad "--affects run failed:"; sed 's/^/ /' "$tmp/aff.log" >&2; }
+for f in apps/alpha infra/beta; do
+ [ "$(tail -n1 "$tmp/$f/component.yaml")" = "# orun: redeploy 05-edge via-contract" ] \
+ || bad "$f: --affects did not touch it"
+done
+grep -q '2 of 2' "$tmp/aff.log" && ok "spec.affects named both, and both were touched" \
+ || bad "--affects touched the wrong number: $(tail -1 "$tmp/aff.log")"
+printf 'spec:\n affects: [alpha, beta]\n' > "$tmp/flow.yaml"
+(cd "$tmp" && ORUN_RUN_ID=flow node "$retouch" --phase p --affects flow.yaml --check) >/dev/null 2>&1 \
+ && ok 'the flow form `affects: [a, b]` reads too' || bad "the flow form of affects did not read"
+printf 'spec:\n goal: nothing\n' > "$tmp/none.yaml"
+(cd "$tmp" && node "$retouch" --phase p --affects none.yaml --check) >/dev/null 2>&1 \
+ && bad "a contract with no affects passed --check" || ok "a contract with no affects refuses"
+
+# ── THE BLUEPRINT'S OWN HOOKS RESOLVE IN THIS TREE ─────────────────────────
+# Every `retouch` hook in repo-blueprint.yaml names the components a phase
+# redeploys, through a contract (.baseline/tasks/) or a list. A product is placed with this
+# repository's layout, so each must resolve here — a contract that names a
+# component nobody ships, or a component that moved, fails a real bootstrap at
+# the landing, an hour in. `{{ .baseline.dir }}` is this checkout.
+echo "── the blueprint's retouch hooks, against this tree"
+hooks=0
+while IFS= read -r line; do
+ hooks=$((hooks + 1))
+ argv="$(printf '%s' "$line" | sed -e 's/^[[:space:]]*run:[[:space:]]*//' \
+ -e "s#{{ \.baseline\.dir }}#$root#g" -e 's#{{ \.phase\.name }}#probe#g')"
+ if (cd "$root" && node -e '
+ const argv = JSON.parse(process.argv[1]);
+ const { spawnSync } = require("node:child_process");
+ const r = spawnSync(argv[0], [...argv.slice(1), "--check"], { stdio: ["ignore", "pipe", "pipe"] });
+ process.stdout.write(r.stdout); process.stderr.write(r.stderr);
+ process.exit(r.status ?? 1);
+ ' "$argv") > "$tmp/hook.log" 2>&1; then
+ ok "$(grep -c -- '->' "$tmp/hook.log") component(s): ${argv#*retouch.mjs\", }"
+ else
+ bad "a retouch hook does not resolve: $argv"; sed 's/^/ /' "$tmp/hook.log" >&2
+ fi
+done < <(grep -E '^\s*run: \[.*retouch\.mjs' "$root/repo-blueprint.yaml")
+[ "$hooks" -ge 1 ] || bad "only $hooks retouch hook(s) in repo-blueprint.yaml — 01-product lands the deployable product and needs one"
+
+[ "$fail" -eq 0 ] || exit 1
+echo "retouch.test.sh: ok"
diff --git a/tooling/bootstrap/dev-lanes.mjs b/tooling/bootstrap/dev-lanes.mjs
new file mode 100755
index 0000000..4684043
--- /dev/null
+++ b/tooling/bootstrap/dev-lanes.mjs
@@ -0,0 +1,114 @@
+#!/usr/bin/env node
+// The dev verify lanes stay off main's convergences while a product is being
+// bootstrapped (zero-dependency).
+//
+// intent.yaml activates `dev` on `github-push-main` as well as on pull
+// requests: every merge to main re-verifies every component (builds, tests)
+// on the dev rung beside the stage and prod deploys. That is the right rule
+// for a product that is live. During a bootstrap it proves nothing — the
+// content comes from a pinned baseline whose own CI already ran it, and
+// every phase's pull request is checked by `plan` alone — and it costs the
+// one thing a bootstrap's wall-clock is made of: runner slots. The product's
+// landing is a Next.js build per environment; a third, on the dev rung (with
+// the two test packages beside it), re-proves what the baseline's own CI
+// already proved and competes with stage and prod for the runner pool. (Measured on the Cirrus baseline,
+// where this tool comes from: dev took eight of eighteen lanes and stage and
+// prod got five each.)
+//
+// So 01-product defers the trigger and 02-docs, the last landing, puts it
+// back, exactly as tooling/bootstrap/promotion.mjs does for prod's gate:
+//
+// node tooling/bootstrap/dev-lanes.mjs --defer # 01-product, before the first landing
+// node tooling/bootstrap/dev-lanes.mjs --restore # 02-docs, the last landing
+// node tooling/bootstrap/dev-lanes.mjs --check # prints deferred | active
+//
+// --defer replaces dev's `- github-push-main` trigger line with one marker
+// comment that base64-encodes the exact text removed, so --restore
+// reproduces intent.yaml byte-for-byte. Both are idempotent. Pull requests
+// keep their dev lanes throughout: only the push-to-main activation moves.
+//
+// The trigger is deferred, never dropped: a bootstrap that stops before
+// 02-docs leaves the marker in intent.yaml, and `--restore` (or a re-run of
+// 02-docs) is the whole fix.
+import * as fs from "node:fs";
+
+const FILE = process.argv.includes("--file")
+ ? process.argv[process.argv.indexOf("--file") + 1]
+ : "intent.yaml";
+const MARKER = "@dev-lanes-deferred";
+const TRIGGER = "github-push-main";
+
+function usage() {
+ console.error("usage: dev-lanes.mjs --defer | --restore | --check [--file intent.yaml]");
+ process.exit(2);
+}
+
+// The `- github-push-main` line under environments.dev.activation.triggerRefs.
+function findDevPushTrigger(text) {
+ const lines = text.split("\n");
+ let inEnvs = false;
+ let devIndent = -1;
+ let inDev = false;
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ if (/^environments:\s*$/.test(line)) {
+ inEnvs = true;
+ continue;
+ }
+ if (!inEnvs) continue;
+ if (/^\S/.test(line) && line.trim() !== "") break; // left the section
+ const env = /^(\s+)([A-Za-z0-9_-]+):\s*$/.exec(line);
+ if (env && (devIndent < 0 || env[1].length <= devIndent)) {
+ inDev = env[2] === "dev";
+ if (inDev) devIndent = env[1].length;
+ continue;
+ }
+ if (!inDev) continue;
+ if (new RegExp(`^\\s+-\\s+${TRIGGER}\\s*$`).test(line)) return { lines, index: i };
+ }
+ return { lines, index: -1 };
+}
+
+function defer() {
+ const text = fs.readFileSync(FILE, "utf8");
+ if (text.includes(`# ${MARKER}:`)) {
+ console.log(`dev-lanes --defer: already deferred in ${FILE}`);
+ return;
+ }
+ const { lines, index } = findDevPushTrigger(text);
+ if (index < 0) {
+ console.log(`dev-lanes --defer: dev is not activated on ${TRIGGER} in ${FILE} — nothing to defer`);
+ return;
+ }
+ const original = lines[index];
+ const indent = /^(\s*)/.exec(original)[1];
+ const b64 = Buffer.from(original, "utf8").toString("base64");
+ const marker = `${indent}# ${MARKER}:${b64} (tooling/bootstrap/dev-lanes.mjs --restore puts it back)`;
+ const out = [...lines.slice(0, index), marker, ...lines.slice(index + 1)].join("\n");
+ fs.writeFileSync(FILE, out);
+ console.log(`dev-lanes --defer: dev's verify lanes stay off main's convergences until --restore (${FILE})`);
+}
+
+function restore() {
+ const text = fs.readFileSync(FILE, "utf8");
+ const re = new RegExp(`^[ \\t]*# ${MARKER}:([A-Za-z0-9+/=]+) \\(tooling/bootstrap/dev-lanes\\.mjs --restore puts it back\\)$`, "m");
+ const m = re.exec(text);
+ if (!m) {
+ console.log(`dev-lanes --restore: nothing deferred in ${FILE}`);
+ return;
+ }
+ const original = Buffer.from(m[1], "base64").toString("utf8");
+ fs.writeFileSync(FILE, text.slice(0, m.index) + original + text.slice(m.index + m[0].length));
+ console.log(`dev-lanes --restore: dev verifies every merge to main again (${FILE})`);
+}
+
+function check() {
+ const text = fs.readFileSync(FILE, "utf8");
+ console.log(text.includes(`# ${MARKER}:`) ? "deferred" : "active");
+}
+
+const mode = process.argv[2];
+if (mode === "--defer") defer();
+else if (mode === "--restore") restore();
+else if (mode === "--check") check();
+else usage();
diff --git a/tooling/bootstrap/promotion.mjs b/tooling/bootstrap/promotion.mjs
new file mode 100644
index 0000000..ec8f4f5
--- /dev/null
+++ b/tooling/bootstrap/promotion.mjs
@@ -0,0 +1,123 @@
+#!/usr/bin/env node
+// Stage and prod deploy side by side while a product is being bootstrapped
+// (zero-dependency).
+//
+// intent.yaml gates prod behind stage: `environments.prod.promotion.dependsOn:
+// [stage]`, which orun plans as an in-run edge from every prod job to the
+// same component's stage job. That is the right rule for a product that is
+// live — a change reaches prod only after it deployed to stage. During a
+// bootstrap it protects nothing (both environments are empty, and every phase
+// is watched to green before the next one starts) and it doubles the length
+// of every convergence: each worker's prod deploy waits out its stage deploy.
+//
+// So 01-product defers the gate and 02-docs, the last landing, puts it back:
+//
+// node tooling/bootstrap/promotion.mjs --defer # 01-product, before the first landing
+// node tooling/bootstrap/promotion.mjs --restore # 02-docs, the last landing
+// node tooling/bootstrap/promotion.mjs --check # prints deferred | enforced
+//
+// --defer replaces the prod `promotion:` block with one marker comment that
+// base64-encodes the exact text removed, so --restore reproduces intent.yaml
+// byte-for-byte. Both are idempotent. Restoring is a change to intent.yaml's
+// `environments` section only, which `orun plan --changed` (intent impact
+// `watch`, the default) maps to no component: the landing that restores it
+// deploys nothing.
+//
+// The gate is deferred, never dropped: a bootstrap that stops before 02-docs
+// leaves the marker in intent.yaml, and `--restore` (or a re-run of 02-docs)
+// is the whole fix. docs/phases/02-docs.md says so.
+
+import * as fs from "node:fs";
+
+const FILE = process.argv.includes("--file")
+ ? process.argv[process.argv.indexOf("--file") + 1]
+ : "intent.yaml";
+const MARKER = "@promotion-deferred";
+
+function usage() {
+ console.error("usage: promotion.mjs --defer | --restore | --check [--file intent.yaml]");
+ process.exit(2);
+}
+
+// The `promotion:` block of the `prod:` environment: from its `promotion:`
+// line up to (not including) the next line indented at or above it.
+function findProdPromotion(text) {
+ const lines = text.split("\n");
+ let inEnvs = false;
+ let prodIndent = -1;
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ if (/^environments:\s*$/.test(line)) {
+ inEnvs = true;
+ continue;
+ }
+ if (!inEnvs) continue;
+ if (/^\S/.test(line) && line.trim() !== "") break; // left the section
+ const prod = /^(\s+)prod:\s*$/.exec(line);
+ if (prod) {
+ prodIndent = prod[1].length;
+ continue;
+ }
+ if (prodIndent < 0) continue;
+ const indent = line.length - line.trimStart().length;
+ if (line.trim() !== "" && indent <= prodIndent) {
+ prodIndent = -1; // left prod without finding one
+ continue;
+ }
+ const m = /^(\s+)promotion:\s*$/.exec(line);
+ if (!m) continue;
+ const own = m[1].length;
+ let end = i + 1;
+ while (end < lines.length) {
+ const l = lines[end];
+ if (l.trim() !== "" && l.length - l.trimStart().length <= own) break;
+ end++;
+ }
+ return { lines, start: i, end, indent: m[1] };
+ }
+ return null;
+}
+
+function defer() {
+ const text = fs.readFileSync(FILE, "utf8");
+ if (text.includes(MARKER)) {
+ console.log(`promotion --defer: already deferred in ${FILE}`);
+ return;
+ }
+ const found = findProdPromotion(text);
+ if (!found) {
+ console.log(`promotion --defer: prod has no promotion block in ${FILE} — nothing to defer`);
+ return;
+ }
+ const { lines, start, end, indent } = found;
+ const removed = lines.slice(start, end).join("\n");
+ const b64 = Buffer.from(removed, "utf8").toString("base64");
+ const marker = `${indent}# ${MARKER}:${b64} (tooling/bootstrap/promotion.mjs --restore puts it back)`;
+ const out = [...lines.slice(0, start), marker, ...lines.slice(end)].join("\n");
+ fs.writeFileSync(FILE, out);
+ console.log(`promotion --defer: prod no longer waits on stage until --restore (${FILE})`);
+}
+
+function restore() {
+ const text = fs.readFileSync(FILE, "utf8");
+ const re = new RegExp(`^[ \\t]*# ${MARKER}:([A-Za-z0-9+/=]+).*$`, "m");
+ const m = re.exec(text);
+ if (!m) {
+ console.log(`promotion --restore: nothing deferred in ${FILE}`);
+ return;
+ }
+ const original = Buffer.from(m[1], "base64").toString("utf8");
+ fs.writeFileSync(FILE, text.slice(0, m.index) + original + text.slice(m.index + m[0].length));
+ console.log(`promotion --restore: prod waits on stage again (${FILE})`);
+}
+
+function check() {
+ const text = fs.readFileSync(FILE, "utf8");
+ console.log(text.includes(MARKER) ? "deferred" : "enforced");
+}
+
+const mode = process.argv[2];
+if (mode === "--defer") defer();
+else if (mode === "--restore") restore();
+else if (mode === "--check") check();
+else usage();
diff --git a/tooling/bootstrap/retouch.mjs b/tooling/bootstrap/retouch.mjs
new file mode 100644
index 0000000..c31e99a
--- /dev/null
+++ b/tooling/bootstrap/retouch.mjs
@@ -0,0 +1,254 @@
+#!/usr/bin/env node
+// Give a re-run phase something to land (zero-dependency).
+//
+// A phase lands as a pull request and is verified by the convergence run that
+// follows the merge. When that convergence FAILS — a provider error, a runner
+// starved out, a smoke that raced route propagation past its retries — the
+// merge has already happened, so every file the phase places is on main. orun
+// derives phase state from the files on disk (never from a stored record), so
+// a retried build finds the phase placed, and even a forced re-run of it
+// produces an EMPTY diff: `orun.pr/land@v1` has nothing to commit, and the
+// product's CI (`orun plan --changed`) deploys a component only when one of
+// its files changed in the push. Nothing lands, nothing redeploys, and the
+// operator is told the phase is fine.
+//
+// This tool is what the phase's `retouch` hook runs before it stages and
+// lands: for each component the phase deploys, it rewrites ONE trailing line
+// in that component's `component.yaml`,
+//
+// # orun: redeploy
+//
+// replacing the previous marker if there is one (never accumulating), so the
+// landing has a diff and exactly those components are in the changed set. The
+// same convention was hand-edited before this existed (`# ci: re-trigger
+// deploy …` lines, duplicated by hand); this is that edit with a name, a
+// stamp, and a phase to answer for it.
+//
+// THE MARKER IS A DEPLOY TRIGGER, NOT STATE. Nothing reads it back: orun does
+// not learn from it whether a phase ran, and this repository's invariant —
+// phase state is DERIVED from the tree, never stored in it — holds. Delete the
+// line and nothing is lost but the next redeploy's reason to happen.
+//
+// node retouch.mjs --phase 01-product --affects .baseline/tasks/01-product.TaskContract.yaml
+// node retouch.mjs --phase 01-product --components web,db-migrate
+//
+// Options:
+// --phase the phase the marker names (required)
+// --components a,b,c the components to touch, by `metadata.name` …
+// --affects … or read them from a TaskContract's `spec.affects`
+// --check resolve every component and exit non-zero naming
+// any without a component.yaml; write nothing
+// --dry-run print what would change; write nothing
+//
+// The stamp is ORUN_RUN_ID if set, else ORUN_SESSION_ID, else a UTC timestamp
+// (YYYYMMDDTHHMMSSZ) — whichever identifies the run that asked for the deploy.
+//
+// Runs in the product checkout (the phase hooks' working directory). A
+// component is found by the `metadata.name` its component.yaml declares, not
+// by directory: `apps/web` and `tests/web` both carry one, and only the
+// first is named `web`.
+
+import * as fs from "node:fs";
+import * as path from "node:path";
+
+const MARKER_RE = /^# orun: redeploy \S+ \S+\r?$/;
+const SKIP_DIRS = new Set(["node_modules", ".git", ".orun", "dist", ".next", ".open-next", ".turbo"]);
+const MAX_DEPTH = 4;
+
+function usage(msg) {
+ if (msg) console.error(`retouch: ${msg}`);
+ console.error(
+ "usage: retouch.mjs --phase (--components a,b,c | --affects ) [--check] [--dry-run]",
+ );
+ process.exit(2);
+}
+
+function parseArgs(argv) {
+ const opts = { phase: null, components: null, affects: null, check: false, dryRun: false };
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ const next = () => {
+ if (i + 1 >= argv.length) usage(`${a} needs a value`);
+ return argv[++i];
+ };
+ if (a === "--phase") opts.phase = next();
+ else if (a === "--components") opts.components = next();
+ else if (a === "--affects") opts.affects = next();
+ else if (a === "--check") opts.check = true;
+ else if (a === "--dry-run") opts.dryRun = true;
+ else if (a === "-h" || a === "--help") usage();
+ else usage(`unknown argument ${a}`);
+ }
+ if (!opts.phase) usage("--phase is required");
+ if (/\s/.test(opts.phase)) usage("--phase must be a single token");
+ if (!opts.components && !opts.affects) usage("one of --components or --affects is required");
+ if (opts.components && opts.affects) usage("--components and --affects are exclusive");
+ return opts;
+}
+
+// `spec.affects` from a TaskContract, with a reader small enough to need no
+// YAML dependency: the contracts are a flat mapping with one block sequence.
+// Accepts the block form (`affects:` then `- name` lines indented under it)
+// and the flow form (`affects: [a, b]`).
+function readAffects(file) {
+ let text;
+ try {
+ text = fs.readFileSync(file, "utf8");
+ } catch (e) {
+ console.error(`retouch: cannot read ${file}: ${e.message}`);
+ process.exit(1);
+ }
+ const lines = text.split(/\r?\n/);
+ const names = [];
+ for (let i = 0; i < lines.length; i++) {
+ const m = /^(\s*)affects:\s*(.*?)\s*$/.exec(lines[i]);
+ if (!m) continue;
+ const indent = m[1].length;
+ const inline = m[2].replace(/\s+#.*$/, "");
+ if (inline.startsWith("[")) {
+ const body = inline.replace(/^\[/, "").replace(/\]\s*$/, "");
+ for (const part of body.split(",")) {
+ const v = part.trim().replace(/^["']|["']$/g, "");
+ if (v) names.push(v);
+ }
+ break;
+ }
+ for (let j = i + 1; j < lines.length; j++) {
+ const line = lines[j];
+ if (/^\s*(#.*)?$/.test(line)) continue;
+ const lead = /^(\s*)/.exec(line)[1].length;
+ if (lead <= indent) break;
+ const item = /^\s*-\s*(.+?)\s*$/.exec(line);
+ if (!item) break;
+ names.push(item[1].replace(/\s+#.*$/, "").replace(/^["']|["']$/g, ""));
+ }
+ break;
+ }
+ if (names.length === 0) {
+ console.error(`retouch: ${file} declares no spec.affects — nothing to touch`);
+ process.exit(1);
+ }
+ return names;
+}
+
+// `metadata.name` from a component.yaml, read the same minimal way.
+function componentName(file) {
+ const lines = fs.readFileSync(file, "utf8").split(/\r?\n/);
+ for (let i = 0; i < lines.length; i++) {
+ const m = /^(\s*)metadata:\s*$/.exec(lines[i]);
+ if (!m) continue;
+ const indent = m[1].length;
+ for (let j = i + 1; j < lines.length; j++) {
+ const line = lines[j];
+ if (/^\s*(#.*)?$/.test(line)) continue;
+ const lead = /^(\s*)/.exec(line)[1].length;
+ if (lead <= indent) break;
+ const nm = /^\s*name:\s*(.+?)\s*$/.exec(line);
+ if (nm && lead === indent + 2) return nm[1].replace(/^["']|["']$/g, "");
+ }
+ }
+ return null;
+}
+
+// Every component.yaml in the tree, by the name it declares.
+function indexComponents(root) {
+ const byName = new Map();
+ const walk = (dir, depth) => {
+ let entries;
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const ent of entries) {
+ const full = path.join(dir, ent.name);
+ if (ent.isDirectory()) {
+ if (SKIP_DIRS.has(ent.name) || depth >= MAX_DEPTH) continue;
+ walk(full, depth + 1);
+ } else if (ent.name === "component.yaml") {
+ const name = componentName(full);
+ if (!name) continue;
+ const rel = path.relative(root, full);
+ if (byName.has(name)) {
+ console.error(
+ `retouch: two component.yaml files declare metadata.name ${name}: ${byName.get(name)} and ${rel}`,
+ );
+ process.exit(1);
+ }
+ byName.set(name, rel);
+ }
+ }
+ };
+ walk(root, 0);
+ return byName;
+}
+
+function stamp() {
+ for (const key of ["ORUN_RUN_ID", "ORUN_SESSION_ID"]) {
+ const v = (process.env[key] || "").trim();
+ if (v) return v.replace(/\s+/g, "-");
+ }
+ return new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
+}
+
+// The file with exactly one marker line, last, and a trailing newline. Every
+// other byte is kept as it was.
+function retouched(text, marker) {
+ const hadTrailingNewline = text.endsWith("\n");
+ const lines = text.split("\n");
+ if (hadTrailingNewline) lines.pop();
+ const kept = lines.filter((l) => !MARKER_RE.test(l));
+ // A file that was only a marker, or empty, still ends up valid.
+ const body = kept.length ? kept.join("\n") + "\n" : "";
+ return body + marker + "\n";
+}
+
+function main() {
+ const opts = parseArgs(process.argv.slice(2));
+ const root = process.cwd();
+ const wanted = opts.components
+ ? opts.components.split(",").map((s) => s.trim()).filter(Boolean)
+ : readAffects(opts.affects);
+ if (wanted.length === 0) usage("no components named");
+
+ const index = indexComponents(root);
+ const missing = wanted.filter((n) => !index.has(n));
+ if (missing.length) {
+ console.error(
+ `retouch: no component.yaml declares metadata.name for: ${missing.join(", ")} (looked under ${root})`,
+ );
+ process.exit(1);
+ }
+ if (opts.check) {
+ for (const n of wanted) console.log(`retouch --check: ${n} -> ${index.get(n)}`);
+ console.log(`retouch --check: ${wanted.length} component(s) resolve.`);
+ return;
+ }
+
+ const marker = `# orun: redeploy ${opts.phase} ${stamp()}`;
+ const verb = opts.dryRun ? "would" : "";
+ let changed = 0;
+ for (const n of wanted) {
+ const rel = index.get(n);
+ const file = path.join(root, rel);
+ const before = fs.readFileSync(file, "utf8");
+ const after = retouched(before, marker);
+ const had = before.split("\n").some((l) => MARKER_RE.test(l));
+ if (after === before) {
+ console.log(`retouch: ${rel}: unchanged (marker already ${marker.slice(2)})`);
+ continue;
+ }
+ if (!opts.dryRun) fs.writeFileSync(file, after);
+ changed++;
+ console.log(`retouch: ${rel}: ${verb ? "would " : ""}${had ? "replace" : "add"} marker`);
+ }
+ console.log(
+ opts.dryRun
+ ? `retouch --dry-run: ${changed} of ${wanted.length} file(s) would change; nothing written.`
+ : changed > 0
+ ? `retouch: ${changed} of ${wanted.length} component.yaml file(s) marked "${marker.slice(2)}" — the landing has a diff.`
+ : `retouch: nothing to do (every marker already current).`,
+ );
+}
+
+main();
diff --git a/tooling/bootstrap/work-tree.mjs b/tooling/bootstrap/work-tree.mjs
new file mode 100644
index 0000000..ad48ba6
--- /dev/null
+++ b/tooling/bootstrap/work-tree.mjs
@@ -0,0 +1,73 @@
+#!/usr/bin/env node
+// A product carries no work tree of the baseline's (zero-dependency).
+//
+// This repository's intent.yaml declares where ITS work lives:
+//
+// work:
+// epics: specs/epics
+// tasks: tasks
+// sync: on-merge
+//
+// and `orun plan` on main reconciles that tree into the workspace's work
+// plane. A product built from this baseline has neither directory — `specs/` and
+// `tasks/` are the factory's, and the leak gate keeps them out — and its
+// bootstrap work is opened on the platform by the build itself. Left in, the
+// block would point the product's every plan at two directories that do not
+// exist.
+//
+// So 01-product removes it from the product's copy, before the first landing:
+//
+// node tooling/bootstrap/work-tree.mjs --strip # 01-product
+// node tooling/bootstrap/work-tree.mjs --check # prints declared | absent
+//
+// The block removed is the top-level `work:` key with everything indented
+// under it, and the comment lines directly above it that belong to it. It is
+// not put back: a product that wants a work tree declares its own. Idempotent.
+import * as fs from "node:fs";
+
+const FILE = process.argv.includes("--file")
+ ? process.argv[process.argv.indexOf("--file") + 1]
+ : "intent.yaml";
+
+function usage() {
+ console.error("usage: work-tree.mjs --strip | --check [--file intent.yaml]");
+ process.exit(2);
+}
+
+function findWork(lines) {
+ const start = lines.findIndex((l) => /^work:\s*(#.*)?$/.test(l));
+ if (start < 0) return null;
+ let end = start + 1;
+ while (end < lines.length && (lines[end].trim() === "" || /^\s/.test(lines[end]))) end++;
+ // Trailing blank lines belong to the gap before the next key, not the block.
+ while (end > start + 1 && lines[end - 1].trim() === "") end--;
+ // Its own comment: the contiguous `#` lines directly above it.
+ let from = start;
+ while (from > 0 && /^#/.test(lines[from - 1])) from--;
+ return { from, end };
+}
+
+function strip() {
+ const text = fs.readFileSync(FILE, "utf8");
+ const lines = text.split("\n");
+ const found = findWork(lines);
+ if (!found) {
+ console.log(`work-tree --strip: ${FILE} declares no work tree — nothing to do`);
+ return;
+ }
+ let { from, end } = found;
+ // Drop one of the blank lines that separated it from its neighbours.
+ if (end < lines.length && lines[end].trim() === "" && from > 0 && lines[from - 1].trim() === "") end++;
+ fs.writeFileSync(FILE, [...lines.slice(0, from), ...lines.slice(end)].join("\n"));
+ console.log(`work-tree --strip: removed the baseline's work tree from ${FILE}`);
+}
+
+function check() {
+ const lines = fs.readFileSync(FILE, "utf8").split("\n");
+ console.log(findWork(lines) ? "declared" : "absent");
+}
+
+const mode = process.argv[2];
+if (mode === "--strip") strip();
+else if (mode === "--check") check();
+else usage();
diff --git a/tooling/rebrand/rebrand.mjs b/tooling/rebrand/rebrand.mjs
new file mode 100644
index 0000000..9b9251f
--- /dev/null
+++ b/tooling/rebrand/rebrand.mjs
@@ -0,0 +1,488 @@
+#!/usr/bin/env node
+// Rebrand renamer for the postgres-kysely baseline (zero-dependency).
+//
+// This repository is a baseline: a product is instantiated from it, branded,
+// and deployed as somebody's own. This script rewrites every *instance
+// identity* literal in the product tree — repo slug (the intent, the secret
+// project, the Supabase project and Hyperdrive config names Terraform derives
+// from it), the product's display name, the product domain, Cloudflare worker
+// resource names (so an instance is account-safe even when it shares an
+// account with another), the workers.dev subdomain placeholder — to the values
+// in a values file, and leaves *org-owned* identity alone (the orun state
+// backend, the `sourceplane.io` manifest apiVersion, company mailboxes) and
+// the UPSTREAM template's own identity too (its directory in vercel/examples
+// and its demo, which the page's "Source" link and the app's README name:
+// they say where the code came from, not this product).
+//
+// The engine is Cirrus's (sourceplane/cirrus-baseline tooling/rebrand): the
+// FROM side declared in `.baseline/identity.json`, every written value held
+// opaque until the last rule has run, and a leftover sweep that fails on any
+// identity a rule did not rename. The rules are this tree's.
+//
+// Usage (from the product root, on a git tree with the files staged):
+// node tooling/rebrand/rebrand.mjs --values .rebrand/values.json [--dry-run] [--allow-dirty]
+// node tooling/rebrand/rebrand.mjs --verify [--values .rebrand/values.json]
+//
+// Values file (see tooling/rebrand/values.example.json):
+// {
+// "reponame": "acme-postgres", // required — repo slug
+// "productname": "Acme Cloud", // required — the product's display name
+// "productdomain": "acme.dev", // optional — default .example.com (set later)
+// "githuborg": "acme-inc", // owner of the product repo (source link in docs)
+// "brandSlug": "acme", // default: reponame — worker name prefix
+// "subdomain": "acme", // default: your-workers-subdomain
+// "orunWorkspace": "ws_XXXXXXXX", // the segment secret refs name
+// "orunWorkspaceSlug": "acme-space" // optional: wins over orunWorkspace there
+// }
+//
+// Modes:
+// (default) apply the rename map in place, then run the leftover sweep
+// --dry-run report per-rule match counts; change nothing
+// --verify only run the leftover sweep (non-zero exit on residue)
+
+import { execFileSync } from "node:child_process";
+import * as fs from "node:fs";
+import * as path from "node:path";
+import { fileURLToPath } from "node:url";
+
+// ── Inputs ─────────────────────────────────────────────────────
+
+function flag(name) {
+ return process.argv.includes(`--${name}`);
+}
+function arg(name) {
+ const i = process.argv.indexOf(`--${name}`);
+ return i >= 0 ? process.argv[i + 1] : undefined;
+}
+
+const dryRun = flag("dry-run");
+const verifyOnly = flag("verify");
+
+let values = {};
+// --verify takes --values too, optionally: without them it cannot tell the
+// product's own identity from a leftover of the baseline's.
+const valuesPath = arg("values");
+if (!verifyOnly && !valuesPath) {
+ console.error("usage: rebrand.mjs --values [--dry-run] | --verify [--values ]");
+ process.exit(2);
+}
+if (valuesPath) {
+ values = JSON.parse(fs.readFileSync(valuesPath, "utf8"));
+ for (const required of ["reponame", "productname"]) {
+ if (typeof values[required] !== "string" || values[required].length === 0) {
+ console.error(`rebrand: values file is missing required field "${required}"`);
+ process.exit(2);
+ }
+ }
+}
+
+// ── THE BASELINE'S OWN IDENTITY — the FROM side, declared ──────
+//
+// Read from `.baseline/identity.json` beside THIS SCRIPT, not the working
+// directory: the rebrand runs with its cwd set to the PRODUCT being branded,
+// and a product does not carry `.baseline/` (no module places it). The phase
+// hooks invoke this as `node {{ .baseline.dir }}/tooling/rebrand/rebrand.mjs`,
+// so the script's own path is the one thing that always points at the
+// baseline. `--baseline-identity ` overrides it (the test suite pins one).
+//
+// slug the repo slug: intent name, worker prefix, secret project,
+// the `repo` Terraform names the Supabase project after
+// pascal the code-identifier form (swept for, never expected)
+// productName the display name, as the SITE_NAME seam spells it
+// domain the product domain (BASE_DOMAIN)
+// subdomain the workers.dev subdomain this tree carries
+// githubOwner the owner in this repository's source link
+const BASELINE_IDENTITY_FILE =
+ arg("baseline-identity") ??
+ path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".baseline", "identity.json");
+const BASELINE_DEFAULTS = {
+ slug: "postgres-kysely",
+ pascal: "PostgresKysely",
+ productName: "Postgres on Cloudflare",
+ domain: "postgres-kysely.example.com",
+ subdomain: "your-workers-subdomain",
+ githubOwner: "sourceplane",
+};
+const baseline = (() => {
+ let declared = {};
+ try {
+ declared = JSON.parse(fs.readFileSync(BASELINE_IDENTITY_FILE, "utf8"));
+ } catch {
+ declared = {}; // absent is fine: the defaults ARE this baseline's identity
+ }
+ const id = { ...BASELINE_DEFAULTS };
+ for (const k of Object.keys(BASELINE_DEFAULTS)) {
+ if (declared[k] !== undefined) id[k] = declared[k];
+ }
+ for (const [k, v] of Object.entries(id)) {
+ if (typeof v !== "string" || v.length === 0) {
+ console.error(`rebrand: ${BASELINE_IDENTITY_FILE} field "${k}" must be a non-empty string`);
+ process.exit(2);
+ }
+ }
+ if (/[^a-z0-9-]/.test(id.slug)) {
+ console.error(`rebrand: ${BASELINE_IDENTITY_FILE} "slug" must be a lowercase slug ([a-z0-9-])`);
+ process.exit(2);
+ }
+ return { ...id, envPrefix: id.slug.toUpperCase().replace(/-/g, "_") };
+})();
+// Regex-escape, for the rules that build a pattern out of the identity.
+const rx = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+
+// All fields are unused under --verify; the fallbacks keep derivation total.
+const reponame = values.reponame ?? "";
+const productname = values.productname ?? "";
+// The domain is NOT ASKED at bootstrap: a product goes live on workers.dev and
+// an owner sets a domain later. Until then the reserved placeholder
+// `.example.com` (RFC 2606 — it can never be someone else's) stands
+// wherever the domain goes, so setting it is replacing one string.
+const productdomain = (values.productdomain ?? "").trim() || (reponame ? `${reponame}.example.com` : "");
+const githuborg = (values.githuborg ?? "").trim() || baseline.githubOwner;
+const brandSlug = (values.brandSlug ?? "").trim() || reponame;
+const subdomain = (values.subdomain ?? "").trim() || "your-workers-subdomain";
+// A `secret://///` ref names the WORKSPACE first
+// and the project (repo) second. The workspace segment is the product's
+// workspace — an explicit slug if one was given, else the ws_… id itself
+// (the platform's resolve accepts a slug, a public id or a ws_ ref) — and the
+// repo name only as the last resort when no workspace was given at all.
+const orunWorkspaceSlug = (() => {
+ const explicit = (values.orunWorkspaceSlug ?? "").trim();
+ if (explicit) return explicit;
+ const ws = (values.orunWorkspace ?? "").trim();
+ if (ws) return ws;
+ return reponame;
+})();
+
+if (!verifyOnly && /[^a-z0-9-]/.test(`${reponame}${brandSlug}`)) {
+ console.error("rebrand: reponame/brandSlug must be lowercase slugs ([a-z0-9-])");
+ process.exit(2);
+}
+if (!verifyOnly && /[^A-Za-z0-9-]/.test(githuborg)) {
+ console.error("rebrand: githuborg must be a GitHub owner name ([A-Za-z0-9-])");
+ process.exit(2);
+}
+
+// In-place rewrite of the whole tree: insist on a clean checkout so the
+// result is reviewable as one diff (and trivially revertible).
+if (!verifyOnly && !dryRun && !flag("allow-dirty")) {
+ const status = execFileSync("git", ["status", "--porcelain"], { encoding: "utf8" });
+ if (status.trim().length > 0) {
+ console.error("rebrand: working tree is not clean — commit/stash first (or pass --allow-dirty)");
+ process.exit(2);
+ }
+}
+
+// ── File set ───────────────────────────────────────────────────
+
+// Tracked text files only. Exclusions are generated/locked artifacts, this
+// tool and the identity it reads, and binary content.
+const EXCLUDE_RE = new RegExp(
+ [
+ "^tooling/rebrand/",
+ "^\\.rebrand/",
+ // The baseline's declared identity. Renaming its contents would make the
+ // product claim to be a baseline called by the product's own name.
+ "^\\.baseline/",
+ "^pnpm-lock\\.yaml$",
+ // Migrations are immutable once applied: db-migrate compares each file's
+ // sha256 to packages/db/src/manifest.ts and to the database's ledger, so
+ // a byte renamed here would stop every later deploy. (None names this
+ // baseline's identity; packages/db's tests hold their checksums.)
+ "^packages/db/src/migrations/",
+ "\\.(png|jpg|jpeg|ico|gif|webp|woff2?|ttf|eot)$",
+ ].join("|"),
+);
+
+function trackedFiles() {
+ return execFileSync("git", ["ls-files"], { encoding: "utf8" })
+ .split("\n")
+ .filter((f) => f.length > 0 && !EXCLUDE_RE.test(f))
+ .filter((f) => {
+ // `git ls-files` also lists gitlinks (a grounded sandbox checkout carries
+ // `baseline/` as one) and paths deleted from disk. Only regular files
+ // are sweepable.
+ try {
+ return fs.statSync(f).isFile();
+ } catch {
+ return false;
+ }
+ });
+}
+
+// ── The upstream template's identity (never rewritten) ─────────
+//
+// This tree IS Vercel's Postgres + Kysely Next.js Starter, whose own name
+// (`postgres-kysely`) is this baseline's slug. Where the code names its
+// upstream — the page's "Source" link and its sibling demos, the app's README —
+// the name is the upstream's, and the repo-slug rule WOULD rewrite it: a
+// product's visitors would be pointed at a vercel/examples directory that does
+// not exist. So it is protected (masked before the rules run, restored after),
+// and allowed by the leftover sweep too.
+const UPSTREAM = [
+ /github\.com\/vercel\/examples\/tree\/main\/storage\/postgres-kysely\b/g, // the template's directory
+ /postgres-kysely\.vercel\.app\b/g, // its demo
+];
+
+// ── Protected literals (org-owned identity, never rewritten) ───
+//
+// Masked before the rules run and restored after, so no rename can touch the
+// org's shared infrastructure identity.
+const PROTECTED = [
+ /https:\/\/orun-api\.sourceplane\.ai/g, // orun state backend
+ /sourceplane\.io/g, // manifest apiVersion, owned by the orun tooling
+ /[A-Za-z0-9._%+-]+@sourceplane\.ai/g, // company mailboxes
+ ...UPSTREAM,
+];
+const MASK = (i, j) => `\u0000REBRAND_PROTECTED_${i}_${j}\u0000`;
+
+// ── Substituted values are opaque ──────────────────────────────
+//
+// The rules run in sequence over one buffer. If each wrote its VALUE into it,
+// every later rule could match that value again — a product whose domain
+// contains the baseline's slug would have it renamed a second time by the
+// repo-slug rule, and every phase of a bootstrap re-runs this over the whole
+// tree. So a rule writes a TOKEN standing for its value, and every token is
+// expanded once, after the last rule. A token is NUL, `H`, NUL; its outer
+// characters take the word/non-word class of the value's own edges, so a
+// later rule's `\b` sees the boundary the value would have given it.
+const heldValues = [];
+const heldIndex = new Map();
+function hold(value) {
+ if (value === "") return "";
+ let i = heldIndex.get(value);
+ if (i === undefined) {
+ i = heldValues.push(value) - 1;
+ heldIndex.set(value, i);
+ }
+ const edge = (c) => (/\w/.test(c) ? "0" : "\u0001");
+ return `${edge(value[0])}\u0000H${i}\u0000${edge(value[value.length - 1])}`;
+}
+const HELD_RE = /[0\u0001]\u0000H(\d+)\u0000[0\u0001]/g;
+function release(text) {
+ return text.replace(HELD_RE, (_, i) => heldValues[Number(i)]);
+}
+
+// ── Worker resource names ──────────────────────────────────────
+//
+// Every Cloudflare worker ships prefixed with the slug (`-`, the
+// base being its `apps//` directory): the component's `workerName`, the
+// environment URLs, the deploy smoke. Re-prefix it so an instance's workers
+// never collide with another's in a shared account.
+function workerBases(files) {
+ const bases = new Set();
+ for (const file of files) {
+ const m = /^apps\/([^/]+)\//.exec(file);
+ if (m) bases.add(m[1]);
+ }
+ return [...bases];
+}
+
+// ── Rename map (ordered, most specific first) ──────────────────
+
+function literalPairs() {
+ return [
+ // This repository's source link, wherever the docs give it. Before the
+ // repo-slug rule, which would otherwise rename only its tail and leave the
+ // link pointing at the baseline's owner.
+ [`github.com/${baseline.githubOwner}/${baseline.slug}`, `github.com/${githuborg}/${reponame}`, "source repository link"],
+ // The product domain wherever it is the product's (BASE_DOMAIN, docs).
+ // Before the repo-slug rule: the placeholder domain starts with the slug.
+ [baseline.domain, productdomain, "product domain"],
+ // The workers.dev subdomain (component parameters, build origin, intent
+ // environment URLs, docs).
+ [baseline.subdomain, subdomain, "workers.dev subdomain"],
+ ];
+}
+
+function regexPairs(files) {
+ const list = [
+ // The display-name seam (apps/web/lib/site.ts: the page's heading and its
+ // ). JSON.stringify writes a valid TS string for any name the
+ // card's pattern admits (apostrophes and ampersands included).
+ {
+ re: new RegExp(`SITE_NAME = "${rx(baseline.productName)}"`, "g"),
+ replacement: () => `SITE_NAME = ${JSON.stringify(productname)}`,
+ label: "site name seam",
+ },
+ // Secret refs: `secret:////…`. MUST precede the
+ // repo-slug pass, which would otherwise rewrite only the project half. The
+ // workspace segment is ANY segment — a ws_… id or a slug.
+ {
+ re: new RegExp(`\\bsecret://[A-Za-z0-9_-]+/${rx(baseline.slug)}/`, "g"),
+ replacement: () => `secret://${orunWorkspaceSlug}/${reponame}/`,
+ label: "secret ref workspace/project",
+ },
+ ];
+
+ const bases = workerBases(files);
+ if (bases.length > 0) {
+ // Longest-first so an alternation never matches a shorter prefix of a base.
+ const wb = bases.slice().sort((a, b) => b.length - a.length).map(rx).join("|");
+ list.push({
+ re: new RegExp(`\\b${rx(baseline.slug)}-(${wb})\\b`, "g"),
+ replacement: (_m, base) => `${brandSlug}-${base}`,
+ label: "worker CF name",
+ });
+ }
+
+ // Repo slug: intent metadata.name and per-env `repo:` params (the Supabase
+ // project and the Hyperdrive config are named after it), db-migrate's
+ // `repo`, the root package name, the fixture's Hyperdrive names, docs. Runs
+ // AFTER the worker pass so `-` has already been consumed.
+ list.push({
+ re: new RegExp(`\\b${rx(baseline.slug)}\\b`, "g"),
+ replacement: () => reponame,
+ label: "repo slug",
+ });
+ return list;
+}
+
+// ── Leftover sweep ─────────────────────────────────────────────
+//
+// After a rebrand (or under --verify) every remaining baseline-identity
+// literal is residue: either org-owned (allowed, masked above) or a missed
+// rename (reported, non-zero exit). The pascal form and the env-var prefix
+// have no rule because nothing in this tree spells them; they are swept so
+// that the first file that does fails here, naming itself, rather than
+// shipping the baseline's name.
+//
+// The placeholder subdomain is residue only when the product changed it — a
+// product that kept the placeholder has not deployed yet, and that is not a
+// missed rename. Under --verify without values it is skipped for the same
+// reason.
+const subdomainChanged = !verifyOnly && subdomain !== baseline.subdomain;
+const RESIDUE_RE = new RegExp(
+ (subdomainChanged ? `${rx(baseline.subdomain)}|` : "") +
+ [
+ `\\b${rx(baseline.slug)}\\b`,
+ `${rx(baseline.slug)}-`,
+ rx(baseline.pascal),
+ `${rx(baseline.envPrefix)}_`,
+ rx(baseline.domain),
+ ].join("|"),
+ "g",
+);
+const ALLOWED_RESIDUE = [
+ /https:\/\/orun-api\.sourceplane\.ai/, // orun state backend
+ /[A-Za-z0-9._%+-]+@sourceplane\.ai/, // company mailboxes
+ ...UPSTREAM,
+];
+
+function sweep(files, allowedLiterals = []) {
+ const residue = [];
+ for (const file of files) {
+ let text;
+ try {
+ text = fs.readFileSync(file, "utf8");
+ } catch {
+ continue;
+ }
+ for (const line of text.split("\n")) {
+ let cleaned = ALLOWED_RESIDUE.reduce((l, re) => l.replace(new RegExp(re.source, "g"), ""), line);
+ // The rename's own TARGET values: a product legitimately named with the
+ // baseline's slug inside it is not residue.
+ for (const lit of allowedLiterals) {
+ if (lit) cleaned = cleaned.split(lit).join("");
+ }
+ if (new RegExp(RESIDUE_RE.source).test(cleaned)) {
+ residue.push(`${file}: ${line.trim().slice(0, 120)}`);
+ }
+ }
+ }
+ return residue;
+}
+
+// ── Main ───────────────────────────────────────────────────────
+
+const files = trackedFiles();
+const literals = literalPairs();
+const regexes = regexPairs(files);
+
+// Every value a rule can write. A value some rule would match again is HELD
+// wherever it already stands: every phase of a bootstrap re-runs this over the
+// whole tree, so what an earlier phase wrote is input to the next pass and
+// must come out of it unchanged.
+const produced = [
+ ...literals.map(([, to]) => to),
+ `SITE_NAME = ${JSON.stringify(productname)}`,
+ `secret://${orunWorkspaceSlug}/${reponame}/`,
+ reponame,
+ ...workerBases(files).map((base) => `${brandSlug}-${base}`),
+].filter((v, i, all) => v && all.indexOf(v) === i);
+const rematchable = (v) =>
+ literals.some(([from]) => v.includes(from)) || regexes.some(({ re }) => new RegExp(re.source).test(v));
+// Longest first, so a held value is never split by a shorter one inside it.
+const guarded = produced.filter(rematchable).sort((a, b) => b.length - a.length);
+const allowedTargets = produced.filter((to) => new RegExp(RESIDUE_RE.source).test(to));
+
+if (verifyOnly) {
+ const residue = sweep(files, valuesPath ? allowedTargets : []);
+ if (residue.length > 0) {
+ console.error(`rebrand --verify: ${residue.length} baseline-identity leftover(s):`);
+ for (const r of residue) console.error(` ${r}`);
+ process.exit(1);
+ }
+ console.log("rebrand --verify: no baseline-identity leftovers.");
+ process.exit(0);
+}
+
+const counts = new Map();
+const touched = new Set();
+const count = (label, n = 1) => counts.set(label, (counts.get(label) ?? 0) + n);
+
+for (const file of files) {
+ let text;
+ try {
+ text = fs.readFileSync(file, "utf8");
+ } catch {
+ continue;
+ }
+ if (text.includes("\0")) continue; // binary safety net
+ const original = text;
+
+ const masks = [];
+ PROTECTED.forEach((re, i) => {
+ text = text.replace(re, (m) => {
+ const token = MASK(i, masks.length);
+ masks.push([token, m]);
+ return token;
+ });
+ });
+
+ // What a previous pass already wrote stays as written.
+ for (const value of guarded) text = text.split(value).join(hold(value));
+
+ for (const [from, to, label] of literals) {
+ const n = text.split(from).length - 1;
+ if (n === 0) continue;
+ text = text.split(from).join(hold(to));
+ count(label, n);
+ }
+ for (const { re, replacement, label } of regexes) {
+ text = text.replace(re, (...m) => {
+ count(label);
+ return hold(replacement(...m));
+ });
+ }
+
+ // Every rule has run; only now do the values it wrote appear.
+ text = release(text);
+ for (const [token, value] of masks) text = text.split(token).join(value);
+
+ if (text !== original) {
+ touched.add(file);
+ if (!dryRun) fs.writeFileSync(file, text);
+ }
+}
+
+console.log(`rebrand${dryRun ? " (dry-run)" : ""}: ${touched.size} file(s) affected`);
+for (const [label, n] of counts) console.log(` ${String(n).padStart(5)} ${label}`);
+if (dryRun) process.exit(0);
+
+const residue = sweep(trackedFiles(), allowedTargets);
+if (residue.length > 0) {
+ console.error(`rebrand: ${residue.length} baseline-identity leftover(s) after rename:`);
+ for (const r of residue) console.error(` ${r}`);
+ process.exit(1);
+}
+console.log("rebrand: leftover sweep clean.");
diff --git a/tooling/rebrand/values.example.json b/tooling/rebrand/values.example.json
new file mode 100644
index 0000000..ebc2c4a
--- /dev/null
+++ b/tooling/rebrand/values.example.json
@@ -0,0 +1,8 @@
+{
+ "reponame": "acme-postgres",
+ "productname": "Acme Cloud",
+ "productdomain": "acme.dev",
+ "githuborg": "acme-inc",
+ "subdomain": "acme",
+ "orunWorkspace": "ws_XXXXXXXX"
+}