From 99d034bac064f1c1017ae81b66cc74517685a1a9 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 10:32:53 +0100 Subject: [PATCH 01/21] Test: a template file rendered once per item of a list (each) Co-Authored-By: Claude Opus 5.5 --- packages/cli-template/src/each.test.ts | 116 +++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 packages/cli-template/src/each.test.ts diff --git a/packages/cli-template/src/each.test.ts b/packages/cli-template/src/each.test.ts new file mode 100644 index 00000000..1bca4b9c --- /dev/null +++ b/packages/cli-template/src/each.test.ts @@ -0,0 +1,116 @@ +// A file rendered once per item of a list: the manifest's `each` names, by the +// file's source path, a variable of the template's scope that holds a list, +// and the file is rendered for every item with `_item` bound to it. +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { render } from './index.ts'; +import { listing, template } from './testing/trees.ts'; + +const fruits = + 'name: basket\nquestions:\n fruits:\n type: yaml\n default: []\neach:\n "{{ _item.name }}.txt.jinja": fruits\n'; +const file = { '{{ _item.name }}.txt.jinja': 'A {{ _item.colour }} {{ _item.name }}.' }; + +test('a file listed under each is rendered once per item, with _item bound in its path and its text', () => { + const result = render([template(fruits, file)], { + fruits: [ + { name: 'apple', colour: 'red' }, + { name: 'pear', colour: 'green' }, + ], + }); + assert.deepEqual(result.errors, []); + assert.deepEqual(listing(result.tree), { 'apple.txt': 'A red apple.', 'pear.txt': 'A green pear.' }); +}); + +test('an empty list renders the file nowhere', () => { + const result = render([template(fruits, file)], { fruits: [] }); + assert.deepEqual(result.errors, []); + assert.deepEqual(listing(result.tree), {}); +}); + +test('the policy of the source applies to every path it renders to', () => { + const manifest = `${fruits}policies:\n "{{ _item.name }}.txt.jinja": birth-only\n`; + const result = render([template(manifest, file)], { fruits: [{ name: 'apple' }, { name: 'pear' }] }); + assert.deepEqual(result.errors, []); + assert.deepEqual( + [...result.files], + [ + ['apple.txt', { template: 'basket', policy: 'birth-only' }], + ['pear.txt', { template: 'basket', policy: 'birth-only' }], + ], + ); +}); + +test('an item whose path renders empty is skipped, as any file whose name renders empty is', () => { + const manifest = + 'name: basket\nreads:\n fruits:\neach:\n "{% if _item.ripe %}{{ _item.name }}.txt{% endif %}.jinja": fruits\n'; + const result = render([template(manifest, { '{% if _item.ripe %}{{ _item.name }}.txt{% endif %}.jinja': 'ripe' })], { + fruits: [ + { name: 'apple', ripe: true }, + { name: 'pear', ripe: false }, + ], + }); + assert.deepEqual(result.errors, []); + assert.deepEqual(listing(result.tree), { 'apple.txt': 'ripe' }); +}); + +test('the list may be a read that a given answer supplies', () => { + const manifest = 'name: basket\nreads:\n fruits:\neach:\n "{{ _item }}.txt.jinja": fruits\n'; + const result = render([template(manifest, { '{{ _item }}.txt.jinja': '{{ _item }}' })], { fruits: ['apple'] }); + assert.deepEqual(result.errors, []); + assert.deepEqual(listing(result.tree), { 'apple.txt': 'apple' }); +}); + +test('a file not listed under each sees no _item', () => { + const result = render([template(fruits, { ...file, 'plain.txt.jinja': '{{ _item }}' })], { fruits: [] }); + assert.equal(result.errors.length, 1); + assert.match(result.errors[0]?.message ?? '', /_item/); + assert.equal(result.errors[0]?.path, 'files/plain.txt.jinja'); +}); + +test('two items that render to one path are an error naming the source', () => { + const manifest = 'name: basket\nreads:\n fruits:\neach:\n "fruit.txt.jinja": fruits\n'; + const result = render([template(manifest, { 'fruit.txt.jinja': '{{ _item }}' })], { fruits: ['apple', 'pear'] }); + assert.equal(result.errors.length, 1); + assert.match(result.errors[0]?.message ?? '', /both render to fruit\.txt/); +}); + +test('a variable that holds no list is an error naming the file and the variable', () => { + const result = render([template(fruits, file)], { fruits: { name: 'apple' } }); + assert.deepEqual( + result.errors.map(({ path, message }) => ({ path, message })), + [{ path: 'files/{{ _item.name }}.txt.jinja', message: 'each names fruits, which holds no list' }], + ); +}); + +test('each names a variable of the template’s scope: one it neither asks nor reads is an error of the manifest', () => { + const manifest = 'name: basket\neach:\n "{{ _item }}.txt.jinja": fruits\n'; + const result = render([template(manifest, { '{{ _item }}.txt.jinja': '' })], { fruits: ['apple'] }); + assert.deepEqual( + result.errors.map(({ path, message }) => ({ path, message })), + [ + { + path: 'template.yml', + message: 'each names fruits for {{ _item }}.txt.jinja, which the template neither asks nor reads', + }, + ], + ); +}); + +test('each names files below files/, each by a variable name', () => { + for (const [manifest, message] of [ + ['name: basket\nreads:\n fruits:\neach: [a.txt]\n', /each is a map/], + [ + 'name: basket\nreads:\n fruits:\neach:\n missing.txt: fruits\n', + /each names missing\.txt, which is no file below files\//, + ], + [ + 'name: basket\nreads:\n fruits:\neach:\n a.txt: "{{ fruits }}"\n', + /each names a\.txt by \{\{ fruits \}\}, which is no variable name/, + ], + ] as const) { + const result = render([template(manifest, { 'a.txt': 'a' })], { fruits: ['apple'] }); + assert.equal(result.errors.length, 1, manifest); + assert.match(result.errors[0]?.message ?? '', message); + assert.equal(result.errors[0]?.path, 'template.yml'); + } +}); From 982338d5724feeb5e339f13bc174b81d54b1ee0e Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 10:34:23 +0100 Subject: [PATCH 02/21] plx-template renders a file once per item of a list: each, with _item A template's manifest names under each, by source path, a variable of its scope that holds a list; the file is rendered once per item with _item bound. The environment files of a stack and the promotion workflow of each environment are one file per declared environment. Co-Authored-By: Claude Opus 5.5 --- packages/cli-template/src/each.test.ts | 7 +++- packages/cli-template/src/files.ts | 57 ++++++++++++++++++-------- packages/cli-template/src/manifest.ts | 42 +++++++++++++++---- packages/cli-template/src/render.ts | 3 +- packages/cli-template/src/types.ts | 5 +++ 5 files changed, 87 insertions(+), 27 deletions(-) diff --git a/packages/cli-template/src/each.test.ts b/packages/cli-template/src/each.test.ts index 1bca4b9c..92cc1dbb 100644 --- a/packages/cli-template/src/each.test.ts +++ b/packages/cli-template/src/each.test.ts @@ -29,7 +29,12 @@ test('an empty list renders the file nowhere', () => { test('the policy of the source applies to every path it renders to', () => { const manifest = `${fruits}policies:\n "{{ _item.name }}.txt.jinja": birth-only\n`; - const result = render([template(manifest, file)], { fruits: [{ name: 'apple' }, { name: 'pear' }] }); + const result = render([template(manifest, file)], { + fruits: [ + { name: 'apple', colour: 'red' }, + { name: 'pear', colour: 'green' }, + ], + }); assert.deepEqual(result.errors, []); assert.deepEqual( [...result.files], diff --git a/packages/cli-template/src/files.ts b/packages/cli-template/src/files.ts index 73fb24eb..35b7e315 100644 --- a/packages/cli-template/src/files.ts +++ b/packages/cli-template/src/files.ts @@ -19,6 +19,12 @@ // 0o755, as types.ts states. A file whose Jinja fails is an error naming its // path in the template; where it reads a variable nothing gives, the error names it. // +// A file the manifest lists under `each` is rendered once per item of the list +// its variable holds, with `_item` bound to the item in its name and its text, +// each rendering a file of its own at the path its name renders to; an empty +// list renders it nowhere, and a variable that holds no list is an error +// naming the file. Its policy is the source's, for every path. +// // The templates of a render land in one tree, and every path is written once, // by one template. Two sources that render to one path are an error naming // both, a file beside its `.jinja` sibling included, as is a file with another @@ -38,7 +44,7 @@ // (manifest.ts). import { messageOf } from './errors.ts'; import { type Context, renderString, usedVariables } from './jinja.ts'; -import { FILES, type Template } from './manifest.ts'; +import { FILES, ITEM_VARIABLE, type Template } from './manifest.ts'; import { DIRECTORY, type Entry, fileMode, isExecutable, MODE_TYPE, REGULAR, type RenderError } from './types.ts'; /** A rendered entry, with the template and the path below `files/` it came from. */ @@ -166,9 +172,9 @@ function renderTemplate( used: Set, ): Map { // Every Jinja source rendered, a file's text or a part of its path, adds the names it reads to `used`. - const show = (source: string): string => { + const show = (source: string, scope: Context = context): string => { for (const name of usedVariables(source)) used.add(name); - return renderString(source, context); + return renderString(source, scope); }; const fail = (source: string, message: string): 'failed' => { errors.push({ template: template.manifest.name, path: `${FILES}${source}`, message }); @@ -176,11 +182,11 @@ function renderTemplate( }; // Where the source name `name`, which is the last part of `source`, lands below the rendered directory `parent`. - const locate = (parent: Location, name: string, source: string): Location => { + const locate = (parent: Location, name: string, source: string, scope: Context = context): Location => { if (typeof parent === 'string') return 'skipped'; let part: string; try { - part = show(name); + part = show(name, scope); } catch (error) { return fail(source, `error rendering template path ${source}: ${messageOf(error)}`); } @@ -203,6 +209,27 @@ function renderTemplate( return located; }; + // A file of the source `source`, landing under `name` below its directory, rendered in `scope`. + const renderFile = (source: string, entry: Entry, name: string, isTemplate: boolean, scope: Context): void => { + const located = locate(directoryOf(parentOf(source)), name, source, scope); + if (typeof located === 'string') return; + const path = located.path; + if (path === '') { + fail(source, `${source} renders to the output's root, which is no file`); + return; + } + const text = isTemplate ? textOf(entry.bytes) : undefined; + if (text === undefined) { + put(path, { entry: written(entry.bytes, entry.mode), source, owner: template }); + return; + } + try { + put(path, { entry: written(encoder.encode(show(text, scope)), entry.mode), source, owner: template }); + } catch (error) { + fail(source, messageOf(error)); + } + }; + for (const [source, entry] of template.files) { if ((entry.mode & MODE_TYPE) === DIRECTORY) { directoryOf(source); @@ -214,23 +241,17 @@ function renderTemplate( continue; } const name = isTemplate ? nameOf(source).slice(0, -SUFFIX.length) : nameOf(source); - const located = locate(directoryOf(parentOf(source)), name, source); - if (typeof located === 'string') continue; - const path = located.path; - if (path === '') { - fail(source, `${source} renders to the output's root, which is no file`); + const list = template.manifest.each.get(source); + if (list === undefined) { + renderFile(source, entry, name, isTemplate, context); continue; } - const text = isTemplate ? textOf(entry.bytes) : undefined; - if (text === undefined) { - put(path, { entry: written(entry.bytes, entry.mode), source, owner: template }); + const items = context[list]; + if (!Array.isArray(items)) { + fail(source, `each names ${list}, which holds no list`); continue; } - try { - put(path, { entry: written(encoder.encode(show(text)), entry.mode), source, owner: template }); - } catch (error) { - fail(source, messageOf(error)); - } + for (const item of items) renderFile(source, entry, name, isTemplate, { ...context, [ITEM_VARIABLE]: item }); } // Directories at one path are one, and the first source names it. diff --git a/packages/cli-template/src/manifest.ts b/packages/cli-template/src/manifest.ts index 025461e6..ec75e455 100644 --- a/packages/cli-template/src/manifest.ts +++ b/packages/cli-template/src/manifest.ts @@ -15,7 +15,7 @@ // beside the manifest and not below `files/`, so that no file a template // renders can be it. A template without the file has no variables. // -// The manifest is YAML, a map of five keys, of which only `name` is required: +// The manifest is YAML, a map of six keys, of which only `name` is required: // // name: fruit-basket # lowercase letters, digits and hyphens, from a letter // questions: # the answers this template owns, in the order they resolve @@ -32,13 +32,16 @@ // size: {default: small} # optional: the default when nothing supplies it // policies: # by source path below files/, as written there // "notes.md.jinja": born-once # merge (every path not listed), born-once or birth-only +// each: # by source path below files/, as written there: the file +// "{{ _item }}.md.jinja": fruits # is rendered once per item of the list the variable holds // birth: # commands for whoever creates a directory from the // - [git, init] # template, each an argument vector; never run here // // What a question's fields mean when its answer is resolved is questions.ts's. // The reader checks the shape: every key known, every value of its kind, every -// policy naming a file below `files/`, no read of a question the template owns -// itself. Names starting with `_` are left to the engine's own variables. Each +// policy and every `each` naming a file below `files/`, every `each` a question +// or read of the template's own or an engine variable, no read of a question the +// template owns itself. Names starting with `_` are left to the engine's own variables. Each // problem is an error of the render naming `template.yml`, the template, and // the question or read where there is one; the reader reports all of them, and // a template with any is not rendered. Until its name is read, a template is @@ -76,15 +79,19 @@ export const FILES = 'files/'; /** Where a template's tree holds its variables. */ export const VARIABLES = 'variables.json'; -const KEYS = ['name', 'questions', 'reads', 'policies', 'birth']; +const KEYS = ['name', 'questions', 'reads', 'policies', 'each', 'birth']; const FIELDS = ['type', 'default', 'help', 'when', 'validator', 'choices']; const TYPES: readonly string[] = ['str', 'int', 'float', 'bool', 'yaml', 'json'] satisfies QuestionType[]; const POLICIES: readonly string[] = ['merge', 'born-once', 'birth-only'] satisfies Policy[]; /** What a template is called: lowercase letters, digits and hyphens, from a letter. */ export const TEMPLATE_NAME = /^[a-z][a-z0-9-]*$/; const VARIABLE = /^[A-Za-z][A-Za-z0-9_]*$/; +/** The name of an engine variable: `_`, then a letter, then letters, digits and `_`. */ +const ENGINE_VARIABLE = /^_[A-Za-z][A-Za-z0-9_]*$/; /** The one variable the engine makes itself, the names of the templates rendered together. */ export const TEMPLATES_VARIABLE = '_templates'; +/** The variable the engine binds to the item a file listed under `each` is rendered for. */ +export const ITEM_VARIABLE = '_item'; const utf8 = new TextDecoder('utf-8', { fatal: true }); @@ -118,10 +125,11 @@ export function readTemplate(tree: Tree, position: number, errors: RenderError[] const questions = readQuestions(data.questions, doc, problem); const reads = readReads(data.reads, questions, problem); const policies = readPolicies(data.policies, files, problem); + const each = readEach(data.each, files, [...questions, ...reads], problem); const birth = readBirth(data.birth, problem); const variables = readVariables(tree, problem); if (failed) return undefined; - return { manifest: { name: template, questions, reads, policies, birth }, files, variables }; + return { manifest: { name: template, questions, reads, policies, each, birth }, files, variables }; } /** The variables of the tree's `variables.json`, none where it has none; its problems go to `problem`. */ @@ -140,9 +148,9 @@ function readVariables(tree: Tree, problem: Problem): Record { return {}; } for (const name of Object.keys(data)) { - if (!name.startsWith('_') || name === TEMPLATES_VARIABLE) + if (!name.startsWith('_') || name === TEMPLATES_VARIABLE || name === ITEM_VARIABLE) problem( - name === TEMPLATES_VARIABLE + name === TEMPLATES_VARIABLE || name === ITEM_VARIABLE ? `${VARIABLES} names \`${name}\`, which is the engine's own` : `${VARIABLES} names \`${name}\`, and the names of variables start with \`_\``, undefined, @@ -261,6 +269,26 @@ function readPolicies(value: unknown, files: Tree, problem: Problem): Map { + const each = new Map(); + for (const [path, name] of section(value, 'each', problem)) { + const entry = files.get(path); + if (entry === undefined || (entry.mode & MODE_TYPE) !== REGULAR) + problem(`each names ${path}, which is no file below ${FILES}`); + else if (typeof name !== 'string' || !(VARIABLE.test(name) || ENGINE_VARIABLE.test(name))) + problem(`each names ${path} by ${String(name)}, which is no variable name`); + else if (!name.startsWith('_') && !scope.some((s) => s.name === name)) + problem(`each names ${name} for ${path}, which the template neither asks nor reads`); + else each.set(path, name); + } + return each; +} + function readBirth(value: unknown, problem: Problem): string[][] { if (value === undefined || value === null) return []; if (!Array.isArray(value)) { diff --git a/packages/cli-template/src/render.ts b/packages/cli-template/src/render.ts index 5edbddf5..5a980bc5 100644 --- a/packages/cli-template/src/render.ts +++ b/packages/cli-template/src/render.ts @@ -64,7 +64,8 @@ // forbids for questions and reads. `_templates` is the names of the templates // rendered together, sorted by name so that it does not depend on the order // given, for a file that is written only when another template is present -// (`{% if 'shelf' in _templates %}`). The others are the template's own: the +// (`{% if 'shelf' in _templates %}`). `_item` is the item a file listed under +// `each` is rendered for, which that file alone sees (files.ts). The others are the template's own: the // values of its `variables.json` (manifest.ts), which only that template sees // and which are in no answer and no manifest. The engine knows no name among // them. A variable the template's file lacks is undefined, an error that names diff --git a/packages/cli-template/src/types.ts b/packages/cli-template/src/types.ts index b85b92b1..61ca9ec1 100644 --- a/packages/cli-template/src/types.ts +++ b/packages/cli-template/src/types.ts @@ -132,6 +132,11 @@ export interface Manifest { readonly reads: readonly Read[]; /** By source path below `files/`, as it is written there; a path not listed is `merge`. */ readonly policies: ReadonlyMap; + /** + * By source path below `files/`, as it is written there: the variable whose list the file is rendered once per item + * of, with `_item` bound to the item; a path not listed is rendered once. + */ + readonly each: ReadonlyMap; /** Each an argument vector, its first element the program. */ readonly birth: readonly (readonly string[])[]; } From 7e31cd690ac395927aa1a02035ef095b06066be3 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 10:35:54 +0100 Subject: [PATCH 03/21] Test: a stack is born with a file for each declared environment, and a render is given the declaration A newborn repo with a stack and no declaration passes the doctor: its stack is born with no environment file. The stop-gap declaration of the two names the stack template wrote is gone from newSite.test.ts. Co-Authored-By: Claude Opus 5.5 --- packages/lib/src/declaredEnvironments.test.ts | 21 +++++++++ packages/lib/src/newSite.test.ts | 47 +++++++------------ packages/lib/src/stack.test.ts | 46 +++++++++++++----- packages/lib/src/testing/bundled.ts | 8 +++- 4 files changed, 79 insertions(+), 43 deletions(-) diff --git a/packages/lib/src/declaredEnvironments.test.ts b/packages/lib/src/declaredEnvironments.test.ts index d60c6905..e51848ff 100644 --- a/packages/lib/src/declaredEnvironments.test.ts +++ b/packages/lib/src/declaredEnvironments.test.ts @@ -8,6 +8,7 @@ import { environmentBranch, environmentOfBranch, readDeclaredEnvironments, + templateAnswers, } from './declaredEnvironments.ts'; import { fakeIo, type Tree } from './testing/fakeIo.ts'; @@ -166,3 +167,23 @@ test('a refusal says the repo declares no environment and where one is declared, assert.equal(invalid, 'the `environments` of the root marker are invalid: `b` has no `promotes_from`'); assert.doesNotMatch(String(invalid), /env\//); }); + +test('a render is given the declaration as declared_environments: each environment with its branch, its source and whether it promotes itself, in the order written', () => { + const answers = { tenant: 'acme', environments: TWO }; + assert.deepEqual(templateAnswers(answers), { + ...answers, + declared_environments: [ + { name: 'staging', branch: 'env/staging', source: 'main', auto_promote: true }, + { name: 'production', branch: 'env/production', source: 'env/staging', auto_promote: false }, + ], + }); +}); + +test('no declaration, an empty one and an invalid one give a render no environment', () => { + for (const environments of [undefined, null, {}, { staging: { promotes_from: 'nowhere' } }, 'staging']) + assert.deepEqual(templateAnswers({ environments }).declared_environments, [], JSON.stringify(environments)); +}); + +test('declared_environments is computed and never answered: a given value is replaced', () => { + assert.deepEqual(templateAnswers({ declared_environments: [{ name: 'qa' }] }).declared_environments, []); +}); diff --git a/packages/lib/src/newSite.test.ts b/packages/lib/src/newSite.test.ts index e48e5c10..311466e8 100644 --- a/packages/lib/src/newSite.test.ts +++ b/packages/lib/src/newSite.test.ts @@ -321,24 +321,17 @@ test('a directory inside a repo whose root has no marker is a new repo of its ow // The two sites the verb exists for, from the bundled templates. const bundled = createRequire(import.meta.url)('../package.json') as { version: string }; -/** - * The `stack` template writes `production.yaml` and `staging.yaml` by name while the repo declares no environment, - * so a newborn with a stack fails `PLX-Stack/FileNamesDeclared`: the repos that must pass the doctor declare the - * two names. The stack template is to render the files from the declaration, which removes this. - */ -const FILE_ENVIRONMENTS = { staging: { promotes_from: 'main' }, production: { promotes_from: 'staging' } }; - /** * A newborn of repo-turbo with updates beside it, named `shop`, its birth faked and git made by hand: the app finds its - * repo by git. It declares the two environments of the stack template's files, unless `declared` is false. + * repo by git. It declares no environment. */ -async function bornTurbo(declared = true) { +async function bornTurbo() { const target = scratch.fresh('turbo'); const { ctx, ran } = recording(); const created = await newSite(ctx, { dir: target, templates: ['repo-turbo', 'updates'], - answers: { tenant: 'acme', repo: 'shop', ...(declared ? { environments: FILE_ENVIRONMENTS } : {}) }, + answers: { tenant: 'acme', repo: 'shop' }, plxVersion: bundled.version, root: templatesRoot(), }); @@ -367,13 +360,13 @@ async function doctorOf(target: string): Promise<{ findings: string[]; units: nu } } -test('a repo from repo-turbo with updates beside it, an app from app-nextjs and a stack from stack in it: the trees and the markers, and the newborn repo that declares the stack files’ two environments passes the doctor', async () => { +test('a repo from repo-turbo with updates beside it, an app from app-nextjs and a stack from stack in it: the trees and the markers, and the newborn repo that declares no environment passes the doctor', async () => { const { target, ran, created: repo } = await bornTurbo(); assert.equal(repo.kind, 'repo'); + // Without an environment nothing deploys, so there is no workflow of the environments' branches. assert.deepEqual(repo.files, [ '.github/workflows/on_commit.yml', '.github/workflows/on_pr.yml', - '.github/workflows/on_push.yml', '.github/workflows/plx-update.yml', '.gitignore', 'PLEXUS.md', @@ -429,7 +422,7 @@ test('a repo from repo-turbo with updates beside it, an app from app-nextjs and ]); const stack = await nested(join(target, 'stack'), ['stack'], { apps: 'web' }); - assert.deepEqual(stack.files, ['PLEXUS.md', 'compose.yaml', 'production.yaml', 'staging.yaml']); + assert.deepEqual(stack.files, ['PLEXUS.md', 'compose.yaml']); assert.match(text(target, 'stack/PLEXUS.md'), /^---\ntemplates: \[stack\]\nprofile: stateless\n---\n\n/); assert.match( text(target, 'stack/compose.yaml'), @@ -441,7 +434,7 @@ 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 () => { +test('a repo born with environments holds the declaration in its marker, read back as given; its stack is born with a file for each, and it passes the doctor', async () => { const environments = { staging: { promotes_from: 'main', auto_promote: true }, production: { promotes_from: 'staging' }, @@ -465,28 +458,24 @@ test('a repo born with environments holds the declaration in its marker, read ba ['env/production', 'env/staging', false], ], ); + // Nothing computed from the declaration is written into the marker: it is computed again for every render. + assert.doesNotMatch(text(target, 'PLEXUS.md'), /declared_environments/); 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'), - }); + const stack = await nested(join(target, 'stack'), ['stack'], { apps: 'web' }); + assert.deepEqual(stack.files, ['PLEXUS.md', 'compose.yaml', 'production.yaml', 'staging.yaml']); + assert.doesNotMatch(text(target, 'stack/PLEXUS.md'), /declared_environments/); 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') }); + write(target, { 'stack/qa.yaml': 'host: 192.0.2.3\nhostname: qa.shop.example.com\n' }); assert.deepEqual((await doctorOf(target)).findings.length, 1); }); -test('a newborn repo with a stack and no declaration fails the doctor for both files the stack template writes', async () => { - const { target } = await bornTurbo(false); +test('a newborn repo with a stack and no declaration passes the doctor: its stack is born with no environment file', async () => { + const { target } = await bornTurbo(); await nested(join(target, 'apps', 'web'), ['app-nextjs'], { name: 'web' }); - await nested(join(target, 'stack'), ['stack'], { apps: 'web' }); - assert.deepEqual( - (await doctorOf(target)).findings.map((f) => f.replace(/ names the environment.*/, '')), - ['.: stack/production.yaml', '.: stack/staging.yaml'], - ); - assert.ok((await doctorOf(target)).findings.every((f) => f.includes('does not declare under `environments`'))); + const stack = await nested(join(target, 'stack'), ['stack'], { apps: 'web' }); + assert.deepEqual(stack.files, ['PLEXUS.md', 'compose.yaml']); + assert.deepEqual((await doctorOf(target)).findings, []); }); test('a stateful stack whose app carries the migration passes the doctor as born', async () => { diff --git a/packages/lib/src/stack.test.ts b/packages/lib/src/stack.test.ts index b33ec640..f52fc73b 100644 --- a/packages/lib/src/stack.test.ts +++ b/packages/lib/src/stack.test.ts @@ -3,8 +3,11 @@ import { test } from 'node:test'; import { parse } from 'yaml'; import { generatedFrom, pathsOf, renderBundled, textOf } from './testing/bundled.ts'; +/** The environments of the enclosing repo, which the root marker declares: none of them named as a tool would know it. */ +const DECLARED = { qa: { promotes_from: 'main', auto_promote: true }, live: { promotes_from: 'qa' } }; + const render = (answers: Record = {}) => - renderBundled(['stack'], { tenant: 'acme', apps: 'shop', ...answers }); + renderBundled(['stack'], { tenant: 'acme', apps: 'shop', environments: DECLARED, ...answers }); /** The services of the rendered compose file. */ const servicesOf = async (answers: Record = {}) => { @@ -16,10 +19,10 @@ const servicesOf = async (answers: Record = {}) => { const TAGGED = (app: string) => `ghcr.io/acme/${app}:\${PLEXUS_TAG:?set by the deploy}`; const LOOPBACK = '127.0.0.1:${PLEXUS_LOOPBACK_PORT:?set by the platform playbook}:3000'; -test('a stack is its compose file, its marker and a file for each environment the branches deploy, all its own from birth, with nothing run at birth', async () => { +test('a stack is its compose file, its marker and a file for each environment the repo declares, all its own from birth, with nothing run at birth', async () => { const result = await render(); assert.deepEqual(result.errors, []); - assert.deepEqual(pathsOf(result), ['PLEXUS.md', 'compose.yaml', 'production.yaml', 'staging.yaml']); + assert.deepEqual(pathsOf(result), ['PLEXUS.md', 'compose.yaml', 'live.yaml', 'qa.yaml']); // The compose file and the marker are never re-synced; an environment's file is written at a birth alone, so that an // update adds none to a stack that was born before the template had it. for (const [path, origin] of result.files) @@ -27,6 +30,14 @@ test('a stack is its compose file, its marker and a file for each environment th assert.deepEqual(result.birth, []); }); +test('a stack of a repo that declares no environment, or whose declaration is invalid, is born with no environment file', async () => { + for (const environments of [{}, undefined, { qa: { promotes_from: 'nowhere' } }]) { + const result = await render({ environments }); + assert.deepEqual(result.errors, []); + assert.deepEqual(pathsOf(result), ['PLEXUS.md', 'compose.yaml'], JSON.stringify(environments)); + } +}); + test('the profile is stateless unless the stack says stateful, and the apps are kept in no answer', async () => { assert.deepEqual((await render()).answers, { profile: 'stateless' }); assert.deepEqual((await render({ profile: 'stateful' })).answers, { profile: 'stateful' }); @@ -131,7 +142,7 @@ test('the compose file and the environment files say they were generated once an const lines = generatedFrom(await render()); assert.deepEqual( lines.map(([path]) => path), - ['compose.yaml', 'production.yaml', 'staging.yaml'], + ['compose.yaml', 'live.yaml', 'qa.yaml'], ); for (const [, line] of lines) assert.match(line, /^# Generated from plexus-ms\/tooling, templates\/stack, once:/); }); @@ -140,25 +151,36 @@ test('the compose file and the environment files say they were generated once an const environmentOf = async (name: string, answers: Record = {}) => parse(textOf(await render(answers), `${name}.yaml`)) as Record; -test('an environment file names the four keys: the host to replace, a hostname for the first app, no values and no secrets yet', async () => { +test('an environment file names the four keys: the host to replace, a hostname for the first app in that environment, no values and no secrets yet', async () => { for (const [name, hostname] of [ - ['production', 'shop.example.com'], - ['staging', 'shop.staging.example.com'], + ['live', 'shop.live.example.com'], + ['qa', 'shop.qa.example.com'], ] as const) assert.deepEqual(await environmentOf(name), { host: 'host.example.com', hostname, env: {}, secrets: {} }, name); // The first of several apps publishes the port, so it names the stack's hostname. - assert.equal((await environmentOf('staging', { apps: 'admin,shop' })).hostname, 'admin.staging.example.com'); + assert.equal((await environmentOf('qa', { apps: 'admin,shop' })).hostname, 'admin.qa.example.com'); +}); + +test('each environment file says which environment it is, by the name the repo declares', async () => { + const result = await render(); + for (const name of ['live', 'qa']) + assert.match( + textOf(result, `${name}.yaml`), + new RegExp(`^# Generated .*: the environment \`${name}\` of this stack`, 'm'), + ); }); test('a stack of no app has no hostname to name, for it has no port: its environment files hold the host alone', async () => { - const result = await renderBundled(['stack'], { tenant: 'acme' }); - for (const name of ['production', 'staging']) + const result = await renderBundled(['stack'], { tenant: 'acme', environments: DECLARED }); + for (const name of ['live', 'qa']) assert.deepEqual(parse(textOf(result, `${name}.yaml`)), { host: 'host.example.com', env: {}, secrets: {} }, name); }); -test('the marker says where an environment’s host, hostname, values and secrets go, and that a new environment is a new file', async () => { +test('the marker says where an environment’s host, hostname, values and secrets go, and that a new environment is a new file written by hand', async () => { const marker = textOf(await render(), 'PLEXUS.md'); - assert.match(marker, /`production\.yaml`/); + assert.match(marker, /`\.yaml`/); + assert.match(marker, /written by hand/); + assert.doesNotMatch(marker, /production|staging/); assert.match(marker, /`host`/); assert.match(marker, /`op:\/\/`/); }); diff --git a/packages/lib/src/testing/bundled.ts b/packages/lib/src/testing/bundled.ts index f9066fc1..526b3d80 100644 --- a/packages/lib/src/testing/bundled.ts +++ b/packages/lib/src/testing/bundled.ts @@ -2,17 +2,21 @@ // and handed to the engine. Not shipped (excluded in tsconfig). import { join } from 'node:path'; import { type Answers, type RenderResult, readTree, render, type Tree } from '@plexus-ms/cli-template'; +import { templateAnswers } from '../declaredEnvironments.ts'; import { templatesRoot } from '../templatesRoot.ts'; import { VARIABLES_FILE, variablesText } from '../templateVersion.ts'; import { CURRENT } from './before.ts'; -/** The templates `trees`, rendered together with `answers`, each carrying a variables file of the Plexus `version`, by default the one this workspace's packages are. */ +/** + * The templates `trees`, rendered together with `answers` as plx gives them (`templateAnswers`), each carrying a + * variables file of the Plexus `version`, by default the one this workspace's packages are. + */ export const renderAt = (trees: readonly Tree[], answers: Answers, version = CURRENT): RenderResult => render( trees.map((tree) => new Map(tree).set(VARIABLES_FILE, { bytes: Buffer.from(variablesText(version)), mode: 0o100644 }), ), - answers, + templateAnswers(answers), ); /** The bundled templates `names`, rendered together with `answers`, at the Plexus `version` their variables file names. */ From 634079975749d0f367eb52997c90e9618eb53a21 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 10:37:46 +0100 Subject: [PATCH 04/21] A stack is born with a file for each declared environment; every render is given the declaration templateAnswers adds declared_environments, each environment's name, branch, source and auto_promote, to the answers of every render plx makes (new, apply, update, doctor): no template spells a branch. The stack template renders one environment file per item, birth-only, so a newborn repo with a stack and no declaration passes the doctor. Co-Authored-By: Claude Opus 5.5 --- packages/lib/src/declaredEnvironments.ts | 26 +++++++++++++++++++ packages/lib/src/index.ts | 1 + packages/lib/src/newSite.ts | 14 ++++++++-- packages/lib/src/siteTemplates.ts | 6 +++-- packages/lib/src/sync.test.ts | 5 ++-- packages/lib/src/sync.ts | 11 +++++--- packages/lib/src/testing/bundled.ts | 11 +++++--- templates/stack/files/PLEXUS.md.jinja | 2 +- templates/stack/files/staging.yaml.jinja | 9 ------- ...yaml.jinja => {{ _item.name }}.yaml.jinja} | 4 +-- templates/stack/template.yml | 15 +++++++---- 11 files changed, 74 insertions(+), 30 deletions(-) delete mode 100644 templates/stack/files/staging.yaml.jinja rename templates/stack/files/{production.yaml.jinja => {{ _item.name }}.yaml.jinja} (73%) diff --git a/packages/lib/src/declaredEnvironments.ts b/packages/lib/src/declaredEnvironments.ts index 6173e8d1..fabec0d9 100644 --- a/packages/lib/src/declaredEnvironments.ts +++ b/packages/lib/src/declaredEnvironments.ts @@ -25,6 +25,14 @@ // `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. +// +// A template reads the declaration as plx computes it, never the raw answer: +// `templateAnswers` gives every render the answer `declared_environments`, a +// list of each environment's `name`, `branch`, `source` and `auto_promote`, in +// the order written, and empty where the declaration is invalid, so that no +// template spells a branch and a repo whose declaration is invalid renders no +// branch at all. It is computed for every render and never written into a +// marker; a value given for it is replaced. import { join } from 'node:path'; import { isMapping } from './compose.ts'; import type { Context } from './context.ts'; @@ -67,6 +75,24 @@ 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 answer a render is given the declaration under (`templateAnswers`). */ +export const DECLARED_ENVIRONMENTS_KEY = 'declared_environments'; + +/** The answers a render is given: `answers` with the declaration of their `environments`, as the header says. */ +export function templateAnswers>(answers: T): T & Record { + const declared = declareEnvironments(answers[ENVIRONMENTS_KEY]); + const environments = + declared.problems.length > 0 + ? [] + : declared.environments.map(({ name, branch, source, autoPromote }) => ({ + name, + branch, + source, + auto_promote: autoPromote, + })); + return { ...answers, [DECLARED_ENVIRONMENTS_KEY]: environments }; +} + /** The branches of a valid declaration for a refusal, joined by `joiner`. */ export const describeBranches = (declared: DeclaredEnvironments, joiner: 'and' | 'or'): string => declared.environments.map((e) => e.branch).join(` ${joiner} `); diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index 169330c0..44893f14 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -45,6 +45,7 @@ export { environmentBranch, environmentOfBranch, readDeclaredEnvironments, + templateAnswers, } from './declaredEnvironments.ts'; export { type DeployOptions, diff --git a/packages/lib/src/newSite.ts b/packages/lib/src/newSite.ts index 532991c2..a66c561e 100644 --- a/packages/lib/src/newSite.ts +++ b/packages/lib/src/newSite.ts @@ -22,7 +22,11 @@ // question of the app's templates that the root answers, which would // stand in two markers. Every template that cannot be read is reported // together, and that stops the run; only when all are read are the -// render errors, all of them, reported together. +// render errors, all of them, reported together. The render is given +// the declaration of the environments as every render is +// (`templateAnswers`, declaredEnvironments.ts), computed from the +// answers a first render resolved, since `-a` gives a structured +// answer as text that the engine casts. // 4. Write the tree, then the marker's frontmatter into the file the render // produced (`PLEXUS.md`; a render without one is refused, as the marker // is where the answers go). The frontmatter is `version`, for a repo @@ -51,6 +55,7 @@ import type { Answers, Manifest } from '@plexus-ms/cli-template'; import { versionRefusal } from './apply.ts'; import { readTemplate } from './bundled.ts'; import type { Context } from './context.ts'; +import { templateAnswers } from './declaredEnvironments.ts'; import { describe, run } from './effects.ts'; import { engine } from './engine.ts'; import { MARKER_FILE, type MarkerConfig, parseMarkerConfig, setMarkerKeys } from './marker.ts'; @@ -173,7 +178,12 @@ export async function newSite(ctx: Context, options: NewOptions): Promise 0) throw new Error(unreadable.join('\n')); - const result = render(trees, { ...inherited, ...options.answers }); + // The declaration a render is given is computed from the answers as the templates resolve them, which a first render + // casts: `-a` gives a structured answer as text. + const answers = { ...inherited, ...options.answers }; + const resolved = render(trees, templateAnswers(answers)); + const result = + resolved.errors.length > 0 ? resolved : render(trees, templateAnswers({ ...answers, ...resolved.answers })); if (result.errors.length > 0) throw new Error(result.errors.map((e) => describeError(dir, e)).join('\n')); const own = Object.keys(result.answers).filter((key) => inherited && Object.hasOwn(inherited, key)); if (own.length > 0) diff --git a/packages/lib/src/siteTemplates.ts b/packages/lib/src/siteTemplates.ts index a226d33e..45a4d768 100644 --- a/packages/lib/src/siteTemplates.ts +++ b/packages/lib/src/siteTemplates.ts @@ -50,6 +50,7 @@ import { readdir } from 'node:fs/promises'; import { join } from 'node:path'; import type { render, Tree } from '@plexus-ms/cli-template'; import { readTemplate } from './bundled.ts'; +import { templateAnswers } from './declaredEnvironments.ts'; import { engine } from './engine.ts'; import { MARKER_FILE } from './marker.ts'; import { type MarkerSite, siteAnswers } from './sites.ts'; @@ -139,8 +140,9 @@ function judge( const root = dir === '.'; const mine = [...new Set(listed(site))]; if (!config || (root ? everywhere.length === 0 : mine.length === 0)) continue; - const given = answersOf(sites, dir, rootAnswers); - if (!given) continue; + const marked = answersOf(sites, dir, rootAnswers); + if (!marked) continue; + const given = templateAnswers(marked); const own = mine.length > 0 ? bundled.render(trees(mine), given) : undefined; for (const { question, template, message } of own?.errors ?? []) { if (question === undefined) continue; diff --git a/packages/lib/src/sync.test.ts b/packages/lib/src/sync.test.ts index ebb074a2..79b21d2b 100644 --- a/packages/lib/src/sync.test.ts +++ b/packages/lib/src/sync.test.ts @@ -59,9 +59,10 @@ test("planSync renders a side by that side's own render, the root first and its { dir: 'apps/x', old: crate, new: crate }, { dir: '.', old: basket, new: basket }, ]); + // Every render is given the declaration of the environments, computed, here of none. assert.deepEqual(given, [ - { names: ['basket'], answers: { fruit: 'apple' } }, - { names: ['crate'], answers: { fruit: 'apple', count: 3 } }, + { names: ['basket'], answers: { fruit: 'apple', declared_environments: [] } }, + { names: ['crate'], answers: { fruit: 'apple', count: 3, declared_environments: [] } }, ]); await plan.perform(); assert.equal(text(repo, 'list.txt'), '3 apples\nfresh\n'); diff --git a/packages/lib/src/sync.ts b/packages/lib/src/sync.ts index f0b1e95d..924f8c87 100644 --- a/packages/lib/src/sync.ts +++ b/packages/lib/src/sync.ts @@ -66,6 +66,7 @@ import { join } from 'node:path'; import type { Answers, MergeEntry, MergePlan, RenderError, RenderedSide } from '@plexus-ms/cli-template'; import { loadTemplate, readTemplate } from './bundled.ts'; import type { Context } from './context.ts'; +import { templateAnswers } from './declaredEnvironments.ts'; import { type Plan, write } from './effects.ts'; import { engine } from './engine.ts'; import { MARKER_FILE, removeMarkerKeys, setMarkerKeys } from './marker.ts'; @@ -168,7 +169,10 @@ class Errors { } } -/** The render of a source with `templates`; its problems go to `errors`. */ +/** + * The render of a source with `templates`, given its answers as plx gives every render (`templateAnswers`); its + * problems go to `errors`. + */ async function renderSource( templates: Templates, dir: string, @@ -176,8 +180,9 @@ async function renderSource( label: string, errors: Errors, ): Promise { + const answers = templateAnswers(source.answers); if (templates.render) { - const { rendered, errors: found } = await templates.render(source.templates, source.answers); + const { rendered, errors: found } = await templates.render(source.templates, answers); for (const e of found) errors.add(`${dir}: ${e}`, label); return found.length > 0 ? undefined : rendered; } @@ -191,7 +196,7 @@ async function renderSource( } } if (trees.length < source.templates.length) return undefined; - const result = render(trees, source.answers); + const result = render(trees, answers); for (const e of result.errors) errors.add(describeError(dir, e), label); if (result.errors.length > 0) return undefined; return { tree: result.tree, policies: result.files, answers: result.answers }; diff --git a/packages/lib/src/testing/bundled.ts b/packages/lib/src/testing/bundled.ts index 526b3d80..a569d6f1 100644 --- a/packages/lib/src/testing/bundled.ts +++ b/packages/lib/src/testing/bundled.ts @@ -2,22 +2,25 @@ // and handed to the engine. Not shipped (excluded in tsconfig). import { join } from 'node:path'; import { type Answers, type RenderResult, readTree, render, type Tree } from '@plexus-ms/cli-template'; -import { templateAnswers } from '../declaredEnvironments.ts'; +import { DECLARED_ENVIRONMENTS_KEY, templateAnswers } from '../declaredEnvironments.ts'; import { templatesRoot } from '../templatesRoot.ts'; import { VARIABLES_FILE, variablesText } from '../templateVersion.ts'; import { CURRENT } from './before.ts'; /** * The templates `trees`, rendered together with `answers` as plx gives them (`templateAnswers`), each carrying a - * variables file of the Plexus `version`, by default the one this workspace's packages are. + * variables file of the Plexus `version`, by default the one this workspace's packages are. The declaration plx + * computes is no answer of the person's, so it is not among the unused, as plx reports none of it. */ -export const renderAt = (trees: readonly Tree[], answers: Answers, version = CURRENT): RenderResult => - render( +export function renderAt(trees: readonly Tree[], answers: Answers, version = CURRENT): RenderResult { + const result = render( trees.map((tree) => new Map(tree).set(VARIABLES_FILE, { bytes: Buffer.from(variablesText(version)), mode: 0o100644 }), ), templateAnswers(answers), ); + return { ...result, unused: result.unused.filter((key) => key !== DECLARED_ENVIRONMENTS_KEY) }; +} /** The bundled templates `names`, rendered together with `answers`, at the Plexus `version` their variables file names. */ export async function renderBundled( diff --git a/templates/stack/files/PLEXUS.md.jinja b/templates/stack/files/PLEXUS.md.jinja index 9a0a36a5..ffb09ac4 100644 --- a/templates/stack/files/PLEXUS.md.jinja +++ b/templates/stack/files/PLEXUS.md.jinja @@ -4,7 +4,7 @@ - Born with no app of the repo, its compose file holds `services: {}`, which `plx doctor` reports until the services of the software it runs are written. {%- endif %} - An app joins it by a service whose image is `//:${PLEXUS_TAG:?set by the deploy}`, which loads `.env` and `.env.secret` (optional) and declares a healthcheck; one service of the stack publishes `PLEXUS_LOOPBACK_PORT`. -- Each environment is a file beside the compose file, named after it: `production.yaml` and `staging.yaml` are born with the stack, and a further environment is a further file. +- Each environment is a file beside the compose file, named after it, `.yaml`: one for each environment the root marker declares is born with the stack, and an environment declared later gets its file written by hand, as `plx doctor` asks where no stack has one. Its `host` is where it deploys, `[user@]address[:port]`, and replacing the placeholder is the first thing to do; its `hostname` is the public name the proxy serves, which the service that publishes the loopback port needs. Its `env` holds the plain values the compose file reads, and its `secrets` the same kind of names as `op://` pointers, which the deploy resolves; every environment lists the same names. - A second stack in the repo moves `stack/` to `stacks//` and is created beside it with `plx new stacks/ stack -a apps=`. diff --git a/templates/stack/files/staging.yaml.jinja b/templates/stack/files/staging.yaml.jinja deleted file mode 100644 index 2bd1dd7d..00000000 --- a/templates/stack/files/staging.yaml.jinja +++ /dev/null @@ -1,9 +0,0 @@ -{%- set names = apps.split(',') | map('trim') | reject('equalto', '') | list -%} -# Generated from plexus-ms/tooling, templates/stack, once: the environment `staging` of this stack (PLX-Stack), its own from then on. -# Replace `host` (`[user@]address[:port]`); list the values the compose file reads under `env` and each secret, an `op://` pointer, under `secrets`. -host: host.example.com -{%- if names %} -hostname: {{ names[0] }}.staging.example.com -{%- endif %} -env: {} -secrets: {} diff --git a/templates/stack/files/production.yaml.jinja b/templates/stack/files/{{ _item.name }}.yaml.jinja similarity index 73% rename from templates/stack/files/production.yaml.jinja rename to templates/stack/files/{{ _item.name }}.yaml.jinja index 963c80dd..dc66350b 100644 --- a/templates/stack/files/production.yaml.jinja +++ b/templates/stack/files/{{ _item.name }}.yaml.jinja @@ -1,9 +1,9 @@ {%- set names = apps.split(',') | map('trim') | reject('equalto', '') | list -%} -# Generated from plexus-ms/tooling, templates/stack, once: the environment `production` of this stack (PLX-Stack), its own from then on. +# Generated from plexus-ms/tooling, templates/stack, once: the environment `{{ _item.name }}` of this stack (PLX-Stack), its own from then on. # Replace `host` (`[user@]address[:port]`); list the values the compose file reads under `env` and each secret, an `op://` pointer, under `secrets`. host: host.example.com {%- if names %} -hostname: {{ names[0] }}.example.com +hostname: {{ names[0] }}.{{ _item.name }}.example.com {%- endif %} env: {} secrets: {} diff --git a/templates/stack/template.yml b/templates/stack/template.yml index d97f5e98..a5ec4f14 100644 --- a/templates/stack/template.yml +++ b/templates/stack/template.yml @@ -1,11 +1,13 @@ # One stack (PLX-Stack), rendered at stack/ in a repo with one stack and at stacks// in a repo with several: -# its compose file, its marker and the file of each environment the branches deploy today. +# its compose file, its marker and the file of each environment the repo declares. # Its name is its directory's, or at stack/ the repo's, so no question asks it. name: stack -# The enclosing repo's answer; whoever renders the stack passes it. +# The enclosing repo's answer, and the environments its root marker declares as plx computes them for every render; +# whoever renders the stack passes both. reads: tenant: + declared_environments: questions: profile: @@ -50,8 +52,11 @@ policies: # Every file is the stack's own from birth and never re-synced: the services of the compose file are the # person's, the marker's body is the stack's prose, its frontmatter is plx's, and an environment's file holds the # person's host, values and pointers. An update never adds an environment's file to a stack that was born without - # it: the files are birth-only. + # it, nor plx apply one for an environment declared after the stack's birth: the files are birth-only. PLEXUS.md.jinja: born-once compose.yaml.jinja: born-once - production.yaml.jinja: birth-only - staging.yaml.jinja: birth-only + "{{ _item.name }}.yaml.jinja": birth-only + +# One file for each environment the repo declares, at the stack's birth. +each: + "{{ _item.name }}.yaml.jinja": declared_environments From e8cc6fbe6b4151c870d48404751dd1b9bd7c6116 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 10:44:57 +0100 Subject: [PATCH 05/21] Test the workflows rendered from the declared environments on_push runs on the branch of each declared environment, listed by name, and on_commit on every other branch; a repo without a declaration has no on_push. An environment that promotes itself gets a workflow that fast-forwards its branch with plx promote after a green run on its source, pushed with the App's token. The operations repo deploys the same way. The newborns move off develop and declare their environments. PLX-303 Co-Authored-By: Claude Opus 5.5 --- newborns/app-nextjs.test.ts | 4 +- newborns/deploy-job.test.ts | 10 +- newborns/e2e-playwright.test.ts | 4 +- newborns/helpers.ts | 8 +- newborns/pipeline.test.ts | 19 +-- newborns/repo-operations.test.ts | 9 +- newborns/repo-turbo.test.ts | 56 ++++++- newborns/update-released.test.ts | 24 ++- packages/lib/src/newSite.test.ts | 18 +++ packages/lib/src/operationsPipeline.test.ts | 85 +++++++++-- packages/lib/src/pipeline.test.ts | 158 +++++++++++++++++++- packages/lib/src/repoOperations.test.ts | 8 +- packages/lib/src/testing/shapes.ts | 11 ++ 13 files changed, 342 insertions(+), 72 deletions(-) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index 91b68687..3039a3eb 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -28,6 +28,7 @@ import { born, bornStacks, close, + ENVIRONMENTS, freePort, git, open, @@ -35,7 +36,6 @@ import { plxNew, put, relock, - STACK_FILE_ENVIRONMENTS, sh, start, tryRun, @@ -58,7 +58,7 @@ before(async () => { here = await open('app-nextjs'); repo = await born(join(here, 'acme'), ['repo-turbo', 'updates'], { tenant: 'acme', - environments: STACK_FILE_ENVIRONMENTS, + environments: ENVIRONMENTS, }); for (const profile of PROFILES) await born(join(repo, 'apps', profile), ['app-nextjs'], { diff --git a/newborns/deploy-job.test.ts b/newborns/deploy-job.test.ts index 945073b5..761cfbfb 100644 --- a/newborns/deploy-job.test.ts +++ b/newborns/deploy-job.test.ts @@ -36,7 +36,7 @@ import { createServer, type Server } from 'node:http'; import { basename, join } from 'node:path'; import { after, before, test } from 'node:test'; import { parse } from 'yaml'; -import { born, builtVersion, close, git, open, put, type Ran, sh, tryRun } from './helpers.ts'; +import { born, builtVersion, close, ENVIRONMENTS, git, open, put, type Ran, sh, tryRun } from './helpers.ts'; /** The variable the repo's [env] sets: what the job deploy must not export. */ const VARIABLE = 'PLX_DEPLOY_JOB_PROBE'; @@ -68,7 +68,11 @@ let slotContainer = ''; before(async () => { here = await open('deploy-job'); - repo = await born(join(here, 'web'), ['repo-turbo'], { tenant: 'acme', ci_strategy: 'byom' }); + repo = await born(join(here, 'web'), ['repo-turbo'], { + tenant: 'acme', + ci_strategy: 'byom', + environments: ENVIRONMENTS, + }); // A project for [monorepo].config_roots to match, as the apps of a real repo are: the job repo's step installs by them. put(repo, { 'packages/probe/package.json': { name: '@acme/probe', private: true } }); const workflow = parse(readFileSync(join(repo, '.github', 'workflows', 'on_push.yml'), 'utf8')); @@ -199,7 +203,7 @@ function actionEnv(dir: string, temp: string, inputs: Record): GITHUB_OUTPUT: files.output as string, GITHUB_STATE: files.state as string, GITHUB_REPOSITORY: 'acme/web', - GITHUB_REF: 'refs/heads/develop', + GITHUB_REF: 'refs/heads/env/staging', GITHUB_SHA: '0'.repeat(40), }; } diff --git a/newborns/e2e-playwright.test.ts b/newborns/e2e-playwright.test.ts index 8609b46b..1b956dbb 100644 --- a/newborns/e2e-playwright.test.ts +++ b/newborns/e2e-playwright.test.ts @@ -49,13 +49,13 @@ import { born, bornStacks, close, + ENVIRONMENTS, git, type Launched, launch, open, put, relock, - STACK_FILE_ENVIRONMENTS, sh, tryRun, until, @@ -227,7 +227,7 @@ async function newborn( ): Promise { const dir = await born(join(here, name), ['repo-turbo', 'updates'], { tenant: 'acme', - environments: STACK_FILE_ENVIRONMENTS, + environments: ENVIRONMENTS, ...answers, }); await bornStacks( diff --git a/newborns/helpers.ts b/newborns/helpers.ts index 0e0acd5d..82e37179 100644 --- a/newborns/helpers.ts +++ b/newborns/helpers.ts @@ -408,11 +408,11 @@ export async function born( } /** - * The `stack` template writes `production.yaml` and `staging.yaml` by name while the repo declares no environment, - * so a newborn with a stack fails `PLX-Stack/FileNamesDeclared`: the repos that must pass the doctor declare the - * two names. The stack template is to render the files from the declaration, which removes this. + * The environments of a newborn that deploys, as `plx new -a` gives them: staging, which promotes itself from main, + * and production, promoted by hand from staging. Its stacks are born with a file for each. */ -export const STACK_FILE_ENVIRONMENTS = '{staging: {promotes_from: main}, production: {promotes_from: staging}}'; +export const ENVIRONMENTS = + '{staging: {promotes_from: main, auto_promote: true}, production: {promotes_from: staging}}'; /** * The stacks of a newborn app repo, each created by `plx new` from the template `stack` with its profile and the diff --git a/newborns/pipeline.test.ts b/newborns/pipeline.test.ts index d1b21b1d..3289b054 100644 --- a/newborns/pipeline.test.ts +++ b/newborns/pipeline.test.ts @@ -1,7 +1,7 @@ // A newborn app repo through the job repo of its on_push.yml: the steps as the // rendered workflow lists them, read out of the job's own checkout, each run // here in its order, as a job of the forge (GITHUB_ACTIONS=true) on a push to -// develop, by the walk of jobs.ts. The workflow itself runs only on the forge; +// env/staging, by the walk of jobs.ts. The workflow itself runs only on the forge; // what of a step this file stands in for: // // actions/checkout a fresh clone of the repo's origin at the pushed commit @@ -38,18 +38,7 @@ import { join } from 'node:path'; import { after, before, test } from 'node:test'; import { parse } from 'yaml'; import { type Caches, startCaches } from './caches.ts'; -import { - born, - bornStacks, - close, - freePort, - open, - put, - relock, - STACK_FILE_ENVIRONMENTS, - sh, - tryRun, -} from './helpers.ts'; +import { born, bornStacks, close, ENVIRONMENTS, freePort, open, put, relock, sh, tryRun } from './helpers.ts'; import { type Done, gitOk, of, type Step, walk } from './jobs.ts'; const BROWSERS = join(import.meta.dirname, '..', 'node_modules', '.cache', 'ms-playwright'); @@ -91,7 +80,7 @@ before(async () => { GITHUB_REPOSITORY: 'acme/web', GITHUB_ACTOR: 'a-maintainer', GITHUB_EVENT_NAME: 'push', - GITHUB_REF_NAME: 'develop', + GITHUB_REF_NAME: 'env/staging', // A slot of the runner host names its host's servers and carries their tokens. PLX_TURBO_SHARED: `http://127.0.0.1:${sharedPort}`, PLX_TURBO_SHARED_TOKEN: 'a-shared-token', @@ -107,7 +96,7 @@ before(async () => { tenant: 'acme', repo: 'web', ci_strategy: 'byom', - environments: STACK_FILE_ENVIRONMENTS, + environments: ENVIRONMENTS, }); await born(join(repo, 'apps', 'web'), ['app-nextjs'], { name: '@acme/web' }); await born(join(repo, 'e2e', 'web'), ['e2e-playwright'], { app: '@acme/web' }); diff --git a/newborns/repo-operations.test.ts b/newborns/repo-operations.test.ts index 7a508aca..7cfd9fd1 100644 --- a/newborns/repo-operations.test.ts +++ b/newborns/repo-operations.test.ts @@ -33,12 +33,12 @@ import { born, bornStacks, close, + ENVIRONMENTS, git, mise, open, pass, put, - STACK_FILE_ENVIRONMENTS, sh, tryRun, } from './helpers.ts'; @@ -537,7 +537,7 @@ interface DeployStep { test('the job deploy of a newborn operations repo deploys two stacks of third-party software through its own steps, and one that fails leaves the other deployed', async () => { const dir = await born(join(here, 'deploy-job'), ['repo-operations', 'updates'], { tenant: 'acme', - environments: STACK_FILE_ENVIRONMENTS, + environments: ENVIRONMENTS, }); const root = join(here, 'deploy-run'); const bin = runnerTools(root); @@ -565,7 +565,7 @@ test('the job deploy of a newborn operations repo deploys two stacks of third-pa GITHUB_ACTOR: 'a-maintainer', GITHUB_RUN_ID: '41', GITHUB_EVENT_NAME: 'push', - GITHUB_REF_NAME: 'main', + GITHUB_REF_NAME: 'env/production', RUNNER_TEMP: temp, RUNNER_ENVIRONMENT: 'self-hosted', LOGS: logs, @@ -616,7 +616,8 @@ test('the job deploy of a newborn operations repo deploys two stacks of third-pa /** The verb step of the workflow, run as the forge runs it: its command, and its environment with the input `dry_run` given as `input`. */ const verb = async (input: string) => { - const step = steps.find((s) => /\bplx deploy --environment production$/.test(s.run ?? '')); + // The verb deploys the environment of the branch the run is on, env/production. + const step = steps.find((s) => /\bplx deploy$/.test(s.run ?? '')); assert.ok(step?.run, 'the workflow has the verb step'); const env = envOf(step, { '${{ inputs.dry_run }}': input }); return tryRun('mise', ['exec', '--', ...step.run.split(' ')], dir, { ...jobEnv, ...env }); diff --git a/newborns/repo-turbo.test.ts b/newborns/repo-turbo.test.ts index 565e9b52..d427c1d2 100644 --- a/newborns/repo-turbo.test.ts +++ b/newborns/repo-turbo.test.ts @@ -22,10 +22,11 @@ // mise run newborn # every template // KEEP=1 mise run newborn # leave the newborns in place and say where import assert from 'node:assert/strict'; -import { readFileSync, writeFileSync } from 'node:fs'; +import { readdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { after, before, describe, test } from 'node:test'; -import { born, close, git, mise, open, pass, put, relock, sh, tryRun } from './helpers.ts'; +import { parse } from 'yaml'; +import { born, close, ENVIRONMENTS, git, mise, open, pass, put, relock, sh, tryRun } from './helpers.ts'; let here = ''; before(async () => { @@ -71,10 +72,16 @@ function projects(dir: string, specs: Record parse(read(dir, `.github/workflows/${name}.yml`)); + +/** The workflows of `dir` by file name. */ +const workflows = (dir: string) => readdirSync(join(dir, '.github', 'workflows')).sort(); + describe('an app repo', () => { let dir = ''; before(async () => { - dir = await newborn('app'); + dir = await newborn('app', { environments: ENVIRONMENTS }); }); test('passes its own verbs, and its push workflow writes no tag', async () => { @@ -82,6 +89,49 @@ describe('an app repo', () => { assert.doesNotMatch(read(dir, '.github/workflows/on_push.yml'), /contents: write/); }); + test('runs on_push on the branch of each declared environment and on_commit on every other, and promotes staging from main after a green run there', () => { + const branches = ['env/staging', 'env/production']; + assert.deepEqual(workflow(dir, 'on_push').on.push, { branches }); + assert.deepEqual(workflow(dir, 'on_commit').on.push['branches-ignore'], branches); + assert.deepEqual(workflows(dir), [ + 'on_commit.yml', + 'on_pr.yml', + 'on_push.yml', + 'plx-update.yml', + 'promote-staging.yml', + ]); + const promotion = workflow(dir, 'promote-staging'); + assert.deepEqual(promotion.on.workflow_run, { + workflows: ['on_commit', 'on_push'], + types: ['completed'], + branches: ['main'], + }); + assert.equal(promotion.jobs.promote.steps.at(-1).run, 'plx -y promote staging'); + }); + + test('promoting an environment from another one instead renders the same workflow, with the other two branch names', async () => { + const other = await newborn('promotes-from-staging', { + environments: '{staging: {promotes_from: main}, production: {promotes_from: staging, auto_promote: true}}', + }); + assert.deepEqual(workflows(other), [ + 'on_commit.yml', + 'on_pr.yml', + 'on_push.yml', + 'plx-update.yml', + 'promote-production.yml', + ]); + assert.deepEqual(workflow(other, 'promote-production').on.workflow_run.branches, ['env/staging']); + assert.equal( + read(other, '.github/workflows/promote-production.yml'), + read(dir, '.github/workflows/promote-staging.yml') + .replaceAll('branches: [main]', 'branches: [env/staging]') + .replaceAll('promote-staging', 'promote-production') + .replaceAll('promote staging', 'promote production') + .replaceAll('env/staging to the head of main', 'env/production to the head of env/staging') + .replaceAll('on main, the branch staging promotes from', 'on env/staging, the branch production promotes from'), + ); + }); + test('scopes a verb to a project by name: with what it depends on, e2e with what depends on it, and refuses an unknown name', async () => { // Under packages/, where plx doctor asks nothing of a project, so that a refusal can only be the name's. projects(dir, { diff --git a/newborns/update-released.test.ts b/newborns/update-released.test.ts index 67efe16b..8863810d 100644 --- a/newborns/update-released.test.ts +++ b/newborns/update-released.test.ts @@ -181,29 +181,23 @@ async function repoAt( kind: 'app' | 'package' | 'operations', answers: string[] = [], ): Promise { - const [branch, templates] = - kind === 'operations' - ? ['main', ['repo-operations', 'updates']] - : [kind === 'app' ? 'develop' : 'main', ['repo-turbo', 'updates']]; + // Every repo is on main, its default branch, where an update lands. + const branch = 'main'; + const templates = kind === 'operations' ? ['repo-operations', 'updates'] : ['repo-turbo', 'updates']; if (kind === 'package') answers = ['-a', 'publishes_packages=true', ...answers]; made += 1; const name = `${kind}-${version}-${made}`; const dir = join(here, 'repos', name); const origin = join(here, 'origins', `${name}.git`); - await sh( - 'node', - [plxOf(version), 'new', dir, ...(templates as string[]), '-a', 'tenant=acme', ...answers], - here, - env, - ); + await sh('node', [plxOf(version), 'new', dir, ...templates, '-a', 'tenant=acme', ...answers], here, env); // The forge's default branch is the branch the repo is on, as a forge makes it when a first push creates one. - await sh('git', ['init', '--bare', '--quiet', '--initial-branch', branch as string, origin], here, env); - await sh('git', ['checkout', '-q', '-B', branch as string], dir, env); + await sh('git', ['init', '--bare', '--quiet', '--initial-branch', branch, origin], here, env); + await sh('git', ['checkout', '-q', '-B', branch], dir, env); await sh('git', ['remote', 'add', 'origin', origin], dir, env); await git(dir, 'add', '-A'); const committed = await git(dir, 'commit', '-q', '-m', `born at ${version}`); if (!committed.ok) throw new Error(committed.output); - await sh('git', ['push', '-q', 'origin', branch as string], dir, env); + await sh('git', ['push', '-q', 'origin', branch], dir, env); return dir; } @@ -629,7 +623,7 @@ async function updateJob( } for (const [kind, branch] of [ - ['app', 'develop'], + ['app', 'main'], ['package', 'main'], ['operations', 'main'], ] as const) { @@ -685,7 +679,7 @@ for (const [kind, branch] of [ test('app: a repo with neither the App’s credentials on the forge nor a vault fails the setup in one line that names both ways, and runs no update', async () => { const repo = await repoAt(FIRST, 'app'); - const run = await updateJob(FIRST, repo, 'develop', 'schedule', { credentials: false }); + const run = await updateJob(FIRST, repo, 'main', 'schedule', { credentials: false }); assert.ok(run.failed); assert.deepEqual( run.done.map((d) => d.step), diff --git a/packages/lib/src/newSite.test.ts b/packages/lib/src/newSite.test.ts index 311466e8..03d0f8dc 100644 --- a/packages/lib/src/newSite.test.ts +++ b/packages/lib/src/newSite.test.ts @@ -460,6 +460,10 @@ test('a repo born with environments holds the declaration in its marker, read ba ); // Nothing computed from the declaration is written into the marker: it is computed again for every render. assert.doesNotMatch(text(target, 'PLEXUS.md'), /declared_environments/); + // The workflows follow the declaration: on_push on both branches, a promotion for the one that promotes itself. + assert.match(text(target, '.github/workflows/on_push.yml'), /branches: \[env\/staging, env\/production\]/); + assert.match(text(target, '.github/workflows/promote-staging.yml'), /branches: \[main\]/); + assert.equal(existsSync(join(target, '.github/workflows/promote-production.yml')), false); await nested(join(target, 'apps', 'web'), ['app-nextjs'], { name: 'web' }); const stack = await nested(join(target, 'stack'), ['stack'], { apps: 'web' }); assert.deepEqual(stack.files, ['PLEXUS.md', 'compose.yaml', 'production.yaml', 'staging.yaml']); @@ -470,6 +474,20 @@ test('a repo born with environments holds the declaration in its marker, read ba assert.deepEqual((await doctorOf(target)).findings.length, 1); }); +test('a declaration given as text, as `plx new -a` gives it, renders the workflows as the declaration it reads as', async () => { + const target = scratch.fresh('turbo-environments-text'); + const { ctx } = recording(); + await newSite(ctx, { + dir: target, + templates: ['repo-turbo'], + answers: { tenant: 'acme', repo: 'shop', environments: '{qa: {promotes_from: main, auto_promote: true}}' }, + plxVersion: bundled.version, + root: templatesRoot(), + }); + assert.match(text(target, '.github/workflows/on_push.yml'), /branches: \[env\/qa\]/); + assert.match(text(target, '.github/workflows/promote-qa.yml'), /plx -y promote qa/); +}); + test('a newborn repo with a stack and no declaration passes the doctor: its stack is born with no environment file', async () => { const { target } = await bornTurbo(); await nested(join(target, 'apps', 'web'), ['app-nextjs'], { name: 'web' }); diff --git a/packages/lib/src/operationsPipeline.test.ts b/packages/lib/src/operationsPipeline.test.ts index 44a7ae9f..264e2dd5 100644 --- a/packages/lib/src/operationsPipeline.test.ts +++ b/packages/lib/src/operationsPipeline.test.ts @@ -8,6 +8,9 @@ import type { Answers } from '@plexus-ms/cli-template'; import { parse } from 'yaml'; import { pathsOf, renderBundled, textOf } from './testing/bundled.ts'; +/** Two environments: one that promotes itself from main, one promoted by hand from the first. */ +const DECLARED = { qa: { promotes_from: 'main', auto_promote: true }, live: { promotes_from: 'qa' } }; + interface Step { id?: string; uses?: string; @@ -38,9 +41,13 @@ type Rendered = { text: string; workflow: Workflow }; const NAMES = ['on_commit', 'on_pr', 'deploy'] as const; type Name = (typeof NAMES)[number]; -/** The operations repo's three workflows rendered with `answers`, as text and parsed. */ +/** The operations repo's three workflows rendered with `answers`, the two environments above declared unless they say otherwise, as text and parsed. */ async function operations(answers: Answers = {}, version?: string): Promise> { - const result = await renderBundled(['repo-operations'], { tenant: 'acme', ...answers }, version); + const result = await renderBundled( + ['repo-operations'], + { tenant: 'acme', environments: DECLARED, ...answers }, + version, + ); assert.deepEqual(result.errors, []); const of = (name: Name): Rendered => { const text = textOf(result, `.github/workflows/${name}.yml`); @@ -117,7 +124,9 @@ test('the job repo of on_commit and on_pr asks for a repo slot under byom and th test('the triggers, the Markdown filter, the permissions and the cancelling of a newer push are those of the reusable form', async () => { const { on_commit, on_pr } = await operations(); - assert.deepEqual(on_commit.workflow.on, { push: { branches: ['main'], 'paths-ignore': ['**/*.md'] } }); + assert.deepEqual(on_commit.workflow.on, { + push: { 'branches-ignore': ['env/qa', 'env/live'], 'paths-ignore': ['**/*.md'] }, + }); assert.deepEqual(on_pr.workflow.on, { pull_request: { 'paths-ignore': ['**/*.md'] } }); for (const { workflow } of [on_commit, on_pr]) { assert.deepEqual(workflow.permissions, { contents: 'read' }); @@ -139,10 +148,11 @@ test('deploy.yml holds one job and no matrix, and runs on a delivery slot under } }); -test('deploy.yml keeps its triggers and its permissions, and can be started by hand', async () => { +test('deploy.yml runs on a push to the branch of each declared environment, listed by name, and can be started by hand', async () => { const { workflow } = (await operations()).deploy; assert.deepEqual(Object.keys(workflow.on), ['push', 'workflow_dispatch']); - assert.deepEqual(workflow.on.push, { branches: ['main'], paths: ['stack/**', 'stacks/**'] }); + // No paths filter: a promotion that creates the branch at a known commit pushes no files and would start nothing. + assert.deepEqual(workflow.on.push, { branches: ['env/qa', 'env/live'] }); assert.deepEqual(workflow.permissions, { contents: 'read' }); assert.equal(workflow.jobs.deploy?.permissions, undefined); }); @@ -154,7 +164,7 @@ const VERSION = '7.8.9'; const DEPLOY_KEY = '${{ secrets.DEPLOY_SSH_KEY }}'; const DEPLOY_TOKEN = '${{ secrets.DEPLOY_VAULT_TOKEN }}'; /** The verb of the job deploy: the Connect server of a slot reads another vault, so the verb's `op` never sees it. */ -const VERB = 'env -u OP_CONNECT_HOST -u OP_CONNECT_TOKEN plx deploy --environment production'; +const VERB = 'env -u OP_CONNECT_HOST -u OP_CONNECT_TOKEN plx deploy'; test('setup of the job deploy follows the checkout, runs in its root, and is handed the deploy key and, to join the overlay, the CI vault’s token; the verb alone holds the deploy token', async () => { for (const ci_overlay of ['none', 'netbird']) { @@ -181,7 +191,11 @@ test('setup of the job deploy follows the checkout, runs in its root, and is han test('the job deploy is the checkout, mise without an install, the install of plx and plx-ci, setup, Ansible, and the verb', async () => { for (const answers of SHAPES) { - const result = await renderBundled(['repo-operations'], { tenant: 'acme', ...answers }, VERSION); + const result = await renderBundled( + ['repo-operations'], + { tenant: 'acme', environments: DECLARED, ...answers }, + VERSION, + ); const deploy = (parse(textOf(result, '.github/workflows/deploy.yml')) as Workflow).jobs.deploy; const leave = answers.ci_overlay === 'netbird' ? ['sudo netbird down || true'] : []; const tool = (name: string) => `'npm:@plexus-ms/${name}[allow_low_downloads=true]@${VERSION}'`; @@ -211,7 +225,7 @@ test('the job deploy is the checkout, mise without an install, the install of pl }); test('the job deploy reads no mise.toml of the repo and installs plx outside the checkout, as the job deploy of an app repo does', async () => { - const result = await renderBundled(['repo-operations'], { tenant: 'acme' }, VERSION); + const result = await renderBundled(['repo-operations'], { tenant: 'acme', environments: DECLARED }, VERSION); const deploy = (parse(textOf(result, '.github/workflows/deploy.yml')) as Workflow).jobs.deploy; assert.deepEqual(deploy?.env, { MISE_IGNORED_CONFIG_PATHS: '${{ github.workspace }}' }); assert.equal(deploy?.steps?.[1]?.uses, 'jdx/mise-action@7e2b3c3d1450331892809a84e22e30e3f52c1e92'); @@ -223,16 +237,53 @@ test('the job deploy reads no mise.toml of the repo and installs plx outside the assert.match(deploy?.steps?.[2]?.run ?? '', new RegExp(`^mise use -g node@${node} `)); }); -test('the deploy is never cancelled and is queued: one run at a time, the newest waiting', async () => { +test('the deploy is never cancelled and is queued per branch: one run at a time, the newest waiting', async () => { const { workflow } = (await operations()).deploy; assert.equal(workflow.concurrency, undefined); - assert.deepEqual(workflow.jobs.deploy?.concurrency, { group: 'deploy-production', 'cancel-in-progress': false }); + assert.deepEqual(workflow.jobs.deploy?.concurrency, { + group: 'deploy-${{ github.ref }}', + 'cancel-in-progress': false, + }); +}); + +test('an operations repo that declares no environment has no deploy.yml and no promotion: on_commit runs on every branch', async () => { + const result = await renderBundled(['repo-operations'], { tenant: 'acme' }); + assert.deepEqual(result.errors, []); + const workflows = pathsOf(result).filter((path) => path.startsWith('.github/workflows/')); + assert.deepEqual(workflows, ['.github/workflows/on_commit.yml', '.github/workflows/on_pr.yml']); + const on_commit = parse(textOf(result, '.github/workflows/on_commit.yml')) as Workflow; + assert.deepEqual(on_commit.on, { push: { branches: ['**'], 'paths-ignore': ['**/*.md'] } }); +}); + +test('an environment of an operations repo that promotes itself has the app repo’s promotion workflow, after a green run of on_commit or deploy', async () => { + const ops = await renderBundled(['repo-operations'], { tenant: 'acme', environments: DECLARED }); + const app = await renderBundled(['repo-turbo'], { tenant: 'acme', environments: DECLARED }); + const path = '.github/workflows/promote-qa.yml'; + assert.deepEqual( + pathsOf(ops).filter((p) => p.startsWith('.github/workflows/promote')), + [path], + ); + const workflow = parse(textOf(ops, path)) as Workflow; + assert.deepEqual(workflow.on, { + workflow_run: { workflows: ['on_commit', 'deploy'], types: ['completed'], branches: ['main'] }, + }); + assert.equal( + textOf(ops, path), + textOf(app, path) + .replace('workflows: [on_commit, on_push]', 'workflows: [on_commit, deploy]') + .replace('templates/repo-turbo', 'templates/repo-operations') + .replace('so that on_push runs there', 'so that deploy runs there'), + ); }); test('no workflow of an operations repo but the housekeeping’s names plexus-ms/tooling, but to install the collection, and only deploy.yml names a Plexus version', async () => { for (const answers of SHAPES) for (const housekeeping of [false, true]) { - const result = await renderBundled(['repo-operations'], { tenant: 'acme', ...answers, housekeeping }, VERSION); + const result = await renderBundled( + ['repo-operations'], + { tenant: 'acme', environments: DECLARED, ...answers, housekeeping }, + VERSION, + ); const workflows = pathsOf(result).filter((path) => path.startsWith('.github/workflows/')); assert.deepEqual( workflows, @@ -241,6 +292,7 @@ test('no workflow of an operations repo but the housekeeping’s names plexus-ms ...(housekeeping ? ['.github/workflows/housekeeping.yml'] : []), '.github/workflows/on_commit.yml', '.github/workflows/on_pr.yml', + '.github/workflows/promote-qa.yml', ], JSON.stringify(answers), ); @@ -303,13 +355,18 @@ test('a step of an operations repo’s workflows is one command or one pinned ac }); test('the job deploy starts as an app repo’s does: the same env, checkout, mise step and install step', async () => { - const app = await renderBundled(['repo-turbo'], { tenant: 'acme' }); + const app = await renderBundled(['repo-turbo'], { tenant: 'acme', environments: DECLARED }); const push = (parse(textOf(app, '.github/workflows/on_push.yml')) as Workflow).jobs.deploy; const mine = (await operations()).deploy.workflow.jobs.deploy; assert.deepEqual(mine?.env, push?.env); assert.deepEqual(mine?.steps?.slice(0, 3), push?.steps?.slice(0, 3)); }); -test('the header of deploy.yml names the push to main and the start by hand', async () => { - assert.match((await operations()).deploy.text, /^# .*started by hand, where it can be run dry/m); +test('the header of deploy.yml names the push to an environment’s branch and the start by hand, and no environment', async () => { + const { text } = (await operations()).deploy; + assert.match( + text, + /^# On a push to the branch of an environment the repo declares, .*started by hand on one, where it can be run dry/m, + ); + assert.doesNotMatch(text, /production|staging/); }); diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index 53269cf2..4a54cfb1 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -69,9 +69,15 @@ const APP = ['on_commit', 'on_pr', 'on_push'] as const; type AppWorkflow = (typeof APP)[number]; type Rendered = { text: string; workflow: Workflow }; -/** An app repo's three workflows rendered with `answers`, as text and parsed. */ +/** + * Two environments as a repo declares them: one that promotes itself from main, one promoted by hand from the first. + * No name has a meaning to a tool, so the tests use names a tool could not know. + */ +const DECLARED = { qa: { promotes_from: 'main', auto_promote: true }, live: { promotes_from: 'qa' } }; + +/** An app repo's three workflows rendered with `answers`, the two environments above declared unless they say otherwise, as text and parsed. */ async function appRepo(answers: Answers = {}): Promise> { - const result = await renderBundled(['repo-turbo'], { tenant: 'acme', ...answers }); + const result = await renderBundled(['repo-turbo'], { tenant: 'acme', environments: DECLARED, ...answers }); assert.deepEqual(result.errors, []); const of = (name: AppWorkflow): Rendered => { const text = textOf(result, `.github/workflows/${name}.yml`); @@ -361,10 +367,146 @@ test('a newer push to the same ref cancels the job repo in all three workflows; test('on_commit and on_pr start no run for a change to nothing but Markdown; on_push has no filter', async () => { const { on_commit, on_pr, on_push } = await appRepo(); assert.deepEqual(on_commit.workflow.on, { - push: { 'branches-ignore': ['main', 'develop'], 'paths-ignore': ['**/*.md'] }, + push: { 'branches-ignore': ['env/qa', 'env/live'], 'paths-ignore': ['**/*.md'] }, }); assert.deepEqual(on_pr.workflow.on, { pull_request: { 'paths-ignore': ['**/*.md'] } }); - assert.deepEqual(on_push.workflow.on, { push: { branches: ['main', 'develop'] }, workflow_dispatch: null }); + assert.deepEqual(on_push.workflow.on, { push: { branches: ['env/qa', 'env/live'] }, workflow_dispatch: null }); +}); + +test('on_push runs on a push to the branch of each declared environment, listed by name, and on no other; on_commit on every other branch, main among them', async () => { + const three = { + staging: { promotes_from: 'main' }, + production: { promotes_from: 'staging' }, + demo: { promotes_from: 'main', auto_promote: true }, + }; + const { on_commit, on_push } = await appRepo({ environments: three }); + const branches = ['env/staging', 'env/production', 'env/demo']; + assert.deepEqual(on_push.workflow.on.push, { branches }); + assert.deepEqual(on_commit.workflow.on.push?.['branches-ignore'], branches); + assert.match(on_push.text, /^# On a push to the branch of an environment the repo declares, and on no other, /m); +}); + +test('a repo that declares no environment, or whose declaration is invalid, has no on_push and no promotion: on_commit runs on every branch', async () => { + for (const environments of [{}, { qa: { promotes_from: 'nowhere' } }]) { + const result = await renderBundled(['repo-turbo'], { tenant: 'acme', environments }); + assert.deepEqual(result.errors, []); + const workflows = pathsOf(result).filter((path) => path.startsWith('.github/workflows/')); + assert.deepEqual(workflows, ['.github/workflows/on_commit.yml', '.github/workflows/on_pr.yml']); + const on_commit = parse(textOf(result, '.github/workflows/on_commit.yml')) as Workflow; + assert.deepEqual(on_commit.on, { push: { branches: ['**'], 'paths-ignore': ['**/*.md'] } }); + for (const path of workflows) assert.doesNotMatch(textOf(result, path), /env\//, path); + } +}); + +test('the job repo of on_push checks out the whole history with its tags, which the version of its images needs; on_commit and on_pr check out the commit', async () => { + const { on_commit, on_pr, on_push } = await appRepo(); + assert.deepEqual(on_push.workflow.jobs.repo?.steps?.[0]?.with, { 'fetch-depth': 0 }); + for (const { workflow } of [on_commit, on_pr]) assert.equal(workflow.jobs.repo?.steps?.[0]?.with, undefined); +}); + +/** The promotion workflows an app repo renders with `environments`, by path, as text and parsed. */ +async function promotions(environments: unknown, answers: Answers = {}): Promise> { + const result = await renderBundled(['repo-turbo'], { tenant: 'acme', environments, ...answers }); + assert.deepEqual(result.errors, []); + return new Map( + pathsOf(result) + .filter((path) => path.startsWith('.github/workflows/promote')) + .map((path) => { + const text = textOf(result, path); + return [path, { text, workflow: parse(text) as Workflow }]; + }), + ); +} + +/** The App's credentials, which setup takes from the forge where the repo holds them. */ +const APP_CREDENTIALS = { GH_CLIENT_ID: '${{ vars.GH_CLIENT_ID }}', GH_PRIVATE_KEY: '${{ secrets.GH_PRIVATE_KEY }}' }; + +test('an environment that promotes itself from main has a workflow that, after a green run of on_commit on main, fast-forwards its branch with plx promote, pushed as the App', async () => { + for (const answers of SHAPES) { + const found = await promotions(DECLARED, answers); + assert.deepEqual([...found.keys()], ['.github/workflows/promote-qa.yml'], JSON.stringify(answers)); + const { workflow } = found.get('.github/workflows/promote-qa.yml') as Rendered; + assert.deepEqual(workflow.on, { + workflow_run: { workflows: ['on_commit', 'on_push'], types: ['completed'], branches: ['main'] }, + }); + assert.deepEqual(workflow.permissions, { contents: 'read' }); + assert.deepEqual(Object.keys(workflow.jobs), ['promote']); + const job = workflow.jobs.promote; + assert.equal(job?.if, "${{ github.event.workflow_run.conclusion == 'success' }}"); + assert.equal(job?.['runs-on'], runner(String(answers.ci_strategy), 'ci-repo')); + assert.deepEqual(job?.concurrency, { group: 'promote-qa', 'cancel-in-progress': false }); + assert.deepEqual(stepsOf(job), [ + 'actions/checkout', + 'jdx/mise-action', + 'plx-ci setup promote', + 'actions/checkout', + 'plx -y promote qa', + ]); + const [, , setup, checkout] = job?.steps ?? []; + assert.equal(setup?.id, 'setup'); + assert.deepEqual(setup?.env, { + ...APP_CREDENTIALS, + ...(answers.ci_service_account ? { OP_SERVICE_ACCOUNT_TOKEN: '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}' } : {}), + }); + // The promotion pushes with the App's token, persisted by the second checkout, so that the push starts on_push on + // the environment's branch; plx promote needs the whole history to tell a fast-forward. + assert.deepEqual(checkout?.with, { 'fetch-depth': 0, token: '${{ steps.setup.outputs.app-token }}' }); + } +}); + +test('an environment that promotes itself from another environment renders the same workflow, after a green run on that environment’s branch', async () => { + const qa = (await promotions(DECLARED)).get('.github/workflows/promote-qa.yml') as Rendered; + const found = await promotions({ qa: { promotes_from: 'main' }, live: { promotes_from: 'qa', auto_promote: true } }); + assert.deepEqual([...found.keys()], ['.github/workflows/promote-live.yml']); + const live = found.get('.github/workflows/promote-live.yml') as Rendered; + assert.deepEqual(live.workflow.on.workflow_run?.branches, ['env/qa']); + assert.equal( + live.text, + qa.text + .replaceAll('branches: [main]', 'branches: [env/qa]') + .replaceAll('promote-qa', 'promote-live') + .replaceAll('promote qa', 'promote live') + .replaceAll('env/qa to the head of main', 'env/live to the head of env/qa') + .replaceAll('on main, the branch qa promotes from', 'on env/qa, the branch live promotes from'), + ); +}); + +test('two environments that promote themselves have a workflow each, and one promoted by hand has none', async () => { + const found = await promotions({ + qa: { promotes_from: 'main', auto_promote: true }, + live: { promotes_from: 'qa', auto_promote: true }, + demo: { promotes_from: 'main', auto_promote: false }, + }); + assert.deepEqual([...found.keys()], ['.github/workflows/promote-live.yml', '.github/workflows/promote-qa.yml']); +}); + +test('a step of a promotion workflow is one command, and its only expressions are the runner, the cache of mise, the App’s credentials and token, the vault’s token and the run’s conclusion', async () => { + for (const ci_strategy of STRATEGIES) { + const allowed = new Set([ + runner(ci_strategy, 'ci-repo'), + "${{ runner.environment == 'github-hosted' }}", + "${{ github.event.workflow_run.conclusion == 'success' }}", + APP_CREDENTIALS.GH_CLIENT_ID, + APP_CREDENTIALS.GH_PRIVATE_KEY, + '${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}', + '${{ steps.setup.outputs.app-token }}', + ]); + for (const [path, { text, workflow }] of await promotions(DECLARED, { ci_strategy })) { + for (const expression of expressions(text)) assert.ok(allowed.has(expression), `${path}: ${expression}`); + for (const step of workflow.jobs.promote?.steps ?? []) + if (step.run) assert.doesNotMatch(step.run, /[\n;|&$`<>]/, `${path}: ${step.run}`); + } + } +}); + +test('no workflow a template renders holds a condition on an environment’s name or branch', () => { + for (const { path, text } of renderedWorkflows()) + for (const [, condition = ''] of text.matchAll(/^\s*(?:- )?if: (.*)$/gm)) + assert.doesNotMatch( + condition, + /env\/|qa|live|staging|production|head_branch|github\.ref/, + `${path}: ${condition}`, + ); }); test('the job repo of on_push writes packages, the job deploy reads them, and nothing else of an app repo writes anything', async () => { @@ -486,10 +628,10 @@ test('no workflow of an app repo names plexus-ms/tooling but to install the coll ); assert.ok(shapes.length > 10, `${shapes.length} shapes`); for (const { answers, result } of shapes) - for (const name of APP) { - const text = textOf(result, `.github/workflows/${name}.yml`); - assert.doesNotMatch(withoutCollection(text), /plexus-ms\/tooling/, `${name} ${JSON.stringify(answers)}`); - assert.equal(text.includes(CURRENT), name === 'on_push', `${name} and ${CURRENT}`); + for (const path of pathsOf(result).filter((p) => p.startsWith('.github/workflows/'))) { + const text = textOf(result, path); + assert.doesNotMatch(withoutCollection(text), /plexus-ms\/tooling/, `${path} ${JSON.stringify(answers)}`); + assert.equal(text.includes(CURRENT), path.endsWith('/on_push.yml'), `${path} and ${CURRENT}`); } }); diff --git a/packages/lib/src/repoOperations.test.ts b/packages/lib/src/repoOperations.test.ts index e783be72..7fbcfece 100644 --- a/packages/lib/src/repoOperations.test.ts +++ b/packages/lib/src/repoOperations.test.ts @@ -15,8 +15,9 @@ const toolsOf = (mise: string): string[] => .map((line) => /^("[^"]+"|[\w-]+) = /.exec(line)?.[1] ?? '') .filter(Boolean); +/** An operations repo of one environment, promoted by hand, unless the answers say otherwise. */ const render = (answers: Record = {}) => - renderBundled(['repo-operations'], { tenant: 'acme', ...answers }); + renderBundled(['repo-operations'], { tenant: 'acme', environments: { live: { promotes_from: 'main' } }, ...answers }); const COMMON = [ '.github/workflows/deploy.yml', @@ -78,7 +79,7 @@ test('no file holds anything of the registry pair or its question', async () => }); test('the answers are the questions’ defaults, and the org follows the tenant', async () => { - assert.deepEqual((await render()).answers, { + assert.deepEqual((await renderBundled(['repo-operations'], { tenant: 'acme' })).answers, { tenant: 'acme', repo: '', github_org: 'acme', @@ -129,6 +130,9 @@ test('the marker is written once, and without frontmatter, which plx writes', as // Third-party software is stacks of no app, as plx deploy reads them; nothing is under apps/. assert.match(textOf(result, 'PLEXUS.md'), /`stacks\/\/`.*`stack\/`/); assert.match(textOf(result, 'PLEXUS.md'), /plx deploy --environment `.*a file for that environment/); + // The workflow deploy deploys each environment from its branch, and the marker names none. + assert.match(textOf(result, 'PLEXUS.md'), /workflow `deploy` deploys each environment on a push to its branch/); + assert.doesNotMatch(textOf(result, 'PLEXUS.md'), /production|staging/); assert.doesNotMatch(textOf(result, 'PLEXUS.md'), /--inventory/); assert.doesNotMatch(textOf(result, 'PLEXUS.md'), /apps\//); // And what a person adds to the compose file plx new gives such a stack, so that plx doctor passes. diff --git a/packages/lib/src/testing/shapes.ts b/packages/lib/src/testing/shapes.ts index 3c71d8da..66dd0bb8 100644 --- a/packages/lib/src/testing/shapes.ts +++ b/packages/lib/src/testing/shapes.ts @@ -8,11 +8,21 @@ import type { Answers, RenderResult } from '@plexus-ms/cli-template'; type Choices = Readonly>; +/** No environment, and two that promote themselves, the second from the first. */ +const ENVIRONMENTS = [ + {}, + { + staging: { promotes_from: 'main', auto_promote: true }, + production: { promotes_from: 'staging', auto_promote: true }, + }, +]; + /** The answers each repo template, and `updates` beside it, is rendered with. */ export const CHOICES: Readonly> = { 'repo-turbo': { tenant: ['acme'], publishes_packages: [false, true], + environments: ENVIRONMENTS, package_registry: ['npm', 'github'], private_packages_scope: ['', '@acme'], ci_strategy: ['github', 'byom'], @@ -26,6 +36,7 @@ export const CHOICES: Readonly 'repo-operations': { tenant: ['acme'], github_org: ['acme', 'acme-gh'], + environments: ENVIRONMENTS, infrastructure: [false, true], ci_strategy: ['github', 'byom'], ci_overlay: ['none', 'netbird'], From d3485bb2e347ec898d6516b30ce9fb440f5716df Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 10:50:05 +0100 Subject: [PATCH 06/21] Test that an app repo without a declared environment has no on_push The renders that read on_push or deploy.yml declare an environment; the pins and the held app pipeline are checked with and without one, the triggers and the whole-history checkout left out of what is held. PLX-303 Co-Authored-By: Claude Opus 5.5 --- packages/lib/src/newSite.test.ts | 2 +- packages/lib/src/packageRepoPipeline.test.ts | 23 +++++++++++++++++--- packages/lib/src/pipeline.test.ts | 10 ++++++--- packages/lib/src/repoTurbo.test.ts | 10 ++++++--- packages/lib/src/templatePins.test.ts | 12 ++++++---- 5 files changed, 43 insertions(+), 14 deletions(-) diff --git a/packages/lib/src/newSite.test.ts b/packages/lib/src/newSite.test.ts index 03d0f8dc..3b80137f 100644 --- a/packages/lib/src/newSite.test.ts +++ b/packages/lib/src/newSite.test.ts @@ -796,7 +796,7 @@ test('the pins of a new repo name the version its templates carry, which the bui await newSite(recording().ctx, { dir: target, templates: ['repo-operations'], - answers: { tenant: 'acme' }, + answers: { tenant: 'acme', environments: { live: { promotes_from: 'main' } } }, plxVersion: '7.7.7', root, }); diff --git a/packages/lib/src/packageRepoPipeline.test.ts b/packages/lib/src/packageRepoPipeline.test.ts index 30c6057a..3c36a0f1 100644 --- a/packages/lib/src/packageRepoPipeline.test.ts +++ b/packages/lib/src/packageRepoPipeline.test.ts @@ -329,11 +329,27 @@ const uncommented = (text: string) => const withoutDeploy = (text: string) => text.replace(/^ {2}deploy:\n[\s\S]*$/m, '').replace(/, then the job deploy deploys every (app|stack)\.$/m, ''); +/** + * A workflow from its permissions on, without the whole-history checkout: its header and its triggers follow the + * declared environments since, and the job repo of on_push checks out the history its images' version is told from. + */ +const withoutTriggers = (text: string) => + text + .slice(text.indexOf('\npermissions:')) + .replace(/^ {6}# The whole history with its tags, .*\n/m, '') + .replace(/^ {8}with:\n {10}fetch-depth: 0\n/m, ''); + /** The file at `path` of a render, as far as an app repo's render still holds it to the earlier one. */ const held = (path: string, text: string) => - path === 'mise.toml' ? withoutPublish(text) : path.endsWith('on_push.yml') ? withoutDeploy(uncommented(text)) : text; + path === 'mise.toml' + ? withoutPublish(text) + : path.endsWith('on_push.yml') + ? withoutTriggers(withoutDeploy(uncommented(text))) + : path.endsWith('on_commit.yml') + ? withoutTriggers(text) + : text; -test('an app repo’s three workflows but the comment on the key of its publish step and the job deploy, and its mise.toml but its publish, render as they did at the last version whose package repos called the reusable workflows', () => { +test('an app repo’s three workflows but their triggers, the comment on the key of its publish step and the job deploy, and its mise.toml but its publish, render as they did at the last version whose package repos called the reusable workflows', () => { const shapes = distinct({ ...CHOICES['repo-turbo'], publishes_packages: [false] }, (answers: Answers) => renderAt([repoTurbo, updates], answers), ); @@ -341,10 +357,11 @@ test('an app repo’s three workflows but the comment on the key of its publish for (const { answers, result } of shapes) { const then = renderAt([released, updates], answers); assert.deepEqual(then.errors, []); + // A repo that declares no environment has no on_push since. for (const path of [ '.github/workflows/on_commit.yml', '.github/workflows/on_pr.yml', - '.github/workflows/on_push.yml', + ...(result.files.has('.github/workflows/on_push.yml') ? ['.github/workflows/on_push.yml'] : []), 'mise.toml', ]) assert.equal( diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index 4a54cfb1..1768a9ec 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -243,7 +243,7 @@ const VERSION = '7.8.9'; test('the job deploy reads no mise.toml of the repo: its config paths are ignored and its tools are given by version in one step', async () => { for (const answers of SHAPES) { - const result = await renderBundled(['repo-turbo'], { tenant: 'acme', ...answers }, VERSION); + const result = await renderBundled(['repo-turbo'], { tenant: 'acme', environments: DECLARED, ...answers }, VERSION); assert.deepEqual(result.errors, []); const deploy = (parse(textOf(result, '.github/workflows/on_push.yml')) as Workflow).jobs.deploy; // Job-level, so that every step of the job, the later ones through mise's shims too, ignores the checkout's config. @@ -273,8 +273,12 @@ test('the job deploy reads no mise.toml of the repo: its config paths are ignore }); test('the Plexus version is named in the job deploy of on_push and in no other workflow of an app repo', async () => { - const result = await renderBundled(['repo-turbo'], { tenant: 'acme', ci_strategy: 'byom' }, VERSION); - for (const name of ['on_commit', 'on_pr'] as const) + const result = await renderBundled( + ['repo-turbo'], + { tenant: 'acme', ci_strategy: 'byom', environments: DECLARED }, + VERSION, + ); + for (const name of ['on_commit', 'on_pr', 'promote-qa'] as const) assert.ok(!textOf(result, `.github/workflows/${name}.yml`).includes(VERSION), name); const push = textOf(result, '.github/workflows/on_push.yml'); assert.equal(push.split(VERSION).length - 1, 3, 'plx and plx-ci, in one line, and the collection'); diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index f4d6a0e9..aa03955b 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -16,7 +16,6 @@ const render = (answers: Record = {}) => renderBundled(['repo-t const COMMON = [ '.github/workflows/on_pr.yml', - '.github/workflows/on_push.yml', '.gitignore', 'PLEXUS.md', 'biome.json', @@ -29,16 +28,21 @@ const COMMON = [ 'turbow', ]; -test('an app repo is rendered with its apps directory and its commit workflows', async () => { +test('an app repo is rendered with its apps directory and its commit workflows, and on_push once it declares an environment', async () => { const result = await render(); assert.deepEqual(result.errors, []); assert.deepEqual(pathsOf(result), [...COMMON, '.github/workflows/on_commit.yml', 'apps/.gitkeep'].sort()); + const declared = await render({ environments: { live: { promotes_from: 'main' } } }); + assert.deepEqual( + pathsOf(declared), + [...COMMON, '.github/workflows/on_commit.yml', '.github/workflows/on_push.yml', 'apps/.gitkeep'].sort(), + ); }); test('a package repo has changesets instead of apps and the commit workflows', async () => { const result = await render({ publishes_packages: true }); assert.deepEqual(result.errors, []); - assert.deepEqual(pathsOf(result), [...COMMON, '.changeset/config.json'].sort()); + assert.deepEqual(pathsOf(result), [...COMMON, '.changeset/config.json', '.github/workflows/on_push.yml'].sort()); }); test('no repo, in any shape, holds a housekeeping workflow or anything of the registry pair and its question', async () => { diff --git a/packages/lib/src/templatePins.test.ts b/packages/lib/src/templatePins.test.ts index 533b422a..4f7184f6 100644 --- a/packages/lib/src/templatePins.test.ts +++ b/packages/lib/src/templatePins.test.ts @@ -9,14 +9,18 @@ import { pathsOf, renderBundled, textOf } from './testing/bundled.ts'; const [FROM, TO] = ['7.7.7', '8.8.8']; /** Every shape of repo the templates render, by the templates and answers that make it. */ +/** An environment that promotes itself from main, so that a repo has every workflow it can have. */ +const environments = { live: { promotes_from: 'main', auto_promote: true } }; + const SHAPES: Record]> = { - 'an app repo': [['repo-turbo', 'updates'], { tenant: 'acme' }], - 'an app repo on its own slots': [['repo-turbo', 'updates'], { tenant: 'acme', ci_strategy: 'byom' }], + 'an app repo': [['repo-turbo', 'updates'], { tenant: 'acme', environments }], + 'an app repo on its own slots': [['repo-turbo', 'updates'], { tenant: 'acme', ci_strategy: 'byom', environments }], + 'an app repo that declares no environment': [['repo-turbo', 'updates'], { tenant: 'acme' }], 'a package repo': [['repo-turbo', 'updates'], { tenant: 'acme', publishes_packages: true }], - 'an operations repo': [['repo-operations', 'updates'], { tenant: 'acme' }], + 'an operations repo': [['repo-operations', 'updates'], { tenant: 'acme', environments }], 'an operations repo with runners of its own': [ ['repo-operations', 'updates'], - { tenant: 'acme', ci_strategy: 'byom' }, + { tenant: 'acme', ci_strategy: 'byom', environments }, ], }; From e003896254d9824dad950bb07b0847842253eb89 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 10:50:57 +0100 Subject: [PATCH 07/21] Render the workflows from the declared environments on_push of an app repo and deploy of an operations repo run on a push to the branch of each declared environment, listed by name, and on no other; on_commit runs on every other branch, main among them. A repo that declares none has neither, and on_commit runs on every branch. The job repo of on_push checks out the whole history with its tags. Each environment that promotes itself has a workflow that runs plx promote after a green run on its source and pushes as the tenant's App. The operations repo deploys the environment of its branch, queued per branch. PLX-303 Co-Authored-By: Claude Opus 5.5 --- renovate/operations.json | 4 +- .../.github/workflows/on_commit.yml.jinja | 10 +++-- ...mote-{{ _item.name }}.yml{% endif %}.jinja | 40 +++++++++++++++++++ ...nvironments %}deploy.yml{% endif %}.jinja} | 13 +++--- .../repo-operations/files/PLEXUS.md.jinja | 2 +- templates/repo-operations/template.yml | 11 +++++ ...mote-{{ _item.name }}.yml{% endif %}.jinja | 40 +++++++++++++++++++ ..._packages %}on_commit.yml{% endif %}.jinja | 10 +++-- ...vironments %}on_push.yml{% endif %}.jinja} | 7 +++- templates/repo-turbo/template.yml | 8 ++++ 10 files changed, 128 insertions(+), 17 deletions(-) create mode 100644 templates/repo-operations/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja rename templates/repo-operations/files/.github/workflows/{deploy.yml.jinja => {% if declared_environments %}deploy.yml{% endif %}.jinja} (85%) create mode 100644 templates/repo-turbo/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja rename templates/repo-turbo/files/.github/workflows/{on_push.yml.jinja => {% if publishes_packages or declared_environments %}on_push.yml{% endif %}.jinja} (95%) diff --git a/renovate/operations.json b/renovate/operations.json index 4664aba9..e3e694fa 100644 --- a/renovate/operations.json +++ b/renovate/operations.json @@ -1,8 +1,8 @@ { "$schema": "https://docs.renovatebot.com/renovate-schema.json", "description": [ - "For an operations repo (PLX-Tenancy), extended after the shared preset: a merge to main under apps/ deploys a third-party image to production, and the only check before it is the playbooks' syntax.", - "The weekly group therefore waits for a human, who reads the release notes before production runs the new versions; a security fix still merges on green CI." + "For an operations repo (PLX-Tenancy), extended after the shared preset: a merge to main of a third-party image reaches every environment that promotes itself from main without a person, and the only check before it is the playbooks' syntax.", + "The weekly group therefore waits for a human, who reads the release notes before an environment runs the new versions; a security fix still merges on green CI." ], "packageRules": [ { diff --git a/templates/repo-operations/files/.github/workflows/on_commit.yml.jinja b/templates/repo-operations/files/.github/workflows/on_commit.yml.jinja index d8e6c19c..d19086ef 100644 --- a/templates/repo-operations/files/.github/workflows/on_commit.yml.jinja +++ b/templates/repo-operations/files/.github/workflows/on_commit.yml.jinja @@ -1,11 +1,15 @@ {% raw %}name: on_commit # Generated from templates/repo-operations of @plexus-ms/cli: edit the template, never this file. -# The check of a push to main, the trunk that takes an operator's direct pushes: the job repo runs test, which runs check first. +# On a push to any branch but those of the declared environments, main among them, the trunk that takes an operator's direct pushes: the job repo runs test, which runs check first. on: - push: - branches: [main] + push:{% endraw %} +{%- if declared_environments %} + branches-ignore: [{{ declared_environments | map(attribute='branch') | join(', ') }}] +{%- else %} + branches: ['**'] +{%- endif %}{% raw %} paths-ignore: ['**/*.md'] permissions: diff --git a/templates/repo-operations/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja b/templates/repo-operations/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja new file mode 100644 index 00000000..a9d28c05 --- /dev/null +++ b/templates/repo-operations/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja @@ -0,0 +1,40 @@ +{% raw %}name: promote-{% endraw %}{{ _item.name }}{% raw %} + +# Generated from templates/repo-operations of @plexus-ms/cli: edit the template, never this file. +# After a green run of the workflow that runs on {% endraw %}{{ _item.source }}{% raw %}, the branch {% endraw %}{{ _item.name }}{% raw %} promotes from: plx promote fast-forwards {% endraw %}{{ _item.branch }}{% raw %} to the head of {% endraw %}{{ _item.source }}{% raw %}, and changes nothing where that is no fast-forward. It pushes as the tenant's GitHub App, so that deploy runs there. + +on: + workflow_run: + workflows: [on_commit, deploy] + types: [completed] + branches: [{% endraw %}{{ _item.source }}{% raw %}] + +permissions: + contents: read + +jobs: + promote: + if: ${{ github.event.workflow_run.conclusion == 'success' }} + runs-on: ${{ (vars.CI_STRATEGY || '{% endraw %}{{ ci_jobs_strategy }}{% raw %}') == 'github' && 'ubuntu-latest' || 'ci-repo' }} + # One promotion at a time, never cancelled: each moves the branch to the head it finds. + concurrency: + group: promote-{% endraw %}{{ _item.name }}{% raw %} + cancel-in-progress: false + steps: + # The first checkout brings the mise.toml that pins plx and plx-ci. Setup mints the App's token, and the second + # checkout persists it with the whole history, which plx promote tells a fast-forward by. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: jdx/mise-action@7e2b3c3d1450331892809a84e22e30e3f52c1e92 # v5.5.0 + with: + cache: ${{ runner.environment == 'github-hosted' }} + - id: setup + env: + GH_CLIENT_ID: ${{ vars.GH_CLIENT_ID }} + GH_PRIVATE_KEY: ${{ secrets.GH_PRIVATE_KEY }}{% endraw %}{% if ci_service_account %}{% raw %} + OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}{% endraw %}{% endif %}{% raw %} + run: plx-ci setup promote + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + token: ${{ steps.setup.outputs.app-token }} + - run: plx -y promote {% endraw %}{{ _item.name }} diff --git a/templates/repo-operations/files/.github/workflows/deploy.yml.jinja b/templates/repo-operations/files/.github/workflows/{% if declared_environments %}deploy.yml{% endif %}.jinja similarity index 85% rename from templates/repo-operations/files/.github/workflows/deploy.yml.jinja rename to templates/repo-operations/files/.github/workflows/{% if declared_environments %}deploy.yml{% endif %}.jinja index f3f14990..105a6a34 100644 --- a/templates/repo-operations/files/.github/workflows/deploy.yml.jinja +++ b/templates/repo-operations/files/.github/workflows/{% if declared_environments %}deploy.yml{% endif %}.jinja @@ -1,12 +1,12 @@ {% raw %}name: deploy # Generated from templates/repo-operations of @plexus-ms/cli: edit the template, never this file. -# On a push to main that changes a stack, or started by hand, where it can be run dry: the job deploy deploys every stack of the repo, each of third-party software, into production. +# On a push to the branch of an environment the repo declares, and on no other, or started by hand on one, where it can be run dry: the job deploy deploys every stack of the repo, each of third-party software, to the environment of the branch. on: + # No paths filter: a branch created at a known commit pushes no files and would start nothing. push: - branches: [main] - paths: ['stack/**', 'stacks/**'] + branches: [{% endraw %}{{ declared_environments | map(attribute='branch') | join(', ') }}{% raw %}] workflow_dispatch: inputs: dry_run: @@ -20,9 +20,10 @@ permissions: jobs: deploy: runs-on: ${{ (vars.CI_STRATEGY || '{% endraw %}{{ ci_jobs_strategy }}{% raw %}') == 'github' && 'ubuntu-latest' || 'ci-delivery' }} - # One deploy of production at a time, the newest push waiting; a deploy that runs is never cancelled. + # One deploy of an environment at a time, the newest push to its branch waiting; a deploy that runs is never + # cancelled. concurrency: - group: deploy-production + group: deploy-${{ github.ref }} cancel-in-progress: false # The job holds the deploy key and runs nothing of the repo's code: mise ignores every config file of the # checkout, and installs plx and what it runs on from the versions named here. @@ -67,7 +68,7 @@ jobs: ANSIBLE_COLLECTIONS_PATH: ${{ runner.temp }}/collections OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.DEPLOY_VAULT_TOKEN }} PLX_DRY_RUN: ${{ inputs.dry_run }} - run: env -u OP_CONNECT_HOST -u OP_CONNECT_TOKEN plx deploy --environment production{% endraw %} + run: env -u OP_CONNECT_HOST -u OP_CONNECT_TOKEN plx deploy{% endraw %} {%- if ci_overlay == 'netbird' %}{% raw %} - if: ${{ always() && steps.setup.outputs.joined == 'true' }} run: sudo netbird down || true{% endraw %} diff --git a/templates/repo-operations/files/PLEXUS.md.jinja b/templates/repo-operations/files/PLEXUS.md.jinja index 8396c2e7..f5eba47c 100644 --- a/templates/repo-operations/files/PLEXUS.md.jinja +++ b/templates/repo-operations/files/PLEXUS.md.jinja @@ -2,6 +2,6 @@ - `plx new stacks/ stack` gives a stack of third-party software a compose file of `services: {}` (`plx new stack stack` for the one stack of a repo that has one, which also needs `repo` in this marker, the repo's name). For `plx doctor` to pass, add its services, each with its image pinned and the label `plexus.tenant: {{ tenant }}`. The service that serves it publishes `127.0.0.1:${PLEXUS_LOOPBACK_PORT:?set by the platform playbook}:`, as the one port of the stack, declares a healthcheck, and loads under `env_file` both `.env` and `.env.secret`, the latter with `required: false`. -- `plx deploy --environment ` deploys every stack that has a file for that environment, to the host the file names; the workflow `deploy` does it into production. +- `plx deploy --environment ` deploys every stack that has a file for that environment, to the host the file names; the workflow `deploy` deploys each environment on a push to its branch. - `mise :platform` applies the platform layer{% if infrastructure %}, `mise :infrastructure` the infrastructure layer{% endif %}; `mise :check` checks the repo and `mise :test` runs check first. - The Plexus version the repo is on is the `version` of this marker, and its `plx` pin in `mise.toml` follows it, the collections in `requirements.yml` pinned to the same. diff --git a/templates/repo-operations/template.yml b/templates/repo-operations/template.yml index dbf232ea..8f6fff37 100644 --- a/templates/repo-operations/template.yml +++ b/templates/repo-operations/template.yml @@ -123,6 +123,17 @@ questions: default: "" when: "{{ housekeeping }}" +# The environments the root marker declares, as plx computes them for every render: the branches the workflows run +# on, and one promotion workflow for each that promotes itself; and whether the promotion hands its setup the vault's +# token, which nothing here asks, so that it reads the App's credentials from the vault as plx-update does. +reads: + declared_environments: + ci_service_account: + default: true + +each: + ".github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja": declared_environments + policies: # The marker is born once: its body is the repo's own prose, which an update would conflict with, and # its frontmatter is plx's. diff --git a/templates/repo-turbo/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja b/templates/repo-turbo/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja new file mode 100644 index 00000000..2fa92076 --- /dev/null +++ b/templates/repo-turbo/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja @@ -0,0 +1,40 @@ +{% raw %}name: promote-{% endraw %}{{ _item.name }}{% raw %} + +# Generated from templates/repo-turbo of @plexus-ms/cli: edit the template, never this file. +# After a green run of the workflow that runs on {% endraw %}{{ _item.source }}{% raw %}, the branch {% endraw %}{{ _item.name }}{% raw %} promotes from: plx promote fast-forwards {% endraw %}{{ _item.branch }}{% raw %} to the head of {% endraw %}{{ _item.source }}{% raw %}, and changes nothing where that is no fast-forward. It pushes as the tenant's GitHub App, so that on_push runs there. + +on: + workflow_run: + workflows: [on_commit, on_push] + types: [completed] + branches: [{% endraw %}{{ _item.source }}{% raw %}] + +permissions: + contents: read + +jobs: + promote: + if: ${{ github.event.workflow_run.conclusion == 'success' }} + runs-on: ${{ (vars.CI_STRATEGY || '{% endraw %}{{ ci_jobs_strategy }}{% raw %}') == 'github' && 'ubuntu-latest' || 'ci-repo' }} + # One promotion at a time, never cancelled: each moves the branch to the head it finds. + concurrency: + group: promote-{% endraw %}{{ _item.name }}{% raw %} + cancel-in-progress: false + steps: + # The first checkout brings the mise.toml that pins plx and plx-ci. Setup mints the App's token, and the second + # checkout persists it with the whole history, which plx promote tells a fast-forward by. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: jdx/mise-action@7e2b3c3d1450331892809a84e22e30e3f52c1e92 # v5.5.0 + with: + cache: ${{ runner.environment == 'github-hosted' }} + - id: setup + env: + GH_CLIENT_ID: ${{ vars.GH_CLIENT_ID }} + GH_PRIVATE_KEY: ${{ secrets.GH_PRIVATE_KEY }}{% endraw %}{% if ci_service_account %}{% raw %} + OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}{% endraw %}{% endif %}{% raw %} + run: plx-ci setup promote + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + token: ${{ steps.setup.outputs.app-token }} + - run: plx -y promote {% endraw %}{{ _item.name }} diff --git a/templates/repo-turbo/files/.github/workflows/{% if not publishes_packages %}on_commit.yml{% endif %}.jinja b/templates/repo-turbo/files/.github/workflows/{% if not publishes_packages %}on_commit.yml{% endif %}.jinja index d1befe99..a7d82768 100644 --- a/templates/repo-turbo/files/.github/workflows/{% if not publishes_packages %}on_commit.yml{% endif %}.jinja +++ b/templates/repo-turbo/files/.github/workflows/{% if not publishes_packages %}on_commit.yml{% endif %}.jinja @@ -1,11 +1,15 @@ {% raw %}name: on_commit # Generated from templates/repo-turbo of @plexus-ms/cli: edit the template, never this file. -# On a push to any branch but main and develop: the job repo runs test, which runs check first; a newer push cancels it. +# On a push to any branch but those of the declared environments, main among them: the job repo runs test, which runs check first; a newer push cancels it. on: - push: - branches-ignore: [main, develop] + push:{% endraw %} +{%- if declared_environments %} + branches-ignore: [{{ declared_environments | map(attribute='branch') | join(', ') }}] +{%- else %} + branches: ['**'] +{%- endif %}{% raw %} paths-ignore: ['**/*.md'] permissions: diff --git a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja b/templates/repo-turbo/files/.github/workflows/{% if publishes_packages or declared_environments %}on_push.yml{% endif %}.jinja similarity index 95% rename from templates/repo-turbo/files/.github/workflows/on_push.yml.jinja rename to templates/repo-turbo/files/.github/workflows/{% if publishes_packages or declared_environments %}on_push.yml{% endif %}.jinja index 184aca16..09765e31 100644 --- a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja +++ b/templates/repo-turbo/files/.github/workflows/{% if publishes_packages or declared_environments %}on_push.yml{% endif %}.jinja @@ -65,12 +65,12 @@ jobs: {% endraw %}{% else %}{% raw %}name: on_push # Generated from templates/repo-turbo of @plexus-ms/cli: edit the template, never this file. -# On a push to main or develop: the job repo runs test, build, e2e and publish, then the job deploy deploys every stack. +# On a push to the branch of an environment the repo declares, and on no other, or started by hand on one: the job repo runs test, build, e2e and publish, then the job deploy deploys every stack to the environment of the branch. on: # No paths filter: a branch created at a known commit pushes no files and would start nothing. push: - branches: [main, develop] + branches: [{% endraw %}{{ declared_environments | map(attribute='branch') | join(', ') }}{% raw %}] workflow_dispatch: permissions: @@ -86,7 +86,10 @@ jobs: contents: read packages: write steps: + # The whole history with its tags, from which the images' version is told. - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 - uses: jdx/mise-action@7e2b3c3d1450331892809a84e22e30e3f52c1e92 # v5.5.0 with: cache: ${{ runner.environment == 'github-hosted' }} diff --git a/templates/repo-turbo/template.yml b/templates/repo-turbo/template.yml index 3f6aedfd..19125093 100644 --- a/templates/repo-turbo/template.yml +++ b/templates/repo-turbo/template.yml @@ -119,6 +119,14 @@ questions: 'abcdefghijklmnopqrstuvwxyz0123456789.-' %}x{% endif %}{% endfor %}{% endset %}{% if bad %}A host name or IPv4 address, as in ci-cache.example.internal, or empty{% endif %}{% endif %} +# The environments the root marker declares, as plx computes them for every render: one promotion workflow for each +# that promotes itself, and the branches the workflows run on. +reads: + declared_environments: + +each: + ".github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja": declared_environments + policies: # The marker is born once: its body is the repo's own prose, which an update would conflict with, and # its frontmatter is plx's. From 301e32cbc16fea811902a62b6c4fe30286390ae9 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 10:51:13 +0100 Subject: [PATCH 08/21] Test plx-ci setup promote and the job deploy refused off an environment's branch setup promote mints the App's token with contents and workflows write, so that the promoting push starts the pipeline of the environment's branch. A job deploy is refused off a declared environment's branch in whatever workflow mounts it, the operations repo's deploy among them. PLX-303 Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/setup.test.ts | 37 +++++++++++++++++++ .../cli-ci/src/commands/setupAppToken.test.ts | 7 +++- .../cli-ci/src/commands/setupUsage.test.ts | 5 +++ 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/packages/cli-ci/src/commands/setup.test.ts b/packages/cli-ci/src/commands/setup.test.ts index a087bfcf..50c61323 100644 --- a/packages/cli-ci/src/commands/setup.test.ts +++ b/packages/cli-ci/src/commands/setup.test.ts @@ -480,6 +480,43 @@ for (const job of ['repo', 'deploy'] as const) { }); } +// The job deploy is refused off an environment's branch in whatever workflow mounts it: an operations repo's is +// `deploy`, and a person can start it by hand on any branch or tag. +for (const workflow of ['deploy', 'on_push', 'anything']) { + for (const [ref, type] of [ + ['main', 'branch'], + ['feature-x', 'branch'], + ['env/preview', 'branch'], + ['env/staging', 'tag'], + ] as const) + test(`a deploy job of ${workflow} on the ${type} ${ref} fails in one line before anything is read`, () => { + const run = runJob(['deploy'], { + env: { ...CONNECT, ...DEPLOY_KEY, ...RUN(workflow, ref, 'workflow_dispatch', type) }, + vault: VAULT, + marker: DECLARES, + }); + assert.equal(run.status, 1, run.log); + assert.deepEqual(run.calls, []); + assert.match( + run.log, + new RegExp( + `${workflow} on ${type === 'tag' ? 'tag ' : ''}${ref.replace('/', '\\/')} deploys nowhere: this repo deploys from env/staging and env/production`, + ), + ); + assert.equal(run.log.trim().split('\n').length, 1, run.log); + }); + test(`a deploy job of ${workflow} on a declared environment's branch is not refused`, () => { + for (const event of ['push', 'workflow_dispatch']) { + const run = runJob(['deploy'], { + env: { ...CONNECT, ...DEPLOY_KEY, ...RUN(workflow, 'env/production', event) }, + vault: VAULT, + marker: DECLARES, + }); + assert.equal(run.status, 0, run.log); + } + }); +} + test('a branch named like a property of every object deploys nowhere either', () => { const run = runJob(['repo'], { env: { ...CONNECT, ...RUN('on_push', 'constructor') }, diff --git a/packages/cli-ci/src/commands/setupAppToken.test.ts b/packages/cli-ci/src/commands/setupAppToken.test.ts index d553b852..b2fc0a0b 100644 --- a/packages/cli-ci/src/commands/setupAppToken.test.ts +++ b/packages/cli-ci/src/commands/setupAppToken.test.ts @@ -1,5 +1,6 @@ // plx-ci setup in a job that pushes to its own repo as the tenant's GitHub App: the job that commits the changeset a -// bump owes (`changeset`) and the job that takes a version (`update`). The App's token is minted for the job's repo +// bump owes (`changeset`), the job that takes a version (`update`) and the one that promotes an environment +// (`promote`), whose push of the environment's branch must start the pipeline there. The App's token is minted for the job's repo // with the permissions the job needs, from the App's credentials on the forge, or without them from the vault. import assert from 'node:assert/strict'; import { createVerify, generateKeyPairSync } from 'node:crypto'; @@ -38,6 +39,8 @@ const masksFirst = (log: string): string[] => { for (const [job, permissions] of [ ['changeset', { contents: 'write' }], ['update', { contents: 'write', pull_requests: 'write', workflows: 'write' }], + // A fast-forward that brings a changed workflow file onto the environment's branch needs workflows. + ['promote', { contents: 'write', workflows: 'write' }], ] as const) { test(`${job === 'update' ? 'an' : 'a'} ${job} job is handed a token of the tenant’s App for its own repo, with ${Object.keys(permissions).join(', ')} write, from the forge’s credentials`, () => { const run = runJob([job], { env: FORGE_APP }); @@ -146,7 +149,7 @@ test('a job on a runner without op installs it to read the App’s credentials f ); }); -for (const job of ['changeset', 'update'] as const) +for (const job of ['changeset', 'update', 'promote'] as const) test(`${job}: a job with neither the forge’s credentials nor the vault’s fails in one line that names both ways, and reads nothing`, () => { const run = runJob([job], { vault: VAULT }); assert.equal(run.status, 1, run.log); diff --git a/packages/cli-ci/src/commands/setupUsage.test.ts b/packages/cli-ci/src/commands/setupUsage.test.ts index 07fd01df..4457d034 100644 --- a/packages/cli-ci/src/commands/setupUsage.test.ts +++ b/packages/cli-ci/src/commands/setupUsage.test.ts @@ -14,6 +14,11 @@ for (const [args, belongs] of [ ['deploy', '--private-packages'], /--private-packages is an option of the jobs repo, changeset and update, not of deploy/, ], + [['promote', '--publishes', 'npm'], /--publishes is an option of the job repo, not of promote/], + [ + ['promote', '--private-packages'], + /--private-packages is an option of the jobs repo, changeset and update, not of promote/, + ], ] as const) test(`setup ${args.join(' ')} is refused in one line that names the kind the option belongs to`, () => { const job = runJob([...args], { env: CONNECT }); From 87944f61cb0172db65631001a4e7d9ec95f03b23 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 10:52:16 +0100 Subject: [PATCH 09/21] plx-ci setup promote, and the job deploy refused off an environment's branch in any workflow setup promote mints the App's token with contents and workflows write for the job that fast-forwards an environment's branch. The refusal of a run on a branch that deploys nowhere covers a deploy job in whatever workflow mounts it, so that a deploy started by hand on another branch or a tag fails before any host is reached. PLX-303 Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/setup.ts | 37 +++++++++++++++++---------- packages/cli-ci/src/core/setup.ts | 30 +++++++++++++--------- 2 files changed, 41 insertions(+), 26 deletions(-) diff --git a/packages/cli-ci/src/commands/setup.ts b/packages/cli-ci/src/commands/setup.ts index 2025ba9e..e2ce9c08 100644 --- a/packages/cli-ci/src/commands/setup.ts +++ b/packages/cli-ci/src/commands/setup.ts @@ -1,4 +1,4 @@ -// plx-ci setup : prepare a job of a repo's +// plx-ci setup : prepare a job of a repo's // workflows in one step, before every step that needs what it prepares, so // that each later step is one command. What it does depends on what the job // is for: @@ -21,20 +21,25 @@ // owes, and pushes it to the bot's branch. // update the job that takes a version (plx update): pushes a branch // that may change a workflow file, and opens its pull request. +// promote the job that promotes an environment (plx promote): +// fast-forwards the environment's branch, which may bring a +// changed workflow file onto it, as the App, so that the push +// starts the pipeline there. // -// changeset and update can run before the checkout, which they make with the -// token this step hands them. Every kind also depends on where it runs: a +// changeset, update and promote can run before the checkout, which they make +// with the token this step hands them. Every kind also depends on where it runs: a // forge runner (RUNNER_ENVIRONMENT github-hosted) or a slot of the tenant's // runner host, which is on the overlay already and whose repo slots carry // their host's cache servers. In order: // -// 1. Refuse, before anything is read, a run of the workflow on_push (the -// forge's GITHUB_WORKFLOW) of an app repo, a repo job publishing images or -// a deploy job, on a branch that deploys nowhere, or on a tag, as a run -// started by hand can be: the command fails in one line naming the branch -// and the branches that deploy. A package repo's on_push, started by hand -// on any branch for snapshot versions, is not refused. -// 2. changeset and update: take the tenant's GitHub App from the forge where +// 1. Refuse, before anything is read, a deploy job in any workflow (the +// forge's GITHUB_WORKFLOW), and a repo job publishing images in the +// workflow on_push of an app repo, on a branch that deploys nowhere, or +// on a tag, as a run started by hand can be: the command fails in one +// line naming the branch and the branches that deploy. A package repo's +// on_push, started by hand on any branch for snapshot versions, is not +// refused. +// 2. changeset, update and promote: take the tenant's GitHub App from the forge where // the step has both the variable GH_CLIENT_ID and the secret // GH_PRIVATE_KEY in its environment, masking the key, and then read // nothing from the vault. @@ -55,7 +60,7 @@ // runner itself names cache servers and tokens, as a slot of a runner // host does. A repo job publishing images in the workflow on_push, whose // images carry the repo's one key, a deploy job that joins the overlay, -// and a changeset or update job without the App on the forge fail there, +// and a changeset, update or promote job without the App on the forge fail there, // in one line that names the credentials missing; the last names both // ways to the App. // 4. Read from the vault `-ci` what the job needs, every read through @@ -76,7 +81,8 @@ // without it fails for in one line, as nothing can be // deployed // changeset without the App on the forge: github-app/client-id and -// update github-app/private-key +// update, github-app/private-key +// promote // A key pasted into a one-line field, of the vault or of the repository // secret, gets its lines back, and each of them is masked as it is // restored. @@ -92,6 +98,7 @@ // changeset the job's own repo, contents write // update the job's own repo, contents, pull requests and workflows // write +// promote the job's own repo, contents and workflows write // Each call waits 10 s for a connection and 30 s for its answer. Where // GitHub refuses the App (401), finds it not installed on the repo // (404), or does not answer, the job fails in one line naming the App's @@ -130,8 +137,9 @@ // 10. Hand later steps what they need. As outputs of the step: // repo server-actions-key, publishing images, for the build and // publish steps alone -// changeset app-token, for the checkout that pushes and, in update, -// update for gh (GH_TOKEN) +// changeset, app-token, for the checkout that pushes and, in update, +// update, for gh (GH_TOKEN) +// promote // repo and joined=true, where the job joined the overlay // deploy // As variables of the job (GITHUB_ENV): DOCKER_CONFIG; with an npmrc, @@ -153,6 +161,7 @@ // plx-ci setup repo --publishes github // plx-ci setup deploy --overlay netbird // plx-ci setup changeset +// plx-ci setup promote // plx-ci setup update --private-packages import { UsageError } from '@plexus-ms/lib'; diff --git a/packages/cli-ci/src/core/setup.ts b/packages/cli-ci/src/core/setup.ts index 57249deb..92bdf89f 100644 --- a/packages/cli-ci/src/core/setup.ts +++ b/packages/cli-ci/src/core/setup.ts @@ -19,19 +19,22 @@ import { ghOf } from './gh.ts'; import { opOf } from './op.ts'; import { mask, type Vault, vaultAccess, vaultOf, withoutSecrets } from './vault.ts'; -export const JOBS = ['repo', 'deploy', 'changeset', 'update'] as const; +export const JOBS = ['repo', 'deploy', 'changeset', 'update', 'promote'] as const; export type Job = (typeof JOBS)[number]; /** * The jobs that push to their own repo as the tenant's GitHub App, and the * permissions of the App's token each is handed: the changeset job commits to - * the update bot's branch, and the update job pushes a branch that may change - * a workflow file and opens its pull request. Named as GitHub's API names them - * (GitHub's docs, "Create an installation access token for an app"). + * the update bot's branch, the update job pushes a branch that may change + * a workflow file and opens its pull request, and the promote job + * fast-forwards an environment's branch, which may bring a changed workflow + * file onto it. Named as GitHub's API names them (GitHub's docs, "Create an + * installation access token for an app"). */ const PUSHES: Partial>> = { changeset: { contents: 'write' }, update: { contents: 'write', pull_requests: 'write', workflows: 'write' }, + promote: { contents: 'write', workflows: 'write' }, }; /** @@ -72,19 +75,22 @@ const NETBIRD_VERSION = '0.82.0'; const cacheHostOf = (env: NodeJS.ProcessEnv): string | undefined => env.PLX_TURBO_CACHE_HOST?.trim() || undefined; /** - * A run of the workflow on_push, which a person can start on any branch, on a - * branch that deploys nowhere would build and push images and only then fail - * 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. + * A run on a branch that deploys nowhere, or on a tag, as a run started by + * hand can be, fails here, before anything is read, built or pushed: a deploy + * job in whatever workflow mounts it, and a repo job publishing images in the + * workflow on_push, which would build and push them and only then fail in the + * deploy. The workflow is told by its name, which the forge hands every step; + * a step that names none runs in no workflow and is not refused. */ -async function refuseOnPushWithoutEnvironment(ctx: Context, env: NodeJS.ProcessEnv): Promise { - if (env.GITHUB_WORKFLOW !== 'on_push') return; +async function refuseOffEnvironment(ctx: Context, env: NodeJS.ProcessEnv, deploys: boolean): Promise { + const workflow = env.GITHUB_WORKFLOW; + if (!workflow || (!deploys && workflow !== 'on_push')) return; const ref = env.GITHUB_REF_NAME ?? ''; const tag = env.GITHUB_REF_TYPE === 'tag'; 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: ${declarationRefusal(declared) ?? `this repo deploys from ${describeBranches(declared, 'and')}; run on_push there`}`, + `${workflow} on ${tag ? 'tag ' : ''}${ref} deploys nowhere: ${declarationRefusal(declared) ?? `this repo deploys from ${describeBranches(declared, 'and')}; run ${workflow} there`}`, ); } @@ -146,7 +152,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') await refuseOnPushWithoutEnvironment(ctx, env); + if (images || options.job === 'deploy') await refuseOffEnvironment(ctx, env, options.job === 'deploy'); const repository = need('GITHUB_REPOSITORY', env); const owner = ownerOf(repository); const repo = repository.split('/')[1] ?? repository; From e51cd705599876b0a020297c9d38e0f0a105ccaa Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 10:52:33 +0100 Subject: [PATCH 10/21] Test that plx deploy --environment refuses a name the repo does not declare PLX-303 Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/commands/deploy.test.ts | 51 +++++++++++++++++++++--- 1 file changed, 46 insertions(+), 5 deletions(-) diff --git a/packages/cli/src/commands/deploy.test.ts b/packages/cli/src/commands/deploy.test.ts index 9de04bc4..f87d81ba 100644 --- a/packages/cli/src/commands/deploy.test.ts +++ b/packages/cli/src/commands/deploy.test.ts @@ -203,6 +203,9 @@ interface Fixture { * A checkout with the apps shop and admin and the stacks shop, admin and docs, which has no app; a file for staging * in each, shop and admin on one host, docs on another as a user of its own and on its own port. */ +/** The declaration of one environment, staging, as a root marker's frontmatter holds it. */ +const STAGING = 'environments:\n staging:\n promotes_from: main\n'; + function fixture(prefix = 'case-'): Fixture { const root = mkdtempSync(join(scratch, prefix)); const repo = join(root, 'repo'); @@ -419,7 +422,7 @@ test('a repo whose stacks have zero apps deploys the same way: no image is resol const f = fixture(); const ops = join(f.root, 'operations'); put(ops, { - 'PLEXUS.md': '---\ntemplates: [repo-operations]\n---\n', + 'PLEXUS.md': '---\ntemplates: [repo-operations]\nenvironments:\n staging:\n promotes_from: main\n---\n', ...stack('docs', DOCS_COMPOSE), ...stack('wiki', DOCS_COMPOSE), ...environment('docs', 'staging', 'b.example.com'), @@ -470,6 +473,41 @@ test('a repo that declares no environment deploys from no branch, and a declarat assert.deepEqual(runs(f.fake), []); }); +test('--environment names a declared environment: any other name is refused before anything is read, and so is every name where the repo declares none or its declaration is invalid', async () => { + const f = fixture(); + const args = (name: string) => ['deploy', '-e', name, '--commit', SHA, '-C', f.repo]; + put(f.repo, { 'stack/qa.yaml': 'host: a.example.com\n' }); + for (const name of ['production', 'qa', 'main']) + await assert.rejects( + plx(args(name), f.fake), + (e: unknown) => + e instanceof UsageError && + e.message.includes(`--environment ${name}: the repo declares no environment \`${name}\`; it declares staging`), + name, + ); + // Also where the run stands on a declared branch: the name given is what is deployed, and it is refused. + await assert.rejects( + plx(args('production'), f.fake, { GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'env/staging' }), + UsageError, + ); + for (const marker of [ + '---\nrepo: shop\n---\n', + '---\nrepo: shop\nenvironments:\n staging:\n promotes_from: develop\n---\n', + ]) { + put(f.repo, { 'PLEXUS.md': marker }); + await assert.rejects( + plx(args('staging'), f.fake), + (e: unknown) => + e instanceof UsageError && + e.message.startsWith('--environment staging: ') && + /declares no environment; declare one|are invalid/.test(e.message), + marker, + ); + } + assert.deepEqual(runs(f.fake), []); + assert.equal(existsSync(join(f.fake, 'docker.log')), false); +}); + /** `plx` as its own process, which ends as a command line does: its exit code and what it wrote to stderr. */ function plxProcess(args: string[]): { status: number | null; stderr: string } { const bin = fileURLToPath(new URL('../bin.ts', import.meta.url)); @@ -541,7 +579,7 @@ test('an image the registry refuses to an anonymous client names the login it ne test('a checkout without a stack is refused, for there is nothing to deploy; a compose file inside an app is named as the old layout', async () => { const f = fixture(); const bare = join(f.root, 'bare'); - put(bare, { 'PLEXUS.md': '---\nrepo: shop\n---\n' }); + put(bare, { 'PLEXUS.md': `---\nrepo: shop\n${STAGING}---\n` }); const args = ['deploy', '-e', 'staging', '-C', bare]; await assert.rejects( plx(args, f.fake), @@ -566,6 +604,7 @@ test('a checkout without a stack is refused, for there is nothing to deploy; a c test('where no stack has a file for the environment, each is named, and the run fails, for nothing was deployed; it needs no Ansible', async () => { const f = fixture(); + put(f.repo, { 'PLEXUS.md': `---\nrepo: shop\n${STAGING} production:\n promotes_from: staging\n---\n` }); const noAnsible = fakes(join(f.root, 'no-ansible'), ['docker']); const err = await plx( staging(f).map((a) => (a === 'staging' ? 'production' : a)), @@ -668,6 +707,7 @@ test('a commit that YAML would read as a number goes in quoted, for PLEXUS_TAG a const ops = join(f.root, 'operations'); const numeric = `1234e5${'6'.repeat(34)}`; put(ops, { + 'PLEXUS.md': `---\n${STAGING}---\n`, ...stack( 'docs', `services:\n web:\n image: docker.io/acme/docs:1.2.3\n environment:\n RELEASE: \${PLEXUS_TAG}\n COMMIT: \${PLEXUS_COMMIT_SHA:-}\n`, @@ -752,7 +792,7 @@ test('a repo whose stack/ its root marker does not name is refused, naming the k const f = fixture(); const one = join(f.root, 'one'); put(one, { - 'PLEXUS.md': '---\ntemplates: [repo-turbo]\n---\n', + 'PLEXUS.md': `---\ntemplates: [repo-turbo]\n${STAGING}---\n`, 'apps/shop/Dockerfile': 'FROM scratch\n', 'stack/PLEXUS.md': '---\nprofile: stateless\n---\n', 'stack/compose.yaml': SHOP_COMPOSE, @@ -767,7 +807,7 @@ test('a repo whose stack/ its root marker does not name is refused, naming the k !/frontmatter/.test(e.message), ); assert.equal(existsSync(join(f.fake, 'ansible.log')), false); - put(one, { 'PLEXUS.md': '---\ntemplates: [repo-turbo]\nrepo: shop\n---\n' }); + put(one, { 'PLEXUS.md': `---\ntemplates: [repo-turbo]\nrepo: shop\n${STAGING}---\n` }); const err = await plx(args, f.fake); assert.deepEqual(summary(err), ['✓ shop-staging: deployed']); }); @@ -790,6 +830,7 @@ test('a repo whose stacks the loader finds a problem with is refused with every function operations(f: Fixture): string[] { const ops = join(f.root, 'operations'); put(ops, { + 'PLEXUS.md': `---\n${STAGING}---\n`, ...stack('docs', DOCS_COMPOSE), ...stack('wiki', DOCS_COMPOSE), ...environment('docs', 'staging', 'b.example.com'), @@ -1059,7 +1100,7 @@ test('against this machine’s Docker daemon: deployed, unchanged, one service r const repo = join(root, 'repo'); put(repo, { - 'PLEXUS.md': '---\nrepo: shop\n---\n', + 'PLEXUS.md': `---\nrepo: shop\n${STAGING}---\n`, 'apps/shop/Dockerfile': 'FROM busybox:1.37\n', 'apps/admin/Dockerfile': 'FROM busybox:1.37\n', [`stacks/${run}-shop/compose.yaml`]: `services: From f5571c53255f777f22d85090fa08e91444680c65 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 10:54:45 +0100 Subject: [PATCH 11/21] plx deploy --environment refuses a name the repo does not declare The name given must be an environment of the root marker's declaration; any other is refused before anything is read, naming those declared, and a repo that declares none, or whose declaration is invalid, deploys nowhere, with --environment as without. PLX-303 Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/commands/deploy.ts | 9 +++++++-- packages/lib/src/declaredEnvironments.ts | 10 ++++++++++ packages/lib/src/index.ts | 1 + 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/commands/deploy.ts b/packages/cli/src/commands/deploy.ts index 57e02f3d..af1c9dc9 100644 --- a/packages/cli/src/commands/deploy.ts +++ b/packages/cli/src/commands/deploy.ts @@ -3,8 +3,10 @@ // (§ 6 PLX-Delivery). lib's `deploy` does the work, and its header says how, // in order; this file maps the arguments and sets the exit code. // -// The environment is --environment, else follows from the branch of the -// forge's run (GITHUB_EVENT_NAME, GITHUB_REF_NAME). Nothing but the checkout +// The environment is --environment, which must name an environment the root +// marker declares, else follows from the branch of the forge's run +// (GITHUB_EVENT_NAME, GITHUB_REF_NAME); a repo that declares none, or whose +// declaration is invalid, deploys nowhere. Nothing but the checkout // is read: the host is in each stack's file, and the secrets the file points // at are read by the playbook, with the `op` of whoever runs the verb, in a job // with its service account's token (OP_SERVICE_ACCOUNT_TOKEN) and by a person @@ -23,6 +25,7 @@ import { deploy, describeBranches, environmentOf, + environmentRefusal, readDeclaredEnvironments, UsageError, } from '@plexus-ms/lib'; @@ -55,6 +58,8 @@ export function register(program: Command): void { throw new UsageError(`--commit ${opts.commit}: a full commit hash, 40 or 64 hex digits in lower case`); const env = process.env; const declared = await readDeclaredEnvironments(ctx, resolve(opts.dir)); + const refused = opts.environment ? environmentRefusal(declared, opts.environment) : undefined; + if (refused) throw new UsageError(`--environment ${opts.environment}: ${refused}`); const environment = environmentOf( declared, env.GITHUB_EVENT_NAME ?? '', diff --git a/packages/lib/src/declaredEnvironments.ts b/packages/lib/src/declaredEnvironments.ts index fabec0d9..b4f03dd8 100644 --- a/packages/lib/src/declaredEnvironments.ts +++ b/packages/lib/src/declaredEnvironments.ts @@ -109,6 +109,16 @@ export const declarationRefusal = (declared: DeclaredEnvironments): string | und ? `the repo declares no environment; declare one under ${code(ENVIRONMENTS_KEY)} in the root marker` : undefined; +/** + * Why `name` is no environment a run may deploy into: the declaration's refusal where no branch deploys, that the + * repo does not declare it, naming those it does, and undefined where it declares it. + */ +export const environmentRefusal = (declared: DeclaredEnvironments, name: string): string | undefined => + declarationRefusal(declared) ?? + (declared.environments.some((e) => e.name === name) + ? undefined + : `the repo declares no environment ${code(name)}; it declares ${declared.environments.map((e) => e.name).join(' and ')}`); + /** 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: [] }; diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index 44893f14..66f90480 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -44,6 +44,7 @@ export { ENVIRONMENTS_KEY, environmentBranch, environmentOfBranch, + environmentRefusal, readDeclaredEnvironments, templateAnswers, } from './declaredEnvironments.ts'; From c2e6af38158551ae34a60bfc13699efd2171f61e Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 10:57:04 +0100 Subject: [PATCH 12/21] Test that the templates render without the computed declaration The plx of an earlier version hands the templates of the version a repo takes the marker's answers alone; the templates then render as a repo that declares no environment, rather than fail the update. PLX-303 Co-Authored-By: Claude Opus 5.5 --- packages/lib/src/declaredEnvironments.test.ts | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/packages/lib/src/declaredEnvironments.test.ts b/packages/lib/src/declaredEnvironments.test.ts index e51848ff..66408fcd 100644 --- a/packages/lib/src/declaredEnvironments.test.ts +++ b/packages/lib/src/declaredEnvironments.test.ts @@ -1,5 +1,7 @@ import assert from 'node:assert/strict'; +import { join } from 'node:path'; import { test } from 'node:test'; +import { readTree, render } from '@plexus-ms/cli-template'; import { Context } from './context.ts'; import { declarationRefusal, @@ -10,6 +12,9 @@ import { readDeclaredEnvironments, templateAnswers, } from './declaredEnvironments.ts'; +import { templatesRoot } from './templatesRoot.ts'; +import { VARIABLES_FILE, variablesText } from './templateVersion.ts'; +import { CURRENT } from './testing/before.ts'; import { fakeIo, type Tree } from './testing/fakeIo.ts'; const TWO = { @@ -187,3 +192,20 @@ test('no declaration, an empty one and an invalid one give a render no environme test('declared_environments is computed and never answered: a given value is replaced', () => { assert.deepEqual(templateAnswers({ declared_environments: [{ name: 'qa' }] }).declared_environments, []); }); + +test('the templates given the answers alone, as the plx of an earlier version renders a version it takes, render as a repo that declares no environment', async () => { + for (const [names, answers] of [ + [['repo-turbo', 'updates'], { tenant: 'acme', environments: TWO }], + [['repo-operations', 'updates'], { tenant: 'acme', environments: TWO }], + [['stack'], { tenant: 'acme', profile: 'stateless' }], + ] as const) { + const variables = { bytes: Buffer.from(variablesText(CURRENT)), mode: 0o100644 }; + const trees = await Promise.all( + names.map(async (name) => new Map(await readTree(join(templatesRoot(), name))).set(VARIABLES_FILE, variables)), + ); + const result = render(trees, { ...answers }); + assert.deepEqual(result.errors, [], names.join(' ')); + for (const path of result.files.keys()) + assert.doesNotMatch(path, /on_push|deploy\.yml|promote-|staging|production/, `${names.join(' ')}: ${path}`); + } +}); From 5db1f66a6cb9ebdf5c4d3f07ca30029a71ef69f5 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 10:58:02 +0100 Subject: [PATCH 13/21] The templates read the computed declaration with an empty default So that the plx of an earlier version, which hands the templates of the version a repo takes the answers alone, renders them as for a repo that declares no environment instead of failing the update. PLX-303 Co-Authored-By: Claude Opus 5.5 --- packages/lib/src/declaredEnvironments.ts | 5 ++++- templates/repo-operations/template.yml | 7 +++++-- templates/repo-turbo/template.yml | 4 +++- templates/stack/template.yml | 4 +++- 4 files changed, 15 insertions(+), 5 deletions(-) diff --git a/packages/lib/src/declaredEnvironments.ts b/packages/lib/src/declaredEnvironments.ts index b4f03dd8..1510123f 100644 --- a/packages/lib/src/declaredEnvironments.ts +++ b/packages/lib/src/declaredEnvironments.ts @@ -32,7 +32,10 @@ // the order written, and empty where the declaration is invalid, so that no // template spells a branch and a repo whose declaration is invalid renders no // branch at all. It is computed for every render and never written into a -// marker; a value given for it is replaced. +// marker; a value given for it is replaced. The plx of an earlier version, +// which renders the templates of the version a repo takes and hands them the +// answers alone, computes none: the templates read it with an empty default, +// and render as for a repo that declares no environment. import { join } from 'node:path'; import { isMapping } from './compose.ts'; import type { Context } from './context.ts'; diff --git a/templates/repo-operations/template.yml b/templates/repo-operations/template.yml index 8f6fff37..4ca33c20 100644 --- a/templates/repo-operations/template.yml +++ b/templates/repo-operations/template.yml @@ -124,10 +124,13 @@ questions: when: "{{ housekeeping }}" # The environments the root marker declares, as plx computes them for every render: the branches the workflows run -# on, and one promotion workflow for each that promotes itself; and whether the promotion hands its setup the vault's -# token, which nothing here asks, so that it reads the App's credentials from the vault as plx-update does. +# on, and one promotion workflow for each that promotes itself. The plx of an earlier version, which renders this one +# when a repo takes it, hands the answers alone, and it renders as for a repo that declares none. And whether the +# promotion hands its setup the vault's token, which nothing here asks, so that it reads the App's credentials from +# the vault as plx-update does. reads: declared_environments: + default: [] ci_service_account: default: true diff --git a/templates/repo-turbo/template.yml b/templates/repo-turbo/template.yml index 19125093..c2cf307a 100644 --- a/templates/repo-turbo/template.yml +++ b/templates/repo-turbo/template.yml @@ -120,9 +120,11 @@ questions: address, as in ci-cache.example.internal, or empty{% endif %}{% endif %} # The environments the root marker declares, as plx computes them for every render: one promotion workflow for each -# that promotes itself, and the branches the workflows run on. +# that promotes itself, and the branches the workflows run on. The plx of an earlier version, which renders this one +# when a repo takes it, hands the answers alone, and it renders as for a repo that declares none. reads: declared_environments: + default: [] each: ".github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja": declared_environments diff --git a/templates/stack/template.yml b/templates/stack/template.yml index a5ec4f14..028d0f81 100644 --- a/templates/stack/template.yml +++ b/templates/stack/template.yml @@ -4,10 +4,12 @@ name: stack # The enclosing repo's answer, and the environments its root marker declares as plx computes them for every render; -# whoever renders the stack passes both. +# whoever renders the stack passes both, but the plx of an earlier version, which renders this one when a repo takes +# it and hands it the answers alone: it renders as for a repo that declares none. reads: tenant: declared_environments: + default: [] questions: profile: From 1a089b925c23c6fcaaa7a992371b2c78b4786311 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 10:58:54 +0100 Subject: [PATCH 14/21] Test what taking the version does to the workflow that deploys A repo taken by the plx of an earlier version, or declaring no environment, has no on_push or deploy.yml after the update; one born with a declaration keeps its workflow, moved to the version. A repo of 0.138.0 deploying from main and develop gets its environments' workflows once it declares them and runs plx apply. PLX-303 Co-Authored-By: Claude Opus 5.5 --- newborns/update-released.test.ts | 66 +++++++++++++++++++++++++------- 1 file changed, 52 insertions(+), 14 deletions(-) diff --git a/newborns/update-released.test.ts b/newborns/update-released.test.ts index 8863810d..f189f57f 100644 --- a/newborns/update-released.test.ts +++ b/newborns/update-released.test.ts @@ -30,7 +30,7 @@ import { createServer, type Server } from 'node:http'; import { basename, dirname, join } from 'node:path'; import { after, before, test } from 'node:test'; import { parse } from 'yaml'; -import { close, git, open, sh, tryRun } from './helpers.ts'; +import { close, ENVIRONMENTS, git, open, sh, tryRun } from './helpers.ts'; import { startRegistry } from './registry.ts'; const RELEASED = '0.134.1'; @@ -181,8 +181,9 @@ async function repoAt( kind: 'app' | 'package' | 'operations', answers: string[] = [], ): Promise { - // Every repo is on main, its default branch, where an update lands. - const branch = 'main'; + // A released plx lands an app repo's update on develop, the branch it was born on; a plx of this checkout lands + // every repo's on its default branch, main. + const branch = kind === 'app' && (version === RELEASED || version === STACKED) ? 'develop' : 'main'; const templates = kind === 'operations' ? ['repo-operations', 'updates'] : ['repo-turbo', 'updates']; if (kind === 'package') answers = ['-a', 'publishes_packages=true', ...answers]; made += 1; @@ -212,6 +213,8 @@ async function take(by: string, repo: string, to: string) { return { ...ran, read: (path: string) => execFileSync('git', ['show', `plexus/${to}:${path}`], { cwd: origin, encoding: 'utf8' }), + /** Whether the branch holds a file at `path`. */ + has: (path: string) => spawnSync('git', ['cat-file', '-e', `plexus/${to}:${path}`], { cwd: origin }).status === 0, /** The lines of the files of the branch that hold `text`. */ lines: (text: string) => spawnSync('git', ['grep', '-n', '-F', text, `plexus/${to}`], { cwd: origin, encoding: 'utf8' }) @@ -221,8 +224,12 @@ async function take(by: string, repo: string, to: string) { } for (const kind of ['app', 'operations'] as const) { - /** The repo names `version` in its marker and pins plx at it, and no line of it holds `from`. */ - const moved = (taken: Awaited>, version: string, from: string) => { + /** + * The repo names `version` in its marker and pins plx at it, and no line of it holds `from`. The workflow that + * deploys is rendered from the declared environments, which the plx of a version before them cannot compute: a + * repo that declares none, or is taken by such a plx, has none after the update (`deploys` false). + */ + const moved = (taken: Awaited>, version: string, from: string, deploys: boolean) => { assert.ok(taken.ok, `${taken.output}\ngh was asked:\n${readFileSync(join(here, 'gh.log'), 'utf8')}`); assert.match(taken.read('PLEXUS.md'), new RegExp(`^version: ${version.replaceAll('.', '\\.')}$`, 'm')); assert.match( @@ -230,28 +237,31 @@ for (const kind of ['app', 'operations'] as const) { new RegExp(`"npm:@plexus-ms/cli" = \\{ version = "${version.replaceAll('.', '\\.')}"`), ); assert.deepEqual(taken.lines(from), [], `no line still names ${from}`); - // The job deploy of an app repo names the version itself, so the version moves it: the branch has the file at - // the new version, and nothing of the three-way merge is left in it. - if (kind === 'app') { - const push = taken.read('.github/workflows/on_push.yml'); + const workflow = kind === 'app' ? '.github/workflows/on_push.yml' : '.github/workflows/deploy.yml'; + assert.equal(taken.has(workflow), deploys, workflow); + // The job deploy names the version itself, so the version moves it: the branch has the file at the new version, + // and nothing of the three-way merge is left in it. + if (deploys) { + const text = taken.read(workflow); assert.match( - push, + text, new RegExp(`npm:@plexus-ms/cli\\[allow_low_downloads=true\\]@${version.replaceAll('.', '\\.')}`), ); - assert.doesNotMatch(push, /^(<<<<<<<|=======|>>>>>>>)/m); + assert.doesNotMatch(text, /^(<<<<<<<|=======|>>>>>>>)/m); } }; test(`${kind}: the released plx ${RELEASED} takes ${FIRST}, whose templates it can give no variable`, async () => { - moved(await take(RELEASED, await repoAt(RELEASED, kind), FIRST), FIRST, RELEASED); + moved(await take(RELEASED, await repoAt(RELEASED, kind), FIRST), FIRST, RELEASED, false); }); test(`${kind}: the plx of ${FIRST} takes the repo the released plx made, its old side fetched from the registry`, async () => { - moved(await take(FIRST, await repoAt(RELEASED, kind), FIRST), FIRST, RELEASED); + moved(await take(FIRST, await repoAt(RELEASED, kind), FIRST), FIRST, RELEASED, false); }); test(`${kind}: the plx of ${FIRST} takes ${SECOND}, both sides after the change`, async () => { - moved(await take(FIRST, await repoAt(FIRST, kind), SECOND), SECOND, FIRST); + const repo = await repoAt(FIRST, kind, ['-a', `environments=${ENVIRONMENTS}`]); + moved(await take(FIRST, repo, SECOND), SECOND, FIRST, true); }); } @@ -317,6 +327,34 @@ test(`operations: a stack of ${STACKED} gets no environment file from the update assert.doesNotMatch(taken.output, /staging\.yaml/); }); +test(`app: a repo of ${STACKED}, deploying from main and develop, takes ${NEXT} by its own plx: it deploys nothing until it declares its environments, which plx apply then renders`, async () => { + const repo = await repoAt(STACKED, 'app'); + const before = readFileSync(join(repo, '.github', 'workflows', 'on_push.yml'), 'utf8'); + assert.match(before, /branches: \[main, develop\]/); + const taken = await take(STACKED, repo, NEXT); + assert.ok(taken.ok, taken.output); + // The plx of the version the repo is on computes no declaration: on_push goes, and on_commit runs on every branch. + assert.equal(taken.has('.github/workflows/on_push.yml'), false); + assert.match(taken.read('.github/workflows/on_commit.yml'), /^ {4}branches: \['\*\*'\]$/m); + // On the version, whose update wrote the question's default into the marker, the person declares the environments + // there and applies them. + await sh('git', ['fetch', '-q', 'origin', `plexus/${NEXT}`], repo, env); + await sh('git', ['checkout', '-q', '-B', 'declared', 'FETCH_HEAD'], repo, env); + const marker = join(repo, 'PLEXUS.md'); + const text = readFileSync(marker, 'utf8'); + assert.match(text, /^environments: \{\}$/m); + writeFileSync(marker, text.replace(/^environments: \{\}\n/m, DECLARATION)); + const applied = await tryRun('node', [plxOf(NEXT), '-y', 'apply'], repo, env); + assert.ok(applied.ok, applied.output); + const workflows = join(repo, '.github', 'workflows'); + assert.match(readFileSync(join(workflows, 'on_push.yml'), 'utf8'), /branches: \[env\/staging, env\/production\]/); + assert.match( + readFileSync(join(workflows, 'on_commit.yml'), 'utf8'), + /branches-ignore: \[env\/staging, env\/production\]/, + ); + assert.match(readFileSync(join(workflows, 'promote-staging.yml'), 'utf8'), /plx -y promote 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'); From 77d71c3db4906fa4710363bfa1589308869b21db Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 11:03:15 +0100 Subject: [PATCH 15/21] Read the declared workflows of a newborn app repo of their own A repo that declares environments and has no stack fails the doctor's check for a file of each, so the newborn whose verbs run declares none, and the workflows are read from a second newborn that does. PLX-303 Co-Authored-By: Claude Opus 5.5 --- newborns/repo-turbo.test.ts | 88 +++++++++++++++++++++---------------- 1 file changed, 50 insertions(+), 38 deletions(-) diff --git a/newborns/repo-turbo.test.ts b/newborns/repo-turbo.test.ts index d427c1d2..87ac6431 100644 --- a/newborns/repo-turbo.test.ts +++ b/newborns/repo-turbo.test.ts @@ -81,17 +81,64 @@ const workflows = (dir: string) => readdirSync(join(dir, '.github', 'workflows') describe('an app repo', () => { let dir = ''; before(async () => { - dir = await newborn('app', { environments: ENVIRONMENTS }); + dir = await newborn('app'); }); - test('passes its own verbs, and its push workflow writes no tag', async () => { + test('passes its own verbs', async () => { await passesItsVerbs(dir, 'app'); - assert.doesNotMatch(read(dir, '.github/workflows/on_push.yml'), /contents: write/); + }); + + test('scopes a verb to a project by name: with what it depends on, e2e with what depends on it, and refuses an unknown name', async () => { + // Under packages/, where plx doctor asks nothing of a project, so that a refusal can only be the name's. + projects(dir, { + 'demo-lib': { verbs: ['build', 'check', 'test'] }, + 'demo-app': { verbs: ['build', 'check', 'test', 'e2e'], needs: ['demo-lib'] }, + 'demo-other': { verbs: ['build', 'check', 'test', 'e2e'] }, + }); + await relock(dir); + for (const verb of ['build', 'check', 'test']) { + const app = await mise(dir, verb, 'demo-app'); + assert.ok(app.ok, app.output); + assert.match(app.output, new RegExp(`${verb}-ran packages/demo-app`), `${verb} of the app`); + assert.match(app.output, new RegExp(`${verb}-ran packages/demo-lib`), `${verb} of what the app depends on`); + assert.doesNotMatch(app.output, new RegExp(`${verb}-ran packages/demo-other`), `${verb} of no other project`); + const lib = await mise(dir, verb, 'demo-lib'); + assert.ok(lib.ok, lib.output); + assert.match(lib.output, new RegExp(`${verb}-ran packages/demo-lib`)); + assert.doesNotMatch(lib.output, new RegExp(`${verb}-ran packages/demo-(app|other)`), `${verb} of no dependent`); + } + // test runs check first, with the same name. + const tested = await mise(dir, 'test', 'demo-lib'); + assert.match(tested.output, /check-ran packages\/demo-lib/); + assert.doesNotMatch(tested.output, /check-ran packages\/demo-(app|other)/, 'the name goes on to check'); + const suite = await mise(dir, 'e2e', 'demo-lib'); + assert.ok(suite.ok, suite.output); + assert.match(suite.output, /e2e-ran packages\/demo-app/, 'the suite of a dependent runs'); + assert.doesNotMatch(suite.output, /e2e-ran packages\/demo-other/, 'and of no unrelated project'); + // publish makes every app's image, so it accepts a name and ignores it. + for (const verb of VERDICTS.filter((v) => v !== 'publish')) { + const unknown = await mise(dir, verb, 'demo-none'); + assert.equal(unknown.ok, false, `${verb} refuses an unknown name`); + assert.match(unknown.output, /no app or package demo-none/, `${verb} says why`); + } + }); +}); +// A repo that declares its environments: its workflows are read, and its verbs are not run, since it has no stack, +// of which `plx doctor` asks a file for each environment. +describe('an app repo that declares its environments', () => { + let dir = ''; + before(async () => { + dir = await newborn('declared', { environments: ENVIRONMENTS }); }); test('runs on_push on the branch of each declared environment and on_commit on every other, and promotes staging from main after a green run there', () => { const branches = ['env/staging', 'env/production']; assert.deepEqual(workflow(dir, 'on_push').on.push, { branches }); + assert.doesNotMatch( + read(dir, '.github/workflows/on_push.yml'), + /contents: write/, + 'its push workflow writes no tag', + ); assert.deepEqual(workflow(dir, 'on_commit').on.push['branches-ignore'], branches); assert.deepEqual(workflows(dir), [ 'on_commit.yml', @@ -131,41 +178,6 @@ describe('an app repo', () => { .replaceAll('on main, the branch staging promotes from', 'on env/staging, the branch production promotes from'), ); }); - - test('scopes a verb to a project by name: with what it depends on, e2e with what depends on it, and refuses an unknown name', async () => { - // Under packages/, where plx doctor asks nothing of a project, so that a refusal can only be the name's. - projects(dir, { - 'demo-lib': { verbs: ['build', 'check', 'test'] }, - 'demo-app': { verbs: ['build', 'check', 'test', 'e2e'], needs: ['demo-lib'] }, - 'demo-other': { verbs: ['build', 'check', 'test', 'e2e'] }, - }); - await relock(dir); - for (const verb of ['build', 'check', 'test']) { - const app = await mise(dir, verb, 'demo-app'); - assert.ok(app.ok, app.output); - assert.match(app.output, new RegExp(`${verb}-ran packages/demo-app`), `${verb} of the app`); - assert.match(app.output, new RegExp(`${verb}-ran packages/demo-lib`), `${verb} of what the app depends on`); - assert.doesNotMatch(app.output, new RegExp(`${verb}-ran packages/demo-other`), `${verb} of no other project`); - const lib = await mise(dir, verb, 'demo-lib'); - assert.ok(lib.ok, lib.output); - assert.match(lib.output, new RegExp(`${verb}-ran packages/demo-lib`)); - assert.doesNotMatch(lib.output, new RegExp(`${verb}-ran packages/demo-(app|other)`), `${verb} of no dependent`); - } - // test runs check first, with the same name. - const tested = await mise(dir, 'test', 'demo-lib'); - assert.match(tested.output, /check-ran packages\/demo-lib/); - assert.doesNotMatch(tested.output, /check-ran packages\/demo-(app|other)/, 'the name goes on to check'); - const suite = await mise(dir, 'e2e', 'demo-lib'); - assert.ok(suite.ok, suite.output); - assert.match(suite.output, /e2e-ran packages\/demo-app/, 'the suite of a dependent runs'); - assert.doesNotMatch(suite.output, /e2e-ran packages\/demo-other/, 'and of no unrelated project'); - // publish makes every app's image, so it accepts a name and ignores it. - for (const verb of VERDICTS.filter((v) => v !== 'publish')) { - const unknown = await mise(dir, verb, 'demo-none'); - assert.equal(unknown.ok, false, `${verb} refuses an unknown name`); - assert.match(unknown.output, /no app or package demo-none/, `${verb} says why`); - } - }); }); test('publish runs the publish of every project after its build, never cached, then every app’s image, and no other verb; a name is ignored', async () => { From 70b13fc5fc6a39425d86cb35fbc3bf43f315883c Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 12:14:17 +0100 Subject: [PATCH 16/21] Test each through a merge, and the paths an item may name An item taken out of the list deletes its file, or keeps an edit to it as a conflict; an item added adds one, a rename does both, and an emptied list deletes every file. An item may name a path below the source's directory, and one outside the output is refused. PLX-303 Co-Authored-By: Claude Opus 5.5 --- packages/cli-template/src/each.test.ts | 81 +++++++++++++++++++++++++- 1 file changed, 79 insertions(+), 2 deletions(-) diff --git a/packages/cli-template/src/each.test.ts b/packages/cli-template/src/each.test.ts index 92cc1dbb..7161f00c 100644 --- a/packages/cli-template/src/each.test.ts +++ b/packages/cli-template/src/each.test.ts @@ -3,8 +3,8 @@ // and the file is rendered for every item with `_item` bound to it. import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { render } from './index.ts'; -import { listing, template } from './testing/trees.ts'; +import { gitMergeFile, merge, render } from './index.ts'; +import { type Listing, listing, template, tree } from './testing/trees.ts'; const fruits = 'name: basket\nquestions:\n fruits:\n type: yaml\n default: []\neach:\n "{{ _item.name }}.txt.jinja": fruits\n'; @@ -119,3 +119,80 @@ test('each names files below files/, each by a variable name', () => { assert.equal(result.errors[0]?.path, 'template.yml'); } }); + +/** A list of fruits, each item a name and a colour. */ +const basket = (...names: string[]) => names.map((name) => ({ name, colour: name === 'pear' ? 'green' : 'red' })); + +/** + * An update of a render from the list `before` to the list `after`, merged into the old render with `edits` made to + * it: the tree that results, and the outcome of each path. + */ +async function update(before: unknown[], after: unknown[], edits: Listing = {}) { + const old = render([template(fruits, file)], { fruits: before }); + const next = render([template(fruits, file)], { fruits: after }); + assert.deepEqual([old.errors, next.errors], [[], []]); + const result = await merge( + { + old: old.tree, + new: next.tree, + current: tree({ ...listing(old.tree), ...edits }), + files: { old: old.files, new: next.files }, + }, + gitMergeFile, + ); + return { tree: listing(result.tree), report: result.report.map(({ path, outcome }) => `${path}: ${outcome}`) }; +} + +test('an item taken out of the list deletes its file where it is unedited', async () => { + assert.deepEqual(await update(basket('apple', 'pear'), basket('apple')), { + tree: { 'apple.txt': 'A red apple.' }, + report: ['pear.txt: deleted'], + }); +}); + +test('an item taken out of the list whose file was edited keeps the edit, as a conflict', async () => { + const { tree: merged, report } = await update(basket('apple', 'pear'), basket('apple'), { + 'pear.txt': 'A green pear, ripe.', + }); + assert.deepEqual(report, ['pear.txt: conflicted']); + assert.match(String(merged['pear.txt']), /A green pear, ripe\./); +}); + +test('an item added to the list adds its file', async () => { + assert.deepEqual(await update(basket('apple'), basket('apple', 'pear')), { + tree: { 'apple.txt': 'A red apple.', 'pear.txt': 'A green pear.' }, + report: ['pear.txt: added'], + }); +}); + +test('an item renamed deletes the old file and adds the new one', async () => { + assert.deepEqual(await update(basket('apple'), [{ name: 'quince', colour: 'red' }]), { + tree: { 'quince.txt': 'A red quince.' }, + report: ['apple.txt: deleted', 'quince.txt: added'], + }); +}); + +test('an item emptied out of the list deletes every file the source rendered', async () => { + assert.deepEqual(await update(basket('apple', 'pear'), []), { + tree: {}, + report: ['apple.txt: deleted', 'pear.txt: deleted'], + }); +}); + +/** A source named by its item alone, each item a path. */ +const named = 'name: basket\nreads:\n fruits:\neach:\n "{{ _item }}.txt.jinja": fruits\n'; + +test('an item may name a path below the source’s directory', () => { + const result = render([template(named, { '{{ _item }}.txt.jinja': '{{ _item }}' })], { fruits: ['crate/apple'] }); + assert.deepEqual(result.errors, []); + assert.deepEqual(listing(result.tree), { 'crate/apple.txt': 'crate/apple' }); +}); + +test('an item that names a path outside the output is the error any such path is', () => { + for (const item of ['../x', '/abs', 'a/../../b']) { + const result = render([template(named, { '{{ _item }}.txt.jinja': '' })], { fruits: [item] }); + assert.equal(result.errors.length, 1, item); + assert.match(result.errors[0]?.message ?? '', /is forbidden: it is not inside the output/, item); + assert.deepEqual(listing(result.tree), {}, item); + } +}); From 709a4b489c8a73f9cfcddf5a125f915f65b475c7 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 12:14:36 +0100 Subject: [PATCH 17/21] Say in the header of files.ts what an item of each may name PLX-303 Co-Authored-By: Claude Opus 5.5 --- packages/cli-template/src/files.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/cli-template/src/files.ts b/packages/cli-template/src/files.ts index 35b7e315..2c4c3abc 100644 --- a/packages/cli-template/src/files.ts +++ b/packages/cli-template/src/files.ts @@ -23,7 +23,10 @@ // its variable holds, with `_item` bound to the item in its name and its text, // each rendering a file of its own at the path its name renders to; an empty // list renders it nowhere, and a variable that holds no list is an error -// naming the file. Its policy is the source's, for every path. +// naming the file. Its policy is the source's, for every path. An item may name +// a path below the source's directory, as any rendered part may hold slashes, +// and one that leaves the output is the error any such path is: the engine +// checks nothing else of an item, and the caller bounds what its items name. // // The templates of a render land in one tree, and every path is written once, // by one template. Two sources that render to one path are an error naming From ea9b709e43a0112027527403b020f4a6c6b33950 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 12:15:13 +0100 Subject: [PATCH 18/21] Derive the names a workflow's condition must not hold from the declarations it is rendered with PLX-303 Co-Authored-By: Claude Opus 5.5 --- packages/lib/src/pipeline.test.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index 1768a9ec..5773f4d6 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -504,13 +504,15 @@ test('a step of a promotion workflow is one command, and its only expressions ar }); test('no workflow a template renders holds a condition on an environment’s name or branch', () => { + // The names of every declaration the workflows are rendered with, their branches, and what names a run's branch. + const names = [CHOICES['repo-turbo'], CHOICES['repo-operations']].flatMap((choices) => + (choices.environments ?? []).flatMap((environments) => Object.keys(environments as object)), + ); + assert.ok(names.length > 0, 'the workflows are rendered with environments declared'); + const named = new RegExp([...new Set(names), 'env/', 'head_branch', 'github\\.ref'].join('|')); for (const { path, text } of renderedWorkflows()) for (const [, condition = ''] of text.matchAll(/^\s*(?:- )?if: (.*)$/gm)) - assert.doesNotMatch( - condition, - /env\/|qa|live|staging|production|head_branch|github\.ref/, - `${path}: ${condition}`, - ); + assert.doesNotMatch(condition, named, `${path}: ${condition}`); }); test('the job repo of on_push writes packages, the job deploy reads them, and nothing else of an app repo writes anything', async () => { From 32513719a3ae613a0fca96fcc8a8d066b3715422 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 12:16:36 +0100 Subject: [PATCH 19/21] Say what a promotion promotes, and why its token and the vault's The promotion workflow and the header of setup promote say that the head of the source as it stands when the job runs is promoted, whichever run started the job, and that a newer push's run promotes again; why the App's token has workflows write; and why setup is handed the vault's token where the repo holds no App credentials on the forge. PLX-303 Co-Authored-By: Claude Opus 5.5 --- packages/cli-ci/src/commands/setup.ts | 11 ++++++++--- packages/cli-ci/src/core/setup.ts | 5 +++-- ...te %}promote-{{ _item.name }}.yml{% endif %}.jinja | 6 +++++- ...te %}promote-{{ _item.name }}.yml{% endif %}.jinja | 6 +++++- 4 files changed, 21 insertions(+), 7 deletions(-) diff --git a/packages/cli-ci/src/commands/setup.ts b/packages/cli-ci/src/commands/setup.ts index e2ce9c08..517d1a1e 100644 --- a/packages/cli-ci/src/commands/setup.ts +++ b/packages/cli-ci/src/commands/setup.ts @@ -22,9 +22,14 @@ // update the job that takes a version (plx update): pushes a branch // that may change a workflow file, and opens its pull request. // promote the job that promotes an environment (plx promote): -// fast-forwards the environment's branch, which may bring a -// changed workflow file onto it, as the App, so that the push -// starts the pipeline there. +// fast-forwards the environment's branch, as the App, so that +// the push starts the pipeline there, to the head of its source +// as it stands when the job runs, whichever run started the job; +// a newer push's own run, once green, promotes again. The fast- +// forward may bring a changed workflow file onto the branch, +// hence the token's workflows write: GitHub's docs ask it of an +// App that edits a file under .github/workflows; that the forge +// refuses a fast-forward without it is relied on, not verified. // // changeset, update and promote can run before the checkout, which they make // with the token this step hands them. Every kind also depends on where it runs: a diff --git a/packages/cli-ci/src/core/setup.ts b/packages/cli-ci/src/core/setup.ts index 92bdf89f..1e38fbdd 100644 --- a/packages/cli-ci/src/core/setup.ts +++ b/packages/cli-ci/src/core/setup.ts @@ -28,8 +28,9 @@ export type Job = (typeof JOBS)[number]; * the update bot's branch, the update job pushes a branch that may change * a workflow file and opens its pull request, and the promote job * fast-forwards an environment's branch, which may bring a changed workflow - * file onto it. Named as GitHub's API names them (GitHub's docs, "Create an - * installation access token for an app"). + * file onto it (commands/setup.ts says why that asks for workflows write). + * Named as GitHub's API names them (GitHub's docs, "Create an installation + * access token for an app"). */ const PUSHES: Partial>> = { changeset: { contents: 'write' }, diff --git a/templates/repo-operations/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja b/templates/repo-operations/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja index a9d28c05..d445ec8f 100644 --- a/templates/repo-operations/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja +++ b/templates/repo-operations/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja @@ -1,7 +1,7 @@ {% raw %}name: promote-{% endraw %}{{ _item.name }}{% raw %} # Generated from templates/repo-operations of @plexus-ms/cli: edit the template, never this file. -# After a green run of the workflow that runs on {% endraw %}{{ _item.source }}{% raw %}, the branch {% endraw %}{{ _item.name }}{% raw %} promotes from: plx promote fast-forwards {% endraw %}{{ _item.branch }}{% raw %} to the head of {% endraw %}{{ _item.source }}{% raw %}, and changes nothing where that is no fast-forward. It pushes as the tenant's GitHub App, so that deploy runs there. +# After a green run of the workflow that runs on {% endraw %}{{ _item.source }}{% raw %}, the branch {% endraw %}{{ _item.name }}{% raw %} promotes from: plx promote fast-forwards {% endraw %}{{ _item.branch }}{% raw %} to the head of {% endraw %}{{ _item.source }}{% raw %} as it stands when the job runs, and changes nothing where that is no fast-forward. It pushes as the tenant's GitHub App, so that deploy runs there. on: workflow_run: @@ -27,14 +27,18 @@ jobs: - uses: jdx/mise-action@7e2b3c3d1450331892809a84e22e30e3f52c1e92 # v5.5.0 with: cache: ${{ runner.environment == 'github-hosted' }} + # The App's token has workflows write, which GitHub asks of an App that changes a file under .github/workflows. - id: setup env: GH_CLIENT_ID: ${{ vars.GH_CLIENT_ID }} GH_PRIVATE_KEY: ${{ secrets.GH_PRIVATE_KEY }}{% endraw %}{% if ci_service_account %}{% raw %} + # The App's credentials are in the vault where the repo holds none on the forge (PLX-Delivery/CIVault). OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}{% endraw %}{% endif %}{% raw %} run: plx-ci setup promote - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 token: ${{ steps.setup.outputs.app-token }} + # The source's head as it stands now, which can be newer than the commit whose run started this job; the run of + # that newer push, once green, promotes again. - run: plx -y promote {% endraw %}{{ _item.name }} diff --git a/templates/repo-turbo/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja b/templates/repo-turbo/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja index 2fa92076..0d813bf9 100644 --- a/templates/repo-turbo/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja +++ b/templates/repo-turbo/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja @@ -1,7 +1,7 @@ {% raw %}name: promote-{% endraw %}{{ _item.name }}{% raw %} # Generated from templates/repo-turbo of @plexus-ms/cli: edit the template, never this file. -# After a green run of the workflow that runs on {% endraw %}{{ _item.source }}{% raw %}, the branch {% endraw %}{{ _item.name }}{% raw %} promotes from: plx promote fast-forwards {% endraw %}{{ _item.branch }}{% raw %} to the head of {% endraw %}{{ _item.source }}{% raw %}, and changes nothing where that is no fast-forward. It pushes as the tenant's GitHub App, so that on_push runs there. +# After a green run of the workflow that runs on {% endraw %}{{ _item.source }}{% raw %}, the branch {% endraw %}{{ _item.name }}{% raw %} promotes from: plx promote fast-forwards {% endraw %}{{ _item.branch }}{% raw %} to the head of {% endraw %}{{ _item.source }}{% raw %} as it stands when the job runs, and changes nothing where that is no fast-forward. It pushes as the tenant's GitHub App, so that on_push runs there. on: workflow_run: @@ -27,14 +27,18 @@ jobs: - uses: jdx/mise-action@7e2b3c3d1450331892809a84e22e30e3f52c1e92 # v5.5.0 with: cache: ${{ runner.environment == 'github-hosted' }} + # The App's token has workflows write, which GitHub asks of an App that changes a file under .github/workflows. - id: setup env: GH_CLIENT_ID: ${{ vars.GH_CLIENT_ID }} GH_PRIVATE_KEY: ${{ secrets.GH_PRIVATE_KEY }}{% endraw %}{% if ci_service_account %}{% raw %} + # The App's credentials are in the vault where the repo holds none on the forge (PLX-Delivery/CIVault). OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}{% endraw %}{% endif %}{% raw %} run: plx-ci setup promote - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 token: ${{ steps.setup.outputs.app-token }} + # The source's head as it stands now, which can be newer than the commit whose run started this job; the run of + # that newer push, once green, promotes again. - run: plx -y promote {% endraw %}{{ _item.name }} From c89e2bd89fb07eabf24b25b7fc880ea7259ec81d Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 12:20:15 +0100 Subject: [PATCH 20/21] Say why the promotion is handed the vault's token: a repo that deploys keeps the App's credentials there PLX-303 Co-Authored-By: Claude Opus 5.5 --- ...to_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja | 2 +- templates/repo-operations/template.yml | 4 ++-- ...to_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/templates/repo-operations/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja b/templates/repo-operations/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja index d445ec8f..44caf845 100644 --- a/templates/repo-operations/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja +++ b/templates/repo-operations/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja @@ -32,7 +32,7 @@ jobs: env: GH_CLIENT_ID: ${{ vars.GH_CLIENT_ID }} GH_PRIVATE_KEY: ${{ secrets.GH_PRIVATE_KEY }}{% endraw %}{% if ci_service_account %}{% raw %} - # The App's credentials are in the vault where the repo holds none on the forge (PLX-Delivery/CIVault). + # A repo that deploys reads the vault, so the App's credentials are there and not on the forge (PLX-Delivery/CIVault). OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}{% endraw %}{% endif %}{% raw %} run: plx-ci setup promote - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/templates/repo-operations/template.yml b/templates/repo-operations/template.yml index 4ca33c20..78babb39 100644 --- a/templates/repo-operations/template.yml +++ b/templates/repo-operations/template.yml @@ -126,8 +126,8 @@ questions: # The environments the root marker declares, as plx computes them for every render: the branches the workflows run # on, and one promotion workflow for each that promotes itself. The plx of an earlier version, which renders this one # when a repo takes it, hands the answers alone, and it renders as for a repo that declares none. And whether the -# promotion hands its setup the vault's token, which nothing here asks, so that it reads the App's credentials from -# the vault as plx-update does. +# promotion hands its setup the vault's token, which nothing here asks: the repo deploys, so the App's credentials +# are in the vault (PLX-Delivery/CIVault), and a runner host's slot reads them through its Connect server instead. reads: declared_environments: default: [] diff --git a/templates/repo-turbo/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja b/templates/repo-turbo/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja index 0d813bf9..9de9735e 100644 --- a/templates/repo-turbo/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja +++ b/templates/repo-turbo/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja @@ -32,7 +32,7 @@ jobs: env: GH_CLIENT_ID: ${{ vars.GH_CLIENT_ID }} GH_PRIVATE_KEY: ${{ secrets.GH_PRIVATE_KEY }}{% endraw %}{% if ci_service_account %}{% raw %} - # The App's credentials are in the vault where the repo holds none on the forge (PLX-Delivery/CIVault). + # A repo that deploys reads the vault, so the App's credentials are there and not on the forge (PLX-Delivery/CIVault). OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}{% endraw %}{% endif %}{% raw %} run: plx-ci setup promote - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 From 0743777d53c780e551126b119b25caacbe9c90ff Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 12:43:16 +0100 Subject: [PATCH 21/21] Say only that a deploying repo's App credentials may be in the vault, and that the token finds them PLX-303 Co-Authored-By: Claude Opus 5.5 --- ...to_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja | 2 +- templates/repo-operations/template.yml | 4 ++-- ...to_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/templates/repo-operations/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja b/templates/repo-operations/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja index 44caf845..aca5b58c 100644 --- a/templates/repo-operations/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja +++ b/templates/repo-operations/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja @@ -32,7 +32,7 @@ jobs: env: GH_CLIENT_ID: ${{ vars.GH_CLIENT_ID }} GH_PRIVATE_KEY: ${{ secrets.GH_PRIVATE_KEY }}{% endraw %}{% if ci_service_account %}{% raw %} - # A repo that deploys reads the vault, so the App's credentials are there and not on the forge (PLX-Delivery/CIVault). + # A repo that deploys reads the vault, so the App's credentials may be there (PLX-Delivery/CIVault): the token finds them. OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}{% endraw %}{% endif %}{% raw %} run: plx-ci setup promote - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/templates/repo-operations/template.yml b/templates/repo-operations/template.yml index 78babb39..058ffc61 100644 --- a/templates/repo-operations/template.yml +++ b/templates/repo-operations/template.yml @@ -126,8 +126,8 @@ questions: # The environments the root marker declares, as plx computes them for every render: the branches the workflows run # on, and one promotion workflow for each that promotes itself. The plx of an earlier version, which renders this one # when a repo takes it, hands the answers alone, and it renders as for a repo that declares none. And whether the -# promotion hands its setup the vault's token, which nothing here asks: the repo deploys, so the App's credentials -# are in the vault (PLX-Delivery/CIVault), and a runner host's slot reads them through its Connect server instead. +# promotion hands its setup the vault's token, which nothing here asks: the repo deploys and so reads the vault, +# where the App's credentials may be (PLX-Delivery/CIVault), and the token is how the setup finds them there. reads: declared_environments: default: [] diff --git a/templates/repo-turbo/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja b/templates/repo-turbo/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja index 9de9735e..8cb40a0b 100644 --- a/templates/repo-turbo/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja +++ b/templates/repo-turbo/files/.github/workflows/{% if _item.auto_promote %}promote-{{ _item.name }}.yml{% endif %}.jinja @@ -32,7 +32,7 @@ jobs: env: GH_CLIENT_ID: ${{ vars.GH_CLIENT_ID }} GH_PRIVATE_KEY: ${{ secrets.GH_PRIVATE_KEY }}{% endraw %}{% if ci_service_account %}{% raw %} - # A repo that deploys reads the vault, so the App's credentials are there and not on the forge (PLX-Delivery/CIVault). + # A repo that deploys reads the vault, so the App's credentials may be there (PLX-Delivery/CIVault): the token finds them. OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}{% endraw %}{% endif %}{% raw %} run: plx-ci setup promote - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1