cast/src/resolve.ts

729 lines
32 KiB
TypeScript
Raw Normal View History

feat: cast — the Coolify executor, extracted from the infra state repo Public tool, private state. cast holds no hostnames, no bindings, no secrets: it joins a product repo's .infra/ manifest with a state directory you point it at, and makes Coolify match. Extracted from heavy-duty/infra, which was half tool and half state — the inconsistency that made it impossible to say whether "infra" named a CLI or a runbook. rig builds the boxes; cast fills them; infra is what they are filled with. Two changes were required to make it genuinely stateless and publishable: - The implicit cwd contract (environments.yaml / secrets/ / .coolify.env resolved against the working directory, silently reading the wrong file from the wrong place) is now an explicit --state <dir> / $CAST_STATE. - BANNED_IN_PROD — a hardcoded list of one product's ALLOW_* flags, the only product knowledge in the executor — becomes the generic, operator- owned environments.<env>.forbidden_var_patterns. The guard now lives in private state, so a product-side change cannot lower its own guard, and it is a pattern rather than a list, so it catches unforeseen siblings. Age identities resolve as $CAST_AGE_KEY_FILE_<ENV> then ~/.config/cast/age-<env>.key — which is the entire attended-vs-unattended apply mechanism, with no environment names known to the tool. Instance identity (org names, the GitHub App name, founder domains) is out of the fixtures and out of register-github-app.sh, which took APP_NAME and ORG as arguments rather than baking them in. 69 tests green; bin/cast + curl installer mirror rig's shape. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 12:25:44 +00:00
import { execFileSync } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { Desired } from "./diff.js";
feat: cast capture — adopt a hand-built Coolify into the age secret store (#15) cast was scoped to the steady state: manifest → Coolify, forever. It had no adoption path — no way to bootstrap the age store from an instance built by hand, before any manifest existed. The operator did it by hand: curl the envs, assemble 17 name=value pairs into /dev/shm/prod.env, age -r, shred. Every input to that pipeline is something cast already has, so a human was shuffling cast's own inputs through a terminal, with the leak (scrollback, history, a tmp file that never got shredded) and the silent miss both live. cast capture <org>/<repo> --env <env> [--generated N] [--override N] [--force] The required set comes from the MANIFEST, not the box: the ${...} refs in that environment's env templates, read by the same parser apply uses to demand them. resolveTemplate and templateRefs now share one grammar — a drift between them would mean capture collects a different set than apply later requires, which is exactly the "a name silently missed" failure this verb exists to remove. The mapping is deliberately NOT mechanical. A DATABASE_URL read off the source points at the SOURCE box's Postgres: confidently wrong, entirely plausible, and the target's real URL does not exist until Coolify creates the resource. So the manifest declares `generated_secrets:` and those names are written as the literal `pending-coolify-generated`. staging's ADMIN_EMAIL must be the operator, not the source's — staging and prod share a Mailgun domain, so a staging box carrying the real address can mail real users; that is --override. A "capture everything" verb would be wrong in ~4 of 17 entries, silently — worse than being wrong in all of them. So every name is forced into a disposition, and two of the four stop the run: a name required by a template but absent from the source REFUSES (an empty substitutes to nothing and the app boots misconfigured), as does one name carrying different values on two resources. generated_secrets is a manifest property rather than a flag the operator must remember, because the manifest is what knows DATABASE_URL comes from a database it declares. An entry no template refers to is a hard error: a guard standing over nothing reads like a guard, and the likeliest cause is a typo whose real name is then captured from the source instead of placeheld. Secret hygiene, all covered by tests asserting on real values: - the plan prints names and provenance, NEVER values - an --override's value comes from $CAST_CAPTURE_<NAME>, never argv (`ps`) - plaintext is piped to age on stdin — never a temp file, stdout, or history - an existing store is not overwritten without --force: it may hold the only copy of values the source no longer has (apply's never-delete, applied here) capture inherits diff's absent-target refusal (D-237) — against a project that isn't there it would report every secret as missing, an alarming report about the wrong box — plus the team assert and the --path/--env prod ban. The last gate is a typed confirmation of the environment's name; there is no --yes. The end-to-end test decrypts the store cast wrote and asserts on its contents, so "exactly the names the manifest requires, no more and no fewer" is checked against real ciphertext rather than against cast's own console output. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 16:51:43 +00:00
import {
type ResolvedEnv,
feat(resolve): derive DATABASE_URL/REDIS_URL from the database cast created (#60) Add a ${resource:<name>.url} env-template ref that resolves to the internal URL of a database the same manifest declares, read back from the live resource's internal_db_url — never stored in the age store, never decrypted, never printed. This deletes the two-pass generated-secret bootstrap for a database's own URL rather than automating it: no placeholder, no stored copy to drift or overwrite, and a rotated password is simply followed on the next apply. Resolution runs in one function (fillDerivedEnv) against two URL maps: at diff time against databases already on the box (so a matching app shows no drift — killing the "secret DATABASE_URL differs" noise that ran on every plan), and in the executor at apply time against a database created earlier in the same run (the from-nothing case; apply acts databases-before-applications, #45). The unresolved sentinel is never written — the executor refuses, rather than write a blank that boots the app pointed at nothing, and re-running once the database is up resolves it as an ordinary update. A ${resource:X.url} naming a database the manifest does not declare, or an attribute other than .url, is a hard plan-time error refused by every verb that opens a template (apply, diff, capture). generated_secrets and the two-pass bootstrap remain for the residual class — a provider-generated value that genuinely is not derivable. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 23:46:26 +00:00
fillDerivedEnv,
feat(resolve): derive base-URL env vars from manifest domains via ${domain:...} (#66) A public base URL an app reads (LANDING_BASE_URL, ADMIN_WEB_BASE_URL) is a fact the manifest already states in `domains`/`service_domains` — the same fields cast parses to reconcile Coolify domains. Hand-transcribing it into an env template is a second copy that drifts (incubator's prod LANDING_BASE_URL silently kept a pre-apex host). So a template can now say it directly: LANDING_BASE_URL=${domain:landing} ADMIN_WEB_BASE_URL=${domain:core.admin} - ${domain:<app>} -> applications.<app>.domains[0] - ${domain:<app>.<service>} -> applications.<app>.service_domains.<service>[0] Symmetric with ${resource:...} (#60) — parse -> sentinel -> validate -> fill — but a domain is PURE MANIFEST DATA, known at plan time, so it resolves fully in desiredFromManifest against a map built from the manifest: no live read, no executor deferral, no unresolved-at-write path. Domains are PUBLIC, so they resolve to secret:false (printed in diffs) and read as plain literals downstream (no diff.ts change). Not secrets: excluded from templateRefs, never captured. assertDomainRefs is the single validation gate (apply/diff/capture), refusing an undeclared app/service, a wrong-shape ref, or an empty/blank domain list before the sentinel can escape. Applications only (Coolify 4.1.2 can't set service domains). REPORTING_TZ-style operator literals stay literal. Closes #66. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 12:02:33 +00:00
fillDomainEnv,
feat: cast capture — adopt a hand-built Coolify into the age secret store (#15) cast was scoped to the steady state: manifest → Coolify, forever. It had no adoption path — no way to bootstrap the age store from an instance built by hand, before any manifest existed. The operator did it by hand: curl the envs, assemble 17 name=value pairs into /dev/shm/prod.env, age -r, shred. Every input to that pipeline is something cast already has, so a human was shuffling cast's own inputs through a terminal, with the leak (scrollback, history, a tmp file that never got shredded) and the silent miss both live. cast capture <org>/<repo> --env <env> [--generated N] [--override N] [--force] The required set comes from the MANIFEST, not the box: the ${...} refs in that environment's env templates, read by the same parser apply uses to demand them. resolveTemplate and templateRefs now share one grammar — a drift between them would mean capture collects a different set than apply later requires, which is exactly the "a name silently missed" failure this verb exists to remove. The mapping is deliberately NOT mechanical. A DATABASE_URL read off the source points at the SOURCE box's Postgres: confidently wrong, entirely plausible, and the target's real URL does not exist until Coolify creates the resource. So the manifest declares `generated_secrets:` and those names are written as the literal `pending-coolify-generated`. staging's ADMIN_EMAIL must be the operator, not the source's — staging and prod share a Mailgun domain, so a staging box carrying the real address can mail real users; that is --override. A "capture everything" verb would be wrong in ~4 of 17 entries, silently — worse than being wrong in all of them. So every name is forced into a disposition, and two of the four stop the run: a name required by a template but absent from the source REFUSES (an empty substitutes to nothing and the app boots misconfigured), as does one name carrying different values on two resources. generated_secrets is a manifest property rather than a flag the operator must remember, because the manifest is what knows DATABASE_URL comes from a database it declares. An entry no template refers to is a hard error: a guard standing over nothing reads like a guard, and the likeliest cause is a typo whose real name is then captured from the source instead of placeheld. Secret hygiene, all covered by tests asserting on real values: - the plan prints names and provenance, NEVER values - an --override's value comes from $CAST_CAPTURE_<NAME>, never argv (`ps`) - plaintext is piped to age on stdin — never a temp file, stdout, or history - an existing store is not overwritten without --force: it may hold the only copy of values the source no longer has (apply's never-delete, applied here) capture inherits diff's absent-target refusal (D-237) — against a project that isn't there it would report every secret as missing, an alarming report about the wrong box — plus the team assert and the --path/--env prod ban. The last gate is a typed confirmation of the environment's name; there is no --yes. The end-to-end test decrypts the store cast wrote and asserts on its contents, so "exactly the names the manifest requires, no more and no fewer" is checked against real ciphertext rather than against cast's own console output. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 16:51:43 +00:00
resolveTemplate,
feat(resolve): derive base-URL env vars from manifest domains via ${domain:...} (#66) A public base URL an app reads (LANDING_BASE_URL, ADMIN_WEB_BASE_URL) is a fact the manifest already states in `domains`/`service_domains` — the same fields cast parses to reconcile Coolify domains. Hand-transcribing it into an env template is a second copy that drifts (incubator's prod LANDING_BASE_URL silently kept a pre-apex host). So a template can now say it directly: LANDING_BASE_URL=${domain:landing} ADMIN_WEB_BASE_URL=${domain:core.admin} - ${domain:<app>} -> applications.<app>.domains[0] - ${domain:<app>.<service>} -> applications.<app>.service_domains.<service>[0] Symmetric with ${resource:...} (#60) — parse -> sentinel -> validate -> fill — but a domain is PURE MANIFEST DATA, known at plan time, so it resolves fully in desiredFromManifest against a map built from the manifest: no live read, no executor deferral, no unresolved-at-write path. Domains are PUBLIC, so they resolve to secret:false (printed in diffs) and read as plain literals downstream (no diff.ts change). Not secrets: excluded from templateRefs, never captured. assertDomainRefs is the single validation gate (apply/diff/capture), refusing an undeclared app/service, a wrong-shape ref, or an empty/blank domain list before the sentinel can escape. Applications only (Coolify 4.1.2 can't set service domains). REPORTING_TZ-style operator literals stay literal. Closes #66. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 12:02:33 +00:00
templateDomainRefs,
feat: read-side coordinates (#17, #18) + cast inventory (#19) Three fixes at one seam: cast could not READ a box it did not build. #17 — the environment had no read-side coordinate. `--project` exists because a hand-built project is called whatever someone typed. The environment has the identical problem and had no flag, so reading a legacy box forced a choice between mutating that box's UI and renaming OUR environment to match it. The second is what happened: `prod` became `production` across the manifest and environments.yaml — a box being deleted next week naming the environment of the box that replaces it, permanently (apply creates the environment from --env), moving the store to incubator.production.env.age and invalidating every runbook. Reverted. `--environment` is now the coordinate. `--env` stays OURS: manifest block, binding, age key, store path, team assert. `--environment` is theirs, on the wire, and nothing else. #18 — an absent RESOURCE reported as N missing secrets. The D-237 lie, one level deeper. A resource that is absent reads back exactly like one present with no env vars, so capture reported all 15 required names as individually MISSING — from a box that was serving production and sending mail at that moment — and offered --override as the remedy. Taking that offer would have "worked": a valid store, hand-carried values, and the real finding (the manifest and the box disagree about what the app is called) buried. capture now refuses on the resource, names what does exist, and only reports per-name MISSING for resources it actually found — where it means what it says. #19 — cast inventory: see the box before you adopt it. The missing first step. cast could describe a box it built, change one, and take values off one for names a manifest declares — but not tell you what is on a box you did not build, which is the first thing adoption needs. Every mismatch above surfaced as a refusal from a verb already committed to a course of action, and the tempting fix for two of them was to bend the manifest toward the legacy box. inventory reads resources and env var KEYS (never values), sorts them into on-both / manifest-only / box-only, and needs no store, no age key and no recipient — it runs before adoption exists. Its output is a document: inventory → human reads → manifest PR → capture → apply That boundary is what lets capture stay strict. inventory may read everything, because a person reads its output. capture may only write what the manifest declares, because `apply` reads its output. Same box, two consumers, two contracts. A manifest-draft emitter is deliberately NOT included: it would be one `cp` away from becoming desired state, which is the failure this design exists to prevent. Zero drift against a hand-built box is reported as suspicious, not as a pass. npm run check + build clean; 164 tests passing, 18 files (was 151/16). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 18:20:53 +00:00
templateKeys,
feat: cast capture — adopt a hand-built Coolify into the age secret store (#15) cast was scoped to the steady state: manifest → Coolify, forever. It had no adoption path — no way to bootstrap the age store from an instance built by hand, before any manifest existed. The operator did it by hand: curl the envs, assemble 17 name=value pairs into /dev/shm/prod.env, age -r, shred. Every input to that pipeline is something cast already has, so a human was shuffling cast's own inputs through a terminal, with the leak (scrollback, history, a tmp file that never got shredded) and the silent miss both live. cast capture <org>/<repo> --env <env> [--generated N] [--override N] [--force] The required set comes from the MANIFEST, not the box: the ${...} refs in that environment's env templates, read by the same parser apply uses to demand them. resolveTemplate and templateRefs now share one grammar — a drift between them would mean capture collects a different set than apply later requires, which is exactly the "a name silently missed" failure this verb exists to remove. The mapping is deliberately NOT mechanical. A DATABASE_URL read off the source points at the SOURCE box's Postgres: confidently wrong, entirely plausible, and the target's real URL does not exist until Coolify creates the resource. So the manifest declares `generated_secrets:` and those names are written as the literal `pending-coolify-generated`. staging's ADMIN_EMAIL must be the operator, not the source's — staging and prod share a Mailgun domain, so a staging box carrying the real address can mail real users; that is --override. A "capture everything" verb would be wrong in ~4 of 17 entries, silently — worse than being wrong in all of them. So every name is forced into a disposition, and two of the four stop the run: a name required by a template but absent from the source REFUSES (an empty substitutes to nothing and the app boots misconfigured), as does one name carrying different values on two resources. generated_secrets is a manifest property rather than a flag the operator must remember, because the manifest is what knows DATABASE_URL comes from a database it declares. An entry no template refers to is a hard error: a guard standing over nothing reads like a guard, and the likeliest cause is a typo whose real name is then captured from the source instead of placeheld. Secret hygiene, all covered by tests asserting on real values: - the plan prints names and provenance, NEVER values - an --override's value comes from $CAST_CAPTURE_<NAME>, never argv (`ps`) - plaintext is piped to age on stdin — never a temp file, stdout, or history - an existing store is not overwritten without --force: it may hold the only copy of values the source no longer has (apply's never-delete, applied here) capture inherits diff's absent-target refusal (D-237) — against a project that isn't there it would report every secret as missing, an alarming report about the wrong box — plus the team assert and the --path/--env prod ban. The last gate is a typed confirmation of the environment's name; there is no --yes. The end-to-end test decrypts the store cast wrote and asserts on its contents, so "exactly the names the manifest requires, no more and no fewer" is checked against real ciphertext rather than against cast's own console output. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 16:51:43 +00:00
templateRefs,
feat(resolve): derive DATABASE_URL/REDIS_URL from the database cast created (#60) Add a ${resource:<name>.url} env-template ref that resolves to the internal URL of a database the same manifest declares, read back from the live resource's internal_db_url — never stored in the age store, never decrypted, never printed. This deletes the two-pass generated-secret bootstrap for a database's own URL rather than automating it: no placeholder, no stored copy to drift or overwrite, and a rotated password is simply followed on the next apply. Resolution runs in one function (fillDerivedEnv) against two URL maps: at diff time against databases already on the box (so a matching app shows no drift — killing the "secret DATABASE_URL differs" noise that ran on every plan), and in the executor at apply time against a database created earlier in the same run (the from-nothing case; apply acts databases-before-applications, #45). The unresolved sentinel is never written — the executor refuses, rather than write a blank that boots the app pointed at nothing, and re-running once the database is up resolves it as an ordinary update. A ${resource:X.url} naming a database the manifest does not declare, or an attribute other than .url, is a hard plan-time error refused by every verb that opens a template (apply, diff, capture). generated_secrets and the two-pass bootstrap remain for the residual class — a provider-generated value that genuinely is not derivable. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 23:46:26 +00:00
templateResourceRefs,
feat: cast capture — adopt a hand-built Coolify into the age secret store (#15) cast was scoped to the steady state: manifest → Coolify, forever. It had no adoption path — no way to bootstrap the age store from an instance built by hand, before any manifest existed. The operator did it by hand: curl the envs, assemble 17 name=value pairs into /dev/shm/prod.env, age -r, shred. Every input to that pipeline is something cast already has, so a human was shuffling cast's own inputs through a terminal, with the leak (scrollback, history, a tmp file that never got shredded) and the silent miss both live. cast capture <org>/<repo> --env <env> [--generated N] [--override N] [--force] The required set comes from the MANIFEST, not the box: the ${...} refs in that environment's env templates, read by the same parser apply uses to demand them. resolveTemplate and templateRefs now share one grammar — a drift between them would mean capture collects a different set than apply later requires, which is exactly the "a name silently missed" failure this verb exists to remove. The mapping is deliberately NOT mechanical. A DATABASE_URL read off the source points at the SOURCE box's Postgres: confidently wrong, entirely plausible, and the target's real URL does not exist until Coolify creates the resource. So the manifest declares `generated_secrets:` and those names are written as the literal `pending-coolify-generated`. staging's ADMIN_EMAIL must be the operator, not the source's — staging and prod share a Mailgun domain, so a staging box carrying the real address can mail real users; that is --override. A "capture everything" verb would be wrong in ~4 of 17 entries, silently — worse than being wrong in all of them. So every name is forced into a disposition, and two of the four stop the run: a name required by a template but absent from the source REFUSES (an empty substitutes to nothing and the app boots misconfigured), as does one name carrying different values on two resources. generated_secrets is a manifest property rather than a flag the operator must remember, because the manifest is what knows DATABASE_URL comes from a database it declares. An entry no template refers to is a hard error: a guard standing over nothing reads like a guard, and the likeliest cause is a typo whose real name is then captured from the source instead of placeheld. Secret hygiene, all covered by tests asserting on real values: - the plan prints names and provenance, NEVER values - an --override's value comes from $CAST_CAPTURE_<NAME>, never argv (`ps`) - plaintext is piped to age on stdin — never a temp file, stdout, or history - an existing store is not overwritten without --force: it may hold the only copy of values the source no longer has (apply's never-delete, applied here) capture inherits diff's absent-target refusal (D-237) — against a project that isn't there it would report every secret as missing, an alarming report about the wrong box — plus the team assert and the --path/--env prod ban. The last gate is a typed confirmation of the environment's name; there is no --yes. The end-to-end test decrypts the store cast wrote and asserts on its contents, so "exactly the names the manifest requires, no more and no fewer" is checked against real ciphertext rather than against cast's own console output. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 16:51:43 +00:00
} from "./envtemplate.js";
feat(resolve): derive base-URL env vars from manifest domains via ${domain:...} (#66) A public base URL an app reads (LANDING_BASE_URL, ADMIN_WEB_BASE_URL) is a fact the manifest already states in `domains`/`service_domains` — the same fields cast parses to reconcile Coolify domains. Hand-transcribing it into an env template is a second copy that drifts (incubator's prod LANDING_BASE_URL silently kept a pre-apex host). So a template can now say it directly: LANDING_BASE_URL=${domain:landing} ADMIN_WEB_BASE_URL=${domain:core.admin} - ${domain:<app>} -> applications.<app>.domains[0] - ${domain:<app>.<service>} -> applications.<app>.service_domains.<service>[0] Symmetric with ${resource:...} (#60) — parse -> sentinel -> validate -> fill — but a domain is PURE MANIFEST DATA, known at plan time, so it resolves fully in desiredFromManifest against a map built from the manifest: no live read, no executor deferral, no unresolved-at-write path. Domains are PUBLIC, so they resolve to secret:false (printed in diffs) and read as plain literals downstream (no diff.ts change). Not secrets: excluded from templateRefs, never captured. assertDomainRefs is the single validation gate (apply/diff/capture), refusing an undeclared app/service, a wrong-shape ref, or an empty/blank domain list before the sentinel can escape. Applications only (Coolify 4.1.2 can't set service domains). REPORTING_TZ-style operator literals stay literal. Closes #66. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 12:02:33 +00:00
import type { EnvironmentSpec } from "./manifest.js";
feat: cast — the Coolify executor, extracted from the infra state repo Public tool, private state. cast holds no hostnames, no bindings, no secrets: it joins a product repo's .infra/ manifest with a state directory you point it at, and makes Coolify match. Extracted from heavy-duty/infra, which was half tool and half state — the inconsistency that made it impossible to say whether "infra" named a CLI or a runbook. rig builds the boxes; cast fills them; infra is what they are filled with. Two changes were required to make it genuinely stateless and publishable: - The implicit cwd contract (environments.yaml / secrets/ / .coolify.env resolved against the working directory, silently reading the wrong file from the wrong place) is now an explicit --state <dir> / $CAST_STATE. - BANNED_IN_PROD — a hardcoded list of one product's ALLOW_* flags, the only product knowledge in the executor — becomes the generic, operator- owned environments.<env>.forbidden_var_patterns. The guard now lives in private state, so a product-side change cannot lower its own guard, and it is a pattern rather than a list, so it catches unforeseen siblings. Age identities resolve as $CAST_AGE_KEY_FILE_<ENV> then ~/.config/cast/age-<env>.key — which is the entire attended-vs-unattended apply mechanism, with no environment names known to the tool. Instance identity (org names, the GitHub App name, founder domains) is out of the fixtures and out of register-github-app.sh, which took APP_NAME and ORG as arguments rather than baking them in. 69 tests green; bin/cast + curl installer mirror rig's shape. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 12:25:44 +00:00
import { loadManifest } from "./manifest.js";
fix: never write an env var whose name Coolify injects itself (#50) Coolify injects SOURCE_COMMIT and the COOLIFY_* family into an application's runtime environment itself, and SKIPS its own injection of a name the resource already carries a var of (ApplicationDeploymentJob.php v4.1.2, line 2994 — `->where('key', 'SOURCE_COMMIT')->isEmpty()`). A resource-level var of that name therefore SUPPRESSES the platform's value. An empty one suppresses it just as completely: presence, not value. And it fails green — the deploy succeeds, health checks pass, and the only symptom is /version reporting "unknown", the endpoint a production cutover is gated on (D-266). The rule is now a property of cast, not of one code path. A new src/reserved.ts owns it, and every place cast touches an env var honors it: - resolve — every manifest read (desiredFromManifest, requiredSecrets, manifestResources) refuses a template declaring a reserved name, before any write. So apply, diff, capture and inventory all refuse identically. - draft — a reserved name read off a live box gets its own provenance, `suppressed`: out of the template, out of the age store, its live value read into no artifact, and named in UNCAPTURED.md with the consequence. - diff — promoted out of the remove-candidate orphan list ("apply never removes these; read them by eye") and printed as a FINDING with its consequence. Not clean. apply still never deletes: cast reports, the human removes it. - capture (classify) and cli (syncEnv) carry the same assertion at the file and at the wire — unreachable through the CLI today, and kept because the invariant is "cast never writes one", not "the CLI happens to check first". - smoke writes an env var too; its probe names are asserted outside the space. The rule lives in cast's code, NOT beside forbidden_var_patterns in private state: that one is policy an environment may set for itself, this one is a fact about Coolify, true on every box — nothing a manifest change could lower. 19 tests in test/reserved.test.ts, one per path. Closes #50.
2026-07-14 22:29:23 +00:00
import {
type ReservedHit,
assertNoReservedEnvNames,
reservedHits,
} from "./reserved.js";
feat: cast — the Coolify executor, extracted from the infra state repo Public tool, private state. cast holds no hostnames, no bindings, no secrets: it joins a product repo's .infra/ manifest with a state directory you point it at, and makes Coolify match. Extracted from heavy-duty/infra, which was half tool and half state — the inconsistency that made it impossible to say whether "infra" named a CLI or a runbook. rig builds the boxes; cast fills them; infra is what they are filled with. Two changes were required to make it genuinely stateless and publishable: - The implicit cwd contract (environments.yaml / secrets/ / .coolify.env resolved against the working directory, silently reading the wrong file from the wrong place) is now an explicit --state <dir> / $CAST_STATE. - BANNED_IN_PROD — a hardcoded list of one product's ALLOW_* flags, the only product knowledge in the executor — becomes the generic, operator- owned environments.<env>.forbidden_var_patterns. The guard now lives in private state, so a product-side change cannot lower its own guard, and it is a pattern rather than a list, so it catches unforeseen siblings. Age identities resolve as $CAST_AGE_KEY_FILE_<ENV> then ~/.config/cast/age-<env>.key — which is the entire attended-vs-unattended apply mechanism, with no environment names known to the tool. Instance identity (org names, the GitHub App name, founder domains) is out of the fixtures and out of register-github-app.sh, which took APP_NAME and ORG as arguments rather than baking them in. 69 tests green; bin/cast + curl installer mirror rig's shape. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 12:25:44 +00:00
fix: authenticate clones via gh / token, never fall into git's prompt (#13) resolveCheckout shelled out to a bare `git clone` and relied entirely on the ambient credential helper. On a workstation with none configured, git falls through to its interactive username/password prompt — which GitHub no longer accepts — and the resulting error talks about *the repository* rather than about cast's missing credentials. Being logged into `gh` does not help: `gh auth login` alone does not wire git's helper (that is `gh auth setup-git`, a separate act most people never run). Not routable around for prod: resolveCheckout refuses --path with --env prod, so the clone is the only path and its auth is mandatory. cast now resolves credentials itself, in order: `gh` borrowed as a per-invocation credential helper (no mutation of the user's global git config), then GITHUB_TOKEN / GH_TOKEN, then the ambient helper. The token is never embedded in the clone URL or in http.extraheader — both leak it into `ps`, and the latter persists it into the clone's git config. The helper reads it from the environment at run time, so what lands in argv is the literal text `$CAST_GIT_TOKEN`, never its value. GIT_TERMINAL_PROMPT=0 on every path: whichever credential was used, git may never fall through to a prompt it cannot satisfy — it can only hang, or hide the real fault. When there were no credentials at all, cast now says so, and names the fix. Note that the empty `credential.helper=` reset clears URL-scoped helpers (`credential.https://github.com.helper`, what `gh auth setup-git` writes) as well as generic ones — verified against a live private clone, along with all three acceptance criteria. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 16:30:04 +00:00
// How cast authenticated (or failed to authenticate) a clone.
//
// gh — `gh` is installed and holds a token; borrowed as a credential
// helper for this invocation only
// token — GITHUB_TOKEN / GH_TOKEN in the environment (the CI path)
// ambient — neither; whatever git's own credential helper does, if anything
export type GitAuth = {
source: "gh" | "token" | "ambient";
configArgs: string[];
env: Record<string, string>;
};
// A credential helper reads the token from the ENVIRONMENT at run time. The
// alternatives both leak it: a token in the clone URL shows up in `ps` and in
// git's own error messages, and `http.extraheader` additionally persists into
// the clone's .git/config. What lands in argv here is the literal text
// `$CAST_GIT_TOKEN`, never its value.
const TOKEN_HELPER =
'!f() { test "$1" = get || exit 0; echo username=x-access-token; echo "password=$CAST_GIT_TOKEN"; }; f';
// `gh auth login` alone does NOT wire git's credential helper — that is
// `gh auth setup-git`, a separate act most people never run. So being logged
// into `gh` does not make `git clone` work, which is exactly the trap #13
// fell into. Borrowing gh as a helper for this one invocation closes that gap
// without mutating the operator's global git config.
const GH_HELPER = "!gh auth git-credential";
function ghHasToken(): boolean {
try {
// A local keyring/config read, not a network call. We never keep the
// value — the helper re-reads it inside git.
execFileSync("gh", ["auth", "token"], { stdio: "pipe" });
return true;
} catch {
return false;
}
}
// Resolve clone credentials INSIDE cast, in a fixed order, rather than leaving
// it to whatever the ambient git config happens to do. `credential.helper=`
// (empty) first RESETS the inherited helper list — otherwise a helper
// configured globally is consulted before ours and silently decides the
// outcome, which is the same "the connection target is implicit in a file's
// contents" problem #14 is about.
export function resolveGitAuth(
env: NodeJS.ProcessEnv = process.env,
hasGh: () => boolean = ghHasToken,
): GitAuth {
if (hasGh()) {
return {
source: "gh",
configArgs: [
"-c",
"credential.helper=",
"-c",
`credential.helper=${GH_HELPER}`,
],
env: {},
};
}
const token = env.GITHUB_TOKEN || env.GH_TOKEN;
if (token) {
return {
source: "token",
configArgs: [
"-c",
"credential.helper=",
"-c",
`credential.helper=${TOKEN_HELPER}`,
],
env: { CAST_GIT_TOKEN: token },
};
}
return { source: "ambient", configArgs: [], env: {} };
}
// GitHub answers "you cannot see this" with a 404, not a 403 — so a private
// repo you lack access to and a repo that does not exist are the same message
// on the wire. The failure text must not pick one; it has to name both, and
// name the credential cast actually used, or the operator debugs the wrong
// half. (The original bug reported *the repository* when the real fault was
// cast's missing credentials.)
export function cloneFailureMessage(
orgRepo: string,
auth: GitAuth,
stderr: string,
): string {
const detail = stderr.trim();
const tail = detail
? ["", "git said:", ...detail.split("\n").map((l) => ` ${l}`)]
: [];
if (auth.source === "ambient") {
return [
`cannot clone ${orgRepo}: no GitHub credentials.`,
"",
"cast looked for, in order:",
" 1. `gh` — not installed, or not logged in (`gh auth token` failed)",
" 2. GITHUB_TOKEN / GH_TOKEN — not set in the environment",
" 3. git's own credential helper — did not supply credentials either",
"",
"Run `gh auth login`, or set GITHUB_TOKEN. (`gh auth setup-git` also works,",
"but cast borrows `gh` as a credential helper on its own, so logging in is",
"enough — you do not need to change your global git config.)",
...tail,
].join("\n");
}
const used =
auth.source === "gh"
? "`gh` (borrowed as a credential helper for this clone)"
: "GITHUB_TOKEN / GH_TOKEN from the environment";
return [
`cannot clone ${orgRepo}: authenticated with ${used}, and GitHub still refused.`,
"",
"GitHub answers 'you cannot see this' with a 404, so this is one of:",
` - ${orgRepo} does not exist (check the slug)`,
" - it is private and this credential has no access to it",
" - the credential is expired, or lacks the `repo` scope",
...tail,
].join("\n");
}
feat: --all — every project in an environment, and a report that says so (#26) Every cast verb was single-project, so "do this to the whole instance" was a shell loop the operator wrote from memory — and the project they forgot is the one that drifted. `cast diff --env prod --all` and `cast apply --env prod --all` iterate the registry (#25) instead. The bulk of this is a refactor: the apply/diff block in cli.ts was one long inline body, and it is now `runProject` — checkout → secrets → desired → bindings → live → diff → optionally apply. Both the single-repo path and the `--all` loop call it, so there is exactly ONE implementation of what a project run is. A second, parallel fleet path is how the two would drift, and drift is the subject of this tool. `openCoolify` and the team assert are hoisted out of it: one --env means one instance and one team, so asserting once still lands strictly before the FIRST project's first read — the read is already the lie. Fails closed on the aggregate. A registered project cast cannot reach is an ERROR, never a skip: the clone failing, no manifest block for this environment, an absent or undecryptable store, an absent Coolify project/environment, any HTTP error. A silently skipped project reads exactly like a clean one — #12/#18/ #22 at fleet scale — so the report leads with COVERAGE (registered / read / clean / drifted / unreachable), and: diff --all 0 every registered project was READ, and every one is clean 1 every one was read, and at least one has drift 2 a project could not be read — outranking drift, because an unreadable project is not a diff result but the absence of one apply --all 0 every registered project applied; non-zero otherwise `diff --all` runs every project to completion (stopping hides the drift in the projects it never reached); `apply --all` STOPS at the first failure and names what it applied and what it did not touch (continuing to mutate a fleet after an unexplained failure is not a thing cast gets to do). Two refusals. An empty or absent registry refuses rather than printing "0 projects, clean" — an empty fleet reading as a clean fleet is the whole failure this is against; the message distinguishes an unmigrated state file from a registry pointed elsewhere and prints the YAML to write. And `--all` is mutually exclusive with the repo positional and with every single-project coordinate (--path, --project, --environment, --resource, --hostname-overlay): each names ONE project's checkout, ONE project's Coolify name, ONE box's resource names, and `--project X` across a fleet would point every project at the same Coolify project — a false report on diff, and on apply every manifest in the fleet written into one project. Also: `projectsIn`'s doc-comment guessed that `[]` made a fleet verb over an unmigrated state file "a clean no-op rather than a crash". It is precisely backwards, and now says so. And the --path/--env-prod refusal is hoisted to the CLI's up-front flag validation (one rule, one string, two call sites in resolve.ts) — it used to be caught only by accident of resolveCheckout running before the bindings load. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 20:21:27 +00:00
// Holds for every verb that reads a manifest (apply, diff, capture, inventory):
// a feature-branch checkout must not be able to decide what prod runs, nor which
// secret names land in prod's store.
//
// The rule is a value, not only a throw inside resolveCheckout, because the CLI
// refuses this combination UP FRONT — before it opens a state file, a store or a
// Coolify. A flag pairing that can never be honored must not need the rest of the
// invocation to be well-formed in order to be caught (it used to be caught late,
// and only by accident of resolveCheckout running before the bindings load). One
// rule, one string, two call sites — never two spellings of the same refusal.
export const PATH_IN_PROD_REFUSAL =
"refuses --path with --env prod: prod always reads the default branch";
export function refusesPathInProd(opts: {
env: string;
path?: string;
}): boolean {
return opts.path !== undefined && opts.env === "prod";
}
feat: cast — the Coolify executor, extracted from the infra state repo Public tool, private state. cast holds no hostnames, no bindings, no secrets: it joins a product repo's .infra/ manifest with a state directory you point it at, and makes Coolify match. Extracted from heavy-duty/infra, which was half tool and half state — the inconsistency that made it impossible to say whether "infra" named a CLI or a runbook. rig builds the boxes; cast fills them; infra is what they are filled with. Two changes were required to make it genuinely stateless and publishable: - The implicit cwd contract (environments.yaml / secrets/ / .coolify.env resolved against the working directory, silently reading the wrong file from the wrong place) is now an explicit --state <dir> / $CAST_STATE. - BANNED_IN_PROD — a hardcoded list of one product's ALLOW_* flags, the only product knowledge in the executor — becomes the generic, operator- owned environments.<env>.forbidden_var_patterns. The guard now lives in private state, so a product-side change cannot lower its own guard, and it is a pattern rather than a list, so it catches unforeseen siblings. Age identities resolve as $CAST_AGE_KEY_FILE_<ENV> then ~/.config/cast/age-<env>.key — which is the entire attended-vs-unattended apply mechanism, with no environment names known to the tool. Instance identity (org names, the GitHub App name, founder domains) is out of the fixtures and out of register-github-app.sh, which took APP_NAME and ORG as arguments rather than baking them in. 69 tests green; bin/cast + curl installer mirror rig's shape. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 12:25:44 +00:00
export function resolveCheckout(
orgRepo: string,
opts: { env: string; path?: string },
): string {
feat: --all — every project in an environment, and a report that says so (#26) Every cast verb was single-project, so "do this to the whole instance" was a shell loop the operator wrote from memory — and the project they forgot is the one that drifted. `cast diff --env prod --all` and `cast apply --env prod --all` iterate the registry (#25) instead. The bulk of this is a refactor: the apply/diff block in cli.ts was one long inline body, and it is now `runProject` — checkout → secrets → desired → bindings → live → diff → optionally apply. Both the single-repo path and the `--all` loop call it, so there is exactly ONE implementation of what a project run is. A second, parallel fleet path is how the two would drift, and drift is the subject of this tool. `openCoolify` and the team assert are hoisted out of it: one --env means one instance and one team, so asserting once still lands strictly before the FIRST project's first read — the read is already the lie. Fails closed on the aggregate. A registered project cast cannot reach is an ERROR, never a skip: the clone failing, no manifest block for this environment, an absent or undecryptable store, an absent Coolify project/environment, any HTTP error. A silently skipped project reads exactly like a clean one — #12/#18/ #22 at fleet scale — so the report leads with COVERAGE (registered / read / clean / drifted / unreachable), and: diff --all 0 every registered project was READ, and every one is clean 1 every one was read, and at least one has drift 2 a project could not be read — outranking drift, because an unreadable project is not a diff result but the absence of one apply --all 0 every registered project applied; non-zero otherwise `diff --all` runs every project to completion (stopping hides the drift in the projects it never reached); `apply --all` STOPS at the first failure and names what it applied and what it did not touch (continuing to mutate a fleet after an unexplained failure is not a thing cast gets to do). Two refusals. An empty or absent registry refuses rather than printing "0 projects, clean" — an empty fleet reading as a clean fleet is the whole failure this is against; the message distinguishes an unmigrated state file from a registry pointed elsewhere and prints the YAML to write. And `--all` is mutually exclusive with the repo positional and with every single-project coordinate (--path, --project, --environment, --resource, --hostname-overlay): each names ONE project's checkout, ONE project's Coolify name, ONE box's resource names, and `--project X` across a fleet would point every project at the same Coolify project — a false report on diff, and on apply every manifest in the fleet written into one project. Also: `projectsIn`'s doc-comment guessed that `[]` made a fleet verb over an unmigrated state file "a clean no-op rather than a crash". It is precisely backwards, and now says so. And the --path/--env-prod refusal is hoisted to the CLI's up-front flag validation (one rule, one string, two call sites in resolve.ts) — it used to be caught only by accident of resolveCheckout running before the bindings load. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 20:21:27 +00:00
if (refusesPathInProd(opts)) {
throw new Error(PATH_IN_PROD_REFUSAL);
feat: cast — the Coolify executor, extracted from the infra state repo Public tool, private state. cast holds no hostnames, no bindings, no secrets: it joins a product repo's .infra/ manifest with a state directory you point it at, and makes Coolify match. Extracted from heavy-duty/infra, which was half tool and half state — the inconsistency that made it impossible to say whether "infra" named a CLI or a runbook. rig builds the boxes; cast fills them; infra is what they are filled with. Two changes were required to make it genuinely stateless and publishable: - The implicit cwd contract (environments.yaml / secrets/ / .coolify.env resolved against the working directory, silently reading the wrong file from the wrong place) is now an explicit --state <dir> / $CAST_STATE. - BANNED_IN_PROD — a hardcoded list of one product's ALLOW_* flags, the only product knowledge in the executor — becomes the generic, operator- owned environments.<env>.forbidden_var_patterns. The guard now lives in private state, so a product-side change cannot lower its own guard, and it is a pattern rather than a list, so it catches unforeseen siblings. Age identities resolve as $CAST_AGE_KEY_FILE_<ENV> then ~/.config/cast/age-<env>.key — which is the entire attended-vs-unattended apply mechanism, with no environment names known to the tool. Instance identity (org names, the GitHub App name, founder domains) is out of the fixtures and out of register-github-app.sh, which took APP_NAME and ORG as arguments rather than baking them in. 69 tests green; bin/cast + curl installer mirror rig's shape. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 12:25:44 +00:00
}
if (opts.path) return opts.path;
const dir = mkdtempSync(join(tmpdir(), "infra-checkout-"));
fix: authenticate clones via gh / token, never fall into git's prompt (#13) resolveCheckout shelled out to a bare `git clone` and relied entirely on the ambient credential helper. On a workstation with none configured, git falls through to its interactive username/password prompt — which GitHub no longer accepts — and the resulting error talks about *the repository* rather than about cast's missing credentials. Being logged into `gh` does not help: `gh auth login` alone does not wire git's helper (that is `gh auth setup-git`, a separate act most people never run). Not routable around for prod: resolveCheckout refuses --path with --env prod, so the clone is the only path and its auth is mandatory. cast now resolves credentials itself, in order: `gh` borrowed as a per-invocation credential helper (no mutation of the user's global git config), then GITHUB_TOKEN / GH_TOKEN, then the ambient helper. The token is never embedded in the clone URL or in http.extraheader — both leak it into `ps`, and the latter persists it into the clone's git config. The helper reads it from the environment at run time, so what lands in argv is the literal text `$CAST_GIT_TOKEN`, never its value. GIT_TERMINAL_PROMPT=0 on every path: whichever credential was used, git may never fall through to a prompt it cannot satisfy — it can only hang, or hide the real fault. When there were no credentials at all, cast now says so, and names the fix. Note that the empty `credential.helper=` reset clears URL-scoped helpers (`credential.https://github.com.helper`, what `gh auth setup-git` writes) as well as generic ones — verified against a live private clone, along with all three acceptance criteria. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 16:30:04 +00:00
const auth = resolveGitAuth();
try {
execFileSync(
"git",
[
...auth.configArgs,
"clone",
"--depth",
"1",
`https://github.com/${orgRepo}.git`,
dir,
],
{
stdio: "pipe",
env: {
...process.env,
...auth.env,
// Belt and braces: whatever credential path we took, git may NEVER
// fall through to its interactive username/password prompt. GitHub
// stopped accepting passwords there years ago, so it cannot succeed
// — it can only hang cast, or (in the original report) hand back an
// error about the repository that hides the real fault.
GIT_TERMINAL_PROMPT: "0",
},
},
);
} catch (err) {
const stderr = String((err as { stderr?: Buffer | string })?.stderr ?? "");
throw new Error(cloneFailureMessage(orgRepo, auth, stderr));
}
feat: cast — the Coolify executor, extracted from the infra state repo Public tool, private state. cast holds no hostnames, no bindings, no secrets: it joins a product repo's .infra/ manifest with a state directory you point it at, and makes Coolify match. Extracted from heavy-duty/infra, which was half tool and half state — the inconsistency that made it impossible to say whether "infra" named a CLI or a runbook. rig builds the boxes; cast fills them; infra is what they are filled with. Two changes were required to make it genuinely stateless and publishable: - The implicit cwd contract (environments.yaml / secrets/ / .coolify.env resolved against the working directory, silently reading the wrong file from the wrong place) is now an explicit --state <dir> / $CAST_STATE. - BANNED_IN_PROD — a hardcoded list of one product's ALLOW_* flags, the only product knowledge in the executor — becomes the generic, operator- owned environments.<env>.forbidden_var_patterns. The guard now lives in private state, so a product-side change cannot lower its own guard, and it is a pattern rather than a list, so it catches unforeseen siblings. Age identities resolve as $CAST_AGE_KEY_FILE_<ENV> then ~/.config/cast/age-<env>.key — which is the entire attended-vs-unattended apply mechanism, with no environment names known to the tool. Instance identity (org names, the GitHub App name, founder domains) is out of the fixtures and out of register-github-app.sh, which took APP_NAME and ORG as arguments rather than baking them in. 69 tests green; bin/cast + curl installer mirror rig's shape. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 12:25:44 +00:00
return dir;
}
feat: cast capture — adopt a hand-built Coolify into the age secret store (#15) cast was scoped to the steady state: manifest → Coolify, forever. It had no adoption path — no way to bootstrap the age store from an instance built by hand, before any manifest existed. The operator did it by hand: curl the envs, assemble 17 name=value pairs into /dev/shm/prod.env, age -r, shred. Every input to that pipeline is something cast already has, so a human was shuffling cast's own inputs through a terminal, with the leak (scrollback, history, a tmp file that never got shredded) and the silent miss both live. cast capture <org>/<repo> --env <env> [--generated N] [--override N] [--force] The required set comes from the MANIFEST, not the box: the ${...} refs in that environment's env templates, read by the same parser apply uses to demand them. resolveTemplate and templateRefs now share one grammar — a drift between them would mean capture collects a different set than apply later requires, which is exactly the "a name silently missed" failure this verb exists to remove. The mapping is deliberately NOT mechanical. A DATABASE_URL read off the source points at the SOURCE box's Postgres: confidently wrong, entirely plausible, and the target's real URL does not exist until Coolify creates the resource. So the manifest declares `generated_secrets:` and those names are written as the literal `pending-coolify-generated`. staging's ADMIN_EMAIL must be the operator, not the source's — staging and prod share a Mailgun domain, so a staging box carrying the real address can mail real users; that is --override. A "capture everything" verb would be wrong in ~4 of 17 entries, silently — worse than being wrong in all of them. So every name is forced into a disposition, and two of the four stop the run: a name required by a template but absent from the source REFUSES (an empty substitutes to nothing and the app boots misconfigured), as does one name carrying different values on two resources. generated_secrets is a manifest property rather than a flag the operator must remember, because the manifest is what knows DATABASE_URL comes from a database it declares. An entry no template refers to is a hard error: a guard standing over nothing reads like a guard, and the likeliest cause is a typo whose real name is then captured from the source instead of placeheld. Secret hygiene, all covered by tests asserting on real values: - the plan prints names and provenance, NEVER values - an --override's value comes from $CAST_CAPTURE_<NAME>, never argv (`ps`) - plaintext is piped to age on stdin — never a temp file, stdout, or history - an existing store is not overwritten without --force: it may hold the only copy of values the source no longer has (apply's never-delete, applied here) capture inherits diff's absent-target refusal (D-237) — against a project that isn't there it would report every secret as missing, an alarming report about the wrong box — plus the team assert and the --path/--env prod ban. The last gate is a typed confirmation of the environment's name; there is no --yes. The end-to-end test decrypts the store cast wrote and asserts on its contents, so "exactly the names the manifest requires, no more and no fewer" is checked against real ciphertext rather than against cast's own console output. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 16:51:43 +00:00
// One secret the manifest requires: the ${REF} a template names (the key it
// gets in the age store), the resource that needs it, and the env var it lands
// on there. That last pair is what `capture` reads the live value from — the
// store is keyed by REF, but the live box knows it as `resource.key`.
export type RequiredSecret = { ref: string; resource: string; key: string };
feat(resolve): derive DATABASE_URL/REDIS_URL from the database cast created (#60) Add a ${resource:<name>.url} env-template ref that resolves to the internal URL of a database the same manifest declares, read back from the live resource's internal_db_url — never stored in the age store, never decrypted, never printed. This deletes the two-pass generated-secret bootstrap for a database's own URL rather than automating it: no placeholder, no stored copy to drift or overwrite, and a rotated password is simply followed on the next apply. Resolution runs in one function (fillDerivedEnv) against two URL maps: at diff time against databases already on the box (so a matching app shows no drift — killing the "secret DATABASE_URL differs" noise that ran on every plan), and in the executor at apply time against a database created earlier in the same run (the from-nothing case; apply acts databases-before-applications, #45). The unresolved sentinel is never written — the executor refuses, rather than write a blank that boots the app pointed at nothing, and re-running once the database is up resolves it as an ordinary update. A ${resource:X.url} naming a database the manifest does not declare, or an attribute other than .url, is a hard plan-time error refused by every verb that opens a template (apply, diff, capture). generated_secrets and the two-pass bootstrap remain for the residual class — a provider-generated value that genuinely is not derivable. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 23:46:26 +00:00
// The dead-reference check, pointed at derived edges instead of generated
// secrets (#60). The same failure the generated_secrets check below catches — a
// name that resolves against nothing, dressed up as config that guards or
// derives something — and refused in the same voice, wherever a template is
// opened: `apply`, `diff`, and `capture` all validate before they act, because a
// `${resource:X.url}` naming a database the manifest does not declare is broken
// for all three, not just the verb about to write.
//
// - an attr other than `.url`: nothing else is derivable, so it can only be a
// mistake — named here rather than resolved to `undefined` and written blank.
// - a resource the manifest does not declare: the URL would resolve against
// nothing on every box, forever. The likeliest cause is a typo.
function assertResourceRefs(
envName: string,
databases: Set<string>,
refs: Array<{ key: string; resource: string; attr: string }>,
): void {
for (const r of refs) {
if (r.attr !== "url") {
throw new Error(
[
`manifest environment ${envName}: ${r.key} refers to \${resource:${r.resource}.${r.attr}}, an unknown resource attribute`,
"",
"Only `.url` is derivable — the internal URL of a database the manifest",
"declares. Fix the attribute, or make it a plain ${SECRET} the store holds.",
].join("\n"),
);
}
if (!databases.has(r.resource)) {
throw new Error(
[
`manifest environment ${envName}: ${r.key} refers to \${resource:${r.resource}.url}, but the manifest declares no database named ${r.resource}`,
"",
` declares: ${[...databases].sort().join(", ") || "(no databases)"}`,
"",
"A ${resource:…} ref derives the URL of a database this manifest creates. One",
"that names a database the manifest does not declare derives nothing, on every",
"box, forever — the likeliest cause is a typo. Fix the name, or declare the",
"database.",
].join("\n"),
);
}
}
}
feat(resolve): derive base-URL env vars from manifest domains via ${domain:...} (#66) A public base URL an app reads (LANDING_BASE_URL, ADMIN_WEB_BASE_URL) is a fact the manifest already states in `domains`/`service_domains` — the same fields cast parses to reconcile Coolify domains. Hand-transcribing it into an env template is a second copy that drifts (incubator's prod LANDING_BASE_URL silently kept a pre-apex host). So a template can now say it directly: LANDING_BASE_URL=${domain:landing} ADMIN_WEB_BASE_URL=${domain:core.admin} - ${domain:<app>} -> applications.<app>.domains[0] - ${domain:<app>.<service>} -> applications.<app>.service_domains.<service>[0] Symmetric with ${resource:...} (#60) — parse -> sentinel -> validate -> fill — but a domain is PURE MANIFEST DATA, known at plan time, so it resolves fully in desiredFromManifest against a map built from the manifest: no live read, no executor deferral, no unresolved-at-write path. Domains are PUBLIC, so they resolve to secret:false (printed in diffs) and read as plain literals downstream (no diff.ts change). Not secrets: excluded from templateRefs, never captured. assertDomainRefs is the single validation gate (apply/diff/capture), refusing an undeclared app/service, a wrong-shape ref, or an empty/blank domain list before the sentinel can escape. Applications only (Coolify 4.1.2 can't set service domains). REPORTING_TZ-style operator literals stay literal. Closes #66. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 12:02:33 +00:00
// The domains an environment's manifest declares, flattened to the map keys a
// ${domain:…} ref resolves against: `<app>` → `applications.<app>.domains[0]`,
// and `<app>.<service>` → `applications.<app>.service_domains.<service>[0]`. The
// [0] is the PRIMARY domain — a domain list may carry several, and a ref names
// the app, not an index. A malformed (missing/empty) array is simply not added:
// the lookup then misses and assertDomainRefs reports it, rather than this
// helper throwing far from the ref that caused it. Applications only — Coolify
// 4.1.2 cannot set service domains, and a service's own domains are unhonorable
// by apply anyway (see the service loop).
function buildDomainMap(envSpec: EnvironmentSpec): Record<string, string> {
const map: Record<string, string> = {};
for (const [name, app] of Object.entries(envSpec.applications)) {
if (app.domains && app.domains.length > 0) map[name] = app.domains[0];
for (const [svc, arr] of Object.entries(app.service_domains ?? {})) {
if (arr.length > 0) map[`${name}.${svc}`] = arr[0];
}
}
return map;
}
// The dead-reference check for domain refs, in the same voice as
// assertResourceRefs. A ${domain:…} ref is pure manifest data, so a ref that
// does not resolve is a ref that names something the manifest does not declare —
// caught at plan time, before the sentinel can escape, and refused by every verb
// that opens a template (`apply`, `diff`, `capture`). Each branch names what IS
// declared, so the fix is one edit away.
function assertDomainRefs(
envName: string,
applications: EnvironmentSpec["applications"],
refs: Array<{ key: string; app: string; service?: string }>,
): void {
const appNames = Object.keys(applications).sort();
for (const r of refs) {
const app = applications[r.app];
if (!app) {
throw new Error(
[
`manifest environment ${envName}: ${r.key} refers to \${domain:${r.app}${r.service ? `.${r.service}` : ""}}, but the manifest declares no application named ${r.app}`,
"",
` declares: ${appNames.join(", ") || "(no applications)"}`,
"",
"A ${domain:…} ref resolves to a public domain this manifest declares. One",
"that names an application the manifest does not declare resolves to nothing,",
"on every box, forever — the likeliest cause is a typo. Fix the name, or",
"declare the application.",
].join("\n"),
);
}
// Which SHAPE the app is, by KEY PRESENCE — not by array non-emptiness. The
// manifest schema makes `domains` and `service_domains` mutually exclusive
// and requires exactly one (AppSpecSchema superRefine: a non-compose app
// requires `domains` and forbids `service_domains`; a compose app the
// reverse), so a present-but-empty `domains: []` is still a domains app —
// asking about its array length here would mis-route a `${domain:app.svc}`
// ref into the unknown-service branch below with a misleading message.
const hasDomains = app.domains !== undefined;
const hasServiceDomains = app.service_domains !== undefined;
const svcNames = Object.keys(app.service_domains ?? {}).sort();
if (!r.service && hasServiceDomains && !hasDomains) {
throw new Error(
[
`manifest environment ${envName}: ${r.key} refers to \${domain:${r.app}}, but ${r.app} is a compose app whose domains live per service`,
"",
` services: ${svcNames.join(", ")}`,
"",
`Name one: write \${domain:${r.app}.<service>}.`,
].join("\n"),
);
}
if (r.service && hasDomains && !hasServiceDomains) {
throw new Error(
[
`manifest environment ${envName}: ${r.key} refers to \${domain:${r.app}.${r.service}}, but ${r.app} declares a plain \`domains\` list, not per-service domains`,
"",
`Drop the service: write \${domain:${r.app}}.`,
].join("\n"),
);
}
if (r.service && !(r.service in (app.service_domains ?? {}))) {
throw new Error(
[
`manifest environment ${envName}: ${r.key} refers to \${domain:${r.app}.${r.service}}, but ${r.app} declares no service named ${r.service}`,
"",
` services: ${svcNames.join(", ") || "(none)"}`,
"",
"Fix the service name, or declare it under the app's service_domains.",
].join("\n"),
);
}
// The selected array — the exact list this ref resolves against — must
// actually hold a domain. Missing, empty (`domains: []`), or a blank first
// entry (`domains: [""]`, which is schema-valid: a non-empty array of
// strings) all resolve to nothing, and the last would slip past buildDomainMap
// (it stores `""`) and past fillDomainEnv (whose `!== ""` guard reads `""` as
// unresolved) to leave the sentinel in a returned env. Caught here, so this
// assert stays the single gate and the sentinel can never escape.
const arr = r.service ? app.service_domains?.[r.service] : app.domains;
if (!arr || arr.length === 0 || arr[0] === "") {
throw new Error(
[
`manifest environment ${envName}: ${r.key} refers to \${domain:${r.app}${r.service ? `.${r.service}` : ""}}, but that domain list is empty or its first entry is blank`,
"",
"A ${domain:…} ref resolves to the FIRST domain in the list. An empty list,",
"or one whose first entry is an empty string, has none to resolve to —",
"declare a real domain, or drop the ref.",
].join("\n"),
);
}
}
}
feat: cast capture — adopt a hand-built Coolify into the age secret store (#15) cast was scoped to the steady state: manifest → Coolify, forever. It had no adoption path — no way to bootstrap the age store from an instance built by hand, before any manifest existed. The operator did it by hand: curl the envs, assemble 17 name=value pairs into /dev/shm/prod.env, age -r, shred. Every input to that pipeline is something cast already has, so a human was shuffling cast's own inputs through a terminal, with the leak (scrollback, history, a tmp file that never got shredded) and the silent miss both live. cast capture <org>/<repo> --env <env> [--generated N] [--override N] [--force] The required set comes from the MANIFEST, not the box: the ${...} refs in that environment's env templates, read by the same parser apply uses to demand them. resolveTemplate and templateRefs now share one grammar — a drift between them would mean capture collects a different set than apply later requires, which is exactly the "a name silently missed" failure this verb exists to remove. The mapping is deliberately NOT mechanical. A DATABASE_URL read off the source points at the SOURCE box's Postgres: confidently wrong, entirely plausible, and the target's real URL does not exist until Coolify creates the resource. So the manifest declares `generated_secrets:` and those names are written as the literal `pending-coolify-generated`. staging's ADMIN_EMAIL must be the operator, not the source's — staging and prod share a Mailgun domain, so a staging box carrying the real address can mail real users; that is --override. A "capture everything" verb would be wrong in ~4 of 17 entries, silently — worse than being wrong in all of them. So every name is forced into a disposition, and two of the four stop the run: a name required by a template but absent from the source REFUSES (an empty substitutes to nothing and the app boots misconfigured), as does one name carrying different values on two resources. generated_secrets is a manifest property rather than a flag the operator must remember, because the manifest is what knows DATABASE_URL comes from a database it declares. An entry no template refers to is a hard error: a guard standing over nothing reads like a guard, and the likeliest cause is a typo whose real name is then captured from the source instead of placeheld. Secret hygiene, all covered by tests asserting on real values: - the plan prints names and provenance, NEVER values - an --override's value comes from $CAST_CAPTURE_<NAME>, never argv (`ps`) - plaintext is piped to age on stdin — never a temp file, stdout, or history - an existing store is not overwritten without --force: it may hold the only copy of values the source no longer has (apply's never-delete, applied here) capture inherits diff's absent-target refusal (D-237) — against a project that isn't there it would report every secret as missing, an alarming report about the wrong box — plus the team assert and the --path/--env prod ban. The last gate is a typed confirmation of the environment's name; there is no --yes. The end-to-end test decrypts the store cast wrote and asserts on its contents, so "exactly the names the manifest requires, no more and no fewer" is checked against real ciphertext rather than against cast's own console output. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 16:51:43 +00:00
// Exactly the set of secret names an environment's manifest demands — the same
// set `apply` will later insist on, read from the same templates by the same
// parser. `capture` uses this to know what to go and fetch; nothing else has to
// be told, and nothing can be silently missed.
//
// Deliberately does NOT take a secrets map: at capture time the store does not
// exist yet. That is the whole point of the verb.
export function requiredSecrets(
checkoutDir: string,
envName: string,
): { required: RequiredSecret[]; generated: string[] } {
const manifest = loadManifest(join(checkoutDir, ".infra", "manifest.yaml"));
const envSpec = manifest.environments[envName];
if (!envSpec) {
throw new Error(
`environment ${envName} not in manifest (has: ${Object.keys(manifest.environments).join(", ") || "none"})`,
);
}
const required: RequiredSecret[] = [];
feat(resolve): derive DATABASE_URL/REDIS_URL from the database cast created (#60) Add a ${resource:<name>.url} env-template ref that resolves to the internal URL of a database the same manifest declares, read back from the live resource's internal_db_url — never stored in the age store, never decrypted, never printed. This deletes the two-pass generated-secret bootstrap for a database's own URL rather than automating it: no placeholder, no stored copy to drift or overwrite, and a rotated password is simply followed on the next apply. Resolution runs in one function (fillDerivedEnv) against two URL maps: at diff time against databases already on the box (so a matching app shows no drift — killing the "secret DATABASE_URL differs" noise that ran on every plan), and in the executor at apply time against a database created earlier in the same run (the from-nothing case; apply acts databases-before-applications, #45). The unresolved sentinel is never written — the executor refuses, rather than write a blank that boots the app pointed at nothing, and re-running once the database is up resolves it as an ordinary update. A ${resource:X.url} naming a database the manifest does not declare, or an attribute other than .url, is a hard plan-time error refused by every verb that opens a template (apply, diff, capture). generated_secrets and the two-pass bootstrap remain for the residual class — a provider-generated value that genuinely is not derivable. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 23:46:26 +00:00
const resourceRefs: Array<{ key: string; resource: string; attr: string }> =
[];
feat(resolve): derive base-URL env vars from manifest domains via ${domain:...} (#66) A public base URL an app reads (LANDING_BASE_URL, ADMIN_WEB_BASE_URL) is a fact the manifest already states in `domains`/`service_domains` — the same fields cast parses to reconcile Coolify domains. Hand-transcribing it into an env template is a second copy that drifts (incubator's prod LANDING_BASE_URL silently kept a pre-apex host). So a template can now say it directly: LANDING_BASE_URL=${domain:landing} ADMIN_WEB_BASE_URL=${domain:core.admin} - ${domain:<app>} -> applications.<app>.domains[0] - ${domain:<app>.<service>} -> applications.<app>.service_domains.<service>[0] Symmetric with ${resource:...} (#60) — parse -> sentinel -> validate -> fill — but a domain is PURE MANIFEST DATA, known at plan time, so it resolves fully in desiredFromManifest against a map built from the manifest: no live read, no executor deferral, no unresolved-at-write path. Domains are PUBLIC, so they resolve to secret:false (printed in diffs) and read as plain literals downstream (no diff.ts change). Not secrets: excluded from templateRefs, never captured. assertDomainRefs is the single validation gate (apply/diff/capture), refusing an undeclared app/service, a wrong-shape ref, or an empty/blank domain list before the sentinel can escape. Applications only (Coolify 4.1.2 can't set service domains). REPORTING_TZ-style operator literals stay literal. Closes #66. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 12:02:33 +00:00
const domainRefs: Array<{ key: string; app: string; service?: string }> = [];
fix: never write an env var whose name Coolify injects itself (#50) Coolify injects SOURCE_COMMIT and the COOLIFY_* family into an application's runtime environment itself, and SKIPS its own injection of a name the resource already carries a var of (ApplicationDeploymentJob.php v4.1.2, line 2994 — `->where('key', 'SOURCE_COMMIT')->isEmpty()`). A resource-level var of that name therefore SUPPRESSES the platform's value. An empty one suppresses it just as completely: presence, not value. And it fails green — the deploy succeeds, health checks pass, and the only symptom is /version reporting "unknown", the endpoint a production cutover is gated on (D-266). The rule is now a property of cast, not of one code path. A new src/reserved.ts owns it, and every place cast touches an env var honors it: - resolve — every manifest read (desiredFromManifest, requiredSecrets, manifestResources) refuses a template declaring a reserved name, before any write. So apply, diff, capture and inventory all refuse identically. - draft — a reserved name read off a live box gets its own provenance, `suppressed`: out of the template, out of the age store, its live value read into no artifact, and named in UNCAPTURED.md with the consequence. - diff — promoted out of the remove-candidate orphan list ("apply never removes these; read them by eye") and printed as a FINDING with its consequence. Not clean. apply still never deletes: cast reports, the human removes it. - capture (classify) and cli (syncEnv) carry the same assertion at the file and at the wire — unreachable through the CLI today, and kept because the invariant is "cast never writes one", not "the CLI happens to check first". - smoke writes an env var too; its probe names are asserted outside the space. The rule lives in cast's code, NOT beside forbidden_var_patterns in private state: that one is policy an environment may set for itself, this one is a fact about Coolify, true on every box — nothing a manifest change could lower. 19 tests in test/reserved.test.ts, one per path. Closes #50.
2026-07-14 22:29:23 +00:00
// Reserved names are checked HERE, and in manifestResources, and in
// desiredFromManifest — every function in this file that opens an env
// template, rather than once in the verb that writes. The rule is a property
// of cast, not of `apply`: a template that declares SOURCE_COMMIT is broken
// whether the verb about to run is going to write it (`apply`), store its live
// value (`capture`), or merely compare it (`diff`, `inventory`). Refusing in
// one place and reporting in another would leave `capture` writing a store for
// a manifest `apply` will refuse — a green run that guarantees a red one. See
// reserved.ts. (Reads ALL template keys, not just the ${…} refs: a bare
// `SOURCE_COMMIT=` literal suppresses the injection exactly as well.)
const reserved: ReservedHit[] = [];
feat: cast capture — adopt a hand-built Coolify into the age secret store (#15) cast was scoped to the steady state: manifest → Coolify, forever. It had no adoption path — no way to bootstrap the age store from an instance built by hand, before any manifest existed. The operator did it by hand: curl the envs, assemble 17 name=value pairs into /dev/shm/prod.env, age -r, shred. Every input to that pipeline is something cast already has, so a human was shuffling cast's own inputs through a terminal, with the leak (scrollback, history, a tmp file that never got shredded) and the silent miss both live. cast capture <org>/<repo> --env <env> [--generated N] [--override N] [--force] The required set comes from the MANIFEST, not the box: the ${...} refs in that environment's env templates, read by the same parser apply uses to demand them. resolveTemplate and templateRefs now share one grammar — a drift between them would mean capture collects a different set than apply later requires, which is exactly the "a name silently missed" failure this verb exists to remove. The mapping is deliberately NOT mechanical. A DATABASE_URL read off the source points at the SOURCE box's Postgres: confidently wrong, entirely plausible, and the target's real URL does not exist until Coolify creates the resource. So the manifest declares `generated_secrets:` and those names are written as the literal `pending-coolify-generated`. staging's ADMIN_EMAIL must be the operator, not the source's — staging and prod share a Mailgun domain, so a staging box carrying the real address can mail real users; that is --override. A "capture everything" verb would be wrong in ~4 of 17 entries, silently — worse than being wrong in all of them. So every name is forced into a disposition, and two of the four stop the run: a name required by a template but absent from the source REFUSES (an empty substitutes to nothing and the app boots misconfigured), as does one name carrying different values on two resources. generated_secrets is a manifest property rather than a flag the operator must remember, because the manifest is what knows DATABASE_URL comes from a database it declares. An entry no template refers to is a hard error: a guard standing over nothing reads like a guard, and the likeliest cause is a typo whose real name is then captured from the source instead of placeheld. Secret hygiene, all covered by tests asserting on real values: - the plan prints names and provenance, NEVER values - an --override's value comes from $CAST_CAPTURE_<NAME>, never argv (`ps`) - plaintext is piped to age on stdin — never a temp file, stdout, or history - an existing store is not overwritten without --force: it may hold the only copy of values the source no longer has (apply's never-delete, applied here) capture inherits diff's absent-target refusal (D-237) — against a project that isn't there it would report every secret as missing, an alarming report about the wrong box — plus the team assert and the --path/--env prod ban. The last gate is a typed confirmation of the environment's name; there is no --yes. The end-to-end test decrypts the store cast wrote and asserts on its contents, so "exactly the names the manifest requires, no more and no fewer" is checked against real ciphertext rather than against cast's own console output. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 16:51:43 +00:00
const collect = (resource: string, template?: string) => {
if (!template) return;
const file = join(checkoutDir, ".infra", "env", template);
if (!existsSync(file))
throw new Error(
`env template missing: ${file} (referenced by ${resource})`,
);
fix: never write an env var whose name Coolify injects itself (#50) Coolify injects SOURCE_COMMIT and the COOLIFY_* family into an application's runtime environment itself, and SKIPS its own injection of a name the resource already carries a var of (ApplicationDeploymentJob.php v4.1.2, line 2994 — `->where('key', 'SOURCE_COMMIT')->isEmpty()`). A resource-level var of that name therefore SUPPRESSES the platform's value. An empty one suppresses it just as completely: presence, not value. And it fails green — the deploy succeeds, health checks pass, and the only symptom is /version reporting "unknown", the endpoint a production cutover is gated on (D-266). The rule is now a property of cast, not of one code path. A new src/reserved.ts owns it, and every place cast touches an env var honors it: - resolve — every manifest read (desiredFromManifest, requiredSecrets, manifestResources) refuses a template declaring a reserved name, before any write. So apply, diff, capture and inventory all refuse identically. - draft — a reserved name read off a live box gets its own provenance, `suppressed`: out of the template, out of the age store, its live value read into no artifact, and named in UNCAPTURED.md with the consequence. - diff — promoted out of the remove-candidate orphan list ("apply never removes these; read them by eye") and printed as a FINDING with its consequence. Not clean. apply still never deletes: cast reports, the human removes it. - capture (classify) and cli (syncEnv) carry the same assertion at the file and at the wire — unreachable through the CLI today, and kept because the invariant is "cast never writes one", not "the CLI happens to check first". - smoke writes an env var too; its probe names are asserted outside the space. The rule lives in cast's code, NOT beside forbidden_var_patterns in private state: that one is policy an environment may set for itself, this one is a fact about Coolify, true on every box — nothing a manifest change could lower. 19 tests in test/reserved.test.ts, one per path. Closes #50.
2026-07-14 22:29:23 +00:00
const text = readFileSync(file, "utf8");
reserved.push(...reservedHits(resource, templateKeys(text)));
feat(resolve): derive DATABASE_URL/REDIS_URL from the database cast created (#60) Add a ${resource:<name>.url} env-template ref that resolves to the internal URL of a database the same manifest declares, read back from the live resource's internal_db_url — never stored in the age store, never decrypted, never printed. This deletes the two-pass generated-secret bootstrap for a database's own URL rather than automating it: no placeholder, no stored copy to drift or overwrite, and a rotated password is simply followed on the next apply. Resolution runs in one function (fillDerivedEnv) against two URL maps: at diff time against databases already on the box (so a matching app shows no drift — killing the "secret DATABASE_URL differs" noise that ran on every plan), and in the executor at apply time against a database created earlier in the same run (the from-nothing case; apply acts databases-before-applications, #45). The unresolved sentinel is never written — the executor refuses, rather than write a blank that boots the app pointed at nothing, and re-running once the database is up resolves it as an ordinary update. A ${resource:X.url} naming a database the manifest does not declare, or an attribute other than .url, is a hard plan-time error refused by every verb that opens a template (apply, diff, capture). generated_secrets and the two-pass bootstrap remain for the residual class — a provider-generated value that genuinely is not derivable. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 23:46:26 +00:00
resourceRefs.push(...templateResourceRefs(text));
feat(resolve): derive base-URL env vars from manifest domains via ${domain:...} (#66) A public base URL an app reads (LANDING_BASE_URL, ADMIN_WEB_BASE_URL) is a fact the manifest already states in `domains`/`service_domains` — the same fields cast parses to reconcile Coolify domains. Hand-transcribing it into an env template is a second copy that drifts (incubator's prod LANDING_BASE_URL silently kept a pre-apex host). So a template can now say it directly: LANDING_BASE_URL=${domain:landing} ADMIN_WEB_BASE_URL=${domain:core.admin} - ${domain:<app>} -> applications.<app>.domains[0] - ${domain:<app>.<service>} -> applications.<app>.service_domains.<service>[0] Symmetric with ${resource:...} (#60) — parse -> sentinel -> validate -> fill — but a domain is PURE MANIFEST DATA, known at plan time, so it resolves fully in desiredFromManifest against a map built from the manifest: no live read, no executor deferral, no unresolved-at-write path. Domains are PUBLIC, so they resolve to secret:false (printed in diffs) and read as plain literals downstream (no diff.ts change). Not secrets: excluded from templateRefs, never captured. assertDomainRefs is the single validation gate (apply/diff/capture), refusing an undeclared app/service, a wrong-shape ref, or an empty/blank domain list before the sentinel can escape. Applications only (Coolify 4.1.2 can't set service domains). REPORTING_TZ-style operator literals stay literal. Closes #66. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 12:02:33 +00:00
domainRefs.push(...templateDomainRefs(text));
fix: never write an env var whose name Coolify injects itself (#50) Coolify injects SOURCE_COMMIT and the COOLIFY_* family into an application's runtime environment itself, and SKIPS its own injection of a name the resource already carries a var of (ApplicationDeploymentJob.php v4.1.2, line 2994 — `->where('key', 'SOURCE_COMMIT')->isEmpty()`). A resource-level var of that name therefore SUPPRESSES the platform's value. An empty one suppresses it just as completely: presence, not value. And it fails green — the deploy succeeds, health checks pass, and the only symptom is /version reporting "unknown", the endpoint a production cutover is gated on (D-266). The rule is now a property of cast, not of one code path. A new src/reserved.ts owns it, and every place cast touches an env var honors it: - resolve — every manifest read (desiredFromManifest, requiredSecrets, manifestResources) refuses a template declaring a reserved name, before any write. So apply, diff, capture and inventory all refuse identically. - draft — a reserved name read off a live box gets its own provenance, `suppressed`: out of the template, out of the age store, its live value read into no artifact, and named in UNCAPTURED.md with the consequence. - diff — promoted out of the remove-candidate orphan list ("apply never removes these; read them by eye") and printed as a FINDING with its consequence. Not clean. apply still never deletes: cast reports, the human removes it. - capture (classify) and cli (syncEnv) carry the same assertion at the file and at the wire — unreachable through the CLI today, and kept because the invariant is "cast never writes one", not "the CLI happens to check first". - smoke writes an env var too; its probe names are asserted outside the space. The rule lives in cast's code, NOT beside forbidden_var_patterns in private state: that one is policy an environment may set for itself, this one is a fact about Coolify, true on every box — nothing a manifest change could lower. 19 tests in test/reserved.test.ts, one per path. Closes #50.
2026-07-14 22:29:23 +00:00
for (const { key, ref } of templateRefs(text)) {
feat: cast capture — adopt a hand-built Coolify into the age secret store (#15) cast was scoped to the steady state: manifest → Coolify, forever. It had no adoption path — no way to bootstrap the age store from an instance built by hand, before any manifest existed. The operator did it by hand: curl the envs, assemble 17 name=value pairs into /dev/shm/prod.env, age -r, shred. Every input to that pipeline is something cast already has, so a human was shuffling cast's own inputs through a terminal, with the leak (scrollback, history, a tmp file that never got shredded) and the silent miss both live. cast capture <org>/<repo> --env <env> [--generated N] [--override N] [--force] The required set comes from the MANIFEST, not the box: the ${...} refs in that environment's env templates, read by the same parser apply uses to demand them. resolveTemplate and templateRefs now share one grammar — a drift between them would mean capture collects a different set than apply later requires, which is exactly the "a name silently missed" failure this verb exists to remove. The mapping is deliberately NOT mechanical. A DATABASE_URL read off the source points at the SOURCE box's Postgres: confidently wrong, entirely plausible, and the target's real URL does not exist until Coolify creates the resource. So the manifest declares `generated_secrets:` and those names are written as the literal `pending-coolify-generated`. staging's ADMIN_EMAIL must be the operator, not the source's — staging and prod share a Mailgun domain, so a staging box carrying the real address can mail real users; that is --override. A "capture everything" verb would be wrong in ~4 of 17 entries, silently — worse than being wrong in all of them. So every name is forced into a disposition, and two of the four stop the run: a name required by a template but absent from the source REFUSES (an empty substitutes to nothing and the app boots misconfigured), as does one name carrying different values on two resources. generated_secrets is a manifest property rather than a flag the operator must remember, because the manifest is what knows DATABASE_URL comes from a database it declares. An entry no template refers to is a hard error: a guard standing over nothing reads like a guard, and the likeliest cause is a typo whose real name is then captured from the source instead of placeheld. Secret hygiene, all covered by tests asserting on real values: - the plan prints names and provenance, NEVER values - an --override's value comes from $CAST_CAPTURE_<NAME>, never argv (`ps`) - plaintext is piped to age on stdin — never a temp file, stdout, or history - an existing store is not overwritten without --force: it may hold the only copy of values the source no longer has (apply's never-delete, applied here) capture inherits diff's absent-target refusal (D-237) — against a project that isn't there it would report every secret as missing, an alarming report about the wrong box — plus the team assert and the --path/--env prod ban. The last gate is a typed confirmation of the environment's name; there is no --yes. The end-to-end test decrypts the store cast wrote and asserts on its contents, so "exactly the names the manifest requires, no more and no fewer" is checked against real ciphertext rather than against cast's own console output. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 16:51:43 +00:00
required.push({ ref, resource, key });
}
};
for (const [name, app] of Object.entries(envSpec.applications)) {
collect(name, app.env_template);
}
for (const [name, svc] of Object.entries(envSpec.services ?? {})) {
collect(name, svc.env_template);
}
fix: never write an env var whose name Coolify injects itself (#50) Coolify injects SOURCE_COMMIT and the COOLIFY_* family into an application's runtime environment itself, and SKIPS its own injection of a name the resource already carries a var of (ApplicationDeploymentJob.php v4.1.2, line 2994 — `->where('key', 'SOURCE_COMMIT')->isEmpty()`). A resource-level var of that name therefore SUPPRESSES the platform's value. An empty one suppresses it just as completely: presence, not value. And it fails green — the deploy succeeds, health checks pass, and the only symptom is /version reporting "unknown", the endpoint a production cutover is gated on (D-266). The rule is now a property of cast, not of one code path. A new src/reserved.ts owns it, and every place cast touches an env var honors it: - resolve — every manifest read (desiredFromManifest, requiredSecrets, manifestResources) refuses a template declaring a reserved name, before any write. So apply, diff, capture and inventory all refuse identically. - draft — a reserved name read off a live box gets its own provenance, `suppressed`: out of the template, out of the age store, its live value read into no artifact, and named in UNCAPTURED.md with the consequence. - diff — promoted out of the remove-candidate orphan list ("apply never removes these; read them by eye") and printed as a FINDING with its consequence. Not clean. apply still never deletes: cast reports, the human removes it. - capture (classify) and cli (syncEnv) carry the same assertion at the file and at the wire — unreachable through the CLI today, and kept because the invariant is "cast never writes one", not "the CLI happens to check first". - smoke writes an env var too; its probe names are asserted outside the space. The rule lives in cast's code, NOT beside forbidden_var_patterns in private state: that one is policy an environment may set for itself, this one is a fact about Coolify, true on every box — nothing a manifest change could lower. 19 tests in test/reserved.test.ts, one per path. Closes #50.
2026-07-14 22:29:23 +00:00
assertNoReservedEnvNames(reserved);
feat(resolve): derive DATABASE_URL/REDIS_URL from the database cast created (#60) Add a ${resource:<name>.url} env-template ref that resolves to the internal URL of a database the same manifest declares, read back from the live resource's internal_db_url — never stored in the age store, never decrypted, never printed. This deletes the two-pass generated-secret bootstrap for a database's own URL rather than automating it: no placeholder, no stored copy to drift or overwrite, and a rotated password is simply followed on the next apply. Resolution runs in one function (fillDerivedEnv) against two URL maps: at diff time against databases already on the box (so a matching app shows no drift — killing the "secret DATABASE_URL differs" noise that ran on every plan), and in the executor at apply time against a database created earlier in the same run (the from-nothing case; apply acts databases-before-applications, #45). The unresolved sentinel is never written — the executor refuses, rather than write a blank that boots the app pointed at nothing, and re-running once the database is up resolves it as an ordinary update. A ${resource:X.url} naming a database the manifest does not declare, or an attribute other than .url, is a hard plan-time error refused by every verb that opens a template (apply, diff, capture). generated_secrets and the two-pass bootstrap remain for the residual class — a provider-generated value that genuinely is not derivable. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 23:46:26 +00:00
assertResourceRefs(
envName,
new Set(Object.keys(envSpec.databases ?? {})),
resourceRefs,
);
feat(resolve): derive base-URL env vars from manifest domains via ${domain:...} (#66) A public base URL an app reads (LANDING_BASE_URL, ADMIN_WEB_BASE_URL) is a fact the manifest already states in `domains`/`service_domains` — the same fields cast parses to reconcile Coolify domains. Hand-transcribing it into an env template is a second copy that drifts (incubator's prod LANDING_BASE_URL silently kept a pre-apex host). So a template can now say it directly: LANDING_BASE_URL=${domain:landing} ADMIN_WEB_BASE_URL=${domain:core.admin} - ${domain:<app>} -> applications.<app>.domains[0] - ${domain:<app>.<service>} -> applications.<app>.service_domains.<service>[0] Symmetric with ${resource:...} (#60) — parse -> sentinel -> validate -> fill — but a domain is PURE MANIFEST DATA, known at plan time, so it resolves fully in desiredFromManifest against a map built from the manifest: no live read, no executor deferral, no unresolved-at-write path. Domains are PUBLIC, so they resolve to secret:false (printed in diffs) and read as plain literals downstream (no diff.ts change). Not secrets: excluded from templateRefs, never captured. assertDomainRefs is the single validation gate (apply/diff/capture), refusing an undeclared app/service, a wrong-shape ref, or an empty/blank domain list before the sentinel can escape. Applications only (Coolify 4.1.2 can't set service domains). REPORTING_TZ-style operator literals stay literal. Closes #66. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 12:02:33 +00:00
// Domain refs are validated even by capture — a ref that names an undeclared
// app/service is broken for every verb — but they never enter `required`: a
// domain is manifest data, not a secret the store must hold.
assertDomainRefs(envName, envSpec.applications, domainRefs);
feat: cast capture — adopt a hand-built Coolify into the age secret store (#15) cast was scoped to the steady state: manifest → Coolify, forever. It had no adoption path — no way to bootstrap the age store from an instance built by hand, before any manifest existed. The operator did it by hand: curl the envs, assemble 17 name=value pairs into /dev/shm/prod.env, age -r, shred. Every input to that pipeline is something cast already has, so a human was shuffling cast's own inputs through a terminal, with the leak (scrollback, history, a tmp file that never got shredded) and the silent miss both live. cast capture <org>/<repo> --env <env> [--generated N] [--override N] [--force] The required set comes from the MANIFEST, not the box: the ${...} refs in that environment's env templates, read by the same parser apply uses to demand them. resolveTemplate and templateRefs now share one grammar — a drift between them would mean capture collects a different set than apply later requires, which is exactly the "a name silently missed" failure this verb exists to remove. The mapping is deliberately NOT mechanical. A DATABASE_URL read off the source points at the SOURCE box's Postgres: confidently wrong, entirely plausible, and the target's real URL does not exist until Coolify creates the resource. So the manifest declares `generated_secrets:` and those names are written as the literal `pending-coolify-generated`. staging's ADMIN_EMAIL must be the operator, not the source's — staging and prod share a Mailgun domain, so a staging box carrying the real address can mail real users; that is --override. A "capture everything" verb would be wrong in ~4 of 17 entries, silently — worse than being wrong in all of them. So every name is forced into a disposition, and two of the four stop the run: a name required by a template but absent from the source REFUSES (an empty substitutes to nothing and the app boots misconfigured), as does one name carrying different values on two resources. generated_secrets is a manifest property rather than a flag the operator must remember, because the manifest is what knows DATABASE_URL comes from a database it declares. An entry no template refers to is a hard error: a guard standing over nothing reads like a guard, and the likeliest cause is a typo whose real name is then captured from the source instead of placeheld. Secret hygiene, all covered by tests asserting on real values: - the plan prints names and provenance, NEVER values - an --override's value comes from $CAST_CAPTURE_<NAME>, never argv (`ps`) - plaintext is piped to age on stdin — never a temp file, stdout, or history - an existing store is not overwritten without --force: it may hold the only copy of values the source no longer has (apply's never-delete, applied here) capture inherits diff's absent-target refusal (D-237) — against a project that isn't there it would report every secret as missing, an alarming report about the wrong box — plus the team assert and the --path/--env prod ban. The last gate is a typed confirmation of the environment's name; there is no --yes. The end-to-end test decrypts the store cast wrote and asserts on its contents, so "exactly the names the manifest requires, no more and no fewer" is checked against real ciphertext rather than against cast's own console output. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 16:51:43 +00:00
const generated = envSpec.generated_secrets ?? [];
// A generated_secrets entry naming something no template refs is dead
// config — and dead config in THIS list is not merely untidy, it is
// dangerous: it reads like a guard standing over a name while standing over
// nothing. The likeliest cause is a typo, and the consequence of the typo is
// that the real name gets CAPTURED from the source box instead of placeheld.
const refs = new Set(required.map((r) => r.ref));
const dead = generated.filter((g) => !refs.has(g));
if (dead.length > 0) {
throw new Error(
[
`manifest environment ${envName}: generated_secrets names ${dead.join(", ")}, which no env template refers to`,
"",
` declared: ${generated.join(", ")}`,
` templates: ${[...refs].sort().join(", ") || "(no ${...} refs at all)"}`,
"",
"A generated name that matches nothing guards nothing — and if this is a",
"typo, the name it was meant to guard is being captured from the source",
"box instead of placeheld. Fix the spelling, or drop the entry.",
].join("\n"),
);
}
return { required, generated };
}
feat: read-side coordinates (#17, #18) + cast inventory (#19) Three fixes at one seam: cast could not READ a box it did not build. #17 — the environment had no read-side coordinate. `--project` exists because a hand-built project is called whatever someone typed. The environment has the identical problem and had no flag, so reading a legacy box forced a choice between mutating that box's UI and renaming OUR environment to match it. The second is what happened: `prod` became `production` across the manifest and environments.yaml — a box being deleted next week naming the environment of the box that replaces it, permanently (apply creates the environment from --env), moving the store to incubator.production.env.age and invalidating every runbook. Reverted. `--environment` is now the coordinate. `--env` stays OURS: manifest block, binding, age key, store path, team assert. `--environment` is theirs, on the wire, and nothing else. #18 — an absent RESOURCE reported as N missing secrets. The D-237 lie, one level deeper. A resource that is absent reads back exactly like one present with no env vars, so capture reported all 15 required names as individually MISSING — from a box that was serving production and sending mail at that moment — and offered --override as the remedy. Taking that offer would have "worked": a valid store, hand-carried values, and the real finding (the manifest and the box disagree about what the app is called) buried. capture now refuses on the resource, names what does exist, and only reports per-name MISSING for resources it actually found — where it means what it says. #19 — cast inventory: see the box before you adopt it. The missing first step. cast could describe a box it built, change one, and take values off one for names a manifest declares — but not tell you what is on a box you did not build, which is the first thing adoption needs. Every mismatch above surfaced as a refusal from a verb already committed to a course of action, and the tempting fix for two of them was to bend the manifest toward the legacy box. inventory reads resources and env var KEYS (never values), sorts them into on-both / manifest-only / box-only, and needs no store, no age key and no recipient — it runs before adoption exists. Its output is a document: inventory → human reads → manifest PR → capture → apply That boundary is what lets capture stay strict. inventory may read everything, because a person reads its output. capture may only write what the manifest declares, because `apply` reads its output. Same box, two consumers, two contracts. A manifest-draft emitter is deliberately NOT included: it would be one `cp` away from becoming desired state, which is the failure this design exists to prevent. Zero drift against a hand-built box is reported as suspicious, not as a pass. npm run check + build clean; 164 tests passing, 18 files (was 151/16). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 18:20:53 +00:00
// What the manifest declares for an environment, as names only — no secrets, no
// age key, no store. `inventory` runs BEFORE any of those exist (that is the
// point of it: you read the box before you can possibly have adopted it), so it
// must be able to describe the manifest side without resolving a single value.
export type ManifestResource = {
kind: "application" | "database" | "service";
name: string;
envKeys: string[];
};
export function manifestResources(
checkoutDir: string,
envName: string,
): ManifestResource[] {
const manifest = loadManifest(join(checkoutDir, ".infra", "manifest.yaml"));
const envSpec = manifest.environments[envName];
if (!envSpec) {
throw new Error(
`environment ${envName} not in manifest (has: ${Object.keys(manifest.environments).join(", ") || "none"})`,
);
}
fix: never write an env var whose name Coolify injects itself (#50) Coolify injects SOURCE_COMMIT and the COOLIFY_* family into an application's runtime environment itself, and SKIPS its own injection of a name the resource already carries a var of (ApplicationDeploymentJob.php v4.1.2, line 2994 — `->where('key', 'SOURCE_COMMIT')->isEmpty()`). A resource-level var of that name therefore SUPPRESSES the platform's value. An empty one suppresses it just as completely: presence, not value. And it fails green — the deploy succeeds, health checks pass, and the only symptom is /version reporting "unknown", the endpoint a production cutover is gated on (D-266). The rule is now a property of cast, not of one code path. A new src/reserved.ts owns it, and every place cast touches an env var honors it: - resolve — every manifest read (desiredFromManifest, requiredSecrets, manifestResources) refuses a template declaring a reserved name, before any write. So apply, diff, capture and inventory all refuse identically. - draft — a reserved name read off a live box gets its own provenance, `suppressed`: out of the template, out of the age store, its live value read into no artifact, and named in UNCAPTURED.md with the consequence. - diff — promoted out of the remove-candidate orphan list ("apply never removes these; read them by eye") and printed as a FINDING with its consequence. Not clean. apply still never deletes: cast reports, the human removes it. - capture (classify) and cli (syncEnv) carry the same assertion at the file and at the wire — unreachable through the CLI today, and kept because the invariant is "cast never writes one", not "the CLI happens to check first". - smoke writes an env var too; its probe names are asserted outside the space. The rule lives in cast's code, NOT beside forbidden_var_patterns in private state: that one is policy an environment may set for itself, this one is a fact about Coolify, true on every box — nothing a manifest change could lower. 19 tests in test/reserved.test.ts, one per path. Closes #50.
2026-07-14 22:29:23 +00:00
const reserved: ReservedHit[] = [];
feat: read-side coordinates (#17, #18) + cast inventory (#19) Three fixes at one seam: cast could not READ a box it did not build. #17 — the environment had no read-side coordinate. `--project` exists because a hand-built project is called whatever someone typed. The environment has the identical problem and had no flag, so reading a legacy box forced a choice between mutating that box's UI and renaming OUR environment to match it. The second is what happened: `prod` became `production` across the manifest and environments.yaml — a box being deleted next week naming the environment of the box that replaces it, permanently (apply creates the environment from --env), moving the store to incubator.production.env.age and invalidating every runbook. Reverted. `--environment` is now the coordinate. `--env` stays OURS: manifest block, binding, age key, store path, team assert. `--environment` is theirs, on the wire, and nothing else. #18 — an absent RESOURCE reported as N missing secrets. The D-237 lie, one level deeper. A resource that is absent reads back exactly like one present with no env vars, so capture reported all 15 required names as individually MISSING — from a box that was serving production and sending mail at that moment — and offered --override as the remedy. Taking that offer would have "worked": a valid store, hand-carried values, and the real finding (the manifest and the box disagree about what the app is called) buried. capture now refuses on the resource, names what does exist, and only reports per-name MISSING for resources it actually found — where it means what it says. #19 — cast inventory: see the box before you adopt it. The missing first step. cast could describe a box it built, change one, and take values off one for names a manifest declares — but not tell you what is on a box you did not build, which is the first thing adoption needs. Every mismatch above surfaced as a refusal from a verb already committed to a course of action, and the tempting fix for two of them was to bend the manifest toward the legacy box. inventory reads resources and env var KEYS (never values), sorts them into on-both / manifest-only / box-only, and needs no store, no age key and no recipient — it runs before adoption exists. Its output is a document: inventory → human reads → manifest PR → capture → apply That boundary is what lets capture stay strict. inventory may read everything, because a person reads its output. capture may only write what the manifest declares, because `apply` reads its output. Same box, two consumers, two contracts. A manifest-draft emitter is deliberately NOT included: it would be one `cp` away from becoming desired state, which is the failure this design exists to prevent. Zero drift against a hand-built box is reported as suspicious, not as a pass. npm run check + build clean; 164 tests passing, 18 files (was 151/16). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 18:20:53 +00:00
const keysOf = (resource: string, template?: string): string[] => {
if (!template) return [];
const file = join(checkoutDir, ".infra", "env", template);
if (!existsSync(file))
throw new Error(
`env template missing: ${file} (referenced by ${resource})`,
);
fix: never write an env var whose name Coolify injects itself (#50) Coolify injects SOURCE_COMMIT and the COOLIFY_* family into an application's runtime environment itself, and SKIPS its own injection of a name the resource already carries a var of (ApplicationDeploymentJob.php v4.1.2, line 2994 — `->where('key', 'SOURCE_COMMIT')->isEmpty()`). A resource-level var of that name therefore SUPPRESSES the platform's value. An empty one suppresses it just as completely: presence, not value. And it fails green — the deploy succeeds, health checks pass, and the only symptom is /version reporting "unknown", the endpoint a production cutover is gated on (D-266). The rule is now a property of cast, not of one code path. A new src/reserved.ts owns it, and every place cast touches an env var honors it: - resolve — every manifest read (desiredFromManifest, requiredSecrets, manifestResources) refuses a template declaring a reserved name, before any write. So apply, diff, capture and inventory all refuse identically. - draft — a reserved name read off a live box gets its own provenance, `suppressed`: out of the template, out of the age store, its live value read into no artifact, and named in UNCAPTURED.md with the consequence. - diff — promoted out of the remove-candidate orphan list ("apply never removes these; read them by eye") and printed as a FINDING with its consequence. Not clean. apply still never deletes: cast reports, the human removes it. - capture (classify) and cli (syncEnv) carry the same assertion at the file and at the wire — unreachable through the CLI today, and kept because the invariant is "cast never writes one", not "the CLI happens to check first". - smoke writes an env var too; its probe names are asserted outside the space. The rule lives in cast's code, NOT beside forbidden_var_patterns in private state: that one is policy an environment may set for itself, this one is a fact about Coolify, true on every box — nothing a manifest change could lower. 19 tests in test/reserved.test.ts, one per path. Closes #50.
2026-07-14 22:29:23 +00:00
const keys = templateKeys(readFileSync(file, "utf8"));
reserved.push(...reservedHits(resource, keys));
return keys;
feat: read-side coordinates (#17, #18) + cast inventory (#19) Three fixes at one seam: cast could not READ a box it did not build. #17 — the environment had no read-side coordinate. `--project` exists because a hand-built project is called whatever someone typed. The environment has the identical problem and had no flag, so reading a legacy box forced a choice between mutating that box's UI and renaming OUR environment to match it. The second is what happened: `prod` became `production` across the manifest and environments.yaml — a box being deleted next week naming the environment of the box that replaces it, permanently (apply creates the environment from --env), moving the store to incubator.production.env.age and invalidating every runbook. Reverted. `--environment` is now the coordinate. `--env` stays OURS: manifest block, binding, age key, store path, team assert. `--environment` is theirs, on the wire, and nothing else. #18 — an absent RESOURCE reported as N missing secrets. The D-237 lie, one level deeper. A resource that is absent reads back exactly like one present with no env vars, so capture reported all 15 required names as individually MISSING — from a box that was serving production and sending mail at that moment — and offered --override as the remedy. Taking that offer would have "worked": a valid store, hand-carried values, and the real finding (the manifest and the box disagree about what the app is called) buried. capture now refuses on the resource, names what does exist, and only reports per-name MISSING for resources it actually found — where it means what it says. #19 — cast inventory: see the box before you adopt it. The missing first step. cast could describe a box it built, change one, and take values off one for names a manifest declares — but not tell you what is on a box you did not build, which is the first thing adoption needs. Every mismatch above surfaced as a refusal from a verb already committed to a course of action, and the tempting fix for two of them was to bend the manifest toward the legacy box. inventory reads resources and env var KEYS (never values), sorts them into on-both / manifest-only / box-only, and needs no store, no age key and no recipient — it runs before adoption exists. Its output is a document: inventory → human reads → manifest PR → capture → apply That boundary is what lets capture stay strict. inventory may read everything, because a person reads its output. capture may only write what the manifest declares, because `apply` reads its output. Same box, two consumers, two contracts. A manifest-draft emitter is deliberately NOT included: it would be one `cp` away from becoming desired state, which is the failure this design exists to prevent. Zero drift against a hand-built box is reported as suspicious, not as a pass. npm run check + build clean; 164 tests passing, 18 files (was 151/16). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 18:20:53 +00:00
};
fix: never write an env var whose name Coolify injects itself (#50) Coolify injects SOURCE_COMMIT and the COOLIFY_* family into an application's runtime environment itself, and SKIPS its own injection of a name the resource already carries a var of (ApplicationDeploymentJob.php v4.1.2, line 2994 — `->where('key', 'SOURCE_COMMIT')->isEmpty()`). A resource-level var of that name therefore SUPPRESSES the platform's value. An empty one suppresses it just as completely: presence, not value. And it fails green — the deploy succeeds, health checks pass, and the only symptom is /version reporting "unknown", the endpoint a production cutover is gated on (D-266). The rule is now a property of cast, not of one code path. A new src/reserved.ts owns it, and every place cast touches an env var honors it: - resolve — every manifest read (desiredFromManifest, requiredSecrets, manifestResources) refuses a template declaring a reserved name, before any write. So apply, diff, capture and inventory all refuse identically. - draft — a reserved name read off a live box gets its own provenance, `suppressed`: out of the template, out of the age store, its live value read into no artifact, and named in UNCAPTURED.md with the consequence. - diff — promoted out of the remove-candidate orphan list ("apply never removes these; read them by eye") and printed as a FINDING with its consequence. Not clean. apply still never deletes: cast reports, the human removes it. - capture (classify) and cli (syncEnv) carry the same assertion at the file and at the wire — unreachable through the CLI today, and kept because the invariant is "cast never writes one", not "the CLI happens to check first". - smoke writes an env var too; its probe names are asserted outside the space. The rule lives in cast's code, NOT beside forbidden_var_patterns in private state: that one is policy an environment may set for itself, this one is a fact about Coolify, true on every box — nothing a manifest change could lower. 19 tests in test/reserved.test.ts, one per path. Closes #50.
2026-07-14 22:29:23 +00:00
const resources = [
feat: read-side coordinates (#17, #18) + cast inventory (#19) Three fixes at one seam: cast could not READ a box it did not build. #17 — the environment had no read-side coordinate. `--project` exists because a hand-built project is called whatever someone typed. The environment has the identical problem and had no flag, so reading a legacy box forced a choice between mutating that box's UI and renaming OUR environment to match it. The second is what happened: `prod` became `production` across the manifest and environments.yaml — a box being deleted next week naming the environment of the box that replaces it, permanently (apply creates the environment from --env), moving the store to incubator.production.env.age and invalidating every runbook. Reverted. `--environment` is now the coordinate. `--env` stays OURS: manifest block, binding, age key, store path, team assert. `--environment` is theirs, on the wire, and nothing else. #18 — an absent RESOURCE reported as N missing secrets. The D-237 lie, one level deeper. A resource that is absent reads back exactly like one present with no env vars, so capture reported all 15 required names as individually MISSING — from a box that was serving production and sending mail at that moment — and offered --override as the remedy. Taking that offer would have "worked": a valid store, hand-carried values, and the real finding (the manifest and the box disagree about what the app is called) buried. capture now refuses on the resource, names what does exist, and only reports per-name MISSING for resources it actually found — where it means what it says. #19 — cast inventory: see the box before you adopt it. The missing first step. cast could describe a box it built, change one, and take values off one for names a manifest declares — but not tell you what is on a box you did not build, which is the first thing adoption needs. Every mismatch above surfaced as a refusal from a verb already committed to a course of action, and the tempting fix for two of them was to bend the manifest toward the legacy box. inventory reads resources and env var KEYS (never values), sorts them into on-both / manifest-only / box-only, and needs no store, no age key and no recipient — it runs before adoption exists. Its output is a document: inventory → human reads → manifest PR → capture → apply That boundary is what lets capture stay strict. inventory may read everything, because a person reads its output. capture may only write what the manifest declares, because `apply` reads its output. Same box, two consumers, two contracts. A manifest-draft emitter is deliberately NOT included: it would be one `cp` away from becoming desired state, which is the failure this design exists to prevent. Zero drift against a hand-built box is reported as suspicious, not as a pass. npm run check + build clean; 164 tests passing, 18 files (was 151/16). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 18:20:53 +00:00
...Object.entries(envSpec.applications).map(([name, app]) => ({
kind: "application" as const,
name,
envKeys: keysOf(name, app.env_template),
})),
...Object.entries(envSpec.databases ?? {}).map(([name]) => ({
kind: "database" as const,
name,
envKeys: [],
})),
...Object.entries(envSpec.services ?? {}).map(([name, svc]) => ({
kind: "service" as const,
name,
envKeys: keysOf(name, svc.env_template),
})),
];
fix: never write an env var whose name Coolify injects itself (#50) Coolify injects SOURCE_COMMIT and the COOLIFY_* family into an application's runtime environment itself, and SKIPS its own injection of a name the resource already carries a var of (ApplicationDeploymentJob.php v4.1.2, line 2994 — `->where('key', 'SOURCE_COMMIT')->isEmpty()`). A resource-level var of that name therefore SUPPRESSES the platform's value. An empty one suppresses it just as completely: presence, not value. And it fails green — the deploy succeeds, health checks pass, and the only symptom is /version reporting "unknown", the endpoint a production cutover is gated on (D-266). The rule is now a property of cast, not of one code path. A new src/reserved.ts owns it, and every place cast touches an env var honors it: - resolve — every manifest read (desiredFromManifest, requiredSecrets, manifestResources) refuses a template declaring a reserved name, before any write. So apply, diff, capture and inventory all refuse identically. - draft — a reserved name read off a live box gets its own provenance, `suppressed`: out of the template, out of the age store, its live value read into no artifact, and named in UNCAPTURED.md with the consequence. - diff — promoted out of the remove-candidate orphan list ("apply never removes these; read them by eye") and printed as a FINDING with its consequence. Not clean. apply still never deletes: cast reports, the human removes it. - capture (classify) and cli (syncEnv) carry the same assertion at the file and at the wire — unreachable through the CLI today, and kept because the invariant is "cast never writes one", not "the CLI happens to check first". - smoke writes an env var too; its probe names are asserted outside the space. The rule lives in cast's code, NOT beside forbidden_var_patterns in private state: that one is policy an environment may set for itself, this one is a fact about Coolify, true on every box — nothing a manifest change could lower. 19 tests in test/reserved.test.ts, one per path. Closes #50.
2026-07-14 22:29:23 +00:00
assertNoReservedEnvNames(reserved);
return resources;
feat: read-side coordinates (#17, #18) + cast inventory (#19) Three fixes at one seam: cast could not READ a box it did not build. #17 — the environment had no read-side coordinate. `--project` exists because a hand-built project is called whatever someone typed. The environment has the identical problem and had no flag, so reading a legacy box forced a choice between mutating that box's UI and renaming OUR environment to match it. The second is what happened: `prod` became `production` across the manifest and environments.yaml — a box being deleted next week naming the environment of the box that replaces it, permanently (apply creates the environment from --env), moving the store to incubator.production.env.age and invalidating every runbook. Reverted. `--environment` is now the coordinate. `--env` stays OURS: manifest block, binding, age key, store path, team assert. `--environment` is theirs, on the wire, and nothing else. #18 — an absent RESOURCE reported as N missing secrets. The D-237 lie, one level deeper. A resource that is absent reads back exactly like one present with no env vars, so capture reported all 15 required names as individually MISSING — from a box that was serving production and sending mail at that moment — and offered --override as the remedy. Taking that offer would have "worked": a valid store, hand-carried values, and the real finding (the manifest and the box disagree about what the app is called) buried. capture now refuses on the resource, names what does exist, and only reports per-name MISSING for resources it actually found — where it means what it says. #19 — cast inventory: see the box before you adopt it. The missing first step. cast could describe a box it built, change one, and take values off one for names a manifest declares — but not tell you what is on a box you did not build, which is the first thing adoption needs. Every mismatch above surfaced as a refusal from a verb already committed to a course of action, and the tempting fix for two of them was to bend the manifest toward the legacy box. inventory reads resources and env var KEYS (never values), sorts them into on-both / manifest-only / box-only, and needs no store, no age key and no recipient — it runs before adoption exists. Its output is a document: inventory → human reads → manifest PR → capture → apply That boundary is what lets capture stay strict. inventory may read everything, because a person reads its output. capture may only write what the manifest declares, because `apply` reads its output. Same box, two consumers, two contracts. A manifest-draft emitter is deliberately NOT included: it would be one `cp` away from becoming desired state, which is the failure this design exists to prevent. Zero drift against a hand-built box is reported as suspicious, not as a pass. npm run check + build clean; 164 tests passing, 18 files (was 151/16). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 18:20:53 +00:00
}
feat: cast — the Coolify executor, extracted from the infra state repo Public tool, private state. cast holds no hostnames, no bindings, no secrets: it joins a product repo's .infra/ manifest with a state directory you point it at, and makes Coolify match. Extracted from heavy-duty/infra, which was half tool and half state — the inconsistency that made it impossible to say whether "infra" named a CLI or a runbook. rig builds the boxes; cast fills them; infra is what they are filled with. Two changes were required to make it genuinely stateless and publishable: - The implicit cwd contract (environments.yaml / secrets/ / .coolify.env resolved against the working directory, silently reading the wrong file from the wrong place) is now an explicit --state <dir> / $CAST_STATE. - BANNED_IN_PROD — a hardcoded list of one product's ALLOW_* flags, the only product knowledge in the executor — becomes the generic, operator- owned environments.<env>.forbidden_var_patterns. The guard now lives in private state, so a product-side change cannot lower its own guard, and it is a pattern rather than a list, so it catches unforeseen siblings. Age identities resolve as $CAST_AGE_KEY_FILE_<ENV> then ~/.config/cast/age-<env>.key — which is the entire attended-vs-unattended apply mechanism, with no environment names known to the tool. Instance identity (org names, the GitHub App name, founder domains) is out of the fixtures and out of register-github-app.sh, which took APP_NAME and ORG as arguments rather than baking them in. 69 tests green; bin/cast + curl installer mirror rig's shape. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 12:25:44 +00:00
export function desiredFromManifest(
checkoutDir: string,
envName: string,
secrets: Record<string, string>,
): {
desired: Desired[];
resolvedEnvs: Record<string, ResolvedEnv>;
} {
const manifest = loadManifest(join(checkoutDir, ".infra", "manifest.yaml"));
const envSpec = manifest.environments[envName];
if (!envSpec) {
throw new Error(
`environment ${envName} not in manifest (has: ${Object.keys(manifest.environments).join(", ") || "none"})`,
);
}
const desired: Desired[] = [];
const resolvedEnvs: Record<string, ResolvedEnv> = {};
fix: never write an env var whose name Coolify injects itself (#50) Coolify injects SOURCE_COMMIT and the COOLIFY_* family into an application's runtime environment itself, and SKIPS its own injection of a name the resource already carries a var of (ApplicationDeploymentJob.php v4.1.2, line 2994 — `->where('key', 'SOURCE_COMMIT')->isEmpty()`). A resource-level var of that name therefore SUPPRESSES the platform's value. An empty one suppresses it just as completely: presence, not value. And it fails green — the deploy succeeds, health checks pass, and the only symptom is /version reporting "unknown", the endpoint a production cutover is gated on (D-266). The rule is now a property of cast, not of one code path. A new src/reserved.ts owns it, and every place cast touches an env var honors it: - resolve — every manifest read (desiredFromManifest, requiredSecrets, manifestResources) refuses a template declaring a reserved name, before any write. So apply, diff, capture and inventory all refuse identically. - draft — a reserved name read off a live box gets its own provenance, `suppressed`: out of the template, out of the age store, its live value read into no artifact, and named in UNCAPTURED.md with the consequence. - diff — promoted out of the remove-candidate orphan list ("apply never removes these; read them by eye") and printed as a FINDING with its consequence. Not clean. apply still never deletes: cast reports, the human removes it. - capture (classify) and cli (syncEnv) carry the same assertion at the file and at the wire — unreachable through the CLI today, and kept because the invariant is "cast never writes one", not "the CLI happens to check first". - smoke writes an env var too; its probe names are asserted outside the space. The rule lives in cast's code, NOT beside forbidden_var_patterns in private state: that one is policy an environment may set for itself, this one is a fact about Coolify, true on every box — nothing a manifest change could lower. 19 tests in test/reserved.test.ts, one per path. Closes #50.
2026-07-14 22:29:23 +00:00
const reserved: ReservedHit[] = [];
feat(resolve): derive DATABASE_URL/REDIS_URL from the database cast created (#60) Add a ${resource:<name>.url} env-template ref that resolves to the internal URL of a database the same manifest declares, read back from the live resource's internal_db_url — never stored in the age store, never decrypted, never printed. This deletes the two-pass generated-secret bootstrap for a database's own URL rather than automating it: no placeholder, no stored copy to drift or overwrite, and a rotated password is simply followed on the next apply. Resolution runs in one function (fillDerivedEnv) against two URL maps: at diff time against databases already on the box (so a matching app shows no drift — killing the "secret DATABASE_URL differs" noise that ran on every plan), and in the executor at apply time against a database created earlier in the same run (the from-nothing case; apply acts databases-before-applications, #45). The unresolved sentinel is never written — the executor refuses, rather than write a blank that boots the app pointed at nothing, and re-running once the database is up resolves it as an ordinary update. A ${resource:X.url} naming a database the manifest does not declare, or an attribute other than .url, is a hard plan-time error refused by every verb that opens a template (apply, diff, capture). generated_secrets and the two-pass bootstrap remain for the residual class — a provider-generated value that genuinely is not derivable. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 23:46:26 +00:00
const resourceRefs: Array<{ key: string; resource: string; attr: string }> =
[];
feat(resolve): derive base-URL env vars from manifest domains via ${domain:...} (#66) A public base URL an app reads (LANDING_BASE_URL, ADMIN_WEB_BASE_URL) is a fact the manifest already states in `domains`/`service_domains` — the same fields cast parses to reconcile Coolify domains. Hand-transcribing it into an env template is a second copy that drifts (incubator's prod LANDING_BASE_URL silently kept a pre-apex host). So a template can now say it directly: LANDING_BASE_URL=${domain:landing} ADMIN_WEB_BASE_URL=${domain:core.admin} - ${domain:<app>} -> applications.<app>.domains[0] - ${domain:<app>.<service>} -> applications.<app>.service_domains.<service>[0] Symmetric with ${resource:...} (#60) — parse -> sentinel -> validate -> fill — but a domain is PURE MANIFEST DATA, known at plan time, so it resolves fully in desiredFromManifest against a map built from the manifest: no live read, no executor deferral, no unresolved-at-write path. Domains are PUBLIC, so they resolve to secret:false (printed in diffs) and read as plain literals downstream (no diff.ts change). Not secrets: excluded from templateRefs, never captured. assertDomainRefs is the single validation gate (apply/diff/capture), refusing an undeclared app/service, a wrong-shape ref, or an empty/blank domain list before the sentinel can escape. Applications only (Coolify 4.1.2 can't set service domains). REPORTING_TZ-style operator literals stay literal. Closes #66. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 12:02:33 +00:00
const domainRefs: Array<{ key: string; app: string; service?: string }> = [];
// A domain is pure manifest data, so its map is built once from the manifest
// itself — independent of any template — and every resolved env is filled
// against it at plan time. assertDomainRefs at the end throws on any ref that
// did not resolve, so the sentinel never escapes into a returned env.
const domainMap = buildDomainMap(envSpec);
feat: cast — the Coolify executor, extracted from the infra state repo Public tool, private state. cast holds no hostnames, no bindings, no secrets: it joins a product repo's .infra/ manifest with a state directory you point it at, and makes Coolify match. Extracted from heavy-duty/infra, which was half tool and half state — the inconsistency that made it impossible to say whether "infra" named a CLI or a runbook. rig builds the boxes; cast fills them; infra is what they are filled with. Two changes were required to make it genuinely stateless and publishable: - The implicit cwd contract (environments.yaml / secrets/ / .coolify.env resolved against the working directory, silently reading the wrong file from the wrong place) is now an explicit --state <dir> / $CAST_STATE. - BANNED_IN_PROD — a hardcoded list of one product's ALLOW_* flags, the only product knowledge in the executor — becomes the generic, operator- owned environments.<env>.forbidden_var_patterns. The guard now lives in private state, so a product-side change cannot lower its own guard, and it is a pattern rather than a list, so it catches unforeseen siblings. Age identities resolve as $CAST_AGE_KEY_FILE_<ENV> then ~/.config/cast/age-<env>.key — which is the entire attended-vs-unattended apply mechanism, with no environment names known to the tool. Instance identity (org names, the GitHub App name, founder domains) is out of the fixtures and out of register-github-app.sh, which took APP_NAME and ORG as arguments rather than baking them in. 69 tests green; bin/cast + curl installer mirror rig's shape. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 12:25:44 +00:00
const resolveEnvFile = (
name: string,
template?: string,
): ResolvedEnv | undefined => {
if (!template) return undefined;
const file = join(checkoutDir, ".infra", "env", template);
if (!existsSync(file))
throw new Error(`env template missing: ${file} (referenced by ${name})`);
feat(resolve): derive DATABASE_URL/REDIS_URL from the database cast created (#60) Add a ${resource:<name>.url} env-template ref that resolves to the internal URL of a database the same manifest declares, read back from the live resource's internal_db_url — never stored in the age store, never decrypted, never printed. This deletes the two-pass generated-secret bootstrap for a database's own URL rather than automating it: no placeholder, no stored copy to drift or overwrite, and a rotated password is simply followed on the next apply. Resolution runs in one function (fillDerivedEnv) against two URL maps: at diff time against databases already on the box (so a matching app shows no drift — killing the "secret DATABASE_URL differs" noise that ran on every plan), and in the executor at apply time against a database created earlier in the same run (the from-nothing case; apply acts databases-before-applications, #45). The unresolved sentinel is never written — the executor refuses, rather than write a blank that boots the app pointed at nothing, and re-running once the database is up resolves it as an ordinary update. A ${resource:X.url} naming a database the manifest does not declare, or an attribute other than .url, is a hard plan-time error refused by every verb that opens a template (apply, diff, capture). generated_secrets and the two-pass bootstrap remain for the residual class — a provider-generated value that genuinely is not derivable. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 23:46:26 +00:00
const text = readFileSync(file, "utf8");
feat(resolve): derive base-URL env vars from manifest domains via ${domain:...} (#66) A public base URL an app reads (LANDING_BASE_URL, ADMIN_WEB_BASE_URL) is a fact the manifest already states in `domains`/`service_domains` — the same fields cast parses to reconcile Coolify domains. Hand-transcribing it into an env template is a second copy that drifts (incubator's prod LANDING_BASE_URL silently kept a pre-apex host). So a template can now say it directly: LANDING_BASE_URL=${domain:landing} ADMIN_WEB_BASE_URL=${domain:core.admin} - ${domain:<app>} -> applications.<app>.domains[0] - ${domain:<app>.<service>} -> applications.<app>.service_domains.<service>[0] Symmetric with ${resource:...} (#60) — parse -> sentinel -> validate -> fill — but a domain is PURE MANIFEST DATA, known at plan time, so it resolves fully in desiredFromManifest against a map built from the manifest: no live read, no executor deferral, no unresolved-at-write path. Domains are PUBLIC, so they resolve to secret:false (printed in diffs) and read as plain literals downstream (no diff.ts change). Not secrets: excluded from templateRefs, never captured. assertDomainRefs is the single validation gate (apply/diff/capture), refusing an undeclared app/service, a wrong-shape ref, or an empty/blank domain list before the sentinel can escape. Applications only (Coolify 4.1.2 can't set service domains). REPORTING_TZ-style operator literals stay literal. Closes #66. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 12:02:33 +00:00
const env = fillDomainEnv(resolveTemplate(text, secrets), domainMap);
fix: never write an env var whose name Coolify injects itself (#50) Coolify injects SOURCE_COMMIT and the COOLIFY_* family into an application's runtime environment itself, and SKIPS its own injection of a name the resource already carries a var of (ApplicationDeploymentJob.php v4.1.2, line 2994 — `->where('key', 'SOURCE_COMMIT')->isEmpty()`). A resource-level var of that name therefore SUPPRESSES the platform's value. An empty one suppresses it just as completely: presence, not value. And it fails green — the deploy succeeds, health checks pass, and the only symptom is /version reporting "unknown", the endpoint a production cutover is gated on (D-266). The rule is now a property of cast, not of one code path. A new src/reserved.ts owns it, and every place cast touches an env var honors it: - resolve — every manifest read (desiredFromManifest, requiredSecrets, manifestResources) refuses a template declaring a reserved name, before any write. So apply, diff, capture and inventory all refuse identically. - draft — a reserved name read off a live box gets its own provenance, `suppressed`: out of the template, out of the age store, its live value read into no artifact, and named in UNCAPTURED.md with the consequence. - diff — promoted out of the remove-candidate orphan list ("apply never removes these; read them by eye") and printed as a FINDING with its consequence. Not clean. apply still never deletes: cast reports, the human removes it. - capture (classify) and cli (syncEnv) carry the same assertion at the file and at the wire — unreachable through the CLI today, and kept because the invariant is "cast never writes one", not "the CLI happens to check first". - smoke writes an env var too; its probe names are asserted outside the space. The rule lives in cast's code, NOT beside forbidden_var_patterns in private state: that one is policy an environment may set for itself, this one is a fact about Coolify, true on every box — nothing a manifest change could lower. 19 tests in test/reserved.test.ts, one per path. Closes #50.
2026-07-14 22:29:23 +00:00
reserved.push(...reservedHits(name, Object.keys(env.vars)));
feat(resolve): derive DATABASE_URL/REDIS_URL from the database cast created (#60) Add a ${resource:<name>.url} env-template ref that resolves to the internal URL of a database the same manifest declares, read back from the live resource's internal_db_url — never stored in the age store, never decrypted, never printed. This deletes the two-pass generated-secret bootstrap for a database's own URL rather than automating it: no placeholder, no stored copy to drift or overwrite, and a rotated password is simply followed on the next apply. Resolution runs in one function (fillDerivedEnv) against two URL maps: at diff time against databases already on the box (so a matching app shows no drift — killing the "secret DATABASE_URL differs" noise that ran on every plan), and in the executor at apply time against a database created earlier in the same run (the from-nothing case; apply acts databases-before-applications, #45). The unresolved sentinel is never written — the executor refuses, rather than write a blank that boots the app pointed at nothing, and re-running once the database is up resolves it as an ordinary update. A ${resource:X.url} naming a database the manifest does not declare, or an attribute other than .url, is a hard plan-time error refused by every verb that opens a template (apply, diff, capture). generated_secrets and the two-pass bootstrap remain for the residual class — a provider-generated value that genuinely is not derivable. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 23:46:26 +00:00
resourceRefs.push(...templateResourceRefs(text));
feat(resolve): derive base-URL env vars from manifest domains via ${domain:...} (#66) A public base URL an app reads (LANDING_BASE_URL, ADMIN_WEB_BASE_URL) is a fact the manifest already states in `domains`/`service_domains` — the same fields cast parses to reconcile Coolify domains. Hand-transcribing it into an env template is a second copy that drifts (incubator's prod LANDING_BASE_URL silently kept a pre-apex host). So a template can now say it directly: LANDING_BASE_URL=${domain:landing} ADMIN_WEB_BASE_URL=${domain:core.admin} - ${domain:<app>} -> applications.<app>.domains[0] - ${domain:<app>.<service>} -> applications.<app>.service_domains.<service>[0] Symmetric with ${resource:...} (#60) — parse -> sentinel -> validate -> fill — but a domain is PURE MANIFEST DATA, known at plan time, so it resolves fully in desiredFromManifest against a map built from the manifest: no live read, no executor deferral, no unresolved-at-write path. Domains are PUBLIC, so they resolve to secret:false (printed in diffs) and read as plain literals downstream (no diff.ts change). Not secrets: excluded from templateRefs, never captured. assertDomainRefs is the single validation gate (apply/diff/capture), refusing an undeclared app/service, a wrong-shape ref, or an empty/blank domain list before the sentinel can escape. Applications only (Coolify 4.1.2 can't set service domains). REPORTING_TZ-style operator literals stay literal. Closes #66. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 12:02:33 +00:00
domainRefs.push(...templateDomainRefs(text));
feat: cast — the Coolify executor, extracted from the infra state repo Public tool, private state. cast holds no hostnames, no bindings, no secrets: it joins a product repo's .infra/ manifest with a state directory you point it at, and makes Coolify match. Extracted from heavy-duty/infra, which was half tool and half state — the inconsistency that made it impossible to say whether "infra" named a CLI or a runbook. rig builds the boxes; cast fills them; infra is what they are filled with. Two changes were required to make it genuinely stateless and publishable: - The implicit cwd contract (environments.yaml / secrets/ / .coolify.env resolved against the working directory, silently reading the wrong file from the wrong place) is now an explicit --state <dir> / $CAST_STATE. - BANNED_IN_PROD — a hardcoded list of one product's ALLOW_* flags, the only product knowledge in the executor — becomes the generic, operator- owned environments.<env>.forbidden_var_patterns. The guard now lives in private state, so a product-side change cannot lower its own guard, and it is a pattern rather than a list, so it catches unforeseen siblings. Age identities resolve as $CAST_AGE_KEY_FILE_<ENV> then ~/.config/cast/age-<env>.key — which is the entire attended-vs-unattended apply mechanism, with no environment names known to the tool. Instance identity (org names, the GitHub App name, founder domains) is out of the fixtures and out of register-github-app.sh, which took APP_NAME and ORG as arguments rather than baking them in. 69 tests green; bin/cast + curl installer mirror rig's shape. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 12:25:44 +00:00
resolvedEnvs[name] = env;
return env;
};
for (const [name, app] of Object.entries(envSpec.applications)) {
if (app.build.pack === "dockercompose") {
// Coolify gates the SOURCE_COMMIT *build arg* behind a per-application
// setting — `ApplicationSetting.include_source_commit_in_build`, default
// false — and in 4.1.2 that setting has NO API surface. Verified against
// the v4.1.2 source: it appears in zero API controllers, and both the
// create and the PATCH allowlists in ApplicationsController.php (l.914,
// l.2368) reject unrecognized keys outright ("This field is not
// allowed."), so sending it would fail the whole request rather than be
// quietly ignored. Its only writer is the Livewire Advanced tab
// (app/Livewire/Project/Application/Advanced.php:128) — i.e. a human, in
// the UI. Do NOT add it to `fields` below expecting apply to set it the
// way it sets `connect_to_docker_network` (which *is* in the allowlist,
// which is why that one works): apply would 422 on every run. Warning is
// the only honest move — a manual step the tool knows about and does not
// mention is one that gets forgotten, and this one fails green.
//
// Scope: the toggle gates the BUILD-time arg only. Coolify's *runtime*
// injection of SOURCE_COMMIT is unconditional with respect to it
// (ApplicationDeploymentJob.php:2949 — `if (! $forBuildTime || ...)`,
// which short-circuits true at runtime), so a service that reads
// process.env.SOURCE_COMMIT per request does not need this toggle at all.
// What *does* silently suppress that runtime value is an application-level
// env var of the same name (ApplicationDeploymentJob.php:2950) — a
// different bug, tracked separately.
console.warn(
`application ${name} builds with dockercompose, but apply cannot enable "Include Source Commit in Build" on Coolify 4.1.2 — the setting is absent from the API's field allowlist. If the build consumes SOURCE_COMMIT as a build arg, enable it in the Coolify UI and redeploy; Coolify injects SOURCE_COMMIT at runtime regardless.`,
);
}
feat: cast — the Coolify executor, extracted from the infra state repo Public tool, private state. cast holds no hostnames, no bindings, no secrets: it joins a product repo's .infra/ manifest with a state directory you point it at, and makes Coolify match. Extracted from heavy-duty/infra, which was half tool and half state — the inconsistency that made it impossible to say whether "infra" named a CLI or a runbook. rig builds the boxes; cast fills them; infra is what they are filled with. Two changes were required to make it genuinely stateless and publishable: - The implicit cwd contract (environments.yaml / secrets/ / .coolify.env resolved against the working directory, silently reading the wrong file from the wrong place) is now an explicit --state <dir> / $CAST_STATE. - BANNED_IN_PROD — a hardcoded list of one product's ALLOW_* flags, the only product knowledge in the executor — becomes the generic, operator- owned environments.<env>.forbidden_var_patterns. The guard now lives in private state, so a product-side change cannot lower its own guard, and it is a pattern rather than a list, so it catches unforeseen siblings. Age identities resolve as $CAST_AGE_KEY_FILE_<ENV> then ~/.config/cast/age-<env>.key — which is the entire attended-vs-unattended apply mechanism, with no environment names known to the tool. Instance identity (org names, the GitHub App name, founder domains) is out of the fixtures and out of register-github-app.sh, which took APP_NAME and ORG as arguments rather than baking them in. 69 tests green; bin/cast + curl installer mirror rig's shape. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 12:25:44 +00:00
desired.push({
kind: "application",
name,
fields: {
git_repository: app.source.repo,
git_branch: app.source.branch,
build_pack: app.build.pack,
base_directory: app.build.base_directory,
...(app.build.publish_directory
? { publish_directory: app.build.publish_directory }
: {}),
...(app.build.pack === "dockercompose"
? {
docker_compose_location: app.build.compose_file,
docker_compose_domains: app.service_domains,
}
: {
...(app.port !== undefined ? { port: app.port } : {}),
...(app.healthcheck ? { healthcheck: app.healthcheck } : {}),
domains: app.domains,
// Emitted only when the manifest DECLARES `static:` — like the
// three commands, not unconditionally. Emitting `is_static:false`
// on every non-compose app would make the first apply after this
// ships PATCH `is_static=false` onto any static/SPA app configured
// in the UI whose manifest has not yet been migrated — silently
// disabling static serving and re-creating the #63 crash, now
// caused by cast. And a `pack: static` app that Coolify couples to
// is_static=true would drift-and-revert forever. So managing
// is_static is opt-in: declare `static: true` to serve, `static:
// false` to actively guard against a UI flip to true, or omit it to
// leave the field alone. (Coolify keeps pack and is_static
// independent, which is why this stays an explicit field, not a
// heuristic off `pack`.)
...(app.build.static !== undefined
? { is_static: app.build.static }
: {}),
...(app.build.install_command !== undefined
? { install_command: app.build.install_command }
: {}),
...(app.build.build_command !== undefined
? { build_command: app.build.build_command }
: {}),
...(app.build.start_command !== undefined
? { start_command: app.build.start_command }
: {}),
feat: cast — the Coolify executor, extracted from the infra state repo Public tool, private state. cast holds no hostnames, no bindings, no secrets: it joins a product repo's .infra/ manifest with a state directory you point it at, and makes Coolify match. Extracted from heavy-duty/infra, which was half tool and half state — the inconsistency that made it impossible to say whether "infra" named a CLI or a runbook. rig builds the boxes; cast fills them; infra is what they are filled with. Two changes were required to make it genuinely stateless and publishable: - The implicit cwd contract (environments.yaml / secrets/ / .coolify.env resolved against the working directory, silently reading the wrong file from the wrong place) is now an explicit --state <dir> / $CAST_STATE. - BANNED_IN_PROD — a hardcoded list of one product's ALLOW_* flags, the only product knowledge in the executor — becomes the generic, operator- owned environments.<env>.forbidden_var_patterns. The guard now lives in private state, so a product-side change cannot lower its own guard, and it is a pattern rather than a list, so it catches unforeseen siblings. Age identities resolve as $CAST_AGE_KEY_FILE_<ENV> then ~/.config/cast/age-<env>.key — which is the entire attended-vs-unattended apply mechanism, with no environment names known to the tool. Instance identity (org names, the GitHub App name, founder domains) is out of the fixtures and out of register-github-app.sh, which took APP_NAME and ORG as arguments rather than baking them in. 69 tests green; bin/cast + curl installer mirror rig's shape. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 12:25:44 +00:00
}),
},
env: resolveEnvFile(name, app.env_template),
});
}
for (const [name, db] of Object.entries(envSpec.databases ?? {})) {
desired.push({
kind: "database",
name,
feat: diff and apply a database's backup schedule (#51) Backup schedules were write-only, filed under "known limitations" on the claim that "live Coolify state doesn't expose it back". The parenthesis was load-bearing and false: a schedule is not on the database's own GET, but it was never meant to be — it has its own route, GET /databases/{uuid}/backups, which cast had been POSTing to all along and had simply never read. The cost was exact. A database created before its `backup:` block was declared never got one (apply set the schedule only inside the create branch); a schedule deleted in the UI was invisible; and the `--full` diff that gates a production cutover passed with an unbacked-up production database. Shape settled from the source rather than the vendored spec, which documents the body as "Content is very complex. Will be implemented later.": DatabasesController@database_backup_details_uuid (v4.1.2) returns a raw Eloquent collection — a JSON array of ScheduledDatabaseBackup rows, columns per $fillable (uuid, enabled, frequency, database_backup_retention_amount_locally). `frequency` round-trips verbatim: the controller validates it and stores $request->only(...) unchanged, with no mutator on the model. The "diffing it would flag spurious drift" fear was a guess about a read nobody had performed. - `backup` becomes a diffed field like any other (resolve.ts), replacing the side channel that carried it around the diff. - The live side reads the route (coolify.ts, fetchLive), and apply sets the schedule on UPDATE as well as create — POST or PATCH, decided by a read. - A disabled schedule is a row that backs nothing up: neither clean nor absent. cast diffs it and re-enables it. Degrades honestly, since no live box was probed: an unreachable or unrecognized response can only ever produce "declared, NOT compared — verify in the Coolify UI", never invented drift and never a clean bill on an unread database. On the write side the same failure raises rather than guessing — POSTing blind would duplicate a schedule that may already exist.
2026-07-14 22:37:01 +00:00
fields: {
type: db.type,
...(db.version ? { version: db.version } : {}),
// `backup` is a DIFFED FIELD, like any other.
//
// It used to be routed around `fields` into a side channel, on the
// stated grounds that "live Coolify state doesn't expose it back" — so
// diffing it would flag spurious drift forever. That premise was false:
// it is not on the database's own GET, but GET /databases/{uuid}/backups
// is a route (cast has always POSTed to it), and frequency/retention
// round-trip verbatim through it. The side channel is what made a
// `backup:` block added to an EXISTING database do nothing, silently,
// and made `diff --full` pass on a production database with no backups.
//
// Key order matters: computeDiff compares by JSON.stringify, and the
// live side (fetchLive in cli.ts) builds this same object in this same
// order. Do not reorder one without the other.
...(db.backup
? {
backup: {
frequency: db.backup.frequency,
retention: db.backup.retention,
},
}
: {}),
},
feat: cast — the Coolify executor, extracted from the infra state repo Public tool, private state. cast holds no hostnames, no bindings, no secrets: it joins a product repo's .infra/ manifest with a state directory you point it at, and makes Coolify match. Extracted from heavy-duty/infra, which was half tool and half state — the inconsistency that made it impossible to say whether "infra" named a CLI or a runbook. rig builds the boxes; cast fills them; infra is what they are filled with. Two changes were required to make it genuinely stateless and publishable: - The implicit cwd contract (environments.yaml / secrets/ / .coolify.env resolved against the working directory, silently reading the wrong file from the wrong place) is now an explicit --state <dir> / $CAST_STATE. - BANNED_IN_PROD — a hardcoded list of one product's ALLOW_* flags, the only product knowledge in the executor — becomes the generic, operator- owned environments.<env>.forbidden_var_patterns. The guard now lives in private state, so a product-side change cannot lower its own guard, and it is a pattern rather than a list, so it catches unforeseen siblings. Age identities resolve as $CAST_AGE_KEY_FILE_<ENV> then ~/.config/cast/age-<env>.key — which is the entire attended-vs-unattended apply mechanism, with no environment names known to the tool. Instance identity (org names, the GitHub App name, founder domains) is out of the fixtures and out of register-github-app.sh, which took APP_NAME and ORG as arguments rather than baking them in. 69 tests green; bin/cast + curl installer mirror rig's shape. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 12:25:44 +00:00
});
}
for (const [name, svc] of Object.entries(envSpec.services ?? {})) {
if (svc.domains && svc.domains.length > 0) {
// Coolify 4.1.2's service executor has no flat `domains` concept —
// hostnames live per-container on `urls` (see serviceApiFields in
// cli.ts) — so a manifest-declared service `domains` list is silently
// unhonorable by apply. Warn at build time, once per run, while the
// service name is still in scope.
console.warn(
`service ${name} declares domains (${svc.domains.join(", ")}), but apply cannot set them on Coolify 4.1.2 services — configure hostnames manually in the Coolify UI`,
);
}
desired.push({
kind: "service",
name,
feat: diff and apply a database's backup schedule (#51) Backup schedules were write-only, filed under "known limitations" on the claim that "live Coolify state doesn't expose it back". The parenthesis was load-bearing and false: a schedule is not on the database's own GET, but it was never meant to be — it has its own route, GET /databases/{uuid}/backups, which cast had been POSTing to all along and had simply never read. The cost was exact. A database created before its `backup:` block was declared never got one (apply set the schedule only inside the create branch); a schedule deleted in the UI was invisible; and the `--full` diff that gates a production cutover passed with an unbacked-up production database. Shape settled from the source rather than the vendored spec, which documents the body as "Content is very complex. Will be implemented later.": DatabasesController@database_backup_details_uuid (v4.1.2) returns a raw Eloquent collection — a JSON array of ScheduledDatabaseBackup rows, columns per $fillable (uuid, enabled, frequency, database_backup_retention_amount_locally). `frequency` round-trips verbatim: the controller validates it and stores $request->only(...) unchanged, with no mutator on the model. The "diffing it would flag spurious drift" fear was a guess about a read nobody had performed. - `backup` becomes a diffed field like any other (resolve.ts), replacing the side channel that carried it around the diff. - The live side reads the route (coolify.ts, fetchLive), and apply sets the schedule on UPDATE as well as create — POST or PATCH, decided by a read. - A disabled schedule is a row that backs nothing up: neither clean nor absent. cast diffs it and re-enables it. Degrades honestly, since no live box was probed: an unreachable or unrecognized response can only ever produce "declared, NOT compared — verify in the Coolify UI", never invented drift and never a clean bill on an unread database. On the write side the same failure raises rather than guessing — POSTing blind would duplicate a schedule that may already exist.
2026-07-14 22:37:01 +00:00
// domains dropped from fields: the live side (projectLiveFields in
// cli.ts) can't read service domains and the write side
// (serviceApiFields) drops them, so keeping domains in fields makes
// every domain-bearing service diff as a perpetual update. Hostnames
// stay a manual Coolify UI act (warned above).
//
// This USED to cite database `backup` as its precedent. It no longer
// can: `backup` was dropped on the same reasoning and the reasoning
// turned out to be false there (a read route existed, unlooked-for —
// see the databases loop above). The difference is that this one was
// re-checked: Coolify 4.1.2 genuinely exposes no flat `domains` on a
// service, on any route. If that is ever disproved the same way, this
// belongs in `fields` too.
feat: cast — the Coolify executor, extracted from the infra state repo Public tool, private state. cast holds no hostnames, no bindings, no secrets: it joins a product repo's .infra/ manifest with a state directory you point it at, and makes Coolify match. Extracted from heavy-duty/infra, which was half tool and half state — the inconsistency that made it impossible to say whether "infra" named a CLI or a runbook. rig builds the boxes; cast fills them; infra is what they are filled with. Two changes were required to make it genuinely stateless and publishable: - The implicit cwd contract (environments.yaml / secrets/ / .coolify.env resolved against the working directory, silently reading the wrong file from the wrong place) is now an explicit --state <dir> / $CAST_STATE. - BANNED_IN_PROD — a hardcoded list of one product's ALLOW_* flags, the only product knowledge in the executor — becomes the generic, operator- owned environments.<env>.forbidden_var_patterns. The guard now lives in private state, so a product-side change cannot lower its own guard, and it is a pattern rather than a list, so it catches unforeseen siblings. Age identities resolve as $CAST_AGE_KEY_FILE_<ENV> then ~/.config/cast/age-<env>.key — which is the entire attended-vs-unattended apply mechanism, with no environment names known to the tool. Instance identity (org names, the GitHub App name, founder domains) is out of the fixtures and out of register-github-app.sh, which took APP_NAME and ORG as arguments rather than baking them in. 69 tests green; bin/cast + curl installer mirror rig's shape. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 12:25:44 +00:00
fields: { type: svc.type },
env: resolveEnvFile(name, svc.env_template),
});
}
fix: never write an env var whose name Coolify injects itself (#50) Coolify injects SOURCE_COMMIT and the COOLIFY_* family into an application's runtime environment itself, and SKIPS its own injection of a name the resource already carries a var of (ApplicationDeploymentJob.php v4.1.2, line 2994 — `->where('key', 'SOURCE_COMMIT')->isEmpty()`). A resource-level var of that name therefore SUPPRESSES the platform's value. An empty one suppresses it just as completely: presence, not value. And it fails green — the deploy succeeds, health checks pass, and the only symptom is /version reporting "unknown", the endpoint a production cutover is gated on (D-266). The rule is now a property of cast, not of one code path. A new src/reserved.ts owns it, and every place cast touches an env var honors it: - resolve — every manifest read (desiredFromManifest, requiredSecrets, manifestResources) refuses a template declaring a reserved name, before any write. So apply, diff, capture and inventory all refuse identically. - draft — a reserved name read off a live box gets its own provenance, `suppressed`: out of the template, out of the age store, its live value read into no artifact, and named in UNCAPTURED.md with the consequence. - diff — promoted out of the remove-candidate orphan list ("apply never removes these; read them by eye") and printed as a FINDING with its consequence. Not clean. apply still never deletes: cast reports, the human removes it. - capture (classify) and cli (syncEnv) carry the same assertion at the file and at the wire — unreachable through the CLI today, and kept because the invariant is "cast never writes one", not "the CLI happens to check first". - smoke writes an env var too; its probe names are asserted outside the space. The rule lives in cast's code, NOT beside forbidden_var_patterns in private state: that one is policy an environment may set for itself, this one is a fact about Coolify, true on every box — nothing a manifest change could lower. 19 tests in test/reserved.test.ts, one per path. Closes #50.
2026-07-14 22:29:23 +00:00
// Before the caller can diff it, and long before apply can write it: a
// resolved env that carries a reserved name is not desired state, it is a
// suppression of the platform's own value dressed up as one. See reserved.ts.
assertNoReservedEnvNames(reserved);
feat(resolve): derive DATABASE_URL/REDIS_URL from the database cast created (#60) Add a ${resource:<name>.url} env-template ref that resolves to the internal URL of a database the same manifest declares, read back from the live resource's internal_db_url — never stored in the age store, never decrypted, never printed. This deletes the two-pass generated-secret bootstrap for a database's own URL rather than automating it: no placeholder, no stored copy to drift or overwrite, and a rotated password is simply followed on the next apply. Resolution runs in one function (fillDerivedEnv) against two URL maps: at diff time against databases already on the box (so a matching app shows no drift — killing the "secret DATABASE_URL differs" noise that ran on every plan), and in the executor at apply time against a database created earlier in the same run (the from-nothing case; apply acts databases-before-applications, #45). The unresolved sentinel is never written — the executor refuses, rather than write a blank that boots the app pointed at nothing, and re-running once the database is up resolves it as an ordinary update. A ${resource:X.url} naming a database the manifest does not declare, or an attribute other than .url, is a hard plan-time error refused by every verb that opens a template (apply, diff, capture). generated_secrets and the two-pass bootstrap remain for the residual class — a provider-generated value that genuinely is not derivable. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 23:46:26 +00:00
assertResourceRefs(
envName,
new Set(Object.keys(envSpec.databases ?? {})),
resourceRefs,
);
feat(resolve): derive base-URL env vars from manifest domains via ${domain:...} (#66) A public base URL an app reads (LANDING_BASE_URL, ADMIN_WEB_BASE_URL) is a fact the manifest already states in `domains`/`service_domains` — the same fields cast parses to reconcile Coolify domains. Hand-transcribing it into an env template is a second copy that drifts (incubator's prod LANDING_BASE_URL silently kept a pre-apex host). So a template can now say it directly: LANDING_BASE_URL=${domain:landing} ADMIN_WEB_BASE_URL=${domain:core.admin} - ${domain:<app>} -> applications.<app>.domains[0] - ${domain:<app>.<service>} -> applications.<app>.service_domains.<service>[0] Symmetric with ${resource:...} (#60) — parse -> sentinel -> validate -> fill — but a domain is PURE MANIFEST DATA, known at plan time, so it resolves fully in desiredFromManifest against a map built from the manifest: no live read, no executor deferral, no unresolved-at-write path. Domains are PUBLIC, so they resolve to secret:false (printed in diffs) and read as plain literals downstream (no diff.ts change). Not secrets: excluded from templateRefs, never captured. assertDomainRefs is the single validation gate (apply/diff/capture), refusing an undeclared app/service, a wrong-shape ref, or an empty/blank domain list before the sentinel can escape. Applications only (Coolify 4.1.2 can't set service domains). REPORTING_TZ-style operator literals stay literal. Closes #66. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 12:02:33 +00:00
// Throws BEFORE the desired set is returned, so an invalid domain ref never
// ships the sentinel: every env in `resolvedEnvs` and every `desired[].env` is
// already domain-filled by resolveEnvFile above.
assertDomainRefs(envName, envSpec.applications, domainRefs);
feat: diff and apply a database's backup schedule (#51) Backup schedules were write-only, filed under "known limitations" on the claim that "live Coolify state doesn't expose it back". The parenthesis was load-bearing and false: a schedule is not on the database's own GET, but it was never meant to be — it has its own route, GET /databases/{uuid}/backups, which cast had been POSTing to all along and had simply never read. The cost was exact. A database created before its `backup:` block was declared never got one (apply set the schedule only inside the create branch); a schedule deleted in the UI was invisible; and the `--full` diff that gates a production cutover passed with an unbacked-up production database. Shape settled from the source rather than the vendored spec, which documents the body as "Content is very complex. Will be implemented later.": DatabasesController@database_backup_details_uuid (v4.1.2) returns a raw Eloquent collection — a JSON array of ScheduledDatabaseBackup rows, columns per $fillable (uuid, enabled, frequency, database_backup_retention_amount_locally). `frequency` round-trips verbatim: the controller validates it and stores $request->only(...) unchanged, with no mutator on the model. The "diffing it would flag spurious drift" fear was a guess about a read nobody had performed. - `backup` becomes a diffed field like any other (resolve.ts), replacing the side channel that carried it around the diff. - The live side reads the route (coolify.ts, fetchLive), and apply sets the schedule on UPDATE as well as create — POST or PATCH, decided by a read. - A disabled schedule is a row that backs nothing up: neither clean nor absent. cast diffs it and re-enables it. Degrades honestly, since no live box was probed: an unreachable or unrecognized response can only ever produce "declared, NOT compared — verify in the Coolify UI", never invented drift and never a clean bill on an unread database. On the write side the same failure raises rather than guessing — POSTing blind would duplicate a schedule that may already exist.
2026-07-14 22:37:01 +00:00
return { desired, resolvedEnvs };
feat: cast — the Coolify executor, extracted from the infra state repo Public tool, private state. cast holds no hostnames, no bindings, no secrets: it joins a product repo's .infra/ manifest with a state directory you point it at, and makes Coolify match. Extracted from heavy-duty/infra, which was half tool and half state — the inconsistency that made it impossible to say whether "infra" named a CLI or a runbook. rig builds the boxes; cast fills them; infra is what they are filled with. Two changes were required to make it genuinely stateless and publishable: - The implicit cwd contract (environments.yaml / secrets/ / .coolify.env resolved against the working directory, silently reading the wrong file from the wrong place) is now an explicit --state <dir> / $CAST_STATE. - BANNED_IN_PROD — a hardcoded list of one product's ALLOW_* flags, the only product knowledge in the executor — becomes the generic, operator- owned environments.<env>.forbidden_var_patterns. The guard now lives in private state, so a product-side change cannot lower its own guard, and it is a pattern rather than a list, so it catches unforeseen siblings. Age identities resolve as $CAST_AGE_KEY_FILE_<ENV> then ~/.config/cast/age-<env>.key — which is the entire attended-vs-unattended apply mechanism, with no environment names known to the tool. Instance identity (org names, the GitHub App name, founder domains) is out of the fixtures and out of register-github-app.sh, which took APP_NAME and ORG as arguments rather than baking them in. 69 tests green; bin/cast + curl installer mirror rig's shape. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 12:25:44 +00:00
}
feat(resolve): derive DATABASE_URL/REDIS_URL from the database cast created (#60) Add a ${resource:<name>.url} env-template ref that resolves to the internal URL of a database the same manifest declares, read back from the live resource's internal_db_url — never stored in the age store, never decrypted, never printed. This deletes the two-pass generated-secret bootstrap for a database's own URL rather than automating it: no placeholder, no stored copy to drift or overwrite, and a rotated password is simply followed on the next apply. Resolution runs in one function (fillDerivedEnv) against two URL maps: at diff time against databases already on the box (so a matching app shows no drift — killing the "secret DATABASE_URL differs" noise that ran on every plan), and in the executor at apply time against a database created earlier in the same run (the from-nothing case; apply acts databases-before-applications, #45). The unresolved sentinel is never written — the executor refuses, rather than write a blank that boots the app pointed at nothing, and re-running once the database is up resolves it as an ordinary update. A ${resource:X.url} naming a database the manifest does not declare, or an attribute other than .url, is a hard plan-time error refused by every verb that opens a template (apply, diff, capture). generated_secrets and the two-pass bootstrap remain for the residual class — a provider-generated value that genuinely is not derivable. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 23:46:26 +00:00
// Fill the derived vars in a desired set against a URL map keyed by MANIFEST
// resource name. Used twice, with two different maps, and that is the whole
// point of it being one function: diff/apply fills first against the resources
// that already exist on the box (so an app whose DATABASE_URL already equals the
// live database's URL shows no drift — the "differs on every plan" noise #60
// deletes), and the executor fills again against a database it has just created
// (the from-nothing case, where nothing existed to resolve against at plan
// time). A ref whose resource is in neither map stays unresolved; the executor
// is the one place that refuses to WRITE one that never resolved.
export function fillDesiredDerived(
desired: Desired[],
urls: Record<string, string>,
): Desired[] {
return desired.map((d) =>
d.env ? { ...d, env: fillDerivedEnv(d.env, urls) } : d,
);
}