From 2f7799714dcfe96e241825aa79e53ebaa5379733 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:08:40 +0100 Subject: [PATCH 01/17] Test: an environment file may list no name under PLEXUS_ Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.test.ts | 7 +++++++ packages/lib/src/stacks.test.ts | 10 ++++++++++ 2 files changed, 17 insertions(+) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 097a4547..b3dc6e22 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -2684,6 +2684,13 @@ test('PLX-Stack/SinglePort: with environment files a stack that binds two port m assert.equal(found.length, 1); }); +test('a name under the reserved prefix is one finding of its file, and not also reported as missing from the other files', async () => { + const found = await environmentFindings( + environmentFiles({ 'staging.yaml': STAGING.replace('env:\n', 'env:\n PLEXUS_OWN: x\n') }), + ); + assert.deepEqual(found, ['staging.yaml: `PLEXUS_OWN` is under the reserved prefix `PLEXUS_`; remove it']); +}); + test('a name the platform supplies, or listed under both maps, is not also reported as missing from the other files', async () => { const platform = await environmentFindings( environmentFiles({ 'staging.yaml': STAGING.replace('env:\n', 'env:\n PLEXUS_TAG: x\n') }), diff --git a/packages/lib/src/stacks.test.ts b/packages/lib/src/stacks.test.ts index 5fba8bbd..4a42cfe3 100644 --- a/packages/lib/src/stacks.test.ts +++ b/packages/lib/src/stacks.test.ts @@ -501,6 +501,16 @@ test('an environment file that cannot be used says why in its own problems, one 'host: 192.0.2.1\nenv:\n PLEXUS_LOOPBACK_PORT: x\n', /`PLEXUS_LOOPBACK_PORT` is supplied by the platform/, ], + [ + 'staging', + 'host: 192.0.2.1\nenv:\n PLEXUS_OWN: x\n', + /`PLEXUS_OWN` is under the reserved prefix `PLEXUS_`; remove it/, + ], + [ + 'staging', + 'host: 192.0.2.1\nsecrets:\n PLEXUS_OWN: op://a/b/c\n', + /`PLEXUS_OWN` is under the reserved prefix `PLEXUS_`; remove it/, + ], ['Staging', 'host: 192.0.2.1\n', /one lowercase word/], ['pre-prod', 'host: 192.0.2.1\n', /one lowercase word/], ['stage2', 'host: 192.0.2.1\n', /one lowercase word/], From ec56c95f4e3a98d234d8cbe429e68ad0c98e9591 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:10:02 +0100 Subject: [PATCH 02/17] An environment file may list no name under PLEXUS_, under env or secrets Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.ts | 11 ++++------- packages/lib/src/environments.ts | 14 ++++++++++++-- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index cac85802..8041511a 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -107,7 +107,7 @@ import { } from './compose.ts'; import { filesWithConflictMarkers } from './conflicts.ts'; import type { Context } from './context.ts'; -import { type Environment, PLATFORM_VARIABLES, requiredVariables } from './environments.ts'; +import { type Environment, isReservedName, PLATFORM_VARIABLES, requiredVariables } from './environments.ts'; import { ExecError } from './io.ts'; import { REQUIREMENT_NAME } from './lints.ts'; import { type Declaration, MARKER_FILE, parseMarker, reasonGiven } from './marker.ts'; @@ -557,22 +557,19 @@ const readEnvironments = (stack: StackFacts): Environment[] => stack.environment /** * PLX-Stack/EnvironmentParity: the files list the same names under `env` and * under `secrets`, one line for each name an environment lacks, naming the - * first that has it. A name the platform supplies, or one listed under both + * first that has it. A name the platform supplies or under the reserved prefix, or one listed under both * maps, has its finding in EnvironmentFile already. */ function environmentParity(stack: StackFacts): string[] { const read = readEnvironments(stack); - const doubled = new Set([ - ...PLATFORM_VARIABLES, - ...read.flatMap((e) => listed(e, 'env').filter((n) => listed(e, 'secrets').includes(n))), - ]); + const doubled = new Set(read.flatMap((e) => listed(e, 'env').filter((n) => listed(e, 'secrets').includes(n)))); const problems: string[] = []; for (const key of ['env', 'secrets'] as const) { const of = read.filter((e) => !e.invalid.includes(key)); for (const name of new Set(of.flatMap((e) => listed(e, key)))) { const holder = of.find((e) => listed(e, key).includes(name)); for (const e of of) - if (holder && !doubled.has(name) && !listed(e, key).includes(name)) + if (holder && !isReservedName(name) && !doubled.has(name) && !listed(e, key).includes(name)) problems.push(`${e.name}.yaml lists no \`${name}\` under \`${key}\`, which ${holder.name}.yaml does`); } } diff --git a/packages/lib/src/environments.ts b/packages/lib/src/environments.ts index 85dc613b..f1a3eec7 100644 --- a/packages/lib/src/environments.ts +++ b/packages/lib/src/environments.ts @@ -34,8 +34,9 @@ // with another YAML parser, and only a string reads the same in both // secrets a map of names to `op://` pointers, strings; absent reads as empty; // a string that is no pointer is returned and is a problem -// No name stands in both maps, and none is one `PLATFORM_VARIABLES` lists: the -// platform supplies those, so no file does. +// No name stands in both maps, none is one `PLATFORM_VARIABLES` lists (the +// platform supplies those, so no file does), and none is under `RESERVED_PREFIX`, +// which belongs to the platform, the deployer and the pipeline. // `readEnvironments` returns one `Environment` per file in the order of their // names, and never throws: whatever makes a file unusable is a line of its // `problems` that names the file, one line per bad value, and the values it @@ -67,6 +68,13 @@ export const PLATFORM_VARIABLES: readonly string[] = [ 'PLEXUS_COMMIT_SHA', ]; +/** The prefix of the names the platform, the deployer and the pipeline bind: no environment file lists a name under it. */ +export const RESERVED_PREFIX = 'PLEXUS_'; + +/** Whether an environment file may not list the name: one the platform supplies, or one under `RESERVED_PREFIX`. */ +export const isReservedName = (name: string): boolean => + PLATFORM_VARIABLES.includes(name) || name.startsWith(RESERVED_PREFIX); + /** An SSH destination, parsed. */ export interface SshTarget { address: string; @@ -228,6 +236,8 @@ async function readEnvironment(ctx: Context, dir: string, label: string): Promis if (listed('env').includes(variable) && listed('secrets').includes(variable)) problem(`\`${variable}\` is listed under both \`env\` and \`secrets\``); else if (PLATFORM_VARIABLES.includes(variable)) problem(`\`${variable}\` is supplied by the platform; remove it`); + else if (isReservedName(variable)) + problem(`\`${variable}\` is under the reserved prefix \`${RESERVED_PREFIX}\`; remove it`); } return environment; } From 965673db300166c6e40a21aea4bbed6636d41f2e Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:10:40 +0100 Subject: [PATCH 03/17] Test: the declaration of environments in the root marker, its validation and its branches Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/declaredEnvironments.test.ts | 157 ++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 packages/lib/src/declaredEnvironments.test.ts diff --git a/packages/lib/src/declaredEnvironments.test.ts b/packages/lib/src/declaredEnvironments.test.ts new file mode 100644 index 00000000..21da3048 --- /dev/null +++ b/packages/lib/src/declaredEnvironments.test.ts @@ -0,0 +1,157 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { Context } from './context.ts'; +import { + declareEnvironments, + describeBranches, + environmentBranch, + environmentOfBranch, + readDeclaredEnvironments, +} from './declaredEnvironments.ts'; +import { fakeIo, type Tree } from './testing/fakeIo.ts'; + +const TWO = { + staging: { promotes_from: 'main', auto_promote: true }, + production: { promotes_from: 'staging' }, +}; + +/** The declaration read from the root marker of an in-memory repo at /work/shop. */ +const read = (marker: string | null) => + readDeclaredEnvironments( + new Context({}, fakeIo({ work: { shop: (marker === null ? {} : { 'PLEXUS.md': marker }) as Tree } })), + '/work/shop', + ); + +test('a valid declaration is returned in the order written, each with its branch, its source branch and auto_promote false by default', () => { + const { environments, problems } = declareEnvironments(TWO); + assert.deepEqual(problems, []); + assert.deepEqual(environments, [ + { name: 'staging', promotesFrom: 'main', autoPromote: true, branch: 'env/staging', source: 'main' }, + { + name: 'production', + promotesFrom: 'staging', + autoPromote: false, + branch: 'env/production', + source: 'env/staging', + }, + ]); +}); + +test('an absent, empty or null declaration declares nothing and is no problem', () => { + for (const value of [undefined, null, {}]) + assert.deepEqual(declareEnvironments(value), { environments: [], problems: [] }); +}); + +test('a name that is no lowercase word, and main, are refused', () => { + for (const name of ['Prod', 'pre-prod', 'stage2', 'a.b', '']) { + const { problems } = declareEnvironments({ [name]: { promotes_from: 'main' } }); + assert.equal(problems.length, 1, name); + assert.match(problems[0] ?? '', /is no environment name; a name is one lowercase word/, name); + } + const { problems } = declareEnvironments({ main: { promotes_from: 'main' } }); + assert.deepEqual(problems, ['`main` is no environment name: it is the branch environments promote from']); +}); + +test('promotes_from is required and names main or a declared environment', () => { + assert.deepEqual(declareEnvironments({ staging: {} }).problems, ['`staging` has no `promotes_from`']); + assert.deepEqual(declareEnvironments({ staging: null }).problems, ['`staging` has no `promotes_from`']); + assert.deepEqual(declareEnvironments({ staging: { promotes_from: 3 } }).problems, [ + '`staging`: `promotes_from` is not a string', + ]); + assert.deepEqual(declareEnvironments({ staging: { promotes_from: 'develop' } }).problems, [ + '`staging`: `promotes_from` names `develop`, which is neither `main` nor a declared environment', + ]); + assert.deepEqual(declareEnvironments({ staging: 'main' }).problems, [ + '`staging` is not a map of `promotes_from` and `auto_promote`', + ]); +}); + +test('auto_promote is a boolean', () => { + for (const value of ['yes', 1, null, []]) + assert.deepEqual(declareEnvironments({ staging: { promotes_from: 'main', auto_promote: value } }).problems, [ + '`staging`: `auto_promote` is not a boolean', + ]); + assert.equal( + declareEnvironments({ staging: { promotes_from: 'main', auto_promote: false } }).environments[0]?.autoPromote, + false, + ); +}); + +test('a key but promotes_from and auto_promote is refused by name', () => { + assert.deepEqual(declareEnvironments({ staging: { promotes_from: 'main', host: 'x' } }).problems, [ + '`staging`: unknown key `host`; the keys are `promotes_from` and `auto_promote`', + ]); +}); + +test('a cycle of sources is refused, once, naming its members, and so is an environment that promotes from itself', () => { + const cycle = declareEnvironments({ + a: { promotes_from: 'c' }, + b: { promotes_from: 'a' }, + c: { promotes_from: 'b' }, + d: { promotes_from: 'main' }, + }); + assert.deepEqual(cycle.problems, ['the environments `a`, `c`, `b` promote from one another in a cycle']); + assert.deepEqual(declareEnvironments({ a: { promotes_from: 'a' } }).problems, [ + 'the environment `a` promotes from itself', + ]); +}); + +test('every problem of a declaration is found in one run, and an invalid one still returns what could be read', () => { + const { environments, problems } = declareEnvironments({ + Bad: { promotes_from: 'main' }, + staging: { promotes_from: 'main', auto_promote: 'x' }, + }); + assert.equal(problems.length, 2); + assert.deepEqual( + environments.map((e) => e.name), + ['staging'], + ); +}); + +test('a declaration that is no map is refused', () => { + for (const value of ['staging', ['staging'], 3]) + assert.deepEqual(declareEnvironments(value).problems, [ + '`environments` is not a map of environment names to their `promotes_from` and `auto_promote`', + ]); +}); + +test('the declaration is read from the root marker of a repo, nested value and all', async () => { + const marker = `---\nrepo: shop\nenvironments:\n staging:\n promotes_from: main\n auto_promote: true\n production:\n promotes_from: staging\n---\n\nA repo.\n`; + const { environments, problems } = await read(marker); + assert.deepEqual(problems, []); + assert.deepEqual( + environments.map((e) => [e.name, e.promotesFrom, e.autoPromote]), + [ + ['staging', 'main', true], + ['production', 'staging', false], + ], + ); +}); + +test('a repo with no marker, or a marker with no environments, declares nothing', async () => { + assert.deepEqual(await read(null), { environments: [], problems: [] }); + assert.deepEqual(await read('---\nrepo: shop\n---\n'), { environments: [], problems: [] }); +}); + +test('a marker that cannot be read gives one problem that names the file', async () => { + const { environments, problems } = await read('---\nenvironments: [\n---\n'); + assert.deepEqual(environments, []); + assert.equal(problems.length, 1); + assert.match(problems[0] ?? '', /^PLEXUS\.md: /); +}); + +test('the branch of an environment is env/, and the environment of a branch is found among the declared ones only', () => { + const { environments } = declareEnvironments(TWO); + assert.equal(environmentBranch('anything'), 'env/anything'); + assert.equal(environmentOfBranch(environments, 'env/staging'), 'staging'); + assert.equal(environmentOfBranch(environments, 'env/production'), 'production'); + for (const ref of ['main', 'staging', 'env/preview', 'env/', 'feature/env/staging', 'constructor', '__proto__']) + assert.equal(environmentOfBranch(environments, ref), undefined, ref); + assert.equal(environmentOfBranch([], 'env/staging'), undefined); +}); + +test('the branches that deploy are listed for a refusal, and a repo that declares none says so', () => { + const { environments } = declareEnvironments(TWO); + assert.equal(describeBranches(environments, 'or'), 'env/staging or env/production'); + assert.match(describeBranches([], 'or'), /declares no environments/); +}); From 1cbdd86ceb07512a4b2040c48a7b2af0ac206817 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:11:25 +0100 Subject: [PATCH 04/17] One function reads the declared environments and says each one's branch Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/declaredEnvironments.ts | 178 +++++++++++++++++++++++ packages/lib/src/environments.ts | 10 +- packages/lib/src/index.ts | 11 ++ 3 files changed, 197 insertions(+), 2 deletions(-) create mode 100644 packages/lib/src/declaredEnvironments.ts diff --git a/packages/lib/src/declaredEnvironments.ts b/packages/lib/src/declaredEnvironments.ts new file mode 100644 index 00000000..7733b147 --- /dev/null +++ b/packages/lib/src/declaredEnvironments.ts @@ -0,0 +1,178 @@ +// The environments a repo declares: the one place that reads them, validates +// them, and says which branch each deploys from. A tool that needs the +// declaration calls `readDeclaredEnvironments` (or `declareEnvironments` on a +// value it has read itself) and never looks at the marker's `environments` +// itself; no code outside this file spells a branch `env/`. +// +// The declaration is the answer `environments` of the repo's root marker +// (§ 1.4 PLX, § 3 PLX-Delivery), a map keyed by the environment's name: +// : +// promotes_from required: `main`, or the name of another declared +// environment; a cycle of sources is refused +// auto_promote optional boolean, false where left out +// A name is one lowercase word by the rule environment files follow +// (environments.ts, `environmentNameProblem`), and `main` is none. No other +// key is allowed. No name has a meaning: the declaration is the one place +// that orders the environments, and the branch of an environment is +// `env/` for every name (`environmentBranch`), found again from the +// branch by `environmentOfBranch`; a branch of a name the repo does not +// declare belongs to no environment. +// +// `declareEnvironments` never throws: whatever makes the declaration invalid +// is a line of `problems`, one per fault, every one found in one run, and the +// environments that could be read are returned all the same, so that `plx +// doctor` reports everything and a verb that deploys refuses any problem. +// `readDeclaredEnvironments` reads the root marker's frontmatter; a repo +// without a marker, or a marker without `environments` (or with an empty one), +// declares nothing, and a marker that cannot be read is one problem. +import { join } from 'node:path'; +import { isMapping } from './compose.ts'; +import type { Context } from './context.ts'; +import { environmentNameProblem } from './environments.ts'; +import { MARKER_FILE, splitFrontmatter } from './marker.ts'; + +/** The branch every change lands on, and the source of the environments that promote first. */ +export const DEFAULT_BRANCH = 'main'; + +/** The answer of a root marker that holds the declaration. */ +export const ENVIRONMENTS_KEY = 'environments'; + +/** One declared environment. */ +export interface DeclaredEnvironment { + name: string; + /** `main` or another declared environment's name. */ + promotesFrom: string; + autoPromote: boolean; + /** Its branch, `env/`. */ + branch: string; + /** The branch it promotes from: `main`, or the branch of the environment it promotes from. */ + source: string; +} + +/** The declaration as far as it could be read, and what makes it invalid. */ +export interface DeclaredEnvironments { + /** In the order written. */ + environments: DeclaredEnvironment[]; + /** One line per fault; empty when the declaration is valid. */ + problems: string[]; +} + +const KEYS = ['promotes_from', 'auto_promote']; +const code = (text: string) => `\`${text}\``; + +/** The branch of an environment. */ +export const environmentBranch = (name: string): string => `env/${name}`; + +/** The environment a branch deploys, or undefined where the branch is none's. */ +export const environmentOfBranch = (environments: readonly DeclaredEnvironment[], ref: string): string | undefined => + environments.find((e) => e.branch === ref)?.name; + +/** The branches of the declaration for a refusal, joined by `joiner`; a line that says so where there are none. */ +export const describeBranches = (environments: readonly DeclaredEnvironment[], joiner: 'and' | 'or'): string => + environments.length > 0 + ? environments.map((e) => e.branch).join(` ${joiner} `) + : 'no branch, since the repo declares no environments'; + +/** The declaration from the value of `environments`: undefined, null and an empty map declare nothing. */ +export function declareEnvironments(value: unknown): DeclaredEnvironments { + if (value === undefined || value === null) return { environments: [], problems: [] }; + if (!isMapping(value)) + return { + environments: [], + problems: [ + `${code(ENVIRONMENTS_KEY)} is not a map of environment names to their \`promotes_from\` and \`auto_promote\``, + ], + }; + const problems: string[] = []; + const read: { name: string; promotesFrom?: string; autoPromote: boolean }[] = []; + for (const [name, entry] of Object.entries(value)) { + const nameProblem = + name === DEFAULT_BRANCH + ? `${code(name)} is no environment name: it is the branch environments promote from` + : environmentNameProblem(name); + if (nameProblem) { + problems.push(nameProblem); + continue; + } + if (entry === null || entry === undefined) { + problems.push(`${code(name)} has no \`promotes_from\``); + continue; + } + if (!isMapping(entry)) { + problems.push(`${code(name)} is not a map of \`promotes_from\` and \`auto_promote\``); + continue; + } + for (const key of Object.keys(entry).filter((k) => !KEYS.includes(k))) + problems.push(`${code(name)}: unknown key ${code(key)}; the keys are \`promotes_from\` and \`auto_promote\``); + const from = entry.promotes_from; + if (from === undefined || from === null) problems.push(`${code(name)} has no \`promotes_from\``); + else if (typeof from !== 'string') problems.push(`${code(name)}: \`promotes_from\` is not a string`); + const auto = entry.auto_promote === undefined ? false : entry.auto_promote; + if (typeof auto !== 'boolean') problems.push(`${code(name)}: \`auto_promote\` is not a boolean`); + read.push({ name, ...(typeof from === 'string' ? { promotesFrom: from } : {}), autoPromote: auto === true }); + } + const declared = new Set(read.map((e) => e.name)); + for (const e of read) + if (e.promotesFrom !== undefined && e.promotesFrom !== DEFAULT_BRANCH && !declared.has(e.promotesFrom)) + problems.push( + `${code(e.name)}: \`promotes_from\` names ${code(e.promotesFrom)}, which is neither \`${DEFAULT_BRANCH}\` nor a declared environment`, + ); + problems.push(...cycles(read)); + const environments = read.flatMap((e): DeclaredEnvironment[] => + e.promotesFrom === undefined + ? [] + : [ + { + name: e.name, + promotesFrom: e.promotesFrom, + autoPromote: e.autoPromote, + branch: environmentBranch(e.name), + source: e.promotesFrom === DEFAULT_BRANCH ? DEFAULT_BRANCH : environmentBranch(e.promotesFrom), + }, + ], + ); + return { environments, problems }; +} + +/** One line for each cycle of sources, its members in the order the walk from the first declared of them meets them. */ +function cycles(read: { name: string; promotesFrom?: string }[]): string[] { + const from = new Map(read.map((e) => [e.name, e.promotesFrom])); + const seen = new Set(); + const lines: string[] = []; + for (const { name } of read) { + const path: string[] = []; + let at: string | undefined = name; + while (at !== undefined && !path.includes(at) && !seen.has(at)) { + path.push(at); + at = from.get(at); + } + for (const visited of path) seen.add(visited); + const start = at === undefined ? -1 : path.indexOf(at); + if (start < 0) continue; + const members = path.slice(start); + lines.push( + members.length === 1 + ? `the environment ${code(members[0] ?? '')} promotes from itself` + : `the environments ${members.map(code).join(', ')} promote from one another in a cycle`, + ); + } + return lines; +} + +/** The declaration of the repo at `dir`, from its root marker. */ +export async function readDeclaredEnvironments(ctx: Context, dir: string): Promise { + let text: string; + try { + text = await ctx.readFile(join(dir, MARKER_FILE)); + } catch { + return { environments: [], problems: [] }; + } + try { + return declareEnvironments(splitFrontmatter(text).data[ENVIRONMENTS_KEY]); + } catch (error) { + return { + environments: [], + problems: [`${MARKER_FILE}: ${error instanceof Error ? error.message : String(error)}`], + }; + } +} diff --git a/packages/lib/src/environments.ts b/packages/lib/src/environments.ts index f1a3eec7..44d24be2 100644 --- a/packages/lib/src/environments.ts +++ b/packages/lib/src/environments.ts @@ -153,6 +153,12 @@ export interface Environment { /** What an environment's name is: one lowercase word. */ const ENVIRONMENT_NAME = /^[a-z]+$/; +/** Why a name is no environment's, or undefined: the one rule of the files' names and of the declaration's. */ +export const environmentNameProblem = (name: string): string | undefined => + ENVIRONMENT_NAME.test(name) + ? undefined + : `\`${name}\` is no environment name; a name is one lowercase word (letters only, no \`-\`)`; + const KEYS = ['host', 'hostname', 'env', 'secrets']; /** The environments in the files `names` (`.yaml`) of the directory `dir`, by name. */ @@ -175,8 +181,8 @@ async function readEnvironment(ctx: Context, dir: string, label: string): Promis problems: [], }; const problem = (text: string) => environment.problems.push(`${label}: ${text}`); - if (!ENVIRONMENT_NAME.test(name)) - problem(`\`${name}\` is no environment name; a name is one lowercase word (letters only, no \`-\`)`); + const named = environmentNameProblem(name); + if (named) problem(named); const unread = (text: string): Environment => { problem(text); environment.unread = true; diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index 9c755896..ba8ab7ef 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -33,6 +33,17 @@ export { type Compose, declaresHealthcheck, type Mapping, parseCompose } from '. export { filesWithConflictMarkers, hasConflictMarkers, hasUnmergedEntries } from './conflicts.ts'; export { type Consumer, expectedBranch, findRepos } from './consumers.ts'; export { Context, type Options } from './context.ts'; +export { + DEFAULT_BRANCH, + type DeclaredEnvironment, + type DeclaredEnvironments, + declareEnvironments, + describeBranches, + ENVIRONMENTS_KEY, + environmentBranch, + environmentOfBranch, + readDeclaredEnvironments, +} from './declaredEnvironments.ts'; export { type DeployOptions, type DeployOutcome, From 3ace953d1063ad2b9c3089067b6fa5bb6b85e78c Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:14:49 +0100 Subject: [PATCH 05/17] Test: the environment of a branch follows the declaration, and a repo that declares none deploys from no branch Co-Authored-By: Claude Sonnet 5.5 --- packages/cli-ci/src/commands/setup.test.ts | 80 ++++++++++++++++--- .../src/commands/setupWithoutToken.test.ts | 8 +- packages/cli/src/commands/deploy.test.ts | 28 ++++++- packages/lib/src/deployTargets.test.ts | 37 ++++++--- 4 files changed, 126 insertions(+), 27 deletions(-) diff --git a/packages/cli-ci/src/commands/setup.test.ts b/packages/cli-ci/src/commands/setup.test.ts index b73ae5e1..09ea822a 100644 --- a/packages/cli-ci/src/commands/setup.test.ts +++ b/packages/cli-ci/src/commands/setup.test.ts @@ -530,29 +530,49 @@ const RUN = (workflow: string, ref: string, event = 'workflow_dispatch', type = GITHUB_REF_TYPE: type, }); +/** The root marker of a repo that declares two environments, so that the branches env/staging and env/production deploy. */ +const DECLARES = `--- +environments: + staging: + promotes_from: main + auto_promote: true + production: + promotes_from: staging +--- +`; + for (const job of ['repo', 'deploy'] as const) { test(`${job}: a run of on_push on a branch that deploys nowhere fails in one line naming the branch and the branches that deploy, before anything is read`, () => { - const run = runJob([job], { env: { ...CONNECT, ...RUN('on_push', 'feature-x') }, vault: VAULT }); + const run = runJob([job], { + env: { ...CONNECT, ...RUN('on_push', 'feature-x') }, + vault: VAULT, + marker: DECLARES, + }); assert.equal(run.status, 1, run.log); assert.deepEqual(run.calls, []); - assert.match(run.log, /on_push.*feature-x.*main.*develop/); + assert.match(run.log, /on_push.*feature-x.*env\/staging and env\/production/); assert.equal(run.log.trim().split('\n').length, 1, run.log); assert.deepEqual([run.output, run.env], [{}, {}]); }); } test('a branch named like a property of every object deploys nowhere either', () => { - const run = runJob(['repo'], { env: { ...CONNECT, ...RUN('on_push', 'constructor') }, vault: VAULT }); + const run = runJob(['repo'], { + env: { ...CONNECT, ...RUN('on_push', 'constructor') }, + vault: VAULT, + marker: DECLARES, + }); assert.equal(run.status, 1, run.log); assert.deepEqual(run.calls, []); assert.match(run.log, /on_push on constructor deploys nowhere/); }); -for (const tag of ['v1', 'main']) { +for (const tag of ['v1', 'env/staging']) { test(`a run of on_push on the tag ${tag} is refused, and the message says tag`, () => { const run = runJob(['repo'], { env: { ...CONNECT, ...RUN('on_push', tag, 'workflow_dispatch', 'tag') }, vault: VAULT, + marker: DECLARES, }); assert.equal(run.status, 1, run.log); assert.deepEqual(run.calls, []); @@ -562,17 +582,59 @@ for (const tag of ['v1', 'main']) { } for (const [branch, event] of [ - ['main', 'push'], - ['develop', 'push'], - ['main', 'workflow_dispatch'], - ['develop', 'workflow_dispatch'], + ['env/staging', 'push'], + ['env/production', 'push'], + ['env/staging', 'workflow_dispatch'], + ['env/production', 'workflow_dispatch'], ]) { test(`a run of on_push on ${branch} by ${event} is not refused`, () => { - const run = runJob(['repo'], { env: { ...CONNECT, ...RUN('on_push', branch, event) }, vault: VAULT }); + const run = runJob(['repo'], { + env: { ...CONNECT, ...RUN('on_push', branch, event) }, + vault: VAULT, + marker: DECLARES, + }); assert.equal(run.status, 0, run.log); }); } +test('a run of on_push on main, or on an env/ branch the repo does not declare, is refused, and the line lists the branches that deploy', () => { + for (const branch of ['main', 'develop', 'env/preview']) { + const run = runJob(['repo'], { + env: { ...CONNECT, ...RUN('on_push', branch, 'push') }, + vault: VAULT, + marker: DECLARES, + }); + assert.equal(run.status, 1, `${branch}: ${run.log}`); + assert.match( + run.log, + new RegExp( + `on_push on ${branch.replace('/', '\\/')} deploys nowhere: this repo deploys from env/staging and env/production; run on_push there`, + ), + ); + } +}); + +test('a run of on_push in a repo that declares no environment is refused, and the line says so', () => { + for (const marker of [undefined, '---\nrepo: shop\n---\n']) { + const run = runJob(['repo'], { env: { ...CONNECT, ...RUN('on_push', 'main', 'push') }, vault: VAULT, marker }); + assert.equal(run.status, 1, run.log); + assert.match( + run.log, + /on_push on main deploys nowhere: this repo deploys from no branch, since the repo declares no environments; run on_push there/, + ); + } +}); + +test('a run of on_push in a repo whose declaration is invalid is refused with the reason', () => { + const run = runJob(['repo'], { + env: { ...CONNECT, ...RUN('on_push', 'env/staging', 'push') }, + vault: VAULT, + marker: '---\nenvironments:\n staging:\n promotes_from: develop\n---\n', + }); + assert.equal(run.status, 1, run.log); + assert.match(run.log, /`staging`: `promotes_from` names `develop`/); +}); + for (const [workflow, event] of [ ['on_commit', 'push'], ['on_pr', 'pull_request'], diff --git a/packages/cli-ci/src/commands/setupWithoutToken.test.ts b/packages/cli-ci/src/commands/setupWithoutToken.test.ts index 500a8b66..f7956eab 100644 --- a/packages/cli-ci/src/commands/setupWithoutToken.test.ts +++ b/packages/cli-ci/src/commands/setupWithoutToken.test.ts @@ -10,7 +10,9 @@ const FORGE_RUNNER = { RUNNER_ENVIRONMENT: 'github-hosted' }; const CACHE_HOST = { PLX_TURBO_CACHE_HOST: 'cache.acme.internal' }; const VAULT = { 'op://acme-ci/repo_web/server-actions-key': 'a-key' }; /** A pull request from a fork: a forge runner, the repo's cache host, the overlay, and no secret. */ -const ON_PUSH = { GITHUB_WORKFLOW: 'on_push', GITHUB_REF_NAME: 'main', GITHUB_EVENT_NAME: 'push' }; +const ON_PUSH = { GITHUB_WORKFLOW: 'on_push', GITHUB_REF_NAME: 'env/staging', GITHUB_EVENT_NAME: 'push' }; +/** The root marker of a repo whose branch env/staging deploys. */ +const MARKER = '---\nenvironments:\n staging:\n promotes_from: main\n---\n'; const FORK = { ...FORGE_RUNNER, ...CACHE_HOST, GITHUB_WORKFLOW: 'on_pr', GITHUB_EVENT_NAME: 'pull_request' }; /** The one line the step says about it. */ @@ -49,7 +51,7 @@ test('a repo job of the workflow on_commit or on_pr reads nothing where it has n const job = runJob(['repo'], { env: { GITHUB_WORKFLOW }, vault: VAULT }); assert.equal(job.status, 0, `${GITHUB_WORKFLOW}\n${job.log}`); } - const job = runJob(['repo'], { env: ON_PUSH, vault: VAULT }); + const job = runJob(['repo'], { env: ON_PUSH, vault: VAULT, marker: MARKER }); assert.equal(job.status, 1, job.log); assert.match(job.log, /on_push .*vault/); assert.match(job.log, /OP_SERVICE_ACCOUNT_TOKEN/); @@ -57,7 +59,7 @@ test('a repo job of the workflow on_commit or on_pr reads nothing where it has n }); test('a deploy job with no token fails, since it cannot deploy', () => { - const job = runJob(['deploy'], { env: { ...FORGE_RUNNER, ...ON_PUSH }, vault: VAULT }); + const job = runJob(['deploy'], { env: { ...FORGE_RUNNER, ...ON_PUSH }, vault: VAULT, marker: MARKER }); assert.equal(job.status, 1, job.log); assert.match(job.log, /OP_CONNECT_HOST and OP_CONNECT_TOKEN/); assert.match(job.log, /OP_SERVICE_ACCOUNT_TOKEN/); diff --git a/packages/cli/src/commands/deploy.test.ts b/packages/cli/src/commands/deploy.test.ts index db8f4baa..16872d04 100644 --- a/packages/cli/src/commands/deploy.test.ts +++ b/packages/cli/src/commands/deploy.test.ts @@ -188,7 +188,7 @@ function fixture(): Fixture { const root = mkdtempSync(join(scratch, 'case-')); const repo = join(root, 'repo'); put(repo, { - 'PLEXUS.md': '---\nrepo: shop\n---\n', + 'PLEXUS.md': '---\nrepo: shop\nenvironments:\n staging:\n promotes_from: main\n---\n', 'apps/shop/Dockerfile': 'FROM scratch\n', 'apps/admin/Dockerfile': 'FROM scratch\n', ...stack('shop', SHOP_COMPOSE), @@ -365,19 +365,41 @@ test('a repo whose stacks have zero apps deploys the same way: no image is resol assert.equal(existsSync(join(f.fake, 'docker.log')), false); }); -test('without --environment the environment follows the branch; where it follows none, the verb says so', async () => { +test('without --environment the environment follows the declared branch; where it follows none, the verb says so and names the branches', async () => { const f = fixture(); const args = ['deploy', '--inventory', f.inv, '--commit', SHA, '-C', f.repo]; await assert.rejects( plx(args, f.fake, { GITHUB_EVENT_NAME: 'pull_request', GITHUB_REF_NAME: '3/merge' }), UsageError, ); + for (const ref of ['main', 'develop', 'env/preview']) + await assert.rejects( + plx(args, f.fake, { GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: ref }), + (e: unknown) => e instanceof UsageError && e.message.includes('run on a push to env/staging'), + ref, + ); assert.deepEqual(runs(f.fake), []); - const err = await plx(args, f.fake, { GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'develop' }); + const err = await plx(args, f.fake, { GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'env/staging' }); assert.equal(runs(f.fake).length, 3); assert.equal(summary(err).length, 3); }); +test('a repo that declares no environment deploys from no branch, and a declaration that is invalid is refused with its reason', async () => { + const f = fixture(); + const args = ['deploy', '--inventory', f.inv, '--commit', SHA, '-C', f.repo]; + put(f.repo, { 'PLEXUS.md': '---\nrepo: shop\n---\n' }); + await assert.rejects( + plx(args, f.fake, { GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'env/staging' }), + (e: unknown) => e instanceof UsageError && e.message.includes('declares no environments'), + ); + put(f.repo, { 'PLEXUS.md': '---\nrepo: shop\nenvironments:\n staging:\n promotes_from: develop\n---\n' }); + await assert.rejects( + plx(args, f.fake, { GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'env/staging' }), + (e: unknown) => e instanceof UsageError && e.message.includes('`promotes_from` names `develop`'), + ); + assert.deepEqual(runs(f.fake), []); +}); + test('plx deploy needs the inventory the records are read from, and says what to pass in the same words in every repo', async () => { const f = fixture(); const refusal = (e: unknown) => diff --git a/packages/lib/src/deployTargets.test.ts b/packages/lib/src/deployTargets.test.ts index 39179494..3d2a2091 100644 --- a/packages/lib/src/deployTargets.test.ts +++ b/packages/lib/src/deployTargets.test.ts @@ -1,9 +1,9 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { Context } from './context.ts'; +import { declareEnvironments } from './declaredEnvironments.ts'; import { deployLegs, - ENVIRONMENT_BRANCHES, environmentOf, parseInventoryFile, readInventory, @@ -138,21 +138,34 @@ test('an app of the repo with a record and no target is neither a leg nor withou assert.deepEqual(untargeted, [{ app: 'pocket-id', files: ['/inv/host_vars/vm103.yml'] }]); }); -test('the environment follows the branch on a push or a run by hand, and a given one stands in', () => { - assert.equal(environmentOf('push', 'main'), 'production'); - assert.equal(environmentOf('workflow_dispatch', 'develop'), 'staging'); - assert.equal(environmentOf('push', 'feature'), ''); - assert.equal(environmentOf('pull_request', 'main'), ''); - assert.equal(environmentOf('pull_request', '12/merge', 'staging'), 'staging'); +const DECLARED = declareEnvironments({ + staging: { promotes_from: 'main', auto_promote: true }, + production: { promotes_from: 'staging' }, }); -test('the branches that deploy are the ones environmentOf maps to an environment', () => { - for (const [branch, environment] of Object.entries(ENVIRONMENT_BRANCHES)) - assert.equal(environmentOf('push', branch), environment); - assert.deepEqual(Object.keys(ENVIRONMENT_BRANCHES), ['main', 'develop']); +test('the environment follows the declared branch on a push or a run by hand, and a given one stands in', () => { + assert.equal(environmentOf(DECLARED, 'push', 'env/production'), 'production'); + assert.equal(environmentOf(DECLARED, 'workflow_dispatch', 'env/staging'), 'staging'); + assert.equal(environmentOf(DECLARED, 'push', 'main'), ''); + assert.equal(environmentOf(DECLARED, 'push', 'feature'), ''); + assert.equal(environmentOf(DECLARED, 'push', 'env/preview'), ''); + assert.equal(environmentOf(DECLARED, 'pull_request', 'env/staging'), ''); + assert.equal(environmentOf(DECLARED, 'pull_request', '12/merge', 'staging'), 'staging'); +}); + +test('a repo that declares no environment deploys from no branch', () => { + for (const ref of ['main', 'develop', 'env/staging']) + assert.equal(environmentOf(declareEnvironments(undefined), 'push', ref), '', ref); +}); + +test('a repo whose declaration is invalid deploys from no branch, even one it declares', () => { + const invalid = declareEnvironments({ staging: { promotes_from: 'develop' } }); + assert.equal(invalid.environments[0]?.branch, 'env/staging'); + assert.equal(environmentOf(invalid, 'push', 'env/staging'), ''); + assert.equal(environmentOf(invalid, 'push', 'env/staging', 'staging'), 'staging'); }); test('a branch named like a property of every object deploys nowhere', () => { for (const ref of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) - assert.equal(environmentOf('push', ref), '', ref); + assert.equal(environmentOf(DECLARED, 'push', ref), '', ref); }); From adc0190ee5b0ef2125f93c6803eda0684e8856ed Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:15:05 +0100 Subject: [PATCH 06/17] Test: a refusal names the declared branches and what is wrong with the declaration Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/declaredEnvironments.test.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/packages/lib/src/declaredEnvironments.test.ts b/packages/lib/src/declaredEnvironments.test.ts index 21da3048..f6b20cb9 100644 --- a/packages/lib/src/declaredEnvironments.test.ts +++ b/packages/lib/src/declaredEnvironments.test.ts @@ -150,8 +150,15 @@ test('the branch of an environment is env/, and the environment of a branc assert.equal(environmentOfBranch([], 'env/staging'), undefined); }); -test('the branches that deploy are listed for a refusal, and a repo that declares none says so', () => { - const { environments } = declareEnvironments(TWO); - assert.equal(describeBranches(environments, 'or'), 'env/staging or env/production'); - assert.match(describeBranches([], 'or'), /declares no environments/); +test('the branches that deploy are listed for a refusal, what is wrong with the declaration after them, and a repo that declares none says so', () => { + assert.equal(describeBranches(declareEnvironments(TWO), 'or'), 'env/staging or env/production'); + assert.equal(describeBranches(declareEnvironments(TWO), 'and'), 'env/staging and env/production'); + assert.equal( + describeBranches(declareEnvironments(undefined), 'or'), + 'no branch, since the repo declares no environments', + ); + assert.equal( + describeBranches(declareEnvironments({ staging: { promotes_from: 'main' }, b: {} }), 'or'), + 'env/staging; `b` has no `promotes_from`', + ); }); From 76123d67e9c2ca6b62dd3d77d82c5805f54ddab6 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:15:16 +0100 Subject: [PATCH 07/17] The branch that deploys is read from the declaration; ENVIRONMENT_BRANCHES is gone Co-Authored-By: Claude Sonnet 5.5 --- packages/cli-ci/src/core/setup.ts | 12 +++++++----- packages/cli/src/commands/deploy.ts | 14 ++++++++++---- packages/lib/src/declaredEnvironments.ts | 10 +++++----- packages/lib/src/deployTargets.ts | 19 +++++++++---------- packages/lib/src/index.ts | 1 - 5 files changed, 31 insertions(+), 25 deletions(-) diff --git a/packages/cli-ci/src/core/setup.ts b/packages/cli-ci/src/core/setup.ts index f437d1c8..50a71d0c 100644 --- a/packages/cli-ci/src/core/setup.ts +++ b/packages/cli-ci/src/core/setup.ts @@ -4,12 +4,13 @@ import { appendFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { type Context, + describeBranches, detailOf, - ENVIRONMENT_BRANCHES, environmentOf, isOperationsRepo, orAbsent, type Plan, + readDeclaredEnvironments, run, write, } from '@plexus-ms/lib'; @@ -78,13 +79,14 @@ const cacheHostOf = (env: NodeJS.ProcessEnv): string | undefined => env.PLX_TURB * in the deploy: it fails here, before anything is read, built or pushed. The * workflow is told by its name, which the forge hands every step. */ -function refuseOnPushWithoutEnvironment(env: NodeJS.ProcessEnv): void { +async function refuseOnPushWithoutEnvironment(ctx: Context, env: NodeJS.ProcessEnv): Promise { if (env.GITHUB_WORKFLOW !== 'on_push') return; const ref = env.GITHUB_REF_NAME ?? ''; const tag = env.GITHUB_REF_TYPE === 'tag'; - if (!tag && environmentOf(env.GITHUB_EVENT_NAME ?? '', ref)) return; + const declared = await readDeclaredEnvironments(ctx, '.'); + if (!tag && environmentOf(declared, env.GITHUB_EVENT_NAME ?? '', ref)) return; throw new Error( - `on_push on ${tag ? 'tag ' : ''}${ref} deploys nowhere: only the branches ${Object.keys(ENVIRONMENT_BRANCHES).join(' and ')} deploy; run on_push there`, + `on_push on ${tag ? 'tag ' : ''}${ref} deploys nowhere: this repo deploys from ${describeBranches(declared, 'and')}; run on_push there`, ); } @@ -145,7 +147,7 @@ async function vaultFor( export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.ProcessEnv = process.env): Promise { // The job repo of an app repo, whose publish pushes the apps' images. const images = options.job === 'repo' && (options.publishes ?? 'images') === 'images'; - if (images || options.job === 'deploy') refuseOnPushWithoutEnvironment(env); + if (images || options.job === 'deploy') await refuseOnPushWithoutEnvironment(ctx, env); const repository = need('GITHUB_REPOSITORY', env); const owner = ownerOf(repository); const repo = repository.split('/')[1] ?? repository; diff --git a/packages/cli/src/commands/deploy.ts b/packages/cli/src/commands/deploy.ts index a4e4f61e..e5d8c635 100644 --- a/packages/cli/src/commands/deploy.ts +++ b/packages/cli/src/commands/deploy.ts @@ -14,10 +14,10 @@ // absent one, so a mount can always pass the flag. // // plx deploy --environment staging --inventory ../operations/inventory -// plx deploy --inventory operations/inventory # in a job, on a push to main or develop +// plx deploy --inventory operations/inventory # in a job, on a push to a declared env/ branch // plx deploy -e production --inventory inventory -- -e stack_wait_timeout=180 import { resolve } from 'node:path'; -import { deploy, ENVIRONMENT_BRANCHES, environmentOf, UsageError } from '@plexus-ms/lib'; +import { deploy, describeBranches, environmentOf, readDeclaredEnvironments, UsageError } from '@plexus-ms/lib'; import type { Command } from 'commander'; import { contextOf, version } from '../program.ts'; @@ -52,10 +52,16 @@ export function register(program: Command): void { if (opts.commit && !/^([0-9a-f]{40}|[0-9a-f]{64})$/.test(opts.commit)) throw new UsageError(`--commit ${opts.commit}: a full commit hash, 40 or 64 hex digits in lower case`); const env = process.env; - const environment = environmentOf(env.GITHUB_EVENT_NAME ?? '', env.GITHUB_REF_NAME ?? '', opts.environment); + const declared = await readDeclaredEnvironments(ctx, resolve(opts.dir)); + const environment = environmentOf( + declared, + env.GITHUB_EVENT_NAME ?? '', + env.GITHUB_REF_NAME ?? '', + opts.environment, + ); if (!environment) throw new UsageError( - `no environment: pass --environment, or run on a push to ${Object.keys(ENVIRONMENT_BRANCHES).join(' or ')}`, + `no environment: pass --environment, or run on a push to ${describeBranches(declared, 'or')}`, ); const result = await deploy(ctx, { environment, diff --git a/packages/lib/src/declaredEnvironments.ts b/packages/lib/src/declaredEnvironments.ts index 7733b147..90aff40b 100644 --- a/packages/lib/src/declaredEnvironments.ts +++ b/packages/lib/src/declaredEnvironments.ts @@ -67,11 +67,11 @@ export const environmentBranch = (name: string): string => `env/${name}`; export const environmentOfBranch = (environments: readonly DeclaredEnvironment[], ref: string): string | undefined => environments.find((e) => e.branch === ref)?.name; -/** The branches of the declaration for a refusal, joined by `joiner`; a line that says so where there are none. */ -export const describeBranches = (environments: readonly DeclaredEnvironment[], joiner: 'and' | 'or'): string => - environments.length > 0 - ? environments.map((e) => e.branch).join(` ${joiner} `) - : 'no branch, since the repo declares no environments'; +/** The branches of the declaration for a refusal, joined by `joiner`, with what is wrong with the declaration after them; a line that says so where it declares none. */ +export const describeBranches = (declared: DeclaredEnvironments, joiner: 'and' | 'or'): string => + (declared.environments.length > 0 + ? declared.environments.map((e) => e.branch).join(` ${joiner} `) + : 'no branch, since the repo declares no environments') + declared.problems.map((p) => `; ${p}`).join(''); /** The declaration from the value of `environments`: undefined, null and an empty map declare nothing. */ export function declareEnvironments(value: unknown): DeclaredEnvironments { diff --git a/packages/lib/src/deployTargets.ts b/packages/lib/src/deployTargets.ts index fb6fc491..64fc919b 100644 --- a/packages/lib/src/deployTargets.ts +++ b/packages/lib/src/deployTargets.ts @@ -22,6 +22,7 @@ import { join } from 'node:path'; import { parse } from 'yaml'; import type { Context } from './context.ts'; +import { type DeclaredEnvironments, environmentOfBranch } from './declaredEnvironments.ts'; import { UsageError } from './version.ts'; const VARS_DIRS = ['group_vars', 'host_vars']; @@ -31,21 +32,19 @@ export const DEFAULT_ENVIRONMENT = 'production'; /** * The environment a run deploys into (§ 3 PLX-Delivery): `given` when the - * caller stands in for an environment branch, else main is production and - * develop is staging, on a push or a run by hand; anything else, a pull - * request among it, deploys nowhere (the empty string). The one place the - * rule is written, for `plx` and `plx-ci`. + * caller stands in for an environment branch, else the environment the repo + * declares for the branch (`environments`, declaredEnvironments.ts), on a push + * or a run by hand; anything else, a pull request among it, deploys nowhere + * (the empty string). The one place the rule is written, for `plx` and + * `plx-ci`. */ -export function environmentOf(event: string, ref: string, given = ''): string { +export function environmentOf(declared: DeclaredEnvironments, event: string, ref: string, given = ''): string { if (given) return given; if (event !== 'push' && event !== 'workflow_dispatch') return ''; - // Own keys only: a branch can be named constructor or toString. - return Object.hasOwn(ENVIRONMENT_BRANCHES, ref) ? (ENVIRONMENT_BRANCHES[ref] ?? '') : ''; + // An invalid declaration deploys nowhere: a caller names its problems. + return declared.problems.length > 0 ? '' : (environmentOfBranch(declared.environments, ref) ?? ''); } -/** The branches that deploy, each into its environment: the rule `environmentOf` applies, and the list a refusal names. */ -export const ENVIRONMENT_BRANCHES: Readonly> = { main: DEFAULT_ENVIRONMENT, develop: 'staging' }; - /** App name → environment → deploy target. */ export type DeployTargets = Record>; diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index ba8ab7ef..b32d7c47 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -60,7 +60,6 @@ export { type Deployment, type DeployTargets, deployLegs, - ENVIRONMENT_BRANCHES, type EnvironmentTargets, environmentOf, type InventoryFile, From c37cc0dd50c54dcddfd6efaeec79cc00c48ec65f Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:16:31 +0100 Subject: [PATCH 08/17] Test: both repo templates ask for the environments and are born on main Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/environmentsQuestion.test.ts | 60 +++++++++++++++++++ packages/lib/src/repoOperations.test.ts | 3 +- packages/lib/src/repoTurbo.test.ts | 3 +- 3 files changed, 64 insertions(+), 2 deletions(-) create mode 100644 packages/lib/src/environmentsQuestion.test.ts diff --git a/packages/lib/src/environmentsQuestion.test.ts b/packages/lib/src/environmentsQuestion.test.ts new file mode 100644 index 00000000..182077e1 --- /dev/null +++ b/packages/lib/src/environmentsQuestion.test.ts @@ -0,0 +1,60 @@ +// What the two repo templates do about a repo's environments and its first branch: both ask `environments`, a +// structured answer the engine hands on as it was given, and both are born on `main` whatever git is configured to. +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { renderBundled } from './testing/bundled.ts'; + +const REPOS = ['repo-turbo', 'repo-operations']; + +const TWO = { + staging: { promotes_from: 'main', auto_promote: true }, + production: { promotes_from: 'staging' }, +}; + +test('a repo template asks for the environments, and the default declares none', async () => { + for (const name of REPOS) { + const result = await renderBundled([name], { tenant: 'acme' }); + assert.deepEqual(result.errors, [], name); + assert.deepEqual(result.answers.environments, {}, name); + } +}); + +test('the declaration given is the answer, nested values and all, unchanged', async () => { + for (const name of REPOS) { + const result = await renderBundled([name], { tenant: 'acme', environments: TWO }); + assert.deepEqual(result.errors, [], name); + assert.deepEqual(result.answers.environments, TWO, name); + } +}); + +test('an answer written as YAML text is read as the declaration', async () => { + const text = 'staging: {promotes_from: main, auto_promote: true}\nproduction: {promotes_from: staging}\n'; + for (const name of REPOS) + assert.deepEqual((await renderBundled([name], { tenant: 'acme', environments: text })).answers.environments, TWO); +}); + +test('a package repo, which has no stack, is not asked', async () => { + const result = await renderBundled(['repo-turbo'], { tenant: 'acme', publishes_packages: true }); + assert.equal('environments' in result.answers, false); +}); + +test('a new repo is born on main, whatever git is configured to name its first branch', async () => { + for (const name of REPOS) { + const [init] = (await renderBundled([name], { tenant: 'acme' })).birth.map((b) => b.command); + assert.equal(init?.[0], 'git'); + const dir = mkdtempSync(join(tmpdir(), 'plx-birth-')); + try { + // No configuration at all: not the user's, not the system's, so `init.defaultBranch` is unset and git says master. + const env = { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null', HOME: dir }; + execFileSync(init?.[0] ?? '', init?.slice(1) ?? [], { cwd: dir, env, stdio: 'ignore' }); + const head = execFileSync('git', ['symbolic-ref', '--short', 'HEAD'], { cwd: dir, env, encoding: 'utf8' }); + assert.equal(head.trim(), 'main', name); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + } +}); diff --git a/packages/lib/src/repoOperations.test.ts b/packages/lib/src/repoOperations.test.ts index d93ca004..5be1baed 100644 --- a/packages/lib/src/repoOperations.test.ts +++ b/packages/lib/src/repoOperations.test.ts @@ -86,6 +86,7 @@ test('the answers are the questions’ defaults, and the org follows the tenant' ci_strategy: 'github', ci_overlay: 'none', housekeeping: false, + environments: {}, }); const byom = await render({ ci_strategy: 'byom', github_org: 'acme-gh' }); assert.equal(byom.answers.github_org, 'acme-gh'); @@ -152,7 +153,7 @@ test('a new repo is born with git and mise', async () => { assert.deepEqual( (await render()).birth.map((b) => b.command), [ - ['git', 'init'], + ['git', 'init', '--initial-branch=main'], ['mise', 'trust'], ['mise', 'install'], ], diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index bc8edaaa..8ac4a5d3 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -68,6 +68,7 @@ test('the answers of a plain app repo are the questions’ defaults', async () = ci_service_account: true, postgres: '', turbo_cache_host: '', + environments: {}, }); }); @@ -167,7 +168,7 @@ test('a new repo is born with git, mise and the two exact toolchain pins', async assert.deepEqual( (await render()).birth.map((b) => b.command), [ - ['git', 'init'], + ['git', 'init', '--initial-branch=main'], ['mise', 'trust'], ['mise', 'install'], ['mise', 'exec', '--', 'npx', 'corepack', 'use', 'pnpm@12'], From a0713eb0e4e711b9f72a35d5d352eca0e8839ef6 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:17:10 +0100 Subject: [PATCH 09/17] Test: a new repo of repo-turbo is born on main Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/newSite.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/lib/src/newSite.test.ts b/packages/lib/src/newSite.test.ts index 3fcbf9eb..e89f0ccf 100644 --- a/packages/lib/src/newSite.test.ts +++ b/packages/lib/src/newSite.test.ts @@ -371,7 +371,7 @@ test('a repo from repo-turbo with updates beside it, an app from app-nextjs and assert.deepEqual( ran.map((r) => [r.command, ...r.args].join(' ')), [ - 'git init', + 'git init --initial-branch=main', 'mise trust', 'mise install', 'mise exec -- npx corepack use pnpm@12', From f535363cc8ae958472e960e3d0fffd1dbd1590d7 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:17:22 +0100 Subject: [PATCH 10/17] The repo templates ask for the environments, and a new repo is born on main Co-Authored-By: Claude Sonnet 5.5 --- templates/repo-operations/template.yml | 11 ++++++++++- templates/repo-turbo/template.yml | 12 +++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/templates/repo-operations/template.yml b/templates/repo-operations/template.yml index 9cf753f8..fc467130 100644 --- a/templates/repo-operations/template.yml +++ b/templates/repo-operations/template.yml @@ -22,6 +22,15 @@ questions: help: "GitHub org of the tenant (image registry owner and forge org)" default: "{{ tenant }}" + # The repo's environments (§ 3 PLX-Delivery): a map from each environment's name to where it promotes from, `main` or + # another declared name, and optionally `auto_promote`. The answer is structured and the engine hands it on as given; + # it is read and validated in one place, lib's declaredEnvironments.ts, which `plx doctor` runs over it, so no + # validator is written here a second time. Empty by default: a repo that declares none deploys nothing. + environments: + type: yaml + help: "The environments of the repo's stacks, as a map of each name (one lowercase word, never main) to promotes_from (main, or another declared name) and optionally auto_promote (true or false), as in {staging: {promotes_from: main, auto_promote: true}, production: {promotes_from: staging}}; each deploys from its branch env/" + default: {} + infrastructure: type: bool help: "Does this tenant build its own infrastructure layer (Proxmox hypervisor, backup server, ingress VM) instead of buying hosts from a provider? Adds infrastructure.yml, the mount of plexus.infrastructure.playbook" @@ -123,6 +132,6 @@ policies: "{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/hosts.auto.tfvars": born-once birth: - - [git, init] + - [git, init, --initial-branch=main] - [mise, trust] - [mise, install] diff --git a/templates/repo-turbo/template.yml b/templates/repo-turbo/template.yml index 03ffe30d..27915aa7 100644 --- a/templates/repo-turbo/template.yml +++ b/templates/repo-turbo/template.yml @@ -20,6 +20,16 @@ questions: help: "Does this repo publish npm packages from its trunk (changesets, § 5 PLX-Delivery) instead of deploying apps from environment branches?" default: false + # The repo's environments (§ 3 PLX-Delivery): a map from each environment's name to where it promotes from, `main` or + # another declared name, and optionally `auto_promote`. The answer is structured and the engine hands it on as given; + # it is read and validated in one place, lib's declaredEnvironments.ts, which `plx doctor` runs over it, so no + # validator is written here a second time. Empty by default: a repo that declares none deploys nothing. + environments: + type: yaml + help: "The environments of the repo's stacks, as a map of each name (one lowercase word, never main) to promotes_from (main, or another declared name) and optionally auto_promote (true or false), as in {staging: {promotes_from: main, auto_promote: true}, production: {promotes_from: staging}}; each deploys from its branch env/" + default: {} + when: "{{ not publishes_packages }}" + package_registry: type: str help: "Where the packages are published (§ 5 PLX-Delivery): npm, the public registry, through OIDC trusted publishing; github, the forge's package registry, private to the tenant, with the workflow's own token" @@ -115,7 +125,7 @@ policies: PLEXUS.md.jinja: born-once birth: - - [git, init] + - [git, init, --initial-branch=main] - [mise, trust] - [mise, install] # The two pins the toolchain needs exact, written at birth only (§ 3 PLX-Updates). From 0d51debf795dec8d3c321f9cbad6d541c57397d0 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:19:47 +0100 Subject: [PATCH 11/17] Test: doctor fails an invalid declaration, an undeclared environment file and a declared environment without a file The index of requirement names gets the two names of the new pages by hand, as the last change did; ship regenerates the file. Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.test.ts | 174 ++++++++++++++++++++++ packages/lib/src/standard-index.json | 4 +- packages/lib/src/testing/doctor-checks.md | 6 +- 3 files changed, 181 insertions(+), 3 deletions(-) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index b3dc6e22..c93dce63 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -5,6 +5,7 @@ import { test } from 'node:test'; import { REGULAR, readTree, render, type Tree as Template } from '@plexus-ms/cli-template'; import { type Compose, type Mapping, parseCompose } from './compose.ts'; import { Context } from './context.ts'; +import { declareEnvironments } from './declaredEnvironments.ts'; import { type AppFacts, CHECKS, diagnose, examine, type Facts, type RepoFacts, type StackFacts } from './doctor.ts'; import type { Environment } from './environments.ts'; import { REQUIREMENT_NAME } from './lints.ts'; @@ -319,6 +320,23 @@ const FAILING: Record Facts; problem: ), problem: /^compose\.yaml requires `MODE`, which staging\.yaml does not list under `env`$/, }, + 'PLX-Stack/FileNamesDeclared': { + unit: (deviations = []) => + repo({ + stacks: stacksOf({ stacks: [loaded({ environments: [envFile('staging')] })] }), + marker: { declaration: { deviations, body: reasoned(deviations) } }, + }), + problem: + /^stack\/staging\.yaml names the environment `staging`, which the root PLEXUS\.md does not declare under `environments`; it declares none$/, + }, + 'PLX-Stack/DeclaredHasFile': { + unit: (deviations = []) => + repo({ + declared: declareEnvironments({ staging: { promotes_from: 'main' } }), + marker: { declaration: { deviations, body: reasoned(deviations) } }, + }), + problem: /^the environment `staging` is declared in the root PLEXUS\.md and no stack has a file `staging\.yaml`$/, + }, 'PLX-Stack/SinglePort': { unit: onStack('stateless', { web: web({ @@ -1749,8 +1767,20 @@ async function webReport(change: (web: Tree) => void, tracked: string[] = []) { }; } +/** The root marker of the `web` repo, declaring each of `names` as an environment that promotes from main, written as a person would. */ +const declaring = (...names: string[]): string => + `---\nrepo: web\nenvironments:\n${names.map((n) => ` ${n}:\n promotes_from: main\n`).join('')}---\n\n- A repo.\n`; + +/** + * Files put into the stack's directory; the environment each `.yaml` stands for is declared in the repo's root + * marker, so that what a test is about is not also an undeclared environment. + */ const withStack = (web: Tree, files: Tree) => { web.stack = { ...(web.stack as Tree), ...files }; + const names = Object.keys(files) + .filter((f) => /^[a-z]+\.yaml$/.test(f) && f !== 'compose.yaml') + .map((f) => f.slice(0, -'.yaml'.length)); + if (names.length > 0) web['PLEXUS.md'] = declaring(...names); }; const SITE_SERVICES = ` env_file: [{ path: .env, required: false }, { path: .env.secret, required: false }] labels: { plexus.tenant: t } @@ -1870,6 +1900,150 @@ test('PLX-Stack/Stateful/Seed: the package.json of the app whose image migrate r assert.deepEqual(await seeded(undefined), []); }); +// --- the declaration of the environments ---------------------------------------------- + +/** The findings of the repo's own unit under one requirement, or of no requirement. */ +const declared = async (marker: string | undefined, files: Tree = {}, requirement?: string) => { + const { text } = await webReport((web) => { + if (marker !== undefined) web['PLEXUS.md'] = marker; + web.stack = { ...(web.stack as Tree), ...files }; + }); + return text('.', requirement); +}; +const UNDECLARED = (file: string, name: string, rest: string) => + `${file} names the environment \`${name}\`, which the root PLEXUS.md does not declare under \`environments\`${rest}`; + +test('a repo with stacks and no `environments` and no environment file deploys nothing and passes', async () => { + const { of } = await webReport(() => {}); + assert.deepEqual(of('.'), []); +}); + +test('a repo without environments and without stacks passes', async () => { + const { of } = await webReport((web) => delete web.stack); + assert.deepEqual( + of('.').filter((f) => f.requirement?.startsWith('PLX-Stack/') && f.requirement !== 'PLX-Stack/AppInStack'), + [], + ); +}); + +test('PLX-Stack/FileNamesDeclared: an environment file that no declaration names is a finding, with or without a declaration', async () => { + const file = { 'staging.yaml': STAGING }; + assert.deepEqual(await declared(undefined, file, 'PLX-Stack/FileNamesDeclared'), [ + UNDECLARED('stack/staging.yaml', 'staging', '; it declares none'), + ]); + assert.deepEqual(await declared(declaring('production'), file, 'PLX-Stack/FileNamesDeclared'), [ + UNDECLARED('stack/staging.yaml', 'staging', '; it declares `production`'), + ]); + assert.deepEqual(await declared(declaring('staging'), file, 'PLX-Stack/FileNamesDeclared'), []); +}); + +test('PLX-Stack/FileNamesDeclared: each file of each stack is named by its own path', async () => { + const { text } = await webReport((web) => { + delete web.stack; + const good = { 'PLEXUS.md': '---\nprofile: stateless\n---\n', 'compose.yaml': compose(SITE_WEB) }; + web.stacks = { + a: { ...good, 'staging.yaml': STAGING }, + b: { ...good, 'staging.yaml': STAGING, 'qa.yaml': STAGING }, + }; + web['PLEXUS.md'] = declaring('staging'); + }); + assert.deepEqual(text('.', 'PLX-Stack/FileNamesDeclared'), [ + UNDECLARED('stacks/b/qa.yaml', 'qa', '; it declares `staging`'), + ]); +}); + +test('PLX-Stack/DeclaredHasFile: a declared environment that no stack has a file for is a finding, one in any stack is enough', async () => { + assert.deepEqual( + await declared(declaring('staging', 'production'), { 'staging.yaml': STAGING }, 'PLX-Stack/DeclaredHasFile'), + ['the environment `production` is declared in the root PLEXUS.md and no stack has a file `production.yaml`'], + ); + const { text } = await webReport((web) => { + delete web.stack; + const good = { 'PLEXUS.md': '---\nprofile: stateless\n---\n', 'compose.yaml': compose(SITE_WEB) }; + web.stacks = { a: good, b: { ...good, 'staging.yaml': STAGING } }; + web['PLEXUS.md'] = declaring('staging'); + }); + assert.deepEqual(text('.', 'PLX-Stack/DeclaredHasFile'), []); +}); + +test('PLX-Stack/DeclaredHasFile: a repo with no stack that declares an environment fails it', async () => { + const { text } = await webReport((web) => { + delete web.stack; + web['PLEXUS.md'] = declaring('staging'); + }); + assert.deepEqual(text('.', 'PLX-Stack/DeclaredHasFile'), [ + 'the environment `staging` is declared in the root PLEXUS.md and no stack has a file `staging.yaml`', + ]); +}); + +test('an invalid declaration is a finding of no requirement that gives the reason, and no deviation silences it', async () => { + const env = (body: string) => `---\nrepo: web\nenvironments:\n${body}---\n`; + const cases: [string, string, string][] = [ + [ + 'a cycle', + ' a:\n promotes_from: b\n b:\n promotes_from: a\n', + 'the environments `a`, `b` promote from one another in a cycle', + ], + [ + 'main as a name', + ' main:\n promotes_from: main\n', + '`main` is no environment name: it is the branch environments promote from', + ], + [ + 'an unknown key', + ' staging:\n promotes_from: main\n host: x\n', + '`staging`: unknown key `host`; the keys are `promotes_from` and `auto_promote`', + ], + ['no source', ' staging: {}\n', '`staging` has no `promotes_from`'], + [ + 'a name that is no word', + ' Stage-1:\n promotes_from: main\n', + '`Stage-1` is no environment name; a name is one lowercase word (letters only, no `-`)', + ], + [ + 'a source that is not declared', + ' staging:\n promotes_from: develop\n', + '`staging`: `promotes_from` names `develop`, which is neither `main` nor a declared environment', + ], + [ + 'auto_promote that is no boolean', + ' staging:\n promotes_from: main\n auto_promote: soon\n', + '`staging`: `auto_promote` is not a boolean', + ], + ]; + for (const [what, body, reason] of cases) { + const { of } = await webReport((web) => { + web['PLEXUS.md'] = env(body); + }); + assert.ok( + of('.').some((f) => f.requirement === undefined && f.problem === reason), + `${what}: ${of('.') + .map((f) => f.problem) + .join('; ')}`, + ); + } + const silenced = await webReport((web) => { + web['PLEXUS.md'] = + '---\nrepo: web\ndeviations: [PLX-Stack/DeclaredHasFile]\nenvironments:\n staging:\n promotes_from: develop\n---\n\n- `PLX-Stack/DeclaredHasFile`: the reason.\n'; + }); + assert.ok( + silenced.of('.').some((f) => f.requirement === undefined && f.problem.includes('`promotes_from` names `develop`')), + ); +}); + +test('a root marker that cannot be read is reported once, not again as a problem of the declaration', async () => { + const { of } = await webReport((web) => { + web['PLEXUS.md'] = '---\nenvironments: [\n---\n'; + }); + assert.equal( + of('.').filter((f) => f.problem.startsWith('PLEXUS.md: ')).length, + 1, + of('.') + .map((f) => f.problem) + .join('; '), + ); +}); + test('two stacks: what is wrong with one is reported on it and not on the other', async () => { const { of } = await webReport((web) => { delete web.stack; diff --git a/packages/lib/src/standard-index.json b/packages/lib/src/standard-index.json index ebd23ff5..3833ab0c 100644 --- a/packages/lib/src/standard-index.json +++ b/packages/lib/src/standard-index.json @@ -254,6 +254,8 @@ "PLX-Stack/EnvironmentFile", "PLX-Stack/EnvironmentParity", "PLX-Stack/EnvironmentCoverage", - "PLX-Stack/HostnamePort" + "PLX-Stack/HostnamePort", + "PLX-Stack/FileNamesDeclared", + "PLX-Stack/DeclaredHasFile" ] } diff --git a/packages/lib/src/testing/doctor-checks.md b/packages/lib/src/testing/doctor-checks.md index ae495645..74168fd2 100644 --- a/packages/lib/src/testing/doctor-checks.md +++ b/packages/lib/src/testing/doctor-checks.md @@ -10,7 +10,7 @@ set to a compendium checkout it reads the pages themselves instead. `plx doctor` checks of `PLX-Repo/Hooks` that `hk.pkl` wires a pre-commit hook and a pre-push hook, written literally in its `hooks` block, not what either runs. -`plx doctor` checks of `PLX-Repo/Verbs` that `dev`, `build`, `check`, `test` and `e2e` exist as root mise tasks and that no `verify` is left, not what they run, in which order, or whether they pass. +`plx doctor` checks of `PLX-Repo/Verbs` that `dev`, `build`, `check`, `test`, `e2e` and `publish` exist as root mise tasks and that no `verify` is left, not what they run, in which order, or whether they pass. `plx doctor` checks `PLX-App/Marker`. @@ -22,10 +22,12 @@ set to a compendium checkout it reads the pages themselves instead. `plx doctor` checks `PLX-Stack/EnvFileLoad` on the service that publishes the loopback port and on every service that runs the image of one of the stack's apps, and of `PLX-Stack/NoCommittedSecrets` that the repo tracks no `.env` and no `.env.secret`. -It checks `PLX-Stack/EnvironmentFile`, of `host` its form and not that the host answers, refusing a number or a boolean under `env` with the advice to quote it, and checks `PLX-Stack/EnvironmentParity`. +It checks `PLX-Stack/EnvironmentFile`, of `host` its form and not that the host answers, refusing a number or a boolean under `env` with the advice to quote it, and of its last clause that neither `env` nor `secrets` lists `COMPOSE_PROJECT_NAME` or a variable of the table below, not every name under `PLEXUS_`; and it checks `PLX-Stack/EnvironmentParity`. It checks of `PLX-Stack/EnvironmentCoverage` that every variable interpolated in a value of the compose file is listed under `env` of every environment file; it reads no key of the compose file, and not how a secret reaches a container. +It checks `PLX-Stack/FileNamesDeclared` and `PLX-Stack/DeclaredHasFile`, the files and the declaration, not the branches. + `plx doctor` checks of `PLX-Stack/SinglePort` that a stack whose environments have a `hostname` binds `PLEXUS_LOOPBACK_PORT` in exactly one port mapping, a stack whose environments have none binds it in none, and a stack without environment files binds it in exactly one, not that the service speaks plain HTTP. It checks `PLX-Stack/LoopbackPort` and `PLX-Stack/HostnamePort`. From 2d94e4c76635f8f51e97baed0db8ef62861a2e0e Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:19:58 +0100 Subject: [PATCH 12/17] plx doctor checks the declaration of the environments against the environment files Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.ts | 61 +++++++++++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index 8041511a..c4019a25 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -107,7 +107,14 @@ import { } from './compose.ts'; import { filesWithConflictMarkers } from './conflicts.ts'; import type { Context } from './context.ts'; -import { type Environment, isReservedName, PLATFORM_VARIABLES, requiredVariables } from './environments.ts'; +import { type DeclaredEnvironments, ENVIRONMENTS_KEY, readDeclaredEnvironments } from './declaredEnvironments.ts'; +import { + type Environment, + environmentNameProblem, + isReservedName, + PLATFORM_VARIABLES, + requiredVariables, +} from './environments.ts'; import { ExecError } from './io.ts'; import { REQUIREMENT_NAME } from './lints.ts'; import { type Declaration, MARKER_FILE, parseMarker, reasonGiven } from './marker.ts'; @@ -158,6 +165,8 @@ export interface RepoFacts { oldComposeFiles?: string[]; /** Its stacks and what is wrong with their layout, as the loader reads them; absent where there are none to read. */ stacks?: RepoStacks; + /** The environments its root marker declares, and what is wrong with the declaration; absent reads as none declared. */ + declared?: DeclaredEnvironments; /** The `plx` pin of its `mise.toml`: the Plexus version it is on. */ pin?: string; /** Every tracked marker read as configuration, the root first; undefined outside a git checkout. */ @@ -526,6 +535,8 @@ export const CHECKS: Readonly> 'PLX-Stack/EnvironmentFile': { binds: 'stack', check: environmentFile }, 'PLX-Stack/EnvironmentParity': { binds: 'stack', check: environmentParity }, 'PLX-Stack/EnvironmentCoverage': { binds: 'stack', check: onCompose(environmentCoverage) }, + 'PLX-Stack/FileNamesDeclared': { binds: 'repo', check: fileNamesDeclared }, + 'PLX-Stack/DeclaredHasFile': { binds: 'repo', check: declaredHasFile }, 'PLX-Stack/SinglePort': { binds: 'stack', check: onCompose(singlePort) }, 'PLX-Stack/LoopbackPort': { binds: 'stack', check: onCompose(loopbackPort) }, 'PLX-Stack/HostnamePort': { binds: 'stack', check: hostnamePort }, @@ -597,6 +608,43 @@ function environmentCoverage(compose: Compose, stack: StackFacts): string[] { ); } +/** The environment files of the repo's stacks, as the loader read them: the stack's directory, relative to the repo, and the environments in it. */ +const environmentFilesOf = (repo: RepoFacts) => + (repo.stacks?.stacks ?? []).map((s) => ({ + dir: relative(repo.stacks?.root ?? '', s.dir), + environments: s.environments, + })); + +/** + * PLX-Stack/FileNamesDeclared: every environment file of every stack names an + * environment the root marker declares, so that a repo that declares none and + * has a file has an undeclared environment. A file whose name is no + * environment's has its finding in EnvironmentFile already. + */ +function fileNamesDeclared(repo: RepoFacts): string[] { + const declared = (repo.declared?.environments ?? []).map((e) => e.name); + const list = declared.length > 0 ? `declares ${declared.map((n) => `\`${n}\``).join(', ')}` : 'declares none'; + return environmentFilesOf(repo).flatMap(({ dir, environments }) => + environments + .filter((e) => environmentNameProblem(e.name) === undefined && !declared.includes(e.name)) + .map( + (e) => + `${dir}/${e.name}.yaml names the environment \`${e.name}\`, which the root ${MARKER_FILE} does not declare under \`${ENVIRONMENTS_KEY}\`; it ${list}`, + ), + ); +} + +/** PLX-Stack/DeclaredHasFile: every declared environment has a file in at least one stack. */ +function declaredHasFile(repo: RepoFacts): string[] { + const files = new Set(environmentFilesOf(repo).flatMap(({ environments }) => environments.map((e) => e.name))); + return (repo.declared?.environments ?? []) + .filter((e) => !files.has(e.name)) + .map( + (e) => + `the environment \`${e.name}\` is declared in the root ${MARKER_FILE} and no stack has a file \`${e.name}.yaml\``, + ); +} + /** The environments whose `hostname`, set or left out, is known: its value is usable. */ const hostnameKnown = (stack: StackFacts): Environment[] => readEnvironments(stack).filter((e) => !e.invalid.includes('hostname')); @@ -646,6 +694,14 @@ function markerConfig(repo: RepoFacts): string[] { ]; } +/** + * What is wrong with the declaration of the environments (declaredEnvironments.ts): + * a finding of no requirement, one line for each fault, which no deviation + * silences. A root marker that cannot be read is reported by PLX-Repo/Marker. + */ +const declarationProblems = (repo: RepoFacts): string[] => + repo.marker?.problem ? [] : (repo.declared?.problems ?? []); + /** Stays for the transition, with the old names in the repo templates; the issues labelled Contraction track its removal. */ const OLD_STRATEGY_NAMES = ['on-prem', 'hybrid']; @@ -814,6 +870,7 @@ function diagnoseUnit(unit: Facts, known: Set): UnitReport { for (const problem of repoNaming(unit)) findings.push({ problem }); for (const file of unit.conflicted ?? []) findings.push({ problem: `\`${file}\` holds a conflict marker` }); for (const problem of markerConfig(unit)) findings.push({ problem }); + for (const problem of declarationProblems(unit)) findings.push({ problem }); } const obsolete = (declaration?.obsolete ?? []).map((k) => `\`${k}\``).join(' and '); const hints: string[] = []; @@ -1051,6 +1108,7 @@ async function readRepo( const conflicted = tracked === undefined ? undefined : await filesWithConflictMarkers(ctx, dir.path); const sites = tracked !== undefined && crossedOver(tracked) ? await readSites(ctx, dir.path) : undefined; const stacks = await loadStacks(ctx, dir.path); + const declared = await readDeclaredEnvironments(ctx, dir.path); return { kind, ...(tracked !== undefined && !crossedOver(tracked) ? { uncrossed: true as const } : {}), @@ -1062,6 +1120,7 @@ async function readRepo( ...(conflicted?.length ? { conflicted } : {}), apps: [], stacks, + declared, ...(dir.pin ? { pin: dir.pin } : {}), ...sites, ...(sites?.sites ? await templateFacts(sites.sites, plxVersion) : {}), From cb77a40d88cbec8dc87b1eabdfd814b70ae87b83 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:21:45 +0100 Subject: [PATCH 13/17] Test: plx new, plx apply and plx update carry the declaration of the environments as it was written Co-Authored-By: Claude Sonnet 5.5 --- newborns/update-released.test.ts | 32 ++++++++++++++++ packages/cli/src/commands/apply.test.ts | 29 +++++++++++++++ packages/lib/src/newSite.test.ts | 49 ++++++++++++++++++++++++- 3 files changed, 109 insertions(+), 1 deletion(-) diff --git a/newborns/update-released.test.ts b/newborns/update-released.test.ts index d4ace612..54b9cb38 100644 --- a/newborns/update-released.test.ts +++ b/newborns/update-released.test.ts @@ -252,6 +252,38 @@ for (const kind of ['app', 'operations'] as const) { }); } +/** A declaration of environments as a person writes it into a marker: a comment, a block, a value nested two deep. */ +const DECLARATION = `# What deploys, and from where. +environments: + staging: + promotes_from: main + auto_promote: true + production: + promotes_from: staging +`; + +for (const kind of ['app', 'operations'] as const) + test(`${kind}: a declaration of environments in the marker of a repo of ${RELEASED} stands as written when ${FIRST} is taken`, async () => { + const repo = await repoAt(RELEASED, kind); + const marker = join(repo, 'PLEXUS.md'); + const text = readFileSync(marker, 'utf8'); + const close = text.indexOf('\n---\n', 4); + writeFileSync(marker, `${text.slice(0, close + 1)}${DECLARATION}${text.slice(close + 1)}`); + await git(repo, 'commit', '-q', '-am', 'declare the environments'); + const branch = execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: repo, encoding: 'utf8' }).trim(); + await sh('git', ['push', '-q', 'origin', branch], repo, env); + const taken = await take(FIRST, repo, FIRST); + assert.ok(taken.ok, taken.output); + const after = taken.read('PLEXUS.md'); + assert.ok(after.includes(DECLARATION), after); + assert.equal(after.match(/^environments:/gm)?.length, 1, 'no default is added beside the answer'); + assert.match(after, new RegExp(`^version: ${FIRST.replaceAll('.', '\\.')}$`, 'm')); + assert.deepEqual(parse(after.split('\n---\n')[0]?.slice(4) ?? '').environments, { + staging: { promotes_from: 'main', auto_promote: true }, + production: { promotes_from: 'staging' }, + }); + }); + /** The repo's group `ci`, as 0.134.1 renders it empty; with `host` listed in it, the tenant's own edit, committed and pushed. */ async function listHost(repo: string, host: string): Promise { const hosts = join(repo, 'inventory', 'hosts.yml'); diff --git a/packages/cli/src/commands/apply.test.ts b/packages/cli/src/commands/apply.test.ts index 74850a13..989e4f0a 100644 --- a/packages/cli/src/commands/apply.test.ts +++ b/packages/cli/src/commands/apply.test.ts @@ -193,3 +193,32 @@ test('apply takes a repo given relatively as the repo it is, not as a directory process.chdir(cwd); } }); + +test('apply brings the files in line with a hand-edited declaration of environments and leaves the marker as written', async () => { + const templates = join(dir, 'fleet-templates'); + put(join(templates, 'fleet'), { + 'template.yml': 'name: fleet\nquestions:\n environments:\n type: yaml\n default: {}\n', + 'files/branches.txt.jinja': + '{% for name, e in environments.items() %}env/{{ name }} from {{ e.promotes_from }}{% if e.auto_promote is defined and e.auto_promote %} (auto){% endif %}\n{% endfor %}', + }); + const marker = (environments: string) => + `---\nversion: ${version}\ntemplates: [fleet]\nenvironments:\n${environments}---\n\nThe prose.\n`; + const staging = ' staging:\n promotes_from: main\n'; + const repo = join(dir, 'fleet-repo'); + mkdirSync(repo); + git(repo, 'init', '-q', '-b', 'main'); + put(repo, { 'PLEXUS.md': marker(staging), 'branches.txt': 'env/staging from main\n' }); + git(repo, 'add', '-A'); + git(repo, 'commit', '-q', '-m', 'init'); + const edited = marker( + `${staging} auto_promote: true # promotes itself\n production:\n promotes_from: staging\n`, + ); + put(repo, { 'PLEXUS.md': edited }); + const { code } = await plx('-y', 'apply', '--templates', templates, repo); + assert.equal(code, 0); + assert.equal( + readFileSync(join(repo, 'branches.txt'), 'utf8'), + 'env/staging from main (auto)\nenv/production from staging\n', + ); + assert.equal(readFileSync(join(repo, 'PLEXUS.md'), 'utf8'), edited); +}); diff --git a/packages/lib/src/newSite.test.ts b/packages/lib/src/newSite.test.ts index e89f0ccf..152e5924 100644 --- a/packages/lib/src/newSite.test.ts +++ b/packages/lib/src/newSite.test.ts @@ -8,7 +8,17 @@ import { createRequire } from 'node:module'; import { join } from 'node:path'; import { PassThrough } from 'node:stream'; import { after, test } from 'node:test'; -import { apply, Context, diagnose, examine, newSite, realIo, templatesRoot } from './index.ts'; +import { + apply, + Context, + declareEnvironments, + diagnose, + examine, + newSite, + readDeclaredEnvironments, + realIo, + templatesRoot, +} from './index.ts'; import { writeVersionFiles } from './templateVersion.ts'; import { git, quietContext, repoWith, scratchDir, templatesAt, text, write } from './testing/siteRepo.ts'; @@ -421,6 +431,43 @@ test('a repo from repo-turbo with updates beside it, an app from app-nextjs and assert.equal(report.units, 3); }); +test('a repo born with environments holds the declaration in its marker, read back as given, and with a file for each it passes the doctor', async () => { + const environments = { + staging: { promotes_from: 'main', auto_promote: true }, + production: { promotes_from: 'staging' }, + }; + const target = scratch.fresh('turbo-environments'); + const { ctx } = recording(); + const created = await newSite(ctx, { + dir: target, + templates: ['repo-turbo', 'updates'], + answers: { tenant: 'acme', repo: 'shop', environments }, + plxVersion: bundled.version, + root: templatesRoot(), + }); + git(target, 'init', '-q', '-b', 'main'); + assert.deepEqual(created.answers.environments, environments); + assert.deepEqual(await readDeclaredEnvironments(ctx, target), declareEnvironments(environments)); + assert.deepEqual( + (await readDeclaredEnvironments(ctx, target)).environments.map((e) => [e.branch, e.source, e.autoPromote]), + [ + ['env/staging', 'main', true], + ['env/production', 'env/staging', false], + ], + ); + await nested(join(target, 'apps', 'web'), ['app-nextjs'], { name: 'web' }); + await nested(join(target, 'stack'), ['stack'], { apps: 'web' }); + const file = (host: string, hostname: string) => `host: ${host}\nhostname: ${hostname}\n`; + write(target, { + 'stack/staging.yaml': file('192.0.2.1', 'staging.shop.example.com'), + 'stack/production.yaml': file('192.0.2.2', 'shop.example.com'), + }); + assert.deepEqual((await doctorOf(target)).findings, []); + // Without a file for one of them, or with a file for one that is not declared, it fails. + write(target, { 'stack/qa.yaml': file('192.0.2.3', 'qa.shop.example.com') }); + assert.deepEqual((await doctorOf(target)).findings.length, 1); +}); + test('a stateful stack whose app carries the migration passes the doctor as born', async () => { const { target } = await bornTurbo(); await nested(join(target, 'apps', 'web'), ['app-nextjs'], { name: 'web', migrates: 'true' }); From 01128995613a4e5e418b78fa1002df12e7a3b310 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:23:17 +0100 Subject: [PATCH 14/17] Headers: the marker's answers may be structured, and what doctor checks of the declaration Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/doctor.ts | 9 +++++++++ packages/lib/src/marker.ts | 8 +++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index c4019a25..9b44874d 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -47,6 +47,15 @@ // stack's port the one of PLX-Stack/SinglePort, in its three cases; a stack // without environment files meets the four as it is. // +// A repo's environments are what its root marker declares (declaredEnvironments.ts, +// the one reader and validator): PLX-Stack/FileNamesDeclared holds each +// environment file of each stack against the declaration, a repo that declares +// none included, and PLX-Stack/DeclaredHasFile holds each declared environment +// against the files, a repo with no stack included; a repo with stacks and no +// declaration and no environment file passes. An invalid declaration is a +// finding of no requirement, one line for each fault with its reason, which no +// deviation silences. +// // Also of no requirement, and no deviation silences it: a repo with `stack/` // whose root marker has no `repo` key, which names it (stacks.ts, `no-repo-name`). // diff --git a/packages/lib/src/marker.ts b/packages/lib/src/marker.ts index ec64489f..b9ed0c42 100644 --- a/packages/lib/src/marker.ts +++ b/packages/lib/src/marker.ts @@ -9,9 +9,11 @@ // that a verb can say they can go. // // The configuration (`parseMarkerConfig`) is the frontmatter as the -// templates' answers: the frontmatter -// is flat, `version`, `templates` and `deviations` are reserved, and every -// other key is an answer, `profile` among them. `version` is the +// templates' answers: `version`, `templates` and `deviations` are reserved, and +// every other key is an answer, `profile` among them. An answer may be +// structured: `environments`, the repo's declaration (declaredEnvironments.ts, +// which reads and validates it), is a map of maps, and the writers below keep +// a value they do not set as it was. `version` is the // Plexus version the repo's sites were last rendered at and belongs in the // repo's root marker only, which a reader of one marker cannot tell; that is // sites.ts's to enforce. A marker without `templates` is valid and renders From 312027b55df5f215b1ebe5c8263eab0317e3a471 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 04:40:16 +0100 Subject: [PATCH 15/17] Test: a repo-operations that gains updates is spliced the empty declaration of environments with its other defaults Co-Authored-By: Claude Sonnet 5.5 --- packages/dev/src/ship.integration.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index c62b4bbb..2e32f644 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -2288,7 +2288,7 @@ for (const [template, answers, edits] of [ const end = snapshot(human); const expected = { ...start }; expected['PLEXUS.md'] = { - // The questions the templates have gained since the move are spliced into the marker, as their defaults, and the + // The questions the templates have gained since the move are spliced into the marker, as their defaults (an empty declaration of environments among them), and the // answer to ci_registry, which the version no longer asks, leaves it (the package repo was never asked it). text: removeMarkerKeys( setMarkerKeys(start['PLEXUS.md']?.text ?? '', { @@ -2296,7 +2296,7 @@ for (const [template, answers, edits] of [ templates: [template, 'updates'], ...(template === 'repo-turbo' ? { postgres: '', repo: '', turbo_cache_host: '' } - : { housekeeping: false, repo: '' }), + : { environments: {}, housekeeping: false, repo: '' }), }), template === 'repo-operations' ? ['ci_registry'] : [], ), From 37d6fd66b0544635feeb14f63c806e5ee29cf801 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 05:07:34 +0100 Subject: [PATCH 16/17] Test: a refusal with an invalid declaration names its problems and no deploying branch, and one with none says where to declare Co-Authored-By: Claude Sonnet 5.5 --- packages/cli-ci/src/commands/setup.test.ts | 8 ++++++-- packages/cli/src/commands/deploy.test.ts | 9 +++++++-- packages/lib/src/declaredEnvironments.test.ts | 18 +++++++++++------- 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/packages/cli-ci/src/commands/setup.test.ts b/packages/cli-ci/src/commands/setup.test.ts index 09ea822a..061da900 100644 --- a/packages/cli-ci/src/commands/setup.test.ts +++ b/packages/cli-ci/src/commands/setup.test.ts @@ -620,7 +620,7 @@ test('a run of on_push in a repo that declares no environment is refused, and th assert.equal(run.status, 1, run.log); assert.match( run.log, - /on_push on main deploys nowhere: this repo deploys from no branch, since the repo declares no environments; run on_push there/, + /on_push on main deploys nowhere: the repo declares no environment; declare one under `environments` in the root marker/, ); } }); @@ -632,7 +632,11 @@ test('a run of on_push in a repo whose declaration is invalid is refused with th marker: '---\nenvironments:\n staging:\n promotes_from: develop\n---\n', }); assert.equal(run.status, 1, run.log); - assert.match(run.log, /`staging`: `promotes_from` names `develop`/); + assert.match( + run.log, + /on_push on env\/staging deploys nowhere: the `environments` of the root marker are invalid: `staging`: `promotes_from` names `develop`/, + ); + assert.doesNotMatch(run.log, /deploys from/); }); for (const [workflow, event] of [ diff --git a/packages/cli/src/commands/deploy.test.ts b/packages/cli/src/commands/deploy.test.ts index 16872d04..f59985dd 100644 --- a/packages/cli/src/commands/deploy.test.ts +++ b/packages/cli/src/commands/deploy.test.ts @@ -390,12 +390,17 @@ test('a repo that declares no environment deploys from no branch, and a declarat put(f.repo, { 'PLEXUS.md': '---\nrepo: shop\n---\n' }); await assert.rejects( plx(args, f.fake, { GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'env/staging' }), - (e: unknown) => e instanceof UsageError && e.message.includes('declares no environments'), + (e: unknown) => + e instanceof UsageError && + e.message.includes('the repo declares no environment; declare one under `environments` in the root marker'), ); put(f.repo, { 'PLEXUS.md': '---\nrepo: shop\nenvironments:\n staging:\n promotes_from: develop\n---\n' }); await assert.rejects( plx(args, f.fake, { GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'env/staging' }), - (e: unknown) => e instanceof UsageError && e.message.includes('`promotes_from` names `develop`'), + (e: unknown) => + e instanceof UsageError && + e.message.includes('are invalid: `staging`: `promotes_from` names `develop`') && + !e.message.includes('run on a push'), ); assert.deepEqual(runs(f.fake), []); }); diff --git a/packages/lib/src/declaredEnvironments.test.ts b/packages/lib/src/declaredEnvironments.test.ts index f6b20cb9..d60c6905 100644 --- a/packages/lib/src/declaredEnvironments.test.ts +++ b/packages/lib/src/declaredEnvironments.test.ts @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { Context } from './context.ts'; import { + declarationRefusal, declareEnvironments, describeBranches, environmentBranch, @@ -150,15 +151,18 @@ test('the branch of an environment is env/, and the environment of a branc assert.equal(environmentOfBranch([], 'env/staging'), undefined); }); -test('the branches that deploy are listed for a refusal, what is wrong with the declaration after them, and a repo that declares none says so', () => { +test('the branches that deploy are listed for a refusal', () => { assert.equal(describeBranches(declareEnvironments(TWO), 'or'), 'env/staging or env/production'); assert.equal(describeBranches(declareEnvironments(TWO), 'and'), 'env/staging and env/production'); +}); + +test('a refusal says the repo declares no environment and where one is declared, or that the declaration is invalid and its problems, and names no branch as deploying', () => { + assert.equal(declarationRefusal(declareEnvironments(TWO)), undefined); assert.equal( - describeBranches(declareEnvironments(undefined), 'or'), - 'no branch, since the repo declares no environments', - ); - assert.equal( - describeBranches(declareEnvironments({ staging: { promotes_from: 'main' }, b: {} }), 'or'), - 'env/staging; `b` has no `promotes_from`', + declarationRefusal(declareEnvironments(undefined)), + 'the repo declares no environment; declare one under `environments` in the root marker', ); + const invalid = declarationRefusal(declareEnvironments({ staging: { promotes_from: 'main' }, b: {} })); + assert.equal(invalid, 'the `environments` of the root marker are invalid: `b` has no `promotes_from`'); + assert.doesNotMatch(String(invalid), /env\//); }); From 4e6bcaa937e1f3a4a22665d781f4de57dd506702 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 05:07:46 +0100 Subject: [PATCH 17/17] A refusal names the declaration's problems, or where to declare an environment, instead of a branch that does not deploy; the repo templates say birth needs git 2.28 Co-Authored-By: Claude Sonnet 5.5 --- packages/cli-ci/src/core/setup.ts | 3 ++- packages/cli/src/commands/deploy.ts | 11 +++++++++-- packages/lib/src/declaredEnvironments.ts | 18 ++++++++++++++---- packages/lib/src/index.ts | 1 + templates/repo-operations/template.yml | 1 + templates/repo-turbo/template.yml | 1 + 6 files changed, 28 insertions(+), 7 deletions(-) diff --git a/packages/cli-ci/src/core/setup.ts b/packages/cli-ci/src/core/setup.ts index 50a71d0c..c91d0847 100644 --- a/packages/cli-ci/src/core/setup.ts +++ b/packages/cli-ci/src/core/setup.ts @@ -4,6 +4,7 @@ import { appendFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { type Context, + declarationRefusal, describeBranches, detailOf, environmentOf, @@ -86,7 +87,7 @@ async function refuseOnPushWithoutEnvironment(ctx: Context, env: NodeJS.ProcessE const declared = await readDeclaredEnvironments(ctx, '.'); if (!tag && environmentOf(declared, env.GITHUB_EVENT_NAME ?? '', ref)) return; throw new Error( - `on_push on ${tag ? 'tag ' : ''}${ref} deploys nowhere: this repo deploys from ${describeBranches(declared, 'and')}; run on_push there`, + `on_push on ${tag ? 'tag ' : ''}${ref} deploys nowhere: ${declarationRefusal(declared) ?? `this repo deploys from ${describeBranches(declared, 'and')}; run on_push there`}`, ); } diff --git a/packages/cli/src/commands/deploy.ts b/packages/cli/src/commands/deploy.ts index e5d8c635..4adf2b83 100644 --- a/packages/cli/src/commands/deploy.ts +++ b/packages/cli/src/commands/deploy.ts @@ -17,7 +17,14 @@ // plx deploy --inventory operations/inventory # in a job, on a push to a declared env/ branch // plx deploy -e production --inventory inventory -- -e stack_wait_timeout=180 import { resolve } from 'node:path'; -import { deploy, describeBranches, environmentOf, readDeclaredEnvironments, UsageError } from '@plexus-ms/lib'; +import { + declarationRefusal, + deploy, + describeBranches, + environmentOf, + readDeclaredEnvironments, + UsageError, +} from '@plexus-ms/lib'; import type { Command } from 'commander'; import { contextOf, version } from '../program.ts'; @@ -61,7 +68,7 @@ export function register(program: Command): void { ); if (!environment) throw new UsageError( - `no environment: pass --environment, or run on a push to ${describeBranches(declared, 'or')}`, + `no environment: pass --environment; ${declarationRefusal(declared) ?? `or run on a push to ${describeBranches(declared, 'or')}`}`, ); const result = await deploy(ctx, { environment, diff --git a/packages/lib/src/declaredEnvironments.ts b/packages/lib/src/declaredEnvironments.ts index 90aff40b..6173e8d1 100644 --- a/packages/lib/src/declaredEnvironments.ts +++ b/packages/lib/src/declaredEnvironments.ts @@ -67,11 +67,21 @@ export const environmentBranch = (name: string): string => `env/${name}`; export const environmentOfBranch = (environments: readonly DeclaredEnvironment[], ref: string): string | undefined => environments.find((e) => e.branch === ref)?.name; -/** The branches of the declaration for a refusal, joined by `joiner`, with what is wrong with the declaration after them; a line that says so where it declares none. */ +/** The branches of a valid declaration for a refusal, joined by `joiner`. */ export const describeBranches = (declared: DeclaredEnvironments, joiner: 'and' | 'or'): string => - (declared.environments.length > 0 - ? declared.environments.map((e) => e.branch).join(` ${joiner} `) - : 'no branch, since the repo declares no environments') + declared.problems.map((p) => `; ${p}`).join(''); + declared.environments.map((e) => e.branch).join(` ${joiner} `); + +/** + * Why no branch deploys, for a refusal to put where it would list the branches: the declaration's + * problems where it is invalid, where to declare an environment where there is none, and undefined + * where branches deploy. + */ +export const declarationRefusal = (declared: DeclaredEnvironments): string | undefined => + declared.problems.length > 0 + ? `the ${code(ENVIRONMENTS_KEY)} of the root marker are invalid: ${declared.problems.join('; ')}` + : declared.environments.length === 0 + ? `the repo declares no environment; declare one under ${code(ENVIRONMENTS_KEY)} in the root marker` + : undefined; /** The declaration from the value of `environments`: undefined, null and an empty map declare nothing. */ export function declareEnvironments(value: unknown): DeclaredEnvironments { diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index b32d7c47..2e70cfa2 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -37,6 +37,7 @@ export { DEFAULT_BRANCH, type DeclaredEnvironment, type DeclaredEnvironments, + declarationRefusal, declareEnvironments, describeBranches, ENVIRONMENTS_KEY, diff --git a/templates/repo-operations/template.yml b/templates/repo-operations/template.yml index fc467130..dfa9e2fa 100644 --- a/templates/repo-operations/template.yml +++ b/templates/repo-operations/template.yml @@ -132,6 +132,7 @@ policies: "{% if ci_jobs_strategy == 'byom' %}ci{% endif %}/hosts.auto.tfvars": born-once birth: + # --initial-branch needs git 2.28 or newer; an older git refuses the flag here. - [git, init, --initial-branch=main] - [mise, trust] - [mise, install] diff --git a/templates/repo-turbo/template.yml b/templates/repo-turbo/template.yml index 27915aa7..3936c82f 100644 --- a/templates/repo-turbo/template.yml +++ b/templates/repo-turbo/template.yml @@ -125,6 +125,7 @@ policies: PLEXUS.md.jinja: born-once birth: + # --initial-branch needs git 2.28 or newer; an older git refuses the flag here. - [git, init, --initial-branch=main] - [mise, trust] - [mise, install]