Skip to content

feat(railway): generate Railway deploy files from the deployment model - #652

Merged
dmealing merged 4 commits into
mainfrom
fm/mo-enterprise-packs-railway
Nov 25, 2026
Merged

dmealing merged 4 commits into
mainfrom
fm/mo-enterprise-packs-railway

Conversation

@dmealing

@dmealing dmealing commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

What Changed

  • packs/railway (TypeScript, preview 0.1.0) adds generators that write .railway/railway.ts in Railway's Infrastructure as Code format, plus deploy/unexpressed.md (facts that format cannot hold), deploy/sync-secrets.sh (copies declared secrets from the vault scope to Railway through stdin), deploy/deploy.sh, deploy/doctor.sh and an agent deploy skill. railwayFiles() returns all six. The pack now requires the config pack.
  • packs/delivery gains @watchInclude on builds, @path on value.ref, the readBuild and readProcesses readers for platform generators, and a load-time ERR_DELIVERY_UNSUPPORTED_OUTPUT when a value.ref asks an app for an output it does not produce. Abstract deployments are now skipped by the one-deployment-per-(app, environment) check.
  • Adds conformance fixtures under packs/railway/fixtures/conformance/ (one-service, two-services, environments, abstract deployment, and an unsupported-output error case) with golden output for the generated files. A coverage test checks the generated .railway/railway.ts against every fact of the hand-written configuration the fixtures model, and emit and generated-type tests cover the rest. packs/systems adds the MANAGED_BY_PLATFORM and MANAGED_BY_EXTERNAL constants.

Acceptance, improvements and caveats

Ports: TypeScript only. The systems, delivery, config and railway packs are TypeScript-only under ADR-0069's port rule; no other port carries them, and no core vocabulary or metamodelVersion changes.

Acceptance bar: coverage, not byte identity. The emit fixtures are modelled on two adopters' hand-written Railway configuration (a hand-migrated .railway/railway.ts, and two railway.json files), with every name replaced by a placeholder; the fixtures hold no estate facts.

  • test/coverage.test.ts evaluates each golden .railway/railway.ts through a recording stand-in for railway/iac and checks, fact by fact, that it carries everything that configuration declares: source repository, branch and check suites; watch patterns (in order); Dockerfile path; health-check path and timeout; restart policy; draining seconds; the variable policy.
  • Outside the repository, the same check was run against the adopters' real files: 0 facts missing from the hand-migrated railway.ts, and the watch patterns of both railway.json files match exactly, with each Dockerfile path the service variable held.

Where the generated file improves on the hand-written one:

  • It type-checks against the railway 3.17.0 SDK types; the hand-written file does not (it widens restartPolicyType to string and puts variables in an object literal). RESTART_POLICY is typed to the SDK's union, and test/generated-types.test.ts pins both points.
  • Every service names the app and deployment it comes from, and every variable names its model node.
  • Secrets are never written: each is preserve(), and deploy/sync-secrets.sh copies the value from the vault through stdin.
  • Facts the format cannot hold are listed in deploy/unexpressed.md instead of being dropped. Examples: resources Railway runs beside the service, DNS, a branch on an image source, a port with no domain.
  • Domains, the health path and every reference to another service (${{db.DATABASE_URL}}, private domains) come from the model.
  • One abstract deployment holds what every environment shares, and each environment's deployment extends it and holds only its differences (railway-emit-environments).

Caveat: variables is not in the SDK's types. variables: { managed: false } is read by the Railway CLI (a plan against a live project with it planned no variable change), but the 3.17.0 SDK's ProjectDefinition does not declare it. The file spreads it from a declared constant (...unmanagedVariables), which the excess-property check does not apply to, so the file still type-checks. If a later SDK declares the key, the spread can become a plain property.

Validation runs: one no-mistakes run (one review fix round, which also took in two scope additions from the maintainer: the coverage bar and abstract per-environment deployments).

Validation

Risk Assessment

✅ Low: Fix round verified: abstract deployments are skipped in the delivery duplicate check and in readRailway, unexpressed.md lists the image-source branch/checkSuites and portless-domain cases, and the new fixtures and tests are backed by golden output and a parsed-AST type check. I found no defect or intent contradiction in the code I read.

Testing

Drove four live scenarios against the real pack code and loader: generate the environments output, load abstract-base and duplicate-deployment models, list unexpressed facts for an @image deployment, and run the generated secret sync with stubbed keys-axi and railway. The generated railway.ts also type-checks against the real railway 3.17.0 SDK. All passed. deploy.sh and doctor.sh need a live Railway account and vault identity, so they stayed untested. Temporary driver and scratch removed; worktree clean; evidence saved under the evidence directory.

  • Live validation: ✅ go - 7 of 8 scenarios driven live against the product
Scenario Result Live Evidence
Generate .railway/railway.ts from the environments model: one abstract base, production and staging each render their own branch, domains, replicas and values; staging overrides the base value; no ser… ✅ pass live generated-railway-environments.ts (real runGen, disposable project, identical to golden)
Abstract deployment with @Environment plus a concrete child loads clean ✅ pass live loadModels over fixture abstract-deployment-with-environment: no error thrown by the real strict MetaDataLoader
Adversarial: two concrete deployments for the same app and environment are still rejected ✅ pass live loadModels over fixture error-duplicate-deployment threw ERR_DELIVERY_DUPLICATE_DEPLOYMENT
Adversarial: facts that Railway IaC cannot hold are listed, not dropped (@Branch and @checkSuites with @image; port with no domain) ✅ pass live generated-unexpressed-one-service-with-image.md lists branch main, check suites false, and port 8080 rows
Secret sync: declared secret reaches Railway through stdin, never on a command line, and --dry-run writes nothing ✅ pass live sync-secrets-run.log and sync-secrets-railway-calls.log: argv contains no secret occurrence, stdin carried the value; dry-run line printed
Adversarial: secret missing from the vault scope fails the sync and Railway is never called ✅ pass live sync-secrets-run.log: 'sync-secrets: LLM_API_KEY is not in the vault scope', exit=1, railway invoked: 0
Generated railway.ts type-checks against the railway 3.17.0 SDK types ✅ pass live tsc --noEmit strict nodenext over generated .railway/railway.ts with railway@3.17.0 installed in a scratch prefix: exit 0
deploy.sh and doctor.sh run against a real Railway project and vault ⏸️ untested no Tried: no Railway account, railway CLI login or keys-axi vault identity in this environment, and no network-side platform was in scope. To drive it, provide a Railway test project with a linked repo a…
Evidence: Generated .railway/railway.ts, two environments from one abstract base (live generate, matches golden)
// @generated by @metaobjectsdev/pack-railway (railway-ts) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.
// Railway Infrastructure as Code for project acme-shop, from the model (railway pack).
// The `railway/iac` DSL of the `railway` npm package 3.17.0.
//
// Railway does not read this file during a deploy. It takes effect when `railway config apply`
// runs against an environment; `railway config plan` previews it. Both need the SDK beside it:
// `npm install --no-save --prefix .railway railway@3.17.0`. deploy/deploy.sh does both.
//
// A named partial: it manages only the services below. Databases and anything else it does
// not declare are left as they are, and the facts it cannot hold are in deploy/unexpressed.md.
// Variables are managed: the file declares every variable of its services, and an apply
// deletes one it does not declare. A secret is preserve(): deploy/sync-secrets.sh copies its
// value from the vault.
import { defineRailway, github, project, service } from "railway/iac";

export const partial = "shop";

export default defineRailway((ctx) => {
  if (ctx.environment === "production") {
    return project("acme-shop", {
      resources: [
        // app.service acme::shop::Shop.server, deployed by deployment.railway acme::shop::server-production
        service("shop", {
          source: github("acme/shop", { branch: "main" }),
          build: {
            builder: "DOCKERFILE",
            dockerfilePath: "server/Dockerfile",
            watchPatterns: [
              "server/**",
            ],
          },
          deploy: {
            healthcheckPath: "/health",
          },
          domains: [
            {
              domain: "shop.example.com",
              port: 8080,
            },
          ],
          replicas: 2,
          env: {
            BANNER: "production", // value.literal banner
            LOG_LEVEL: "info", // value.literal log
          },
        }),
      ],
    });
  }
  if (ctx.environment === "staging") {
    return project("acme-shop", {
      resources: [
        // app.service acme::shop::Shop.server, deployed by deployment.railway acme::shop::server-staging
        service("shop", {
          source: github("acme/shop", { branch: "staging" }),
          build: {
            builder: "DOCKERFILE",
            dockerfilePath: "server/Dockerfile",
            watchPatterns: [
              "server/**",
            ],
          },
          deploy: {
            healthcheckPath: "/health",
          },
          domains: [
            {
              domain: "staging.shop.example.com",
              port: 8080,
            },
          ],
          env: {
            BANNER: "staging", // value.literal banner
            LOG_LEVEL: "debug", // value.literal log
          },
        }),
      ],
    });
  }
  throw new Error(`.railway/railway.ts: the model deploys nothing to environment "${ctx.environment}" (it deploys to: production, staging)`);
});
Evidence: Generated deploy/unexpressed.md for @image deployment with @Branch, @checkSuites and port without domain
<!-- @generated by @metaobjectsdev/pack-railway (railway-unexpressed) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -->

# What `.railway/railway.ts` does not hold: Railway project `game`

Facts the model declares that Railway's Infrastructure as Code file cannot carry, or that this
file leaves to something else, each with how it is carried instead. Generated from the model:
change the model, not this file.

## game in production

From deployment.railway `acme::game::server-production`.

| Fact | How it is carried |
|---|---|
| resource.database `db` (postgres 18) | Not declared, so the partial neither creates nor deletes it. It must exist in the Railway project under the name `db`, which every reference to it uses. |
| resource.cache `cache` (redis) | Not declared, so the partial neither creates nor deletes it. It must exist in the Railway project under the name `cache`, which every reference to it uses. |
| Branch `main` (deployment.railway @branch) | The service's source is the image `ghcr.io/acme/game:1`, which has no branch to deploy from. The file leaves the branch out. |
| Check suites `false` (deployment.railway @checkSuites) | The service's source is the image `ghcr.io/acme/game:1`, which has no check suites to wait for. The file leaves the setting out. |
| Port `8080` (runtime.process @port) | The file carries a port only beside a domain, and this deployment has none. Railway takes the port from the service's PORT variable (or a domain's target port): set PORT=8080 on the service in Railway. References from other services to this port use the model's value. |
| Secret values: `LLM_API_KEY` | Never in the file. deploy/sync-secrets.sh production copies them from the vault scope `acme-game/prod`; deploy/doctor.sh checks the names are in the vault and on Railway. |
| Non-secret settings: `DATABASE_URL`, `REDIS_URL`, `LLM_MODEL` | The file leaves variables unmanaged, so these keep the value set on Railway (or the application's default). Declare a value.* node on the deployment to have the file manage variables. |
Evidence: Generated deploy/sync-secrets.sh used in live run
#!/usr/bin/env bash
# @generated by @metaobjectsdev/pack-railway (railway-sync-secrets) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.
# Copies every secret setting the model declares from the vault to Railway project game,
# for one environment. A value goes from keys-axi's environment through a pipe into
# `railway variable set --stdin`: it is never printed and never on a command line. It sets
# with --skip-deploys, so the next deploy picks the values up.
#
# Needs: keys-axi (an identity that may read the vault scope) and railway (logged in, run
# from the linked repository).
#
#   bash deploy/sync-secrets.sh <environment> [--dry-run]
set -euo pipefail
cd "$(dirname "$0")/.."

ENVIRONMENT="${1:-}"
DRY_RUN=0
for arg in "${@:2}"; do
  case "$arg" in
    --dry-run) DRY_RUN=1 ;;
    *) echo 'usage: bash deploy/sync-secrets.sh <environment> [--dry-run]' >&2; exit 2 ;;
  esac
done

# copy <vault project> <vault environment> <railway service> <railway environment> <NAME>
copy() {
  if [ "$DRY_RUN" = 1 ]; then echo "would copy $5 from $1/$2 to service $3 ($4)"; return; fi
  # shellcheck disable=SC2016 # the inner shell expands it: the value never enters this one
  keys-axi run --project "$1" --env "$2" --only "$5" -- bash -c '
    [ -n "${!1+set}" ] || { echo "sync-secrets: $1 is not in the vault scope" >&2; exit 1; }
    printf %s "${!1}" | railway variable set "$1" --stdin --service "$2" --environment "$3" --skip-deploys >/dev/null
  ' sync-secret "$5" "$3" "$4"
  echo "copied $5 to service $3 ($4)"
}

case "$ENVIRONMENT" in
  production)
    copy acme-game prod game production LLM_API_KEY
    ;;
  *) echo 'usage: bash deploy/sync-secrets.sh <environment> [--dry-run] (environments: production)' >&2; exit 2 ;;
esac
Evidence: sync-secrets live run transcript: dry run, real run, vault-scope-missing failure
== success path (dry run, then real)
would copy LLM_API_KEY from acme-game/prod to service game (production)
exit=0
copied LLM_API_KEY to service game (production)
exit=0
== railway argv log:
keys-axi run --project acme-game --env prod --only LLM_API_KEY -- bash -c 
    [ -n "${!1+set}" ] || { echo "sync-secrets: $1 is not in the vault scope" >&2; exit 1; }
    printf %s "${!1}" | railway variable set "$1" --stdin --service "$2" --environment "$3" --skip-deploys >/dev/null
   sync-secret LLM_API_KEY game production
railway variable set LLM_API_KEY --stdin --service game --environment production --skip-deploys
== stdin piped to railway:
synthetic-secret-value-123
== secret value in argv log count: 0
== vault scope missing:
sync-secrets: LLM_API_KEY is not in the vault scope
exit=1
railway invoked: 0
0
Evidence: Stub railway argv log from sync-secrets run (secret never in argv)
keys-axi run --project acme-game --env prod --only LLM_API_KEY -- bash -c 
    [ -n "${!1+set}" ] || { echo "sync-secrets: $1 is not in the vault scope" >&2; exit 1; }
    printf %s "${!1}" | railway variable set "$1" --stdin --service "$2" --environment "$3" --skip-deploys >/dev/null
   sync-secret LLM_API_KEY game production

Pipeline

Updates from git push no-mistakes

✅ **Intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 2 issues found → auto-fixed ✅
  • ⚠️ packs/railway/typescript/src/files.ts:28 - Declared facts are neither emitted nor listed in deploy/unexpressed.md, against the intent "unexpressible facts are listed rather than dropped". (1) @branch and @checkSuites on a deployment with @image: sourceCall emits image(...) and silently ignores both. (2) A runtime.process @port on a deployment with no @domains: the port only reaches the file inside the { domain, port } entries, and unexpressedFacts has no row for it, although other services' reference templates use that port. Fix: add rows to unexpressedFacts for these cases (or reject @branch/@checkSuites together with @image in readDeployment), then regenerate the goldens with UPDATE_GOLDEN=1.
  • ℹ️ packs/railway/typescript/test/coverage.test.ts:1 - The type-check improvement claimed in the intent (the generated file type-checks against the railway 3.17.0 SDK) is not pinned by any test in the repo. railway is not a dependency of the pack, and the golden .railway/railway.ts files sit under a dot-directory that the tsconfig test/**/* include does not match. coverage.test.ts mocks railway/iac, so it checks declared facts, not SDK types. A regression to a widened restartPolicyType string or an inline variables literal would pass the suite.

🔧 Fix applied.
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 7 of 8 scenarios driven live against the product
Scenario Result Live Evidence
Generate .railway/railway.ts from the environments model: one abstract base, production and staging each render their own branch, domains, replicas and values; staging overrides the base value; no ser… ✅ pass live generated-railway-environments.ts (real runGen, disposable project, identical to golden)
Abstract deployment with @Environment plus a concrete child loads clean ✅ pass live loadModels over fixture abstract-deployment-with-environment: no error thrown by the real strict MetaDataLoader
Adversarial: two concrete deployments for the same app and environment are still rejected ✅ pass live loadModels over fixture error-duplicate-deployment threw ERR_DELIVERY_DUPLICATE_DEPLOYMENT
Adversarial: facts that Railway IaC cannot hold are listed, not dropped (@Branch and @checkSuites with @image; port with no domain) ✅ pass live generated-unexpressed-one-service-with-image.md lists branch main, check suites false, and port 8080 rows
Secret sync: declared secret reaches Railway through stdin, never on a command line, and --dry-run writes nothing ✅ pass live sync-secrets-run.log and sync-secrets-railway-calls.log: argv contains no secret occurrence, stdin carried the value; dry-run line printed
Adversarial: secret missing from the vault scope fails the sync and Railway is never called ✅ pass live sync-secrets-run.log: 'sync-secrets: LLM_API_KEY is not in the vault scope', exit=1, railway invoked: 0
Generated railway.ts type-checks against the railway 3.17.0 SDK types ✅ pass live tsc --noEmit strict nodenext over generated .railway/railway.ts with railway@3.17.0 installed in a scratch prefix: exit 0
deploy.sh and doctor.sh run against a real Railway project and vault ⏸️ untested no Tried: no Railway account, railway CLI login or keys-axi vault identity in this environment, and no network-side platform was in scope. To drive it, provide a Railway test project with a linked repo a…
  • scripts/ci-local.sh --affected --strict-toolchains
  • Live: real codegen runGen with railwayFiles() over fixture railway-emit-environments (input from packs/railway/fixtures/conformance) into a disposable project; output byte-identical to test/golden/railway-emit-environments (diff empty)
  • Live: loadModels (real MetaDataLoader, strict) over fixture abstract-deployment-with-environment: loads without error
  • Live: loadModels over fixture error-duplicate-deployment: rejected with ERR_DELIVERY_DUPLICATE_DEPLOYMENT
  • Live: runGen over a one-service fixture modified to carry @image on the deployment with @branch and @checkSuites, and a runtime.process @port with no @domains; deploy/unexpressed.md lists branch, check suites and port rows
  • Live: generated deploy/sync-secrets.sh run with fake keys-axi and railway stubs on PATH: --dry-run prints plan; real run pipes the synthetic secret to railway variable set --stdin, argv log holds zero secret occurrences
  • Live: generated sync-secrets.sh with keys-axi stub that leaves the secret unset: exits 1 with 'not in the vault scope' and railway is never invoked
  • Live: tsc --noEmit (strict, nodenext) over the generated .railway/railway.ts against railway@3.17.0 installed into a scratch prefix: exit 0
  • Not run: deploy/deploy.sh and deploy/doctor.sh against Railway and the vault (no Railway account or keys-axi identity in this environment)
  • Not run: broad regression; configured scripts/ci-local.sh --affected --strict-toolchains already passed at target commit and no source or test files changed in this turn
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

…ploy and doctor scripts

The railway pack now generates Railway's Infrastructure as Code file
(.railway/railway.ts, the railway/iac DSL of the railway npm package
3.17.0, as a named partial) from deployment.railway and the app it
places, plus deploy/unexpressed.md (the facts the file cannot hold),
deploy/sync-secrets.sh (declared secrets copied from the vault scope to
Railway through keys-axi and railway variable set --stdin, never printed
or on a command line), deploy/deploy.sh, deploy/doctor.sh and a deploy
skill. The generators write files only; the library talks to no
platform.

Vocabulary: deployment.railway gains @repo, @image and @checkSuites
(a plan with no source disconnects a service); the delivery pack gains
@watchInclude on build.* and @path on value.ref. The railway pack now
requires the config pack for settings and vaults.

Two new conformance fixtures (one service, unmanaged variables; two
services from one monorepo, managed variables with references) carry
golden output tests, and model checks refuse what Railway cannot do.
TypeScript only. No core vocabulary or version change.
…ers and output check

- The generated .railway/railway.ts type-checks against the railway SDK: the unmanaged
  variables policy is spread from a constant, which the excess-property check skips.
- Each service names the app and deployment it comes from.
- A coverage test holds the generated file to every fact of the hand-written configuration
  the emit fixtures are modelled on, fact by fact, instead of byte identity.
- A managed file declares every setting even for a deployment with no values; a reference
  resolves only within its Railway project; a settings problem is reported alone.
- delivery: readBuild/readProcesses readers, and ERR_DELIVERY_UNSUPPORTED_OUTPUT at load for a
  value.ref asking for an output its producer lacks (railway fixture
  error-value-ref-unsupported-output).
- Scripts: unknown flags refused, deploy --yes quoted safely, doctor's cd guarded, shellcheck
  clean at every level.
@dmealing
dmealing merged commit d5fd8ac into main Nov 25, 2026
11 checks passed
@dmealing
dmealing deleted the fm/mo-enterprise-packs-railway branch November 25, 2026 10:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant