.workers.dev")
+for env in ("stage", "prod"):
+ sj = jobs.get(("supabase", env))
+ exported = "\n".join(s.get("run") or "" for s in (sj or {}).get("steps") or [])
+ for var, want in (("repo", repo), ("workersDevSubdomain", sub), ("authEmailConfirmation", "false")):
+ if f"printf 'TF_VAR_{var}=%s\\n' '{want}'" not in exported:
+ bad(f"supabase@{env} does not export TF_VAR_{var}={want}")
+ if f"printf 'TF_VAR_environment=%s\\n' \"{env}\"" not in exported:
+ bad(f"supabase@{env} does not export TF_VAR_environment={env}")
+ j = jobs.get(("web", env))
+ if not j:
+ continue
+ own = [r for r in j.get("secretRefs") or [] if r["asEnv"] == f"WIRING_SUPABASE_{env.upper()}"]
+ if not own or not own[0]["ref"].endswith(f"/{env}/WIRING_SUPABASE"):
+ bad(f"web@{env} does not read its own environment's WIRING_SUPABASE")
+ 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 "--components supabase" not in steps.get("build-app", ""):
+ bad(f"web@{env} does not render its wrangler config from the Supabase wiring before it builds")
+ if 'if [ "${ORUN_ENVIRONMENT}" != dev ]' not in steps.get("build-app", ""):
+ bad(f"web@{env} renders its wiring on dev too, where nothing is published")
+ 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", "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 Chat & 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..231afe7
--- /dev/null
+++ b/testing/rebrand.test.sh
@@ -0,0 +1,187 @@
+#!/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 one the
+# Supabase project's Auth sends its links to), 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. What must NOT be renamed: the upstream example's own link, a
+# migration (its checksum is in the manifest and in every project it was
+# applied to), and what merely spells `supabase` — a wiring token names the
+# component, not this baseline.
+#
+# The identity is PINNED (fixtures/baseline-identity.supabase-slack-clone.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.supabase-slack-clone.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-chat","productname":"Acme Chat","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 = "Slack Clone"' \
+ 'export const SITE_NAME = "Acme Chat"'
+check "…and stays a valid string for a name with an apostrophe and an ampersand" \
+ '{"reponame":"sams-chat","productname":"Sam'"'"'s Chat & Co","productdomain":"sam.dev"}' \
+ apps/web/lib/site.ts 'export const SITE_NAME = "Slack Clone"' \
+ 'export const SITE_NAME = "Sam'"'"'s Chat & Co"'
+check "the display name elsewhere is content, and is left alone" \
+ "$acme" apps/web/app/x.tsx 'Welcome to the Slack Clone.
' \
+ 'Welcome to the Slack Clone.
'
+check "the worker name is re-prefixed, the environment suffix kept" \
+ "$acme" apps/web/component.yaml 'workerName: supabase-slack-clone-web' \
+ 'workerName: acme-chat-web'
+check "the Worker's own origin: worker name and subdomain" \
+ "$acme" intent.yaml ' url: https://supabase-slack-clone-web-stage.your-workers-subdomain.workers.dev' \
+ ' url: https://acme-chat-web-stage.acme.workers.dev'
+check "the subdomain the deploy's smoke reaches the Worker on" \
+ "$acme" apps/web/component.yaml ' workersDevSubdomain: your-workers-subdomain' \
+ ' workersDevSubdomain: acme'
+check "the subdomain the Supabase project's Auth Site URL is built from" \
+ "$acme" infra/terraform/supabase/component.yaml ' workersDevSubdomain: your-workers-subdomain' \
+ ' workersDevSubdomain: acme'
+check "the placeholder domain is the product's domain, not a renamed slug" \
+ "$acme" intent.yaml ' BASE_DOMAIN: supabase-slack-clone.example.com' \
+ ' BASE_DOMAIN: acme.dev'
+check "no domain given: the reserved placeholder, for an owner to replace later" \
+ '{"reponame":"acme-chat","productname":"Acme Chat","githuborg":"acme-inc","subdomain":"acme"}' \
+ intent.yaml ' BASE_DOMAIN: supabase-slack-clone.example.com' \
+ ' BASE_DOMAIN: acme-chat.example.com'
+check "an empty domain is no domain" \
+ '{"reponame":"acme-chat","productname":"Acme Chat","productdomain":""}' \
+ intent.yaml ' BASE_DOMAIN: supabase-slack-clone.example.com' \
+ ' BASE_DOMAIN: acme-chat.example.com'
+check "the repo slug" \
+ "$acme" package.json ' "name": "supabase-slack-clone",' \
+ ' "name": "acme-chat",'
+check "the repo Terraform names the Supabase project after" \
+ "$acme" intent.yaml ' repo: supabase-slack-clone' \
+ ' repo: acme-chat'
+check "…and the Terraform variable's default" \
+ "$acme" infra/terraform/supabase/terraform/main.tf ' default = "supabase-slack-clone"' \
+ ' default = "acme-chat"'
+check "a secret ref names the product's workspace and project" \
+ "$acme" apps/web/component.yaml \
+ ' WIRING_SUPABASE_STAGE: "secret://supabase-slack-clone/supabase-slack-clone/stage/WIRING_SUPABASE"' \
+ ' WIRING_SUPABASE_STAGE: "secret://ws_79BDXAZQ/acme-chat/stage/WIRING_SUPABASE"'
+check "this repository's source link names the product's owner and repository" \
+ "$acme" README.md 'See https://github.com/sourceplane/supabase-slack-clone.' \
+ 'See https://github.com/acme-inc/acme-chat.'
+check "a migration is never rewritten (its checksum is in the manifest and in every project it was applied to)" \
+ "$acme" packages/db/src/migrations/040_x/up.sql '-- supabase-slack-clone: a comment the checksum covers' \
+ '-- supabase-slack-clone: a comment the checksum covers'
+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 not this baseline's"
+check "a wiring token names the component, not the baseline" \
+ "$acme" apps/web/wrangler.template.jsonc \
+ ' "NEXT_PUBLIC_SUPABASE_URL": "@@wiring(supabase/__ENV__:supabase_url)@@",' \
+ ' "NEXT_PUBLIC_SUPABASE_URL": "@@wiring(supabase/__ENV__:supabase_url)@@",'
+check "the upstream example's home is upstream's" \
+ "$acme" README.md '[Slack clone](https://github.com/supabase/supabase/tree/master/examples/slack-clone/nextjs-slack-clone)' \
+ '[Slack clone](https://github.com/supabase/supabase/tree/master/examples/slack-clone/nextjs-slack-clone)'
+
+echo "── rebrand: a written value is not rewritten, in any later pass"
+contains='{"reponame":"supabase-slack-clone-2","productname":"Slack Clone 2","productdomain":"supabase-slack-clone.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": "supabase-slack-clone",' \
+ ' "name": "supabase-slack-clone-2",' 3
+check "a worker name built on it survives three passes" \
+ "$contains" apps/web/component.yaml 'workerName: supabase-slack-clone-web' \
+ 'workerName: supabase-slack-clone-2-web' 3
+check "a domain containing the baseline's domain survives three passes" \
+ "$contains" intent.yaml 'BASE_DOMAIN: supabase-slack-clone.example.com' \
+ 'BASE_DOMAIN: supabase-slack-clone.example.com.au' 3
+check "a subdomain containing the placeholder survives three passes" \
+ "$contains" infra/terraform/supabase/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 = "Slack Clone"' \
+ 'export const SITE_NAME = "Slack Clone 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": "supabase-slack-clone-2"' pass --values
+verify "without them it cannot know, and fails" \
+ "$contains" package.json '"name": "supabase-slack-clone-2"' fail
+verify "given the values, a real leftover still fails" \
+ "$acme" package.json '"name": "supabase-slack-clone"' fail --values
+verify "a leftover worker name fails" \
+ "$acme" apps/web/component.yaml 'workerName: supabase-slack-clone-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 SupabaseSlackClone {}' fail --values
+verify "the upstream example's links are not residue" \
+ "$acme" apps/web/README.md 'the [example](https://github.com/supabase/supabase/tree/master/examples/slack-clone/nextjs-slack-clone)' pass --values
+verify "a clean product passes" \
+ "$acme" package.json '"name": "acme-chat"' 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 = "SUPABASE_SLACK_CLONE_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/catalog/gen-component-docs.py b/tooling/catalog/gen-component-docs.py
new file mode 100644
index 0000000..743782b
--- /dev/null
+++ b/tooling/catalog/gen-component-docs.py
@@ -0,0 +1,550 @@
+#!/usr/bin/env python3
+"""Generate each component's docs (overview / architecture / runbook).
+
+ python3 tooling/catalog/gen-component-docs.py # write
+ python3 tooling/catalog/gen-component-docs.py --check # fail on drift (CI)
+
+Every `component.yaml` attaches its `docs/` folder in `spec.docs` (overview,
+architecture, runbook), which is what the Orun workspace's Docs library shows
+and what the catalog's docs and runbook checks read; a folder nothing declares
+is never attached (testing/coverage.test.sh holds the rule). These pages are
+generated, not hand-written, because almost
+everything in them is already declared somewhere CI validates: the component's
+manifest (type, description, dependencies, environments, the secrets a lane
+resolves, the smoke), its Worker config (bindings, triggers, the wiring the
+deploy fills in), its Terraform (resources and outputs), its migrations and its
+package scripts. A hand-written copy of those facts drifts the first time one
+changes; a generated one cannot, because `--check` fails the pull request that
+changes the fact without the page.
+
+What is NOT derivable (why a component exists, what a failure means for this
+product in particular) belongs in the component's `description` and in the
+product's own docs, not here.
+
+The pages ship with the component into every product built from this tree, so
+they say nothing about where they came from: no factory paths, no generator
+path, no provenance. Zero dependencies beyond PyYAML.
+"""
+
+from __future__ import annotations
+
+import json
+import pathlib
+import re
+import sys
+
+try:
+ import yaml
+except ImportError: # pragma: no cover - the contract job installs it
+ sys.exit("gen-component-docs needs PyYAML (pip install pyyaml)")
+
+ROOT = pathlib.Path(__file__).resolve().parents[2]
+ROOTS = ("apps", "packages", "infra", "tests")
+SKIP_DIRS = {"node_modules", "dist", ".turbo", "docs", ".next", ".open-next",
+ ".wrangler", ".svelte-kit", ".nuxt", ".output", ".astro", "coverage"}
+
+# Paths a shipped page must never name: products are not placed with them.
+FACTORY = re.compile(
+ r"repo-blueprint|BOOTSTRAP\.md|(? str:
+ """JSONC → JSON: drop comments outside strings, then trailing commas."""
+ out, i, n, in_str = [], 0, len(text), False
+ while i < n:
+ c = text[i]
+ if in_str:
+ out.append(c)
+ if c == "\\" and i + 1 < n:
+ out.append(text[i + 1])
+ i += 2
+ continue
+ if c == '"':
+ in_str = False
+ i += 1
+ continue
+ if c == '"':
+ in_str = True
+ out.append(c)
+ i += 1
+ elif text.startswith("//", i):
+ j = text.find("\n", i)
+ i = n if j < 0 else j
+ elif text.startswith("/*", i):
+ j = text.find("*/", i + 2)
+ i = n if j < 0 else j + 2
+ else:
+ out.append(c)
+ i += 1
+ return re.sub(r",(\s*[}\]])", r"\1", "".join(out))
+
+
+def read_json(path: pathlib.Path) -> dict | None:
+ try:
+ return json.loads(strip_jsonc(path.read_text(encoding="utf-8")))
+ except (OSError, ValueError):
+ return None
+
+
+def rel(p: pathlib.Path) -> str:
+ return p.relative_to(ROOT).as_posix()
+
+
+def discover() -> list[dict]:
+ found = []
+ for root in ROOTS:
+ base = ROOT / root
+ if not base.is_dir():
+ continue
+ stack = [base]
+ while stack:
+ d = stack.pop()
+ for entry in sorted(d.iterdir()):
+ if entry.is_dir():
+ if entry.name in SKIP_DIRS or entry.name.startswith("."):
+ continue
+ if (entry / "main.tf").exists() and not (entry / "component.yaml").exists():
+ continue
+ if len(entry.relative_to(base).parts) <= 3:
+ stack.append(entry)
+ elif entry.name == "component.yaml":
+ found.append(read_component(entry))
+ comps = [c for c in found if c["name"] and c["type"]]
+ return sorted(comps, key=lambda c: c["name"])
+
+
+def read_component(file: pathlib.Path) -> dict:
+ doc = yaml.safe_load(file.read_text(encoding="utf-8")) or {}
+ meta, spec = doc.get("metadata") or {}, doc.get("spec") or {}
+ params = spec.get("parameters") or {}
+ deps = [d.get("component") for d in (spec.get("dependsOn") or []) if isinstance(d, dict)]
+ envs = []
+ # Secrets may be declared for the whole component or per environment
+ # (`subscribe.environments[].secretEnv`); a page lists both.
+ req_env = set((spec.get("secretEnv") or {}).keys())
+ opt_env = set((spec.get("optionalSecretEnv") or {}).keys())
+ for e in ((spec.get("subscribe") or {}).get("environments") or []):
+ req_env |= set((e.get("secretEnv") or {}).keys())
+ opt_env |= set((e.get("optionalSecretEnv") or {}).keys())
+ rules = [(r.get("profile"), ((r.get("when") or {}).get("triggerRef")))
+ for r in (e.get("profileRules") or [])]
+ envs.append({"name": e.get("name"), "profile": e.get("profile"), "rules": rules})
+ return {
+ "dir": file.parent,
+ "path": rel(file.parent),
+ "name": meta.get("name"),
+ "description": (meta.get("description") or "").strip(),
+ "type": spec.get("type"),
+ "deps": [d for d in deps if d],
+ "secret_env": sorted(req_env),
+ "optional_env": sorted(opt_env - req_env),
+ "envs": envs,
+ "params": params,
+ "migrations_path": spec.get("path") if spec.get("type") == "db-migrate" else None,
+ }
+
+
+def package_of(c: dict) -> dict | None:
+ return read_json(c["dir"] / "package.json")
+
+
+def worker_config(c: dict) -> tuple[str | None, dict | None]:
+ """The config a deploy uses: the template when wiring renders one."""
+ names = ["wrangler.template.jsonc", c["params"].get("wranglerConfig") or "",
+ "wrangler.jsonc", "wrangler.json"]
+ for name in names:
+ if name and (c["dir"] / name).is_file():
+ return name, read_json(c["dir"] / name)
+ return None, None
+
+
+WIRING = re.compile(r"@@wiring\(([^/)]+)/__ENV__:([^)]+)\)@@")
+
+
+def wired(value) -> str | None:
+ m = WIRING.search(str(value)) if value is not None else None
+ return f"`{m.group(2)}` from `{m.group(1)}`" if m else None
+
+
+def bindings(cfg: dict) -> list[tuple[str, str, str]]:
+ rows = []
+ for kv in cfg.get("kv_namespaces") or []:
+ rows.append((kv.get("binding"), "Workers KV namespace", wired(kv.get("id")) or "declared in the config"))
+ for b in cfg.get("r2_buckets") or []:
+ rows.append((b.get("binding"), "R2 bucket", wired(b.get("bucket_name")) or f"`{b.get('bucket_name')}`"))
+ for d in cfg.get("d1_databases") or []:
+ rows.append((d.get("binding"), "D1 database", wired(d.get("database_id")) or "declared in the config"))
+ for h in cfg.get("hyperdrive") or []:
+ rows.append((h.get("binding"), "Hyperdrive (pooled Postgres)", wired(h.get("id")) or "declared in the config"))
+ if isinstance(cfg.get("ai"), dict) and cfg["ai"].get("binding"):
+ rows.append((cfg["ai"]["binding"], "Workers AI", "account-level; no resource to provision"))
+ for d in ((cfg.get("durable_objects") or {}).get("bindings") or []):
+ rows.append((d.get("name"), "Durable Object", f"class `{d.get('class_name')}`"))
+ for s in cfg.get("services") or []:
+ rows.append((s.get("binding"), "Service binding", f"Worker `{s.get('service')}`"))
+ for q in ((cfg.get("queues") or {}).get("producers") or []):
+ rows.append((q.get("binding"), "Queue producer", f"queue `{q.get('queue')}`"))
+ for r in cfg.get("ratelimits") or []:
+ simple = r.get("simple") or {}
+ rows.append((r.get("name"), "Rate limiter",
+ f"{simple.get('limit')} requests / {simple.get('period')}s per location"))
+ assets = cfg.get("assets") or {}
+ if assets.get("binding"):
+ rows.append((assets["binding"], "Static assets", f"`{assets.get('directory')}`"))
+ return [r for r in rows if r[0]]
+
+
+def tf_facts(c: dict) -> dict:
+ tf_dir = c["dir"] / (c["params"].get("terraformDir") or "terraform")
+ resources, outputs, variables, backend = [], [], [], None
+ for f in sorted(tf_dir.glob("*.tf")) if tf_dir.is_dir() else []:
+ text = f.read_text(encoding="utf-8")
+ resources += [f"{t}.{n}" for t, n in re.findall(r'^resource\s+"([^"]+)"\s+"([^"]+)"', text, re.M)]
+ outputs += re.findall(r'^output\s+"([^"]+)"', text, re.M)
+ variables += re.findall(r'^variable\s+"([^"]+)"', text, re.M)
+ m = re.search(r'backend\s+"([^"]+)"', text)
+ backend = backend or (m.group(1) if m else None)
+ imports = (tf_dir / "adopt.tf").is_file() if tf_dir.is_dir() else False
+ return {"dir": rel(tf_dir) if tf_dir.is_dir() else None, "resources": resources,
+ "outputs": outputs, "variables": variables, "backend": backend, "adopt": imports}
+
+
+def published(c: dict) -> list[tuple[str, str]]:
+ spec = c["params"].get("secretOutputs") or ""
+ pairs = []
+ for part in str(spec).split(","):
+ if "=" in part:
+ k, v = part.split("=", 1)
+ pairs.append((k.strip(), v.strip()))
+ return pairs
+
+
+def test_files(c: dict) -> list[str]:
+ out = []
+ for p in sorted(c["dir"].rglob("*")):
+ if any(part in SKIP_DIRS for part in p.relative_to(c["dir"]).parts):
+ continue
+ if p.is_file() and re.search(r"\.(test|spec)\.(ts|tsx|js|mjs|cjs)$", p.name):
+ out.append(p.name)
+ return out
+
+
+def migrations(c: dict) -> list[str]:
+ path = c["migrations_path"]
+ if not path:
+ return []
+ d = ROOT / path
+ if not d.is_dir():
+ return []
+ return sorted(p.name for p in d.iterdir() if p.is_dir() or p.suffix == ".sql")
+
+
+# ── markdown ─────────────────────────────────────────────────────────────
+
+def md_table(header: list[str], rows: list[list[str]]) -> list[str]:
+ """A table laid out the way prettier lays it out, so a repo whose lint is
+ `prettier --check` accepts the page as written."""
+ cols = len(header)
+ width = [max(3, len(header[i]), *(len(r[i]) for r in rows)) for i in range(cols)]
+ def line(cells):
+ return "| " + " | ".join(c.ljust(width[i]) for i, c in enumerate(cells)) + " |"
+ return [line(header), "| " + " | ".join("-" * w for w in width) + " |", *(line(r) for r in rows)]
+
+
+# ── phrasing ─────────────────────────────────────────────────────────────
+
+KIND = {
+ "cloudflare-worker-turbo": "A Cloudflare Worker, deployed per environment by its CI lane.",
+ "cloudflare-workers-assets-turbo": "A Cloudflare Worker with Static Assets (server rendering plus "
+ "static files), deployed per environment by its CI lane.",
+ "terraform": "Terraform-managed infrastructure, planned and applied per environment by its CI lane.",
+ "db-migrate": "Applies this repository's ordered database migrations per environment: "
+ "plan on pull requests, apply on merge to `main`.",
+ "turbo-package": "A workspace package built by the turbo pipeline. It deploys nothing itself: "
+ "its lane type-checks, lints, tests and builds it.",
+}
+
+TRIGGER = {"github-push-main": "a push to `main`", "github-pull-request": "a pull request"}
+
+
+def env_line(e: dict) -> str:
+ s = f"`{e['name']}`: `{e['profile']}`"
+ for profile, ref in e["rules"]:
+ s += f", `{profile}` on {TRIGGER.get(ref, f'`{ref}`')}"
+ return s
+
+
+def is_tests(c: dict) -> bool:
+ return c["name"].endswith("-tests") or c["path"].startswith("tests/")
+
+
+def subject_of(c: dict, by_name: dict) -> str | None:
+ if c["name"].endswith("-tests"):
+ s = c["name"][: -len("-tests")]
+ return s if s in by_name else None
+ return None
+
+
+def names_list(c: dict, keep) -> list[str]:
+ """Secret names a lane resolves, required first; an optional one (from
+ `optionalSecretEnv`) is resolved when it exists and skipped when not."""
+ req = [f"- `{k}`" for k in c["secret_env"] if keep(k)]
+ opt = [f"- `{k}` (optional)" for k in c["optional_env"] if keep(k)]
+ return req + opt
+
+
+def bullet_list(names: list[str], by_name: dict) -> list[str]:
+ if not names:
+ return ["- (none)"]
+ out = []
+ for n in names:
+ d = by_name.get(n)
+ out.append(f"- **{n}** — {d['description']}" if d and d["description"] else f"- **{n}**")
+ return out
+
+
+# ── pages ────────────────────────────────────────────────────────────────
+
+def overview(c: dict, by_name: dict, dependents: list[str]) -> str:
+ pkg = package_of(c)
+ kind = KIND.get(c["type"], f"A `{c['type']}` component.")
+ subject = subject_of(c, by_name)
+ if is_tests(c):
+ kind = (f"The test suite for **{subject}**. " if subject else "A test suite. ") + \
+ "It deploys nothing: its lane installs, builds and runs the tests."
+ lines = [f"# {c['name']}", ""]
+ if c["description"]:
+ lines += [c["description"], ""]
+ facts = [["Type", f"`{c['type']}`"], ["Source", f"`{c['path']}`"]]
+ if pkg and pkg.get("name"):
+ facts.append(["Package", f"`{pkg['name']}`"])
+ if c["envs"]:
+ facts.append(["Environments", " · ".join(env_line(e) for e in c["envs"])])
+ lines += [kind, "", *md_table(["", ""], facts)]
+ lines += ["", "## Depends on", "", *bullet_list(c["deps"], by_name),
+ "", "## Depended on by", "", *bullet_list(dependents, by_name), ""]
+ return "\n".join(lines)
+
+
+def architecture(c: dict, by_name: dict) -> str:
+ lines = [f"# {c['name']} — architecture", ""]
+ t = c["type"]
+
+ if t == "terraform":
+ f = tf_facts(c)
+ lines += [f"A `terraform` root at `{f['dir'] or c['path']}`.", ""]
+ if f["backend"] == "http":
+ lines += ["- **State** lives in the Orun Cloud HTTP state backend — no local state and",
+ " no state bucket to manage."]
+ lines += ["- **Credentials are brokered per run** from the workspace's provider",
+ " connections and resolved by name; none is stored in this repository."]
+ if f["adopt"]:
+ lines += ["- **Adoption** (`adopt.tf`): when state is empty but the resource already",
+ " exists, plan-time import adopts it instead of failing."]
+ lines.append("")
+ if f["resources"]:
+ lines += ["## Resources", "", *[f"- `{r}`" for r in f["resources"]], ""]
+ pub = published(c)
+ if pub:
+ lines += ["## Published outputs", "",
+ "Written as job-output secrets on each environment after an apply; deploy",
+ "lanes downstream resolve them by name.", "",
+ *md_table(["Secret", "Terraform output"], [[f"`{k}`", f"`{v}`"] for k, v in pub]), ""]
+ elif f["outputs"]:
+ lines += ["## Outputs", "", *[f"- `{o}`" for o in f["outputs"]], ""]
+ if c["secret_env"] or c["optional_env"]:
+ lines += ["## Resolved at run time (names only)", "", *names_list(c, lambda k: True), ""]
+ return "\n".join(lines)
+
+ if t == "db-migrate":
+ migs = migrations(c)
+ lines += [f"Applies the migrations under `{c['migrations_path']}` in order, recording each one",
+ "it applies so a run only ever applies what is new. An already-applied migration",
+ "is never edited: a change is a new, later migration.", ""]
+ if migs:
+ lines += ["## Migrations", "", *[f"- `{m}`" for m in migs], ""]
+ if c["secret_env"] or c["optional_env"]:
+ lines += ["## Resolved at run time (names only)", "", *names_list(c, lambda k: True), ""]
+ return "\n".join(lines)
+
+ pkg = package_of(c)
+ if t.startswith("cloudflare-"):
+ cfg_name, cfg = worker_config(c)
+ lines += [f"Built by the turbo pipeline from `{c['path']}` and deployed with wrangler.", ""]
+ if cfg:
+ facts = [["Worker config", f"`{c['path']}/{cfg_name}`"]]
+ if cfg.get("main"):
+ facts.append(["Entry", f"`{cfg['main']}`"])
+ if cfg.get("compatibility_date"):
+ facts.append(["Compatibility date", f"`{cfg['compatibility_date']}`"])
+ if cfg.get("compatibility_flags"):
+ facts.append(["Compatibility flags", ", ".join(f"`{x}`" for x in cfg["compatibility_flags"])])
+ lines += [*md_table(["", ""], facts), ""]
+ rows = bindings(cfg)
+ lines += ["## Bindings", ""]
+ if rows:
+ lines += [*md_table(["Binding", "Kind", "Source"], [[f"`{b}`", k, s] for b, k, s in rows]), ""]
+ if any("from `" in s for _, _, s in rows):
+ lines += ["Identifiers marked _from_ a component are filled in at deploy time from",
+ "that component's published outputs for the environment being deployed.", ""]
+ else:
+ lines += ["None: the Worker binds no storage or service.", ""]
+ crons = (cfg.get("triggers") or {}).get("crons") or []
+ if crons:
+ lines += ["## Scheduled triggers", "", *[f"- `{x}`" for x in crons], ""]
+ env_names = sorted((cfg.get("env") or {}).keys())
+ var_names = sorted((cfg.get("vars") or {}).keys())
+ if var_names:
+ lines += ["## Variables", "", ", ".join(f"`{v}`" for v in var_names)
+ + (f" — overridden per environment ({', '.join(f'`{e}`' for e in env_names)})."
+ if env_names else "."), ""]
+ wiring = names_list(c, lambda k: k.startswith("WIRING_"))
+ others = names_list(c, lambda k: not k.startswith("WIRING_"))
+ if wiring:
+ lines += ["## Wiring", "",
+ "Resolved at deploy time from secrets the infrastructure lanes publish (names only):",
+ "", *wiring, ""]
+ if others:
+ lines += ["## Secrets resolved by the lane (names only)", "", *others, ""]
+ return "\n".join(lines)
+
+ # turbo-package
+ if is_tests(c):
+ files = test_files(c)
+ lines += [f"A test package at `{c['path']}`. Its lane runs the suite before it builds.", ""]
+ if files:
+ lines += [f"## Suites ({len(files)})", "", *[f"- `{f}`" for f in files], ""]
+ return "\n".join(lines)
+ lines += [f"A workspace package at `{c['path']}`, consumed by the components that depend",
+ "on it. It has no deployed surface of its own.", ""]
+ if pkg and pkg.get("exports"):
+ ex = pkg["exports"]
+ keys = sorted(ex.keys()) if isinstance(ex, dict) else ["."]
+ lines += ["## Exports", "", *[f"- `{k}`" for k in keys], ""]
+ return "\n".join(lines)
+
+
+def runbook(c: dict, by_name: dict) -> str:
+ t = c["type"]
+ pkg = package_of(c)
+ lines = [f"# {c['name']} — runbook", "", "## How it runs", ""]
+ deploys = [e["name"] for e in c["envs"]
+ if any(ref == "github-push-main" for _, ref in e["rules"])]
+ if deploys and t in ("terraform", "db-migrate"):
+ lines += [f"Pull requests plan it; a merge to `main` applies it to "
+ f"{', '.join(f'`{e}`' for e in deploys)}."]
+ elif deploys:
+ lines += [f"Pull requests verify it; a merge to `main` deploys it to "
+ f"{', '.join(f'`{e}`' for e in deploys)}."]
+ else:
+ lines += ["Its lane runs on every pull request that changes it; it has no deployed surface."]
+ lines += ["CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`;",
+ "the plan orders a component after everything it depends on.", ""]
+
+ if pkg and pkg.get("scripts"):
+ name = pkg.get("name")
+ wanted = [s for s in ("dev", "build", "test", "typecheck", "lint", "preview") if s in pkg["scripts"]]
+ if name and wanted:
+ lines += ["## Local commands", "", "```bash",
+ *[f"pnpm --filter {name} {s}" for s in wanted], "```", ""]
+
+ smoke = c["params"].get("smokeCommand")
+ if smoke and "No smoke" not in str(smoke):
+ lines += ["## Verify", "", "After a deploy the lane runs this smoke against the environment it",
+ "deployed (`ORUN_ENVIRONMENT`); `DEPLOYED_URL` overrides the URL:", "",
+ "```bash", str(smoke).strip(), "```", ""]
+
+ lines += ["## Rollback", "",
+ "Revert the commit on `main`. The next convergence applies the previous desired",
+ "state; nothing was changed out of band, so there is nothing else to undo.", "",
+ "## Common failures", ""]
+ if t == "terraform":
+ lines += ["- **Provider authentication fails**: the workspace's provider connection is",
+ " missing or revoked. Reconnect it in the console; credentials are brokered",
+ " from it per run.",
+ "- **\"Already exists\" on a first apply**: state is empty but the resource is",
+ " not." + (" `adopt.tf` imports it at plan time; if it still fails, the resource"
+ " was renamed outside Terraform." if tf_facts(c)["adopt"] else
+ " Import it, or delete the stray resource, then re-run."), ""]
+ elif t == "db-migrate":
+ lines += ["- **An applied migration's file changed**: the run stops rather than guess.",
+ " Restore the file and write the change as a new migration.",
+ "- **The database is unreachable**: the infrastructure lane it depends on has",
+ " not applied for this environment; that lane runs first in a convergence.", ""]
+ elif t.startswith("cloudflare-"):
+ _, cfg = worker_config(c)
+ takes_wiring = any(k.startswith("WIRING_") for k in c["secret_env"] + c["optional_env"]) or \
+ bool(cfg and WIRING.search(json.dumps(cfg)))
+ if takes_wiring:
+ lines += ["- **A `WIRING_*` secret is missing at deploy**: an infrastructure lane upstream",
+ " has not applied for this environment yet. Within one convergence the plan",
+ " runs it first; on its own, re-run that lane."]
+ lines += ["- **The smoke fails right after a first deploy**: a new workers.dev route can",
+ " answer 4xx for a few seconds and the lane retries. A failure that persists",
+ " is a regression in the deployed code.", ""]
+ else:
+ lines += ["- **A dependent fails to build after a change here**: run `pnpm typecheck`",
+ " across the workspace before merging.", ""]
+ return "\n".join(lines)
+
+
+# ── main ─────────────────────────────────────────────────────────────────
+
+def main() -> int:
+ check = "--check" in sys.argv[1:]
+ comps = discover()
+ if not comps:
+ print("no component.yaml found", file=sys.stderr)
+ return 1
+ by_name = {c["name"]: c for c in comps}
+ dependents: dict[str, list[str]] = {c["name"]: [] for c in comps}
+ for c in comps:
+ for d in c["deps"]:
+ dependents.setdefault(d, []).append(c["name"])
+
+ drifted, written, leaks = [], 0, []
+ for c in comps:
+ pages = {
+ "overview.md": overview(c, by_name, sorted(dependents.get(c["name"], []))),
+ "architecture.md": architecture(c, by_name),
+ "runbook.md": runbook(c, by_name),
+ }
+ for fname, body in pages.items():
+ target = c["dir"] / "docs" / fname
+ for n, line in enumerate(body.splitlines(), 1):
+ m = FACTORY.search(line)
+ if m:
+ leaks.append(f"{rel(target)}:{n} would name {m.group(0)!r}")
+ current = target.read_text(encoding="utf-8") if target.exists() else None
+ if current == body:
+ continue
+ if check:
+ drifted.append(rel(target))
+ continue
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(body, encoding="utf-8")
+ written += 1
+
+ if leaks:
+ print("✗ a generated page would name a path products do not have:", file=sys.stderr)
+ for l in leaks:
+ print(f" {l}", file=sys.stderr)
+ return 1
+ if check:
+ if drifted:
+ print(f"✗ {len(drifted)} component doc(s) differ from what the manifests say:", file=sys.stderr)
+ for f in drifted:
+ print(f" {f}", file=sys.stderr)
+ print("\nRun: python3 tooling/catalog/gen-component-docs.py", file=sys.stderr)
+ return 1
+ print(f"✓ component docs match {len(comps)} component.yaml file(s)")
+ return 0
+ print(f"✓ wrote {written} page(s) for {len(comps)} component(s)")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tooling/rebrand/rebrand.mjs b/tooling/rebrand/rebrand.mjs
new file mode 100644
index 0000000..ccd2fb4
--- /dev/null
+++ b/tooling/rebrand/rebrand.mjs
@@ -0,0 +1,491 @@
+#!/usr/bin/env node
+// Rebrand renamer for the supabase-slack-clone baseline (zero-dependency).
+//
+// This repository is a baseline: a product is instantiated from it, branded,
+// and deployed as somebody's own team chat. This script rewrites every
+// *instance identity* literal in the product tree — repo slug (the intent, the
+// secret project, the Supabase project 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 (which the Supabase
+// project's Auth Site URL is built from too) — 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
+// example's own identity too (where in supabase/supabase the code came from,
+// which the READMEs and the licence credit name: 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-chat", // required — repo slug
+// "productname": "Acme Chat", // 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: "supabase-slack-clone",
+ pascal: "SupabaseSlackClone",
+ productName: "Slack Clone",
+ domain: "supabase-slack-clone.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 supabase/supabase's Next.js Slack clone example. Where the
+// docs and the licence credit name it — its directory in supabase/supabase,
+// whose name spells this baseline's slug (`supabase-slack-clone` is what the
+// example's own package and deploy button call it) — they point at the
+// example's real home. Protected from every rule and allowed by the leftover
+// sweep, so a product's README keeps naming where its code came from instead
+// of a repository that does not exist.
+//
+// ENCLOSING FIRST: the masks are taken in this order and put back in it, so a
+// link that CONTAINS another must be masked whole before the one inside it is
+// looked for.
+const UPSTREAM = [
+ /github\.com\/supabase\/supabase\/tree\/master\/examples\/slack-clone\/nextjs-slack-clone\b/g, // the example's home
+];
+
+// ── 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), which every page's
+ // and the sign-in page's heading read. 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
+ // projects are named after it), the root package name, 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..a51fad2
--- /dev/null
+++ b/tooling/rebrand/values.example.json
@@ -0,0 +1,8 @@
+{
+ "reponame": "acme-chat",
+ "productname": "Acme Chat",
+ "productdomain": "acme.dev",
+ "githuborg": "acme-inc",
+ "subdomain": "acme",
+ "orunWorkspace": "ws_XXXXXXXX"
+}