From c36ab1acdd6c7a1f628f1cd1bd75a4796e484f96 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:45:09 +0100 Subject: [PATCH 001/194] test(repo-turbo): the five verbs, the data-dependency graph and the new hooks Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/repoTurbo.test.ts | 119 +++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index 0e509598..afd7aba8 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -170,3 +170,122 @@ test('a generated file says its template lives in tooling', async () => { test('no turbo input names an answers file', async () => { assert.doesNotMatch(textOf(await render(), 'turbo.json'), /answers/); }); + +// The five verbs, the task graph and the hooks (§ 1 and § 6 of the decisions, PLX-Repo). + +/** The body of the task `name` in a rendered `mise.toml`, up to the next table. */ +const taskOf = (mise: string, name: string): string => + new RegExp(`^\\[tasks\\.${name}\\]\\n([\\s\\S]*?)(?=^\\[[a-z]|(?![\\s\\S]))`, 'm').exec(mise)?.[1] ?? ''; + +/** What a task runs: its body from `run =` on, which leaves out its description. */ +const runOf = (mise: string, name: string): string => { + const body = taskOf(mise, name); + return body.slice(body.indexOf('run =')); +}; + +/** The names of a rendered `mise.toml`'s tasks. */ +const tasksOf = (mise: string): string[] => [...mise.matchAll(/^\[tasks\.([\w-]+)\]/gm)].map((m) => m[1] ?? ''); + +/** The tasks of a rendered `turbo.json`. */ +const turboOf = (result: Awaited>) => + JSON.parse(textOf(result, 'turbo.json')).tasks as Record< + string, + { dependsOn?: string[]; inputs?: string[]; env?: string[]; passThroughEnv?: string[]; cache?: boolean } + >; + +const SHAPES = [{}, { publishes_packages: true }]; + +test('a repo has the five verbs as root tasks, each taking an optional name, and no verify', async () => { + for (const answers of SHAPES) { + const mise = textOf(await render(answers), 'mise.toml'); + const tasks = tasksOf(mise); + for (const verb of ['dev', 'build', 'check', 'test', 'e2e']) { + assert.ok(tasks.includes(verb), `${verb} ${JSON.stringify(answers)}`); + assert.match(taskOf(mise, verb), /^usage = .*\[name\]/m, verb); + } + assert.ok(!tasks.includes('verify'), 'no verify task'); + } +}); + +test('no rendered file but the workflows mentions verify', async () => { + for (const answers of SHAPES) { + const result = await render(answers); + for (const path of pathsOf(result)) + if (!path.startsWith('.github/workflows/')) assert.doesNotMatch(textOf(result, path), /verify/i, path); + } +}); + +test('check is lint, then plx doctor, then the check of Turbo', async () => { + for (const answers of SHAPES) { + const run = runOf(textOf(await render(answers), 'mise.toml'), 'check'); + const at = (needle: RegExp) => run.search(needle); + assert.ok(at(/mise run lint/) >= 0 && at(/plx doctor/) > at(/mise run lint/), 'doctor after lint'); + assert.ok(at(/turbo run check/) > at(/plx doctor/), 'turbo after doctor'); + assert.doesNotMatch(run, /turbo run (test|build|e2e)/); + } +}); + +test('test runs check, then the test of Turbo, in a run of its own', async () => { + for (const answers of SHAPES) { + const run = runOf(textOf(await render(answers), 'mise.toml'), 'test'); + assert.ok(run.search(/mise run check/) >= 0 && run.search(/turbo run test/) > run.search(/mise run check/), run); + assert.doesNotMatch(run, /turbo run (check|build|e2e)/); + } +}); + +test('e2e runs the e2e of Turbo alone: it neither tests nor checks', async () => { + for (const answers of SHAPES) { + const run = runOf(textOf(await render(answers), 'mise.toml'), 'e2e'); + assert.match(run, /turbo run e2e/); + assert.doesNotMatch(run, /mise run (test|check)|turbo run (check|test|build)/); + } +}); + +test('the dependsOn of the graph hold data dependencies only', async () => { + for (const answers of SHAPES) { + const tasks = turboOf(await render(answers)); + for (const task of ['build', 'check', 'test', 'e2e']) assert.deepEqual(tasks[task]?.dependsOn, ['^build'], task); + assert.equal(tasks.dev?.cache, false); + assert.equal(tasks.dev?.dependsOn, undefined); + } +}); + +test('test files are no input of build, and are an input of check and test', async () => { + const tasks = turboOf(await render()); + assert.deepEqual( + tasks.build?.inputs?.filter((input) => input.startsWith('!') && /test|spec|tests|vitest/.test(input)), + ['!**/*.{test,spec}.*', '!**/{__tests__,__snapshots__}/**', '!tests/**', '!{vitest,playwright,jest}*.config.*'], + ); + for (const task of ['check', 'test', 'e2e']) + assert.ok(!tasks[task]?.inputs?.some((input) => /test|spec|vitest/.test(input)), task); +}); + +test('the platform is mise’s, in the env of no task of the root and in the global env of no one', async () => { + const result = await render(); + assert.match(textOf(result, 'mise.toml'), /^PLX_PLATFORM = "\{\{ ?os\(\) ?\}\}-\{\{ ?arch\(\) ?\}\}"$/m); + assert.doesNotMatch(textOf(result, 'turbo.json'), /PLX_PLATFORM|globalEnv|globalPassThroughEnv/); +}); + +test('the PostgreSQL major is an input of test and e2e, and no passthrough variable changes what is tested', async () => { + const result = await render(); + const tasks = turboOf(result); + const major = /^PLX_POSTGRES_MAJOR = "(\d+)"$/m.exec(textOf(result, 'mise.toml')); + assert.ok(major, 'one declaration of the major, in mise’s env'); + for (const task of ['test', 'e2e']) assert.ok(tasks[task]?.env?.includes('PLX_POSTGRES_MAJOR'), task); + for (const task of ['build', 'check']) assert.ok(!tasks[task]?.env?.includes('PLX_POSTGRES_MAJOR'), task); + for (const task of ['test', 'e2e']) + for (const name of tasks[task]?.passThroughEnv ?? []) + assert.doesNotMatch(name, /DATABASE|URL|E2E_|POSTGRES/, `${task} passes ${name} through`); +}); + +test('pre-commit fixes lint on the staged files, then checks; pre-push tests', async () => { + const hk = textOf(await render(), 'hk.pkl'); + const hook = (name: string) => new RegExp(`\\["${name}"\\] \\{([\\s\\S]*?)\\n \\}`).exec(hk)?.[1] ?? ''; + const commit = hook('pre-commit'); + assert.match(commit, /fix = "mise :lint --write \{\{ files \}\}"/); + assert.ok(commit.indexOf('["check"]') > commit.indexOf('["lint"]'), 'check follows lint'); + assert.match(commit, /\["check"\] \{[^}]*mise :check/); + const push = hook('pre-push'); + assert.match(push, /mise :test/); + assert.doesNotMatch(push, /mise :check/); +}); From 5a1343c9ea696bc23f9a2e243f1543ec8b12e5f4 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:46:26 +0100 Subject: [PATCH 002/194] repo-turbo: the five verbs, data dependencies in the task graph, check before a commit and test before a push Co-Authored-By: Claude Fable 5.2 --- templates/repo-turbo/files/PLEXUS.md.jinja | 2 +- templates/repo-turbo/files/hk.pkl | 8 ++- templates/repo-turbo/files/mise.toml.jinja | 62 ++++++++++++--------- templates/repo-turbo/files/turbo.json.jinja | 22 +++++++- 4 files changed, 61 insertions(+), 33 deletions(-) diff --git a/templates/repo-turbo/files/PLEXUS.md.jinja b/templates/repo-turbo/files/PLEXUS.md.jinja index 37900d56..1124f865 100644 --- a/templates/repo-turbo/files/PLEXUS.md.jinja +++ b/templates/repo-turbo/files/PLEXUS.md.jinja @@ -3,7 +3,7 @@ {% else -%} - An app repo of `{{ tenant }}`: its apps under `apps/`, each with a marker of its own, and the workspace packages they share under `packages/`. {% endif -%} -- The verbs answer at the root, `mise :dev`, `mise :build` and `mise :verify`, and hand over to Turborepo, which runs each project's `package.json` scripts in the order of the workspace graph. +- The verbs answer at the root, `mise :dev`, `mise :build`, `mise :check`, `mise :test` and `mise :e2e`, and hand over to Turborepo, which runs each project's `package.json` scripts in the order of the workspace graph. {% if not publishes_packages and display_versions -%} - Display versions (PLX-Releases): a production release that changes an app cuts the version tag `.` with a GitHub Release, and the apps show their display version. `major` above is the major the next version takes; raise it in the pull request that warrants it, and the minor counts up by itself. diff --git a/templates/repo-turbo/files/hk.pkl b/templates/repo-turbo/files/hk.pkl index 6ec23d47..8f7c3682 100644 --- a/templates/repo-turbo/files/hk.pkl +++ b/templates/repo-turbo/files/hk.pkl @@ -10,12 +10,16 @@ hooks { check = "mise :lint {{ files }}" fix = "mise :lint --write {{ files }}" } + ["check"] { + depends = "lint" + check = "mise :check" + } } } ["pre-push"] { steps { - ["check"] { - check = "mise :check" + ["test"] { + check = "mise :test" } } } diff --git a/templates/repo-turbo/files/mise.toml.jinja b/templates/repo-turbo/files/mise.toml.jinja index bccbdf4f..3a8ff8c8 100644 --- a/templates/repo-turbo/files/mise.toml.jinja +++ b/templates/repo-turbo/files/mise.toml.jinja @@ -53,6 +53,11 @@ postinstall = "if command -v hk >/dev/null; then hk install --mise; fi && npx co [env] _.path = ["{% raw %}{{config_root}}{% endraw %}/node_modules/.bin"] +# The two values below are read by Turbo, which hashes them where a turbo.json declares them: the platform +# by an app's build, the PostgreSQL major by test and e2e. Neither belongs to the root's env or globalEnv, +# which would move the hash of every task. +PLX_PLATFORM = "{% raw %}{{ os() }}-{{ arch() }}{% endraw %}" +PLX_POSTGRES_MAJOR = "18" {% if not publishes_packages -%} [tasks.promote] @@ -88,34 +93,9 @@ run = ''' turbo run build ${dir:+--filter="{./$dir}..."} ''' -[tasks.verify] -description = "Perform all steps that verify code quality" -{{ name_arg("verify") }} -run = [ - 'mise run check ${usage_name:+"$usage_name"}', - 'mise run test ${usage_name:+"$usage_name"}', -] - -[tasks.install] -description = "Install and wire up project dependencies" -hide = true -run = "pnpm install" -sources = ["package.json", {% if not publishes_packages %}"apps/*/package.json", {% endif %}"packages/*/package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"] -outputs = ["node_modules/.pnpm/lock.yaml"] - -[tasks.lint] -depends = ["install"] -description = "Lint and format the codebase" -usage = ''' -flag "--write" help="Apply safe fixes and formatting in place" -arg "" var=#true default="." help="Files or directories to lint (defaults to the whole repo)" -''' -# usage shell-quotes var-arg values, so re-parse them via eval instead of bare expansion. -run = 'eval "set -- $usage_paths"; biome check ${usage_write:+--write} --no-errors-on-unmatched "$@"' - [tasks.check] depends = ["install"] -description = "Run static checks on the codebase: lint and the contracts' checks (plx doctor), repo-wide, then each project's check script" +description = "Run every static check, executing no test: lint (Biome) and the contracts' checks (plx doctor), repo-wide, then each project's check script" {{ name_arg("check") }} run = ''' {{ scoped("check") }} @@ -126,9 +106,37 @@ turbo run check ${dir:+--filter="{./$dir}..."} [tasks.test] depends = ["install"] -description = "Run tests on the codebase" +description = "Run check, then every test that lives beside the code; no built app is needed" {{ name_arg("test") }} run = ''' {{ scoped("test") }} +mise run check ${usage_name:+"$usage_name"} turbo run test ${dir:+--filter="{./$dir}..."} ''' + +[tasks.e2e] +depends = ["install"] +description = "Run the suites that need the built app, building what they need first; it neither checks nor tests" +{{ name_arg("e2e") }} +# A name selects the project and the projects that depend on it, since a suite is a package that depends on its app. +run = ''' +{{ scoped("e2e") }} +turbo run e2e ${dir:+--filter="...{./$dir}"} +''' + +[tasks.install] +description = "Install and wire up project dependencies" +hide = true +run = "pnpm install" +sources = ["package.json", {% if not publishes_packages %}"apps/*/package.json", {% endif %}"packages/*/package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"] +outputs = ["node_modules/.pnpm/lock.yaml"] + +[tasks.lint] +depends = ["install"] +description = "Lint and format the codebase" +usage = ''' +flag "--write" help="Apply safe fixes and formatting in place" +arg "" var=#true default="." help="Files or directories to lint (defaults to the whole repo)" +''' +# usage shell-quotes var-arg values, so re-parse them via eval instead of bare expansion. +run = 'eval "set -- $usage_paths"; biome check ${usage_write:+--write} --no-errors-on-unmatched "$@"' diff --git a/templates/repo-turbo/files/turbo.json.jinja b/templates/repo-turbo/files/turbo.json.jinja index b4ccd60e..c530d139 100644 --- a/templates/repo-turbo/files/turbo.json.jinja +++ b/templates/repo-turbo/files/turbo.json.jinja @@ -3,7 +3,16 @@ "tasks": { "build": { "dependsOn": ["^build"], - "inputs": ["$TURBO_DEFAULT$", "!**/{README,AGENTS,PLEXUS}.md", "!docs/**", "!docker/compose*.yaml"], + "inputs": [ + "$TURBO_DEFAULT$", + "!**/{README,AGENTS,PLEXUS}.md", + "!docs/**", + "!docker/compose*.yaml", + "!**/*.{test,spec}.*", + "!**/{__tests__,__snapshots__}/**", + "!tests/**", + "!{vitest,playwright,jest}*.config.*" + ], "outputs": [{% if not publishes_packages %}".next/**", "!.next/cache/**", {% endif %}"dist/**"] }, "check": { @@ -11,9 +20,16 @@ "inputs": ["$TURBO_DEFAULT$", "!**/{README,AGENTS,PLEXUS}.md", "!docs/**", "!docker/compose*.yaml"] }, "test": { - "dependsOn": ["build"], + "dependsOn": ["^build"], + "inputs": ["$TURBO_DEFAULT$", "!**/{README,AGENTS,PLEXUS}.md", "!docs/**"], + "env": ["PLX_POSTGRES_MAJOR"], + "passThroughEnv": ["CI"] + }, + "e2e": { + "dependsOn": ["^build"], "inputs": ["$TURBO_DEFAULT$", "!**/{README,AGENTS,PLEXUS}.md", "!docs/**"], - "passThroughEnv": ["CI", "DATABASE_URL", "E2E_*", "PLAYWRIGHT_*", "PW_TEST_*"] + "env": ["PLX_POSTGRES_MAJOR"], + "passThroughEnv": ["CI", "PLAYWRIGHT_BROWSERS_PATH"] }, "dev": { "cache": false, From 320040addfbfe795ca41cc89dce7c8e17e75bedc Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:46:32 +0100 Subject: [PATCH 003/194] test(repo-turbo): a workflow asks only for tasks the repo has Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/repoTurbo.test.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index afd7aba8..5994ffd7 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -289,3 +289,13 @@ test('pre-commit fixes lint on the staged files, then checks; pre-push tests', a assert.match(push, /mise :test/); assert.doesNotMatch(push, /mise :check/); }); + +test('a workflow asks _check.yml only for tasks the repo has', async () => { + for (const answers of SHAPES) { + const result = await render(answers); + const tasks = tasksOf(textOf(result, 'mise.toml')); + for (const path of pathsOf(result).filter((p) => p.startsWith('.github/workflows/'))) + for (const [, asked] of textOf(result, path).matchAll(/^ +tasks: (.+)$/gm)) + for (const task of (asked ?? '').split(' ')) assert.ok(tasks.includes(task), `${path} asks for ${task}`); + } +}); From d430a33d2c589db6e38992fa83d98eec20ca26a8 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:46:36 +0100 Subject: [PATCH 004/194] repo-turbo: a package repo's workflows run test, which includes check, since verify is gone (forced edit of the workflow templates) Co-Authored-By: Claude Fable 5.2 --- templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja | 2 +- templates/repo-turbo/files/.github/workflows/on_push.yml.jinja | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja b/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja index 517cea35..240cd07a 100644 --- a/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja +++ b/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja @@ -19,7 +19,7 @@ jobs: uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - tasks: verify{% endraw %}{% if private_packages_scope %} + tasks: test{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} changeset-status: diff --git a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja b/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja index 0f9cc504..1b226e4b 100644 --- a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja +++ b/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja @@ -30,7 +30,7 @@ jobs: uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - tasks: verify{% endraw %}{% if private_packages_scope %} + tasks: test{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} publish: From 5e4d92f17aba40656271c368a81752fe8f0fb8d7 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:49:02 +0100 Subject: [PATCH 005/194] newborns: a repo-turbo newborn passes check, test, build and e2e, and an edited test file moves only the hash of test Co-Authored-By: Claude Fable 5.2 --- newborns/helpers.ts | 12 ++-- newborns/repo-turbo.test.ts | 126 +++++++++++++++++++++++++++--------- 2 files changed, 105 insertions(+), 33 deletions(-) diff --git a/newborns/helpers.ts b/newborns/helpers.ts index c541c70e..c84425ac 100644 --- a/newborns/helpers.ts +++ b/newborns/helpers.ts @@ -328,13 +328,17 @@ export async function assertBuilt(dir: string): Promise { } } -/** `mise run verify` in the newborn, which must pass. */ -export async function verify(dir: string, name: string, env: NodeJS.ProcessEnv = {}): Promise { +/** `mise run ` in the newborn, which must pass: the built tools, then the task. */ +export async function pass(dir: string, name: string, task: string, env: NodeJS.ProcessEnv = {}): Promise { await assertBuilt(dir); - const ran = await tryRun('mise', ['run', 'verify'], dir, env); - if (!ran.ok) throw new Error(`the newborn ${name} fails its own verify:\n${ran.output}`); + const ran = await tryRun('mise', ['run', task], dir, env); + if (!ran.ok) throw new Error(`the newborn ${name} fails its own ${task}:\n${ran.output}`); } +/** `mise run verify` in the newborn, which must pass: the verb of the templates that still have one. */ +export const verify = (dir: string, name: string, env: NodeJS.ProcessEnv = {}): Promise => + pass(dir, name, 'verify', env); + /** Writes files below `root`, creating directories; a value that is no string is written as formatted JSON. */ export function put(root: string, files: Record): void { for (const [path, content] of Object.entries(files)) { diff --git a/newborns/repo-turbo.test.ts b/newborns/repo-turbo.test.ts index e8bfaf11..bf62104b 100644 --- a/newborns/repo-turbo.test.ts +++ b/newborns/repo-turbo.test.ts @@ -1,19 +1,22 @@ // A newborn repo of the Turborepo template, born as a repo is with updates -// beside its template, passes its own `verify`, in each shape that changes -// what is generated: an app repo, a package repo, each also with the tenant's -// private packages, and an app repo also with display versions. In an app repo a verb scopes to an app or a package by name, with -// what it depends on, and refuses an unknown one. A package repo also has what -// a release needs: a workspace package with a pending changeset passes -// `verify`, scoped to it by name, and `changeset version` takes the changeset -// in. Created by `plx new`; it needs the network (`mise install`, `pnpm add`). +// beside its template, passes its own five verbs (`check`, `test`, `build`, +// `e2e`, and `dev` where it has one), in each shape that changes what is +// generated: an app repo, a package repo, each also with the tenant's private +// packages, and an app repo also with display versions. A verb scopes to an app +// or a package by name, with what it depends on, and refuses an unknown one. +// Editing a test file moves the hash of `test` and leaves the hash of `build`. +// A package repo also has what a release needs: a workspace package with a +// pending changeset passes `test`, scoped to it by name, and `changeset +// version` takes the changeset in. Created by `plx new`; it needs the network +// (`mise install`, `pnpm add`). // // 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 } from 'node:fs'; +import { readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { after, before, describe, test } from 'node:test'; -import { born, close, mise, open, put, sh, verify } from './helpers.ts'; +import { born, close, mise, open, pass, put, sh, tryRun } from './helpers.ts'; let here = ''; before(async () => { @@ -21,11 +24,50 @@ before(async () => { }); after(close); -const newborn = (name: string, answers: Record = {}) => - born(join(here, name), ['repo-turbo', 'updates'], { tenant: 'acme', ...answers }); +/** + * The verbs of the contract are still `dev`, `build` and `verify` in `plx doctor`, which the issue of the doctor + * brings to the five (PLX-Repo/Verbs and PLX-Repo/SubVerbs name the verbs it checks); until then the newborn + * states the two as deviations, the way a repo that does not meet a requirement does, and `mise check` runs on. + */ +function deviating(dir: string): string { + const marker = join(dir, 'PLEXUS.md'); + const text = readFileSync(marker, 'utf8'); + const reasons = ['PLX-Repo/Verbs', 'PLX-Repo/SubVerbs'].map( + (name) => `- \`${name}\`: doctor still expects \`verify\`.\n`, + ); + writeFileSync( + marker, + `${text.replace(/^---\n/, '---\ndeviations: [PLX-Repo/Verbs, PLX-Repo/SubVerbs]\n')}${reasons.join('')}`, + ); + return dir; +} + +const newborn = async (name: string, answers: Record = {}) => + deviating(await born(join(here, name), ['repo-turbo', 'updates'], { tenant: 'acme', ...answers })); const read = (dir: string, file: string) => readFileSync(join(dir, file), 'utf8'); +/** The verbs a repo answers with a verdict, each from the checkout as it is. */ +const VERDICTS = ['check', 'test', 'build', 'e2e']; + +async function passesItsVerbs(dir: string, name: string): Promise { + for (const verb of VERDICTS) await pass(dir, name, verb); + const gone = await mise(dir, 'verify'); + assert.equal(gone.ok, false, 'no verify task is left'); +} + +/** The hashes of the tasks `turbo run ` would run for one package, from a dry run. */ +async function hashes(dir: string, pkg: string, tasks: string[]): Promise> { + const ran = await tryRun( + 'mise', + ['exec', '--', 'turbo', 'run', ...tasks, `--filter=${pkg}`, '--only', '--dry=json'], + dir, + ); + assert.ok(ran.ok, ran.output); + const dry = JSON.parse(ran.output.slice(ran.output.indexOf('{'))); + return Object.fromEntries(dry.tasks.map((t: { task: string; hash: string }) => [t.task, t.hash])); +} + /** The lockfile predates workspace packages added to a newborn; a frozen install (CI=true) would refuse it. */ const relock = (dir: string) => sh('mise', ['exec', '--', 'pnpm', 'install', '--lockfile-only'], dir); @@ -35,43 +77,69 @@ describe('an app repo', () => { dir = await newborn('app'); }); - test('passes its own verify, and has no display versions unasked', async () => { - await verify(dir, 'app'); + test('passes its own verbs, and has no display versions unasked', async () => { + await passesItsVerbs(dir, 'app'); assert.doesNotMatch(read(dir, '.github/workflows/on_push.yml'), /display-versions|contents: write/); assert.doesNotMatch(read(dir, 'PLEXUS.md'), /^major:/m); }); - test('scopes a verb to an app or a package by name, with what it depends on', async () => { + test('scopes a verb to an app or a package by name: build with what it depends on, e2e with what depends on it', async () => { put(dir, { 'apps/demo-app/package.json': { name: 'demo-app', version: '0.0.0', private: true, - scripts: { test: 'echo tested apps/demo-app' }, + scripts: { build: 'echo built apps/demo-app', e2e: 'echo e2e apps/demo-app' }, dependencies: { 'demo-lib': 'workspace:*' }, }, 'packages/demo-lib/package.json': { name: 'demo-lib', version: '0.0.0', private: true, - scripts: { test: 'echo tested packages/demo-lib' }, + scripts: { build: 'echo built packages/demo-lib' }, }, }); await relock(dir); - const app = await mise(dir, 'test', 'demo-app'); + const app = await mise(dir, 'build', 'demo-app'); assert.ok(app.ok, app.output); - assert.match(app.output, /tested apps\/demo-app/); - assert.match(app.output, /tested packages\/demo-lib/, 'the dependency is tested with the app'); - const lib = await mise(dir, 'test', 'demo-lib'); + assert.match(app.output, /built apps\/demo-app/); + assert.match(app.output, /built packages\/demo-lib/, 'the dependency is built with the app'); + const lib = await mise(dir, 'build', 'demo-lib'); assert.ok(lib.ok, lib.output); - assert.match(lib.output, /tested packages\/demo-lib/); - assert.doesNotMatch(lib.output, /tested apps\/demo-app/, 'never a dependent'); - assert.equal((await mise(dir, 'test', 'demo-none')).ok, false, 'an unknown name is refused'); + assert.match(lib.output, /built packages\/demo-lib/); + assert.doesNotMatch(lib.output, /built apps\/demo-app/, 'never a dependent'); + const suite = await mise(dir, 'e2e', 'demo-lib'); + assert.ok(suite.ok, suite.output); + assert.match(suite.output, /e2e apps\/demo-app/, 'the suite of a dependent runs'); + for (const verb of ['build', 'check', 'test', 'e2e']) + assert.equal((await mise(dir, verb, 'demo-none')).ok, false, `${verb} refuses an unknown name`); + }); + + test('editing a test file moves the hash of test and leaves the hash of build', async () => { + put(dir, { + 'apps/hashed/package.json': { + name: 'hashed', + version: '0.0.0', + private: true, + scripts: { build: 'echo built', check: 'echo checked', test: 'echo tested' }, + }, + 'apps/hashed/src/index.ts': 'export const answer = 42;\n', + 'apps/hashed/src/index.test.ts': 'export const first = 1;\n', + }); + await relock(dir); + const before = await hashes(dir, 'hashed', ['build', 'test']); + put(dir, { 'apps/hashed/src/index.test.ts': 'export const first = 2;\n' }); + const after = await hashes(dir, 'hashed', ['build', 'test']); + assert.notEqual(after.test, before.test, 'the test file is an input of test'); + assert.equal(after.build, before.build, 'and of no build'); + put(dir, { 'apps/hashed/src/index.ts': 'export const answer = 43;\n' }); + const edited = await hashes(dir, 'hashed', ['build', 'test']); + assert.notEqual(edited.build, after.build, 'a source file still moves the build'); }); }); -test('a private app repo with reviewers passes its own verify', async () => { - await verify( +test('a private app repo with reviewers passes its own verbs', async () => { + await passesItsVerbs( await newborn('private-app', { private_packages_scope: '@acme', pr_reviewers: 'reviewer-a,reviewer-b' }), 'private-app', ); @@ -79,7 +147,7 @@ test('a private app repo with reviewers passes its own verify', async () => { test('an app repo with display versions asks for them and states its major', async () => { const dir = await newborn('versioned-app', { display_versions: 'true' }); - await verify(dir, 'versioned-app'); + await passesItsVerbs(dir, 'versioned-app'); assert.match(read(dir, '.github/workflows/on_push.yml'), /display-versions: true/); assert.match(read(dir, 'PLEXUS.md'), /^major: 1$/m); }); @@ -88,9 +156,9 @@ for (const [name, answers] of [ ['packages', { publishes_packages: 'true' }], ['private-packages', { publishes_packages: 'true', package_registry: 'github', private_packages_scope: '@acme' }], ] as const) { - test(`a package repo (${name}) passes its own verify and takes a changeset in`, async () => { + test(`a package repo (${name}) passes its own verbs and takes a changeset in`, async () => { const dir = await newborn(name, answers); - await verify(dir, name); + await passesItsVerbs(dir, name); put(dir, { 'packages/demo/package.json': { name: '@acme/demo', @@ -100,7 +168,7 @@ for (const [name, answers] of [ '.changeset/first-change.md': '---\n"@acme/demo": minor\n---\n\nA first change.\n', }); await relock(dir); - const scoped = await mise(dir, 'verify', 'demo'); + const scoped = await mise(dir, 'test', 'demo'); assert.ok(scoped.ok, scoped.output); await sh('mise', ['exec', '--', 'pnpm', 'exec', 'changeset', 'version'], dir); assert.match(read(dir, 'packages/demo/package.json'), /"version": "0\.2\.0"/); From ad6c410ee749e6694a724653a917897ead072a30 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:49:20 +0100 Subject: [PATCH 006/194] newborns: the deviation that waits for plx doctor to know the five verbs is a helper, for every newborn of repo-turbo Co-Authored-By: Claude Fable 5.2 --- newborns/helpers.ts | 18 ++++++++++++++++++ newborns/repo-turbo.test.ts | 22 ++-------------------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/newborns/helpers.ts b/newborns/helpers.ts index c84425ac..3aae95f7 100644 --- a/newborns/helpers.ts +++ b/newborns/helpers.ts @@ -328,6 +328,24 @@ export async function assertBuilt(dir: string): Promise { } } +/** + * The verbs of the contract are still `dev`, `build` and `verify` in `plx doctor`, which the issue of the doctor + * brings to the five (PLX-Repo/Verbs and PLX-Repo/SubVerbs name the verbs it checks); until then the newborn + * states the two as deviations, the way a repo that does not meet a requirement does, and `mise check` runs on. + */ +export function deviating(dir: string): string { + const marker = join(dir, 'PLEXUS.md'); + const text = readFileSync(marker, 'utf8'); + const reasons = ['PLX-Repo/Verbs', 'PLX-Repo/SubVerbs'].map( + (name) => `- \`${name}\`: doctor still expects \`verify\`.\n`, + ); + writeFileSync( + marker, + `${text.replace(/^---\n/, '---\ndeviations: [PLX-Repo/Verbs, PLX-Repo/SubVerbs]\n')}${reasons.join('')}`, + ); + return dir; +} + /** `mise run ` in the newborn, which must pass: the built tools, then the task. */ export async function pass(dir: string, name: string, task: string, env: NodeJS.ProcessEnv = {}): Promise { await assertBuilt(dir); diff --git a/newborns/repo-turbo.test.ts b/newborns/repo-turbo.test.ts index bf62104b..0085a207 100644 --- a/newborns/repo-turbo.test.ts +++ b/newborns/repo-turbo.test.ts @@ -13,10 +13,10 @@ // 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 { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { after, before, describe, test } from 'node:test'; -import { born, close, mise, open, pass, put, sh, tryRun } from './helpers.ts'; +import { born, close, deviating, mise, open, pass, put, sh, tryRun } from './helpers.ts'; let here = ''; before(async () => { @@ -24,24 +24,6 @@ before(async () => { }); after(close); -/** - * The verbs of the contract are still `dev`, `build` and `verify` in `plx doctor`, which the issue of the doctor - * brings to the five (PLX-Repo/Verbs and PLX-Repo/SubVerbs name the verbs it checks); until then the newborn - * states the two as deviations, the way a repo that does not meet a requirement does, and `mise check` runs on. - */ -function deviating(dir: string): string { - const marker = join(dir, 'PLEXUS.md'); - const text = readFileSync(marker, 'utf8'); - const reasons = ['PLX-Repo/Verbs', 'PLX-Repo/SubVerbs'].map( - (name) => `- \`${name}\`: doctor still expects \`verify\`.\n`, - ); - writeFileSync( - marker, - `${text.replace(/^---\n/, '---\ndeviations: [PLX-Repo/Verbs, PLX-Repo/SubVerbs]\n')}${reasons.join('')}`, - ); - return dir; -} - const newborn = async (name: string, answers: Record = {}) => deviating(await born(join(here, name), ['repo-turbo', 'updates'], { tenant: 'acme', ...answers })); From 5b6eb3ced512ce70b6e08d257e87ae3beb7282f0 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:49:57 +0100 Subject: [PATCH 007/194] newborns: the newborn of app-nextjs runs test and not the verify that is gone (forced edit of a file of the app template) Co-Authored-By: Claude Fable 5.2 --- newborns/app-nextjs.test.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index 63f4a5c3..faef05f2 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -1,4 +1,4 @@ -// A newborn app of the Next.js template passes its repo's own `verify`: the +// A newborn app of the Next.js template passes its repo's own `test`: the // repo is a newborn of the Turborepo template with updates beside it, an app // of each profile is created inside it by `plx new`, taking the tenant from // the repo's marker. @@ -9,7 +9,7 @@ import assert from 'node:assert/strict'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { after, before, test } from 'node:test'; -import { born, close, open, plxNew, sh, tryRun, verify } from './helpers.ts'; +import { born, close, deviating, open, pass, plxNew, sh, tryRun } from './helpers.ts'; let here = ''; let repo = ''; @@ -17,7 +17,7 @@ const PROFILES = ['stateless', 'stateful']; before(async () => { here = await open('app-nextjs'); - repo = await born(join(here, 'acme'), ['repo-turbo', 'updates'], { tenant: 'acme' }); + repo = deviating(await born(join(here, 'acme'), ['repo-turbo', 'updates'], { tenant: 'acme' })); for (const profile of PROFILES) await born(join(repo, 'apps', profile), ['app-nextjs'], { name: `@acme/${profile}`, profile }); }); @@ -44,8 +44,8 @@ for (const profile of PROFILES) { }); } -test('the repo around the apps passes its own verify', async () => { +test('the repo around the apps passes its own test, which includes check', async () => { // The lockfile predates the apps, and under CI=true the check's frozen install refuses it. await sh('mise', ['exec', '--', 'pnpm', 'install', '--lockfile-only'], repo); - await verify(repo, 'acme'); + await pass(repo, 'acme', 'test'); }); From 3118d546421fa4e83c1ffa57e9640a0484b62306 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:53:03 +0100 Subject: [PATCH 008/194] tests of repo-turbo in lib: the doctor's one finding that waits for the five verbs, and the move test without the template that has moved on Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/newSite.test.ts | 11 ++++++++++- packages/lib/src/updatesMove.test.ts | 3 ++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/lib/src/newSite.test.ts b/packages/lib/src/newSite.test.ts index ae90e5e6..29c5b9b0 100644 --- a/packages/lib/src/newSite.test.ts +++ b/packages/lib/src/newSite.test.ts @@ -392,10 +392,19 @@ test('a repo from repo-turbo with updates beside it and an app from app-nextjs i git(target, 'add', '-A'); const { facts } = await examine(new Context({}, realIo()), target, bundled.version); const report = diagnose(facts); + // The doctor still wants a `verify` task of the repo, which repo-turbo no longer has: the one finding that waits + // for the doctor to follow the five verbs, and no other is let through. + const WAITING = 'no root mise task `verify`'; assert.deepEqual( - report.units.flatMap((u) => u.findings.map((f) => `${u.path}: ${f.problem}`)), + report.units.flatMap((u) => + u.findings.filter((f) => f.problem !== WAITING).map((f) => `${u.path}: ${f.problem}`), + ), [], ); + assert.deepEqual( + report.units.flatMap((u) => u.findings.filter((f) => f.problem === WAITING).map((f) => u.path)), + ['.', '.'], + ); assert.equal(report.units.length, 2); } finally { delete process.env.MISE_TRUSTED_CONFIG_PATHS; diff --git a/packages/lib/src/updatesMove.test.ts b/packages/lib/src/updatesMove.test.ts index b4d37144..3bfac47a 100644 --- a/packages/lib/src/updatesMove.test.ts +++ b/packages/lib/src/updatesMove.test.ts @@ -46,7 +46,8 @@ function comparable(tree: Tree, files: ReadonlyMap, ); } -for (const repo of ['repo-turbo', 'repo-operations'] as const) +// repo-turbo is left out: its verbs and hooks changed after the move, which is what this header says ends the test. +for (const repo of ['repo-operations'] as const) test(`${repo} beside updates renders what ${repo} alone rendered before the move, in every answer shape`, async () => { const old = [await readTree(join(before, repo))]; const now = [await readTree(join(templatesRoot(), repo)), await readTree(join(templatesRoot(), 'updates'))]; From db3c0b33947e102cb9d6b2e6a623e7599c598462 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:56:30 +0100 Subject: [PATCH 009/194] tests of the move in dev: an edit beside [settings], and the end state compared on the files the move concerns, since repo-turbo has moved on (forced edit) Co-Authored-By: Claude Fable 5.2 --- packages/dev/src/ship.integration.test.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index f1d08782..1a94c63e 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -1850,7 +1850,11 @@ for (const [template, answers, edits] of [ (dir: string) => { const onPr = join(dir, '.github/workflows/on_pr.yml'); put(onPr, read(onPr).replace(' pull_request:\n', ' pull_request:\n types: [opened, synchronize]\n')); - put(join(dir, 'mise.toml'), `${read(join(dir, 'mise.toml'))}\n[tasks.mine]\nrun = "echo mine"\n`); + // Beside [settings], which no change of the template touches: the end of the file is where its tasks change. + put( + join(dir, 'mise.toml'), + read(join(dir, 'mise.toml')).replace('[settings]\n', '[tasks.mine]\nrun = "echo mine"\n\n[settings]\n'), + ); }, ], [ @@ -1897,7 +1901,13 @@ for (const [template, answers, edits] of [ executable: false, text: (workflow?.text ?? '').replace(`templates/${template}: edit`, 'templates/updates: edit'), }; - assert.deepEqual(end, expected); + // repo-turbo has changed since the move (its verbs, its hooks), so what the update took in of it is no longer the + // repo as it was: the files the move concerns are what is compared. repo-operations is still as it was. + const concerned = (files: typeof end) => + template === 'repo-turbo' + ? Object.fromEntries(Object.entries(files).filter(([path]) => path === 'PLEXUS.md' || MOVED.includes(path))) + : files; + assert.deepEqual(concerned(end), concerned(expected)); }); test('update: a moved file the repo edited is kept by the update, and meets the template again as a conflict when updates is added', async () => { From f74141d49ad8a0d83786762ee04c5118cd135bce Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:59:06 +0100 Subject: [PATCH 010/194] Test: an app builds into one directory that serves all of it A newborn app built by the repo's verb leaves .next/standalone, which, copied elsewhere and started as server.js from another working directory, serves its page, a static chunk, a file of public/ and an optimised image. Red: the static files and public/ lie beside the standalone output, not in it. The newborn helpers gain a long-running server, a free port, and bytes in put. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- newborns/app-nextjs.test.ts | 58 ++++++++++++++++++++++++++++++-- newborns/helpers.ts | 66 +++++++++++++++++++++++++++++++++++-- 2 files changed, 120 insertions(+), 4 deletions(-) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index 63f4a5c3..60261929 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -5,21 +5,44 @@ // An app created where no repo's marker gives a tenant is refused. Each app's // compose file refuses an unset loopback port and publishes a set one // (PLX-App/LoopbackPort), which needs docker compose. +// An app's `build`, run by the repo's verb, leaves one directory that serves +// the whole app wherever it lies, started as the standalone server. import assert from 'node:assert/strict'; +import { cpSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { after, before, test } from 'node:test'; -import { born, close, open, plxNew, sh, tryRun, verify } from './helpers.ts'; +import { born, close, freePort, open, plxNew, put, sh, start, tryRun, verify } from './helpers.ts'; let here = ''; let repo = ''; const PROFILES = ['stateless', 'stateful']; +/** + * The platform as mise's `{{ os() }}-{{ arch() }}` gives it, for a build's + * environment: the repo template's `mise.toml` does not set it yet, so the + * tests do, with the value it will set. + */ +const PLATFORM = { PLX_PLATFORM: `${process.platform === 'darwin' ? 'macos' : process.platform}-${process.arch}` }; + +/** A one-pixel PNG, for the app's public/ and its image optimiser. */ +const PIXEL = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', + 'base64', +); + +/** The directory an app's build leaves. */ +const output = (app: string) => join(repo, 'apps', app, '.next', 'standalone'); + before(async () => { here = await open('app-nextjs'); repo = await born(join(here, 'acme'), ['repo-turbo', 'updates'], { tenant: 'acme' }); for (const profile of PROFILES) await born(join(repo, 'apps', profile), ['app-nextjs'], { name: `@acme/${profile}`, profile }); + put(join(repo, 'apps', 'stateless'), { 'public/pixel.png': PIXEL }); + await sh('mise', ['exec', '--', 'pnpm', 'install'], repo); + // Tracked, as in a checkout: Turbo hashes what git tracks, and an untracked app's build output with it. + await sh('git', ['add', '-A'], repo); }); after(close); @@ -44,8 +67,39 @@ for (const profile of PROFILES) { }); } +test('an app builds into one directory that serves all of it, its static files and public/ included, wherever it lies', async () => { + await sh('mise', ['run', 'build', 'stateless'], repo, PLATFORM); + const moved = join(here, 'moved'); + cpSync(output('stateless'), moved, { recursive: true, verbatimSymlinks: true }); + const port = await freePort(); + const url = (path: string) => `http://127.0.0.1:${port}${path}`; + const server = await start( + process.execPath, + [join(moved, 'apps', 'stateless', 'server.js')], + here, + { PORT: String(port), HOSTNAME: '127.0.0.1' }, + async () => (await fetch(url('/healthz'))).ok, + ); + try { + const page = await fetch(url('/')); + assert.equal(page.status, 200); + const html = await page.text(); + assert.match(html, /

@acme\/stateless<\/h1>/); + const asset = /\/_next\/static\/[^"]+\.js/.exec(html)?.[0]; + assert.ok(asset, html); + assert.equal((await fetch(url(asset))).status, 200, asset); + assert.equal((await fetch(url('/pixel.png'))).status, 200); + const image = await fetch(url('/_next/image?url=%2Fpixel.png&w=64&q=75'), { headers: { accept: 'image/webp' } }); + assert.equal(image.status, 200); + assert.equal(image.headers.get('content-type'), 'image/webp'); + } finally { + await server.stop(); + rmSync(moved, { recursive: true, force: true }); + } +}); + test('the repo around the apps passes its own verify', async () => { // The lockfile predates the apps, and under CI=true the check's frozen install refuses it. await sh('mise', ['exec', '--', 'pnpm', 'install', '--lockfile-only'], repo); - await verify(repo, 'acme'); + await verify(repo, 'acme', PLATFORM); }); diff --git a/newborns/helpers.ts b/newborns/helpers.ts index c541c70e..8188cfec 100644 --- a/newborns/helpers.ts +++ b/newborns/helpers.ts @@ -50,6 +50,7 @@ import { symlinkSync, writeFileSync, } from 'node:fs'; +import { createServer } from 'node:net'; import { homedir, tmpdir } from 'node:os'; import { dirname, join, sep } from 'node:path'; import { PUBLISHED, pack } from './pack.ts'; @@ -335,10 +336,71 @@ export async function verify(dir: string, name: string, env: NodeJS.ProcessEnv = if (!ran.ok) throw new Error(`the newborn ${name} fails its own verify:\n${ran.output}`); } -/** Writes files below `root`, creating directories; a value that is no string is written as formatted JSON. */ +/** Writes files below `root`, creating directories; a value that is neither a string nor bytes is written as formatted JSON. */ export function put(root: string, files: Record): void { for (const [path, content] of Object.entries(files)) { mkdirSync(dirname(join(root, path)), { recursive: true }); - writeFileSync(join(root, path), typeof content === 'string' ? content : `${JSON.stringify(content, null, 2)}\n`); + const raw = typeof content === 'string' || content instanceof Uint8Array; + writeFileSync(join(root, path), raw ? content : `${JSON.stringify(content, null, 2)}\n`); } } + +/** A TCP port on loopback that nothing listens on at the time of asking. */ +export function freePort(): Promise { + return new Promise((resolve, reject) => { + const server = createServer(); + server.on('error', reject); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + server.close(() => + address && typeof address === 'object' ? resolve(address.port) : reject(new Error('no port')), + ); + }); + }); +} + +/** A server a test started, and its stop. */ +export interface Started { + stop(): Promise; +} + +/** + * Starts a long-running command, a server, leading a process group of its + * own, and resolves once `ready` answers true; rejects with what the command + * printed when it exits first or LIMIT passes. `stop` kills the whole group. + */ +export async function start( + command: string, + args: string[], + cwd: string, + env: NodeJS.ProcessEnv, + ready: () => Promise, +): Promise { + const child = spawn(command, args, { cwd, env: cleanEnv(env), stdio: ['ignore', 'pipe', 'pipe'], detached: true }); + let output = ''; + const collect = (chunk: Buffer) => { + output += chunk; + }; + child.stdout.on('data', collect); + child.stderr.on('data', collect); + let gone = false; + const exited = new Promise((resolve) => + child.on('close', () => { + gone = true; + resolve(); + }), + ); + const stop = async () => { + try { + if (child.pid) process.kill(-child.pid, 'SIGKILL'); + } catch {} + await exited; + }; + const until = Date.now() + LIMIT; + while (!gone && Date.now() < until) { + if (await ready().catch(() => false)) return { stop }; + await new Promise((resolve) => setTimeout(resolve, 200)); + } + await stop(); + throw new Error(`${command} ${args.join(' ')} ${gone ? 'exited' : 'never became ready'} in ${cwd}:\n${output}`); +} From fec8fc2c35e0f396f01a397fc8e20449c09e5b18 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:59:21 +0100 Subject: [PATCH 011/194] An app's build puts its static files and public/ into the standalone output The build script copies .next/static and public/ to where the standalone server looks for them, the app's own directory inside .next/standalone, as Next's documentation of output: 'standalone' says to do by hand after next build. Where that directory lies in the output is Next's own record, relativeAppDir of required-server-files.json, so that it holds under an umbrella too. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- templates/app-nextjs/files/package.json.jinja | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/app-nextjs/files/package.json.jinja b/templates/app-nextjs/files/package.json.jinja index 6f9ffc34..a8674f84 100644 --- a/templates/app-nextjs/files/package.json.jinja +++ b/templates/app-nextjs/files/package.json.jinja @@ -4,7 +4,7 @@ "private": true, "scripts": { "dev": "next dev", - "build": "next build", + "build": "next build && out=.next/standalone/$(node -p \"require('./.next/required-server-files.json').relativeAppDir\") && cp -R .next/static \"$out/.next/\" && if [ -d public ]; then cp -R public \"$out/\"; fi", "start": "next start", "check": "next typegen && tsc --noEmit"{% if profile == 'stateful' %}, "migrate": "echo 'migrate: not written yet. Name the migration command here; the migrate service of docker/compose.yaml runs it in the image, which holds node and the standalone build.' >&2; exit 1", From 94c89849ffcb82bc51a26a9c5e80c456ff7ee590 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:00:16 +0100 Subject: [PATCH 012/194] test(cli-ci): an instance runs its runner in the environment image The user-data pulls the image and starts the runner in a container of it, on the host's network with no Docker socket, as a slot does; the runner's config arrives as the variable a slot's does, its log stays on the host, and the registry pair still answers on loopback. The image is the one of plx-ci's own version unless RUNNER_IMAGE names another. Failing until the instance side follows. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/commands/hybrid.test.ts | 25 ++++++++++ .../cli-ci/src/core/createInstances.test.ts | 4 +- packages/cli-ci/src/core/userData.test.ts | 48 +++++++++++++++++-- 3 files changed, 73 insertions(+), 4 deletions(-) create mode 100644 packages/cli-ci/src/commands/hybrid.test.ts diff --git a/packages/cli-ci/src/commands/hybrid.test.ts b/packages/cli-ci/src/commands/hybrid.test.ts new file mode 100644 index 00000000..9f072a74 --- /dev/null +++ b/packages/cli-ci/src/commands/hybrid.test.ts @@ -0,0 +1,25 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { version } from '../program.ts'; +import { launchOptionsFromEnv } from './hybrid.ts'; + +const env = { + GITHUB_REPOSITORY: 'acme/web', + GITHUB_RUN_ID: '41', + GITHUB_RUN_ATTEMPT: '1', + RUNNER_TOKEN: 'ghs_x', + SELF_DELETE_KEY: 'EXOsd', + SELF_DELETE_SECRET: 'sd', + NO_JOB_MINUTES: '10', + DEATH_MINUTES: '45', + POWEROFF_MINUTES: '50', +}; + +test('an instance runs its job in the environment image of this plx-ci’s version', () => { + assert.equal(launchOptionsFromEnv(env).image, `ghcr.io/plexus-ms/ci-runner:${version}`); +}); + +test('RUNNER_IMAGE names another, an unreleased build of it for a trial', () => { + const image = 'ghcr.io/plexus-ms/ci-runner:sha-abc'; + assert.equal(launchOptionsFromEnv({ ...env, RUNNER_IMAGE: image }).image, image); +}); diff --git a/packages/cli-ci/src/core/createInstances.test.ts b/packages/cli-ci/src/core/createInstances.test.ts index 309e9de4..0000aa94 100644 --- a/packages/cli-ci/src/core/createInstances.test.ts +++ b/packages/cli-ci/src/core/createInstances.test.ts @@ -33,6 +33,7 @@ const options: LaunchOptions = { sshKey: 'runners', onlineSeconds: 5, tries: 2, + image: 'ghcr.io/plexus-ms/ci-runner:sha-abc', now: () => now, sleep: async () => {}, }; @@ -43,7 +44,8 @@ test('the user-data is rendered with the run’s facts and the week’s buckets, assert.match(text, /REGISTRY_BUCKET=acme-ci-registry-2026-w45/); assert.match(text, /REGISTRY_PREVIOUS_BUCKET=acme-ci-registry-2026-w44/); assert.match(text, /SELF_LAYERS=off/); - assert.match(text, /content: "JIT"/); + assert.match(text, /ACTIONS_RUNNER_INPUT_JITCONFIG=JIT$/m); + assert.match(text, /docker pull -q ghcr\.io\/plexus-ms\/ci-runner:sha-abc$/m); assert.ok(encodeUserData(text).length < DEFAULTS.userDataLimit); }); diff --git a/packages/cli-ci/src/core/userData.test.ts b/packages/cli-ci/src/core/userData.test.ts index e0abc5d4..de238eab 100644 --- a/packages/cli-ci/src/core/userData.test.ts +++ b/packages/cli-ci/src/core/userData.test.ts @@ -3,8 +3,9 @@ import { test } from 'node:test'; import { placeholders, RUNNER_USER_DATA, render } from './userData.ts'; test('the templates name their placeholders, digits included', () => { - assert.ok(placeholders(RUNNER_USER_DATA).includes('RUNNER_SHA256')); + assert.ok(placeholders(RUNNER_USER_DATA).includes('NO_JOB_MINUTES')); assert.ok(placeholders(RUNNER_USER_DATA).includes('JITCONFIG')); + assert.ok(placeholders(RUNNER_USER_DATA).includes('IMAGE')); }); test('render fills every placeholder and refuses a leftover', () => { @@ -17,10 +18,51 @@ test('render fills every placeholder and refuses a leftover', () => { ); }); -test('the runner template is cloud-config that arms the timers first and runs the runner last', () => { +test('the runner template is cloud-config that arms the timers first, pulls the image, and runs the runner last', () => { assert.ok(RUNNER_USER_DATA.startsWith('#cloud-config')); const start = RUNNER_USER_DATA.indexOf('systemctl start plexus-ci-no-job.timer'); + const pull = RUNNER_USER_DATA.indexOf('docker pull -q @@IMAGE@@'); const runner = RUNNER_USER_DATA.indexOf('systemctl start plexus-ci-runner.service'); - assert.ok(start > 0 && runner > start); + assert.ok(start > 0 && pull > start && runner > pull); assert.match(RUNNER_USER_DATA, /SELF_LAYERS=@@SELF_LAYERS@@/); }); + +/** The line of the user-data that starts with `key=`, trimmed. */ +const unitLine = (key: string) => + RUNNER_USER_DATA.split('\n') + .find((l) => l.trim().startsWith(`${key}=`)) + ?.trim() ?? ''; + +test('the job runs in a container of the environment image, as on a slot: the host’s network, no Docker socket', () => { + const run = unitLine('ExecStart'); + assert.match(run, /^ExecStart=\/usr\/bin\/docker run --rm --init /); + assert.match(run, / --network host /); + assert.match(run, / --env-file \/etc\/plexus-ci\/runner\.env /); + assert.match(run, / @@IMAGE@@ \.\/run\.sh$/); + assert.doesNotMatch(run, /docker\.sock|--privileged/); + assert.equal(unitLine('ExecStopPost'), 'ExecStopPost=+/usr/local/sbin/plexus-ci-self-delete runner-exit'); +}); + +test('the runner’s config reaches the container as the variable a slot’s does, in a root-only file', () => { + assert.match( + RUNNER_USER_DATA, + / {2}- path: \/etc\/plexus-ci\/runner\.env\n {4}permissions: "0600"\n {4}content: \|\n {6}ACTIONS_RUNNER_INPUT_JITCONFIG=@@JITCONFIG@@\n/, + ); +}); + +test('the runner’s log stays on the host, where the no-job layer and a kept instance’s reader look', () => { + assert.match(unitLine('ExecStart'), / -v \/opt\/runner\/_diag:\/home\/runner\/_diag /); + assert.match(RUNNER_USER_DATA, /ls \/opt\/runner\/_diag\/Worker_\*\.log/); +}); + +test('the instance gives the job no Docker daemon: no runner on the host, no builder, no test images', () => { + assert.doesNotMatch( + RUNNER_USER_DATA, + /actions-runner-linux|installdependencies|useradd|buildx create|docker pull -q postgres/, + ); +}); + +test('the registry pair still answers on the host’s loopback, which the job’s container shares', () => { + assert.match(RUNNER_USER_DATA, /-p 127\.0\.0\.1:5000:5000 /); + assert.match(RUNNER_USER_DATA, /-p 127\.0\.0\.1:5001:5000 /); +}); From 2c8c07debabcc4400b468a9eaa009b7f44fb77dd Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:00:17 +0100 Subject: [PATCH 013/194] Test: the one directory is all an app's build leaves, and its cache holds After a cache hit the app's .next holds the standalone directory alone, whole: server, package.json, build ID, static files and public/. The render of the template lists the app's own turbo.json. Red: the repo's outputs cache all of .next, and the template has no turbo.json. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- newborns/app-nextjs.test.ts | 16 ++++++++++++++-- packages/lib/src/appNextjs.test.ts | 1 + packages/lib/src/newSite.test.ts | 1 + 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index 60261929..a4a46b40 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -6,9 +6,10 @@ // compose file refuses an unset loopback port and publishes a set one // (PLX-App/LoopbackPort), which needs docker compose. // An app's `build`, run by the repo's verb, leaves one directory that serves -// the whole app wherever it lies, started as the standalone server. +// the whole app wherever it lies, started as the standalone server, and is +// what the build task's cache holds. import assert from 'node:assert/strict'; -import { cpSync, rmSync } from 'node:fs'; +import { cpSync, existsSync, readdirSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { after, before, test } from 'node:test'; @@ -98,6 +99,17 @@ test('an app builds into one directory that serves all of it, its static files a } }); +test('that directory is all the build leaves: a cache hit restores it whole', async () => { + const dotNext = join(repo, 'apps', 'stateless', '.next'); + await sh('mise', ['run', 'build', 'stateless'], repo, PLATFORM); + rmSync(dotNext, { recursive: true, force: true }); + assert.match(await sh('mise', ['run', 'build', 'stateless'], repo, PLATFORM), /cache hit/); + assert.deepEqual(readdirSync(dotNext), ['standalone']); + const app = join(output('stateless'), 'apps', 'stateless'); + for (const path of ['server.js', 'package.json', '.next/BUILD_ID', '.next/static', 'public/pixel.png']) + assert.ok(existsSync(join(app, path)), path); +}); + test('the repo around the apps passes its own verify', async () => { // The lockfile predates the apps, and under CI=true the check's frozen install refuses it. await sh('mise', ['exec', '--', 'pnpm', 'install', '--lockfile-only'], repo); diff --git a/packages/lib/src/appNextjs.test.ts b/packages/lib/src/appNextjs.test.ts index 5a75b5bc..14a13bbe 100644 --- a/packages/lib/src/appNextjs.test.ts +++ b/packages/lib/src/appNextjs.test.ts @@ -21,6 +21,7 @@ test('an app is rendered with its docker files and its source', async () => { 'src/app/layout.tsx', 'src/app/page.tsx', 'tsconfig.json', + 'turbo.json', ]); }); diff --git a/packages/lib/src/newSite.test.ts b/packages/lib/src/newSite.test.ts index ae90e5e6..39bfaff7 100644 --- a/packages/lib/src/newSite.test.ts +++ b/packages/lib/src/newSite.test.ts @@ -384,6 +384,7 @@ test('a repo from repo-turbo with updates beside it and an app from app-nextjs i 'src/app/layout.tsx', 'src/app/page.tsx', 'tsconfig.json', + 'turbo.json', ]); // The doctor reads what git tracks, and lists the tasks of a mise.toml that `mise trust` (faked above) would have trusted. From 313d9f3f2b0324a548249426a9bb07d5ab2101c7 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:00:24 +0100 Subject: [PATCH 014/194] The standalone directory is the outputs of an app's build task The app's own turbo.json, extending the root's, names .next/standalone as the build's outputs, so the cache holds the one directory and a hit restores it whole, and nothing else of .next. The start script goes: next start needs the rest of .next, which a hit no longer restores, and the directory is started as its own server.js. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- templates/app-nextjs/files/package.json.jinja | 1 - templates/app-nextjs/files/turbo.json | 8 ++++++++ 2 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 templates/app-nextjs/files/turbo.json diff --git a/templates/app-nextjs/files/package.json.jinja b/templates/app-nextjs/files/package.json.jinja index a8674f84..36d0b065 100644 --- a/templates/app-nextjs/files/package.json.jinja +++ b/templates/app-nextjs/files/package.json.jinja @@ -5,7 +5,6 @@ "scripts": { "dev": "next dev", "build": "next build && out=.next/standalone/$(node -p \"require('./.next/required-server-files.json').relativeAppDir\") && cp -R .next/static \"$out/.next/\" && if [ -d public ]; then cp -R public \"$out/\"; fi", - "start": "next start", "check": "next typegen && tsc --noEmit"{% if profile == 'stateful' %}, "migrate": "echo 'migrate: not written yet. Name the migration command here; the migrate service of docker/compose.yaml runs it in the image, which holds node and the standalone build.' >&2; exit 1", "seed": "echo 'seed: not written yet. Name the command here that loads development sample data into a fresh, migrated database.' >&2; exit 1"{% endif %} diff --git a/templates/app-nextjs/files/turbo.json b/templates/app-nextjs/files/turbo.json new file mode 100644 index 00000000..2a1a7d39 --- /dev/null +++ b/templates/app-nextjs/files/turbo.json @@ -0,0 +1,8 @@ +{ + "extends": ["//"], + "tasks": { + "build": { + "outputs": [".next/standalone/**"] + } + } +} From 5d7d4458fc459412c677a2f591e9637f2aaad986 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:01:06 +0100 Subject: [PATCH 015/194] Test: the platform is in the hash of an app's build and not in its check's A dry run with PLX_PLATFORM linux-x64 and with macos-arm64 gives the app's build two hashes and its check one. Red: nothing declares the variable on the app's build. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- newborns/app-nextjs.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index a4a46b40..f8434188 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -110,6 +110,20 @@ test('that directory is all the build leaves: a cache hit restores it whole', as assert.ok(existsSync(join(app, path)), path); }); +/** Turbo's hash of each task of an app, by task name, from a dry run in mise's environment with the platform given. */ +async function hashes(app: string, platform: string): Promise> { + const dry = `mise exec -- env PLX_PLATFORM=${platform} turbo run build check test --filter=@acme/${app} --dry=json`; + const plan = JSON.parse(await sh('sh', ['-c', `${dry} 2>/dev/null`], repo)); + return Object.fromEntries(plan.tasks.map((task: { task: string; hash: string }) => [task.task, task.hash])); +} + +test("the platform is in the hash of an app's build, and not in its check's", async () => { + const linux = await hashes('stateless', 'linux-x64'); + const mac = await hashes('stateless', 'macos-arm64'); + assert.notEqual(linux.build, mac.build); + assert.equal(linux.check, mac.check); +}); + test('the repo around the apps passes its own verify', async () => { // The lockfile predates the apps, and under CI=true the check's frozen install refuses it. await sh('mise', ['exec', '--', 'pnpm', 'install', '--lockfile-only'], repo); From 8f0e97a62b5c726727b7d5e13466f39cf69d95c5 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:01:06 +0100 Subject: [PATCH 016/194] The platform is in the hash of an app's build The app's turbo.json declares PLX_PLATFORM in its build's env, after $TURBO_EXTENDS$ so that the root's env stays; the repo's mise.toml sets it. Package builds, check and test do not carry it. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- templates/app-nextjs/files/turbo.json | 1 + 1 file changed, 1 insertion(+) diff --git a/templates/app-nextjs/files/turbo.json b/templates/app-nextjs/files/turbo.json index 2a1a7d39..1237df92 100644 --- a/templates/app-nextjs/files/turbo.json +++ b/templates/app-nextjs/files/turbo.json @@ -2,6 +2,7 @@ "extends": ["//"], "tasks": { "build": { + "env": ["$TURBO_EXTENDS$", "PLX_PLATFORM"], "outputs": [".next/standalone/**"] } } From ff0aa0fa65a46503cde80e31772427352f152557 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:01:43 +0100 Subject: [PATCH 017/194] Test: the build ID is the hash of the app's build, and the build guards it The BUILD_ID of the directory is Turbo's hash of the app's build task; a build started outside Turbo (pnpm run build) fails naming TURBO_HASH, and a build through Turbo without PLX_PLATFORM fails naming PLX_PLATFORM. Red: next.config.ts reads BUILD_HASH, and Next draws a random ID without it. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- newborns/app-nextjs.test.ts | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index f8434188..b784dc94 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -9,7 +9,7 @@ // the whole app wherever it lies, started as the standalone server, and is // what the build task's cache holds. import assert from 'node:assert/strict'; -import { cpSync, existsSync, readdirSync, rmSync } from 'node:fs'; +import { cpSync, existsSync, readdirSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { after, before, test } from 'node:test'; @@ -124,6 +124,24 @@ test("the platform is in the hash of an app's build, and not in its check's", as assert.equal(linux.check, mac.check); }); +test("the build ID is the hash of the app's build, and a build outside Turbo or without the platform fails", async () => { + await sh('mise', ['run', 'build', 'stateless'], repo, PLATFORM); + const { build } = await hashes('stateless', PLATFORM.PLX_PLATFORM); + assert.equal(readFileSync(join(output('stateless'), 'apps', 'stateless', '.next', 'BUILD_ID'), 'utf8'), build); + const outside = await tryRun( + 'mise', + ['exec', '--', 'pnpm', '--filter', '@acme/stateless', 'run', 'build'], + repo, + PLATFORM, + ); + assert.equal(outside.ok, false, outside.output); + assert.match(outside.output, /TURBO_HASH/); + const bare = ['exec', '--', 'env', '-u', 'PLX_PLATFORM', 'turbo', 'run', 'build', '--filter=@acme/stateless']; + const unplatformed = await tryRun('mise', bare, repo); + assert.equal(unplatformed.ok, false, unplatformed.output); + assert.match(unplatformed.output, /PLX_PLATFORM/); +}); + test('the repo around the apps passes its own verify', async () => { // The lockfile predates the apps, and under CI=true the check's frozen install refuses it. await sh('mise', ['exec', '--', 'pnpm', 'install', '--lockfile-only'], repo); From 9c8743ccd2026856a5c0374bae298cd2f00e2436 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:01:53 +0100 Subject: [PATCH 018/194] The build ID is Turbo's hash of the app's build, read from TURBO_HASH Turbo sets TURBO_HASH inside every task it runs, so generateBuildId returns it, and BUILD_HASH goes. It throws when TURBO_HASH or PLX_PLATFORM is missing: a build by hand or outside mise fails instead of shipping a random ID or a hash without the platform. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- templates/app-nextjs/files/next.config.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/templates/app-nextjs/files/next.config.ts b/templates/app-nextjs/files/next.config.ts index c19a6ef5..b55ccfe6 100644 --- a/templates/app-nextjs/files/next.config.ts +++ b/templates/app-nextjs/files/next.config.ts @@ -7,8 +7,16 @@ const root = process.env.PLX_UMBRELLA_ROOT || fileURLToPath(new URL('../../', im const nextConfig: NextConfig = { output: 'standalone', - // BUILD_HASH comes from the image build; without it Next draws a random ID, as in development. - generateBuildId: () => process.env.BUILD_HASH || null, + // The build ID is Turbo's hash of this app's build task, which carries the platform (turbo.json). + // A build started outside Turbo, or outside mise, which sets PLX_PLATFORM, would get another ID. + generateBuildId: () => { + const { TURBO_HASH, PLX_PLATFORM } = process.env; + if (!TURBO_HASH || !PLX_PLATFORM) + throw new Error( + `build through \`mise build\`, which sets TURBO_HASH and PLX_PLATFORM: TURBO_HASH=${TURBO_HASH ?? ''} PLX_PLATFORM=${PLX_PLATFORM ?? ''}`, + ); + return TURBO_HASH; + }, outputFileTracingRoot: root, turbopack: { root }, }; From a8423ab46387bb88676f427659245dc353270b62 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:03:35 +0100 Subject: [PATCH 019/194] Test: the build does not type-check, and check does With a type error in a test file, the app's build passes on a cache miss and on the hit of the same hash, and check fails naming the file. The guard's test now says which variable each failing build lacked. Red: next build type-checks the test file and fails the miss. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- newborns/app-nextjs.test.ts | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index b784dc94..d09299cc 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -135,11 +135,28 @@ test("the build ID is the hash of the app's build, and a build outside Turbo or PLATFORM, ); assert.equal(outside.ok, false, outside.output); - assert.match(outside.output, /TURBO_HASH/); + assert.match(outside.output, /TURBO_HASH= PLX_PLATFORM=\S/); const bare = ['exec', '--', 'env', '-u', 'PLX_PLATFORM', 'turbo', 'run', 'build', '--filter=@acme/stateless']; const unplatformed = await tryRun('mise', bare, repo); assert.equal(unplatformed.ok, false, unplatformed.output); - assert.match(unplatformed.output, /PLX_PLATFORM/); + assert.match(unplatformed.output, /TURBO_HASH=[0-9a-f]{16} PLX_PLATFORM=$/m); +}); + +test('the build does not type-check, so a hit and a miss of one hash agree, and check does', async () => { + const typo = join(repo, 'apps', 'stateless', 'src', 'typo.test.ts'); + put(repo, { 'apps/stateless/src/typo.test.ts': "export const n: number = 'not a number';\n" }); + await sh('git', ['add', '-A'], repo); + try { + assert.match(await sh('mise', ['run', 'build', 'stateless'], repo, PLATFORM), /cache miss/); + rmSync(join(repo, 'apps', 'stateless', '.next'), { recursive: true, force: true }); + assert.match(await sh('mise', ['run', 'build', 'stateless'], repo, PLATFORM), /cache hit/); + const check = await tryRun('mise', ['run', 'check', 'stateless'], repo); + assert.equal(check.ok, false, check.output); + assert.match(check.output, /typo\.test\.ts.*TS2322/); + } finally { + rmSync(typo, { force: true }); + await sh('git', ['add', '-A'], repo); + } }); test('the repo around the apps passes its own verify', async () => { From 1c751f239f8b96aadd276e6b2f6b6ceae99cf0ae Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:03:35 +0100 Subject: [PATCH 020/194] The build does not type-check: check is the type gate typescript.ignoreBuildErrors is set in the template's next.config.ts, so next build skips its type check; check (next typegen && tsc --noEmit) remains, and the build's outcome is the same on a hit and a miss of one hash once test files are no input of the build. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- templates/app-nextjs/files/next.config.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/templates/app-nextjs/files/next.config.ts b/templates/app-nextjs/files/next.config.ts index b55ccfe6..830af217 100644 --- a/templates/app-nextjs/files/next.config.ts +++ b/templates/app-nextjs/files/next.config.ts @@ -17,6 +17,9 @@ const nextConfig: NextConfig = { ); return TURBO_HASH; }, + // `check` is the type gate. The build's inputs need not hold every file the app's tsconfig.json + // includes, its tests among them, so a type check here could fail a miss where a hit of one hash passes. + typescript: { ignoreBuildErrors: true }, outputFileTracingRoot: root, turbopack: { root }, }; From 6a3c25f50bb7a9878cc63fc682759aea3c790a28 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:04:29 +0100 Subject: [PATCH 021/194] Test: an app's tests run by the repo's verb, and pass while it has none mise run test runs the app's own test task for an app of each profile, and passes with no test in the app. Red: the template's package.json has no test script, so Turbo runs nothing. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- newborns/app-nextjs.test.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index d09299cc..6469b541 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -159,6 +159,11 @@ test('the build does not type-check, so a hit and a miss of one hash agree, and } }); +test("an app's tests run by the repo's verb, and pass while it has none", async () => { + for (const profile of PROFILES) + assert.match(await sh('mise', ['run', 'test', profile], repo, PLATFORM), new RegExp(`@acme/${profile}:test`)); +}); + test('the repo around the apps passes its own verify', async () => { // The lockfile predates the apps, and under CI=true the check's frozen install refuses it. await sh('mise', ['exec', '--', 'pnpm', 'install', '--lockfile-only'], repo); From a6924410e27672720264d3945ccd126c019fd581 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:04:29 +0100 Subject: [PATCH 022/194] An app has a test script: Node's test runner, which passes with no tests node --test runs the app's *.test.ts files beside its source with Node's own type stripping, needs no dependency, and passes in an app without a test, as tooling's and the libraries' packages run theirs. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- templates/app-nextjs/files/package.json.jinja | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/templates/app-nextjs/files/package.json.jinja b/templates/app-nextjs/files/package.json.jinja index 36d0b065..6927e189 100644 --- a/templates/app-nextjs/files/package.json.jinja +++ b/templates/app-nextjs/files/package.json.jinja @@ -5,7 +5,8 @@ "scripts": { "dev": "next dev", "build": "next build && out=.next/standalone/$(node -p \"require('./.next/required-server-files.json').relativeAppDir\") && cp -R .next/static \"$out/.next/\" && if [ -d public ]; then cp -R public \"$out/\"; fi", - "check": "next typegen && tsc --noEmit"{% if profile == 'stateful' %}, + "check": "next typegen && tsc --noEmit", + "test": "node --test"{% if profile == 'stateful' %}, "migrate": "echo 'migrate: not written yet. Name the migration command here; the migrate service of docker/compose.yaml runs it in the image, which holds node and the standalone build.' >&2; exit 1", "seed": "echo 'seed: not written yet. Name the command here that loads development sample data into a fresh, migrated database.' >&2; exit 1"{% endif %} }, From f799ac42efa0cf9424f0306bdd94abefde30cf4a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:04:35 +0100 Subject: [PATCH 023/194] A BuildKit service on the runner host for the publish job (PLX-180) actions_runners installs buildkitd from BuildKit's release, pinned by version and SHA-256, and runs it as the unit ci-buildkit on 127.0.0.1 only, so that a small or medium slot builds and pushes an image through buildx's remote driver without a Docker daemon of its own. Its cache is bounded by BuildKit's own garbage collection (maxUsedSpace from a role variable); the daemon and every build step share one MemoryMax without swap, since the steps' cgroups sit below the unit's. The defaults record the three consequences of one shared service that the maintainer accepted, and the hourly housekeeping leaves its state alone. Co-Authored-By: Claude Opus 5.5 --- .../roles/actions_runners/defaults/main.yml | 61 +++++++++ .../files/ci-runner-housekeeping | 5 +- .../roles/actions_runners/tasks/buildkit.yml | 124 ++++++++++++++++++ .../ci/roles/actions_runners/tasks/main.yml | 3 + 4 files changed, 192 insertions(+), 1 deletion(-) create mode 100644 ansible/ci/roles/actions_runners/tasks/buildkit.yml diff --git a/ansible/ci/roles/actions_runners/defaults/main.yml b/ansible/ci/roles/actions_runners/defaults/main.yml index a04b5dfb..a27b829b 100644 --- a/ansible/ci/roles/actions_runners/defaults/main.yml +++ b/ansible/ci/roles/actions_runners/defaults/main.yml @@ -138,3 +138,64 @@ actions_runners_connect_port: 8080 # and so mails through mail, when the root file system is fuller # than this afterwards. actions_runners_disk_alert_percent: 85 + +# The BuildKit service (§ 8 PLX-Delivery): one buildkitd on the host, the +# systemd unit ci-buildkit, through which the publish job of a small or +# medium slot builds and pushes its image without a Docker daemon of its +# own, with buildx's remote driver: +# +# docker buildx create --name --driver remote tcp://127.0.0.1: +# docker buildx build --builder --platform linux/amd64 --push … +# +# It listens on 127.0.0.1 alone, without TLS. The small and medium slots +# share the host's network and reach it there; a large slot, on a network +# of its own, does not, and has a daemon of its own. No slot gains a socket +# or a privilege for it. The registry credentials travel from the job's +# ~/.docker/config.json through the build's session; the service holds +# none. Its state is /var/lib/buildkit, bounded by BuildKit's own garbage +# collection, which runs when the daemon starts and after builds; the +# hourly housekeeping leaves it alone. A change to the binary, the +# configuration or the unit restarts it, which a publish job in flight does +# not survive. Under the strategy `github` there is no runner host and so +# no service: the publish job uses the runner's Docker. +# +# One service for every job of every repo the host serves is accepted as it +# behaves, inside the one tenant the host serves (§ 1 PLX-Tenancy): +# - The layer cache is shared across jobs and repos. A step that used a +# secret mount (RUN --mount=type=secret) is reused from it by another job +# with the first job's secret, since the secret is not part of the cache +# key; a Dockerfile never bakes a secret into a layer. +# - Any job that reaches the endpoint can list and prune the whole cache. +# - A RUN step of a build runs on the host's network and reaches every +# service listening on the host's loopback. +# +# buildkitd runs as root, as dockerd does; its RUN steps are containers +# without privileges, since it grants no insecure entitlement such as +# security.insecure. Its rootless mode is not used: it needs RootlessKit, +# newuidmap and a subuid range on the host, and puts every RUN step on the +# host's network all the same. + +# The release, from github.com/moby/buildkit/releases for linux-amd64, by +# version and the tarball's SHA-256 (the asset's digest on the release page); +# the two move together, by hand, since no update bot can rewrite the +# checksum of a download. buildkitd, buildkit-runc and buildctl go to +# /usr/local/bin; buildctl is the operator's on the host, as in +# `buildctl --addr tcp://127.0.0.1: du`. +actions_runners_buildkit_version: v0.35.1 +actions_runners_buildkit_sha256: b248c2b91698aafef11818fe8b681dc5e341581f7d5676709ff45ca1f29b0408 +# The port on 127.0.0.1, which the publish job names in its remote driver. +actions_runners_buildkit_port: 1234 +# The most disk the cache may use, BuildKit's maxUsedSpace: bytes with a +# unit (10GB, as base 1024) or a percentage of the disk (20%); what is above +# it the garbage collection reclaims. +actions_runners_buildkit_cache_max: 10GB +# The memory of the daemon and every build step it runs, together, as +# systemd's MemoryMax= takes it (4G), with no swap beside it; empty is no +# limit. A build runs in the service, not in the slot that asked for it, so +# a slot's limit does not bound it; over this one a step is killed and its +# build fails, rather than the host starving the slots. A publish of the +# template's Dockerfile only copies the build output onto the base image +# and needs little; an app with a Dockerfile of its own builds inside it +# and needs what its build needs. The sum of the slots' limits and this one +# is the host's to afford. +actions_runners_buildkit_memory: 4G diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping b/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping index bc8c2ef3..5d23589a 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping +++ b/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping @@ -28,10 +28,13 @@ docker image ls --format '{{.Repository}}:{{.Tag}} {{.ID}}' | while read -r ref case "$ref" in "$IMAGE" | "$REGISTRY_IMAGE") continue ;; esac docker image rm "$id" >/dev/null 2>&1 && echo "removed the image $ref" || true done +# The BuildKit service (ci-buildkit) keeps its cache in /var/lib/buildkit, +# outside this daemon, and bounds it by its own garbage collection; nothing +# here touches it, since a build may be using it. used=$(df --output=pcent / | tail -1 | tr -dc '0-9') echo "root file system ${used}% used" if [ "$used" -gt "$DISK_ALERT_PERCENT" ]; then - echo "above ${DISK_ALERT_PERCENT}%: look at /var/cache/ci-runner (the pnpm store) and docker system df" >&2 + echo "above ${DISK_ALERT_PERCENT}%: look at /var/cache/ci-runner (the pnpm store), docker system df and /var/lib/buildkit (buildctl --addr tcp://127.0.0.1: du)" >&2 exit 1 fi diff --git a/ansible/ci/roles/actions_runners/tasks/buildkit.yml b/ansible/ci/roles/actions_runners/tasks/buildkit.yml new file mode 100644 index 00000000..05899575 --- /dev/null +++ b/ansible/ci/roles/actions_runners/tasks/buildkit.yml @@ -0,0 +1,124 @@ +--- +# The BuildKit service (defaults: actions_runners_buildkit_*): buildkitd from +# BuildKit's release, its configuration in BuildKit's default place, and the +# unit ci-buildkit. Started or restarted at the end, without a handler, so +# that the service answers once this file has run. +- name: Which buildkitd is installed + ansible.builtin.command: + cmd: /usr/local/bin/buildkitd --version + register: actions_runners_buildkit_installed + changed_when: false + failed_when: false + check_mode: false + +# `buildkitd --version` prints `buildkitd github.com/moby/buildkit `. +- name: Install buildkitd from the pinned release + when: actions_runners_buildkit_version not in actions_runners_buildkit_installed.stdout.split() + vars: + tarball: /var/tmp/buildkit-{{ actions_runners_buildkit_version }}.linux-amd64.tar.gz + block: + - name: Download the release + ansible.builtin.get_url: + url: >- + https://github.com/moby/buildkit/releases/download/{{ actions_runners_buildkit_version + }}/buildkit-{{ actions_runners_buildkit_version }}.linux-amd64.tar.gz + dest: "{{ tarball }}" + checksum: sha256:{{ actions_runners_buildkit_sha256 }} + owner: root + group: root + mode: "0600" + + # The daemon, the runc it runs build steps with, and the client; the + # tarball's emulators and CNI plugins are left out, since the builds are + # for the host's own platform and on the host's network. + - name: Unpack buildkitd, buildkit-runc and buildctl + ansible.builtin.unarchive: + src: "{{ tarball }}" + dest: /usr/local/bin + remote_src: true + include: [bin/buildkitd, bin/buildkit-runc, bin/buildctl] + extra_opts: [--strip-components=1] + owner: root + group: root + register: actions_runners_buildkit_binaries + when: not ansible_check_mode # the module needs the tarball, which check mode does not fetch + + - name: Remove the download + ansible.builtin.file: + path: "{{ tarball }}" + state: absent + +- name: Create the configuration directory + ansible.builtin.file: + path: /etc/buildkit + state: directory + owner: root + group: root + mode: "0755" + +# Both workers are named: the containerd worker would otherwise switch itself +# on beside the OCI worker wherever Docker's containerd socket exists. The +# build steps' cgroups go below the unit's own (Delegate=), so that its +# MemoryMax covers them; BuildKit places each at /buildkit/. +- name: Configure buildkitd + ansible.builtin.copy: + dest: /etc/buildkit/buildkitd.toml + owner: root + group: root + mode: "0644" + content: | + # Managed by Ansible (actions_runners); the role's defaults say why. + [grpc] + address = ["tcp://127.0.0.1:{{ actions_runners_buildkit_port }}"] + + [worker.oci] + enabled = true + gc = true + maxUsedSpace = "{{ actions_runners_buildkit_cache_max }}" + defaultCgroupParent = "system.slice/ci-buildkit.service" + + [worker.containerd] + enabled = false + register: actions_runners_buildkit_config + +# Type=notify: buildkitd reports ready once it listens. The daemon runs in +# the subgroup `daemon` of the unit's cgroup and the build steps beside it, +# since a cgroup that holds a process cannot hand controllers to children. +# The limit holds no swap besides, or a build over it would swap instead of +# failing. +- name: Install the BuildKit unit + ansible.builtin.copy: + dest: /etc/systemd/system/ci-buildkit.service + owner: root + group: root + mode: "0644" + content: | + [Unit] + Description=BuildKit for the publish jobs of the CI runner slots + Documentation=https://github.com/moby/buildkit + + [Service] + Type=notify + ExecStart=/usr/local/bin/buildkitd + Delegate=yes + DelegateSubgroup=daemon + MemoryMax={{ actions_runners_buildkit_memory | default('infinity', true) }} + MemorySwapMax={{ 0 if actions_runners_buildkit_memory else 'infinity' }} + Restart=always + RestartSec=5s + + [Install] + WantedBy=multi-user.target + register: actions_runners_buildkit_unit + +# A dry run that would write the unit has none to look up yet. +- name: Start the BuildKit service, restarted when it changed + when: not (ansible_check_mode and actions_runners_buildkit_unit is changed) + ansible.builtin.systemd_service: + name: ci-buildkit.service + enabled: true + daemon_reload: "{{ actions_runners_buildkit_unit is changed }}" + state: >- + {{ 'restarted' if (actions_runners_buildkit_binaries is changed + or actions_runners_buildkit_config is changed + or actions_runners_buildkit_unit is changed) else 'started' }} diff --git a/ansible/ci/roles/actions_runners/tasks/main.yml b/ansible/ci/roles/actions_runners/tasks/main.yml index 7ddf7d66..342f66a7 100644 --- a/ansible/ci/roles/actions_runners/tasks/main.yml +++ b/ansible/ci/roles/actions_runners/tasks/main.yml @@ -180,6 +180,9 @@ changed_when: actions_runners_connect_removed.stdout | length > 0 failed_when: false +- name: The BuildKit service + ansible.builtin.include_tasks: buildkit.yml + # What a slot's container is made of: the image and the cache for every # slot, the memory limit per size. ci-runner-slot reads both at the start of # a container, and the JIT script reads where to register, so a change to any From 308f86e4785d0aa0f56c13335e67db9eef4e108e Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:06:22 +0100 Subject: [PATCH 024/194] Test: the image is the directory, healthy under the app's compose file For an app of each profile, docker build with the directory as its context yields an image whose /repo lists exactly what the directory lists, with no source outside node_modules; under the app's compose file it becomes healthy and serves its page, a stateful app migrated first by its migrate service from a file the build traced into the directory. The render has one stage and no RUN in its Dockerfile, and no docker/compose.ci.yaml. Red: the Dockerfile builds from the repo root, and compose.ci.yaml is rendered. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- newborns/app-nextjs.test.ts | 75 +++++++++++++++++++++++++++++- packages/lib/src/appNextjs.test.ts | 8 +++- packages/lib/src/newSite.test.ts | 1 - 3 files changed, 80 insertions(+), 4 deletions(-) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index 6469b541..da8c1628 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -7,8 +7,11 @@ // (PLX-App/LoopbackPort), which needs docker compose. // An app's `build`, run by the repo's verb, leaves one directory that serves // the whole app wherever it lies, started as the standalone server, and is -// what the build task's cache holds. +// what the build task's cache holds. The image built from that directory alone +// holds it and nothing else, and becomes healthy under the app's compose file, +// a stateful app migrated first from what the directory holds; that needs docker. import assert from 'node:assert/strict'; +import { randomBytes } from 'node:crypto'; import { cpSync, existsSync, readdirSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -164,6 +167,76 @@ test("an app's tests run by the repo's verb, and pass while it has none", async assert.match(await sh('mise', ['run', 'test', profile], repo, PLATFORM), new RegExp(`@acme/${profile}:test`)); }); +/** Every path below `dir`, sorted, as Node lists it: the same call inside an image and outside. */ +const LIST = "console.log(JSON.stringify(require('fs').readdirSync(process.argv[1], { recursive: true }).sort()))"; + +for (const profile of PROFILES) { + test(`the image of a ${profile} app holds the directory and nothing else, and becomes healthy under its compose file`, async () => { + const app = join(repo, 'apps', profile); + if (profile === 'stateful') { + // What the migrate service runs is put into the directory by the build, here a file Next traces in. + const manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8')); + manifest.scripts.migrate = 'node migrate.mjs'; + const config = readFileSync(join(app, 'next.config.ts'), 'utf8').replace( + "output: 'standalone',", + "output: 'standalone',\n outputFileTracingIncludes: { '/*': ['./migrate.mjs'] },", + ); + put(app, { + 'package.json': manifest, + 'next.config.ts': config, + 'migrate.mjs': "console.log('migrated in', process.cwd());\n", + }); + await sh('git', ['add', '-A'], repo); + } + await sh('mise', ['run', 'build', profile], repo, PLATFORM); + const id = randomBytes(4).toString('hex'); + const tag = `plx-newborn-${profile}:${id}`; + // Limits for every container and build, on a machine others share; the build itself runs nothing. + const limits = { cpus: 4, mem_limit: '6g', pids_limit: 1000 }; + const resources = ['--resource', 'memory=6g', '--resource', 'cpu-quota=400000']; + // As the Dockerfile's header says: the directory is the context. + const dockerfile = join(app, 'docker', 'Dockerfile'); + await sh( + 'docker', + ['build', ...resources, '--build-arg', `APP=${profile}`, '-f', dockerfile, '-t', tag, output(profile)], + repo, + ); + try { + const run = ['run', '--rm', '--cpus', '4', '--memory', '6g', '--pids-limit', '1000', '--entrypoint', 'node']; + const held = JSON.parse( + (await sh('docker', [...run, tag, '-e', LIST, '/repo'], here)).trim().split('\n').at(-1) ?? '', + ); + const local = JSON.parse((await sh(process.execPath, ['-e', LIST, output(profile)], here)).trim()); + assert.deepEqual(held, local); + assert.deepEqual( + held.filter((path: string) => !path.split('/').includes('node_modules') && /(? { // The lockfile predates the apps, and under CI=true the check's frozen install refuses it. await sh('mise', ['exec', '--', 'pnpm', 'install', '--lockfile-only'], repo); diff --git a/packages/lib/src/appNextjs.test.ts b/packages/lib/src/appNextjs.test.ts index 14a13bbe..4ae90a0b 100644 --- a/packages/lib/src/appNextjs.test.ts +++ b/packages/lib/src/appNextjs.test.ts @@ -12,7 +12,6 @@ test('an app is rendered with its docker files and its source', async () => { '.gitignore', 'PLEXUS.md', 'docker/Dockerfile', - 'docker/compose.ci.yaml', 'docker/compose.yaml', 'next.config.ts', 'package.json', @@ -62,7 +61,12 @@ test('the profile is stateless unless the app says stateful', async () => { assert.ok('migrate' in scripts && 'seed' in scripts); assert.match(textOf(stateful, 'docker/compose.yaml'), /profiles: \["migrate"\]/); assert.match(textOf(stateful, 'PLEXUS.md'), /`migrate` and `seed`/); - assert.notEqual(textOf(stateful, 'docker/compose.ci.yaml'), textOf(stateless, 'docker/compose.ci.yaml')); +}); + +test('the Dockerfile has one stage, which builds and installs nothing', async () => { + const dockerfile = textOf(await render(), 'docker/Dockerfile'); + assert.equal(dockerfile.match(/^FROM /gm)?.length, 1); + assert.doesNotMatch(dockerfile, /^RUN /m); }); test('a profile is one of the two the app contract names', async () => { diff --git a/packages/lib/src/newSite.test.ts b/packages/lib/src/newSite.test.ts index 39bfaff7..fc8a7c00 100644 --- a/packages/lib/src/newSite.test.ts +++ b/packages/lib/src/newSite.test.ts @@ -375,7 +375,6 @@ test('a repo from repo-turbo with updates beside it and an app from app-nextjs i '.gitignore', 'PLEXUS.md', 'docker/Dockerfile', - 'docker/compose.ci.yaml', 'docker/compose.yaml', 'next.config.ts', 'package.json', From 3b8ab47538b67c237410657e8fcad69577683d1d Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:07:52 +0100 Subject: [PATCH 025/194] The Dockerfile only copies the directory the app's build leaves One stage: the Debian slim runtime base, the copy of .next/standalone as the build context, the user, the port and the entry point; it installs and builds nothing, and BUILD_HASH, the npmrc and the key's secrets go. Its header says what it is for and how to build by hand: mise build, then docker build with the directory as context, on Linux x64. docker/compose.ci.yaml is no longer rendered. The migrate placeholder and the marker say that what migrate runs goes into the directory, put there by the build. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- templates/app-nextjs/files/PLEXUS.md.jinja | 4 +- templates/app-nextjs/files/docker/Dockerfile | 37 +++---------------- .../files/docker/compose.ci.yaml.jinja | 22 ----------- .../files/docker/compose.yaml.jinja | 2 +- templates/app-nextjs/files/package.json.jinja | 2 +- 5 files changed, 9 insertions(+), 58 deletions(-) delete mode 100644 templates/app-nextjs/files/docker/compose.ci.yaml.jinja diff --git a/templates/app-nextjs/files/PLEXUS.md.jinja b/templates/app-nextjs/files/PLEXUS.md.jinja index d51b9733..31259eb7 100644 --- a/templates/app-nextjs/files/PLEXUS.md.jinja +++ b/templates/app-nextjs/files/PLEXUS.md.jinja @@ -1,5 +1,5 @@ -- `{{ name }}`, a Next.js app: `docker/Dockerfile` builds its image and `docker/compose.yaml` runs it on its host. +- `{{ name }}`, a Next.js app: its `build` leaves one directory that runs as it is, `.next/standalone`, `docker/Dockerfile` copies that directory into its image, and `docker/compose.yaml` runs the image on its host. - Its verbs are the repo root's: `mise :dev `, `mise :build ` and `mise :verify `, `` being this directory's name. {%- if profile == 'stateful' %} -- The `migrate` and `seed` scripts in `package.json` fail until they are written: the deploy verb runs `migrate` in the image, through the compose file's `migrate` service, and `seed` loads development data and never runs on a host. +- The `migrate` and `seed` scripts in `package.json` fail until they are written: the deploy verb runs `migrate` in the image, through the compose file's `migrate` service, from what the build put in the directory, and `seed` loads development data and never runs on a host. {%- endif %} diff --git a/templates/app-nextjs/files/docker/Dockerfile b/templates/app-nextjs/files/docker/Dockerfile index 6bc8931a..ff27282e 100644 --- a/templates/app-nextjs/files/docker/Dockerfile +++ b/templates/app-nextjs/files/docker/Dockerfile @@ -1,39 +1,12 @@ -# syntax=docker/dockerfile:1 # Generated from plexus-ms/tooling, templates/app-nextjs. -# The image build of a Next.js standalone app in the monorepo, from its root or a pruned context (PLX-App/Dockerfile). -FROM node:24-slim@sha256:c86ecead9e55a5210ac1727de38a4ca840bf03dcaf34dc9749addbf383b1920c AS builder +# The app's image: the one directory its build leaves, copied into the runtime base as it is (PLX-App/Dockerfile). +# By hand, on Linux x64 at the repo root: `mise build `, then `docker build --build-arg APP= -f apps//docker/Dockerfile apps//.next/standalone`. +FROM node:24-slim@sha256:c86ecead9e55a5210ac1727de38a4ca840bf03dcaf34dc9749addbf383b1920c ARG APP -WORKDIR /repo -ENV CI=1 -ENV COREPACK_ENABLE_DOWNLOAD_PROMPT=0 -RUN corepack enable -# package.json comes along so that corepack runs the pnpm its packageManager pins. -COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ -# The npmrc secret is the token of the tenant's private package registry, for a repo that installs -# from one (§ 5 PLX-Delivery); a build without the secret mounts nothing. -RUN --mount=type=secret,id=npmrc,target=/root/.npmrc pnpm fetch -COPY turbo.json ./ -COPY packages packages -COPY apps/${APP} apps/${APP} -# public/ is optional; an empty one lets the runner stage copy it unconditionally. -RUN mkdir -p apps/${APP}/public -RUN --mount=type=secret,id=npmrc,target=/root/.npmrc pnpm install --frozen-lockfile --prefer-offline -# pnpm, not Turbo, whose strict environment would hide BUILD_HASH and the key from `next build`; -# the filter's trailing `...` builds the app's workspace dependencies first, as `^build` would. -ARG BUILD_HASH -RUN --mount=type=secret,id=next-server-actions-encryption-key,env=NEXT_SERVER_ACTIONS_ENCRYPTION_KEY \ - BUILD_HASH=${BUILD_HASH} pnpm --filter "{./apps/${APP}}..." run build - -FROM node:24-slim@sha256:c86ecead9e55a5210ac1727de38a4ca840bf03dcaf34dc9749addbf383b1920c AS runner -ARG APP -WORKDIR /repo -ENV NODE_ENV=production -# The standalone output keeps the monorepo's layout; the static files and public/ go in beside it. -COPY --from=builder --chown=node:node /repo/apps/${APP}/.next/standalone ./ -COPY --from=builder --chown=node:node /repo/apps/${APP}/.next/static ./apps/${APP}/.next/static -COPY --from=builder --chown=node:node /repo/apps/${APP}/public ./apps/${APP}/public +COPY --chown=node:node . /repo WORKDIR /repo/apps/${APP} USER node EXPOSE 3000 +ENV NODE_ENV=production ENV HOSTNAME=0.0.0.0 ENTRYPOINT ["node", "server.js"] diff --git a/templates/app-nextjs/files/docker/compose.ci.yaml.jinja b/templates/app-nextjs/files/docker/compose.ci.yaml.jinja deleted file mode 100644 index 307f5604..00000000 --- a/templates/app-nextjs/files/docker/compose.ci.yaml.jinja +++ /dev/null @@ -1,22 +0,0 @@ -# Generated from plexus-ms/tooling, templates/app-nextjs. -# The override of compose.yaml that `plx-ci test` reads beside it, never the deploy verb (§ 1 PLX-Delivery). - -# Added to the environment the specs run in, on the runner beside the stack, to CI, PLEXUS_LOOPBACK_PORT and E2E_BASE_URL. -x-plexus-ci: - env: {} - -# Stands in for .env and .env.secret, with throwaway values. -x-ci-env: &ci-env - PUBLIC_URL: http://127.0.0.1:${PLEXUS_LOOPBACK_PORT:?set by plx-ci test} - -services: - web: - environment: *ci-env - restart: "no" -{%- if profile == "stateful" %} - # plx-ci test runs migrate once before `up`. - migrate: - environment: *ci-env - # Data services go here, published on 127.0.0.1 for the specs and kept in RAM (`volumes: !override []` - # and a tmpfs for the data directory), with the database URL in x-plexus-ci.env above. -{%- endif %} diff --git a/templates/app-nextjs/files/docker/compose.yaml.jinja b/templates/app-nextjs/files/docker/compose.yaml.jinja index 268f3ae4..7db0eaf8 100644 --- a/templates/app-nextjs/files/docker/compose.yaml.jinja +++ b/templates/app-nextjs/files/docker/compose.yaml.jinja @@ -33,7 +33,7 @@ services: migrate: image: ${PLEXUS_DEPLOYMENT_IMAGE:?rendered by the deploy verb} profiles: ["migrate"] - # npm, not pnpm: the image holds node and the standalone build and nothing else. + # npm, not pnpm: the image holds node and the directory the app's build leaves, and nothing else. entrypoint: ["npm", "run", "migrate"] environment: NODE_ENV: production diff --git a/templates/app-nextjs/files/package.json.jinja b/templates/app-nextjs/files/package.json.jinja index 6927e189..b689ea72 100644 --- a/templates/app-nextjs/files/package.json.jinja +++ b/templates/app-nextjs/files/package.json.jinja @@ -7,7 +7,7 @@ "build": "next build && out=.next/standalone/$(node -p \"require('./.next/required-server-files.json').relativeAppDir\") && cp -R .next/static \"$out/.next/\" && if [ -d public ]; then cp -R public \"$out/\"; fi", "check": "next typegen && tsc --noEmit", "test": "node --test"{% if profile == 'stateful' %}, - "migrate": "echo 'migrate: not written yet. Name the migration command here; the migrate service of docker/compose.yaml runs it in the image, which holds node and the standalone build.' >&2; exit 1", + "migrate": "echo 'migrate: not written yet. Name the migration command here; the migrate service of docker/compose.yaml runs it in the image, which holds node and the directory the build leaves, so the build puts in that directory whatever the command needs (outputFileTracingIncludes in next.config.ts, or the build script).' >&2; exit 1", "seed": "echo 'seed: not written yet. Name the command here that loads development sample data into a fresh, migrated database.' >&2; exit 1"{% endif %} }, "dependencies": { From 42196a9d408574dfe3249e20f62adb88c9c531ee Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:11:10 +0100 Subject: [PATCH 026/194] The Dockerfile's header is two lines, as plx requirements allows The generated-from line, then one line saying what the image is and how to build it by hand. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- templates/app-nextjs/files/docker/Dockerfile | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/templates/app-nextjs/files/docker/Dockerfile b/templates/app-nextjs/files/docker/Dockerfile index ff27282e..80945065 100644 --- a/templates/app-nextjs/files/docker/Dockerfile +++ b/templates/app-nextjs/files/docker/Dockerfile @@ -1,6 +1,5 @@ # Generated from plexus-ms/tooling, templates/app-nextjs. -# The app's image: the one directory its build leaves, copied into the runtime base as it is (PLX-App/Dockerfile). -# By hand, on Linux x64 at the repo root: `mise build `, then `docker build --build-arg APP= -f apps//docker/Dockerfile apps//.next/standalone`. +# The app's image, the one directory its build leaves copied in as it is (PLX-App/Dockerfile); by hand, on Linux x64 at the repo root: `mise build `, then `docker build --build-arg APP= -f apps//docker/Dockerfile apps//.next/standalone`. FROM node:24-slim@sha256:c86ecead9e55a5210ac1727de38a4ca840bf03dcaf34dc9749addbf383b1920c ARG APP COPY --chown=node:node . /repo From 7646d2785d767464a5e7966aeb5e8559c25b2623 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:13:08 +0100 Subject: [PATCH 027/194] The BuildKit service's stop is no failure; say what an OOM kill takes buildkitd ends with status 1 on SIGTERM, so every restart by the role and every reboot marked the unit failed and triggered the failure mail that plexus.host.mail makes every service's OnFailure. SuccessExitStatus=1 keeps a stop quiet; a kill, an OOM-killed daemon and a broken configuration still fail. The defaults now say that over the memory limit the kernel may kill the daemon itself, failing every build in flight. Co-Authored-By: Claude Opus 5.5 --- ansible/ci/roles/actions_runners/defaults/main.yml | 13 +++++++------ ansible/ci/roles/actions_runners/tasks/buildkit.yml | 3 +++ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/ansible/ci/roles/actions_runners/defaults/main.yml b/ansible/ci/roles/actions_runners/defaults/main.yml index a27b829b..9e5980be 100644 --- a/ansible/ci/roles/actions_runners/defaults/main.yml +++ b/ansible/ci/roles/actions_runners/defaults/main.yml @@ -192,10 +192,11 @@ actions_runners_buildkit_cache_max: 10GB # The memory of the daemon and every build step it runs, together, as # systemd's MemoryMax= takes it (4G), with no swap beside it; empty is no # limit. A build runs in the service, not in the slot that asked for it, so -# a slot's limit does not bound it; over this one a step is killed and its -# build fails, rather than the host starving the slots. A publish of the -# template's Dockerfile only copies the build output onto the base image -# and needs little; an app with a Dockerfile of its own builds inside it -# and needs what its build needs. The sum of the slots' limits and this one -# is the host's to afford. +# a slot's limit does not bound it. Over this one the kernel kills a +# process of the service rather than starve the slots: a build step, whose +# build fails, or the daemon itself, which systemd starts again, failing +# every build in flight. A publish of the template's Dockerfile only copies +# the build output onto the base image and needs little; an app with a +# Dockerfile of its own builds inside it and needs what its build needs. +# The sum of the slots' limits and this one is the host's to afford. actions_runners_buildkit_memory: 4G diff --git a/ansible/ci/roles/actions_runners/tasks/buildkit.yml b/ansible/ci/roles/actions_runners/tasks/buildkit.yml index 05899575..5be5d18f 100644 --- a/ansible/ci/roles/actions_runners/tasks/buildkit.yml +++ b/ansible/ci/roles/actions_runners/tasks/buildkit.yml @@ -104,6 +104,9 @@ DelegateSubgroup=daemon MemoryMax={{ actions_runners_buildkit_memory | default('infinity', true) }} MemorySwapMax={{ 0 if actions_runners_buildkit_memory else 'infinity' }} + # buildkitd ends with status 1 on SIGTERM: a stop, not a failure, so a + # restart or a reboot marks it failed for nobody. + SuccessExitStatus=1 Restart=always RestartSec=5s From 35ca2d09f533f80cdd3dc764713c5d706862a4d7 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:13:21 +0100 Subject: [PATCH 028/194] feat(cli-ci): an instance runs its runner in the environment image The user-data installs Docker, pulls the environment image and starts the runner in a container of it as a small slot does: the host's network, where the registry pair answers, no Docker socket, the runner's config as ACTIONS_RUNNER_INPUT_JITCONFIG from a root-only file. The runner tarball, its user on the host, the buildx builder and the test images' pulls go; the runner's _diag is the host's /opt/runner/_diag, so the no-job layer and a kept instance's disk read it where they did. The image is the one of plx-ci's own version, or RUNNER_IMAGE for a trial of an unreleased one. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/commands/hybrid.ts | 7 ++- packages/cli-ci/src/core/createInstances.ts | 9 ++-- packages/cli-ci/src/core/userData.test.ts | 5 +- packages/cli-ci/src/core/userData.ts | 54 ++++++++++++--------- 4 files changed, 43 insertions(+), 32 deletions(-) diff --git a/packages/cli-ci/src/commands/hybrid.ts b/packages/cli-ci/src/commands/hybrid.ts index ecb6a717..ae9bea95 100644 --- a/packages/cli-ci/src/commands/hybrid.ts +++ b/packages/cli-ci/src/commands/hybrid.ts @@ -8,7 +8,9 @@ // RUNNER_TOKEN (Administration: write on the repo); EXOSCALE_API_KEY/_SECRET // (ci-launch); SELF_DELETE_KEY/_SECRET; SELF_LAYERS; SMTP_* and MAIL_*, // REGISTRY_* (optional); NO_JOB_MINUTES, DEATH_MINUTES, POWEROFF_MINUTES; -// INSTANCE_TYPE, ZONE, ONLINE_SECONDS. +// INSTANCE_TYPE, ZONE, ONLINE_SECONDS; RUNNER_IMAGE, the environment image the +// runner runs in, by default the one of this plx-ci's version (a trial names +// an unreleased `…:sha-` from runner-image.yml). // // destroy-instances: the run's cleanup, delete what this run and attempt // created and the registrations nothing used; kept instances are left alone. @@ -30,7 +32,7 @@ import { smtpFromEnv } from '../core/mail.ts'; import type { Leg } from '../core/plan.ts'; import { storageFromEnv } from '../core/registry.ts'; import { sweepInstances } from '../core/sweepInstances.ts'; -import { contextOf } from '../program.ts'; +import { contextOf, version } from '../program.ts'; import { exoOf, githubOf, need, runIdentity, zoneOf } from './shared.ts'; /** The launch options the environment carries; label and app come from the plan's legs. */ @@ -56,6 +58,7 @@ export function launchOptionsFromEnv(env: NodeJS.ProcessEnv = process.env): Omit sshKey: DEFAULTS.sshKey, onlineSeconds: Number(env.ONLINE_SECONDS || DEFAULTS.onlineSeconds), tries: DEFAULTS.tries, + image: env.RUNNER_IMAGE || `${DEFAULTS.imageRepository}:${version}`, }; } diff --git a/packages/cli-ci/src/core/createInstances.ts b/packages/cli-ci/src/core/createInstances.ts index dee20bb4..4e749852 100644 --- a/packages/cli-ci/src/core/createInstances.ts +++ b/packages/cli-ci/src/core/createInstances.ts @@ -72,6 +72,8 @@ export interface LaunchOptions { onlineSeconds: number; /** Instances tried before the launch gives up: the first and one replacement. */ tries: number; + /** The environment image the runner runs in, as a slot's does: `:`. */ + image: string; /** The wait between two looks at the runner; the tests pass none. */ sleep?: (ms: number) => Promise; now?: () => Date; @@ -86,8 +88,8 @@ export const DEFAULTS = { sshKey: 'runners', onlineSeconds: 120, tries: 2, - runnerVersion: '2.338.2', - runnerSha256: 'baebf204307bac6193480852732f0aba2ae97b6c5597c244f4d5558390147c40', + /** The environment image, built by runner-image.yml and tagged with the Plexus version. */ + imageRepository: 'ghcr.io/plexus-ms/ci-runner', /** What the API accepts, base64 characters. */ userDataLimit: 32768, } as const; @@ -117,8 +119,7 @@ export function renderUserData(options: LaunchOptions, jitconfig: string, now: D APP: options.app ?? '', REPO: options.run.repo, RUN: options.run.runId, - RUNNER_VERSION: DEFAULTS.runnerVersion, - RUNNER_SHA256: DEFAULTS.runnerSha256, + IMAGE: options.image, JITCONFIG: jitconfig, SELF_DELETE_KEY: options.selfDelete.key, SELF_DELETE_SECRET: options.selfDelete.secret, diff --git a/packages/cli-ci/src/core/userData.test.ts b/packages/cli-ci/src/core/userData.test.ts index de238eab..1c421a14 100644 --- a/packages/cli-ci/src/core/userData.test.ts +++ b/packages/cli-ci/src/core/userData.test.ts @@ -27,9 +27,10 @@ test('the runner template is cloud-config that arms the timers first, pulls the assert.match(RUNNER_USER_DATA, /SELF_LAYERS=@@SELF_LAYERS@@/); }); -/** The line of the user-data that starts with `key=`, trimmed. */ +/** The line of the runner's unit that starts with `key=`, trimmed. */ const unitLine = (key: string) => - RUNNER_USER_DATA.split('\n') + RUNNER_USER_DATA.slice(RUNNER_USER_DATA.indexOf('path: /etc/systemd/system/plexus-ci-runner.service')) + .split('\n') .find((l) => l.trim().startsWith(`${key}=`)) ?.trim() ?? ''; diff --git a/packages/cli-ci/src/core/userData.ts b/packages/cli-ci/src/core/userData.ts index 4c6c066c..19687665 100644 --- a/packages/cli-ci/src/core/userData.ts +++ b/packages/cli-ci/src/core/userData.ts @@ -1,5 +1,9 @@ // The cloud-config an instance boots with (§ 8 PLX-Delivery), as text: a -// runner's, with every teardown layer. The placeholders `@@NAME@@` are filled +// runner's, with every teardown layer. The runner runs as on a runner host's +// slot: in a container of the environment image (actions_runners' ci-runner), +// on the host's network, with no Docker socket, so a job meets the same +// machine under on-prem and hybrid; the instance's own Docker runs that one +// container and the registry pair, and nothing for the job. The placeholders `@@NAME@@` are filled // by render(); a leftover placeholder is an error. Kept as string constants so // that the bundle carries them and the tests render them without a loader. The // cloud-config itself is documented inline; edit here, nowhere else. @@ -38,8 +42,8 @@ export const RUNNER_USER_DATA = `#cloud-config # network, no SSH), so every layer is a systemd timer started in runcmd. # # The self-delete key and the registry bucket's write key sit in -# /etc/plexus-ci/env, readable by root; the job that runs here could read -# them anyway (§ 8 PLX-Delivery). +# /etc/plexus-ci/env, readable by root on the host; the job's container +# mounts none of /etc/plexus-ci (§ 8 PLX-Delivery). hostname: @@LABEL@@ write_files: @@ -66,11 +70,12 @@ write_files: REGISTRY_PREVIOUS_BUCKET=@@REGISTRY_PREVIOUS_BUCKET@@ REGISTRY_ACCESS_KEY=@@REGISTRY_ACCESS_KEY@@ REGISTRY_SECRET_KEY=@@REGISTRY_SECRET_KEY@@ - RUNNER_VERSION=@@RUNNER_VERSION@@ - RUNNER_SHA256=@@RUNNER_SHA256@@ - - path: /etc/plexus-ci/jitconfig + # The runner's config, as a slot's container gets it (ci-runner-jit): the + # runner reads the variable and clears it before any job step runs. + - path: /etc/plexus-ci/runner.env permissions: "0600" - content: "@@JITCONFIG@@" + content: | + ACTIONS_RUNNER_INPUT_JITCONFIG=@@JITCONFIG@@ # The cloud's API with curl, signed with the self-delete key (EXO2-HMAC-SHA256, # as egoscale signs: method and path, body, the query's values, the signed @@ -138,9 +143,10 @@ write_files: content: | #!/bin/sh # Layer 1b: the runner spawns a Worker process for a job and nothing - # else, and logs it as _diag/Worker_*.log; _work itself exists, empty, - # from the runner's start, so it tells nothing. No Worker log by now - # means no job ever came, and nothing will. + # else, and logs it as _diag/Worker_*.log, which the container writes + # to /opt/runner/_diag on the host; _work itself exists, empty, from + # the runner's start, so it tells nothing. No Worker log by now means + # no job ever came, and nothing will. set -u if ! ls /opt/runner/_diag/Worker_*.log >/dev/null 2>&1; then logger -t plexus-ci "no job started, deleting" @@ -234,22 +240,24 @@ write_files: dpkg --configure -a logger -t plexus-ci "apt-free: apt timers masked, dpkg lock free after \${i}s" - # The runner, one job, then layer 1: ExecStopPost runs as root (the +) when - # the runner exits for any reason. + # The runner, one job in a container of the environment image, then layer + # 1: ExecStopPost runs as root (the +) when the container ends for any + # reason, a runner that could not start included. The container is the + # one a small slot of a runner host starts (ci-runner-slot): the host's + # network, where the registry pair answers, and no Docker socket. Its + # _diag is the host's /opt/runner/_diag, which layer 1b reads and which + # a kept instance's disk keeps. - path: /etc/systemd/system/plexus-ci-runner.service content: | [Unit] Description=plexus-ci: GitHub Actions runner @@LABEL@@, one job After=network-online.target docker.service Wants=network-online.target + Requires=docker.service [Service] Type=simple - User=runner - WorkingDirectory=/opt/runner - Environment=HOME=/home/runner - ExecStart=/bin/sh -c 'exec ./run.sh --jitconfig "$(cat /etc/plexus-ci/jitconfig)"' + ExecStart=/usr/bin/docker run --rm --init --name runner --network host --env-file /etc/plexus-ci/runner.env -v /opt/runner/_diag:/home/runner/_diag @@IMAGE@@ ./run.sh ExecStopPost=+/usr/local/sbin/plexus-ci-self-delete runner-exit - KillMode=process TimeoutStopSec=2min runcmd: @@ -257,17 +265,15 @@ runcmd: - systemctl daemon-reload - systemctl start plexus-ci-no-job.timer plexus-ci-death.timer plexus-ci-poweroff.timer - plexus-ci-apt-free - - export DEBIAN_FRONTEND=noninteractive; apt-get update -q && apt-get install -yq --no-install-recommends ca-certificates curl jq git tar unzip + - export DEBIAN_FRONTEND=noninteractive; apt-get update -q && apt-get install -yq --no-install-recommends ca-certificates curl - curl -fsSL https://get.docker.com | sh - - useradd -m -s /bin/bash -G docker runner && echo 'runner ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/runner - - cp /etc/plexus-ci/jitconfig /etc/plexus-ci/jitconfig.runner && chown runner:runner /etc/plexus-ci/jitconfig.runner && mv /etc/plexus-ci/jitconfig.runner /etc/plexus-ci/jitconfig - - . /etc/plexus-ci/env && mkdir -p /opt/runner && cd /opt/runner && curl -fsSLo runner.tgz "https://github.com/actions/runner/releases/download/v\${RUNNER_VERSION}/actions-runner-linux-x64-\${RUNNER_VERSION}.tar.gz" && echo "\${RUNNER_SHA256} runner.tgz" | sha256sum -c - && tar -xzf runner.tgz && rm runner.tgz && ./bin/installdependencies.sh >/dev/null && chown -R runner:runner /opt/runner + # The image's user runner (1001) writes the runner's log here. + - install -d -o 1001 -g 1001 /opt/runner/_diag # The registry sidecars, when the launch named a bucket (§ 8 PLX-Delivery): :5000 on this week's bucket, read-write; :5001 on the previous week's, read-only. The same two containers as .github/ci/registry.sh starts on a GitHub runner. - . /etc/plexus-ci/env && if [ -n "$REGISTRY_ENDPOINT" ]; then docker run -d --name registry --restart unless-stopped -p 127.0.0.1:5000:5000 -e REGISTRY_STORAGE=s3 -e REGISTRY_STORAGE_S3_REGIONENDPOINT="$REGISTRY_ENDPOINT" -e REGISTRY_STORAGE_S3_REGION="$REGISTRY_REGION" -e REGISTRY_STORAGE_S3_BUCKET="$REGISTRY_BUCKET" -e REGISTRY_STORAGE_S3_ACCESSKEY="$REGISTRY_ACCESS_KEY" -e REGISTRY_STORAGE_S3_SECRETKEY="$REGISTRY_SECRET_KEY" -e REGISTRY_STORAGE_S3_FORCEPATHSTYLE=true -e REGISTRY_STORAGE_DELETE_ENABLED=true registry:2 >/dev/null; fi - . /etc/plexus-ci/env && if [ -n "$REGISTRY_ENDPOINT" ]; then docker run -d --name registry-previous --restart on-failure:3 -p 127.0.0.1:5001:5000 -e REGISTRY_STORAGE=s3 -e REGISTRY_STORAGE_S3_REGIONENDPOINT="$REGISTRY_ENDPOINT" -e REGISTRY_STORAGE_S3_REGION="$REGISTRY_REGION" -e REGISTRY_STORAGE_S3_BUCKET="$REGISTRY_PREVIOUS_BUCKET" -e REGISTRY_STORAGE_S3_ACCESSKEY="$REGISTRY_ACCESS_KEY" -e REGISTRY_STORAGE_S3_SECRETKEY="$REGISTRY_SECRET_KEY" -e REGISTRY_STORAGE_S3_FORCEPATHSTYLE=true -e 'REGISTRY_STORAGE_MAINTENANCE_READONLY={"enabled":true}' registry:2 >/dev/null; fi - # A builder: the docker driver cannot export a registry cache, so BuildKit runs in its own container on the host's network, where localhost:5000 is the sidecar; bootstrapped now so that the build does not wait for it. Every instance gets it and the test's images: there is one kind of instance, whatever its leg owes. - - su -s /bin/bash runner -c 'docker buildx create --name ci --driver docker-container --driver-opt network=host --bootstrap >/dev/null' & - - docker pull -q postgres:18.6 >/dev/null & docker pull -q rustfs/rustfs:1.0.4 >/dev/null & + # Pulled here rather than by the runner's unit, so that the log says how long the pull took. + - docker pull -q @@IMAGE@@ - systemctl start plexus-ci-runner.service `; From bcef9f4400f93941444315c35ec0b215e6ebdfc3 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:24:22 +0100 Subject: [PATCH 029/194] feat(actions_runners): one environment image for slots, instances and agent machines The ci-runner image is built on the runtime base of app-nextjs, digest and all (Debian 12 with node 24 today), so that a build in it runs in the image that ships; tests/runner-image-base.sh holds the two equal in check-ops. It holds the runner, mise with plx-ci at the Plexus version, the vault's CLI, gh, crane and exo installed system-wide from its own mise.toml, pnpm through corepack, docker's client with buildx, openssl and the libraries a Chromium needs; no browser, no PostgreSQL, no libvips, no Docker daemon. A repo's pins win over it and install into mise's directories. Every slot now runs the same unprivileged container on the host's network with no Docker socket; ci-runner-dind goes, since no job needs a daemon. The slots share mise's data, state and cache directories, so that two jobs installing one version wait on mise's lock, and Playwright's browsers. Co-Authored-By: Claude Fable 5.2 --- .../roles/actions_runners/defaults/main.yml | 38 ++--- .../actions_runners/files/ci-runner-slot | 53 +++---- .../files/ci-runner/Dockerfile | 146 ++++++++++++++---- .../files/ci-runner/ci-runner-dind | 31 ---- .../actions_runners/files/ci-runner/mise.toml | 22 +++ .../ci/roles/actions_runners/tasks/main.yml | 2 +- mise.toml | 3 +- tests/runner-image-base.sh | 17 ++ 8 files changed, 196 insertions(+), 116 deletions(-) delete mode 100755 ansible/ci/roles/actions_runners/files/ci-runner/ci-runner-dind create mode 100644 ansible/ci/roles/actions_runners/files/ci-runner/mise.toml create mode 100755 tests/runner-image-base.sh diff --git a/ansible/ci/roles/actions_runners/defaults/main.yml b/ansible/ci/roles/actions_runners/defaults/main.yml index a04b5dfb..c1830d46 100644 --- a/ansible/ci/roles/actions_runners/defaults/main.yml +++ b/ansible/ci/roles/actions_runners/defaults/main.yml @@ -13,17 +13,14 @@ # under on-prem all three, under hybrid small and medium, since the large # jobs then run on instances the plan launches. # -# A small or medium slot has no Docker socket: its jobs need none, and a -# socket would be root on this host. It runs with the host's network, so it -# reaches the registry pair on localhost and the overlay's names the host -# resolves. A large slot runs the jobs that need Docker (build, test) and -# has a daemon of its own inside its container, with its data on a volume -# that goes with the container: the job meets an empty machine, as on a -# launched instance, takes its layers from the registry, and leaves nothing -# on the host. That container is privileged, which is root on this host, and -# has a network of its own, so that the two daemons do not share one. Every -# slot holds the job's secrets in flight like any runner: one host serves -# one tenant and runs nothing else (§ 1 PLX-Tenancy). +# Every slot, whatever its size, runs the same container of the environment +# image (files/ci-runner), the one a launched instance runs too: no Docker +# socket, since no job needs a daemon and a socket would be root on this +# host, no privileges, and the host's network, so that it reaches the +# registry pair on localhost and the overlay's names the host resolves. The +# size decides only the memory limit. Every slot holds the job's secrets in +# flight like any runner: one host serves one tenant and runs nothing else +# (§ 1 PLX-Tenancy). # # The host needs Docker before this role (docker). The role opens no # port: the runner polls the forge, and the registry pair listens on loopback. @@ -48,8 +45,8 @@ actions_runners_runner_group: Default # PLX-Delivery: plan, publish, deploy, cleanup and housekeeping are small, # check is medium, build and test are large). `memory` is the limit of one # slot's container, as `docker run --memory` takes it; under it a job is -# killed rather than the host starved, and for a large slot it covers the -# daemon inside and everything the job starts there. Empty, or left out, +# killed rather than the host starved, and it covers everything the job +# starts, a browser and a test database included. Empty, or left out, # is no limit. A size with count 0, or dropped, stops and disables its units. # The sum of count × memory is the host's to afford; one large slot per host # is the layout that keeps two builds from contending. @@ -87,8 +84,7 @@ actions_runners_app_private_key: "{{ lookup('env', 'CI_APP_PRIVATE_KEY') | defau # 127.0.0.1:5000 against this week's bucket, read-write, and on :5001 # against the previous week's, read-only, as a job elsewhere starts them # for itself (`plx-ci registry`, which finds them answering here and starts -# nothing; a large slot, with a network of its own, starts its own pair on -# the same buckets). The buckets are `-ci-registry-`; the +# nothing). The buckets are `-ci-registry-`; the # housekeeping creates this week's when it is missing and moves the pair to # the new buckets at the week change. Set false for a tenant on GHCR alone. actions_runners_registry: true @@ -101,9 +97,15 @@ actions_runners_registry_region: "{{ lookup('env', 'REGISTRY_REGION') | default( actions_runners_registry_access_key: "{{ lookup('env', 'REGISTRY_ACCESS_KEY') | default('', true) }}" actions_runners_registry_secret_key: "{{ lookup('env', 'REGISTRY_SECRET_KEY') | default('', true) }}" -# The caches shared by every slot, bind-mounted into each container: the -# pnpm store, built for concurrent writers (content-addressed, files added -# by atomic rename). Owned by the image's runner user. +# The caches shared by every slot, bind-mounted into each container +# (ci-runner-slot), each safe for concurrent jobs: the pnpm store +# (content-addressed, files added by atomic rename); mise's data, state and +# cache directories, where a repo's pins the image lacks install, its node +# and its PostgreSQL among them (mise locks a version while it installs it); +# and Playwright's browsers, whose version follows each repo (Playwright +# locks the directory while it installs). Nothing prunes them: a version no +# repo pins any more stays until removed by hand. Owned by the image's +# runner user. actions_runners_cache_dir: /var/cache/ci-runner actions_runners_runner_uid: 1001 diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-slot b/ansible/ci/roles/actions_runners/files/ci-runner-slot index c7f90dc7..27cc12ec 100755 --- a/ansible/ci/roles/actions_runners/files/ci-runner-slot +++ b/ansible/ci/roles/actions_runners/files/ci-runner-slot @@ -1,14 +1,16 @@ #!/bin/sh # Runs the container of one slot for one job (ExecStart of -# ci-runner@.service). Managed by Ansible (actions_runners). The slot's size -# is the part of its name before the last dash, and decides the container: +# ci-runner@.service). Managed by Ansible (actions_runners). Every size gets +# the same container of the environment image (files/ci-runner): the host's +# network (the registry pair and the Connect server on localhost, the +# overlay's names), no Docker socket, no privileges, since no job needs a +# Docker daemon; the size is the part of the slot's name before the last +# dash and decides only the memory limit. # -# small, medium the host's network (the registry pair on localhost, the -# overlay's names), no Docker socket, no privileges -# large privileged, a network of its own, and a Docker daemon -# inside with its data on a volume removed with the -# container (ci-runner-dind, in the image): the jobs that -# need Docker meet an empty machine +# The caches every slot shares, bind-mounted from CACHE_DIR: the pnpm store; +# mise's data, state and cache directories, where a repo's pins install (its +# node, its PostgreSQL), all three so that two jobs installing one version +# wait on mise's own lock; and Playwright's browsers. # # From /etc/ci-runner/slot.env: IMAGE and CACHE_DIR; from # /etc/ci-runner/size-.env: MEMORY, the container's limit, empty for @@ -25,36 +27,21 @@ MEMORY= # shellcheck source=/dev/null . "/etc/ci-runner/size-$size.env" -set -- --rm --init --name "ci-runner-$instance" \ +home=/home/runner +set -- --rm --init --name "ci-runner-$instance" --network host \ --env-file "/run/ci-runner/$instance.env" \ -e pnpm_config_store_dir=/cache/pnpm-store \ - -v "$CACHE_DIR/pnpm-store:/cache/pnpm-store" + -v "$CACHE_DIR/pnpm-store:/cache/pnpm-store" \ + -v "$CACHE_DIR/mise/data:$home/.local/share/mise" \ + -v "$CACHE_DIR/mise/state:$home/.local/state/mise" \ + -v "$CACHE_DIR/mise/cache:$home/.cache/mise" \ + -v "$CACHE_DIR/ms-playwright:$home/.cache/ms-playwright" [ -z "$MEMORY" ] || set -- "$@" --memory "$MEMORY" # The host's Connect server, where the role runs one (/etc/ci-runner/connect.env: -# OP_CONNECT_TOKEN and OP_CONNECT_PORT): the job's secret reads go there. A -# small or medium slot reaches it on loopback; the large slot, on a network -# of its own, at Docker's host gateway. -connect_host= +# OP_CONNECT_TOKEN and OP_CONNECT_PORT): the job's secret reads go there. if [ -f /etc/ci-runner/connect.env ]; then # shellcheck source=/dev/null . /etc/ci-runner/connect.env - set -- "$@" --env-file /etc/ci-runner/connect.env - connect_host=127.0.0.1 - [ "$size" != large ] || connect_host=host.docker.internal - set -- "$@" -e "OP_CONNECT_HOST=http://$connect_host:$OP_CONNECT_PORT" + set -- "$@" --env-file /etc/ci-runner/connect.env -e "OP_CONNECT_HOST=http://127.0.0.1:$OP_CONNECT_PORT" fi -case "$size" in - large) - # The daemon inside starts as root and hands over to the runner user; - # a privileged container is root on the host already, so the engine's - # no-new-privileges buys nothing here and is lifted, which lets a job - # install system packages as it would on a machine of its own. - set -- "$@" --privileged --security-opt no-new-privileges=false --user 0 \ - --add-host host.docker.internal:host-gateway \ - -v /var/lib/docker "$IMAGE" ci-runner-dind - ;; - *) - set -- "$@" --network host "$IMAGE" ./run.sh - ;; -esac -exec /usr/bin/docker run "$@" +exec /usr/bin/docker run "$@" "$IMAGE" ./run.sh diff --git a/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile b/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile index 3b06da0a..f617bda7 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile +++ b/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile @@ -1,38 +1,120 @@ -# The runner image of a runner host's container slots (§ 8 PLX-Delivery, -# actions_runners), one image for every size: the official runner image plus -# what the jobs expect of GitHub's runners and the official image leaves -# out. One container runs one job and is removed after it; nothing here is a -# cache or a secret. Built and pushed by runner-image.yml as -# ghcr.io/plexus-ms/ci-runner at the Plexus version, with provenance, or built -# on the host itself (actions_runners_image_build); Renovate moves the base. +# The environment image (§ 8 PLX-Delivery, actions_runners): the one machine +# a CI job runs in, on a runner host's slots, on the hybrid strategy's +# throwaway instances (plx-ci's user-data), and on an agent's Linux machine. +# One container runs one job and is removed after it; nothing here is a cache +# or a secret, and the token for a tenant's private packages is the job's to +# give. Built and pushed by runner-image.yml as ghcr.io/plexus-ms/ci-runner at +# the Plexus version, with provenance, or built on the host itself +# (actions_runners_image_build); Renovate moves the pins. # -# The tools the jobs install themselves (mise and what it pins, exo, crane, -# the 1Password CLI) stay the jobs' business: a slot runs the same steps as -# a GitHub runner, and a version here would be a second pin of each. +# Built on the runtime base of the app-nextjs template, digest and all, so +# that what a job builds here runs in the image that ships: the same Debian +# release, glibc and node (tests/runner-image-base.sh holds the two equal). +# What it holds: # -# A large slot runs a Docker daemon inside its container (ci-runner-dind). -# The official image carries Docker's static binaries, the daemon among -# them, and buildx; what the daemon and the jobs need beyond is here: -# iptables for the daemon's networks, and the compose plugin for the test -# stacks. -FROM ghcr.io/actions/actions-runner:2.338.2@sha256:6d0b2d80d80f143f77dcb676e50920100bbb547e39e883454d57f45ab8c31300 - -USER root -# git for actions/checkout (without it the action downloads a tarball and -# later git commands fail), jq and unzip for the jobs' own steps and the -# 1Password action, zstd for the cache actions, gnupg for apt keys, iptables -# for the daemon of a large slot, libatomic1 for node 26 and later, which -# mise installs for plx-ci where the repo pins no node (an operations repo). +# the runner GitHub's Actions runner and the libraries it needs, run +# as the user runner (1001), with sudo where the engine +# allows it (a slot's no-new-privileges does not) +# node, pnpm node from the base; pnpm through corepack, at the +# version a repo's packageManager names +# mise and, from mise.toml beside this file (mise's system +# config), plx-ci at the Plexus version, the vault's CLI, +# gh, crane and exo, the tools the small jobs installed +# for themselves +# docker's client with buildx, for an image build against a BuildKit +# elsewhere; no daemon, since no job here needs one +# packages git for actions/checkout, jq, unzip, zstd for the cache +# actions, xz and bzip2 for archives mise unpacks, +# libatomic1 for a node 26 mise installs, openssl, by +# which Prisma picks its engine at build time, and the +# libraries a Chromium needs, as Playwright lists them +# +# A repo's own pin of a tool wins once the job has run `mise install`: mise.toml +# here is the lowest of mise's configs, its tools sit in mise's system +# directory, which mise searches after its data directory, and the shims of +# both dispatch by the config of the directory a command runs in. A version +# the image lacks installs into mise's directories under ~/.local/share, +# ~/.local/state and ~/.cache, which a runner host shares between its slots, +# all three, so that two jobs installing one version wait on mise's own lock. +# +# Left out on purpose: +# +# browsers their version follows each repo's Playwright; a repo installs +# them into ~/.cache/ms-playwright, which a runner host shares +# between its slots like mise's data directory +# PostgreSQL its version follows each repo's pin, which mise installs into +# its data directory +# libvips sharp brings its own; a system libvips at or above the +# minimum of a repo's sharp makes sharp compile itself, and the +# install fails +FROM node:24-slim@sha256:c86ecead9e55a5210ac1727de38a4ca840bf03dcaf34dc9749addbf383b1920c + +ENV DEBIAN_FRONTEND=noninteractive +# The runner's own, as in the official runner image: it handles SIGTERM +# itself, and prints its worker log, which a slot's journal keeps. +ENV RUNNER_MANUALLY_TRAP_SIG=1 ACTIONS_RUNNER_PRINT_LOG_TO_STDOUT=1 + RUN apt-get update \ - && apt-get install -y --no-install-recommends ca-certificates curl git gnupg iptables jq libatomic1 unzip zstd \ + && apt-get install -y --no-install-recommends \ + bzip2 ca-certificates curl git gnupg jq libatomic1 openssl sudo unzip xz-utils zstd \ && rm -rf /var/lib/apt/lists/* -# renovate: datasource=github-releases depName=docker/compose -ARG COMPOSE_VERSION=v5.7.0 -ARG COMPOSE_SHA256=7758048ad38e580f22559603312874fec8bb638d021a9e64182385fc17cc12a2 -RUN curl -fsSL -o /usr/local/lib/docker/cli-plugins/docker-compose \ - "https://github.com/docker/compose/releases/download/${COMPOSE_VERSION}/docker-compose-linux-x86_64" \ - && echo "${COMPOSE_SHA256} /usr/local/lib/docker/cli-plugins/docker-compose" | sha256sum -c - \ - && chmod 0755 /usr/local/lib/docker/cli-plugins/docker-compose -COPY --chmod=0755 ci-runner-dind /usr/local/bin/ci-runner-dind + +# renovate: datasource=github-releases depName=actions/runner +ARG RUNNER_VERSION=2.338.2 +ARG RUNNER_SHA256=baebf204307bac6193480852732f0aba2ae97b6c5597c244f4d5558390147c40 +RUN useradd --create-home --uid 1001 --shell /bin/bash runner \ + && echo 'runner ALL=(ALL) NOPASSWD:ALL' >/etc/sudoers.d/runner \ + && cd /home/runner \ + && curl -fsSL -o runner.tgz \ + "https://github.com/actions/runner/releases/download/v${RUNNER_VERSION}/actions-runner-linux-x64-${RUNNER_VERSION}.tar.gz" \ + && echo "${RUNNER_SHA256} runner.tgz" | sha256sum -c - \ + && tar -xzf runner.tgz && rm runner.tgz \ + && apt-get update && ./bin/installdependencies.sh && rm -rf /var/lib/apt/lists/* \ + && mkdir -p .local/share/mise .local/state/mise .cache/mise .cache/ms-playwright \ + && chown -R runner:runner /home/runner + +# renovate: datasource=github-releases depName=docker/cli +ARG DOCKER_VERSION=29.10.1 +ARG DOCKER_SHA256=061642059fa7f2ed9b2f04a327a951cff4249585cf04b2661c2a6539197c9962 +# renovate: datasource=github-releases depName=docker/buildx +ARG BUILDX_VERSION=v0.39.1 +ARG BUILDX_SHA256=903090816da68f8bc1a2ff5346dd163a5adacfce4548d003c75df42cd47a9bf4 +RUN curl -fsSL -o /tmp/docker.tgz "https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_VERSION}.tgz" \ + && echo "${DOCKER_SHA256} /tmp/docker.tgz" | sha256sum -c - \ + && tar -xzf /tmp/docker.tgz -C /usr/local/bin --strip-components 1 docker/docker && rm /tmp/docker.tgz \ + && mkdir -p /usr/local/lib/docker/cli-plugins \ + && curl -fsSL -o /usr/local/lib/docker/cli-plugins/docker-buildx \ + "https://github.com/docker/buildx/releases/download/${BUILDX_VERSION}/buildx-${BUILDX_VERSION}.linux-amd64" \ + && echo "${BUILDX_SHA256} /usr/local/lib/docker/cli-plugins/docker-buildx" | sha256sum -c - \ + && chmod 0755 /usr/local/lib/docker/cli-plugins/docker-buildx + +# The libraries alone: install-deps never downloads a browser. +# renovate: datasource=npm depName=playwright +ARG PLAYWRIGHT_VERSION=1.65.1 +RUN apt-get update \ + && npx --yes "playwright@${PLAYWRIGHT_VERSION}" install-deps chromium \ + && rm -rf /var/lib/apt/lists/* /root/.npm + +# corepack's shims for pnpm, which fetch the version a repo names on first use. +ENV COREPACK_ENABLE_DOWNLOAD_PROMPT=0 +RUN corepack enable pnpm + +# renovate: datasource=github-releases depName=jdx/mise +ARG MISE_VERSION=v2026.11.8 +ARG MISE_SHA256=32b6abe844efa43d37d7ac4ed21d2ec41e9479d66feb19b0db8d2c548cd6e36d +RUN curl -fsSL -o /usr/local/bin/mise "https://github.com/jdx/mise/releases/download/${MISE_VERSION}/mise-${MISE_VERSION}-linux-x64" \ + && echo "${MISE_SHA256} /usr/local/bin/mise" | sha256sum -c - \ + && chmod 0755 /usr/local/bin/mise +COPY mise.toml /etc/mise/config.toml +RUN mise install --system && mise reshim --system && rm -rf /root/.cache /root/.local /root/.npm +# The data directory's shims first, then the system's: either dispatches by +# the config of the directory a command runs in. A job's checkout is under +# _work, which mise trusts without asking, as mise-action does on the forge. +ENV PATH=/home/runner/.local/share/mise/shims:/usr/local/share/mise/shims:$PATH \ + MISE_TRUSTED_CONFIG_PATHS=/home/runner/_work MISE_YES=1 + USER runner WORKDIR /home/runner +# Not the base's node entrypoint: the runner, one job. +ENTRYPOINT [] +CMD ["./run.sh"] diff --git a/ansible/ci/roles/actions_runners/files/ci-runner/ci-runner-dind b/ansible/ci/roles/actions_runners/files/ci-runner/ci-runner-dind deleted file mode 100755 index bd88eff8..00000000 --- a/ansible/ci/roles/actions_runners/files/ci-runner/ci-runner-dind +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh -# The entry of a large slot's container (actions_runners, ci-runner-slot): a -# Docker daemon of the container's own, then the runner as the runner user. -# Started as root in a privileged container; the daemon's data is the volume -# at /var/lib/docker, which goes with the container, so every job meets an -# empty daemon and leaves nothing behind. -set -eu - -# cgroup v2: a cgroup with processes of its own cannot hand controllers to -# children, and the daemon needs them for its containers' limits. Move -# everything here into a child first, then delegate. -if [ -f /sys/fs/cgroup/cgroup.controllers ]; then - mkdir -p /sys/fs/cgroup/init - xargs -rn1 /sys/fs/cgroup/init/cgroup.procs 2>/dev/null || : - sed -e 's/ / +/g' -e 's/^/+/' /sys/fs/cgroup/cgroup.subtree_control 2>/dev/null || : -fi - -dockerd --group docker >/var/log/dockerd.log 2>&1 & -for _ in $(seq 1 60); do - docker info >/dev/null 2>&1 && break - sleep 1 -done -if ! docker info >/dev/null 2>&1; then - echo "ci-runner-dind: the Docker daemon did not come up" >&2 - tail -n 40 /var/log/dockerd.log >&2 || : - exit 1 -fi - -cd /home/runner -export HOME=/home/runner USER=runner LOGNAME=runner -exec setpriv --reuid runner --regid runner --init-groups ./run.sh diff --git a/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml b/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml new file mode 100644 index 00000000..f864fa65 --- /dev/null +++ b/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml @@ -0,0 +1,22 @@ +# The tools the environment image carries (Dockerfile beside this file), as +# mise's system config, /etc/mise/config.toml: the lowest of mise's configs, so +# that a repo's own pin of any of them wins. Installed at build time into mise's +# system directory, which mise searches after its data directory and never +# writes; a version a repo pins and the image lacks installs into the data +# directory, which a runner host shares between its slots. +[tools] +# plx-ci at the Plexus version: the pin is written with each version, never by +# the update bot (§ 1 PLX-Updates); allow_low_downloads only waives npm's +# young-package heuristics. It runs on the base image's node. +"npm:@plexus-ms/cli-ci" = { version = "0.133.0", allow_low_downloads = true } +# The vault's CLI, which load-secrets-action uses where it finds one. +"aqua:1password/cli" = "2.42.0" +# What the small jobs installed for themselves: gh for plx-update, crane for +# the forge's registry, exo for the hybrid strategy's instances. +gh = "2.106.0" +crane = "0.22.1" +"github:exoscale/cli" = { version = "1.103.2", bin = "exo" } + +[settings] +# The image's mise moves with the image, by its pin: no warning about a newer one in every job's log. +disable_update_warning = true diff --git a/ansible/ci/roles/actions_runners/tasks/main.yml b/ansible/ci/roles/actions_runners/tasks/main.yml index 7ddf7d66..ab887495 100644 --- a/ansible/ci/roles/actions_runners/tasks/main.yml +++ b/ansible/ci/roles/actions_runners/tasks/main.yml @@ -118,7 +118,7 @@ owner: "{{ actions_runners_runner_uid }}" group: "{{ actions_runners_runner_uid }}" mode: "0755" - loop: ["", pnpm-store] + loop: ["", pnpm-store, mise, mise/data, mise/state, mise/cache, ms-playwright] - name: Pull the runner image when: not actions_runners_image_build diff --git a/mise.toml b/mise.toml index 494d239c..e57d5d5f 100644 --- a/mise.toml +++ b/mise.toml @@ -125,7 +125,7 @@ fi ''' [tasks.check-ops] -description = "actionlint over the workflows; ansible-lint over the collections (their Galaxy dependencies installed on first use), a syntax check of their playbooks and of a playbook that lists every role" +description = "actionlint over the workflows; ansible-lint over the collections (their Galaxy dependencies installed on first use), a syntax check of their playbooks and of a playbook that lists every role; the runner image on the apps' runtime base" hide = true run = [ 'actionlint', @@ -134,6 +134,7 @@ run = [ 'ansible-playbook --syntax-check -i tests/inventory.yml tests/all-roles.yml', 'ansible-playbook --syntax-check -i tests/inventory.yml plexus.platform.playbook plexus.infrastructure.playbook plexus.ci.playbook', './tests/all-roles-listed.sh', + './tests/runner-image-base.sh', ] # ANSIBLE_HOME keeps ansible-lint's cache and every collections path inside the # project, so a plexus.* collection installed user-wide (a tenant's pin) never diff --git a/tests/runner-image-base.sh b/tests/runner-image-base.sh new file mode 100755 index 00000000..72d3ca59 --- /dev/null +++ b/tests/runner-image-base.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Fails when the environment image is not built on the runtime base of the +# app-nextjs template, digest and all: a build in CI has to run in the image +# that ships (actions_runners' files/ci-runner/Dockerfile). +set -euo pipefail +cd "$(dirname "$0")/.." + +env_image=ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile +runtime=templates/app-nextjs/files/docker/Dockerfile + +# The environment image's one base, and the app's last stage, the one that ships. +ours=$(awk '/^FROM / { print $2; exit }' "$env_image") +theirs=$(awk '/^FROM / { base = $2 } END { print base }' "$runtime") +if [ "$ours" != "$theirs" ]; then + echo "✗ $env_image is built on $ours, the runtime base of $runtime is $theirs" >&2 + exit 1 +fi From dcd0df81078e6a5ffe7bb9a4496b0d7ef154a686 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:25:01 +0100 Subject: [PATCH 030/194] ci: install on the forge's runners only what the environment image carries mise-action, exo, crane and Chromium's system libraries are installed on GitHub-hosted runners alone (runner.environment); on a slot or an instance the environment image carries them, and a step runs mise install for the repo's pins the image lacks, with mise's lock and its directories shared between slots. The jobs, their order and their verbs are as they were. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/_changeset.yml | 8 ++++ .github/workflows/_check.yml | 8 ++++ .github/workflows/_deploy-targets.yml | 8 ++++ .github/workflows/_deploy.yml | 10 ++++- .github/workflows/_housekeeping.yml | 15 +++++-- .github/workflows/_plx-update.yml | 8 ++++ .github/workflows/_publish-package.yml | 8 ++++ .github/workflows/_release.yml | 33 +++++++++++++--- .github/workflows/_verify.yml | 55 ++++++++++++++++++-------- 9 files changed, 127 insertions(+), 26 deletions(-) diff --git a/.github/workflows/_changeset.yml b/.github/workflows/_changeset.yml index b001cf26..69527145 100644 --- a/.github/workflows/_changeset.yml +++ b/.github/workflows/_changeset.yml @@ -115,7 +115,15 @@ jobs: ref: ${{ github.head_ref }} fetch-depth: 0 token: ${{ steps.app.outputs.token }} + # mise and the repo's pins: on the forge's runners from mise-action; in the + # environment image of a slot or an instance (actions_runners), which + # carries mise and the common tools, the pins it lacks install here. - uses: jdx/mise-action@v5 + if: ${{ runner.environment == 'github-hosted' }} + - if: ${{ runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: mise install - run: plx -y changeset --base 'origin/${{ inputs.base }}' - run: | git add .changeset diff --git a/.github/workflows/_check.yml b/.github/workflows/_check.yml index b9fc5031..6df8824b 100644 --- a/.github/workflows/_check.yml +++ b/.github/workflows/_check.yml @@ -135,7 +135,15 @@ jobs: run: | printf '//npm.pkg.github.com/:_authToken=%s\n' "$GITHUB_TOKEN" > "$RUNNER_TEMP/npmrc" echo "NPM_CONFIG_USERCONFIG=$RUNNER_TEMP/npmrc" >> "$GITHUB_ENV" + # mise and the repo's pins: on the forge's runners from mise-action; in the + # environment image of a slot or an instance (actions_runners), which + # carries mise and the common tools, the pins it lacks install here. - uses: jdx/mise-action@v5 + if: ${{ runner.environment == 'github-hosted' }} + - if: ${{ runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: mise install - name: Check env: TASKS: ${{ inputs.tasks }} diff --git a/.github/workflows/_deploy-targets.yml b/.github/workflows/_deploy-targets.yml index f5b62980..c410d7a0 100644 --- a/.github/workflows/_deploy-targets.yml +++ b/.github/workflows/_deploy-targets.yml @@ -35,7 +35,15 @@ jobs: matrix: ${{ steps.run.outputs.matrix }} steps: - uses: actions/checkout@v7 + # mise and the repo's pins: on the forge's runners from mise-action; in the + # environment image of a slot or an instance (actions_runners), which + # carries mise and the common tools, the pins it lacks install here. - uses: jdx/mise-action@v5 + if: ${{ runner.environment == 'github-hosted' }} + - if: ${{ runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: mise install - id: run # The assignment is a line of its own so that a failing verb fails the step. run: | diff --git a/.github/workflows/_deploy.yml b/.github/workflows/_deploy.yml index 3f6627ea..d35c068b 100644 --- a/.github/workflows/_deploy.yml +++ b/.github/workflows/_deploy.yml @@ -131,8 +131,16 @@ jobs: # The caller's repo (the app's source repo) — cwd for the verb, which # reads apps// relative here. Same SHA the image was built from. - uses: actions/checkout@v7 - # The caller's tools, plx among them. + # The caller's tools, plx among them: on the forge's runners from + # mise-action; in the environment image of a slot or an instance + # (actions_runners), which carries mise and the common tools, the pins it + # lacks install here. - uses: jdx/mise-action@v5 + if: ${{ runner.environment == 'github-hosted' }} + - if: ${{ runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: mise install - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: diff --git a/.github/workflows/_housekeeping.yml b/.github/workflows/_housekeeping.yml index 6dc15324..e3b6ed79 100644 --- a/.github/workflows/_housekeeping.yml +++ b/.github/workflows/_housekeeping.yml @@ -89,10 +89,17 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 + # mise and the repo's pins: on the forge's runners from mise-action; in the + # environment image of a slot or an instance (actions_runners), which + # carries mise and the common tools, the pins it lacks install here. - uses: jdx/mise-action@v5 - if: ${{ inputs.tooling-ref == '' }} + if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: install_args: node npm:@plexus-ms/cli-ci + - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: mise install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: @@ -132,10 +139,10 @@ jobs: REGISTRY_REGION: op://${{ env.VAULT }}/bucket-registry/region REGISTRY_ACCESS_KEY: op://${{ env.VAULT }}/bucket-registry/access-key-id REGISTRY_SECRET_KEY: op://${{ env.VAULT }}/bucket-registry/secret-access-key - # Into the job's home, not /usr/local: a small or medium slot of a runner - # host (actions_runners) runs with no-new-privileges, so sudo is no option. + # On the forge's runners only: the environment image of a slot or an + # instance carries it (actions_runners). - name: Install exo - if: ${{ inputs.strategy == 'hybrid' }} + if: ${{ runner.environment == 'github-hosted' && inputs.strategy == 'hybrid' }} run: | mkdir -p "$HOME/.local/bin" && echo "$HOME/.local/bin" >> "$GITHUB_PATH" curl -fsSL "https://github.com/exoscale/cli/releases/download/v${EXO_VERSION}/exoscale-cli_${EXO_VERSION}_linux_amd64.tar.gz" | tar -xz -C "$HOME/.local/bin" exo diff --git a/.github/workflows/_plx-update.yml b/.github/workflows/_plx-update.yml index 02956fe2..3e7723f6 100644 --- a/.github/workflows/_plx-update.yml +++ b/.github/workflows/_plx-update.yml @@ -128,7 +128,15 @@ jobs: - uses: actions/checkout@v7 with: token: ${{ steps.app.outputs.token }} + # mise and the repo's pins: on the forge's runners from mise-action; in the + # environment image of a slot or an instance (actions_runners), which + # carries mise and the common tools, the pins it lacks install here. - uses: jdx/mise-action@v5 + if: ${{ runner.environment == 'github-hosted' }} + - if: ${{ runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: mise install - run: command -v gh >/dev/null || mise use --global gh@latest - run: plx -y update ${{ inputs.version != '' && format('--to {0}', inputs.version) || '' }} ${{ inputs.now && '--now' || '' }} env: diff --git a/.github/workflows/_publish-package.yml b/.github/workflows/_publish-package.yml index fe5af06e..1a3b1a2c 100644 --- a/.github/workflows/_publish-package.yml +++ b/.github/workflows/_publish-package.yml @@ -79,7 +79,15 @@ jobs: printf '@%s:registry=https://npm.pkg.github.com\n' "$scope" } > "$RUNNER_TEMP/npmrc" echo "NPM_CONFIG_USERCONFIG=$RUNNER_TEMP/npmrc" >> "$GITHUB_ENV" + # mise and the repo's pins: on the forge's runners from mise-action; in the + # environment image of a slot or an instance (actions_runners), which + # carries mise and the common tools, the pins it lacks install here. - uses: jdx/mise-action@v5 + if: ${{ runner.environment == 'github-hosted' }} + - if: ${{ runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: mise install - run: pnpm install --frozen-lockfile # Build every package in dependency order before publishing: `changeset # publish` runs the packages' `prepack` hooks alphabetically, so a diff --git a/.github/workflows/_release.yml b/.github/workflows/_release.yml index 1fa5f8d1..7718c956 100644 --- a/.github/workflows/_release.yml +++ b/.github/workflows/_release.yml @@ -141,10 +141,17 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 + # mise and the repo's pins: on the forge's runners from mise-action; in the + # environment image of a slot or an instance (actions_runners), which + # carries mise and the common tools, the pins it lacks install here. - uses: jdx/mise-action@v5 - if: ${{ inputs.tooling-ref == '' }} + if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: install_args: node npm:@plexus-ms/cli-ci + - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: mise install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: @@ -171,9 +178,10 @@ jobs: REGISTRY_REGION: op://${{ env.VAULT }}/bucket-registry/region REGISTRY_ACCESS_KEY: op://${{ env.VAULT }}/bucket-registry/access-key-id REGISTRY_SECRET_KEY: op://${{ env.VAULT }}/bucket-registry/secret-access-key - # Into the job's home, not /usr/local: a small or medium slot of a runner - # host (actions_runners) runs with no-new-privileges, so sudo is no option. + # On the forge's runners only: the environment image of a slot or an + # instance carries it (actions_runners). - name: Install crane + if: ${{ runner.environment == 'github-hosted' }} run: | mkdir -p "$HOME/.local/bin" && echo "$HOME/.local/bin" >> "$GITHUB_PATH" curl -fsSL "https://github.com/google/go-containerregistry/releases/download/v${CRANE_VERSION}/go-containerregistry_Linux_x86_64.tar.gz" | tar -xz -C "$HOME/.local/bin" crane @@ -209,10 +217,17 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 + # mise and the repo's pins: on the forge's runners from mise-action; in the + # environment image of a slot or an instance (actions_runners), which + # carries mise and the common tools, the pins it lacks install here. - uses: jdx/mise-action@v5 - if: ${{ inputs.tooling-ref == '' }} + if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: install_args: node npm:@plexus-ms/cli-ci + - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: mise install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: @@ -230,6 +245,7 @@ jobs: pnpm --filter @plexus-ms/cli-ci... run build >/dev/null mkdir -p bin && ln -sf "$PWD/packages/cli-ci/dist/plx-ci.js" bin/plx-ci && echo "$PWD/bin" >> "$GITHUB_PATH" - name: Install crane + if: ${{ runner.environment == 'github-hosted' }} run: | mkdir -p "$HOME/.local/bin" && echo "$HOME/.local/bin" >> "$GITHUB_PATH" curl -fsSL "https://github.com/google/go-containerregistry/releases/download/v${CRANE_VERSION}/go-containerregistry_Linux_x86_64.tar.gz" | tar -xz -C "$HOME/.local/bin" crane @@ -283,10 +299,17 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 + # mise and the repo's pins: on the forge's runners from mise-action; in the + # environment image of a slot or an instance (actions_runners), which + # carries mise and the common tools, the pins it lacks install here. - uses: jdx/mise-action@v5 - if: ${{ inputs.tooling-ref == '' }} + if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: install_args: node npm:@plexus-ms/cli-ci + - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: mise install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: diff --git a/.github/workflows/_verify.yml b/.github/workflows/_verify.yml index bb1a6f72..f0928e52 100644 --- a/.github/workflows/_verify.yml +++ b/.github/workflows/_verify.yml @@ -162,10 +162,17 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 + # mise and the repo's pins: on the forge's runners from mise-action; in the + # environment image of a slot or an instance (actions_runners), which + # carries mise and the common tools, the pins it lacks install here. - uses: jdx/mise-action@v5 - if: ${{ inputs.tooling-ref == '' }} + if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: install_args: node npm:@plexus-ms/cli-ci + - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: mise install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: @@ -224,17 +231,17 @@ jobs: - name: Read the relay's port from the vault if: ${{ inputs.strategy == 'hybrid' }} run: echo "SMTP_PORT=$(op read "op://${VAULT}/smtp-relay/port")" >> "$GITHUB_ENV" - # Into the job's home, not /usr/local: a small or medium slot of a runner - # host (actions_runners) runs with no-new-privileges, so sudo is no option. + # On the forge's runners only: the environment image of a slot or an + # instance carries it (actions_runners). - name: Install exo - if: ${{ inputs.strategy == 'hybrid' }} + if: ${{ runner.environment == 'github-hosted' && inputs.strategy == 'hybrid' }} run: | mkdir -p "$HOME/.local/bin" && echo "$HOME/.local/bin" >> "$GITHUB_PATH" curl -fsSL "https://github.com/exoscale/cli/releases/download/v${EXO_VERSION}/exoscale-cli_${EXO_VERSION}_linux_amd64.tar.gz" | tar -xz -C "$HOME/.local/bin" exo - # Into the job's home, not /usr/local: a small or medium slot of a runner - # host (actions_runners) runs with no-new-privileges, so sudo is no option. + # On the forge's runners only: the environment image of a slot or an + # instance carries it (actions_runners). - name: Install crane - if: ${{ inputs.registry == 'ghcr' }} + if: ${{ runner.environment == 'github-hosted' && inputs.registry == 'ghcr' }} run: | mkdir -p "$HOME/.local/bin" && echo "$HOME/.local/bin" >> "$GITHUB_PATH" curl -fsSL "https://github.com/google/go-containerregistry/releases/download/v${CRANE_VERSION}/go-containerregistry_Linux_x86_64.tar.gz" | tar -xz -C "$HOME/.local/bin" crane @@ -326,10 +333,17 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 + # mise and the repo's pins: on the forge's runners from mise-action; in the + # environment image of a slot or an instance (actions_runners), which + # carries mise and the common tools, the pins it lacks install here. - uses: jdx/mise-action@v5 - if: ${{ inputs.tooling-ref == '' }} + if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: install_args: node npm:@plexus-ms/cli-ci + - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: mise install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: @@ -367,7 +381,7 @@ jobs: # plx-ci test finds the candidate with crane, which reads the login # docker writes below; into the job's home, as in plan. - name: Install crane - if: ${{ inputs.registry == 'ghcr' && matrix.test != '' }} + if: ${{ runner.environment == 'github-hosted' && inputs.registry == 'ghcr' && matrix.test != '' }} run: | mkdir -p "$HOME/.local/bin" && echo "$HOME/.local/bin" >> "$GITHUB_PATH" curl -fsSL "https://github.com/google/go-containerregistry/releases/download/v${CRANE_VERSION}/go-containerregistry_Linux_x86_64.tar.gz" | tar -xz -C "$HOME/.local/bin" crane @@ -391,9 +405,10 @@ jobs: - name: The registry run: plx-ci registry # The specs and their dependencies, the app's own; Chromium's headless - # shell, which is all a headless spec launches, with its system libraries - # at the Playwright version the lockfile pins. Started here in the - # background, so that it runs beside the build, and awaited below. + # shell, which is all a headless spec launches, at the Playwright version + # the lockfile pins, with its system libraries on the forge's runners + # (the environment image carries them). Started here in the background, + # so that it runs beside the build, and awaited below. - name: Start installing the app's dependencies and the browser if: ${{ matrix.test != '' }} run: | @@ -403,7 +418,7 @@ jobs: set -e corepack enable pnpm install --frozen-lockfile --filter "{./apps/${{ matrix.app }}}..." - pnpm --filter "./apps/${{ matrix.app }}" exec playwright install --with-deps --only-shell chromium + pnpm --filter "./apps/${{ matrix.app }}" exec playwright install ${{ runner.environment == 'github-hosted' && '--with-deps' || '' }} --only-shell chromium ) echo $? > "$RUNNER_TEMP/install.exit" } > "$RUNNER_TEMP/install.log" 2>&1 & @@ -454,10 +469,17 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 + # mise and the repo's pins: on the forge's runners from mise-action; in the + # environment image of a slot or an instance (actions_runners), which + # carries mise and the common tools, the pins it lacks install here. - uses: jdx/mise-action@v5 - if: ${{ inputs.tooling-ref == '' }} + if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: install_args: node npm:@plexus-ms/cli-ci + - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: mise install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: @@ -492,9 +514,10 @@ jobs: owner: ${{ github.repository_owner }} repositories: ${{ github.event.repository.name }} permission-administration: write - # Into the job's home, not /usr/local: a small or medium slot of a runner - # host (actions_runners) runs with no-new-privileges, so sudo is no option. + # On the forge's runners only: the environment image of a slot or an + # instance carries it (actions_runners). - name: Install exo + if: ${{ runner.environment == 'github-hosted' }} run: | mkdir -p "$HOME/.local/bin" && echo "$HOME/.local/bin" >> "$GITHUB_PATH" curl -fsSL "https://github.com/exoscale/cli/releases/download/v${EXO_VERSION}/exoscale-cli_${EXO_VERSION}_linux_amd64.tar.gz" | tar -xz -C "$HOME/.local/bin" exo From d1a16658290d098188f559c12972578b8a7c1ead Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:25:05 +0100 Subject: [PATCH 031/194] ci(runner-image): build the environment image once its plx-ci is on npm The image installs plx-ci at the version from npm, which release.yml publishes from the same release; on a release the build waits for it. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/runner-image.yml | 34 +++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/.github/workflows/runner-image.yml b/.github/workflows/runner-image.yml index d668d3a2..61fc72af 100644 --- a/.github/workflows/runner-image.yml +++ b/.github/workflows/runner-image.yml @@ -1,14 +1,15 @@ name: runner-image -# Builds the runner image of a runner host's slots (the Dockerfile actions_runners -# ships, ansible/ci/roles/actions_runners/files/ci-runner, § 8 -# PLX-Delivery) and pushes it to ghcr.io/plexus-ms/ci-runner with a provenance -# attestation. On the version's GitHub release it is tagged with the version -# number, which is the pin actions_runners carries; run by hand on a branch it -# is tagged `sha-`, which is how a host tries an unreleased image -# before the version (the role's `actions_runners_image`). A tag already in the -# registry is pushed again, from the same source: the Plexus version names one -# commit. +# Builds the environment image a CI job runs in, on a runner host's slots and +# on the hybrid strategy's instances (the Dockerfile actions_runners ships, +# ansible/ci/roles/actions_runners/files/ci-runner, § 8 PLX-Delivery), and +# pushes it to ghcr.io/plexus-ms/ci-runner with a provenance attestation. On +# the version's GitHub release it is tagged with the version number, which is +# the pin actions_runners carries and the image plx-ci's instances pull; run +# by hand on a branch it is tagged `sha-`, which is how a host or an +# instance (RUNNER_IMAGE) tries an unreleased image before the version (the +# role's `actions_runners_image`). A tag already in the registry is pushed +# again, from the same source: the Plexus version names one commit. on: release: @@ -32,6 +33,19 @@ jobs: attestations: write steps: - uses: actions/checkout@v7 + # The image installs plx-ci at the version from npm (its mise.toml), which + # release.yml publishes from the same release, at the same time as this. + - name: Wait for the version's plx-ci on npm + if: ${{ github.event_name == 'release' }} + env: + VERSION: ${{ github.event.release.tag_name }} + run: | + for _ in $(seq 1 60); do + npm view "@plexus-ms/cli-ci@$VERSION" version >/dev/null 2>&1 && exit 0 + sleep 30 + done + echo "@plexus-ms/cli-ci@$VERSION is not on npm after half an hour" >&2 + exit 1 - name: Which tag id: tag env: @@ -54,7 +68,7 @@ jobs: labels: | org.opencontainers.image.source=https://github.com/${{ github.repository }} org.opencontainers.image.revision=${{ github.sha }} - org.opencontainers.image.description=GitHub Actions runner for the container slots of actions_runners + org.opencontainers.image.description=The environment a CI job runs in, on the slots of actions_runners and on plx-ci's instances org.opencontainers.image.licenses=GPL-3.0-or-later - uses: actions/attest-build-provenance@v4 with: From 9a854e044e5d6cf814f55383d9bae2dac1e897ae Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:38:37 +0100 Subject: [PATCH 032/194] test(repo-turbo): the question postgres, answered and not, and a test of depends = lint Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/repoTurbo.test.ts | 68 +++++++++++++++++++++++++++--- 1 file changed, 61 insertions(+), 7 deletions(-) diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index 5994ffd7..9140a676 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -1,5 +1,8 @@ import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; import { test } from 'node:test'; +import { templatesRoot } from './templatesRoot.ts'; import { generatedFrom, pathsOf, renderBundled, textOf } from './testing/bundled.ts'; /** The tools a `mise.toml` pins, by key, in order. */ @@ -66,6 +69,7 @@ test('the answers of a plain app repo are the questions’ defaults', async () = ci_registry: 'ghcr', ci_overlay: 'none', display_versions: false, + postgres: '', }); }); @@ -266,13 +270,58 @@ test('the platform is mise’s, in the env of no task of the root and in the glo assert.doesNotMatch(textOf(result, 'turbo.json'), /PLX_PLATFORM|globalEnv|globalPassThroughEnv/); }); -test('the PostgreSQL major is an input of test and e2e, and no passthrough variable changes what is tested', async () => { - const result = await render(); - const tasks = turboOf(result); - const major = /^PLX_POSTGRES_MAJOR = "(\d+)"$/m.exec(textOf(result, 'mise.toml')); - assert.ok(major, 'one declaration of the major, in mise’s env'); - for (const task of ['test', 'e2e']) assert.ok(tasks[task]?.env?.includes('PLX_POSTGRES_MAJOR'), task); - for (const task of ['build', 'check']) assert.ok(!tasks[task]?.env?.includes('PLX_POSTGRES_MAJOR'), task); +test('no PostgreSQL is asked for unanswered: no pin, no variable, nothing declared by test and e2e', async () => { + for (const answers of SHAPES) { + const result = await render(answers); + assert.doesNotMatch(textOf(result, 'mise.toml'), /conda|postgres/i); + assert.doesNotMatch(textOf(result, 'turbo.json'), /POSTGRES/); + const tasks = turboOf(result); + for (const task of ['test', 'e2e']) assert.equal(tasks[task]?.env, undefined, task); + } +}); + +test('answered, the version is pinned, its major is a variable of mise, and test and e2e declare it', async () => { + for (const [postgres, major] of [ + ['18.6', '18'], + ['17.12', '17'], + ] as const) + for (const answers of SHAPES) { + const result = await render({ ...answers, postgres }); + assert.deepEqual(result.errors, []); + const mise = textOf(result, 'mise.toml'); + assert.deepEqual(toolsOf(mise).slice(0, 3), ['node', 'hk', '"conda:postgresql"']); + assert.match(mise, new RegExp(`^"conda:postgresql" = "${postgres.replace('.', '\\.')}"$`, 'm')); + assert.match(mise, new RegExp(`^PLX_POSTGRES_MAJOR = "${major}"$`, 'm')); + const tasks = turboOf(result); + for (const task of ['test', 'e2e']) assert.deepEqual(tasks[task]?.env, ['PLX_POSTGRES_MAJOR'], task); + for (const task of ['build', 'check', 'dev']) assert.equal(tasks[task]?.env, undefined, task); + } +}); + +test('the major is derived from the answer and asked of no one', async () => { + const result = await render({ postgres: '18.6' }); + assert.equal(result.answers.postgres, '18.6'); + assert.deepEqual( + Object.keys(result.answers).filter((key) => /postgres/i.test(key)), + ['postgres'], + ); + const questions = readFileSync(join(templatesRoot(), 'repo-turbo', 'template.yml'), 'utf8'); + assert.doesNotMatch(questions, /postgres_major/i); +}); + +test('an answer is an exact version, major and minor, or empty', async () => { + for (const postgres of ['', '18.6', '17.12', '9.6']) + assert.deepEqual((await render({ postgres })).errors, [], postgres); + for (const postgres of ['18', '18.6.1', 'v18.6', '18.x', '18.', '.6', ' 18.6', '18.6\n', 'latest', '18-6']) { + const { errors } = await render({ postgres }); + assert.equal(errors.length, 1, JSON.stringify(postgres)); + assert.equal(errors[0]?.question, 'postgres', JSON.stringify(postgres)); + assert.match(errors[0]?.message ?? '', /An exact version, major and minor, as in 18\.6, or empty/); + } +}); + +test('no passthrough variable changes what is tested', async () => { + const tasks = turboOf(await render({ postgres: '18.6' })); for (const task of ['test', 'e2e']) for (const name of tasks[task]?.passThroughEnv ?? []) assert.doesNotMatch(name, /DATABASE|URL|E2E_|POSTGRES/, `${task} passes ${name} through`); @@ -285,6 +334,11 @@ test('pre-commit fixes lint on the staged files, then checks; pre-push tests', a assert.match(commit, /fix = "mise :lint --write \{\{ files \}\}"/); assert.ok(commit.indexOf('["check"]') > commit.indexOf('["lint"]'), 'check follows lint'); assert.match(commit, /\["check"\] \{[^}]*mise :check/); + assert.match( + commit, + /\["check"\] \{\s*depends = "lint"/, + 'check waits for the fixing lint, which hk would run beside it', + ); const push = hook('pre-push'); assert.match(push, /mise :test/); assert.doesNotMatch(push, /mise :check/); From 15ece71678d6904750f9f848b709939000ee3fc5 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:39:16 +0100 Subject: [PATCH 033/194] test(repo-turbo): a comment on a line of its own in turbo.json is read Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/repoTurbo.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index 9140a676..bb593a86 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -192,7 +192,8 @@ const tasksOf = (mise: string): string[] => [...mise.matchAll(/^\[tasks\.([\w-]+ /** The tasks of a rendered `turbo.json`. */ const turboOf = (result: Awaited>) => - JSON.parse(textOf(result, 'turbo.json')).tasks as Record< + // Turbo reads comments in turbo.json, on lines of their own here. + JSON.parse(textOf(result, 'turbo.json').replace(/^\s*\/\/.*$/gm, '')).tasks as Record< string, { dependsOn?: string[]; inputs?: string[]; env?: string[]; passThroughEnv?: string[]; cache?: boolean } >; From a6d50e43c0971caed3ba163f043bd5c702eb217c Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:39:30 +0100 Subject: [PATCH 034/194] repo-turbo: the question postgres pins the binary and declares its major; the comments say what is true Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/repoTurbo.test.ts | 2 +- templates/repo-turbo/files/mise.toml.jinja | 15 ++++++++++----- templates/repo-turbo/files/turbo.json.jinja | 5 +++++ templates/repo-turbo/template.yml | 9 +++++++++ 4 files changed, 25 insertions(+), 6 deletions(-) diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index bb593a86..5ecfa1fd 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -290,7 +290,7 @@ test('answered, the version is pinned, its major is a variable of mise, and test const result = await render({ ...answers, postgres }); assert.deepEqual(result.errors, []); const mise = textOf(result, 'mise.toml'); - assert.deepEqual(toolsOf(mise).slice(0, 3), ['node', 'hk', '"conda:postgresql"']); + assert.equal(toolsOf(mise).at(-1), '"conda:postgresql"'); assert.match(mise, new RegExp(`^"conda:postgresql" = "${postgres.replace('.', '\\.')}"$`, 'm')); assert.match(mise, new RegExp(`^PLX_POSTGRES_MAJOR = "${major}"$`, 'm')); const tasks = turboOf(result); diff --git a/templates/repo-turbo/files/mise.toml.jinja b/templates/repo-turbo/files/mise.toml.jinja index 3a8ff8c8..e19c8027 100644 --- a/templates/repo-turbo/files/mise.toml.jinja +++ b/templates/repo-turbo/files/mise.toml.jinja @@ -41,6 +41,10 @@ hk = "latest" {%- if not publishes_packages %} "npm:@plexus-ms/cli-ci" = { version = "0.133.0", allow_low_downloads = true } {%- endif %} +{%- if postgres %} +# The database of test and e2e: a real server from a binary, never a container or an emulation. +"conda:postgresql" = "{{ postgres }}" +{%- endif %} [settings] # Not a version source: it lets config_roots match a project without a mise config of its own, @@ -53,11 +57,12 @@ postinstall = "if command -v hk >/dev/null; then hk install --mise; fi && npx co [env] _.path = ["{% raw %}{{config_root}}{% endraw %}/node_modules/.bin"] -# The two values below are read by Turbo, which hashes them where a turbo.json declares them: the platform -# by an app's build, the PostgreSQL major by test and e2e. Neither belongs to the root's env or globalEnv, -# which would move the hash of every task. +# Turbo hashes these where a turbo.json declares them: the platform on an app's build only, and never in the +# root's env or globalEnv, which would move the hash of every task; the major in the root's env of test and e2e. PLX_PLATFORM = "{% raw %}{{ os() }}-{{ arch() }}{% endraw %}" -PLX_POSTGRES_MAJOR = "18" +{%- if postgres %} +PLX_POSTGRES_MAJOR = "{{ postgres.split('.')[0] }}" +{%- endif %} {% if not publishes_packages -%} [tasks.promote] @@ -116,7 +121,7 @@ turbo run test ${dir:+--filter="{./$dir}..."} [tasks.e2e] depends = ["install"] -description = "Run the suites that need the built app, building what they need first; it neither checks nor tests" +description = "Run the end-to-end suites, after the workspace packages they depend on are built; it neither checks nor tests" {{ name_arg("e2e") }} # A name selects the project and the projects that depend on it, since a suite is a package that depends on its app. run = ''' diff --git a/templates/repo-turbo/files/turbo.json.jinja b/templates/repo-turbo/files/turbo.json.jinja index c530d139..d6472752 100644 --- a/templates/repo-turbo/files/turbo.json.jinja +++ b/templates/repo-turbo/files/turbo.json.jinja @@ -22,13 +22,18 @@ "test": { "dependsOn": ["^build"], "inputs": ["$TURBO_DEFAULT$", "!**/{README,AGENTS,PLEXUS}.md", "!docs/**"], + {%- if postgres %} "env": ["PLX_POSTGRES_MAJOR"], + {%- endif %} + // CI is passed through, never hashed: a pass on a developer's machine counts in CI, so no test may change what it tests by CI. "passThroughEnv": ["CI"] }, "e2e": { "dependsOn": ["^build"], "inputs": ["$TURBO_DEFAULT$", "!**/{README,AGENTS,PLEXUS}.md", "!docs/**"], + {%- if postgres %} "env": ["PLX_POSTGRES_MAJOR"], + {%- endif %} "passThroughEnv": ["CI", "PLAYWRIGHT_BROWSERS_PATH"] }, "dev": { diff --git a/templates/repo-turbo/template.yml b/templates/repo-turbo/template.yml index f33158db..165737ae 100644 --- a/templates/repo-turbo/template.yml +++ b/templates/repo-turbo/template.yml @@ -76,6 +76,15 @@ questions: validator: "{% if major < 1 %}A major, 1 or higher{% endif %}" when: "{{ display_versions and not publishes_packages }}" + postgres: + type: str + help: "The PostgreSQL the repo's tests run against, as an exact version with major and minor, as in 18.6 (empty: none): mise installs that binary from conda-forge, and its major is an input of test and e2e" + default: "" + # An exact version as string tests, since the engine has no regex: two parts, both digits. + validator: >- + {% if postgres %}{% set parts = postgres.split('.') %}{% if parts | length != 2 or not parts[0].isdigit() or not + parts[1].isdigit() %}An exact version, major and minor, as in 18.6, or empty{% endif %}{% endif %} + 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 e0c6ebcddafe3d4d7ec2609e2c3ef39593a08f9b Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:44:19 +0100 Subject: [PATCH 035/194] tests of repo-turbo: scoping of check and test for the right reason, the hook order, a fresh clone, the postgres answer; a verify task that waits for plx doctor instead of two deviations Co-Authored-By: Claude Fable 5.2 --- newborns/app-nextjs.test.ts | 4 +- newborns/helpers.ts | 29 +-- newborns/repo-turbo.test.ts | 246 +++++++++++++++++----- packages/dev/src/ship.integration.test.ts | 11 +- packages/lib/src/newSite.test.ts | 16 +- packages/lib/src/testing/shapes.ts | 9 + packages/lib/src/updatesMove.test.ts | 9 +- 7 files changed, 230 insertions(+), 94 deletions(-) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index faef05f2..6537f21b 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -9,7 +9,7 @@ import assert from 'node:assert/strict'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { after, before, test } from 'node:test'; -import { born, close, deviating, open, pass, plxNew, sh, tryRun } from './helpers.ts'; +import { awaitingDoctor, born, close, open, pass, plxNew, sh, tryRun } from './helpers.ts'; let here = ''; let repo = ''; @@ -17,7 +17,7 @@ const PROFILES = ['stateless', 'stateful']; before(async () => { here = await open('app-nextjs'); - repo = deviating(await born(join(here, 'acme'), ['repo-turbo', 'updates'], { tenant: 'acme' })); + repo = awaitingDoctor(await born(join(here, 'acme'), ['repo-turbo', 'updates'], { tenant: 'acme' })); for (const profile of PROFILES) await born(join(repo, 'apps', profile), ['app-nextjs'], { name: `@acme/${profile}`, profile }); }); diff --git a/newborns/helpers.ts b/newborns/helpers.ts index 3aae95f7..98a844f2 100644 --- a/newborns/helpers.ts +++ b/newborns/helpers.ts @@ -1,16 +1,16 @@ // What the newborn tests share. A newborn is a repo or an app that `plx new` // creates from the templates the built `plx` bundles, birth commands included, // so that each test runs what a tenant runs on the first day: the tools are -// installed from the network, and `mise run verify` is the newborn's own. +// installed from the network, and the newborn's own verbs are run. // // What is tested with what. Every `@plexus-ms` package a newborn installs // (the `plx` and `plx-ci` its `mise.toml` pins, and the packages those need) is // this workspace's own build, served by a registry of its own (registry.ts) to // the installers that read the scope's registry setting; the libraries of the // scope that are not built here, and every other package, come from npm. So the -// newborn's `plx doctor`, in its own `verify`, is the plx being cut, and a -// version whose packages are not on npm yet is tested all the same; `verify` -// below asserts it of every newborn, whatever the machine has installed. `ship` +// newborn's `plx doctor`, in its own `check` (`verify` where a template still has +// one), is the plx being cut, and a version whose packages are not on npm yet is +// tested all the same; `pass` below asserts it of every newborn, whatever the machine has installed. `ship` // stamps the manifests of the packages and the pins of the templates with one // version in one commit; `open` fails if they differ. // @@ -25,7 +25,7 @@ // install, byte for byte the build (`assertBuilt`). The pnpm cache directory // is scratch for the commands this file starts (`plx new`'s birth commands, a // lock refresh, `mise run`), through the environment. Not scratch: the pnpm -// that turbo starts inside a newborn's `verify`, which turbo's strict +// that turbo starts inside a newborn's verbs, which turbo's strict // environment keeps the variable from, and which writes npm's own metadata of // the newborn's dependencies to the user's pnpm cache; the user's pnpm store, // which is content-addressed, and corepack's cache. None of them receives a @@ -37,6 +37,7 @@ import { execFileSync, spawn } from 'node:child_process'; import { createHash } from 'node:crypto'; import { + appendFileSync, copyFileSync, existsSync, lstatSync, @@ -52,6 +53,7 @@ import { } from 'node:fs'; import { homedir, tmpdir } from 'node:os'; import { dirname, join, sep } from 'node:path'; +import { WAITING_FOR_DOCTOR } from '../packages/lib/src/testing/shapes.ts'; import { PUBLISHED, pack } from './pack.ts'; import { type Registry, startRegistry } from './registry.ts'; @@ -329,20 +331,11 @@ export async function assertBuilt(dir: string): Promise { } /** - * The verbs of the contract are still `dev`, `build` and `verify` in `plx doctor`, which the issue of the doctor - * brings to the five (PLX-Repo/Verbs and PLX-Repo/SubVerbs name the verbs it checks); until then the newborn - * states the two as deviations, the way a repo that does not meet a requirement does, and `mise check` runs on. + * `plx doctor` still wants a root task `verify` (PLX-Repo/Verbs and PLX-Repo/SubVerbs), which repo-turbo has no + * more. The newborn gets a task of that name and meets exactly those two findings, and nothing else is silenced. */ -export function deviating(dir: string): string { - const marker = join(dir, 'PLEXUS.md'); - const text = readFileSync(marker, 'utf8'); - const reasons = ['PLX-Repo/Verbs', 'PLX-Repo/SubVerbs'].map( - (name) => `- \`${name}\`: doctor still expects \`verify\`.\n`, - ); - writeFileSync( - marker, - `${text.replace(/^---\n/, '---\ndeviations: [PLX-Repo/Verbs, PLX-Repo/SubVerbs]\n')}${reasons.join('')}`, - ); +export function awaitingDoctor(dir: string): string { + appendFileSync(join(dir, 'mise.toml'), WAITING_FOR_DOCTOR.task); return dir; } diff --git a/newborns/repo-turbo.test.ts b/newborns/repo-turbo.test.ts index 0085a207..0e4f6227 100644 --- a/newborns/repo-turbo.test.ts +++ b/newborns/repo-turbo.test.ts @@ -1,22 +1,26 @@ // A newborn repo of the Turborepo template, born as a repo is with updates -// beside its template, passes its own five verbs (`check`, `test`, `build`, -// `e2e`, and `dev` where it has one), in each shape that changes what is -// generated: an app repo, a package repo, each also with the tenant's private -// packages, and an app repo also with display versions. A verb scopes to an app -// or a package by name, with what it depends on, and refuses an unknown one. -// Editing a test file moves the hash of `test` and leaves the hash of `build`. -// A package repo also has what a release needs: a workspace package with a -// pending changeset passes `test`, scoped to it by name, and `changeset -// version` takes the changeset in. Created by `plx new`; it needs the network -// (`mise install`, `pnpm add`). +// beside its template, passes its own four verdicts (`check`, `test`, `build`, +// `e2e`) in each shape that changes what is generated: an app repo, a package +// repo, each also with the tenant's private packages, an app repo also with +// display versions, and one repo with the answer `postgres`, which installs +// the binary and shows its version. `check`, `build` and `test` scope to an +// app or a package by name with what it depends on, `e2e` with what depends on +// it, and each refuses an unknown name. Editing a test file moves the hash of +// `test` and leaves the hash of `build`; the answer's major moves `test` and +// `e2e` and nothing else. The pre-commit hook fixes a format error and accepts +// the commit, and refuses it without `depends = "lint"`. `mise e2e` works first +// in a fresh clone. A package repo also has what a release needs: a workspace +// package with a pending changeset passes `test`, scoped to it by name, and +// `changeset version` takes the changeset in. Created by `plx new`; it needs +// the network (`mise install`, `pnpm add`). // // 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 } from 'node:fs'; +import { readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { after, before, describe, test } from 'node:test'; -import { born, close, deviating, mise, open, pass, put, sh, tryRun } from './helpers.ts'; +import { awaitingDoctor, born, close, mise, open, pass, put, sh, tryRun } from './helpers.ts'; let here = ''; before(async () => { @@ -24,8 +28,12 @@ before(async () => { }); after(close); -const newborn = async (name: string, answers: Record = {}) => - deviating(await born(join(here, name), ['repo-turbo', 'updates'], { tenant: 'acme', ...answers })); +/** A newborn, which has no `verify` task: a `verify` is added as `plx doctor` still wants one. */ +async function newborn(name: string, answers: Record = {}): Promise { + const dir = await born(join(here, name), ['repo-turbo', 'updates'], { tenant: 'acme', ...answers }); + assert.doesNotMatch(read(dir, 'mise.toml'), /^\[tasks\.verify\]/m, 'a repo is born without verify'); + return awaitingDoctor(dir); +} const read = (dir: string, file: string) => readFileSync(join(dir, file), 'utf8'); @@ -34,25 +42,41 @@ const VERDICTS = ['check', 'test', 'build', 'e2e']; async function passesItsVerbs(dir: string, name: string): Promise { for (const verb of VERDICTS) await pass(dir, name, verb); - const gone = await mise(dir, 'verify'); - assert.equal(gone.ok, false, 'no verify task is left'); } -/** The hashes of the tasks `turbo run ` would run for one package, from a dry run. */ +/** The hashes of the tasks `turbo run ` would run for one package and what it needs, by task id, from a dry run. */ async function hashes(dir: string, pkg: string, tasks: string[]): Promise> { - const ran = await tryRun( - 'mise', - ['exec', '--', 'turbo', 'run', ...tasks, `--filter=${pkg}`, '--only', '--dry=json'], - dir, - ); + const ran = await tryRun('mise', ['exec', '--', 'turbo', 'run', ...tasks, `--filter=${pkg}`, '--dry=json'], dir); assert.ok(ran.ok, ran.output); const dry = JSON.parse(ran.output.slice(ran.output.indexOf('{'))); - return Object.fromEntries(dry.tasks.map((t: { task: string; hash: string }) => [t.task, t.hash])); + return Object.fromEntries(dry.tasks.map((t: { taskId: string; hash: string }) => [t.taskId, t.hash])); } /** The lockfile predates workspace packages added to a newborn; a frozen install (CI=true) would refuse it. */ const relock = (dir: string) => sh('mise', ['exec', '--', 'pnpm', 'install', '--lockfile-only'], dir); +/** git with an identity and no signing, as a newborn has neither. */ +const git = (dir: string, ...args: string[]) => + tryRun( + 'git', + ['-c', 'commit.gpgsign=false', '-c', 'user.name=newborn', '-c', 'user.email=newborn@example.invalid', ...args], + dir, + ); + +/** Projects of a newborn: each prints what it did, so that a run shows which ones it ran. `needs` are workspace dependencies. */ +function projects(dir: string, specs: Record): void { + for (const [name, { verbs, needs = [] }] of Object.entries(specs)) + put(dir, { + [`packages/${name}/package.json`]: { + name, + version: '0.0.0', + private: true, + scripts: Object.fromEntries(verbs.map((verb) => [verb, `echo ${verb}-ran packages/${name}`])), + dependencies: Object.fromEntries(needs.map((need) => [need, 'workspace:*'])), + }, + }); +} + describe('an app repo', () => { let dir = ''; before(async () => { @@ -65,61 +89,169 @@ describe('an app repo', () => { assert.doesNotMatch(read(dir, 'PLEXUS.md'), /^major:/m); }); - test('scopes a verb to an app or a package by name: build with what it depends on, e2e with what depends on it', async () => { - put(dir, { - 'apps/demo-app/package.json': { - name: 'demo-app', - version: '0.0.0', - private: true, - scripts: { build: 'echo built apps/demo-app', e2e: 'echo e2e apps/demo-app' }, - dependencies: { 'demo-lib': 'workspace:*' }, - }, - 'packages/demo-lib/package.json': { - name: 'demo-lib', - version: '0.0.0', - private: true, - scripts: { build: 'echo built packages/demo-lib' }, - }, + 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); - const app = await mise(dir, 'build', 'demo-app'); - assert.ok(app.ok, app.output); - assert.match(app.output, /built apps\/demo-app/); - assert.match(app.output, /built packages\/demo-lib/, 'the dependency is built with the app'); - const lib = await mise(dir, 'build', 'demo-lib'); - assert.ok(lib.ok, lib.output); - assert.match(lib.output, /built packages\/demo-lib/); - assert.doesNotMatch(lib.output, /built apps\/demo-app/, 'never a dependent'); + 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 apps\/demo-app/, 'the suite of a dependent runs'); - for (const verb of ['build', 'check', 'test', 'e2e']) - assert.equal((await mise(dir, verb, 'demo-none')).ok, false, `${verb} refuses an unknown name`); + 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'); + for (const verb of VERDICTS) { + 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('editing a test file moves the hash of test and leaves the hash of build', async () => { put(dir, { - 'apps/hashed/package.json': { + 'packages/hashed/package.json': { name: 'hashed', version: '0.0.0', private: true, scripts: { build: 'echo built', check: 'echo checked', test: 'echo tested' }, }, - 'apps/hashed/src/index.ts': 'export const answer = 42;\n', - 'apps/hashed/src/index.test.ts': 'export const first = 1;\n', + 'packages/hashed/src/index.ts': 'export const answer = 42;\n', + 'packages/hashed/src/index.test.ts': 'export const first = 1;\n', }); await relock(dir); const before = await hashes(dir, 'hashed', ['build', 'test']); - put(dir, { 'apps/hashed/src/index.test.ts': 'export const first = 2;\n' }); + put(dir, { 'packages/hashed/src/index.test.ts': 'export const first = 2;\n' }); const after = await hashes(dir, 'hashed', ['build', 'test']); - assert.notEqual(after.test, before.test, 'the test file is an input of test'); - assert.equal(after.build, before.build, 'and of no build'); - put(dir, { 'apps/hashed/src/index.ts': 'export const answer = 43;\n' }); + assert.notEqual(after['hashed#test'], before['hashed#test'], 'the test file is an input of test'); + assert.equal(after['hashed#build'], before['hashed#build'], 'and of no build'); + put(dir, { 'packages/hashed/src/index.ts': 'export const answer = 43;\n' }); const edited = await hashes(dir, 'hashed', ['build', 'test']); - assert.notEqual(edited.build, after.build, 'a source file still moves the build'); + assert.notEqual(edited['hashed#build'], after['hashed#build'], 'a source file still moves the build'); + }); +}); + +test('mise e2e works first in a fresh clone: it installs what it needs', async () => { + const dir = await newborn('fresh'); + projects(dir, { suite: { verbs: ['e2e'] } }); + await relock(dir); + await git(dir, 'add', '-A'); + const committed = await git(dir, 'commit', '--no-verify', '-q', '-m', 'born'); + assert.ok(committed.ok, committed.output); + const clone = join(here, 'fresh-clone'); + const cloned = await git(here, 'clone', '-q', dir, clone); + assert.ok(cloned.ok, cloned.output); + const installed = await tryRun('sh', ['-c', 'mise trust && mise install'], clone); + assert.ok(installed.ok, installed.output); + const ran = await mise(clone, 'e2e'); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, /e2e-ran packages\/suite/); +}); + +describe('the hooks', () => { + const UNFORMATTED = 'export const a = {b: 1};\n'; + let dir = ''; + before(async () => { + dir = await newborn('hooks'); + projects(dir, { fmt: { verbs: ['check', 'test'] } }); + await relock(dir); + await git(dir, 'add', '-A'); + const first = await git(dir, 'commit', '-q', '-m', 'born'); + assert.ok(first.ok, first.output); + }); + + test('a commit with a fixable format error is fixed and accepted; without depends = lint it is refused', async () => { + put(dir, { 'packages/fmt/src/one.ts': UNFORMATTED }); + await git(dir, 'add', '-A'); + const fixed = await git(dir, 'commit', '-m', 'one'); + assert.ok(fixed.ok, fixed.output); + assert.notEqual(read(dir, 'packages/fmt/src/one.ts'), UNFORMATTED, 'the lint fixed the file'); + assert.equal((await git(dir, 'status', '--porcelain')).output.trim(), '', 'and the fix is in the commit'); + + const hook = read(dir, 'hk.pkl'); + assert.match(hook, /^ *depends = "lint"\n/m); + writeFileSync(join(dir, 'hk.pkl'), hook.replace(/^ *depends = "lint"\n/m, '')); + await git(dir, 'add', '-A'); + const unhooked = await git(dir, 'commit', '--no-verify', '-q', '-m', 'without depends'); + assert.ok(unhooked.ok, unhooked.output); + put(dir, { 'packages/fmt/src/two.ts': UNFORMATTED }); + await git(dir, 'add', '-A'); + const refused = await git(dir, 'commit', '-m', 'two'); + assert.equal(refused.ok, false, 'check runs beside the fix and sees the unformatted file'); }); }); +describe('a repo that answers postgres', () => { + let dir = ''; + before(async () => { + dir = await newborn('postgres', { postgres: '18.6' }); + projects(dir, { 'pg-lib': { verbs: ['build'] } }); + // What a test of the app sees of the database: the major, which only a variable declared in env reaches. + put(dir, { + 'packages/pg-app/package.json': { + name: 'pg-app', + version: '0.0.0', + private: true, + scripts: { + build: 'echo built', + check: 'echo checked', + test: 'echo major=$PLX_POSTGRES_MAJOR', + e2e: 'echo e2e', + }, + dependencies: { 'pg-lib': 'workspace:*' }, + }, + }); + await relock(dir); + }); + + test('installs the binary at that version, and the test of an app sees the major', async () => { + appendTask(dir); + const version = await mise(dir, 'postgres-version'); + assert.ok(version.ok, version.output); + assert.match(version.output, /postgres \(PostgreSQL\) 18\.6\b/); + const tested = await mise(dir, 'test'); + assert.ok(tested.ok, tested.output); + assert.match(tested.output, /major=18/); + await passesItsVerbs(dir, 'postgres'); + }); + + test('changing the major moves the hashes of test and e2e and of nothing else', async () => { + const tasks = ['build', 'check', 'test', 'e2e']; + const before = await hashes(dir, 'pg-app', tasks); + // What plx apply writes to mise.toml for the answer 17.12; the binary is not installed for a hash. + writeFileSync( + join(dir, 'mise.toml'), + read(dir, 'mise.toml').replace('PLX_POSTGRES_MAJOR = "18"', 'PLX_POSTGRES_MAJOR = "17"'), + ); + const after = await hashes(dir, 'pg-app', tasks); + const moved = Object.keys(after).filter((id) => after[id] !== before[id]); + assert.deepEqual(moved.sort(), ['pg-app#e2e', 'pg-app#test']); + }); +}); + +/** A root task that runs the database server's binary, as a test of an app would. */ +function appendTask(dir: string): void { + writeFileSync( + join(dir, 'mise.toml'), + `${read(dir, 'mise.toml')}\n[tasks.postgres-version]\ndescription = "The version of the pinned binary"\nrun = "postgres --version"\n`, + ); +} + test('a private app repo with reviewers passes its own verbs', async () => { await passesItsVerbs( await newborn('private-app', { private_packages_scope: '@acme', pr_reviewers: 'reviewer-a,reviewer-b' }), diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index 1a94c63e..d99b70e8 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -1886,6 +1886,11 @@ for (const [template, answers, edits] of [ const onPr = onVersion(name, CURRENT, '.github/workflows/on_pr.yml'); assert.doesNotMatch(onPr, /^ {2}changeset:$/m, "no job writes the bot's changesets without updates"); assert.match(onPr, /types: \[opened, synchronize\]/, 'the local edit merged'); + assert.match( + onVersion(name, CURRENT, 'mise.toml'), + /^\[tasks\.mine\]\nrun = "echo mine"$/m, + 'and the local task', + ); } const { human, applied } = await addUpdates(name, template); @@ -1901,11 +1906,11 @@ for (const [template, answers, edits] of [ executable: false, text: (workflow?.text ?? '').replace(`templates/${template}: edit`, 'templates/updates: edit'), }; - // repo-turbo has changed since the move (its verbs, its hooks), so what the update took in of it is no longer the - // repo as it was: the files the move concerns are what is compared. repo-operations is still as it was. + // repo-turbo has changed since the move (its verbs, its hooks, a question more in the marker), so what the update + // took in of it is no longer the repo as it was: the files the move concerns are what is compared. repo-operations is still as it was. const concerned = (files: typeof end) => template === 'repo-turbo' - ? Object.fromEntries(Object.entries(files).filter(([path]) => path === 'PLEXUS.md' || MOVED.includes(path))) + ? Object.fromEntries(Object.entries(files).filter(([path]) => MOVED.includes(path))) : files; assert.deepEqual(concerned(end), concerned(expected)); }); diff --git a/packages/lib/src/newSite.test.ts b/packages/lib/src/newSite.test.ts index 29c5b9b0..bce5c9e3 100644 --- a/packages/lib/src/newSite.test.ts +++ b/packages/lib/src/newSite.test.ts @@ -3,12 +3,13 @@ // through the Context's injected Io, which here records them and runs nothing; // git, which the verb reads the enclosing repo with, goes to the real one. import assert from 'node:assert/strict'; -import { chmodSync, existsSync, mkdirSync } from 'node:fs'; +import { appendFileSync, chmodSync, existsSync, mkdirSync } from 'node:fs'; import { createRequire } from 'node:module'; import { join } from 'node:path'; import { PassThrough } from 'node:stream'; import { after, test } from 'node:test'; import { apply, Context, diagnose, examine, newSite, realIo, templatesRoot } from './index.ts'; +import { WAITING_FOR_DOCTOR } from './testing/shapes.ts'; import { git, quietContext, repoWith, scratchDir, templatesAt, text, write } from './testing/siteRepo.ts'; const scratch = scratchDir('new'); @@ -389,22 +390,15 @@ test('a repo from repo-turbo with updates beside it and an app from app-nextjs i // The doctor reads what git tracks, and lists the tasks of a mise.toml that `mise trust` (faked above) would have trusted. process.env.MISE_TRUSTED_CONFIG_PATHS = target; try { + // The doctor still wants a `verify` task, which repo-turbo no longer has: it finds that and nothing else. + appendFileSync(join(target, 'mise.toml'), WAITING_FOR_DOCTOR.task); git(target, 'add', '-A'); const { facts } = await examine(new Context({}, realIo()), target, bundled.version); const report = diagnose(facts); - // The doctor still wants a `verify` task of the repo, which repo-turbo no longer has: the one finding that waits - // for the doctor to follow the five verbs, and no other is let through. - const WAITING = 'no root mise task `verify`'; assert.deepEqual( - report.units.flatMap((u) => - u.findings.filter((f) => f.problem !== WAITING).map((f) => `${u.path}: ${f.problem}`), - ), + report.units.flatMap((u) => u.findings.map((f) => `${u.path}: ${f.problem}`)), [], ); - assert.deepEqual( - report.units.flatMap((u) => u.findings.filter((f) => f.problem === WAITING).map((f) => u.path)), - ['.', '.'], - ); assert.equal(report.units.length, 2); } finally { delete process.env.MISE_TRUSTED_CONFIG_PATHS; diff --git a/packages/lib/src/testing/shapes.ts b/packages/lib/src/testing/shapes.ts index 2dd8d264..bc539c78 100644 --- a/packages/lib/src/testing/shapes.ts +++ b/packages/lib/src/testing/shapes.ts @@ -23,6 +23,7 @@ export const CHOICES: Readonly major: [1, 3], pr_reviewers: ['', 'alice', 'alice, bob'], update_max_age: [7, 0], + postgres: ['', '18.6'], }, 'repo-operations': { tenant: ['acme'], @@ -37,6 +38,14 @@ export const CHOICES: Readonly }, }; +/** + * What `plx doctor` finds of a repo-turbo repo until it knows the five verbs: it wants a root task `verify` + * (PLX-Repo/Verbs and PLX-Repo/SubVerbs), twice. A repo that appends this task meets it and nothing else is silenced. + */ +export const WAITING_FOR_DOCTOR = { + task: '\n[tasks.verify]\ndescription = "Waits for plx doctor, which still wants this task"\nrun = "true"\n', +} as const; + /** Every combination of the choices, one answers object each. */ export function combinations(choices: Choices): Answers[] { return Object.entries(choices).reduce( diff --git a/packages/lib/src/updatesMove.test.ts b/packages/lib/src/updatesMove.test.ts index 3bfac47a..1860aa76 100644 --- a/packages/lib/src/updatesMove.test.ts +++ b/packages/lib/src/updatesMove.test.ts @@ -6,9 +6,12 @@ // one that names the template a file is generated from, in plx-update.yml, // which names `updates` now. // -// What it proves holds while the templates are as the move left them, but for -// the version pins, which ship stamps: a later change to one of them makes it -// fail, and the change that does ends this test and the archive with it. +// What it proves holds while a template is as the move left it, but for the +// version pins, which ship stamps: a later change to it makes the test fail, +// and the change that does ends the test for that template. repo-turbo has +// changed (its verbs, its hooks, its PostgreSQL question), so only +// repo-operations is left; the archive stays for it and for the update tests +// of packages/dev, which merge from it. import assert from 'node:assert/strict'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; From 3d7134e1303f90b8f8a8daca9a6a10e806e1c487 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:48:54 +0100 Subject: [PATCH 036/194] test(cli-ci): the runner owns its log's directory before the container mounts it Without the line, Docker creates /opt/runner/_diag as root, the runner cannot write its Worker log, and the no-job layer deletes an instance whose job is running. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/core/userData.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/packages/cli-ci/src/core/userData.test.ts b/packages/cli-ci/src/core/userData.test.ts index 1c421a14..7e267d1c 100644 --- a/packages/cli-ci/src/core/userData.test.ts +++ b/packages/cli-ci/src/core/userData.test.ts @@ -56,6 +56,14 @@ test('the runner’s log stays on the host, where the no-job layer and a kept in assert.match(RUNNER_USER_DATA, /ls \/opt\/runner\/_diag\/Worker_\*\.log/); }); +test('the log’s directory is the runner’s before the container mounts it, or the no-job layer deletes a running job', () => { + // Docker would create a missing mount source as root, where the image's + // runner (1001) cannot write its Worker log. + const owned = RUNNER_USER_DATA.indexOf('\n - install -d -o 1001 -g 1001 /opt/runner/_diag\n'); + const runner = RUNNER_USER_DATA.indexOf('systemctl start plexus-ci-runner.service'); + assert.ok(owned > 0 && owned < runner); +}); + test('the instance gives the job no Docker daemon: no runner on the host, no builder, no test images', () => { assert.doesNotMatch( RUNNER_USER_DATA, From 1c2e6c659c99f11cf127acea0298f7a34f5aa4d3 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:52:09 +0100 Subject: [PATCH 037/194] BuildKit service: restart by what is on disk, build steps on a bridge (PLX-180) From the review of the pull request: - A run restarts the daemon whenever its binary, configuration or unit changed after it started (the files' change time against the unit's ExecMainStartTimestamp), not only when this run changed them, so a run that failed after replacing a file no longer leaves the old daemon running behind a run that reports nothing changed. - networkMode = "bridge": a build step gets a network namespace of its own on BuildKit's bridge, with the internet through NAT, instead of the host's. It no longer reaches the host's loopback, nor reads its traffic through a raw socket; the pulls and the push stay the daemon's. The bridge's CNI plugins come from the same release. - KillSignal=SIGHUP instead of SuccessExitStatus=1: buildkitd handles only SIGTERM and SIGINT and ends those with status 1; it dies by SIGHUP, a clean stop to systemd, so a crash that exits 1 is a failure again. - The defaults say what a build step sees, why the rootless mode is not used as BuildKit's documentation describes it, and that nothing removes the service from a host; the disk alert names a command, not a port. Co-Authored-By: Claude Opus 5.5 --- .../roles/actions_runners/defaults/main.yml | 43 ++++++++--- .../files/ci-runner-housekeeping | 2 +- .../roles/actions_runners/tasks/buildkit.yml | 74 ++++++++++++++----- 3 files changed, 87 insertions(+), 32 deletions(-) diff --git a/ansible/ci/roles/actions_runners/defaults/main.yml b/ansible/ci/roles/actions_runners/defaults/main.yml index 9e5980be..53a8a004 100644 --- a/ansible/ci/roles/actions_runners/defaults/main.yml +++ b/ansible/ci/roles/actions_runners/defaults/main.yml @@ -154,10 +154,16 @@ actions_runners_disk_alert_percent: 85 # ~/.docker/config.json through the build's session; the service holds # none. Its state is /var/lib/buildkit, bounded by BuildKit's own garbage # collection, which runs when the daemon starts and after builds; the -# hourly housekeeping leaves it alone. A change to the binary, the -# configuration or the unit restarts it, which a publish job in flight does -# not survive. Under the strategy `github` there is no runner host and so -# no service: the publish job uses the runner's Docker. +# hourly housekeeping leaves it alone. A run restarts the daemon whenever +# its binary, configuration or unit on disk changed after it started, also +# after an earlier run that failed halfway; a publish job in flight does +# not survive that. Under the strategy `github` there is no runner host and +# so no service: the publish job uses the runner's Docker. +# +# Nothing removes the service from a host once this role ran there: a host +# dropped from the group `ci`, or a tenant that switches to `github`, keeps +# it running until someone runs `systemctl disable --now ci-buildkit` and +# deletes the unit, /etc/buildkit, /var/lib/buildkit and the binaries. # # One service for every job of every repo the host serves is accepted as it # behaves, inside the one tenant the host serves (§ 1 PLX-Tenancy): @@ -166,21 +172,34 @@ actions_runners_disk_alert_percent: 85 # with the first job's secret, since the secret is not part of the cache # key; a Dockerfile never bakes a secret into a layer. # - Any job that reaches the endpoint can list and prune the whole cache. -# - A RUN step of a build runs on the host's network and reaches every -# service listening on the host's loopback. +# - A RUN step runs as root in its container with runc's default +# capabilities, raw sockets among them, so it sees all traffic of its +# network namespace. That namespace is its own, on BuildKit's bridge +# buildkit0 (BuildKit's default subnet 10.10.0.0/16, a route on the host), +# with the internet through NAT and iptables, which Docker brings: a step +# reaches neither the host's loopback nor its traffic, and reaches the +# host itself only at the bridge's address, through the host firewall's +# input rules; steps of builds running at the same time share the bridge. +# RUN --network=host is refused, since the network.host entitlement is +# not granted. The pulls and the push are the daemon's, on the host's +# network. # # buildkitd runs as root, as dockerd does; its RUN steps are containers # without privileges, since it grants no insecure entitlement such as -# security.insecure. Its rootless mode is not used: it needs RootlessKit, -# newuidmap and a subuid range on the host, and puts every RUN step on the -# host's network all the same. +# security.insecure. Its rootless mode is not used. BuildKit's +# documentation for it puts the build steps on the daemon's network and +# recommends isolating the daemon's network namespace from the host's +# through RootlessKit; the daemon would then no longer listen on the host's +# loopback, where the slots reach it. It needs RootlessKit, which the +# release does not ship, newuidmap and a subuid range on the host, and no +# one has run it on a runner host. # The release, from github.com/moby/buildkit/releases for linux-amd64, by # version and the tarball's SHA-256 (the asset's digest on the release page); # the two move together, by hand, since no update bot can rewrite the -# checksum of a download. buildkitd, buildkit-runc and buildctl go to -# /usr/local/bin; buildctl is the operator's on the host, as in -# `buildctl --addr tcp://127.0.0.1: du`. +# checksum of a download. buildkitd, buildkit-runc, the bridge's CNI +# plugins (buildkit-cni-*) and buildctl go to /usr/local/bin; buildctl is +# the operator's on the host, as in `buildctl --addr tcp://127.0.0.1:1234 du`. actions_runners_buildkit_version: v0.35.1 actions_runners_buildkit_sha256: b248c2b91698aafef11818fe8b681dc5e341581f7d5676709ff45ca1f29b0408 # The port on 127.0.0.1, which the publish job names in its remote driver. diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping b/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping index 5d23589a..c9843808 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping +++ b/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping @@ -35,6 +35,6 @@ done used=$(df --output=pcent / | tail -1 | tr -dc '0-9') echo "root file system ${used}% used" if [ "$used" -gt "$DISK_ALERT_PERCENT" ]; then - echo "above ${DISK_ALERT_PERCENT}%: look at /var/cache/ci-runner (the pnpm store), docker system df and /var/lib/buildkit (buildctl --addr tcp://127.0.0.1: du)" >&2 + echo "above ${DISK_ALERT_PERCENT}%: look at /var/cache/ci-runner (the pnpm store), docker system df, and du -sh /var/lib/buildkit against maxUsedSpace in /etc/buildkit/buildkitd.toml" >&2 exit 1 fi diff --git a/ansible/ci/roles/actions_runners/tasks/buildkit.yml b/ansible/ci/roles/actions_runners/tasks/buildkit.yml index 5be5d18f..1a044a0a 100644 --- a/ansible/ci/roles/actions_runners/tasks/buildkit.yml +++ b/ansible/ci/roles/actions_runners/tasks/buildkit.yml @@ -2,7 +2,9 @@ # The BuildKit service (defaults: actions_runners_buildkit_*): buildkitd from # BuildKit's release, its configuration in BuildKit's default place, and the # unit ci-buildkit. Started or restarted at the end, without a handler, so -# that the service answers once this file has run. +# that the service answers once this file has run, and restarted by what is +# on disk rather than by what this run changed, so that a run that failed +# halfway leaves no daemon behind its files. - name: Which buildkitd is installed ansible.builtin.command: cmd: /usr/local/bin/buildkitd --version @@ -28,19 +30,25 @@ group: root mode: "0600" - # The daemon, the runc it runs build steps with, and the client; the - # tarball's emulators and CNI plugins are left out, since the builds are - # for the host's own platform and on the host's network. - - name: Unpack buildkitd, buildkit-runc and buildctl + # The daemon, the runc it runs build steps with, the CNI plugins of its + # bridge (found on PATH by their names), and the client; the tarball's + # emulators are left out, since the builds are for the host's platform. + - name: Unpack buildkitd, buildkit-runc, the bridge's plugins and buildctl ansible.builtin.unarchive: src: "{{ tarball }}" dest: /usr/local/bin remote_src: true - include: [bin/buildkitd, bin/buildkit-runc, bin/buildctl] + include: + - bin/buildkitd + - bin/buildkit-runc + - bin/buildkit-cni-bridge + - bin/buildkit-cni-firewall + - bin/buildkit-cni-host-local + - bin/buildkit-cni-loopback + - bin/buildctl extra_opts: [--strip-components=1] owner: root group: root - register: actions_runners_buildkit_binaries when: not ansible_check_mode # the module needs the tarball, which check mode does not fetch - name: Remove the download @@ -58,8 +66,10 @@ # Both workers are named: the containerd worker would otherwise switch itself # on beside the OCI worker wherever Docker's containerd socket exists. The -# build steps' cgroups go below the unit's own (Delegate=), so that its -# MemoryMax covers them; BuildKit places each at /buildkit/. +# bridge gives each build step a network namespace of its own instead of +# the host's, BuildKit's fallback without a CNI configuration. The build +# steps' cgroups go below the unit's own (Delegate=), so that its MemoryMax +# covers them; BuildKit places each at /buildkit/. - name: Configure buildkitd ansible.builtin.copy: dest: /etc/buildkit/buildkitd.toml @@ -73,6 +83,7 @@ [worker.oci] enabled = true + networkMode = "bridge" gc = true maxUsedSpace = "{{ actions_runners_buildkit_cache_max }}" defaultCgroupParent = "system.slice/ci-buildkit.service" @@ -104,9 +115,11 @@ DelegateSubgroup=daemon MemoryMax={{ actions_runners_buildkit_memory | default('infinity', true) }} MemorySwapMax={{ 0 if actions_runners_buildkit_memory else 'infinity' }} - # buildkitd ends with status 1 on SIGTERM: a stop, not a failure, so a - # restart or a reboot marks it failed for nobody. - SuccessExitStatus=1 + # buildkitd ends with status 1 on SIGTERM and SIGINT, the signals it + # handles; it leaves SIGHUP to Go's default, death by the signal, + # which systemd counts as a clean stop. A restart or a reboot then + # marks it failed for nobody, and a crash with any status still does. + KillSignal=SIGHUP Restart=always RestartSec=5s @@ -114,14 +127,37 @@ WantedBy=multi-user.target register: actions_runners_buildkit_unit -# A dry run that would write the unit has none to look up yet. -- name: Start the BuildKit service, restarted when it changed +# The running daemon is what is on disk only if it started after the last of +# its files changed. The change time, not the modification time: tar keeps +# the release's modification times. +- name: Find the files that changed since buildkitd started + ansible.builtin.shell: + executable: /bin/bash + cmd: | + set -euo pipefail + started=$(systemctl show -P ExecMainStartTimestamp --timestamp=us+utc ci-buildkit.service) + [ -n "$started" ] || exit 0 + started=$(date -d "$started" +%s%6N) + for f in /usr/local/bin/buildkitd /usr/local/bin/buildkit-runc \ + /etc/buildkit/buildkitd.toml /etc/systemd/system/ci-buildkit.service; do + changed=$(stat -c %.6Z "$f" 2>/dev/null) || { echo "$f"; continue; } + [ "${changed/./}" -lt "$started" ] || echo "$f" + done + register: actions_runners_buildkit_newer + changed_when: false + check_mode: false + +# A dry run writes nothing, so there what this run would change stands in +# for the files; and it has no unit to look up while the unit is new. +- name: Start the BuildKit service, restarted when it is not what is on disk when: not (ansible_check_mode and actions_runners_buildkit_unit is changed) + vars: + restart: >- + {{ actions_runners_buildkit_newer.stdout | length > 0 + or (ansible_check_mode and (actions_runners_buildkit_config is changed + or actions_runners_buildkit_unit is changed)) }} ansible.builtin.systemd_service: name: ci-buildkit.service enabled: true - daemon_reload: "{{ actions_runners_buildkit_unit is changed }}" - state: >- - {{ 'restarted' if (actions_runners_buildkit_binaries is changed - or actions_runners_buildkit_config is changed - or actions_runners_buildkit_unit is changed) else 'started' }} + daemon_reload: "{{ restart | bool }}" + state: "{{ 'restarted' if restart | bool else 'started' }}" From cf8727aeff6ae3db2edda43b6448b45aa2b53805 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:03:32 +0100 Subject: [PATCH 038/194] fix(actions_runners): trust under _work alone, corepack for the runner, its download shared mise trusted every config under CI, and MISE_YES trusted and recorded any other: paranoid mode for config, in the image's mise.toml, leaves MISE_TRUSTED_CONFIG_PATHS (the job's checkout under _work) the only config that loads, refuses the rest at once, and records no trust in the state directory the slots share. corepack enable now links pnpm and yarn at build time, so that a job's own corepack enable as the runner user finds nothing to rewrite in /usr/local/bin instead of failing on the base's yarn. The pnpm a repo's packageManager names is downloaded once per host: the slots share corepack's directory, into which corepack moves each download whole. ci-mise-install is a job's mise-action in the image: mise install, then the repo's [env] into GITHUB_ENV and the PATH entries mise manages into GITHUB_PATH, without downloading mise or restoring the forge's cache into the shared directories. Co-Authored-By: Claude Fable 5.2 --- .../roles/actions_runners/defaults/main.yml | 1 + .../actions_runners/files/ci-runner-slot | 4 ++- .../files/ci-runner/Dockerfile | 30 ++++++++++++++----- .../files/ci-runner/ci-mise-install | 27 +++++++++++++++++ .../actions_runners/files/ci-runner/mise.toml | 5 ++++ .../ci/roles/actions_runners/tasks/main.yml | 2 +- 6 files changed, 59 insertions(+), 10 deletions(-) create mode 100644 ansible/ci/roles/actions_runners/files/ci-runner/ci-mise-install diff --git a/ansible/ci/roles/actions_runners/defaults/main.yml b/ansible/ci/roles/actions_runners/defaults/main.yml index c1830d46..0a7d8f57 100644 --- a/ansible/ci/roles/actions_runners/defaults/main.yml +++ b/ansible/ci/roles/actions_runners/defaults/main.yml @@ -102,6 +102,7 @@ actions_runners_registry_secret_key: "{{ lookup('env', 'REGISTRY_SECRET_KEY') | # (content-addressed, files added by atomic rename); mise's data, state and # cache directories, where a repo's pins the image lacks install, its node # and its PostgreSQL among them (mise locks a version while it installs it); +# corepack's downloads of the pnpm a repo names (each moved into place whole); # and Playwright's browsers, whose version follows each repo (Playwright # locks the directory while it installs). Nothing prunes them: a version no # repo pins any more stays until removed by hand. Owned by the image's diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-slot b/ansible/ci/roles/actions_runners/files/ci-runner-slot index 27cc12ec..ba431b75 100755 --- a/ansible/ci/roles/actions_runners/files/ci-runner-slot +++ b/ansible/ci/roles/actions_runners/files/ci-runner-slot @@ -10,7 +10,8 @@ # The caches every slot shares, bind-mounted from CACHE_DIR: the pnpm store; # mise's data, state and cache directories, where a repo's pins install (its # node, its PostgreSQL), all three so that two jobs installing one version -# wait on mise's own lock; and Playwright's browsers. +# wait on mise's own lock; corepack's downloads of pnpm; and Playwright's +# browsers. # # From /etc/ci-runner/slot.env: IMAGE and CACHE_DIR; from # /etc/ci-runner/size-.env: MEMORY, the container's limit, empty for @@ -35,6 +36,7 @@ set -- --rm --init --name "ci-runner-$instance" --network host \ -v "$CACHE_DIR/mise/data:$home/.local/share/mise" \ -v "$CACHE_DIR/mise/state:$home/.local/state/mise" \ -v "$CACHE_DIR/mise/cache:$home/.cache/mise" \ + -v "$CACHE_DIR/corepack:$home/.cache/node/corepack" \ -v "$CACHE_DIR/ms-playwright:$home/.cache/ms-playwright" [ -z "$MEMORY" ] || set -- "$@" --memory "$MEMORY" # The host's Connect server, where the role runs one (/etc/ci-runner/connect.env: diff --git a/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile b/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile index f617bda7..8542f950 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile +++ b/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile @@ -15,12 +15,14 @@ # the runner GitHub's Actions runner and the libraries it needs, run # as the user runner (1001), with sudo where the engine # allows it (a slot's no-new-privileges does not) -# node, pnpm node from the base; pnpm through corepack, at the -# version a repo's packageManager names +# node, pnpm node from the base; pnpm and yarn through corepack, at +# the version a repo's packageManager names, downloaded +# into ~/.cache/node/corepack # mise and, from mise.toml beside this file (mise's system # config), plx-ci at the Plexus version, the vault's CLI, # gh, crane and exo, the tools the small jobs installed -# for themselves +# for themselves; ci-mise-install beside it is a job's +# mise-action here # docker's client with buildx, for an image build against a BuildKit # elsewhere; no daemon, since no job here needs one # packages git for actions/checkout, jq, unzip, zstd for the cache @@ -35,7 +37,14 @@ # both dispatch by the config of the directory a command runs in. A version # the image lacks installs into mise's directories under ~/.local/share, # ~/.local/state and ~/.cache, which a runner host shares between its slots, -# all three, so that two jobs installing one version wait on mise's own lock. +# all three, so that two jobs installing one version wait on mise's own lock; +# corepack's and Playwright's downloads are shared the same way. +# +# mise loads a project's config only under ~/_work, where the runner checks +# a job's repo out: mise.toml turns on paranoid mode for config, which ends +# mise's trust of everything under CI and of whatever a command it runs +# would trust implicitly, and MISE_TRUSTED_CONFIG_PATHS names _work. Any +# other config is refused at once, with no prompt and no trust recorded. # # Left out on purpose: # @@ -70,7 +79,7 @@ RUN useradd --create-home --uid 1001 --shell /bin/bash runner \ && echo "${RUNNER_SHA256} runner.tgz" | sha256sum -c - \ && tar -xzf runner.tgz && rm runner.tgz \ && apt-get update && ./bin/installdependencies.sh && rm -rf /var/lib/apt/lists/* \ - && mkdir -p .local/share/mise .local/state/mise .cache/mise .cache/ms-playwright \ + && mkdir -p .local/share/mise .local/state/mise .cache/mise .cache/ms-playwright .cache/node/corepack \ && chown -R runner:runner /home/runner # renovate: datasource=github-releases depName=docker/cli @@ -95,9 +104,12 @@ RUN apt-get update \ && npx --yes "playwright@${PLAYWRIGHT_VERSION}" install-deps chromium \ && rm -rf /var/lib/apt/lists/* /root/.npm -# corepack's shims for pnpm, which fetch the version a repo names on first use. +# corepack's shims for pnpm and yarn, which fetch the version a repo names on +# first use. All of them: a job's own `corepack enable` rewrites only a link +# that differs, so it then has nothing to write in /usr/local/bin, which the +# runner user may not. ENV COREPACK_ENABLE_DOWNLOAD_PROMPT=0 -RUN corepack enable pnpm +RUN corepack enable # renovate: datasource=github-releases depName=jdx/mise ARG MISE_VERSION=v2026.11.8 @@ -106,10 +118,12 @@ RUN curl -fsSL -o /usr/local/bin/mise "https://github.com/jdx/mise/releases/down && echo "${MISE_SHA256} /usr/local/bin/mise" | sha256sum -c - \ && chmod 0755 /usr/local/bin/mise COPY mise.toml /etc/mise/config.toml +COPY --chmod=0755 ci-mise-install /usr/local/bin/ci-mise-install RUN mise install --system && mise reshim --system && rm -rf /root/.cache /root/.local /root/.npm # The data directory's shims first, then the system's: either dispatches by # the config of the directory a command runs in. A job's checkout is under -# _work, which mise trusts without asking, as mise-action does on the forge. +# _work, the one place mise loads a project's config from (above); MISE_YES +# answers mise's other questions, as mise-action has it on the forge. ENV PATH=/home/runner/.local/share/mise/shims:/usr/local/share/mise/shims:$PATH \ MISE_TRUSTED_CONFIG_PATHS=/home/runner/_work MISE_YES=1 diff --git a/ansible/ci/roles/actions_runners/files/ci-runner/ci-mise-install b/ansible/ci/roles/actions_runners/files/ci-runner/ci-mise-install new file mode 100644 index 00000000..1ab07bbc --- /dev/null +++ b/ansible/ci/roles/actions_runners/files/ci-runner/ci-mise-install @@ -0,0 +1,27 @@ +#!/bin/sh +# What jdx/mise-action does for a job on the forge's runners, for a job in the +# environment image (the reusable workflows call it where runner.environment +# is not github-hosted), without what the image already has: no download of +# mise, and no restore of the forge's cache into mise's directories, which a +# runner host shares between its slots. In the directory of the repo's +# config, run as a step: +# +# ci-mise-install [TOOL...] +# +# installs the repo's pins, all of them or the TOOLs named, with +# `mise install`, then hands the later steps the repo's environment the way +# mise-action does: the values mise marks for redaction masked, every +# variable of `mise env` but PATH into GITHUB_ENV, and the PATH entries mise +# manages (the tools' and the config's `_.path`) into GITHUB_PATH, last +# first, since the runner puts each line it reads in front of the rest. +set -eu +: "${GITHUB_ENV:?a step of a GitHub Actions job sets GITHUB_ENV}" "${GITHUB_PATH:?and GITHUB_PATH}" + +mise install "$@" + +mise env --redacted --json | jq -r '.[] | "::add-mask::" + .' +# A delimiter no value holds, as the runner's multiline syntax requires. +delimiter="mise_env_$(od -An -N8 -tx1 /dev/urandom | tr -d ' \n')" +mise env --json | jq -r --arg d "$delimiter" \ + 'to_entries[] | select(.key != "PATH") | "\(.key)<<\($d)\n\(.value)\n\($d)"' >>"$GITHUB_ENV" +mise env --paths | tac >>"$GITHUB_PATH" diff --git a/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml b/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml index f864fa65..8c3bad25 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml +++ b/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml @@ -18,5 +18,10 @@ crane = "0.22.1" "github:exoscale/cli" = { version = "1.103.2", bin = "exo" } [settings] +# Trust for a project's config is the content's, never automatic, never by CI +# and never by --yes, so only MISE_TRUSTED_CONFIG_PATHS (the job's checkout +# under _work) loads without a `mise trust`, and no trust mise grants on its +# own is written where another job sharing mise's directories would read it. +paranoid = ["config"] # The image's mise moves with the image, by its pin: no warning about a newer one in every job's log. disable_update_warning = true diff --git a/ansible/ci/roles/actions_runners/tasks/main.yml b/ansible/ci/roles/actions_runners/tasks/main.yml index ab887495..66ed101b 100644 --- a/ansible/ci/roles/actions_runners/tasks/main.yml +++ b/ansible/ci/roles/actions_runners/tasks/main.yml @@ -118,7 +118,7 @@ owner: "{{ actions_runners_runner_uid }}" group: "{{ actions_runners_runner_uid }}" mode: "0755" - loop: ["", pnpm-store, mise, mise/data, mise/state, mise/cache, ms-playwright] + loop: ["", pnpm-store, mise, mise/data, mise/state, mise/cache, corepack, ms-playwright] - name: Pull the runner image when: not actions_runners_image_build From 3d9ff01f1d2dd8ad72fd4cae1da9aadb8282af5a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:03:36 +0100 Subject: [PATCH 039/194] ci: hand the repo's [env] and paths to the later steps in the environment image The step in place of mise-action on a slot or an instance is now the image's ci-mise-install, which exports what mise-action exports, so that a plain run step sees the repo's [env] variables and _.path entries on either kind of runner. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/_changeset.yml | 9 +++++---- .github/workflows/_check.yml | 9 +++++---- .github/workflows/_deploy-targets.yml | 9 +++++---- .github/workflows/_deploy.yml | 10 +++++----- .github/workflows/_housekeeping.yml | 9 +++++---- .github/workflows/_plx-update.yml | 9 +++++---- .github/workflows/_publish-package.yml | 9 +++++---- .github/workflows/_release.yml | 27 ++++++++++++++------------ .github/workflows/_verify.yml | 27 ++++++++++++++------------ 9 files changed, 65 insertions(+), 53 deletions(-) diff --git a/.github/workflows/_changeset.yml b/.github/workflows/_changeset.yml index 69527145..99591839 100644 --- a/.github/workflows/_changeset.yml +++ b/.github/workflows/_changeset.yml @@ -115,15 +115,16 @@ jobs: ref: ${{ github.head_ref }} fetch-depth: 0 token: ${{ steps.app.outputs.token }} - # mise and the repo's pins: on the forge's runners from mise-action; in the - # environment image of a slot or an instance (actions_runners), which - # carries mise and the common tools, the pins it lacks install here. + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 if: ${{ runner.environment == 'github-hosted' }} - if: ${{ runner.environment != 'github-hosted' }} env: MISE_GITHUB_TOKEN: ${{ github.token }} - run: mise install + run: ci-mise-install - run: plx -y changeset --base 'origin/${{ inputs.base }}' - run: | git add .changeset diff --git a/.github/workflows/_check.yml b/.github/workflows/_check.yml index 6df8824b..b2f5f666 100644 --- a/.github/workflows/_check.yml +++ b/.github/workflows/_check.yml @@ -135,15 +135,16 @@ jobs: run: | printf '//npm.pkg.github.com/:_authToken=%s\n' "$GITHUB_TOKEN" > "$RUNNER_TEMP/npmrc" echo "NPM_CONFIG_USERCONFIG=$RUNNER_TEMP/npmrc" >> "$GITHUB_ENV" - # mise and the repo's pins: on the forge's runners from mise-action; in the - # environment image of a slot or an instance (actions_runners), which - # carries mise and the common tools, the pins it lacks install here. + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 if: ${{ runner.environment == 'github-hosted' }} - if: ${{ runner.environment != 'github-hosted' }} env: MISE_GITHUB_TOKEN: ${{ github.token }} - run: mise install + run: ci-mise-install - name: Check env: TASKS: ${{ inputs.tasks }} diff --git a/.github/workflows/_deploy-targets.yml b/.github/workflows/_deploy-targets.yml index c410d7a0..8582cbbd 100644 --- a/.github/workflows/_deploy-targets.yml +++ b/.github/workflows/_deploy-targets.yml @@ -35,15 +35,16 @@ jobs: matrix: ${{ steps.run.outputs.matrix }} steps: - uses: actions/checkout@v7 - # mise and the repo's pins: on the forge's runners from mise-action; in the - # environment image of a slot or an instance (actions_runners), which - # carries mise and the common tools, the pins it lacks install here. + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 if: ${{ runner.environment == 'github-hosted' }} - if: ${{ runner.environment != 'github-hosted' }} env: MISE_GITHUB_TOKEN: ${{ github.token }} - run: mise install + run: ci-mise-install - id: run # The assignment is a line of its own so that a failing verb fails the step. run: | diff --git a/.github/workflows/_deploy.yml b/.github/workflows/_deploy.yml index d35c068b..f5b3ce46 100644 --- a/.github/workflows/_deploy.yml +++ b/.github/workflows/_deploy.yml @@ -131,16 +131,16 @@ jobs: # The caller's repo (the app's source repo) — cwd for the verb, which # reads apps// relative here. Same SHA the image was built from. - uses: actions/checkout@v7 - # The caller's tools, plx among them: on the forge's runners from - # mise-action; in the environment image of a slot or an instance - # (actions_runners), which carries mise and the common tools, the pins it - # lacks install here. + # The caller's tools, plx among them, and its [env] for the later steps: + # on the forge's runners from mise-action; in the environment image of a + # slot or an instance (actions_runners), which carries mise and the + # common tools, from its ci-mise-install. - uses: jdx/mise-action@v5 if: ${{ runner.environment == 'github-hosted' }} - if: ${{ runner.environment != 'github-hosted' }} env: MISE_GITHUB_TOKEN: ${{ github.token }} - run: mise install + run: ci-mise-install - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: diff --git a/.github/workflows/_housekeeping.yml b/.github/workflows/_housekeeping.yml index e3b6ed79..cd7b9b31 100644 --- a/.github/workflows/_housekeeping.yml +++ b/.github/workflows/_housekeeping.yml @@ -89,9 +89,10 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 - # mise and the repo's pins: on the forge's runners from mise-action; in the - # environment image of a slot or an instance (actions_runners), which - # carries mise and the common tools, the pins it lacks install here. + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: @@ -99,7 +100,7 @@ jobs: - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} env: MISE_GITHUB_TOKEN: ${{ github.token }} - run: mise install node npm:@plexus-ms/cli-ci + run: ci-mise-install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: diff --git a/.github/workflows/_plx-update.yml b/.github/workflows/_plx-update.yml index 3e7723f6..514f0150 100644 --- a/.github/workflows/_plx-update.yml +++ b/.github/workflows/_plx-update.yml @@ -128,15 +128,16 @@ jobs: - uses: actions/checkout@v7 with: token: ${{ steps.app.outputs.token }} - # mise and the repo's pins: on the forge's runners from mise-action; in the - # environment image of a slot or an instance (actions_runners), which - # carries mise and the common tools, the pins it lacks install here. + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 if: ${{ runner.environment == 'github-hosted' }} - if: ${{ runner.environment != 'github-hosted' }} env: MISE_GITHUB_TOKEN: ${{ github.token }} - run: mise install + run: ci-mise-install - run: command -v gh >/dev/null || mise use --global gh@latest - run: plx -y update ${{ inputs.version != '' && format('--to {0}', inputs.version) || '' }} ${{ inputs.now && '--now' || '' }} env: diff --git a/.github/workflows/_publish-package.yml b/.github/workflows/_publish-package.yml index 1a3b1a2c..1e15ea87 100644 --- a/.github/workflows/_publish-package.yml +++ b/.github/workflows/_publish-package.yml @@ -79,15 +79,16 @@ jobs: printf '@%s:registry=https://npm.pkg.github.com\n' "$scope" } > "$RUNNER_TEMP/npmrc" echo "NPM_CONFIG_USERCONFIG=$RUNNER_TEMP/npmrc" >> "$GITHUB_ENV" - # mise and the repo's pins: on the forge's runners from mise-action; in the - # environment image of a slot or an instance (actions_runners), which - # carries mise and the common tools, the pins it lacks install here. + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 if: ${{ runner.environment == 'github-hosted' }} - if: ${{ runner.environment != 'github-hosted' }} env: MISE_GITHUB_TOKEN: ${{ github.token }} - run: mise install + run: ci-mise-install - run: pnpm install --frozen-lockfile # Build every package in dependency order before publishing: `changeset # publish` runs the packages' `prepack` hooks alphabetically, so a diff --git a/.github/workflows/_release.yml b/.github/workflows/_release.yml index 7718c956..7c84bcba 100644 --- a/.github/workflows/_release.yml +++ b/.github/workflows/_release.yml @@ -141,9 +141,10 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 - # mise and the repo's pins: on the forge's runners from mise-action; in the - # environment image of a slot or an instance (actions_runners), which - # carries mise and the common tools, the pins it lacks install here. + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: @@ -151,7 +152,7 @@ jobs: - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} env: MISE_GITHUB_TOKEN: ${{ github.token }} - run: mise install node npm:@plexus-ms/cli-ci + run: ci-mise-install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: @@ -217,9 +218,10 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 - # mise and the repo's pins: on the forge's runners from mise-action; in the - # environment image of a slot or an instance (actions_runners), which - # carries mise and the common tools, the pins it lacks install here. + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: @@ -227,7 +229,7 @@ jobs: - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} env: MISE_GITHUB_TOKEN: ${{ github.token }} - run: mise install node npm:@plexus-ms/cli-ci + run: ci-mise-install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: @@ -299,9 +301,10 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 - # mise and the repo's pins: on the forge's runners from mise-action; in the - # environment image of a slot or an instance (actions_runners), which - # carries mise and the common tools, the pins it lacks install here. + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: @@ -309,7 +312,7 @@ jobs: - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} env: MISE_GITHUB_TOKEN: ${{ github.token }} - run: mise install node npm:@plexus-ms/cli-ci + run: ci-mise-install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: diff --git a/.github/workflows/_verify.yml b/.github/workflows/_verify.yml index f0928e52..3cc28ef8 100644 --- a/.github/workflows/_verify.yml +++ b/.github/workflows/_verify.yml @@ -162,9 +162,10 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 - # mise and the repo's pins: on the forge's runners from mise-action; in the - # environment image of a slot or an instance (actions_runners), which - # carries mise and the common tools, the pins it lacks install here. + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: @@ -172,7 +173,7 @@ jobs: - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} env: MISE_GITHUB_TOKEN: ${{ github.token }} - run: mise install node npm:@plexus-ms/cli-ci + run: ci-mise-install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: @@ -333,9 +334,10 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 - # mise and the repo's pins: on the forge's runners from mise-action; in the - # environment image of a slot or an instance (actions_runners), which - # carries mise and the common tools, the pins it lacks install here. + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: @@ -343,7 +345,7 @@ jobs: - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} env: MISE_GITHUB_TOKEN: ${{ github.token }} - run: mise install node npm:@plexus-ms/cli-ci + run: ci-mise-install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: @@ -469,9 +471,10 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 - # mise and the repo's pins: on the forge's runners from mise-action; in the - # environment image of a slot or an instance (actions_runners), which - # carries mise and the common tools, the pins it lacks install here. + # mise, the repo's pins and its [env] for the later steps: on the forge's + # runners from mise-action; in the environment image of a slot or an + # instance (actions_runners), which carries mise and the common tools, + # from its ci-mise-install. - uses: jdx/mise-action@v5 if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} with: @@ -479,7 +482,7 @@ jobs: - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} env: MISE_GITHUB_TOKEN: ${{ github.token }} - run: mise install node npm:@plexus-ms/cli-ci + run: ci-mise-install node npm:@plexus-ms/cli-ci - uses: actions/checkout@v7 if: ${{ inputs.tooling-ref != '' }} with: From 6ba06e3a3c83d416f090c15fe92aa38b9a68381c Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:04:00 +0100 Subject: [PATCH 040/194] Test: the image test builds with no flag a Docker may lack docker build --resource is a recent buildx flag, and the build only copies, so it needs no limit; the containers keep theirs through the compose override and docker run's long-standing flags. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- newborns/app-nextjs.test.ts | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index da8c1628..8b175cd6 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -191,16 +191,11 @@ for (const profile of PROFILES) { await sh('mise', ['run', 'build', profile], repo, PLATFORM); const id = randomBytes(4).toString('hex'); const tag = `plx-newborn-${profile}:${id}`; - // Limits for every container and build, on a machine others share; the build itself runs nothing. + // Limits for every container, on a machine others share; the build runs nothing and needs none. const limits = { cpus: 4, mem_limit: '6g', pids_limit: 1000 }; - const resources = ['--resource', 'memory=6g', '--resource', 'cpu-quota=400000']; // As the Dockerfile's header says: the directory is the context. const dockerfile = join(app, 'docker', 'Dockerfile'); - await sh( - 'docker', - ['build', ...resources, '--build-arg', `APP=${profile}`, '-f', dockerfile, '-t', tag, output(profile)], - repo, - ); + await sh('docker', ['build', '--build-arg', `APP=${profile}`, '-f', dockerfile, '-t', tag, output(profile)], repo); try { const run = ['run', '--rm', '--cpus', '4', '--memory', '6g', '--pids-limit', '1000', '--entrypoint', 'node']; const held = JSON.parse( From 6b8f6ee8113a9e654c1e33c0c3e82b92476c912a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:08:34 +0100 Subject: [PATCH 041/194] Test: the image's user, port, environment, ownership and base The image test reads the image's configuration: it runs as node, exposes 3000 alone, and sets NODE_ENV=production. It requests an optimised image and finds the optimiser's cache written below the copied tree, which the image's user can only do when it owns the tree. The render test asserts the Debian slim base. Each was broken once (no --chown, no USER, no EXPOSE, no NODE_ENV, an alpine base) and a test failed; with the template as it is, they pass. The stateful app gets its public/ only in its image test, so that the earlier builds still show a build without one. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- newborns/app-nextjs.test.ts | 13 +++++++++++++ packages/lib/src/appNextjs.test.ts | 3 ++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index 8b175cd6..e7cefece 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -43,6 +43,7 @@ before(async () => { repo = await born(join(here, 'acme'), ['repo-turbo', 'updates'], { tenant: 'acme' }); for (const profile of PROFILES) await born(join(repo, 'apps', profile), ['app-nextjs'], { name: `@acme/${profile}`, profile }); + // The stateful app has no public/ until its image test, so that a build without one is shown too. put(join(repo, 'apps', 'stateless'), { 'public/pixel.png': PIXEL }); await sh('mise', ['exec', '--', 'pnpm', 'install'], repo); // Tracked, as in a checkout: Turbo hashes what git tracks, and an untracked app's build output with it. @@ -185,6 +186,7 @@ for (const profile of PROFILES) { 'package.json': manifest, 'next.config.ts': config, 'migrate.mjs': "console.log('migrated in', process.cwd());\n", + 'public/pixel.png': PIXEL, }); await sh('git', ['add', '-A'], repo); } @@ -197,6 +199,10 @@ for (const profile of PROFILES) { const dockerfile = join(app, 'docker', 'Dockerfile'); await sh('docker', ['build', '--build-arg', `APP=${profile}`, '-f', dockerfile, '-t', tag, output(profile)], repo); try { + const config = JSON.parse(await sh('docker', ['image', 'inspect', '--format', '{{json .Config}}', tag], here)); + assert.equal(config.User, 'node'); + assert.deepEqual(Object.keys(config.ExposedPorts ?? {}), ['3000/tcp']); + assert.ok(config.Env.includes('NODE_ENV=production'), config.Env.join(' ')); const run = ['run', '--rm', '--cpus', '4', '--memory', '6g', '--pids-limit', '1000', '--entrypoint', 'node']; const held = JSON.parse( (await sh('docker', [...run, tag, '-e', LIST, '/repo'], here)).trim().split('\n').at(-1) ?? '', @@ -223,6 +229,13 @@ for (const profile of PROFILES) { ); await sh('docker', [...compose, 'up', '--detach', '--wait'], here, env); assert.equal((await fetch(`http://127.0.0.1:${port}/`)).status, 200); + // The optimiser writes its cache below the copied tree, as the image's user. + const image = await fetch(`http://127.0.0.1:${port}/_next/image?url=%2Fpixel.png&w=64&q=75`, { + headers: { accept: 'image/webp' }, + }); + assert.equal(image.headers.get('content-type'), 'image/webp'); + const cached = "console.log(require('fs').readdirSync('.next/cache/images').length)"; + assert.match(await sh('docker', [...compose, 'exec', '-T', 'web', 'node', '-e', cached], here, env), /^[1-9]/m); } finally { await tryRun('docker', [...compose, 'down', '--volumes'], here, env); } diff --git a/packages/lib/src/appNextjs.test.ts b/packages/lib/src/appNextjs.test.ts index 4ae90a0b..88701f10 100644 --- a/packages/lib/src/appNextjs.test.ts +++ b/packages/lib/src/appNextjs.test.ts @@ -63,9 +63,10 @@ test('the profile is stateless unless the app says stateful', async () => { assert.match(textOf(stateful, 'PLEXUS.md'), /`migrate` and `seed`/); }); -test('the Dockerfile has one stage, which builds and installs nothing', async () => { +test('the Dockerfile has one stage on the Debian slim base, which builds and installs nothing', async () => { const dockerfile = textOf(await render(), 'docker/Dockerfile'); assert.equal(dockerfile.match(/^FROM /gm)?.length, 1); + assert.match(dockerfile, /^FROM node:\d+-slim@sha256:[0-9a-f]{64}$/m); assert.doesNotMatch(dockerfile, /^RUN /m); }); From 1b762946c8e103abc0d493a11b57bc2d32829e65 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:08:46 +0100 Subject: [PATCH 042/194] Test: the marker names an app's verbs, its test script's files, its build The marker of a new app names mise :dev, :build, :check, :test and :e2e with and no verify; it quotes the file names node --test runs; and it says that build puts the static files and public/ into the standalone output. Red: it names mise :verify and says neither. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/appNextjs.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/packages/lib/src/appNextjs.test.ts b/packages/lib/src/appNextjs.test.ts index 88701f10..3a0c59da 100644 --- a/packages/lib/src/appNextjs.test.ts +++ b/packages/lib/src/appNextjs.test.ts @@ -83,6 +83,14 @@ test('the source an author edits and the marker are written once, the rest is me assert.equal(origin.policy, once.includes(path) ? 'born-once' : 'merge', path); }); +test('the marker names the verbs an app has, what its test script runs, and what its build leaves', async () => { + const marker = textOf(await render(), 'PLEXUS.md'); + for (const verb of ['dev', 'build', 'check', 'test', 'e2e']) assert.match(marker, new RegExp(`mise :${verb} `)); + assert.doesNotMatch(marker, /verify/); + assert.match(marker, /`node --test`.*\*\*\/\*\.test\.\{cts,mts,ts\}/); + assert.match(marker, /static files and `public\/`/); +}); + test('the marker has no frontmatter, which plx writes', async () => { assert.ok(!textOf(await render({ profile: 'stateful' }), 'PLEXUS.md').startsWith('---')); }); From e18fd634a7c495fc6bdc5f919582e3864e648c07 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:09:12 +0100 Subject: [PATCH 043/194] The marker names an app's verbs, what its test script runs, and its build A new app's marker names the verbs it has now, dev, build, check, test and e2e, and not verify, which is gone; it is born once, so it must be right at birth. It quotes the file names node --test runs by Node's rule (Node 24 documentation, "Running tests from the command line"), says that no .tsx file runs and no @/ import resolves, and that an app with such tests names its own runner. It says that build completes Next's standalone output in place with the static files and public/, as Next's documentation describes, since the script can carry no comment. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- templates/app-nextjs/files/PLEXUS.md.jinja | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/templates/app-nextjs/files/PLEXUS.md.jinja b/templates/app-nextjs/files/PLEXUS.md.jinja index 31259eb7..030f7fd8 100644 --- a/templates/app-nextjs/files/PLEXUS.md.jinja +++ b/templates/app-nextjs/files/PLEXUS.md.jinja @@ -1,5 +1,8 @@ - `{{ name }}`, a Next.js app: its `build` leaves one directory that runs as it is, `.next/standalone`, `docker/Dockerfile` copies that directory into its image, and `docker/compose.yaml` runs the image on its host. -- Its verbs are the repo root's: `mise :dev `, `mise :build ` and `mise :verify `, `` being this directory's name. +- The `build` script completes Next's standalone output in place: after `next build` it copies the static files and `public/` into it, as Next's documentation of `output: 'standalone'` describes. +- Its verbs are the repo root's: `mise :dev `, `mise :build `, `mise :check `, `mise :test ` and `mise :e2e `, `` being this directory's name. +- The `test` script is `node --test`, which runs the files of Node's rule, `**/*.test.{cts,mts,ts}`, `**/*-test.{cts,mts,ts}`, `**/*_test.{cts,mts,ts}`, `**/test-*.{cts,mts,ts}`, `**/test.{cts,mts,ts}` and `**/test/**/*.{cts,mts,ts}` and their `.cjs`, `.mjs` and `.js` siblings, with relative imports: no `.tsx` file runs, and no `@/` import resolves. + An app with such tests names its own runner in that script. {%- if profile == 'stateful' %} - The `migrate` and `seed` scripts in `package.json` fail until they are written: the deploy verb runs `migrate` in the image, through the compose file's `migrate` service, from what the build put in the directory, and `seed` loads development data and never runs on a host. {%- endif %} From feff77525ebcb35e46c2cdfecb08029f418f092c Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:09:16 +0100 Subject: [PATCH 044/194] Say that a build outside Turbo or mise throws, as it does The comment above generateBuildId said such a build would get another ID; the guard below it throws instead. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- templates/app-nextjs/files/next.config.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/app-nextjs/files/next.config.ts b/templates/app-nextjs/files/next.config.ts index 830af217..43cdee40 100644 --- a/templates/app-nextjs/files/next.config.ts +++ b/templates/app-nextjs/files/next.config.ts @@ -8,7 +8,7 @@ const root = process.env.PLX_UMBRELLA_ROOT || fileURLToPath(new URL('../../', im const nextConfig: NextConfig = { output: 'standalone', // The build ID is Turbo's hash of this app's build task, which carries the platform (turbo.json). - // A build started outside Turbo, or outside mise, which sets PLX_PLATFORM, would get another ID. + // A build started outside Turbo, or outside mise, which sets PLX_PLATFORM, throws here instead. generateBuildId: () => { const { TURBO_HASH, PLX_PLATFORM } = process.env; if (!TURBO_HASH || !PLX_PLATFORM) From 9adba164ea1e666387c9dee042ebd616d5cbfe5a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:09:56 +0100 Subject: [PATCH 045/194] The newborn helpers start a command one way, for tryRun and start alike launch spawns a command leading its own process group, collects what it prints, kills the group when the command exits and reports its end; tryRun adds its limit, start its readiness and its stop, and neither repeats the spawn, the kill or the collection. (PLX-178) Co-Authored-By: Claude Fable 5.2 --- newborns/helpers.ts | 104 +++++++++++++++++++++++--------------------- 1 file changed, 55 insertions(+), 49 deletions(-) diff --git a/newborns/helpers.ts b/newborns/helpers.ts index 8188cfec..7f4b47c6 100644 --- a/newborns/helpers.ts +++ b/newborns/helpers.ts @@ -87,49 +87,66 @@ export interface Ran { */ export const LIMIT = 10 * 60_000; +/** A command started leading a process group of its own: what it printed so far, the group's kill, and its end. */ +interface Launched { + output(): string; + kill(): void; + /** Its exit code once its output is closed; null where it was killed or could not start. */ + closed: Promise; +} + +/** + * Starts a command in a process group of its own and collects what it prints; + * the group is killed once the command exits, so that nothing it started + * outlives it. A command that cannot start ends with the error as its output. + */ +function launch(command: string, args: string[], cwd: string, env: NodeJS.ProcessEnv): Launched { + const child = spawn(command, args, { cwd, env: cleanEnv(env), stdio: ['ignore', 'pipe', 'pipe'], detached: true }); + let output = ''; + const collect = (chunk: Buffer) => { + output += chunk; + }; + child.stdout.on('data', collect); + child.stderr.on('data', collect); + const kill = () => { + try { + if (child.pid) process.kill(-child.pid, 'SIGKILL'); + } catch {} + }; + child.on('exit', kill); + const closed = new Promise((resolve) => { + child.on('error', (error) => { + output = error.message; + resolve(null); + }); + child.on('close', resolve); + }); + return { output: () => output, kill, closed }; +} + /** * Runs a command and returns what it printed; a failure, a command killed at * its limit included, is returned, never thrown. The command leads a process * group of its own, which is killed at the limit and when the command is done, * so that nothing it started outlives it. */ -export function tryRun( +export async function tryRun( command: string, args: string[], cwd: string, env: NodeJS.ProcessEnv = {}, limit = LIMIT, ): Promise { - return new Promise((resolve) => { - const child = spawn(command, args, { cwd, env: cleanEnv(env), stdio: ['ignore', 'pipe', 'pipe'], detached: true }); - const killGroup = () => { - try { - if (child.pid) process.kill(-child.pid, 'SIGKILL'); - } catch {} - }; - let output = ''; - let timedOut = false; - child.stdout.on('data', (chunk: Buffer) => { - output += chunk; - }); - child.stderr.on('data', (chunk: Buffer) => { - output += chunk; - }); - const timer = setTimeout(() => { - timedOut = true; - killGroup(); - }, limit); - child.on('error', (error) => { - clearTimeout(timer); - resolve({ ok: false, output: error.message }); - }); - child.on('exit', () => killGroup()); - child.on('close', (code) => { - clearTimeout(timer); - if (timedOut) resolve({ ok: false, output: `${command} timed out after ${limit} ms and was killed\n${output}` }); - else resolve({ ok: code === 0, output }); - }); - }); + const run = launch(command, args, cwd, env); + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + run.kill(); + }, limit); + const code = await run.closed; + clearTimeout(timer); + if (timedOut) return { ok: false, output: `${command} timed out after ${limit} ms and was killed\n${run.output()}` }; + return { ok: code === 0, output: run.output() }; } /** Runs a command that must succeed; its output goes with the error otherwise. */ @@ -376,25 +393,14 @@ export async function start( env: NodeJS.ProcessEnv, ready: () => Promise, ): Promise { - const child = spawn(command, args, { cwd, env: cleanEnv(env), stdio: ['ignore', 'pipe', 'pipe'], detached: true }); - let output = ''; - const collect = (chunk: Buffer) => { - output += chunk; - }; - child.stdout.on('data', collect); - child.stderr.on('data', collect); + const run = launch(command, args, cwd, env); let gone = false; - const exited = new Promise((resolve) => - child.on('close', () => { - gone = true; - resolve(); - }), - ); + void run.closed.then(() => { + gone = true; + }); const stop = async () => { - try { - if (child.pid) process.kill(-child.pid, 'SIGKILL'); - } catch {} - await exited; + run.kill(); + await run.closed; }; const until = Date.now() + LIMIT; while (!gone && Date.now() < until) { @@ -402,5 +408,5 @@ export async function start( await new Promise((resolve) => setTimeout(resolve, 200)); } await stop(); - throw new Error(`${command} ${args.join(' ')} ${gone ? 'exited' : 'never became ready'} in ${cwd}:\n${output}`); + throw new Error(`${command} ${args.join(' ')} ${gone ? 'exited' : 'never became ready'} in ${cwd}:\n${run.output()}`); } From b4dd664fb1171c9f20b3932df8e2c60f6815bf56 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:14:24 +0100 Subject: [PATCH 046/194] BuildKit service: the bridge's subnet as a variable; say what outlives a stop (PLX-180) From the second review of the pull request: - actions_runners_buildkit_subnet, empty for BuildKit's own 10.10.0.0/16, is written as bridgeSubnet only when set, for a host that routes a network overlapping BuildKit's default. buildkitd does not readdress a bridge that exists, so a change takes deleting buildkit0 first; the variable's comment says so. - The defaults say that the bridge, its route and its NAT rules outlive a stop of the service, and add them to what a removal by hand takes away; and that the restart goes by change time, so a touched file restarts the daemon once and a clock stepped back can hide a change. Co-Authored-By: Claude Opus 5.5 --- .../roles/actions_runners/defaults/main.yml | 22 +++++++++++++++---- .../roles/actions_runners/tasks/buildkit.yml | 3 +++ 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/ansible/ci/roles/actions_runners/defaults/main.yml b/ansible/ci/roles/actions_runners/defaults/main.yml index 53a8a004..75755d39 100644 --- a/ansible/ci/roles/actions_runners/defaults/main.yml +++ b/ansible/ci/roles/actions_runners/defaults/main.yml @@ -157,13 +157,19 @@ actions_runners_disk_alert_percent: 85 # hourly housekeeping leaves it alone. A run restarts the daemon whenever # its binary, configuration or unit on disk changed after it started, also # after an earlier run that failed halfway; a publish job in flight does -# not survive that. Under the strategy `github` there is no runner host and -# so no service: the publish job uses the runner's Docker. +# not survive that. It goes by the files' change time, so a file touched +# without a change restarts the daemon once, and a clock stepped back after +# the daemon started can hide a later change. Under the strategy `github` +# there is no runner host and so no service: the publish job uses the +# runner's Docker. # # Nothing removes the service from a host once this role ran there: a host # dropped from the group `ci`, or a tenant that switches to `github`, keeps # it running until someone runs `systemctl disable --now ci-buildkit` and -# deletes the unit, /etc/buildkit, /var/lib/buildkit and the binaries. +# deletes the unit, /etc/buildkit, /var/lib/buildkit and the binaries. The +# bridge buildkit0, its route and its NAT rules (iptables chains CNI-*) +# outlive a stop of the service until a reboot or `ip link delete +# buildkit0` and the removal of those rules. # # One service for every job of every repo the host serves is accepted as it # behaves, inside the one tenant the host serves (§ 1 PLX-Tenancy): @@ -175,7 +181,7 @@ actions_runners_disk_alert_percent: 85 # - A RUN step runs as root in its container with runc's default # capabilities, raw sockets among them, so it sees all traffic of its # network namespace. That namespace is its own, on BuildKit's bridge -# buildkit0 (BuildKit's default subnet 10.10.0.0/16, a route on the host), +# buildkit0 (a route on the host, actions_runners_buildkit_subnet), # with the internet through NAT and iptables, which Docker brings: a step # reaches neither the host's loopback nor its traffic, and reaches the # host itself only at the bridge's address, through the host firewall's @@ -219,3 +225,11 @@ actions_runners_buildkit_cache_max: 10GB # Dockerfile of its own builds inside it and needs what its build needs. # The sum of the slots' limits and this one is the host's to afford. actions_runners_buildkit_memory: 4G +# The subnet of the build steps' bridge buildkit0, BuildKit's bridgeSubnet +# (in its source, not its documentation); empty is BuildKit's default, +# 10.10.0.0/16. A host that routes a network overlapping it sets another. +# buildkitd does not readdress a bridge that exists: a change takes +# `systemctl stop ci-buildkit && ip link delete buildkit0` before the run, +# or the daemon fails to start ("buildkit0" already has an IP address +# different from …) and the run with it. +actions_runners_buildkit_subnet: "" diff --git a/ansible/ci/roles/actions_runners/tasks/buildkit.yml b/ansible/ci/roles/actions_runners/tasks/buildkit.yml index 1a044a0a..60c7ced3 100644 --- a/ansible/ci/roles/actions_runners/tasks/buildkit.yml +++ b/ansible/ci/roles/actions_runners/tasks/buildkit.yml @@ -84,6 +84,9 @@ [worker.oci] enabled = true networkMode = "bridge" + {% if actions_runners_buildkit_subnet %} + bridgeSubnet = "{{ actions_runners_buildkit_subnet }}" + {% endif %} gc = true maxUsedSpace = "{{ actions_runners_buildkit_cache_max }}" defaultCgroupParent = "system.slice/ci-buildkit.service" From 36644e382014b6759a6a8627f786a968f96516d2 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:18:33 +0100 Subject: [PATCH 047/194] test(repo-turbo): an answer of postgres has ASCII digits and no leading zero Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/repoTurbo.test.ts | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index 5ecfa1fd..95e78a23 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -311,9 +311,26 @@ test('the major is derived from the answer and asked of no one', async () => { }); test('an answer is an exact version, major and minor, or empty', async () => { - for (const postgres of ['', '18.6', '17.12', '9.6']) + for (const postgres of ['', '18.6', '17.12', '9.6', '18.0', '10.10']) assert.deepEqual((await render({ postgres })).errors, [], postgres); - for (const postgres of ['18', '18.6.1', 'v18.6', '18.x', '18.', '.6', ' 18.6', '18.6\n', 'latest', '18-6']) { + for (const postgres of [ + '18', + '18.6.1', + 'v18.6', + '18.x', + '18.', + '.6', + ' 18.6', + '18.6\n', + 'latest', + '18-6', + '018.6', + '18.06', + '00.6', + '18.00', + '٣.٤', + '18.6', + ]) { const { errors } = await render({ postgres }); assert.equal(errors.length, 1, JSON.stringify(postgres)); assert.equal(errors[0]?.question, 'postgres', JSON.stringify(postgres)); From 483e082c537949ed27c90d8941bf558f82ab015a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:18:38 +0100 Subject: [PATCH 048/194] repo-turbo: a postgres answer is two numbers of ASCII digits, none with a leading zero Co-Authored-By: Claude Fable 5.2 --- templates/repo-turbo/template.yml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/templates/repo-turbo/template.yml b/templates/repo-turbo/template.yml index 165737ae..7b0c2bd5 100644 --- a/templates/repo-turbo/template.yml +++ b/templates/repo-turbo/template.yml @@ -80,10 +80,13 @@ questions: type: str help: "The PostgreSQL the repo's tests run against, as an exact version with major and minor, as in 18.6 (empty: none): mise installs that binary from conda-forge, and its major is an input of test and e2e" default: "" - # An exact version as string tests, since the engine has no regex: two parts, both digits. + # An exact version as string tests, since the engine has no regex: two parts of ASCII digits, none with a leading zero + # but a lone 0. validator: >- - {% if postgres %}{% set parts = postgres.split('.') %}{% if parts | length != 2 or not parts[0].isdigit() or not - parts[1].isdigit() %}An exact version, major and minor, as in 18.6, or empty{% endif %}{% endif %} + {% if postgres %}{% set parts = postgres.split('.') %}{% set bad %}{% if parts | length != 2 %}x{% endif %}{% for + part in parts %}{% if part == '' or (part | length > 1 and part[0] == '0') %}x{% endif %}{% for c in part %}{% if c + not in '0123456789' %}x{% endif %}{% endfor %}{% endfor %}{% endset %}{% if bad %}An exact version, major and + minor, as in 18.6, or empty{% endif %}{% endif %} policies: # The marker is born once: its body is the repo's own prose, which an update would conflict with, and From ba06f7cd428a9a4b5543e55f3c8173fccf762773 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:20:28 +0100 Subject: [PATCH 049/194] tests of repo-turbo: the hash test on an app under apps/, the doctor's two findings asserted before the stub, the end marker compared again Co-Authored-By: Claude Fable 5.2 --- newborns/app-nextjs.test.ts | 2 +- newborns/helpers.ts | 12 ++++++- newborns/repo-turbo.test.ts | 44 ++++++++++++----------- packages/dev/src/ship.integration.test.ts | 14 +++++--- 4 files changed, 45 insertions(+), 27 deletions(-) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index 6537f21b..7bdeaabd 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -17,7 +17,7 @@ const PROFILES = ['stateless', 'stateful']; before(async () => { here = await open('app-nextjs'); - repo = awaitingDoctor(await born(join(here, 'acme'), ['repo-turbo', 'updates'], { tenant: 'acme' })); + repo = await awaitingDoctor(await born(join(here, 'acme'), ['repo-turbo', 'updates'], { tenant: 'acme' })); for (const profile of PROFILES) await born(join(repo, 'apps', profile), ['app-nextjs'], { name: `@acme/${profile}`, profile }); }); diff --git a/newborns/helpers.ts b/newborns/helpers.ts index 98a844f2..edf23e6e 100644 --- a/newborns/helpers.ts +++ b/newborns/helpers.ts @@ -333,8 +333,18 @@ export async function assertBuilt(dir: string): Promise { /** * `plx doctor` still wants a root task `verify` (PLX-Repo/Verbs and PLX-Repo/SubVerbs), which repo-turbo has no * more. The newborn gets a task of that name and meets exactly those two findings, and nothing else is silenced. + * It first asserts that the doctor finds exactly those two, so that this fails, and is removed, on the day the + * doctor knows the five verbs. */ -export function awaitingDoctor(dir: string): string { +export async function awaitingDoctor(dir: string): Promise { + await sh('git', ['add', '-A'], dir); + const ran = await tryRun('mise', ['exec', '--', 'plx', 'doctor'], dir); + const found = ran.output.split('\n').filter((line) => line.startsWith('✗ PLX-')); + const expected = ['PLX-Repo/Verbs', 'PLX-Repo/SubVerbs'].map((name) => `✗ ${name} .: no root mise task \`verify\``); + if (JSON.stringify(found.sort()) !== JSON.stringify(expected.sort())) + throw new Error( + `plx doctor knows the five verbs, or finds more than the two verify findings: remove awaitingDoctor.\n${ran.output}`, + ); appendFileSync(join(dir, 'mise.toml'), WAITING_FOR_DOCTOR.task); return dir; } diff --git a/newborns/repo-turbo.test.ts b/newborns/repo-turbo.test.ts index 0e4f6227..37e87ed1 100644 --- a/newborns/repo-turbo.test.ts +++ b/newborns/repo-turbo.test.ts @@ -32,7 +32,7 @@ after(close); async function newborn(name: string, answers: Record = {}): Promise { const dir = await born(join(here, name), ['repo-turbo', 'updates'], { tenant: 'acme', ...answers }); assert.doesNotMatch(read(dir, 'mise.toml'), /^\[tasks\.verify\]/m, 'a repo is born without verify'); - return awaitingDoctor(dir); + return await awaitingDoctor(dir); } const read = (dir: string, file: string) => readFileSync(join(dir, file), 'utf8'); @@ -122,28 +122,30 @@ describe('an app repo', () => { assert.match(unknown.output, /no app or package demo-none/, `${verb} says why`); } }); +}); - test('editing a test file moves the hash of test and leaves the hash of build', async () => { - put(dir, { - 'packages/hashed/package.json': { - name: 'hashed', - version: '0.0.0', - private: true, - scripts: { build: 'echo built', check: 'echo checked', test: 'echo tested' }, - }, - 'packages/hashed/src/index.ts': 'export const answer = 42;\n', - 'packages/hashed/src/index.test.ts': 'export const first = 1;\n', - }); - await relock(dir); - const before = await hashes(dir, 'hashed', ['build', 'test']); - put(dir, { 'packages/hashed/src/index.test.ts': 'export const first = 2;\n' }); - const after = await hashes(dir, 'hashed', ['build', 'test']); - assert.notEqual(after['hashed#test'], before['hashed#test'], 'the test file is an input of test'); - assert.equal(after['hashed#build'], before['hashed#build'], 'and of no build'); - put(dir, { 'packages/hashed/src/index.ts': 'export const answer = 43;\n' }); - const edited = await hashes(dir, 'hashed', ['build', 'test']); - assert.notEqual(edited['hashed#build'], after['hashed#build'], 'a source file still moves the build'); +test('in a repo with one app, editing a test file moves the hash of test and leaves the hash of build', async () => { + // A repo of its own: the app has no marker or compose file, which only a run of plx doctor would ask for. + const dir = await newborn('one-app'); + put(dir, { + 'apps/hashed/package.json': { + name: 'hashed', + version: '0.0.0', + private: true, + scripts: { build: 'echo built', check: 'echo checked', test: 'echo tested' }, + }, + 'apps/hashed/src/index.ts': 'export const answer = 42;\n', + 'apps/hashed/src/index.test.ts': 'export const first = 1;\n', }); + await relock(dir); + const before = await hashes(dir, 'hashed', ['build', 'test']); + put(dir, { 'apps/hashed/src/index.test.ts': 'export const first = 2;\n' }); + const after = await hashes(dir, 'hashed', ['build', 'test']); + assert.notEqual(after['hashed#test'], before['hashed#test'], 'the test file is an input of test'); + assert.equal(after['hashed#build'], before['hashed#build'], 'and of no build'); + put(dir, { 'apps/hashed/src/index.ts': 'export const answer = 43;\n' }); + const edited = await hashes(dir, 'hashed', ['build', 'test']); + assert.notEqual(edited['hashed#build'], after['hashed#build'], 'a source file still moves the build'); }); test('mise e2e works first in a fresh clone: it installs what it needs', async () => { diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index d99b70e8..30ee1b36 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -1898,7 +1898,12 @@ for (const [template, answers, edits] of [ const end = snapshot(human); const expected = { ...start }; expected['PLEXUS.md'] = { - text: setMarkerKeys(start['PLEXUS.md']?.text ?? '', { version: CURRENT, templates: [template, 'updates'] }), + // The question repo-turbo has gained since the move is spliced into the marker, as an empty answer. + text: setMarkerKeys(start['PLEXUS.md']?.text ?? '', { + version: CURRENT, + templates: [template, 'updates'], + ...(template === 'repo-turbo' ? { postgres: '' } : {}), + }), executable: false, }; const workflow = start[MOVED[0] ?? '']; @@ -1906,11 +1911,12 @@ for (const [template, answers, edits] of [ executable: false, text: (workflow?.text ?? '').replace(`templates/${template}: edit`, 'templates/updates: edit'), }; - // repo-turbo has changed since the move (its verbs, its hooks, a question more in the marker), so what the update - // took in of it is no longer the repo as it was: the files the move concerns are what is compared. repo-operations is still as it was. + // repo-turbo has changed since the move (its verbs, its hooks, a question more), so what the update took in of it is + // no longer the repo as it was: the marker, with that question added, and the files the move concerns are + // compared. repo-operations is still as it was. const concerned = (files: typeof end) => template === 'repo-turbo' - ? Object.fromEntries(Object.entries(files).filter(([path]) => MOVED.includes(path))) + ? Object.fromEntries(Object.entries(files).filter(([path]) => path === 'PLEXUS.md' || MOVED.includes(path))) : files; assert.deepEqual(concerned(end), concerned(expected)); }); From e249dd1af594ddf34c7294493cd3fe65aceec863 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:21:05 +0100 Subject: [PATCH 050/194] test(cli-ci): an instance's job container mounts no cache The instance runs one job and is deleted, so nothing is shared between jobs there: the runner's container mounts _diag and nothing else, and the comment where the user-data starts it says so. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/core/userData.test.ts | 4 ++++ packages/cli-ci/src/core/userData.ts | 8 +++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/cli-ci/src/core/userData.test.ts b/packages/cli-ci/src/core/userData.test.ts index 7e267d1c..f944969b 100644 --- a/packages/cli-ci/src/core/userData.test.ts +++ b/packages/cli-ci/src/core/userData.test.ts @@ -56,6 +56,10 @@ test('the runner’s log stays on the host, where the no-job layer and a kept in assert.match(RUNNER_USER_DATA, /ls \/opt\/runner\/_diag\/Worker_\*\.log/); }); +test('the job’s container mounts nothing but the log’s directory: an instance runs one job, so no cache is shared', () => { + assert.deepEqual(unitLine('ExecStart').match(/ -v \S+/g), [' -v /opt/runner/_diag:/home/runner/_diag']); +}); + test('the log’s directory is the runner’s before the container mounts it, or the no-job layer deletes a running job', () => { // Docker would create a missing mount source as root, where the image's // runner (1001) cannot write its Worker log. diff --git a/packages/cli-ci/src/core/userData.ts b/packages/cli-ci/src/core/userData.ts index 19687665..561a5ec2 100644 --- a/packages/cli-ci/src/core/userData.ts +++ b/packages/cli-ci/src/core/userData.ts @@ -244,9 +244,11 @@ write_files: # 1: ExecStopPost runs as root (the +) when the container ends for any # reason, a runner that could not start included. The container is the # one a small slot of a runner host starts (ci-runner-slot): the host's - # network, where the registry pair answers, and no Docker socket. Its - # _diag is the host's /opt/runner/_diag, which layer 1b reads and which - # a kept instance's disk keeps. + # network, where the registry pair answers, and no Docker socket. It + # mounts no cache: the instance runs this one job and is deleted, so + # nothing is shared between jobs, and what the job installs goes with the + # container. Its only mount, _diag, is the host's /opt/runner/_diag, which + # layer 1b reads and which a kept instance's disk keeps. - path: /etc/systemd/system/plexus-ci-runner.service content: | [Unit] From 9bff651bfc91c615f00918eda18bc719b179f225 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:21:06 +0100 Subject: [PATCH 051/194] fix(actions_runners): small slots share no directory of executables The maintainer's decision: the small jobs (plan, publish, deploy, housekeeping) hold the deploy and publish secrets, so a small slot mounts none of mise's data, state and cache directories, corepack's directory or Playwright's cache. It runs what the image carries, read-only, and installs a repo's pin into its own container, which goes with the job. Medium and large slots, which run test and e2e, share those directories among themselves, a job there able to change what a later one runs: accepted. The pnpm store stays shared by every size, as it was. The slot variables now say what pnpm's documentation says of it: a job that can write the store can alter both the cached files and the hashes pnpm checks them against. Co-Authored-By: Claude Fable 5.2 --- .../roles/actions_runners/defaults/main.yml | 46 +++++++++++++------ .../actions_runners/files/ci-runner-slot | 39 ++++++++++------ .../files/ci-runner/Dockerfile | 12 +++-- 3 files changed, 67 insertions(+), 30 deletions(-) diff --git a/ansible/ci/roles/actions_runners/defaults/main.yml b/ansible/ci/roles/actions_runners/defaults/main.yml index 0a7d8f57..d51baf8e 100644 --- a/ansible/ci/roles/actions_runners/defaults/main.yml +++ b/ansible/ci/roles/actions_runners/defaults/main.yml @@ -18,9 +18,9 @@ # socket, since no job needs a daemon and a socket would be root on this # host, no privileges, and the host's network, so that it reaches the # registry pair on localhost and the overlay's names the host resolves. The -# size decides only the memory limit. Every slot holds the job's secrets in -# flight like any runner: one host serves one tenant and runs nothing else -# (§ 1 PLX-Tenancy). +# size decides the memory limit and which caches the slot shares (below). +# Every slot holds the job's secrets in flight like any runner: one host +# serves one tenant and runs nothing else (§ 1 PLX-Tenancy). # # The host needs Docker before this role (docker). The role opens no # port: the runner polls the forge, and the registry pair listens on loopback. @@ -97,16 +97,36 @@ actions_runners_registry_region: "{{ lookup('env', 'REGISTRY_REGION') | default( actions_runners_registry_access_key: "{{ lookup('env', 'REGISTRY_ACCESS_KEY') | default('', true) }}" actions_runners_registry_secret_key: "{{ lookup('env', 'REGISTRY_SECRET_KEY') | default('', true) }}" -# The caches shared by every slot, bind-mounted into each container -# (ci-runner-slot), each safe for concurrent jobs: the pnpm store -# (content-addressed, files added by atomic rename); mise's data, state and -# cache directories, where a repo's pins the image lacks install, its node -# and its PostgreSQL among them (mise locks a version while it installs it); -# corepack's downloads of the pnpm a repo names (each moved into place whole); -# and Playwright's browsers, whose version follows each repo (Playwright -# locks the directory while it installs). Nothing prunes them: a version no -# repo pins any more stays until removed by hand. Owned by the image's -# runner user. +# The caches the slots share, bind-mounted into their containers +# (ci-runner-slot), each safe for concurrent jobs. A cache one job writes and +# another runs from is a way for the first to plant code in the second, so +# which slots share what follows the secrets their jobs hold (the +# maintainer's decision): +# +# every size the pnpm store (content-addressed, files added by atomic +# rename). pnpm checks a cached file against the hash its +# index records, which catches corruption, not a job that +# rewrites both; its documentation (storeDir, +# verifyStoreIntegrity) keeps a store to mutually trusted +# jobs. So a package a test job altered here can run in a +# small slot's job that installs it: shared all the same, +# as before, and open with the maintainer +# medium, large mise's data, state and cache directories, where a repo's +# pins the image lacks install, its node and its +# PostgreSQL among them (mise locks a version while it +# installs it); corepack's downloads of the pnpm a repo +# names (each moved into place whole); and Playwright's +# browsers, whose version follows each repo (Playwright +# locks the directory while it installs) +# +# A small slot runs plan, publish, deploy and housekeeping, the jobs that +# hold the deploy and publish secrets: it shares none of the second row, runs +# only what the image carries, read-only, and installs a repo's pin it needs +# into its own container, which goes with the job. The medium and large +# slots run test and e2e and share the second row among themselves, a job +# there able to change what a later one runs: accepted, since none of them +# holds those secrets. Nothing prunes the caches: a version no repo pins any +# more stays until removed by hand. Owned by the image's runner user. actions_runners_cache_dir: /var/cache/ci-runner actions_runners_runner_uid: 1001 diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-slot b/ansible/ci/roles/actions_runners/files/ci-runner-slot index ba431b75..460f7628 100755 --- a/ansible/ci/roles/actions_runners/files/ci-runner-slot +++ b/ansible/ci/roles/actions_runners/files/ci-runner-slot @@ -4,14 +4,24 @@ # the same container of the environment image (files/ci-runner): the host's # network (the registry pair and the Connect server on localhost, the # overlay's names), no Docker socket, no privileges, since no job needs a -# Docker daemon; the size is the part of the slot's name before the last -# dash and decides only the memory limit. +# Docker daemon. The size is the part of the slot's name before the last +# dash and decides the memory limit and which caches the container shares, +# bind-mounted from CACHE_DIR: # -# The caches every slot shares, bind-mounted from CACHE_DIR: the pnpm store; -# mise's data, state and cache directories, where a repo's pins install (its -# node, its PostgreSQL), all three so that two jobs installing one version -# wait on mise's own lock; corepack's downloads of pnpm; and Playwright's -# browsers. +# every size the pnpm store +# medium, large also the directories of executables a job installs and +# a later job runs: mise's data, state and cache +# directories, where a repo's pins install (its node, its +# PostgreSQL), all three so that two jobs installing one +# version wait on mise's own lock; corepack's downloads of +# pnpm; and Playwright's browsers +# +# A small slot shares none of those (the maintainer's decision): its jobs, +# plan, publish, deploy and housekeeping, hold the deploy and publish +# secrets, so they run only what the image carries, read-only, and install a +# repo's pin they need into their own container, which goes with the job. +# The medium and large slots run test and e2e, which hold none of those +# secrets and share the installs among themselves. # # From /etc/ci-runner/slot.env: IMAGE and CACHE_DIR; from # /etc/ci-runner/size-.env: MEMORY, the container's limit, empty for @@ -32,12 +42,15 @@ home=/home/runner set -- --rm --init --name "ci-runner-$instance" --network host \ --env-file "/run/ci-runner/$instance.env" \ -e pnpm_config_store_dir=/cache/pnpm-store \ - -v "$CACHE_DIR/pnpm-store:/cache/pnpm-store" \ - -v "$CACHE_DIR/mise/data:$home/.local/share/mise" \ - -v "$CACHE_DIR/mise/state:$home/.local/state/mise" \ - -v "$CACHE_DIR/mise/cache:$home/.cache/mise" \ - -v "$CACHE_DIR/corepack:$home/.cache/node/corepack" \ - -v "$CACHE_DIR/ms-playwright:$home/.cache/ms-playwright" + -v "$CACHE_DIR/pnpm-store:/cache/pnpm-store" +if [ "$size" != small ]; then + set -- "$@" \ + -v "$CACHE_DIR/mise/data:$home/.local/share/mise" \ + -v "$CACHE_DIR/mise/state:$home/.local/state/mise" \ + -v "$CACHE_DIR/mise/cache:$home/.cache/mise" \ + -v "$CACHE_DIR/corepack:$home/.cache/node/corepack" \ + -v "$CACHE_DIR/ms-playwright:$home/.cache/ms-playwright" +fi [ -z "$MEMORY" ] || set -- "$@" --memory "$MEMORY" # The host's Connect server, where the role runs one (/etc/ci-runner/connect.env: # OP_CONNECT_TOKEN and OP_CONNECT_PORT): the job's secret reads go there. diff --git a/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile b/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile index 8542f950..fa398169 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile +++ b/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile @@ -36,9 +36,13 @@ # directory, which mise searches after its data directory, and the shims of # both dispatch by the config of the directory a command runs in. A version # the image lacks installs into mise's directories under ~/.local/share, -# ~/.local/state and ~/.cache, which a runner host shares between its slots, -# all three, so that two jobs installing one version wait on mise's own lock; -# corepack's and Playwright's downloads are shared the same way. +# ~/.local/state and ~/.cache. A runner host shares those between its medium +# and large slots, which run test and e2e, all three, so that two jobs +# installing one version wait on mise's own lock, and corepack's and +# Playwright's downloads the same way. A small slot, whose jobs hold the +# deploy and publish secrets, and an instance, which runs one job, share +# none of them: there the image's own tools run, and a pin they lack installs +# into the container and goes with it (actions_runners' ci-runner-slot). # # mise loads a project's config only under ~/_work, where the runner checks # a job's repo out: mise.toml turns on paranoid mode for config, which ends @@ -50,7 +54,7 @@ # # browsers their version follows each repo's Playwright; a repo installs # them into ~/.cache/ms-playwright, which a runner host shares -# between its slots like mise's data directory +# between its medium and large slots like mise's directories # PostgreSQL its version follows each repo's pin, which mise installs into # its data directory # libvips sharp brings its own; a system libvips at or above the From ec3686af82c986e244391032a8cec5d2966df132 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:30:23 +0100 Subject: [PATCH 052/194] test(actions_runners): a small slot mounts nothing of the host's cache The maintainer's decision: a small slot, whose jobs (plan, publish, deploy, housekeeping) hold the deploy and publish secrets, mounts no directory another job can write, the pnpm store included; medium and large slots mount the pnpm store and the directories of executables they share. tests/runner-slot-mounts.sh runs ci-runner-slot with its paths moved into a directory of its own and a docker stub that prints the arguments, and reads the mounts per size. It fails here: the small slot still mounts the pnpm store. It joins check-ops with the code that makes it pass. Co-Authored-By: Claude Fable 5.2 --- tests/runner-slot-mounts.sh | 56 +++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100755 tests/runner-slot-mounts.sh diff --git a/tests/runner-slot-mounts.sh b/tests/runner-slot-mounts.sh new file mode 100755 index 00000000..974aa6dd --- /dev/null +++ b/tests/runner-slot-mounts.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Fails when a slot's container mounts other than its size allows +# (actions_runners' files/ci-runner-slot): a small slot, whose jobs hold the +# deploy and publish secrets, mounts nothing of the host's cache, the pnpm +# store included; a medium or large slot mounts the pnpm store and the +# directories of executables those sizes share. Runs the script itself, its +# paths moved into a directory of its own and docker replaced by a stub that +# prints the arguments. +set -euo pipefail +cd "$(dirname "$0")/.." + +slot=ansible/ci/roles/actions_runners/files/ci-runner-slot +dir=$(mktemp -d) +trap 'rm -rf "$dir"' EXIT +mkdir "$dir/etc" "$dir/run" +sed -e "s|/etc/ci-runner/|$dir/etc/|g" -e "s|/run/ci-runner/|$dir/run/|g" \ + -e "s|/usr/bin/docker|$dir/docker|g" "$slot" >"$dir/ci-runner-slot" +printf '#!/bin/sh\nprintf "%%s\\n" "$@"\n' >"$dir/docker" +chmod +x "$dir/docker" +printf 'IMAGE=image\nCACHE_DIR=/cache-dir\n' >"$dir/etc/slot.env" + +home=/home/runner +shared="/cache-dir/corepack:$home/.cache/node/corepack +/cache-dir/mise/cache:$home/.cache/mise +/cache-dir/mise/data:$home/.local/share/mise +/cache-dir/mise/state:$home/.local/state/mise +/cache-dir/ms-playwright:$home/.cache/ms-playwright +/cache-dir/pnpm-store:/cache/pnpm-store" + +failed=0 +for size in small medium large; do + printf 'MEMORY=1g\n' >"$dir/etc/size-$size.env" + : >"$dir/run/$size-1.env" + args=$(sh "$dir/ci-runner-slot" "$size-1") + mounts=$(printf '%s\n' "$args" | awk 'prev ~ /^(-v|--volume|--mount)$/ { print } { prev = $0 }' | sort) + if printf '%s\n' "$args" | grep -qE '^--(volume|mount)='; then + echo "✗ a $size slot mounts with a flag this check does not read:" >&2 + printf '%s\n' "$args" | grep -E '^--(volume|mount)=' >&2 + failed=1 + continue + fi + if [ "$size" = small ]; then + if [ -n "$mounts" ] || printf '%s\n' "$args" | grep -q -e /cache-dir -e pnpm_config_store_dir; then + echo "✗ a small slot mounts or names the host's cache:" >&2 + printf '%s\n' "$args" | grep -e /cache-dir -e pnpm_config_store_dir >&2 || true + failed=1 + fi + else + if [ "$mounts" != "$shared" ] || ! printf '%s\n' "$args" | grep -qx pnpm_config_store_dir=/cache/pnpm-store; then + echo "✗ a $size slot mounts other than the shared caches:" >&2 + printf '%s\n' "$mounts" >&2 + failed=1 + fi + fi +done +exit "$failed" From 09c95158a5f4572f4f404c7c5fb042cf43d892c4 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:31:20 +0100 Subject: [PATCH 053/194] fix(actions_runners): a small slot mounts no pnpm store either The maintainer's decision: a small slot, whose jobs (plan, publish, deploy, housekeeping) hold the deploy and publish secrets, mounts no directory another job can write, the pnpm store included. ci-runner-slot now mounts the store, and points pnpm at it, only for medium and large slots, which keep sharing it with mise's, corepack's and Playwright's directories. A small job that installs packages does so into its own container. The role's defaults and the image's header say so; the defaults keep why the store counts as such a directory (pnpm's documentation keeps a store to mutually trusted jobs). tests/runner-slot-mounts.sh joins check-ops. Co-Authored-By: Claude Fable 5.2 --- .../roles/actions_runners/defaults/main.yml | 51 +++++++++---------- .../actions_runners/files/ci-runner-slot | 37 +++++++------- .../files/ci-runner/Dockerfile | 9 ++-- mise.toml | 3 +- 4 files changed, 51 insertions(+), 49 deletions(-) diff --git a/ansible/ci/roles/actions_runners/defaults/main.yml b/ansible/ci/roles/actions_runners/defaults/main.yml index bdf24d99..2bd2e838 100644 --- a/ansible/ci/roles/actions_runners/defaults/main.yml +++ b/ansible/ci/roles/actions_runners/defaults/main.yml @@ -97,36 +97,35 @@ actions_runners_registry_region: "{{ lookup('env', 'REGISTRY_REGION') | default( actions_runners_registry_access_key: "{{ lookup('env', 'REGISTRY_ACCESS_KEY') | default('', true) }}" actions_runners_registry_secret_key: "{{ lookup('env', 'REGISTRY_SECRET_KEY') | default('', true) }}" -# The caches the slots share, bind-mounted into their containers -# (ci-runner-slot), each safe for concurrent jobs. A cache one job writes and -# another runs from is a way for the first to plant code in the second, so -# which slots share what follows the secrets their jobs hold (the -# maintainer's decision): +# The caches the medium and large slots share, bind-mounted into their +# containers (ci-runner-slot), each safe for concurrent jobs: # -# every size the pnpm store (content-addressed, files added by atomic -# rename). pnpm checks a cached file against the hash its -# index records, which catches corruption, not a job that -# rewrites both; its documentation (storeDir, -# verifyStoreIntegrity) keeps a store to mutually trusted -# jobs. So a package a test job altered here can run in a -# small slot's job that installs it: shared all the same, -# as before, and open with the maintainer -# medium, large mise's data, state and cache directories, where a repo's +# pnpm-store the pnpm store, content-addressed, files added by atomic +# rename +# mise mise's data, state and cache directories, where a repo's # pins the image lacks install, its node and its # PostgreSQL among them (mise locks a version while it -# installs it); corepack's downloads of the pnpm a repo -# names (each moved into place whole); and Playwright's -# browsers, whose version follows each repo (Playwright -# locks the directory while it installs) +# installs it) +# corepack corepack's downloads of the pnpm a repo names, each moved +# into place whole +# ms-playwright Playwright's browsers, whose version follows each repo +# (Playwright locks the directory while it installs) # -# A small slot runs plan, publish, deploy and housekeeping, the jobs that -# hold the deploy and publish secrets: it shares none of the second row, runs -# only what the image carries, read-only, and installs a repo's pin it needs -# into its own container, which goes with the job. The medium and large -# slots run test and e2e and share the second row among themselves, a job -# there able to change what a later one runs: accepted, since none of them -# holds those secrets. Nothing prunes the caches: a version no repo pins any -# more stays until removed by hand. Owned by the image's runner user. +# A cache one job writes and another runs from is a way for the first to +# plant code in the second. That holds for the pnpm store too: pnpm checks a +# cached file against the hash its index records, which catches corruption, +# not a job that rewrites both, and its documentation (storeDir, +# verifyStoreIntegrity) keeps a store to mutually trusted jobs. So which +# slots share follows the secrets their jobs hold (the maintainer's +# decision). A small slot runs plan, publish, deploy and housekeeping, the +# jobs that hold the deploy and publish secrets: it mounts none of these, +# runs only what the image carries, read-only, and installs a repo's pin or +# its packages it needs into its own container, which goes with the job. +# The medium and large slots run test and e2e and share all four among +# themselves, a job there able to change what a later one runs: accepted, +# since none of them holds those secrets. Nothing prunes the caches: a +# version no repo pins any more stays until removed by hand. Owned by the +# image's runner user. actions_runners_cache_dir: /var/cache/ci-runner actions_runners_runner_uid: 1001 diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-slot b/ansible/ci/roles/actions_runners/files/ci-runner-slot index 460f7628..8112b63c 100755 --- a/ansible/ci/roles/actions_runners/files/ci-runner-slot +++ b/ansible/ci/roles/actions_runners/files/ci-runner-slot @@ -5,23 +5,24 @@ # network (the registry pair and the Connect server on localhost, the # overlay's names), no Docker socket, no privileges, since no job needs a # Docker daemon. The size is the part of the slot's name before the last -# dash and decides the memory limit and which caches the container shares, -# bind-mounted from CACHE_DIR: +# dash and decides the memory limit and whether the container shares the +# caches, bind-mounted from CACHE_DIR: # -# every size the pnpm store -# medium, large also the directories of executables a job installs and -# a later job runs: mise's data, state and cache -# directories, where a repo's pins install (its node, its -# PostgreSQL), all three so that two jobs installing one -# version wait on mise's own lock; corepack's downloads of -# pnpm; and Playwright's browsers +# small nothing +# medium, large the pnpm store, and the directories of executables a job +# installs and a later job runs: mise's data, state and +# cache directories, where a repo's pins install (its node, +# its PostgreSQL), all three so that two jobs installing +# one version wait on mise's own lock; corepack's downloads +# of pnpm; and Playwright's browsers # -# A small slot shares none of those (the maintainer's decision): its jobs, -# plan, publish, deploy and housekeeping, hold the deploy and publish -# secrets, so they run only what the image carries, read-only, and install a -# repo's pin they need into their own container, which goes with the job. -# The medium and large slots run test and e2e, which hold none of those -# secrets and share the installs among themselves. +# A small slot mounts no directory another job can write (the maintainer's +# decision): its jobs, plan, publish, deploy and housekeeping, hold the +# deploy and publish secrets, so they run only what the image carries, +# read-only, and install a repo's pin or its packages they need into their +# own container, which goes with the job. The medium and large slots run +# test and e2e, which hold none of those secrets, and share the caches among +# themselves (tests/runner-slot-mounts.sh holds the mounts of each size). # # From /etc/ci-runner/slot.env: IMAGE and CACHE_DIR; from # /etc/ci-runner/size-.env: MEMORY, the container's limit, empty for @@ -40,11 +41,11 @@ MEMORY= home=/home/runner set -- --rm --init --name "ci-runner-$instance" --network host \ - --env-file "/run/ci-runner/$instance.env" \ - -e pnpm_config_store_dir=/cache/pnpm-store \ - -v "$CACHE_DIR/pnpm-store:/cache/pnpm-store" + --env-file "/run/ci-runner/$instance.env" if [ "$size" != small ]; then set -- "$@" \ + -e pnpm_config_store_dir=/cache/pnpm-store \ + -v "$CACHE_DIR/pnpm-store:/cache/pnpm-store" \ -v "$CACHE_DIR/mise/data:$home/.local/share/mise" \ -v "$CACHE_DIR/mise/state:$home/.local/state/mise" \ -v "$CACHE_DIR/mise/cache:$home/.cache/mise" \ diff --git a/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile b/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile index fa398169..8fdbd85c 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile +++ b/ansible/ci/roles/actions_runners/files/ci-runner/Dockerfile @@ -39,10 +39,11 @@ # ~/.local/state and ~/.cache. A runner host shares those between its medium # and large slots, which run test and e2e, all three, so that two jobs # installing one version wait on mise's own lock, and corepack's and -# Playwright's downloads the same way. A small slot, whose jobs hold the -# deploy and publish secrets, and an instance, which runs one job, share -# none of them: there the image's own tools run, and a pin they lack installs -# into the container and goes with it (actions_runners' ci-runner-slot). +# Playwright's downloads and the pnpm store the same way. A small slot, +# whose jobs hold the deploy and publish secrets, and an instance, which runs +# one job, share none of them, the pnpm store included: there the image's +# own tools run, and a pin or a package they lack installs into the container +# and goes with it (actions_runners' ci-runner-slot). # # mise loads a project's config only under ~/_work, where the runner checks # a job's repo out: mise.toml turns on paranoid mode for config, which ends diff --git a/mise.toml b/mise.toml index e57d5d5f..1aefa51d 100644 --- a/mise.toml +++ b/mise.toml @@ -125,7 +125,7 @@ fi ''' [tasks.check-ops] -description = "actionlint over the workflows; ansible-lint over the collections (their Galaxy dependencies installed on first use), a syntax check of their playbooks and of a playbook that lists every role; the runner image on the apps' runtime base" +description = "actionlint over the workflows; ansible-lint over the collections (their Galaxy dependencies installed on first use), a syntax check of their playbooks and of a playbook that lists every role; the runner image on the apps' runtime base; what each size of slot mounts" hide = true run = [ 'actionlint', @@ -135,6 +135,7 @@ run = [ 'ansible-playbook --syntax-check -i tests/inventory.yml plexus.platform.playbook plexus.infrastructure.playbook plexus.ci.playbook', './tests/all-roles-listed.sh', './tests/runner-image-base.sh', + './tests/runner-slot-mounts.sh', ] # ANSIBLE_HOME keeps ansible-lint's cache and every collections path inside the # project, so a plexus.* collection installed user-wide (a tenant's pin) never From 39803803f570afacbf1c0495275f4578ef02add0 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:45:44 +0100 Subject: [PATCH 054/194] plx doctor: tests of the five verbs, the leftover verify and the hooks (red) Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/doctor.test.ts | 216 ++++++++++++++++++---- packages/lib/src/testing/doctor-checks.md | 2 +- 2 files changed, 183 insertions(+), 35 deletions(-) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 441b7087..c307d353 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -37,13 +37,23 @@ test('the checks are exactly the requirements the contract pages say doctor chec // --- fixtures: a repo and its apps that pass every check ------------------------- +/** The five repo verbs, as `plx doctor` asks for them. */ +const VERBS = ['dev', 'build', 'check', 'test', 'e2e']; + +/** The hooks of a repo that meets PLX-Repo/Hooks: the commands of each hook's steps. `test` runs `check` first. */ +/** The mise tasks of a repo that has these: `test` runs `check` first, as the templates write it. */ +const tasksOf = (names: string[]) => ({ names, calls: { test: ['check'] } }); + +const HOOKS = { 'pre-commit': ['mise :lint {{ files }}'], 'pre-push': ['mise :test'] }; + const reasoned = (names: string[]) => names.map((n) => `- \`${n}\`: the reason.`).join('\n'); const repo = (over: Partial = {}): RepoFacts => ({ kind: 'repo', path: 'r', marker: { declaration: { deviations: [], body: '' } }, - tasks: { names: ['dev', 'build', 'verify', 'lint', 'check', 'test', 'install'] }, + tasks: tasksOf([...VERBS, 'lint', 'install']), + hk: HOOKS, tracked: ['mise.toml', 'apps/a/docker/compose.yaml'], apps: ['apps/a'], ...over, @@ -106,18 +116,18 @@ const FAILING: Record Facts; problem: 'PLX-Repo/Verbs': { unit: (deviations = []) => repo({ - tasks: { names: ['dev', 'verify', 'lint', 'check', 'test'] }, + tasks: tasksOf(VERBS.filter((v) => v !== 'build')), marker: { declaration: { deviations, body: reasoned(deviations) } }, }), problem: /^no root mise task `build`$/, }, - 'PLX-Repo/SubVerbs': { + 'PLX-Repo/Hooks': { unit: (deviations = []) => repo({ - tasks: { names: ['dev', 'build', 'verify', 'check', 'test'] }, + hk: { ...HOOKS, 'pre-push': ['mise :check'] }, marker: { declaration: { deviations, body: reasoned(deviations) } }, }), - problem: /^no root mise task `lint`$/, + problem: /^the `pre-push` hook does not run `test`$/, }, 'PLX-App/Marker': { unit: (d) => app(undefined, {}, d), @@ -296,6 +306,113 @@ test('mise could not list the tasks: PLX-Repo/Verbs says why, once', () => { ]); }); +// --- the five verbs and the hooks ---------------------------------------------------- + +test('a repo with the five verbs passes, with or without a lint task; each one missing is a finding naming it', () => { + assert.deepEqual(findings(repo({ tasks: tasksOf(VERBS) })), []); + for (const verb of VERBS) + assert.deepEqual(findings(repo({ tasks: tasksOf(VERBS.filter((v) => v !== verb)) })), [ + { requirement: 'PLX-Repo/Verbs', problem: `no root mise task \`${verb}\`` }, + ]); +}); + +test('a leftover verify task is a finding of PLX-Repo/Verbs that names its replacement', () => { + const found = findings(repo({ tasks: tasksOf([...VERBS, 'verify']) })); + assert.equal(found.length, 1); + assert.equal(found[0]?.requirement, 'PLX-Repo/Verbs'); + assert.match(found[0]?.problem ?? '', /^a root mise task `verify` is left over: `check` and `test` replace it/); +}); + +test('PLX-Repo/Hooks: a pre-push hook runs check and test, directly or through a task that runs them', () => { + const push = (commands: string[], calls: Record = {}) => + findings(repo({ hk: { ...HOOKS, 'pre-push': commands }, tasks: { names: VERBS, calls } })).map((f) => f.problem); + assert.deepEqual(push(['mise :check', 'mise :test']), []); + assert.deepEqual(push(['mise :test'], { test: ['check'] }), [], 'test runs check first'); + assert.deepEqual(push(['mise run test'], { test: ['check'] }), [], 'in either spelling'); + assert.deepEqual(push(['mise :check']), ['the `pre-push` hook does not run `test`']); + assert.deepEqual(push(['mise :test']), ['the `pre-push` hook does not run `check`'], 'a test that does not check'); + assert.deepEqual(push(['mise :lint']), [ + 'the `pre-push` hook does not run `check`', + 'the `pre-push` hook does not run `test`', + ]); + assert.deepEqual(push(['mise :gates'], { gates: ['check', 'test'] }), [], 'through a task of the repo'); + assert.deepEqual(push(['mise :a'], { a: ['b'], b: ['a'] }), [ + 'the `pre-push` hook does not run `check`', + 'the `pre-push` hook does not run `test`', + ]); +}); + +test('PLX-Repo/Hooks: a pre-commit hook is required, and what it runs is not read', () => { + assert.deepEqual( + findings(repo({ hk: { 'pre-push': HOOKS['pre-push'] } })).map((f) => f.problem), + ['hk.pkl wires no `pre-commit` hook'], + ); + assert.deepEqual(findings(repo({ hk: { ...HOOKS, 'pre-commit': [] } })), []); +}); + +test('PLX-Repo/Hooks: no hk.pkl, and no pre-push hook, are findings', () => { + const { hk: _, ...bare } = repo(); + assert.deepEqual( + findings(bare).map((f) => f.problem), + ['no hk.pkl, which wires the git hooks'], + ); + assert.deepEqual( + findings(repo({ hk: { 'pre-commit': [] } })).map((f) => f.problem), + ['hk.pkl wires no `pre-push` hook'], + ); +}); + +/** The findings of the repo at /ws/web whose hk.pkl and `test` task are as given. */ +async function hooksOver(pkl: string | undefined, testRuns = 'mise run check\nturbo run test') { + const tree = ws(); + const web = tree.web as Tree; + if (pkl === undefined) delete web['hk.pkl']; + else web['hk.pkl'] = pkl; + const task = (name: string) => ({ + name: `//:${name}`, + source: '/ws/web/mise.toml', + global: false, + ...(name === 'test' ? { run: [testRuns] } : {}), + }); + const git = (cwd: string, args: string[]) => (args[0] === 'ls-files' && cwd === '/ws/web' ? '' : undefined); + const ctx = new Context({}, fakeIo(tree, git, { mise: () => JSON.stringify(ALL_TASKS.map(task)) })); + return diagnose((await examine(ctx, '/ws/web')).facts).units[0]?.findings.map((f) => f.problem); +} + +const PKL = (push: string, commit = 'mise :lint {{ files }}') => `amends "package://example.org/hk@1/Config.pkl" + +hooks { + ["pre-commit"] { + fix = true + steps { + ["lint"] { + check = "${commit}" + fix = "mise :lint --write {{ files }}" + } + } + } + ["pre-push"] { + steps { + ["test"] { + check = "${push}" + } + } + } +} +`; + +test('doctor reads the hooks from hk.pkl and what a task runs from mise', async () => { + assert.deepEqual(await hooksOver(PKL('mise :test')), [], 'the template: pre-push runs test, which runs check'); + assert.deepEqual(await hooksOver(PKL('mise :test'), 'turbo run test'), ['the `pre-push` hook does not run `check`']); + assert.deepEqual(await hooksOver(PKL('mise :check')), ['the `pre-push` hook does not run `test`']); + assert.deepEqual(await hooksOver(undefined), ['no hk.pkl, which wires the git hooks']); + assert.deepEqual(await hooksOver(PKL('mise :test').replace('["pre-commit"]', '["commit-msg"]')), [ + 'hk.pkl wires no `pre-commit` hook', + ]); + // A brace inside a command does not end its block. + assert.deepEqual(await hooksOver(PKL('echo } && mise :test', 'echo { }')), []); +}); + // --- compose's spellings ----------------------------------------------------------- const appOf = (text: string, profile = 'stateless') => app(profile, { compose: parseCompose(text, 'c') }); @@ -623,17 +740,46 @@ const miseTasks = const names = own[cwd]; if (!names) return undefined; return JSON.stringify([ - ...names.map((n) => ({ name: `//:${n}`, source: `${cwd}/mise.toml`, global: false })), + // `test` runs `check` first, as the templates write it. + ...names.map((n) => ({ + name: `//:${n}`, + source: `${cwd}/mise.toml`, + global: false, + ...(n === 'test' ? { run: ['mise run check\nturbo run test'] } : {}), + })), { name: 'pull', source: '/ws/mise.toml', global: false }, { name: 'fmt', source: '/home/.config/mise/config.toml', global: true }, ]); }; +/** The hk.pkl of the fixture repos: a pre-commit hook, and a pre-push hook that runs both gates. */ +const HK = `hooks { + ["pre-commit"] { + steps { + ["lint"] { + check = "mise :lint {{ files }}" + } + } + } + ["pre-push"] { + steps { + ["check"] { + check = "mise :check" + } + ["test"] { + check = "mise :test" + } + } + } +} +`; + const ws = (): Tree => ({ 'mise.toml': '', web: { '.git': {}, 'PLEXUS.md': MARKER, + 'hk.pkl': HK, 'mise.toml': '', apps: { site: { @@ -649,6 +795,7 @@ const ws = (): Tree => ({ 'PLEXUS.md': '---\nversion: 0.1.0\ntemplates: [repo-operations]\ntenant: acme\ndeviations: [PLX-Repo/SubVerbs]\n---\n\n- `PLX-Repo/SubVerbs`: the playbooks are checked by `check`.\n', 'mise.toml': '[tools]\n"npm:@plexus-ms/cli" = "0.1.0"\n', + 'hk.pkl': HK, apps: { id: { 'PLEXUS.md': '---\nprofile: stateful\n---\n', @@ -660,12 +807,13 @@ const ws = (): Tree => ({ }, }); -const VERBS = ['dev', 'build', 'verify', 'lint', 'check', 'test']; +/** What mise lists of a repo whose five verbs and lint exist. */ +const ALL_TASKS = [...VERBS, 'lint']; async function doctorOver( tree: Tree, root: string, - webTasks: string[] = VERBS, + webTasks: string[] = ALL_TASKS, tracked: Record = {}, around: Tree = {}, plx?: string, @@ -673,7 +821,7 @@ async function doctorOver( const files: Record = { '/ws/web': ['PLEXUS.md', 'apps/site/docker/compose.yaml'], ...tracked }; const git = (cwd: string, args: string[]) => args[0] === 'ls-files' && files[cwd] ? files[cwd].map((f) => `${f}\0`).join('') : undefined; - const mise = miseTasks({ '/ws/web': webTasks, '/ws/ops': ['dev', 'build', 'verify', 'check', 'test'] }); + const mise = miseTasks({ '/ws/web': webTasks, '/ws/ops': VERBS }); const ctx = new Context({}, fakeIo({ ...around, ws: tree }, git, { mise: (cwd) => mise(cwd) })); const { facts, ...examined } = await examine(ctx, root, plx); return { ...examined, facts, ...diagnose(facts) }; @@ -683,7 +831,7 @@ const requirements = (report: Awaited>) => report.units.map((u) => [u.path, u.kind, u.findings.map((f) => f.requirement)]); test('doctor in a repo fails on a missing build task and passes once it exists', async () => { - const verbs = ['dev', 'verify', 'lint', 'check', 'test']; + const verbs = ALL_TASKS.filter((v) => v !== 'build'); const before = await doctorOver(ws(), '/ws/web', verbs); assert.deepEqual( before.units.map((u) => [u.path, u.kind, u.findings]), @@ -719,7 +867,7 @@ test('a repo that has not crossed over is judged by the plx it pins: what needs const tree = ws(); // Its markers say nothing yet, so this plx cannot tell the operations repo from another, and its app is third-party or built. (tree.ops as Tree)['PLEXUS.md'] = '---\n---\n\n- Third-party apps.\n'; - const report = await doctorOver(tree, '/ws/ops', VERBS, { '/ws/ops': ['PLEXUS.md', '.copier-answers.yml'] }); + const report = await doctorOver(tree, '/ws/ops', ALL_TASKS, { '/ws/ops': ['PLEXUS.md', '.copier-answers.yml'] }); const [repo, app] = report.units; assert.deepEqual( app?.findings.map((f) => f.requirement), @@ -727,7 +875,7 @@ test('a repo that has not crossed over is judged by the plx it pins: what needs 'no PLX-App/ImageRef or PLX-App/Dockerfile: the app may be third-party', ); assert.match(repo?.hints?.join('\n') ?? '', /has not crossed over.*judged by the plx it pins/); - const crossed = await doctorOver(tree, '/ws/ops', VERBS, { '/ws/ops': ['PLEXUS.md'] }); + const crossed = await doctorOver(tree, '/ws/ops', ALL_TASKS, { '/ws/ops': ['PLEXUS.md'] }); assert.ok( crossed.units[1]?.findings.some((f) => f.requirement === 'PLX-App/ImageRef'), 'a crossed-over repo is judged', @@ -828,14 +976,14 @@ test('(e) git roots beneath make a workspace, whatever lies above; with none ben const around: Tree = { '.git': {} }; const tree = ws(); tree.notes = { 'todo.md': '- write it down\n' }; - const workspace = await doctorOver(tree, '/ws', VERBS, {}, around); + const workspace = await doctorOver(tree, '/ws', ALL_TASKS, {}, around); assert.equal(workspace.inRepo, false); assert.equal(workspace.root, '/ws'); assert.deepEqual( workspace.units.map((u) => u.path), ['ops', 'ops/apps/id', 'web', 'web/apps/site'], ); - const inside = await doctorOver(tree, '/ws/notes', VERBS, {}, around); + const inside = await doctorOver(tree, '/ws/notes', ALL_TASKS, {}, around); assert.equal(inside.inRepo, true, 'nothing beneath: the directory is part of the repo above'); assert.equal(inside.root, '/'); }); @@ -900,10 +1048,10 @@ test('(h) a symlinked directory in apps/ and a symlinked repo are not followed, const apps = webOf(tree).apps as Tree; apps.shared = link('/elsewhere/app'); apps['notes.txt'] = link('/elsewhere/file.txt'); - const workspace = await doctorOver(tree, '/ws', VERBS, {}, around); + const workspace = await doctorOver(tree, '/ws', ALL_TASKS, {}, around); assert.deepEqual(workspace.links, ['mirror', 'web/apps/shared'], 'a link to a plain directory or a file is no unit'); assert.ok(!workspace.units.some((u) => u.path.startsWith('mirror') || u.path === 'web/apps/shared')); - const repo = await doctorOver(tree, '/ws/web', VERBS, {}, around); + const repo = await doctorOver(tree, '/ws/web', ALL_TASKS, {}, around); assert.deepEqual(repo.links, ['apps/shared']); }); @@ -957,7 +1105,7 @@ test("a task's alias counts as the task, as `mise run` finds it", async () => { JSON.stringify([ task('//:dev'), task('//:build'), - task('//:verify'), + task('//:e2e'), task('//:test'), task('//:static', ['//:check']), task('biome', ['lint']), @@ -975,20 +1123,20 @@ test("a task from a file the repo includes from outside counts by its `dir`; a p JSON.stringify([ task('dev', '/ws/web/mise.toml', '/ws/web'), task('build', '/shared/tasks.toml', '/ws/web'), - task('verify', '/ws/web/../shared/more.toml', '/ws/web'), + task('e2e', '/ws/web/../shared/more.toml', '/ws/web'), task('lint', '/ws/web/mise/tasks.toml', '/elsewhere'), task('check', '/ws/mise.toml', '/ws'), task('test', '/ws/web/../mise.toml', '/ws'), ]), ); assert.deepEqual(report.units[0]?.findings, [ - { requirement: 'PLX-Repo/SubVerbs', problem: 'no root mise task `check`' }, - { requirement: 'PLX-Repo/SubVerbs', problem: 'no root mise task `test`' }, + { requirement: 'PLX-Repo/Verbs', problem: 'no root mise task `check`' }, + { requirement: 'PLX-Repo/Verbs', problem: 'no root mise task `test`' }, ]); }); test('a task list without `source` fails with one clear message, not every task missing', async () => { - const report = await withMise(() => JSON.stringify(VERBS.map((name) => ({ name, global: false })))); + const report = await withMise(() => JSON.stringify(ALL_TASKS.map((name) => ({ name, global: false })))); assert.deepEqual(report.units[0]?.findings, [ { requirement: 'PLX-Repo/Verbs', @@ -1146,7 +1294,7 @@ test('doctor reads the plx pin and the tracked markers, and fails the repo for e const site = (web.apps as Tree).site as Tree; site['PLEXUS.md'] = '---\nprofile: stateless\nversion: 0.131.0\n---\n'; const tracked = { '/ws/web': ['PLEXUS.md', 'mise.toml', 'apps/site/PLEXUS.md', 'apps/site/docker/compose.yaml'] }; - const report = await doctorOver(tree, '/ws/web', VERBS, tracked); + const report = await doctorOver(tree, '/ws/web', ALL_TASKS, tracked); assert.deepEqual( report.units.map((u) => [u.path, u.findings]), [ @@ -1180,7 +1328,7 @@ test('a repo whose root marker lists the operations template, with no answers fi (tree.web as Tree)['PLEXUS.md'] = '---\nversion: 0.131.0\ntemplates: [repo-operations]\n---\n'; (tree.web as Tree)['mise.toml'] = '[tools]\n"npm:@plexus-ms/cli" = "0.131.0"\n'; const tracked = { '/ws/web': ['PLEXUS.md', 'mise.toml', 'apps/site/docker/compose.yaml'] }; - const report = await doctorOver(tree, '/ws/web', VERBS, tracked); + const report = await doctorOver(tree, '/ws/web', ALL_TASKS, tracked); assert.deepEqual( report.units.map((u) => [u.path, u.kind]), [ @@ -1197,7 +1345,7 @@ test('a tracked marker that cannot be read is a finding of its repo and stops no return tree; }; const tracked = { '/ws/web': ['PLEXUS.md', 'apps/x/PLEXUS.md', 'apps/site/docker/compose.yaml'] }; - const report = await doctorOver(broken(), '/ws', VERBS, tracked); + const report = await doctorOver(broken(), '/ws', ALL_TASKS, tracked); assert.deepEqual( report.units.filter((u) => u.kind !== 'app').map((u) => [u.path, u.findings.map((f) => f.problem)]), [ @@ -1206,7 +1354,7 @@ test('a tracked marker that cannot be read is a finding of its repo and stops no ], ); const onCopier = { '/ws/web': [...(tracked['/ws/web'] ?? []), '.copier-answers.yml'] }; - const skipped = await doctorOver(broken(), '/ws/web', VERBS, onCopier); + const skipped = await doctorOver(broken(), '/ws/web', ALL_TASKS, onCopier); assert.deepEqual(skipped.units[0]?.findings, []); }); @@ -1237,7 +1385,7 @@ test('doctor reads which tracked files hold a conflict marker, and fails the rep if (args[0] === 'grep') return 'mise.toml\0'; return undefined; }; - const mise = miseTasks({ '/ws/web': VERBS }); + const mise = miseTasks({ '/ws/web': ALL_TASKS }); const ctx = new Context({}, fakeIo({ ws: tree }, git, { mise: (cwd) => mise(cwd) })); const { facts } = await examine(ctx, '/ws/web'); const report = diagnose(facts); @@ -1456,7 +1604,7 @@ test('doctor reads the templates this plx bundles from disk and runs the marker '---\nversion: 0.131.0\ntemplates: [repo-turbo, ghost]\ntenant: plexus\nci_strategy: cloud\nstray: 1\n---\n'; web['mise.toml'] = '[tools]\n"npm:@plexus-ms/cli" = "0.131.0"\n'; const tracked = { '/ws/web': ['PLEXUS.md', 'mise.toml', 'apps/site/docker/compose.yaml'] }; - const report = await doctorOver(tree, '/ws/web', VERBS, tracked); + const report = await doctorOver(tree, '/ws/web', ALL_TASKS, tracked); const problems = report.units[0]?.findings.map((f) => f.problem) ?? []; assert.ok( problems.some((p) => p?.includes('`templates` names `ghost`, which this plx does not bundle')), @@ -1475,7 +1623,7 @@ test('doctor reads the templates this plx bundles from disk and runs the marker const turboMarker = (answers: string) => marked(`---\nversion: 0.130.0\ntemplates: [repo-turbo]\ntenant: plexus\n${answers}---\n`); const problemsOf = async (tree: Tree) => - (await doctorOver(tree, '/ws/web', VERBS, CROSSED, {}, '0.130.0')).units[0]?.findings.map((f) => f.problem); + (await doctorOver(tree, '/ws/web', ALL_TASKS, CROSSED, {}, '0.130.0')).units[0]?.findings.map((f) => f.problem); test("repo-turbo's major is a question of a repo with display versions, and a number", async () => { assert.deepEqual(await problemsOf(turboMarker('display_versions: true\nmajor: 1\n')), []); @@ -1511,12 +1659,12 @@ const marked = (marker: string) => { const BROKEN = '---\nversion: 0.130.0\ntemplates: [repo-turbo, ghost]\ntenant: plexus\nstray: 1\n---\n'; test("the marker checks against the templates run where the running plx is the root marker's version", async () => { - const report = await doctorOver(marked(BROKEN), '/ws/web', VERBS, CROSSED, {}, '0.130.0'); + const report = await doctorOver(marked(BROKEN), '/ws/web', ALL_TASKS, CROSSED, {}, '0.130.0'); assert.ok(report.units[0]?.findings.some((f) => f.problem?.includes('`stray` is neither reserved'))); }); test("they are skipped, and a line says so, where the running plx is not the root marker's version", async () => { - const report = await doctorOver(marked(BROKEN), '/ws/web', VERBS, CROSSED, {}, '0.131.0'); + const report = await doctorOver(marked(BROKEN), '/ws/web', ALL_TASKS, CROSSED, {}, '0.131.0'); assert.deepEqual(report.units[0]?.findings, []); assert.deepEqual(report.units[0]?.hints, [ 'the markers are not checked against the templates: this plx is 0.131.0, the root marker names version 0.130.0; run the plx that version pins', @@ -1524,7 +1672,7 @@ test("they are skipped, and a line says so, where the running plx is not the roo const unset = await doctorOver( marked('---\ntemplates: [repo-turbo]\n---\n'), '/ws/web', - VERBS, + ALL_TASKS, CROSSED, {}, '0.131.0', @@ -1535,10 +1683,10 @@ test("they are skipped, and a line says so, where the running plx is not the roo }); test('the bundled templates are read only for a repo in which a marker lists templates', async () => { - const listing = await doctorOver(marked(BROKEN), '/ws/web', VERBS, CROSSED, {}, '0.130.0'); + const listing = await doctorOver(marked(BROKEN), '/ws/web', ALL_TASKS, CROSSED, {}, '0.130.0'); assert.ok((listing.facts[0] as RepoFacts).templates); for (const marker of ['---\nversion: 0.130.0\n---\n', '---\nversion: 0.130.0\ntemplates: []\n---\n']) { - const report = await doctorOver(marked(marker), '/ws/web', VERBS, CROSSED, {}, '0.130.0'); + const report = await doctorOver(marked(marker), '/ws/web', ALL_TASKS, CROSSED, {}, '0.130.0'); const facts = report.facts[0] as RepoFacts; assert.equal(facts.templates, undefined, marker); assert.equal(facts.rootAnswers, undefined, marker); @@ -1547,7 +1695,7 @@ test('the bundled templates are read only for a repo in which a marker lists tem test("the root marker's resolved answers, defaults included, are read from the templates", async () => { const valid = marked('---\nversion: 0.130.0\ntemplates: [repo-turbo]\ntenant: plexus\n---\n'); - const report = await doctorOver(valid, '/ws/web', VERBS, CROSSED, {}, '0.130.0'); + const report = await doctorOver(valid, '/ws/web', ALL_TASKS, CROSSED, {}, '0.130.0'); assert.equal((report.facts[0] as RepoFacts).rootAnswers?.ci_strategy, 'github'); }); diff --git a/packages/lib/src/testing/doctor-checks.md b/packages/lib/src/testing/doctor-checks.md index 73d0123b..87827db6 100644 --- a/packages/lib/src/testing/doctor-checks.md +++ b/packages/lib/src/testing/doctor-checks.md @@ -8,7 +8,7 @@ set to a compendium checkout it reads the pages themselves instead. `plx doctor` checks `PLX-Repo/Marker`. -`plx doctor` checks of `PLX-Repo/Verbs` that `dev`, `build` and `verify` exist as root mise tasks, and of `PLX-Repo/SubVerbs` that `lint`, `check`, `test` and `verify` do, not what they run, in which order, or whether they pass. +`plx doctor` checks of `PLX-Repo/Verbs` that `dev`, `build`, `check`, `test` and `e2e` exist as root mise tasks and that no `verify` is left, not what they run, in which order, or whether they pass, and of `PLX-Repo/Hooks` that `hk.pkl` wires a pre-commit hook and a pre-push hook that runs `check` and `test`, not what the pre-commit hook runs. `plx doctor` checks `PLX-App/Marker`. From aeaa6d624becaa552da91fc91aae1d0f10411635 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:47:03 +0100 Subject: [PATCH 055/194] a newborn repo-turbo repo passes the doctor as born, with no stub task (red) Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/doctor.test.ts | 2 +- packages/lib/src/newSite.test.ts | 11 ++++------- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index c307d353..fcb25de9 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -375,7 +375,7 @@ async function hooksOver(pkl: string | undefined, testRuns = 'mise run check\ntu ...(name === 'test' ? { run: [testRuns] } : {}), }); const git = (cwd: string, args: string[]) => (args[0] === 'ls-files' && cwd === '/ws/web' ? '' : undefined); - const ctx = new Context({}, fakeIo(tree, git, { mise: () => JSON.stringify(ALL_TASKS.map(task)) })); + const ctx = new Context({}, fakeIo({ ws: tree }, git, { mise: () => JSON.stringify(ALL_TASKS.map(task)) })); return diagnose((await examine(ctx, '/ws/web')).facts).units[0]?.findings.map((f) => f.problem); } diff --git a/packages/lib/src/newSite.test.ts b/packages/lib/src/newSite.test.ts index bce5c9e3..516795c6 100644 --- a/packages/lib/src/newSite.test.ts +++ b/packages/lib/src/newSite.test.ts @@ -9,7 +9,6 @@ import { join } from 'node:path'; import { PassThrough } from 'node:stream'; import { after, test } from 'node:test'; import { apply, Context, diagnose, examine, newSite, realIo, templatesRoot } from './index.ts'; -import { WAITING_FOR_DOCTOR } from './testing/shapes.ts'; import { git, quietContext, repoWith, scratchDir, templatesAt, text, write } from './testing/siteRepo.ts'; const scratch = scratchDir('new'); @@ -390,8 +389,6 @@ test('a repo from repo-turbo with updates beside it and an app from app-nextjs i // The doctor reads what git tracks, and lists the tasks of a mise.toml that `mise trust` (faked above) would have trusted. process.env.MISE_TRUSTED_CONFIG_PATHS = target; try { - // The doctor still wants a `verify` task, which repo-turbo no longer has: it finds that and nothing else. - appendFileSync(join(target, 'mise.toml'), WAITING_FOR_DOCTOR.task); git(target, 'add', '-A'); const { facts } = await examine(new Context({}, realIo()), target, bundled.version); const report = diagnose(facts); @@ -683,12 +680,12 @@ test('a repo made from app-nextjs alone, with the tenant it reads, raises no fin git(target, 'add', '-A'); const { facts } = await examine(new Context({}, realIo()), target, bundled.version); const report = diagnose(facts); - // Such a repo has no mise.toml, so the repo contract's checks fail; what is pinned is that the marker's - // keys, the read `tenant` among them, raise no finding against the templates. + // Such a repo has no mise.toml and no hk.pkl, so the repo contract's checks fail; what is pinned is that the + // marker's keys, the read `tenant` among them, raise no finding against the templates. const problems = report.units.flatMap((u) => u.findings.map((f) => f.problem)); - assert.ok(problems.length > 0, 'the repo contract finds the missing mise.toml'); + assert.ok(problems.length > 0, 'the repo contract finds the missing mise.toml and hk.pkl'); assert.deepEqual( - problems.filter((p) => !/mise|plx/.test(p)), + problems.filter((p) => !/mise|plx|hk\.pkl/.test(p)), [], ); assert.equal(report.units.length, 1); From 66367422a75976ca0927f0b7690aadb8e43bb6f8 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:47:21 +0100 Subject: [PATCH 056/194] plx doctor: the five verbs, a leftover verify, and PLX-Repo/Hooks PLX-Repo/SubVerbs has no check any more: there is no verify to be made of parts, and the order of the gates is kept by the tasks. Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/doctor.ts | 127 ++++++++++++++++++++++++++----- packages/lib/src/newSite.test.ts | 2 +- 2 files changed, 108 insertions(+), 21 deletions(-) diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index dd29b255..55a917b5 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -10,8 +10,8 @@ // checks …", § 1.3 PLX), and a test holds the two equal. // // The checks are static: they read the marker, `docker/compose.yaml`, the -// task list as mise reports it, an app's `package.json`, and git's list of -// tracked files. They never reach a host or a running app, and need no +// task list as mise reports it, the hooks of `hk.pkl`, an app's `package.json`, +// and git's list of tracked files. They never reach a host or a running app, and need no // compendium: the requirement names a deviation may list come from the index // this plx carries (standardIndex.ts). A deviation the marker lists silences // its check; a deviation without a reason in the marker's body, or naming no @@ -56,6 +56,20 @@ // apply` renders; otherwise the three are skipped and a hint says why (the // version against the pin is reported beside, as before). // +// The repo's verbs are the five of VERBS, root mise tasks: PLX-Repo/Verbs +// reports each that is missing, and a task `verify`, which no repo has any +// more, with the tasks that replace it. The order of the gates (`check`, +// `test`, `build`, `e2e`) is kept by the tasks, not by a requirement, so +// nothing reads what a task runs, except for PLX-Repo/Hooks: the hooks are +// read from the `hooks` block of `hk.pkl` as a repo's template writes it +// (hookCommands), the `check` command of every step of a hook, and a hook runs +// a task when a command names it (`mise :t`, `mise run t`) or a task it names +// runs it, by `depends` or by a `mise` line of its `run` (taskCalls). That +// lets the pre-push hook of a repo whose `test` runs `check` first run `test` +// alone. Which hook steps run, with which files, is hk's business; the check +// asks that a pre-commit hook is wired and that the pre-push hook reaches +// `check` and `test`. +// // plx doctor # this repo and its apps, from anywhere inside it // plx doctor ~/dev # every Plexus repo beneath, and its apps import { readdir, realpath } from 'node:fs/promises'; @@ -102,8 +116,10 @@ export interface RepoFacts { path: string; /** Undefined when the repo carries no marker. */ marker?: MarkerRead; - /** The root mise tasks, or why mise could not list them. */ - tasks: { names: string[] } | { problem: string }; + /** The root mise tasks, with the tasks each depends on or runs, or why mise could not list them. */ + tasks: { names: string[]; calls?: Record } | { problem: string }; + /** The `check` commands of the steps of each hook of `hk.pkl`, by hook; undefined where there is no `hk.pkl`. */ + hk?: Record; /** The files git tracks, relative to the repo; undefined outside a git checkout. */ tracked?: string[]; /** The tracked files that hold a conflict marker, relative to the repo. */ @@ -152,28 +168,55 @@ export type Facts = RepoFacts | AppFacts; // // Each returns what is wrong, one line per problem; an empty list passes. -const ROOT_VERBS = ['dev', 'build', 'verify']; -const SUB_VERBS = ['lint', 'check', 'test', 'verify']; +/** The repo verbs, in the order of the gates: one list for the check and for anything that names them. */ +export const VERBS = ['dev', 'build', 'check', 'test', 'e2e'] as const; + +/** The two verbs the pre-push hook must reach. */ +const GATES = ['check', 'test']; function repoMarker(repo: RepoFacts): string[] { if (!repo.marker) return [`no ${MARKER_FILE} at the repo's root`]; return repo.marker.problem ? [repo.marker.problem] : []; } -const missingTasks = (repo: RepoFacts, wanted: string[]): string[] => - 'names' in repo.tasks - ? wanted - .filter((t) => !(repo.tasks as { names: string[] }).names.includes(t)) - .map((t) => `no root mise task \`${t}\``) - : []; - function verbs(repo: RepoFacts): string[] { if ('problem' in repo.tasks) return [`mise could not list the tasks: ${repo.tasks.problem}`]; - return missingTasks(repo, ROOT_VERBS); + const { names } = repo.tasks; + return [ + ...VERBS.filter((verb) => !names.includes(verb)).map((verb) => `no root mise task \`${verb}\``), + ...(names.includes('verify') + ? ['a root mise task `verify` is left over: `check` and `test` replace it, `mise test` running `check` first'] + : []), + ]; } -/** Existence only: what `verify` runs, in which order, and what `check` includes is not read (see the report). */ -const subVerbs = (repo: RepoFacts): string[] => missingTasks(repo, SUB_VERBS); +/** The tasks a shell command names: `mise :t`, `mise t`, `mise run t`. */ +const tasksNamed = (command: string): string[] => + [...command.matchAll(/(?:^|[\s;&|(])mise\s+(?:run\s+)?:?([A-Za-z][\w:-]*)/g)].map((m) => m[1] ?? ''); + +/** Existence only: the commands of each hook are read to find the tasks it reaches, not to judge them. */ +function hooks(repo: RepoFacts): string[] { + const { hk } = repo; + if (!hk) return ['no hk.pkl, which wires the git hooks']; + const problems: string[] = []; + if (!hk['pre-commit']) problems.push('hk.pkl wires no `pre-commit` hook'); + const push = hk['pre-push']; + if (!push) return [...problems, 'hk.pkl wires no `pre-push` hook']; + // Which tasks a hook reaches is unknown while mise cannot list them, which PLX-Repo/Verbs reports. + if ('problem' in repo.tasks) return problems; + const calls = repo.tasks.calls ?? {}; + const reached = new Set(); + const queue = push.flatMap(tasksNamed); + for (let task = queue.pop(); task !== undefined; task = queue.pop()) + if (!reached.has(task)) { + reached.add(task); + queue.push(...(calls[task] ?? [])); + } + return [ + ...problems, + ...GATES.filter((g) => !reached.has(g)).map((g) => `the \`pre-push\` hook does not run \`${g}\``), + ]; +} function appMarker(app: AppFacts): string[] { const { declaration, problem } = app.marker; @@ -369,7 +412,7 @@ interface AppCheck { export const CHECKS: Readonly> = { 'PLX-Repo/Marker': { binds: 'repo', check: repoMarker }, 'PLX-Repo/Verbs': { binds: 'repo', check: verbs }, - 'PLX-Repo/SubVerbs': { binds: 'repo', check: subVerbs }, + 'PLX-Repo/Hooks': { binds: 'repo', check: hooks }, 'PLX-App/Marker': { binds: 'app', check: appMarker }, 'PLX-App/Compose': { binds: 'app', check: composeFile }, 'PLX-App/TenantLabel': { binds: 'app', check: onCompose(tenantLabel) }, @@ -648,6 +691,7 @@ async function readRepo( plxVersion?: string, ): Promise { const marker = markerOf(dir); + const hk = await ctx.readFile(join(dir.path, 'hk.pkl')).then(hookCommands, () => undefined); const tracked = await ctx .read('git', ['ls-files', '-z'], { cwd: dir.path }) .then((out) => out.split('\0').filter(Boolean)) @@ -663,6 +707,7 @@ async function readRepo( path, ...(marker ? { marker } : {}), tasks: await rootTasks(ctx, dir.path), + ...(hk ? { hk } : {}), tracked, ...(conflicted?.length ? { conflicted } : {}), apps: [], @@ -725,6 +770,40 @@ async function readSites(ctx: Context, repo: string): Promise { + const start = /^hooks\s*\{/m.exec(pkl); + if (!start) return {}; + const open = start.index + start[0].length - 1; + const body = pkl.slice(open + 1, closing(pkl, open)); + const found: Record = {}; + const hook = /\[\s*"([^"]+)"\s*\]\s*\{/g; + for (let at = hook.exec(body); at; at = hook.exec(body)) { + const from = at.index + at[0].length - 1; + const end = closing(body, from); + found[at[1] ?? ''] = [...body.slice(from, end).matchAll(/\bcheck\s*=\s*"((?:[^"\\]|\\.)*)"/g)].map( + (m) => m[1] ?? '', + ); + hook.lastIndex = end; + } + return found; +} + /** * The repo's root mise tasks, hidden ones included, as mise lists them, so * that tasks from every file mise reads count; a task counts under its name @@ -769,18 +848,26 @@ async function rootTasks(ctx: Context, repo: string): Promise = {}; + const bare = (name: string) => (name.startsWith('//:') ? name.slice(3) : name); for (const task of listed) { if (!isOwn(task)) continue; + const runs = (Array.isArray(task.run) ? task.run : []).flatMap((r: unknown) => + typeof r === 'string' ? tasksNamed(r) : isMapping(r) && typeof r.task === 'string' ? [r.task] : [], + ); + const depends = (Array.isArray(task.depends) ? task.depends : []).filter((d: unknown) => typeof d === 'string'); const aliases = Array.isArray(task.aliases) ? task.aliases.filter((a: unknown): a is string => typeof a === 'string') : []; for (const name of [task.name as string, ...aliases]) { // A monorepo root names its own tasks `//:`; `//:` is a sub-project's. - if (name.startsWith('//:')) names.push(name.slice(3)); - else if (!name.startsWith('//')) names.push(name); + if (name.startsWith('//:') || !name.startsWith('//')) { + names.push(bare(name)); + calls[bare(name)] = [...depends, ...runs].map(bare); + } } } - return { names }; + return { names, calls }; } async function readApp(ctx: Context, dir: Directory, path: string, inRepo: string, repo: RepoFacts): Promise { diff --git a/packages/lib/src/newSite.test.ts b/packages/lib/src/newSite.test.ts index 516795c6..2d99bf7f 100644 --- a/packages/lib/src/newSite.test.ts +++ b/packages/lib/src/newSite.test.ts @@ -3,7 +3,7 @@ // through the Context's injected Io, which here records them and runs nothing; // git, which the verb reads the enclosing repo with, goes to the real one. import assert from 'node:assert/strict'; -import { appendFileSync, chmodSync, existsSync, mkdirSync } from 'node:fs'; +import { chmodSync, existsSync, mkdirSync } from 'node:fs'; import { createRequire } from 'node:module'; import { join } from 'node:path'; import { PassThrough } from 'node:stream'; From 6d2811f59edb10601b2a816de945c528bb23d132 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:48:00 +0100 Subject: [PATCH 057/194] the helpers that read a rendered mise.toml move to testing/bundled.ts, for both repo templates Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/repoTurbo.test.ts | 15 +-------------- packages/lib/src/testing/bundled.ts | 13 +++++++++++++ 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index 95e78a23..321734d6 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -3,7 +3,7 @@ import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { test } from 'node:test'; import { templatesRoot } from './templatesRoot.ts'; -import { generatedFrom, pathsOf, renderBundled, textOf } from './testing/bundled.ts'; +import { generatedFrom, pathsOf, renderBundled, runOf, taskOf, tasksOf, textOf } from './testing/bundled.ts'; /** The tools a `mise.toml` pins, by key, in order. */ const toolsOf = (mise: string): string[] => @@ -177,19 +177,6 @@ test('no turbo input names an answers file', async () => { // The five verbs, the task graph and the hooks (§ 1 and § 6 of the decisions, PLX-Repo). -/** The body of the task `name` in a rendered `mise.toml`, up to the next table. */ -const taskOf = (mise: string, name: string): string => - new RegExp(`^\\[tasks\\.${name}\\]\\n([\\s\\S]*?)(?=^\\[[a-z]|(?![\\s\\S]))`, 'm').exec(mise)?.[1] ?? ''; - -/** What a task runs: its body from `run =` on, which leaves out its description. */ -const runOf = (mise: string, name: string): string => { - const body = taskOf(mise, name); - return body.slice(body.indexOf('run =')); -}; - -/** The names of a rendered `mise.toml`'s tasks. */ -const tasksOf = (mise: string): string[] => [...mise.matchAll(/^\[tasks\.([\w-]+)\]/gm)].map((m) => m[1] ?? ''); - /** The tasks of a rendered `turbo.json`. */ const turboOf = (result: Awaited>) => // Turbo reads comments in turbo.json, on lines of their own here. diff --git a/packages/lib/src/testing/bundled.ts b/packages/lib/src/testing/bundled.ts index aa6499cf..a387d953 100644 --- a/packages/lib/src/testing/bundled.ts +++ b/packages/lib/src/testing/bundled.ts @@ -28,3 +28,16 @@ export function generatedFrom(result: RenderResult): [path: string, line: string if (line.includes('Generated from')) found.push([path, line]); return found; } + +/** The body of the task `name` in a rendered `mise.toml`, up to the next table. */ +export const taskOf = (mise: string, name: string): string => + new RegExp(`^\\[tasks\\.${name}\\]\\n([\\s\\S]*?)(?=^\\[[a-z]|(?![\\s\\S]))`, 'm').exec(mise)?.[1] ?? ''; + +/** What a task runs: its body from `run =` on, which leaves out its description. */ +export const runOf = (mise: string, name: string): string => { + const body = taskOf(mise, name); + return body.slice(body.indexOf('run =')); +}; + +/** The names of a rendered `mise.toml`'s tasks. */ +export const tasksOf = (mise: string): string[] => [...mise.matchAll(/^\[tasks\.([\w-]+)\]/gm)].map((m) => m[1] ?? ''); From 92ede78489796fe71db4edd75c5a2445c5bfeb2a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:48:07 +0100 Subject: [PATCH 058/194] repo-operations: tests of the five verbs and the hooks (red) Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/repoOperations.test.ts | 58 ++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/packages/lib/src/repoOperations.test.ts b/packages/lib/src/repoOperations.test.ts index 796f2248..c0c2e21d 100644 --- a/packages/lib/src/repoOperations.test.ts +++ b/packages/lib/src/repoOperations.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { generatedFrom, pathsOf, renderBundled, textOf } from './testing/bundled.ts'; +import { generatedFrom, pathsOf, renderBundled, runOf, taskOf, tasksOf, textOf } from './testing/bundled.ts'; /** The tools a `mise.toml` pins, by key, in order. */ const toolsOf = (mise: string): string[] => @@ -138,3 +138,59 @@ test('a generated file says its template lives in tooling', async () => { path, ); }); + +// --- the five verbs and the hooks (as repo-turbo has them) -------------------------------- + +const SHAPES = [ + {}, + { infrastructure: true, ci_strategy: 'hybrid' }, + { ci_strategy: 'on-prem', ci_overlay: 'netbird' }, + { ci_registry: 'own' }, +]; + +test('a repo has the five verbs as root tasks, each taking an optional name, and no verify', async () => { + for (const answers of SHAPES) { + const mise = textOf(await render(answers), 'mise.toml'); + const tasks = tasksOf(mise); + for (const verb of ['dev', 'build', 'check', 'test', 'e2e']) { + assert.ok(tasks.includes(verb), `${verb} ${JSON.stringify(answers)}`); + assert.match(taskOf(mise, verb), /^usage = .*\[name\]/m, verb); + } + assert.ok(!tasks.includes('verify'), 'no verify task'); + } +}); + +test('no rendered file mentions verify', async () => { + for (const answers of SHAPES) { + const result = await render(answers); + for (const path of pathsOf(result)) assert.doesNotMatch(textOf(result, path), /verify/i, path); + } +}); + +test('dev, build and e2e are no-ops that pass; test runs check first and then has nothing to run', async () => { + const mise = textOf(await render(), 'mise.toml'); + for (const verb of ['dev', 'build', 'e2e']) assert.match(runOf(mise, verb), /^run = 'echo "\w+: nothing/, verb); + assert.match(runOf(mise, 'test'), /^run = \[\s*'mise run check',\s*'echo "test: nothing/); + assert.doesNotMatch(runOf(mise, 'e2e'), /mise run/, 'e2e runs alone'); +}); + +test('pre-commit runs lint; pre-push runs test, which runs check first', async () => { + const hk = textOf(await render(), 'hk.pkl'); + const hook = (name: string) => new RegExp(`\\["${name}"\\] \\{([\\s\\S]*?)\\n \\}`).exec(hk)?.[1] ?? ''; + assert.match(hook('pre-commit'), /fix = "mise :lint --write \{\{ files \}\}"/); + assert.doesNotMatch(hook('pre-commit'), /mise :(check|test)/); + assert.match(hook('pre-push'), /mise :test/); + assert.doesNotMatch(hook('pre-push'), /mise :check/); +}); + +test('the workflows call test, which runs check first, and only tasks the repo has', async () => { + for (const answers of SHAPES) { + const result = await render(answers); + const tasks = tasksOf(textOf(result, 'mise.toml')); + for (const path of ['.github/workflows/on_commit.yml', '.github/workflows/on_pr.yml']) { + const asked = [...textOf(result, path).matchAll(/^ +tasks: (.+)$/gm)].map((m) => m[1]); + assert.deepEqual(asked, ['test'], path); + assert.ok(tasks.includes('test')); + } + } +}); From f0302f41d060d0170567e33532619e897a3e7fb1 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:48:12 +0100 Subject: [PATCH 059/194] repo-operations: the five verbs, the hooks of repo-turbo, and workflows that call test Co-Authored-By: Claude Fable 5.2 --- .../.github/workflows/on_commit.yml.jinja | 2 +- .../files/.github/workflows/on_pr.yml.jinja | 2 +- .../repo-operations/files/PLEXUS.md.jinja | 2 +- templates/repo-operations/files/hk.pkl | 4 ++-- .../repo-operations/files/mise.toml.jinja | 20 +++++++++++++------ 5 files changed, 19 insertions(+), 11 deletions(-) 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 82629355..1154bdca 100644 --- a/templates/repo-operations/files/.github/workflows/on_commit.yml.jinja +++ b/templates/repo-operations/files/.github/workflows/on_commit.yml.jinja @@ -21,5 +21,5 @@ jobs: with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} size: small - tasks: verify + tasks: test {% endraw %} \ No newline at end of file diff --git a/templates/repo-operations/files/.github/workflows/on_pr.yml.jinja b/templates/repo-operations/files/.github/workflows/on_pr.yml.jinja index c81fe622..0c29e5c8 100644 --- a/templates/repo-operations/files/.github/workflows/on_pr.yml.jinja +++ b/templates/repo-operations/files/.github/workflows/on_pr.yml.jinja @@ -20,5 +20,5 @@ jobs: with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} size: small - tasks: verify + tasks: test {% endraw %} \ No newline at end of file diff --git a/templates/repo-operations/files/PLEXUS.md.jinja b/templates/repo-operations/files/PLEXUS.md.jinja index 26603b2e..94da9aee 100644 --- a/templates/repo-operations/files/PLEXUS.md.jinja +++ b/templates/repo-operations/files/PLEXUS.md.jinja @@ -1,3 +1,3 @@ - The operations repo of `{{ tenant }}`: the playbooks that mount the `plexus.*` collections, one per layer, the inventory they run on, and the third-party apps under `apps/`, each with a marker of its own. -- `mise :platform` applies the platform layer{% if infrastructure %}, `mise :infrastructure` the infrastructure layer{% endif %}{% if ci_strategy != 'github' %}, `mise :ci` the runner host{% endif %}; `mise :verify` checks the repo. +- `mise :platform` applies the platform layer{% if infrastructure %}, `mise :infrastructure` the infrastructure layer{% endif %}{% if ci_strategy != 'github' %}, `mise :ci` the runner host{% 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/files/hk.pkl b/templates/repo-operations/files/hk.pkl index 1c360dc8..aad65538 100644 --- a/templates/repo-operations/files/hk.pkl +++ b/templates/repo-operations/files/hk.pkl @@ -13,8 +13,8 @@ hooks { } ["pre-push"] { steps { - ["check"] { - check = "mise :check" + ["test"] { + check = "mise :test" } } } diff --git a/templates/repo-operations/files/mise.toml.jinja b/templates/repo-operations/files/mise.toml.jinja index cd0b2244..a883b0d0 100644 --- a/templates/repo-operations/files/mise.toml.jinja +++ b/templates/repo-operations/files/mise.toml.jinja @@ -46,10 +46,12 @@ run = './ansible-playbookw ci.yml' {% endif -%} [tasks.dev] description = "No-op: an operations repo has no development environment to start" +usage = 'arg "[name]" hide=#true' run = 'echo "dev: nothing to start in an operations repo"' [tasks.build] description = "No-op: an operations repo produces no artifact; third-party apps pin published images" +usage = 'arg "[name]" hide=#true' run = 'echo "build: nothing to build in an operations repo"' [tasks.lint] @@ -73,7 +75,8 @@ exit "$status" [tasks.check] depends = ["collections"] -description = "Static checks: lint, the contracts' checks (plx doctor), then playbook syntax against the pinned collections" +description = "Run every static check, executing no test: lint, the contracts' checks (plx doctor), then playbook syntax against the pinned collections" +usage = 'arg "[name]" hide=#true' run = [ 'mise run lint', 'plx doctor', @@ -87,12 +90,17 @@ run = [ ] [tasks.test] -description = "No-op: an operations repo has no tests that gate a deploy" -run = 'echo "test: nothing to test in an operations repo"' +description = "Run check, then every test that lives beside the code: an operations repo has none that gate a deploy" +usage = 'arg "[name]" hide=#true' +run = [ + 'mise run check', + 'echo "test: nothing to test in an operations repo"', +] -[tasks.verify] -description = "Perform all steps that verify code quality" -run = ['mise run check', 'mise run test'] +[tasks.e2e] +description = "No-op: an operations repo has no end-to-end suites; it neither checks nor tests" +usage = 'arg "[name]" hide=#true' +run = 'echo "e2e: nothing to run in an operations repo"' [tasks.collections] description = "Install the pinned plexus.* collections" From acde2b6877d7c9eea827641d7db9c83f1c127e41 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:48:23 +0100 Subject: [PATCH 060/194] newborn operations repos pass their five verbs (red until the template, which is in the commit before) Co-Authored-By: Claude Fable 5.2 --- newborns/repo-operations.test.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/newborns/repo-operations.test.ts b/newborns/repo-operations.test.ts index a55364ff..92e04653 100644 --- a/newborns/repo-operations.test.ts +++ b/newborns/repo-operations.test.ts @@ -1,11 +1,11 @@ // A newborn operations repo, born as a repo is with updates beside its -// template, passes its own `verify`, lint, `plx doctor` and the playbooks' -// syntax, in each shape that changes what is generated; the collections go +// template, passes its own five verbs, with `plx doctor`, lint and the playbooks' +// syntax in `check`, in each shape that changes what is generated; the collections go // into the scratch directory, not into ~/.ansible. Created by `plx new`; it // needs the network (`mise install`, the collections). import { join } from 'node:path'; import { after, before, test } from 'node:test'; -import { born, close, open, verify } from './helpers.ts'; +import { born, close, open, pass } from './helpers.ts'; let here = ''; before(async () => { @@ -20,12 +20,12 @@ const SHAPES: [string, Record][] = [ ['own-registry', { ci_registry: 'own' }], ]; +/** The verbs a repo answers with a verdict, each from the checkout as it is. */ +const VERBS = ['dev', 'build', 'check', 'test', 'e2e']; + for (const [name, answers] of SHAPES) - test(`a newborn operations repo (${name}) passes its own verify`, async () => { + test(`a newborn operations repo (${name}) passes its own five verbs`, async () => { const env = { ANSIBLE_COLLECTIONS_PATH: join(here, 'collections') }; - await verify( - await born(join(here, name), ['repo-operations', 'updates'], { tenant: 'acme', ...answers }, env), - name, - env, - ); + const dir = await born(join(here, name), ['repo-operations', 'updates'], { tenant: 'acme', ...answers }, env); + for (const verb of VERBS) await pass(dir, name, verb, env); }); From 9941c4e91c23687358757be8390b79feea745961 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:48:29 +0100 Subject: [PATCH 061/194] newborns/app-nextjs: the newborn repo passes the doctor as born, with no awaitingDoctor Co-Authored-By: Claude Fable 5.2 --- newborns/app-nextjs.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index 7bdeaabd..f0b4482f 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -9,7 +9,7 @@ import assert from 'node:assert/strict'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { after, before, test } from 'node:test'; -import { awaitingDoctor, born, close, open, pass, plxNew, sh, tryRun } from './helpers.ts'; +import { born, close, open, pass, plxNew, sh, tryRun } from './helpers.ts'; let here = ''; let repo = ''; @@ -17,7 +17,7 @@ const PROFILES = ['stateless', 'stateful']; before(async () => { here = await open('app-nextjs'); - repo = await awaitingDoctor(await born(join(here, 'acme'), ['repo-turbo', 'updates'], { tenant: 'acme' })); + repo = await born(join(here, 'acme'), ['repo-turbo', 'updates'], { tenant: 'acme' }); for (const profile of PROFILES) await born(join(repo, 'apps', profile), ['app-nextjs'], { name: `@acme/${profile}`, profile }); }); From b9606d64a574cb7f20285a4015e3a35bd94cf4ea Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:48:38 +0100 Subject: [PATCH 062/194] remove awaitingDoctor, WAITING_FOR_DOCTOR and the verify helper: the doctor knows the five verbs Co-Authored-By: Claude Fable 5.2 --- newborns/helpers.ts | 31 +++--------------------------- newborns/repo-turbo.test.ts | 6 +++--- packages/lib/src/testing/shapes.ts | 8 -------- 3 files changed, 6 insertions(+), 39 deletions(-) diff --git a/newborns/helpers.ts b/newborns/helpers.ts index edf23e6e..0166ece1 100644 --- a/newborns/helpers.ts +++ b/newborns/helpers.ts @@ -8,9 +8,9 @@ // this workspace's own build, served by a registry of its own (registry.ts) to // the installers that read the scope's registry setting; the libraries of the // scope that are not built here, and every other package, come from npm. So the -// newborn's `plx doctor`, in its own `check` (`verify` where a template still has -// one), is the plx being cut, and a version whose packages are not on npm yet is -// tested all the same; `pass` below asserts it of every newborn, whatever the machine has installed. `ship` +// newborn's `plx doctor`, in its own `check`, is the plx being cut, and a +// version whose packages are not on npm yet is tested all the same; `pass` +// below asserts it of every newborn, whatever the machine has installed. `ship` // stamps the manifests of the packages and the pins of the templates with one // version in one commit; `open` fails if they differ. // @@ -37,7 +37,6 @@ import { execFileSync, spawn } from 'node:child_process'; import { createHash } from 'node:crypto'; import { - appendFileSync, copyFileSync, existsSync, lstatSync, @@ -53,7 +52,6 @@ import { } from 'node:fs'; import { homedir, tmpdir } from 'node:os'; import { dirname, join, sep } from 'node:path'; -import { WAITING_FOR_DOCTOR } from '../packages/lib/src/testing/shapes.ts'; import { PUBLISHED, pack } from './pack.ts'; import { type Registry, startRegistry } from './registry.ts'; @@ -330,25 +328,6 @@ export async function assertBuilt(dir: string): Promise { } } -/** - * `plx doctor` still wants a root task `verify` (PLX-Repo/Verbs and PLX-Repo/SubVerbs), which repo-turbo has no - * more. The newborn gets a task of that name and meets exactly those two findings, and nothing else is silenced. - * It first asserts that the doctor finds exactly those two, so that this fails, and is removed, on the day the - * doctor knows the five verbs. - */ -export async function awaitingDoctor(dir: string): Promise { - await sh('git', ['add', '-A'], dir); - const ran = await tryRun('mise', ['exec', '--', 'plx', 'doctor'], dir); - const found = ran.output.split('\n').filter((line) => line.startsWith('✗ PLX-')); - const expected = ['PLX-Repo/Verbs', 'PLX-Repo/SubVerbs'].map((name) => `✗ ${name} .: no root mise task \`verify\``); - if (JSON.stringify(found.sort()) !== JSON.stringify(expected.sort())) - throw new Error( - `plx doctor knows the five verbs, or finds more than the two verify findings: remove awaitingDoctor.\n${ran.output}`, - ); - appendFileSync(join(dir, 'mise.toml'), WAITING_FOR_DOCTOR.task); - return dir; -} - /** `mise run ` in the newborn, which must pass: the built tools, then the task. */ export async function pass(dir: string, name: string, task: string, env: NodeJS.ProcessEnv = {}): Promise { await assertBuilt(dir); @@ -356,10 +335,6 @@ export async function pass(dir: string, name: string, task: string, env: NodeJS. if (!ran.ok) throw new Error(`the newborn ${name} fails its own ${task}:\n${ran.output}`); } -/** `mise run verify` in the newborn, which must pass: the verb of the templates that still have one. */ -export const verify = (dir: string, name: string, env: NodeJS.ProcessEnv = {}): Promise => - pass(dir, name, 'verify', env); - /** Writes files below `root`, creating directories; a value that is no string is written as formatted JSON. */ export function put(root: string, files: Record): void { for (const [path, content] of Object.entries(files)) { diff --git a/newborns/repo-turbo.test.ts b/newborns/repo-turbo.test.ts index 37e87ed1..801205c5 100644 --- a/newborns/repo-turbo.test.ts +++ b/newborns/repo-turbo.test.ts @@ -20,7 +20,7 @@ import assert from 'node:assert/strict'; import { readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { after, before, describe, test } from 'node:test'; -import { awaitingDoctor, born, close, mise, open, pass, put, sh, tryRun } from './helpers.ts'; +import { born, close, mise, open, pass, put, sh, tryRun } from './helpers.ts'; let here = ''; before(async () => { @@ -28,11 +28,11 @@ before(async () => { }); after(close); -/** A newborn, which has no `verify` task: a `verify` is added as `plx doctor` still wants one. */ +/** A newborn, which has no `verify` task. */ async function newborn(name: string, answers: Record = {}): Promise { const dir = await born(join(here, name), ['repo-turbo', 'updates'], { tenant: 'acme', ...answers }); assert.doesNotMatch(read(dir, 'mise.toml'), /^\[tasks\.verify\]/m, 'a repo is born without verify'); - return await awaitingDoctor(dir); + return dir; } const read = (dir: string, file: string) => readFileSync(join(dir, file), 'utf8'); diff --git a/packages/lib/src/testing/shapes.ts b/packages/lib/src/testing/shapes.ts index bc539c78..8090d8b2 100644 --- a/packages/lib/src/testing/shapes.ts +++ b/packages/lib/src/testing/shapes.ts @@ -38,14 +38,6 @@ export const CHOICES: Readonly }, }; -/** - * What `plx doctor` finds of a repo-turbo repo until it knows the five verbs: it wants a root task `verify` - * (PLX-Repo/Verbs and PLX-Repo/SubVerbs), twice. A repo that appends this task meets it and nothing else is silenced. - */ -export const WAITING_FOR_DOCTOR = { - task: '\n[tasks.verify]\ndescription = "Waits for plx doctor, which still wants this task"\nrun = "true"\n', -} as const; - /** Every combination of the choices, one answers object each. */ export function combinations(choices: Choices): Answers[] { return Object.entries(choices).reduce( From e8f1be205706e4659bcc6f54f6ceaa3030135413 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:48:46 +0100 Subject: [PATCH 063/194] newborns: a test file is no input of an app's build, so the type-check test forces its miss Since repo-turbo excludes test files from the inputs of build (PLX-176), adding a test file with a type error leaves the build's hash as it was: the build is a hit, and the miss is forced with turbo's --force. Without ignoreBuildErrors the forced miss fails on that file (tried by hand in a newborn). Co-Authored-By: Claude Fable 5.2 --- newborns/app-nextjs.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index cb9bc9b0..7cb4d899 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -151,9 +151,10 @@ test('the build does not type-check, so a hit and a miss of one hash agree, and put(repo, { 'apps/stateless/src/typo.test.ts': "export const n: number = 'not a number';\n" }); await sh('git', ['add', '-A'], repo); try { - assert.match(await sh('mise', ['run', 'build', 'stateless'], repo, PLATFORM), /cache miss/); - rmSync(join(repo, 'apps', 'stateless', '.next'), { recursive: true, force: true }); + // A test file is no input of the build, so the hash is the one built before, and the miss is forced. assert.match(await sh('mise', ['run', 'build', 'stateless'], repo, PLATFORM), /cache hit/); + const miss = ['exec', '--', 'turbo', 'run', 'build', '--filter=@acme/stateless', '--force']; + assert.match(await sh('mise', miss, repo, PLATFORM), /cache bypass/); const check = await tryRun('mise', ['run', 'check', 'stateless'], repo); assert.equal(check.ok, false, check.output); assert.match(check.output, /typo\.test\.ts.*TS2322/); From 5b00bd004db2a2c3ee6cf41eb0edf54e81389fa4 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:49:56 +0100 Subject: [PATCH 064/194] newborns: the app-nextjs newborn builds with the platform its repo's mise.toml sets, none by hand repo-turbo sets PLX_PLATFORM in the [env] of the repo's mise.toml (PLX-176), so the tests no longer give it to mise build, mise test or the build outside Turbo; the build ID is compared with the dry run's hash in mise's own environment. A platform is still given by hand only where the test compares two of them. Co-Authored-By: Claude Fable 5.2 --- newborns/app-nextjs.test.ts | 38 +++++++++++++------------------------ 1 file changed, 13 insertions(+), 25 deletions(-) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index 7cb4d899..b4d95330 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -22,13 +22,6 @@ let here = ''; let repo = ''; const PROFILES = ['stateless', 'stateful']; -/** - * The platform as mise's `{{ os() }}-{{ arch() }}` gives it, for a build's - * environment: the repo template's `mise.toml` does not set it yet, so the - * tests do, with the value it will set. - */ -const PLATFORM = { PLX_PLATFORM: `${process.platform === 'darwin' ? 'macos' : process.platform}-${process.arch}` }; - /** A one-pixel PNG, for the app's public/ and its image optimiser. */ const PIXEL = Buffer.from( 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', @@ -73,7 +66,7 @@ for (const profile of PROFILES) { } test('an app builds into one directory that serves all of it, its static files and public/ included, wherever it lies', async () => { - await sh('mise', ['run', 'build', 'stateless'], repo, PLATFORM); + await sh('mise', ['run', 'build', 'stateless'], repo); const moved = join(here, 'moved'); cpSync(output('stateless'), moved, { recursive: true, verbatimSymlinks: true }); const port = await freePort(); @@ -105,18 +98,18 @@ test('an app builds into one directory that serves all of it, its static files a test('that directory is all the build leaves: a cache hit restores it whole', async () => { const dotNext = join(repo, 'apps', 'stateless', '.next'); - await sh('mise', ['run', 'build', 'stateless'], repo, PLATFORM); + await sh('mise', ['run', 'build', 'stateless'], repo); rmSync(dotNext, { recursive: true, force: true }); - assert.match(await sh('mise', ['run', 'build', 'stateless'], repo, PLATFORM), /cache hit/); + assert.match(await sh('mise', ['run', 'build', 'stateless'], repo), /cache hit/); assert.deepEqual(readdirSync(dotNext), ['standalone']); const app = join(output('stateless'), 'apps', 'stateless'); for (const path of ['server.js', 'package.json', '.next/BUILD_ID', '.next/static', 'public/pixel.png']) assert.ok(existsSync(join(app, path)), path); }); -/** Turbo's hash of each task of an app, by task name, from a dry run in mise's environment with the platform given. */ -async function hashes(app: string, platform: string): Promise> { - const dry = `mise exec -- env PLX_PLATFORM=${platform} turbo run build check test --filter=@acme/${app} --dry=json`; +/** Turbo's hash of each task of an app, by task name, from a dry run in mise's environment, with another platform where one is given. */ +async function hashes(app: string, platform?: string): Promise> { + const dry = `mise exec -- env ${platform ? `PLX_PLATFORM=${platform}` : ''} turbo run build check test --filter=@acme/${app} --dry=json`; const plan = JSON.parse(await sh('sh', ['-c', `${dry} 2>/dev/null`], repo)); return Object.fromEntries(plan.tasks.map((task: { task: string; hash: string }) => [task.task, task.hash])); } @@ -129,15 +122,10 @@ test("the platform is in the hash of an app's build, and not in its check's", as }); test("the build ID is the hash of the app's build, and a build outside Turbo or without the platform fails", async () => { - await sh('mise', ['run', 'build', 'stateless'], repo, PLATFORM); - const { build } = await hashes('stateless', PLATFORM.PLX_PLATFORM); + await sh('mise', ['run', 'build', 'stateless'], repo); + const { build } = await hashes('stateless'); assert.equal(readFileSync(join(output('stateless'), 'apps', 'stateless', '.next', 'BUILD_ID'), 'utf8'), build); - const outside = await tryRun( - 'mise', - ['exec', '--', 'pnpm', '--filter', '@acme/stateless', 'run', 'build'], - repo, - PLATFORM, - ); + const outside = await tryRun('mise', ['exec', '--', 'pnpm', '--filter', '@acme/stateless', 'run', 'build'], repo); assert.equal(outside.ok, false, outside.output); assert.match(outside.output, /TURBO_HASH= PLX_PLATFORM=\S/); const bare = ['exec', '--', 'env', '-u', 'PLX_PLATFORM', 'turbo', 'run', 'build', '--filter=@acme/stateless']; @@ -152,9 +140,9 @@ test('the build does not type-check, so a hit and a miss of one hash agree, and await sh('git', ['add', '-A'], repo); try { // A test file is no input of the build, so the hash is the one built before, and the miss is forced. - assert.match(await sh('mise', ['run', 'build', 'stateless'], repo, PLATFORM), /cache hit/); + assert.match(await sh('mise', ['run', 'build', 'stateless'], repo), /cache hit/); const miss = ['exec', '--', 'turbo', 'run', 'build', '--filter=@acme/stateless', '--force']; - assert.match(await sh('mise', miss, repo, PLATFORM), /cache bypass/); + assert.match(await sh('mise', miss, repo), /cache bypass/); const check = await tryRun('mise', ['run', 'check', 'stateless'], repo); assert.equal(check.ok, false, check.output); assert.match(check.output, /typo\.test\.ts.*TS2322/); @@ -166,7 +154,7 @@ test('the build does not type-check, so a hit and a miss of one hash agree, and test("an app's tests run by the repo's verb, and pass while it has none", async () => { for (const profile of PROFILES) - assert.match(await sh('mise', ['run', 'test', profile], repo, PLATFORM), new RegExp(`@acme/${profile}:test`)); + assert.match(await sh('mise', ['run', 'test', profile], repo), new RegExp(`@acme/${profile}:test`)); }); /** Every path below `dir`, sorted, as Node lists it: the same call inside an image and outside. */ @@ -191,7 +179,7 @@ for (const profile of PROFILES) { }); await sh('git', ['add', '-A'], repo); } - await sh('mise', ['run', 'build', profile], repo, PLATFORM); + await sh('mise', ['run', 'build', profile], repo); const id = randomBytes(4).toString('hex'); const tag = `plx-newborn-${profile}:${id}`; // Limits for every container, on a machine others share; the build runs nothing and needs none. From 93a22e71f7d4b5c5d5528181cab95982b9477d66 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:51:15 +0100 Subject: [PATCH 065/194] test(app-nextjs): the app's build adds the platform to the root's build and keeps its env, inputs and dependsOn Passes at once: the behaviour already holds. The app's turbo.json extends the root's, which since PLX-176 declares inputs (test files left out) and dependsOn for build, and no env yet, so $TURBO_EXTENDS$ has nothing to keep today and the test asserts the root's env plus PLX_PLATFORM for the day it has. Tried by hand in a newborn: an app turbo.json that sets inputs to $TURBO_DEFAULT$ lets a test file move the hash, and one that sets dependsOn to [] resolves to []. Co-Authored-By: Claude Fable 5.2 --- newborns/app-nextjs.test.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index b4d95330..c1a71ccb 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -121,6 +121,31 @@ test("the platform is in the hash of an app's build, and not in its check's", as assert.equal(linux.check, mac.check); }); +test("the app's build adds the platform to what the root declares for build, and keeps its env, inputs and dependsOn", async () => { + // Turbo reads the comment lines of the root's turbo.json, JSON does not. + const text = readFileSync(join(repo, 'turbo.json'), 'utf8').replace(/^\s*\/\/.*$/gm, ''); + const declared = JSON.parse(text).tasks.build; + const dry = 'mise exec -- turbo run build --filter=@acme/stateless --dry=json 2>/dev/null'; + const [resolved] = JSON.parse(await sh('sh', ['-c', dry], repo)).tasks; + assert.deepEqual(resolved.resolvedTaskDefinition.dependsOn, declared.dependsOn); + assert.deepEqual(resolved.resolvedTaskDefinition.env.sort(), [...(declared.env ?? []), 'PLX_PLATFORM'].sort()); + const { build } = await hashes('stateless'); + assert.notEqual((await hashes('stateless', 'none-none')).build, build); + // The root's inputs leave test files out of the build; a source file is in. + const app = join(repo, 'apps', 'stateless', 'src'); + try { + put(app, { 'kept.test.ts': 'export {};\n' }); + await sh('git', ['add', '-A'], repo); + assert.equal((await hashes('stateless')).build, build); + put(app, { 'kept.ts': 'export {};\n' }); + await sh('git', ['add', '-A'], repo); + assert.notEqual((await hashes('stateless')).build, build); + } finally { + for (const file of ['kept.test.ts', 'kept.ts']) rmSync(join(app, file), { force: true }); + await sh('git', ['add', '-A'], repo); + } +}); + test("the build ID is the hash of the app's build, and a build outside Turbo or without the platform fails", async () => { await sh('mise', ['run', 'build', 'stateless'], repo); const { build } = await hashes('stateless'); From 2d39f65cafecedc9173f1b0e46b0618591a64150 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:55:54 +0100 Subject: [PATCH 066/194] newborns: a forced run of the workspace does not force the newborns' turbo Under TURBO_FORCE=true, as the forced verify sets it, the variable reached every newborn's turbo, so each build bypassed the cache, and the two tests of app-nextjs that read a cache hit failed ("that directory is all the build leaves" since this branch began, and the type-check test). A newborn's cache is new anyway, so the helpers remove TURBO_FORCE from what the newborn's tools inherit, beside git's local variables. The red test was the forced verify itself; the app-nextjs and helpers tests pass under TURBO_FORCE=true with this. Co-Authored-By: Claude Fable 5.2 --- newborns/helpers.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/newborns/helpers.ts b/newborns/helpers.ts index 14b675fb..03c66ec6 100644 --- a/newborns/helpers.ts +++ b/newborns/helpers.ts @@ -66,12 +66,14 @@ const PLX = join(WORKSPACE, 'packages', 'cli', 'dist', 'plx.js'); /** * The environment of the tools a test runs: a hook that runs this leaves * GIT_DIR and its siblings set, which would point a newborn's `git init` - * at the pushing repository, so git's own list of them is removed. + * at the pushing repository, so git's own list of them is removed. A forced + * run of this workspace (TURBO_FORCE) is this workspace's: a newborn's cache + * is new anyway, and its tests read its hits and misses, so it is removed too. */ function cleanEnv(extra: NodeJS.ProcessEnv): NodeJS.ProcessEnv { const local = execFileSync('git', ['rev-parse', '--local-env-vars'], { encoding: 'utf8' }).split('\n'); const env = { ...process.env }; - for (const name of local) delete env[name]; + for (const name of [...local, 'TURBO_FORCE']) delete env[name]; return { ...env, ...world?.env, ...extra }; } From 7007df4c18fa189248ee0a6830b39392cfbd8cf5 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 17:58:53 +0100 Subject: [PATCH 067/194] tests of repo-turbo: the verbs reach Turbo through turbow, which picks the shared or the trusted cache server Red: turbow does not exist yet. The four cases of the issue (the shared server answers; none answers; CI with the trusted server; CI without it), the tenant without a bucket, and owner-repo from any remote and directory. Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/repoTurbo.test.ts | 16 +- packages/lib/src/repoTurboCache.test.ts | 242 ++++++++++++++++++++++++ 2 files changed, 252 insertions(+), 6 deletions(-) create mode 100644 packages/lib/src/repoTurboCache.test.ts diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index 95e78a23..12b38998 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -26,6 +26,7 @@ const COMMON = [ 'packages/.gitkeep', 'pnpm-workspace.yaml', 'turbo.json', + 'turbow', ]; test('an app repo is rendered with its apps directory and its commit workflows', async () => { @@ -225,24 +226,27 @@ test('check is lint, then plx doctor, then the check of Turbo', async () => { const run = runOf(textOf(await render(answers), 'mise.toml'), 'check'); const at = (needle: RegExp) => run.search(needle); assert.ok(at(/mise run lint/) >= 0 && at(/plx doctor/) > at(/mise run lint/), 'doctor after lint'); - assert.ok(at(/turbo run check/) > at(/plx doctor/), 'turbo after doctor'); - assert.doesNotMatch(run, /turbo run (test|build|e2e)/); + assert.ok(at(/turbow \w+ run check/) > at(/plx doctor/), 'turbo after doctor'); + assert.doesNotMatch(run, /turbow \w+ run (test|build|e2e)/); } }); test('test runs check, then the test of Turbo, in a run of its own', async () => { for (const answers of SHAPES) { const run = runOf(textOf(await render(answers), 'mise.toml'), 'test'); - assert.ok(run.search(/mise run check/) >= 0 && run.search(/turbo run test/) > run.search(/mise run check/), run); - assert.doesNotMatch(run, /turbo run (check|build|e2e)/); + assert.ok( + run.search(/mise run check/) >= 0 && run.search(/turbow \w+ run test/) > run.search(/mise run check/), + run, + ); + assert.doesNotMatch(run, /turbow \w+ run (check|build|e2e)/); } }); test('e2e runs the e2e of Turbo alone: it neither tests nor checks', async () => { for (const answers of SHAPES) { const run = runOf(textOf(await render(answers), 'mise.toml'), 'e2e'); - assert.match(run, /turbo run e2e/); - assert.doesNotMatch(run, /mise run (test|check)|turbo run (check|test|build)/); + assert.match(run, /turbow \w+ run e2e/); + assert.doesNotMatch(run, /mise run (test|check)|turbow \w+ run (check|test|build)/); } }); diff --git a/packages/lib/src/repoTurboCache.test.ts b/packages/lib/src/repoTurboCache.test.ts new file mode 100644 index 00000000..dd2fd17f --- /dev/null +++ b/packages/lib/src/repoTurboCache.test.ts @@ -0,0 +1,242 @@ +// The two remote caches of a repo-turbo repo (Decisions § 5): the verbs reach +// Turbo through `turbow`, which the template renders beside `mise.toml`, and +// which picks the cache server for each one. Here `turbow` is run as the tasks +// run it, in a git checkout with an origin, with a stub `turbo` first on PATH +// that prints what it was handed, and with a health endpoint on a free loopback +// port standing in for a cache server; the newborn test (newborns/) runs it +// against a real server and an S3 stand-in. +import assert from 'node:assert/strict'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { after, before, test } from 'node:test'; +import { renderBundled, textOf } from './testing/bundled.ts'; + +const SHAPES = [{}, { publishes_packages: true }]; +const render = (answers: Record = {}) => renderBundled(['repo-turbo'], { tenant: 'acme', ...answers }); + +let scratch = ''; +let turbow = ''; +let server: Server; +let answering = ''; +let silent = ''; + +/** A loopback port nothing listens on: taken from the system, then given back. */ +async function freePort(): Promise { + const probe = createServer(); + await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); + const { port } = probe.address() as AddressInfo; + await new Promise((resolve) => probe.close(() => resolve())); + return port; +} + +before(async () => { + scratch = mkdtempSync(join(tmpdir(), 'plx-turbow-')); + turbow = textOf(await render(), 'turbow'); + // The stub prints what turbow hands to Turbo: the three variables, and the arguments. + mkdirSync(join(scratch, 'bin')); + writeFileSync( + join(scratch, 'bin', 'turbo'), + '#!/bin/sh\necho "turbo api=$TURBO_API team=$TURBO_TEAM token=$TURBO_TOKEN args=$*"\n', + ); + chmodSync(join(scratch, 'bin', 'turbo'), 0o755); + server = createServer((req, res) => { + res.statusCode = req.url === '/management/health' ? 200 : 404; + res.end(); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + answering = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + silent = `http://127.0.0.1:${await freePort()}`; +}); + +after(async () => { + await new Promise((resolve) => server.close(() => resolve())); + rmSync(scratch, { recursive: true, force: true }); +}); + +let checkouts = 0; +/** A checkout with `turbow` at its root, and `origin` at `remote` when one is given. */ +function checkout(remote?: string): string { + const dir = join(scratch, `checkout-${checkouts++}`); + mkdirSync(dir); + writeFileSync(join(dir, 'turbow'), turbow); + chmodSync(join(dir, 'turbow'), 0o755); + execFileSync('git', ['init', '-q'], { cwd: dir }); + if (remote) execFileSync('git', ['remote', 'add', 'origin', remote], { cwd: dir }); + return dir; +} + +interface Ran { + status: number | null; + /** What the stub turbo printed, or undefined when turbow never started it. */ + turbo?: { api: string; team: string; token: string; args: string }; + /** The lines turbow wrote itself. */ + said: string[]; +} + +/** + * `./turbow run check --filter=…` in `dir`, as a task runs it, with + * nothing of the caller's CI, Turbo or cache variables but `env`: a test run + * in CI must see what one on a laptop sees. + */ +function turbowIn(dir: string, cache: string, env: Record = {}): Ran { + const base = Object.fromEntries( + Object.entries(process.env).filter(([name]) => name !== 'CI' && !/^(TURBO_|PLX_TURBO_)/.test(name)), + ); + const ran = spawnSync('./turbow', [cache, 'run', 'check', '--filter={./apps/web}...'], { + cwd: dir, + encoding: 'utf8', + env: { ...base, PATH: `${join(scratch, 'bin')}:${process.env.PATH}`, ...env }, + }); + const lines = `${ran.stdout}${ran.stderr}`.split('\n').filter(Boolean); + const printed = lines.find((line) => line.startsWith('turbo api=')); + const m = printed && /^turbo api=(.*) team=(.*) token=(.*) args=(.*)$/.exec(printed); + return { + status: ran.status, + turbo: m ? { api: m[1] ?? '', team: m[2] ?? '', token: m[3] ?? '', args: m[4] ?? '' } : undefined, + said: lines.filter((line) => line !== printed), + }; +} + +const REMOTE = 'git@github.com:acme/web.git'; + +test('turbow is rendered in every repo, executable, beside mise.toml', async () => { + for (const answers of SHAPES) { + const result = await render(answers); + assert.equal(result.tree.get('turbow')?.mode, 0o100755, JSON.stringify(answers)); + assert.match(textOf(result, 'turbow'), /^#!\/bin\/sh\n/); + } +}); + +/** What a task runs: its body from `run =` on. */ +const runOf = (mise: string, name: string): string => { + const body = new RegExp(`^\\[tasks\\.${name}\\]\\n([\\s\\S]*?)(?=^\\[[a-z]|(?![\\s\\S]))`, 'm').exec(mise)?.[1] ?? ''; + return body.slice(body.indexOf('run =')); +}; + +test('check and test reach Turbo through the shared cache, build and e2e through the trusted one, dev through none', async () => { + for (const answers of SHAPES) { + const mise = textOf(await render(answers), 'mise.toml'); + for (const [verb, cache] of [ + ['check', 'shared'], + ['test', 'shared'], + ['build', 'trusted'], + ['e2e', 'trusted'], + ] as const) { + const run = runOf(mise, verb); + assert.match(run, new RegExp(`^\\./turbow ${cache} run ${verb}\\b`, 'm'), `${verb} ${JSON.stringify(answers)}`); + assert.doesNotMatch(run, /^turbo /m, `${verb} calls no turbo but through turbow`); + } + assert.doesNotMatch(runOf(mise, 'dev'), /turbow/, 'dev, whose task is never cached, asks for no cache'); + } +}); + +test('outside CI the shared server is the one on the fixed port, unless PLX_TURBO_SHARED names another', () => { + assert.match(turbow, /\$\{PLX_TURBO_SHARED:-http:\/\/127\.0\.0\.1:8585\}/); +}); + +test('outside CI, with the shared server answering, every verb uses it, as the repo’s owner-repo', () => { + const dir = checkout(REMOTE); + for (const cache of ['shared', 'trusted']) { + const ran = turbowIn(dir, cache, { PLX_TURBO_SHARED: answering }); + assert.equal(ran.status, 0, ran.said.join('\n')); + assert.equal(ran.turbo?.api, answering, cache); + assert.equal(ran.turbo?.team, 'acme-web'); + assert.notEqual(ran.turbo?.token, '', 'Turbo sends no request without a token, though the server asks for none'); + assert.equal(ran.turbo?.args, 'run check --filter={./apps/web}...'); + assert.equal(ran.said.length, 1, ran.said.join('\n')); + assert.match(ran.said[0] ?? '', new RegExp(`shared remote cache at ${answering.replaceAll('.', '\\.')}`)); + } +}); + +test('outside CI, with no server answering, every verb runs without a remote cache and says so in one line', () => { + const dir = checkout(REMOTE); + for (const shared of [silent, 'none']) + for (const cache of ['shared', 'trusted']) { + // What the caller's shell may hold: without TURBO_API, Turbo would send the team and token to Vercel. + const ran = turbowIn(dir, cache, { + PLX_TURBO_SHARED: shared, + TURBO_API: 'https://example.invalid', + TURBO_TEAM: 'someone', + TURBO_TOKEN: 'secret', + }); + assert.equal(ran.status, 0, ran.said.join('\n')); + assert.deepEqual(ran.turbo, { api: '', team: '', token: '', args: 'run check --filter={./apps/web}...' }); + assert.equal(ran.said.length, 1, ran.said.join('\n')); + assert.match(ran.said[0] ?? '', /without a remote cache/); + } +}); + +test('in CI, build and e2e reach the trusted server the job started, and check and test the shared one, never the other', () => { + const dir = checkout('https://github.com/acme/web'); + const ci = { + CI: 'true', + PLX_TURBO_SHARED: silent, + PLX_TURBO_SHARED_TOKEN: 'shared-job-token', + PLX_TURBO_TRUSTED: answering, + PLX_TURBO_TRUSTED_TOKEN: 'trusted-job-token', + }; + const trusted = turbowIn(dir, 'trusted', ci); + assert.equal(trusted.status, 0, trusted.said.join('\n')); + assert.deepEqual(trusted.turbo, { + api: answering, + team: 'acme-web', + token: 'trusted-job-token', + args: 'run check --filter={./apps/web}...', + }); + const shared = turbowIn(dir, 'shared', ci); + assert.equal(shared.turbo?.api, silent); + assert.equal(shared.turbo?.token, 'shared-job-token'); + // A job with the trusted server alone, as the e2e job is: check and test find no shared server there. + const alone = turbowIn(dir, 'shared', { CI: 'true', PLX_TURBO_TRUSTED: answering, PLX_TURBO_TRUSTED_TOKEN: 't' }); + assert.equal(alone.status, 0, alone.said.join('\n')); + assert.deepEqual(alone.turbo, { api: '', team: '', token: '', args: 'run check --filter={./apps/web}...' }); + assert.match(alone.said.join('\n'), /without a remote cache/); +}); + +test('in CI without the trusted server, build and e2e fail and say why; they never fall back to the shared one', () => { + const dir = checkout(REMOTE); + for (const env of [{ PLX_TURBO_SHARED: answering, PLX_TURBO_SHARED_TOKEN: 't' }, {}]) { + const ran = turbowIn(dir, 'trusted', { CI: 'true', ...env }); + assert.notEqual(ran.status, 0); + assert.equal(ran.turbo, undefined, 'Turbo never ran'); + assert.match(ran.said.join('\n'), /trusted cache server/); + assert.match(ran.said.join('\n'), /PLX_TURBO_TRUSTED/); + } +}); + +test('in CI where the tenant has no bucket, every verb runs without a remote cache and says so in one line', () => { + const dir = checkout(REMOTE); + for (const cache of ['shared', 'trusted']) { + const ran = turbowIn(dir, cache, { CI: 'true', PLX_TURBO_SHARED: 'none', PLX_TURBO_TRUSTED: 'none' }); + assert.equal(ran.status, 0, ran.said.join('\n')); + assert.deepEqual(ran.turbo, { api: '', team: '', token: '', args: 'run check --filter={./apps/web}...' }); + assert.equal(ran.said.length, 1, ran.said.join('\n')); + assert.match(ran.said[0] ?? '', /without a remote cache/); + } +}); + +test('the team is owner-repo of origin, the same from SSH and HTTPS remotes and from any directory', () => { + for (const remote of [ + 'git@github.com:acme/web.git', + 'git@github.com:Acme/Web', + 'https://github.com/acme/web', + 'https://github.com/acme/web.git', + 'https://github.com/acme/web/', + 'ssh://git@github.com/acme/web.git', + ]) { + const ran = turbowIn(checkout(remote), 'shared', { PLX_TURBO_SHARED: answering }); + assert.equal(ran.turbo?.team, 'acme-web', remote); + } +}); + +test('a checkout without origin has no team, and runs without a remote cache', () => { + const ran = turbowIn(checkout(), 'shared', { PLX_TURBO_SHARED: answering }); + assert.equal(ran.status, 0, ran.said.join('\n')); + assert.deepEqual(ran.turbo, { api: '', team: '', token: '', args: 'run check --filter={./apps/web}...' }); + assert.equal(ran.said.length, 1, ran.said.join('\n')); + assert.match(ran.said[0] ?? '', /without a remote cache.*origin/); +}); From eddc53d5baf0de3088aa83a5cee5ec7bb18331df Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:01:33 +0100 Subject: [PATCH 068/194] repo-turbo: turbow, the one helper by which the verbs pick their remote cache check and test call ./turbow shared, build and e2e ./turbow trusted; dev stays plain turbo. Outside CI every verb uses the shared server, by default on 127.0.0.1:8585, and runs without a remote cache where none answers; in CI each uses only the server its job started, and build and e2e fail without the trusted one. The team is owner-repo from origin. The tests of the previous commit run turbow asynchronously now: the stand-in server answers from the test's own process. newSite's list of a born repo's files gains turbow. Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/newSite.test.ts | 1 + packages/lib/src/repoTurboCache.test.ts | 60 ++++++++++------- templates/repo-turbo/files/mise.toml.jinja | 8 +-- templates/repo-turbo/files/turbow | 76 ++++++++++++++++++++++ 4 files changed, 117 insertions(+), 28 deletions(-) create mode 100755 templates/repo-turbo/files/turbow diff --git a/packages/lib/src/newSite.test.ts b/packages/lib/src/newSite.test.ts index bce5c9e3..e972d2aa 100644 --- a/packages/lib/src/newSite.test.ts +++ b/packages/lib/src/newSite.test.ts @@ -340,6 +340,7 @@ test('a repo from repo-turbo with updates beside it and an app from app-nextjs i 'pnpm-workspace.yaml', 'renovate.json', 'turbo.json', + 'turbow', ]); assert.deepEqual( ran.map((r) => [r.command, ...r.args].join(' ')), diff --git a/packages/lib/src/repoTurboCache.test.ts b/packages/lib/src/repoTurboCache.test.ts index dd2fd17f..7f27be15 100644 --- a/packages/lib/src/repoTurboCache.test.ts +++ b/packages/lib/src/repoTurboCache.test.ts @@ -6,7 +6,7 @@ // port standing in for a cache server; the newborn test (newborns/) runs it // against a real server and an S3 stand-in. import assert from 'node:assert/strict'; -import { execFileSync, spawnSync } from 'node:child_process'; +import { execFile, execFileSync } from 'node:child_process'; import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { createServer, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; @@ -82,16 +82,24 @@ interface Ran { * nothing of the caller's CI, Turbo or cache variables but `env`: a test run * in CI must see what one on a laptop sees. */ -function turbowIn(dir: string, cache: string, env: Record = {}): Ran { +async function turbowIn(dir: string, cache: string, env: Record = {}): Promise { const base = Object.fromEntries( Object.entries(process.env).filter(([name]) => name !== 'CI' && !/^(TURBO_|PLX_TURBO_)/.test(name)), ); - const ran = spawnSync('./turbow', [cache, 'run', 'check', '--filter={./apps/web}...'], { - cwd: dir, - encoding: 'utf8', - env: { ...base, PATH: `${join(scratch, 'bin')}:${process.env.PATH}`, ...env }, + // Not spawnSync: the stand-in server answers from this process, whose loop must keep turning meanwhile. + const ran = await new Promise<{ status: number | null; output: string }>((resolve) => { + execFile( + './turbow', + [cache, 'run', 'check', '--filter={./apps/web}...'], + { cwd: dir, env: { ...base, PATH: `${join(scratch, 'bin')}:${process.env.PATH}`, ...env } }, + (error, stdout, stderr) => + resolve({ + status: error ? (typeof error.code === 'number' ? error.code : 1) : 0, + output: `${stdout}${stderr}`, + }), + ); }); - const lines = `${ran.stdout}${ran.stderr}`.split('\n').filter(Boolean); + const lines = ran.output.split('\n').filter(Boolean); const printed = lines.find((line) => line.startsWith('turbo api=')); const m = printed && /^turbo api=(.*) team=(.*) token=(.*) args=(.*)$/.exec(printed); return { @@ -134,14 +142,14 @@ test('check and test reach Turbo through the shared cache, build and e2e through } }); -test('outside CI the shared server is the one on the fixed port, unless PLX_TURBO_SHARED names another', () => { +test('outside CI the shared server is the one on the fixed port, unless PLX_TURBO_SHARED names another', async () => { assert.match(turbow, /\$\{PLX_TURBO_SHARED:-http:\/\/127\.0\.0\.1:8585\}/); }); -test('outside CI, with the shared server answering, every verb uses it, as the repo’s owner-repo', () => { +test('outside CI, with the shared server answering, every verb uses it, as the repo’s owner-repo', async () => { const dir = checkout(REMOTE); for (const cache of ['shared', 'trusted']) { - const ran = turbowIn(dir, cache, { PLX_TURBO_SHARED: answering }); + const ran = await turbowIn(dir, cache, { PLX_TURBO_SHARED: answering }); assert.equal(ran.status, 0, ran.said.join('\n')); assert.equal(ran.turbo?.api, answering, cache); assert.equal(ran.turbo?.team, 'acme-web'); @@ -152,12 +160,12 @@ test('outside CI, with the shared server answering, every verb uses it, as the r } }); -test('outside CI, with no server answering, every verb runs without a remote cache and says so in one line', () => { +test('outside CI, with no server answering, every verb runs without a remote cache and says so in one line', async () => { const dir = checkout(REMOTE); for (const shared of [silent, 'none']) for (const cache of ['shared', 'trusted']) { // What the caller's shell may hold: without TURBO_API, Turbo would send the team and token to Vercel. - const ran = turbowIn(dir, cache, { + const ran = await turbowIn(dir, cache, { PLX_TURBO_SHARED: shared, TURBO_API: 'https://example.invalid', TURBO_TEAM: 'someone', @@ -170,7 +178,7 @@ test('outside CI, with no server answering, every verb runs without a remote cac } }); -test('in CI, build and e2e reach the trusted server the job started, and check and test the shared one, never the other', () => { +test('in CI, build and e2e reach the trusted server the job started, and check and test the shared one, never the other', async () => { const dir = checkout('https://github.com/acme/web'); const ci = { CI: 'true', @@ -179,7 +187,7 @@ test('in CI, build and e2e reach the trusted server the job started, and check a PLX_TURBO_TRUSTED: answering, PLX_TURBO_TRUSTED_TOKEN: 'trusted-job-token', }; - const trusted = turbowIn(dir, 'trusted', ci); + const trusted = await turbowIn(dir, 'trusted', ci); assert.equal(trusted.status, 0, trusted.said.join('\n')); assert.deepEqual(trusted.turbo, { api: answering, @@ -187,20 +195,24 @@ test('in CI, build and e2e reach the trusted server the job started, and check a token: 'trusted-job-token', args: 'run check --filter={./apps/web}...', }); - const shared = turbowIn(dir, 'shared', ci); + const shared = await turbowIn(dir, 'shared', ci); assert.equal(shared.turbo?.api, silent); assert.equal(shared.turbo?.token, 'shared-job-token'); // A job with the trusted server alone, as the e2e job is: check and test find no shared server there. - const alone = turbowIn(dir, 'shared', { CI: 'true', PLX_TURBO_TRUSTED: answering, PLX_TURBO_TRUSTED_TOKEN: 't' }); + const alone = await turbowIn(dir, 'shared', { + CI: 'true', + PLX_TURBO_TRUSTED: answering, + PLX_TURBO_TRUSTED_TOKEN: 't', + }); assert.equal(alone.status, 0, alone.said.join('\n')); assert.deepEqual(alone.turbo, { api: '', team: '', token: '', args: 'run check --filter={./apps/web}...' }); assert.match(alone.said.join('\n'), /without a remote cache/); }); -test('in CI without the trusted server, build and e2e fail and say why; they never fall back to the shared one', () => { +test('in CI without the trusted server, build and e2e fail and say why; they never fall back to the shared one', async () => { const dir = checkout(REMOTE); for (const env of [{ PLX_TURBO_SHARED: answering, PLX_TURBO_SHARED_TOKEN: 't' }, {}]) { - const ran = turbowIn(dir, 'trusted', { CI: 'true', ...env }); + const ran = await turbowIn(dir, 'trusted', { CI: 'true', ...env }); assert.notEqual(ran.status, 0); assert.equal(ran.turbo, undefined, 'Turbo never ran'); assert.match(ran.said.join('\n'), /trusted cache server/); @@ -208,10 +220,10 @@ test('in CI without the trusted server, build and e2e fail and say why; they nev } }); -test('in CI where the tenant has no bucket, every verb runs without a remote cache and says so in one line', () => { +test('in CI where the tenant has no bucket, every verb runs without a remote cache and says so in one line', async () => { const dir = checkout(REMOTE); for (const cache of ['shared', 'trusted']) { - const ran = turbowIn(dir, cache, { CI: 'true', PLX_TURBO_SHARED: 'none', PLX_TURBO_TRUSTED: 'none' }); + const ran = await turbowIn(dir, cache, { CI: 'true', PLX_TURBO_SHARED: 'none', PLX_TURBO_TRUSTED: 'none' }); assert.equal(ran.status, 0, ran.said.join('\n')); assert.deepEqual(ran.turbo, { api: '', team: '', token: '', args: 'run check --filter={./apps/web}...' }); assert.equal(ran.said.length, 1, ran.said.join('\n')); @@ -219,7 +231,7 @@ test('in CI where the tenant has no bucket, every verb runs without a remote cac } }); -test('the team is owner-repo of origin, the same from SSH and HTTPS remotes and from any directory', () => { +test('the team is owner-repo of origin, the same from SSH and HTTPS remotes and from any directory', async () => { for (const remote of [ 'git@github.com:acme/web.git', 'git@github.com:Acme/Web', @@ -228,13 +240,13 @@ test('the team is owner-repo of origin, the same from SSH and HTTPS remotes and 'https://github.com/acme/web/', 'ssh://git@github.com/acme/web.git', ]) { - const ran = turbowIn(checkout(remote), 'shared', { PLX_TURBO_SHARED: answering }); + const ran = await turbowIn(checkout(remote), 'shared', { PLX_TURBO_SHARED: answering }); assert.equal(ran.turbo?.team, 'acme-web', remote); } }); -test('a checkout without origin has no team, and runs without a remote cache', () => { - const ran = turbowIn(checkout(), 'shared', { PLX_TURBO_SHARED: answering }); +test('a checkout without origin has no team, and runs without a remote cache', async () => { + const ran = await turbowIn(checkout(), 'shared', { PLX_TURBO_SHARED: answering }); assert.equal(ran.status, 0, ran.said.join('\n')); assert.deepEqual(ran.turbo, { api: '', team: '', token: '', args: 'run check --filter={./apps/web}...' }); assert.equal(ran.said.length, 1, ran.said.join('\n')); diff --git a/templates/repo-turbo/files/mise.toml.jinja b/templates/repo-turbo/files/mise.toml.jinja index e19c8027..73c78447 100644 --- a/templates/repo-turbo/files/mise.toml.jinja +++ b/templates/repo-turbo/files/mise.toml.jinja @@ -95,7 +95,7 @@ description = "Build the production artifacts, an app after the workspace packag {{ name_arg("build") }} run = ''' {{ scoped("build") }} -turbo run build ${dir:+--filter="{./$dir}..."} +./turbow trusted run build ${dir:+--filter="{./$dir}..."} ''' [tasks.check] @@ -106,7 +106,7 @@ run = ''' {{ scoped("check") }} mise run lint plx doctor -turbo run check ${dir:+--filter="{./$dir}..."} +./turbow shared run check ${dir:+--filter="{./$dir}..."} ''' [tasks.test] @@ -116,7 +116,7 @@ description = "Run check, then every test that lives beside the code; no built a run = ''' {{ scoped("test") }} mise run check ${usage_name:+"$usage_name"} -turbo run test ${dir:+--filter="{./$dir}..."} +./turbow shared run test ${dir:+--filter="{./$dir}..."} ''' [tasks.e2e] @@ -126,7 +126,7 @@ description = "Run the end-to-end suites, after the workspace packages they depe # A name selects the project and the projects that depend on it, since a suite is a package that depends on its app. run = ''' {{ scoped("e2e") }} -turbo run e2e ${dir:+--filter="...{./$dir}"} +./turbow trusted run e2e ${dir:+--filter="...{./$dir}"} ''' [tasks.install] diff --git a/templates/repo-turbo/files/turbow b/templates/repo-turbo/files/turbow new file mode 100755 index 00000000..ed710f6a --- /dev/null +++ b/templates/repo-turbo/files/turbow @@ -0,0 +1,76 @@ +#!/bin/sh +# Generated from plexus-ms/tooling, templates/repo-turbo. +# Turbo with the remote cache its verb may use: ./turbow , as the tasks of mise.toml +# call it. check and test use the shared cache, the bucket -ci-turbo, which every machine and CI write; build +# and e2e use the trusted one, -ci-turbo-trusted, whose keys only CI holds. A bucket is reached through a cache +# server on loopback: +# - Outside CI there is no trusted server, so every verb uses the shared one: the server PLX_TURBO_SHARED names, +# by default this machine's own on the fixed port, http://127.0.0.1:8585, which runs without a token. +# - In CI (CI is set) a verb uses only the server its job started (the step .github/actions/turbo-cache of +# plexus-ms/tooling), which PLX_TURBO_SHARED or PLX_TURBO_TRUSTED names, with the job's token in +# PLX_TURBO_SHARED_TOKEN or PLX_TURBO_TRUSTED_TOKEN. build and e2e never use the shared one there: without a +# trusted server they fail. +# A server named `none` is no server: the tenant has no bucket. Where there is no server, nothing answers, or the +# checkout has no origin, the verb runs without a remote cache and says so in one line. The team, which keeps the +# repos of a tenant apart in a bucket, is the repo's owner-repo, from the URL of origin, in lower case. +set -eu + +cache=${1:-} +case $cache in + shared | trusted) shift ;; + *) + echo "usage: ./turbow " >&2 + exit 2 + ;; +esac + +# Turbo sends a team and a token to Vercel when TURBO_API is unset, so the three are set together or not at all. +unset TURBO_API TURBO_TEAM TURBO_TOKEN + +reason= +case ${CI:-} in + '' | false | 0) + from=shared server=${PLX_TURBO_SHARED:-http://127.0.0.1:8585} token=${PLX_TURBO_SHARED_TOKEN:-local} + if [ "$server" != none ] && ! node -e ' + fetch(process.argv[1], { signal: AbortSignal.timeout(2000) }).then( + (answer) => process.exit(answer.ok ? 0 : 1), + () => process.exit(1), + );' "$server/management/health"; then + reason="nothing answers at $server" + fi + ;; + *) + if [ "$cache" = trusted ]; then + if [ -z "${PLX_TURBO_TRUSTED:-}" ]; then + echo "turbow: in CI, build and e2e need the trusted cache server, and this job started none (PLX_TURBO_TRUSTED is unset); they never use the shared one" >&2 + exit 1 + fi + from=trusted server=$PLX_TURBO_TRUSTED token=${PLX_TURBO_TRUSTED_TOKEN:-local} + else + from=shared server=${PLX_TURBO_SHARED:-} token=${PLX_TURBO_SHARED_TOKEN:-local} + [ -n "$server" ] || reason="this job started no shared cache server (PLX_TURBO_SHARED is unset)" + fi + ;; +esac +if [ "$server" = none ]; then + reason="the tenant has no $from bucket" +fi + +if [ -z "$reason" ]; then + if url=$(git remote get-url origin 2>/dev/null); then + path=${url%/} + path=${path%.git} + rest=${path%/*} + team=$(printf '%s-%s' "${rest##*[/:]}" "${path##*/}" | tr '[:upper:]' '[:lower:]') + else + reason="the checkout has no origin to name its team" + fi +fi + +if [ -n "$reason" ]; then + echo "turbow: without a remote cache: $reason" >&2 +else + echo "turbow: the $from remote cache at $server, team $team" >&2 + export TURBO_API="$server" TURBO_TEAM="$team" TURBO_TOKEN="$token" +fi +exec turbo "$@" From e77b29db7bb2920360b58158c07fc5b9de37fbc8 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:01:13 +0100 Subject: [PATCH 069/194] newborns: relock is a helper, shared by the newborn tests that add workspace packages Moved from repo-turbo.test.ts unchanged, with its reason, so that the newborn of app-nextjs relocks the same way; repo-turbo.test.ts now imports it. Co-Authored-By: Claude Fable 5.2 --- newborns/helpers.ts | 3 +++ newborns/repo-turbo.test.ts | 5 +---- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/newborns/helpers.ts b/newborns/helpers.ts index 03c66ec6..dab1db08 100644 --- a/newborns/helpers.ts +++ b/newborns/helpers.ts @@ -316,6 +316,9 @@ export async function born( /** The newborn's own `mise run `; extra arguments follow the task. */ export const mise = (dir: string, ...args: string[]) => tryRun('mise', ['run', ...args], dir); +/** The lockfile predates workspace packages added to a newborn; a frozen install (CI=true) would refuse it. */ +export const relock = (dir: string) => sh('mise', ['exec', '--', 'pnpm', 'install', '--lockfile-only'], dir); + /** The tools a newborn's `mise.toml` may pin from the packages built here, with the file of the build each one is. */ const BUILT = [ { tool: 'plx', pkg: 'cli', file: 'plx.js' }, diff --git a/newborns/repo-turbo.test.ts b/newborns/repo-turbo.test.ts index 37e87ed1..d9deafbb 100644 --- a/newborns/repo-turbo.test.ts +++ b/newborns/repo-turbo.test.ts @@ -20,7 +20,7 @@ import assert from 'node:assert/strict'; import { readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { after, before, describe, test } from 'node:test'; -import { awaitingDoctor, born, close, mise, open, pass, put, sh, tryRun } from './helpers.ts'; +import { awaitingDoctor, born, close, mise, open, pass, put, relock, sh, tryRun } from './helpers.ts'; let here = ''; before(async () => { @@ -52,9 +52,6 @@ async function hashes(dir: string, pkg: string, tasks: string[]): Promise [t.taskId, t.hash])); } -/** The lockfile predates workspace packages added to a newborn; a frozen install (CI=true) would refuse it. */ -const relock = (dir: string) => sh('mise', ['exec', '--', 'pnpm', 'install', '--lockfile-only'], dir); - /** git with an identity and no signing, as a newborn has neither. */ const git = (dir: string, ...args: string[]) => tryRun( From ab922a38eb5ab285688668158d87ddc92d87a6a0 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:02:04 +0100 Subject: [PATCH 070/194] newborns: the app-nextjs newborn relocks before it installs, so that it installs under CI=true On a runner CI=true makes pnpm's install frozen, and the lockfile of the newborn repo predates its two apps: the before hook failed with ERR_PNPM_PACKAGE_MANAGER_NO_IMPORTER and took all 13 tests with it (reproduced here with CI=true). It now relocks with the shared helper first, as the repo-turbo newborns do; the relock in the last test is then no longer needed. Co-Authored-By: Claude Fable 5.2 --- newborns/app-nextjs.test.ts | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/newborns/app-nextjs.test.ts b/newborns/app-nextjs.test.ts index c1a71ccb..3d5f23b0 100644 --- a/newborns/app-nextjs.test.ts +++ b/newborns/app-nextjs.test.ts @@ -16,7 +16,20 @@ import { cpSync, existsSync, readdirSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { after, before, test } from 'node:test'; -import { awaitingDoctor, born, close, freePort, open, pass, plxNew, put, sh, start, tryRun } from './helpers.ts'; +import { + awaitingDoctor, + born, + close, + freePort, + open, + pass, + plxNew, + put, + relock, + sh, + start, + tryRun, +} from './helpers.ts'; let here = ''; let repo = ''; @@ -38,6 +51,7 @@ before(async () => { await born(join(repo, 'apps', profile), ['app-nextjs'], { name: `@acme/${profile}`, profile }); // The stateful app has no public/ until its image test, so that a build without one is shown too. put(join(repo, 'apps', 'stateless'), { 'public/pixel.png': PIXEL }); + await relock(repo); await sh('mise', ['exec', '--', 'pnpm', 'install'], repo); // Tracked, as in a checkout: Turbo hashes what git tracks, and an untracked app's build output with it. await sh('git', ['add', '-A'], repo); @@ -260,7 +274,5 @@ for (const profile of PROFILES) { } test('the repo around the apps passes its own test, which includes check', async () => { - // The lockfile predates the apps, and under CI=true the check's frozen install refuses it. - await sh('mise', ['exec', '--', 'pnpm', 'install', '--lockfile-only'], repo); await pass(repo, 'acme', 'test'); }); From d9ad843ea58c2dbf6f35fe527e10751c707e6013 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:03:08 +0100 Subject: [PATCH 071/194] newborns: a newborn's verbs against a real cache server and an S3 stand-in, and the cache step as a job runs it Red: the step .github/actions/turbo-cache does not exist yet. On a developer's machine mise test writes the shared bucket and a second clone hits it; in a CI job the step's trusted server takes build and e2e and the shared server sees nothing; a tenant without a bucket runs without a remote cache; a CI job without the step fails its build. The newborn world names no cache server, so that no newborn reaches the user's own, or fails in CI for want of a trusted one. Co-Authored-By: Claude Fable 5.2 --- newborns/helpers.ts | 7 + newborns/turbo-cache.test.ts | 318 +++++++++++++++++++++++++++++++++++ 2 files changed, 325 insertions(+) create mode 100644 newborns/turbo-cache.test.ts diff --git a/newborns/helpers.ts b/newborns/helpers.ts index edf23e6e..d7f38361 100644 --- a/newborns/helpers.ts +++ b/newborns/helpers.ts @@ -32,6 +32,11 @@ // package built here: mise installs those, into scratch. Nothing is written to // the user's `~/.npmrc` or mise configuration. // +// Remote cache. A newborn's verbs reach no Turbo remote cache unless its test +// names the server (PLX_TURBO_SHARED, PLX_TURBO_TRUSTED, read by repo-turbo's +// turbow): never the server the user's machine may run on its fixed port, and +// in CI no build fails for want of a trusted server. +// // Time limit. A command that outlives LIMIT is killed with everything it // started, its whole process group. import { execFileSync, spawn } from 'node:child_process'; @@ -235,6 +240,8 @@ export async function open(name: string, options: { users?: string; registry?: b MISE_STATE_DIR: join(dir, 'mise-state'), MISE_DATA_DIR: join(dir, 'mise-data'), MISE_SYSTEM_DATA_DIR: seeFromUsers(dir, options.users), + PLX_TURBO_SHARED: 'none', + PLX_TURBO_TRUSTED: 'none', }; world = { dir, env }; try { diff --git a/newborns/turbo-cache.test.ts b/newborns/turbo-cache.test.ts new file mode 100644 index 00000000..edfdd085 --- /dev/null +++ b/newborns/turbo-cache.test.ts @@ -0,0 +1,318 @@ +// A newborn app repo with Turbo's two remote caches (repo-turbo's turbow, and +// the step .github/actions/turbo-cache of this repo), against a real cache +// server and an S3 stand-in. The stand-in is RustFS in a container, published +// on a free loopback port, with the tenant acme's two buckets; the server is +// the binary the step's action starts, fetched at the commit the step pins. +// +// On a developer's machine (CI unset), with the shared server running without +// a token as a developer runs it: `mise test` writes the shared bucket under +// the team acme-web, and a second clone, by another remote form of the same +// repo, hits every task; `mise build` and `mise e2e` use the shared server too. +// In a CI job (CI=true), run as a job runs the step: its scripts plan and +// announce around the server, which is started with the environment the step +// gives the action, and the vault's read stood in for by the stand-in's keys. +// With the trusted server, `build` and `e2e` write the trusted bucket and the +// shared server sees no request; `check` and `test` find no shared server in +// that job and run without one. Where the tenant has no bucket the verbs run +// without a remote cache; without the step `build` fails. Every case sets or +// unsets CI itself. Needs Docker and the network, as the newborns do. +import assert from 'node:assert/strict'; +import { type ChildProcess, spawn } from 'node:child_process'; +import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { arch, platform } from 'node:os'; +import { join } from 'node:path'; +import { after, before, describe, test } from 'node:test'; +import { awaitingDoctor, born, close, open, put, sh, tryRun } from './helpers.ts'; + +const WORKSPACE = join(import.meta.dirname, '..'); +const STEP = join(WORKSPACE, '.github', 'actions', 'turbo-cache'); +const RUSTFS = 'rustfs/rustfs:1.0.5'; +const KEY = 'newborn-access'; +const SECRET = 'newborn-secret-not-a-real-one'; +const SHARED_BUCKET = 'acme-ci-turbo'; +const TRUSTED_BUCKET = 'acme-ci-turbo-trusted'; + +let here = ''; +let container = ''; +let s3 = ''; +let binary = ''; +const servers: { child: ChildProcess; log: string[] }[] = []; + +async function freePort(): Promise { + const probe = createServer(); + await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); + const address = probe.address(); + await new Promise((resolve) => probe.close(() => resolve())); + if (address === null || typeof address === 'string') throw new Error('no port'); + return address.port; +} + +/** Waits until `url` answers 200, or throws after a minute. */ +async function answers(url: string): Promise { + const until = Date.now() + 60_000; + for (;;) { + try { + if ((await fetch(url)).ok) return; + } catch {} + if (Date.now() > until) throw new Error(`${url} did not answer`); + await new Promise((resolve) => setTimeout(resolve, 250)); + } +} + +/** One S3 call to the stand-in, signed by curl. */ +const s3call = (method: string, path: string) => + sh( + 'curl', + ['-fsS', '-X', method, '--aws-sigv4', 'aws:amz:us-east-1:s3', '--user', `${KEY}:${SECRET}`, `${s3}/${path}`], + here, + ); + +/** The keys of a bucket below a team, as the server writes them: `/`. */ +async function keys(bucket: string, team = 'acme-web'): Promise { + const xml = await s3call('GET', `${bucket}?list-type=2&prefix=${team}/`); + return [...xml.matchAll(/([^<]*)<\/Key>/g)].map((m) => m[1] ?? ''); +} + +/** The server's binary for this machine, at the commit of the action the step pins. */ +async function fetchServer(): Promise { + const step = readFileSync(join(STEP, 'action.yml'), 'utf8'); + const sha = /uses: brunojppb\/turbo-cache-server@([0-9a-f]{40})/.exec(step)?.[1]; + if (!sha) throw new Error('the step pins no brunojppb/turbo-cache-server by commit'); + // The names the action's own action/util.mjs picks. + const name = platform() === 'darwin' ? `decay-darwin-${arch()}` : `decay-${arch()}`; + const answer = await fetch(`https://raw.githubusercontent.com/brunojppb/turbo-cache-server/${sha}/action/${name}`); + if (!answer.ok) throw new Error(`no server binary ${name} at ${sha}: ${answer.status}`); + const path = join(here, name); + writeFileSync(path, Buffer.from(await answer.arrayBuffer())); + chmodSync(path, 0o755); + return path; +} + +/** + * A cache server for `bucket` on `port`, from an empty environment and an empty + * directory, so that no TURBO_TOKEN reaches it but `token`; its log is kept. + */ +async function serve(bucket: string, port: number, token?: string): Promise { + const cwd = join(here, `server-${port}`); + mkdirSync(cwd); + const child = spawn(binary, [], { + cwd, + detached: true, + stdio: ['ignore', 'pipe', 'pipe'], + env: { + PATH: '/usr/bin:/bin', + OTEL_SDK_DISABLED: 'true', + PORT: String(port), + S3_ENDPOINT: s3, + S3_REGION: 'us-east-1', + S3_BUCKET_NAME: bucket, + S3_ACCESS_KEY: KEY, + S3_SECRET_KEY: SECRET, + S3_USE_PATH_STYLE: 'true', + ...(token ? { TURBO_TOKEN: token } : {}), + }, + }); + const log: string[] = []; + child.stdout?.on('data', (chunk: Buffer) => log.push(...chunk.toString().split('\n').filter(Boolean))); + child.stderr?.on('data', (chunk: Buffer) => log.push(...chunk.toString().split('\n').filter(Boolean))); + servers.push({ child, log }); + await answers(`http://127.0.0.1:${port}/management/health`); + return log; +} + +/** The artifact requests of a server's log. */ +const requests = (log: string[]) => log.filter((line) => line.includes('/v8/artifacts')); + +before(async () => { + here = await open('turbo-cache'); + container = ( + await sh( + 'docker', + [ + 'run', + '-d', + '--rm', + '-p', + '127.0.0.1::9000', + '-e', + `RUSTFS_ACCESS_KEY=${KEY}`, + '-e', + `RUSTFS_SECRET_KEY=${SECRET}`, + RUSTFS, + ], + here, + ) + ).trim(); + const published = (await sh('docker', ['port', container, '9000/tcp'], here)).trim().split('\n')[0] ?? ''; + s3 = `http://${published}`; + const until = Date.now() + 60_000; + const listing = ['-fsS', '-o', '/dev/null', '--aws-sigv4', 'aws:amz:us-east-1:s3', '--user', `${KEY}:${SECRET}`]; + while ((await tryRun('curl', [...listing, `${s3}/`], here)).ok === false) { + if (Date.now() > until) throw new Error(`the S3 stand-in at ${s3} did not come up`); + await new Promise((resolve) => setTimeout(resolve, 500)); + } + await s3call('PUT', SHARED_BUCKET); + await s3call('PUT', TRUSTED_BUCKET); + binary = await fetchServer(); +}); + +after(async () => { + for (const { child } of servers) + try { + if (child.pid) process.kill(-child.pid, 'SIGKILL'); + } catch {} + if (container) await tryRun('docker', ['rm', '-f', container], here); + await close(); +}); + +/** git with an identity and no signing, as a newborn has neither. */ +const git = (dir: string, ...args: string[]) => + sh( + 'git', + ['-c', 'commit.gpgsign=false', '-c', 'user.name=newborn', '-c', 'user.email=newborn@example.invalid', ...args], + dir, + ); + +/** A fresh clone of `from`, its origin at `remote`, with its tools installed: what a checkout on another machine is. */ +async function clone(from: string, name: string, remote: string): Promise { + const dir = join(here, name); + await git(here, 'clone', '-q', from, dir); + await git(dir, 'remote', 'set-url', 'origin', remote); + await sh('sh', ['-c', 'mise trust && mise install'], dir); + return dir; +} + +/** `mise run ` in `dir` with `env`, which must pass; its output. */ +async function verb(dir: string, task: string, env: Record): Promise { + const ran = await tryRun('mise', ['run', task], dir, env); + if (!ran.ok) throw new Error(`mise run ${task} failed in ${dir}:\n${ran.output}`); + return ran.output; +} + +/** The lines `KEY=value` a step wrote to a file of the runner's, GITHUB_OUTPUT or GITHUB_ENV. */ +const pairs = (file: string): Record => + Object.fromEntries( + readFileSync(file, 'utf8') + .split('\n') + .filter((line) => line.includes('=')) + .map((line) => [line.slice(0, line.indexOf('=')), line.slice(line.indexOf('=') + 1)]), + ); + +let runs = 0; +/** One phase of the step's script, as its action runs it: `env` and the runner's files; what it wrote to each. */ +async function step(phase: string, env: Record) { + const n = runs++; + const output = join(here, `github-output-${n}`); + const githubEnv = join(here, `github-env-${n}`); + writeFileSync(output, ''); + writeFileSync(githubEnv, ''); + const ran = await tryRun('bash', [join(STEP, 'turbo-cache.sh'), phase], here, { + GITHUB_OUTPUT: output, + GITHUB_ENV: githubEnv, + OP_CONNECT_HOST: '', + OP_CONNECT_TOKEN: '', + ...env, + }); + assert.ok(ran.ok, ran.output); + return { said: ran.output, outputs: pairs(output), env: pairs(githubEnv) }; +} + +describe('a newborn app repo with the two remote caches', () => { + let origin = ''; + let sharedUrl = ''; + let sharedLog: string[] = []; + before(async () => { + origin = await awaitingDoctor(await born(join(here, 'web'), ['repo-turbo', 'updates'], { tenant: 'acme' })); + // A package and an app built from it, each writing its build output and printing what it ran. + const scripts = (name: string) => ({ + build: `mkdir -p dist && echo ${name} > dist/index.js && echo build-ran ${name}`, + check: `echo check-ran ${name}`, + test: `echo test-ran ${name}`, + e2e: `echo e2e-ran ${name}`, + }); + put(origin, { + 'packages/lib/package.json': { name: 'lib', version: '0.0.0', private: true, scripts: scripts('lib') }, + 'packages/site/package.json': { + name: 'site', + version: '0.0.0', + private: true, + scripts: scripts('site'), + dependencies: { lib: 'workspace:*' }, + }, + }); + await sh('mise', ['exec', '--', 'pnpm', 'install', '--lockfile-only'], origin); + await git(origin, 'add', '-A'); + await git(origin, 'commit', '--no-verify', '-q', '-m', 'born'); + const port = await freePort(); + sharedUrl = `http://127.0.0.1:${port}`; + sharedLog = await serve(SHARED_BUCKET, port); + }); + + test('on a developer’s machine, mise test writes the shared bucket, and a second clone hits it', async () => { + const machine = { CI: '', PLX_TURBO_SHARED: sharedUrl, PLX_TURBO_TRUSTED: '' }; + const first = await clone(origin, 'first', 'https://github.com/acme/web.git'); + const tested = await verb(first, 'test', machine); + assert.match(tested, /turbow: the shared remote cache at http:\/\/127\.0\.0\.1:\d+, team acme-web/); + assert.match(tested, /test-ran site/); + const written = await keys(SHARED_BUCKET); + assert.ok(written.length >= 4, `the shared bucket holds the run's tasks under acme-web: ${written}`); + + const second = await clone(origin, 'second', 'git@github.com:acme/web.git'); + const again = await verb(second, 'test', machine); + assert.match(again, /cache hit, replaying logs/); + assert.doesNotMatch(again, /cache miss/, 'every task of the second clone is a hit'); + + // Outside CI there is no trusted server: build and e2e use the shared one. + for (const task of ['build', 'e2e']) + assert.match(await verb(second, task, machine), /turbow: the shared remote cache at /, task); + }); + + test('in a CI job with the step’s trusted server, build and e2e write the trusted bucket, and the shared server sees nothing', async () => { + const job = await clone(origin, 'trusted-job', 'https://github.com/acme/web'); + const plan = await step('plan', { CACHE: 'trusted', OWNER: 'acme', VAULT: 'acme-ci', SERVICE_ACCOUNT: 'true' }); + assert.equal(plan.outputs.read, 'true'); + assert.equal(plan.outputs.bucket, TRUSTED_BUCKET); + assert.equal(plan.outputs.item, 'bucket-turbo-trusted'); + const port = Number(plan.outputs.port); + const token = plan.outputs.token ?? ''; + assert.match(token, /^[0-9a-f]{64}$/, 'a token minted for the job'); + // What the action is given by the step: the planned port and token, the bucket, and the keys the vault holds. + await serve(plan.outputs.bucket ?? '', port, token); + const told = await step('announce', { CACHE: 'trusted', KEYS: 'success', PORT: String(port), TOKEN: token }); + assert.deepEqual(told.env, { PLX_TURBO_TRUSTED: `http://127.0.0.1:${port}`, PLX_TURBO_TRUSTED_TOKEN: token }); + + const before = requests(sharedLog).length; + const ci = { CI: 'true', PLX_TURBO_SHARED: '', ...told.env }; + for (const task of ['build', 'e2e']) + assert.match(await verb(job, task, ci), /turbow: the trusted remote cache at /, task); + assert.ok((await keys(TRUSTED_BUCKET)).length >= 3, 'the trusted bucket holds the builds and the e2e runs'); + const tested = await verb(job, 'test', ci); + assert.match(tested, /turbow: without a remote cache: this job started no shared cache server/); + assert.equal(requests(sharedLog).length, before, 'the shared server saw no request from the job'); + }); + + test('in a CI job where the tenant has no bucket, the step says so and every verb runs without a remote cache', async () => { + const job = await clone(origin, 'bucketless-job', 'https://github.com/acme/web'); + const plan = await step('plan', { CACHE: 'trusted', OWNER: 'acme', VAULT: 'acme-ci', SERVICE_ACCOUNT: 'false' }); + assert.equal(plan.outputs.read, 'false'); + const told = await step('announce', { CACHE: 'trusted', KEYS: 'skipped' }); + assert.deepEqual(told.env, { PLX_TURBO_TRUSTED: 'none' }); + assert.match(told.said, /without the trusted remote cache/); + const built = await verb(job, 'build', { CI: 'true', PLX_TURBO_SHARED: '', ...told.env }); + assert.match(built, /turbow: without a remote cache: the tenant has no trusted bucket/); + assert.match(built, /build-ran site/); + }); + + test('in a CI job without the step, build fails and says why', async () => { + const job = await clone(origin, 'stepless-job', 'https://github.com/acme/web'); + const ran = await tryRun('mise', ['run', 'build'], job, { + CI: 'true', + PLX_TURBO_SHARED: sharedUrl, + PLX_TURBO_TRUSTED: '', + }); + assert.equal(ran.ok, false); + assert.match(ran.output, /in CI, build and e2e need the trusted cache server/); + assert.doesNotMatch(ran.output, /build-ran/); + }); +}); From 479ad7b5e184e93900b780c5babbf2f2eec3933a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:06:05 +0100 Subject: [PATCH 072/194] the step turbo-cache: one cache server per job, shared or trusted, from the tenant's vault A composite action for the reusable workflows: plan (bucket, vault item, whether the vault can be read, a free port from 8585 and a token minted for the job), the keys from the vault, the server, and announce, which tells turbow where the server is, or that the job runs without that remote cache because the vault has no such bucket. The keys go to the server alone. The header lists the two vault items with their buckets. The newborn test's build output is a text file now: an app repo's dist/ is not ignored, and biome linted the fixture's. Co-Authored-By: Claude Fable 5.2 --- .github/actions/turbo-cache/action.yml | 87 ++++++++++++++++++++++ .github/actions/turbo-cache/turbo-cache.sh | 81 ++++++++++++++++++++ newborns/turbo-cache.test.ts | 2 +- 3 files changed, 169 insertions(+), 1 deletion(-) create mode 100644 .github/actions/turbo-cache/action.yml create mode 100755 .github/actions/turbo-cache/turbo-cache.sh diff --git a/.github/actions/turbo-cache/action.yml b/.github/actions/turbo-cache/action.yml new file mode 100644 index 00000000..d21b9986 --- /dev/null +++ b/.github/actions/turbo-cache/action.yml @@ -0,0 +1,87 @@ +name: Turbo cache server +description: >- + Starts the Turbo remote cache server a job needs, on loopback, against the + tenant's shared or trusted bucket, and tells the repo's turbow where it is. + +# A step for the jobs of the reusable workflows, which call it as +# `uses: $/.github/actions/turbo-cache`: from this repo at the commit of the +# workflow that calls it, never a version behind or ahead of it. One cache per +# job: a job that runs check and test starts the shared one, a job that runs +# build or e2e the trusted one, and never the two together, so that nothing the +# shared bucket supplied enters a build written to the trusted bucket. +# +# The vault items it reads, in the vault `-ci` unless `vault` names +# another, each with the fields endpoint, region, access-key-id and +# secret-access-key of an S3 store: +# +# bucket-turbo the shared bucket -ci-turbo +# bucket-turbo-trusted the trusted bucket -ci-turbo-trusted +# +# The server is brunojppb/turbo-cache-server, path-style against the bucket, +# with a token minted for the job and on the first free port from 8585 up +# (turbo-cache.sh says why). A job without vault credentials, or whose vault +# has no such item, runs without that remote cache and says so in one line: +# a tenant without the bucket. The keys go to the server alone and never to +# the job's environment; what the job's later steps get is the server's +# address and token, in the variables turbow reads. + +inputs: + cache: + description: "`shared`, the bucket -ci-turbo, for check and test; `trusted`, the bucket -ci-turbo-trusted, for build and e2e." + required: true + vault: + description: The vault the keys are read from (§ 3 PLX-Secrets). Default -ci. + required: false + default: '' + op-service-account-token: + description: The vault's service account token; not needed on a slot of a runner host, which reads the vault through its Connect server. + required: false + default: '' + +runs: + using: composite + steps: + - name: Plan the cache server + id: plan + shell: bash + env: + CACHE: ${{ inputs.cache }} + OWNER: ${{ github.repository_owner }} + VAULT: ${{ inputs.vault || format('{0}-ci', github.repository_owner) }} + SERVICE_ACCOUNT: ${{ inputs.op-service-account-token != '' }} + run: '"$GITHUB_ACTION_PATH/turbo-cache.sh" plan' + # A failed read is a tenant without the bucket, or a vault that cannot be + # read: the job runs on without the remote cache, and announce says so. + - name: Load the bucket's keys from the vault + id: keys + if: ${{ steps.plan.outputs.read == 'true' }} + continue-on-error: true + uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 + env: + # On a slot the Connect server alone, as both would warn. + OP_SERVICE_ACCOUNT_TOKEN: ${{ steps.plan.outputs.connect != 'true' && inputs.op-service-account-token || '' }} + ENDPOINT: op://${{ steps.plan.outputs.vault }}/${{ steps.plan.outputs.item }}/endpoint + REGION: op://${{ steps.plan.outputs.vault }}/${{ steps.plan.outputs.item }}/region + ACCESS_KEY: op://${{ steps.plan.outputs.vault }}/${{ steps.plan.outputs.item }}/access-key-id + SECRET_KEY: op://${{ steps.plan.outputs.vault }}/${{ steps.plan.outputs.item }}/secret-access-key + - name: Start the cache server + if: ${{ steps.keys.outcome == 'success' }} + uses: brunojppb/turbo-cache-server@7d5eed8f1768a2209c88b2af58da1827b47eedcc # 5.0.4 + env: + PORT: ${{ steps.plan.outputs.port }} + TURBO_TOKEN: ${{ steps.plan.outputs.token }} + S3_ENDPOINT: ${{ steps.keys.outputs.ENDPOINT }} + S3_REGION: ${{ steps.keys.outputs.REGION }} + S3_BUCKET_NAME: ${{ steps.plan.outputs.bucket }} + S3_ACCESS_KEY: ${{ steps.keys.outputs.ACCESS_KEY }} + S3_SECRET_KEY: ${{ steps.keys.outputs.SECRET_KEY }} + S3_USE_PATH_STYLE: 'true' + - name: Tell turbow where the server is + shell: bash + env: + CACHE: ${{ inputs.cache }} + KEYS: ${{ steps.keys.outcome || 'skipped' }} + VAULT: ${{ steps.plan.outputs.vault }} + PORT: ${{ steps.plan.outputs.port }} + TOKEN: ${{ steps.plan.outputs.token }} + run: '"$GITHUB_ACTION_PATH/turbo-cache.sh" announce' diff --git a/.github/actions/turbo-cache/turbo-cache.sh b/.github/actions/turbo-cache/turbo-cache.sh new file mode 100755 index 00000000..a300fb11 --- /dev/null +++ b/.github/actions/turbo-cache/turbo-cache.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# The two phases of the step turbo-cache (action.yml beside this file) that +# are its own, around the vault's read and the server's start, which are +# actions of their own: +# +# plan Which bucket and vault item the cache (CACHE, `shared` or +# `trusted`) names for the owner (OWNER), and whether the job can +# read the vault (VAULT): through the runner's Connect server +# (OP_CONNECT_HOST and OP_CONNECT_TOKEN, as a slot of a runner host +# has them) or with the service account (SERVICE_ACCOUNT, `true` +# when the caller passed its token). For the server: the first +# free port from 8585 up, since the slots of a runner host share +# its loopback, and a token minted for this job, masked in the log, +# without which another job on the host could read and write the +# bucket through the server. Outputs: read, connect, vault, item, +# bucket, port, token. +# announce Tells turbow (repo-turbo) where the server is, through the job's +# environment: PLX_TURBO_SHARED or PLX_TURBO_TRUSTED with the +# server's address and PLX_TURBO__TOKEN with the job's token +# when the keys were read (KEYS, the outcome of the read: `success`) +# and the server started on PORT with TOKEN; else the variable is +# `none`, and the step says in one line why the job runs without +# that remote cache: no vault to read (`skipped`), or no item in it +# that could be read (`failure`, the step above says why). +# +# Run by hand, a phase needs only GITHUB_OUTPUT and GITHUB_ENV to name files. +set -euo pipefail + +case ${CACHE:-} in + shared) item=bucket-turbo suffix='' var=PLX_TURBO_SHARED ;; + trusted) item=bucket-turbo-trusted suffix=-trusted var=PLX_TURBO_TRUSTED ;; + *) + echo "::error::The cache is shared or trusted, not '${CACHE:-}'." + exit 1 + ;; +esac + +case ${1:-} in + plan) + connect=false + if [ -n "${OP_CONNECT_HOST:-}" ] && [ -n "${OP_CONNECT_TOKEN:-}" ]; then connect=true; fi + read=$connect + if [ "${SERVICE_ACCOUNT:-false}" = true ]; then read=true; fi + port=8585 + while (exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null; do port=$((port + 1)); done + token=$(openssl rand -hex 32) + echo "::add-mask::$token" + { + echo "read=$read" + echo "connect=$connect" + echo "vault=$VAULT" + echo "item=$item" + echo "bucket=$OWNER-ci-turbo$suffix" + echo "port=$port" + echo "token=$token" + } >>"$GITHUB_OUTPUT" + ;; + announce) + case ${KEYS:-} in + success) + { + echo "$var=http://127.0.0.1:${PORT:?}" + echo "${var}_TOKEN=${TOKEN:?}" + } >>"$GITHUB_ENV" + echo "The $CACHE remote cache: a server on 127.0.0.1:$PORT." + ;; + skipped) + echo "$var=none" >>"$GITHUB_ENV" + echo "Turbo runs without the $CACHE remote cache: this job has no vault to read its keys from." + ;; + *) + echo "$var=none" >>"$GITHUB_ENV" + echo "Turbo runs without the $CACHE remote cache: the vault ${VAULT:-} has no item $item that could be read (the step above says why)." + ;; + esac + ;; + *) + echo "usage: turbo-cache.sh plan|announce" >&2 + exit 2 + ;; +esac diff --git a/newborns/turbo-cache.test.ts b/newborns/turbo-cache.test.ts index edfdd085..a2870985 100644 --- a/newborns/turbo-cache.test.ts +++ b/newborns/turbo-cache.test.ts @@ -226,7 +226,7 @@ describe('a newborn app repo with the two remote caches', () => { origin = await awaitingDoctor(await born(join(here, 'web'), ['repo-turbo', 'updates'], { tenant: 'acme' })); // A package and an app built from it, each writing its build output and printing what it ran. const scripts = (name: string) => ({ - build: `mkdir -p dist && echo ${name} > dist/index.js && echo build-ran ${name}`, + build: `mkdir -p dist && echo ${name} > dist/out.txt && echo build-ran ${name}`, check: `echo check-ran ${name}`, test: `echo test-ran ${name}`, e2e: `echo e2e-ran ${name}`, From 47b00d85667167a16c04a357c1707544228313ae Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:06:50 +0100 Subject: [PATCH 073/194] tests: the cache is wired for every repo, and no answer about registries reads it Red: _check.yml still has the input turbo-cache, the workflows of repo-turbo still pass it from ci_registry, and a package repo's check job does not hand the vault's token on. The tests of packages/lib now take .github/ as an input, since one of them reads _check.yml. Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/repoTurboCache.test.ts | 51 ++++++++++++++++++++++++- packages/lib/turbo.json | 2 +- 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/packages/lib/src/repoTurboCache.test.ts b/packages/lib/src/repoTurboCache.test.ts index 7f27be15..f3c64f64 100644 --- a/packages/lib/src/repoTurboCache.test.ts +++ b/packages/lib/src/repoTurboCache.test.ts @@ -7,13 +7,14 @@ // against a real server and an S3 stand-in. import assert from 'node:assert/strict'; import { execFile, execFileSync } from 'node:child_process'; -import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { createServer, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { after, before, test } from 'node:test'; -import { renderBundled, textOf } from './testing/bundled.ts'; +import { parse } from 'yaml'; +import { pathsOf, renderBundled, textOf } from './testing/bundled.ts'; const SHAPES = [{}, { publishes_packages: true }]; const render = (answers: Record = {}) => renderBundled(['repo-turbo'], { tenant: 'acme', ...answers }); @@ -252,3 +253,49 @@ test('a checkout without origin has no team, and runs without a remote cache', a assert.equal(ran.said.length, 1, ran.said.join('\n')); assert.match(ran.said[0] ?? '', /without a remote cache.*origin/); }); + +// Where a job gets its cache server: the step turbo-cache of this repo, which _check.yml starts for every repo. + +/** The job `name` of a rendered workflow, as text, up to the next job. */ +const jobOf = (workflow: string, name: string): string => + new RegExp(`^ ${name}:\\n([\\s\\S]*?)(?=^ [\\w-]+:\\n|(?![\\s\\S]))`, 'm').exec(workflow)?.[1] ?? ''; + +test('no workflow of a repo asks for the cache, and the answer ci_registry changes nothing of the check job', async () => { + for (const ci_strategy of ['github', 'on-prem', 'hybrid']) + for (const answers of SHAPES) { + const results = await Promise.all( + ['ghcr', 'own'].map((ci_registry) => render({ ...answers, ci_strategy, ci_registry })), + ); + for (const result of results) + for (const path of pathsOf(result).filter((p) => p.startsWith('.github/workflows/'))) + assert.doesNotMatch(textOf(result, path), /turbo-cache/, path); + const [ghcr, own] = results; + if (!ghcr || !own) throw new Error('two renders'); + for (const path of pathsOf(ghcr).filter((p) => p.startsWith('.github/workflows/on_'))) + assert.equal(jobOf(textOf(ghcr, path), 'check'), jobOf(textOf(own, path), 'check'), `${path} ${ci_strategy}`); + } +}); + +test('a package repo’s check job hands the vault’s token to _check.yml, as an app repo’s does', async () => { + for (const answers of SHAPES) { + const result = await render(answers); + for (const path of ['.github/workflows/on_pr.yml', '.github/workflows/on_push.yml']) { + const check = jobOf(textOf(result, path), 'check'); + assert.match(check, /_check\.yml@/, path); + assert.match(check, /op-service-account-token: \$\{\{ secrets\.OP_SERVICE_ACCOUNT_TOKEN \}\}/, path); + } + } +}); + +test('_check.yml starts the shared cache server for every repo, by the step at the commit of the workflow', () => { + const workflow = parse( + readFileSync(join(import.meta.dirname, '..', '..', '..', '.github', 'workflows', '_check.yml'), 'utf8'), + ); + assert.ok(!('turbo-cache' in workflow.on.workflow_call.inputs), 'no input switches the cache'); + const steps: { uses?: string; if?: string; with?: Record }[] = workflow.jobs.check.steps; + const cache = steps.filter((step) => step.uses?.includes('turbo-cache')); + assert.equal(cache.length, 1); + assert.equal(cache[0]?.uses, '$/.github/actions/turbo-cache'); + assert.equal(cache[0]?.with?.cache, 'shared'); + assert.equal(cache[0]?.if, undefined, 'started for every repo'); +}); diff --git a/packages/lib/turbo.json b/packages/lib/turbo.json index 70ca5e94..0f0696d1 100644 --- a/packages/lib/turbo.json +++ b/packages/lib/turbo.json @@ -2,7 +2,7 @@ "extends": ["//"], "tasks": { "test": { - "inputs": ["$TURBO_DEFAULT$", "../../templates/**"] + "inputs": ["$TURBO_DEFAULT$", "../../templates/**", "../../.github/**"] } } } From bf38e8a0d8390997c7787b250e420da17f0736b8 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:07:15 +0100 Subject: [PATCH 074/194] _check.yml: the shared cache server for every repo, through the step turbo-cache (forced edit) The input turbo-cache goes, and with it the answer ci_registry as the switch: every job of _check.yml starts the shared server, by $/.github/actions/turbo-cache at the commit of the workflow, and runs without it where the tenant has no bucket. actionlint 1.7.12 does not know the reference $/, documented by GitHub and in runners from 2.336.0; its one message about it is ignored until an actionlint that knows it. Co-Authored-By: Claude Fable 5.2 --- .github/actionlint.yaml | 8 ++++ .github/workflows/_check.yml | 78 +++++------------------------------- 2 files changed, 19 insertions(+), 67 deletions(-) create mode 100644 .github/actionlint.yaml diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 00000000..7b7c9bdc --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,8 @@ +# actionlint 1.7.12, the newest, does not know the reference `$/` to an +# action of the repo that holds the workflow, at the workflow's own commit, +# which GitHub documents and runners have from 2.336.0. Drop this when an +# actionlint that knows it is pinned. +paths: + .github/workflows/**/*.yml: + ignore: + - 'specifying action "\$/[^"]+" in invalid format because ref is missing' diff --git a/.github/workflows/_check.yml b/.github/workflows/_check.yml index b9fc5031..4821f2e4 100644 --- a/.github/workflows/_check.yml +++ b/.github/workflows/_check.yml @@ -7,10 +7,11 @@ name: _check # repo without images to build passes `tasks: verify`, its whole contract # verb. The incantations are the repo's own mise tasks. # -# With `turbo-cache`, Turbo's remote cache (§ 8 PLX-Delivery): a cache server -# for the length of the job, on loopback, backed by the bucket -# -ci-turbo, whose keys are read from the vault; a task whose inputs -# did not change is replayed from any earlier job on any runner. +# Turbo's shared remote cache (§ 8 PLX-Delivery), for every repo: a cache +# server for the length of the job, on loopback, backed by the bucket +# -ci-turbo, started by the step turbo-cache of this repo at the +# commit of this workflow; a task whose inputs did not change is replayed from +# any earlier job on any runner. A tenant without the bucket runs without it. on: workflow_call: @@ -34,11 +35,6 @@ on: required: false type: string default: check - turbo-cache: - description: Use Turbo's remote cache in the tenant's bucket; needs the vault's token. - required: false - type: boolean - default: false private-packages: description: >- The repo installs private packages of the tenant's from the forge's @@ -54,76 +50,24 @@ on: default: '' secrets: op-service-account-token: - description: The vault's service account token; needed with `turbo-cache` only. + description: The vault's service account token, for the cache's keys where the runner has no Connect server. required: false # No permissions of its own: the job has what its caller grants, `contents: # read` and, with `private-packages`, `packages: read`. A block here would # have to name the larger set, and every caller would then have to grant it. -env: - VAULT: ${{ inputs.vault || format('{0}-ci', github.repository_owner) }} - jobs: check: runs-on: ${{ inputs.strategy == 'github' && 'ubuntu-latest' || format('ci-{0}', inputs.size) }} steps: - # How the job reads the vault (§ 8 PLX-Delivery): a slot of a runner host - # carries its Connect server's address and token (actions_runners), and - # every other runner gets the service account's. Never both: each read - # would warn, and a slot's job has no use for the service account. - - name: How the vault is read - if: ${{ inputs.turbo-cache }} - env: - TOKEN: ${{ secrets.op-service-account-token }} - run: | - if [ -n "${OP_CONNECT_HOST:-}" ] && [ -n "${OP_CONNECT_TOKEN:-}" ]; then - echo "Through the runner's Connect server." - else - echo "OP_SERVICE_ACCOUNT_TOKEN=$TOKEN" >> "$GITHUB_ENV" - echo "With the service account." - fi - uses: actions/checkout@v7 - - name: Load the Turbo cache bucket's keys from the vault - if: ${{ inputs.turbo-cache }} - uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 + - name: Start the shared cache server + uses: $/.github/actions/turbo-cache with: - export-env: true - env: - TURBO_CACHE_ENDPOINT: op://${{ env.VAULT }}/bucket-turbo/endpoint - TURBO_CACHE_REGION: op://${{ env.VAULT }}/bucket-turbo/region - TURBO_CACHE_ACCESS_KEY: op://${{ env.VAULT }}/bucket-turbo/access-key-id - TURBO_CACHE_SECRET_KEY: op://${{ env.VAULT }}/bucket-turbo/secret-access-key - # The server's token is minted here and never leaves the machine; the - # port is the first free one, since the slots of a runner host share - # its network. - - name: Prepare the Turbo remote cache - id: turbo-cache - if: ${{ inputs.turbo-cache }} - run: | - port=8585 - while (exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null; do port=$((port + 1)); done - token=$(openssl rand -hex 32) - echo "::add-mask::$token" - { - echo "port=$port" - echo "bucket=${GITHUB_REPOSITORY_OWNER}-ci-turbo" - } >> "$GITHUB_OUTPUT" - { - echo "TURBO_API=http://127.0.0.1:$port" - echo "TURBO_TOKEN=$token" - echo "TURBO_TEAM=${GITHUB_REPOSITORY//\//-}" - } >> "$GITHUB_ENV" - - uses: brunojppb/turbo-cache-server@7d5eed8f1768a2209c88b2af58da1827b47eedcc # 5.0.4 - if: ${{ inputs.turbo-cache }} - env: - PORT: ${{ steps.turbo-cache.outputs.port }} - S3_ENDPOINT: ${{ env.TURBO_CACHE_ENDPOINT }} - S3_REGION: ${{ env.TURBO_CACHE_REGION }} - S3_BUCKET_NAME: ${{ steps.turbo-cache.outputs.bucket }} - S3_ACCESS_KEY: ${{ env.TURBO_CACHE_ACCESS_KEY }} - S3_SECRET_KEY: ${{ env.TURBO_CACHE_SECRET_KEY }} - S3_USE_PATH_STYLE: 'true' + cache: shared + vault: ${{ inputs.vault }} + op-service-account-token: ${{ secrets.op-service-account-token }} # The tenant's private packages (§ 5 PLX-Delivery): the job's own token # in a user-level npmrc of the job's own, which pnpm and npm read beside # the scope's registry in pnpm-workspace.yaml. The repo holds no token, From 8b4cff2c143d70eedbf94e52a7bc52690246d2fd Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:08:20 +0100 Subject: [PATCH 075/194] repo-turbo's workflows: no turbo-cache from ci_registry, and a package repo hands the vault's token to _check.yml (forced edit) _check.yml has no input turbo-cache any more; the check jobs of an app repo stop passing it, and those of a package repo pass the vault's token, with which the step reads the shared bucket's keys off a runner host. Co-Authored-By: Claude Fable 5.2 --- templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja | 5 +++-- .../repo-turbo/files/.github/workflows/on_push.yml.jinja | 5 +++-- ...f not publishes_packages %}on_commit.yml{% endif %}.jinja | 3 +-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja b/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja index 240cd07a..f51798aa 100644 --- a/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja +++ b/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja @@ -21,6 +21,8 @@ jobs: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} tasks: test{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} + secrets: + op-service-account-token: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} changeset-status: {% endraw %}{% if 'updates' in _templates %}{% raw %} # `changeset version` consumed the release branch's changesets, and the bot's branches get theirs from the @@ -74,8 +76,7 @@ jobs: check: uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 with: - strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - turbo-cache: {% endraw %}{{ 'true' if ci_registry == 'own' else 'false' }}{% if private_packages_scope %} + strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }}{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} secrets: op-service-account-token: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} diff --git a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja b/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja index 1b226e4b..545b3ab4 100644 --- a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja +++ b/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja @@ -32,6 +32,8 @@ jobs: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} tasks: test{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} + secrets: + op-service-account-token: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} publish: needs: check @@ -63,8 +65,7 @@ jobs: cancel-in-progress: true uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 with: - strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - turbo-cache: {% endraw %}{{ 'true' if ci_registry == 'own' else 'false' }}{% if private_packages_scope %} + strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }}{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} secrets: op-service-account-token: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} 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 7493980a..8541f4cc 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 @@ -20,8 +20,7 @@ jobs: check: uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 with: - strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - turbo-cache: {% endraw %}{{ 'true' if ci_registry == 'own' else 'false' }}{% if private_packages_scope %} + strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }}{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} secrets: op-service-account-token: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} From 034bf9bc79bfd63c3ae05738c9507d20cd9509e7 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:08:28 +0100 Subject: [PATCH 076/194] doctor: header wording Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/doctor.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index 55a917b5..3353f9eb 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -11,8 +11,8 @@ // // The checks are static: they read the marker, `docker/compose.yaml`, the // task list as mise reports it, the hooks of `hk.pkl`, an app's `package.json`, -// and git's list of tracked files. They never reach a host or a running app, and need no -// compendium: the requirement names a deviation may list come from the index +// and git's list of tracked files. They never reach a host or a running app, +// and need no compendium: the requirement names a deviation may list come from the index // this plx carries (standardIndex.ts). A deviation the marker lists silences // its check; a deviation without a reason in the marker's body, or naming no // requirement, is a finding of its own. Findings are reported, never fixed. @@ -64,7 +64,7 @@ // read from the `hooks` block of `hk.pkl` as a repo's template writes it // (hookCommands), the `check` command of every step of a hook, and a hook runs // a task when a command names it (`mise :t`, `mise run t`) or a task it names -// runs it, by `depends` or by a `mise` line of its `run` (taskCalls). That +// runs it, by `depends` or by a `mise` line of its `run` (`rootTasks`). That // lets the pre-push hook of a repo whose `test` runs `check` first run `test` // alone. Which hook steps run, with which files, is hk's business; the check // asks that a pre-commit hook is wired and that the pre-push hook reaches @@ -169,7 +169,7 @@ export type Facts = RepoFacts | AppFacts; // Each returns what is wrong, one line per problem; an empty list passes. /** The repo verbs, in the order of the gates: one list for the check and for anything that names them. */ -export const VERBS = ['dev', 'build', 'check', 'test', 'e2e'] as const; +const VERBS = ['dev', 'build', 'check', 'test', 'e2e'] as const; /** The two verbs the pre-push hook must reach. */ const GATES = ['check', 'test']; From 670a28e86924720cdbe404045fae2ace70656473 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:09:35 +0100 Subject: [PATCH 077/194] remove updatesMove.test.ts: its header says a change of a template ends the test for it, and repo-operations was the last one left Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/updatesMove.test.ts | 75 ---------------------------- 1 file changed, 75 deletions(-) delete mode 100644 packages/lib/src/updatesMove.test.ts diff --git a/packages/lib/src/updatesMove.test.ts b/packages/lib/src/updatesMove.test.ts deleted file mode 100644 index 1860aa76..00000000 --- a/packages/lib/src/updatesMove.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -// The move of PLX-Updates' files out of the two repo templates and into -// `updates` changes nothing a repo holds: in every answer shape, a repo -// template rendered beside `updates` gives the tree that template alone gave -// at 0.132.0, the version before the move (testing/before.ts), byte for byte -// and mode for mode, with the same policies. The one line that differs is the -// one that names the template a file is generated from, in plx-update.yml, -// which names `updates` now. -// -// What it proves holds while a template is as the move left it, but for the -// version pins, which ship stamps: a later change to it makes the test fail, -// and the change that does ends the test for that template. repo-turbo has -// changed (its verbs, its hooks, its PostgreSQL question), so only -// repo-operations is left; the archive stays for it and for the update tests -// of packages/dev, which merge from it. -import assert from 'node:assert/strict'; -import { mkdtempSync, rmSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { after, test } from 'node:test'; -import { type Answers, readTree, render, type Tree } from '@plexus-ms/cli-template'; -import { templatesRoot } from './templatesRoot.ts'; -import { templatesBefore } from './testing/before.ts'; -import { CHOICES, distinct } from './testing/shapes.ts'; - -const scratch = mkdtempSync(join(tmpdir(), 'plx-updates-move-')); -after(() => rmSync(scratch, { recursive: true, force: true })); -const before = templatesBefore(scratch); - -/** The workflow's line naming its template, as each repo template wrote it before the move, and as updates does. */ -const header = (name: string) => - `# Generated from plexus-ms/tooling, templates/${name}: edit the template, never this file.\n`; -const WORKFLOW = '.github/workflows/plx-update.yml'; - -/** A tree with each path's policy beside its bytes and mode, the workflow's header put back as it was. */ -function comparable(tree: Tree, files: ReadonlyMap, repo: string) { - const decoder = new TextDecoder(); - return Object.fromEntries( - [...tree].map(([path, { bytes, mode }]) => { - const text = decoder.decode(bytes); - return [ - path, - { - mode, - policy: files.get(path)?.policy, - text: path === WORKFLOW ? text.replace(header('updates'), header(repo)) : text, - }, - ]; - }), - ); -} - -// repo-turbo is left out: its verbs and hooks changed after the move, which is what this header says ends the test. -for (const repo of ['repo-operations'] as const) - test(`${repo} beside updates renders what ${repo} alone rendered before the move, in every answer shape`, async () => { - const old = [await readTree(join(before, repo))]; - const now = [await readTree(join(templatesRoot(), repo)), await readTree(join(templatesRoot(), 'updates'))]; - const shapes = distinct(CHOICES[repo], (answers: Answers) => render(old, answers)); - assert.ok(shapes.length > 100, `${shapes.length} shapes`); - for (const { answers, result: reference } of shapes) { - const shape = JSON.stringify(answers); - assert.deepEqual(reference.errors, [], shape); - const moved = render(now, answers); - assert.deepEqual(moved.errors, [], shape); - assert.match( - new TextDecoder().decode(moved.tree.get(WORKFLOW)?.bytes), - new RegExp(`^[^\\n]*\\n\\n${header('updates')}`), - ); - assert.deepEqual( - comparable(moved.tree, moved.files, repo), - comparable(reference.tree, reference.files, repo), - shape, - ); - assert.deepEqual(moved.answers, reference.answers, shape); - } - }); From a90d0570c5add5f3130d4db1dc0253389eb661da Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:10:32 +0100 Subject: [PATCH 078/194] the update test compares the files the move concerns for repo-operations too: its verbs and hooks have changed Co-Authored-By: Claude Fable 5.2 --- packages/dev/src/ship.integration.test.ts | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index 30ee1b36..2b1aa009 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -1911,13 +1911,11 @@ for (const [template, answers, edits] of [ executable: false, text: (workflow?.text ?? '').replace(`templates/${template}: edit`, 'templates/updates: edit'), }; - // repo-turbo has changed since the move (its verbs, its hooks, a question more), so what the update took in of it is - // no longer the repo as it was: the marker, with that question added, and the files the move concerns are - // compared. repo-operations is still as it was. + // Both templates have changed since the move (their verbs, their hooks, a question more in repo-turbo), so what the + // update took in of them is no longer the repo as it was: the marker, with that question added, and the files the + // move concerns are compared. const concerned = (files: typeof end) => - template === 'repo-turbo' - ? Object.fromEntries(Object.entries(files).filter(([path]) => path === 'PLEXUS.md' || MOVED.includes(path))) - : files; + Object.fromEntries(Object.entries(files).filter(([path]) => path === 'PLEXUS.md' || MOVED.includes(path))); assert.deepEqual(concerned(end), concerned(expected)); }); From 3acd859a2550f51336d114a46c7115b18958cede Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:11:27 +0100 Subject: [PATCH 079/194] before.ts: its header no longer names the removed move test Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/testing/before.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/lib/src/testing/before.ts b/packages/lib/src/testing/before.ts index 126e7ca5..ed49ceff 100644 --- a/packages/lib/src/testing/before.ts +++ b/packages/lib/src/testing/before.ts @@ -1,8 +1,8 @@ // The two repo templates as Plexus 0.132.0 bundled them, the last version // before the files of PLX-Updates moved into a template of their own, -// `updates`: the reference of the tests that the move changes no file a repo -// holds (updatesMove.test.ts here, and the update through it in -// @plexus-ms/dev's ship.integration.test.ts). Not shipped (excluded in +// `updates`: the reference of the test that the update through the move +// changes no file a repo holds but the ones it concerns (@plexus-ms/dev's +// ship.integration.test.ts). Not shipped (excluded in // tsconfig). // // The archive holds `templates/repo-turbo` and `templates/repo-operations` of From dc6542bf7c208f186a83b3b33eee407f33f33764 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:15:17 +0100 Subject: [PATCH 080/194] docs(actions_runners): say what the slots are now where comments still told otherwise No slot has a network or a daemon of its own any more, and only the medium and large slots mount the host's caches. The comments of the BuildKit service, the Connect server, the housekeeping, the slot variables, the image's mise.toml and plx-ci's registry said otherwise; they now say what the code does. The housekeeping's disk alert names what the cache directory holds. No behaviour changes: the Connect API still listens on the bridge's gateway, which no slot uses. Co-Authored-By: Claude Fable 5.2 --- ansible/ci/roles/actions_runners/defaults/main.yml | 10 +++++----- .../ci/roles/actions_runners/files/ci-connect-refresh | 3 ++- .../roles/actions_runners/files/ci-runner-housekeeping | 10 +++++----- .../ci/roles/actions_runners/files/ci-runner/mise.toml | 3 ++- ansible/ci/roles/actions_runners/tasks/connect.yml | 5 ++--- ansible/ci/roles/actions_runners/tasks/main.yml | 5 +++-- packages/cli-ci/src/core/registry.ts | 4 ++-- 7 files changed, 21 insertions(+), 19 deletions(-) diff --git a/ansible/ci/roles/actions_runners/defaults/main.yml b/ansible/ci/roles/actions_runners/defaults/main.yml index 2bd2e838..029eca04 100644 --- a/ansible/ci/roles/actions_runners/defaults/main.yml +++ b/ansible/ci/roles/actions_runners/defaults/main.yml @@ -152,7 +152,8 @@ actions_runners_connect_image_api: 1password/connect-api:1.8.4 actions_runners_connect_image_sync: 1password/connect-sync:1.8.4 # The user the containers run as, which owns the credentials file. actions_runners_connect_uid: 999 -# The API's port on loopback and on the Docker bridge's gateway. +# The API's port, on loopback, where every slot reaches it over the host's +# network, and on the Docker bridge's gateway, which no slot uses. actions_runners_connect_port: 8080 # Housekeeping, hourly: the registry pair onto this week's buckets, the @@ -169,10 +170,9 @@ actions_runners_disk_alert_percent: 85 # docker buildx create --name --driver remote tcp://127.0.0.1: # docker buildx build --builder --platform linux/amd64 --push … # -# It listens on 127.0.0.1 alone, without TLS. The small and medium slots -# share the host's network and reach it there; a large slot, on a network -# of its own, does not, and has a daemon of its own. No slot gains a socket -# or a privilege for it. The registry credentials travel from the job's +# It listens on 127.0.0.1 alone, without TLS. Every slot shares the host's +# network and reaches it there. No slot gains a socket or a privilege for +# it. The registry credentials travel from the job's # ~/.docker/config.json through the build's session; the service holds # none. Its state is /var/lib/buildkit, bounded by BuildKit's own garbage # collection, which runs when the daemon starts and after builds; the diff --git a/ansible/ci/roles/actions_runners/files/ci-connect-refresh b/ansible/ci/roles/actions_runners/files/ci-connect-refresh index a9f5c52d..4b902ff3 100755 --- a/ansible/ci/roles/actions_runners/files/ci-connect-refresh +++ b/ansible/ci/roles/actions_runners/files/ci-connect-refresh @@ -14,7 +14,8 @@ set -eu # shellcheck source=/dev/null . /etc/op-connect/connect.env stamp=$(sha256sum "$CREDENTIALS" | cut -c1-16) -# The host's address on the default bridge, for the large slot's own network. +# The host's address on the default bridge, where the API listens too; no +# slot uses it, since every slot shares the host's network. gateway=$(docker network inspect bridge --format '{{ (index .IPAM.Config 0).Gateway }}') ensure() { diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping b/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping index c9843808..97ec2b3d 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping +++ b/ansible/ci/roles/actions_runners/files/ci-runner-housekeeping @@ -15,10 +15,10 @@ set -eu # The pinned image, present before the next slot container needs it. [ "$PULL" != true ] || docker pull --quiet "$IMAGE" >/dev/null -# The slots run with --rm and start no containers on this daemon (a small -# or medium slot has no socket, a large one a daemon of its own), so a -# stopped container is one a crash left, and so is a volume nothing uses: a -# large slot's daemon data goes with its container otherwise. Every image +# The slots run with --rm and start no containers on this daemon (no slot +# has a socket), so a stopped container is one a crash left, and a volume +# nothing uses is no slot's: a slot's container mounts directories of the +# host and no volume. Every image # but the pinned runner image and the registry's is a previous pin's; the # pinned one is kept although a slot between two containers leaves it unused # for a moment, and an image a container still uses refuses removal. @@ -35,6 +35,6 @@ done used=$(df --output=pcent / | tail -1 | tr -dc '0-9') echo "root file system ${used}% used" if [ "$used" -gt "$DISK_ALERT_PERCENT" ]; then - echo "above ${DISK_ALERT_PERCENT}%: look at /var/cache/ci-runner (the pnpm store), docker system df, and du -sh /var/lib/buildkit against maxUsedSpace in /etc/buildkit/buildkitd.toml" >&2 + echo "above ${DISK_ALERT_PERCENT}%: look at /var/cache/ci-runner (the medium and large slots' caches: the pnpm store, mise, corepack, Playwright), docker system df, and du -sh /var/lib/buildkit against maxUsedSpace in /etc/buildkit/buildkitd.toml" >&2 exit 1 fi diff --git a/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml b/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml index 8c3bad25..04c0c0ee 100644 --- a/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml +++ b/ansible/ci/roles/actions_runners/files/ci-runner/mise.toml @@ -3,7 +3,8 @@ # that a repo's own pin of any of them wins. Installed at build time into mise's # system directory, which mise searches after its data directory and never # writes; a version a repo pins and the image lacks installs into the data -# directory, which a runner host shares between its slots. +# directory, which a runner host shares between its medium and large slots; in +# a small slot or on an instance it stays in the job's container. [tools] # plx-ci at the Plexus version: the pin is written with each version, never by # the update bot (§ 1 PLX-Updates); allow_low_downloads only waives npm's diff --git a/ansible/ci/roles/actions_runners/tasks/connect.yml b/ansible/ci/roles/actions_runners/tasks/connect.yml index 8ebe4aac..782501cd 100644 --- a/ansible/ci/roles/actions_runners/tasks/connect.yml +++ b/ansible/ci/roles/actions_runners/tasks/connect.yml @@ -61,9 +61,8 @@ # What a slot's container gets, so that the job's secret reads go to the # server: load-secrets-action prefers Connect over the service account token -# the workflow also sets. The large slot has a network of its own and reaches -# the host at Docker's host gateway; the small and medium slots share the -# host's network and use loopback (ci-runner-slot sets the host). +# the workflow also sets. Every slot shares the host's network and uses +# loopback (ci-runner-slot sets the host). - name: Write the slots' Connect token when: actions_runners_connect_token | length > 0 no_log: true diff --git a/ansible/ci/roles/actions_runners/tasks/main.yml b/ansible/ci/roles/actions_runners/tasks/main.yml index 5bf4478f..796279cf 100644 --- a/ansible/ci/roles/actions_runners/tasks/main.yml +++ b/ansible/ci/roles/actions_runners/tasks/main.yml @@ -183,8 +183,9 @@ - name: The BuildKit service ansible.builtin.include_tasks: buildkit.yml -# What a slot's container is made of: the image and the cache for every -# slot, the memory limit per size. ci-runner-slot reads both at the start of +# What a slot's container is made of: the image for every slot and the +# cache directory a medium or large slot mounts from, the memory limit per +# size. ci-runner-slot reads both at the start of # a container, and the JIT script reads where to register, so a change to any # of them restarts the slots (the handler): a job in flight on this host # fails and is run again by hand, which a configure run on a runner host diff --git a/packages/cli-ci/src/core/registry.ts b/packages/cli-ci/src/core/registry.ts index 5f020a72..2b02ae11 100644 --- a/packages/cli-ci/src/core/registry.ts +++ b/packages/cli-ci/src/core/registry.ts @@ -3,8 +3,8 @@ // bucket, read-write, and on 127.0.0.1:5001 for the previous week's, // read-only; both the same registry API over the tenant's object storage, // nothing reads the bucket layout directly. A runner host keeps the pair -// running; a forge runner, a launched instance or a large slot starts it for -// the length of its job. In the first week the previous bucket does not +// running, and so does a launched instance from its boot (its user-data); a +// forge runner starts it for the length of its job. In the first week the previous bucket does not // exist and registry:2 answers 503 (its storage health check fails): that // sidecar is optional, and a build names it as a cache source only when it // answers 200. `ghcr` is the forge's registry itself, where the published From 42c8169bf0ab3878ee5eb852f01dc410ca946f6f Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:21:20 +0100 Subject: [PATCH 081/194] test(e2e-playwright): a suite renders as a package of its own with one script, and repo-turbo makes room for it The template e2e-playwright does not exist yet, and repo-turbo's workspace does not list e2e/*: every test here fails. Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/e2ePlaywright.test.ts | 71 ++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 packages/lib/src/e2ePlaywright.test.ts diff --git a/packages/lib/src/e2ePlaywright.test.ts b/packages/lib/src/e2ePlaywright.test.ts new file mode 100644 index 00000000..4b23d0f5 --- /dev/null +++ b/packages/lib/src/e2ePlaywright.test.ts @@ -0,0 +1,71 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { pathsOf, renderBundled, textOf } from './testing/bundled.ts'; + +const render = (answers: Record = { app: '@acme/web' }) => renderBundled(['e2e-playwright'], answers); + +test('a suite is rendered as a package of its own: its Playwright configuration, its setup, a spec and its marker', async () => { + const result = await render(); + assert.deepEqual(result.errors, []); + assert.deepEqual(pathsOf(result), [ + '.gitignore', + 'PLEXUS.md', + 'package.json', + 'playwright.config.ts', + 'setup.ts', + 'specs/home.spec.ts', + ]); +}); + +test('the app is required, and the error carries its help', async () => { + const result = await renderBundled(['e2e-playwright'], {}); + assert.equal(result.errors[0]?.question, 'app'); + assert.match(result.errors[0]?.message ?? '', /package name/); +}); + +test('the package lists the app as a workspace dependency and has one script, e2e', async () => { + const manifest = JSON.parse(textOf(await render({ app: '@acme/shop' }), 'package.json')); + assert.equal(manifest.name, '@acme/shop-e2e'); + assert.equal(manifest.private, true); + assert.deepEqual(Object.keys(manifest.scripts), ['e2e']); + const dependencies = { ...manifest.dependencies, ...manifest.devDependencies }; + assert.equal(dependencies['@acme/shop'], 'workspace:*'); + assert.ok(dependencies['@playwright/test'], 'Playwright'); + assert.ok(dependencies['@plexus-ms/test-postgres'], 'the throwaway PostgreSQL of a stateful app'); +}); + +test("the spec looks for the app's name, which its page shows", async () => { + assert.match(textOf(await render({ app: '@acme/shop' }), 'specs/home.spec.ts'), /toHaveText\('@acme\/shop'\)/); +}); + +test('no file imports by a relative path out of the suite, starts Next itself, or takes a running app', async () => { + const result = await render(); + for (const path of pathsOf(result).filter((p) => p.endsWith('.ts'))) { + const text = textOf(result, path); + assert.doesNotMatch(text, /(from |import\(|require\()\s*['"]\.\.\//, path); + assert.doesNotMatch(text, /next (start|dev)|webServer/, path); + } +}); + +test('the marker and the spec are written once, the rest is merged', async () => { + const result = await render(); + const once = ['PLEXUS.md', 'specs/home.spec.ts']; + for (const [path, origin] of result.files) + assert.equal(origin.policy, once.includes(path) ? 'born-once' : 'merge', path); +}); + +test('the marker has no frontmatter, which plx writes, and nothing runs at birth', async () => { + const result = await render(); + assert.ok(!textOf(result, 'PLEXUS.md').startsWith('---')); + assert.deepEqual(result.birth, []); +}); + +test('repo-turbo makes room for suites: e2e/* is a workspace glob, and its package files are sources of install', async () => { + const result = await renderBundled(['repo-turbo'], { tenant: 'acme' }); + const packages = /^packages:\n((?: {2}- .*\n)+)/m.exec(textOf(result, 'pnpm-workspace.yaml'))?.[1] ?? ''; + const globs = [...packages.matchAll(/"([^"]+)"/g)].map((m) => m[1] as string); + assert.ok(globs.includes('e2e/*'), globs.join(' ')); + const sources = /^sources = \[(.*)\]$/m.exec(textOf(result, 'mise.toml').split('[tasks.install]')[1] ?? '')?.[1]; + for (const glob of globs) + assert.match(sources ?? '', new RegExp(`"${glob.replace('*', '\\*')}/package\\.json"`), glob); +}); From 773b62d3d1f7fd4facf2ccdb86f0c1678d8384d9 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:22:08 +0100 Subject: [PATCH 082/194] feat(e2e-playwright): a template for an E2E suite as a workspace package of its own The suite at e2e/ lists the app as a workspace dependency, has one script, e2e, and starts the app's build output as the standalone server in its global setup, after a throwaway PostgreSQL, migrate and seed for a stateful app. Co-Authored-By: Claude Fable 5.2 --- .../e2e-playwright/files/.gitignore.jinja | 2 + .../e2e-playwright/files/PLEXUS.md.jinja | 3 + .../e2e-playwright/files/package.json.jinja | 13 ++ .../e2e-playwright/files/playwright.config.ts | 11 ++ templates/e2e-playwright/files/setup.ts.jinja | 127 ++++++++++++++++++ .../files/specs/home.spec.ts.jinja | 6 + templates/e2e-playwright/template.yml | 14 ++ 7 files changed, 176 insertions(+) create mode 100644 templates/e2e-playwright/files/.gitignore.jinja create mode 100644 templates/e2e-playwright/files/PLEXUS.md.jinja create mode 100644 templates/e2e-playwright/files/package.json.jinja create mode 100644 templates/e2e-playwright/files/playwright.config.ts create mode 100644 templates/e2e-playwright/files/setup.ts.jinja create mode 100644 templates/e2e-playwright/files/specs/home.spec.ts.jinja create mode 100644 templates/e2e-playwright/template.yml diff --git a/templates/e2e-playwright/files/.gitignore.jinja b/templates/e2e-playwright/files/.gitignore.jinja new file mode 100644 index 00000000..53808aaf --- /dev/null +++ b/templates/e2e-playwright/files/.gitignore.jinja @@ -0,0 +1,2 @@ +/test-results/ +/playwright-report/ diff --git a/templates/e2e-playwright/files/PLEXUS.md.jinja b/templates/e2e-playwright/files/PLEXUS.md.jinja new file mode 100644 index 00000000..b5e10a9e --- /dev/null +++ b/templates/e2e-playwright/files/PLEXUS.md.jinja @@ -0,0 +1,3 @@ +- The end-to-end suite of `{{ app }}`: Playwright runs the specs in `specs/` in Chromium against the app's build output, which `setup.ts` starts as the standalone server, after a throwaway PostgreSQL, the app's `migrate` and its `seed` where the app's marker states the `stateful` profile. +- It runs with `mise :e2e `, `` being the app's directory name, which builds the app first; the suite's `e2e` script never builds, and fails without the build output. +- Chromium comes from Playwright's shared cache, into which `pnpm exec playwright install chromium`, run in this directory, installs it. diff --git a/templates/e2e-playwright/files/package.json.jinja b/templates/e2e-playwright/files/package.json.jinja new file mode 100644 index 00000000..362f5f6c --- /dev/null +++ b/templates/e2e-playwright/files/package.json.jinja @@ -0,0 +1,13 @@ +{ + "name": "{{ app }}-e2e", + "private": true, + "type": "module", + "scripts": { + "e2e": "playwright test" + }, + "devDependencies": { + "{{ app }}": "workspace:*", + "@playwright/test": "^1.65.1", + "@plexus-ms/test-postgres": "^0.1.0" + } +} diff --git a/templates/e2e-playwright/files/playwright.config.ts b/templates/e2e-playwright/files/playwright.config.ts new file mode 100644 index 00000000..e1db170a --- /dev/null +++ b/templates/e2e-playwright/files/playwright.config.ts @@ -0,0 +1,11 @@ +// The suite's Playwright configuration: the specs in specs/, run in Chromium against the app that setup.ts starts. +import { defineConfig, devices } from '@playwright/test'; + +export default defineConfig({ + testDir: 'specs', + globalSetup: './setup.ts', + reporter: 'list', + // Set by setup.ts once the app answers, before any worker reads this file; whatever it held before is replaced. + use: { baseURL: process.env.PLX_E2E_BASE_URL }, + projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], +}); diff --git a/templates/e2e-playwright/files/setup.ts.jinja b/templates/e2e-playwright/files/setup.ts.jinja new file mode 100644 index 00000000..1d32d5e9 --- /dev/null +++ b/templates/e2e-playwright/files/setup.ts.jinja @@ -0,0 +1,127 @@ +// The suite's global setup: it starts the app as its image runs it, from the directory the app's build leaves, and +// hands the specs its address. It never builds: `mise e2e` builds the app first, as the suite depends on it. +// +// 1. The app is found through the workspace dependency, never by a relative path, and its build output, +// `.next/standalone`, must exist; without it the run fails, saying so. +// 2. Chromium must start from Playwright's shared cache; without it the run fails with the command that installs it. +// 3. The output is copied to a temporary directory, since a running server writes into its own directory. +// 4. Where the app's marker states the stateful profile: a throwaway PostgreSQL from the binary the repo pins +// (@plexus-ms/test-postgres, at the major PLX_POSTGRES_MAJOR names), a database of its own, the app's `migrate` +// run in the copy as the image runs it, and its `seed` run in the app's directory, the development command it is; +// each, and the server, gets that database as DATABASE_URL. +// 5. The standalone server on a free port of 127.0.0.1, ready once /healthz answers. It exits at the end of its +// stdin, which this process holds, so that it never outlives this process, however that ends; the database's +// supervisor does the same. +// +// The returned teardown stops what was started and removes the copy. +import { type ChildProcess, spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { existsSync } from 'node:fs'; +import { cp, mkdtemp, readFile, rm } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { createServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { chromium } from '@playwright/test'; + +/** The app this suite tests, by its package name. */ +const APP = '{{ app }}'; + +export default async function setup(): Promise<() => Promise> { + const app = path.dirname(createRequire(import.meta.url).resolve(`${APP}/package.json`)); + const output = path.join(app, '.next', 'standalone'); + if (!existsSync(output)) + throw new Error( + `${APP} has no build output at ${output}: the suite starts it and never builds it; mise e2e builds it first`, + ); + await chromium.launch().then( + (browser) => browser.close(), + (error: Error) => { + if (!/Executable doesn't exist/.test(error.message)) throw error; + throw new Error( + `Playwright's shared cache holds no Chromium: install it with \`pnpm exec playwright install chromium\` in ${process.cwd()}`, + ); + }, + ); + const stops: (() => Promise)[] = []; + const teardown = async () => { + for (const stop of stops.reverse()) await stop(); + }; + try { + const copy = await mkdtemp(path.join(tmpdir(), 'plx-e2e-')); + stops.push(() => rm(copy, { recursive: true, force: true })); + await cp(output, copy, { recursive: true, verbatimSymlinks: true }); + const server = within(copy, app); + const env: NodeJS.ProcessEnv = { ...process.env }; + if (await stateful(app)) { + const { createDatabase, startPostgres } = await import('@plexus-ms/test-postgres'); + const postgres = await startPostgres({ major: Number(process.env.PLX_POSTGRES_MAJOR) }); + stops.push(postgres.stop); + env.DATABASE_URL = await createDatabase(postgres.url); + await run(['npm', 'run', 'migrate'], server, { ...env, NODE_ENV: 'production' }); + await run(['npm', 'run', 'seed'], app, env); + } + const port = await freePort(); + const guard = "process.stdin.on('end', () => process.exit()).resume(); require('./server.js');"; + const started = spawn(process.execPath, ['-e', guard], { + cwd: server, + env: { ...env, PORT: String(port), HOSTNAME: '127.0.0.1' }, + stdio: ['pipe', 'inherit', 'inherit'], + }); + stops.push(() => end(started)); + process.env.PLX_E2E_BASE_URL = `http://127.0.0.1:${port}`; + await ready(`${process.env.PLX_E2E_BASE_URL}/healthz`, started); + } catch (error) { + await teardown(); + throw error; + } + return teardown; +} + +/** The app's directory in the output, which mirrors the workspace from its root: the shortest end of the app's path that holds the server. */ +function within(output: string, app: string): string { + const parts = app.split(path.sep); + for (let at = parts.length - 1; at > 0; at--) { + const dir = path.join(output, ...parts.slice(at)); + if (existsSync(path.join(dir, 'server.js'))) return dir; + } + throw new Error(`the build output of ${APP} holds no server.js for ${app}`); +} + +/** Whether the frontmatter of the app's marker states the stateful profile. */ +async function stateful(app: string): Promise { + const marker = await readFile(path.join(app, 'PLEXUS.md'), 'utf8'); + return /^profile:\s*["']?stateful["']?\s*$/m.test(/^---\n([\s\S]*?)\n---/.exec(marker)?.[1] ?? ''); +} + +async function run([command, ...args]: string[], cwd: string, env: NodeJS.ProcessEnv): Promise { + const child = spawn(command as string, args, { cwd, env, stdio: 'inherit' }); + const [code, signal] = await once(child, 'exit'); + if (code !== 0) throw new Error(`${[command, ...args].join(' ')} in ${cwd} failed with ${signal ?? code}`); +} + +function freePort(): Promise { + return new Promise((resolve, reject) => { + const probe = createServer().once('error', reject); + probe.listen(0, '127.0.0.1', () => { + const { port } = probe.address() as { port: number }; + probe.close(() => resolve(port)); + }); + }); +} + +async function ready(url: string, server: ChildProcess): Promise { + for (const until = Date.now() + 60_000; Date.now() < until; ) { + if (server.exitCode !== null) throw new Error(`the server exited with ${server.exitCode} before ${url} answered`); + if (await fetch(url).then((response) => response.ok, () => false)) return; + await new Promise((resolve) => setTimeout(resolve, 200)); + } + throw new Error(`${url} did not answer within a minute`); +} + +async function end(server: ChildProcess): Promise { + if (server.exitCode !== null || server.signalCode !== null) return; + const exited = once(server, 'exit'); + server.kill(); + await exited; +} diff --git a/templates/e2e-playwright/files/specs/home.spec.ts.jinja b/templates/e2e-playwright/files/specs/home.spec.ts.jinja new file mode 100644 index 00000000..c25e12c0 --- /dev/null +++ b/templates/e2e-playwright/files/specs/home.spec.ts.jinja @@ -0,0 +1,6 @@ +import { expect, test } from '@playwright/test'; + +test('the home page shows the name of the app', async ({ page }) => { + await page.goto('/'); + await expect(page.getByRole('heading', { level: 1 })).toHaveText('{{ app }}'); +}); diff --git a/templates/e2e-playwright/template.yml b/templates/e2e-playwright/template.yml new file mode 100644 index 00000000..9a4e2cca --- /dev/null +++ b/templates/e2e-playwright/template.yml @@ -0,0 +1,14 @@ +# files/.gitignore.jinja is a .gitignore: npm leaves a file of that name out of a package, so the +# template carries it with the suffix, which renders it to the same bytes. +name: e2e-playwright + +questions: + app: + type: str + help: "The app this suite tests, by its package name as its package.json gives it (as in @acme/shop): the suite lists it as a workspace dependency and starts its build output" + +policies: + # The marker and the spec are rendered at birth only: the spec is the author's from then on, and the + # marker's frontmatter is plx's. + PLEXUS.md.jinja: born-once + specs/home.spec.ts.jinja: born-once From 98a6844a57dd027065b0445a6b1b1663263f89bf Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:23:38 +0100 Subject: [PATCH 083/194] newborns: the cache test takes freePort and relock from the helpers, which have them since the merge Co-Authored-By: Claude Fable 5.2 --- newborns/turbo-cache.test.ts | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/newborns/turbo-cache.test.ts b/newborns/turbo-cache.test.ts index a2870985..191e2407 100644 --- a/newborns/turbo-cache.test.ts +++ b/newborns/turbo-cache.test.ts @@ -19,11 +19,10 @@ import assert from 'node:assert/strict'; import { type ChildProcess, spawn } from 'node:child_process'; import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; -import { createServer } from 'node:net'; import { arch, platform } from 'node:os'; import { join } from 'node:path'; import { after, before, describe, test } from 'node:test'; -import { awaitingDoctor, born, close, open, put, sh, tryRun } from './helpers.ts'; +import { awaitingDoctor, born, close, freePort, open, put, relock, sh, tryRun } from './helpers.ts'; const WORKSPACE = join(import.meta.dirname, '..'); const STEP = join(WORKSPACE, '.github', 'actions', 'turbo-cache'); @@ -39,15 +38,6 @@ let s3 = ''; let binary = ''; const servers: { child: ChildProcess; log: string[] }[] = []; -async function freePort(): Promise { - const probe = createServer(); - await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); - const address = probe.address(); - await new Promise((resolve) => probe.close(() => resolve())); - if (address === null || typeof address === 'string') throw new Error('no port'); - return address.port; -} - /** Waits until `url` answers 200, or throws after a minute. */ async function answers(url: string): Promise { const until = Date.now() + 60_000; @@ -241,7 +231,7 @@ describe('a newborn app repo with the two remote caches', () => { dependencies: { lib: 'workspace:*' }, }, }); - await sh('mise', ['exec', '--', 'pnpm', 'install', '--lockfile-only'], origin); + await relock(origin); await git(origin, 'add', '-A'); await git(origin, 'commit', '--no-verify', '-q', '-m', 'born'); const port = await freePort(); From 29b9dcc05e136e6925231656e29bd305b4f361ea Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:24:04 +0100 Subject: [PATCH 084/194] newborns: launch is shared, with the pid of the command it starts So that a newborn test can signal the command alone, as a run is killed. Co-Authored-By: Claude Fable 5.2 --- newborns/helpers.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/newborns/helpers.ts b/newborns/helpers.ts index dab1db08..4fc44332 100644 --- a/newborns/helpers.ts +++ b/newborns/helpers.ts @@ -92,7 +92,9 @@ export interface Ran { export const LIMIT = 10 * 60_000; /** A command started leading a process group of its own: what it printed so far, the group's kill, and its end. */ -interface Launched { +export interface Launched { + /** The command's process id, which leads the group; undefined where it could not start. */ + pid: number | undefined; output(): string; kill(): void; /** Its exit code once its output is closed; null where it was killed or could not start. */ @@ -104,7 +106,7 @@ interface Launched { * the group is killed once the command exits, so that nothing it started * outlives it. A command that cannot start ends with the error as its output. */ -function launch(command: string, args: string[], cwd: string, env: NodeJS.ProcessEnv): Launched { +export function launch(command: string, args: string[], cwd: string, env: NodeJS.ProcessEnv): Launched { const child = spawn(command, args, { cwd, env: cleanEnv(env), stdio: ['ignore', 'pipe', 'pipe'], detached: true }); let output = ''; const collect = (chunk: Buffer) => { @@ -125,7 +127,7 @@ function launch(command: string, args: string[], cwd: string, env: NodeJS.Proces }); child.on('close', resolve); }); - return { output: () => output, kill, closed }; + return { pid: child.pid, output: () => output, kill, closed }; } /** From e2df6ac557b85831582833c057679fe052243aa9 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:24:40 +0100 Subject: [PATCH 085/194] turbow: a header of two lines, as a template file has; each rule above the code it governs plx requirements refuses a template file that opens with more than two header comment lines: the rest is the compendium's. Co-Authored-By: Claude Fable 5.2 --- templates/repo-turbo/files/turbow | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/templates/repo-turbo/files/turbow b/templates/repo-turbo/files/turbow index ed710f6a..df6280ff 100755 --- a/templates/repo-turbo/files/turbow +++ b/templates/repo-turbo/files/turbow @@ -1,18 +1,6 @@ #!/bin/sh # Generated from plexus-ms/tooling, templates/repo-turbo. -# Turbo with the remote cache its verb may use: ./turbow , as the tasks of mise.toml -# call it. check and test use the shared cache, the bucket -ci-turbo, which every machine and CI write; build -# and e2e use the trusted one, -ci-turbo-trusted, whose keys only CI holds. A bucket is reached through a cache -# server on loopback: -# - Outside CI there is no trusted server, so every verb uses the shared one: the server PLX_TURBO_SHARED names, -# by default this machine's own on the fixed port, http://127.0.0.1:8585, which runs without a token. -# - In CI (CI is set) a verb uses only the server its job started (the step .github/actions/turbo-cache of -# plexus-ms/tooling), which PLX_TURBO_SHARED or PLX_TURBO_TRUSTED names, with the job's token in -# PLX_TURBO_SHARED_TOKEN or PLX_TURBO_TRUSTED_TOKEN. build and e2e never use the shared one there: without a -# trusted server they fail. -# A server named `none` is no server: the tenant has no bucket. Where there is no server, nothing answers, or the -# checkout has no origin, the verb runs without a remote cache and says so in one line. The team, which keeps the -# repos of a tenant apart in a bucket, is the repo's owner-repo, from the URL of origin, in lower case. +# Turbo with the remote cache its verb may use, as the tasks call it: ./turbow . set -eu cache=${1:-} @@ -28,6 +16,9 @@ esac unset TURBO_API TURBO_TEAM TURBO_TOKEN reason= +# Outside CI no machine holds the trusted keys: every verb uses the shared server, by default this machine's own, run +# without a token. In CI a verb uses only the server its job started (.github/actions/turbo-cache of plexus-ms/tooling), +# with the job's token, and build and e2e never use the shared one. A server named none is a tenant without the bucket. case ${CI:-} in '' | false | 0) from=shared server=${PLX_TURBO_SHARED:-http://127.0.0.1:8585} token=${PLX_TURBO_SHARED_TOKEN:-local} @@ -56,6 +47,7 @@ if [ "$server" = none ]; then reason="the tenant has no $from bucket" fi +# The team keeps the repos of a tenant apart in a bucket: owner-repo, from the URL of origin, in lower case. if [ -z "$reason" ]; then if url=$(git remote get-url origin 2>/dev/null); then path=${url%/} From a6db23ec9cac4d7a9ffd9de9fd55e84f15fb8acf Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:29:58 +0100 Subject: [PATCH 086/194] newborns: the cache test reads the stand-in's container id among what a first pull prints On the forge's runner the image was pulled by the run itself, and its progress came before the id in what the test read as the id. Co-Authored-By: Claude Fable 5.2 --- newborns/turbo-cache.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/newborns/turbo-cache.test.ts b/newborns/turbo-cache.test.ts index 191e2407..876901e1 100644 --- a/newborns/turbo-cache.test.ts +++ b/newborns/turbo-cache.test.ts @@ -116,7 +116,8 @@ const requests = (log: string[]) => log.filter((line) => line.includes('/v8/arti before(async () => { here = await open('turbo-cache'); - container = ( + // The container's id, the one line of its kind: a first run pulls the image and prints its progress too. + const started = ( await sh( 'docker', [ @@ -133,7 +134,9 @@ before(async () => { ], here, ) - ).trim(); + ).match(/^[0-9a-f]{64}$/m); + container = started?.[0] ?? ''; + if (!container) throw new Error('docker run printed no container id'); const published = (await sh('docker', ['port', container, '9000/tcp'], here)).trim().split('\n')[0] ?? ''; s3 = `http://${published}`; const until = Date.now() + 60_000; From e2796cf477f245802496be5d4d8b9d3839ee1ca9 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:39:39 +0100 Subject: [PATCH 087/194] test(e2e-playwright): newborn suites pass mise e2e from a fresh clone, and a killed run leaves nothing behind A repo with a stateless app and its suite, and one with the answer postgres, a stateful app and its suite. Red: repo-turbo's workspace does not list e2e/*, so the suites are no workspace packages (no e2e task runs, pnpm finds no @acme/stateless-e2e), and the rendered setup.ts is not formatted as Biome wants it, so the newborn's check fails. Co-Authored-By: Claude Fable 5.2 --- newborns/e2e-playwright.test.ts | 262 ++++++++++++++++++++++++++++++++ 1 file changed, 262 insertions(+) create mode 100644 newborns/e2e-playwright.test.ts diff --git a/newborns/e2e-playwright.test.ts b/newborns/e2e-playwright.test.ts new file mode 100644 index 00000000..87436ee8 --- /dev/null +++ b/newborns/e2e-playwright.test.ts @@ -0,0 +1,262 @@ +// An E2E suite of the template e2e-playwright, in newborn repos of the +// Turborepo template with updates beside it: one with a stateless app and its +// suite, and one with the answer `postgres`, a stateful app and its suite, the +// app's `migrate` and `seed` written as its author writes them. Each passes +// `mise e2e` from a fresh clone, its suite starting the app's build output. +// Without Chromium in Playwright's shared cache the run fails, naming the +// command that installs it, and that command does. The suite's own `e2e` fails +// without the build output and does not build it. Editing a spec moves the +// hash of the suite's `e2e` and leaves the app's `build`; editing the app moves +// both. A run killed by SIGINT or SIGKILL of `mise`, or by SIGKILL of the +// Playwright runner that started the app, leaves no server and no PostgreSQL +// behind. The repo's own `check`, `plx doctor` in it, passes. Created by `plx +// new`; it needs the network. +// +// Playwright's shared cache is, for these tests, `node_modules/.cache/ms-playwright` +// of this workspace: kept from one run to the next and never the user's. +import assert from 'node:assert/strict'; +import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { after, before, describe, test } from 'node:test'; +import { awaitingDoctor, born, close, type Launched, launch, open, pass, put, relock, sh, tryRun } from './helpers.ts'; + +const SHARED = { PLAYWRIGHT_BROWSERS_PATH: join(import.meta.dirname, '..', 'node_modules', '.cache', 'ms-playwright') }; + +let here = ''; +before(async () => { + here = await open('e2e-playwright'); +}); +after(close); + +/** git with an identity and no signing, as a newborn has neither. */ +const git = (dir: string, ...args: string[]) => + sh( + 'git', + ['-c', 'commit.gpgsign=false', '-c', 'user.name=newborn', '-c', 'user.email=newborn@example.invalid', ...args], + dir, + ); + +/** What the stateful app's author writes: a migrate and a seed, run with the database in DATABASE_URL, and a page that reads it. */ +function authored(app: string): void { + const manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8')); + const psql = (sql: string) => `psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -c "${sql}"`; + manifest.scripts.migrate = psql('create table greeting (text text not null)'); + manifest.scripts.seed = psql("insert into greeting values ('hello from the seed')"); + put(app, { + 'package.json': manifest, + 'src/app/greeting/page.tsx': [ + "import { execFileSync } from 'node:child_process';", + "import { connection } from 'next/server';", + '', + 'export default async function Greeting() {', + ' await connection();', + " const sql = ['-Atc', 'select text from greeting'];", + " return

{execFileSync('psql', [process.env.DATABASE_URL ?? '', ...sql], { encoding: 'utf8' }).trim()}

;", + '}', + '', + ].join('\n'), + }); +} + +/** + * A newborn repo with an app of `profile` at apps/ and its suite at + * e2e/, committed; returns the repo. `fresh` clones it. + */ +async function newborn(profile: string, answers: Record = {}): Promise { + const dir = await born(join(here, profile), ['repo-turbo', 'updates'], { tenant: 'acme', ...answers }); + await born(join(dir, 'apps', profile), ['app-nextjs'], { name: `@acme/${profile}`, profile }); + await born(join(dir, 'e2e', profile), ['e2e-playwright'], { app: `@acme/${profile}` }); + if (profile === 'stateful') { + authored(join(dir, 'apps', profile)); + put(dir, { + 'e2e/stateful/specs/greeting.spec.ts': [ + "import { expect, test } from '@playwright/test';", + '', + "test('the page shows what the seed wrote into the migrated database', async ({ page }) => {", + " await page.goto('/greeting');", + " await expect(page.getByText('hello from the seed')).toBeVisible();", + '});', + '', + ].join('\n'), + }); + } + await relock(dir); + await awaitingDoctor(dir); + await git(dir, 'add', '-A'); + await git(dir, 'commit', '--no-verify', '-q', '-m', 'born'); + return dir; +} + +/** A fresh clone of `dir`, its tools installed, as a checkout on another machine. */ +async function fresh(dir: string, name: string): Promise { + const clone = join(here, name); + await git(here, 'clone', '-q', dir, clone); + await sh('sh', ['-c', 'mise trust && mise install'], clone); + return clone; +} + +/** Turbo's hashes of the suite's e2e and what it depends on, by task id, from a dry run. */ +async function hashes(dir: string, suite: string): Promise> { + const ran = await tryRun('mise', ['exec', '--', 'turbo', 'run', 'e2e', `--filter=${suite}`, '--dry=json'], dir); + assert.ok(ran.ok, ran.output); + const dry = JSON.parse(ran.output.slice(ran.output.indexOf('{'))); + return Object.fromEntries(dry.tasks.map((t: { taskId: string; hash: string }) => [t.taskId, t.hash])); +} + +describe('a repo with a stateless app and its suite', () => { + let repo = ''; + before(async () => { + repo = await newborn('stateless'); + }); + + test("the suite's marker lists its template and names the app", () => { + const marker = readFileSync(join(repo, 'e2e', 'stateless', 'PLEXUS.md'), 'utf8'); + assert.match(marker, /^---\ntemplates: \[e2e-playwright\]\napp: "@acme\/stateless"\n---\n/); + }); + + test('without Chromium in the shared cache, mise e2e fails naming the command that installs it, which does', async () => { + const clone = await fresh(repo, 'stateless-browserless'); + const empty = join(here, 'no-browsers'); + mkdirSync(empty, { recursive: true }); + const ran = await tryRun('mise', ['run', 'e2e'], clone, { PLAYWRIGHT_BROWSERS_PATH: empty }); + assert.equal(ran.ok, false, ran.output); + const named = /install it with `([^`]+)` in (\S+)/.exec(ran.output); + assert.ok(named, ran.output); + const [, command, where] = named as unknown as [string, string, string]; + assert.equal(where, join(clone, 'e2e', 'stateless')); + await sh('mise', ['exec', '--', 'sh', '-c', command], where, SHARED); + const again = await tryRun('mise', ['run', 'e2e'], clone, SHARED); + assert.ok(again.ok, again.output); + }); + + describe('from a fresh clone', () => { + let clone = ''; + before(async () => { + clone = await fresh(repo, 'stateless-clone'); + }); + + test('passes mise e2e: the suite starts the build output, and its spec finds the app', async () => { + const ran = await tryRun('mise', ['run', 'e2e'], clone, SHARED); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, /@acme\/stateless-e2e:e2e: .*1 passed/); + }); + + test('passes its own check: lint of the suite, and plx doctor', async () => { + await pass(clone, 'stateless', 'check'); + }); + + test("the suite's own e2e fails without the build output, and does not build it", async () => { + const dotNext = join(clone, 'apps', 'stateless', '.next'); + rmSync(dotNext, { recursive: true, force: true }); + const ran = await tryRun( + 'mise', + ['exec', '--', 'pnpm', '--filter', '@acme/stateless-e2e', 'run', 'e2e'], + clone, + SHARED, + ); + assert.equal(ran.ok, false, ran.output); + assert.match(ran.output, /@acme\/stateless has no build output at \S+\.next\/standalone/); + assert.equal(existsSync(dotNext), false, 'nothing was built'); + }); + + test("editing a spec moves the suite's e2e and not the app's build; editing the app moves both", async () => { + const [e2e, build] = ['@acme/stateless-e2e#e2e', '@acme/stateless#build']; + const first = await hashes(clone, '@acme/stateless-e2e'); + assert.ok(first[e2e] && first[build], JSON.stringify(first)); + const spec = join(clone, 'e2e', 'stateless', 'specs', 'home.spec.ts'); + put(clone, { 'e2e/stateless/specs/home.spec.ts': `${readFileSync(spec, 'utf8')}// edited\n` }); + await git(clone, 'add', '-A'); + const specEdited = await hashes(clone, '@acme/stateless-e2e'); + assert.notEqual(specEdited[e2e], first[e2e]); + assert.equal(specEdited[build], first[build]); + const page = join(clone, 'apps', 'stateless', 'src', 'app', 'page.tsx'); + put(clone, { 'apps/stateless/src/app/page.tsx': `${readFileSync(page, 'utf8')}// edited\n` }); + await git(clone, 'add', '-A'); + const appEdited = await hashes(clone, '@acme/stateless-e2e'); + assert.notEqual(appEdited[e2e], specEdited[e2e]); + assert.notEqual(appEdited[build], specEdited[build]); + }); + }); +}); + +/** The command lines of every process that mentions `text`. */ +async function mentioning(text: string): Promise { + const ps = await sh('ps', ['-axww', '-o', 'args='], here); + return ps.split('\n').filter((line) => line.includes(text)); +} + +/** Resolves once `check` holds, polling; rejects after `seconds`. */ +async function until(what: string, seconds: number, check: () => Promise | boolean): Promise { + for (const end = Date.now() + seconds * 1000; Date.now() < end; ) { + if (await check()) return; + await new Promise((resolve) => setTimeout(resolve, 250)); + } + throw new Error(`${what}: not within ${seconds} s`); +} + +describe('a repo with a stateful app, its suite and the answer postgres', () => { + let clone = ''; + before(async () => { + clone = await fresh(await newborn('stateful', { postgres: '18.6' }), 'stateful-clone'); + }); + + test('passes mise e2e from a fresh clone: migrate and seed run against the database the server gets', async () => { + const ran = await tryRun('mise', ['run', 'e2e', 'stateful'], clone, SHARED); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, /CREATE TABLE/); + assert.match(ran.output, /INSERT 0 1/); + assert.match(ran.output, /@acme\/stateful-e2e:e2e: .*2 passed/); + }); + + const kills: [string, (run: Launched) => Promise][] = [ + ['SIGINT of mise', async (run) => void process.kill(run.pid as number, 'SIGINT')], + ['SIGKILL of mise', async (run) => void process.kill(run.pid as number, 'SIGKILL')], + [ + 'SIGKILL of the Playwright runner', + async () => { + const ps = await sh('ps', ['-axww', '-o', 'pid=,args='], here); + const runner = ps + .split('\n') + .find( + (line) => line.includes(join(clone, 'e2e', 'stateful')) && /@playwright\/test\/cli\.js test/.test(line), + ); + assert.ok(runner, ps); + process.kill(Number.parseInt(runner, 10), 'SIGKILL'); + }, + ], + ]; + for (const [how, kill] of kills) + test(`a run killed by ${how} leaves no server and no PostgreSQL behind`, async () => { + // A spec that outlasts the kill; its temporary files, the database's cluster among them, are found by TMPDIR. + const tmp = join(here, `tmp-${how.replace(/\W+/g, '-')}`); + mkdirSync(tmp, { recursive: true }); + put(clone, { + 'e2e/stateful/specs/slow.spec.ts': + "import { test } from '@playwright/test';\n\ntest('waits', async () => {\n await new Promise((resolve) => setTimeout(resolve, 20_000));\n});\n", + }); + const run = launch('mise', ['run', 'e2e', 'stateful'], clone, { ...SHARED, TMPDIR: tmp }); + try { + await until('the specs run', 300, () => /Running \d+ tests/.test(run.output())); + const port = /http:\/\/127\.0\.0\.1:(\d+)/.exec(run.output())?.[1]; + assert.ok(port, run.output()); + const answers = () => + fetch(`http://127.0.0.1:${port}/healthz`).then( + (r) => r.ok, + () => false, + ); + assert.ok(await answers(), 'the server answers before the kill'); + assert.ok( + (await mentioning(tmp)).some((line) => /postgres/.test(line)), + 'and its database runs', + ); + await kill(run); + await Promise.race([run.closed, new Promise((resolve) => setTimeout(resolve, 120_000))]); + await until(`after ${how}, the server and the database are gone`, 30, async () => { + return !(await answers()) && (await mentioning(tmp)).length === 0; + }); + } finally { + run.kill(); + rmSync(join(clone, 'e2e', 'stateful', 'specs', 'slow.spec.ts'), { force: true }); + } + }); +}); From a28127ed83f6b7b63f8e990c53364ce43f94d489 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:39:43 +0100 Subject: [PATCH 088/194] feat(repo-turbo): e2e/* is a workspace glob of an app repo, where a suite is a package of its own Co-Authored-By: Claude Fable 5.2 --- templates/repo-turbo/files/pnpm-workspace.yaml.jinja | 1 + 1 file changed, 1 insertion(+) diff --git a/templates/repo-turbo/files/pnpm-workspace.yaml.jinja b/templates/repo-turbo/files/pnpm-workspace.yaml.jinja index 0c11733a..f31060af 100644 --- a/templates/repo-turbo/files/pnpm-workspace.yaml.jinja +++ b/templates/repo-turbo/files/pnpm-workspace.yaml.jinja @@ -1,6 +1,7 @@ packages: {%- if not publishes_packages %} - "apps/*" + - "e2e/*" {%- endif %} - "packages/*" catalog: From 5a2f94fa16c78d7d45e488be451e641c29955c9f Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:39:43 +0100 Subject: [PATCH 089/194] feat(repo-turbo): a suite's package.json is a source of install, as an app's is So that a change to a suite's dependencies runs pnpm install again before a verb. Co-Authored-By: Claude Fable 5.2 --- templates/repo-turbo/files/mise.toml.jinja | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/repo-turbo/files/mise.toml.jinja b/templates/repo-turbo/files/mise.toml.jinja index e19c8027..51edaa40 100644 --- a/templates/repo-turbo/files/mise.toml.jinja +++ b/templates/repo-turbo/files/mise.toml.jinja @@ -133,7 +133,7 @@ turbo run e2e ${dir:+--filter="...{./$dir}"} description = "Install and wire up project dependencies" hide = true run = "pnpm install" -sources = ["package.json", {% if not publishes_packages %}"apps/*/package.json", {% endif %}"packages/*/package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"] +sources = ["package.json", {% if not publishes_packages %}"apps/*/package.json", "e2e/*/package.json", {% endif %}"packages/*/package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"] outputs = ["node_modules/.pnpm/lock.yaml"] [tasks.lint] From a2075df4435bf2ede0f5fe76feb2dc5e328e702f Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:39:57 +0100 Subject: [PATCH 090/194] fix(e2e-playwright): setup.ts as a newborn's Biome formats it, so that the repo's check passes Co-Authored-By: Claude Fable 5.2 --- templates/e2e-playwright/files/setup.ts.jinja | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/templates/e2e-playwright/files/setup.ts.jinja b/templates/e2e-playwright/files/setup.ts.jinja index 1d32d5e9..a164ffd5 100644 --- a/templates/e2e-playwright/files/setup.ts.jinja +++ b/templates/e2e-playwright/files/setup.ts.jinja @@ -113,7 +113,11 @@ function freePort(): Promise { async function ready(url: string, server: ChildProcess): Promise { for (const until = Date.now() + 60_000; Date.now() < until; ) { if (server.exitCode !== null) throw new Error(`the server exited with ${server.exitCode} before ${url} answered`); - if (await fetch(url).then((response) => response.ok, () => false)) return; + const answered = await fetch(url).then( + (response) => response.ok, + () => false, + ); + if (answered) return; await new Promise((resolve) => setTimeout(resolve, 200)); } throw new Error(`${url} did not answer within a minute`); From b3cca1bc4c0e821081ea9ca2a19af817e5bd5b62 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 18:40:00 +0100 Subject: [PATCH 091/194] docs(cli): plx new's header names e2e-playwright among the templates it bundles Co-Authored-By: Claude Fable 5.2 --- packages/cli/src/commands/new.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/commands/new.ts b/packages/cli/src/commands/new.ts index f2009d87..bf5f3307 100644 --- a/packages/cli/src/commands/new.ts +++ b/packages/cli/src/commands/new.ts @@ -8,8 +8,9 @@ // where the root lists templates and is on another version than this plx or // names none; anywhere else it is a new repo. The templates are the ones this // plx bundles, named as the directories of `templates/` are (repo-turbo, -// repo-operations, app-nextjs, updates). A repo is born from its repo -// template with `updates` beside it, which a repo may also go without. +// repo-operations, app-nextjs, e2e-playwright, updates). A repo is born from +// its repo template with `updates` beside it, which a repo may also go +// without. // Answers come as `-a key=value`, repeatable, and as a JSON object in a file // (`--answers`); a flag wins over the file, a value is cast to its question's // type. Nothing is ever asked: a missing answer fails the run, listing every @@ -23,6 +24,7 @@ // // plx new ~/dev/acme/web repo-turbo updates -a tenant=acme // plx new ~/dev/acme/web/apps/shop app-nextjs -a name=shop -a profile=stateful +// plx new ~/dev/acme/web/e2e/shop e2e-playwright -a app=shop // plx new ./ops repo-operations updates --answers ops.json // plx -n new ./web repo-turbo updates -a tenant=acme # what it would write and run import { resolve } from 'node:path'; From 16bc4e22e0d9e2bef3923d3b4788882a482b76c8 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 19:02:27 +0100 Subject: [PATCH 092/194] plx doctor: PLX-Repo/Hooks asks only that hk.pkl wires a pre-commit and a pre-push hook; a missing verb says what to write (red) Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/doctor.test.ts | 163 ++++++++++------------ packages/lib/src/testing/doctor-checks.md | 2 +- 2 files changed, 76 insertions(+), 89 deletions(-) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index fcb25de9..eb625ff7 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -40,11 +40,12 @@ test('the checks are exactly the requirements the contract pages say doctor chec /** The five repo verbs, as `plx doctor` asks for them. */ const VERBS = ['dev', 'build', 'check', 'test', 'e2e']; -/** The hooks of a repo that meets PLX-Repo/Hooks: the commands of each hook's steps. `test` runs `check` first. */ -/** The mise tasks of a repo that has these: `test` runs `check` first, as the templates write it. */ -const tasksOf = (names: string[]) => ({ names, calls: { test: ['check'] } }); +/** The hooks `hk.pkl` of a repo that meets PLX-Repo/Hooks wires. */ +const HOOKS = ['pre-commit', 'pre-push']; -const HOOKS = { 'pre-commit': ['mise :lint {{ files }}'], 'pre-push': ['mise :test'] }; +/** What `plx doctor` says of a verb the repo lacks, which a repo with no use for it answers with a no-op that passes. */ +const noTask = (verb: string) => + `no root mise task \`${verb}\`: add one, a no-op that passes where the repo has no use for it`; const reasoned = (names: string[]) => names.map((n) => `- \`${n}\`: the reason.`).join('\n'); @@ -52,7 +53,7 @@ const repo = (over: Partial = {}): RepoFacts => ({ kind: 'repo', path: 'r', marker: { declaration: { deviations: [], body: '' } }, - tasks: tasksOf([...VERBS, 'lint', 'install']), + tasks: { names: [...VERBS, 'lint', 'install'] }, hk: HOOKS, tracked: ['mise.toml', 'apps/a/docker/compose.yaml'], apps: ['apps/a'], @@ -116,18 +117,18 @@ const FAILING: Record Facts; problem: 'PLX-Repo/Verbs': { unit: (deviations = []) => repo({ - tasks: tasksOf(VERBS.filter((v) => v !== 'build')), + tasks: { names: VERBS.filter((v) => v !== 'build') }, marker: { declaration: { deviations, body: reasoned(deviations) } }, }), - problem: /^no root mise task `build`$/, + problem: /^no root mise task `build`: add one, a no-op that passes/, }, 'PLX-Repo/Hooks': { unit: (deviations = []) => repo({ - hk: { ...HOOKS, 'pre-push': ['mise :check'] }, + hk: ['pre-commit'], marker: { declaration: { deviations, body: reasoned(deviations) } }, }), - problem: /^the `pre-push` hook does not run `test`$/, + problem: /^hk\.pkl wires no `pre-push` hook$/, }, 'PLX-App/Marker': { unit: (d) => app(undefined, {}, d), @@ -309,108 +310,100 @@ test('mise could not list the tasks: PLX-Repo/Verbs says why, once', () => { // --- the five verbs and the hooks ---------------------------------------------------- test('a repo with the five verbs passes, with or without a lint task; each one missing is a finding naming it', () => { - assert.deepEqual(findings(repo({ tasks: tasksOf(VERBS) })), []); + assert.deepEqual(findings(repo({ tasks: { names: VERBS } })), []); for (const verb of VERBS) - assert.deepEqual(findings(repo({ tasks: tasksOf(VERBS.filter((v) => v !== verb)) })), [ - { requirement: 'PLX-Repo/Verbs', problem: `no root mise task \`${verb}\`` }, + assert.deepEqual(findings(repo({ tasks: { names: VERBS.filter((v) => v !== verb) } })), [ + { requirement: 'PLX-Repo/Verbs', problem: noTask(verb) }, ]); }); test('a leftover verify task is a finding of PLX-Repo/Verbs that names its replacement', () => { - const found = findings(repo({ tasks: tasksOf([...VERBS, 'verify']) })); + const found = findings(repo({ tasks: { names: [...VERBS, 'verify'] } })); assert.equal(found.length, 1); assert.equal(found[0]?.requirement, 'PLX-Repo/Verbs'); assert.match(found[0]?.problem ?? '', /^a root mise task `verify` is left over: `check` and `test` replace it/); }); -test('PLX-Repo/Hooks: a pre-push hook runs check and test, directly or through a task that runs them', () => { - const push = (commands: string[], calls: Record = {}) => - findings(repo({ hk: { ...HOOKS, 'pre-push': commands }, tasks: { names: VERBS, calls } })).map((f) => f.problem); - assert.deepEqual(push(['mise :check', 'mise :test']), []); - assert.deepEqual(push(['mise :test'], { test: ['check'] }), [], 'test runs check first'); - assert.deepEqual(push(['mise run test'], { test: ['check'] }), [], 'in either spelling'); - assert.deepEqual(push(['mise :check']), ['the `pre-push` hook does not run `test`']); - assert.deepEqual(push(['mise :test']), ['the `pre-push` hook does not run `check`'], 'a test that does not check'); - assert.deepEqual(push(['mise :lint']), [ - 'the `pre-push` hook does not run `check`', - 'the `pre-push` hook does not run `test`', - ]); - assert.deepEqual(push(['mise :gates'], { gates: ['check', 'test'] }), [], 'through a task of the repo'); - assert.deepEqual(push(['mise :a'], { a: ['b'], b: ['a'] }), [ - 'the `pre-push` hook does not run `check`', - 'the `pre-push` hook does not run `test`', - ]); -}); - -test('PLX-Repo/Hooks: a pre-commit hook is required, and what it runs is not read', () => { +test('PLX-Repo/Hooks: hk.pkl must wire a pre-commit and a pre-push hook, one finding for each that is missing', () => { + assert.deepEqual(findings(repo({ hk: HOOKS })), []); assert.deepEqual( - findings(repo({ hk: { 'pre-push': HOOKS['pre-push'] } })).map((f) => f.problem), + findings(repo({ hk: ['pre-push'] })).map((f) => f.problem), ['hk.pkl wires no `pre-commit` hook'], ); - assert.deepEqual(findings(repo({ hk: { ...HOOKS, 'pre-commit': [] } })), []); -}); - -test('PLX-Repo/Hooks: no hk.pkl, and no pre-push hook, are findings', () => { + assert.deepEqual( + findings(repo({ hk: ['pre-commit'] })).map((f) => f.problem), + ['hk.pkl wires no `pre-push` hook'], + ); + assert.deepEqual( + findings(repo({ hk: ['commit-msg'] })).map((f) => f.problem), + ['hk.pkl wires no `pre-commit` hook', 'hk.pkl wires no `pre-push` hook'], + ); const { hk: _, ...bare } = repo(); assert.deepEqual( findings(bare).map((f) => f.problem), ['no hk.pkl, which wires the git hooks'], ); - assert.deepEqual( - findings(repo({ hk: { 'pre-commit': [] } })).map((f) => f.problem), - ['hk.pkl wires no `pre-push` hook'], - ); }); -/** The findings of the repo at /ws/web whose hk.pkl and `test` task are as given. */ -async function hooksOver(pkl: string | undefined, testRuns = 'mise run check\nturbo run test') { +/** The findings of the repo at /ws/web whose hk.pkl is as given. */ +async function hooksOver(pkl: string | undefined) { const tree = ws(); const web = tree.web as Tree; if (pkl === undefined) delete web['hk.pkl']; else web['hk.pkl'] = pkl; - const task = (name: string) => ({ - name: `//:${name}`, - source: '/ws/web/mise.toml', - global: false, - ...(name === 'test' ? { run: [testRuns] } : {}), - }); const git = (cwd: string, args: string[]) => (args[0] === 'ls-files' && cwd === '/ws/web' ? '' : undefined); - const ctx = new Context({}, fakeIo({ ws: tree }, git, { mise: () => JSON.stringify(ALL_TASKS.map(task)) })); + const ctx = new Context({}, fakeIo({ ws: tree }, git, { mise: miseTasks({ '/ws/web': ALL_TASKS }) })); return diagnose((await examine(ctx, '/ws/web')).facts).units[0]?.findings.map((f) => f.problem); } -const PKL = (push: string, commit = 'mise :lint {{ files }}') => `amends "package://example.org/hk@1/Config.pkl" +const STEP = '{ steps { ["s"] { check = "mise :check" } } }'; +const PKL = (hooks: string) => `amends "package://example.org/hk@1/Config.pkl"\n\nhooks {\n${hooks}\n}\n`; +const WIRED = PKL(` ["pre-commit"] ${STEP}\n ["pre-push"] ${STEP}`); -hooks { - ["pre-commit"] { - fix = true - steps { - ["lint"] { - check = "${commit}" - fix = "mise :lint --write {{ files }}" - } - } - } - ["pre-push"] { - steps { - ["test"] { - check = "${push}" - } - } - } -} -`; +test('PLX-Repo/Hooks is existence only: a pre-push hook that runs only check passes, as does a hook without steps', async () => { + assert.deepEqual(await hooksOver(WIRED), []); + assert.deepEqual( + await hooksOver(PKL(` ["pre-commit"] {}\n ["pre-push"] ${STEP.replace('mise :check', 'true')}`)), + [], + ); +}); -test('doctor reads the hooks from hk.pkl and what a task runs from mise', async () => { - assert.deepEqual(await hooksOver(PKL('mise :test')), [], 'the template: pre-push runs test, which runs check'); - assert.deepEqual(await hooksOver(PKL('mise :test'), 'turbo run test'), ['the `pre-push` hook does not run `check`']); - assert.deepEqual(await hooksOver(PKL('mise :check')), ['the `pre-push` hook does not run `test`']); +test('PLX-Repo/Hooks: no hk.pkl, and a hook of another name, are findings', async () => { assert.deepEqual(await hooksOver(undefined), ['no hk.pkl, which wires the git hooks']); - assert.deepEqual(await hooksOver(PKL('mise :test').replace('["pre-commit"]', '["commit-msg"]')), [ + assert.deepEqual(await hooksOver(WIRED.replace('"pre-commit"', '"commit-msg"')), [ + 'hk.pkl wires no `pre-commit` hook', + ]); + assert.deepEqual(await hooksOver(WIRED.replace('"pre-push"', '"post-merge"')), ['hk.pkl wires no `pre-push` hook']); + assert.deepEqual(await hooksOver('amends "package://example.org/hk@1/Config.pkl"\n'), [ 'hk.pkl wires no `pre-commit` hook', + 'hk.pkl wires no `pre-push` hook', ]); - // A brace inside a command does not end its block. - assert.deepEqual(await hooksOver(PKL('echo } && mise :test', 'echo { }')), []); +}); + +test('PLX-Repo/Hooks: a hook behind a comment is not wired', async () => { + const noPush = ['hk.pkl wires no `pre-push` hook']; + const commit = ` ["pre-commit"] ${STEP}\n`; + assert.deepEqual(await hooksOver(PKL(`${commit} /* ["pre-push"] ${STEP} */`)), noPush, 'a block comment'); + assert.deepEqual(await hooksOver(PKL(`${commit} /*\n ["pre-push"] ${STEP}\n */`)), noPush, 'over lines'); + assert.deepEqual(await hooksOver(PKL(`${commit} // ["pre-push"] ${STEP}`)), noPush, 'a line comment'); + assert.deepEqual(await hooksOver(PKL(`${commit} // ["pre-push"] {\n }`)), noPush, 'a key line commented out'); +}); + +test('PLX-Repo/Hooks: a hook name inside a string, or as a step of another hook, is not a hook', async () => { + const commit = ` ["pre-commit"] ${STEP}\n`; + const noPush = ['hk.pkl wires no `pre-push` hook']; + assert.deepEqual( + await hooksOver(PKL(`${commit} ["post-merge"] { steps { ["s"] { check = "x [\\"pre-push\\"] {" } } }`)), + noPush, + 'in a string', + ); + assert.deepEqual( + await hooksOver(PKL(` ["pre-commit"] { steps { ["pre-push"] { check = "true" } } }`)), + noPush, + 'a step of that name', + ); + assert.deepEqual(await hooksOver(PKL(`${commit} ["s"] { check = "http://x" }\n ["pre-push"] ${STEP}`)), []); + assert.deepEqual(await hooksOver(`["pre-push"] ${STEP}\n${PKL(commit)}`), noPush, 'outside the hooks block'); }); // --- compose's spellings ----------------------------------------------------------- @@ -740,13 +733,7 @@ const miseTasks = const names = own[cwd]; if (!names) return undefined; return JSON.stringify([ - // `test` runs `check` first, as the templates write it. - ...names.map((n) => ({ - name: `//:${n}`, - source: `${cwd}/mise.toml`, - global: false, - ...(n === 'test' ? { run: ['mise run check\nturbo run test'] } : {}), - })), + ...names.map((n) => ({ name: `//:${n}`, source: `${cwd}/mise.toml`, global: false })), { name: 'pull', source: '/ws/mise.toml', global: false }, { name: 'fmt', source: '/home/.config/mise/config.toml', global: true }, ]); @@ -836,7 +823,7 @@ test('doctor in a repo fails on a missing build task and passes once it exists', assert.deepEqual( before.units.map((u) => [u.path, u.kind, u.findings]), [ - ['.', 'repo', [{ requirement: 'PLX-Repo/Verbs', problem: 'no root mise task `build`' }]], + ['.', 'repo', [{ requirement: 'PLX-Repo/Verbs', problem: noTask('build') }]], ['apps/site', 'app', []], ], ); @@ -1130,8 +1117,8 @@ test("a task from a file the repo includes from outside counts by its `dir`; a p ]), ); assert.deepEqual(report.units[0]?.findings, [ - { requirement: 'PLX-Repo/Verbs', problem: 'no root mise task `check`' }, - { requirement: 'PLX-Repo/Verbs', problem: 'no root mise task `test`' }, + { requirement: 'PLX-Repo/Verbs', problem: noTask('check') }, + { requirement: 'PLX-Repo/Verbs', problem: noTask('test') }, ]); }); diff --git a/packages/lib/src/testing/doctor-checks.md b/packages/lib/src/testing/doctor-checks.md index 87827db6..571d5a32 100644 --- a/packages/lib/src/testing/doctor-checks.md +++ b/packages/lib/src/testing/doctor-checks.md @@ -8,7 +8,7 @@ set to a compendium checkout it reads the pages themselves instead. `plx doctor` checks `PLX-Repo/Marker`. -`plx doctor` checks of `PLX-Repo/Verbs` that `dev`, `build`, `check`, `test` and `e2e` exist as root mise tasks and that no `verify` is left, not what they run, in which order, or whether they pass, and of `PLX-Repo/Hooks` that `hk.pkl` wires a pre-commit hook and a pre-push hook that runs `check` and `test`, not what the pre-commit hook runs. +`plx doctor` checks of `PLX-Repo/Verbs` that `dev`, `build`, `check`, `test` and `e2e` exist as root mise tasks and that no `verify` is left, not what they run, in which order, or whether they pass, and of `PLX-Repo/Hooks` that `hk.pkl` wires a pre-commit hook and a pre-push hook, not what either runs. `plx doctor` checks `PLX-App/Marker`. From c77c8737a462003fbc35cf1cdb5eeda771eb4b8d Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 19:03:11 +0100 Subject: [PATCH 093/194] plx doctor: PLX-Repo/Hooks reads only which hooks hk.pkl wires; a missing verb says what to write Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/doctor.ts | 134 +++++++++++++------------------------ 1 file changed, 47 insertions(+), 87 deletions(-) diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index 3353f9eb..e87b84cb 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -58,17 +58,11 @@ // // The repo's verbs are the five of VERBS, root mise tasks: PLX-Repo/Verbs // reports each that is missing, and a task `verify`, which no repo has any -// more, with the tasks that replace it. The order of the gates (`check`, -// `test`, `build`, `e2e`) is kept by the tasks, not by a requirement, so -// nothing reads what a task runs, except for PLX-Repo/Hooks: the hooks are -// read from the `hooks` block of `hk.pkl` as a repo's template writes it -// (hookCommands), the `check` command of every step of a hook, and a hook runs -// a task when a command names it (`mise :t`, `mise run t`) or a task it names -// runs it, by `depends` or by a `mise` line of its `run` (`rootTasks`). That -// lets the pre-push hook of a repo whose `test` runs `check` first run `test` -// alone. Which hook steps run, with which files, is hk's business; the check -// asks that a pre-commit hook is wired and that the pre-push hook reaches -// `check` and `test`. +// more, with the tasks that replace it. Only the names of the tasks are read, +// never what a task runs: the order of the gates (`check`, `test`, `build`, +// `e2e`) is kept by the tasks, not by a requirement. PLX-Repo/Hooks is +// existence only in the same way: `hk.pkl` wires a pre-commit and a pre-push +// hook (`hooksWired`), and what either runs is not read. // // plx doctor # this repo and its apps, from anywhere inside it // plx doctor ~/dev # every Plexus repo beneath, and its apps @@ -116,10 +110,10 @@ export interface RepoFacts { path: string; /** Undefined when the repo carries no marker. */ marker?: MarkerRead; - /** The root mise tasks, with the tasks each depends on or runs, or why mise could not list them. */ - tasks: { names: string[]; calls?: Record } | { problem: string }; - /** The `check` commands of the steps of each hook of `hk.pkl`, by hook; undefined where there is no `hk.pkl`. */ - hk?: Record; + /** The root mise tasks, or why mise could not list them. */ + tasks: { names: string[] } | { problem: string }; + /** The hooks `hk.pkl` wires, by name; undefined where there is no `hk.pkl`. */ + hk?: string[]; /** The files git tracks, relative to the repo; undefined outside a git checkout. */ tracked?: string[]; /** The tracked files that hold a conflict marker, relative to the repo. */ @@ -171,9 +165,6 @@ export type Facts = RepoFacts | AppFacts; /** The repo verbs, in the order of the gates: one list for the check and for anything that names them. */ const VERBS = ['dev', 'build', 'check', 'test', 'e2e'] as const; -/** The two verbs the pre-push hook must reach. */ -const GATES = ['check', 'test']; - function repoMarker(repo: RepoFacts): string[] { if (!repo.marker) return [`no ${MARKER_FILE} at the repo's root`]; return repo.marker.problem ? [repo.marker.problem] : []; @@ -183,39 +174,20 @@ function verbs(repo: RepoFacts): string[] { if ('problem' in repo.tasks) return [`mise could not list the tasks: ${repo.tasks.problem}`]; const { names } = repo.tasks; return [ - ...VERBS.filter((verb) => !names.includes(verb)).map((verb) => `no root mise task \`${verb}\``), + ...VERBS.filter((verb) => !names.includes(verb)).map( + (verb) => `no root mise task \`${verb}\`: add one, a no-op that passes where the repo has no use for it`, + ), ...(names.includes('verify') ? ['a root mise task `verify` is left over: `check` and `test` replace it, `mise test` running `check` first'] : []), ]; } -/** The tasks a shell command names: `mise :t`, `mise t`, `mise run t`. */ -const tasksNamed = (command: string): string[] => - [...command.matchAll(/(?:^|[\s;&|(])mise\s+(?:run\s+)?:?([A-Za-z][\w:-]*)/g)].map((m) => m[1] ?? ''); - -/** Existence only: the commands of each hook are read to find the tasks it reaches, not to judge them. */ +/** Existence only: what a hook runs is not read. */ function hooks(repo: RepoFacts): string[] { - const { hk } = repo; - if (!hk) return ['no hk.pkl, which wires the git hooks']; - const problems: string[] = []; - if (!hk['pre-commit']) problems.push('hk.pkl wires no `pre-commit` hook'); - const push = hk['pre-push']; - if (!push) return [...problems, 'hk.pkl wires no `pre-push` hook']; - // Which tasks a hook reaches is unknown while mise cannot list them, which PLX-Repo/Verbs reports. - if ('problem' in repo.tasks) return problems; - const calls = repo.tasks.calls ?? {}; - const reached = new Set(); - const queue = push.flatMap(tasksNamed); - for (let task = queue.pop(); task !== undefined; task = queue.pop()) - if (!reached.has(task)) { - reached.add(task); - queue.push(...(calls[task] ?? [])); - } - return [ - ...problems, - ...GATES.filter((g) => !reached.has(g)).map((g) => `the \`pre-push\` hook does not run \`${g}\``), - ]; + if (!repo.hk) return ['no hk.pkl, which wires the git hooks']; + const wired = repo.hk; + return ['pre-commit', 'pre-push'].filter((h) => !wired.includes(h)).map((h) => `hk.pkl wires no \`${h}\` hook`); } function appMarker(app: AppFacts): string[] { @@ -691,7 +663,7 @@ async function readRepo( plxVersion?: string, ): Promise { const marker = markerOf(dir); - const hk = await ctx.readFile(join(dir.path, 'hk.pkl')).then(hookCommands, () => undefined); + const hk = await ctx.readFile(join(dir.path, 'hk.pkl')).then(hooksWired, () => undefined); const tracked = await ctx .read('git', ['ls-files', '-z'], { cwd: dir.path }) .then((out) => out.split('\0').filter(Boolean)) @@ -770,38 +742,34 @@ async function readSites(ctx: Context, repo: string): Promise { - const start = /^hooks\s*\{/m.exec(pkl); - if (!start) return {}; - const open = start.index + start[0].length - 1; - const body = pkl.slice(open + 1, closing(pkl, open)); - const found: Record = {}; - const hook = /\[\s*"([^"]+)"\s*\]\s*\{/g; - for (let at = hook.exec(body); at; at = hook.exec(body)) { - const from = at.index + at[0].length - 1; - const end = closing(body, from); - found[at[1] ?? ''] = [...body.slice(from, end).matchAll(/\bcheck\s*=\s*"((?:[^"\\]|\\.)*)"/g)].map( - (m) => m[1] ?? '', - ); - hook.lastIndex = end; - } - return found; + let inside = false; + tokens.forEach(({ string, text }, i) => { + if (string) return; + if (text === '{') depth++; + else if (text === '}') depth--; + if (depth === 0) inside = false; + const next = tokens.slice(i + 1, i + 4).map((t) => (t.string ? '"' : t.text)); + if (depth === 0 && text === 'hooks' && next[0] === '{') inside = true; + const key = tokens[i + 1]; + if (inside && depth === 1 && text === '[' && next.join('') === '"]{' && key) wired.push(key.text); + }); + return wired; } /** @@ -848,26 +816,18 @@ async function rootTasks(ctx: Context, repo: string): Promise = {}; - const bare = (name: string) => (name.startsWith('//:') ? name.slice(3) : name); for (const task of listed) { if (!isOwn(task)) continue; - const runs = (Array.isArray(task.run) ? task.run : []).flatMap((r: unknown) => - typeof r === 'string' ? tasksNamed(r) : isMapping(r) && typeof r.task === 'string' ? [r.task] : [], - ); - const depends = (Array.isArray(task.depends) ? task.depends : []).filter((d: unknown) => typeof d === 'string'); const aliases = Array.isArray(task.aliases) ? task.aliases.filter((a: unknown): a is string => typeof a === 'string') : []; for (const name of [task.name as string, ...aliases]) { // A monorepo root names its own tasks `//:`; `//:` is a sub-project's. - if (name.startsWith('//:') || !name.startsWith('//')) { - names.push(bare(name)); - calls[bare(name)] = [...depends, ...runs].map(bare); - } + if (name.startsWith('//:')) names.push(name.slice(3)); + else if (!name.startsWith('//')) names.push(name); } } - return { names, calls }; + return { names }; } async function readApp(ctx: Context, dir: Directory, path: string, inRepo: string, repo: RepoFacts): Promise { From 798f4fe338d56cb57425660ae64bfc55c7e2c2c9 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 19:03:11 +0100 Subject: [PATCH 094/194] the move test of repo-operations asserts its local edit survives, and its title says what it compares Co-Authored-By: Claude Fable 5.2 --- packages/dev/src/ship.integration.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index 2b1aa009..8197159b 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -1865,7 +1865,7 @@ for (const [template, answers, edits] of [ }, ], ] as const) - test(`update: ${template} loses the files updates now holds, and adding updates on the branch gives back the repo as it was`, async () => { + test(`update: ${template} loses the files updates now holds, keeps its local edits, and gets those files back, with the marker, when updates is added on the branch`, async () => { fixture(`move-${template}`); const { dir, name, start } = await bornBefore(template, answers, edits); for (const path of MOVED) assert.ok(path in start, `born with ${path}`); @@ -1882,6 +1882,8 @@ for (const [template, answers, edits] of [ assert.match(marker, new RegExp(`^---\\nversion: ${CURRENT}\\ntemplates: \\[${template}\\]\\n`)); assert.match(marker, /\npr_reviewers: alice\n/, 'the answers stay in the marker'); assert.equal(pull(name, CURRENT, '.reviewers'), 'alice', 'and are read'); + if (template === 'repo-operations') + assert.match(onVersion(name, CURRENT, 'inventory/hosts.yml'), /^# our hosts$/m, 'the local edit kept'); if (template === 'repo-turbo') { const onPr = onVersion(name, CURRENT, '.github/workflows/on_pr.yml'); assert.doesNotMatch(onPr, /^ {2}changeset:$/m, "no job writes the bot's changesets without updates"); From 54cbea552d98ae7e4db8bb34764878aba9bfe353 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 19:03:48 +0100 Subject: [PATCH 095/194] doctor test: a key of another block is not a hook Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/doctor.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index eb625ff7..322b57b7 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -403,7 +403,8 @@ test('PLX-Repo/Hooks: a hook name inside a string, or as a step of another hook, 'a step of that name', ); assert.deepEqual(await hooksOver(PKL(`${commit} ["s"] { check = "http://x" }\n ["pre-push"] ${STEP}`)), []); - assert.deepEqual(await hooksOver(`["pre-push"] ${STEP}\n${PKL(commit)}`), noPush, 'outside the hooks block'); + const other = `other {\n ["pre-push"] ${STEP}\n}\n${PKL(commit)}`; + assert.deepEqual(await hooksOver(other), noPush, 'a key of another block'); }); // --- compose's spellings ----------------------------------------------------------- From 4d14a695225e394a8bf9cc16b4755180ad5239e5 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 19:03:51 +0100 Subject: [PATCH 096/194] tests: no remote cache is none, a trusted verb reads no local cache, a job is the forge's, a safe team, a loopback server, a warning on the run Red against the code. turbow: where it runs without a remote cache Turbo is told so (TURBO_CACHE=local:rw, empty server, team and token) and no other remote-cache variable of the caller reaches it; a trusted verb with its server runs on the remote cache alone; TURBO_FORCE keeps its meaning; a job is GITHUB_ACTIONS=true, CI alone is any machine's; the team holds [a-z0-9._-] and needs an owner. The step: the item and bucket of each cache, the token masked first, announce for its own cache only, one warning annotation per cause, a server bound to 127.0.0.1 and one that does not come up failing no job. Newborns: a login and a linked repo send nothing anywhere; with both servers a build after a test in one checkout replays nothing. Green already, as tests of what the code does: Turbo's exit status and arguments with spaces. Co-Authored-By: Claude Fable 5.2 --- newborns/turbo-cache.test.ts | 137 ++++++++++---- packages/lib/src/repoTurboCache.test.ts | 232 +++++++++++++++++------- packages/lib/src/turboCacheStep.test.ts | 129 +++++++++++++ 3 files changed, 390 insertions(+), 108 deletions(-) create mode 100644 packages/lib/src/turboCacheStep.test.ts diff --git a/newborns/turbo-cache.test.ts b/newborns/turbo-cache.test.ts index 876901e1..1af30299 100644 --- a/newborns/turbo-cache.test.ts +++ b/newborns/turbo-cache.test.ts @@ -4,21 +4,26 @@ // on a free loopback port, with the tenant acme's two buckets; the server is // the binary the step's action starts, fetched at the commit the step pins. // -// On a developer's machine (CI unset), with the shared server running without -// a token as a developer runs it: `mise test` writes the shared bucket under -// the team acme-web, and a second clone, by another remote form of the same -// repo, hits every task; `mise build` and `mise e2e` use the shared server too. -// In a CI job (CI=true), run as a job runs the step: its scripts plan and -// announce around the server, which is started with the environment the step -// gives the action, and the vault's read stood in for by the stand-in's keys. -// With the trusted server, `build` and `e2e` write the trusted bucket and the -// shared server sees no request; `check` and `test` find no shared server in -// that job and run without one. Where the tenant has no bucket the verbs run -// without a remote cache; without the step `build` fails. Every case sets or -// unsets CI itself. Needs Docker and the network, as the newborns do. +// On a developer's machine (outside a job of the forge, whatever CI says), with +// the shared server running without a token as a developer runs it: `mise +// test` writes the shared bucket under the team acme-web, and a second clone, +// by another remote form of the same repo, hits every task; `mise build` and +// `mise e2e` use the shared server too. With a Turbo login and a linked repo +// but no server, no verb sends a request anywhere. +// In a job of the forge (GITHUB_ACTIONS=true), run as a job runs the step: its +// scripts plan and announce around the server, which is started with the +// environment the step gives the action, and the vault's read stood in for by +// the stand-in's keys. With the trusted server, `build` and `e2e` write the +// trusted bucket and the shared server sees no request; `check` and `test` find +// no shared server in that job and run without one. With both servers in one +// checkout, a build after a test reads nothing of the local cache the test +// filled. Where the tenant has no bucket the verbs run without a remote cache; +// without the step `build` fails. Every case sets or unsets GITHUB_ACTIONS +// itself. Needs Docker and the network, as the newborns do. import assert from 'node:assert/strict'; import { type ChildProcess, spawn } from 'node:child_process'; import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:http'; import { arch, platform } from 'node:os'; import { join } from 'node:path'; import { after, before, describe, test } from 'node:test'; @@ -242,70 +247,126 @@ describe('a newborn app repo with the two remote caches', () => { sharedLog = await serve(SHARED_BUCKET, port); }); + /** A server the step plans, starts and announces in a job, for `cache`: what the job's later steps get. */ + async function jobServer(cache: 'shared' | 'trusted'): Promise> { + const plan = await step('plan', { CACHE: cache, OWNER: 'acme', VAULT: 'acme-ci', SERVICE_ACCOUNT: 'true' }); + const port = Number(plan.outputs.port); + const token = plan.outputs.token ?? ''; + // What the action is given by the step: the planned port and token, the bucket, and the keys the vault holds. + await serve(plan.outputs.bucket ?? '', port, token); + const told = await step('announce', { + CACHE: cache, + KEYS: 'success', + SERVER: 'success', + PORT: String(port), + TOKEN: token, + }); + return told.env; + } + + /** A developer's machine: no job of the forge, though CI may be set there too. */ + const machine = () => ({ GITHUB_ACTIONS: '', CI: 'true', PLX_TURBO_SHARED: sharedUrl, PLX_TURBO_TRUSTED: '' }); + test('on a developer’s machine, mise test writes the shared bucket, and a second clone hits it', async () => { - const machine = { CI: '', PLX_TURBO_SHARED: sharedUrl, PLX_TURBO_TRUSTED: '' }; const first = await clone(origin, 'first', 'https://github.com/acme/web.git'); - const tested = await verb(first, 'test', machine); + const tested = await verb(first, 'test', machine()); assert.match(tested, /turbow: the shared remote cache at http:\/\/127\.0\.0\.1:\d+, team acme-web/); assert.match(tested, /test-ran site/); const written = await keys(SHARED_BUCKET); assert.ok(written.length >= 4, `the shared bucket holds the run's tasks under acme-web: ${written}`); const second = await clone(origin, 'second', 'git@github.com:acme/web.git'); - const again = await verb(second, 'test', machine); + const again = await verb(second, 'test', machine()); assert.match(again, /cache hit, replaying logs/); assert.doesNotMatch(again, /cache miss/, 'every task of the second clone is a hit'); - // Outside CI there is no trusted server: build and e2e use the shared one. + // Outside a job there is no trusted server: build and e2e use the shared one, CI set or not. for (const task of ['build', 'e2e']) - assert.match(await verb(second, task, machine), /turbow: the shared remote cache at /, task); + assert.match(await verb(second, task, machine()), /turbow: the shared remote cache at /, task); }); - test('in a CI job with the step’s trusted server, build and e2e write the trusted bucket, and the shared server sees nothing', async () => { - const job = await clone(origin, 'trusted-job', 'https://github.com/acme/web'); - const plan = await step('plan', { CACHE: 'trusted', OWNER: 'acme', VAULT: 'acme-ci', SERVICE_ACCOUNT: 'true' }); - assert.equal(plan.outputs.read, 'true'); - assert.equal(plan.outputs.bucket, TRUSTED_BUCKET); - assert.equal(plan.outputs.item, 'bucket-turbo-trusted'); - const port = Number(plan.outputs.port); - const token = plan.outputs.token ?? ''; - assert.match(token, /^[0-9a-f]{64}$/, 'a token minted for the job'); - // What the action is given by the step: the planned port and token, the bucket, and the keys the vault holds. - await serve(plan.outputs.bucket ?? '', port, token); - const told = await step('announce', { CACHE: 'trusted', KEYS: 'success', PORT: String(port), TOKEN: token }); - assert.deepEqual(told.env, { PLX_TURBO_TRUSTED: `http://127.0.0.1:${port}`, PLX_TURBO_TRUSTED_TOKEN: token }); + test('on a developer’s machine with a Turbo login and a linked repo, a verb without a server sends nothing anywhere', async () => { + let hits = 0; + const listener = createServer((req, res) => { + hits++; + req.resume(); + res.statusCode = 404; + res.end(); + }); + const port = await freePort(); + await new Promise((resolve) => listener.listen(port, '127.0.0.1', resolve)); + try { + const linked = await clone(origin, 'linked', 'https://github.com/acme/web'); + // What `turbo link` leaves in the checkout, and `turbo login` in Turbo's configuration directory, which + // TURBO_CONFIG_DIR_PATH names (read by Turbo 2.11.13 as run, not documented). + put(linked, { '.turbo/config.json': { apiUrl: `http://127.0.0.1:${port}`, teamSlug: 'linked' } }); + put(here, { 'turbo-login/turborepo/config.json': { token: 'a-login-token' } }); + const env = { ...machine(), PLX_TURBO_SHARED: 'none', TURBO_CONFIG_DIR_PATH: join(here, 'turbo-login') }; + // The control: Turbo alone sends the linked team's artifacts with the login token. + const alone = await tryRun('mise', ['exec', '--', 'turbo', 'run', 'check', '--force'], linked, env); + assert.ok(alone.ok, alone.output); + assert.ok(hits > 0, 'Turbo alone reaches the linked server'); + hits = 0; + for (const task of ['check', 'test', 'build', 'e2e']) { + const ran = await verb(linked, task, env); + assert.match(ran, /turbow: without a remote cache/, task); + assert.match(ran, /Remote caching disabled/, task); + } + assert.equal(hits, 0, 'no request reached the linked server'); + } finally { + await new Promise((resolve) => listener.close(() => resolve())); + } + }); + test('in a job with the step’s trusted server, build and e2e write the trusted bucket, and the shared server sees nothing', async () => { + const job = await clone(origin, 'trusted-job', 'https://github.com/acme/web'); + const told = await jobServer('trusted'); + assert.deepEqual(Object.keys(told).sort(), ['PLX_TURBO_TRUSTED', 'PLX_TURBO_TRUSTED_TOKEN']); const before = requests(sharedLog).length; - const ci = { CI: 'true', PLX_TURBO_SHARED: '', ...told.env }; + const env = { GITHUB_ACTIONS: 'true', CI: 'true', PLX_TURBO_SHARED: '', ...told }; for (const task of ['build', 'e2e']) - assert.match(await verb(job, task, ci), /turbow: the trusted remote cache at /, task); + assert.match(await verb(job, task, env), /turbow: the trusted remote cache at /, task); assert.ok((await keys(TRUSTED_BUCKET)).length >= 3, 'the trusted bucket holds the builds and the e2e runs'); - const tested = await verb(job, 'test', ci); + const tested = await verb(job, 'test', env); assert.match(tested, /turbow: without a remote cache: this job started no shared cache server/); assert.equal(requests(sharedLog).length, before, 'the shared server saw no request from the job'); }); - test('in a CI job where the tenant has no bucket, the step says so and every verb runs without a remote cache', async () => { + test('in a job with both servers, a build after a test in one checkout reads nothing the test left in the local cache', async () => { + // A repo of its own name, so that neither bucket holds its tasks yet. + const job = await clone(origin, 'one-checkout', 'https://github.com/acme/one-checkout'); + const env = { GITHUB_ACTIONS: 'true', CI: 'true', ...(await jobServer('shared')), ...(await jobServer('trusted')) }; + const tested = await verb(job, 'test', env); + assert.match(tested, /lib:build: cache miss, executing/, 'the test built lib, into the local cache'); + const built = await verb(job, 'build', env); + assert.doesNotMatch(built, /cache hit/, 'nothing replayed'); + assert.match(built, /lib:build: cache miss, executing/); + assert.match(built, /site:build: cache miss, executing/); + assert.equal((await keys(TRUSTED_BUCKET, 'acme-one-checkout')).length, 2, 'both builds reached the trusted bucket'); + }); + + test('in a job where the tenant has no bucket, the step says so and every verb runs without a remote cache', async () => { const job = await clone(origin, 'bucketless-job', 'https://github.com/acme/web'); const plan = await step('plan', { CACHE: 'trusted', OWNER: 'acme', VAULT: 'acme-ci', SERVICE_ACCOUNT: 'false' }); assert.equal(plan.outputs.read, 'false'); - const told = await step('announce', { CACHE: 'trusted', KEYS: 'skipped' }); + const told = await step('announce', { CACHE: 'trusted', KEYS: 'skipped', SERVER: 'skipped' }); assert.deepEqual(told.env, { PLX_TURBO_TRUSTED: 'none' }); assert.match(told.said, /without the trusted remote cache/); - const built = await verb(job, 'build', { CI: 'true', PLX_TURBO_SHARED: '', ...told.env }); + const built = await verb(job, 'build', { GITHUB_ACTIONS: 'true', CI: 'true', PLX_TURBO_SHARED: '', ...told.env }); assert.match(built, /turbow: without a remote cache: the tenant has no trusted bucket/); assert.match(built, /build-ran site/); }); - test('in a CI job without the step, build fails and says why', async () => { + test('in a job without the step, build fails and says why', async () => { const job = await clone(origin, 'stepless-job', 'https://github.com/acme/web'); const ran = await tryRun('mise', ['run', 'build'], job, { + GITHUB_ACTIONS: 'true', CI: 'true', PLX_TURBO_SHARED: sharedUrl, PLX_TURBO_TRUSTED: '', }); assert.equal(ran.ok, false); - assert.match(ran.output, /in CI, build and e2e need the trusted cache server/); + assert.match(ran.output, /in a job of the forge, build and e2e need the trusted cache server/); assert.doesNotMatch(ran.output, /build-ran/); }); }); diff --git a/packages/lib/src/repoTurboCache.test.ts b/packages/lib/src/repoTurboCache.test.ts index f3c64f64..3ea22dc9 100644 --- a/packages/lib/src/repoTurboCache.test.ts +++ b/packages/lib/src/repoTurboCache.test.ts @@ -2,9 +2,10 @@ // Turbo through `turbow`, which the template renders beside `mise.toml`, and // which picks the cache server for each one. Here `turbow` is run as the tasks // run it, in a git checkout with an origin, with a stub `turbo` first on PATH -// that prints what it was handed, and with a health endpoint on a free loopback -// port standing in for a cache server; the newborn test (newborns/) runs it -// against a real server and an S3 stand-in. +// that prints every TURBO_ variable and argument it was handed, and with a +// health endpoint on a free loopback port standing in for a cache server; the +// newborn test (newborns/) runs it against a real server and an S3 stand-in. +// A job of the forge is GITHUB_ACTIONS=true; CI alone is any machine's. import assert from 'node:assert/strict'; import { execFile, execFileSync } from 'node:child_process'; import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; @@ -37,11 +38,19 @@ async function freePort(): Promise { before(async () => { scratch = mkdtempSync(join(tmpdir(), 'plx-turbow-')); turbow = textOf(await render(), 'turbow'); - // The stub prints what turbow hands to Turbo: the three variables, and the arguments. + // The stub prints what turbow hands to Turbo, every TURBO_ variable and each argument on a line, and exits + // with STUB_EXIT. mkdirSync(join(scratch, 'bin')); writeFileSync( join(scratch, 'bin', 'turbo'), - '#!/bin/sh\necho "turbo api=$TURBO_API team=$TURBO_TEAM token=$TURBO_TOKEN args=$*"\n', + [ + '#!/bin/sh', + 'echo turbo-ran', + "env | grep '^TURBO_' | sed 's/^/turbo-env /'", + 'for a in "$@"; do echo "turbo-arg $a"; done', + 'exit "$STUB_EXIT"', + '', + ].join('\n'), ); chmodSync(join(scratch, 'bin', 'turbo'), 0o755); server = createServer((req, res) => { @@ -72,27 +81,31 @@ function checkout(remote?: string): string { interface Ran { status: number | null; - /** What the stub turbo printed, or undefined when turbow never started it. */ - turbo?: { api: string; team: string; token: string; args: string }; + /** What the stub turbo was handed, or undefined when turbow never started it. */ + turbo?: { env: Record; args: string[] }; /** The lines turbow wrote itself. */ said: string[]; } +const ARGS = ['run', 'check', '--filter={./apps/web}...']; + /** * `./turbow run check --filter=…` in `dir`, as a task runs it, with * nothing of the caller's CI, Turbo or cache variables but `env`: a test run - * in CI must see what one on a laptop sees. + * in a job of the forge must see what one on a laptop sees. */ -async function turbowIn(dir: string, cache: string, env: Record = {}): Promise { +async function turbowIn(dir: string, cache: string, env: Record = {}, args = ARGS): Promise { const base = Object.fromEntries( - Object.entries(process.env).filter(([name]) => name !== 'CI' && !/^(TURBO_|PLX_TURBO_)/.test(name)), + Object.entries(process.env).filter( + ([name]) => name !== 'CI' && name !== 'GITHUB_ACTIONS' && !/^(TURBO_|PLX_TURBO_)/.test(name), + ), ); // Not spawnSync: the stand-in server answers from this process, whose loop must keep turning meanwhile. const ran = await new Promise<{ status: number | null; output: string }>((resolve) => { execFile( './turbow', - [cache, 'run', 'check', '--filter={./apps/web}...'], - { cwd: dir, env: { ...base, PATH: `${join(scratch, 'bin')}:${process.env.PATH}`, ...env } }, + [cache, ...args], + { cwd: dir, env: { ...base, STUB_EXIT: '0', PATH: `${join(scratch, 'bin')}:${process.env.PATH}`, ...env } }, (error, stdout, stderr) => resolve({ status: error ? (typeof error.code === 'number' ? error.code : 1) : 0, @@ -101,16 +114,38 @@ async function turbowIn(dir: string, cache: string, env: Record ); }); const lines = ran.output.split('\n').filter(Boolean); - const printed = lines.find((line) => line.startsWith('turbo api=')); - const m = printed && /^turbo api=(.*) team=(.*) token=(.*) args=(.*)$/.exec(printed); - return { - status: ran.status, - turbo: m ? { api: m[1] ?? '', team: m[2] ?? '', token: m[3] ?? '', args: m[4] ?? '' } : undefined, - said: lines.filter((line) => line !== printed), - }; + const ours = (line: string) => /^turbo-(ran|env|arg)\b/.test(line); + const turbo = lines.includes('turbo-ran') + ? { + env: Object.fromEntries( + lines + .filter((line) => line.startsWith('turbo-env ')) + .map((line) => line.slice('turbo-env '.length)) + .map((pair) => [pair.slice(0, pair.indexOf('=')), pair.slice(pair.indexOf('=') + 1)]), + ), + args: lines.filter((line) => line.startsWith('turbo-arg ')).map((line) => line.slice('turbo-arg '.length)), + } + : undefined; + return { status: ran.status, turbo, said: lines.filter((line) => !ours(line)) }; } const REMOTE = 'git@github.com:acme/web.git'; +/** What Turbo gets where it runs without a remote cache: no server, no team, no token, and the local cache alone. */ +const UNCACHED = { TURBO_API: '', TURBO_TEAM: '', TURBO_TOKEN: '', TURBO_CACHE: 'local:rw' }; +/** What a caller's shell or a machine may hold that would send artifacts elsewhere, or otherwise, than turbow says. */ +const STRAY = { + TURBO_API: 'https://example.invalid', + TURBO_TEAM: 'someone', + TURBO_TEAMID: 'team_someone', + TURBO_TOKEN: 'secret', + TURBO_CACHE: 'remote:r', + TURBO_REMOTE_CACHE_SIGNATURE_KEY: 'a-key', + TURBO_REMOTE_CACHE_READ_ONLY: 'true', + TURBO_PREFLIGHT: 'true', + TURBO_REMOTE_ONLY: 'true', +}; +/** A job of the forge, which sets both. */ +const JOB = { GITHUB_ACTIONS: 'true', CI: 'true' }; test('turbow is rendered in every repo, executable, beside mise.toml', async () => { for (const answers of SHAPES) { @@ -143,77 +178,93 @@ test('check and test reach Turbo through the shared cache, build and e2e through } }); -test('outside CI the shared server is the one on the fixed port, unless PLX_TURBO_SHARED names another', async () => { +test('outside a job the shared server is the one on the fixed port, unless PLX_TURBO_SHARED names another', async () => { assert.match(turbow, /\$\{PLX_TURBO_SHARED:-http:\/\/127\.0\.0\.1:8585\}/); }); -test('outside CI, with the shared server answering, every verb uses it, as the repo’s owner-repo', async () => { +test('outside a job, CI set or not, with the shared server answering, every verb uses it, as the repo’s owner-repo, and nothing else reaches Turbo', async () => { const dir = checkout(REMOTE); - for (const cache of ['shared', 'trusted']) { - const ran = await turbowIn(dir, cache, { PLX_TURBO_SHARED: answering }); - assert.equal(ran.status, 0, ran.said.join('\n')); - assert.equal(ran.turbo?.api, answering, cache); - assert.equal(ran.turbo?.team, 'acme-web'); - assert.notEqual(ran.turbo?.token, '', 'Turbo sends no request without a token, though the server asks for none'); - assert.equal(ran.turbo?.args, 'run check --filter={./apps/web}...'); - assert.equal(ran.said.length, 1, ran.said.join('\n')); - assert.match(ran.said[0] ?? '', new RegExp(`shared remote cache at ${answering.replaceAll('.', '\\.')}`)); - } + for (const ci of [{}, { CI: 'true' }]) + for (const cache of ['shared', 'trusted']) { + const ran = await turbowIn(dir, cache, { ...STRAY, ...ci, PLX_TURBO_SHARED: answering }); + assert.equal(ran.status, 0, ran.said.join('\n')); + assert.deepEqual(ran.turbo?.env, { + TURBO_API: answering, + TURBO_TEAM: 'acme-web', + TURBO_TOKEN: 'local', + TURBO_CACHE: 'local:rw,remote:rw', + }); + assert.deepEqual(ran.turbo?.args, ARGS); + assert.equal(ran.said.length, 1, ran.said.join('\n')); + assert.match(ran.said[0] ?? '', new RegExp(`shared remote cache at ${answering.replaceAll('.', '\\.')}`)); + } }); -test('outside CI, with no server answering, every verb runs without a remote cache and says so in one line', async () => { +test('outside a job, with no server answering, every verb runs without a remote cache, tells Turbo so, and says so in one line', async () => { const dir = checkout(REMOTE); for (const shared of [silent, 'none']) for (const cache of ['shared', 'trusted']) { - // What the caller's shell may hold: without TURBO_API, Turbo would send the team and token to Vercel. - const ran = await turbowIn(dir, cache, { - PLX_TURBO_SHARED: shared, - TURBO_API: 'https://example.invalid', - TURBO_TEAM: 'someone', - TURBO_TOKEN: 'secret', - }); + const ran = await turbowIn(dir, cache, { ...STRAY, PLX_TURBO_SHARED: shared }); assert.equal(ran.status, 0, ran.said.join('\n')); - assert.deepEqual(ran.turbo, { api: '', team: '', token: '', args: 'run check --filter={./apps/web}...' }); + assert.deepEqual(ran.turbo?.env, UNCACHED); assert.equal(ran.said.length, 1, ran.said.join('\n')); assert.match(ran.said[0] ?? '', /without a remote cache/); } }); -test('in CI, build and e2e reach the trusted server the job started, and check and test the shared one, never the other', async () => { +test('in a job, build and e2e reach the trusted server the job started, with the remote cache alone, and check and test the shared one', async () => { const dir = checkout('https://github.com/acme/web'); - const ci = { - CI: 'true', + const job = { + ...STRAY, + ...JOB, PLX_TURBO_SHARED: silent, PLX_TURBO_SHARED_TOKEN: 'shared-job-token', PLX_TURBO_TRUSTED: answering, PLX_TURBO_TRUSTED_TOKEN: 'trusted-job-token', }; - const trusted = await turbowIn(dir, 'trusted', ci); + const trusted = await turbowIn(dir, 'trusted', job); assert.equal(trusted.status, 0, trusted.said.join('\n')); - assert.deepEqual(trusted.turbo, { - api: answering, - team: 'acme-web', - token: 'trusted-job-token', - args: 'run check --filter={./apps/web}...', + // The local cache may hold what a shared run restored in this checkout; a trusted run never reads it. + assert.deepEqual(trusted.turbo?.env, { + TURBO_API: answering, + TURBO_TEAM: 'acme-web', + TURBO_TOKEN: 'trusted-job-token', + TURBO_CACHE: 'remote:rw', }); - const shared = await turbowIn(dir, 'shared', ci); - assert.equal(shared.turbo?.api, silent); - assert.equal(shared.turbo?.token, 'shared-job-token'); - // A job with the trusted server alone, as the e2e job is: check and test find no shared server there. - const alone = await turbowIn(dir, 'shared', { - CI: 'true', - PLX_TURBO_TRUSTED: answering, - PLX_TURBO_TRUSTED_TOKEN: 't', + const shared = await turbowIn(dir, 'shared', job); + assert.deepEqual(shared.turbo?.env, { + TURBO_API: silent, + TURBO_TEAM: 'acme-web', + TURBO_TOKEN: 'shared-job-token', + TURBO_CACHE: 'local:rw,remote:rw', }); + // A job with the trusted server alone, as the e2e job is: check and test find no shared server there. + const alone = await turbowIn(dir, 'shared', { ...JOB, PLX_TURBO_TRUSTED: answering, PLX_TURBO_TRUSTED_TOKEN: 't' }); assert.equal(alone.status, 0, alone.said.join('\n')); - assert.deepEqual(alone.turbo, { api: '', team: '', token: '', args: 'run check --filter={./apps/web}...' }); + assert.deepEqual(alone.turbo?.env, UNCACHED); assert.match(alone.said.join('\n'), /without a remote cache/); }); -test('in CI without the trusted server, build and e2e fail and say why; they never fall back to the shared one', async () => { +test('TURBO_FORCE stays what it was, a run that reads no cache and writes the caches it has', async () => { + const dir = checkout(REMOTE); + const force = { TURBO_FORCE: 'true' }; + assert.equal( + (await turbowIn(dir, 'shared', { ...force, PLX_TURBO_SHARED: answering })).turbo?.env.TURBO_CACHE, + 'local:w,remote:w', + ); + assert.equal( + (await turbowIn(dir, 'shared', { ...force, PLX_TURBO_SHARED: 'none' })).turbo?.env.TURBO_CACHE, + 'local:w', + ); + const trusted = await turbowIn(dir, 'trusted', { ...force, ...JOB, PLX_TURBO_TRUSTED: answering }); + assert.equal(trusted.turbo?.env.TURBO_CACHE, 'remote:w'); + assert.equal(trusted.turbo?.env.TURBO_FORCE, undefined, 'the cache setting says it all'); +}); + +test('in a job without the trusted server, build and e2e fail and say why; they never fall back to the shared one', async () => { const dir = checkout(REMOTE); for (const env of [{ PLX_TURBO_SHARED: answering, PLX_TURBO_SHARED_TOKEN: 't' }, {}]) { - const ran = await turbowIn(dir, 'trusted', { CI: 'true', ...env }); + const ran = await turbowIn(dir, 'trusted', { ...JOB, ...env }); assert.notEqual(ran.status, 0); assert.equal(ran.turbo, undefined, 'Turbo never ran'); assert.match(ran.said.join('\n'), /trusted cache server/); @@ -221,17 +272,34 @@ test('in CI without the trusted server, build and e2e fail and say why; they nev } }); -test('in CI where the tenant has no bucket, every verb runs without a remote cache and says so in one line', async () => { +test('CI alone is no job: build and e2e on a machine with CI=true use the shared server, and fail for want of none', async () => { + const dir = checkout(REMOTE); + for (const ci of ['true', '1', 'yes']) { + const ran = await turbowIn(dir, 'trusted', { CI: ci, PLX_TURBO_SHARED: answering }); + assert.equal(ran.status, 0, ran.said.join('\n')); + assert.equal(ran.turbo?.env.TURBO_API, answering, ci); + } +}); + +test('in a job where the tenant has no bucket, every verb runs without a remote cache and says so in one line', async () => { const dir = checkout(REMOTE); for (const cache of ['shared', 'trusted']) { - const ran = await turbowIn(dir, cache, { CI: 'true', PLX_TURBO_SHARED: 'none', PLX_TURBO_TRUSTED: 'none' }); + const ran = await turbowIn(dir, cache, { ...JOB, PLX_TURBO_SHARED: 'none', PLX_TURBO_TRUSTED: 'none' }); assert.equal(ran.status, 0, ran.said.join('\n')); - assert.deepEqual(ran.turbo, { api: '', team: '', token: '', args: 'run check --filter={./apps/web}...' }); + assert.deepEqual(ran.turbo?.env, UNCACHED); assert.equal(ran.said.length, 1, ran.said.join('\n')); assert.match(ran.said[0] ?? '', /without a remote cache/); } }); +test('turbow exits with Turbo’s status and hands it every argument as it was given', async () => { + const dir = checkout(REMOTE); + const failed = await turbowIn(dir, 'shared', { PLX_TURBO_SHARED: answering, STUB_EXIT: '3' }); + assert.equal(failed.status, 3); + const args = ['run', 'check', '--filter=a b', '', '--summarize=two spaces']; + assert.deepEqual((await turbowIn(dir, 'shared', { PLX_TURBO_SHARED: 'none' }, args)).turbo?.args, args); +}); + test('the team is owner-repo of origin, the same from SSH and HTTPS remotes and from any directory', async () => { for (const remote of [ 'git@github.com:acme/web.git', @@ -240,18 +308,42 @@ test('the team is owner-repo of origin, the same from SSH and HTTPS remotes and 'https://github.com/acme/web.git', 'https://github.com/acme/web/', 'ssh://git@github.com/acme/web.git', + 'HTTPS://GITHUB.COM/ACME/WEB.GIT', + 'ssh://git@github.com:2222/acme/web', + 'https://user:token@github.com/acme/web.git', ]) { const ran = await turbowIn(checkout(remote), 'shared', { PLX_TURBO_SHARED: answering }); - assert.equal(ran.turbo?.team, 'acme-web', remote); + assert.equal(ran.turbo?.env.TURBO_TEAM, 'acme-web', remote); } }); -test('a checkout without origin has no team, and runs without a remote cache', async () => { - const ran = await turbowIn(checkout(), 'shared', { PLX_TURBO_SHARED: answering }); - assert.equal(ran.status, 0, ran.said.join('\n')); - assert.deepEqual(ran.turbo, { api: '', team: '', token: '', args: 'run check --filter={./apps/web}...' }); - assert.equal(ran.said.length, 1, ran.said.join('\n')); - assert.match(ran.said[0] ?? '', /without a remote cache.*origin/); +test('the team holds only [a-z0-9._-], every other character a dash, and a nested group keeps its last two names', async () => { + for (const [remote, team] of [ + ['https://git.example.com/Group/Sub%20Group/re po.git', 'sub-20group-re-po'], + ['https://git.example.com/o/r#x?y.git', 'o-r-x-y'], + ['https://git.example.com/ä/ü.git', 'o-r'], + ['https://git.example.com/group/sub/repo.git', 'sub-repo'], + ['git@git.example.com:acme/web.v2_x.git', 'acme-web.v2_x'], + ] as const) { + const ran = await turbowIn(checkout(remote), 'shared', { PLX_TURBO_SHARED: answering }); + if (team === 'o-r') assert.match(ran.turbo?.env.TURBO_TEAM ?? '', /^-+--+$/, remote); + else assert.equal(ran.turbo?.env.TURBO_TEAM, team, remote); + } +}); + +test('a checkout without origin, or whose origin names no owner, has no team, and runs without a remote cache', async () => { + for (const [remote, why] of [ + [undefined, /origin/], + ['git@git.example.com:repo.git', /owner/], + ['https://git.example.com/repo.git', /owner/], + ] as const) { + const ran = await turbowIn(checkout(remote), 'shared', { PLX_TURBO_SHARED: answering }); + assert.equal(ran.status, 0, ran.said.join('\n')); + assert.deepEqual(ran.turbo?.env, UNCACHED, String(remote)); + assert.equal(ran.said.length, 1, ran.said.join('\n')); + assert.match(ran.said[0] ?? '', /without a remote cache/); + assert.match(ran.said[0] ?? '', why); + } }); // Where a job gets its cache server: the step turbo-cache of this repo, which _check.yml starts for every repo. diff --git a/packages/lib/src/turboCacheStep.test.ts b/packages/lib/src/turboCacheStep.test.ts new file mode 100644 index 00000000..26dd4b8b --- /dev/null +++ b/packages/lib/src/turboCacheStep.test.ts @@ -0,0 +1,129 @@ +// The step turbo-cache of this repo (.github/actions/turbo-cache), as a job +// runs it: its script's phases with GITHUB_OUTPUT and GITHUB_ENV as files of +// their own, and the wiring of its action.yml, which no machine but a runner +// of the forge runs. The newborn test (newborns/turbo-cache.test.ts) runs the +// phases around a real server. +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { after, before, test } from 'node:test'; +import { parse } from 'yaml'; + +const STEP = join(import.meta.dirname, '..', '..', '..', '.github', 'actions', 'turbo-cache'); +const CACHES = [ + { cache: 'shared', variable: 'PLX_TURBO_SHARED', item: 'bucket-turbo', bucket: 'acme-ci-turbo' }, + { cache: 'trusted', variable: 'PLX_TURBO_TRUSTED', item: 'bucket-turbo-trusted', bucket: 'acme-ci-turbo-trusted' }, +]; + +let scratch = ''; +before(() => { + scratch = mkdtempSync(join(tmpdir(), 'plx-turbo-cache-step-')); +}); +after(() => rmSync(scratch, { recursive: true, force: true })); + +/** `KEY=value` lines of a runner's file. */ +const pairs = (text: string): Record => + Object.fromEntries( + text + .split('\n') + .filter((line) => line.includes('=')) + .map((line) => [line.slice(0, line.indexOf('=')), line.slice(line.indexOf('=') + 1)]), + ); + +let runs = 0; +/** One phase of the script, with nothing of the vault's credentials but `env`. */ +function phase(name: string, env: Record) { + const n = runs++; + const output = join(scratch, `output-${n}`); + const githubEnv = join(scratch, `env-${n}`); + writeFileSync(output, ''); + writeFileSync(githubEnv, ''); + const base = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(OP_|GITHUB_|PLX_)/.test(key))); + const ran = spawnSync('bash', [join(STEP, 'turbo-cache.sh'), name], { + encoding: 'utf8', + env: { ...base, GITHUB_OUTPUT: output, GITHUB_ENV: githubEnv, ...env }, + }); + assert.equal(ran.status, 0, ran.stderr); + return { + stdout: ran.stdout, + outputs: pairs(readFileSync(output, 'utf8')), + env: pairs(readFileSync(githubEnv, 'utf8')), + }; +} + +const plan = (cache: string) => + phase('plan', { CACHE: cache, OWNER: 'acme', VAULT: 'acme-ci', SERVICE_ACCOUNT: 'true' }); +const announce = (cache: string, keys: string, server = keys === 'success' ? 'success' : 'skipped') => + phase('announce', { CACHE: cache, KEYS: keys, SERVER: server, VAULT: 'acme-ci', PORT: '8585', TOKEN: 'job-token' }); + +test('plan names the vault item and the bucket of each cache', () => { + for (const { cache, item, bucket } of CACHES) { + const planned = plan(cache).outputs; + assert.equal(planned.item, item, cache); + assert.equal(planned.bucket, bucket, cache); + assert.equal(planned.vault, 'acme-ci'); + } +}); + +test('plan masks the job’s token before anything prints it, and announce never prints it', () => { + const planned = plan('trusted'); + const token = planned.outputs.token ?? ''; + assert.match(token, /^[0-9a-f]{64}$/); + const lines = planned.stdout.split('\n'); + assert.equal(lines[0], `::add-mask::${token}`); + assert.ok(!lines.slice(1).join('\n').includes(token), 'the token is printed once, in the mask command'); + const told = phase('announce', { CACHE: 'trusted', KEYS: 'success', SERVER: 'success', PORT: '8585', TOKEN: token }); + assert.ok(!told.stdout.includes(token)); +}); + +test('announce tells turbow of the cache it was asked for, and never of the other', () => { + for (const { cache, variable } of CACHES) { + assert.deepEqual(announce(cache, 'success').env, { + [variable]: 'http://127.0.0.1:8585', + [`${variable}_TOKEN`]: 'job-token', + }); + for (const [keys, server] of [ + ['skipped', 'skipped'], + ['failure', 'skipped'], + ['success', 'failure'], + ]) + assert.deepEqual(announce(cache, keys, server).env, { [variable]: 'none' }, `${cache} ${keys} ${server}`); + } +}); + +test('a job without the remote cache it asked for gets one warning on the run, naming the cause; a job with its server none', () => { + for (const { cache, item } of CACHES) { + const warnings = (stdout: string) => stdout.split('\n').filter((line) => line.startsWith('::warning ')); + for (const [keys, server, cause] of [ + ['skipped', 'skipped', /no vault/], + ['failure', 'skipped', new RegExp(`${item}\\b.*the vault acme-ci`)], + ['success', 'failure', /did not come up/], + ] as const) { + const said = warnings(announce(cache, keys, server).stdout); + assert.equal(said.length, 1, `${cache} ${keys} ${server}: ${said.join('\n')}`); + assert.match(said[0] ?? '', new RegExp(`^::warning title=Turbo runs without the ${cache} remote cache::`)); + assert.match(said[0] ?? '', cause); + } + assert.deepEqual(warnings(announce(cache, 'success').stdout), [], cache); + } +}); + +/** The steps of action.yml, by id. */ +function steps(): Record; 'continue-on-error'?: boolean; uses?: string }> { + const action = parse(readFileSync(join(STEP, 'action.yml'), 'utf8')); + return Object.fromEntries(action.runs.steps.map((step: { id?: string }) => [step.id, step])); +} + +test('the server binds loopback whatever the job’s environment holds', () => { + const server = steps().server; + assert.match(server?.uses ?? '', /^brunojppb\/turbo-cache-server@[0-9a-f]{40} /); + assert.equal(server?.env?.HOST, '127.0.0.1'); +}); + +test('a server that does not come up fails no job: announce hears of it', () => { + const { server, announce } = steps(); + assert.equal(server?.['continue-on-error'], true); + assert.match(announce?.env?.SERVER ?? '', /^\$\{\{ steps\.server\.outcome \}\}$/); +}); From 8dc9b459fc6b568baa75ffd3b9337096b37fcc5b Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 19:04:24 +0100 Subject: [PATCH 097/194] turbow: none is none, a trusted verb reads no local cache, a job is the forge's, the team is safe Without a remote cache Turbo is told so: an empty server, team and token, and TURBO_CACHE=local:rw, so that a login and a linked repo send nothing. A trusted verb with its server runs with TURBO_CACHE=remote:rw. Every remote-cache variable of the caller is unset, and TURBO_FORCE is turned into the same setting without reads. A job is GITHUB_ACTIONS=true; CI alone no longer picks the cache. The team is the last two names of origin's path, lower case, without .git, every other character a dash; an origin without an owner runs uncached and says why. Co-Authored-By: Claude Fable 5.2 --- templates/repo-turbo/files/turbow | 90 +++++++++++++++++++------------ 1 file changed, 55 insertions(+), 35 deletions(-) diff --git a/templates/repo-turbo/files/turbow b/templates/repo-turbo/files/turbow index df6280ff..349fc62e 100755 --- a/templates/repo-turbo/files/turbow +++ b/templates/repo-turbo/files/turbow @@ -12,48 +12,62 @@ case $cache in ;; esac -# Turbo sends a team and a token to Vercel when TURBO_API is unset, so the three are set together or not at all. -unset TURBO_API TURBO_TEAM TURBO_TOKEN +# Where and how artifacts go is turbow's alone: no remote-cache setting of the caller's shell reaches Turbo, and no +# artifact is signed. TURBO_FORCE keeps its meaning, a run that reads no cache and writes those it has. +read=r +if [ "${TURBO_FORCE:-}" = true ]; then read=; fi +unset TURBO_API TURBO_TEAM TURBO_TEAMID TURBO_TOKEN TURBO_CACHE TURBO_FORCE TURBO_REMOTE_CACHE_SIGNATURE_KEY \ + TURBO_REMOTE_CACHE_READ_ONLY TURBO_PREFLIGHT TURBO_REMOTE_ONLY reason= -# Outside CI no machine holds the trusted keys: every verb uses the shared server, by default this machine's own, run -# without a token. In CI a verb uses only the server its job started (.github/actions/turbo-cache of plexus-ms/tooling), -# with the job's token, and build and e2e never use the shared one. A server named none is a tenant without the bucket. -case ${CI:-} in - '' | false | 0) - from=shared server=${PLX_TURBO_SHARED:-http://127.0.0.1:8585} token=${PLX_TURBO_SHARED_TOKEN:-local} - if [ "$server" != none ] && ! node -e ' - fetch(process.argv[1], { signal: AbortSignal.timeout(2000) }).then( - (answer) => process.exit(answer.ok ? 0 : 1), - () => process.exit(1), - );' "$server/management/health"; then - reason="nothing answers at $server" - fi - ;; - *) - if [ "$cache" = trusted ]; then - if [ -z "${PLX_TURBO_TRUSTED:-}" ]; then - echo "turbow: in CI, build and e2e need the trusted cache server, and this job started none (PLX_TURBO_TRUSTED is unset); they never use the shared one" >&2 - exit 1 - fi - from=trusted server=$PLX_TURBO_TRUSTED token=${PLX_TURBO_TRUSTED_TOKEN:-local} - else - from=shared server=${PLX_TURBO_SHARED:-} token=${PLX_TURBO_SHARED_TOKEN:-local} - [ -n "$server" ] || reason="this job started no shared cache server (PLX_TURBO_SHARED is unset)" - fi - ;; -esac +# Outside a job of the forge no machine holds the trusted keys: every verb uses the shared server, by default this +# machine's own, run without a token. In a job (GITHUB_ACTIONS=true, which the forge's runner sets and CI alone does not) +# a verb uses only the server its job started (.github/actions/turbo-cache of plexus-ms/tooling), with the job's token, +# and build and e2e never use the shared one. A server named none is a tenant without the bucket. +if [ "${GITHUB_ACTIONS:-}" != true ]; then + from=shared server=${PLX_TURBO_SHARED:-http://127.0.0.1:8585} token=${PLX_TURBO_SHARED_TOKEN:-local} + if [ "$server" != none ] && ! node -e ' + fetch(process.argv[1], { signal: AbortSignal.timeout(2000) }).then( + (answer) => process.exit(answer.ok ? 0 : 1), + () => process.exit(1), + );' "$server/management/health"; then + reason="nothing answers at $server" + fi +elif [ "$cache" = trusted ]; then + if [ -z "${PLX_TURBO_TRUSTED:-}" ]; then + echo "turbow: in a job of the forge, build and e2e need the trusted cache server, and this job started none (PLX_TURBO_TRUSTED is unset); they never use the shared one" >&2 + exit 1 + fi + from=trusted server=$PLX_TURBO_TRUSTED token=${PLX_TURBO_TRUSTED_TOKEN:-local} +else + from=shared server=${PLX_TURBO_SHARED:-} token=${PLX_TURBO_SHARED_TOKEN:-local} + [ -n "$server" ] || reason="this job started no shared cache server (PLX_TURBO_SHARED is unset)" +fi if [ "$server" = none ]; then reason="the tenant has no $from bucket" fi -# The team keeps the repos of a tenant apart in a bucket: owner-repo, from the URL of origin, in lower case. +# The team keeps the repos of a tenant apart in a bucket: owner-repo, the last two names of the path of origin's URL +# (a nested group keeps its last two), in lower case, without .git, every character but [a-z0-9._-] a dash. if [ -z "$reason" ]; then if url=$(git remote get-url origin 2>/dev/null); then - path=${url%/} + path=$(printf '%s' "$url" | LC_ALL=C tr '[:upper:]' '[:lower:]') + case $path in + *://*) + path=${path#*://} + path=${path#*/} + ;; + *) case ${path%%/*} in *:*) path=${path#*:} ;; esac ;; + esac + path=${path%/} path=${path%.git} - rest=${path%/*} - team=$(printf '%s-%s' "${rest##*[/:]}" "${path##*/}" | tr '[:upper:]' '[:lower:]') + case $path in + */*) + rest=${path%/*} + team=$(printf '%s-%s' "${rest##*/}" "${path##*/}" | LC_ALL=C sed 's/[^a-z0-9._-]/-/g') + ;; + *) reason="origin's URL names no owner to name the team with ($url)" ;; + esac else reason="the checkout has no origin to name its team" fi @@ -61,8 +75,14 @@ fi if [ -n "$reason" ]; then echo "turbow: without a remote cache: $reason" >&2 + # Told to Turbo too: a login and a linked repo would otherwise send the artifacts there. + export TURBO_API='' TURBO_TEAM='' TURBO_TOKEN='' TURBO_CACHE="local:${read}w" +elif [ "$from" = trusted ]; then + echo "turbow: the trusted remote cache at $server, team $team" >&2 + # Never the local cache, which a shared run of this checkout may have filled from the shared bucket. + export TURBO_API="$server" TURBO_TEAM="$team" TURBO_TOKEN="$token" TURBO_CACHE="remote:${read}w" else - echo "turbow: the $from remote cache at $server, team $team" >&2 - export TURBO_API="$server" TURBO_TEAM="$team" TURBO_TOKEN="$token" + echo "turbow: the shared remote cache at $server, team $team" >&2 + export TURBO_API="$server" TURBO_TEAM="$team" TURBO_TOKEN="$token" TURBO_CACHE="local:${read}w,remote:${read}w" fi exec turbo "$@" From 1dd28d0e689e3c297ac353a4194cab452a3221c1 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 19:07:03 +0100 Subject: [PATCH 098/194] the step turbo-cache: a server bound to 127.0.0.1, and a warning on the run where a job goes without its cache The server's start sets HOST=127.0.0.1, which the server binds (read in its src/app_settings.rs at the pinned commit), so that no HOST of the job widens it. No job fails over its cache: a server that does not come up is continue-on-error, and announce, told of it, writes none. Each cause of a job without the remote cache it asked for (no vault, an item it could not read, a server that did not come up) is one line of the log and one ::warning:: on the run. The header says that a server that cannot use its bucket is not probed. Tests: the start step's uses has no trailing comment once parsed; a task's miss is matched in Turbo's own grouping of a job's log, and the control of the linked-repo test runs after the verbs have installed Turbo. Co-Authored-By: Claude Fable 5.2 --- .github/actions/turbo-cache/action.yml | 26 +++++++++++---- .github/actions/turbo-cache/turbo-cache.sh | 39 +++++++++++----------- newborns/turbo-cache.test.ts | 18 +++++----- packages/lib/src/turboCacheStep.test.ts | 2 +- 4 files changed, 50 insertions(+), 35 deletions(-) diff --git a/.github/actions/turbo-cache/action.yml b/.github/actions/turbo-cache/action.yml index d21b9986..2d0ebed8 100644 --- a/.github/actions/turbo-cache/action.yml +++ b/.github/actions/turbo-cache/action.yml @@ -17,13 +17,19 @@ description: >- # bucket-turbo the shared bucket -ci-turbo # bucket-turbo-trusted the trusted bucket -ci-turbo-trusted # -# The server is brunojppb/turbo-cache-server, path-style against the bucket, -# with a token minted for the job and on the first free port from 8585 up -# (turbo-cache.sh says why). A job without vault credentials, or whose vault -# has no such item, runs without that remote cache and says so in one line: -# a tenant without the bucket. The keys go to the server alone and never to -# the job's environment; what the job's later steps get is the server's -# address and token, in the variables turbow reads. +# The server is brunojppb/turbo-cache-server, bound to 127.0.0.1 whatever the +# job's environment holds (its HOST), path-style against the bucket, with a +# token minted for the job and on the first free port from 8585 up +# (turbo-cache.sh says why). The keys go to the server alone and never to the +# job's environment; what the job's later steps get is the server's address +# and token, in the variables turbow reads. +# +# No job fails over its cache. A job without vault credentials, whose vault +# item could not be read, or whose server did not come up, runs without that +# remote cache, and says why in one line of the log and in one warning on the +# run; a tenant without the bucket on purpose gets the same warning. A server +# that comes up and cannot use its bucket is not probed: Turbo's own warning +# in the job's log says so. inputs: cache: @@ -64,10 +70,14 @@ runs: REGION: op://${{ steps.plan.outputs.vault }}/${{ steps.plan.outputs.item }}/region ACCESS_KEY: op://${{ steps.plan.outputs.vault }}/${{ steps.plan.outputs.item }}/access-key-id SECRET_KEY: op://${{ steps.plan.outputs.vault }}/${{ steps.plan.outputs.item }}/secret-access-key + # A server that does not come up fails no job: announce says so. - name: Start the cache server + id: server if: ${{ steps.keys.outcome == 'success' }} + continue-on-error: true uses: brunojppb/turbo-cache-server@7d5eed8f1768a2209c88b2af58da1827b47eedcc # 5.0.4 env: + HOST: 127.0.0.1 PORT: ${{ steps.plan.outputs.port }} TURBO_TOKEN: ${{ steps.plan.outputs.token }} S3_ENDPOINT: ${{ steps.keys.outputs.ENDPOINT }} @@ -77,10 +87,12 @@ runs: S3_SECRET_KEY: ${{ steps.keys.outputs.SECRET_KEY }} S3_USE_PATH_STYLE: 'true' - name: Tell turbow where the server is + id: announce shell: bash env: CACHE: ${{ inputs.cache }} KEYS: ${{ steps.keys.outcome || 'skipped' }} + SERVER: ${{ steps.server.outcome }} VAULT: ${{ steps.plan.outputs.vault }} PORT: ${{ steps.plan.outputs.port }} TOKEN: ${{ steps.plan.outputs.token }} diff --git a/.github/actions/turbo-cache/turbo-cache.sh b/.github/actions/turbo-cache/turbo-cache.sh index a300fb11..b8eab0b6 100755 --- a/.github/actions/turbo-cache/turbo-cache.sh +++ b/.github/actions/turbo-cache/turbo-cache.sh @@ -18,10 +18,12 @@ # environment: PLX_TURBO_SHARED or PLX_TURBO_TRUSTED with the # server's address and PLX_TURBO__TOKEN with the job's token # when the keys were read (KEYS, the outcome of the read: `success`) -# and the server started on PORT with TOKEN; else the variable is -# `none`, and the step says in one line why the job runs without -# that remote cache: no vault to read (`skipped`), or no item in it -# that could be read (`failure`, the step above says why). +# and the server came up (SERVER, the outcome of its start) on PORT +# with TOKEN; else the variable is `none`, and the step says why the +# job runs without that remote cache, in one line of the log and in +# one warning on the run: no vault to read (`skipped`), an item it +# could not read (`failure`, the step above says why), or a server +# that did not come up. No job fails over its cache. # # Run by hand, a phase needs only GITHUB_OUTPUT and GITHUB_ENV to name files. set -euo pipefail @@ -56,23 +58,22 @@ case ${1:-} in } >>"$GITHUB_OUTPUT" ;; announce) + if [ "${KEYS:-}" = success ] && [ "${SERVER:-}" = success ]; then + { + echo "$var=http://127.0.0.1:${PORT:?}" + echo "${var}_TOKEN=${TOKEN:?}" + } >>"$GITHUB_ENV" + echo "The $CACHE remote cache: a server on 127.0.0.1:$PORT." + exit 0 + fi case ${KEYS:-} in - success) - { - echo "$var=http://127.0.0.1:${PORT:?}" - echo "${var}_TOKEN=${TOKEN:?}" - } >>"$GITHUB_ENV" - echo "The $CACHE remote cache: a server on 127.0.0.1:$PORT." - ;; - skipped) - echo "$var=none" >>"$GITHUB_ENV" - echo "Turbo runs without the $CACHE remote cache: this job has no vault to read its keys from." - ;; - *) - echo "$var=none" >>"$GITHUB_ENV" - echo "Turbo runs without the $CACHE remote cache: the vault ${VAULT:-} has no item $item that could be read (the step above says why)." - ;; + skipped) cause="This job has no vault to read the item $item from." ;; + success) cause="The cache server did not come up on 127.0.0.1:${PORT:-} (the step above says why)." ;; + *) cause="The step could not read the item $item from the vault ${VAULT:-} (the step above says why)." ;; esac + echo "$var=none" >>"$GITHUB_ENV" + echo "Turbo runs without the $CACHE remote cache: $cause" + echo "::warning title=Turbo runs without the $CACHE remote cache::$cause" ;; *) echo "usage: turbo-cache.sh plan|announce" >&2 diff --git a/newborns/turbo-cache.test.ts b/newborns/turbo-cache.test.ts index 1af30299..6a581053 100644 --- a/newborns/turbo-cache.test.ts +++ b/newborns/turbo-cache.test.ts @@ -264,6 +264,9 @@ describe('a newborn app repo with the two remote caches', () => { return told.env; } + /** A task's miss as Turbo prints it, in a job of the forge as a group of the log. */ + const missed = (task: string) => new RegExp(`(?:${task}: |::group::${task}\\n)cache miss, executing`); + /** A developer's machine: no job of the forge, though CI may be set there too. */ const machine = () => ({ GITHUB_ACTIONS: '', CI: 'true', PLX_TURBO_SHARED: sharedUrl, PLX_TURBO_TRUSTED: '' }); @@ -302,17 +305,16 @@ describe('a newborn app repo with the two remote caches', () => { put(linked, { '.turbo/config.json': { apiUrl: `http://127.0.0.1:${port}`, teamSlug: 'linked' } }); put(here, { 'turbo-login/turborepo/config.json': { token: 'a-login-token' } }); const env = { ...machine(), PLX_TURBO_SHARED: 'none', TURBO_CONFIG_DIR_PATH: join(here, 'turbo-login') }; - // The control: Turbo alone sends the linked team's artifacts with the login token. - const alone = await tryRun('mise', ['exec', '--', 'turbo', 'run', 'check', '--force'], linked, env); - assert.ok(alone.ok, alone.output); - assert.ok(hits > 0, 'Turbo alone reaches the linked server'); - hits = 0; for (const task of ['check', 'test', 'build', 'e2e']) { const ran = await verb(linked, task, env); assert.match(ran, /turbow: without a remote cache/, task); assert.match(ran, /Remote caching disabled/, task); } assert.equal(hits, 0, 'no request reached the linked server'); + // The control: Turbo alone sends the linked team's artifacts with the login token. + const alone = await tryRun('mise', ['exec', '--', 'turbo', 'run', 'check', '--force'], linked, env); + assert.ok(alone.ok, alone.output); + assert.ok(hits > 0, 'Turbo alone reaches the linked server'); } finally { await new Promise((resolve) => listener.close(() => resolve())); } @@ -337,11 +339,11 @@ describe('a newborn app repo with the two remote caches', () => { const job = await clone(origin, 'one-checkout', 'https://github.com/acme/one-checkout'); const env = { GITHUB_ACTIONS: 'true', CI: 'true', ...(await jobServer('shared')), ...(await jobServer('trusted')) }; const tested = await verb(job, 'test', env); - assert.match(tested, /lib:build: cache miss, executing/, 'the test built lib, into the local cache'); + assert.match(tested, missed('lib:build'), 'the test built lib, into the local cache'); const built = await verb(job, 'build', env); assert.doesNotMatch(built, /cache hit/, 'nothing replayed'); - assert.match(built, /lib:build: cache miss, executing/); - assert.match(built, /site:build: cache miss, executing/); + assert.match(built, missed('lib:build')); + assert.match(built, missed('site:build')); assert.equal((await keys(TRUSTED_BUCKET, 'acme-one-checkout')).length, 2, 'both builds reached the trusted bucket'); }); diff --git a/packages/lib/src/turboCacheStep.test.ts b/packages/lib/src/turboCacheStep.test.ts index 26dd4b8b..4927e6a2 100644 --- a/packages/lib/src/turboCacheStep.test.ts +++ b/packages/lib/src/turboCacheStep.test.ts @@ -118,7 +118,7 @@ function steps(): Record; 'continue-on-er test('the server binds loopback whatever the job’s environment holds', () => { const server = steps().server; - assert.match(server?.uses ?? '', /^brunojppb\/turbo-cache-server@[0-9a-f]{40} /); + assert.match(server?.uses ?? '', /^brunojppb\/turbo-cache-server@[0-9a-f]{40}$/); assert.equal(server?.env?.HOST, '127.0.0.1'); }); From e1f546d459ccc53d8dcba9a4bbf746cd12625d21 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 19:13:13 +0100 Subject: [PATCH 099/194] test(e2e-playwright): the killed runs start from a shell, signal as a terminal does, and each miss the cache Found when the tests first ran green: a mise that leads its own session hands a SIGINT on to no task, so the SIGINT run went on to its end and its cache hit made the next kill test meaningless. The run now starts from sh, the SIGINT goes to its process group as a Ctrl-C does, the SIGKILL to mise found below sh, and each run has a spec of its own. TMPDIR is short, since the database's socket lies in it. A run that ends before its specs fails at once, with its output. Without the server's stdin guard in setup.ts, the test of SIGKILL of the Playwright runner fails (tried). Co-Authored-By: Claude Fable 5.2 --- newborns/e2e-playwright.test.ts | 61 ++++++++++++++++++++++++--------- 1 file changed, 44 insertions(+), 17 deletions(-) diff --git a/newborns/e2e-playwright.test.ts b/newborns/e2e-playwright.test.ts index 87436ee8..cac654b5 100644 --- a/newborns/e2e-playwright.test.ts +++ b/newborns/e2e-playwright.test.ts @@ -208,35 +208,62 @@ describe('a repo with a stateful app, its suite and the answer postgres', () => assert.match(ran.output, /@acme\/stateful-e2e:e2e: .*2 passed/); }); + /** The pid of the one process whose parent is `parent` (any, where undefined) and whose command line matches `pattern`. */ + async function pidOf(pattern: RegExp, parent?: number): Promise { + const ps = await sh('ps', ['-axww', '-o', 'pid=,ppid=,args='], here); + const found = ps + .split('\n') + .map((line) => /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line)) + .filter((m) => m && (parent === undefined || Number(m[2]) === parent) && pattern.test(m[3] as string)); + assert.equal(found.length, 1, `${pattern} under ${parent}:\n${ps}`); + return Number(found[0]?.[1]); + } + + // The run is started from a shell, as from a terminal: mise then neither leads its process group nor its session, + // and a SIGINT to the group reaches it as a Ctrl-C does. (A mise that leads its own session hands a SIGINT on to + // no task, and the run goes on to its end.) const kills: [string, (run: Launched) => Promise][] = [ - ['SIGINT of mise', async (run) => void process.kill(run.pid as number, 'SIGINT')], - ['SIGKILL of mise', async (run) => void process.kill(run.pid as number, 'SIGKILL')], + ['SIGINT of the run, as a Ctrl-C', async (run) => void process.kill(-(run.pid as number), 'SIGINT')], + [ + 'SIGKILL of mise', + async (run) => process.kill(await pidOf(/^mise run e2e stateful$/, run.pid as number), 'SIGKILL'), + ], [ 'SIGKILL of the Playwright runner', async () => { - const ps = await sh('ps', ['-axww', '-o', 'pid=,args='], here); - const runner = ps - .split('\n') - .find( - (line) => line.includes(join(clone, 'e2e', 'stateful')) && /@playwright\/test\/cli\.js test/.test(line), - ); - assert.ok(runner, ps); - process.kill(Number.parseInt(runner, 10), 'SIGKILL'); + const where = join(clone, 'e2e', 'stateful'); + const runner = new RegExp(`${where.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\S*@playwright/test/cli\\.js test$`); + process.kill(await pidOf(runner), 'SIGKILL'); }, ], ]; - for (const [how, kill] of kills) + for (const [at, [how, kill]] of kills.entries()) test(`a run killed by ${how} leaves no server and no PostgreSQL behind`, async () => { - // A spec that outlasts the kill; its temporary files, the database's cluster among them, are found by TMPDIR. - const tmp = join(here, `tmp-${how.replace(/\W+/g, '-')}`); + // A spec that outlasts the kill; the run's temporary files, the database's cluster among them, are found by TMPDIR. + // Short, as the database's socket lies in it and a socket's path holds at most about a hundred bytes. + const tmp = join(here, `t${at}`); mkdirSync(tmp, { recursive: true }); + // A spec of its own in each run, so that a run that went on to its end leaves no cache hit for the next. put(clone, { - 'e2e/stateful/specs/slow.spec.ts': - "import { test } from '@playwright/test';\n\ntest('waits', async () => {\n await new Promise((resolve) => setTimeout(resolve, 20_000));\n});\n", + 'e2e/stateful/specs/slow.spec.ts': [ + "import { test } from '@playwright/test';", + '', + `test('waits, to be killed by ${how}', async () => {`, + ' await new Promise((resolve) => setTimeout(resolve, 20_000));', + '});', + '', + ].join('\n'), }); - const run = launch('mise', ['run', 'e2e', 'stateful'], clone, { ...SHARED, TMPDIR: tmp }); + const run = launch('sh', ['-c', 'mise run e2e stateful; exit'], clone, { ...SHARED, TMPDIR: tmp }); try { - await until('the specs run', 300, () => /Running \d+ tests/.test(run.output())); + let ended = false; + void run.closed.then(() => { + ended = true; + }); + await until('the specs run', 300, () => { + assert.ok(!ended, `the run ended before its specs ran:\n${run.output()}`); + return /Running \d+ tests/.test(run.output()); + }); const port = /http:\/\/127\.0\.0\.1:(\d+)/.exec(run.output())?.[1]; assert.ok(port, run.output()); const answers = () => From 16fa96aaa55837221fbd2c9a9e7f8e9f51e3c03f Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 19:23:43 +0100 Subject: [PATCH 100/194] fix(e2e-playwright): setup.ts opens with two header lines, as plx requirements wants of a template file Its steps are said beside the code instead. The address is set once the server answers, and the configuration's read of it says why Turbo need not know it. Co-Authored-By: Claude Fable 5.2 --- .../e2e-playwright/files/playwright.config.ts | 1 + templates/e2e-playwright/files/setup.ts.jinja | 29 +++++++------------ 2 files changed, 11 insertions(+), 19 deletions(-) diff --git a/templates/e2e-playwright/files/playwright.config.ts b/templates/e2e-playwright/files/playwright.config.ts index e1db170a..e0d68928 100644 --- a/templates/e2e-playwright/files/playwright.config.ts +++ b/templates/e2e-playwright/files/playwright.config.ts @@ -6,6 +6,7 @@ export default defineConfig({ globalSetup: './setup.ts', reporter: 'list', // Set by setup.ts once the app answers, before any worker reads this file; whatever it held before is replaced. + // biome-ignore lint/suspicious/noUndeclaredEnvVars: set inside the task by setup.ts, so no input of the task use: { baseURL: process.env.PLX_E2E_BASE_URL }, projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], }); diff --git a/templates/e2e-playwright/files/setup.ts.jinja b/templates/e2e-playwright/files/setup.ts.jinja index a164ffd5..7070f89f 100644 --- a/templates/e2e-playwright/files/setup.ts.jinja +++ b/templates/e2e-playwright/files/setup.ts.jinja @@ -1,19 +1,5 @@ -// The suite's global setup: it starts the app as its image runs it, from the directory the app's build leaves, and -// hands the specs its address. It never builds: `mise e2e` builds the app first, as the suite depends on it. -// -// 1. The app is found through the workspace dependency, never by a relative path, and its build output, -// `.next/standalone`, must exist; without it the run fails, saying so. -// 2. Chromium must start from Playwright's shared cache; without it the run fails with the command that installs it. -// 3. The output is copied to a temporary directory, since a running server writes into its own directory. -// 4. Where the app's marker states the stateful profile: a throwaway PostgreSQL from the binary the repo pins -// (@plexus-ms/test-postgres, at the major PLX_POSTGRES_MAJOR names), a database of its own, the app's `migrate` -// run in the copy as the image runs it, and its `seed` run in the app's directory, the development command it is; -// each, and the server, gets that database as DATABASE_URL. -// 5. The standalone server on a free port of 127.0.0.1, ready once /healthz answers. It exits at the end of its -// stdin, which this process holds, so that it never outlives this process, however that ends; the database's -// supervisor does the same. -// -// The returned teardown stops what was started and removes the copy. +// The suite's global setup: it starts the app's build output as its image runs it, a stateful app's database, migrate +// and seed first, and hands the specs the address; it never builds, as `mise e2e` builds the app before the suite. import { type ChildProcess, spawn } from 'node:child_process'; import { once } from 'node:events'; import { existsSync } from 'node:fs'; @@ -28,6 +14,7 @@ import { chromium } from '@playwright/test'; const APP = '{{ app }}'; export default async function setup(): Promise<() => Promise> { + // Through the workspace dependency, never by a relative path. const app = path.dirname(createRequire(import.meta.url).resolve(`${APP}/package.json`)); const output = path.join(app, '.next', 'standalone'); if (!existsSync(output)) @@ -48,12 +35,14 @@ export default async function setup(): Promise<() => Promise> { for (const stop of stops.reverse()) await stop(); }; try { + // A copy, since a running server writes into its own directory. const copy = await mkdtemp(path.join(tmpdir(), 'plx-e2e-')); stops.push(() => rm(copy, { recursive: true, force: true })); await cp(output, copy, { recursive: true, verbatimSymlinks: true }); const server = within(copy, app); const env: NodeJS.ProcessEnv = { ...process.env }; if (await stateful(app)) { + // From the binary the repo pins; migrate runs in the copy as the image runs it, seed in the app as a developer does. const { createDatabase, startPostgres } = await import('@plexus-ms/test-postgres'); const postgres = await startPostgres({ major: Number(process.env.PLX_POSTGRES_MAJOR) }); stops.push(postgres.stop); @@ -62,6 +51,7 @@ export default async function setup(): Promise<() => Promise> { await run(['npm', 'run', 'seed'], app, env); } const port = await freePort(); + // The server exits at the end of its stdin, which this process holds, so that it never outlives this process. const guard = "process.stdin.on('end', () => process.exit()).resume(); require('./server.js');"; const started = spawn(process.execPath, ['-e', guard], { cwd: server, @@ -69,8 +59,9 @@ export default async function setup(): Promise<() => Promise> { stdio: ['pipe', 'inherit', 'inherit'], }); stops.push(() => end(started)); - process.env.PLX_E2E_BASE_URL = `http://127.0.0.1:${port}`; - await ready(`${process.env.PLX_E2E_BASE_URL}/healthz`, started); + const address = `http://127.0.0.1:${port}`; + await ready(`${address}/healthz`, started); + process.env.PLX_E2E_BASE_URL = address; } catch (error) { await teardown(); throw error; @@ -78,7 +69,7 @@ export default async function setup(): Promise<() => Promise> { return teardown; } -/** The app's directory in the output, which mirrors the workspace from its root: the shortest end of the app's path that holds the server. */ +/** The app's directory in the output, which mirrors the workspace: the shortest end of the app's path with a server. */ function within(output: string, app: string): string { const parts = app.split(path.sep); for (let at = parts.length - 1; at > 0; at--) { From 6840a6533832314dc781cb52bb227457fd2c1e28 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 19:26:57 +0100 Subject: [PATCH 101/194] plx doctor tests: multi-line and custom-delimited strings, the hooks not seen, the advice per missing verb (red) Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/doctor.test.ts | 43 ++++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 322b57b7..89e67abe 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -43,9 +43,16 @@ const VERBS = ['dev', 'build', 'check', 'test', 'e2e']; /** The hooks `hk.pkl` of a repo that meets PLX-Repo/Hooks wires. */ const HOOKS = ['pre-commit', 'pre-push']; -/** What `plx doctor` says of a verb the repo lacks, which a repo with no use for it answers with a no-op that passes. */ -const noTask = (verb: string) => - `no root mise task \`${verb}\`: add one, a no-op that passes where the repo has no use for it`; +/** What `plx doctor` says of a verb the repo lacks, and what to write: a no-op that passes for the three a repo may have no use for. */ +const NO_USE = 'add one, a no-op that passes where the repo has no use for it'; +const ADVICE: Record = { + dev: NO_USE, + build: NO_USE, + check: "add one that runs the repo's static checks", + test: "add one that runs `check` and then the repo's tests", + e2e: NO_USE, +}; +const noTask = (verb: string) => `no root mise task \`${verb}\`: ${ADVICE[verb]}`; const reasoned = (names: string[]) => names.map((n) => `- \`${n}\`: the reason.`).join('\n'); @@ -389,6 +396,36 @@ test('PLX-Repo/Hooks: a hook behind a comment is not wired', async () => { assert.deepEqual(await hooksOver(PKL(`${commit} // ["pre-push"] {\n }`)), noPush, 'a key line commented out'); }); +test('PLX-Repo/Hooks: braces and keys inside a multi-line or a custom-delimited string are text, not code', async () => { + const commit = (check: string) => ` ["pre-commit"] { steps { ["s"] { check = ${check} } } }\n`; + const push = ` ["pre-push"] ${STEP}\n`; + const noPush = ['hk.pkl wires no `pre-push` hook']; + const fake = '} } } ["pre-push"] { {'; + assert.deepEqual(await hooksOver(PKL(commit(`"""\n${fake}\n"""`))), noPush, 'a hook inside a multi-line string'); + assert.deepEqual(await hooksOver(PKL(commit(`#"${fake}"#`))), noPush, 'inside #"…"#'); + assert.deepEqual(await hooksOver(PKL(commit(`##"${fake} "# "##`))), noPush, 'inside ##"…"##, a shorter closer in it'); + assert.deepEqual(await hooksOver(PKL(commit(`#"""\n${fake}\n"""#`))), noPush, 'inside #"""…"""#'); + assert.deepEqual( + await hooksOver(PKL(`${commit(`"""\nsed -i 's/}$//' file\n"""`)}${push}`)), + [], + 'an unbalanced brace', + ); + assert.deepEqual(await hooksOver(PKL(`${commit('#"sed -i \'s/}$//\'"#')}${push}`)), []); +}); + +test('PLX-Repo/Hooks: a hook not written as a key of the hooks block in this file is not seen', async () => { + const both = ['hk.pkl wires no `pre-commit` hook', 'hk.pkl wires no `pre-push` hook']; + const body = ` ["pre-commit"] ${STEP}\n ["pre-push"] ${STEP}`; + assert.deepEqual(await hooksOver(`hooks = new Mapping {\n${body}\n}\n`), both, 'hooks = new Mapping'); + const commit = ` ["pre-commit"] ${STEP}\n`; + assert.deepEqual( + await hooksOver(`local push = new Hook ${STEP}\n${PKL(`${commit} ["pre-push"] = push`)}`), + ['hk.pkl wires no `pre-push` hook'], + 'a hook assigned from a variable', + ); + assert.deepEqual(await hooksOver(PKL(`${commit} [#"pre-push"#] ${STEP}`)), ['hk.pkl wires no `pre-push` hook']); +}); + test('PLX-Repo/Hooks: a hook name inside a string, or as a step of another hook, is not a hook', async () => { const commit = ` ["pre-commit"] ${STEP}\n`; const noPush = ['hk.pkl wires no `pre-push` hook']; From 5217e9483afbe12cf3a7507fba369268f1627cf3 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 19:27:13 +0100 Subject: [PATCH 102/194] plx doctor: Pkl's multi-line and custom-delimited strings are read as strings; the finding for a missing check or test says what to write Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/doctor.ts | 42 ++++++++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index e87b84cb..ec469988 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -60,7 +60,7 @@ // reports each that is missing, and a task `verify`, which no repo has any // more, with the tasks that replace it. Only the names of the tasks are read, // never what a task runs: the order of the gates (`check`, `test`, `build`, -// `e2e`) is kept by the tasks, not by a requirement. PLX-Repo/Hooks is +// `e2e`) is kept by the tasks, and no check reads it. PLX-Repo/Hooks is // existence only in the same way: `hk.pkl` wires a pre-commit and a pre-push // hook (`hooksWired`), and what either runs is not read. // @@ -162,8 +162,15 @@ export type Facts = RepoFacts | AppFacts; // // Each returns what is wrong, one line per problem; an empty list passes. -/** The repo verbs, in the order of the gates: one list for the check and for anything that names them. */ -const VERBS = ['dev', 'build', 'check', 'test', 'e2e'] as const; +/** The repo verbs, in the order of the gates, each with what a repo that lacks it is told to write. */ +const NO_USE = 'add one, a no-op that passes where the repo has no use for it'; +const VERBS: Readonly> = { + dev: NO_USE, + build: NO_USE, + check: "add one that runs the repo's static checks", + test: "add one that runs `check` and then the repo's tests", + e2e: NO_USE, +}; function repoMarker(repo: RepoFacts): string[] { if (!repo.marker) return [`no ${MARKER_FILE} at the repo's root`]; @@ -174,9 +181,9 @@ function verbs(repo: RepoFacts): string[] { if ('problem' in repo.tasks) return [`mise could not list the tasks: ${repo.tasks.problem}`]; const { names } = repo.tasks; return [ - ...VERBS.filter((verb) => !names.includes(verb)).map( - (verb) => `no root mise task \`${verb}\`: add one, a no-op that passes where the repo has no use for it`, - ), + ...Object.entries(VERBS) + .filter(([verb]) => !names.includes(verb)) + .map(([verb, advice]) => `no root mise task \`${verb}\`: ${advice}`), ...(names.includes('verify') ? ['a root mise task `verify` is left over: `check` and `test` replace it, `mise test` running `check` first'] : []), @@ -746,16 +753,25 @@ async function readSites(ctx: Context, repo: string): Promise Date: Mon, 30 Nov 2026 19:27:45 +0100 Subject: [PATCH 103/194] doctor test: the custom-delimited cases hold a quote, so that a plain string would read them differently Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/doctor.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 89e67abe..232bc70f 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -402,8 +402,8 @@ test('PLX-Repo/Hooks: braces and keys inside a multi-line or a custom-delimited const noPush = ['hk.pkl wires no `pre-push` hook']; const fake = '} } } ["pre-push"] { {'; assert.deepEqual(await hooksOver(PKL(commit(`"""\n${fake}\n"""`))), noPush, 'a hook inside a multi-line string'); - assert.deepEqual(await hooksOver(PKL(commit(`#"${fake}"#`))), noPush, 'inside #"…"#'); - assert.deepEqual(await hooksOver(PKL(commit(`##"${fake} "# "##`))), noPush, 'inside ##"…"##, a shorter closer in it'); + assert.deepEqual(await hooksOver(PKL(commit(`#"x "${fake}"#`))), noPush, 'inside #"…"#'); + assert.deepEqual(await hooksOver(PKL(commit(`##"x "#${fake}"##`))), noPush, 'inside ##"…"##, a shorter closer in it'); assert.deepEqual(await hooksOver(PKL(commit(`#"""\n${fake}\n"""#`))), noPush, 'inside #"""…"""#'); assert.deepEqual( await hooksOver(PKL(`${commit(`"""\nsed -i 's/}$//' file\n"""`)}${push}`)), From f186fc4e68cec7552eb016dcc9cc11161209b1c1 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 19:40:17 +0100 Subject: [PATCH 104/194] tests: TURBO_FORCE, true or 1, reaches Turbo as given in each case of turbow Red: turbow translates TURBO_FORCE=true into a cache setting without reads and unsets it. Raw Turbo 2.11.13 forces with TURBO_FORCE=true or 1 whatever TURBO_CACHE says, read-only remote included; the earlier claim that TURBO_CACHE beats it came from a zsh run in which the two assignments were one word. Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/repoTurboCache.test.ts | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/packages/lib/src/repoTurboCache.test.ts b/packages/lib/src/repoTurboCache.test.ts index 3ea22dc9..94470830 100644 --- a/packages/lib/src/repoTurboCache.test.ts +++ b/packages/lib/src/repoTurboCache.test.ts @@ -245,20 +245,18 @@ test('in a job, build and e2e reach the trusted server the job started, with the assert.match(alone.said.join('\n'), /without a remote cache/); }); -test('TURBO_FORCE stays what it was, a run that reads no cache and writes the caches it has', async () => { +test('TURBO_FORCE reaches Turbo as it was given, which forces whatever TURBO_CACHE says, in every case', async () => { const dir = checkout(REMOTE); - const force = { TURBO_FORCE: 'true' }; - assert.equal( - (await turbowIn(dir, 'shared', { ...force, PLX_TURBO_SHARED: answering })).turbo?.env.TURBO_CACHE, - 'local:w,remote:w', - ); - assert.equal( - (await turbowIn(dir, 'shared', { ...force, PLX_TURBO_SHARED: 'none' })).turbo?.env.TURBO_CACHE, - 'local:w', - ); - const trusted = await turbowIn(dir, 'trusted', { ...force, ...JOB, PLX_TURBO_TRUSTED: answering }); - assert.equal(trusted.turbo?.env.TURBO_CACHE, 'remote:w'); - assert.equal(trusted.turbo?.env.TURBO_FORCE, undefined, 'the cache setting says it all'); + for (const force of ['true', '1']) + for (const [cache, env, setting] of [ + ['shared', { PLX_TURBO_SHARED: 'none' }, 'local:rw'], + ['shared', { PLX_TURBO_SHARED: answering }, 'local:rw,remote:rw'], + ['trusted', { ...JOB, PLX_TURBO_TRUSTED: answering }, 'remote:rw'], + ] as const) { + const ran = await turbowIn(dir, cache, { ...env, TURBO_FORCE: force }); + assert.equal(ran.turbo?.env.TURBO_FORCE, force, `${force} ${cache} ${setting}`); + assert.equal(ran.turbo?.env.TURBO_CACHE, setting, `${force} ${cache}`); + } }); test('in a job without the trusted server, build and e2e fail and say why; they never fall back to the shared one', async () => { From da00180b0a4f3825c4e496dd68b61e245d989118 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 19:40:39 +0100 Subject: [PATCH 105/194] turbow: TURBO_FORCE is Turbo's, untouched Turbo forces with TURBO_FORCE=true or 1 whatever TURBO_CACHE says (raw runs, warm local and warm remote cache), so turbow neither reads nor unsets it, and sets its cache settings without a reads switch. Co-Authored-By: Claude Fable 5.2 --- templates/repo-turbo/files/turbow | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/templates/repo-turbo/files/turbow b/templates/repo-turbo/files/turbow index 349fc62e..110baee7 100755 --- a/templates/repo-turbo/files/turbow +++ b/templates/repo-turbo/files/turbow @@ -13,10 +13,8 @@ case $cache in esac # Where and how artifacts go is turbow's alone: no remote-cache setting of the caller's shell reaches Turbo, and no -# artifact is signed. TURBO_FORCE keeps its meaning, a run that reads no cache and writes those it has. -read=r -if [ "${TURBO_FORCE:-}" = true ]; then read=; fi -unset TURBO_API TURBO_TEAM TURBO_TEAMID TURBO_TOKEN TURBO_CACHE TURBO_FORCE TURBO_REMOTE_CACHE_SIGNATURE_KEY \ +# artifact is signed. +unset TURBO_API TURBO_TEAM TURBO_TEAMID TURBO_TOKEN TURBO_CACHE TURBO_REMOTE_CACHE_SIGNATURE_KEY \ TURBO_REMOTE_CACHE_READ_ONLY TURBO_PREFLIGHT TURBO_REMOTE_ONLY reason= @@ -76,13 +74,13 @@ fi if [ -n "$reason" ]; then echo "turbow: without a remote cache: $reason" >&2 # Told to Turbo too: a login and a linked repo would otherwise send the artifacts there. - export TURBO_API='' TURBO_TEAM='' TURBO_TOKEN='' TURBO_CACHE="local:${read}w" + export TURBO_API='' TURBO_TEAM='' TURBO_TOKEN='' TURBO_CACHE=local:rw elif [ "$from" = trusted ]; then echo "turbow: the trusted remote cache at $server, team $team" >&2 # Never the local cache, which a shared run of this checkout may have filled from the shared bucket. - export TURBO_API="$server" TURBO_TEAM="$team" TURBO_TOKEN="$token" TURBO_CACHE="remote:${read}w" + export TURBO_API="$server" TURBO_TEAM="$team" TURBO_TOKEN="$token" TURBO_CACHE=remote:rw else echo "turbow: the shared remote cache at $server, team $team" >&2 - export TURBO_API="$server" TURBO_TEAM="$team" TURBO_TOKEN="$token" TURBO_CACHE="local:${read}w,remote:${read}w" + export TURBO_API="$server" TURBO_TEAM="$team" TURBO_TOKEN="$token" TURBO_CACHE=local:rw,remote:rw fi exec turbo "$@" From c771e652612a872d983c76b8b554d99fc55a91ff Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 19:40:53 +0100 Subject: [PATCH 106/194] the step turbo-cache: its header says exactly when a job runs on without its cache The three named cases run on and warn; the step itself still fails the job where it cannot run at all, as without openssl, which the environment image carries. Co-Authored-By: Claude Fable 5.2 --- .github/actions/turbo-cache/action.yml | 15 ++++++++------- .github/actions/turbo-cache/turbo-cache.sh | 2 +- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/.github/actions/turbo-cache/action.yml b/.github/actions/turbo-cache/action.yml index 2d0ebed8..3a86796b 100644 --- a/.github/actions/turbo-cache/action.yml +++ b/.github/actions/turbo-cache/action.yml @@ -24,12 +24,13 @@ description: >- # job's environment; what the job's later steps get is the server's address # and token, in the variables turbow reads. # -# No job fails over its cache. A job without vault credentials, whose vault -# item could not be read, or whose server did not come up, runs without that -# remote cache, and says why in one line of the log and in one warning on the -# run; a tenant without the bucket on purpose gets the same warning. A server -# that comes up and cannot use its bucket is not probed: Turbo's own warning -# in the job's log says so. +# A job without vault credentials, whose vault item could not be read, or +# whose server did not come up, runs on without that remote cache, and says +# why in one line of the log and in one warning on the run; a tenant without +# the bucket on purpose gets the same warning. The step itself still fails the +# job where it cannot run at all, as without openssl, which the environment +# image carries. A server that comes up and cannot use its bucket is not +# probed: Turbo's own warning in the job's log says so. inputs: cache: @@ -70,7 +71,7 @@ runs: REGION: op://${{ steps.plan.outputs.vault }}/${{ steps.plan.outputs.item }}/region ACCESS_KEY: op://${{ steps.plan.outputs.vault }}/${{ steps.plan.outputs.item }}/access-key-id SECRET_KEY: op://${{ steps.plan.outputs.vault }}/${{ steps.plan.outputs.item }}/secret-access-key - # A server that does not come up fails no job: announce says so. + # A server that does not come up does not fail the job: announce says so. - name: Start the cache server id: server if: ${{ steps.keys.outcome == 'success' }} diff --git a/.github/actions/turbo-cache/turbo-cache.sh b/.github/actions/turbo-cache/turbo-cache.sh index b8eab0b6..410051b6 100755 --- a/.github/actions/turbo-cache/turbo-cache.sh +++ b/.github/actions/turbo-cache/turbo-cache.sh @@ -23,7 +23,7 @@ # job runs without that remote cache, in one line of the log and in # one warning on the run: no vault to read (`skipped`), an item it # could not read (`failure`, the step above says why), or a server -# that did not come up. No job fails over its cache. +# that did not come up. In these three the job runs on. # # Run by hand, a phase needs only GITHUB_OUTPUT and GITHUB_ENV to name files. set -euo pipefail From 986e2c3b97c5fe5f703c26935ee79c7717f5318a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 19:43:21 +0100 Subject: [PATCH 107/194] test(e2e-playwright): the newborn suites hold on GitHub Actions, where Turbo groups a task's output Found on the branch's first CI run, where every suite passed and the tests failed: under GitHub Actions Turbo drops a task's prefix from its lines and holds its output back until it ends. A pass is now read without the prefix, and the killed runs stream their output (TURBO_LOG_ORDER=stream, tried), so that the specs are seen running before the kill. Green here with CI=true and GITHUB_ACTIONS=true, and without either. Co-Authored-By: Claude Fable 5.2 --- newborns/e2e-playwright.test.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/newborns/e2e-playwright.test.ts b/newborns/e2e-playwright.test.ts index cac654b5..e79b72d4 100644 --- a/newborns/e2e-playwright.test.ts +++ b/newborns/e2e-playwright.test.ts @@ -138,7 +138,7 @@ describe('a repo with a stateless app and its suite', () => { test('passes mise e2e: the suite starts the build output, and its spec finds the app', async () => { const ran = await tryRun('mise', ['run', 'e2e'], clone, SHARED); assert.ok(ran.ok, ran.output); - assert.match(ran.output, /@acme\/stateless-e2e:e2e: .*1 passed/); + assert.match(ran.output, /\s1 passed \(/); }); test('passes its own check: lint of the suite, and plx doctor', async () => { @@ -205,7 +205,7 @@ describe('a repo with a stateful app, its suite and the answer postgres', () => assert.ok(ran.ok, ran.output); assert.match(ran.output, /CREATE TABLE/); assert.match(ran.output, /INSERT 0 1/); - assert.match(ran.output, /@acme\/stateful-e2e:e2e: .*2 passed/); + assert.match(ran.output, /\s2 passed \(/); }); /** The pid of the one process whose parent is `parent` (any, where undefined) and whose command line matches `pattern`. */ @@ -254,7 +254,9 @@ describe('a repo with a stateful app, its suite and the answer postgres', () => '', ].join('\n'), }); - const run = launch('sh', ['-c', 'mise run e2e stateful; exit'], clone, { ...SHARED, TMPDIR: tmp }); + // Streamed, as on a terminal: under GitHub Actions Turbo holds a task's output back until the task ends. + const env = { ...SHARED, TMPDIR: tmp, TURBO_LOG_ORDER: 'stream' }; + const run = launch('sh', ['-c', 'mise run e2e stateful; exit'], clone, env); try { let ended = false; void run.closed.then(() => { From 5b118df814071b7883b6478098e0318477069609 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 19:43:26 +0100 Subject: [PATCH 108/194] test(newborns): a package repo's changeset version writes a changelog its check accepts The newborn package repo asserts the CHANGELOG.md that changeset version writes and runs its own check on the result, so that a changelog the repo's Biome would refuse, or a formatter changesets cannot start, fails here. Refs PLX-196 Co-Authored-By: Claude Fable 5.2 --- newborns/repo-turbo.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/newborns/repo-turbo.test.ts b/newborns/repo-turbo.test.ts index d9deafbb..4c58b8e2 100644 --- a/newborns/repo-turbo.test.ts +++ b/newborns/repo-turbo.test.ts @@ -11,8 +11,9 @@ // the commit, and refuses it without `depends = "lint"`. `mise e2e` works first // in a fresh clone. A package repo also has what a release needs: a workspace // package with a pending changeset passes `test`, scoped to it by name, and -// `changeset version` takes the changeset in. Created by `plx new`; it needs -// the network (`mise install`, `pnpm add`). +// `changeset version` takes the changeset in, with a changelog that `check` +// then accepts. Created by `plx new`; it needs the network (`mise install`, +// `pnpm add`). // // mise run newborn # every template // KEEP=1 mise run newborn # leave the newborns in place and say where @@ -285,5 +286,7 @@ for (const [name, answers] of [ assert.ok(scoped.ok, scoped.output); await sh('mise', ['exec', '--', 'pnpm', 'exec', 'changeset', 'version'], dir); assert.match(read(dir, 'packages/demo/package.json'), /"version": "0\.2\.0"/); + assert.match(read(dir, 'packages/demo/CHANGELOG.md'), /^## 0\.2\.0\n\n### Minor Changes\n\n- A first change\.$/m); + await pass(dir, name, 'check'); }); } From b2d1c3b184b4da18d80ea2f635aa778764fe9980 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 19:45:08 +0100 Subject: [PATCH 109/194] fix(repo-turbo): a package repo's changesets format nothing @changesets/cli 3.1.0 (apply-release-plan 8.2.0, write 1.1.0) adds Biome to the formatters its default "format": "auto" detects, finds biome.json, and formats each changelog and changeset it writes with `pnpm exec @biomejs/biome format`. pnpm exec runs a binary, and Biome's is `biome`, so changeset version exits 1 in every package repo of the template (changesets/format#56, open). Biome would have nothing to do anyway: the shared configuration turns its formatter off for Markdown. "format": false, which @changesets/config 4.0 already accepts, says so and holds for 3.0 and 3.1 alike. Refs PLX-196 Co-Authored-By: Claude Fable 5.2 --- .../config.json.jinja | 2 ++ 1 file changed, 2 insertions(+) diff --git a/templates/repo-turbo/files/{% if publishes_packages %}.changeset{% endif %}/config.json.jinja b/templates/repo-turbo/files/{% if publishes_packages %}.changeset{% endif %}/config.json.jinja index e86af74a..cdd5d63c 100644 --- a/templates/repo-turbo/files/{% if publishes_packages %}.changeset{% endif %}/config.json.jinja +++ b/templates/repo-turbo/files/{% if publishes_packages %}.changeset{% endif %}/config.json.jinja @@ -4,6 +4,8 @@ "commit": false, "access": "{{ 'restricted' if package_registry == 'github' else 'public' }}", "baseBranch": "main", + {#- No formatter for changelogs and changesets: Biome formats no Markdown here (@plexus-ms/config), and changesets would start it as `pnpm exec @biomejs/biome`, which pnpm cannot run. #} + "format": false, "updateInternalDependencies": "patch", "fixed": [], "linked": [], From 084117176a3167619f3d58b3afa50c365527594a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 20:16:24 +0100 Subject: [PATCH 110/194] tooling: check runs lint and plx doctor over itself (red until the five verbs) Co-Authored-By: Claude Fable 5.2 --- mise.toml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/mise.toml b/mise.toml index 1aefa51d..942063dc 100644 --- a/mise.toml +++ b/mise.toml @@ -86,8 +86,8 @@ arg "" var=#true default="." help="Files or directories to lint (defaults run = "biome check ${usage_write:+--write} --no-errors-on-unmatched $usage_paths" [tasks.check] -depends = ["check-js", "check-ops", "check-requirements"] -description = "Run static checks on the codebase: the packages, the workflows, the collection, the citations" +depends = ["lint", "check-js", "check-ops", "check-requirements", "check-doctor"] +description = "Run every static check, executing no test: lint, the packages' types, the workflows, the collection, the citations, the repo contract" [tasks.newborn] depends = ["build"] @@ -124,6 +124,12 @@ else fi ''' +[tasks.check-doctor] +depends = ["build"] +description = "plx doctor over this repo, with the workspace's own build: the repo holds itself to the repo contract it ships" +hide = true +run = "pnpm plx doctor" + [tasks.check-ops] description = "actionlint over the workflows; ansible-lint over the collections (their Galaxy dependencies installed on first use), a syntax check of their playbooks and of a playbook that lists every role; the runner image on the apps' runtime base; what each size of slot mounts" hide = true From 097cb6cbdeee4e3797ac7e80cea1cdd9eac48748 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 20:18:28 +0100 Subject: [PATCH 111/194] tooling takes the five verbs: test runs check first, the newborns are e2e, pre-commit runs lint and check Co-Authored-By: Claude Fable 5.2 --- .github/workflows/{verify.yml => test.yml} | 0 hk.pkl | 10 ++--- mise.toml | 47 ++++++++++------------ 3 files changed, 26 insertions(+), 31 deletions(-) rename .github/workflows/{verify.yml => test.yml} (100%) diff --git a/.github/workflows/verify.yml b/.github/workflows/test.yml similarity index 100% rename from .github/workflows/verify.yml rename to .github/workflows/test.yml diff --git a/hk.pkl b/hk.pkl index df59babb..8f7c3682 100644 --- a/hk.pkl +++ b/hk.pkl @@ -10,16 +10,16 @@ hooks { check = "mise :lint {{ files }}" fix = "mise :lint --write {{ files }}" } - ["ops"] { - glob = List("ansible/**", "tests/**", ".github/workflows/*.yml") - check = "mise :check-ops" + ["check"] { + depends = "lint" + check = "mise :check" } } } ["pre-push"] { steps { - ["check"] { - check = "mise :check" + ["test"] { + check = "mise :test" } } } diff --git a/mise.toml b/mise.toml index 942063dc..11b39443 100644 --- a/mise.toml +++ b/mise.toml @@ -53,15 +53,31 @@ depends = ["install"] description = "Build the packages (the collection and the workflows ship as source)" run = "turbo run build" -[tasks.verify] -depends = ["lint", "check", "test", "newborn"] -description = "Perform all steps that verify code quality" +[tasks.check] +depends = ["lint", "check-js", "check-ops", "check-requirements", "check-doctor"] +description = "Run every static check, executing no test: lint, the packages' types, the workflows, the collection, the citations, the repo contract" + +[tasks.test] +depends = ["check", "install"] +description = "Run check, then the unit tests of the packages (the roles are exercised by the dogfood tenant's playbook runs, the mounts by its pipelines)" +usage = 'arg "[package]" help="Package to test (defaults to all)"' +run = 'turbo run test ${usage_package:+--filter=$usage_package}' + +[tasks.e2e] +depends = ["build"] +description = "Each template as a newborn: created by plx new from this checkout's build, birth commands included, and its own verbs run (newborns/); it neither checks nor tests this repo" +# Never a turbo task, so never cached: what it exercises is the network (the +# tools a newborn installs). The packages of this workspace are packed once and +# served to the newborns by a registry of the run's own, so a newborn runs the +# plx being cut, also where its version is not on npm yet (newborns/helpers.ts). +env = { NEWBORN_TARBALLS = "{{config_root}}/node_modules/.cache/newborn-tarballs" } +run = ["node newborns/pack.ts", "node --test newborns/*.test.ts"] # The upstream's verb (§ 1.5 PLX) [tasks.ship] -depends = ["build", "newborn"] -description = "Cut the version from this checkout's own build, after every template has passed as a newborn: plx-dev ship over the workspace this checkout sits in (plexus-ms/tooling under it)" +depends = ["build", "e2e"] +description = "Cut the version from this checkout's own build, after every template has passed as a newborn (e2e): plx-dev ship over the workspace this checkout sits in (plexus-ms/tooling under it)" # Never a published package: the tool that releases the version is the code at # main, built here, so it cannot lag behind the release it cuts. Flags follow # `--`: `mise ship -- -n` previews, `mise ship -- -y` runs unattended. @@ -85,21 +101,6 @@ arg "" var=#true default="." help="Files or directories to lint (defaults ''' run = "biome check ${usage_write:+--write} --no-errors-on-unmatched $usage_paths" -[tasks.check] -depends = ["lint", "check-js", "check-ops", "check-requirements", "check-doctor"] -description = "Run every static check, executing no test: lint, the packages' types, the workflows, the collection, the citations, the repo contract" - -[tasks.newborn] -depends = ["build"] -description = "Each template as a newborn: created by plx new from this checkout's build, birth commands included, and its own verify run (newborns/)" -hide = true -# Never a turbo task, so never cached: what it exercises is the network (the -# tools a newborn installs). The packages of this workspace are packed once and -# served to the newborns by a registry of the run's own, so a newborn runs the -# plx being cut, also where its version is not on npm yet (newborns/helpers.ts). -env = { NEWBORN_TARBALLS = "{{config_root}}/node_modules/.cache/newborn-tarballs" } -run = ["node newborns/pack.ts", "node --test newborns/*.test.ts"] - [tasks.check-js] depends = ["install"] description = "Type-check the packages" @@ -149,9 +150,3 @@ run = [ # puts the four plexus.* collections there and installs what their galaxy.yml # files depend on, which no other path would supply. env = { ANSIBLE_HOME = "{{config_root}}/.ansible", ANSIBLE_COLLECTIONS_PATH = "{{config_root}}/.ansible/collections" } - -[tasks.test] -depends = ["install"] -description = "Run tests on the packages (the roles are exercised by the dogfood tenant's playbook runs, the mounts by its pipelines)" -usage = 'arg "[package]" help="Package to test (defaults to all)"' -run = 'turbo run test ${usage_package:+--filter=$usage_package}' From 2737e3da96c0872922e280dde6890075d0fc04a7 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 20:18:36 +0100 Subject: [PATCH 112/194] ship: the header names the verbs it depends on, e2e for the newborns Co-Authored-By: Claude Fable 5.2 --- packages/dev/src/ship.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/dev/src/ship.ts b/packages/dev/src/ship.ts index 71e15418..f7265ed3 100644 --- a/packages/dev/src/ship.ts +++ b/packages/dev/src/ship.ts @@ -23,8 +23,8 @@ // dry run is the one place consumers still appear: it previews the unreleased // templates against the workspace's consumers (preview.ts), a maintainer's // test. That the templates are sound is no preflight of ship's: `mise ship` -// depends on the `newborn` task, which creates each template with `plx new`, -// runs its own verify and the doctor of this build over it (newborns/). +// depends on the `e2e` task, which creates each template with `plx new` and +// runs its own verbs and the doctor of this build over it (newborns/). // // Every release lists the subjects of the commits since the previous version, // each a code span, so a tenant can read what a version concerns. The step of @@ -52,10 +52,10 @@ // ship runs from the source of the tooling checkout it cuts, never as a // published package: the tool that releases the version is never itself a // release that could lag behind it. Run it with `mise ship` there, which first -// runs the `newborn` task, every template created and passing its own verify -// with this checkout's own build of the packages a newborn installs, whether -// or not that version is on npm yet (newborns/); `plx-dev ship` run directly has -// no such guard. +// runs `build` and the `e2e` task, every template created and passing its own +// verbs with this checkout's own build of the packages a newborn installs, +// whether or not that version is on npm yet (newborns/); `plx-dev ship` run +// directly has no such guard. // // mise ship # next version = minor+1 over the latest // mise ship -- --to 1.0.0 # explicit Plexus version; also what finishes a half-cut one From 37b76a88fa00ae548dc68f616dd89945c42469b3 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 20:18:41 +0100 Subject: [PATCH 113/194] tooling's own workflow: test on a push, e2e on a pull request Co-Authored-By: Claude Fable 5.2 --- .github/workflows/test.yml | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 91fca7c4..23c48e8c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,23 +1,34 @@ -name: verify +name: test -# Mounts the verify verb on every push (§ 2 PLX-Delivery): the same `mise -# verify` the pre-push hook runs, through this repo's own reusable _check.yml -# with the whole contract verb as its task. +# Mounts the verbs on this repo's own events (§ 3 PLX-Delivery): `test` on +# every push, which includes `check` (`mise test` runs it first) and is the +# same `mise test` the pre-push hook runs, and `e2e` on a pull request, the +# newborn tests, which need the network, a local registry and Docker. Both go +# through this repo's own reusable _check.yml with the verb as its task. A +# pull request's head commit has been pushed, so its `test` is the push run, +# and `e2e` does not run it again. # Every push includes the update bot's branches, whose pull requests merge # unattended only once a check is green, and the version's bookkeeping commits. on: push: + pull_request: permissions: contents: read concurrency: - group: verify-${{ github.ref }} + group: test-${{ github.ref }} cancel-in-progress: true jobs: - verify: + test: + if: github.event_name == 'push' uses: ./.github/workflows/_check.yml with: - tasks: verify + tasks: test + e2e: + if: github.event_name == 'pull_request' + uses: ./.github/workflows/_check.yml + with: + tasks: e2e From 37149dcf1ad6956c2cf1fbb4e8e91988b234e6df Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 20:25:42 +0100 Subject: [PATCH 114/194] tooling: check-js waits for the build, so a forced check never rebuilds lib while plx reads it Co-Authored-By: Claude Fable 5.2 --- mise.toml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/mise.toml b/mise.toml index 11b39443..4ed575d6 100644 --- a/mise.toml +++ b/mise.toml @@ -102,9 +102,11 @@ arg "" var=#true default="." help="Files or directories to lint (defaults run = "biome check ${usage_write:+--write} --no-errors-on-unmatched $usage_paths" [tasks.check-js] -depends = ["install"] +depends = ["build"] description = "Type-check the packages" hide = true +# After the build, not beside it: under TURBO_FORCE two turbo runs would each +# rebuild lib/dist, while the other, or plx itself, reads it. usage = 'arg "[package]" help="Package to check (defaults to all)"' run = 'turbo run check ${usage_package:+--filter=$usage_package}' From 1ecbec45c91472d5f59baf16d6fde8851ce7c7cd Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 20:50:58 +0100 Subject: [PATCH 115/194] newborns: git with a newborn's identity is a shared helper repo-turbo.test.ts and e2e-playwright.test.ts each had their own copy. Co-Authored-By: Claude Fable 5.2 --- newborns/e2e-playwright.test.ts | 24 +++++++++++------------- newborns/helpers.ts | 8 ++++++++ newborns/repo-turbo.test.ts | 10 +--------- 3 files changed, 20 insertions(+), 22 deletions(-) diff --git a/newborns/e2e-playwright.test.ts b/newborns/e2e-playwright.test.ts index e5a20ee9..3111b77b 100644 --- a/newborns/e2e-playwright.test.ts +++ b/newborns/e2e-playwright.test.ts @@ -18,7 +18,7 @@ import assert from 'node:assert/strict'; import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { after, before, describe, test } from 'node:test'; -import { born, close, type Launched, launch, open, pass, put, relock, sh, tryRun } from './helpers.ts'; +import { born, close, git, type Launched, launch, open, pass, put, relock, sh, tryRun } from './helpers.ts'; const SHARED = { PLAYWRIGHT_BROWSERS_PATH: join(import.meta.dirname, '..', 'node_modules', '.cache', 'ms-playwright') }; @@ -28,13 +28,11 @@ before(async () => { }); after(close); -/** git with an identity and no signing, as a newborn has neither. */ -const git = (dir: string, ...args: string[]) => - sh( - 'git', - ['-c', 'commit.gpgsign=false', '-c', 'user.name=newborn', '-c', 'user.email=newborn@example.invalid', ...args], - dir, - ); +/** `git` that must succeed. */ +async function gitOk(dir: string, ...args: string[]): Promise { + const ran = await git(dir, ...args); + assert.ok(ran.ok, ran.output); +} /** What the stateful app's author writes: a migrate and a seed, run with the database in DATABASE_URL, and a page that reads it. */ function authored(app: string): void { @@ -81,15 +79,15 @@ async function newborn(profile: string, answers: Record = {}): P }); } await relock(dir); - await git(dir, 'add', '-A'); - await git(dir, 'commit', '--no-verify', '-q', '-m', 'born'); + await gitOk(dir, 'add', '-A'); + await gitOk(dir, 'commit', '--no-verify', '-q', '-m', 'born'); return dir; } /** A fresh clone of `dir`, its tools installed, as a checkout on another machine. */ async function fresh(dir: string, name: string): Promise { const clone = join(here, name); - await git(here, 'clone', '-q', dir, clone); + await gitOk(here, 'clone', '-q', dir, clone); await sh('sh', ['-c', 'mise trust && mise install'], clone); return clone; } @@ -164,13 +162,13 @@ describe('a repo with a stateless app and its suite', () => { assert.ok(first[e2e] && first[build], JSON.stringify(first)); const spec = join(clone, 'e2e', 'stateless', 'specs', 'home.spec.ts'); put(clone, { 'e2e/stateless/specs/home.spec.ts': `${readFileSync(spec, 'utf8')}// edited\n` }); - await git(clone, 'add', '-A'); + await gitOk(clone, 'add', '-A'); const specEdited = await hashes(clone, '@acme/stateless-e2e'); assert.notEqual(specEdited[e2e], first[e2e]); assert.equal(specEdited[build], first[build]); const page = join(clone, 'apps', 'stateless', 'src', 'app', 'page.tsx'); put(clone, { 'apps/stateless/src/app/page.tsx': `${readFileSync(page, 'utf8')}// edited\n` }); - await git(clone, 'add', '-A'); + await gitOk(clone, 'add', '-A'); const appEdited = await hashes(clone, '@acme/stateless-e2e'); assert.notEqual(appEdited[e2e], specEdited[e2e]); assert.notEqual(appEdited[build], specEdited[build]); diff --git a/newborns/helpers.ts b/newborns/helpers.ts index 596fc876..fab0c06e 100644 --- a/newborns/helpers.ts +++ b/newborns/helpers.ts @@ -158,6 +158,14 @@ export async function tryRun( return { ok: code === 0, output: run.output() }; } +/** git with an identity and no signing, as a newborn has neither; unfailing, as `tryRun` is. */ +export const git = (dir: string, ...args: string[]) => + tryRun( + 'git', + ['-c', 'commit.gpgsign=false', '-c', 'user.name=newborn', '-c', 'user.email=newborn@example.invalid', ...args], + dir, + ); + /** Runs a command that must succeed; its output goes with the error otherwise. */ export async function sh(command: string, args: string[], cwd: string, env: NodeJS.ProcessEnv = {}): Promise { const ran = await tryRun(command, args, cwd, env); diff --git a/newborns/repo-turbo.test.ts b/newborns/repo-turbo.test.ts index 2c8c8635..62d4cd3b 100644 --- a/newborns/repo-turbo.test.ts +++ b/newborns/repo-turbo.test.ts @@ -21,7 +21,7 @@ import assert from 'node:assert/strict'; import { readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { after, before, describe, test } from 'node:test'; -import { born, close, mise, open, pass, put, relock, sh, tryRun } from './helpers.ts'; +import { born, close, git, mise, open, pass, put, relock, sh, tryRun } from './helpers.ts'; let here = ''; before(async () => { @@ -53,14 +53,6 @@ async function hashes(dir: string, pkg: string, tasks: string[]): Promise [t.taskId, t.hash])); } -/** git with an identity and no signing, as a newborn has neither. */ -const git = (dir: string, ...args: string[]) => - tryRun( - 'git', - ['-c', 'commit.gpgsign=false', '-c', 'user.name=newborn', '-c', 'user.email=newborn@example.invalid', ...args], - dir, - ); - /** Projects of a newborn: each prints what it did, so that a run shows which ones it ran. `needs` are workspace dependencies. */ function projects(dir: string, specs: Record): void { for (const [name, { verbs, needs = [] }] of Object.entries(specs)) From da92a8e3205eda9326df6e654208566639ad5968 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 20:51:44 +0100 Subject: [PATCH 116/194] newborns: until, the poll loop of start, is a shared helper, and the suite's kill tests use it Co-Authored-By: Claude Fable 5.2 --- newborns/e2e-playwright.test.ts | 31 ++++++++++++++----------------- newborns/helpers.ts | 28 +++++++++++++++++++++++----- 2 files changed, 37 insertions(+), 22 deletions(-) diff --git a/newborns/e2e-playwright.test.ts b/newborns/e2e-playwright.test.ts index 3111b77b..efaba24a 100644 --- a/newborns/e2e-playwright.test.ts +++ b/newborns/e2e-playwright.test.ts @@ -18,7 +18,7 @@ import assert from 'node:assert/strict'; import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { after, before, describe, test } from 'node:test'; -import { born, close, git, type Launched, launch, open, pass, put, relock, sh, tryRun } from './helpers.ts'; +import { born, close, git, type Launched, launch, open, pass, put, relock, sh, tryRun, until } from './helpers.ts'; const SHARED = { PLAYWRIGHT_BROWSERS_PATH: join(import.meta.dirname, '..', 'node_modules', '.cache', 'ms-playwright') }; @@ -182,15 +182,6 @@ async function mentioning(text: string): Promise { return ps.split('\n').filter((line) => line.includes(text)); } -/** Resolves once `check` holds, polling; rejects after `seconds`. */ -async function until(what: string, seconds: number, check: () => Promise | boolean): Promise { - for (const end = Date.now() + seconds * 1000; Date.now() < end; ) { - if (await check()) return; - await new Promise((resolve) => setTimeout(resolve, 250)); - } - throw new Error(`${what}: not within ${seconds} s`); -} - describe('a repo with a stateful app, its suite and the answer postgres', () => { let clone = ''; before(async () => { @@ -259,10 +250,14 @@ describe('a repo with a stateful app, its suite and the answer postgres', () => void run.closed.then(() => { ended = true; }); - await until('the specs run', 300, () => { - assert.ok(!ended, `the run ended before its specs ran:\n${run.output()}`); - return /Running \d+ tests/.test(run.output()); - }); + await until( + 'the specs run', + () => { + assert.ok(!ended, `the run ended before its specs ran:\n${run.output()}`); + return /Running \d+ tests/.test(run.output()); + }, + 300_000, + ); const port = /http:\/\/127\.0\.0\.1:(\d+)/.exec(run.output())?.[1]; assert.ok(port, run.output()); const answers = () => @@ -277,9 +272,11 @@ describe('a repo with a stateful app, its suite and the answer postgres', () => ); await kill(run); await Promise.race([run.closed, new Promise((resolve) => setTimeout(resolve, 120_000))]); - await until(`after ${how}, the server and the database are gone`, 30, async () => { - return !(await answers()) && (await mentioning(tmp)).length === 0; - }); + await until( + `after ${how}, the server and the database are gone`, + async () => !(await answers()) && (await mentioning(tmp)).length === 0, + 30_000, + ); } finally { run.kill(); rmSync(join(clone, 'e2e', 'stateful', 'specs', 'slow.spec.ts'), { force: true }); diff --git a/newborns/helpers.ts b/newborns/helpers.ts index fab0c06e..0d0b0fc3 100644 --- a/newborns/helpers.ts +++ b/newborns/helpers.ts @@ -424,11 +424,29 @@ export async function start( run.kill(); await run.closed; }; - const until = Date.now() + LIMIT; - while (!gone && Date.now() < until) { - if (await ready().catch(() => false)) return { stop }; + try { + await until(`${command} ready`, async () => { + if (gone) throw new Error(`${command} exited`); + return ready().catch(() => false); + }); + return { stop }; + } catch { + await stop(); + throw new Error( + `${command} ${args.join(' ')} ${gone ? 'exited' : 'never became ready'} in ${cwd}:\n${run.output()}`, + ); + } +} + +/** + * Resolves once `check` answers true, asking every 200 ms; rejects, naming + * `what`, once `limit` milliseconds have passed. A check that throws ends the + * wait with its error. + */ +export async function until(what: string, check: () => boolean | Promise, limit = LIMIT): Promise { + for (const end = Date.now() + limit; Date.now() < end; ) { + if (await check()) return; await new Promise((resolve) => setTimeout(resolve, 200)); } - await stop(); - throw new Error(`${command} ${args.join(' ')} ${gone ? 'exited' : 'never became ready'} in ${cwd}:\n${run.output()}`); + throw new Error(`${what}: not within ${limit} ms`); } From b6ed879a64d46ecee0567da97e57caf467521c9d Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 20:51:49 +0100 Subject: [PATCH 117/194] fix(newborns): a killed run is awaited by polling, so that no timer holds the file 120 s after its tests The race with a two-minute timer left the timer running, and node --test waited for it: the file ended two minutes after its last test. Co-Authored-By: Claude Fable 5.2 --- newborns/e2e-playwright.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/newborns/e2e-playwright.test.ts b/newborns/e2e-playwright.test.ts index efaba24a..bef5bcd2 100644 --- a/newborns/e2e-playwright.test.ts +++ b/newborns/e2e-playwright.test.ts @@ -271,7 +271,7 @@ describe('a repo with a stateful app, its suite and the answer postgres', () => 'and its database runs', ); await kill(run); - await Promise.race([run.closed, new Promise((resolve) => setTimeout(resolve, 120_000))]); + await until(`the run ends after ${how}`, () => ended, 120_000); await until( `after ${how}, the server and the database are gone`, async () => !(await answers()) && (await mentioning(tmp)).length === 0, From 5256f687728366546d1e303bb98bbb0aa3dcf94f Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 20:55:28 +0100 Subject: [PATCH 118/194] test(e2e-playwright): the database follows the app's migrate and seed scripts, a missing postgres answer is named, the marker names mise e2e Red: the suite still reads the app's marker, so an app with a seed script and the stateless profile gets no database, and an app with a migrate script in a repo without the postgres answer passes without one; the configuration's unused biome-ignore is reported by every newborn's check; the marker names mise :e2e. New and green already, to hold behaviour the review found untested: a run leaves no copy in its TMPDIR, the output holds nothing the server wrote, and migrate runs with NODE_ENV=production. Two apps, one name the end of the other's, each pass their own suite. Co-Authored-By: Claude Fable 5.2 --- newborns/e2e-playwright.test.ts | 255 +++++++++++++++++-------- packages/lib/src/e2ePlaywright.test.ts | 6 + 2 files changed, 181 insertions(+), 80 deletions(-) diff --git a/newborns/e2e-playwright.test.ts b/newborns/e2e-playwright.test.ts index bef5bcd2..c52934e1 100644 --- a/newborns/e2e-playwright.test.ts +++ b/newborns/e2e-playwright.test.ts @@ -1,24 +1,30 @@ -// An E2E suite of the template e2e-playwright, in newborn repos of the -// Turborepo template with updates beside it: one with a stateless app and its -// suite, and one with the answer `postgres`, a stateful app and its suite, the -// app's `migrate` and `seed` written as its author writes them. Each passes -// `mise e2e` from a fresh clone, its suite starting the app's build output. +// E2E suites of the template e2e-playwright, in newborn repos of the +// Turborepo template with updates beside it: one with two stateless apps, +// `stateless` and `less`, each with its suite, and one with the answer +// `postgres`, a stateful app whose `migrate` and `seed` are written as its +// author writes them and an app with a `seed` script only, each with its suite. +// Each repo passes `mise e2e` from a fresh clone, each suite starting a copy of +// its own app's build output and removing it at the end; a database is started +// for an app with a `migrate` or `seed` script and for no other, `migrate` runs +// with NODE_ENV=production, then `seed`. An app that needs a database in a repo +// without the answer `postgres` fails before anything starts, naming the answer. // Without Chromium in Playwright's shared cache the run fails, naming the // command that installs it, and that command does. The suite's own `e2e` fails // without the build output and does not build it. Editing a spec moves the -// hash of the suite's `e2e` and leaves the app's `build`; editing the app moves -// both. A run killed by SIGINT or SIGKILL of `mise`, or by SIGKILL of the -// Playwright runner that started the app, leaves no server and no PostgreSQL -// behind. The repo's own `check`, `plx doctor` in it, passes. Created by `plx +// hash of the suite's `e2e` and leaves the app's `build`; editing the app, or +// giving it a `migrate` script, moves both. A run killed by SIGINT or SIGKILL +// of `mise`, or by SIGKILL of the Playwright runner that started the app, +// leaves no server and no PostgreSQL behind. The repo's own `check`, `plx +// doctor` in it, passes, and says nothing of the suites' files. Created by `plx // new`; it needs the network. // // Playwright's shared cache is, for these tests, `node_modules/.cache/ms-playwright` // of this workspace: kept from one run to the next and never the user's. import assert from 'node:assert/strict'; -import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'; +import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { after, before, describe, test } from 'node:test'; -import { born, close, git, type Launched, launch, open, pass, put, relock, sh, tryRun, until } from './helpers.ts'; +import { born, close, git, type Launched, launch, open, put, relock, sh, tryRun, until } from './helpers.ts'; const SHARED = { PLAYWRIGHT_BROWSERS_PATH: join(import.meta.dirname, '..', 'node_modules', '.cache', 'ms-playwright') }; @@ -34,49 +40,85 @@ async function gitOk(dir: string, ...args: string[]): Promise { assert.ok(ran.ok, ran.output); } -/** What the stateful app's author writes: a migrate and a seed, run with the database in DATABASE_URL, and a page that reads it. */ -function authored(app: string): void { +/** A one-pixel PNG, for an app's public/ and its image optimiser, which writes its cache below the server's directory. */ +const PIXEL = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', + 'base64', +); + +/** A spec of `lines`, as a file of the suite. */ +const spec = (...lines: string[]) => ["import { expect, test } from '@playwright/test';", '', ...lines, ''].join('\n'); + +/** Adds scripts to an app's package.json. */ +function scripts(app: string, added: Record): void { const manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8')); - const psql = (sql: string) => `psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -c "${sql}"`; - manifest.scripts.migrate = psql('create table greeting (text text not null)'); - manifest.scripts.seed = psql("insert into greeting values ('hello from the seed')"); - put(app, { - 'package.json': manifest, - 'src/app/greeting/page.tsx': [ - "import { execFileSync } from 'node:child_process';", - "import { connection } from 'next/server';", - '', - 'export default async function Greeting() {', - ' await connection();', - " const sql = ['-Atc', 'select text from greeting'];", - " return

{execFileSync('psql', [process.env.DATABASE_URL ?? '', ...sql], { encoding: 'utf8' }).trim()}

;", - '}', - '', - ].join('\n'), - }); + put(app, { 'package.json': { ...manifest, scripts: { ...manifest.scripts, ...added } } }); } -/** - * A newborn repo with an app of `profile` at apps/ and its suite at - * e2e/, committed; returns the repo. `fresh` clones it. - */ -async function newborn(profile: string, answers: Record = {}): Promise { - const dir = await born(join(here, profile), ['repo-turbo', 'updates'], { tenant: 'acme', ...answers }); - await born(join(dir, 'apps', profile), ['app-nextjs'], { name: `@acme/${profile}`, profile }); - await born(join(dir, 'e2e', profile), ['e2e-playwright'], { app: `@acme/${profile}` }); - if (profile === 'stateful') { - authored(join(dir, 'apps', profile)); - put(dir, { - 'e2e/stateful/specs/greeting.spec.ts': [ - "import { expect, test } from '@playwright/test';", +const psql = (sql: string) => `psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -c "${sql}"`; + +/** What a newborn app gets beside the template's files, given its directory and its suite's. */ +const EXTRAS: Record void> = { + // A request the image optimiser answers, which makes the server write below its own directory. + stateless: (app, suite) => { + put(app, { 'public/pixel.png': PIXEL }); + put(suite, { + 'specs/image.spec.ts': spec( + "test('the image optimiser answers', async ({ request }) => {", + " const image = await request.get('/_next/image?url=%2Fpixel.png&w=64&q=75', { headers: { accept: 'image/webp' } });", + ' expect(image.ok()).toBe(true);', + '});', + ), + }); + }, + // The stateful app's migrate and seed as its author writes them, run with the database in DATABASE_URL, and a page + // that reads what they wrote; migrate says which NODE_ENV it ran with. + stateful: (app, suite) => { + scripts(app, { + migrate: `echo "migrate saw NODE_ENV=$NODE_ENV" && ${psql('create table greeting (text text not null)')}`, + seed: psql("insert into greeting values ('hello from the seed')"), + }); + put(app, { + 'src/app/greeting/page.tsx': [ + "import { execFileSync } from 'node:child_process';", + "import { connection } from 'next/server';", '', + 'export default async function Greeting() {', + ' await connection();', + " const sql = ['-Atc', 'select text from greeting'];", + " return

{execFileSync('psql', [process.env.DATABASE_URL ?? '', ...sql], { encoding: 'utf8' }).trim()}

;", + '}', + '', + ].join('\n'), + }); + put(suite, { + 'specs/greeting.spec.ts': spec( "test('the page shows what the seed wrote into the migrated database', async ({ page }) => {", " await page.goto('/greeting');", " await expect(page.getByText('hello from the seed')).toBeVisible();", '});', - '', - ].join('\n'), + ), }); + }, + // An app of the stateless profile with a seed script and no migrate. + seeded: (app) => scripts(app, { seed: `echo "seed saw $DATABASE_URL" && ${psql('select 1')}` }), +}; + +/** + * A newborn repo with an app at apps/ of each profile given, plus what + * EXTRAS gives it, and its suite at e2e/, committed; returns the repo. + * `fresh` clones it. + */ +async function newborn( + name: string, + apps: Record, + answers: Record = {}, +): Promise { + const dir = await born(join(here, name), ['repo-turbo', 'updates'], { tenant: 'acme', ...answers }); + for (const [app, profile] of Object.entries(apps)) { + await born(join(dir, 'apps', app), ['app-nextjs'], { name: `@acme/${app}`, profile }); + await born(join(dir, 'e2e', app), ['e2e-playwright'], { app: `@acme/${app}` }); + EXTRAS[app]?.(join(dir, 'apps', app), join(dir, 'e2e', app)); } await relock(dir); await gitOk(dir, 'add', '-A'); @@ -84,6 +126,16 @@ async function newborn(profile: string, answers: Record = {}): P return dir; } +/** A new directory for a run's TMPDIR, short, as a database's socket lies in it and a socket's path holds about a hundred bytes. */ +function tmp(name: string): string { + const dir = join(here, name); + mkdirSync(dir, { recursive: true }); + return dir; +} + +/** What a run left in its TMPDIR of the suite's copies and the database's clusters. */ +const leftIn = (dir: string) => readdirSync(dir).filter((entry) => /^(plx-e2e|test-postgres)-/.test(entry)); + /** A fresh clone of `dir`, its tools installed, as a checkout on another machine. */ async function fresh(dir: string, name: string): Promise { const clone = join(here, name); @@ -100,10 +152,10 @@ async function hashes(dir: string, suite: string): Promise [t.taskId, t.hash])); } -describe('a repo with a stateless app and its suite', () => { +describe('a repo with two stateless apps, one name the end of the other, and their suites', () => { let repo = ''; before(async () => { - repo = await newborn('stateless'); + repo = await newborn('stateless', { stateless: 'stateless', less: 'stateless' }); }); test("the suite's marker lists its template and names the app", () => { @@ -115,14 +167,14 @@ describe('a repo with a stateless app and its suite', () => { const clone = await fresh(repo, 'stateless-browserless'); const empty = join(here, 'no-browsers'); mkdirSync(empty, { recursive: true }); - const ran = await tryRun('mise', ['run', 'e2e'], clone, { PLAYWRIGHT_BROWSERS_PATH: empty }); + const ran = await tryRun('mise', ['run', 'e2e', 'stateless'], clone, { PLAYWRIGHT_BROWSERS_PATH: empty }); assert.equal(ran.ok, false, ran.output); const named = /install it with `([^`]+)` in (\S+)/.exec(ran.output); assert.ok(named, ran.output); const [, command, where] = named as unknown as [string, string, string]; assert.equal(where, join(clone, 'e2e', 'stateless')); await sh('mise', ['exec', '--', 'sh', '-c', command], where, SHARED); - const again = await tryRun('mise', ['run', 'e2e'], clone, SHARED); + const again = await tryRun('mise', ['run', 'e2e', 'stateless'], clone, SHARED); assert.ok(again.ok, again.output); }); @@ -132,14 +184,24 @@ describe('a repo with a stateless app and its suite', () => { clone = await fresh(repo, 'stateless-clone'); }); - test('passes mise e2e: the suite starts the build output, and its spec finds the app', async () => { - const ran = await tryRun('mise', ['run', 'e2e'], clone, SHARED); + test('passes mise e2e: each suite starts a copy of its own app, no database where the app has neither migrate nor seed, and removes the copy', async () => { + const run = tmp('s0'); + const ran = await tryRun('mise', ['run', 'e2e'], clone, { ...SHARED, TMPDIR: run }); assert.ok(ran.ok, ran.output); - assert.match(ran.output, /\s1 passed \(/); + assert.match(ran.output, /\s2 passed \(/, 'the two specs of stateless'); + assert.match(ran.output, /\s1 passed \(/, 'the one spec of less'); + assert.doesNotMatch(ran.output, /> @acme\/\w+@[\d.]+ (migrate|seed)/); + assert.deepEqual(leftIn(run), [], 'no copy is left'); + // The optimiser wrote its cache below the server's directory: in the copy, and not in the output. + const served = join(clone, 'apps', 'stateless', '.next', 'standalone', 'apps', 'stateless'); + assert.ok(existsSync(join(served, 'server.js')), served); + assert.equal(existsSync(join(served, '.next', 'cache', 'images')), false, 'the output was served itself'); }); - test('passes its own check: lint of the suite, and plx doctor', async () => { - await pass(clone, 'stateless', 'check'); + test('passes its own check, plx doctor in it, which says nothing of the suites', async () => { + const ran = await tryRun('mise', ['run', 'check'], clone); + assert.ok(ran.ok, ran.output); + assert.doesNotMatch(ran.output, /e2e\/\w+\/\S+:\d+:\d+|Suppression comment/); }); test("the suite's own e2e fails without the build output, and does not build it", async () => { @@ -156,22 +218,45 @@ describe('a repo with a stateless app and its suite', () => { assert.equal(existsSync(dotNext), false, 'nothing was built'); }); - test("editing a spec moves the suite's e2e and not the app's build; editing the app moves both", async () => { + test("editing a spec moves the suite's e2e and not the app's build; editing the app or giving it a migrate moves both", async () => { const [e2e, build] = ['@acme/stateless-e2e#e2e', '@acme/stateless#build']; - const first = await hashes(clone, '@acme/stateless-e2e'); - assert.ok(first[e2e] && first[build], JSON.stringify(first)); - const spec = join(clone, 'e2e', 'stateless', 'specs', 'home.spec.ts'); - put(clone, { 'e2e/stateless/specs/home.spec.ts': `${readFileSync(spec, 'utf8')}// edited\n` }); - await gitOk(clone, 'add', '-A'); - const specEdited = await hashes(clone, '@acme/stateless-e2e'); - assert.notEqual(specEdited[e2e], first[e2e]); - assert.equal(specEdited[build], first[build]); - const page = join(clone, 'apps', 'stateless', 'src', 'app', 'page.tsx'); - put(clone, { 'apps/stateless/src/app/page.tsx': `${readFileSync(page, 'utf8')}// edited\n` }); - await gitOk(clone, 'add', '-A'); - const appEdited = await hashes(clone, '@acme/stateless-e2e'); - assert.notEqual(appEdited[e2e], specEdited[e2e]); - assert.notEqual(appEdited[build], specEdited[build]); + const app = join(clone, 'apps', 'stateless'); + try { + const first = await hashes(clone, '@acme/stateless-e2e'); + assert.ok(first[e2e] && first[build], JSON.stringify(first)); + const specFile = join(clone, 'e2e', 'stateless', 'specs', 'home.spec.ts'); + put(clone, { 'e2e/stateless/specs/home.spec.ts': `${readFileSync(specFile, 'utf8')}// edited\n` }); + await gitOk(clone, 'add', '-A'); + const specEdited = await hashes(clone, '@acme/stateless-e2e'); + assert.notEqual(specEdited[e2e], first[e2e]); + assert.equal(specEdited[build], first[build]); + const page = join(app, 'src', 'app', 'page.tsx'); + put(app, { 'src/app/page.tsx': `${readFileSync(page, 'utf8')}// edited\n` }); + await gitOk(clone, 'add', '-A'); + const appEdited = await hashes(clone, '@acme/stateless-e2e'); + assert.notEqual(appEdited[e2e], specEdited[e2e]); + assert.notEqual(appEdited[build], specEdited[build]); + scripts(app, { migrate: 'echo migrated' }); + await gitOk(clone, 'add', '-A'); + assert.notEqual((await hashes(clone, '@acme/stateless-e2e'))[e2e], appEdited[e2e], 'a migrate script'); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + + test('an app with a migrate script, in a repo without the answer postgres, fails before anything starts, naming the answer', async () => { + const app = join(clone, 'apps', 'stateless'); + const run = tmp('s1'); + try { + scripts(app, { migrate: 'echo migrated' }); + const ran = await tryRun('mise', ['run', 'e2e', 'stateless'], clone, { ...SHARED, TMPDIR: run }); + assert.equal(ran.ok, false, ran.output); + assert.match(ran.output, /answer `postgres` in the repo's PLEXUS\.md.*`plx apply`/); + assert.doesNotMatch(ran.output, /migrated/); + assert.deepEqual(leftIn(run), []); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } }); }); }); @@ -182,20 +267,32 @@ async function mentioning(text: string): Promise { return ps.split('\n').filter((line) => line.includes(text)); } -describe('a repo with a stateful app, its suite and the answer postgres', () => { +describe('a repo with the answer postgres, a stateful app, an app with a seed alone, and their suites', () => { let clone = ''; before(async () => { - clone = await fresh(await newborn('stateful', { postgres: '18.6' }), 'stateful-clone'); + clone = await fresh( + await newborn('stateful', { stateful: 'stateful', seeded: 'stateless' }, { postgres: '18.6' }), + 'stateful-clone', + ); }); - test('passes mise e2e from a fresh clone: migrate and seed run against the database the server gets', async () => { + test('passes mise e2e from a fresh clone: migrate in production, then seed, against the database the server gets', async () => { const ran = await tryRun('mise', ['run', 'e2e', 'stateful'], clone, SHARED); assert.ok(ran.ok, ran.output); - assert.match(ran.output, /CREATE TABLE/); - assert.match(ran.output, /INSERT 0 1/); + assert.match(ran.output, /migrate saw NODE_ENV=production\b/); + assert.match(ran.output, /CREATE TABLE[\s\S]*INSERT 0 1/); assert.match(ran.output, /\s2 passed \(/); }); + test('an app with a seed script and no migrate gets a database and its seed, and no migrate', async () => { + const ran = await tryRun('mise', ['run', 'e2e', 'seeded'], clone, SHARED); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, /> @acme\/seeded@[\d.]+ seed/); + assert.match(ran.output, /seed saw postgres(ql)?:\/\//); + assert.doesNotMatch(ran.output, /> @acme\/seeded@[\d.]+ migrate/); + assert.match(ran.output, /\s1 passed \(/); + }); + /** The pid of the one process whose parent is `parent` (any, where undefined) and whose command line matches `pattern`. */ async function pidOf(pattern: RegExp, parent?: number): Promise { const ps = await sh('ps', ['-axww', '-o', 'pid=,ppid=,args='], here); @@ -228,9 +325,7 @@ describe('a repo with a stateful app, its suite and the answer postgres', () => for (const [at, [how, kill]] of kills.entries()) test(`a run killed by ${how} leaves no server and no PostgreSQL behind`, async () => { // A spec that outlasts the kill; the run's temporary files, the database's cluster among them, are found by TMPDIR. - // Short, as the database's socket lies in it and a socket's path holds at most about a hundred bytes. - const tmp = join(here, `t${at}`); - mkdirSync(tmp, { recursive: true }); + const dir = tmp(`t${at}`); // A spec of its own in each run, so that a run that went on to its end leaves no cache hit for the next. put(clone, { 'e2e/stateful/specs/slow.spec.ts': [ @@ -243,7 +338,7 @@ describe('a repo with a stateful app, its suite and the answer postgres', () => ].join('\n'), }); // Streamed, as on a terminal: under GitHub Actions Turbo holds a task's output back until the task ends. - const env = { ...SHARED, TMPDIR: tmp, TURBO_LOG_ORDER: 'stream' }; + const env = { ...SHARED, TMPDIR: dir, TURBO_LOG_ORDER: 'stream' }; const run = launch('sh', ['-c', 'mise run e2e stateful; exit'], clone, env); try { let ended = false; @@ -267,14 +362,14 @@ describe('a repo with a stateful app, its suite and the answer postgres', () => ); assert.ok(await answers(), 'the server answers before the kill'); assert.ok( - (await mentioning(tmp)).some((line) => /postgres/.test(line)), + (await mentioning(dir)).some((line) => /postgres/.test(line)), 'and its database runs', ); await kill(run); await until(`the run ends after ${how}`, () => ended, 120_000); await until( `after ${how}, the server and the database are gone`, - async () => !(await answers()) && (await mentioning(tmp)).length === 0, + async () => !(await answers()) && (await mentioning(dir)).length === 0, 30_000, ); } finally { diff --git a/packages/lib/src/e2ePlaywright.test.ts b/packages/lib/src/e2ePlaywright.test.ts index 4b23d0f5..55a71e5c 100644 --- a/packages/lib/src/e2ePlaywright.test.ts +++ b/packages/lib/src/e2ePlaywright.test.ts @@ -47,6 +47,12 @@ test('no file imports by a relative path out of the suite, starts Next itself, o } }); +test("the marker names the verb that runs the suite: mise e2e at the repo's root, with the app's name", async () => { + const marker = textOf(await render(), 'PLEXUS.md'); + assert.match(marker, /`mise e2e ` at the repo's root/); + assert.doesNotMatch(marker, /mise :e2e/); +}); + test('the marker and the spec are written once, the rest is merged', async () => { const result = await render(); const once = ['PLEXUS.md', 'specs/home.spec.ts']; From 8a7ba244a3842b2f76a15d4c61aae810a4a44675 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 20:55:34 +0100 Subject: [PATCH 119/194] fix(e2e-playwright): the app's migrate and seed scripts decide the database, a missing postgres answer is named, the server's directory is the build's record The suite reads the app's package.json, an input of its e2e, and no longer the frontmatter of the app's marker: a migrate or a seed script means a database, and those of the two that exist run, migrate first. Without the repo's postgres answer it fails before anything starts, naming the answer and plx apply. The server's directory in the output is relativeAppDir of the one required-server-files.json the build left there, not a guess from the app's path. Co-Authored-By: Claude Fable 5.2 --- templates/e2e-playwright/files/setup.ts.jinja | 64 ++++++++++++------- 1 file changed, 41 insertions(+), 23 deletions(-) diff --git a/templates/e2e-playwright/files/setup.ts.jinja b/templates/e2e-playwright/files/setup.ts.jinja index 7070f89f..058adb05 100644 --- a/templates/e2e-playwright/files/setup.ts.jinja +++ b/templates/e2e-playwright/files/setup.ts.jinja @@ -1,8 +1,8 @@ -// The suite's global setup: it starts the app's build output as its image runs it, a stateful app's database, migrate -// and seed first, and hands the specs the address; it never builds, as `mise e2e` builds the app before the suite. +// The suite's global setup: it starts the app's build output as its image runs it, after a database, migrate and seed +// where the app has them, and hands the specs the address; it never builds: `mise e2e` builds the app before the suite. import { type ChildProcess, spawn } from 'node:child_process'; import { once } from 'node:events'; -import { existsSync } from 'node:fs'; +import { existsSync, readdirSync, readFileSync } from 'node:fs'; import { cp, mkdtemp, readFile, rm } from 'node:fs/promises'; import { createRequire } from 'node:module'; import { createServer } from 'node:net'; @@ -21,6 +21,14 @@ export default async function setup(): Promise<() => Promise> { throw new Error( `${APP} has no build output at ${output}: the suite starts it and never builds it; mise e2e builds it first`, ); + // The app needs a database when it has a migrate or a seed entry point, as the stateful profile requires of it. + const { scripts = {} } = JSON.parse(await readFile(path.join(app, 'package.json'), 'utf8')); + const entries = ['migrate', 'seed'].filter((name) => scripts[name] !== undefined); + const major = process.env.PLX_POSTGRES_MAJOR; + if (entries.length > 0 && !major) + throw new Error( + `${APP} has a ${entries.join(' and a ')} script, so its suite needs PostgreSQL, and the repo pins none: answer \`postgres\` in the repo's PLEXUS.md, an exact version as in 18.6, and run \`plx apply\` at the repo's root`, + ); await chromium.launch().then( (browser) => browser.close(), (error: Error) => { @@ -39,16 +47,16 @@ export default async function setup(): Promise<() => Promise> { const copy = await mkdtemp(path.join(tmpdir(), 'plx-e2e-')); stops.push(() => rm(copy, { recursive: true, force: true })); await cp(output, copy, { recursive: true, verbatimSymlinks: true }); - const server = within(copy, app); + const server = within(copy); const env: NodeJS.ProcessEnv = { ...process.env }; - if (await stateful(app)) { - // From the binary the repo pins; migrate runs in the copy as the image runs it, seed in the app as a developer does. + if (entries.length > 0) { + // From the binary the repo pins; migrate runs in the copy as the image runs it, seed in the app as developers do. const { createDatabase, startPostgres } = await import('@plexus-ms/test-postgres'); - const postgres = await startPostgres({ major: Number(process.env.PLX_POSTGRES_MAJOR) }); + const postgres = await startPostgres({ major: Number(major) }); stops.push(postgres.stop); env.DATABASE_URL = await createDatabase(postgres.url); - await run(['npm', 'run', 'migrate'], server, { ...env, NODE_ENV: 'production' }); - await run(['npm', 'run', 'seed'], app, env); + if (entries.includes('migrate')) await run(['npm', 'run', 'migrate'], server, { ...env, NODE_ENV: 'production' }); + if (entries.includes('seed')) await run(['npm', 'run', 'seed'], app, env); } const port = await freePort(); // The server exits at the end of its stdin, which this process holds, so that it never outlives this process. @@ -69,20 +77,30 @@ export default async function setup(): Promise<() => Promise> { return teardown; } -/** The app's directory in the output, which mirrors the workspace: the shortest end of the app's path with a server. */ -function within(output: string, app: string): string { - const parts = app.split(path.sep); - for (let at = parts.length - 1; at > 0; at--) { - const dir = path.join(output, ...parts.slice(at)); - if (existsSync(path.join(dir, 'server.js'))) return dir; - } - throw new Error(`the build output of ${APP} holds no server.js for ${app}`); -} - -/** Whether the frontmatter of the app's marker states the stateful profile. */ -async function stateful(app: string): Promise { - const marker = await readFile(path.join(app, 'PLEXUS.md'), 'utf8'); - return /^profile:\s*["']?stateful["']?\s*$/m.test(/^---\n([\s\S]*?)\n---/.exec(marker)?.[1] ?? ''); +/** + * The app's directory in the output, as the app's build recorded it: `relativeAppDir` of the one + * `.next/required-server-files.json` the output holds outside `node_modules`. + */ +function within(output: string): string { + const records: string[] = []; + const look = (dir: string): void => { + for (const entry of readdirSync(dir, { withFileTypes: true })) + if (entry.isDirectory() && entry.name !== 'node_modules') { + const at = path.join(dir, entry.name); + if (entry.name === '.next' && existsSync(path.join(at, 'required-server-files.json'))) records.push(at); + else look(at); + } + }; + look(output); + if (records.length !== 1) + throw new Error( + `the build output of ${APP} holds ${records.length} .next/required-server-files.json, where its build writes one: build it again`, + ); + const record = path.join(records[0] as string, 'required-server-files.json'); + const server = path.join(output, JSON.parse(readFileSync(record, 'utf8')).relativeAppDir); + if (!existsSync(path.join(server, 'server.js'))) + throw new Error(`the build output of ${APP} holds no server.js where ${record} places the app: build it again`); + return server; } async function run([command, ...args]: string[], cwd: string, env: NodeJS.ProcessEnv): Promise { From 2fb74bdde76ef53046b836bc7358ab4fd1631014 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 20:55:34 +0100 Subject: [PATCH 120/194] fix(e2e-playwright): the suite's marker names mise e2e at the repo's root, which works Co-Authored-By: Claude Fable 5.2 --- templates/e2e-playwright/files/PLEXUS.md.jinja | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/templates/e2e-playwright/files/PLEXUS.md.jinja b/templates/e2e-playwright/files/PLEXUS.md.jinja index b5e10a9e..05c3813d 100644 --- a/templates/e2e-playwright/files/PLEXUS.md.jinja +++ b/templates/e2e-playwright/files/PLEXUS.md.jinja @@ -1,3 +1,3 @@ -- The end-to-end suite of `{{ app }}`: Playwright runs the specs in `specs/` in Chromium against the app's build output, which `setup.ts` starts as the standalone server, after a throwaway PostgreSQL, the app's `migrate` and its `seed` where the app's marker states the `stateful` profile. -- It runs with `mise :e2e `, `` being the app's directory name, which builds the app first; the suite's `e2e` script never builds, and fails without the build output. +- The end-to-end suite of `{{ app }}`: Playwright runs the specs in `specs/` in Chromium against the app's build output, which `setup.ts` starts as the standalone server, after a throwaway PostgreSQL and the app's `migrate` and `seed` where its `package.json` has either. +- It runs with `mise e2e ` at the repo's root, `` being the app's directory name, which builds the app first (the suite's own name is no name the verb takes); the suite's `e2e` script never builds, and fails without the build output. - Chromium comes from Playwright's shared cache, into which `pnpm exec playwright install chromium`, run in this directory, installs it. From 66d7008e32d197870b7cb0c247af60bda6a68b88 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 20:55:34 +0100 Subject: [PATCH 121/194] fix(e2e-playwright): no biome-ignore in the configuration, which every newborn's check reported as unused Co-Authored-By: Claude Fable 5.2 --- templates/e2e-playwright/files/playwright.config.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/templates/e2e-playwright/files/playwright.config.ts b/templates/e2e-playwright/files/playwright.config.ts index e0d68928..e1db170a 100644 --- a/templates/e2e-playwright/files/playwright.config.ts +++ b/templates/e2e-playwright/files/playwright.config.ts @@ -6,7 +6,6 @@ export default defineConfig({ globalSetup: './setup.ts', reporter: 'list', // Set by setup.ts once the app answers, before any worker reads this file; whatever it held before is replaced. - // biome-ignore lint/suspicious/noUndeclaredEnvVars: set inside the task by setup.ts, so no input of the task use: { baseURL: process.env.PLX_E2E_BASE_URL }, projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], }); From 7f09243e0b6da116f66f8237fa5b937db583899c Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 21:04:41 +0100 Subject: [PATCH 122/194] tooling: every verb takes an optional package name; the own workflow runs test, then e2e on a pull request; the marker drops the keys the doctor says are not read; check's description holds Co-Authored-By: Claude Fable 5.2 --- .github/workflows/test.yml | 23 ++++++--------- PLEXUS.md | 2 -- mise.toml | 59 +++++++++++++++++++++++++++++++------- 3 files changed, 57 insertions(+), 27 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 23c48e8c..016e65a6 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,12 +1,13 @@ name: test -# Mounts the verbs on this repo's own events (§ 3 PLX-Delivery): `test` on -# every push, which includes `check` (`mise test` runs it first) and is the -# same `mise test` the pre-push hook runs, and `e2e` on a pull request, the -# newborn tests, which need the network, a local registry and Docker. Both go -# through this repo's own reusable _check.yml with the verb as its task. A -# pull request's head commit has been pushed, so its `test` is the push run, -# and `e2e` does not run it again. +# Mounts the verbs on this repo's own events (§ 2 PLX-Delivery), through this +# repo's own reusable _check.yml with the verbs as its tasks: `test` on every +# push, which includes `check` (`mise test` runs it first) and is the same +# `mise test` the pre-push hook runs, and on a pull request `test`, then `e2e`, +# the newborn tests, which need the network, a local registry and Docker. The +# tasks run in one job, in order, and a failing `test` stops it before `e2e` +# (the step runs under `bash -e`). On a pull request `test` runs on the merge +# commit, so a pull request from a fork gets it too. # Every push includes the update bot's branches, whose pull requests merge # unattended only once a check is green, and the version's bookkeeping commits. @@ -23,12 +24,6 @@ concurrency: jobs: test: - if: github.event_name == 'push' uses: ./.github/workflows/_check.yml with: - tasks: test - e2e: - if: github.event_name == 'pull_request' - uses: ./.github/workflows/_check.yml - with: - tasks: e2e + tasks: ${{ github.event_name == 'pull_request' && 'test e2e' || 'test' }} diff --git a/PLEXUS.md b/PLEXUS.md index 2045c323..b9550beb 100644 --- a/PLEXUS.md +++ b/PLEXUS.md @@ -1,6 +1,4 @@ --- -plexus: 0.101.0 -modules: [PLX-Repo, PLX-JS, PLX-Updates] --- - `tooling` ships the methodology's primitives (§ 1.6 PLX): the four `plexus.*` Ansible collections under `ansible//` (host, platform, infrastructure, ci; § 2 PLX-Platform), the reusable workflows under `.github/workflows/_*.yml`, the Plexus-versioned packages `@plexus-ms/{cli,cli-ci,cli-template,lib}` under `packages/`, and the shared Renovate preset under `renovate/`. diff --git a/mise.toml b/mise.toml index 4ed575d6..e84e9957 100644 --- a/mise.toml +++ b/mise.toml @@ -45,27 +45,54 @@ _.path = ["{{config_root}}/node_modules/.bin"] # Contract verbs (§ 3 PLX-Repo) [tasks.dev] -description = "No-op: nothing to start; the roles are applied by tenant playbooks, the workflows run on the forge" +description = "No-op: nothing to start; the roles are applied by tenant playbooks, the workflows run on the forge; a name is accepted and ignored, it applies to the whole repo" +usage = 'arg "[name]" hide=#true' run = 'echo "dev: nothing to start in tooling"' [tasks.build] depends = ["install"] -description = "Build the packages (the collection and the workflows ship as source)" -run = "turbo run build" +description = "Build the packages (the collection and the workflows ship as source), each after the workspace packages it depends on" +usage = 'arg "[name]" help="Package to build, by its directory name under packages/ (e.g. lib, defaults to all)"' +run = ''' +dir= +if [ -n "${usage_name:-}" ]; then + case $usage_name in + */* | . | ..) echo "build: $usage_name is not a directory name under packages/" >&2; exit 1 ;; + esac + [ ! -f "packages/$usage_name/package.json" ] || dir=packages/$usage_name + [ -n "$dir" ] || { echo "build: no package $usage_name under packages/" >&2; exit 1; } +fi +turbo run build ${dir:+--filter="{./$dir}"} +''' [tasks.check] -depends = ["lint", "check-js", "check-ops", "check-requirements", "check-doctor"] -description = "Run every static check, executing no test: lint, the packages' types, the workflows, the collection, the citations, the repo contract" +depends = ["lint", "check-ops", "check-requirements", "check-doctor"] +description = "Run every static check, none of them a test of the code under test (check-ops runs a script against a stub): lint, the packages' types, the workflows, the collection, the citations, the repo contract" +usage = 'arg "[name]" help="Package to check, by its directory name under packages/ (e.g. lib, defaults to all)"' +# The repo-wide checks cannot be scoped; the name scopes the types of the packages. +run = 'mise run check-js ${usage_name:+"$usage_name"}' [tasks.test] -depends = ["check", "install"] +depends = ["install"] description = "Run check, then the unit tests of the packages (the roles are exercised by the dogfood tenant's playbook runs, the mounts by its pipelines)" -usage = 'arg "[package]" help="Package to test (defaults to all)"' -run = 'turbo run test ${usage_package:+--filter=$usage_package}' +usage = 'arg "[name]" help="Package to test, by its directory name under packages/ (e.g. lib, defaults to all)"' +run = ''' +dir= +if [ -n "${usage_name:-}" ]; then + case $usage_name in + */* | . | ..) echo "test: $usage_name is not a directory name under packages/" >&2; exit 1 ;; + esac + [ ! -f "packages/$usage_name/package.json" ] || dir=packages/$usage_name + [ -n "$dir" ] || { echo "test: no package $usage_name under packages/" >&2; exit 1; } +fi +mise run check ${usage_name:+"$usage_name"} +turbo run test ${dir:+--filter="{./$dir}"} +''' [tasks.e2e] depends = ["build"] -description = "Each template as a newborn: created by plx new from this checkout's build, birth commands included, and its own verbs run (newborns/); it neither checks nor tests this repo" +description = "Each template as a newborn: created by plx new from this checkout's build, birth commands included, and its own verbs run (newborns/); it neither checks nor tests this repo; a name is accepted and ignored, it applies to the whole repo" +usage = 'arg "[name]" hide=#true' # Never a turbo task, so never cached: what it exercises is the network (the # tools a newborn installs). The packages of this workspace are packed once and # served to the newborns by a registry of the run's own, so a newborn runs the @@ -107,8 +134,18 @@ description = "Type-check the packages" hide = true # After the build, not beside it: under TURBO_FORCE two turbo runs would each # rebuild lib/dist, while the other, or plx itself, reads it. -usage = 'arg "[package]" help="Package to check (defaults to all)"' -run = 'turbo run check ${usage_package:+--filter=$usage_package}' +usage = 'arg "[name]" help="Package to check, by its directory name under packages/ (e.g. lib, defaults to all)"' +run = ''' +dir= +if [ -n "${usage_name:-}" ]; then + case $usage_name in + */* | . | ..) echo "check: $usage_name is not a directory name under packages/" >&2; exit 1 ;; + esac + [ ! -f "packages/$usage_name/package.json" ] || dir=packages/$usage_name + [ -n "$dir" ] || { echo "check: no package $usage_name under packages/" >&2; exit 1; } +fi +turbo run check ${dir:+--filter="{./$dir}"} +''' [tasks.check-requirements] depends = ["build"] From 9b7266a3c3c6b9e41578a64656c5eb3c2ea96f02 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 21:46:54 +0100 Subject: [PATCH 123/194] Test: plx-ci plan hashes build alone with the lockfile's Turbo, refuses without PLX_PLATFORM, and plans an e2e leg per app with its suite, its image's context and whether publish builds Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/core/plan.test.ts | 277 ++++++++++++++++---------- 1 file changed, 169 insertions(+), 108 deletions(-) diff --git a/packages/cli-ci/src/core/plan.test.ts b/packages/cli-ci/src/core/plan.test.ts index b13ddcca..20964b8d 100644 --- a/packages/cli-ci/src/core/plan.test.ts +++ b/packages/cli-ci/src/core/plan.test.ts @@ -1,67 +1,129 @@ import assert from 'node:assert/strict'; +import type { PassThrough } from 'node:stream'; import { test } from 'node:test'; import { Context } from '@plexus-ms/lib'; -import { fakeIo, notThere } from '../testing/fakeIo.ts'; -import { deployLegsOf, environmentOf, hashesOf, legsOf, plan, readHashes, verbsOf } from './plan.ts'; +import { fakeIo, notThere, type Tree } from '../testing/fakeIo.ts'; +import { deployLegsOf, environmentOf, hashesOf, legsOf, plan, readHashes } from './plan.ts'; const dryRun = JSON.stringify({ tasks: [ { taskId: '@acme/website#build', package: '@acme/website', hash: '0f2a', command: 'next build' }, - { taskId: '@acme/website#test', package: '@acme/website', hash: 'dc97', command: '' }, { taskId: '@acme/my-lib#build', package: '@acme/my-lib', hash: '4b6a' }, { taskId: '@acme/my-app#build', package: '@acme/my-app', hash: 'c51b', command: 'next build' }, - { taskId: '@acme/my-app#test', package: '@acme/my-app', hash: '5b05', command: 'pnpm test' }, + { taskId: '@acme/solver#build', package: '@acme/solver', hash: '9e1d', command: 'make' }, + { taskId: '@acme/stub#build', package: '@acme/stub', hash: 'aaaa', command: '' }, { taskId: '@other/x#build', package: '@other/x', hash: 'ffff', command: 'x' }, ], }); -const packages = { website: '@acme/website', 'my-app': '@acme/my-app' }; +const packages = { website: '@acme/website', 'my-app': '@acme/my-app', solver: '@acme/solver' }; const hashes = hashesOf(dryRun, packages); const run = { runId: '41', attempt: '1' }; -test('hashesOf keeps the build hash of each app’s package, and the test hash where the script exists', () => { +/** The lockfile of pnpm 11 and later: the package manager's document, then the workspace's. */ +const LOCKFILE = [ + '---', + "lockfileVersion: '9.0'", + 'importers:', + ' .:', + ' packageManagerDependencies:', + ' pnpm:', + ' specifier: 12.21.0', + ' version: 12.21.0', + '---', + "lockfileVersion: '9.0'", + 'importers:', + ' .:', + ' devDependencies:', + ' turbo:', + ' specifier: ^2.9.0', + ' version: 2.11.13', + ' apps/site:', + ' dependencies:', + ' next:', + ' specifier: ^16', + ' version: 16.4.6', + '', +].join('\n'); + +/** An app's directory: its package.json and the marker `plx new` writes, with the templates it lists. */ +const app = (name: string, templates: string[]): Tree => ({ + 'package.json': JSON.stringify({ name }), + 'PLEXUS.md': `---\ntemplates: [${templates.join(', ')}]\nname: ${name}\nprofile: stateless\n---\n`, +}); + +/** A suite at e2e/, the package the template e2e-playwright renders. */ +const suite = (of: string): Tree => ({ + 'package.json': JSON.stringify({ + name: `${of}-e2e`, + scripts: { e2e: 'playwright test' }, + devDependencies: { [of]: 'workspace:*', '@playwright/test': '^1.65.1' }, + }), +}); + +/** A checkout with three apps: website and my-app from app-nextjs, solver with a Dockerfile of its own; a suite for website only. */ +const REPO: Tree = { + repo: { + 'package.json': JSON.stringify({ devDependencies: { turbo: '^2.9.0' } }), + 'pnpm-lock.yaml': LOCKFILE, + apps: { + website: app('@acme/website', ['app-nextjs']), + 'my-app': app('@acme/my-app', ['app-nextjs']), + solver: app('@acme/solver', []), + }, + e2e: { website: suite('@acme/website'), tools: { 'package.json': JSON.stringify({ name: 'tools' }) } }, + }, +}; + +/** What a context narrated so far. */ +const narrated = (ctx: Context): string => String((ctx.io.stderr as PassThrough).read() ?? ''); + +test('hashesOf keeps the build hash of each app’s package and nothing else', () => { assert.deepEqual(hashes, [ { app: 'website', hash: '0f2a' }, - { app: 'my-app', hash: 'c51b', test: '5b05' }, + { app: 'my-app', hash: 'c51b' }, + { app: 'solver', hash: '9e1d' }, ]); - assert.deepEqual(hashesOf(dryRun, { nope: '@acme/nope' }), []); + assert.deepEqual(hashesOf(dryRun, { nope: '@acme/nope', stub: '@acme/stub' }), []); }); -test('readHashes asks each app’s package.json for the name Turbo knows it by', async () => { - const io = fakeIo( - { - repo: { - 'package.json': JSON.stringify({ devDependencies: { turbo: '2.9.0' } }), - apps: { site: { 'package.json': JSON.stringify({ name: '@acme/website' }) } }, - }, - }, - undefined, - { - npx: (_cwd, args) => { - assert.deepEqual(args, ['--yes', 'turbo@2.9.0', 'run', 'build', 'test', '--dry-run=json']); - return dryRun; - }, +test('readHashes runs the dry run of build with the Turbo the lockfile has, in the environment it is given', async () => { + const seen: { args: string[]; cwd: string }[] = []; + const io = fakeIo(REPO, undefined, { + npx: (cwd, args) => { + seen.push({ cwd, args }); + return dryRun; }, - ); - assert.deepEqual(await readHashes(new Context({}, io), '/repo', ['site']), [{ app: 'site', hash: '0f2a' }]); + }); + const env = { PLX_PLATFORM: 'linux-x64' }; + assert.deepEqual(await readHashes(new Context({}, io), '/repo', ['website'], env), [ + { app: 'website', hash: '0f2a' }, + ]); + assert.deepEqual(seen, [{ cwd: '/repo', args: ['--yes', 'turbo@2.11.13', 'run', 'build', '--dry-run=json'] }]); }); -test('a leg names its runner from the strategy: the forge’s, a large slot, or an instance of its own', () => { - assert.deepEqual(legsOf(['website'], hashes, 'build', 'hybrid', run), [ - { app: 'website', hash: '0f2a', runner: 'exo-large-41-website-1', n: 1, build: true, test: '' }, - ]); - assert.equal(legsOf(['website'], hashes, 'build', 'github', run)[0]?.runner, 'ubuntu-latest'); - assert.equal(legsOf(['website'], hashes, 'build', 'on-prem', run)[0]?.runner, 'ci-large'); - assert.deepEqual( - legsOf(['my-app'], hashes, 'repro', 'hybrid', { runId: '41', attempt: '2' }).map((l) => l.runner), - ['exo-large-41-my-app-2-1', 'exo-large-41-my-app-2-2'], +test('readHashes refuses to run without PLX_PLATFORM, which no build lacks, and runs nothing', async () => { + const io = fakeIo(REPO, undefined, { npx: () => assert.fail('no dry run without the platform') }); + await assert.rejects(readHashes(new Context({}, io), '/repo', ['website'], {}), /PLX_PLATFORM is empty.*mise/s); +}); + +test('readHashes refuses a lockfile without Turbo for the workspace root', async () => { + const io = fakeIo( + { repo: { ...(REPO.repo as Tree), 'pnpm-lock.yaml': "lockfileVersion: '9.0'\nimporters:\n .: {}\n" } }, + undefined, + { npx: () => assert.fail('no dry run without a locked Turbo') }, + ); + await assert.rejects( + readHashes(new Context({}, io), '/repo', ['website'], { PLX_PLATFORM: 'linux-x64' }), + /pnpm-lock\.yaml locks no turbo/, ); - assert.throws(() => legsOf(['nope'], hashes, 'build', 'hybrid', run), /no build hash for nope/); }); -test('a leg is named after the verbs it mounts', () => { - assert.equal(verbsOf({ build: true, test: '5b05' }), 'build, test'); - assert.equal(verbsOf({ build: true, test: '' }), 'build'); - assert.equal(verbsOf({ build: false, test: '5b05' }), 'test'); +test('a leg names the runner of its e2e job from the strategy: the forge’s, a large slot, or an instance of its own', () => { + assert.equal(legsOf(['website'], hashes, 'hybrid', run)[0]?.runner, 'exo-large-41-website-1'); + assert.equal(legsOf(['website'], hashes, 'github', run)[0]?.runner, 'ubuntu-latest'); + assert.equal(legsOf(['website'], hashes, 'on-prem', run)[0]?.runner, 'ci-large'); + assert.equal(legsOf(['my-app'], hashes, 'hybrid', { runId: '41', attempt: '2' })[0]?.runner, 'exo-large-41-my-app-2'); + assert.throws(() => legsOf(['nope'], hashes, 'hybrid', run), /no build hash for nope/); }); test('the environment follows the branch on a push or a run by hand, and a given one stands in', () => { @@ -79,91 +141,90 @@ test('deployLegsOf: an app with a target deploys the commit’s image there, one }); }); -test('the plan skips what the registry holds, per build and per test, and plans the deploys of an environment', async () => { - // The pair holds website's build and nothing of my-app. - const io = fakeIo({}, undefined, { - curl: (_cwd, args) => (args.at(-1)?.endsWith(':5000/v2/website/manifests/build-0f2a') ? '' : notThere('curl')), +/** A forge registry, as crane sees it, holding the refs given; every look-up is recorded. */ +function forge(holds: string[]) { + const asked: string[] = []; + const io = fakeIo(REPO, undefined, { + crane: (_cwd, args) => { + asked.push(args.join(' ')); + return args[0] === 'digest' && holds.includes(args[1] ?? '') ? 'sha256:abc' : notThere('crane'); + }, }); - const result = await plan(new Context({}, io), { - apps: ['website', 'my-app'], - mode: 'build', - tests: true, + return { io, asked }; +} + +test('every app gets a leg: its e2e job runs whatever the registry holds, and publish builds only a missing image', async () => { + const { io, asked } = forge(['ghcr.io/acme/website:build-0f2a']); + const result = await plan(new Context({}, io), '/repo', { + apps: ['website', 'my-app', 'solver'], hashes, strategy: 'hybrid', - registry: { kind: 'own' }, + prefix: 'ghcr.io/Acme', run, - deploy: { - environment: 'staging', - targets: { 'my-app': 'ssh://plexus@host-a' }, - prefix: 'ghcr.io/acme', - sha: 'abc', - }, }); - // One leg, one instance: my-app's build and its test after it. + assert.deepEqual(asked, [ + 'digest ghcr.io/acme/website:build-0f2a', + 'digest ghcr.io/acme/my-app:build-c51b', + 'digest ghcr.io/acme/solver:build-9e1d', + ]); assert.deepEqual(result.legs, [ - { app: 'my-app', hash: 'c51b', runner: 'exo-large-41-my-app-1', n: 1, build: true, test: '5b05' }, + // The image is there: its e2e job runs all the same, and publish adds the commit's tag. + { + app: 'website', + hash: '0f2a', + runner: 'exo-large-41-website-1', + suite: 'e2e/website', + context: 'output', + build: false, + }, + // No suite: its e2e job builds the app into the trusted cache and runs no suite; the image is missing. + { app: 'my-app', hash: 'c51b', runner: 'exo-large-41-my-app-1', suite: '', context: 'output', build: true }, + // A Dockerfile of its own: the image is built from a pruned context, not from the build output. + { app: 'solver', hash: '9e1d', runner: 'exo-large-41-solver-1', suite: '', context: 'pruned', build: true }, ]); - assert.deepEqual(result.skipped, [{ app: 'website', hash: '0f2a', ref: 'localhost:5000/website:build-0f2a' }]); - assert.deepEqual(result.apps, hashes); - assert.equal(result.environment, 'staging'); - assert.deepEqual(result.deploys, [{ app: 'my-app', host: 'ssh://plexus@host-a', image: 'ghcr.io/acme/my-app:abc' }]); + assert.equal(result.environment, ''); + assert.deepEqual(result.deploys, []); }); -test('an app whose build the registry holds and whose test it does not gets a leg that only tests', async () => { - const io = fakeIo({}, undefined, { - curl: (_cwd, args) => (args.at(-1)?.includes('/manifests/build-') ? '' : notThere('curl')), - }); - const result = await plan(new Context({}, io), { +test('the plan says which images exist and which publish will build', async () => { + const { io } = forge(['ghcr.io/acme/website:build-0f2a']); + const ctx = new Context({}, io); + await plan(ctx, '/repo', { apps: ['website', 'my-app'], hashes, strategy: 'github', prefix: 'ghcr.io/acme', run }); + assert.equal( + narrated(ctx), + [ + 'website: ghcr.io/acme/website:build-0f2a exists; publish tags it', + 'my-app: ghcr.io/acme/my-app:build-c51b is missing; publish builds it', + '', + ].join('\n'), + ); +}); + +test('a look-up that cannot run is the job’s fault, never a missing image', async () => { + const io = fakeIo(REPO, undefined, { crane: () => undefined }); + await assert.rejects( + plan(new Context({}, io), '/repo', { apps: ['website'], hashes, strategy: 'github', prefix: 'ghcr.io/acme', run }), + /could not look up ghcr.io\/acme\/website:build-0f2a/, + ); +}); + +test('with an environment the plan adds the deploys of the apps with a target there', async () => { + const { io } = forge([]); + const result = await plan(new Context({}, io), '/repo', { apps: ['website', 'my-app'], - mode: 'build', - tests: true, hashes, - strategy: 'hybrid', - registry: { kind: 'own' }, - run, - }); - assert.deepEqual(result.legs, [ - { app: 'my-app', hash: 'c51b', runner: 'exo-large-41-my-app-1', n: 1, build: false, test: '5b05' }, - ]); - assert.equal(result.skipped.length, 2); - // Without --test and in repro mode no leg tests. - const builds = await plan(new Context({}, io), { - apps: ['my-app'], - mode: 'repro', - tests: true, - hashes, - strategy: 'hybrid', - registry: { kind: 'own' }, + strategy: 'on-prem', + prefix: 'ghcr.io/acme', run, + deploy: { environment: 'staging', targets: { 'my-app': 'ssh://plexus@host-a' }, sha: 'abc' }, }); assert.deepEqual( - builds.legs.map((l) => [l.n, l.build, l.test]), + result.legs.map((l) => [l.app, l.runner, l.build]), [ - [1, true, ''], - [2, true, ''], + ['website', 'ci-large', true], + ['my-app', 'ci-large', true], ], ); -}); - -test('with the forge’s registry the look-up is crane’s, and without an environment nothing deploys', async () => { - const asked: string[] = []; - const io = fakeIo({}, undefined, { - crane: (_cwd, args) => { - asked.push(args.join(' ')); - return args[1]?.endsWith(':build-0f2a') ? 'sha256:abc' : notThere('crane'); - }, - }); - const result = await plan(new Context({}, io), { - apps: ['website'], - mode: 'build', - tests: true, - hashes, - strategy: 'github', - registry: { kind: 'ghcr', prefix: 'ghcr.io/plexus-ms-tenant' }, - run, - }); - assert.deepEqual(asked, ['digest ghcr.io/plexus-ms-tenant/website:build-0f2a']); - assert.deepEqual(result.legs, []); - assert.deepEqual(result.deploys, []); - assert.equal(result.environment, ''); + assert.equal(result.environment, 'staging'); + assert.deepEqual(result.deploys, [{ app: 'my-app', host: 'ssh://plexus@host-a', image: 'ghcr.io/acme/my-app:abc' }]); }); From 613ffb703d757d2e7f4db1fdfb5c9ab13b333bc0 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 21:47:32 +0100 Subject: [PATCH 124/194] Remove plx-ci test: the app's compose stack on a candidate, compose.ci.yaml with x-plexus-ci, and the tag test- MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The repo's own e2e replaces it (§ 3.2, § 4.5, § 4.6 of the Decisions). Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/commands/index.ts | 2 - packages/cli-ci/src/commands/test.ts | 40 -------- packages/cli-ci/src/core/test.test.ts | 30 ------ packages/cli-ci/src/core/test.ts | 131 -------------------------- packages/cli-ci/src/program.test.ts | 3 +- 5 files changed, 1 insertion(+), 205 deletions(-) delete mode 100644 packages/cli-ci/src/commands/test.ts delete mode 100644 packages/cli-ci/src/core/test.test.ts delete mode 100644 packages/cli-ci/src/core/test.ts diff --git a/packages/cli-ci/src/commands/index.ts b/packages/cli-ci/src/commands/index.ts index a1b01188..1862c775 100644 --- a/packages/cli-ci/src/commands/index.ts +++ b/packages/cli-ci/src/commands/index.ts @@ -12,13 +12,11 @@ import { register as plan } from './plan.ts'; import { register as publish } from './publish.ts'; import { register as registry } from './registry.ts'; import { register as report } from './report.ts'; -import { register as test } from './test.ts'; export const commands: ((program: Command) => void)[] = [ registry, plan, build, - test, publish, displayVersions, report, diff --git a/packages/cli-ci/src/commands/test.ts b/packages/cli-ci/src/commands/test.ts deleted file mode 100644 index 227ba5d7..00000000 --- a/packages/cli-ci/src/commands/test.ts +++ /dev/null @@ -1,40 +0,0 @@ -// plx-ci test : the app's compose stack with the -// candidate image from the registry, migrate, up, the app's test script against -// it, and on success the tag test- (§ 8 PLX-Delivery). Runs on a large -// runner in a checkout with the app's dependencies installed. From the -// environment: CI_STRATEGY, CI_REGISTRY; PLEXUS_LOOPBACK_PORT (default 3000), the port the stack -// publishes the app on. Prints the tested digest, and writes it to -// GITHUB_OUTPUT when that is set. -// -// plx-ci test my-app d135e9416e1cf4e8 5b052598a4d84145 -import { appendFileSync } from 'node:fs'; -import { resolve } from 'node:path'; -import type { Command } from 'commander'; -import { test } from '../core/test.ts'; -import { contextOf } from '../program.ts'; -import { registryFor, settings, withStrategy } from './shared.ts'; - -export function register(program: Command): void { - withStrategy(program.command('test')) - .description('run one app’s tests against its compose stack on the candidate image, and tag the image tested') - .argument('', 'the app, apps/ in the checkout') - .argument('', 'Turbo’s hash of the app’s build task, the candidate’s tag') - .argument('', 'Turbo’s hash of the app’s test task, the tag on success') - .option('-C, --dir ', 'the checkout to read', '.') - .action( - async (app: string, build: string, hash: string, opts: { strategy?: string; dir: string }, command: Command) => { - const ctx = contextOf(command); - const result = await test(ctx, { - app, - build, - hash, - dir: resolve(opts.dir), - registry: registryFor(settings(opts)), - port: process.env.PLEXUS_LOOPBACK_PORT ? Number(process.env.PLEXUS_LOOPBACK_PORT) : undefined, - }); - ctx.result(result, (r) => r.digest ?? ''); - if (process.env.GITHUB_OUTPUT && result.digest) - appendFileSync(process.env.GITHUB_OUTPUT, `digest=${result.digest}\n`); - }, - ); -} diff --git a/packages/cli-ci/src/core/test.test.ts b/packages/cli-ci/src/core/test.test.ts deleted file mode 100644 index 8a5a382c..00000000 --- a/packages/cli-ci/src/core/test.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import assert from 'node:assert/strict'; -import { test } from 'node:test'; -import { composeArgs, overrideEnv, specEnv } from './test.ts'; - -test('the override’s x-plexus-ci.env is the specs’ environment, beside the port and the base URL', () => { - const env = overrideEnv( - 'x-plexus-ci:\n env:\n DATABASE_URL: postgres://u:p@127.0.0.1:5432/db\nservices:\n db: {}\n', - ); - assert.deepEqual(env, { DATABASE_URL: 'postgres://u:p@127.0.0.1:5432/db' }); - assert.deepEqual(specEnv(3000, env), { - CI: '1', - PLEXUS_LOOPBACK_PORT: '3000', - E2E_BASE_URL: 'http://127.0.0.1:3000', - DATABASE_URL: 'postgres://u:p@127.0.0.1:5432/db', - }); - assert.deepEqual(overrideEnv('services: {}\n'), {}); - assert.throws(() => overrideEnv('x-plexus-ci:\n env: nope\n'), /not a map/); -}); - -test('every stack command names the project and both files', () => { - assert.deepEqual(composeArgs('ci-my-app'), [ - 'compose', - '--project-name', - 'ci-my-app', - '--file', - 'compose.yaml', - '--file', - 'compose.ci.yaml', - ]); -}); diff --git a/packages/cli-ci/src/core/test.ts b/packages/cli-ci/src/core/test.ts deleted file mode 100644 index cf8c177b..00000000 --- a/packages/cli-ci/src/core/test.ts +++ /dev/null @@ -1,131 +0,0 @@ -// Test one app's candidate image (§ 8 PLX-Delivery): on a large runner, the -// app's own compose.yaml with the CI override beside it, the candidate -// pulled from the registry, `migrate` once, `up --wait`, then the -// app's test script against the running stack, and on success the tag -// test- on the very manifest that was tested. The specs run on the -// runner, outside the containers: the override's `x-plexus-ci.env` says how -// they reach the stack (the database's published port), beside what every -// app gets: CI, PLEXUS_LOOPBACK_PORT and E2E_BASE_URL, the app's loopback origin. -import { join } from 'node:path'; -import type { Context } from '@plexus-ms/lib'; -import { run, UsageError } from '@plexus-ms/lib'; -import { parse } from 'yaml'; -import { candidateRef, digestOf, findTag, type Registry } from './registry.ts'; - -export const OVERRIDE = 'compose.ci.yaml'; - -export interface TestOptions { - app: string; - /** Turbo's hash of the app's test task; the tag the tested image gets. */ - hash: string; - /** Turbo's hash of the app's build task; the candidate's tag. */ - build: string; - /** The port the stack publishes the app on; the override reads it as PLEXUS_LOOPBACK_PORT. */ - port?: number; - /** The checkout; default the cwd. */ - dir?: string; - /** Where the candidates live. */ - registry: Registry; -} - -export interface TestResult { - app: string; - hash: string; - image: string; - tag: string; - digest?: string; - /** Seconds the stack took to come up, and the tests to run. */ - stackSeconds: number; - testSeconds: number; -} - -/** What the override tells the runner side: `x-plexus-ci.env`, the specs' environment. */ -export function overrideEnv(text: string): Record { - // The override may carry compose's own tags (`!override`), which are not ours to resolve. - const data: unknown = parse(text, { logLevel: 'silent' }); - const x = data !== null && typeof data === 'object' ? (data as Record)['x-plexus-ci'] : undefined; - const env = x !== null && typeof x === 'object' ? (x as Record).env : undefined; - if (env === undefined) return {}; - if (env === null || typeof env !== 'object') throw new UsageError(`${OVERRIDE}: x-plexus-ci.env is not a map`); - return Object.fromEntries(Object.entries(env as Record).map(([k, v]) => [k, String(v)])); -} - -/** The `docker compose` prefix every stack command shares: the project, both files. */ -export function composeArgs(project: string): string[] { - return ['compose', '--project-name', project, '--file', 'compose.yaml', '--file', OVERRIDE]; -} - -/** The environment the specs run with. */ -export function specEnv(port: number, fromOverride: Record): NodeJS.ProcessEnv { - return { - CI: '1', - PLEXUS_LOOPBACK_PORT: String(port), - E2E_BASE_URL: `http://127.0.0.1:${port}`, - ...fromOverride, - }; -} - -export async function test(ctx: Context, options: TestOptions): Promise { - const { app, hash, build, registry } = options; - const dir = options.dir ?? '.'; - const port = options.port ?? 3000; - const appDir = join(dir, 'apps', app); - const composeDir = join(appDir, 'docker'); - const project = `ci-${app}`; - - const image = - (await findTag(ctx, registry, app, `build-${build}`)) ?? - (ctx.dryRun ? candidateRef(registry, app, `build-${build}`) : undefined); - if (image === undefined) - throw new Error(`${app}:build-${build} is in no registry here; the build failed or never ran`); - const tag = `test-${hash}`; - - const fromOverride = overrideEnv(await ctx.readFile(join(composeDir, OVERRIDE))); - const composeEnv = { PLEXUS_DEPLOYMENT_IMAGE: image, PLEXUS_LOOPBACK_PORT: String(port) }; - const compose = (args: string[]) => - run('docker', [...composeArgs(project), ...args], { cwd: composeDir, env: composeEnv }); - - let stackSeconds = 0; - let testSeconds = 0; - let t = Date.now(); - try { - ctx.say(`test: ${app} ${image} as ${project} on :${port}`); - await ctx.apply([ - compose(['--profile', 'migrate', 'pull', '--quiet']), - compose(['run', '--rm', '--quiet-pull', 'migrate']), - compose(['up', '--detach', '--wait', '--quiet-pull']), - ]); - stackSeconds = Math.round((Date.now() - t) / 1000); - ctx.say(`test: stack up ${stackSeconds}s`); - t = Date.now(); - // The specs' output is the job's log: inherited, not captured. - await ctx.apply([run('pnpm', ['test'], { cwd: appDir, env: specEnv(port, fromOverride), interactive: true })]); - testSeconds = Math.round((Date.now() - t) / 1000); - ctx.say(`test: tests ${testSeconds}s`); - } catch (error) { - if (!ctx.dryRun) { - const logs = await ctx - .read('docker', [...composeArgs(project), 'logs', '--no-color', '--tail', '200'], { - cwd: composeDir, - env: composeEnv, - }) - .catch(() => ''); - if (logs) ctx.say(`test: the stack's last lines\n${logs}`); - } - throw error; - } finally { - await ctx.apply([compose(['--profile', 'migrate', 'down', '--volumes', '--remove-orphans', '--timeout', '10'])]); - } - - // The tag goes on the manifest that was tested, copied into this week's - // registry when the candidate came from the previous one. - await ctx.apply([ - run('docker', ['buildx', 'imagetools', 'create', '--tag', candidateRef(registry, app, tag), image]), - ]); - const result: TestResult = { app, hash, image, tag, stackSeconds, testSeconds }; - if (!ctx.dryRun) { - result.digest = await digestOf(ctx, registry, app, tag); - ctx.say(`test: ${app} ${tag} -> ${result.digest ?? ''}`); - } - return result; -} diff --git a/packages/cli-ci/src/program.test.ts b/packages/cli-ci/src/program.test.ts index f6dbf4a8..fdd12de2 100644 --- a/packages/cli-ci/src/program.test.ts +++ b/packages/cli-ci/src/program.test.ts @@ -39,14 +39,13 @@ test('the universal commands take --strategy, and hybrid holds the instances’ 'registry', 'plan', 'build', - 'test', 'publish', 'display-versions', 'tag-display-version', 'report', 'hybrid', ]); - for (const name of ['registry', 'plan', 'build', 'test', 'publish', 'report']) { + for (const name of ['registry', 'plan', 'build', 'publish', 'report']) { const command = program.commands.find((c) => c.name() === name); assert.ok( command?.options.some((o) => o.long === '--strategy'), From 750368783368be752c9f6eece76ed8513fb9eeb4 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 21:48:43 +0100 Subject: [PATCH 125/194] Remove plx-ci report, which compared the two image builds of plan's repro mode MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The image is a copy of the build output, made once per hash by publish (§ 4.2, § 4.4 of the Decisions); no job builds an image twice to compare, and plan loses its modes with this. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/commands/index.ts | 11 +---------- packages/cli-ci/src/commands/report.ts | 26 -------------------------- packages/cli-ci/src/program.test.ts | 3 +-- 3 files changed, 2 insertions(+), 38 deletions(-) delete mode 100644 packages/cli-ci/src/commands/report.ts diff --git a/packages/cli-ci/src/commands/index.ts b/packages/cli-ci/src/commands/index.ts index 1862c775..eeaa4b76 100644 --- a/packages/cli-ci/src/commands/index.ts +++ b/packages/cli-ci/src/commands/index.ts @@ -11,14 +11,5 @@ import { register as hybrid } from './hybrid.ts'; import { register as plan } from './plan.ts'; import { register as publish } from './publish.ts'; import { register as registry } from './registry.ts'; -import { register as report } from './report.ts'; -export const commands: ((program: Command) => void)[] = [ - registry, - plan, - build, - publish, - displayVersions, - report, - hybrid, -]; +export const commands: ((program: Command) => void)[] = [registry, plan, build, publish, displayVersions, hybrid]; diff --git a/packages/cli-ci/src/commands/report.ts b/packages/cli-ci/src/commands/report.ts deleted file mode 100644 index 0104c33c..00000000 --- a/packages/cli-ci/src/commands/report.ts +++ /dev/null @@ -1,26 +0,0 @@ -// plx-ci report --mode : what the registry holds after a -// build run, every app's digest and, in repro mode, the two builds of each -// app compared layer by layer (§ 4 PLX-Delivery). Needs the registry -// reachable here (`plx-ci registry`). From the environment: CI_STRATEGY, -// CI_REGISTRY, GITHUB_RUN_ID. -// -// plx-ci report --mode repro "$MATRIX" -import type { Command } from 'commander'; -import { type Leg, type Mode, report } from '../core/plan.ts'; -import { contextOf } from '../program.ts'; -import { need, registryFor, settings, withStrategy } from './shared.ts'; - -export function register(program: Command): void { - withStrategy(program.command('report')) - .description('the digests the registry holds for a run’s matrix, and in repro mode the layer-by-layer comparison') - .argument('', 'the plan’s matrix, JSON') - .requiredOption('--mode ', 'build, force or repro') - .action(async (matrix: string, opts: { strategy?: string; mode: Mode }, command: Command) => { - const ctx = contextOf(command); - const legs = JSON.parse(matrix) as Leg[]; - const result = await report(ctx, registryFor(settings(opts)), legs, opts.mode, need('GITHUB_RUN_ID')); - // The report narrates every digest and difference as it reads them; the - // result repeats nothing unless asked for as JSON. - ctx.result(result, () => ''); - }); -} diff --git a/packages/cli-ci/src/program.test.ts b/packages/cli-ci/src/program.test.ts index fdd12de2..37554999 100644 --- a/packages/cli-ci/src/program.test.ts +++ b/packages/cli-ci/src/program.test.ts @@ -42,10 +42,9 @@ test('the universal commands take --strategy, and hybrid holds the instances’ 'publish', 'display-versions', 'tag-display-version', - 'report', 'hybrid', ]); - for (const name of ['registry', 'plan', 'build', 'publish', 'report']) { + for (const name of ['registry', 'plan', 'build', 'publish']) { const command = program.commands.find((c) => c.name() === name); assert.ok( command?.options.some((o) => o.long === '--strategy'), From 4b57156ba4d1ed892544d196d86035432e546a5d Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 21:49:13 +0100 Subject: [PATCH 126/194] plx-ci plan: one leg per app for its e2e job, the build hash alone from the lockfile's Turbo in mise's environment, the image looked up in the forge's registry The plan refuses without PLX_PLATFORM, computes no test hash, and says per app its suite, what publish makes the image from, and whether it builds it. The test's marker fixture quotes the package name, as YAML wants a value starting with @. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/commands/plan.ts | 62 +++--- packages/cli-ci/src/core/plan.test.ts | 9 +- packages/cli-ci/src/core/plan.ts | 300 ++++++++++++-------------- 3 files changed, 173 insertions(+), 198 deletions(-) diff --git a/packages/cli-ci/src/commands/plan.ts b/packages/cli-ci/src/commands/plan.ts index 9de15309..ec11fe1c 100644 --- a/packages/cli-ci/src/commands/plan.ts +++ b/packages/cli-ci/src/commands/plan.ts @@ -1,30 +1,31 @@ -// plx-ci plan [--test] [--deploy] [apps...]: the hashes and the look-ups -// (§ 8 PLX-Delivery), printed as the matrix the large jobs fan out over, each -// leg naming its runner from the strategy and what it owes there, the build, -// the test or both, and the apps with their hashes for the publish. With --deploy, the environment the run -// releases into and each app's target there, from a checkout of the platform -// repo's inventory. Launches nothing: under hybrid, `plx-ci hybrid -// create-instances` reads the matrix next. Writes matrix=, apps=, deploys= -// and environment= to GITHUB_OUTPUT when that is set. -// From the environment: CI_STRATEGY, CI_REGISTRY, CI_OVERLAY; GITHUB_RUN_ID -// and GITHUB_RUN_ATTEMPT (they name the instances under hybrid); for -// --deploy GITHUB_EVENT_NAME, GITHUB_REF_NAME, GITHUB_SHA and IMAGE_PREFIX. +// plx-ci plan [--deploy] [apps...]: the build hashes and the look-ups in the +// forge's registry (§ 8 PLX-Delivery), printed as the matrix the e2e jobs and +// the publishes fan out over, one leg per app, each naming the runner of its +// e2e job from the strategy, its suite, and whether publish builds its image +// or tags the one there, and from what. With --deploy, the environment the +// run deploys into and each app's target there, from a checkout of the +// operations repo's inventory. Launches nothing: under hybrid, `plx-ci hybrid +// create-instances` reads the matrix next. Writes matrix=, deploys= and +// environment= to GITHUB_OUTPUT when that is set. Runs in the repo's mise +// environment, which gives it PLX_PLATFORM as it gives it to the build. +// From the environment: CI_STRATEGY; PLX_PLATFORM; IMAGE_PREFIX or +// GITHUB_REPOSITORY, where the images live; GITHUB_RUN_ID and +// GITHUB_RUN_ATTEMPT (they name the instances under hybrid); for --deploy +// GITHUB_EVENT_NAME, GITHUB_REF_NAME and GITHUB_SHA. crane on the PATH, +// logged in to the forge's registry. // -// plx-ci --json plan --test -// plx-ci plan --test --deploy --inventory platform/inventory -// plx-ci plan --mode repro website +// plx-ci --json plan +// plx-ci plan --deploy --inventory operations/inventory import { appendFileSync } from 'node:fs'; import { resolve } from 'node:path'; import { readDeployTargets, targetsIn } from '@plexus-ms/lib'; import type { Command } from 'commander'; -import { environmentOf, type Mode, plan, readHashes, verbsOf } from '../core/plan.ts'; +import { environmentOf, plan, readHashes } from '../core/plan.ts'; import { contextOf } from '../program.ts'; -import { imagePrefix, need, registryFor, settings, withStrategy } from './shared.ts'; +import { imagePrefix, need, settings, withStrategy } from './shared.ts'; interface Opts { strategy?: string; - mode: Mode; - test?: boolean; deploy?: boolean; environment?: string; inventory: string; @@ -34,18 +35,12 @@ interface Opts { export function register(program: Command): void { withStrategy(program.command('plan')) .description( - 'compute the build and test hashes, look them up in the registry, and print the builds, tests and deploys the run needs', + 'compute the build hashes, look the images up in the forge’s registry, and print the e2e jobs, publishes and deploys the run needs', ) .argument('[apps...]', 'the apps (default: every directory under apps/)') - .option( - '--mode ', - 'build (skip what the registry holds), force (build all), repro (two no-cache builds per app)', - 'build', - ) - .option('--test', 'plan the tests too, for the apps with a test task') .option('--deploy', 'plan the deploys too: the environment and each app’s target in it') - .option('--environment ', 'the environment to release into (default: from the branch, main or develop)') - .option('--inventory ', 'the platform repo’s inventory, for --deploy', 'platform/inventory') + .option('--environment ', 'the environment to deploy into (default: from the branch, main or develop)') + .option('--inventory ', 'the operations repo’s inventory, for --deploy', 'platform/inventory') .option('-C, --dir ', 'the checkout to read', '.') .action(async (apps: string[], opts: Opts, command: Command) => { const ctx = contextOf(command); @@ -62,13 +57,11 @@ export function register(program: Command): void { const environment = opts.deploy ? environmentOf(env.GITHUB_EVENT_NAME ?? '', env.GITHUB_REF_NAME ?? '', opts.environment) : ''; - const result = await plan(ctx, { + const result = await plan(ctx, dir, { apps: all, - mode: opts.mode, - tests: opts.test ?? false, hashes: await readHashes(ctx, dir, all), strategy: s.strategy, - registry: registryFor(s), + prefix: imagePrefix(), // Only hybrid names anything after the run: its instances. run: s.strategy === 'hybrid' @@ -78,14 +71,16 @@ export function register(program: Command): void { ? { environment, targets: targetsIn(await readDeployTargets(ctx, resolve(opts.inventory)), environment), - prefix: imagePrefix(), sha: need('GITHUB_SHA'), } : undefined, }); ctx.result(result, (r) => [ - ...r.legs.map((l) => `${verbsOf(l)} ${l.app} ${l.hash}${l.test ? ` ${l.test}` : ''} ${l.runner}`), + ...r.legs.map( + (l) => + `e2e ${l.app} ${l.hash} ${l.suite || '(no suite)'} ${l.runner}; publish ${l.build ? `builds from ${l.context === 'output' ? 'the build output' : 'a pruned context'}` : 'tags'}`, + ), ...r.deploys.map((l) => `deploy ${l.app} ${l.host} ${l.image}`), ].join('\n'), ); @@ -94,7 +89,6 @@ export function register(program: Command): void { env.GITHUB_OUTPUT, [ `matrix=${JSON.stringify(result.legs)}`, - `apps=${JSON.stringify(result.apps)}`, `deploys=${JSON.stringify(result.deploys)}`, `environment=${result.environment}`, '', diff --git a/packages/cli-ci/src/core/plan.test.ts b/packages/cli-ci/src/core/plan.test.ts index 20964b8d..ca2aad23 100644 --- a/packages/cli-ci/src/core/plan.test.ts +++ b/packages/cli-ci/src/core/plan.test.ts @@ -48,7 +48,7 @@ const LOCKFILE = [ /** An app's directory: its package.json and the marker `plx new` writes, with the templates it lists. */ const app = (name: string, templates: string[]): Tree => ({ 'package.json': JSON.stringify({ name }), - 'PLEXUS.md': `---\ntemplates: [${templates.join(', ')}]\nname: ${name}\nprofile: stateless\n---\n`, + 'PLEXUS.md': `---\ntemplates: [${templates.join(', ')}]\nname: '${name}'\nprofile: stateless\n---\n`, }); /** A suite at e2e/, the package the template e2e-playwright renders. */ @@ -75,7 +75,12 @@ const REPO: Tree = { }; /** What a context narrated so far. */ -const narrated = (ctx: Context): string => String((ctx.io.stderr as PassThrough).read() ?? ''); +function narrated(ctx: Context): string { + const chunks: string[] = []; + for (let chunk = (ctx.io.stderr as PassThrough).read(); chunk !== null; chunk = (ctx.io.stderr as PassThrough).read()) + chunks.push(String(chunk)); + return chunks.join(''); +} test('hashesOf keeps the build hash of each app’s package and nothing else', () => { assert.deepEqual(hashes, [ diff --git a/packages/cli-ci/src/core/plan.ts b/packages/cli-ci/src/core/plan.ts index 8fd89671..578e2eca 100644 --- a/packages/cli-ci/src/core/plan.ts +++ b/packages/cli-ci/src/core/plan.ts @@ -1,32 +1,44 @@ -// The plan of a run (§ 8 PLX-Delivery): for every app, the build and the test -// hash from one Turbo dry run and a look-up in the registry, which leaves one -// leg per app that owes something: the build where its image is missing, the -// test where its test tag is, both on one machine, the test after the build -// (two build legs without cache in repro mode, which plans no test). Each leg -// names the runner its job asks for, from the strategy: the forge's, a large -// slot, or, under hybrid, the one label of an instance `hybrid -// create-instances` then creates for it. With a deploy asked for, the plan also says which -// environment the run releases into and where each app deploys there, from -// the platform repo's inventory. The plan decides and launches nothing: its -// result is the matrices the jobs fan out over. +// The plan of a run (§ 8 PLX-Delivery): every app's build hash from one Turbo +// dry run, and a look-up of `build-` in the forge's registry, which +// leaves one leg per app. Every app's leg runs its e2e job, whatever the +// registry holds: a suite or a test file is no input of the app's build, so +// only Turbo's cache in that job knows whether there is anything to run. What +// the registry decides is publish's share of the leg: `build`, the image is +// missing and publish makes it, or the image is there and publish adds the +// commit's tag. A leg also says what publish makes the image from, `output`, +// the directory the app's build leaves (an app from app-nextjs, by its +// marker), or `pruned`, a pruned context its Dockerfile builds itself from (§ +// 4 PLX-Delivery); and the directory of the app's E2E suite, empty for none, +// for its e2e job's browser. Each leg names the runner of its e2e job, from +// the strategy: the forge's, a large slot, or, under hybrid, the one label of +// an instance `hybrid create-instances` then creates for it. With a deploy +// asked for, the plan also says which environment the run deploys into and +// where each app deploys there, from the operations repo's inventory. The +// plan decides and launches nothing: its result is the matrices the jobs fan +// out over. No test hash is computed and nothing records that an image was +// tested: that publish follows the e2e job is the order of the jobs. +// +// The hash is the build's own only when the dry run sees what the build sees: +// the Turbo the lockfile has, run with no node_modules, and the environment +// of the repo's mise, which gives PLX_PLATFORM to every task (§ 1.10 of the +// app's build hash). Without PLX_PLATFORM the plan refuses: its hash would be +// one no build ever has. import type { Context, EnvironmentTargets } from '@plexus-ms/lib'; -import { UsageError } from '@plexus-ms/lib'; -import { digestOf, findTag, imageName, layersOf, type Registry } from './registry.ts'; +import { MARKER_FILE, parseMarkerConfig, UsageError } from '@plexus-ms/lib'; +import { parseAllDocuments } from 'yaml'; +import { craneDigest, imageName } from './registry.ts'; import { runnerOf, type Strategy } from './strategy.ts'; -export type Mode = 'build' | 'force' | 'repro'; - -/** One app's hashes: of its build task, and of its test task when it has one. */ +/** One app's build hash, Turbo's hash of its package's build task. */ export interface Hash { app: string; hash: string; - test?: string; } /** Turbo's marker for a task whose script the package does not define. */ const NONEXISTENT = ''; -/** The build and test hashes from Turbo's dry run (`turbo run build test --dry-run=json`), per app, by its package's name. */ +/** The build hashes from Turbo's dry run (`turbo run build --dry-run=json`), per app, by its package's name. */ export function hashesOf(dryRun: string, packages: Record): Hash[] { const data = JSON.parse(dryRun) as { tasks?: { taskId: string; package: string; hash: string; command?: string }[]; @@ -34,9 +46,7 @@ export function hashesOf(dryRun: string, packages: Record): Hash const tasks = (data.tasks ?? []).filter((t) => t.command !== NONEXISTENT); return Object.entries(packages).flatMap(([app, name]) => { const build = tasks.find((t) => t.package === name && t.taskId.endsWith('#build')); - if (!build) return []; - const test = tasks.find((t) => t.package === name && t.taskId.endsWith('#test')); - return [{ app, hash: build.hash, ...(test ? { test: test.hash } : {}) }]; + return build ? [{ app, hash: build.hash }] : []; }); } @@ -47,73 +57,124 @@ export async function packageName(ctx: Context, dir: string, app: string): Promi return pkg.name; } -/** Turbo at the version the repo's root pins. */ +/** + * Turbo at the version the repo's lockfile has for its root, `turbo@`, + * which npx runs without an install. pnpm 11 and later write the package + * manager's own document before the workspace's; the workspace's is the one + * whose root lists turbo. + */ export async function turboOf(ctx: Context, dir: string): Promise { - const pkg = JSON.parse(await ctx.readFile(`${dir}/package.json`)) as { devDependencies?: Record }; - return `turbo@${pkg.devDependencies?.turbo ?? 'latest'}`; + const text = await ctx.readFile(`${dir}/pnpm-lock.yaml`); + for (const doc of parseAllDocuments(text)) { + const lock = (Array.isArray(doc) ? undefined : doc.toJS()) as { + importers?: Record }>; + } | null; + const version = lock?.importers?.['.']?.devDependencies?.turbo?.version; + if (version) return `turbo@${version}`; + } + throw new UsageError('pnpm-lock.yaml locks no turbo for the workspace root, which the repo’s verbs run'); } -export async function readHashes(ctx: Context, dir: string, apps: string[]): Promise { +/** The build hashes of `apps`, from the dry run of the Turbo the lockfile has, in `env`, the repo's mise environment. */ +export async function readHashes( + ctx: Context, + dir: string, + apps: string[], + env: NodeJS.ProcessEnv = process.env, +): Promise { + if (!env.PLX_PLATFORM) + throw new UsageError( + 'PLX_PLATFORM is empty: the plan runs in the repo’s mise environment, as its build does (after `mise install`, or under `mise exec`), or its hashes are ones no build has', + ); const packages: Record = {}; for (const app of apps) packages[app] = await packageName(ctx, dir, app); - const out = await ctx.read('npx', ['--yes', await turboOf(ctx, dir), 'run', 'build', 'test', '--dry-run=json'], { - cwd: dir, - }); + const turbo = await turboOf(ctx, dir); + const out = await ctx.read('npx', ['--yes', turbo, 'run', 'build', '--dry-run=json'], { cwd: dir, env }); return hashesOf(out, packages); } +/** What publish makes an app's image from: the directory its build leaves, or a pruned context its own Dockerfile builds in. */ +export type ImageContext = 'output' | 'pruned'; + +/** An app's image context: `output` where its marker lists the template app-nextjs, whose Dockerfile only copies the build output; `pruned` otherwise. */ +export async function imageContextOf(ctx: Context, dir: string, app: string): Promise { + let marker: string; + try { + marker = await ctx.readFile(`${dir}/apps/${app}/${MARKER_FILE}`); + } catch { + return 'pruned'; + } + return (parseMarkerConfig(marker).templates ?? []).includes('app-nextjs') ? 'output' : 'pruned'; +} + +/** The directory of the E2E suite of the package `name`, `e2e/`: a package there with an `e2e` script that depends on it; empty for none. */ +export async function suiteOf(ctx: Context, dir: string, name: string): Promise { + let entries: { name: string; directory: boolean }[] = []; + try { + entries = await ctx.readDir(`${dir}/e2e`); + } catch { + return ''; + } + for (const entry of entries.filter((e) => e.directory).sort((a, b) => a.name.localeCompare(b.name))) { + let pkg: { scripts?: Record; dependencies?: object; devDependencies?: object }; + try { + pkg = JSON.parse(await ctx.readFile(`${dir}/e2e/${entry.name}/package.json`)); + } catch { + continue; + } + if (pkg.scripts?.e2e && (name in (pkg.dependencies ?? {}) || name in (pkg.devDependencies ?? {}))) + return `e2e/${entry.name}`; + } + return ''; +} + /** The run a plan is for; names the instances under hybrid. */ export interface Run { runId: string; attempt: string; } -/** - * A large job: one app, the runner it asks for, and what it owes there. `hash` - * is the build hash, the candidate's tag, whether or not the leg builds it. - */ +/** One app of the run: the runner of its e2e job, and what its publish does. */ export interface Leg { app: string; + /** The build hash: the image's tag `build-`. */ hash: string; + /** The runner the app's e2e job asks for. */ runner: string; - n: number; - /** The image is to be built. */ + /** The directory of the app's E2E suite, empty for none. */ + suite: string; + /** What publish makes the image from. */ + context: ImageContext; + /** The forge's registry lacks `build-`: publish builds the image; else it tags the one there. */ build: boolean; - /** The test hash where the candidate is to be tested, else empty. */ - test: string; } -/** A deploy job: one app, where it deploys in the run's environment, and the image the release publishes. */ +/** A deploy job: one app, where it deploys in the run's environment, and the image the run publishes. */ export interface DeployLeg { app: string; host: string; image: string; } -/** The verbs a leg owes, as the plan prints them: `build`, `test`, or `build, test`. */ -export const verbsOf = (leg: Pick): string => - [leg.build ? 'build' : '', leg.test ? 'test' : ''].filter((v) => v !== '').join(', '); - -/** The legs a mode asks for, one per app (two in repro mode), before the registry is consulted and the tests are added. */ -export function legsOf(apps: string[], hashes: Hash[], mode: Mode, strategy: Strategy, run: Run): Leg[] { - return apps.flatMap((app) => { +/** The runner of each app's e2e job, before the checkout and the registry are read. */ +export function legsOf( + apps: string[], + hashes: Hash[], + strategy: Strategy, + run: Run, +): Omit[] { + return apps.map((app) => { const hash = hashes.find((h) => h.app === app)?.hash; if (!hash) throw new UsageError(`no build hash for ${app}; is it an app package of the workspace?`); - const copies = mode === 'repro' ? 2 : 1; - return Array.from({ length: copies }, (_, i) => { - const n = i + 1; - const base = `exo-large-${run.runId}-${app}-${run.attempt}`; - const runner = runnerOf(strategy, 'large', mode === 'repro' ? `${base}-${n}` : base); - return { app, hash, runner, n, build: true, test: '' }; - }); + return { app, hash, runner: runnerOf(strategy, 'large', `exo-large-${run.runId}-${app}-${run.attempt}`) }; }); } /** - * The environment a run releases into (§ 3 PLX-Delivery): `given` when the + * The environment a run deploys into (§ 3 PLX-Delivery): `given` when the * caller stands in for an environment branch, else main is production and * develop is staging, on a push or a run by hand; anything else, a pull - * request among it, releases nowhere. + * request among it, deploys nowhere. */ export function environmentOf(event: string, ref: string, given = ''): string { if (given) return given; @@ -139,130 +200,45 @@ export function deployLegsOf( } export interface Plan { - /** The large jobs to run: per app, the build, the test, or both. */ + /** One per app: what its e2e job and its publish fan out over. */ legs: Leg[]; - /** Every app planned, with its hashes: what the publish fans out over. */ - apps: Hash[]; - /** The environment the run releases into, empty for none. */ + /** The environment the run deploys into, empty for none. */ environment: string; - /** The deploys of the release, empty without an environment. */ + /** The deploys of the run, empty without an environment. */ deploys: DeployLeg[]; - skipped: { app: string; hash: string; ref: string }[]; - skippedTests: { app: string; hash: string; ref: string }[]; } export interface PlanOptions { apps: string[]; - mode: Mode; - /** Plan tests too; off for the build measurements. */ - tests?: boolean; hashes: Hash[]; strategy: Strategy; - registry: Registry; + /** Where the published images live, `ghcr.io/`. */ + prefix: string; run: Run; - /** With a deploy asked for: the environment, its targets, and what names the published image. */ - deploy?: { environment: string; targets: EnvironmentTargets; prefix: string; sha: string }; -} - -export async function plan(ctx: Context, options: PlanOptions): Promise { - const { apps, hashes, mode, strategy, registry, run } = options; - const result: Plan = { - legs: [], - apps: apps.map((app) => { - const h = hashes.find((x) => x.app === app); - if (!h) throw new UsageError(`no build hash for ${app}; is it an app package of the workspace?`); - return h; - }), - environment: options.deploy?.environment ?? '', - deploys: [], - skipped: [], - skippedTests: [], - }; - for (const leg of legsOf(apps, hashes, mode, strategy, run)) { - let build = true; - if (mode === 'build') { - const ref = await findTag(ctx, registry, leg.app, `build-${leg.hash}`); - if (ref !== undefined) { - ctx.say(`${leg.app}: ${ref} exists, nothing to build`); - result.skipped.push({ app: leg.app, hash: leg.hash, ref }); - build = false; - } - } - // The test of an app with a test task, on the machine that builds it or, - // the build being there already, on one that only tests. - let test = (options.tests && mode !== 'repro' && hashes.find((h) => h.app === leg.app)?.test) || ''; - if (test && mode === 'build') { - const ref = await findTag(ctx, registry, leg.app, `test-${test}`); - if (ref !== undefined) { - ctx.say(`${leg.app}: ${ref} exists, nothing to test`); - result.skippedTests.push({ app: leg.app, hash: test, ref }); - test = ''; - } - } - if (build || test) result.legs.push({ ...leg, build, test }); + /** With a deploy asked for: the environment, its targets, and the commit the deploys take. */ + deploy?: { environment: string; targets: EnvironmentTargets; sha: string }; +} + +/** The plan of `dir`, a checkout: a leg per app, its image looked up in the forge's registry, and the deploys. */ +export async function plan(ctx: Context, dir: string, options: PlanOptions): Promise { + const { apps, hashes, strategy, prefix, run } = options; + const result: Plan = { legs: [], environment: options.deploy?.environment ?? '', deploys: [] }; + for (const leg of legsOf(apps, hashes, strategy, run)) { + const ref = `${imageName(prefix, leg.app)}:build-${leg.hash}`; + const build = (await craneDigest(ctx, ref)) === undefined; + ctx.say(`${leg.app}: ${ref} ${build ? 'is missing; publish builds it' : 'exists; publish tags it'}`); + result.legs.push({ + ...leg, + suite: await suiteOf(ctx, dir, await packageName(ctx, dir, leg.app)), + context: await imageContextOf(ctx, dir, leg.app), + build, + }); } if (options.deploy?.environment) { - const { environment, targets, prefix, sha } = options.deploy; + const { environment, targets, sha } = options.deploy; const { legs, without } = deployLegsOf(apps, targets, prefix, sha); result.deploys = legs; for (const app of without) ctx.say(`${app} has no deployment in ${environment}; nothing to deploy`); } return result; } - -export interface Comparison { - app: string; - hash: string; - digest?: string; - /** In repro mode: the two builds' digests and the layers that differ. */ - repro?: { one?: string; two?: string; identical: boolean; layers: number; same: number; differing: string[] }; -} - -/** What the registry holds after a run: every app's digest, and in repro mode the two builds compared layer by layer. */ -export async function report( - ctx: Context, - registry: Registry, - legs: Leg[], - mode: Mode, - runId: string, -): Promise { - const apps = [...new Set(legs.map((l) => l.app))].sort(); - const out: Comparison[] = []; - for (const app of apps) { - const hash = legs.find((l) => l.app === app)?.hash ?? ''; - const c: Comparison = { app, hash, digest: await digestOf(ctx, registry, app, `build-${hash}`) }; - ctx.say(`${app} build-${hash}: ${c.digest ?? 'missing'}`); - if (mode === 'repro') { - const [one, two] = await Promise.all([ - digestOf(ctx, registry, app, `repro-${runId}-1`), - digestOf(ctx, registry, app, `repro-${runId}-2`), - ]); - const identical = one !== undefined && one === two; - const [l1, l2] = identical - ? [[], []] - : await Promise.all([ - layersOf(ctx, registry, app, `repro-${runId}-1`), - layersOf(ctx, registry, app, `repro-${runId}-2`), - ]); - const differing: string[] = []; - const a = l1 ?? []; - const b = l2 ?? []; - for (let i = 0; i < Math.max(a.length, b.length); i++) { - if (a[i]?.digest !== b[i]?.digest) - differing.push( - `layer ${i + 1}: ${a[i]?.digest ?? '-'} (${a[i]?.size ?? '-'}) vs ${b[i]?.digest ?? '-'} (${b[i]?.size ?? '-'})`, - ); - } - c.repro = { one, two, identical, layers: a.length, same: a.length - differing.length, differing }; - if (identical) ctx.say(` reproducible: both builds are ${one}`); - else { - ctx.say( - ` not identical: ${one ?? '-'} vs ${two ?? '-'}; layers: ${a.length} in each, ${a.length - differing.length} identical`, - ); - for (const d of differing) ctx.say(` ${d}`); - } - } - out.push(c); - } - return out; -} From 3edc45f31f3b95e8a7b9dc42da6472135e6c7124 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 21:50:37 +0100 Subject: [PATCH 127/194] Test: plx-ci publish tags an image the forge holds, else builds it from a fresh restore of the build output or, for a Dockerfile of the app's own, from a pruned context, through the runner's Docker or the BuildKit service The plan's fixture checkout moves to src/testing/checkout.ts for both tests, and the fake Io hands a command its environment. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/core/plan.test.ts | 56 +---- packages/cli-ci/src/core/publish.test.ts | 258 ++++++++++++++++------- packages/cli-ci/src/testing/checkout.ts | 59 ++++++ packages/cli-ci/src/testing/fakeIo.ts | 4 +- 4 files changed, 243 insertions(+), 134 deletions(-) create mode 100644 packages/cli-ci/src/testing/checkout.ts diff --git a/packages/cli-ci/src/core/plan.test.ts b/packages/cli-ci/src/core/plan.test.ts index ca2aad23..53ee5e27 100644 --- a/packages/cli-ci/src/core/plan.test.ts +++ b/packages/cli-ci/src/core/plan.test.ts @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import type { PassThrough } from 'node:stream'; import { test } from 'node:test'; import { Context } from '@plexus-ms/lib'; +import { REPO } from '../testing/checkout.ts'; import { fakeIo, notThere, type Tree } from '../testing/fakeIo.ts'; import { deployLegsOf, environmentOf, hashesOf, legsOf, plan, readHashes } from './plan.ts'; @@ -19,61 +20,6 @@ const packages = { website: '@acme/website', 'my-app': '@acme/my-app', solver: ' const hashes = hashesOf(dryRun, packages); const run = { runId: '41', attempt: '1' }; -/** The lockfile of pnpm 11 and later: the package manager's document, then the workspace's. */ -const LOCKFILE = [ - '---', - "lockfileVersion: '9.0'", - 'importers:', - ' .:', - ' packageManagerDependencies:', - ' pnpm:', - ' specifier: 12.21.0', - ' version: 12.21.0', - '---', - "lockfileVersion: '9.0'", - 'importers:', - ' .:', - ' devDependencies:', - ' turbo:', - ' specifier: ^2.9.0', - ' version: 2.11.13', - ' apps/site:', - ' dependencies:', - ' next:', - ' specifier: ^16', - ' version: 16.4.6', - '', -].join('\n'); - -/** An app's directory: its package.json and the marker `plx new` writes, with the templates it lists. */ -const app = (name: string, templates: string[]): Tree => ({ - 'package.json': JSON.stringify({ name }), - 'PLEXUS.md': `---\ntemplates: [${templates.join(', ')}]\nname: '${name}'\nprofile: stateless\n---\n`, -}); - -/** A suite at e2e/, the package the template e2e-playwright renders. */ -const suite = (of: string): Tree => ({ - 'package.json': JSON.stringify({ - name: `${of}-e2e`, - scripts: { e2e: 'playwright test' }, - devDependencies: { [of]: 'workspace:*', '@playwright/test': '^1.65.1' }, - }), -}); - -/** A checkout with three apps: website and my-app from app-nextjs, solver with a Dockerfile of its own; a suite for website only. */ -const REPO: Tree = { - repo: { - 'package.json': JSON.stringify({ devDependencies: { turbo: '^2.9.0' } }), - 'pnpm-lock.yaml': LOCKFILE, - apps: { - website: app('@acme/website', ['app-nextjs']), - 'my-app': app('@acme/my-app', ['app-nextjs']), - solver: app('@acme/solver', []), - }, - e2e: { website: suite('@acme/website'), tools: { 'package.json': JSON.stringify({ name: 'tools' }) } }, - }, -}; - /** What a context narrated so far. */ function narrated(ctx: Context): string { const chunks: string[] = []; diff --git a/packages/cli-ci/src/core/publish.test.ts b/packages/cli-ci/src/core/publish.test.ts index 07bba66f..9f457a19 100644 --- a/packages/cli-ci/src/core/publish.test.ts +++ b/packages/cli-ci/src/core/publish.test.ts @@ -1,99 +1,203 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { Context } from '@plexus-ms/lib'; -import { fakeIo, notThere } from '../testing/fakeIo.ts'; +import { REPO } from '../testing/checkout.ts'; +import { fakeIo, notThere, type Tree } from '../testing/fakeIo.ts'; import { publish } from './publish.ts'; -const own = { kind: 'own' } as const; +const SHA = 'deadbeef'; +const KEY = 'the-apps-key'; -test('a publish copies the tested manifest when the forge’s registry lacks it, and only tags when it is there', async () => { - const calls: string[][] = []; - const io = (there: boolean) => - fakeIo({}, undefined, { - crane: (_cwd, args) => { - calls.push(args); - if (args[0] === 'digest') return there ? 'sha256:abc' : notThere('crane'); - return ''; - }, - curl: (_cwd, args) => (args.at(-1)?.includes(':5000/') ? '' : notThere('curl')), - }); - const options = { - app: 'my-app', - build: 'b1', - test: 't1', - sha: 'deadbeef', - prefix: 'ghcr.io/acme', - registry: own, +/** A command a publish ran: its name, arguments, directory, and the environment it was given beyond the process's. */ +interface Call { + command: string; + args: string[]; + cwd: string; + env?: NodeJS.ProcessEnv; +} + +/** + * The checkout of REPO with the build outputs `outputs` (app → the BUILD_ID a + * restore leaves), and a forge registry holding `holds`; every command is + * recorded. `docker buildx build` writes the digest to its metadata file, as + * BuildKit does; `docker buildx inspect` finds no builder unless `builders` + * names it. + */ +function world(options: { holds?: string[]; outputs?: Record; builders?: string[] } = {}) { + const tree = structuredClone(REPO); + const calls: Call[] = []; + const record = + (command: string, answer: (args: string[]) => string | undefined = () => '') => + (cwd: string, args: string[], _input?: string, env?: NodeJS.ProcessEnv) => { + calls.push({ command, args, cwd, ...(env ? { env } : {}) }); + return answer(args); + }; + const put = (path: string, content: string) => { + const parts = path.split('/').filter(Boolean); + const name = parts.pop() ?? ''; + let node = tree; + for (const part of parts) { + node[part] ??= {}; + node = node[part] as Tree; + } + node[name] = content; }; + const io = fakeIo(tree, undefined, { + crane: record('crane', (args) => + args[0] !== 'digest' ? '' : (options.holds ?? []).includes(args[1] ?? '') ? 'sha256:there' : notThere('crane'), + ), + mise: record('mise', (args) => { + // `mise run build `: the restore leaves the output and its BUILD_ID. + const app = args[2] ?? ''; + const id = options.outputs?.[app]; + if (id !== undefined) put(`/repo/apps/${app}/.next/standalone/apps/${app}/.next/BUILD_ID`, id); + return ''; + }), + docker: record('docker', (args) => { + if (args[1] === 'inspect') return (options.builders ?? []).includes(args[2] ?? '') ? '' : undefined; + const metadata = args[args.indexOf('--metadata-file') + 1]; + if (args[1] === 'build' && metadata) put(metadata, JSON.stringify({ 'containerimage.digest': 'sha256:built' })); + return ''; + }), + npx: record('npx'), + rm: record('rm'), + cp: record('cp'), + mkdir: record('mkdir'), + }); + return { ctx: new Context({}, io), calls }; +} + +const options = { + hash: '0f2a', + sha: SHA, + prefix: 'ghcr.io/Acme', + dir: '/repo', + strategy: 'github' as const, + encryptionKey: KEY, +}; - const copied = await publish(new Context({}, io(false)), options); - assert.equal(copied.copied, true); - assert.deepEqual(copied.tags, ['build-b1', 'deadbeef', 'test-t1']); +const buildOf = (calls: Call[]) => calls.find((c) => c.command === 'docker' && c.args[1] === 'build'); + +test('an image the forge’s registry holds gets the commit’s tag, and nothing is built or restored', async () => { + const { ctx, calls } = world({ holds: ['ghcr.io/acme/website:build-0f2a'] }); + const result = await publish(ctx, { ...options, app: 'website' }); + assert.deepEqual(result, { + app: 'website', + image: 'ghcr.io/acme/website', + built: false, + tags: ['build-0f2a', SHA], + }); assert.deepEqual( - calls.filter((c) => c[0] !== 'digest'), + calls.map((c) => [c.command, ...c.args]), [ - ['copy', '--insecure', 'localhost:5000/my-app:test-t1', 'ghcr.io/acme/my-app:build-b1'], - ['tag', 'ghcr.io/acme/my-app:build-b1', 'deadbeef'], - ['tag', 'ghcr.io/acme/my-app:build-b1', 'test-t1'], + ['crane', 'digest', 'ghcr.io/acme/website:build-0f2a'], + ['crane', 'tag', 'ghcr.io/acme/website:build-0f2a', SHA], ], ); +}); - calls.length = 0; - const tagged = await publish(new Context({}, io(true)), { ...options, test: undefined }); - assert.equal(tagged.copied, false); - assert.deepEqual( - calls.filter((c) => c[0] !== 'digest'), - [['tag', 'ghcr.io/acme/my-app:build-b1', 'deadbeef']], - ); +test('a missing image of an app from app-nextjs: a fresh restore of its output through the verb, copied into the image', async () => { + const { ctx, calls } = world({ outputs: { website: '0f2a' } }); + const result = await publish(ctx, { ...options, app: 'website' }); + assert.equal(result.built, true); + assert.equal(result.digest, 'sha256:built'); + assert.deepEqual(result.tags, ['build-0f2a', SHA]); + const order = calls.filter((c) => c.command !== 'crane').map((c) => `${c.command} ${c.args.slice(0, 2).join(' ')}`); + assert.deepEqual(order, ['rm -rf /repo/apps/website/.next/standalone', 'mise run build', 'docker buildx build']); + // The repo's own verb, in the checkout, with the key a build that misses the cache needs. + const restore = calls.find((c) => c.command === 'mise'); + assert.deepEqual(restore?.args, ['run', 'build', 'website']); + assert.equal(restore?.cwd, '/repo'); + assert.equal(restore?.env?.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, KEY); + const build = buildOf(calls); + assert.deepEqual(build?.args.slice(0, 7), [ + 'buildx', + 'build', + '/repo/apps/website/.next/standalone', + '--file', + '/repo/apps/website/docker/Dockerfile', + '--platform', + 'linux/amd64', + ]); + const args = build?.args.join(' ') ?? ''; + assert.match(args, /--build-arg APP=website/); + assert.match(args, /--tag ghcr\.io\/acme\/website:build-0f2a --tag ghcr\.io\/acme\/website:deadbeef/); + assert.match(args, /--output type=image,push=true,rewrite-timestamp=true,oci-mediatypes=true/); + assert.match(args, /--provenance=false --sbom=false/); + // No layer cache, no key and no package token: the build output holds what the image runs. + assert.doesNotMatch(args, /--cache-from|--cache-to|:cache|--secret|BUILD_HASH/); + // Under github the runner's own Docker builds: no builder is made. + assert.doesNotMatch(args, /--builder/); + assert.ok(!calls.some((c) => c.command === 'docker' && c.args[1] === 'create')); + assert.equal(build?.env?.SOURCE_DATE_EPOCH, '0'); }); -test('a publish without the tested tag in the sidecar is an error', async () => { - const io = fakeIo({}, undefined, { - crane: (_cwd, args) => (args[0] === 'digest' ? notThere('crane') : ''), - curl: () => notThere('curl'), - }); +test('under on-prem and hybrid the image is built by the BuildKit service on the runner host', async () => { + for (const strategy of ['on-prem', 'hybrid'] as const) { + const { ctx, calls } = world({ outputs: { website: '0f2a' } }); + await publish(ctx, { ...options, strategy, app: 'website' }); + assert.deepEqual( + calls.filter((c) => c.command === 'docker' && c.args[1] !== 'build').map((c) => c.args), + [ + ['buildx', 'inspect', 'plexus-buildkit'], + ['buildx', 'create', '--name', 'plexus-buildkit', '--driver', 'remote', 'tcp://127.0.0.1:1234'], + ], + ); + assert.match(buildOf(calls)?.args.join(' ') ?? '', /--builder plexus-buildkit/); + } + // A builder of the name made by an earlier publish on the machine is used as it is; BUILDKIT_HOST names another service. + const { ctx, calls } = world({ outputs: { website: '0f2a' }, builders: ['plexus-buildkit'] }); + await publish(ctx, { ...options, strategy: 'on-prem', app: 'website', buildkit: 'tcp://127.0.0.1:4321' }); + assert.ok(!calls.some((c) => c.args[1] === 'create')); + const other = world({ outputs: { website: '0f2a' } }); + await publish(other.ctx, { ...options, strategy: 'on-prem', app: 'website', buildkit: 'tcp://127.0.0.1:4321' }); + assert.ok(other.calls.some((c) => c.args.join(' ').endsWith('--driver remote tcp://127.0.0.1:4321'))); +}); + +test('an output whose BUILD_ID is not the plan’s hash is not published under it', async () => { + const { ctx, calls } = world({ outputs: { website: '9999' } }); await assert.rejects( - publish(new Context({}, io), { app: 'a', build: 'b', test: 't', sha: 's', prefix: 'ghcr.io/o', registry: own }), - /a:test-t is in no registry here; the tests did not pass/, + publish(ctx, { ...options, app: 'website' }), + /apps\/website\/\.next\/standalone holds the build 9999, not 0f2a/, ); + assert.equal(buildOf(calls), undefined); }); -test('where the candidates live in the forge’s registry, the tested manifest only gets the commit’s tag', async () => { - const calls: string[][] = []; - const io = (tested: boolean) => - fakeIo({}, undefined, { - crane: (_cwd, args) => { - calls.push(args); - if (args[0] === 'digest') return tested ? 'sha256:abc' : notThere('crane'); - return ''; - }, - }); - const options = { - app: 'website', - build: 'b1', - test: 't1', - sha: 'deadbeef', - prefix: 'ghcr.io/plexus-ms-tenant', - registry: { kind: 'ghcr', prefix: 'ghcr.io/plexus-ms-tenant' } as const, - }; - const result = await publish(new Context({}, io(true)), options); - assert.equal(result.copied, false); - assert.deepEqual(result.tags, ['build-b1', 'test-t1', 'deadbeef']); - assert.deepEqual(calls, [ - ['digest', 'ghcr.io/plexus-ms-tenant/website:test-t1'], - ['tag', 'ghcr.io/plexus-ms-tenant/website:test-t1', 'deadbeef'], - ]); - await assert.rejects(publish(new Context({}, io(false)), options), /website:test-t1 is in no registry here/); +test('an output without BUILD_ID under apps/ is not published: the Dockerfile would start nothing', async () => { + const { ctx, calls } = world({ outputs: {} }); + await assert.rejects(publish(ctx, { ...options, app: 'website' }), /no apps\/website\/\.next\/BUILD_ID/); + assert.equal(buildOf(calls), undefined); }); -test('a dry run publishes where crane is missing, on a placeholder', async () => { - const io = fakeIo({}, undefined, { - crane: () => { - throw Object.assign(new Error('spawn crane ENOENT'), { code: 'ENOENT' }); - }, - }); - const options = { app: 'website', build: 'b1', test: 't1', sha: 'deadbeef', prefix: 'ghcr.io/o' }; - const dry = new Context({ dryRun: true }, io); - assert.equal((await publish(dry, { ...options, registry: { kind: 'ghcr', prefix: 'ghcr.io/o' } })).copied, false); - assert.equal((await publish(dry, { ...options, registry: own })).copied, true); +test('a missing image of an app with a Dockerfile of its own is built from its pruned context, by the lockfile’s Turbo', async () => { + const { ctx, calls } = world(); + const result = await publish(ctx, { ...options, app: 'solver', hash: '9e1d', npmrc: '/run/npmrc' }); + assert.equal(result.built, true); + assert.ok(!calls.some((c) => c.command === 'mise'), 'no restore of a build output'); + const prune = calls.find((c) => c.command === 'npx'); + assert.deepEqual(prune?.args.slice(0, 5), ['--yes', 'turbo@2.11.13', 'prune', '@acme/solver', '--docker']); + const out = prune?.args.at(-1) ?? ''; + const build = buildOf(calls); + assert.equal(build?.args[2], `${out}/full`); + assert.deepEqual(build?.args.slice(3, 5), ['--file', `${out}/full/apps/solver/docker/Dockerfile`]); + const args = build?.args.join(' ') ?? ''; + assert.match(args, /--build-arg APP=solver --build-arg BUILD_HASH=9e1d/); + assert.match(args, /--secret id=next-server-actions-encryption-key,env=NEXT_SERVER_ACTIONS_ENCRYPTION_KEY/); + assert.match(args, /--secret id=npmrc,src=\/run\/npmrc/); + assert.match(args, /--tag ghcr\.io\/acme\/solver:build-9e1d --tag ghcr\.io\/acme\/solver:deadbeef/); + assert.doesNotMatch(args, /--cache-from|--cache-to|:cache/); + assert.equal(build?.env?.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, KEY); + // The pruned context goes after the build. + assert.deepEqual(calls.at(-1)?.args, ['-rf', out]); +}); + +test('a publish that would build refuses without the app’s key; one that only tags needs none', async () => { + const { ctx, calls } = world({ outputs: { website: '0f2a' } }); + await assert.rejects( + publish(ctx, { ...options, app: 'website', encryptionKey: '' }), + /NEXT_SERVER_ACTIONS_ENCRYPTION_KEY is empty/, + ); + assert.ok(!calls.some((c) => c.command !== 'crane')); + const there = world({ holds: ['ghcr.io/acme/website:build-0f2a'] }); + assert.equal((await publish(there.ctx, { ...options, app: 'website', encryptionKey: '' })).built, false); }); diff --git a/packages/cli-ci/src/testing/checkout.ts b/packages/cli-ci/src/testing/checkout.ts new file mode 100644 index 00000000..ab070932 --- /dev/null +++ b/packages/cli-ci/src/testing/checkout.ts @@ -0,0 +1,59 @@ +// A checkout as plan and publish read it, for the tests: an app repo with three +// apps, website and my-app from app-nextjs and solver with a Dockerfile of its +// own, and an E2E suite for website alone. Not shipped (excluded in tsconfig). +import type { Tree } from './fakeIo.ts'; + +/** The lockfile of pnpm 11 and later: the package manager's document, then the workspace's. */ +export const LOCKFILE = [ + '---', + "lockfileVersion: '9.0'", + 'importers:', + ' .:', + ' packageManagerDependencies:', + ' pnpm:', + ' specifier: 12.21.0', + ' version: 12.21.0', + '---', + "lockfileVersion: '9.0'", + 'importers:', + ' .:', + ' devDependencies:', + ' turbo:', + ' specifier: ^2.9.0', + ' version: 2.11.13', + ' apps/site:', + ' dependencies:', + ' next:', + ' specifier: ^16', + ' version: 16.4.6', + '', +].join('\n'); + +/** An app's directory: its package.json and the marker `plx new` writes, with the templates it lists. */ +export const app = (name: string, templates: string[]): Tree => ({ + 'package.json': JSON.stringify({ name }), + 'PLEXUS.md': `---\ntemplates: [${templates.join(', ')}]\nname: '${name}'\nprofile: stateless\n---\n`, +}); + +/** A suite at e2e/, the package the template e2e-playwright renders. */ +export const suite = (of: string): Tree => ({ + 'package.json': JSON.stringify({ + name: `${of}-e2e`, + scripts: { e2e: 'playwright test' }, + devDependencies: { [of]: 'workspace:*', '@playwright/test': '^1.65.1' }, + }), +}); + +/** A checkout with three apps: website and my-app from app-nextjs, solver with a Dockerfile of its own; a suite for website only. */ +export const REPO: Tree = { + repo: { + 'package.json': JSON.stringify({ devDependencies: { turbo: '^2.9.0' } }), + 'pnpm-lock.yaml': LOCKFILE, + apps: { + website: app('@acme/website', ['app-nextjs']), + 'my-app': app('@acme/my-app', ['app-nextjs']), + solver: app('@acme/solver', []), + }, + e2e: { website: suite('@acme/website'), tools: { 'package.json': JSON.stringify({ name: 'tools' }) } }, + }, +}; diff --git a/packages/cli-ci/src/testing/fakeIo.ts b/packages/cli-ci/src/testing/fakeIo.ts index bc34a0ec..d768562d 100644 --- a/packages/cli-ci/src/testing/fakeIo.ts +++ b/packages/cli-ci/src/testing/fakeIo.ts @@ -6,7 +6,7 @@ import { ExecError, type Io } from '@plexus-ms/lib'; export type Tree = { [name: string]: string | Tree }; -export type FakeExec = (cwd: string, args: string[], input?: string) => string | undefined; +export type FakeExec = (cwd: string, args: string[], input?: string, env?: NodeJS.ProcessEnv) => string | undefined; /** What a registry answers for a manifest it does not hold, as curl --fail and crane report it. */ export function notThere(command: 'curl' | 'crane'): never { @@ -28,7 +28,7 @@ export function fakeIo(tree: Tree, git: FakeExec = () => undefined, other: Recor exec: async (command, args, options) => { const handler = command === 'git' ? git : other[command]; assert.ok(handler, `fake io: no handler for ${command}`); - const out = handler(options?.cwd ?? '', args, options?.input); + const out = handler(options?.cwd ?? '', args, options?.input, options?.env); if (out === undefined) throw new ExecError(`${command} ${args.join(' ')}`, 1, `fake ${command} fails in ${options?.cwd}`); return out; From b716f933596b4ce25c259d8b9c9687cc5bc553fe Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 21:52:15 +0100 Subject: [PATCH 128/194] plx-ci publish builds a missing image itself, from a fresh restore of the build output or a pruned context, with no layer cache; plx-ci build goes Under github the runner's Docker builds, under on-prem and hybrid the runner host's BuildKit service through a remote buildx builder. The output must hold the BUILD_ID of the hash it is tagged with. The publish test's order assertion reads the steps by pattern, since the build's scratch directory has a random name. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/commands/build.ts | 55 ----- packages/cli-ci/src/commands/index.ts | 3 +- packages/cli-ci/src/commands/publish.ts | 54 +++-- packages/cli-ci/src/core/build.test.ts | 48 ---- packages/cli-ci/src/core/build.ts | 285 +++++++++++++---------- packages/cli-ci/src/core/publish.test.ts | 9 +- packages/cli-ci/src/core/publish.ts | 78 +++---- packages/cli-ci/src/program.test.ts | 12 +- 8 files changed, 242 insertions(+), 302 deletions(-) delete mode 100644 packages/cli-ci/src/commands/build.ts delete mode 100644 packages/cli-ci/src/core/build.test.ts diff --git a/packages/cli-ci/src/commands/build.ts b/packages/cli-ci/src/commands/build.ts deleted file mode 100644 index 970c35c5..00000000 --- a/packages/cli-ci/src/commands/build.ts +++ /dev/null @@ -1,55 +0,0 @@ -// plx-ci build [tag...]: one app's image from its pruned -// context, with the registry as cache, pushed as build- and the extra -// tags, and as too where the candidates have a registry of their own -// (§§ 4 and 8 PLX-Delivery). From the environment: CI_STRATEGY, CI_REGISTRY; -// NEXT_SERVER_ACTIONS_ENCRYPTION_KEY (the app's fixed key), NO_CACHE=1 for a -// build from scratch, BUILDX_BUILDER (default ci), NPM_CONFIG_USERCONFIG (a -// user-level npmrc with the token of the tenant's private package registry, -// handed to the image's installs as a secret). Prints the digest, and writes -// it to GITHUB_OUTPUT when that is set. -// -// plx-ci build website 0f2a3f35123dfd73 "$GITHUB_SHA" -// NO_CACHE=1 plx-ci build website 0f2a3f35123dfd73 "$GITHUB_SHA" repro--1 -import { appendFileSync } from 'node:fs'; -import { resolve } from 'node:path'; -import type { Command } from 'commander'; -import { build } from '../core/build.ts'; -import { contextOf } from '../program.ts'; -import { registryFor, settings, withStrategy } from './shared.ts'; - -export function register(program: Command): void { - withStrategy(program.command('build')) - .description('build one app’s image from its pruned context against the registry and push it') - .argument('', 'the app, apps/ in the checkout') - .argument('', 'Turbo’s hash of the app’s build task') - .argument('', 'the commit, a second tag') - .argument('[tags...]', 'further tags on the same image') - .option('-C, --dir ', 'the checkout to read', '.') - .action( - async ( - app: string, - hash: string, - sha: string, - tags: string[], - opts: { strategy?: string; dir: string }, - command: Command, - ) => { - const ctx = contextOf(command); - const result = await build(ctx, { - app, - hash, - sha, - tags, - encryptionKey: process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY ?? '', - npmrc: process.env.NPM_CONFIG_USERCONFIG || undefined, - noCache: process.env.NO_CACHE === '1', - dir: resolve(opts.dir), - registry: registryFor(settings(opts)), - builder: process.env.BUILDX_BUILDER, - }); - ctx.result(result, (r) => r.digest ?? ''); - if (process.env.GITHUB_OUTPUT && result.digest) - appendFileSync(process.env.GITHUB_OUTPUT, `digest=${result.digest}\n`); - }, - ); -} diff --git a/packages/cli-ci/src/commands/index.ts b/packages/cli-ci/src/commands/index.ts index eeaa4b76..082f083d 100644 --- a/packages/cli-ci/src/commands/index.ts +++ b/packages/cli-ci/src/commands/index.ts @@ -5,11 +5,10 @@ // holds what only that strategy needs. The display versions, opt-in per // repo, read no strategy and sit where a release uses them, after publish. import type { Command } from 'commander'; -import { register as build } from './build.ts'; import { register as displayVersions } from './displayVersions.ts'; import { register as hybrid } from './hybrid.ts'; import { register as plan } from './plan.ts'; import { register as publish } from './publish.ts'; import { register as registry } from './registry.ts'; -export const commands: ((program: Command) => void)[] = [registry, plan, build, publish, displayVersions, hybrid]; +export const commands: ((program: Command) => void)[] = [registry, plan, publish, displayVersions, hybrid]; diff --git a/packages/cli-ci/src/commands/publish.ts b/packages/cli-ci/src/commands/publish.ts index b49571f2..e28ecfa8 100644 --- a/packages/cli-ci/src/commands/publish.ts +++ b/packages/cli-ci/src/commands/publish.ts @@ -1,40 +1,54 @@ -// plx-ci publish [--test ]: put the tested -// image under its commit in the registry production pulls from: copied from -// the sidecar, or tagged where it is there already (§ 8 PLX-Delivery). Needs -// the registry reachable here (`plx-ci registry`) and crane on the PATH, -// logged in to the forge's registry. From the environment: CI_STRATEGY, -// CI_REGISTRY; IMAGE_PREFIX, where the images live (default ghcr.io/). Prints the image, and writes image= to -// GITHUB_OUTPUT when that is set. +// plx-ci publish : put the app's image under its commit in +// the forge's registry, the one production pulls from (§ 4 PLX-Delivery): +// tagged where build- is there already, else built and pushed under +// both, from the build output restored by the repo's `mise run build ` +// or, for a Dockerfile of the app's own, from a pruned context. Runs in a +// checkout, in the repo's mise environment, with crane on the PATH and +// logged in to the forge's registry, and docker's client with buildx. From +// the environment: CI_STRATEGY, which decides where the image is built (the +// runner's Docker under github, the runner host's BuildKit service +// otherwise); BUILDKIT_HOST, that service where it is not on +// 127.0.0.1:1234; IMAGE_PREFIX, where the images live (default +// ghcr.io/); NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, +// the app's key, needed where it builds; NPM_CONFIG_USERCONFIG, a user-level +// npmrc with the token of the tenant's private package registry, handed to a +// Dockerfile of the app's own as a secret. Prints the image, and writes +// image= to GITHUB_OUTPUT when that is set. // // plx-ci publish website 0f2a3f35123dfd73 "$GITHUB_SHA" -// plx-ci publish my-app d135e9416e1cf4e8 "$GITHUB_SHA" --test 5b052598a4d84145 import { appendFileSync } from 'node:fs'; +import { resolve } from 'node:path'; import type { Command } from 'commander'; import { publish } from '../core/publish.ts'; import { contextOf } from '../program.ts'; -import { imagePrefix, registryFor, settings, withStrategy } from './shared.ts'; +import { imagePrefix, settings, withStrategy } from './shared.ts'; export function register(program: Command): void { withStrategy(program.command('publish')) - .description('publish one app’s tested image as in the forge’s registry, beside build- and test-') - .argument('', 'the app') - .argument('', 'Turbo’s hash of the app’s build task') + .description( + 'publish one app’s image as in the forge’s registry: tag build- where it is there, else build it and push it', + ) + .argument('', 'the app, apps/ in the checkout') + .argument('', 'Turbo’s hash of the app’s build task') .argument('', 'the commit, the tag a deploy takes') - .option('--test ', 'Turbo’s hash of the app’s test task; the image is read from test-') + .option('-C, --dir ', 'the checkout to read', '.') .action( - async (app: string, build: string, sha: string, opts: { strategy?: string; test?: string }, command: Command) => { + async (app: string, hash: string, sha: string, opts: { strategy?: string; dir: string }, command: Command) => { const ctx = contextOf(command); + const env = process.env; const result = await publish(ctx, { app, - build, - test: opts.test || undefined, + hash, sha, prefix: imagePrefix(), - registry: registryFor(settings(opts)), + dir: resolve(opts.dir), + strategy: settings(opts).strategy, + encryptionKey: env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY ?? '', + npmrc: env.NPM_CONFIG_USERCONFIG || undefined, + buildkit: env.BUILDKIT_HOST || undefined, }); - ctx.result(result, (r) => `${r.image}:${sha}${r.copied ? '' : ' (was there)'}`); - if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `image=${result.image}:${sha}\n`); + ctx.result(result, (r) => `${r.image}:${sha}${r.built ? ` (built, ${r.digest ?? 'no digest'})` : ' (tagged)'}`); + if (env.GITHUB_OUTPUT) appendFileSync(env.GITHUB_OUTPUT, `image=${result.image}:${sha}\n`); }, ); } diff --git a/packages/cli-ci/src/core/build.test.ts b/packages/cli-ci/src/core/build.test.ts deleted file mode 100644 index 1ab10679..00000000 --- a/packages/cli-ci/src/core/build.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import assert from 'node:assert/strict'; -import { test } from 'node:test'; -import { buildArgs, buildStep, tagsOf } from './build.ts'; - -const options = { app: 'website', hash: '0f2a', sha: 'abc', encryptionKey: 'k', registry: { kind: 'own' } as const }; - -test('the build names both sidecars as cache sources when the previous one answers, and only the current one otherwise', () => { - const both = buildArgs(options, '/ctx/full', '/ctx/meta.json', true).join(' '); - assert.match(both, /--cache-from type=registry,ref=localhost:5000\/website:cache/); - assert.match(both, /--cache-from type=registry,ref=localhost:5001\/website:cache/); - assert.match(both, /--cache-to type=registry,ref=localhost:5000\/website:cache,mode=max/); - assert.match(both, /--tag localhost:5000\/website:build-0f2a --tag localhost:5000\/website:abc/); - assert.match(both, /--file \/ctx\/full\/apps\/website\/docker\/Dockerfile/); - assert.match(both, /--provenance=false --sbom=false/); - const one = buildArgs(options, '/ctx/full', '/ctx/meta.json', false).join(' '); - assert.doesNotMatch(one, /5001/); -}); - -test('a no-cache build has no cache arguments and carries the extra tags', () => { - const args = buildArgs({ ...options, noCache: true, tags: ['repro-41-1'] }, '/c', '/m', true).join(' '); - assert.match(args, /--no-cache/); - assert.doesNotMatch(args, /cache-from|cache-to/); - assert.match(args, /--tag localhost:5000\/website:repro-41-1/); -}); - -test('in the forge’s registry a build pushes no commit tag and names no previous week', () => { - const ghcr = { ...options, registry: { kind: 'ghcr', prefix: 'ghcr.io/plexus-ms-tenant' } as const }; - assert.deepEqual(tagsOf(ghcr), ['build-0f2a']); - assert.deepEqual(tagsOf(options), ['build-0f2a', 'abc']); - const args = buildArgs(ghcr, '/c', '/m', false).join(' '); - assert.match(args, /--tag ghcr.io\/plexus-ms-tenant\/website:build-0f2a/); - assert.doesNotMatch(args, /website:abc/); - assert.match(args, /--cache-to type=registry,ref=ghcr.io\/plexus-ms-tenant\/website:cache,mode=max/); - assert.doesNotMatch(args, /localhost/); -}); - -test('the private registry’s npmrc is a secret of the build only where the job has one', () => { - assert.doesNotMatch(buildArgs(options, '/c', '/m', false).join(' '), /id=npmrc/); - const args = buildArgs({ ...options, npmrc: '/tmp/npmrc' }, '/c', '/m', false).join(' '); - assert.match(args, /--secret id=npmrc,src=\/tmp\/npmrc/); -}); - -test('the build passes the output of BuildKit through to the log at every verbosity', () => { - const step = buildStep(buildArgs(options, '/c', '/m', false), { BUILDX_BUILDER: 'ci' }); - assert.equal(step.kind, 'run'); - assert.equal(step.kind === 'run' && step.interactive, true); - assert.match(buildArgs(options, '/c', '/m', false).join(' '), /--progress plain/); -}); diff --git a/packages/cli-ci/src/core/build.ts b/packages/cli-ci/src/core/build.ts index 5182d2d5..d57b3bec 100644 --- a/packages/cli-ci/src/core/build.ts +++ b/packages/cli-ci/src/core/build.ts @@ -1,108 +1,119 @@ -// Build one app's image from its pruned context, with the registry as -// BuildKit cache and candidate store (§§ 4 and 8 PLX-Delivery). Runs on a -// large runner, whichever the strategy gives it, in a checkout of the repo -// with node and docker on the PATH, and by hand the same way. BuildKit runs -// as a docker-container builder on the machine's network (the docker driver -// cannot export a registry cache, and localhost:5000 is the sidecar there); a -// launched instance has bootstrapped it by the time the job starts, anywhere -// else the build creates it. +// Build one app's image and push it (§ 4 PLX-Delivery), for publish, which +// builds only an image the forge's registry lacks. An app's image is made in +// one of two ways, by what its Dockerfile is (plan.ts's imageContextOf): // -// The pruned context is `turbo prune --docker` into a -// temporary directory: `json/` with the package manifests alone, `full/` with -// the app and the workspace packages it uses, whole, and the lockfile reduced -// to them beside the two. The build context is `full/`, with the lockfile and -// the repo's root .dockerignore copied in and an empty packages/ made where -// the app uses none; the Dockerfile is apps//docker/Dockerfile in it. -// `json/` goes unused. The directory is removed after the build. +// output an app from app-nextjs: its Dockerfile only copies the one +// directory its build leaves (apps//.next/standalone), and +// that directory is the build context. It is restored by the +// repo's own verb, `mise run build `, which a job runs +// against the trusted cache, where the app's e2e job left it; the +// directory is removed first, so that the image holds the restore +// and nothing a server or an earlier build wrote there. A miss +// builds the app, with the app's key, as the e2e job did. The +// output must hold apps//.next/BUILD_ID, the build's hash +// (generateBuildId in the template's next.config.ts), equal to +// the hash the image is tagged with: an output of another hash, or +// none where the Dockerfile's WORKDIR looks, is refused. +// pruned an app with a Dockerfile of its own builds itself in it, from +// `turbo prune --docker` (the Turbo the lockfile +// has) into a temporary directory: `json/` with the package +// manifests alone, `full/` with the app and the workspace packages +// it uses, whole, and the lockfile reduced to them beside the two. +// The build context is `full/`, with the lockfile and the repo's +// root .dockerignore copied in and an empty packages/ made where +// the app uses none; the Dockerfile is apps//docker/Dockerfile +// in it, given BUILD_HASH, the app's key as a BuildKit secret and, +// where the job has one, the npmrc of the tenant's private +// packages. `json/` goes unused. The directory is removed after. +// +// Either way the image is built for linux/amd64 and pushed under build- +// and the commit, with no layer cache, SOURCE_DATE_EPOCH and +// rewrite-timestamp flattening its timestamps and no provenance or SBOM, so +// that the manifest is the image and nothing else. BuildKit's log is the +// job's, at every verbosity. Where the build runs is the strategy's: under +// github the runner's own Docker (the default builder), under on-prem and +// hybrid the BuildKit service of the runner host (actions_runners), on +// 127.0.0.1:1234 unless BUILDKIT_HOST names another, through a buildx +// builder of the remote driver, plexus-buildkit, made where the machine has +// none of the name yet. The push uses the login of the job's +// ~/.docker/config.json, which BuildKit is handed through the build's session. import { randomBytes } from 'node:crypto'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { Context, Step } from '@plexus-ms/lib'; import { run, UsageError } from '@plexus-ms/lib'; -import { packageName, turboOf } from './plan.ts'; -import { answers, candidateRef, PREVIOUS_PORT, type Registry } from './registry.ts'; +import { type ImageContext, packageName, turboOf } from './plan.ts'; +import type { Strategy } from './strategy.ts'; + +/** The BuildKit service of a runner host, where actions_runners puts it. */ +export const BUILDKIT = 'tcp://127.0.0.1:1234'; +/** The buildx builder of the remote driver that reaches it. */ +export const BUILDER = 'plexus-buildkit'; export interface BuildOptions { app: string; - /** Turbo's hash of the app's build task; the image's primary tag and Next's build ID. */ + /** Turbo's hash of the app's build task; the image's tag build- and its build ID. */ hash: string; + /** The commit, the image's second tag. */ sha: string; - /** Further tags on the same image. */ - tags?: string[]; - /** The app's fixed key, a BuildKit secret; the Dockerfile reads it as next-server-actions-encryption-key. */ + /** The image, `/`, without a tag. */ + image: string; + /** What the image is made from. */ + context: ImageContext; + /** The checkout. */ + dir: string; + strategy: Strategy; + /** The app's server-actions key: for a build of the output that misses the cache, or a secret of a Dockerfile of its own. */ encryptionKey: string; - /** - * A user-level npmrc holding the token of the tenant's private package registry, a BuildKit - * secret; the Dockerfile mounts it as npmrc for its installs. Absent where the repo installs none. - */ + /** A user-level npmrc with the token of the tenant's private package registry, a secret of a Dockerfile of its own. */ npmrc?: string; - /** Build from scratch, the reproducibility measurement. */ - noCache?: boolean; - /** The checkout; default the cwd. */ - dir?: string; - /** Where the candidates live. */ - registry: Registry; - builder?: string; + /** The BuildKit service under on-prem and hybrid; default BUILDKIT. */ + buildkit?: string; } -export interface Build { - app: string; +export interface Built { tags: string[]; digest?: string; - /** Seconds the prune and the build took. */ - pruneSeconds: number; - buildSeconds: number; } -export const PREVIOUS_REGISTRY = `localhost:${PREVIOUS_PORT}`; - -/** - * The tags a build pushes: build- and the extra ones, and the commit - * where the candidates have a registry of their own. In the forge's registry - * the commit's tag marks a published image, which only `publish` may set. - */ -export function tagsOf(options: BuildOptions): string[] { - return [`build-${options.hash}`, ...(options.registry.kind === 'own' ? [options.sha] : []), ...(options.tags ?? [])]; -} +/** The output directory of an app from app-nextjs: the build context of its image. */ +export const outputOf = (dir: string, app: string): string => join(dir, 'apps', app, '.next', 'standalone'); -/** The `docker buildx build` arguments, so that the tests pin them. */ +/** The `docker buildx build` arguments for a context and a Dockerfile, so that the tests pin them. */ export function buildArgs( options: BuildOptions, context: string, + dockerfile: string, metadataFile: string, - previousAnswers: boolean, + builder?: string, ): string[] { - const { app } = options; - const ref = (tag: string) => candidateRef(options.registry, app, tag); - const tags = tagsOf(options).flatMap((t) => ['--tag', ref(t)]); - const cache = options.noCache - ? ['--no-cache'] - : [ - '--cache-from', - `type=registry,ref=${ref('cache')}`, - ...(previousAnswers ? ['--cache-from', `type=registry,ref=${PREVIOUS_REGISTRY}/${app}:cache`] : []), - '--cache-to', - `type=registry,ref=${ref('cache')},mode=max`, - ]; + const { app, image } = options; + const own = + options.context === 'pruned' + ? [ + '--build-arg', + `BUILD_HASH=${options.hash}`, + '--secret', + 'id=next-server-actions-encryption-key,env=NEXT_SERVER_ACTIONS_ENCRYPTION_KEY', + ...(options.npmrc ? ['--secret', `id=npmrc,src=${options.npmrc}`] : []), + ] + : []; return [ 'buildx', 'build', context, '--file', - `${context}/apps/${app}/docker/Dockerfile`, + dockerfile, '--platform', 'linux/amd64', + ...(builder ? ['--builder', builder] : []), '--build-arg', `APP=${app}`, - '--build-arg', - `BUILD_HASH=${options.hash}`, - '--secret', - 'id=next-server-actions-encryption-key,env=NEXT_SERVER_ACTIONS_ENCRYPTION_KEY', - ...(options.npmrc ? ['--secret', `id=npmrc,src=${options.npmrc}`] : []), - ...cache, - ...tags, - // SOURCE_DATE_EPOCH and rewrite-timestamp flatten every timestamp the image - // carries; provenance and SBOM off, so the manifest is the image and nothing else. + ...own, + '--tag', + `${image}:build-${options.hash}`, + '--tag', + `${image}:${options.sha}`, '--output', 'type=image,push=true,rewrite-timestamp=true,oci-mediatypes=true', '--provenance=false', @@ -114,85 +125,107 @@ export function buildArgs( ]; } -/** - * The build as a step. BuildKit's output is the job's log, inherited and not - * captured: which layers came from the cache and what each step cost is read - * there, at every verbosity. - */ +/** The build as a step: BuildKit's output is the job's log, inherited and not captured. */ export function buildStep(args: string[], env: NodeJS.ProcessEnv): Step { return run('docker', args, { env, interactive: true }); } -/** The builder, created where the machine has none of the name yet. */ -async function ensureBuilder(ctx: Context, name: string): Promise { +/** The builder of the strategy: none under github, the runner's Docker; the remote one of the BuildKit service otherwise, made where missing. */ +async function builderFor(ctx: Context, options: BuildOptions): Promise { + if (options.strategy === 'github') return undefined; if (!ctx.dryRun) { try { - await ctx.read('docker', ['buildx', 'inspect', name]); - return; + await ctx.read('docker', ['buildx', 'inspect', BUILDER]); + return BUILDER; } catch {} } await ctx.apply([ - run('docker', [ - 'buildx', - 'create', - '--name', - name, - '--driver', - 'docker-container', - '--driver-opt', - 'network=host', - '--bootstrap', - ]), + run('docker', ['buildx', 'create', '--name', BUILDER, '--driver', 'remote', options.buildkit || BUILDKIT]), ]); + return BUILDER; } -export async function build(ctx: Context, options: BuildOptions): Promise { - if (!options.encryptionKey) throw new UsageError('NEXT_SERVER_ACTIONS_ENCRYPTION_KEY is empty'); - const dir = options.dir ?? '.'; - const out = join(tmpdir(), `plx-ci-build-${randomBytes(4).toString('hex')}`); - const context = join(out, 'full'); - const builder = options.builder ?? 'ci'; - const env = { - NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: options.encryptionKey, - BUILDX_BUILDER: builder, - SOURCE_DATE_EPOCH: '0', - }; - const name = await packageName(ctx, dir, options.app); - await ensureBuilder(ctx, builder); - - // The pruned context: the app, the workspace packages it uses, a lockfile - // reduced to them. turbo writes the lockfile beside `full`, and leaves out - // the root .dockerignore and an empty packages/ when the app uses none; the - // Dockerfile wants all three. - let t = Date.now(); +/** The output restored by the repo's verb into a clean directory, refused unless it is the build of `hash`. */ +async function restoreOutput(ctx: Context, options: BuildOptions): Promise { + const { app, dir, hash } = options; + const output = outputOf(dir, app); await ctx.apply([ - run('npx', ['--yes', await turboOf(ctx, dir), 'prune', name, '--docker', '--out-dir', out], { + run('rm', ['-rf', output]), + run('mise', ['run', 'build', app], { cwd: dir, + env: { NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: options.encryptionKey }, }), + ]); + if (!ctx.dryRun) { + const where = `apps/${app}/.next/standalone`; + let id: string; + try { + id = (await ctx.readFile(join(output, 'apps', app, '.next', 'BUILD_ID'))).trim(); + } catch { + throw new Error( + `${where} holds no apps/${app}/.next/BUILD_ID: the build left no app at the place the Dockerfile starts it`, + ); + } + if (id !== hash) + throw new Error( + `${where} holds the build ${id}, not ${hash}: the plan and the build saw different inputs (another Turbo, or another PLX_PLATFORM)`, + ); + } + return output; +} + +/** A pruned context of the app, in a new temporary directory; its build context is `/full`. */ +async function prunedContext(ctx: Context, options: BuildOptions, out: string): Promise { + const { dir } = options; + const context = join(out, 'full'); + // turbo writes the lockfile beside `full`, and leaves out the root + // .dockerignore and an empty packages/ when the app uses none; the + // Dockerfile wants all three. + await ctx.apply([ + run( + 'npx', + [ + '--yes', + await turboOf(ctx, dir), + 'prune', + await packageName(ctx, dir, options.app), + '--docker', + '--out-dir', + out, + ], + { cwd: dir }, + ), run('cp', [join(out, 'pnpm-lock.yaml'), join(context, 'pnpm-lock.yaml')]), run('cp', [join(dir, '.dockerignore'), join(context, '.dockerignore')]), run('mkdir', ['-p', join(context, 'packages')]), ]); - const pruneSeconds = Math.round((Date.now() - t) / 1000); - ctx.say(`build: prune ${pruneSeconds}s`); + return context; +} - // The previous week's sidecar exists only when its bucket does, and only - // with a registry of the tenant's own. - const previousAnswers = options.registry.kind === 'own' && (ctx.dryRun ? true : await answers(ctx, PREVIOUS_PORT)); - if (options.registry.kind === 'own' && !previousAnswers) - ctx.say(`build: no previous-week registry on ${PREVIOUS_REGISTRY}`); +/** Build the app's image from its context and push it under build- and the commit. */ +export async function build(ctx: Context, options: BuildOptions): Promise { + if (!options.encryptionKey) throw new UsageError('NEXT_SERVER_ACTIONS_ENCRYPTION_KEY is empty'); + const { app } = options; + const builder = await builderFor(ctx, options); + const out = join(tmpdir(), `plx-ci-build-${randomBytes(4).toString('hex')}`); + const pruned = options.context === 'pruned'; + const context = pruned ? await prunedContext(ctx, options, out) : await restoreOutput(ctx, options); + if (!pruned) await ctx.apply([run('mkdir', ['-p', out])]); + const dockerfile = join(pruned ? context : options.dir, 'apps', app, 'docker', 'Dockerfile'); const metadataFile = join(out, 'metadata.json'); - t = Date.now(); - await ctx.apply([buildStep(buildArgs(options, context, metadataFile, previousAnswers), env)]); - const buildSeconds = Math.round((Date.now() - t) / 1000); - ctx.say(`build: build${options.noCache ? ' no-cache' : ''} ${buildSeconds}s`); - - const tags = tagsOf(options); - const result: Build = { app: options.app, tags, pruneSeconds, buildSeconds }; + const env = { + SOURCE_DATE_EPOCH: '0', + ...(pruned ? { NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: options.encryptionKey } : {}), + }; + const t = Date.now(); + await ctx.apply([buildStep(buildArgs(options, context, dockerfile, metadataFile, builder), env)]); + ctx.say(`build: ${app} ${Math.round((Date.now() - t) / 1000)}s`); + const tags = [`build-${options.hash}`, options.sha]; + const result: Built = { tags }; if (!ctx.dryRun) { const meta = JSON.parse(await ctx.readFile(metadataFile)) as { 'containerimage.digest'?: string }; result.digest = meta['containerimage.digest']; - ctx.say(`build: ${options.app} ${tags.join(' ')} -> ${result.digest ?? ''}`); + ctx.say(`build: ${options.image} ${tags.join(' ')} -> ${result.digest ?? ''}`); } await ctx.apply([run('rm', ['-rf', out])]); return result; diff --git a/packages/cli-ci/src/core/publish.test.ts b/packages/cli-ci/src/core/publish.test.ts index 9f457a19..06358888 100644 --- a/packages/cli-ci/src/core/publish.test.ts +++ b/packages/cli-ci/src/core/publish.test.ts @@ -102,8 +102,13 @@ test('a missing image of an app from app-nextjs: a fresh restore of its output t assert.equal(result.built, true); assert.equal(result.digest, 'sha256:built'); assert.deepEqual(result.tags, ['build-0f2a', SHA]); - const order = calls.filter((c) => c.command !== 'crane').map((c) => `${c.command} ${c.args.slice(0, 2).join(' ')}`); - assert.deepEqual(order, ['rm -rf /repo/apps/website/.next/standalone', 'mise run build', 'docker buildx build']); + // The output is removed, restored by the verb, then built from; the scratch directory of the build goes after it. + const order = calls.filter((c) => c.command !== 'crane').map((c) => `${c.command} ${c.args.join(' ')}`); + const at = (line: RegExp) => order.findIndex((o) => line.test(o)); + assert.ok(at(/^rm -rf \/repo\/apps\/website\/\.next\/standalone$/) === 0, order.join('\n')); + assert.ok(at(/^mise run build website$/) === 1, order.join('\n')); + assert.ok(at(/^docker buildx build /) > 1, order.join('\n')); + assert.match(order.at(-1) ?? '', /^rm -rf \/tmp\/plx-ci-build-[0-9a-f]+$/); // The repo's own verb, in the checkout, with the key a build that misses the cache needs. const restore = calls.find((c) => c.command === 'mise'); assert.deepEqual(restore?.args, ['run', 'build', 'website']); diff --git a/packages/cli-ci/src/core/publish.ts b/packages/cli-ci/src/core/publish.ts index daa0bab3..2edbb3d1 100644 --- a/packages/cli-ci/src/core/publish.ts +++ b/packages/cli-ci/src/core/publish.ts @@ -1,60 +1,60 @@ -// Publish one app's tested image under its commit, to the registry -// production pulls from (§ 8 PLX-Delivery). With a registry of the tenant's -// own: copy the manifest, by digest and without an index, from the sidecar to -// the forge's registry as build-, then tag it test- and ; or, -// when it is there already (a promotion, a re-run), only add the tags. Where -// the candidates live in the forge's registry itself, nothing is copied: the -// tested manifest gets the tag . Either way the tag test- is the -// proof the tests passed, and an image without it is not published. crane -// does the copying and tagging, logged in to the forge's registry by the job. +// Publish one app's image under its commit in the forge's registry, the one +// production pulls from (§ 4 PLX-Delivery). Where the registry holds +// `build-` already, the image built for the same content by an earlier +// run, a promotion's among them, gets the commit's tag and nothing is built +// (crane, logged in to the registry by the job). Where it lacks it, the image +// is built and pushed under both tags (build.ts says how). The registry is +// the one place that says whether an image exists; publish records nothing +// else, and that the image was tested is the order of the jobs: a run's +// publish of an app follows that run's test and e2e jobs. import type { Context } from '@plexus-ms/lib'; import { run } from '@plexus-ms/lib'; -import { craneDigest, findTag, imageName, type Registry } from './registry.ts'; +import { build } from './build.ts'; +import { imageContextOf } from './plan.ts'; +import { craneDigest, imageName } from './registry.ts'; +import type { Strategy } from './strategy.ts'; export interface PublishOptions { app: string; /** Turbo's hash of the app's build task. */ - build: string; - /** Turbo's hash of the app's test task when it has one; the tag the image is read from, proof the tests passed. */ - test?: string; + hash: string; + /** The commit, the tag a deploy takes. */ sha: string; /** Where the published images live, `ghcr.io/`; lower-cased, as registries want. */ prefix: string; - /** Where the candidates live. */ - registry: Registry; + /** The checkout. */ + dir: string; + strategy: Strategy; + /** The app's server-actions key, which a build needs and a tag does not. */ + encryptionKey: string; + /** A user-level npmrc with the token of the tenant's private package registry. */ + npmrc?: string; + /** The BuildKit service under on-prem and hybrid, as `tcp://
:`. */ + buildkit?: string; } export interface Published { app: string; image: string; - /** Whether the manifest was copied, or found there already. */ - copied: boolean; + /** Whether the image was built here, or found under build-. */ + built: boolean; tags: string[]; + digest?: string; } export async function publish(ctx: Context, options: PublishOptions): Promise { - const { app, build, test, sha, registry } = options; + const { app, hash, sha } = options; const image = imageName(options.prefix, app); - const target = `${image}:build-${build}`; - const source = test ? `test-${test}` : `build-${build}`; - const missing = `${app}:${source} is in no registry here; ${test ? 'the tests did not pass on this build' : 'the build never ran'}`; - - if (registry.kind === 'ghcr') { - const ref = `${image}:${source}`; - if ((await craneDigest(ctx, ref)) === undefined && !ctx.dryRun) throw new Error(missing); - ctx.say(`publish: ${ref} as ${sha}`); - await ctx.apply([run('crane', ['tag', ref, sha])]); - return { app, image, copied: false, tags: [`build-${build}`, ...(test ? [`test-${test}`] : []), sha] }; + const target = `${image}:build-${hash}`; + if ((await craneDigest(ctx, target)) !== undefined) { + ctx.say(`publish: ${target} is there already, tagging it ${sha}`); + await ctx.apply([run('crane', ['tag', target, sha])]); + return { app, image, built: false, tags: [`build-${hash}`, sha] }; } - - const copied = (await craneDigest(ctx, target)) === undefined; - if (copied) { - const from = await findTag(ctx, registry, app, source); - if (from === undefined && !ctx.dryRun) throw new Error(missing); - ctx.say(`publish: ${app}:${source} -> ${target}`); - await ctx.apply([run('crane', ['copy', '--insecure', from ?? `localhost:5000/${app}:${source}`, target])]); - } else ctx.say(`publish: ${target} is there already, tagging only`); - const tags = [sha, ...(test ? [`test-${test}`] : [])]; - await ctx.apply(tags.map((t) => run('crane', ['tag', target, t]))); - return { app, image, copied, tags: [`build-${build}`, ...tags] }; + const context = await imageContextOf(ctx, options.dir, app); + ctx.say( + `publish: ${target} is missing, building it from ${context === 'output' ? 'the build output' : 'a pruned context'}`, + ); + const built = await build(ctx, { ...options, image, context }); + return { app, image, built: true, tags: built.tags, ...(built.digest ? { digest: built.digest } : {}) }; } diff --git a/packages/cli-ci/src/program.test.ts b/packages/cli-ci/src/program.test.ts index 37554999..598cd084 100644 --- a/packages/cli-ci/src/program.test.ts +++ b/packages/cli-ci/src/program.test.ts @@ -35,16 +35,8 @@ test('help lists the global options', () => { test('the universal commands take --strategy, and hybrid holds the instances’ three', () => { const program = buildProgram(); const names = program.commands.map((c) => c.name()); - assert.deepEqual(names, [ - 'registry', - 'plan', - 'build', - 'publish', - 'display-versions', - 'tag-display-version', - 'hybrid', - ]); - for (const name of ['registry', 'plan', 'build', 'publish']) { + assert.deepEqual(names, ['registry', 'plan', 'publish', 'display-versions', 'tag-display-version', 'hybrid']); + for (const name of ['registry', 'plan', 'publish']) { const command = program.commands.find((c) => c.name() === name); assert.ok( command?.options.some((o) => o.long === '--strategy'), From 31394f16235ac173a1bc376e5f0d26a0d65dd78b Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 21:53:54 +0100 Subject: [PATCH 129/194] Test: the workflows mount test, e2e per app, then publish and deploy, each with its runner size and its one cache, and none names verify Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/pipeline.test.ts | 172 ++++++++++++++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 packages/lib/src/pipeline.test.ts diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts new file mode 100644 index 00000000..6758b3bf --- /dev/null +++ b/packages/lib/src/pipeline.test.ts @@ -0,0 +1,172 @@ +// The pipeline of a repo from repo-turbo as its workflows mount it (§§ 1 and 2 +// PLX-Delivery), read from the rendered workflow templates and the reusable +// workflows of this repo: which job runs which verb, after which job, on which +// size and with which cache. No machine here runs a workflow: actionlint checks +// their syntax (check-ops), and newborns/pipeline.test.ts runs a newborn repo +// through the commands the jobs call, in the order and with the caches they +// give them. +import assert from 'node:assert/strict'; +import { readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { parse } from 'yaml'; +import { pathsOf, renderBundled, textOf } from './testing/bundled.ts'; + +const WORKFLOWS = join(import.meta.dirname, '..', '..', '..', '.github', 'workflows'); + +interface Step { + name?: string; + uses?: string; + if?: string; + run?: string; + with?: Record; + env?: Record; +} +interface Job { + uses?: string; + needs?: string | string[]; + if?: string; + with?: Record; + 'runs-on'?: string; + concurrency?: { group: string; 'cancel-in-progress': boolean }; + steps?: Step[]; +} + +/** A reusable workflow of this repo, parsed. */ +const reusable = ( + name: string, +): { on: { workflow_call: { inputs: Record } }; jobs: Record } => + parse(readFileSync(join(WORKFLOWS, name), 'utf8')); + +/** The jobs of a rendered workflow of repo-turbo. */ +async function jobsOf(answers: Record, workflow: string): Promise> { + const result = await renderBundled(['repo-turbo'], { tenant: 'acme', ...answers }); + return parse(textOf(result, `.github/workflows/${workflow}.yml`)).jobs; +} + +/** The reusable workflow a job calls, by its file name, without the ref. */ +const called = (job: Job | undefined): string => /\.github\/workflows\/([^@]+)@/.exec(job?.uses ?? '')?.[1] ?? ''; + +const needsOf = (job: Job | undefined): string[] => [job?.needs ?? []].flat(); + +const STRATEGIES = ['github', 'on-prem', 'hybrid']; + +test('an app repo’s on_commit runs the test job alone', async () => { + for (const ci_strategy of STRATEGIES) { + const jobs = await jobsOf({ ci_strategy }, 'on_commit'); + assert.deepEqual(Object.keys(jobs), ['test']); + assert.equal(called(jobs.test), '_test.yml'); + assert.equal(jobs.test?.with?.tasks ?? 'test', 'test'); + } +}); + +test('an app repo’s on_pr runs test, then e2e per app, and publishes and deploys nothing', async () => { + for (const ci_strategy of STRATEGIES) { + const jobs = await jobsOf({ ci_strategy }, 'on_pr'); + assert.deepEqual(Object.keys(jobs), ['test', 'e2e']); + assert.equal(called(jobs.test), '_test.yml'); + assert.equal(called(jobs.e2e), '_e2e.yml'); + assert.deepEqual(needsOf(jobs.e2e), ['test']); + assert.notEqual(jobs.e2e?.with?.deploy, true); + } +}); + +test('an app repo’s on_push runs test, e2e per app, then publish and deploy, which need both', async () => { + for (const display_versions of [false, true]) { + const jobs = await jobsOf({ display_versions }, 'on_push'); + assert.deepEqual(Object.keys(jobs), ['test', 'e2e', 'publish-deploy']); + assert.equal(called(jobs.test), '_test.yml'); + assert.equal(called(jobs.e2e), '_e2e.yml'); + assert.deepEqual(needsOf(jobs.e2e), ['test']); + assert.equal(jobs.e2e?.with?.deploy, true); + const publish = jobs['publish-deploy']; + assert.equal(called(publish), '_publish-deploy.yml'); + assert.deepEqual(needsOf(publish).sort(), ['e2e', 'test']); + for (const output of ['apps', 'deploys', 'environment']) + assert.equal(publish?.with?.[output], `\${{ needs.e2e.outputs.${output} }}`, output); + // A newer push cancels test and e2e of the older one, never a publish or a deploy. + for (const name of ['test', 'e2e']) assert.equal(jobs[name]?.concurrency?.['cancel-in-progress'], true, name); + assert.notEqual(publish?.concurrency?.['cancel-in-progress'], true); + } +}); + +test('a package repo’s on_pr is test and the changeset guard, its on_push test then publish', async () => { + const pr = await jobsOf({ publishes_packages: true }, 'on_pr'); + assert.equal(called(pr.test), '_test.yml'); + assert.equal(pr.test?.with?.tasks, 'test'); + assert.ok('changeset-status' in pr); + const push = await jobsOf({ publishes_packages: true }, 'on_push'); + assert.deepEqual(Object.keys(push), ['test', 'publish']); + assert.equal(called(push.test), '_test.yml'); + assert.equal(called(push.publish), '_publish-package.yml'); + assert.deepEqual(needsOf(push.publish), ['test']); +}); + +test('no workflow template and no reusable workflow names verify, as a phase or a verb', async () => { + for (const answers of [{}, { publishes_packages: true }, { ci_strategy: 'hybrid', display_versions: true }]) { + const result = await renderBundled(['repo-turbo'], { tenant: 'acme', ...answers }); + for (const path of pathsOf(result).filter((p) => p.startsWith('.github/workflows/'))) + assert.doesNotMatch(textOf(result, path), /verify/i, path); + } + for (const name of readdirSync(WORKFLOWS)) + assert.doesNotMatch(readFileSync(join(WORKFLOWS, name), 'utf8'), /verify/i, name); +}); + +/** The steps of a job that start a cache server, by the cache they ask for. */ +const caches = (job: Job | undefined): unknown[] => + (job?.steps ?? []).filter((s) => s.uses?.endsWith('/.github/actions/turbo-cache')).map((s) => s.with?.cache); + +/** The command lines of a job's steps, joined. */ +const runs = (job: Job | undefined): string => (job?.steps ?? []).map((s) => s.run ?? '').join('\n'); + +test('_test.yml runs the repo’s test on a medium runner with the shared cache', () => { + const workflow = reusable('_test.yml'); + assert.equal(workflow.on.workflow_call.inputs.tasks?.default, 'test'); + assert.equal(workflow.on.workflow_call.inputs.size?.default, 'medium'); + assert.deepEqual(Object.keys(workflow.jobs), ['test']); + assert.deepEqual(caches(workflow.jobs.test), ['shared']); +}); + +test('_e2e.yml plans, then per app builds the app and runs its suites on a large runner with the trusted cache alone', () => { + const { jobs } = reusable('_e2e.yml'); + assert.deepEqual(Object.keys(jobs), ['plan', 'e2e', 'cleanup']); + assert.match(runs(jobs.plan), /plx-ci plan/); + const e2e = jobs.e2e; + assert.deepEqual(needsOf(e2e), ['plan']); + assert.equal(e2e?.['runs-on'], '${{ matrix.runner }}'); + assert.deepEqual(caches(e2e), ['trusted']); + const lines = runs(e2e); + const build = lines.search(/mise run build "\$APP"/); + const suites = lines.search(/mise run e2e "\$APP"/); + assert.ok(build >= 0 && suites > build, 'build, then e2e'); + // Nothing before the build reads the shared cache: no check and no test in this job. + assert.doesNotMatch(lines, /mise run (check|test)|turbo run/); + // The key reaches the build alone. + const keyed = (e2e?.steps ?? []).filter((s) => JSON.stringify(s.env ?? {}).includes('SERVER_ACTIONS')); + assert.deepEqual( + keyed.map((s) => s.run), + ['mise run build "$APP"'], + ); + // The suite's browser is installed only for an app that has a suite. + const browser = (e2e?.steps ?? []).find((s) => /playwright install/.test(s.run ?? '')); + assert.equal(browser?.if, "${{ matrix.suite != '' }}"); + assert.deepEqual(needsOf(jobs.cleanup).sort(), ['e2e', 'plan']); +}); + +test('_publish-deploy.yml publishes on a small runner with the trusted cache, deploys after it, and reads no candidate registry', () => { + const { jobs } = reusable('_publish-deploy.yml'); + assert.deepEqual(Object.keys(jobs), ['publish', 'display-versions', 'deploy', 'tag-display-version']); + const publish = jobs.publish; + assert.match(publish?.['runs-on'] ?? '', /'ci-small'/); + assert.deepEqual(caches(publish), ['trusted']); + assert.match(runs(publish), /plx-ci publish "\$APP" "\$HASH" "\$GITHUB_SHA"/); + assert.ok(needsOf(jobs.deploy).includes('publish')); + for (const name of ['_e2e.yml', '_publish-deploy.yml']) { + const text = readFileSync(join(WORKFLOWS, name), 'utf8'); + assert.doesNotMatch( + text, + /plx-ci (registry|test|build)\b|bucket-registry|CI_REGISTRY|test-|--cache-from/, + name, + ); + } +}); From 52ab01076565ced995b89d9f5572a4f4c2c224ca Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 21:56:40 +0100 Subject: [PATCH 130/194] The pipeline's workflows: _test.yml, _e2e.yml and _publish-deploy.yml in place of _check.yml, _verify.yml and _release.yml, and repo-turbo's mounts of them on_commit runs test; on_pr test, then e2e per app; on_push test, e2e per app, then publish and deploy, which need both. The e2e job of every app runs mise run build, then mise run e2e, with the trusted cache alone; publish is small, with the trusted cache where it builds from the output. No job reads the candidate registry or the test hash. This repo's test.yml follows the rename. The pipeline test now counts only run steps among those given the key, as the step that loads it holds it too. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/_changeset.yml | 2 +- .github/workflows/_deploy.yml | 4 +- .github/workflows/{_verify.yml => _e2e.yml} | 245 ++++++------------ .../{_release.yml => _publish-deploy.yml} | 120 +++++---- .github/workflows/_publish-package.yml | 4 +- .github/workflows/{_check.yml => _test.yml} | 27 +- .github/workflows/test.yml | 4 +- packages/lib/src/pipeline.test.ts | 2 +- .../files/.github/workflows/on_pr.yml.jinja | 21 +- .../files/.github/workflows/on_push.yml.jinja | 45 ++-- ..._packages %}on_commit.yml{% endif %}.jinja | 6 +- templates/repo-turbo/template.yml | 2 +- 12 files changed, 222 insertions(+), 260 deletions(-) rename .github/workflows/{_verify.yml => _e2e.yml} (66%) rename .github/workflows/{_release.yml => _publish-deploy.yml} (73%) rename .github/workflows/{_check.yml => _test.yml} (81%) diff --git a/.github/workflows/_changeset.yml b/.github/workflows/_changeset.yml index 99591839..2d966dc3 100644 --- a/.github/workflows/_changeset.yml +++ b/.github/workflows/_changeset.yml @@ -67,7 +67,7 @@ jobs: changeset: runs-on: ${{ inputs.strategy == 'github' && 'ubuntu-latest' || 'ci-small' }} # mise install points core.hooksPath at hk; its hooks would run the repo's - # checks on this one commit, which the caller's verify job already does. + # checks on this one commit, which the caller's test job already does. env: HK_SKIP_HOOK: pre-commit,pre-push steps: diff --git a/.github/workflows/_deploy.yml b/.github/workflows/_deploy.yml index f5b3ce46..85f626c8 100644 --- a/.github/workflows/_deploy.yml +++ b/.github/workflows/_deploy.yml @@ -5,8 +5,8 @@ name: _deploy # pinned in the caller's mise.toml), never here; the caller supplies the host # and the environment. The caller is the app's SOURCE repo, because the verb # reads apps//docker/compose.yaml from the checkout and renders it onto -# the host with the image ref pinned: an app repo's release after the -# publish, or the platform repo's deploy.yml for a third-party app, whose +# the host with the image ref pinned: an app repo's _publish-deploy.yml after +# the publish, or the platform repo's deploy.yml for a third-party app, whose # compose.yaml pins its own image (no image-ref). # # The keys come from the vault `-ci` (§ 3 PLX-Secrets), read with its diff --git a/.github/workflows/_verify.yml b/.github/workflows/_e2e.yml similarity index 66% rename from .github/workflows/_verify.yml rename to .github/workflows/_e2e.yml index 3cc28ef8..cad017e7 100644 --- a/.github/workflows/_verify.yml +++ b/.github/workflows/_e2e.yml @@ -1,41 +1,43 @@ -name: _verify +name: _e2e -# Mounts `verify` for an app repo (§§ 1, 2 and 8 PLX-Delivery): build every -# app's image and test it, for the whole repo and run. The tenant's on_pr.yml -# and on_push.yml run it after _check.yml, which gates it: a commit that -# fails the check builds and launches nothing. The logic is plx-ci's -# (@plexus-ms/cli-ci, pinned in the caller's mise.toml); every step here is +# Mounts the e2e job of an app repo (§§ 1, 2 and 8 PLX-Delivery), and the plan +# in front of it: per app, on a large runner, the app's build and the suites +# that need it, the repo's own `mise run build `, then `mise run e2e +# `, against the trusted cache. The tenant's on_pr.yml and on_push.yml +# run it after _test.yml, which gates it: a commit that fails its test plans, +# builds and launches nothing. The logic is plx-ci's (@plexus-ms/cli-ci, +# pinned in the caller's mise.toml) and the repo's verbs; every step here is # one invocation. # -# plan small the build and test hashes from one Turbo dry run, the look-ups, -# the matrix; under hybrid, one instance per app that owes something -# build-and-test large per app, on one machine: `build`, the image from the pruned -# context, pushed to the registry as build-; then `test`, the -# app's compose stack on the candidate, its tests, the tag test- -# cleanup small hybrid only: delete what this run launched +# plan small every app's build hash from one Turbo dry run, its image +# looked up in the forge's registry, the matrix; under +# hybrid, one instance per app +# e2e large per app: `mise run build `, the browser of its suite +# where it has one, `mise run e2e ` +# cleanup small hybrid only: delete what this run launched # -# The large job carries two verbs because they want the same machine: a test -# starts when its own build ends, no second machine boots or idles meanwhile, -# and a failed build tests nothing. Which of the two a leg owes is the plan's: -# both, the test alone where the registry holds the build, or the build alone -# for an app without tests. The job's name is fixed, `build, test`, whatever a -# leg owes; the plan's log and the steps that run say which. +# Every app gets an e2e job, whatever the registry holds: a suite or a test +# file is no input of the app's build, so only Turbo's cache knows whether +# the job has anything to run, and a run on content it has seen replays both +# verbs from the cache. The build runs first, also for an app without a suite, +# so that the trusted cache holds every app's build output for its publish, +# which restores it from there (_publish-deploy.yml). The job neither checks +# nor tests (the test job did) and reaches the trusted cache alone, from a +# fresh checkout, so that nothing the shared cache supplied enters a build +# that is written to the trusted cache or shipped. CI is the trusted cache's +# boundary, a pull request's jobs included; a pull request from a fork gets +# no secrets and so no cache. The job needs no Docker daemon. The app's +# server-actions key reaches its build alone, which puts it into the output. # # Where a job of a size runs is the strategy's (`strategy`): the forge's # runners, the slots of the tenant's runner hosts, or, for a large job under -# hybrid, an instance of its own. Where the candidates live is `registry`: -# the pair on the tenant's object storage, or the forge's registry. -# -# A decision comes from a content hash, never from a diff: the same inputs -# are built once and tested once, and a run whose hashes all hit has no -# large job at all. +# hybrid, an instance of its own. # # The caller's secrets are one: the vault's service account token. # Everything else is read from the vault `-ci` (§ 3 PLX-Secrets): the -# apps' build-time keys always; the object-storage keys with a registry of -# the tenant's own; the cloud keys, the relay and the GitHub App under -# hybrid; the App also where the run plans a deploy, to read the operations -# repo's inventory. +# trusted cache's keys and the apps' server-actions keys always; the cloud +# keys, the relay and the GitHub App under hybrid; the App also where the run +# plans a deploy, to read the operations repo's inventory. on: workflow_call: @@ -49,19 +51,14 @@ on: required: false type: string default: github - registry: - description: "Where the candidates live: `ghcr`, the forge's registry, beside the published images; `own`, the registry pair on the tenant's object storage." - required: false - type: string - default: ghcr deploy: - description: Plan the deploys too, for the release that follows on an environment branch; a pull request deploys nowhere. + description: Plan the deploys too, for the publish and deploy that follow on an environment branch; a pull request deploys nowhere. required: false type: boolean default: false environment: description: >- - With `deploy`: the environment the run releases into. Empty derives + With `deploy`: the environment the run deploys into. Empty derives it from the branch (main → production, develop → staging, else none), which is the rule; a caller sets it only to stand in for an environment branch. @@ -115,25 +112,24 @@ on: required: true outputs: apps: - description: Every app planned, with its hashes, JSON; what _release.yml publishes. - value: ${{ jobs.plan.outputs.apps }} + description: Every app planned, with its build hash and what its publish does, JSON; what _publish-deploy.yml publishes. + value: ${{ jobs.plan.outputs.matrix }} deploys: - description: With `deploy`, the deploys of the release, JSON, for _release.yml; `[]` without an environment. + description: With `deploy`, the deploys of the run, JSON, for _publish-deploy.yml; `[]` without an environment. value: ${{ jobs.plan.outputs.deploys }} environment: - description: With `deploy`, the environment the run releases into; empty for none. + description: With `deploy`, the environment the run deploys into; empty for none. value: ${{ jobs.plan.outputs.environment }} permissions: contents: read - packages: write + packages: read actions: read env: EXO_VERSION: 1.103.2 CRANE_VERSION: 0.22.1 CI_STRATEGY: ${{ inputs.strategy }} - CI_REGISTRY: ${{ inputs.registry }} MAIL_TO: ${{ inputs.alerts-email }} VAULT: ${{ inputs.vault || format('{0}-ci', github.repository_owner) }} IMAGE_PREFIX: ${{ inputs.image-prefix || format('ghcr.io/{0}', github.repository_owner) }} @@ -143,7 +139,6 @@ jobs: runs-on: ${{ inputs.strategy == 'github' && 'ubuntu-latest' || 'ci-small' }} outputs: matrix: ${{ steps.plan.outputs.matrix }} - apps: ${{ steps.plan.outputs.apps }} deploys: ${{ steps.plan.outputs.deploys }} environment: ${{ steps.plan.outputs.environment }} steps: @@ -191,16 +186,6 @@ jobs: pnpm --filter @plexus-ms/cli-ci... run build >/dev/null mkdir -p bin && ln -sf "$PWD/packages/cli-ci/dist/plx-ci.js" bin/plx-ci && echo "$PWD/bin" >> "$GITHUB_PATH" - run: plx-ci --version - - name: Load the registry's keys from the vault - if: ${{ inputs.registry == 'own' }} - uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 - with: - export-env: true - env: - REGISTRY_ENDPOINT: op://${{ env.VAULT }}/bucket-registry/endpoint - REGISTRY_REGION: op://${{ env.VAULT }}/bucket-registry/region - REGISTRY_ACCESS_KEY: op://${{ env.VAULT }}/bucket-registry/access-key-id - REGISTRY_SECRET_KEY: op://${{ env.VAULT }}/bucket-registry/secret-access-key - name: Load the App's key from the vault if: ${{ inputs.deploy || inputs.strategy == 'hybrid' }} uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 @@ -242,17 +227,14 @@ jobs: # On the forge's runners only: the environment image of a slot or an # instance carries it (actions_runners). - name: Install crane - if: ${{ runner.environment == 'github-hosted' && inputs.registry == 'ghcr' }} + if: ${{ runner.environment == 'github-hosted' }} run: | mkdir -p "$HOME/.local/bin" && echo "$HOME/.local/bin" >> "$GITHUB_PATH" curl -fsSL "https://github.com/google/go-containerregistry/releases/download/v${CRANE_VERSION}/go-containerregistry_Linux_x86_64.tar.gz" | tar -xz -C "$HOME/.local/bin" crane - name: Log in to the forge's registry - if: ${{ inputs.registry == 'ghcr' }} env: GITHUB_TOKEN: ${{ github.token }} run: printf '%s' "$GITHUB_TOKEN" | crane auth login ghcr.io --username "$GITHUB_ACTOR" --password-stdin - - name: The registry - run: plx-ci registry # Where each app deploys is the operations repo's inventory # (PLX-Environment), checked out with the tenant's App. - name: A token that may read the operations repo @@ -276,7 +258,7 @@ jobs: env: DEPLOY: ${{ inputs.deploy && 'yes' || '' }} ENVIRONMENT: ${{ inputs.environment }} - run: plx-ci plan --test ${DEPLOY:+--deploy --environment "$ENVIRONMENT" --inventory operations/inventory} + run: plx-ci plan ${DEPLOY:+--deploy --environment "$ENVIRONMENT" --inventory operations/inventory} # Hybrid: one instance per leg, created at once, each waited for until # its runner is online. One that misses is kept, stopped and mailed # about, and replaced once. @@ -298,18 +280,18 @@ jobs: INSTANCE_TYPE: ${{ inputs.instance-type }} # Minutes after boot, each a timer the user-data arms (userData.ts). NO_JOB_MINUTES: 10 # no job started by then: the instance deletes itself, no mail - DEATH_MINUTES: 45 # a few minutes past build-and-test's timeout-minutes: a mail, then self-delete + DEATH_MINUTES: 45 # a few minutes past e2e's timeout-minutes: a mail, then self-delete POWEROFF_MINUTES: 50 # the last resort after the death deadline: power-off, the sweep removes it run: plx-ci hybrid create-instances "$MATRIX" - # One job per leg of the plan, an app that owes something, and one machine - # for it: the build where `matrix.build` says so, then the test where - # `matrix.test` carries its hash. A build that fails ends the job, so its - # test never starts; the other apps' legs run on (fail-fast off). The name - # is fixed: the forge does not evaluate `matrix` for a job it skips, and - # most runs owe nothing. What a leg owes is in the plan's log and its steps. - build-and-test: - name: build, test + # One job per app of the plan, on one machine: the app's build, the browser + # of its suite, its suites. The other apps' jobs run on when one fails + # (fail-fast off), and every publish of the run waits for all of them. The + # name is fixed: the forge does not evaluate `matrix` for a job it skips. + # The plan's mise steps hand PLX_PLATFORM to `plx-ci plan` as this job's + # hand it to the build, so that the two compute one hash. + e2e: + name: e2e needs: plan if: ${{ needs.plan.outputs.matrix != '[]' }} strategy: @@ -334,66 +316,13 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 - # mise, the repo's pins and its [env] for the later steps: on the forge's - # runners from mise-action; in the environment image of a slot or an - # instance (actions_runners), which carries mise and the common tools, - # from its ci-mise-install. - - uses: jdx/mise-action@v5 - if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} - with: - install_args: node npm:@plexus-ms/cli-ci - - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} - env: - MISE_GITHUB_TOKEN: ${{ github.token }} - run: ci-mise-install node npm:@plexus-ms/cli-ci - - uses: actions/checkout@v7 - if: ${{ inputs.tooling-ref != '' }} - with: - repository: plexus-ms/tooling - ref: ${{ inputs.tooling-ref }} - path: .plx-ci - - uses: actions/setup-node@v7 - if: ${{ inputs.tooling-ref != '' }} - with: - node-version-file: .plx-ci/mise.toml - - name: plx-ci from the unreleased tooling - if: ${{ inputs.tooling-ref != '' }} - run: | - cd .plx-ci && corepack enable && pnpm install --frozen-lockfile --ignore-scripts >/dev/null - pnpm --filter @plexus-ms/cli-ci... run build >/dev/null - mkdir -p bin && ln -sf "$PWD/packages/cli-ci/dist/plx-ci.js" bin/plx-ci && echo "$PWD/bin" >> "$GITHUB_PATH" - # A step output, not the job's environment: the key is the build's, and - # the test that follows on this machine has no business with it. - - name: The app's fixed Next key - id: key - if: ${{ matrix.build }} - uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 - env: - NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: op://${{ env.VAULT }}/app_${{ matrix.app }}/server-actions-key - - name: Load the registry's keys from the vault - if: ${{ inputs.registry == 'own' && inputs.strategy != 'hybrid' }} - uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 + - name: Start the trusted cache server + uses: $/.github/actions/turbo-cache with: - export-env: true - env: - REGISTRY_ENDPOINT: op://${{ env.VAULT }}/bucket-registry/endpoint - REGISTRY_REGION: op://${{ env.VAULT }}/bucket-registry/region - REGISTRY_ACCESS_KEY: op://${{ env.VAULT }}/bucket-registry/access-key-id - REGISTRY_SECRET_KEY: op://${{ env.VAULT }}/bucket-registry/secret-access-key - # plx-ci test finds the candidate with crane, which reads the login - # docker writes below; into the job's home, as in plan. - - name: Install crane - if: ${{ runner.environment == 'github-hosted' && inputs.registry == 'ghcr' && matrix.test != '' }} - run: | - mkdir -p "$HOME/.local/bin" && echo "$HOME/.local/bin" >> "$GITHUB_PATH" - curl -fsSL "https://github.com/google/go-containerregistry/releases/download/v${CRANE_VERSION}/go-containerregistry_Linux_x86_64.tar.gz" | tar -xz -C "$HOME/.local/bin" crane - - name: Log in to the forge's registry - if: ${{ inputs.registry == 'ghcr' }} - env: - GITHUB_TOKEN: ${{ github.token }} - run: printf '%s' "$GITHUB_TOKEN" | docker login ghcr.io --username "$GITHUB_ACTOR" --password-stdin - # The tenant's private packages (§ 5 PLX-Delivery), for the test's install - # and, as a BuildKit secret, for the image's (plx-ci build): the job's own token + cache: trusted + vault: ${{ inputs.vault }} + op-service-account-token: ${{ secrets.op-service-account-token }} + # The tenant's private packages (§ 5 PLX-Delivery): the job's own token # in a user-level npmrc of the job's own, which pnpm and npm read beside # the scope's registry in pnpm-workspace.yaml. The repo holds no token, # and the package grants this repo's workflows read access on the forge. @@ -404,42 +333,40 @@ jobs: run: | printf '//npm.pkg.github.com/:_authToken=%s\n' "$GITHUB_TOKEN" > "$RUNNER_TEMP/npmrc" echo "NPM_CONFIG_USERCONFIG=$RUNNER_TEMP/npmrc" >> "$GITHUB_ENV" - - name: The registry - run: plx-ci registry - # The specs and their dependencies, the app's own; Chromium's headless - # shell, which is all a headless spec launches, at the Playwright version - # the lockfile pins, with its system libraries on the forge's runners - # (the environment image carries them). Started here in the background, - # so that it runs beside the build, and awaited below. - - name: Start installing the app's dependencies and the browser - if: ${{ matrix.test != '' }} - run: | - { - set +e - ( - set -e - corepack enable - pnpm install --frozen-lockfile --filter "{./apps/${{ matrix.app }}}..." - pnpm --filter "./apps/${{ matrix.app }}" exec playwright install ${{ runner.environment == 'github-hosted' && '--with-deps' || '' }} --only-shell chromium - ) - echo $? > "$RUNNER_TEMP/install.exit" - } > "$RUNNER_TEMP/install.log" 2>&1 & - echo $! > "$RUNNER_TEMP/install.pid" + # mise, all of the repo's pins and its [env] for the later steps: on the + # forge's runners from mise-action; in the environment image of a slot + # or an instance (actions_runners), which carries mise and the common + # tools, from its ci-mise-install. + - uses: jdx/mise-action@v5 + if: ${{ runner.environment == 'github-hosted' }} + - if: ${{ runner.environment != 'github-hosted' }} + env: + MISE_GITHUB_TOKEN: ${{ github.token }} + run: ci-mise-install + # A step output, not the job's environment: the key is the build's. + - name: The app's server-actions key + id: key + uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 + env: + NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: op://${{ env.VAULT }}/app_${{ matrix.app }}/server-actions-key - name: Build - if: ${{ matrix.build }} env: + APP: ${{ matrix.app }} NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ steps.key.outputs.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }} - run: plx-ci build "${{ matrix.app }}" "${{ matrix.hash }}" "$GITHUB_SHA" - # The install's log, to its end, and its outcome; an install that died - # without one has failed. - - name: Install the app's dependencies and the browser - if: ${{ matrix.test != '' }} - run: | - tail --pid="$(cat "$RUNNER_TEMP/install.pid")" -n +1 -f "$RUNNER_TEMP/install.log" - exit "$(cat "$RUNNER_TEMP/install.exit" 2>/dev/null || echo 1)" - - name: Test - if: ${{ matrix.test != '' }} - run: plx-ci test "${{ matrix.app }}" "${{ matrix.hash }}" "${{ matrix.test }}" + run: mise run build "$APP" + # Chromium at the version the suite's Playwright pins, into the cache + # the medium and large slots share; with its system libraries on the + # forge's runners (the environment image carries them). + - name: The suite's browser + if: ${{ matrix.suite != '' }} + env: + SUITE: ${{ matrix.suite }} + WITH_DEPS: ${{ runner.environment == 'github-hosted' && 'yes' || '' }} + run: cd "$SUITE" && pnpm exec playwright install ${WITH_DEPS:+--with-deps} chromium + - name: E2E + env: + APP: ${{ matrix.app }} + run: mise run e2e "$APP" # Hybrid: delete what this run launched, whatever the jobs ended in: an # instance a failed job left, or a runner that never took one. Skipped @@ -449,7 +376,7 @@ jobs: # fails the run: what it leaves, the instances' own deadlines and the # daily housekeeping remove. cleanup: - needs: [plan, build-and-test] + needs: [plan, e2e] if: >- ${{ always() && inputs.strategy == 'hybrid' && needs.plan.result != 'skipped' && !(needs.plan.result == 'success' && needs.plan.outputs.matrix == '[]') }} diff --git a/.github/workflows/_release.yml b/.github/workflows/_publish-deploy.yml similarity index 73% rename from .github/workflows/_release.yml rename to .github/workflows/_publish-deploy.yml index 7c84bcba..345fb8ce 100644 --- a/.github/workflows/_release.yml +++ b/.github/workflows/_publish-deploy.yml @@ -1,34 +1,47 @@ -name: _release +name: _publish-deploy -# Mounts `release` for an app repo (§§ 1, 2 and 8 PLX-Delivery): publish -# every app's tested image under its commit and deploy it into the run's -# environment. The tenant's on_push.yml runs it after _check.yml and -# _verify.yml on a push to an environment branch, and hands it what the -# verify planned: the apps, the environment, and where each app deploys. +# Mounts publish and deploy for an app repo (§§ 1, 2, 4 and 8 PLX-Delivery): +# every app's image under its commit in the forge's registry, then each +# deployed into the run's environment. The tenant's on_push.yml runs it on a +# push to an environment branch after _test.yml and _e2e.yml, whose jobs it +# needs, and hands it what the plan of _e2e.yml said: the apps, the +# environment, and where each app deploys. # -# publish small the tested manifest under its commit in the forge's registry +# publish small per app: tag the image the registry holds, or +# build it from the app's build output, restored +# from the trusted cache, and push it # display-versions small what each app shows as its version, and the version production cuts # deploy small _deploy.yml per app with a target in the environment # tag-display-version small the cut version's tag and GitHub Release, once every deploy is green # +# That a published image was tested is the order of the jobs, and nothing +# records it: this workflow runs only once the run's test job and every e2e +# job have passed, so an app's image is published from content whose test and +# e2e passed in the same run, and a failed e2e of one app publishes nothing. +# A publish that builds reaches the trusted cache alone, from a fresh checkout, +# where the app's e2e job left the build output, and builds the image through +# the runner's Docker under github and the runner host's BuildKit service +# under on-prem and hybrid (plx-ci publish says how). One whose image exists, +# a promotion's or a change to tests alone, builds nothing, adds the commit's +# tag, and its deploy leaves the app running where the host serves that image. +# # The two display-version jobs run only with the input `display-versions`; -# without it the release is publish and deploy and nothing else. A repo that +# without it this workflow is publish and deploy and nothing else. A repo that # turns it on states `major:` in its PLEXUS.md, grants this workflow # `contents: write` (the tag and the Release), uses ${PLEXUS_DISPLAY_VERSION} -# in the compose files of the apps that show it, and serializes its release -# job (a concurrency group per ref that cancels nothing), so that two pushes -# to main never take the same number. plx-ci's display-versions states how -# the versions are read from the tags and the registry (PLX-Releases). +# in the compose files of the apps that show it, and serializes the job that +# calls this workflow (a concurrency group per ref that cancels nothing), so +# that two pushes to main never take the same number. plx-ci's +# display-versions states how the versions are read from the tags and the +# registry (PLX-Releases). # -# Every deploy is handed the commit released, display versions or not: an +# Every deploy is handed the commit deployed, display versions or not: an # app whose compose file uses ${PLEXUS_COMMIT_SHA} shows the commit it was # started from, and one that does not is deployed as before. # -# A promotion never builds: a commit whose images the registry holds is -# published from them and deployed. Without an environment (a run by hand on -# a branch that names none) nothing is released. A release once started runs -# to its end: the caller cancels a superseded check or verify, never this -# (§ 2 PLX-Delivery). +# Without an environment (a run by hand on a branch that names none) nothing +# is published or deployed. Once started it runs to its end: the caller +# cancels a superseded test or e2e, never this (§ 2 PLX-Delivery). on: workflow_call: @@ -42,26 +55,21 @@ on: required: false type: string default: github - registry: - description: "Where the candidates live: `ghcr`, the forge's registry, beside the published images; `own`, the registry pair on the tenant's object storage." - required: false - type: string - default: ghcr overlay: description: "How a deploy reaches the hosts: `netbird`, over the tenant's overlay, which the job joins itself where its runner is not on it; `none`, as named." required: false type: string default: none apps: - description: The apps to publish, with their hashes, JSON; _verify.yml's output `apps`. + description: The apps to publish, with their hashes and what each publish does, JSON; _e2e.yml's output `apps`. required: true type: string deploys: - description: The deploys, JSON; _verify.yml's output `deploys`. + description: The deploys, JSON; _e2e.yml's output `deploys`. required: true type: string environment: - description: The environment released into; _verify.yml's output `environment`. Empty releases nothing. + description: The environment deployed into; _e2e.yml's output `environment`. Empty publishes and deploys nothing. required: true type: string image-prefix: @@ -82,9 +90,17 @@ on: display-versions: description: >- Give every deployed app a display version, PLEXUS_DISPLAY_VERSION, - and cut a version tag with a GitHub Release when a production release - changes an app (PLX-Releases). Off: the release neither computes nor - tags anything. + and cut a version tag with a GitHub Release when a deploy to production + changes an app (PLX-Releases). Off: nothing computes or tags a version. + required: false + type: boolean + default: false + private-packages: + description: >- + The repo installs private packages of the tenant's from the forge's + package registry (§ 5 PLX-Delivery): a publish that builds logs in to + it with the job's own token, which needs `packages: read` from the + caller. required: false type: boolean default: false @@ -109,14 +125,13 @@ on: env: CRANE_VERSION: 0.22.1 CI_STRATEGY: ${{ inputs.strategy }} - CI_REGISTRY: ${{ inputs.registry }} CI_OVERLAY: ${{ inputs.overlay }} VAULT: ${{ inputs.vault || format('{0}-ci', github.repository_owner) }} IMAGE_PREFIX: ${{ inputs.image-prefix || format('ghcr.io/{0}', github.repository_owner) }} jobs: publish: - if: ${{ inputs.environment != '' }} + if: ${{ inputs.environment != '' && inputs.apps != '[]' }} permissions: contents: read packages: write @@ -141,6 +156,25 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 + # Only where publish builds from the output: the restore of `mise run + # build ` reads the trusted cache, where the app's e2e job left it. + - name: Start the trusted cache server + if: ${{ matrix.build && matrix.context == 'output' }} + uses: $/.github/actions/turbo-cache + with: + cache: trusted + vault: ${{ inputs.vault }} + op-service-account-token: ${{ secrets.op-service-account-token }} + # The tenant's private packages (§ 5 PLX-Delivery), for the restore's + # install and, as a BuildKit secret, for a Dockerfile of the app's own: + # the job's own token in a user-level npmrc of the job's own. + - name: Log in to the forge's package registry + if: ${{ inputs.private-packages && matrix.build }} + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + printf '//npm.pkg.github.com/:_authToken=%s\n' "$GITHUB_TOKEN" > "$RUNNER_TEMP/npmrc" + echo "NPM_CONFIG_USERCONFIG=$RUNNER_TEMP/npmrc" >> "$GITHUB_ENV" # mise, the repo's pins and its [env] for the later steps: on the forge's # runners from mise-action; in the environment image of a slot or an # instance (actions_runners), which carries mise and the common tools, @@ -169,16 +203,14 @@ jobs: cd .plx-ci && corepack enable && pnpm install --frozen-lockfile --ignore-scripts >/dev/null pnpm --filter @plexus-ms/cli-ci... run build >/dev/null mkdir -p bin && ln -sf "$PWD/packages/cli-ci/dist/plx-ci.js" bin/plx-ci && echo "$PWD/bin" >> "$GITHUB_PATH" - - name: Load the registry's keys from the vault - if: ${{ inputs.registry == 'own' }} + # A step output, not the job's environment: the key is the build's, where + # the restore misses the cache, or a Dockerfile of the app's own's. + - name: The app's server-actions key + id: key + if: ${{ matrix.build }} uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 - with: - export-env: true env: - REGISTRY_ENDPOINT: op://${{ env.VAULT }}/bucket-registry/endpoint - REGISTRY_REGION: op://${{ env.VAULT }}/bucket-registry/region - REGISTRY_ACCESS_KEY: op://${{ env.VAULT }}/bucket-registry/access-key-id - REGISTRY_SECRET_KEY: op://${{ env.VAULT }}/bucket-registry/secret-access-key + NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: op://${{ env.VAULT }}/app_${{ matrix.app }}/server-actions-key # On the forge's runners only: the environment image of a slot or an # instance carries it (actions_runners). - name: Install crane @@ -190,12 +222,12 @@ jobs: env: GITHUB_TOKEN: ${{ github.token }} run: printf '%s' "$GITHUB_TOKEN" | crane auth login ghcr.io --username "$GITHUB_ACTOR" --password-stdin - - name: The registry - run: plx-ci registry - name: Publish env: - TEST: ${{ matrix.test }} - run: plx-ci publish "${{ matrix.app }}" "${{ matrix.hash }}" "$GITHUB_SHA" ${TEST:+--test "$TEST"} + APP: ${{ matrix.app }} + HASH: ${{ matrix.hash }} + NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ steps.key.outputs.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }} + run: plx-ci publish "$APP" "$HASH" "$GITHUB_SHA" # One deploy per app with a target in the environment; an app without a # record there has no deployment there, which the plan said. The nested @@ -291,7 +323,7 @@ jobs: op-service-account-token: ${{ secrets.op-service-account-token }} # The version names a state of production that happened: only once every - # deploy of the release is green, and only when it cut one. A re-run of the + # deploy of the run is green, and only when it cut one. A re-run of the # failed deploys gets here with the same number. tag-display-version: needs: [display-versions, deploy] diff --git a/.github/workflows/_publish-package.yml b/.github/workflows/_publish-package.yml index 1e15ea87..ae1eccd7 100644 --- a/.github/workflows/_publish-package.yml +++ b/.github/workflows/_publish-package.yml @@ -6,7 +6,7 @@ name: _publish-package # push that merges that PR it publishes. To npm that is token-less through # OIDC trusted publishing, with provenance; to the forge's package registry, # where a tenant keeps its private packages, with the job's own token. The -# caller runs this after _check.yml in the same run; the verb does not check +# caller runs this after _test.yml in the same run; the verb does not check # again. # # With `snapshot`, nothing is versioned on the trunk: the pending changesets @@ -51,7 +51,7 @@ jobs: # hk, so hk's hooks would fire on anything changesets/action commits or # pushes through the git CLI. Wrong in both directions: pre-push cannot # resolve the tag objects `changeset publish` creates, and re-running - # the checks here only repeats what the check job already ran. + # the checks here only repeats what the test job already ran. env: HK_SKIP_HOOK: pre-commit,pre-push steps: diff --git a/.github/workflows/_check.yml b/.github/workflows/_test.yml similarity index 81% rename from .github/workflows/_check.yml rename to .github/workflows/_test.yml index 7865fc68..9d4b6e9f 100644 --- a/.github/workflows/_check.yml +++ b/.github/workflows/_test.yml @@ -1,17 +1,20 @@ -name: _check +name: _test -# Mounts `check` (§§ 1 and 2 PLX-Delivery): the steps that ascertain code -# quality and need no machine in particular, repo-wide. In an app repo that -# is lint, typecheck and the pure tests, the part of verify that gates -# everything else: a commit that fails here builds and launches nothing. A -# repo without images to build passes `tasks: verify`, its whole contract -# verb. The incantations are the repo's own mise tasks. +# Mounts the test job (§§ 1 and 2 PLX-Delivery): the repo's own mise tasks, +# by default `test`, which runs `check` first, repo-wide, on a medium runner, +# in a checkout of the repo exactly as a developer runs them. It needs no +# built app and no Docker daemon, and gates everything after it: a commit that +# fails here plans, builds and launches nothing. Every repo mounts it, on +# every commit and every pull request; a repo with other verbs to run in the +# same job names them in `tasks`. # # Turbo's shared remote cache (§ 8 PLX-Delivery), for every repo: a cache # server for the length of the job, on loopback, backed by the bucket # -ci-turbo, started by the step turbo-cache of this repo at the # commit of this workflow; a task whose inputs did not change is replayed from -# any earlier job on any runner. A tenant without the bucket runs without it. +# any earlier job or machine that wrote the bucket. A tenant without the +# bucket runs without it. This job never starts the trusted cache: what the +# shared bucket supplied stays out of every build that ships (_e2e.yml). on: workflow_call: @@ -31,10 +34,10 @@ on: type: string default: medium tasks: - description: The repo's mise tasks to run, in order, separated by spaces. `check` includes `lint` by contract (`PLX-Repo/SubVerbs`). + description: The repo's mise tasks to run, in order, separated by spaces; `test` runs `check` first. required: false type: string - default: check + default: test private-packages: description: >- The repo installs private packages of the tenant's from the forge's @@ -58,7 +61,7 @@ on: # have to name the larger set, and every caller would then have to grant it. jobs: - check: + test: runs-on: ${{ inputs.strategy == 'github' && 'ubuntu-latest' || format('ci-{0}', inputs.size) }} steps: - uses: actions/checkout@v7 @@ -89,7 +92,7 @@ jobs: env: MISE_GITHUB_TOKEN: ${{ github.token }} run: ci-mise-install - - name: Check + - name: Test env: TASKS: ${{ inputs.tasks }} run: for task in $TASKS; do mise run "$task"; done diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 016e65a6..7bde1641 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,7 +1,7 @@ name: test # Mounts the verbs on this repo's own events (§ 2 PLX-Delivery), through this -# repo's own reusable _check.yml with the verbs as its tasks: `test` on every +# repo's own reusable _test.yml with the verbs as its tasks: `test` on every # push, which includes `check` (`mise test` runs it first) and is the same # `mise test` the pre-push hook runs, and on a pull request `test`, then `e2e`, # the newborn tests, which need the network, a local registry and Docker. The @@ -24,6 +24,6 @@ concurrency: jobs: test: - uses: ./.github/workflows/_check.yml + uses: ./.github/workflows/_test.yml with: tasks: ${{ github.event_name == 'pull_request' && 'test e2e' || 'test' }} diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index 6758b3bf..ccda46d2 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -142,7 +142,7 @@ test('_e2e.yml plans, then per app builds the app and runs its suites on a large // Nothing before the build reads the shared cache: no check and no test in this job. assert.doesNotMatch(lines, /mise run (check|test)|turbo run/); // The key reaches the build alone. - const keyed = (e2e?.steps ?? []).filter((s) => JSON.stringify(s.env ?? {}).includes('SERVER_ACTIONS')); + const keyed = (e2e?.steps ?? []).filter((s) => s.run && JSON.stringify(s.env ?? {}).includes('SERVER_ACTIONS')); assert.deepEqual( keyed.map((s) => s.run), ['mise run build "$APP"'], diff --git a/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja b/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja index f51798aa..a8f5763e 100644 --- a/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja +++ b/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja @@ -1,7 +1,7 @@ {% if publishes_packages %}{% raw %}name: on_pr # Generated from plexus-ms/tooling, templates/repo-turbo: edit the template, never this file. -# A package repo's pull-request mount, check and the changeset guard (§ 5 PLX-Delivery). +# A package repo's pull-request mount, the test job and the changeset guard (§ 5 PLX-Delivery). on: pull_request: @@ -15,8 +15,8 @@ concurrency: cancel-in-progress: true jobs: - check: - uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 + test: + uses: plexus-ms/tooling/.github/workflows/_test.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} tasks: test{% endraw %}{% if private_packages_scope %} @@ -57,7 +57,7 @@ jobs: {% endraw %}{% endif %}{% else %}{% raw %}name: on_pr # Generated from plexus-ms/tooling, templates/repo-turbo: edit the template, never this file. -# An app repo's pull-request mount, check then verify (§ 2 PLX-Delivery). +# An app repo's pull-request mount, the test job, then the e2e job per app; it publishes and deploys nothing (§ 2 PLX-Delivery). on: pull_request: @@ -65,7 +65,7 @@ on: permissions: contents: read - packages: write + packages: read actions: read concurrency: @@ -73,20 +73,19 @@ concurrency: cancel-in-progress: true jobs: - check: - uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 + test: + uses: plexus-ms/tooling/.github/workflows/_test.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }}{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} secrets: op-service-account-token: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} - verify: - needs: check - uses: plexus-ms/tooling/.github/workflows/_verify.yml@0.133.0 + e2e: + needs: test + uses: plexus-ms/tooling/.github/workflows/_e2e.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - registry: {% endraw %}{{ ci_registry }}{% raw %} alerts-email: '{% endraw %}{{ alerts_email }}{% raw %}'{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} secrets: diff --git a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja b/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja index 545b3ab4..51b29e0c 100644 --- a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja +++ b/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja @@ -1,7 +1,7 @@ {% if publishes_packages %}{% raw %}name: on_push # Generated from plexus-ms/tooling, templates/repo-turbo: edit the template, never this file. -# A package repo's trunk mount, check then publish; started by hand on a branch, snapshot versions of it (§ 5 PLX-Delivery). +# A package repo's trunk mount, the test job then publish; started by hand on a branch, snapshot versions of it (§ 5 PLX-Delivery). on: push: @@ -26,8 +26,8 @@ permissions: {%- endif %}{% raw %} jobs: - check: - uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 + test: + uses: plexus-ms/tooling/.github/workflows/_test.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} tasks: test{% endraw %}{% if private_packages_scope %} @@ -36,7 +36,7 @@ jobs: op-service-account-token: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} publish: - needs: check + needs: test uses: plexus-ms/tooling/.github/workflows/_publish-package.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} @@ -45,7 +45,7 @@ jobs: {% endraw %}{% else %}{% raw %}name: on_push # Generated from plexus-ms/tooling, templates/repo-turbo: edit the template, never this file. -# An app repo's environment-branch mount, check, verify, release (§§ 2 and 3 PLX-Delivery). +# An app repo's environment-branch mount: the test job, the e2e job per app, then publish and deploy into the branch's environment (§§ 2 and 3 PLX-Delivery). on: # No paths filter: a branch created at a known commit pushes no files and would start nothing. @@ -59,52 +59,53 @@ permissions: actions: read jobs: - check: + # A newer push cancels the test and e2e jobs of an older one, never its publish or deploy. + test: concurrency: - group: on_push-verify-${{ github.ref }} + group: on_push-test-${{ github.ref }} cancel-in-progress: true - uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 + uses: plexus-ms/tooling/.github/workflows/_test.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }}{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} secrets: op-service-account-token: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} - verify: - needs: check + e2e: + needs: test concurrency: - group: on_push-verify-${{ github.ref }} + group: on_push-test-${{ github.ref }} cancel-in-progress: true - uses: plexus-ms/tooling/.github/workflows/_verify.yml@0.133.0 + uses: plexus-ms/tooling/.github/workflows/_e2e.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - registry: {% endraw %}{{ ci_registry }}{% raw %} deploy: true alerts-email: '{% endraw %}{{ alerts_email }}{% raw %}'{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} secrets: op-service-account-token: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} - release: - needs: verify{% endraw %}{% if display_versions %}{% raw %} + # Only after the test job and every e2e job of the run: that is what makes a published image a tested one. + publish-deploy: + needs: [test, e2e]{% endraw %}{% if display_versions %}{% raw %} # Display versions (PLX-Releases): serialized per branch and never cancelled, so that two pushes to main # never take the same number, and allowed to write the tag and the GitHub Release of the version it cuts. concurrency: - group: on_push-release-${{ github.ref }} + group: on_push-publish-${{ github.ref }} cancel-in-progress: false permissions: contents: write packages: write actions: read{% endraw %}{% endif %}{% raw %} - uses: plexus-ms/tooling/.github/workflows/_release.yml@0.133.0 + uses: plexus-ms/tooling/.github/workflows/_publish-deploy.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - registry: {% endraw %}{{ ci_registry }}{% raw %} overlay: {% endraw %}{{ ci_overlay }}{% raw %} - apps: ${{ needs.verify.outputs.apps }} - deploys: ${{ needs.verify.outputs.deploys }} - environment: ${{ needs.verify.outputs.environment }}{% endraw %}{% if display_versions %} - display-versions: true{% endif %}{% raw %} + apps: ${{ needs.e2e.outputs.apps }} + deploys: ${{ needs.e2e.outputs.deploys }} + environment: ${{ needs.e2e.outputs.environment }}{% endraw %}{% if display_versions %} + display-versions: true{% endif %}{% if private_packages_scope %} + private-packages: true{% endif %}{% raw %} secrets: op-service-account-token: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }} {% endraw %}{% endif %} \ No newline at end of file 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 8541f4cc..68020bb5 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,7 +1,7 @@ {% raw %}name: on_commit # Generated from plexus-ms/tooling, templates/repo-turbo: edit the template, never this file. -# An app repo's mount for a push to any other branch, check alone (§ 2 PLX-Delivery). +# An app repo's mount for a push to any other branch, the test job alone (§ 2 PLX-Delivery). on: push: @@ -17,8 +17,8 @@ concurrency: cancel-in-progress: true jobs: - check: - uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 + test: + uses: plexus-ms/tooling/.github/workflows/_test.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }}{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} diff --git a/templates/repo-turbo/template.yml b/templates/repo-turbo/template.yml index 7b0c2bd5..45c956bf 100644 --- a/templates/repo-turbo/template.yml +++ b/templates/repo-turbo/template.yml @@ -32,7 +32,7 @@ questions: ci_strategy: type: str - help: "Where the CI jobs run (§ 8 PLX-Delivery): github, the forge's runners; on-prem, container slots on runner hosts of the tenant's own for every job; hybrid, slots for the small and medium jobs and a throwaway cloud instance for each build and test" + help: "Where the CI jobs run (§ 8 PLX-Delivery): github, the forge's runners; on-prem, container slots on runner hosts of the tenant's own for every job; hybrid, slots for the small and medium jobs and a throwaway cloud instance for each app's e2e job" default: github choices: - github From 91a4707d561470d44d96460779897150836ee34f Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 21:56:49 +0100 Subject: [PATCH 131/194] repo-operations calls _test.yml, the name _check.yml has now Forced by the rename of the reusable workflow; nothing else of the template changes. Co-Authored-By: Claude Fable 5.2 --- .../repo-operations/files/.github/workflows/on_commit.yml.jinja | 2 +- .../repo-operations/files/.github/workflows/on_pr.yml.jinja | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 1154bdca..a2a7ded0 100644 --- a/templates/repo-operations/files/.github/workflows/on_commit.yml.jinja +++ b/templates/repo-operations/files/.github/workflows/on_commit.yml.jinja @@ -17,7 +17,7 @@ concurrency: jobs: check: - uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 + uses: plexus-ms/tooling/.github/workflows/_test.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} size: small diff --git a/templates/repo-operations/files/.github/workflows/on_pr.yml.jinja b/templates/repo-operations/files/.github/workflows/on_pr.yml.jinja index 0c29e5c8..ebc68cdb 100644 --- a/templates/repo-operations/files/.github/workflows/on_pr.yml.jinja +++ b/templates/repo-operations/files/.github/workflows/on_pr.yml.jinja @@ -16,7 +16,7 @@ concurrency: jobs: check: - uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 + uses: plexus-ms/tooling/.github/workflows/_test.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} size: small From 827c06839c26e26cfcf40de2a80e3d7e9a5a76d5 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 21:57:05 +0100 Subject: [PATCH 132/194] The cache tests of repo-turbo read _test.yml and its job test, the names _check.yml and check have now Forced by the rename of the reusable workflow and its job; what the tests hold is unchanged. Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/repoTurboCache.test.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/lib/src/repoTurboCache.test.ts b/packages/lib/src/repoTurboCache.test.ts index 0b966bb0..575ad567 100644 --- a/packages/lib/src/repoTurboCache.test.ts +++ b/packages/lib/src/repoTurboCache.test.ts @@ -338,13 +338,13 @@ test('a checkout without origin, or whose origin names no owner, has no team, an } }); -// Where a job gets its cache server: the step turbo-cache of this repo, which _check.yml starts for every repo. +// Where a job gets its cache server: the step turbo-cache of this repo, which _test.yml starts for every repo. /** The job `name` of a rendered workflow, as text, up to the next job. */ const jobOf = (workflow: string, name: string): string => new RegExp(`^ ${name}:\\n([\\s\\S]*?)(?=^ [\\w-]+:\\n|(?![\\s\\S]))`, 'm').exec(workflow)?.[1] ?? ''; -test('no workflow of a repo asks for the cache, and the answer ci_registry changes nothing of the check job', async () => { +test('no workflow of a repo asks for the cache, and the answer ci_registry changes nothing of the test job', async () => { for (const ci_strategy of ['github', 'on-prem', 'hybrid']) for (const answers of SHAPES) { const results = await Promise.all( @@ -356,27 +356,27 @@ test('no workflow of a repo asks for the cache, and the answer ci_registry chang const [ghcr, own] = results; if (!ghcr || !own) throw new Error('two renders'); for (const path of pathsOf(ghcr).filter((p) => p.startsWith('.github/workflows/on_'))) - assert.equal(jobOf(textOf(ghcr, path), 'check'), jobOf(textOf(own, path), 'check'), `${path} ${ci_strategy}`); + assert.equal(jobOf(textOf(ghcr, path), 'test'), jobOf(textOf(own, path), 'test'), `${path} ${ci_strategy}`); } }); -test('a package repo’s check job hands the vault’s token to _check.yml, as an app repo’s does', async () => { +test('a package repo’s test job hands the vault’s token to _test.yml, as an app repo’s does', async () => { for (const answers of SHAPES) { const result = await render(answers); for (const path of ['.github/workflows/on_pr.yml', '.github/workflows/on_push.yml']) { - const check = jobOf(textOf(result, path), 'check'); - assert.match(check, /_check\.yml@/, path); + const check = jobOf(textOf(result, path), 'test'); + assert.match(check, /_test\.yml@/, path); assert.match(check, /op-service-account-token: \$\{\{ secrets\.OP_SERVICE_ACCOUNT_TOKEN \}\}/, path); } } }); -test('_check.yml starts the shared cache server for every repo, by the step at the commit of the workflow', () => { +test('_test.yml starts the shared cache server for every repo, by the step at the commit of the workflow', () => { const workflow = parse( - readFileSync(join(import.meta.dirname, '..', '..', '..', '.github', 'workflows', '_check.yml'), 'utf8'), + readFileSync(join(import.meta.dirname, '..', '..', '..', '.github', 'workflows', '_test.yml'), 'utf8'), ); assert.ok(!('turbo-cache' in workflow.on.workflow_call.inputs), 'no input switches the cache'); - const steps: { uses?: string; if?: string; with?: Record }[] = workflow.jobs.check.steps; + const steps: { uses?: string; if?: string; with?: Record }[] = workflow.jobs.test.steps; const cache = steps.filter((step) => step.uses?.includes('turbo-cache')); assert.equal(cache.length, 1); assert.equal(cache[0]?.uses, '$/.github/actions/turbo-cache'); From 7c1425b2b45f70d9557672539c09edd173c2c5a6 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 21:57:30 +0100 Subject: [PATCH 133/194] plx-ci and the lib tests name the reusable workflows and the large job by their new names Forced by the renames: _e2e.yml holds the plan's outputs and the instances' cleanup, an instance runs an app's e2e job, and _test.yml is what a workflow asks for tasks. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/commands/displayVersions.ts | 4 ++-- packages/cli-ci/src/commands/hybrid.ts | 2 +- packages/cli-ci/src/core/createInstances.ts | 4 ++-- packages/cli-ci/src/core/displayVersions.test.ts | 2 +- packages/cli-ci/src/core/userData.ts | 2 +- packages/lib/src/repoTurbo.test.ts | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/cli-ci/src/commands/displayVersions.ts b/packages/cli-ci/src/commands/displayVersions.ts index 622e8fed..fcb23677 100644 --- a/packages/cli-ci/src/commands/displayVersions.ts +++ b/packages/cli-ci/src/commands/displayVersions.ts @@ -26,7 +26,7 @@ import { displayVersions, tagDisplayVersion } from '../core/displayVersions.ts'; import { contextOf } from '../program.ts'; import { imagePrefix, need } from './shared.ts'; -/** The app names of _verify.yml's output `deploys`. */ +/** The app names of _e2e.yml's output `deploys`. */ export function appsOfDeploys(json: string): string[] { let data: unknown; try { @@ -48,7 +48,7 @@ export function register(program: Command): void { .description('the string each deployed app shows as its version, and the version a production release cuts') .argument('', 'the environment released into') .argument('', 'the commit released') - .requiredOption('--deploys ', 'the deploys, _verify.yml’s output `deploys`') + .requiredOption('--deploys ', 'the deploys, _e2e.yml’s output `deploys`') .option('-C, --dir ', 'the checkout to read, with its tags', '.') .action(async (environment: string, sha: string, opts: { deploys: string; dir: string }, command: Command) => { const ctx = contextOf(command); diff --git a/packages/cli-ci/src/commands/hybrid.ts b/packages/cli-ci/src/commands/hybrid.ts index ae9bea95..4910e5df 100644 --- a/packages/cli-ci/src/commands/hybrid.ts +++ b/packages/cli-ci/src/commands/hybrid.ts @@ -2,7 +2,7 @@ // throwaway instances its large jobs run on. // // create-instances : one instance per leg of the plan, for the -// app's build, its test or both, at once, each waited for until its runner is online; +// app's e2e job, at once, each waited for until its runner is online; // one that misses is kept, stopped and mailed about, and replaced once. From // the environment: GITHUB_REPOSITORY, GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT; // RUNNER_TOKEN (Administration: write on the repo); EXOSCALE_API_KEY/_SECRET diff --git a/packages/cli-ci/src/core/createInstances.ts b/packages/cli-ci/src/core/createInstances.ts index 4e749852..c70fa2d8 100644 --- a/packages/cli-ci/src/core/createInstances.ts +++ b/packages/cli-ci/src/core/createInstances.ts @@ -1,6 +1,6 @@ // Create the throwaway instances a run's large jobs need (§ 8 PLX-Delivery, // the hybrid strategy), one per leg of the plan, at once: the one machine an -// app's build, its test or both run on. +// app's e2e job, its build and its suites, runs on. // For each: a JIT config from GitHub, the raw create-instance call with the // labels the cleanup and the sweep read, user-data that arms the teardown // layers first, then a wait for the runner to show online, since a boot that @@ -10,7 +10,7 @@ // three minutes (waitOperation, exoscale.ts). A create still pending then // fails its launch, which removes its runner registration; once every launch // has settled the command fails, and with it the plan job, after which the -// workflow's `cleanup` job (_verify.yml) deletes what the run launched, found +// workflow's `cleanup` job (_e2e.yml) deletes what the run launched, found // by its labels. A created instance's runner then has `onlineSeconds` to // show online, 120 by default or ONLINE_SECONDS, looked at every five seconds. // diff --git a/packages/cli-ci/src/core/displayVersions.test.ts b/packages/cli-ci/src/core/displayVersions.test.ts index 7e7fc2c5..24ea4bae 100644 --- a/packages/cli-ci/src/core/displayVersions.test.ts +++ b/packages/cli-ci/src/core/displayVersions.test.ts @@ -250,7 +250,7 @@ test('tagging posts a release at the commit, and a re-run finds its tag; a tag e await assert.rejects(tagDisplayVersion(new Context({}, dry.io), { ...opts, version: 'v1.3' }), UsageError); }); -test('the apps are read from the deploys the verify planned', () => { +test('the apps are read from the deploys the plan made', () => { assert.deepEqual(appsOfDeploys('[{"app":"web","host":"h","image":"i"},{"app":"api","host":"h","image":"i"}]'), [ 'web', 'api', diff --git a/packages/cli-ci/src/core/userData.ts b/packages/cli-ci/src/core/userData.ts index 561a5ec2..2654378c 100644 --- a/packages/cli-ci/src/core/userData.ts +++ b/packages/cli-ci/src/core/userData.ts @@ -9,7 +9,7 @@ // cloud-config itself is documented inline; edit here, nowhere else. // // The three deadlines, minutes the caller passes (NO_JOB_MINUTES, -// DEATH_MINUTES, POWEROFF_MINUTES in _verify.yml): +// DEATH_MINUTES, POWEROFF_MINUTES in _e2e.yml): // // no-job no job has started by then: the instance deletes itself, no mail // death it mails the alerts address and deletes itself, whatever runs; diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index c1c7e25a..662e862e 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -353,7 +353,7 @@ test('pre-commit fixes lint on the staged files, then checks; pre-push tests', a assert.doesNotMatch(push, /mise :check/); }); -test('a workflow asks _check.yml only for tasks the repo has', async () => { +test('a workflow asks _test.yml only for tasks the repo has', async () => { for (const answers of SHAPES) { const result = await render(answers); const tasks = tasksOf(textOf(result, 'mise.toml')); From c6cbf5f163017d8303692d2607dcefb8e02c2158 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 21:57:42 +0100 Subject: [PATCH 134/194] No file rendered from repo-turbo mentions verify, its workflows included now Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/repoTurbo.test.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index 662e862e..b7e9ae28 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -200,11 +200,10 @@ test('a repo has the five verbs as root tasks, each taking an optional name, and } }); -test('no rendered file but the workflows mentions verify', async () => { +test('no rendered file mentions verify', async () => { for (const answers of SHAPES) { const result = await render(answers); - for (const path of pathsOf(result)) - if (!path.startsWith('.github/workflows/')) assert.doesNotMatch(textOf(result, path), /verify/i, path); + for (const path of pathsOf(result)) assert.doesNotMatch(textOf(result, path), /verify/i, path); } }); From f56aa414261c2a53ce826504e8b9f8f37e61af5e Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 22:03:59 +0100 Subject: [PATCH 135/194] Keep the name _check.yml for the workflow that runs a repo's mise tasks, and its job check It is named for what it does, runs test by default, and has callers in this repo, repo-operations and the compendium, which ship does not rename. The callers' jobs are named test, the job of the pipeline they mount, which the cache tests of repo-turbo follow; repo-operations calls _check.yml again. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/{_test.yml => _check.yml} | 4 ++-- .github/workflows/_e2e.yml | 2 +- .github/workflows/_publish-deploy.yml | 2 +- .github/workflows/_publish-package.yml | 2 +- .github/workflows/test.yml | 4 ++-- packages/lib/src/pipeline.test.ts | 18 +++++++++--------- packages/lib/src/repoTurbo.test.ts | 2 +- packages/lib/src/repoTurboCache.test.ts | 12 ++++++------ .../.github/workflows/on_commit.yml.jinja | 2 +- .../files/.github/workflows/on_pr.yml.jinja | 2 +- .../files/.github/workflows/on_pr.yml.jinja | 4 ++-- .../files/.github/workflows/on_push.yml.jinja | 4 ++-- ...s_packages %}on_commit.yml{% endif %}.jinja | 2 +- 13 files changed, 30 insertions(+), 30 deletions(-) rename .github/workflows/{_test.yml => _check.yml} (99%) diff --git a/.github/workflows/_test.yml b/.github/workflows/_check.yml similarity index 99% rename from .github/workflows/_test.yml rename to .github/workflows/_check.yml index 9d4b6e9f..e1c434b4 100644 --- a/.github/workflows/_test.yml +++ b/.github/workflows/_check.yml @@ -1,4 +1,4 @@ -name: _test +name: _check # Mounts the test job (§§ 1 and 2 PLX-Delivery): the repo's own mise tasks, # by default `test`, which runs `check` first, repo-wide, on a medium runner, @@ -61,7 +61,7 @@ on: # have to name the larger set, and every caller would then have to grant it. jobs: - test: + check: runs-on: ${{ inputs.strategy == 'github' && 'ubuntu-latest' || format('ci-{0}', inputs.size) }} steps: - uses: actions/checkout@v7 diff --git a/.github/workflows/_e2e.yml b/.github/workflows/_e2e.yml index cad017e7..c6a85f24 100644 --- a/.github/workflows/_e2e.yml +++ b/.github/workflows/_e2e.yml @@ -4,7 +4,7 @@ name: _e2e # in front of it: per app, on a large runner, the app's build and the suites # that need it, the repo's own `mise run build `, then `mise run e2e # `, against the trusted cache. The tenant's on_pr.yml and on_push.yml -# run it after _test.yml, which gates it: a commit that fails its test plans, +# run it after _check.yml, which gates it: a commit that fails its test plans, # builds and launches nothing. The logic is plx-ci's (@plexus-ms/cli-ci, # pinned in the caller's mise.toml) and the repo's verbs; every step here is # one invocation. diff --git a/.github/workflows/_publish-deploy.yml b/.github/workflows/_publish-deploy.yml index 345fb8ce..c219f07f 100644 --- a/.github/workflows/_publish-deploy.yml +++ b/.github/workflows/_publish-deploy.yml @@ -3,7 +3,7 @@ name: _publish-deploy # Mounts publish and deploy for an app repo (§§ 1, 2, 4 and 8 PLX-Delivery): # every app's image under its commit in the forge's registry, then each # deployed into the run's environment. The tenant's on_push.yml runs it on a -# push to an environment branch after _test.yml and _e2e.yml, whose jobs it +# push to an environment branch after _check.yml and _e2e.yml, whose jobs it # needs, and hands it what the plan of _e2e.yml said: the apps, the # environment, and where each app deploys. # diff --git a/.github/workflows/_publish-package.yml b/.github/workflows/_publish-package.yml index ae1eccd7..68bbb103 100644 --- a/.github/workflows/_publish-package.yml +++ b/.github/workflows/_publish-package.yml @@ -6,7 +6,7 @@ name: _publish-package # push that merges that PR it publishes. To npm that is token-less through # OIDC trusted publishing, with provenance; to the forge's package registry, # where a tenant keeps its private packages, with the job's own token. The -# caller runs this after _test.yml in the same run; the verb does not check +# caller runs this after _check.yml in the same run; the verb does not check # again. # # With `snapshot`, nothing is versioned on the trunk: the pending changesets diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7bde1641..016e65a6 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,7 +1,7 @@ name: test # Mounts the verbs on this repo's own events (§ 2 PLX-Delivery), through this -# repo's own reusable _test.yml with the verbs as its tasks: `test` on every +# repo's own reusable _check.yml with the verbs as its tasks: `test` on every # push, which includes `check` (`mise test` runs it first) and is the same # `mise test` the pre-push hook runs, and on a pull request `test`, then `e2e`, # the newborn tests, which need the network, a local registry and Docker. The @@ -24,6 +24,6 @@ concurrency: jobs: test: - uses: ./.github/workflows/_test.yml + uses: ./.github/workflows/_check.yml with: tasks: ${{ github.event_name == 'pull_request' && 'test e2e' || 'test' }} diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index ccda46d2..067b91e4 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -55,7 +55,7 @@ test('an app repo’s on_commit runs the test job alone', async () => { for (const ci_strategy of STRATEGIES) { const jobs = await jobsOf({ ci_strategy }, 'on_commit'); assert.deepEqual(Object.keys(jobs), ['test']); - assert.equal(called(jobs.test), '_test.yml'); + assert.equal(called(jobs.test), '_check.yml'); assert.equal(jobs.test?.with?.tasks ?? 'test', 'test'); } }); @@ -64,7 +64,7 @@ test('an app repo’s on_pr runs test, then e2e per app, and publishes and deplo for (const ci_strategy of STRATEGIES) { const jobs = await jobsOf({ ci_strategy }, 'on_pr'); assert.deepEqual(Object.keys(jobs), ['test', 'e2e']); - assert.equal(called(jobs.test), '_test.yml'); + assert.equal(called(jobs.test), '_check.yml'); assert.equal(called(jobs.e2e), '_e2e.yml'); assert.deepEqual(needsOf(jobs.e2e), ['test']); assert.notEqual(jobs.e2e?.with?.deploy, true); @@ -75,7 +75,7 @@ test('an app repo’s on_push runs test, e2e per app, then publish and deploy, w for (const display_versions of [false, true]) { const jobs = await jobsOf({ display_versions }, 'on_push'); assert.deepEqual(Object.keys(jobs), ['test', 'e2e', 'publish-deploy']); - assert.equal(called(jobs.test), '_test.yml'); + assert.equal(called(jobs.test), '_check.yml'); assert.equal(called(jobs.e2e), '_e2e.yml'); assert.deepEqual(needsOf(jobs.e2e), ['test']); assert.equal(jobs.e2e?.with?.deploy, true); @@ -92,12 +92,12 @@ test('an app repo’s on_push runs test, e2e per app, then publish and deploy, w test('a package repo’s on_pr is test and the changeset guard, its on_push test then publish', async () => { const pr = await jobsOf({ publishes_packages: true }, 'on_pr'); - assert.equal(called(pr.test), '_test.yml'); + assert.equal(called(pr.test), '_check.yml'); assert.equal(pr.test?.with?.tasks, 'test'); assert.ok('changeset-status' in pr); const push = await jobsOf({ publishes_packages: true }, 'on_push'); assert.deepEqual(Object.keys(push), ['test', 'publish']); - assert.equal(called(push.test), '_test.yml'); + assert.equal(called(push.test), '_check.yml'); assert.equal(called(push.publish), '_publish-package.yml'); assert.deepEqual(needsOf(push.publish), ['test']); }); @@ -119,12 +119,12 @@ const caches = (job: Job | undefined): unknown[] => /** The command lines of a job's steps, joined. */ const runs = (job: Job | undefined): string => (job?.steps ?? []).map((s) => s.run ?? '').join('\n'); -test('_test.yml runs the repo’s test on a medium runner with the shared cache', () => { - const workflow = reusable('_test.yml'); +test('_check.yml runs the repo’s test on a medium runner with the shared cache', () => { + const workflow = reusable('_check.yml'); assert.equal(workflow.on.workflow_call.inputs.tasks?.default, 'test'); assert.equal(workflow.on.workflow_call.inputs.size?.default, 'medium'); - assert.deepEqual(Object.keys(workflow.jobs), ['test']); - assert.deepEqual(caches(workflow.jobs.test), ['shared']); + assert.deepEqual(Object.keys(workflow.jobs), ['check']); + assert.deepEqual(caches(workflow.jobs.check), ['shared']); }); test('_e2e.yml plans, then per app builds the app and runs its suites on a large runner with the trusted cache alone', () => { diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index b7e9ae28..427aee16 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -352,7 +352,7 @@ test('pre-commit fixes lint on the staged files, then checks; pre-push tests', a assert.doesNotMatch(push, /mise :check/); }); -test('a workflow asks _test.yml only for tasks the repo has', async () => { +test('a workflow asks _check.yml only for tasks the repo has', async () => { for (const answers of SHAPES) { const result = await render(answers); const tasks = tasksOf(textOf(result, 'mise.toml')); diff --git a/packages/lib/src/repoTurboCache.test.ts b/packages/lib/src/repoTurboCache.test.ts index 575ad567..0a8fbfc8 100644 --- a/packages/lib/src/repoTurboCache.test.ts +++ b/packages/lib/src/repoTurboCache.test.ts @@ -338,7 +338,7 @@ test('a checkout without origin, or whose origin names no owner, has no team, an } }); -// Where a job gets its cache server: the step turbo-cache of this repo, which _test.yml starts for every repo. +// Where a job gets its cache server: the step turbo-cache of this repo, which _check.yml starts for every repo. /** The job `name` of a rendered workflow, as text, up to the next job. */ const jobOf = (workflow: string, name: string): string => @@ -360,23 +360,23 @@ test('no workflow of a repo asks for the cache, and the answer ci_registry chang } }); -test('a package repo’s test job hands the vault’s token to _test.yml, as an app repo’s does', async () => { +test('a package repo’s test job hands the vault’s token to _check.yml, as an app repo’s does', async () => { for (const answers of SHAPES) { const result = await render(answers); for (const path of ['.github/workflows/on_pr.yml', '.github/workflows/on_push.yml']) { const check = jobOf(textOf(result, path), 'test'); - assert.match(check, /_test\.yml@/, path); + assert.match(check, /_check\.yml@/, path); assert.match(check, /op-service-account-token: \$\{\{ secrets\.OP_SERVICE_ACCOUNT_TOKEN \}\}/, path); } } }); -test('_test.yml starts the shared cache server for every repo, by the step at the commit of the workflow', () => { +test('_check.yml starts the shared cache server for every repo, by the step at the commit of the workflow', () => { const workflow = parse( - readFileSync(join(import.meta.dirname, '..', '..', '..', '.github', 'workflows', '_test.yml'), 'utf8'), + readFileSync(join(import.meta.dirname, '..', '..', '..', '.github', 'workflows', '_check.yml'), 'utf8'), ); assert.ok(!('turbo-cache' in workflow.on.workflow_call.inputs), 'no input switches the cache'); - const steps: { uses?: string; if?: string; with?: Record }[] = workflow.jobs.test.steps; + const steps: { uses?: string; if?: string; with?: Record }[] = workflow.jobs.check.steps; const cache = steps.filter((step) => step.uses?.includes('turbo-cache')); assert.equal(cache.length, 1); assert.equal(cache[0]?.uses, '$/.github/actions/turbo-cache'); 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 a2a7ded0..1154bdca 100644 --- a/templates/repo-operations/files/.github/workflows/on_commit.yml.jinja +++ b/templates/repo-operations/files/.github/workflows/on_commit.yml.jinja @@ -17,7 +17,7 @@ concurrency: jobs: check: - uses: plexus-ms/tooling/.github/workflows/_test.yml@0.133.0 + uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} size: small diff --git a/templates/repo-operations/files/.github/workflows/on_pr.yml.jinja b/templates/repo-operations/files/.github/workflows/on_pr.yml.jinja index ebc68cdb..0c29e5c8 100644 --- a/templates/repo-operations/files/.github/workflows/on_pr.yml.jinja +++ b/templates/repo-operations/files/.github/workflows/on_pr.yml.jinja @@ -16,7 +16,7 @@ concurrency: jobs: check: - uses: plexus-ms/tooling/.github/workflows/_test.yml@0.133.0 + uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} size: small diff --git a/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja b/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja index a8f5763e..b1f2f510 100644 --- a/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja +++ b/templates/repo-turbo/files/.github/workflows/on_pr.yml.jinja @@ -16,7 +16,7 @@ concurrency: jobs: test: - uses: plexus-ms/tooling/.github/workflows/_test.yml@0.133.0 + uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} tasks: test{% endraw %}{% if private_packages_scope %} @@ -74,7 +74,7 @@ concurrency: jobs: test: - uses: plexus-ms/tooling/.github/workflows/_test.yml@0.133.0 + uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }}{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} diff --git a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja b/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja index 51b29e0c..d927952f 100644 --- a/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja +++ b/templates/repo-turbo/files/.github/workflows/on_push.yml.jinja @@ -27,7 +27,7 @@ permissions: jobs: test: - uses: plexus-ms/tooling/.github/workflows/_test.yml@0.133.0 + uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} tasks: test{% endraw %}{% if private_packages_scope %} @@ -64,7 +64,7 @@ jobs: concurrency: group: on_push-test-${{ github.ref }} cancel-in-progress: true - uses: plexus-ms/tooling/.github/workflows/_test.yml@0.133.0 + uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }}{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} 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 68020bb5..50c831c0 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 @@ -18,7 +18,7 @@ concurrency: jobs: test: - uses: plexus-ms/tooling/.github/workflows/_test.yml@0.133.0 + uses: plexus-ms/tooling/.github/workflows/_check.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }}{% endraw %}{% if private_packages_scope %} private-packages: true{% endif %}{% raw %} From 51a51a227765d4a291ebd4bf6102b00a3c2eb6f4 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 22:04:09 +0100 Subject: [PATCH 136/194] Newborn: an app repo through test, e2e, publish and deploy, each job from a fresh clone, against a registry on loopback; a second run builds nothing and runs no task, and a change to a spec alone builds no image and restarts nothing Co-Authored-By: Claude Fable 5.2 --- newborns/pipeline.test.ts | 273 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 273 insertions(+) create mode 100644 newborns/pipeline.test.ts diff --git a/newborns/pipeline.test.ts b/newborns/pipeline.test.ts new file mode 100644 index 00000000..5f309262 --- /dev/null +++ b/newborns/pipeline.test.ts @@ -0,0 +1,273 @@ +// A newborn app repo through its pipeline: the commands the jobs of its +// workflows call (_check.yml, _e2e.yml, _publish-deploy.yml and _deploy.yml), +// in the order the jobs run and each job from a fresh clone of the repo's +// origin, with its tools installed as a job installs them. The workflows +// themselves run only on the forge; what of them this file stands in for: +// +// test mise run test +// plan plx-ci plan --deploy, in the repo's mise environment, with crane +// e2e per app: mise run build , the suite's Chromium, mise run e2e +// publish per app: plx-ci publish , under the strategy github, +// through this machine's Docker, into a registry on loopback +// deploy per deploy: plx deploy, over an ssh that runs each line here with +// bash, into a directory standing in for the host's /opt/stacks, with +// this machine's Docker +// +// The repo has one app from app-nextjs, `web`, with its E2E suite. Turbo's +// two remote caches are stood in for by one local cache directory that every +// clone shares (TURBO_CACHE_DIR; turbow runs the verbs uncached-remote, as a +// newborn's PLX_TURBO_* are none): what a later job finds there is what an +// earlier one wrote. The first run builds the app in its e2e job, publishes +// the image from a restore of that output under build- and the commit, +// and deploys it healthy. A second run on the same content runs no task, +// every Turbo task a cache hit, finds the image, builds none, and leaves the +// app running. A change to a spec alone runs the suite again and moves no +// build hash: publish builds no image and the deploy restarts nothing. Needs +// Docker and the network, as the newborns do. +import assert from 'node:assert/strict'; +import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { basename, join } from 'node:path'; +import { after, before, test } from 'node:test'; +import { born, close, freePort, git, open, put, relock, sh, tryRun } from './helpers.ts'; + +const BROWSERS = join(import.meta.dirname, '..', 'node_modules', '.cache', 'ms-playwright'); +/** The app's server-actions key, as the vault would hand it to a build: made up. */ +const KEY = 'bmV3Ym9ybi1zZXJ2ZXItYWN0aW9ucy1rZXktMzJieXQ='; +const CRANE = 'crane@0.22.1'; + +let here = ''; +let origin = ''; +let registry = ''; +let container = ''; +let port = 0; +/** Every job's environment beyond the world's: the caches every clone shares, and where the images go. */ +let env: Record = {}; +const deployments: string[] = []; + +/** `git` that must succeed. */ +async function gitOk(dir: string, ...args: string[]): Promise { + const ran = await git(dir, ...args); + assert.ok(ran.ok, ran.output); + return ran.output.trim(); +} + +before(async () => { + here = await open('pipeline'); + // The forge's registry: a registry on loopback. + const started = (await sh('docker', ['run', '-d', '--rm', '-p', '127.0.0.1::5000', 'registry:2'], here)).match( + /^[0-9a-f]{64}$/m, + ); + container = started?.[0] ?? ''; + if (!container) throw new Error('docker run printed no container id'); + registry = (await sh('docker', ['port', container, '5000/tcp'], here)).trim().split('\n')[0] ?? ''; + // The ssh of a deploy: every line it is given runs here, with bash. + const bin = join(here, 'bin'); + mkdirSync(bin); + writeFileSync( + join(bin, 'ssh'), + '#!/usr/bin/env bash\nfor a in "$@"; do [ "$a" = -O ] && exit 0; done\nwhile [ "$1" != -- ]; do shift; done; shift\nexec bash -c "$1"\n', + ); + chmodSync(join(bin, 'ssh'), 0o755); + env = { + TURBO_CACHE_DIR: join(here, 'turbo-cache'), + PLAYWRIGHT_BROWSERS_PATH: BROWSERS, + IMAGE_PREFIX: `${registry}/acme`, + CI_STRATEGY: 'github', + PATH: `${bin}:${process.env.PATH}`, + }; + port = await freePort(); + + const repo = await born(join(here, 'web'), ['repo-turbo'], { tenant: 'acme' }); + await born(join(repo, 'apps', 'web'), ['app-nextjs'], { name: '@acme/web', profile: 'stateless' }); + await born(join(repo, 'e2e', 'web'), ['e2e-playwright'], { app: '@acme/web' }); + // Where the app deploys in staging: the operations repo's inventory, as the plan reads it. + put(here, { + 'operations/inventory/host_vars/app-host.yml': + 'plexus_deploy_target: ssh://deploy@app-host\nplexus_apps:\n - name: web\n environment: staging\n', + }); + await relock(repo); + await gitOk(repo, 'add', '-A'); + await gitOk(repo, 'commit', '--no-verify', '-q', '-m', 'born'); + origin = join(here, 'origin.git'); + await gitOk(here, 'clone', '-q', '--bare', repo, origin); +}); + +after(async () => { + for (const dir of deployments) await tryRun('docker', ['compose', 'down', '--volumes'], dir); + if (container) await tryRun('docker', ['rm', '-f', container], here); + for (const tag of ['web']) + await tryRun('sh', ['-c', `docker image ls -q '${registry}/acme/${tag}' | xargs -r docker image rm -f`], here); + await close(); +}); + +let jobs = 0; +/** A fresh clone of the origin at `sha`, its tools installed: the checkout of one job. */ +async function checkout(sha: string): Promise { + const dir = join(here, 'jobs', String(jobs++)); + await gitOk(here, 'clone', '-q', origin, dir); + await gitOk(dir, 'checkout', '-q', sha); + await sh('sh', ['-c', 'mise trust -q && mise install -q'], dir); + return dir; +} + +/** A command of a job, which must pass; its output. */ +async function step(dir: string, command: string[], extra: Record = {}): Promise { + const [name = '', ...args] = command; + const ran = await tryRun(name, args, dir, { ...env, ...extra }); + assert.ok(ran.ok, `${command.join(' ')} failed in ${dir}:\n${ran.output}`); + return ran.output; +} + +/** Turbo's summary of a run, ` of `, one per turbo run in the output. */ +const summaries = (output: string): [number, number][] => + [...output.matchAll(/Cached:\s+(\d+) cached, (\d+) total/g)].map((m) => [Number(m[1]), Number(m[2])]); + +interface Leg { + app: string; + hash: string; + suite: string; + context: string; + build: boolean; +} + +interface Run { + test: string; + plan: { legs: Leg[]; deploys: { app: string; host: string; image: string }[]; environment: string }; + build: string; + e2e: string; + published: { built: boolean; tags: string[]; digest?: string }; + deployed: { healthy: boolean; unchanged?: boolean; live?: string }; +} + +/** The pipeline of a push of `sha` to develop: the jobs of on_push, in their order. */ +async function pipeline(sha: string): Promise { + const ci = { GITHUB_SHA: sha, GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'develop' }; + const test = await step(await checkout(sha), ['mise', 'run', 'test']); + + const planned = await checkout(sha); + const inventory = join(here, 'operations', 'inventory'); + const planOut = await step( + planned, + ['mise', 'exec', CRANE, '--', 'plx-ci', '--json', 'plan', '--deploy', '--inventory', inventory], + ci, + ); + const plan = JSON.parse(planOut.slice(planOut.indexOf('{\n'))); + assert.equal(plan.environment, 'staging'); + const [leg] = plan.legs as Leg[]; + assert.ok(leg, planOut); + + const e2eJob = await checkout(sha); + const build = await step(e2eJob, ['mise', 'run', 'build', leg.app], { NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: KEY }); + await step(join(e2eJob, leg.suite), ['mise', 'exec', '--', 'pnpm', 'exec', 'playwright', 'install', 'chromium']); + const e2e = await step(e2eJob, ['mise', 'run', 'e2e', leg.app]); + + const publishJob = await checkout(sha); + const publishOut = await step( + publishJob, + ['mise', 'exec', CRANE, '--', 'plx-ci', '--json', 'publish', leg.app, leg.hash, sha], + { ...ci, NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: KEY }, + ); + const published = JSON.parse(publishOut.slice(publishOut.indexOf('{\n'))); + + const [target] = plan.deploys; + assert.ok(target, planOut); + const deployJob = await checkout(sha); + // Its name is the compose project's, unique to this run. + const appDir = join(here, 'stacks', `${basename(here).toLowerCase()}-web`); + mkdirSync(appDir, { recursive: true }); + if (!deployments.includes(appDir)) deployments.push(appDir); + // What the platform playbook writes beside the compose file. + writeFileSync(join(appDir, '.env'), `PLEXUS_LOOPBACK_PORT=${port}\n`); + const deployOut = await step(deployJob, [ + 'mise', + 'exec', + '--', + 'plx', + '--json', + 'deploy', + target.host, + target.app, + '--environment', + 'staging', + '--image', + target.image, + '--app-dir', + appDir, + ]); + const deployed = JSON.parse(deployOut.slice(deployOut.indexOf('{\n'))); + return { test, plan, build, e2e, published, deployed }; +} + +/** The digest the registry holds under `ref`. */ +const digestOf = async (ref: string) => (await sh('mise', ['exec', CRANE, '--', 'crane', 'digest', ref], here)).trim(); + +let first: Run; +let firstSha = ''; + +test('the first run builds the app in its e2e job, publishes its image from that output, and deploys it healthy', async () => { + firstSha = await gitOk(origin, 'rev-parse', 'HEAD'); + first = await pipeline(firstSha); + const [leg] = first.plan.legs; + assert.deepEqual(leg && { ...leg, hash: '' }, { + app: 'web', + hash: '', + runner: 'ubuntu-latest', + suite: 'e2e/web', + context: 'output', + build: true, + }); + assert.match(first.e2e, /\d+ passed \(/, 'the suite ran'); + assert.equal(first.published.built, true); + const image = `${registry}/acme/web`; + const digest = await digestOf(`${image}:build-${leg?.hash}`); + assert.equal(await digestOf(`${image}:${firstSha}`), digest, 'build- and the commit are one image'); + assert.equal(first.published.digest, digest); + assert.deepEqual(first.plan.deploys, [{ app: 'web', host: 'ssh://deploy@app-host', image: `${image}:${firstSha}` }]); + assert.equal(first.deployed.healthy, true, JSON.stringify(first.deployed)); + const page = await fetch(`http://127.0.0.1:${port}/`); + assert.equal(page.status, 200); +}); + +test('a second run on the same content runs no task and builds no image, and the deploy leaves the app running', async () => { + const clone = join(here, 'push-2'); + await gitOk(here, 'clone', '-q', origin, clone); + await gitOk(clone, 'commit', '--no-verify', '--allow-empty', '-q', '-m', 'the same content again'); + await gitOk(clone, 'push', '-q', 'origin', 'HEAD'); + const sha = await gitOk(clone, 'rev-parse', 'HEAD'); + const again = await pipeline(sha); + assert.equal(again.plan.legs[0]?.hash, first.plan.legs[0]?.hash); + assert.equal(again.plan.legs[0]?.build, false, 'the registry holds the image'); + for (const [job, output] of [ + ['test', again.test], + ['build', again.build], + ['e2e', again.e2e], + ] as const) { + const runs = summaries(output); + assert.ok(runs.length > 0, `${job}: ${output}`); + for (const [cached, total] of runs) assert.equal(cached, total, `${job} runs a task:\n${output}`); + } + assert.equal(again.published.built, false); + assert.equal( + await digestOf(`${registry}/acme/web:${sha}`), + await digestOf(`${registry}/acme/web:${firstSha}`), + 'the new commit tags the image there', + ); + assert.equal(again.deployed.healthy, true); + assert.equal(again.deployed.unchanged, true, JSON.stringify(again.deployed)); +}); + +test('a change to a spec alone runs the suite again, and builds no image and restarts nothing', async () => { + const clone = join(here, 'push-3'); + await gitOk(here, 'clone', '-q', origin, clone); + const spec = join(clone, 'e2e', 'web', 'specs', 'home.spec.ts'); + writeFileSync(spec, `${readFileSync(spec, 'utf8')}// a spec edited, and nothing else\n`); + await gitOk(clone, 'commit', '--no-verify', '-q', '-am', 'a spec alone'); + await gitOk(clone, 'push', '-q', 'origin', 'HEAD'); + const run = await pipeline(await gitOk(clone, 'rev-parse', 'HEAD')); + assert.equal(run.plan.legs[0]?.hash, first.plan.legs[0]?.hash, 'the build hash did not move'); + assert.equal(run.plan.legs[0]?.build, false); + for (const [cached, total] of summaries(run.build)) assert.equal(cached, total, run.build); + assert.match(run.e2e, /\d+ passed \(/, 'the suite ran again'); + assert.equal(run.published.built, false); + assert.equal(run.deployed.unchanged, true, JSON.stringify(run.deployed)); +}); From 2cdf38d96ebeab64056fe51d29284c1f7d486601 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 22:06:58 +0100 Subject: [PATCH 137/194] test: a version that removes a requirement name must pass ship's preflight Two failing tests, before the fix (PLX-198). plx requirements against a compendium that has dropped a requirement name the previous index names: the repo passes while no file of its own cites the name, and fails on the file and line that still does. ship, cutting such a version over scratch repositories, passes its preflight and writes an index without the name. Both fail today: the citation check reads the index tooling carries as a file that cites, and the previous version's index names the dropped name. Co-Authored-By: Claude Fable 5.2 --- packages/dev/src/ship.integration.test.ts | 20 ++++++++++++++++++++ packages/lib/src/requirements.test.ts | 23 ++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index 8197159b..7329ed04 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -1104,6 +1104,26 @@ test('a versioned repo that fails plx requirements stops the version before anyt assert.match(dry.error ?? '', /plx requirements fails in 2 versioned repos/); }); +test('a version that removes a requirement name passes the preflight, and writes an index without it', async () => { + fixture('removed-name'); + // Put together, not written out: this repo's own citation check reads this file. + const [alpha, beta, delta] = ['Alpha', 'Beta', 'Delta'].map((m) => ['§', '1', `PLX-${m}`].join(' ')); + const gone = ['PLX-Beta', 'Gone'].join('/'); + // Tooling carries the index of the version before, which named a requirement of beta's the compendium has dropped. + const prim = up('tooling'); + const index = join(prim, 'packages/lib/src/standard-index.json'); + put(index, `${JSON.stringify({ version: '0.1.0', citable: [alpha, beta, gone] }, null, 2)}\n`); + commit(prim, 'the index of 0.1.0'); + git(prim, 'push', '--quiet', 'origin', 'main'); + + const dry = await run({ dryRun: true }); + assert.equal(dry.error, undefined, dry.out); + const { error, out } = await run({ yes: true }); + assert.equal(error, undefined, out); + assert.ok(allTagged('0.2.0') && allReleased('0.2.0')); + assert.deepEqual(JSON.parse(read(index)), { version: '0.2.0', citable: [alpha, beta, delta] }); +}); + test("a run that stops at the compendium's release leaves the version unseen by any repo; the re-run releases it", async () => { fixture('last-release'); process.env.FAKE_GH_CREATE_FAIL = 'compendium'; diff --git a/packages/lib/src/requirements.test.ts b/packages/lib/src/requirements.test.ts index ae2338ed..a6bee800 100644 --- a/packages/lib/src/requirements.test.ts +++ b/packages/lib/src/requirements.test.ts @@ -13,7 +13,7 @@ import { requirementName, scanPage, } from './requirements.ts'; -import { bundledIndex } from './standardIndex.ts'; +import { bundledIndex, renderStandardIndex, STANDARD_INDEX_FILE } from './standardIndex.ts'; import { fakeIo, type Tree } from './testing/fakeIo.ts'; // Citations, names and identifiers are put together at run time: this repo's @@ -404,6 +404,27 @@ test('checkRepo resolves against a compendium checkout when given one', async () assert.equal(lintCitations(`${name('App', 'Port')}`, 'notes.txt', new Set(bundledIndex().citable)).length, 1); }); +test('a requirement name the compendium has dropped fails where a file still cites it, never in the index that named it', async () => { + const gone = name('App', 'Gone'); + // The index of the version before, as ship wrote it, named a requirement the compendium being cut no longer has. + const previous = renderStandardIndex({ + version: '0.1.0', + citable: [cite('1', 'PLX-App'), name('App', 'Port'), gone], + }); + const repo = (notes: string): Tree => { + const dirs = STANDARD_INDEX_FILE.split('/'); + const file = dirs.pop() ?? ''; + const index = dirs.reduceRight((inner, dir) => ({ [dir]: inner }), { [file]: previous }); + return { ...compendium(), r: { ...index, 'notes.txt': notes } }; + }; + const check = async (notes: string) => + (await checkRepo(new Context({}, checkout(repo(notes), 'r')), '/r', { compendium: '/c' })).defects; + assert.deepEqual(await check(`${name('App', 'Port')}\n`), []); + assert.deepEqual(await check(`${name('App', 'Port')}\n${gone}\n`), [ + `✗ notes.txt: line 2: ${gone} names no requirement line`, + ]); +}); + test('checkCommitMessage reads the comment character from git', async () => { const message = `fix: x\n\n; Please enter the commit message for your changes.\n; On branch ${id('XYZ', 13)}-topic\n`; const io = (char: string | undefined) => From 26c793dd22e9bc613badddab337d878459395146 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 22:07:49 +0100 Subject: [PATCH 138/194] fix: the citation check never reads the citable index tooling carries The index is what citations are checked against, and cites nothing itself. Until ship rewrites it after the preflight, it is the previous version's, and names every requirement the compendium being cut may have dropped: the check read it like any tracked file, so ship's preflight, and tooling's own check against a sibling compendium, failed on it whenever a version removed a requirement name (PLX-198). It is now skipped where the baseline is, the other file of the check's own that holds names and cites nothing. Co-Authored-By: Claude Fable 5.2 --- packages/dev/src/ship.ts | 4 ++-- packages/lib/src/requirements.ts | 8 ++++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/dev/src/ship.ts b/packages/dev/src/ship.ts index f7265ed3..946de2f8 100644 --- a/packages/dev/src/ship.ts +++ b/packages/dev/src/ship.ts @@ -189,8 +189,8 @@ async function preflightImmutable(ctx: Context, versioned: Versioned): Promise { const compendium = versioned.repos.find((r) => r.name === COMPENDIUM)?.path; diff --git a/packages/lib/src/requirements.ts b/packages/lib/src/requirements.ts index 27d69c7f..be4b2430 100644 --- a/packages/lib/src/requirements.ts +++ b/packages/lib/src/requirements.ts @@ -39,6 +39,10 @@ // the index this plx carries (standardIndex.ts), written by `plx-dev ship` // from the compendium at the version it cuts: a tenant repo, which has no // compendium, checks its citations against the version of plx it pins. +// Two files the lints never read: the baseline, which records violations, and +// in tooling that index, which is what citations are checked against and +// cites nothing. Until ship rewrites it, the index is the previous version's, +// and names what the compendium being cut may have dropped. // // plx requirements # lint; exit 1 on any defect // plx requirements --write-baseline # record today's violations @@ -59,7 +63,7 @@ import { renderViolation, type Violation, } from './lints.ts'; -import { bundledIndex, type StandardIndex } from './standardIndex.ts'; +import { bundledIndex, STANDARD_INDEX_FILE, type StandardIndex } from './standardIndex.ts'; export type PageMode = 'map' | 'module'; @@ -390,7 +394,7 @@ export async function lintRepo(ctx: Context, dir: string, options: RepoOptions = const citable: Citable = new Set(index.citable); for (const file of tracked) { - if (file === BASELINE_FILE) continue; + if (file === BASELINE_FILE || file === STANDARD_INDEX_FILE) continue; const text = await ctx.readFile(join(dir, file)).catch(() => undefined); if (text === undefined || text.includes('\0')) continue; // deleted in the worktree, a submodule, or binary if (kind === 'compendium' && /\.mdx?$/.test(file)) result.violations.push(...lintDateOrVersion(text, file)); From 7e36d2144362f8b453d706b2278380227ff68203 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 22:08:32 +0100 Subject: [PATCH 139/194] test: doctor's workspace fixture lists a deviation the test declares known The operations repo of the fixture listed a real requirement as its deviation, one without a check, and the diagnosis took the names it may list from the index the package carries. A version that drops that name (PLX-198) would fail two doctor tests the moment ship writes the new index, at the pre-push of tooling's bookkeeping commit, after its tag. The fixture now lists a made-up name, and the test hands the diagnosis the names it knows, as diagnose already allows. Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/doctor.test.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 232bc70f..297edc70 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -799,6 +799,14 @@ const HK = `hooks { } `; +/** + * The deviation the fixture's operations repo lists, of a requirement without a + * check: made up, and known to the diagnosis because the test says so, so that + * no test depends on the names one version's index happens to hold. Joined at + * run time: written out, plx requirements would read it as a citation of nothing. + */ +const UNCHECKED = ['PLX-Repo', 'Unchecked'].join('/'); + const ws = (): Tree => ({ 'mise.toml': '', web: { @@ -817,8 +825,7 @@ const ws = (): Tree => ({ }, ops: { '.git': {}, - 'PLEXUS.md': - '---\nversion: 0.1.0\ntemplates: [repo-operations]\ntenant: acme\ndeviations: [PLX-Repo/SubVerbs]\n---\n\n- `PLX-Repo/SubVerbs`: the playbooks are checked by `check`.\n', + 'PLEXUS.md': `---\nversion: 0.1.0\ntemplates: [repo-operations]\ntenant: acme\ndeviations: [${UNCHECKED}]\n---\n\n${reasoned([UNCHECKED])}\n`, 'mise.toml': '[tools]\n"npm:@plexus-ms/cli" = "0.1.0"\n', 'hk.pkl': HK, apps: { @@ -849,7 +856,7 @@ async function doctorOver( const mise = miseTasks({ '/ws/web': webTasks, '/ws/ops': VERBS }); const ctx = new Context({}, fakeIo({ ...around, ws: tree }, git, { mise: (cwd) => mise(cwd) })); const { facts, ...examined } = await examine(ctx, root, plx); - return { ...examined, facts, ...diagnose(facts) }; + return { ...examined, facts, ...diagnose(facts, new Set([UNCHECKED])) }; } const requirements = (report: Awaited>) => @@ -874,7 +881,7 @@ test('doctor over a workspace checks every Plexus repo beneath, apps by their re assert.deepEqual( report.units.map((u) => [u.path, u.kind, u.profile, u.deviations, u.findings]), [ - ['ops', 'operations', undefined, ['PLX-Repo/SubVerbs'], []], + ['ops', 'operations', undefined, [UNCHECKED], []], [ 'ops/apps/id', 'app', From 340a98ac14cdacb8c49311b7b351fe064d515276 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 22:12:47 +0100 Subject: [PATCH 140/194] The plan and the publish install mise also in a trial of unreleased tooling: the plan needs PLX_PLATFORM from it, publish its mise run build Co-Authored-By: Claude Fable 5.2 --- .github/workflows/_e2e.yml | 13 +++++++------ .github/workflows/_publish-deploy.yml | 13 +++++++------ 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/.github/workflows/_e2e.yml b/.github/workflows/_e2e.yml index c6a85f24..e7ec02b3 100644 --- a/.github/workflows/_e2e.yml +++ b/.github/workflows/_e2e.yml @@ -157,15 +157,16 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 - # mise, the repo's pins and its [env] for the later steps: on the forge's - # runners from mise-action; in the environment image of a slot or an - # instance (actions_runners), which carries mise and the common tools, - # from its ci-mise-install. + # mise, the repo's pins and its [env] for the later steps, PLX_PLATFORM + # among them, also in a trial of unreleased tooling, whose plx-ci comes + # first on the PATH: on the forge's runners from mise-action; in the + # environment image of a slot or an instance (actions_runners), which + # carries mise and the common tools, from its ci-mise-install. - uses: jdx/mise-action@v5 - if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} + if: ${{ runner.environment == 'github-hosted' }} with: install_args: node npm:@plexus-ms/cli-ci - - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} + - if: ${{ runner.environment != 'github-hosted' }} env: MISE_GITHUB_TOKEN: ${{ github.token }} run: ci-mise-install node npm:@plexus-ms/cli-ci diff --git a/.github/workflows/_publish-deploy.yml b/.github/workflows/_publish-deploy.yml index c219f07f..b150d18a 100644 --- a/.github/workflows/_publish-deploy.yml +++ b/.github/workflows/_publish-deploy.yml @@ -175,15 +175,16 @@ jobs: run: | printf '//npm.pkg.github.com/:_authToken=%s\n' "$GITHUB_TOKEN" > "$RUNNER_TEMP/npmrc" echo "NPM_CONFIG_USERCONFIG=$RUNNER_TEMP/npmrc" >> "$GITHUB_ENV" - # mise, the repo's pins and its [env] for the later steps: on the forge's - # runners from mise-action; in the environment image of a slot or an - # instance (actions_runners), which carries mise and the common tools, - # from its ci-mise-install. + # mise, the repo's pins and its [env] for the later steps, PLX_PLATFORM + # among them, also in a trial of unreleased tooling, whose plx-ci comes + # first on the PATH: on the forge's runners from mise-action; in the + # environment image of a slot or an instance (actions_runners), which + # carries mise and the common tools, from its ci-mise-install. - uses: jdx/mise-action@v5 - if: ${{ inputs.tooling-ref == '' && runner.environment == 'github-hosted' }} + if: ${{ runner.environment == 'github-hosted' }} with: install_args: node npm:@plexus-ms/cli-ci - - if: ${{ inputs.tooling-ref == '' && runner.environment != 'github-hosted' }} + - if: ${{ runner.environment != 'github-hosted' }} env: MISE_GITHUB_TOKEN: ${{ github.token }} run: ci-mise-install node npm:@plexus-ms/cli-ci From 46d1dcfcdc2a2aecf4a815c8312a78a9179adaf6 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 22:29:34 +0100 Subject: [PATCH 141/194] Test: publish pushes without rewrite-timestamp, which the runner's Docker refuses beside its unpack Seen in run 46516092989 of this pull request: "exporter option rewrite-timestamp conflicts with unpack" on ubuntu-latest. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/core/publish.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/cli-ci/src/core/publish.test.ts b/packages/cli-ci/src/core/publish.test.ts index 06358888..a61648f0 100644 --- a/packages/cli-ci/src/core/publish.test.ts +++ b/packages/cli-ci/src/core/publish.test.ts @@ -127,7 +127,9 @@ test('a missing image of an app from app-nextjs: a fresh restore of its output t const args = build?.args.join(' ') ?? ''; assert.match(args, /--build-arg APP=website/); assert.match(args, /--tag ghcr\.io\/acme\/website:build-0f2a --tag ghcr\.io\/acme\/website:deadbeef/); - assert.match(args, /--output type=image,push=true,rewrite-timestamp=true,oci-mediatypes=true/); + // No rewrite-timestamp: the runner's Docker of the forge refuses it beside the unpack of its image store. + assert.match(args, /--output type=image,push=true,oci-mediatypes=true /); + assert.doesNotMatch(args, /rewrite-timestamp/); assert.match(args, /--provenance=false --sbom=false/); // No layer cache, no key and no package token: the build output holds what the image runs. assert.doesNotMatch(args, /--cache-from|--cache-to|:cache|--secret|BUILD_HASH/); From 8a820cb1be2f31ee5df245004a1c2d2d249e72ca Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 22:29:51 +0100 Subject: [PATCH 142/194] publish pushes without rewrite-timestamp, which the runner's Docker of the forge refuses beside its unpack Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/core/build.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/cli-ci/src/core/build.ts b/packages/cli-ci/src/core/build.ts index d57b3bec..73db4640 100644 --- a/packages/cli-ci/src/core/build.ts +++ b/packages/cli-ci/src/core/build.ts @@ -27,9 +27,11 @@ // packages. `json/` goes unused. The directory is removed after. // // Either way the image is built for linux/amd64 and pushed under build- -// and the commit, with no layer cache, SOURCE_DATE_EPOCH and -// rewrite-timestamp flattening its timestamps and no provenance or SBOM, so -// that the manifest is the image and nothing else. BuildKit's log is the +// and the commit, with no layer cache, SOURCE_DATE_EPOCH fixing the times +// BuildKit sets, and no provenance or SBOM, so that the manifest is the image +// and nothing else. No rewrite-timestamp: the runner's Docker of the forge +// refuses it beside the unpack of its image store, and an image is built once +// per hash, so no two builds of it are compared. BuildKit's log is the // job's, at every verbosity. Where the build runs is the strategy's: under // github the runner's own Docker (the default builder), under on-prem and // hybrid the BuildKit service of the runner host (actions_runners), on @@ -115,7 +117,7 @@ export function buildArgs( '--tag', `${image}:${options.sha}`, '--output', - 'type=image,push=true,rewrite-timestamp=true,oci-mediatypes=true', + 'type=image,push=true,oci-mediatypes=true', '--provenance=false', '--sbom=false', '--metadata-file', From 1ffa12a137fdb2ef69c361a06c6c370a5ad76139 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 23:14:05 +0100 Subject: [PATCH 143/194] Test: the test job builds no app, a suite's app included; a dry run of check and test lists no build of it, and of e2e does Co-Authored-By: Claude Fable 5.2 --- newborns/pipeline.test.ts | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/newborns/pipeline.test.ts b/newborns/pipeline.test.ts index 5f309262..18c4cac2 100644 --- a/newborns/pipeline.test.ts +++ b/newborns/pipeline.test.ts @@ -25,7 +25,7 @@ // build hash: publish builds no image and the deploy restarts nothing. Needs // Docker and the network, as the newborns do. import assert from 'node:assert/strict'; -import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { basename, join } from 'node:path'; import { after, before, test } from 'node:test'; import { born, close, freePort, git, open, put, relock, sh, tryRun } from './helpers.ts'; @@ -142,7 +142,10 @@ interface Run { /** The pipeline of a push of `sha` to develop: the jobs of on_push, in their order. */ async function pipeline(sha: string): Promise { const ci = { GITHUB_SHA: sha, GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'develop' }; - const test = await step(await checkout(sha), ['mise', 'run', 'test']); + const testJob = await checkout(sha); + const test = await step(testJob, ['mise', 'run', 'test']); + // The test job needs no built app (§ 1.5 of the verbs), a suite's app included. + assert.equal(existsSync(join(testJob, 'apps', 'web', '.next', 'standalone')), false, 'the test job built the app'); const planned = await checkout(sha); const inventory = join(here, 'operations', 'inventory'); @@ -201,6 +204,23 @@ async function pipeline(sha: string): Promise { /** The digest the registry holds under `ref`. */ const digestOf = async (ref: string) => (await sh('mise', ['exec', CRANE, '--', 'crane', 'digest', ref], here)).trim(); +/** The tasks a Turbo dry run of `task` would run, by id: those whose package has the script. */ +async function planned(dir: string, task: string): Promise { + const out = await step(dir, ['mise', 'exec', '--', 'turbo', 'run', task, '--dry=json']); + const dry = JSON.parse(out.slice(out.indexOf('{'))); + return dry.tasks + .filter((t: { command: string }) => t.command !== '') + .map((t: { taskId: string }) => t.taskId) + .sort(); +} + +test('check and test build no app, a suite’s app included, and e2e builds the app before its suite', async () => { + const dir = await checkout(await gitOk(origin, 'rev-parse', 'HEAD')); + await step(dir, ['mise', 'run', 'install']); + for (const task of ['check', 'test']) assert.ok(!(await planned(dir, task)).includes('@acme/web#build'), task); + assert.deepEqual(await planned(dir, 'e2e'), ['@acme/web#build', '@acme/web-e2e#e2e']); +}); + let first: Run; let firstSha = ''; From b2d61885bcdd1505feeced7cc1eed853e708f065 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 23:15:10 +0100 Subject: [PATCH 144/194] e2e-playwright: a suite's turbo.json takes the root's ^build off its check and test, so the test job builds no app A suite has no check or test script, but Turbo still scheduled the root's ^build for them, and the medium job ran next build of every app with a suite into the shared bucket. Its e2e keeps ^build. The rendered file list of the suite test follows. Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/e2ePlaywright.test.ts | 1 + templates/e2e-playwright/files/turbo.json | 9 +++++++++ 2 files changed, 10 insertions(+) create mode 100644 templates/e2e-playwright/files/turbo.json diff --git a/packages/lib/src/e2ePlaywright.test.ts b/packages/lib/src/e2ePlaywright.test.ts index 55a71e5c..24e3b97f 100644 --- a/packages/lib/src/e2ePlaywright.test.ts +++ b/packages/lib/src/e2ePlaywright.test.ts @@ -14,6 +14,7 @@ test('a suite is rendered as a package of its own: its Playwright configuration, 'playwright.config.ts', 'setup.ts', 'specs/home.spec.ts', + 'turbo.json', ]); }); diff --git a/templates/e2e-playwright/files/turbo.json b/templates/e2e-playwright/files/turbo.json new file mode 100644 index 00000000..e7778a3e --- /dev/null +++ b/templates/e2e-playwright/files/turbo.json @@ -0,0 +1,9 @@ +{ + // A suite has no check or test of its own, and the root's ^build would still build the app it tests for them: + // neither needs a build, so the test job builds no app. Its e2e keeps the root's ^build. + "extends": ["//"], + "tasks": { + "check": { "dependsOn": [] }, + "test": { "dependsOn": [] } + } +} From 7cfda0ef44ce0b10ac5957b317b99390f239c353 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 23:17:00 +0100 Subject: [PATCH 145/194] Test: the plan finds an app's suite in Turbo's graph, says in one line that a checkout has no apps/, names a marker that does not parse, and builds an app without one from a pruned context Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/core/plan.test.ts | 57 +++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 7 deletions(-) diff --git a/packages/cli-ci/src/core/plan.test.ts b/packages/cli-ci/src/core/plan.test.ts index 53ee5e27..d825c15c 100644 --- a/packages/cli-ci/src/core/plan.test.ts +++ b/packages/cli-ci/src/core/plan.test.ts @@ -4,7 +4,7 @@ import { test } from 'node:test'; import { Context } from '@plexus-ms/lib'; import { REPO } from '../testing/checkout.ts'; import { fakeIo, notThere, type Tree } from '../testing/fakeIo.ts'; -import { deployLegsOf, environmentOf, hashesOf, legsOf, plan, readHashes } from './plan.ts'; +import { appsOf, deployLegsOf, environmentOf, hashesOf, imageContextOf, legsOf, plan, readHashes } from './plan.ts'; const dryRun = JSON.stringify({ tasks: [ @@ -14,6 +14,31 @@ const dryRun = JSON.stringify({ { taskId: '@acme/solver#build', package: '@acme/solver', hash: '9e1d', command: 'make' }, { taskId: '@acme/stub#build', package: '@acme/stub', hash: 'aaaa', command: '' }, { taskId: '@other/x#build', package: '@other/x', hash: 'ffff', command: 'x' }, + // The e2e tasks of the same dry run: a suite is a package whose e2e task waits for the app's build. + { + taskId: '@acme/website-e2e#e2e', + package: '@acme/website-e2e', + hash: 'e2e1', + command: 'playwright test', + directory: 'e2e/website', + dependencies: ['@acme/website#build'], + }, + { + taskId: '@acme/website#e2e', + package: '@acme/website', + hash: 'e2e2', + command: '', + directory: 'apps/website', + dependencies: ['@acme/my-lib#build'], + }, + { + taskId: '@acme/tools#e2e', + package: '@acme/tools', + hash: 'e2e3', + command: '', + directory: 'e2e/tools', + dependencies: ['@acme/my-app#build'], + }, ], }); const packages = { website: '@acme/website', 'my-app': '@acme/my-app', solver: '@acme/solver' }; @@ -28,11 +53,12 @@ function narrated(ctx: Context): string { return chunks.join(''); } -test('hashesOf keeps the build hash of each app’s package and nothing else', () => { +test('hashesOf keeps the build hash of each app’s package, and the directory of the suite whose e2e waits for that build', () => { + // The rule `mise run e2e ` follows too: Turbo's graph, never a directory's name. assert.deepEqual(hashes, [ - { app: 'website', hash: '0f2a' }, - { app: 'my-app', hash: 'c51b' }, - { app: 'solver', hash: '9e1d' }, + { app: 'website', hash: '0f2a', suite: 'e2e/website' }, + { app: 'my-app', hash: 'c51b', suite: '' }, + { app: 'solver', hash: '9e1d', suite: '' }, ]); assert.deepEqual(hashesOf(dryRun, { nope: '@acme/nope', stub: '@acme/stub' }), []); }); @@ -47,9 +73,9 @@ test('readHashes runs the dry run of build with the Turbo the lockfile has, in t }); const env = { PLX_PLATFORM: 'linux-x64' }; assert.deepEqual(await readHashes(new Context({}, io), '/repo', ['website'], env), [ - { app: 'website', hash: '0f2a' }, + { app: 'website', hash: '0f2a', suite: 'e2e/website' }, ]); - assert.deepEqual(seen, [{ cwd: '/repo', args: ['--yes', 'turbo@2.11.13', 'run', 'build', '--dry-run=json'] }]); + assert.deepEqual(seen, [{ cwd: '/repo', args: ['--yes', 'turbo@2.11.13', 'run', 'build', 'e2e', '--dry-run=json'] }]); }); test('readHashes refuses to run without PLX_PLATFORM, which no build lacks, and runs nothing', async () => { @@ -179,3 +205,20 @@ test('with an environment the plan adds the deploys of the apps with a target th assert.equal(result.environment, 'staging'); assert.deepEqual(result.deploys, [{ app: 'my-app', host: 'ssh://plexus@host-a', image: 'ghcr.io/acme/my-app:abc' }]); }); + +test('the apps are the directories under apps/, and a checkout without apps/ says so in one line', async () => { + assert.deepEqual(await appsOf(new Context({}, fakeIo(REPO)), '/repo'), ['my-app', 'solver', 'website']); + await assert.rejects(appsOf(new Context({}, fakeIo({ repo: {} })), '/repo'), (error: Error) => { + assert.equal(error.message, '/repo has no apps/: the plan reads the apps of an app repo there'); + return true; + }); +}); + +test('an app without a marker builds from a pruned context; a marker that does not parse is an error that names it', async () => { + const tree = structuredClone(REPO); + const apps = (tree.repo as Tree).apps as Tree; + delete (apps.website as Tree)['PLEXUS.md']; + assert.equal(await imageContextOf(new Context({}, fakeIo(tree)), '/repo', 'website'), 'pruned'); + (apps.website as Tree)['PLEXUS.md'] = '---\ntemplates: [app-nextjs\n - nope\n---\n'; + await assert.rejects(imageContextOf(new Context({}, fakeIo(tree)), '/repo', 'website'), /apps\/website\/PLEXUS\.md/); +}); From b145607864ca5fc4307d6a5adfe81e7d0b661533 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 23:17:05 +0100 Subject: [PATCH 146/194] Test: publish builds through the BuildKit service exactly when BUILDKIT_HOST is set, from the context the plan gives it, with the key never a build argument; the workflow starts the trusted cache exactly where it builds from the output The test of the scratch directory's removal follows TMPDIR. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/core/publish.test.ts | 81 +++++++++++++++--------- packages/lib/src/pipeline.test.ts | 7 +- 2 files changed, 57 insertions(+), 31 deletions(-) diff --git a/packages/cli-ci/src/core/publish.test.ts b/packages/cli-ci/src/core/publish.test.ts index a61648f0..feda20c2 100644 --- a/packages/cli-ci/src/core/publish.test.ts +++ b/packages/cli-ci/src/core/publish.test.ts @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import { tmpdir } from 'node:os'; import { test } from 'node:test'; import { Context } from '@plexus-ms/lib'; import { REPO } from '../testing/checkout.ts'; @@ -72,7 +73,6 @@ const options = { sha: SHA, prefix: 'ghcr.io/Acme', dir: '/repo', - strategy: 'github' as const, encryptionKey: KEY, }; @@ -80,7 +80,7 @@ const buildOf = (calls: Call[]) => calls.find((c) => c.command === 'docker' && c test('an image the forge’s registry holds gets the commit’s tag, and nothing is built or restored', async () => { const { ctx, calls } = world({ holds: ['ghcr.io/acme/website:build-0f2a'] }); - const result = await publish(ctx, { ...options, app: 'website' }); + const result = await publish(ctx, { ...options, app: 'website', context: 'output' }); assert.deepEqual(result, { app: 'website', image: 'ghcr.io/acme/website', @@ -98,7 +98,7 @@ test('an image the forge’s registry holds gets the commit’s tag, and nothing test('a missing image of an app from app-nextjs: a fresh restore of its output through the verb, copied into the image', async () => { const { ctx, calls } = world({ outputs: { website: '0f2a' } }); - const result = await publish(ctx, { ...options, app: 'website' }); + const result = await publish(ctx, { ...options, app: 'website', context: 'output' }); assert.equal(result.built, true); assert.equal(result.digest, 'sha256:built'); assert.deepEqual(result.tags, ['build-0f2a', SHA]); @@ -108,7 +108,7 @@ test('a missing image of an app from app-nextjs: a fresh restore of its output t assert.ok(at(/^rm -rf \/repo\/apps\/website\/\.next\/standalone$/) === 0, order.join('\n')); assert.ok(at(/^mise run build website$/) === 1, order.join('\n')); assert.ok(at(/^docker buildx build /) > 1, order.join('\n')); - assert.match(order.at(-1) ?? '', /^rm -rf \/tmp\/plx-ci-build-[0-9a-f]+$/); + assert.ok(order.at(-1)?.startsWith(`rm -rf ${tmpdir()}/plx-ci-build-`), order.at(-1)); // The repo's own verb, in the checkout, with the key a build that misses the cache needs. const restore = calls.find((c) => c.command === 'mise'); assert.deepEqual(restore?.args, ['run', 'build', 'website']); @@ -133,38 +133,41 @@ test('a missing image of an app from app-nextjs: a fresh restore of its output t assert.match(args, /--provenance=false --sbom=false/); // No layer cache, no key and no package token: the build output holds what the image runs. assert.doesNotMatch(args, /--cache-from|--cache-to|:cache|--secret|BUILD_HASH/); - // Under github the runner's own Docker builds: no builder is made. + // Without BUILDKIT_HOST, as under github, the runner's own Docker builds: no builder is made. assert.doesNotMatch(args, /--builder/); assert.ok(!calls.some((c) => c.command === 'docker' && c.args[1] === 'create')); assert.equal(build?.env?.SOURCE_DATE_EPOCH, '0'); }); -test('under on-prem and hybrid the image is built by the BuildKit service on the runner host', async () => { - for (const strategy of ['on-prem', 'hybrid'] as const) { - const { ctx, calls } = world({ outputs: { website: '0f2a' } }); - await publish(ctx, { ...options, strategy, app: 'website' }); - assert.deepEqual( - calls.filter((c) => c.command === 'docker' && c.args[1] !== 'build').map((c) => c.args), - [ - ['buildx', 'inspect', 'plexus-buildkit'], - ['buildx', 'create', '--name', 'plexus-buildkit', '--driver', 'remote', 'tcp://127.0.0.1:1234'], - ], - ); - assert.match(buildOf(calls)?.args.join(' ') ?? '', /--builder plexus-buildkit/); - } - // A builder of the name made by an earlier publish on the machine is used as it is; BUILDKIT_HOST names another service. - const { ctx, calls } = world({ outputs: { website: '0f2a' }, builders: ['plexus-buildkit'] }); - await publish(ctx, { ...options, strategy: 'on-prem', app: 'website', buildkit: 'tcp://127.0.0.1:4321' }); - assert.ok(!calls.some((c) => c.args[1] === 'create')); - const other = world({ outputs: { website: '0f2a' } }); - await publish(other.ctx, { ...options, strategy: 'on-prem', app: 'website', buildkit: 'tcp://127.0.0.1:4321' }); - assert.ok(other.calls.some((c) => c.args.join(' ').endsWith('--driver remote tcp://127.0.0.1:4321'))); +test('with BUILDKIT_HOST, as a slot of a runner host has it, the image is built by that BuildKit service', async () => { + const { ctx, calls } = world({ outputs: { website: '0f2a' } }); + await publish(ctx, { ...options, app: 'website', context: 'output', buildkit: 'tcp://127.0.0.1:4321' }); + assert.deepEqual( + calls.filter((c) => c.command === 'docker' && c.args[1] !== 'build').map((c) => c.args), + [ + ['buildx', 'inspect', 'plexus-buildkit'], + ['buildx', 'create', '--name', 'plexus-buildkit', '--driver', 'remote', 'tcp://127.0.0.1:4321'], + ], + ); + assert.match(buildOf(calls)?.args.join(' ') ?? '', /--builder plexus-buildkit/); + // A builder of the name made by an earlier publish on the machine is used as it is. + const again = world({ outputs: { website: '0f2a' }, builders: ['plexus-buildkit'] }); + await publish(again.ctx, { ...options, app: 'website', context: 'output', buildkit: 'tcp://127.0.0.1:4321' }); + assert.ok(!again.calls.some((c) => c.args[1] === 'create')); +}); + +test('publish builds from the context the plan gave it and reads no marker', async () => { + // website's marker lists app-nextjs; told `pruned`, publish prunes. + const { ctx, calls } = world(); + await publish(ctx, { ...options, app: 'website', context: 'pruned' }); + assert.ok(calls.some((c) => c.command === 'npx' && c.args.includes('prune'))); + assert.ok(!calls.some((c) => c.command === 'mise')); }); test('an output whose BUILD_ID is not the plan’s hash is not published under it', async () => { const { ctx, calls } = world({ outputs: { website: '9999' } }); await assert.rejects( - publish(ctx, { ...options, app: 'website' }), + publish(ctx, { ...options, app: 'website', context: 'output' }), /apps\/website\/\.next\/standalone holds the build 9999, not 0f2a/, ); assert.equal(buildOf(calls), undefined); @@ -172,13 +175,22 @@ test('an output whose BUILD_ID is not the plan’s hash is not published under i test('an output without BUILD_ID under apps/ is not published: the Dockerfile would start nothing', async () => { const { ctx, calls } = world({ outputs: {} }); - await assert.rejects(publish(ctx, { ...options, app: 'website' }), /no apps\/website\/\.next\/BUILD_ID/); + await assert.rejects( + publish(ctx, { ...options, app: 'website', context: 'output' }), + /no apps\/website\/\.next\/BUILD_ID/, + ); assert.equal(buildOf(calls), undefined); }); test('a missing image of an app with a Dockerfile of its own is built from its pruned context, by the lockfile’s Turbo', async () => { const { ctx, calls } = world(); - const result = await publish(ctx, { ...options, app: 'solver', hash: '9e1d', npmrc: '/run/npmrc' }); + const result = await publish(ctx, { + ...options, + app: 'solver', + hash: '9e1d', + context: 'pruned', + npmrc: '/run/npmrc', + }); assert.equal(result.built, true); assert.ok(!calls.some((c) => c.command === 'mise'), 'no restore of a build output'); const prune = calls.find((c) => c.command === 'npx'); @@ -194,6 +206,12 @@ test('a missing image of an app with a Dockerfile of its own is built from its p assert.match(args, /--tag ghcr\.io\/acme\/solver:build-9e1d --tag ghcr\.io\/acme\/solver:deadbeef/); assert.doesNotMatch(args, /--cache-from|--cache-to|:cache/); assert.equal(build?.env?.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, KEY); + // The key reaches the build as a secret from the environment, never as a build argument or on the command line. + assert.ok(!build?.args.some((a) => a.includes(KEY)), args); + assert.deepEqual( + build?.args.filter((a, i) => build.args[i - 1] === '--build-arg'), + ['APP=solver', 'BUILD_HASH=9e1d'], + ); // The pruned context goes after the build. assert.deepEqual(calls.at(-1)?.args, ['-rf', out]); }); @@ -201,10 +219,13 @@ test('a missing image of an app with a Dockerfile of its own is built from its p test('a publish that would build refuses without the app’s key; one that only tags needs none', async () => { const { ctx, calls } = world({ outputs: { website: '0f2a' } }); await assert.rejects( - publish(ctx, { ...options, app: 'website', encryptionKey: '' }), + publish(ctx, { ...options, app: 'website', context: 'output', encryptionKey: '' }), /NEXT_SERVER_ACTIONS_ENCRYPTION_KEY is empty/, ); assert.ok(!calls.some((c) => c.command !== 'crane')); const there = world({ holds: ['ghcr.io/acme/website:build-0f2a'] }); - assert.equal((await publish(there.ctx, { ...options, app: 'website', encryptionKey: '' })).built, false); + assert.equal( + (await publish(there.ctx, { ...options, app: 'website', context: 'output', encryptionKey: '' })).built, + false, + ); }); diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index 067b91e4..2dcb6d97 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -159,7 +159,12 @@ test('_publish-deploy.yml publishes on a small runner with the trusted cache, de const publish = jobs.publish; assert.match(publish?.['runs-on'] ?? '', /'ci-small'/); assert.deepEqual(caches(publish), ['trusted']); - assert.match(runs(publish), /plx-ci publish "\$APP" "\$HASH" "\$GITHUB_SHA"/); + // The trusted cache exactly where publish builds from the output, whose restore reads it; the plan's context is publish's. + const step = (publish?.steps ?? []).find((s) => s.uses?.endsWith('/.github/actions/turbo-cache')); + assert.equal(step?.if, "${{ matrix.build && matrix.context == 'output' }}"); + assert.match(runs(publish), /plx-ci publish "\$APP" "\$HASH" "\$GITHUB_SHA" --context "\$CONTEXT"/); + const publishStep = (publish?.steps ?? []).find((s) => /plx-ci publish/.test(s.run ?? '')); + assert.equal(publishStep?.env?.CONTEXT, '${{ matrix.context }}'); assert.ok(needsOf(jobs.deploy).includes('publish')); for (const name of ['_e2e.yml', '_publish-deploy.yml']) { const text = readFileSync(join(WORKFLOWS, name), 'utf8'); From 2ba169bde8e7e3c8434b187a9a8a7d7bef1fb6df Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 23:17:10 +0100 Subject: [PATCH 147/194] Test: every slot is handed BUILDKIT_HOST from the port the BuildKit service listens on Not yet in check-ops: the hook would refuse the commit; the role's change adds it. Co-Authored-By: Claude Fable 5.2 --- tests/runner-slot-buildkit.sh | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100755 tests/runner-slot-buildkit.sh diff --git a/tests/runner-slot-buildkit.sh b/tests/runner-slot-buildkit.sh new file mode 100755 index 00000000..8bf85755 --- /dev/null +++ b/tests/runner-slot-buildkit.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Fails unless every slot's container is told where the host's BuildKit +# service listens (actions_runners), from the one variable the service's +# configuration takes its port from: the role writes BUILDKIT_HOST from +# actions_runners_buildkit_port into slot.env, and files/ci-runner-slot hands +# it to the container, whatever its size; a publish job reads it there, and +# builds through the runner's Docker where it is unset. Runs the slot script +# with its paths moved into a directory of its own and docker replaced by a +# stub that prints the arguments, as runner-slot-mounts.sh does. +set -euo pipefail +cd "$(dirname "$0")/.." + +role=ansible/ci/roles/actions_runners +slot=$role/files/ci-runner-slot +failed=0 +port='{{ actions_runners_buildkit_port }}' +if ! grep -qxF " BUILDKIT_HOST=tcp://127.0.0.1:$port" "$role/tasks/main.yml"; then + echo "✗ the role writes no BUILDKIT_HOST=tcp://127.0.0.1:$port into slot.env" >&2 + failed=1 +fi +if ! grep -qF "address = [\"tcp://127.0.0.1:$port\"]" "$role/tasks/buildkit.yml"; then + echo "✗ the BuildKit service listens elsewhere than tcp://127.0.0.1:$port" >&2 + failed=1 +fi + +dir=$(mktemp -d) +trap 'rm -rf "$dir"' EXIT +mkdir "$dir/etc" "$dir/run" +sed -e "s|/etc/ci-runner/|$dir/etc/|g" -e "s|/run/ci-runner/|$dir/run/|g" \ + -e "s|/usr/bin/docker|$dir/docker|g" "$slot" >"$dir/ci-runner-slot" +printf '#!/bin/sh\nprintf "%%s\\n" "$@"\n' >"$dir/docker" +chmod +x "$dir/docker" +printf 'IMAGE=image\nCACHE_DIR=/cache-dir\nBUILDKIT_HOST=tcp://127.0.0.1:4321\n' >"$dir/etc/slot.env" +for size in small medium large; do + printf 'MEMORY=1g\n' >"$dir/etc/size-$size.env" + : >"$dir/run/$size-1.env" + args=$(sh "$dir/ci-runner-slot" "$size-1") + if ! printf '%s\n' "$args" | grep -qx 'BUILDKIT_HOST=tcp://127.0.0.1:4321'; then + echo "✗ a $size slot is not given BUILDKIT_HOST" >&2 + failed=1 + fi +done +exit "$failed" From 95917426035e209464f53543d0985ce51ff25578 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 23:17:58 +0100 Subject: [PATCH 148/194] plx-ci plan: an app's suite from Turbo's graph, the rule mise run e2e follows; one line for a checkout without apps/; a marker that does not parse named The dry run is of build and e2e; the e2e tasks are read for their package's directory and waited-for build alone. The plan's own reading of e2e/* goes. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/commands/plan.ts | 10 +-- packages/cli-ci/src/core/plan.ts | 91 ++++++++++++++++------------ 2 files changed, 54 insertions(+), 47 deletions(-) diff --git a/packages/cli-ci/src/commands/plan.ts b/packages/cli-ci/src/commands/plan.ts index ec11fe1c..ae03f67a 100644 --- a/packages/cli-ci/src/commands/plan.ts +++ b/packages/cli-ci/src/commands/plan.ts @@ -20,7 +20,7 @@ import { appendFileSync } from 'node:fs'; import { resolve } from 'node:path'; import { readDeployTargets, targetsIn } from '@plexus-ms/lib'; import type { Command } from 'commander'; -import { environmentOf, plan, readHashes } from '../core/plan.ts'; +import { appsOf, environmentOf, plan, readHashes } from '../core/plan.ts'; import { contextOf } from '../program.ts'; import { imagePrefix, need, settings, withStrategy } from './shared.ts'; @@ -47,13 +47,7 @@ export function register(program: Command): void { const s = settings(opts); const dir = resolve(opts.dir); const env = process.env; - const all = - apps.length > 0 - ? apps - : (await ctx.readDir(`${dir}/apps`)) - .filter((e) => e.directory) - .map((e) => e.name) - .sort(); + const all = apps.length > 0 ? apps : await appsOf(ctx, dir); const environment = opts.deploy ? environmentOf(env.GITHUB_EVENT_NAME ?? '', env.GITHUB_REF_NAME ?? '', opts.environment) : ''; diff --git a/packages/cli-ci/src/core/plan.ts b/packages/cli-ci/src/core/plan.ts index 578e2eca..b0ec94f6 100644 --- a/packages/cli-ci/src/core/plan.ts +++ b/packages/cli-ci/src/core/plan.ts @@ -8,8 +8,11 @@ // commit's tag. A leg also says what publish makes the image from, `output`, // the directory the app's build leaves (an app from app-nextjs, by its // marker), or `pruned`, a pruned context its Dockerfile builds itself from (§ -// 4 PLX-Delivery); and the directory of the app's E2E suite, empty for none, -// for its e2e job's browser. Each leg names the runner of its e2e job, from +// 4 PLX-Delivery), which publish is handed; and the directory of the app's +// E2E suite, empty for none, for its e2e job's browser. A suite is what +// `mise run e2e ` runs: a package whose e2e task Turbo has wait for the +// app's build, read from the same dry run, of `build` and `e2e`; the e2e +// tasks' hashes are not used. Each leg names the runner of its e2e job, from // the strategy: the forge's, a large slot, or, under hybrid, the one label of // an instance `hybrid create-instances` then creates for it. With a deploy // asked for, the plan also says which environment the run deploys into and @@ -29,27 +32,58 @@ import { parseAllDocuments } from 'yaml'; import { craneDigest, imageName } from './registry.ts'; import { runnerOf, type Strategy } from './strategy.ts'; -/** One app's build hash, Turbo's hash of its package's build task. */ +/** One app's build hash, Turbo's hash of its package's build task, and the directory of its E2E suite, empty for none. */ export interface Hash { app: string; hash: string; + suite: string; } /** Turbo's marker for a task whose script the package does not define. */ const NONEXISTENT = ''; -/** The build hashes from Turbo's dry run (`turbo run build --dry-run=json`), per app, by its package's name. */ +/** + * The build hashes from Turbo's dry run (`turbo run build e2e --dry-run=json`), + * per app, by its package's name, and the directory of the first package + * whose e2e task waits for that build. + */ export function hashesOf(dryRun: string, packages: Record): Hash[] { const data = JSON.parse(dryRun) as { - tasks?: { taskId: string; package: string; hash: string; command?: string }[]; + tasks?: { + taskId: string; + package: string; + hash: string; + command?: string; + directory?: string; + dependencies?: string[]; + }[]; }; const tasks = (data.tasks ?? []).filter((t) => t.command !== NONEXISTENT); return Object.entries(packages).flatMap(([app, name]) => { const build = tasks.find((t) => t.package === name && t.taskId.endsWith('#build')); - return build ? [{ app, hash: build.hash }] : []; + if (!build) return []; + const suites = tasks + .filter((t) => t.taskId.endsWith('#e2e') && t.dependencies?.includes(build.taskId)) + .map((t) => t.directory ?? '') + .sort(); + return [{ app, hash: build.hash, suite: suites[0] ?? '' }]; }); } +/** The apps of a checkout: the directories under apps/, sorted. */ +export async function appsOf(ctx: Context, dir: string): Promise { + let entries: { name: string; directory: boolean }[]; + try { + entries = await ctx.readDir(`${dir}/apps`); + } catch { + throw new UsageError(`${dir} has no apps/: the plan reads the apps of an app repo there`); + } + return entries + .filter((e) => e.directory) + .map((e) => e.name) + .sort(); +} + /** The name of an app's package, `apps//package.json`: what Turbo calls it. */ export async function packageName(ctx: Context, dir: string, app: string): Promise { const pkg = JSON.parse(await ctx.readFile(`${dir}/apps/${app}/package.json`)) as { name?: string }; @@ -75,7 +109,7 @@ export async function turboOf(ctx: Context, dir: string): Promise { throw new UsageError('pnpm-lock.yaml locks no turbo for the workspace root, which the repo’s verbs run'); } -/** The build hashes of `apps`, from the dry run of the Turbo the lockfile has, in `env`, the repo's mise environment. */ +/** The build hashes and suites of `apps`, from the dry run of the Turbo the lockfile has, in `env`, the repo's mise environment. */ export async function readHashes( ctx: Context, dir: string, @@ -89,7 +123,7 @@ export async function readHashes( const packages: Record = {}; for (const app of apps) packages[app] = await packageName(ctx, dir, app); const turbo = await turboOf(ctx, dir); - const out = await ctx.read('npx', ['--yes', turbo, 'run', 'build', '--dry-run=json'], { cwd: dir, env }); + const out = await ctx.read('npx', ['--yes', turbo, 'run', 'build', 'e2e', '--dry-run=json'], { cwd: dir, env }); return hashesOf(out, packages); } @@ -98,34 +132,18 @@ export type ImageContext = 'output' | 'pruned'; /** An app's image context: `output` where its marker lists the template app-nextjs, whose Dockerfile only copies the build output; `pruned` otherwise. */ export async function imageContextOf(ctx: Context, dir: string, app: string): Promise { + const path = `apps/${app}/${MARKER_FILE}`; let marker: string; try { - marker = await ctx.readFile(`${dir}/apps/${app}/${MARKER_FILE}`); + marker = await ctx.readFile(`${dir}/${path}`); } catch { return 'pruned'; } - return (parseMarkerConfig(marker).templates ?? []).includes('app-nextjs') ? 'output' : 'pruned'; -} - -/** The directory of the E2E suite of the package `name`, `e2e/`: a package there with an `e2e` script that depends on it; empty for none. */ -export async function suiteOf(ctx: Context, dir: string, name: string): Promise { - let entries: { name: string; directory: boolean }[] = []; try { - entries = await ctx.readDir(`${dir}/e2e`); - } catch { - return ''; - } - for (const entry of entries.filter((e) => e.directory).sort((a, b) => a.name.localeCompare(b.name))) { - let pkg: { scripts?: Record; dependencies?: object; devDependencies?: object }; - try { - pkg = JSON.parse(await ctx.readFile(`${dir}/e2e/${entry.name}/package.json`)); - } catch { - continue; - } - if (pkg.scripts?.e2e && (name in (pkg.dependencies ?? {}) || name in (pkg.devDependencies ?? {}))) - return `e2e/${entry.name}`; + return (parseMarkerConfig(marker).templates ?? []).includes('app-nextjs') ? 'output' : 'pruned'; + } catch (error) { + throw new UsageError(`${path}: ${error instanceof Error ? error.message : String(error)}`); } - return ''; } /** The run a plan is for; names the instances under hybrid. */ @@ -157,16 +175,12 @@ export interface DeployLeg { } /** The runner of each app's e2e job, before the checkout and the registry are read. */ -export function legsOf( - apps: string[], - hashes: Hash[], - strategy: Strategy, - run: Run, -): Omit[] { +export function legsOf(apps: string[], hashes: Hash[], strategy: Strategy, run: Run): Omit[] { return apps.map((app) => { - const hash = hashes.find((h) => h.app === app)?.hash; - if (!hash) throw new UsageError(`no build hash for ${app}; is it an app package of the workspace?`); - return { app, hash, runner: runnerOf(strategy, 'large', `exo-large-${run.runId}-${app}-${run.attempt}`) }; + const found = hashes.find((h) => h.app === app); + if (!found) throw new UsageError(`no build hash for ${app}; is it an app package of the workspace?`); + const runner = runnerOf(strategy, 'large', `exo-large-${run.runId}-${app}-${run.attempt}`); + return { app, hash: found.hash, runner, suite: found.suite }; }); } @@ -229,7 +243,6 @@ export async function plan(ctx: Context, dir: string, options: PlanOptions): Pro ctx.say(`${leg.app}: ${ref} ${build ? 'is missing; publish builds it' : 'exists; publish tags it'}`); result.legs.push({ ...leg, - suite: await suiteOf(ctx, dir, await packageName(ctx, dir, leg.app)), context: await imageContextOf(ctx, dir, leg.app), build, }); From d71f31947d9093d3f83103019c5ea878cce8ec6e Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 23:18:43 +0100 Subject: [PATCH 149/194] plx-ci publish builds through the BuildKit service exactly when BUILDKIT_HOST is set, from the context the plan's leg gives it No address or port of the service in plx-ci, and no strategy read by publish: a slot of a runner host is handed BUILDKIT_HOST, the forge's runners are not. _publish-deploy.yml passes the leg's context, and its header says the gate on test and e2e is its caller's; the comment above the e2e job of _e2e.yml says what it meant. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/_e2e.yml | 5 ++- .github/workflows/_publish-deploy.yml | 16 +++++--- packages/cli-ci/src/commands/publish.ts | 52 ++++++++++++++++--------- packages/cli-ci/src/core/build.ts | 31 +++++++-------- packages/cli-ci/src/core/publish.ts | 12 +++--- packages/cli-ci/src/program.test.ts | 2 +- 6 files changed, 67 insertions(+), 51 deletions(-) diff --git a/.github/workflows/_e2e.yml b/.github/workflows/_e2e.yml index e7ec02b3..dfc14035 100644 --- a/.github/workflows/_e2e.yml +++ b/.github/workflows/_e2e.yml @@ -289,8 +289,9 @@ jobs: # of its suite, its suites. The other apps' jobs run on when one fails # (fail-fast off), and every publish of the run waits for all of them. The # name is fixed: the forge does not evaluate `matrix` for a job it skips. - # The plan's mise steps hand PLX_PLATFORM to `plx-ci plan` as this job's - # hand it to the build, so that the two compute one hash. + # PLX_PLATFORM reaches the build here and `plx-ci plan` in the plan job from + # the same place, the repo's mise.toml, through the mise steps of each job, + # so that the plan's hash is the build's. e2e: name: e2e needs: plan diff --git a/.github/workflows/_publish-deploy.yml b/.github/workflows/_publish-deploy.yml index b150d18a..7d45d27f 100644 --- a/.github/workflows/_publish-deploy.yml +++ b/.github/workflows/_publish-deploy.yml @@ -15,13 +15,16 @@ name: _publish-deploy # tag-display-version small the cut version's tag and GitHub Release, once every deploy is green # # That a published image was tested is the order of the jobs, and nothing -# records it: this workflow runs only once the run's test job and every e2e -# job have passed, so an app's image is published from content whose test and -# e2e passed in the same run, and a failed e2e of one app publishes nothing. +# records it. The gate is the caller's: on_push.yml of repo-turbo calls this +# workflow with `needs: [test, e2e]`, so it runs only once the run's test job +# and every e2e job have passed, an app's image is published from content +# whose test and e2e passed in the same run, and a failed e2e of one app +# publishes nothing. This workflow has no job that waits on them itself. # A publish that builds reaches the trusted cache alone, from a fresh checkout, # where the app's e2e job left the build output, and builds the image through -# the runner's Docker under github and the runner host's BuildKit service -# under on-prem and hybrid (plx-ci publish says how). One whose image exists, +# the runner host's BuildKit service where the slot has BUILDKIT_HOST (on-prem +# and hybrid), else through the runner's Docker (github; plx-ci publish says +# how). One whose image exists, # a promotion's or a change to tests alone, builds nothing, adds the commit's # tag, and its deploy leaves the app running where the host serves that image. # @@ -227,8 +230,9 @@ jobs: env: APP: ${{ matrix.app }} HASH: ${{ matrix.hash }} + CONTEXT: ${{ matrix.context }} NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ steps.key.outputs.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }} - run: plx-ci publish "$APP" "$HASH" "$GITHUB_SHA" + run: plx-ci publish "$APP" "$HASH" "$GITHUB_SHA" --context "$CONTEXT" # One deploy per app with a target in the environment; an app without a # record there has no deployment there, which the plan said. The nested diff --git a/packages/cli-ci/src/commands/publish.ts b/packages/cli-ci/src/commands/publish.ts index e28ecfa8..2fa0c397 100644 --- a/packages/cli-ci/src/commands/publish.ts +++ b/packages/cli-ci/src/commands/publish.ts @@ -1,39 +1,53 @@ -// plx-ci publish : put the app's image under its commit in -// the forge's registry, the one production pulls from (§ 4 PLX-Delivery): -// tagged where build- is there already, else built and pushed under -// both, from the build output restored by the repo's `mise run build ` -// or, for a Dockerfile of the app's own, from a pruned context. Runs in a +// plx-ci publish --context : put the app's +// image under its commit in the forge's registry, the one production pulls +// from (§ 4 PLX-Delivery): tagged where build- is there already, else +// built and pushed under both, from the build output restored by the repo's +// `mise run build ` (`output`) or, for a Dockerfile of the app's own, +// from a pruned context (`pruned`), as the plan's leg says. Runs in a // checkout, in the repo's mise environment, with crane on the PATH and // logged in to the forge's registry, and docker's client with buildx. From -// the environment: CI_STRATEGY, which decides where the image is built (the -// runner's Docker under github, the runner host's BuildKit service -// otherwise); BUILDKIT_HOST, that service where it is not on -// 127.0.0.1:1234; IMAGE_PREFIX, where the images live (default -// ghcr.io/); NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, -// the app's key, needed where it builds; NPM_CONFIG_USERCONFIG, a user-level -// npmrc with the token of the tenant's private package registry, handed to a -// Dockerfile of the app's own as a secret. Prints the image, and writes -// image= to GITHUB_OUTPUT when that is set. +// the environment: BUILDKIT_HOST, the BuildKit service to build through, +// which a slot of a runner host is handed, else the runner's Docker builds; +// IMAGE_PREFIX, where the images live (default ghcr.io/); NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, the app's key, +// needed where it builds; NPM_CONFIG_USERCONFIG, a user-level npmrc with the +// token of the tenant's private package registry, handed to a Dockerfile of +// the app's own as a secret. Prints the image, and writes image= to +// GITHUB_OUTPUT when that is set. // -// plx-ci publish website 0f2a3f35123dfd73 "$GITHUB_SHA" +// plx-ci publish website 0f2a3f35123dfd73 "$GITHUB_SHA" --context output import { appendFileSync } from 'node:fs'; import { resolve } from 'node:path'; import type { Command } from 'commander'; +import { Option } from 'commander'; +import type { ImageContext } from '../core/plan.ts'; import { publish } from '../core/publish.ts'; import { contextOf } from '../program.ts'; -import { imagePrefix, settings, withStrategy } from './shared.ts'; +import { imagePrefix } from './shared.ts'; export function register(program: Command): void { - withStrategy(program.command('publish')) + program + .command('publish') .description( 'publish one app’s image as in the forge’s registry: tag build- where it is there, else build it and push it', ) .argument('', 'the app, apps/ in the checkout') .argument('', 'Turbo’s hash of the app’s build task') .argument('', 'the commit, the tag a deploy takes') + .addOption( + new Option('--context ', 'what the image is made from, as the plan’s leg says') + .choices(['output', 'pruned']) + .makeOptionMandatory(), + ) .option('-C, --dir ', 'the checkout to read', '.') .action( - async (app: string, hash: string, sha: string, opts: { strategy?: string; dir: string }, command: Command) => { + async ( + app: string, + hash: string, + sha: string, + opts: { context: ImageContext; dir: string }, + command: Command, + ) => { const ctx = contextOf(command); const env = process.env; const result = await publish(ctx, { @@ -42,7 +56,7 @@ export function register(program: Command): void { sha, prefix: imagePrefix(), dir: resolve(opts.dir), - strategy: settings(opts).strategy, + context: opts.context, encryptionKey: env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY ?? '', npmrc: env.NPM_CONFIG_USERCONFIG || undefined, buildkit: env.BUILDKIT_HOST || undefined, diff --git a/packages/cli-ci/src/core/build.ts b/packages/cli-ci/src/core/build.ts index 73db4640..85f993f3 100644 --- a/packages/cli-ci/src/core/build.ts +++ b/packages/cli-ci/src/core/build.ts @@ -1,6 +1,7 @@ // Build one app's image and push it (§ 4 PLX-Delivery), for publish, which // builds only an image the forge's registry lacks. An app's image is made in -// one of two ways, by what its Dockerfile is (plan.ts's imageContextOf): +// one of two ways, by what its Dockerfile is, the context the plan gives it +// (plan.ts's imageContextOf): // // output an app from app-nextjs: its Dockerfile only copies the one // directory its build leaves (apps//.next/standalone), and @@ -32,12 +33,14 @@ // and nothing else. No rewrite-timestamp: the runner's Docker of the forge // refuses it beside the unpack of its image store, and an image is built once // per hash, so no two builds of it are compared. BuildKit's log is the -// job's, at every verbosity. Where the build runs is the strategy's: under -// github the runner's own Docker (the default builder), under on-prem and -// hybrid the BuildKit service of the runner host (actions_runners), on -// 127.0.0.1:1234 unless BUILDKIT_HOST names another, through a buildx -// builder of the remote driver, plexus-buildkit, made where the machine has -// none of the name yet. The push uses the login of the job's +// job's, at every verbosity. Where the build runs is told apart at this step +// by BUILDKIT_HOST alone, which knows no strategy: a slot of a runner host, +// under on-prem and hybrid, is handed the address of the host's BuildKit +// service there (actions_runners, from the port the service listens on), and +// the build goes through a buildx builder of the remote driver to it, +// plexus-buildkit, made where the machine has none of the name yet; without +// it, as on the forge's runners under github, the runner's own Docker builds +// (the default builder). The push uses the login of the job's // ~/.docker/config.json, which BuildKit is handed through the build's session. import { randomBytes } from 'node:crypto'; import { tmpdir } from 'node:os'; @@ -45,10 +48,7 @@ import { join } from 'node:path'; import type { Context, Step } from '@plexus-ms/lib'; import { run, UsageError } from '@plexus-ms/lib'; import { type ImageContext, packageName, turboOf } from './plan.ts'; -import type { Strategy } from './strategy.ts'; -/** The BuildKit service of a runner host, where actions_runners puts it. */ -export const BUILDKIT = 'tcp://127.0.0.1:1234'; /** The buildx builder of the remote driver that reaches it. */ export const BUILDER = 'plexus-buildkit'; @@ -64,12 +64,11 @@ export interface BuildOptions { context: ImageContext; /** The checkout. */ dir: string; - strategy: Strategy; /** The app's server-actions key: for a build of the output that misses the cache, or a secret of a Dockerfile of its own. */ encryptionKey: string; /** A user-level npmrc with the token of the tenant's private package registry, a secret of a Dockerfile of its own. */ npmrc?: string; - /** The BuildKit service under on-prem and hybrid; default BUILDKIT. */ + /** The BuildKit service to build through, `tcp://
:` (BUILDKIT_HOST); without it the runner's Docker. */ buildkit?: string; } @@ -132,18 +131,16 @@ export function buildStep(args: string[], env: NodeJS.ProcessEnv): Step { return run('docker', args, { env, interactive: true }); } -/** The builder of the strategy: none under github, the runner's Docker; the remote one of the BuildKit service otherwise, made where missing. */ +/** The builder: the remote one of the BuildKit service where one is given, made where missing; none, the runner's Docker, otherwise. */ async function builderFor(ctx: Context, options: BuildOptions): Promise { - if (options.strategy === 'github') return undefined; + if (!options.buildkit) return undefined; if (!ctx.dryRun) { try { await ctx.read('docker', ['buildx', 'inspect', BUILDER]); return BUILDER; } catch {} } - await ctx.apply([ - run('docker', ['buildx', 'create', '--name', BUILDER, '--driver', 'remote', options.buildkit || BUILDKIT]), - ]); + await ctx.apply([run('docker', ['buildx', 'create', '--name', BUILDER, '--driver', 'remote', options.buildkit])]); return BUILDER; } diff --git a/packages/cli-ci/src/core/publish.ts b/packages/cli-ci/src/core/publish.ts index 2edbb3d1..aa4396f6 100644 --- a/packages/cli-ci/src/core/publish.ts +++ b/packages/cli-ci/src/core/publish.ts @@ -10,9 +10,8 @@ import type { Context } from '@plexus-ms/lib'; import { run } from '@plexus-ms/lib'; import { build } from './build.ts'; -import { imageContextOf } from './plan.ts'; +import type { ImageContext } from './plan.ts'; import { craneDigest, imageName } from './registry.ts'; -import type { Strategy } from './strategy.ts'; export interface PublishOptions { app: string; @@ -24,12 +23,13 @@ export interface PublishOptions { prefix: string; /** The checkout. */ dir: string; - strategy: Strategy; + /** What the image is made from, as the plan says (plan.ts's imageContextOf). */ + context: ImageContext; /** The app's server-actions key, which a build needs and a tag does not. */ encryptionKey: string; /** A user-level npmrc with the token of the tenant's private package registry. */ npmrc?: string; - /** The BuildKit service under on-prem and hybrid, as `tcp://
:`. */ + /** The BuildKit service to build through, `tcp://
:`; without it the runner's Docker. */ buildkit?: string; } @@ -51,10 +51,10 @@ export async function publish(ctx: Context, options: PublishOptions): Promise c.name()); assert.deepEqual(names, ['registry', 'plan', 'publish', 'display-versions', 'tag-display-version', 'hybrid']); - for (const name of ['registry', 'plan', 'publish']) { + for (const name of ['registry', 'plan']) { const command = program.commands.find((c) => c.name() === name); assert.ok( command?.options.some((o) => o.long === '--strategy'), From 615c8bd370ac6cf334c8eaf41a5dbe143388c8e8 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 23:19:16 +0100 Subject: [PATCH 150/194] actions_runners hands every slot BUILDKIT_HOST from the port its BuildKit service listens on; the size list and the premise of the shared caches say what is true now The one place of the port is actions_runners_buildkit_port: slot.env carries BUILDKIT_HOST from it, and ci-runner-slot passes it to the container. check-ops runs tests/runner-slot-buildkit.sh. The defaults name test medium and e2e large, and say that an e2e job holds the trusted cache's keys and the server-actions key. Co-Authored-By: Claude Fable 5.2 --- ansible/ci/roles/actions_runners/defaults/main.yml | 10 +++++++--- ansible/ci/roles/actions_runners/files/ci-runner-slot | 4 +++- ansible/ci/roles/actions_runners/tasks/main.yml | 9 ++++++--- mise.toml | 3 ++- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/ansible/ci/roles/actions_runners/defaults/main.yml b/ansible/ci/roles/actions_runners/defaults/main.yml index 029eca04..f9a5c3d3 100644 --- a/ansible/ci/roles/actions_runners/defaults/main.yml +++ b/ansible/ci/roles/actions_runners/defaults/main.yml @@ -43,7 +43,7 @@ actions_runners_runner_group: Default # The slots, by size: `small: { count: 4 }` is the units ci-runner@small-1 # to ci-runner@small-4, each registering with the label ci-small (§ 8 # PLX-Delivery: plan, publish, deploy, cleanup and housekeeping are small, -# check is medium, build and test are large). `memory` is the limit of one +# test is medium, e2e is large). `memory` is the limit of one # slot's container, as `docker run --memory` takes it; under it a job is # killed rather than the host starved, and it covers everything the job # starts, a browser and a test database included. Empty, or left out, @@ -123,7 +123,10 @@ actions_runners_registry_secret_key: "{{ lookup('env', 'REGISTRY_SECRET_KEY') | # its packages it needs into its own container, which goes with the job. # The medium and large slots run test and e2e and share all four among # themselves, a job there able to change what a later one runs: accepted, -# since none of them holds those secrets. Nothing prunes the caches: a +# since none of them holds the deploy or publish secrets, though an e2e job +# holds the keys of the trusted cache, in the cache server it starts, and the +# app's server-actions key, so a test or e2e job can change what a later e2e +# job runs while it writes the trusted cache. Nothing prunes the caches: a # version no repo pins any more stays until removed by hand. Owned by the # image's runner user. actions_runners_cache_dir: /var/cache/ci-runner @@ -230,7 +233,8 @@ actions_runners_disk_alert_percent: 85 # the operator's on the host, as in `buildctl --addr tcp://127.0.0.1:1234 du`. actions_runners_buildkit_version: v0.35.1 actions_runners_buildkit_sha256: b248c2b91698aafef11818fe8b681dc5e341581f7d5676709ff45ca1f29b0408 -# The port on 127.0.0.1, which the publish job names in its remote driver. +# The port on 127.0.0.1, which the role hands every slot as BUILDKIT_HOST, where +# the publish job names it in its remote driver. actions_runners_buildkit_port: 1234 # The most disk the cache may use, BuildKit's maxUsedSpace: bytes with a # unit (10GB, as base 1024) or a percentage of the disk (20%); what is above diff --git a/ansible/ci/roles/actions_runners/files/ci-runner-slot b/ansible/ci/roles/actions_runners/files/ci-runner-slot index 8112b63c..6b87a5eb 100755 --- a/ansible/ci/roles/actions_runners/files/ci-runner-slot +++ b/ansible/ci/roles/actions_runners/files/ci-runner-slot @@ -24,7 +24,7 @@ # test and e2e, which hold none of those secrets, and share the caches among # themselves (tests/runner-slot-mounts.sh holds the mounts of each size). # -# From /etc/ci-runner/slot.env: IMAGE and CACHE_DIR; from +# From /etc/ci-runner/slot.env: IMAGE, CACHE_DIR and BUILDKIT_HOST; from # /etc/ci-runner/size-.env: MEMORY, the container's limit, empty for # none. The slot's runner config is /run/ci-runner/.env, minted by # ci-runner-jit before this. Hand-runnable as root, after ci-runner-jit: @@ -53,6 +53,8 @@ if [ "$size" != small ]; then -v "$CACHE_DIR/ms-playwright:$home/.cache/ms-playwright" fi [ -z "$MEMORY" ] || set -- "$@" --memory "$MEMORY" +# The host's BuildKit service, which a publish job builds its image through. +[ -z "${BUILDKIT_HOST:-}" ] || set -- "$@" -e "BUILDKIT_HOST=$BUILDKIT_HOST" # The host's Connect server, where the role runs one (/etc/ci-runner/connect.env: # OP_CONNECT_TOKEN and OP_CONNECT_PORT): the job's secret reads go there. if [ -f /etc/ci-runner/connect.env ]; then diff --git a/ansible/ci/roles/actions_runners/tasks/main.yml b/ansible/ci/roles/actions_runners/tasks/main.yml index 796279cf..b2d6f2c4 100644 --- a/ansible/ci/roles/actions_runners/tasks/main.yml +++ b/ansible/ci/roles/actions_runners/tasks/main.yml @@ -183,9 +183,11 @@ - name: The BuildKit service ansible.builtin.include_tasks: buildkit.yml -# What a slot's container is made of: the image for every slot and the -# cache directory a medium or large slot mounts from, the memory limit per -# size. ci-runner-slot reads both at the start of +# What a slot's container is made of: the image for every slot, the +# cache directory a medium or large slot mounts from, and where the host's +# BuildKit service listens, which every slot's jobs are told as BUILDKIT_HOST +# (a publish builds through it), from the one variable the service's +# configuration takes its port from; the memory limit per size. ci-runner-slot reads both at the start of # a container, and the JIT script reads where to register, so a change to any # of them restarts the slots (the handler): a job in flight on this host # fails and is run again by hand, which a configure run on a runner host @@ -200,6 +202,7 @@ content: | IMAGE={{ actions_runners_image }} CACHE_DIR={{ actions_runners_cache_dir }} + BUILDKIT_HOST=tcp://127.0.0.1:{{ actions_runners_buildkit_port }} notify: Restart the slots - name: Write each size's limit diff --git a/mise.toml b/mise.toml index e84e9957..9052579a 100644 --- a/mise.toml +++ b/mise.toml @@ -171,7 +171,7 @@ hide = true run = "pnpm plx doctor" [tasks.check-ops] -description = "actionlint over the workflows; ansible-lint over the collections (their Galaxy dependencies installed on first use), a syntax check of their playbooks and of a playbook that lists every role; the runner image on the apps' runtime base; what each size of slot mounts" +description = "actionlint over the workflows; ansible-lint over the collections (their Galaxy dependencies installed on first use), a syntax check of their playbooks and of a playbook that lists every role; the runner image on the apps' runtime base; what each size of slot mounts, and that every slot is told where the BuildKit service listens" hide = true run = [ 'actionlint', @@ -182,6 +182,7 @@ run = [ './tests/all-roles-listed.sh', './tests/runner-image-base.sh', './tests/runner-slot-mounts.sh', + './tests/runner-slot-buildkit.sh', ] # ANSIBLE_HOME keeps ansible-lint's cache and every collections path inside the # project, so a plexus.* collection installed user-wide (a tenant's pin) never From 68e6fcd4ac90dd0bb9ad0671a71443d604cf5a3d Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 23:19:26 +0100 Subject: [PATCH 151/194] plx-ci's description no longer promises reproducible image builds Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/cli-ci/package.json b/packages/cli-ci/package.json index a0cd5717..b7b7944b 100644 --- a/packages/cli-ci/package.json +++ b/packages/cli-ci/package.json @@ -1,7 +1,7 @@ { "name": "@plexus-ms/cli-ci", "version": "0.133.0", - "description": "plx-ci, the CI verbs of Plexus: throwaway runners on a cloud, a registry on object storage, reproducible image builds, and their teardown", + "description": "plx-ci, the CI verbs of Plexus: the plan of a run, the publish of an app's image, throwaway runners on a cloud and their teardown, and a registry on object storage", "license": "GPL-3.0-or-later", "type": "module", "bin": { From 60672918d6e6dead45f510baa71692d9b7930c27 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 23:19:51 +0100 Subject: [PATCH 152/194] The newborn's publish is handed the leg's context, as the workflow hands it Co-Authored-By: Claude Fable 5.2 --- newborns/pipeline.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/newborns/pipeline.test.ts b/newborns/pipeline.test.ts index 18c4cac2..16bdcfcc 100644 --- a/newborns/pipeline.test.ts +++ b/newborns/pipeline.test.ts @@ -167,7 +167,7 @@ async function pipeline(sha: string): Promise { const publishJob = await checkout(sha); const publishOut = await step( publishJob, - ['mise', 'exec', CRANE, '--', 'plx-ci', '--json', 'publish', leg.app, leg.hash, sha], + ['mise', 'exec', CRANE, '--', 'plx-ci', '--json', 'publish', leg.app, leg.hash, sha, '--context', leg.context], { ...ci, NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: KEY }, ); const published = JSON.parse(publishOut.slice(publishOut.indexOf('{\n'))); From 5b4d3ad88a3d3fc9347233338e7c81b82bc59e09 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 23:56:41 +0100 Subject: [PATCH 153/194] Tests first: the pipeline and the templates hold nothing of the candidate registry pair or ci_registry These fail until the removal that follows: the commit before it is red on purpose, and the pre-commit hook (static checks) lets it through. Co-Authored-By: Claude Fable 5.2 --- newborns/repo-operations.test.ts | 1 - .../cli-ci/src/core/createInstances.test.ts | 5 +- packages/cli-ci/src/core/registry.test.ts | 185 ++---------------- packages/cli-ci/src/core/strategy.test.ts | 9 +- packages/cli-ci/src/core/time.test.ts | 26 +-- packages/cli-ci/src/core/userData.test.ts | 5 +- packages/cli-ci/src/program.test.ts | 4 +- packages/lib/src/doctor.test.ts | 19 +- packages/lib/src/newSite.test.ts | 1 - packages/lib/src/repoOperations.test.ts | 42 ++-- packages/lib/src/repoTurbo.test.ts | 35 ++-- packages/lib/src/repoTurboCache.test.ts | 15 +- packages/lib/src/testing/shapes.ts | 2 - 13 files changed, 83 insertions(+), 266 deletions(-) diff --git a/newborns/repo-operations.test.ts b/newborns/repo-operations.test.ts index 92e04653..36622a06 100644 --- a/newborns/repo-operations.test.ts +++ b/newborns/repo-operations.test.ts @@ -17,7 +17,6 @@ const SHAPES: [string, Record][] = [ ['github', {}], ['hybrid', { infrastructure: 'true', ci_strategy: 'hybrid', pr_reviewers: 'reviewer-a,reviewer-b' }], ['on-prem', { ci_strategy: 'on-prem', ci_overlay: 'netbird' }], - ['own-registry', { ci_registry: 'own' }], ]; /** The verbs a repo answers with a verdict, each from the checkout as it is. */ diff --git a/packages/cli-ci/src/core/createInstances.test.ts b/packages/cli-ci/src/core/createInstances.test.ts index 0000aa94..1f1765e9 100644 --- a/packages/cli-ci/src/core/createInstances.test.ts +++ b/packages/cli-ci/src/core/createInstances.test.ts @@ -38,11 +38,10 @@ const options: LaunchOptions = { sleep: async () => {}, }; -test('the user-data is rendered with the run’s facts and the week’s buckets, and fits the API', () => { +test('the user-data is rendered with the run’s facts, and fits the API', () => { const text = renderUserData(options, 'JIT', now); assert.match(text, /^hostname: exo-large-41-website-1$/m); - assert.match(text, /REGISTRY_BUCKET=acme-ci-registry-2026-w45/); - assert.match(text, /REGISTRY_PREVIOUS_BUCKET=acme-ci-registry-2026-w44/); + assert.doesNotMatch(text, /REGISTRY/); assert.match(text, /SELF_LAYERS=off/); assert.match(text, /ACTIONS_RUNNER_INPUT_JITCONFIG=JIT$/m); assert.match(text, /docker pull -q ghcr\.io\/plexus-ms\/ci-runner:sha-abc$/m); diff --git a/packages/cli-ci/src/core/registry.test.ts b/packages/cli-ci/src/core/registry.test.ts index 4d8ebc67..00c5bfb7 100644 --- a/packages/cli-ci/src/core/registry.test.ts +++ b/packages/cli-ci/src/core/registry.test.ts @@ -2,79 +2,18 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { Context, ExecError } from '@plexus-ms/lib'; import { fakeIo, notThere } from '../testing/fakeIo.ts'; -import { - candidateRef, - digestOf, - findTag, - imageName, - layersOf, - loggedIn, - registryOf, - rotateBuckets, - startSidecars, -} from './registry.ts'; +import { craneDigest, imageName } from './registry.ts'; -const november = new Date('2026-11-06T12:00:00Z'); - -test('where :5000 answers already, nothing is started and no key is needed', async () => { - const commands: string[] = []; - const io = fakeIo({}, undefined, { - curl: (_cwd, args) => { - commands.push(`curl ${args.at(-1)}`); - return args.at(-1)?.includes(':5000/') ? '{}' : undefined; - }, - docker: () => { - commands.push('docker'); - return ''; - }, - exo: () => { - commands.push('exo'); - return ''; - }, - }); - const sidecars = await startSidecars(new Context({}, io), undefined, 'acme', november); - assert.deepEqual(sidecars, { - current: 'acme-ci-registry-2026-w45', - previous: 'acme-ci-registry-2026-w44', - previousAnswers: false, - }); - assert.deepEqual(commands, ['curl http://127.0.0.1:5000/v2/', 'curl http://127.0.0.1:5001/v2/']); -}); - -test('where nothing answers, the key is needed', async () => { - const io = fakeIo({}, undefined, { curl: () => undefined }); - await assert.rejects( - startSidecars(new Context({}, io), undefined, 'acme', november), - /REGISTRY_ENDPOINT, REGISTRY_REGION, REGISTRY_ACCESS_KEY and REGISTRY_SECRET_KEY are needed/, - ); +test('an image name is the prefix, lower-cased, and the app', () => { + assert.equal(imageName('ghcr.io/Plexus-MS-Tenant/', 'website'), 'ghcr.io/plexus-ms-tenant/website'); }); -test('the image name is the lower-cased prefix and the app', () => { - assert.equal(imageName('ghcr.io/Acme/', 'website'), 'ghcr.io/acme/website'); -}); - -test('a candidate is written to this week’s sidecar, or to the forge’s registry', () => { - assert.equal(candidateRef(registryOf('own', ''), 'website', 'build-0f2a'), 'localhost:5000/website:build-0f2a'); - assert.equal( - candidateRef(registryOf('ghcr', 'ghcr.io/Plexus-MS-Tenant'), 'website', 'build-0f2a'), - 'ghcr.io/plexus-ms-tenant/website:build-0f2a', - ); -}); - -test('findTag answers with the ref that holds the tag: either sidecar, or the forge’s registry through crane', async () => { - const previous = fakeIo({}, undefined, { - curl: (_cwd, args) => (args.at(-1)?.includes(':5001/') ? '' : notThere('curl')), - }); - assert.equal( - await findTag(new Context({}, previous), { kind: 'own' }, 'website', 'build-x'), - 'localhost:5001/website:build-x', - ); - const ghcr = fakeIo({}, undefined, { - crane: (_cwd, args) => (args[1]?.endsWith(':build-x') ? 'sha256:a' : notThere('crane')), +test('craneDigest answers the digest, or undefined where the registry holds no such manifest', async () => { + const io = fakeIo({}, undefined, { + crane: (_cwd, args) => (args[1]?.endsWith(':build-x') ? 'sha256:a\n' : notThere('crane')), }); - const registry = { kind: 'ghcr', prefix: 'ghcr.io/o' } as const; - assert.equal(await findTag(new Context({}, ghcr), registry, 'website', 'build-x'), 'ghcr.io/o/website:build-x'); - assert.equal(await findTag(new Context({}, ghcr), registry, 'website', 'build-y'), undefined); + assert.equal(await craneDigest(new Context({}, io), 'ghcr.io/o/website:build-x'), 'sha256:a'); + assert.equal(await craneDigest(new Context({}, io), 'ghcr.io/o/website:build-y'), undefined); }); test('crane that cannot run is an error, never a missing tag', async () => { @@ -83,13 +22,10 @@ test('crane that cannot run is an error, never a missing tag', async () => { throw Object.assign(new Error('spawn crane ENOENT'), { code: 'ENOENT' }); }, }); - const registry = { kind: 'ghcr', prefix: 'ghcr.io/o' } as const; - await assert.rejects(findTag(new Context({}, missing), registry, 'website', 'build-x'), /crane could not run/); - await assert.rejects(layersOf(new Context({}, missing), registry, 'website', 'build-x'), /crane could not run/); + await assert.rejects(craneDigest(new Context({}, missing), 'ghcr.io/o/website:build-x'), /crane could not run/); }); -test('only the registry’s “not there” is a missing tag; a refused login or a silent sidecar is an error', async () => { - const ghcr = { kind: 'ghcr', prefix: 'ghcr.io/o' } as const; +test('only the registry’s “not there” is a missing tag; a refused login is an error', async () => { const refused = fakeIo({}, undefined, { crane: () => { throw new ExecError( @@ -100,27 +36,9 @@ test('only the registry’s “not there” is a missing tag; a refused login or }, }); await assert.rejects( - findTag(new Context({}, refused), ghcr, 'website', 'build-x'), + craneDigest(new Context({}, refused), 'ghcr.io/o/website:build-x'), /could not look up ghcr.io\/o\/website:build-x: .*UNAUTHORIZED/s, ); - - const down = (port: string) => - fakeIo({}, undefined, { - curl: (_cwd, args) => { - if (args.at(-1)?.includes(`:${port}/`)) throw new ExecError('curl', 7, 'curl: (7) Failed to connect\n'); - return notThere('curl'); - }, - }); - await assert.rejects( - findTag(new Context({}, down('5000')), { kind: 'own' }, 'website', 'build-x'), - /could not look up localhost:5000\/website:build-x/, - ); - await assert.rejects( - digestOf(new Context({}, down('5000')), { kind: 'own' }, 'website', 'build-x'), - /Failed to connect/, - ); - // Last week's sidecar is optional: its silence is absence. - assert.equal(await findTag(new Context({}, down('5001')), { kind: 'own' }, 'website', 'build-x'), undefined); }); test('under --dry-run a look-up that cannot be made is taken for absent, and said', async () => { @@ -128,90 +46,11 @@ test('under --dry-run a look-up that cannot be made is taken for absent, and sai crane: () => { throw Object.assign(new Error('spawn crane ENOENT'), { code: 'ENOENT' }); }, - curl: () => { - throw new ExecError('curl', 7, 'curl: (7) Failed to connect\n'); - }, }); let said = ''; io.stderr.on('data', (chunk: Buffer) => { said += chunk; }); - const dry = new Context({ dryRun: true }, io); - assert.equal(await findTag(dry, { kind: 'ghcr', prefix: 'ghcr.io/o' }, 'website', 'build-x'), undefined); - assert.equal(await findTag(dry, { kind: 'own' }, 'website', 'build-x'), undefined); + assert.equal(await craneDigest(new Context({ dryRun: true }, io), 'ghcr.io/o/website:build-x'), undefined); assert.match(said, /\[dry-run\] crane could not run to look up ghcr.io\/o\/website:build-x/); - assert.match(said, /\[dry-run\] could not look up localhost:5000\/website:build-x/); -}); - -test('a login is an entry for the host in the Docker config, or a credential store', async () => { - const env = { DOCKER_CONFIG: '/cfg' }; - const config = (data: unknown) => new Context({}, fakeIo({ cfg: { 'config.json': JSON.stringify(data) } })); - assert.equal(await loggedIn(config({ auths: { 'ghcr.io': { auth: 'x' } } }), 'ghcr.io', env), true); - assert.equal(await loggedIn(config({ credsStore: 'osxkeychain' }), 'ghcr.io', env), true); - assert.equal(await loggedIn(config({ auths: { 'docker.io': {} } }), 'ghcr.io', env), false); - assert.equal(await loggedIn(new Context({}, fakeIo({})), 'ghcr.io', env), false); -}); - -test('rotate creates this week’s bucket when it is missing and removes the one from two weeks ago, objects first', async () => { - const calls: string[] = []; - let objects = ['docker/registry/v2/a', 'docker/registry/v2/b&c']; - const io = fakeIo({}, undefined, { - curl: (_cwd, _args, input = '') => { - const url = (input.match(/url = "([^"]+)"/)?.[1] ?? '').replace('https://s3.example', ''); - const method = /^head$/m.test(input) ? 'HEAD' : (input.match(/request = "(\w+)"/)?.[1] ?? ''); - calls.push(`${method} ${url}`); - assert.match(input, /aws-sigv4 = "aws:amz:r1:s3"/); - assert.match(input, /user = "k:s"/); - // 2026-w45 is missing, 2026-w43 is still there. - if (method === 'HEAD') return url.endsWith('2026-w43') ? '\n200' : '\n404'; - if (method === 'GET' && url.includes('list-type=2')) { - const xml = `${objects.map((k) => `${k.replace('&', '&')}`).join('')}`; - return `${xml}\n200`; - } - if (method === 'POST') { - assert.match(input, /docker\/registry\/v2\/b&c<\/Key>/); - assert.match(input, /Content-MD5: /); - objects = []; - return '\n200'; - } - if (method === 'GET' && url.includes('uploads=')) - return 'docker/x yu1\n200'; - return method === 'DELETE' ? '\n204' : '\n200'; - }, - }); - const storage = { endpoint: 'https://s3.example/', region: 'r1', accessKey: 'k', secretKey: 's' }; - const result = await rotateBuckets(new Context({}, io), storage, 'acme', november); - assert.deepEqual(result, { created: 'acme-ci-registry-2026-w45', removed: 'acme-ci-registry-2026-w43' }); - assert.deepEqual(calls, [ - 'HEAD /acme-ci-registry-2026-w45', - 'PUT /acme-ci-registry-2026-w45', - 'HEAD /acme-ci-registry-2026-w43', - 'GET /acme-ci-registry-2026-w43?list-type=2&max-keys=1000', - 'POST /acme-ci-registry-2026-w43?delete=', - 'GET /acme-ci-registry-2026-w43?list-type=2&max-keys=1000', - 'GET /acme-ci-registry-2026-w43?uploads=', - 'DELETE /acme-ci-registry-2026-w43/docker/x%20y?uploadId=u1', - 'DELETE /acme-ci-registry-2026-w43', - ]); -}); - -test('a dry run of rotate lists once and deletes nothing; an answer outside 2xx is an error', async () => { - const calls: string[] = []; - const io = (status: string) => - fakeIo({}, undefined, { - curl: (_cwd, _args, input = '') => { - const method = /^head$/m.test(input) ? 'HEAD' : (input.match(/request = "(\w+)"/)?.[1] ?? ''); - calls.push(method); - if (method === 'HEAD') return '\n200'; - if (method === 'GET') return 'a\n200'; - return `no\n${status}`; - }, - }); - const storage = { endpoint: 'https://s3.example', region: 'r1', accessKey: 'k', secretKey: 's' }; - await rotateBuckets(new Context({ dryRun: true }, io('200')), storage, 'acme', november); - assert.deepEqual(calls, ['HEAD', 'HEAD', 'GET']); - await assert.rejects( - rotateBuckets(new Context({}, io('403')), storage, 'acme', november), - /deleting 1 objects of acme-ci-registry-2026-w43 answered 403/, - ); }); diff --git a/packages/cli-ci/src/core/strategy.test.ts b/packages/cli-ci/src/core/strategy.test.ts index 24b8e6de..9443666f 100644 --- a/packages/cli-ci/src/core/strategy.test.ts +++ b/packages/cli-ci/src/core/strategy.test.ts @@ -2,12 +2,10 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { runnerOf, settingsOf } from './strategy.ts'; -test('the settings default to the forge’s runners and registry, and the registry follows the strategy', () => { - assert.deepEqual(settingsOf({}), { strategy: 'github', registry: 'ghcr', overlay: 'none' }); - assert.deepEqual(settingsOf({ CI_STRATEGY: 'hybrid' }), { strategy: 'hybrid', registry: 'own', overlay: 'none' }); - assert.deepEqual(settingsOf({ CI_STRATEGY: 'on-prem', CI_REGISTRY: 'ghcr', CI_OVERLAY: 'netbird' }), { +test('the settings default to the forge’s runners and no overlay', () => { + assert.deepEqual(settingsOf({}), { strategy: 'github', overlay: 'none' }); + assert.deepEqual(settingsOf({ CI_STRATEGY: 'on-prem', CI_OVERLAY: 'netbird' }), { strategy: 'on-prem', - registry: 'ghcr', overlay: 'netbird', }); assert.equal(settingsOf({ CI_STRATEGY: 'hybrid' }, 'github').strategy, 'github'); @@ -18,7 +16,6 @@ test('an answer outside its set is a usage error that names the set', () => { () => settingsOf({ CI_STRATEGY: 'cloud' }), /the strategy is "cloud"; it is one of github, on-prem, hybrid/, ); - assert.throws(() => settingsOf({ CI_REGISTRY: 'dockerhub' }), /CI_REGISTRY is "dockerhub"/); assert.throws(() => settingsOf({ CI_OVERLAY: 'tailscale' }), /CI_OVERLAY is "tailscale"/); }); diff --git a/packages/cli-ci/src/core/time.test.ts b/packages/cli-ci/src/core/time.test.ts index 62eb4823..1e23ab64 100644 --- a/packages/cli-ci/src/core/time.test.ts +++ b/packages/cli-ci/src/core/time.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { deadline, iso, registryBuckets, turboBucket, week } from './time.ts'; +import { deadline, iso } from './time.ts'; const now = new Date('2026-11-04T10:40:27.123Z'); @@ -12,27 +12,3 @@ test('a deadline is minutes from now, in UTC', () => { assert.equal(deadline(now, 5), '2026-11-04T10:45:27Z'); assert.equal(deadline(now, 30), '2026-11-04T11:10:27Z'); }); - -test('weeks are ISO weeks in UTC and roll over the year', () => { - assert.equal(week(now), '2026-w45'); - assert.equal(week(now, -1), '2026-w44'); - // Monday starts a week, Sunday ends it. - assert.equal(week(new Date('2026-11-08T23:59:59Z')), '2026-w45'); - assert.equal(week(new Date('2026-11-09T00:00:00Z')), '2026-w46'); - // A week belongs to the year of its Thursday: 2026 has 53 weeks, 2025 ends in the first week of 2026. - assert.equal(week(new Date('2027-01-03T12:00:00Z')), '2026-w53'); - assert.equal(week(new Date('2027-01-04T12:00:00Z')), '2027-w01'); - assert.equal(week(new Date('2027-01-04T12:00:00Z'), -1), '2026-w53'); - assert.equal(week(new Date('2027-01-04T12:00:00Z'), -2), '2026-w52'); - assert.equal(week(new Date('2025-12-29T00:00:00Z')), '2026-w01'); - assert.equal(week(new Date('2026-01-01T00:00:00Z'), -1), '2025-w52'); -}); - -test('the bucket names follow the convention', () => { - assert.deepEqual(registryBuckets('acme', now), { - current: 'acme-ci-registry-2026-w45', - previous: 'acme-ci-registry-2026-w44', - expired: 'acme-ci-registry-2026-w43', - }); - assert.equal(turboBucket('acme'), 'acme-ci-turbo'); -}); diff --git a/packages/cli-ci/src/core/userData.test.ts b/packages/cli-ci/src/core/userData.test.ts index f944969b..d6bebb3b 100644 --- a/packages/cli-ci/src/core/userData.test.ts +++ b/packages/cli-ci/src/core/userData.test.ts @@ -75,7 +75,6 @@ test('the instance gives the job no Docker daemon: no runner on the host, no bui ); }); -test('the registry pair still answers on the host’s loopback, which the job’s container shares', () => { - assert.match(RUNNER_USER_DATA, /-p 127\.0\.0\.1:5000:5000 /); - assert.match(RUNNER_USER_DATA, /-p 127\.0\.0\.1:5001:5000 /); +test('the instance starts no registry and holds no storage key beside its own', () => { + assert.doesNotMatch(RUNNER_USER_DATA, /registry|REGISTRY|:500[01]/); }); diff --git a/packages/cli-ci/src/program.test.ts b/packages/cli-ci/src/program.test.ts index 642afbb3..272e187b 100644 --- a/packages/cli-ci/src/program.test.ts +++ b/packages/cli-ci/src/program.test.ts @@ -35,8 +35,8 @@ test('help lists the global options', () => { test('the universal commands take --strategy, and hybrid holds the instances’ three', () => { const program = buildProgram(); const names = program.commands.map((c) => c.name()); - assert.deepEqual(names, ['registry', 'plan', 'publish', 'display-versions', 'tag-display-version', 'hybrid']); - for (const name of ['registry', 'plan']) { + assert.deepEqual(names, ['plan', 'publish', 'display-versions', 'tag-display-version', 'hybrid']); + for (const name of ['plan']) { const command = program.commands.find((c) => c.name() === name); assert.ok( command?.options.some((o) => o.long === '--strategy'), diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index 297edc70..c361dc3a 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { test } from 'node:test'; -import { REGULAR, render, type Tree as Template } from '@plexus-ms/cli-template'; +import { REGULAR, readTree, render, type Tree as Template } from '@plexus-ms/cli-template'; import { type Compose, type Mapping, parseCompose } from './compose.ts'; import { Context } from './context.ts'; import { type AppFacts, CHECKS, diagnose, examine, type Facts, type RepoFacts } from './doctor.ts'; @@ -12,6 +12,7 @@ import { unitsOf } from './model.ts'; import { overview } from './overview.ts'; import type { MarkerSite } from './sites.ts'; import type { Bundled } from './siteTemplates.ts'; +import { templatesRoot } from './templatesRoot.ts'; import { type FakeExec, fakeIo, link, type Tree, UNREADABLE } from './testing/fakeIo.ts'; import { UsageError } from './version.ts'; @@ -1495,6 +1496,22 @@ test('every key of the markers is checked, each finding naming its marker', () = ]); }); +test('a marker that still holds ci_registry, a question no template asks any more, is an unknown key', async () => { + const names = ['repo-turbo', 'repo-operations']; + const real: Bundled = { + trees: new Map(await Promise.all(names.map(async (n) => [n, await readTree(join(templatesRoot(), n))] as const))), + render, + }; + for (const name of names) { + const root = site('.', { + version: '0.131.0', + templates: [name], + answers: { tenant: 'acme', ci_strategy: 'github', ci_registry: 'own' }, + }); + assert.deepEqual(findings(crossed([root], { templates: real })), [{ problem: UNKNOWN_ROOT('ci_registry') }], name); + } +}); + test('the root marker may hold answers that a template of a nested site owns or reads', () => { const root = site('.', { version: '0.131.0', diff --git a/packages/lib/src/newSite.test.ts b/packages/lib/src/newSite.test.ts index 875f590a..70647b60 100644 --- a/packages/lib/src/newSite.test.ts +++ b/packages/lib/src/newSite.test.ts @@ -323,7 +323,6 @@ test('a repo from repo-turbo with updates beside it and an app from app-nextjs i assert.equal(repo.kind, 'repo'); assert.deepEqual(repo.files, [ '.dockerignore', - '.github/workflows/housekeeping.yml', '.github/workflows/on_commit.yml', '.github/workflows/on_pr.yml', '.github/workflows/on_push.yml', diff --git a/packages/lib/src/repoOperations.test.ts b/packages/lib/src/repoOperations.test.ts index c0c2e21d..70172077 100644 --- a/packages/lib/src/repoOperations.test.ts +++ b/packages/lib/src/repoOperations.test.ts @@ -43,17 +43,28 @@ test('an infrastructure layer adds its playbook', async () => { assert.match(textOf(result, 'inventory/hosts.yml'), /^proxmox:$/m); }); -test('runners of the tenant’s own add the CI playbook and its housekeeping', async () => { - for (const ci_strategy of ['on-prem', 'hybrid']) { - const result = await render({ ci_strategy }); - assert.deepEqual(result.errors, []); - assert.deepEqual(pathsOf(result), [...COMMON, '.github/workflows/housekeeping.yml', 'ci.yml'].sort(), ci_strategy); +test('runners of the tenant’s own add the CI playbook, and a hybrid strategy its instance sweep', async () => { + const onPrem = await render({ ci_strategy: 'on-prem' }); + assert.deepEqual(onPrem.errors, []); + assert.deepEqual(pathsOf(onPrem), [...COMMON, 'ci.yml'].sort()); + const hybrid = await render({ ci_strategy: 'hybrid' }); + assert.deepEqual(hybrid.errors, []); + assert.deepEqual(pathsOf(hybrid), [...COMMON, '.github/workflows/housekeeping.yml', 'ci.yml'].sort()); +}); + +test('the housekeeping mount sweeps instances and holds nothing of the registry pair or its question', async () => { + for (const ci_strategy of ['github', 'on-prem', 'hybrid'] as const) { + const result = await render({ ci_strategy, alerts_email: 'ops@acme.example' }); + for (const path of pathsOf(result)) + assert.doesNotMatch( + textOf(result, path), + /ci_registry|CI_REGISTRY|plx-ci registry|registry rotate|bucket-registry|:500[01]\b|registry buckets/, + `${path} ${ci_strategy}`, + ); } -}); - -test('a registry of its own adds the housekeeping alone', async () => { - const result = await render({ ci_registry: 'own' }); - assert.deepEqual(pathsOf(result), [...COMMON, '.github/workflows/housekeeping.yml'].sort()); + const text = textOf(await render({ ci_strategy: 'hybrid' }), '.github/workflows/housekeeping.yml'); + assert.doesNotMatch(text, /registry:/); + assert.match(text, /alerts-email: /); }); test('the answers are the questions’ defaults, and the org follows the tenant', async () => { @@ -62,12 +73,10 @@ test('the answers are the questions’ defaults, and the org follows the tenant' github_org: 'acme', infrastructure: false, ci_strategy: 'github', - ci_registry: 'ghcr', ci_overlay: 'none', }); const hybrid = await render({ ci_strategy: 'hybrid', github_org: 'acme-gh', alerts_email: 'ops@acme.example' }); assert.equal(hybrid.answers.github_org, 'acme-gh'); - assert.equal(hybrid.answers.ci_registry, 'own'); assert.equal(hybrid.answers.alerts_email, 'ops@acme.example'); }); @@ -82,7 +91,7 @@ test('the tenant is required, and the error carries its help', async () => { }); test('only a choice of the question is an answer', async () => { - for (const answers of [{ ci_strategy: 'cloud' }, { ci_overlay: 'wireguard' }, { ci_registry: 'docker' }]) { + for (const answers of [{ ci_strategy: 'cloud' }, { ci_overlay: 'wireguard' }]) { assert.equal((await render(answers)).errors.length, 1); } }); @@ -141,12 +150,7 @@ test('a generated file says its template lives in tooling', async () => { // --- the five verbs and the hooks (as repo-turbo has them) -------------------------------- -const SHAPES = [ - {}, - { infrastructure: true, ci_strategy: 'hybrid' }, - { ci_strategy: 'on-prem', ci_overlay: 'netbird' }, - { ci_registry: 'own' }, -]; +const SHAPES = [{}, { infrastructure: true, ci_strategy: 'hybrid' }, { ci_strategy: 'on-prem', ci_overlay: 'netbird' }]; test('a repo has the five verbs as root tasks, each taking an optional name, and no verify', async () => { for (const answers of SHAPES) { diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index 427aee16..925e57b7 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -34,13 +34,7 @@ test('an app repo is rendered with its apps directory and its commit workflows', assert.deepEqual(result.errors, []); assert.deepEqual( pathsOf(result), - [ - ...COMMON, - '.dockerignore', - '.github/workflows/housekeeping.yml', - '.github/workflows/on_commit.yml', - 'apps/.gitkeep', - ].sort(), + [...COMMON, '.dockerignore', '.github/workflows/on_commit.yml', 'apps/.gitkeep'].sort(), ); }); @@ -50,14 +44,19 @@ test('a package repo has changesets instead of apps and the commit workflows', a assert.deepEqual(pathsOf(result), [...COMMON, '.changeset/config.json'].sort()); }); -test('the housekeeping workflow follows the registry, which follows the strategy', async () => { - const github = await render({ ci_strategy: 'github' }); - assert.equal(github.answers.ci_registry, 'ghcr'); - assert.ok(github.files.has('.github/workflows/housekeeping.yml')); - const hybrid = await render({ ci_strategy: 'hybrid', alerts_email: 'ops@acme.example' }); - assert.equal(hybrid.answers.ci_registry, 'own'); - assert.equal(hybrid.answers.alerts_email, 'ops@acme.example'); - assert.ok(!hybrid.files.has('.github/workflows/housekeeping.yml')); +test('no repo, in any shape, holds a housekeeping workflow or anything of the registry pair and its question', async () => { + for (const ci_strategy of ['github', 'on-prem', 'hybrid']) + for (const publishes_packages of [false, true]) { + const result = await render({ ci_strategy, publishes_packages }); + const shape = `${ci_strategy} ${publishes_packages}`; + assert.ok(!result.files.has('.github/workflows/housekeeping.yml'), shape); + for (const path of pathsOf(result)) + assert.doesNotMatch( + textOf(result, path), + /ci_registry|CI_REGISTRY|plx-ci registry|registry rotate|bucket-registry|:500[01]\b|test-|--cache-(from|to)/, + `${path} ${shape}`, + ); + } }); test('the answers of a plain app repo are the questions’ defaults', async () => { @@ -67,17 +66,15 @@ test('the answers of a plain app repo are the questions’ defaults', async () = publishes_packages: false, private_packages_scope: '', ci_strategy: 'github', - ci_registry: 'ghcr', ci_overlay: 'none', display_versions: false, postgres: '', }); }); -test('a package repo is asked where it publishes and nothing about CI registries', async () => { +test('a package repo is asked where it publishes', async () => { const result = await render({ publishes_packages: true }); assert.equal(result.answers.package_registry, 'npm'); - assert.ok(!('ci_registry' in result.answers)); assert.ok(!('display_versions' in result.answers)); const github = await render({ publishes_packages: true, package_registry: 'github' }); assert.match(textOf(github, 'PLEXUS.md'), /the forge's package registry, private to the tenant,/); @@ -116,7 +113,7 @@ test('the major of a display version is 1 or higher', async () => { }); test('only a choice of the question is an answer', async () => { - for (const answers of [{ ci_strategy: 'cloud' }, { ci_overlay: 'wireguard' }, { ci_registry: 'docker' }]) { + for (const answers of [{ ci_strategy: 'cloud' }, { ci_overlay: 'wireguard' }]) { assert.equal((await render(answers)).errors.length, 1); } }); diff --git a/packages/lib/src/repoTurboCache.test.ts b/packages/lib/src/repoTurboCache.test.ts index 0a8fbfc8..079e4e76 100644 --- a/packages/lib/src/repoTurboCache.test.ts +++ b/packages/lib/src/repoTurboCache.test.ts @@ -344,19 +344,12 @@ test('a checkout without origin, or whose origin names no owner, has no team, an const jobOf = (workflow: string, name: string): string => new RegExp(`^ ${name}:\\n([\\s\\S]*?)(?=^ [\\w-]+:\\n|(?![\\s\\S]))`, 'm').exec(workflow)?.[1] ?? ''; -test('no workflow of a repo asks for the cache, and the answer ci_registry changes nothing of the test job', async () => { +test('no workflow of a repo asks for the cache', async () => { for (const ci_strategy of ['github', 'on-prem', 'hybrid']) for (const answers of SHAPES) { - const results = await Promise.all( - ['ghcr', 'own'].map((ci_registry) => render({ ...answers, ci_strategy, ci_registry })), - ); - for (const result of results) - for (const path of pathsOf(result).filter((p) => p.startsWith('.github/workflows/'))) - assert.doesNotMatch(textOf(result, path), /turbo-cache/, path); - const [ghcr, own] = results; - if (!ghcr || !own) throw new Error('two renders'); - for (const path of pathsOf(ghcr).filter((p) => p.startsWith('.github/workflows/on_'))) - assert.equal(jobOf(textOf(ghcr, path), 'test'), jobOf(textOf(own, path), 'test'), `${path} ${ci_strategy}`); + const result = await render({ ...answers, ci_strategy }); + for (const path of pathsOf(result).filter((p) => p.startsWith('.github/workflows/'))) + assert.doesNotMatch(textOf(result, path), /turbo-cache/, path); } }); diff --git a/packages/lib/src/testing/shapes.ts b/packages/lib/src/testing/shapes.ts index 8090d8b2..26787c8c 100644 --- a/packages/lib/src/testing/shapes.ts +++ b/packages/lib/src/testing/shapes.ts @@ -16,7 +16,6 @@ export const CHOICES: Readonly package_registry: ['npm', 'github'], private_packages_scope: ['', '@acme'], ci_strategy: ['github', 'on-prem', 'hybrid'], - ci_registry: ['ghcr', 'own'], ci_overlay: ['none', 'netbird'], alerts_email: ['', 'ops@acme.example'], display_versions: [false, true], @@ -30,7 +29,6 @@ export const CHOICES: Readonly github_org: ['acme', 'acme-gh'], infrastructure: [false, true], ci_strategy: ['github', 'on-prem', 'hybrid'], - ci_registry: ['ghcr', 'own'], ci_overlay: ['none', 'netbird'], alerts_email: ['', 'ops@acme.example'], pr_reviewers: ['', 'alice', 'alice, bob'], From d5cf8755074693f5dd9d1268119df28b5199228e Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 23:58:22 +0100 Subject: [PATCH 154/194] plx-ci drops the candidate registry: its command, its storage client, its prune, and what an instance starts for it Removes plx-ci registry (start, exists, rotate), core/s3.ts, core/ghcr.ts, the registry pair's sidecars, buckets and week names, the CI_REGISTRY setting, and the REGISTRY_* the hybrid launch handed to an instance, with the two lines of the instance's user-data that started the pair. registry.ts keeps craneDigest and imageName, which plan and publish use. The teardown layers are untouched. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/package.json | 2 +- packages/cli-ci/src/commands/hybrid.ts | 12 +- packages/cli-ci/src/commands/index.ts | 3 +- packages/cli-ci/src/commands/registry.ts | 91 ----- packages/cli-ci/src/commands/shared.ts | 10 +- .../cli-ci/src/core/createInstances.test.ts | 2 +- packages/cli-ci/src/core/createInstances.ts | 16 +- .../cli-ci/src/core/displayVersions.test.ts | 2 +- packages/cli-ci/src/core/ghcr.test.ts | 78 ----- packages/cli-ci/src/core/ghcr.ts | 122 ------- packages/cli-ci/src/core/plan.test.ts | 2 +- packages/cli-ci/src/core/publish.test.ts | 2 +- packages/cli-ci/src/core/registry.test.ts | 2 +- packages/cli-ci/src/core/registry.ts | 320 +----------------- packages/cli-ci/src/core/s3.ts | 164 --------- packages/cli-ci/src/core/strategy.ts | 24 +- packages/cli-ci/src/core/time.ts | 26 +- packages/cli-ci/src/core/userData.ts | 20 +- packages/cli-ci/src/testing/fakeIo.ts | 12 +- packages/lib/src/io.ts | 2 +- ...brid' %}housekeeping.yml{% endif %}.jinja} | 0 ...'ghcr' %}housekeeping.yml{% endif %}.jinja | 28 -- 22 files changed, 51 insertions(+), 889 deletions(-) delete mode 100644 packages/cli-ci/src/commands/registry.ts delete mode 100644 packages/cli-ci/src/core/ghcr.test.ts delete mode 100644 packages/cli-ci/src/core/ghcr.ts delete mode 100644 packages/cli-ci/src/core/s3.ts rename templates/repo-operations/files/.github/workflows/{{% if ci_strategy == 'hybrid' or ci_registry == 'own' %}housekeeping.yml{% endif %}.jinja => {% if ci_strategy == 'hybrid' %}housekeeping.yml{% endif %}.jinja} (100%) delete mode 100644 templates/repo-turbo/files/.github/workflows/{% if not publishes_packages and ci_registry == 'ghcr' %}housekeeping.yml{% endif %}.jinja diff --git a/packages/cli-ci/package.json b/packages/cli-ci/package.json index b7b7944b..1bcf858f 100644 --- a/packages/cli-ci/package.json +++ b/packages/cli-ci/package.json @@ -1,7 +1,7 @@ { "name": "@plexus-ms/cli-ci", "version": "0.133.0", - "description": "plx-ci, the CI verbs of Plexus: the plan of a run, the publish of an app's image, throwaway runners on a cloud and their teardown, and a registry on object storage", + "description": "plx-ci, the CI verbs of Plexus: the plan of a run, the publish of an app's image, throwaway runners on a cloud and their teardown", "license": "GPL-3.0-or-later", "type": "module", "bin": { diff --git a/packages/cli-ci/src/commands/hybrid.ts b/packages/cli-ci/src/commands/hybrid.ts index 4910e5df..917e4206 100644 --- a/packages/cli-ci/src/commands/hybrid.ts +++ b/packages/cli-ci/src/commands/hybrid.ts @@ -6,11 +6,11 @@ // one that misses is kept, stopped and mailed about, and replaced once. From // the environment: GITHUB_REPOSITORY, GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT; // RUNNER_TOKEN (Administration: write on the repo); EXOSCALE_API_KEY/_SECRET -// (ci-launch); SELF_DELETE_KEY/_SECRET; SELF_LAYERS; SMTP_* and MAIL_*, -// REGISTRY_* (optional); NO_JOB_MINUTES, DEATH_MINUTES, POWEROFF_MINUTES; -// INSTANCE_TYPE, ZONE, ONLINE_SECONDS; RUNNER_IMAGE, the environment image the -// runner runs in, by default the one of this plx-ci's version (a trial names -// an unreleased `…:sha-` from runner-image.yml). +// (ci-launch); SELF_DELETE_KEY/_SECRET; SELF_LAYERS; SMTP_* and MAIL_* +// (optional); NO_JOB_MINUTES, DEATH_MINUTES, POWEROFF_MINUTES; INSTANCE_TYPE, +// ZONE, ONLINE_SECONDS; RUNNER_IMAGE, the environment image the runner runs in, +// by default the one of this plx-ci's version (a trial names an unreleased +// `…:sha-` from runner-image.yml). // // destroy-instances: the run's cleanup, delete what this run and attempt // created and the registrations nothing used; kept instances are left alone. @@ -30,7 +30,6 @@ import { createInstances, DEFAULTS, type InstanceLeg, type LaunchOptions } from import { destroyInstances } from '../core/destroyInstances.ts'; import { smtpFromEnv } from '../core/mail.ts'; import type { Leg } from '../core/plan.ts'; -import { storageFromEnv } from '../core/registry.ts'; import { sweepInstances } from '../core/sweepInstances.ts'; import { contextOf, version } from '../program.ts'; import { exoOf, githubOf, need, runIdentity, zoneOf } from './shared.ts'; @@ -49,7 +48,6 @@ export function launchOptionsFromEnv(env: NodeJS.ProcessEnv = process.env): Omit poweroffMinutes: minutes('POWEROFF_MINUTES'), }, smtp: smtpFromEnv(env), - registry: storageFromEnv(env), zone: zoneOf(env), instanceType: env.INSTANCE_TYPE || DEFAULTS.instanceType, template: env.TEMPLATE || DEFAULTS.template, diff --git a/packages/cli-ci/src/commands/index.ts b/packages/cli-ci/src/commands/index.ts index 082f083d..b79524b9 100644 --- a/packages/cli-ci/src/commands/index.ts +++ b/packages/cli-ci/src/commands/index.ts @@ -9,6 +9,5 @@ import { register as displayVersions } from './displayVersions.ts'; import { register as hybrid } from './hybrid.ts'; import { register as plan } from './plan.ts'; import { register as publish } from './publish.ts'; -import { register as registry } from './registry.ts'; -export const commands: ((program: Command) => void)[] = [registry, plan, publish, displayVersions, hybrid]; +export const commands: ((program: Command) => void)[] = [plan, publish, displayVersions, hybrid]; diff --git a/packages/cli-ci/src/commands/registry.ts b/packages/cli-ci/src/commands/registry.ts deleted file mode 100644 index 73746661..00000000 --- a/packages/cli-ci/src/commands/registry.ts +++ /dev/null @@ -1,91 +0,0 @@ -// plx-ci registry: make sure this machine reaches the registry the run's -// candidates live in (§ 8 PLX-Delivery). With a registry of the tenant's own -// (CI_REGISTRY=own), that is the pair on localhost: nothing where :5000 -// answers already (a slot of a runner host), else the two sidecars are -// started, creating this week's bucket when it is missing. With the forge's -// registry (CI_REGISTRY=ghcr) it is a check that the job has logged in. -// `exists` asks whether a tag is there; `rotate` is the retention, run daily. -// From the environment: CI_STRATEGY, CI_REGISTRY; for the pair -// REGISTRY_ENDPOINT, REGISTRY_REGION, REGISTRY_ACCESS_KEY, REGISTRY_SECRET_KEY -// (the vault item bucket-registry: any S3-compatible store), GITHUB_REPOSITORY -// (the owner names the buckets); for `rotate` under ghcr, GITHUB_TOKEN (the workflow's own, -// with packages: write), which deletes versions of the packages its repo -// published: the repo's apps, or the ones named. -// -// plx-ci registry -// plx-ci registry exists website build-0f2a3f35123dfd73 # exit 0 when it is, 1 otherwise -// plx-ci registry rotate # the buckets, or the repo's apps in ghcr -// plx-ci -n registry rotate # what would go - -import { resolve } from 'node:path'; -import type { Command } from 'commander'; -import { Packages, packageOf, prune } from '../core/ghcr.ts'; -import { findTag, loggedIn, rotateBuckets, startSidecars, storageFromEnv } from '../core/registry.ts'; -import { contextOf } from '../program.ts'; -import { imagePrefix, need, ownerOf, registryFor, settings, withStrategy } from './shared.ts'; - -export function register(program: Command): void { - const registry = withStrategy(program.command('registry')) - .description( - 'make the candidates’ registry reachable here: the pair on localhost (started unless :5000 answers), or a login check for the forge’s', - ) - .action(async (opts: { strategy?: string }, command: Command) => { - const ctx = contextOf(command); - const s = settings(opts); - if (s.registry === 'ghcr') { - const host = imagePrefix().split('/')[0] ?? 'ghcr.io'; - if (!(await loggedIn(ctx, host)) && !ctx.dryRun) - throw new Error(`no login for ${host} here; the job logs in before it asks for the registry`); - ctx.result(`registry: ${imagePrefix()}, logged in`); - return; - } - const result = await startSidecars(ctx, storageFromEnv(), ownerOf(need('GITHUB_REPOSITORY'))); - ctx.result( - result, - (r) => `:5000 ${r.current}\n:5001 ${r.previous}${r.previousAnswers ? '' : ' (not answering)'}`, - ); - }); - withStrategy(registry.command('exists')) - .description('exit 0 when the registry holds the tag') - .argument('') - .argument('') - .action(async (app: string, tag: string, opts: { strategy?: string }, command: Command) => { - const ctx = contextOf(command); - const ref = await findTag(ctx, registryFor(settings(opts)), app, tag); - if (ref === undefined) { - ctx.say(`${app}:${tag} is in no registry here`); - process.exitCode = 1; - } else ctx.result(ref); - }); - withStrategy(registry.command('rotate')) - .description( - 'the retention: this week’s bucket exists and the one from two weeks ago goes; in the forge’s registry, candidates older than thirty days go', - ) - .argument('[apps...]', 'under ghcr: the apps whose packages are pruned (default: every directory under apps/)') - .option('-C, --dir ', 'the checkout to read', '.') - .action(async (apps: string[], opts: { strategy?: string; dir: string }, command: Command) => { - const ctx = contextOf(command); - const s = settings(opts); - const owner = ownerOf(need('GITHUB_REPOSITORY')); - if (s.registry === 'ghcr') { - const all = - apps.length > 0 - ? apps - : (await ctx.readDir(`${resolve(opts.dir)}/apps`)) - .filter((e) => e.directory) - .map((e) => e.name) - .sort(); - const names = all.map((app) => packageOf(imagePrefix(), app)); - const result = await prune(ctx, new Packages(ctx, owner, need('GITHUB_TOKEN')), names); - ctx.result(result, (r) => r.map((v) => `${v.package} ${v.tags.join(' ')}`).join('\n')); - return; - } - const storage = storageFromEnv(); - if (!storage) - throw new Error('REGISTRY_ENDPOINT, REGISTRY_REGION, REGISTRY_ACCESS_KEY and REGISTRY_SECRET_KEY are needed'); - const result = await rotateBuckets(ctx, storage, owner); - ctx.result(result, (r) => - [...(r.created ? [`created ${r.created}`] : []), ...(r.removed ? [`removed ${r.removed}`] : [])].join('\n'), - ); - }); -} diff --git a/packages/cli-ci/src/commands/shared.ts b/packages/cli-ci/src/commands/shared.ts index 8f0dbf1d..e753fba6 100644 --- a/packages/cli-ci/src/commands/shared.ts +++ b/packages/cli-ci/src/commands/shared.ts @@ -8,7 +8,6 @@ import type { Command } from 'commander'; import type { RunIdentity } from '../core/destroyInstances.ts'; import { Exo } from '../core/exoscale.ts'; import { GitHubRunners } from '../core/github.ts'; -import { type Registry, registryOf } from '../core/registry.ts'; import { type Settings, settingsOf } from '../core/strategy.ts'; export function need(name: string, env: NodeJS.ProcessEnv = process.env): string { @@ -34,7 +33,7 @@ export function githubOf(ctx: Context, env: NodeJS.ProcessEnv = process.env): Gi return env.RUNNER_TOKEN ? new GitHubRunners(ctx, need('GITHUB_REPOSITORY', env), env.RUNNER_TOKEN) : undefined; } -/** The owner of the repo, the prefix of the bucket names. */ +/** The owner of the repo, the default prefix of the image names. */ export const ownerOf = (repo: string): string => repo.split('/')[0] ?? repo; /** The option every universal command takes; the environment answers without it. */ @@ -42,7 +41,7 @@ export function withStrategy(command: Command): Command { return command.option('--strategy ', 'github, on-prem or hybrid (default: CI_STRATEGY, else github)'); } -/** The repo's three answers: --strategy before CI_STRATEGY, then CI_REGISTRY and CI_OVERLAY. */ +/** The repo's two answers: --strategy before CI_STRATEGY, then CI_OVERLAY. */ export function settings(opts: { strategy?: string }, env: NodeJS.ProcessEnv = process.env): Settings { return settingsOf(env, opts.strategy); } @@ -51,8 +50,3 @@ export function settings(opts: { strategy?: string }, env: NodeJS.ProcessEnv = p export function imagePrefix(env: NodeJS.ProcessEnv = process.env): string { return env.IMAGE_PREFIX || `ghcr.io/${ownerOf(need('GITHUB_REPOSITORY', env))}`; } - -/** Where the candidates live, from the settings. */ -export function registryFor(s: Settings, env: NodeJS.ProcessEnv = process.env): Registry { - return registryOf(s.registry, s.registry === 'ghcr' ? imagePrefix(env) : ''); -} diff --git a/packages/cli-ci/src/core/createInstances.test.ts b/packages/cli-ci/src/core/createInstances.test.ts index 1f1765e9..b58ea40c 100644 --- a/packages/cli-ci/src/core/createInstances.test.ts +++ b/packages/cli-ci/src/core/createInstances.test.ts @@ -39,7 +39,7 @@ const options: LaunchOptions = { }; test('the user-data is rendered with the run’s facts, and fits the API', () => { - const text = renderUserData(options, 'JIT', now); + const text = renderUserData(options, 'JIT'); assert.match(text, /^hostname: exo-large-41-website-1$/m); assert.doesNotMatch(text, /REGISTRY/); assert.match(text, /SELF_LAYERS=off/); diff --git a/packages/cli-ci/src/core/createInstances.ts b/packages/cli-ci/src/core/createInstances.ts index c70fa2d8..49e5ecfe 100644 --- a/packages/cli-ci/src/core/createInstances.ts +++ b/packages/cli-ci/src/core/createInstances.ts @@ -40,8 +40,7 @@ import { KEPT_LABEL, type RunIdentity, repoLabel } from './destroyInstances.ts'; import { type CreateInstance, type Exo, sleep } from './exoscale.ts'; import type { GitHubRunners } from './github.ts'; import { type Smtp, sendMail } from './mail.ts'; -import type { ObjectStorage } from './registry.ts'; -import { deadline, iso, registryBuckets } from './time.ts'; +import { deadline, iso } from './time.ts'; import { RUNNER_USER_DATA, render } from './userData.ts'; /** What a runner's user-data is told. */ @@ -61,7 +60,6 @@ export interface LaunchOptions { selfLayers: 'on' | 'off'; deadlines: Deadlines; smtp?: Smtp; - registry?: ObjectStorage; zone: string; instanceType: string; template: string; @@ -107,9 +105,7 @@ export interface Launch { } /** The runner's user-data for one launch, rendered: the values written as they are. */ -export function renderUserData(options: LaunchOptions, jitconfig: string, now: Date): string { - const owner = options.run.repo.split('/')[0] ?? options.run.repo; - const buckets = registryBuckets(owner, now); +export function renderUserData(options: LaunchOptions, jitconfig: string): string { return render(RUNNER_USER_DATA, { POWEROFF_MINUTES: String(options.deadlines.poweroffMinutes), NO_JOB_MINUTES: String(options.deadlines.noJobMinutes), @@ -130,12 +126,6 @@ export function renderUserData(options: LaunchOptions, jitconfig: string, now: D SMTP_PASSWORD: options.smtp?.password ?? '', MAIL_FROM: options.smtp?.from ?? '', MAIL_TO: options.smtp?.to ?? '', - REGISTRY_ENDPOINT: options.registry?.endpoint ?? '', - REGISTRY_REGION: options.registry?.region ?? '', - REGISTRY_BUCKET: buckets.current, - REGISTRY_PREVIOUS_BUCKET: buckets.previous, - REGISTRY_ACCESS_KEY: options.registry?.accessKey ?? '', - REGISTRY_SECRET_KEY: options.registry?.secretKey ?? '', }); } @@ -216,7 +206,7 @@ export async function launch(ctx: Context, exo: Exo, github: GitHubRunners, opti securityGroupId, sshKey: options.sshKey, diskSize: options.diskSize, - userDataBase64: encodeUserData(renderUserData(options, registration?.encodedJitConfig ?? '', t0)), + userDataBase64: encodeUserData(renderUserData(options, registration?.encodedJitConfig ?? '')), labels, }; const operation = await exo.createInstance(request); diff --git a/packages/cli-ci/src/core/displayVersions.test.ts b/packages/cli-ci/src/core/displayVersions.test.ts index 24ea4bae..5af66365 100644 --- a/packages/cli-ci/src/core/displayVersions.test.ts +++ b/packages/cli-ci/src/core/displayVersions.test.ts @@ -58,7 +58,7 @@ function repo(options: { const ref = args[1] ?? ''; crane.push(ref); const key = ref.replace('ghcr.io/acme/', ''); - return options.digests[key] ?? notThere('crane'); + return options.digests[key] ?? notThere(); }, curl: (_cwd, _args, input) => { options.curl?.push([input ?? '']); diff --git a/packages/cli-ci/src/core/ghcr.test.ts b/packages/cli-ci/src/core/ghcr.test.ts deleted file mode 100644 index f3273f43..00000000 --- a/packages/cli-ci/src/core/ghcr.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import assert from 'node:assert/strict'; -import { test } from 'node:test'; -import { Context, ExecError } from '@plexus-ms/lib'; -import { fakeIo, notThere } from '../testing/fakeIo.ts'; -import { Packages, packageOf, prunable, prune, type Version } from './ghcr.ts'; - -const now = new Date('2026-11-06T12:00:00Z'); -const old = '2026-09-30T12:00:00Z'; -const recent = '2026-10-20T12:00:00Z'; -const v = (id: number, createdAt: string, tags: string[]): Version => ({ id, createdAt, tags }); - -test('only a version older than thirty days whose every tag is a candidate’s goes', () => { - const versions = [ - v(1, old, ['build-0f2a']), - v(2, old, ['build-0f2a', 'test-5b05']), - v(3, old, ['build-0f2a', 'test-5b05', '8e51d0821a4c0d1f6b0a9d6e2f0c7d3b5a1e4f90']), - v(4, recent, ['build-c51b']), - v(5, old, []), - v(6, old, ['cache']), - v(7, old, ['build-0f2a', 'latest']), - v(8, old, ['build-notahash']), - ]; - assert.deepEqual( - prunable(versions, now).map((x) => x.id), - [1, 2], - ); -}); - -test('an app’s package is named by what follows the owner in the prefix, and the app', () => { - assert.equal(packageOf('ghcr.io/Acme', 'website'), 'website'); - assert.equal(packageOf('ghcr.io/acme/web/', 'app'), 'web/app'); -}); - -test('prune takes the named packages only, skips one that does not exist, and deletes by the rule; a dry run deletes nothing', async () => { - const calls: string[] = []; - const io = fakeIo({}, undefined, { - curl: (_cwd, _args, input = '') => { - const method = input.match(/request = "(\w+)"/)?.[1]; - const url = input.match(/url = "([^"]+)"/)?.[1] ?? ''; - calls.push(`${method} ${url.replace('https://api.github.com/orgs/acme/packages', '')}`); - assert.match(input, /Authorization: Bearer ghp_x/); - if (method === 'DELETE') return ''; - if (url.includes('/container/website/')) - return JSON.stringify([ - { id: 1, created_at: old, metadata: { container: { tags: ['build-0f2a'] } } }, - { id: 2, created_at: old, metadata: { container: { tags: ['build-aaaa', 'abc123'] } } }, - ]); - if (url.includes('/container/web%2Fapp/')) - return JSON.stringify([{ id: 3, created_at: recent, metadata: { container: { tags: ['test-5b05'] } } }]); - return notThere('curl'); - }, - }); - const ctx = new Context({}, io); - const names = ['website', 'never-built', 'web/app']; - const pruned = await prune(ctx, new Packages(ctx, 'acme', 'ghp_x'), names, now); - assert.deepEqual(pruned, [{ package: 'website', id: 1, tags: ['build-0f2a'] }]); - assert.deepEqual(calls, [ - 'GET /container/website/versions?per_page=100&page=1', - 'DELETE /container/website/versions/1', - 'GET /container/never-built/versions?per_page=100&page=1', - 'GET /container/web%2Fapp/versions?per_page=100&page=1', - ]); - - calls.length = 0; - const dry = new Context({ dryRun: true }, io); - assert.equal((await prune(dry, new Packages(dry, 'acme', 'ghp_x'), names, now)).length, 1); - assert.ok(!calls.some((c) => c.startsWith('DELETE'))); -}); - -test('a package API that refuses the token is an error, not a package that does not exist', async () => { - const io = fakeIo({}, undefined, { - curl: () => { - throw new ExecError('curl', 22, 'curl: (22) The requested URL returned error: 401\n'); - }, - }); - const ctx = new Context({}, io); - await assert.rejects(prune(ctx, new Packages(ctx, 'acme', 'ghp_x'), ['website'], now), /401/); -}); diff --git a/packages/cli-ci/src/core/ghcr.ts b/packages/cli-ci/src/core/ghcr.ts deleted file mode 100644 index 44d0feab..00000000 --- a/packages/cli-ci/src/core/ghcr.ts +++ /dev/null @@ -1,122 +0,0 @@ -// The candidates a repo's runs leave in the forge's registry (`ci_registry: -// ghcr`), pruned (§ 8 PLX-Delivery), for the packages of the repo's own apps -// and no other: a version of a container package whose every tag -// is `build-` or `test-` and that is older than thirty days goes. -// A version that carries any other tag stays, whatever its age: a commit's -// SHA marks a published image, which a rollback may ask for years later, and -// `cache` is the one moving tag BuildKit rewrites. An untagged version stays -// as well, since it may be part of an image this rule knows nothing about. -// Through GitHub's packages API with curl; the token goes to curl as a config -// on stdin, never on argv. That API takes no App token: the workflow's own -// token deletes versions of the packages its repo published, which is why -// the pruning is mounted in the app repo. -import type { Context } from '@plexus-ms/lib'; -import { orAbsent, run } from '@plexus-ms/lib'; -import { curlNotFound } from './registry.ts'; - -export interface Version { - id: number; - /** `2026-11-04T10:40:27Z`. */ - createdAt: string; - tags: string[]; -} - -export const PRUNE_AFTER_DAYS = 30; -const CANDIDATE_TAG = /^(build|test)-[0-9a-f]+$/; - -/** The versions that go: tagged, with candidate tags only, created more than `days` ago. */ -export function prunable(versions: Version[], now: Date, days = PRUNE_AFTER_DAYS): Version[] { - const before = now.getTime() - days * 86_400_000; - return versions.filter( - (v) => v.tags.length > 0 && v.tags.every((t) => CANDIDATE_TAG.test(t)) && Date.parse(v.createdAt) < before, - ); -} - -export class Packages { - readonly ctx: Context; - readonly org: string; - private readonly token: string; - - constructor(ctx: Context, org: string, token: string) { - this.ctx = ctx; - this.org = org; - this.token = token; - } - - private config(method: string, path: string): string { - return `${[ - `url = "https://api.github.com/orgs/${this.org}/packages${path}"`, - `request = "${method}"`, - 'fail-with-body', - 'silent', - 'show-error', - `header = "Authorization: Bearer ${this.token}"`, - 'header = "Accept: application/vnd.github+json"', - 'header = "X-GitHub-Api-Version: 2022-11-28"', - ].join('\n')}\n`; - } - - /** Every page of a list, a hundred entries each. */ - private async pages(path: string): Promise { - const all: T[] = []; - for (let page = 1; ; page++) { - const sep = path.includes('?') ? '&' : '?'; - const out = await this.ctx.read('curl', ['-K', '-'], { - input: this.config('GET', `${path}${sep}per_page=100&page=${page}`), - }); - const items = JSON.parse(out) as T[]; - all.push(...items); - if (items.length < 100) return all; - } - } - - async versions(name: string): Promise { - const raw = await this.pages<{ - id: number; - created_at: string; - metadata?: { container?: { tags?: string[] } }; - }>(`/container/${encodeURIComponent(name)}/versions`); - return raw.map((v) => ({ id: v.id, createdAt: v.created_at, tags: v.metadata?.container?.tags ?? [] })); - } - - async deleteVersion(name: string, id: number): Promise { - await this.ctx.effect( - run('curl', ['-K', '-'], { - input: this.config('DELETE', `/container/${encodeURIComponent(name)}/versions/${id}`), - }), - ); - } -} - -export interface Pruned { - package: string; - id: number; - tags: string[]; -} - -/** The package an app's image is, under `ghcr.io/[/]`: the path and the app. */ -export function packageOf(prefix: string, app: string): string { - const path = prefix.toLowerCase().replace(/\/$/, '').split('/').slice(2); - return [...path, app].join('/'); -} - -/** Prune the named packages by the rule above; a package that does not exist yet has nothing to prune. */ -export async function prune(ctx: Context, packages: Packages, names: string[], now = new Date()): Promise { - const pruned: Pruned[] = []; - for (const name of names) { - const versions = await orAbsent(packages.versions(name), curlNotFound); - if (versions === undefined) { - ctx.say(`rotate: no package ${name} in ghcr.io/${packages.org}`); - continue; - } - for (const v of prunable(versions, now)) { - ctx.say(`rotate: ${name} ${v.tags.join(' ')} (${v.createdAt}) is older than ${PRUNE_AFTER_DAYS} days`); - await packages.deleteVersion(name, v.id); - pruned.push({ package: name, id: v.id, tags: v.tags }); - } - } - ctx.say( - `rotate: ${pruned.length} candidate version(s) pruned from ${names.length} package(s) of ghcr.io/${packages.org}`, - ); - return pruned; -} diff --git a/packages/cli-ci/src/core/plan.test.ts b/packages/cli-ci/src/core/plan.test.ts index d825c15c..b362acf9 100644 --- a/packages/cli-ci/src/core/plan.test.ts +++ b/packages/cli-ci/src/core/plan.test.ts @@ -124,7 +124,7 @@ function forge(holds: string[]) { const io = fakeIo(REPO, undefined, { crane: (_cwd, args) => { asked.push(args.join(' ')); - return args[0] === 'digest' && holds.includes(args[1] ?? '') ? 'sha256:abc' : notThere('crane'); + return args[0] === 'digest' && holds.includes(args[1] ?? '') ? 'sha256:abc' : notThere(); }, }); return { io, asked }; diff --git a/packages/cli-ci/src/core/publish.test.ts b/packages/cli-ci/src/core/publish.test.ts index feda20c2..9e34c06f 100644 --- a/packages/cli-ci/src/core/publish.test.ts +++ b/packages/cli-ci/src/core/publish.test.ts @@ -45,7 +45,7 @@ function world(options: { holds?: string[]; outputs?: Record; bu }; const io = fakeIo(tree, undefined, { crane: record('crane', (args) => - args[0] !== 'digest' ? '' : (options.holds ?? []).includes(args[1] ?? '') ? 'sha256:there' : notThere('crane'), + args[0] !== 'digest' ? '' : (options.holds ?? []).includes(args[1] ?? '') ? 'sha256:there' : notThere(), ), mise: record('mise', (args) => { // `mise run build `: the restore leaves the output and its BUILD_ID. diff --git a/packages/cli-ci/src/core/registry.test.ts b/packages/cli-ci/src/core/registry.test.ts index 00c5bfb7..76d966ab 100644 --- a/packages/cli-ci/src/core/registry.test.ts +++ b/packages/cli-ci/src/core/registry.test.ts @@ -10,7 +10,7 @@ test('an image name is the prefix, lower-cased, and the app', () => { test('craneDigest answers the digest, or undefined where the registry holds no such manifest', async () => { const io = fakeIo({}, undefined, { - crane: (_cwd, args) => (args[1]?.endsWith(':build-x') ? 'sha256:a\n' : notThere('crane')), + crane: (_cwd, args) => (args[1]?.endsWith(':build-x') ? 'sha256:a\n' : notThere()), }); assert.equal(await craneDigest(new Context({}, io), 'ghcr.io/o/website:build-x'), 'sha256:a'); assert.equal(await craneDigest(new Context({}, io), 'ghcr.io/o/website:build-y'), undefined); diff --git a/packages/cli-ci/src/core/registry.ts b/packages/cli-ci/src/core/registry.ts index 2b02ae11..e48d6c17 100644 --- a/packages/cli-ci/src/core/registry.ts +++ b/packages/cli-ci/src/core/registry.ts @@ -1,328 +1,32 @@ -// Where a run's candidates live (§ 8 PLX-Delivery), behind one shape. `own` -// is the registry pair: `registry:2` on 127.0.0.1:5000 for this week's -// bucket, read-write, and on 127.0.0.1:5001 for the previous week's, -// read-only; both the same registry API over the tenant's object storage, -// nothing reads the bucket layout directly. A runner host keeps the pair -// running, and so does a launched instance from its boot (its user-data); a -// forge runner starts it for the length of its job. In the first week the previous bucket does not -// exist and registry:2 answers 503 (its storage health check fails): that -// sidecar is optional, and a build names it as a cache source only when it -// answers 200. `ghcr` is the forge's registry itself, where the published -// images live too: nothing to start, the job logs in, and crane and docker -// reach it. +// What a verb asks the forge's registry (§ 4 PLX-Delivery), where the published +// images and the `build-` tags live: whether it holds a manifest, with +// crane, which the job has logged in to the registry. Nothing is started here. import type { Context } from '@plexus-ms/lib'; -import { ExecError, orAbsent, run } from '@plexus-ms/lib'; -import { sleep } from './exoscale.ts'; -import { type ObjectStorage, S3 } from './s3.ts'; -import type { RegistryKind } from './strategy.ts'; -import { registryBuckets } from './time.ts'; - -/** The registry the candidates of a run live in; `prefix` is where the images of the forge's registry live, `ghcr.io/`. */ -export type Registry = { kind: 'own' } | { kind: 'ghcr'; prefix: string }; +import { ExecError, orAbsent } from '@plexus-ms/lib'; export const imageName = (prefix: string, app: string): string => `${prefix.toLowerCase().replace(/\/$/, '')}/${app}`; -export function registryOf(kind: RegistryKind, prefix: string): Registry { - return kind === 'own' ? { kind } : { kind, prefix }; -} - -export type { ObjectStorage }; - -export const CURRENT_PORT = 5000; -export const PREVIOUS_PORT = 5001; -export const REGISTRY_IMAGE = 'registry:2'; -const ACCEPT = - 'application/vnd.oci.image.manifest.v1+json, application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.v2+json, application/vnd.docker.distribution.manifest.list.v2+json'; - -/** The storage from the environment the vault item bucket-registry fills. */ -export function storageFromEnv(env: NodeJS.ProcessEnv = process.env): ObjectStorage | undefined { - const { REGISTRY_ENDPOINT, REGISTRY_REGION, REGISTRY_ACCESS_KEY, REGISTRY_SECRET_KEY } = env; - if (!REGISTRY_ENDPOINT || !REGISTRY_REGION || !REGISTRY_ACCESS_KEY || !REGISTRY_SECRET_KEY) return undefined; - return { - endpoint: REGISTRY_ENDPOINT, - region: REGISTRY_REGION, - accessKey: REGISTRY_ACCESS_KEY, - secretKey: REGISTRY_SECRET_KEY, - }; -} - -/** The `docker run` of one sidecar; the key on argv is the same exposure as the job's own secrets. */ -export function sidecarArgs( - name: string, - port: number, - bucket: string, - storage: ObjectStorage, - readOnly: boolean, -): string[] { - return [ - 'run', - '-d', - '--name', - name, - '--restart', - readOnly ? 'on-failure:3' : 'unless-stopped', - '-p', - `127.0.0.1:${port}:5000`, - '-e', - 'REGISTRY_STORAGE=s3', - '-e', - `REGISTRY_STORAGE_S3_REGIONENDPOINT=${storage.endpoint}`, - '-e', - `REGISTRY_STORAGE_S3_REGION=${storage.region}`, - '-e', - `REGISTRY_STORAGE_S3_BUCKET=${bucket}`, - '-e', - `REGISTRY_STORAGE_S3_ACCESSKEY=${storage.accessKey}`, - '-e', - `REGISTRY_STORAGE_S3_SECRETKEY=${storage.secretKey}`, - '-e', - 'REGISTRY_STORAGE_S3_FORCEPATHSTYLE=true', - '-e', - // registry:2 panics on the read-only flag as one nested variable - // (…_READONLY_ENABLED=true): the map it builds from it has the wrong - // type. The whole key as one YAML value is read as from a config file. - readOnly ? 'REGISTRY_STORAGE_MAINTENANCE_READONLY={"enabled":true}' : 'REGISTRY_STORAGE_DELETE_ENABLED=true', - REGISTRY_IMAGE, - ]; -} - -/** Whether a sidecar answers `/v2/`. */ -export async function answers(ctx: Context, port: number): Promise { - try { - await ctx.read('curl', ['-fsS', '--max-time', '3', `http://127.0.0.1:${port}/v2/`]); - return true; - } catch { - return false; - } -} - -export interface Sidecars { - current: string; - previous: string; - /** Whether the previous week's sidecar answers. */ - previousAnswers: boolean; -} - -/** - * Create this week's bucket when it does not exist yet (the ci-storage key - * may), start both sidecars, wait for the current one and briefly for the - * previous one. Where the current one answers already, the machine runs the - * pair for its jobs (a slot of a runner host, actions_runners, which keeps - * the pair on this week's buckets and gives the slot no Docker socket): - * nothing is started and no bucket is touched. - */ -export async function startSidecars( - ctx: Context, - storage: ObjectStorage | undefined, - owner: string, - now = new Date(), -): Promise { - const buckets = registryBuckets(owner, now); - if (!ctx.dryRun && (await answers(ctx, CURRENT_PORT))) { - const previousAnswers = await answers(ctx, PREVIOUS_PORT); - ctx.say(`registry: :${CURRENT_PORT} answers already, the host's pair; nothing started`); - return { current: buckets.current, previous: buckets.previous, previousAnswers }; - } - if (!storage) - throw new Error('REGISTRY_ENDPOINT, REGISTRY_REGION, REGISTRY_ACCESS_KEY and REGISTRY_SECRET_KEY are needed'); - const s3 = new S3(ctx, storage); - if (!(await s3.bucketExists(buckets.current))) { - ctx.say(`→ creating the bucket ${buckets.current}`); - await s3.makeBucket(buckets.current); - } - await ctx.apply([ - run('docker', sidecarArgs('registry', CURRENT_PORT, buckets.current, storage, false)), - run('docker', sidecarArgs('registry-previous', PREVIOUS_PORT, buckets.previous, storage, true)), - ]); - if (!ctx.dryRun) { - for (let i = 0; i < 30 && !(await answers(ctx, CURRENT_PORT)); i++) await sleep(1000); - for (let i = 0; i < 5 && !(await answers(ctx, PREVIOUS_PORT)); i++) await sleep(1000); - } - const previousAnswers = ctx.dryRun ? false : await answers(ctx, PREVIOUS_PORT); - ctx.say( - `registry: :${CURRENT_PORT} on ${buckets.current} (read-write), :${PREVIOUS_PORT} on ${buckets.previous} (${previousAnswers ? 'read-only' : 'not answering, bucket missing?'})`, - ); - return { current: buckets.current, previous: buckets.previous, previousAnswers }; -} - -/** curl's exit under --fail when the server answers 404: the one failure that means "not there". */ -export const curlNotFound = (error: ExecError): boolean => error.code === 22 && /\b404\b/.test(error.stderr); - /** crane's answer that the registry holds no such manifest, or no such repository. */ const craneNotFound = (error: ExecError): boolean => /MANIFEST_UNKNOWN|NAME_UNKNOWN|\b404\b/.test(error.stderr); /** - * One look-up of `ref`: the tool's output, or undefined when the registry - * says it holds no such thing (`absent` reads that off the failed command). - * Any other failure is an error: a tool that cannot run, a login the - * registry refuses or a sidecar that does not answer is the job's fault, and - * reporting it as a missing image sends the reader after a build that ran. + * The digest of `ref` on a registry crane is logged in to, or undefined when + * the registry says it holds no such manifest. Any other failure is an error: + * a crane that cannot run or a login the registry refuses is the job's fault, + * and reporting it as a missing image sends the reader after a build that ran. * Under --dry-run the failure is narrated and taken for absent, so a preview - * runs where there is no crane, no login or no sidecar. + * runs where there is no crane or no login. */ -async function lookUp( - ctx: Context, - ref: string, - command: string, - args: string[], - absent: (error: ExecError) => boolean, -): Promise { +export async function craneDigest(ctx: Context, ref: string): Promise { try { - return await orAbsent(ctx.read(command, args), absent); + return (await orAbsent(ctx.read('crane', ['digest', ref]), craneNotFound))?.trim() || undefined; } catch (error) { const why = error instanceof ExecError ? `could not look up ${ref}: ${error.message}` - : `${command} could not run to look up ${ref}; is it installed in this job?`; + : `crane could not run to look up ${ref}; is it installed in this job?`; if (!ctx.dryRun) throw new Error(why, { cause: error }); ctx.say(`[dry-run] ${why.split('\n')[0]}; taken for absent`); return undefined; } } - -const manifestUrl = (port: number, app: string, tag: string): string => - `http://127.0.0.1:${port}/v2/${app}/manifests/${tag}`; - -/** A manifest HEAD against one sidecar: its headers, or undefined where `absent` says so (a 404). */ -const head = (ctx: Context, port: number, app: string, tag: string, absent = curlNotFound) => - lookUp( - ctx, - `localhost:${port}/${app}:${tag}`, - 'curl', - ['-fsS', '-I', '-H', `Accept: ${ACCEPT}`, manifestUrl(port, app, tag)], - absent, - ); - -/** - * The port of the sidecar that holds `app:tag`, or undefined. This week's - * sidecar has to answer; the previous week's is optional (see the top), so - * any failure there is absence. - */ -export async function tagExists(ctx: Context, app: string, tag: string): Promise { - if ((await head(ctx, CURRENT_PORT, app, tag)) !== undefined) return CURRENT_PORT; - if ((await head(ctx, PREVIOUS_PORT, app, tag, () => true)) !== undefined) return PREVIOUS_PORT; - return undefined; -} - -/** The digest of `app:tag` on one sidecar, or undefined. */ -export async function digest(ctx: Context, app: string, tag: string, port = CURRENT_PORT): Promise { - return (await head(ctx, port, app, tag))?.match(/^docker-content-digest:\s*(\S+)/im)?.[1]; -} - -export interface Layer { - digest: string; - size: number; -} - -/** The layers of `app:tag`'s manifest on one sidecar, or undefined. */ -export async function layers( - ctx: Context, - app: string, - tag: string, - port = CURRENT_PORT, -): Promise { - const manifest = await lookUp( - ctx, - `localhost:${port}/${app}:${tag}`, - 'curl', - ['-fsS', '-H', `Accept: ${ACCEPT}`, manifestUrl(port, app, tag)], - curlNotFound, - ); - return manifest === undefined ? undefined : layersIn(manifest); -} - -const layersIn = (manifest: string): Layer[] => - ((JSON.parse(manifest) as { layers?: Layer[] }).layers ?? []).map((l) => ({ digest: l.digest, size: l.size })); - -/** Where a run writes `app:tag`: this week's sidecar, or the forge's registry. */ -export function candidateRef(registry: Registry, app: string, tag: string): string { - return registry.kind === 'own' - ? `localhost:${CURRENT_PORT}/${app}:${tag}` - : `${imageName(registry.prefix, app)}:${tag}`; -} - -/** The digest of `ref` on a registry crane is logged in to, or undefined when the registry holds no such manifest. */ -export async function craneDigest(ctx: Context, ref: string): Promise { - return (await lookUp(ctx, ref, 'crane', ['digest', ref], craneNotFound))?.trim() || undefined; -} - -/** The ref under which the registry holds `app:tag`, either sidecar's under `own`, or undefined. */ -export async function findTag(ctx: Context, registry: Registry, app: string, tag: string): Promise { - if (registry.kind === 'own') { - const port = await tagExists(ctx, app, tag); - return port === undefined ? undefined : `localhost:${port}/${app}:${tag}`; - } - const ref = candidateRef(registry, app, tag); - return (await craneDigest(ctx, ref)) === undefined ? undefined : ref; -} - -/** The digest of `app:tag` where a run writes, or undefined. */ -export function digestOf(ctx: Context, registry: Registry, app: string, tag: string): Promise { - return registry.kind === 'own' ? digest(ctx, app, tag) : craneDigest(ctx, candidateRef(registry, app, tag)); -} - -/** The layers of `app:tag` where a run writes, or undefined. */ -export async function layersOf( - ctx: Context, - registry: Registry, - app: string, - tag: string, -): Promise { - if (registry.kind === 'own') return layers(ctx, app, tag); - const ref = candidateRef(registry, app, tag); - const manifest = await lookUp(ctx, ref, 'crane', ['manifest', ref], craneNotFound); - return manifest === undefined ? undefined : layersIn(manifest); -} - -/** - * Whether this machine holds a login for the forge's registry: an entry in - * the Docker config crane and docker both read, or a credential store that - * answers for it. Read from the file, so that no secret passes through here. - */ -export async function loggedIn(ctx: Context, host: string, env: NodeJS.ProcessEnv = process.env): Promise { - const file = `${env.DOCKER_CONFIG || `${env.HOME}/.docker`}/config.json`; - try { - const config = JSON.parse(await ctx.readFile(file)) as { - auths?: Record; - credsStore?: string; - credHelpers?: Record; - }; - return Boolean(config.auths?.[host] || config.credHelpers?.[host] || config.credsStore); - } catch { - return false; - } -} - -export interface Rotation { - /** This week's bucket, when it had to be created. */ - created?: string; - /** The bucket from two weeks ago, when it was still there. */ - removed?: string; -} - -/** - * Retention by rotation: this week's bucket exists, the one from two weeks - * ago is deleted whole. Writes go to the current week, reads consult the - * current and the previous, so nothing reads what goes. - */ -export async function rotateBuckets( - ctx: Context, - storage: ObjectStorage, - owner: string, - now = new Date(), -): Promise { - const buckets = registryBuckets(owner, now); - const s3 = new S3(ctx, storage); - const result: Rotation = {}; - if (!(await s3.bucketExists(buckets.current))) { - ctx.say(`rotate: creating the bucket ${buckets.current}`); - await s3.makeBucket(buckets.current); - result.created = buckets.current; - } - if (await s3.bucketExists(buckets.expired)) { - ctx.say(`rotate: the registry bucket ${buckets.expired} is two weeks old`); - await s3.removeBucket(buckets.expired); - result.removed = buckets.expired; - } - return result; -} diff --git a/packages/cli-ci/src/core/s3.ts b/packages/cli-ci/src/core/s3.ts deleted file mode 100644 index 0913f02f..00000000 --- a/packages/cli-ci/src/core/s3.ts +++ /dev/null @@ -1,164 +0,0 @@ -// The registry's buckets, through the S3 API itself with curl (§ 8 -// PLX-Delivery): whether a bucket exists, creating it, and deleting it whole. -// Plain S3, signed by curl (`--aws-sigv4`), so that the store is any -// S3-compatible one and the job needs no provider's CLI; the runner host's -// own script (actions_runners, ci-registry-refresh) speaks to it the same way. -// Path-style addressing, as the registry is configured. The key goes to curl -// as a config on stdin, never on argv. -import { createHash } from 'node:crypto'; -import type { Context } from '@plexus-ms/lib'; -import { run } from '@plexus-ms/lib'; - -export interface ObjectStorage { - /** The S3 endpoint, `https://…`, without a bucket. */ - endpoint: string; - region: string; - accessKey: string; - secretKey: string; -} - -interface Call { - method: 'HEAD' | 'GET' | 'PUT' | 'POST' | 'DELETE'; - /** The path below the endpoint, `` or `/`, and its query. */ - path: string; - query?: string; - body?: string; - headers?: string[]; -} - -interface Answer { - status: number; - body: string; -} - -const sha256 = (text: string): string => createHash('sha256').update(text).digest('hex'); -const md5 = (text: string): string => createHash('md5').update(text).digest('base64'); - -const unescapeXml = (text: string): string => - text - .replaceAll('<', '<') - .replaceAll('>', '>') - .replaceAll('"', '"') - .replaceAll(''', "'") - .replaceAll('&', '&'); -const escapeXml = (text: string): string => - text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>'); - -/** Every `…` of an S3 answer, unescaped. */ -export function elements(xml: string, tag: string): string[] { - return [...xml.matchAll(new RegExp(`<${tag}>([^<]*)`, 'g'))].map((m) => unescapeXml(m[1] ?? '')); -} - -/** The uploads a ListMultipartUploads answer names: a key and its upload id each. */ -export function uploads(xml: string): { key: string; id: string }[] { - return [...xml.matchAll(/(.*?)<\/Upload>/gs)].flatMap((m) => { - const key = elements(m[1] ?? '', 'Key')[0]; - const id = elements(m[1] ?? '', 'UploadId')[0]; - return key !== undefined && id !== undefined ? [{ key, id }] : []; - }); -} - -/** The body of a DeleteObjects call for up to a thousand keys. */ -export function deleteBody(keys: string[]): string { - return `true${keys.map((k) => `${escapeXml(k)}`).join('')}`; -} - -export class S3 { - readonly ctx: Context; - private readonly storage: ObjectStorage; - - constructor(ctx: Context, storage: ObjectStorage) { - this.ctx = ctx; - this.storage = storage; - } - - /** The curl config of one call: the URL, the signature's inputs, the body, and the status after the answer. */ - private config(call: Call): string { - const { endpoint, region, accessKey, secretKey } = this.storage; - const url = `${endpoint.replace(/\/$/, '')}/${call.path}${call.query ? `?${call.query}` : ''}`; - const body = call.body ?? ''; - const lines = [ - `url = ${JSON.stringify(url)}`, - call.method === 'HEAD' ? 'head' : `request = "${call.method}"`, - 'silent', - 'show-error', - 'max-time = 60', - `user = ${JSON.stringify(`${accessKey}:${secretKey}`)}`, - `aws-sigv4 = "aws:amz:${region}:s3"`, - // Stated, not left to curl: its versions differ in whether they send it, and S3 wants it signed. - `header = "x-amz-content-sha256: ${sha256(body)}"`, - ...(call.headers ?? []).map((h) => `header = ${JSON.stringify(h)}`), - ...(call.body === undefined ? [] : [`data-binary = ${JSON.stringify(body)}`]), - 'write-out = "\\n%{http_code}"', - ]; - return `${lines.join('\n')}\n`; - } - - private answer(out: string): Answer { - const at = out.lastIndexOf('\n'); - return { status: Number(out.slice(at + 1)), body: out.slice(0, at) }; - } - - private async read(call: Call): Promise { - return this.answer(await this.ctx.read('curl', ['-K', '-'], { input: this.config(call) })); - } - - /** An effect: its answer, or undefined under --dry-run. A status outside 2xx is an error. */ - private async effect(call: Call, what: string): Promise { - const out = await this.ctx.effect(run('curl', ['-K', '-'], { input: this.config(call) })); - if (out === undefined) return undefined; - const answer = this.answer(out); - if (answer.status < 200 || answer.status >= 300) - throw new Error(`${what} answered ${answer.status}: ${answer.body.slice(0, 300)}`); - return answer; - } - - async bucketExists(bucket: string): Promise { - const { status } = await this.read({ method: 'HEAD', path: bucket }); - if (status === 200) return true; - if (status === 404) return false; - throw new Error(`looking up the bucket ${bucket} answered ${status}`); - } - - async makeBucket(bucket: string): Promise { - await this.effect({ method: 'PUT', path: bucket }, `creating the bucket ${bucket}`); - } - - /** - * Delete a bucket whole: its objects a thousand at a time, the uploads - * something left unfinished, then the bucket, which S3 refuses while - * either remains. A dry run lists once and says what would go. - */ - async removeBucket(bucket: string): Promise { - let removed = 0; - for (;;) { - const page = await this.read({ method: 'GET', path: bucket, query: 'list-type=2&max-keys=1000' }); - if (page.status !== 200) throw new Error(`listing the bucket ${bucket} answered ${page.status}`); - const keys = elements(page.body, 'Key'); - if (keys.length === 0) break; - const body = deleteBody(keys); - const answer = await this.effect( - { method: 'POST', path: bucket, query: 'delete=', body, headers: [`Content-MD5: ${md5(body)}`] }, - `deleting ${keys.length} objects of ${bucket}`, - ); - if (answer === undefined) { - this.ctx.say(` (the objects of ${bucket}, ${keys.length} in the first listing, then the bucket)`); - return; - } - const failed = elements(answer.body, 'Message'); - if (answer.body.includes('')) - throw new Error(`deleting objects of ${bucket} failed: ${failed[0] ?? answer.body.slice(0, 300)}`); - removed += keys.length; - } - const pending = await this.read({ method: 'GET', path: bucket, query: 'uploads=' }); - for (const upload of pending.status === 200 ? uploads(pending.body) : []) { - const key = upload.key.split('/').map(encodeURIComponent).join('/'); - await this.effect( - { method: 'DELETE', path: `${bucket}/${key}`, query: `uploadId=${encodeURIComponent(upload.id)}` }, - `aborting an unfinished upload in ${bucket}`, - ); - } - await this.effect({ method: 'DELETE', path: bucket }, `deleting the bucket ${bucket}`); - this.ctx.say(`removed the bucket ${bucket} and its ${removed} object(s)`); - } -} diff --git a/packages/cli-ci/src/core/strategy.ts b/packages/cli-ci/src/core/strategy.ts index 856f0f2b..e2f1f9fc 100644 --- a/packages/cli-ci/src/core/strategy.ts +++ b/packages/cli-ci/src/core/strategy.ts @@ -1,25 +1,19 @@ -// The three answers a repo gives about its CI (§ 8 PLX-Delivery), read once: -// the strategy (where the jobs of each size run), the registry (where the -// candidates live) and the overlay (how a deploy reaches the hosts; the -// deploy mount acts on it, the commands only check it). The -// reusable workflows set them as CI_STRATEGY, CI_REGISTRY and CI_OVERLAY from -// their inputs; `--strategy` overrides the first by hand. Pure, so that the -// tests pin the defaults and the labels. +// The two answers a repo gives about its CI (§ 8 PLX-Delivery), read once: +// the strategy (where the jobs of each size run) and the overlay (how a +// deploy reaches the hosts; the deploy mount acts on it, the commands only +// check it). The reusable workflows set them as CI_STRATEGY and CI_OVERLAY +// from their inputs; `--strategy` overrides the first by hand. Pure, so that +// the tests pin the defaults and the labels. import { UsageError } from '@plexus-ms/lib'; export const STRATEGIES = ['github', 'on-prem', 'hybrid'] as const; export type Strategy = (typeof STRATEGIES)[number]; -export const REGISTRIES = ['ghcr', 'own'] as const; -/** `ghcr`: the candidates live beside the published images; `own`: in the registry pair on the tenant's object storage. */ -export type RegistryKind = (typeof REGISTRIES)[number]; - export const OVERLAYS = ['none', 'netbird'] as const; export type Overlay = (typeof OVERLAYS)[number]; export interface Settings { strategy: Strategy; - registry: RegistryKind; overlay: Overlay; } @@ -32,14 +26,12 @@ function oneOf(name: string, value: string, allowed: readonly /** * The settings from the environment, `flag` (--strategy) before CI_STRATEGY. * Without a strategy it is `github`, the forge's runners, where everything - * runs without a host or a cloud. The registry defaults from the strategy: - * `ghcr` under `github`, `own` otherwise. + * runs without a host or a cloud. */ export function settingsOf(env: NodeJS.ProcessEnv = process.env, flag?: string): Settings { const strategy = oneOf('the strategy', flag || env.CI_STRATEGY || 'github', STRATEGIES); - const registry = oneOf('CI_REGISTRY', env.CI_REGISTRY || (strategy === 'github' ? 'ghcr' : 'own'), REGISTRIES); const overlay = oneOf('CI_OVERLAY', env.CI_OVERLAY || 'none', OVERLAYS); - return { strategy, registry, overlay }; + return { strategy, overlay }; } export type Size = 'small' | 'medium' | 'large'; diff --git a/packages/cli-ci/src/core/time.ts b/packages/cli-ci/src/core/time.ts index e9e2b332..d73c533c 100644 --- a/packages/cli-ci/src/core/time.ts +++ b/packages/cli-ci/src/core/time.ts @@ -1,7 +1,5 @@ // The clock, in one place: deadlines as absolute UTC times (what the instance -// labels and the sweep compare), and the registry's week names (§ 8 -// PLX-Delivery: writes to this week's bucket, reads this and the previous, -// the one before is deleted whole). Pure, so that the tests pin the arithmetic. +// labels and the sweep compare). Pure, so that the tests pin the arithmetic. /** `2026-11-04T10:40:27Z`, the shape every label and log line uses. */ export function iso(at: Date): string { @@ -12,25 +10,3 @@ export function iso(at: Date): string { export function deadline(now: Date, minutes: number): string { return iso(new Date(now.getTime() + minutes * 60_000)); } - -/** - * `YYYY-wWW`, the ISO week `offset` weeks from `now`'s (0 this week, -1 the - * previous), in UTC: weeks start on Monday, and a week belongs to the year - * its Thursday is in, as `date +%G-w%V` prints it. - */ -export function week(now: Date, offset = 0): string { - const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + offset * 7)); - // To the Thursday of the week, whose year is the week's. - d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7)); - const days = (d.getTime() - Date.UTC(d.getUTCFullYear(), 0, 1)) / 86_400_000; - return `${d.getUTCFullYear()}-w${String(Math.floor(days / 7) + 1).padStart(2, '0')}`; -} - -/** The registry bucket names of one owner: by convention `-ci-registry-`. */ -export function registryBuckets(owner: string, now: Date): { current: string; previous: string; expired: string } { - const name = (offset: number) => `${owner}-ci-registry-${week(now, offset)}`; - return { current: name(0), previous: name(-1), expired: name(-2) }; -} - -/** The Turbo cache bucket of one owner, `-ci-turbo`. */ -export const turboBucket = (owner: string): string => `${owner}-ci-turbo`; diff --git a/packages/cli-ci/src/core/userData.ts b/packages/cli-ci/src/core/userData.ts index 2654378c..4fb9f502 100644 --- a/packages/cli-ci/src/core/userData.ts +++ b/packages/cli-ci/src/core/userData.ts @@ -3,8 +3,8 @@ // slot: in a container of the environment image (actions_runners' ci-runner), // on the host's network, with no Docker socket, so a job meets the same // machine under on-prem and hybrid; the instance's own Docker runs that one -// container and the registry pair, and nothing for the job. The placeholders `@@NAME@@` are filled -// by render(); a leftover placeholder is an error. Kept as string constants so +// container, and nothing for the job. The placeholders `@@NAME@@` are filled by +// render(); a leftover placeholder is an error. Kept as string constants so // that the bundle carries them and the tests render them without a loader. The // cloud-config itself is documented inline; edit here, nowhere else. // @@ -41,9 +41,8 @@ export const RUNNER_USER_DATA = `#cloud-config # cloud-init does not get past it (the hostname stays \`localhost\`, no # network, no SSH), so every layer is a systemd timer started in runcmd. # -# The self-delete key and the registry bucket's write key sit in -# /etc/plexus-ci/env, readable by root on the host; the job's container -# mounts none of /etc/plexus-ci (§ 8 PLX-Delivery). +# The self-delete key sits in /etc/plexus-ci/env, readable by root on the +# host; the job's container mounts none of /etc/plexus-ci (§ 8 PLX-Delivery). hostname: @@LABEL@@ write_files: @@ -64,12 +63,6 @@ write_files: SMTP_PASSWORD=@@SMTP_PASSWORD@@ MAIL_FROM=@@MAIL_FROM@@ MAIL_TO=@@MAIL_TO@@ - REGISTRY_ENDPOINT=@@REGISTRY_ENDPOINT@@ - REGISTRY_REGION=@@REGISTRY_REGION@@ - REGISTRY_BUCKET=@@REGISTRY_BUCKET@@ - REGISTRY_PREVIOUS_BUCKET=@@REGISTRY_PREVIOUS_BUCKET@@ - REGISTRY_ACCESS_KEY=@@REGISTRY_ACCESS_KEY@@ - REGISTRY_SECRET_KEY=@@REGISTRY_SECRET_KEY@@ # The runner's config, as a slot's container gets it (ci-runner-jit): the # runner reads the variable and clears it before any job step runs. - path: /etc/plexus-ci/runner.env @@ -244,7 +237,7 @@ write_files: # 1: ExecStopPost runs as root (the +) when the container ends for any # reason, a runner that could not start included. The container is the # one a small slot of a runner host starts (ci-runner-slot): the host's - # network, where the registry pair answers, and no Docker socket. It + # network and no Docker socket. It # mounts no cache: the instance runs this one job and is deleted, so # nothing is shared between jobs, and what the job installs goes with the # container. Its only mount, _diag, is the host's /opt/runner/_diag, which @@ -271,9 +264,6 @@ runcmd: - curl -fsSL https://get.docker.com | sh # The image's user runner (1001) writes the runner's log here. - install -d -o 1001 -g 1001 /opt/runner/_diag - # The registry sidecars, when the launch named a bucket (§ 8 PLX-Delivery): :5000 on this week's bucket, read-write; :5001 on the previous week's, read-only. The same two containers as .github/ci/registry.sh starts on a GitHub runner. - - . /etc/plexus-ci/env && if [ -n "$REGISTRY_ENDPOINT" ]; then docker run -d --name registry --restart unless-stopped -p 127.0.0.1:5000:5000 -e REGISTRY_STORAGE=s3 -e REGISTRY_STORAGE_S3_REGIONENDPOINT="$REGISTRY_ENDPOINT" -e REGISTRY_STORAGE_S3_REGION="$REGISTRY_REGION" -e REGISTRY_STORAGE_S3_BUCKET="$REGISTRY_BUCKET" -e REGISTRY_STORAGE_S3_ACCESSKEY="$REGISTRY_ACCESS_KEY" -e REGISTRY_STORAGE_S3_SECRETKEY="$REGISTRY_SECRET_KEY" -e REGISTRY_STORAGE_S3_FORCEPATHSTYLE=true -e REGISTRY_STORAGE_DELETE_ENABLED=true registry:2 >/dev/null; fi - - . /etc/plexus-ci/env && if [ -n "$REGISTRY_ENDPOINT" ]; then docker run -d --name registry-previous --restart on-failure:3 -p 127.0.0.1:5001:5000 -e REGISTRY_STORAGE=s3 -e REGISTRY_STORAGE_S3_REGIONENDPOINT="$REGISTRY_ENDPOINT" -e REGISTRY_STORAGE_S3_REGION="$REGISTRY_REGION" -e REGISTRY_STORAGE_S3_BUCKET="$REGISTRY_PREVIOUS_BUCKET" -e REGISTRY_STORAGE_S3_ACCESSKEY="$REGISTRY_ACCESS_KEY" -e REGISTRY_STORAGE_S3_SECRETKEY="$REGISTRY_SECRET_KEY" -e REGISTRY_STORAGE_S3_FORCEPATHSTYLE=true -e 'REGISTRY_STORAGE_MAINTENANCE_READONLY={"enabled":true}' registry:2 >/dev/null; fi # Pulled here rather than by the runner's unit, so that the log says how long the pull took. - docker pull -q @@IMAGE@@ - systemctl start plexus-ci-runner.service diff --git a/packages/cli-ci/src/testing/fakeIo.ts b/packages/cli-ci/src/testing/fakeIo.ts index d768562d..fea84372 100644 --- a/packages/cli-ci/src/testing/fakeIo.ts +++ b/packages/cli-ci/src/testing/fakeIo.ts @@ -8,11 +8,13 @@ export type Tree = { [name: string]: string | Tree }; export type FakeExec = (cwd: string, args: string[], input?: string, env?: NodeJS.ProcessEnv) => string | undefined; -/** What a registry answers for a manifest it does not hold, as curl --fail and crane report it. */ -export function notThere(command: 'curl' | 'crane'): never { - throw command === 'curl' - ? new ExecError('curl', 22, 'curl: (22) The requested URL returned error: 404\n') - : new ExecError('crane', 1, 'Error: GET https://ghcr.io/v2/o/a/manifests/t: MANIFEST_UNKNOWN: manifest unknown\n'); +/** What the forge's registry answers for a manifest it does not hold, as crane reports it. */ +export function notThere(): never { + throw new ExecError( + 'crane', + 1, + 'Error: GET https://ghcr.io/v2/o/a/manifests/t: MANIFEST_UNKNOWN: manifest unknown\n', + ); } /** `git` answers git calls; `other` answers any other command, by name. */ diff --git a/packages/lib/src/io.ts b/packages/lib/src/io.ts index 3011c303..e4176562 100644 --- a/packages/lib/src/io.ts +++ b/packages/lib/src/io.ts @@ -138,7 +138,7 @@ export function onInterrupt(cleanup: () => void): () => void { * rejects with an ExecError that `absent` accepts, the error otherwise. By * default any exit is that answer (`git show` of a path the commit lacks, a * check on a host); a read whose tool fails for other reasons too (a registry - * that refuses the login, a sidecar that does not answer) names its own. A + * that refuses the login, a host that does not answer) names its own. A * tool that could not start at all is never "not there". */ export async function orAbsent( diff --git a/templates/repo-operations/files/.github/workflows/{% if ci_strategy == 'hybrid' or ci_registry == 'own' %}housekeeping.yml{% endif %}.jinja b/templates/repo-operations/files/.github/workflows/{% if ci_strategy == 'hybrid' %}housekeeping.yml{% endif %}.jinja similarity index 100% rename from templates/repo-operations/files/.github/workflows/{% if ci_strategy == 'hybrid' or ci_registry == 'own' %}housekeeping.yml{% endif %}.jinja rename to templates/repo-operations/files/.github/workflows/{% if ci_strategy == 'hybrid' %}housekeeping.yml{% endif %}.jinja diff --git a/templates/repo-turbo/files/.github/workflows/{% if not publishes_packages and ci_registry == 'ghcr' %}housekeeping.yml{% endif %}.jinja b/templates/repo-turbo/files/.github/workflows/{% if not publishes_packages and ci_registry == 'ghcr' %}housekeeping.yml{% endif %}.jinja deleted file mode 100644 index f911e7d4..00000000 --- a/templates/repo-turbo/files/.github/workflows/{% if not publishes_packages and ci_registry == 'ghcr' %}housekeeping.yml{% endif %}.jinja +++ /dev/null @@ -1,28 +0,0 @@ -{% raw %}name: housekeeping - -# Generated from plexus-ms/tooling, templates/repo-turbo: edit the template, never this file. -# The retention of the candidates this repo leaves in the forge's registry (§ 8 PLX-Delivery). - -on: - schedule: - - cron: '41 4 * * *' - workflow_dispatch: - inputs: - dry_run: - description: Only list what would be deleted - type: boolean - default: false - -permissions: - contents: read - # Mounted here, not in the operations repo: only this repo's own token may delete versions of its packages. - packages: write - -jobs: - housekeeping: - uses: plexus-ms/tooling/.github/workflows/_housekeeping.yml@0.133.0 - with: - strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - registry: ghcr - dry-run: ${{ inputs.dry_run || false }} -{% endraw %} \ No newline at end of file From ee09fd1219f4d70658ddaccd90b25aa8ed4205ae Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 23:58:35 +0100 Subject: [PATCH 155/194] The templates and the housekeeping workflow stop asking about the candidate registry Removes the question ci_registry from repo-turbo and repo-operations, the app repo's housekeeping mount (it only pruned candidates), and the registry input, the vault read and the rotate step of the reusable housekeeping workflow. The operations repo's housekeeping stays for the hybrid instance sweep alone; the cli-ci pin of its mise.toml follows hybrid only. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/_housekeeping.yml | 38 +++---------------- ...ybrid' %}housekeeping.yml{% endif %}.jinja | 4 +- .../repo-operations/files/mise.toml.jinja | 2 +- templates/repo-operations/template.yml | 8 ---- templates/repo-turbo/template.yml | 9 ----- 5 files changed, 8 insertions(+), 53 deletions(-) diff --git a/.github/workflows/_housekeeping.yml b/.github/workflows/_housekeeping.yml index cd7b9b31..c6e50237 100644 --- a/.github/workflows/_housekeeping.yml +++ b/.github/workflows/_housekeeping.yml @@ -4,16 +4,12 @@ name: _housekeeping # schedule where the thing kept lives. Logic lives in plx-ci # (@plexus-ms/cli-ci, pinned in the caller's mise.toml), never here. # -# hybrid the last layer under the instances: delete every one that is stopped or -# past its death deadline and mail about it; one kept after a missed boot -# is spared, mailed about again after seven days, deleted after fourteen -# registry own the week's buckets: this week's exists, the one from two weeks ago goes -# registry ghcr the candidates of this repo's apps older than thirty days go +# hybrid the last layer under the instances: delete every one that is stopped or +# past its death deadline and mail about it; one kept after a missed boot +# is spared, mailed about again after seven days, deleted after fourteen # -# The instances and the buckets are the tenant's, not one app repo's, so the -# platform repo mounts the first two; the packages are the app repo's, and -# only its own workflow token may delete their versions, so the app repo -# mounts the third. +# The instances are the tenant's, not one app repo's, so the platform repo +# mounts it. on: workflow_call: @@ -27,11 +23,6 @@ on: required: false type: string default: github - registry: - description: "Which retention to run: `own`, the registry buckets; `ghcr`, the candidates of the caller's apps in the forge's registry; `none`, neither." - required: false - type: string - default: none vault: description: The vault CI reads (§ 3 PLX-Secrets). Default -ci. required: false @@ -57,12 +48,11 @@ on: default: '' secrets: op-service-account-token: - description: The vault's service account token; needed under hybrid and with a registry of the tenant's own. + description: The vault's service account token; needed under hybrid. required: false permissions: contents: read - packages: write env: EXO_VERSION: 1.103.2 @@ -130,16 +120,6 @@ jobs: SMTP_USER: op://${{ env.VAULT }}/smtp-relay/username SMTP_PASSWORD: op://${{ env.VAULT }}/smtp-relay/password MAIL_FROM: op://${{ env.VAULT }}/smtp-relay/from - - name: Load the registry's keys from the vault - if: ${{ inputs.registry == 'own' }} - uses: 1password/load-secrets-action@70062d7a876d3eb6334754fa26efd2fbd90c32f2 # v5.0.1 - with: - export-env: true - env: - REGISTRY_ENDPOINT: op://${{ env.VAULT }}/bucket-registry/endpoint - REGISTRY_REGION: op://${{ env.VAULT }}/bucket-registry/region - REGISTRY_ACCESS_KEY: op://${{ env.VAULT }}/bucket-registry/access-key-id - REGISTRY_SECRET_KEY: op://${{ env.VAULT }}/bucket-registry/secret-access-key # On the forge's runners only: the environment image of a slot or an # instance carries it (actions_runners). - name: Install exo @@ -150,9 +130,3 @@ jobs: - name: Sweep the instances if: ${{ inputs.strategy == 'hybrid' }} run: plx-ci ${{ inputs.dry-run && '-n' || '' }} hybrid sweep-instances - - name: Rotate the registry - if: ${{ inputs.registry == 'own' || inputs.registry == 'ghcr' }} - env: - CI_REGISTRY: ${{ inputs.registry }} - GITHUB_TOKEN: ${{ github.token }} - run: plx-ci ${{ inputs.dry-run && '-n' || '' }} registry rotate diff --git a/templates/repo-operations/files/.github/workflows/{% if ci_strategy == 'hybrid' %}housekeeping.yml{% endif %}.jinja b/templates/repo-operations/files/.github/workflows/{% if ci_strategy == 'hybrid' %}housekeeping.yml{% endif %}.jinja index 288c7e2a..cdf27be9 100644 --- a/templates/repo-operations/files/.github/workflows/{% if ci_strategy == 'hybrid' %}housekeeping.yml{% endif %}.jinja +++ b/templates/repo-operations/files/.github/workflows/{% if ci_strategy == 'hybrid' %}housekeeping.yml{% endif %}.jinja @@ -1,7 +1,7 @@ {% raw %}name: housekeeping # Generated from plexus-ms/tooling, templates/repo-operations: edit the template, never this file. -# The daily housekeeping of the tenant's CI: its throwaway instances, its registry buckets (§ 8 PLX-Delivery). +# The daily housekeeping of the tenant's CI: its throwaway instances (§ 8 PLX-Delivery). on: schedule: @@ -15,14 +15,12 @@ on: permissions: contents: read - packages: write jobs: housekeeping: uses: plexus-ms/tooling/.github/workflows/_housekeeping.yml@0.133.0 with: strategy: ${{ vars.CI_STRATEGY || '{% endraw %}{{ ci_strategy }}{% raw %}' }} - registry: {% endraw %}{{ 'own' if ci_registry == 'own' else 'none' }}{% raw %} dry-run: ${{ inputs.dry_run || false }} alerts-email: '{% endraw %}{{ alerts_email }}{% raw %}' secrets: diff --git a/templates/repo-operations/files/mise.toml.jinja b/templates/repo-operations/files/mise.toml.jinja index a883b0d0..bc709659 100644 --- a/templates/repo-operations/files/mise.toml.jinja +++ b/templates/repo-operations/files/mise.toml.jinja @@ -16,7 +16,7 @@ ansible = { version = "latest", uvx = true } # The plx pins are written with each Plexus version, never by the update bot (§ 1 PLX-Updates); # allow_low_downloads only waives npm's young-package heuristics. "npm:@plexus-ms/cli" = { version = "0.133.0", allow_low_downloads = true } -{%- if ci_strategy == 'hybrid' or ci_registry == 'own' %} +{%- if ci_strategy == 'hybrid' %} "npm:@plexus-ms/cli-ci" = { version = "0.133.0", allow_low_downloads = true } {%- endif %} diff --git a/templates/repo-operations/template.yml b/templates/repo-operations/template.yml index 47b3c4b6..2a70de45 100644 --- a/templates/repo-operations/template.yml +++ b/templates/repo-operations/template.yml @@ -26,14 +26,6 @@ questions: - on-prem - hybrid - ci_registry: - type: str - help: "Where the app repos' runs keep the images they build and test (§ 8 PLX-Delivery): ghcr, the forge's registry, nothing to mount here; own, a registry on the tenant's object storage, whose monthly buckets this repo rotates" - choices: - - ghcr - - own - default: "{{ 'ghcr' if ci_strategy == 'github' else 'own' }}" - ci_overlay: type: str help: "How a deploy of a third-party app reaches its host (§ 8 PLX-Delivery): none, as the inventory names it; netbird, over the tenant's overlay, which a job on the forge's runners joins for its length" diff --git a/templates/repo-turbo/template.yml b/templates/repo-turbo/template.yml index 45c956bf..59438d7f 100644 --- a/templates/repo-turbo/template.yml +++ b/templates/repo-turbo/template.yml @@ -39,15 +39,6 @@ questions: - on-prem - hybrid - ci_registry: - type: str - help: "Where the images a run builds and tests live before they are published (§ 8 PLX-Delivery): ghcr, the forge's registry; own, a registry on the tenant's object storage, which also holds Turbo's remote cache" - choices: - - ghcr - - own - default: "{{ 'ghcr' if ci_strategy == 'github' else 'own' }}" - when: "{{ not publishes_packages }}" - ci_overlay: type: str help: "How a deploy reaches the app hosts (§ 8 PLX-Delivery): none, as the inventory names them; netbird, over the tenant's overlay, which a job on the forge's runners joins for its length" From 6adfe08b734108dd7117f0abdb76900a94da6235 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:03:33 +0100 Subject: [PATCH 156/194] newborns: the S3 stand-in and the cache server move to caches.ts, for the pipeline test to start them as the cache test does A move: the cache test imports them and holds what it held. Co-Authored-By: Claude Fable 5.2 --- newborns/caches.ts | 156 +++++++++++++++++++++++++++++++++++ newborns/turbo-cache.test.ts | 128 ++-------------------------- 2 files changed, 164 insertions(+), 120 deletions(-) create mode 100644 newborns/caches.ts diff --git a/newborns/caches.ts b/newborns/caches.ts new file mode 100644 index 00000000..a09a8cfc --- /dev/null +++ b/newborns/caches.ts @@ -0,0 +1,156 @@ +// Turbo's remote caches for the newborn tests, as the step turbo-cache of this +// repo starts them in a job: an S3 stand-in, RustFS in a container published +// on a free loopback port, with the tenant acme's buckets, and the cache +// server the step's action starts, its binary fetched at the commit the step +// pins, each from an empty environment and an empty directory so that no +// TURBO_TOKEN reaches it but the one given. Every server's log is kept: what a +// test reads to count the requests a job made. +import { type ChildProcess, spawn } from 'node:child_process'; +import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { arch, platform } from 'node:os'; +import { join } from 'node:path'; +import { sh, tryRun } from './helpers.ts'; + +const WORKSPACE = join(import.meta.dirname, '..'); +const STEP = join(WORKSPACE, '.github', 'actions', 'turbo-cache'); +const RUSTFS = 'rustfs/rustfs:1.0.5'; +const KEY = 'newborn-access'; +const SECRET = 'newborn-secret-not-a-real-one'; + +/** Waits until `url` answers 200, or throws after a minute. */ +async function answers(url: string): Promise { + const until = Date.now() + 60_000; + for (;;) { + try { + if ((await fetch(url)).ok) return; + } catch {} + if (Date.now() > until) throw new Error(`${url} did not answer`); + await new Promise((resolve) => setTimeout(resolve, 250)); + } +} + +/** The S3 stand-in and the cache servers started against it. */ +export interface Caches { + /** The stand-in's address, `http://127.0.0.1:`. */ + s3: string; + /** One S3 call to the stand-in, signed by curl. */ + call(method: string, path: string): Promise; + /** The keys of a bucket below a team, as the server writes them: `/`. */ + keys(bucket: string, team?: string): Promise; + /** A cache server for `bucket` on `port`, with `token` where given; resolves with its log once it answers. */ + serve(bucket: string, port: number, token?: string): Promise; + /** Kills the servers and removes the stand-in. */ + stop(): Promise; +} + +/** The server's binary for this machine, at the commit of the action the step pins, into `dir`. */ +async function fetchServer(dir: string): Promise { + const step = readFileSync(join(STEP, 'action.yml'), 'utf8'); + const sha = /uses: brunojppb\/turbo-cache-server@([0-9a-f]{40})/.exec(step)?.[1]; + if (!sha) throw new Error('the step pins no brunojppb/turbo-cache-server by commit'); + // The names the action's own action/util.mjs picks. + const name = platform() === 'darwin' ? `decay-darwin-${arch()}` : `decay-${arch()}`; + const answer = await fetch(`https://raw.githubusercontent.com/brunojppb/turbo-cache-server/${sha}/action/${name}`); + if (!answer.ok) throw new Error(`no server binary ${name} at ${sha}: ${answer.status}`); + const path = join(dir, name); + writeFileSync(path, Buffer.from(await answer.arrayBuffer())); + chmodSync(path, 0o755); + return path; +} + +/** RustFS with `buckets`, and the server's binary, in `dir`. */ +export async function startCaches(dir: string, buckets: string[]): Promise { + const servers: ChildProcess[] = []; + // The container's id, the one line of its kind: a first run pulls the image and prints its progress too. + const started = ( + await sh( + 'docker', + [ + 'run', + '-d', + '--rm', + '-p', + '127.0.0.1::9000', + '-e', + `RUSTFS_ACCESS_KEY=${KEY}`, + '-e', + `RUSTFS_SECRET_KEY=${SECRET}`, + RUSTFS, + ], + dir, + ) + ).match(/^[0-9a-f]{64}$/m); + const container = started?.[0] ?? ''; + const stop = async () => { + for (const child of servers) + try { + if (child.pid) process.kill(-child.pid, 'SIGKILL'); + } catch {} + if (container) await tryRun('docker', ['rm', '-f', container], dir); + }; + try { + if (!container) throw new Error('docker run printed no container id'); + const published = (await sh('docker', ['port', container, '9000/tcp'], dir)).trim().split('\n')[0] ?? ''; + const s3 = `http://${published}`; + const call = (method: string, path: string) => + sh( + 'curl', + ['-fsS', '-X', method, '--aws-sigv4', 'aws:amz:us-east-1:s3', '--user', `${KEY}:${SECRET}`, `${s3}/${path}`], + dir, + ); + const until = Date.now() + 60_000; + const listing = ['-fsS', '-o', '/dev/null', '--aws-sigv4', 'aws:amz:us-east-1:s3', '--user', `${KEY}:${SECRET}`]; + while ((await tryRun('curl', [...listing, `${s3}/`], dir)).ok === false) { + if (Date.now() > until) throw new Error(`the S3 stand-in at ${s3} did not come up`); + await new Promise((resolve) => setTimeout(resolve, 500)); + } + for (const bucket of buckets) await call('PUT', bucket); + const binary = await fetchServer(dir); + return { + s3, + call, + keys: async (bucket, team = 'acme-web') => { + const xml = await call('GET', `${bucket}?list-type=2&prefix=${team}/`); + return [...xml.matchAll(/([^<]*)<\/Key>/g)].map((m) => m[1] ?? ''); + }, + serve: async (bucket, port, token) => { + const cwd = join(dir, `server-${port}`); + mkdirSync(cwd); + const child = spawn(binary, [], { + cwd, + detached: true, + stdio: ['ignore', 'pipe', 'pipe'], + env: { + PATH: '/usr/bin:/bin', + OTEL_SDK_DISABLED: 'true', + PORT: String(port), + S3_ENDPOINT: s3, + S3_REGION: 'us-east-1', + S3_BUCKET_NAME: bucket, + S3_ACCESS_KEY: KEY, + S3_SECRET_KEY: SECRET, + S3_USE_PATH_STYLE: 'true', + ...(token ? { TURBO_TOKEN: token } : {}), + }, + }); + const log: string[] = []; + child.stdout?.on('data', (chunk: Buffer) => log.push(...chunk.toString().split('\n').filter(Boolean))); + child.stderr?.on('data', (chunk: Buffer) => log.push(...chunk.toString().split('\n').filter(Boolean))); + servers.push(child); + await answers(`http://127.0.0.1:${port}/management/health`); + return log; + }, + stop, + }; + } catch (error) { + await stop(); + throw error; + } +} + +/** The artifact requests of a server's log. */ +export const requests = (log: string[]) => log.filter((line) => line.includes('/v8/artifacts')); + +/** The requests of a server's log to an artifact, by method: `HEAD`, `GET`, `PUT`. */ +export const artifactMethods = (log: string[]): string[] => + log.flatMap((line) => /"(GET|HEAD|PUT|POST|DELETE) \/v8\/artifacts\/[0-9a-f]+\?/.exec(line)?.[1] ?? []); diff --git a/newborns/turbo-cache.test.ts b/newborns/turbo-cache.test.ts index 0d1e4f9c..9c7f8d51 100644 --- a/newborns/turbo-cache.test.ts +++ b/newborns/turbo-cache.test.ts @@ -21,146 +21,34 @@ // without the step `build` fails. Every case sets or unsets GITHUB_ACTIONS // itself. Needs Docker and the network, as the newborns do. import assert from 'node:assert/strict'; -import { type ChildProcess, spawn } from 'node:child_process'; -import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { readFileSync, writeFileSync } from 'node:fs'; import { createServer } from 'node:http'; -import { arch, platform } from 'node:os'; import { join } from 'node:path'; import { after, before, describe, test } from 'node:test'; +import { type Caches, requests, startCaches } from './caches.ts'; import { born, close, freePort, open, put, relock, sh, tryRun } from './helpers.ts'; const WORKSPACE = join(import.meta.dirname, '..'); const STEP = join(WORKSPACE, '.github', 'actions', 'turbo-cache'); -const RUSTFS = 'rustfs/rustfs:1.0.5'; -const KEY = 'newborn-access'; -const SECRET = 'newborn-secret-not-a-real-one'; const SHARED_BUCKET = 'acme-ci-turbo'; const TRUSTED_BUCKET = 'acme-ci-turbo-trusted'; let here = ''; -let container = ''; -let s3 = ''; -let binary = ''; -const servers: { child: ChildProcess; log: string[] }[] = []; - -/** Waits until `url` answers 200, or throws after a minute. */ -async function answers(url: string): Promise { - const until = Date.now() + 60_000; - for (;;) { - try { - if ((await fetch(url)).ok) return; - } catch {} - if (Date.now() > until) throw new Error(`${url} did not answer`); - await new Promise((resolve) => setTimeout(resolve, 250)); - } -} - -/** One S3 call to the stand-in, signed by curl. */ -const s3call = (method: string, path: string) => - sh( - 'curl', - ['-fsS', '-X', method, '--aws-sigv4', 'aws:amz:us-east-1:s3', '--user', `${KEY}:${SECRET}`, `${s3}/${path}`], - here, - ); +let caches: Caches | undefined; /** The keys of a bucket below a team, as the server writes them: `/`. */ -async function keys(bucket: string, team = 'acme-web'): Promise { - const xml = await s3call('GET', `${bucket}?list-type=2&prefix=${team}/`); - return [...xml.matchAll(/([^<]*)<\/Key>/g)].map((m) => m[1] ?? ''); -} +const keys = (bucket: string, team = 'acme-web') => (caches as Caches).keys(bucket, team); -/** The server's binary for this machine, at the commit of the action the step pins. */ -async function fetchServer(): Promise { - const step = readFileSync(join(STEP, 'action.yml'), 'utf8'); - const sha = /uses: brunojppb\/turbo-cache-server@([0-9a-f]{40})/.exec(step)?.[1]; - if (!sha) throw new Error('the step pins no brunojppb/turbo-cache-server by commit'); - // The names the action's own action/util.mjs picks. - const name = platform() === 'darwin' ? `decay-darwin-${arch()}` : `decay-${arch()}`; - const answer = await fetch(`https://raw.githubusercontent.com/brunojppb/turbo-cache-server/${sha}/action/${name}`); - if (!answer.ok) throw new Error(`no server binary ${name} at ${sha}: ${answer.status}`); - const path = join(here, name); - writeFileSync(path, Buffer.from(await answer.arrayBuffer())); - chmodSync(path, 0o755); - return path; -} - -/** - * A cache server for `bucket` on `port`, from an empty environment and an empty - * directory, so that no TURBO_TOKEN reaches it but `token`; its log is kept. - */ -async function serve(bucket: string, port: number, token?: string): Promise { - const cwd = join(here, `server-${port}`); - mkdirSync(cwd); - const child = spawn(binary, [], { - cwd, - detached: true, - stdio: ['ignore', 'pipe', 'pipe'], - env: { - PATH: '/usr/bin:/bin', - OTEL_SDK_DISABLED: 'true', - PORT: String(port), - S3_ENDPOINT: s3, - S3_REGION: 'us-east-1', - S3_BUCKET_NAME: bucket, - S3_ACCESS_KEY: KEY, - S3_SECRET_KEY: SECRET, - S3_USE_PATH_STYLE: 'true', - ...(token ? { TURBO_TOKEN: token } : {}), - }, - }); - const log: string[] = []; - child.stdout?.on('data', (chunk: Buffer) => log.push(...chunk.toString().split('\n').filter(Boolean))); - child.stderr?.on('data', (chunk: Buffer) => log.push(...chunk.toString().split('\n').filter(Boolean))); - servers.push({ child, log }); - await answers(`http://127.0.0.1:${port}/management/health`); - return log; -} - -/** The artifact requests of a server's log. */ -const requests = (log: string[]) => log.filter((line) => line.includes('/v8/artifacts')); +/** A cache server for `bucket` on `port`, with `token` where given; its log. */ +const serve = (bucket: string, port: number, token?: string) => (caches as Caches).serve(bucket, port, token); before(async () => { here = await open('turbo-cache'); - // The container's id, the one line of its kind: a first run pulls the image and prints its progress too. - const started = ( - await sh( - 'docker', - [ - 'run', - '-d', - '--rm', - '-p', - '127.0.0.1::9000', - '-e', - `RUSTFS_ACCESS_KEY=${KEY}`, - '-e', - `RUSTFS_SECRET_KEY=${SECRET}`, - RUSTFS, - ], - here, - ) - ).match(/^[0-9a-f]{64}$/m); - container = started?.[0] ?? ''; - if (!container) throw new Error('docker run printed no container id'); - const published = (await sh('docker', ['port', container, '9000/tcp'], here)).trim().split('\n')[0] ?? ''; - s3 = `http://${published}`; - const until = Date.now() + 60_000; - const listing = ['-fsS', '-o', '/dev/null', '--aws-sigv4', 'aws:amz:us-east-1:s3', '--user', `${KEY}:${SECRET}`]; - while ((await tryRun('curl', [...listing, `${s3}/`], here)).ok === false) { - if (Date.now() > until) throw new Error(`the S3 stand-in at ${s3} did not come up`); - await new Promise((resolve) => setTimeout(resolve, 500)); - } - await s3call('PUT', SHARED_BUCKET); - await s3call('PUT', TRUSTED_BUCKET); - binary = await fetchServer(); + caches = await startCaches(here, [SHARED_BUCKET, TRUSTED_BUCKET]); }); after(async () => { - for (const { child } of servers) - try { - if (child.pid) process.kill(-child.pid, 'SIGKILL'); - } catch {} - if (container) await tryRun('docker', ['rm', '-f', container], here); + await caches?.stop(); await close(); }); From b6c3d349c9c4cbef26219a3e4b177926ec1a9e32 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:05:27 +0100 Subject: [PATCH 157/194] Test: the plan asks the trusted cache through turbow and gives an app a large job only where a task its job needs is a MISS; what it cannot find out counts as work, and it says why The rule, per app: with a suite, its build or its suite's e2e a MISS; without one and built from the output, its image missing and its build a MISS; with a Dockerfile of its own and no suite, never. Publish still fans out over every app. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/core/plan.test.ts | 39 ++- packages/cli-ci/src/core/planCache.test.ts | 292 +++++++++++++++++++++ 2 files changed, 322 insertions(+), 9 deletions(-) create mode 100644 packages/cli-ci/src/core/planCache.test.ts diff --git a/packages/cli-ci/src/core/plan.test.ts b/packages/cli-ci/src/core/plan.test.ts index d825c15c..86c0b19a 100644 --- a/packages/cli-ci/src/core/plan.test.ts +++ b/packages/cli-ci/src/core/plan.test.ts @@ -63,7 +63,7 @@ test('hashesOf keeps the build hash of each app’s package, and the directory o assert.deepEqual(hashesOf(dryRun, { nope: '@acme/nope', stub: '@acme/stub' }), []); }); -test('readHashes runs the dry run of build with the Turbo the lockfile has, in the environment it is given', async () => { +test('without a turbow, readHashes runs a plain dry run of build and e2e with the Turbo the lockfile has, in the environment it is given', async () => { const seen: { args: string[]; cwd: string }[] = []; const io = fakeIo(REPO, undefined, { npx: (cwd, args) => { @@ -72,9 +72,10 @@ test('readHashes runs the dry run of build with the Turbo the lockfile has, in t }, }); const env = { PLX_PLATFORM: 'linux-x64' }; - assert.deepEqual(await readHashes(new Context({}, io), '/repo', ['website'], env), [ - { app: 'website', hash: '0f2a', suite: 'e2e/website' }, - ]); + assert.deepEqual(await readHashes(new Context({}, io), '/repo', ['website'], env), { + hashes: [{ app: 'website', hash: '0f2a', suite: 'e2e/website' }], + why: 'the checkout has no turbow to name the trusted cache with', + }); assert.deepEqual(seen, [{ cwd: '/repo', args: ['--yes', 'turbo@2.11.13', 'run', 'build', 'e2e', '--dry-run=json'] }]); }); @@ -130,7 +131,7 @@ function forge(holds: string[]) { return { io, asked }; } -test('every app gets a leg: its e2e job runs whatever the registry holds, and publish builds only a missing image', async () => { +test('every app gets a publish leg, and a large job where the plan could not ask the cache and its job’s tasks are needed', async () => { const { io, asked } = forge(['ghcr.io/acme/website:build-0f2a']); const result = await plan(new Context({}, io), '/repo', { apps: ['website', 'my-app', 'solver'], @@ -145,7 +146,7 @@ test('every app gets a leg: its e2e job runs whatever the registry holds, and pu 'digest ghcr.io/acme/solver:build-9e1d', ]); assert.deepEqual(result.legs, [ - // The image is there: its e2e job runs all the same, and publish adds the commit's tag. + // The image is there: publish adds the commit’s tag; its suite still runs, the cache unasked. { app: 'website', hash: '0f2a', @@ -153,11 +154,29 @@ test('every app gets a leg: its e2e job runs whatever the registry holds, and pu suite: 'e2e/website', context: 'output', build: false, + // Nothing asked of the trusted cache: its tasks count as work. + large: true, }, // No suite: its e2e job builds the app into the trusted cache and runs no suite; the image is missing. - { app: 'my-app', hash: 'c51b', runner: 'exo-large-41-my-app-1', suite: '', context: 'output', build: true }, - // A Dockerfile of its own: the image is built from a pruned context, not from the build output. - { app: 'solver', hash: '9e1d', runner: 'exo-large-41-solver-1', suite: '', context: 'pruned', build: true }, + { + app: 'my-app', + hash: 'c51b', + runner: 'exo-large-41-my-app-1', + suite: '', + context: 'output', + build: true, + large: true, + }, + // A Dockerfile of its own and no suite: built from a pruned context, and no large job. + { + app: 'solver', + hash: '9e1d', + runner: 'exo-large-41-solver-1', + suite: '', + context: 'pruned', + build: true, + large: false, + }, ]); assert.equal(result.environment, ''); assert.deepEqual(result.deploys, []); @@ -171,7 +190,9 @@ test('the plan says which images exist and which publish will build', async () = narrated(ctx), [ 'website: ghcr.io/acme/website:build-0f2a exists; publish tags it', + 'website: the trusted cache was not asked; a large job', 'my-app: ghcr.io/acme/my-app:build-c51b is missing; publish builds it', + 'my-app: the trusted cache was not asked; a large job', '', ].join('\n'), ); diff --git a/packages/cli-ci/src/core/planCache.test.ts b/packages/cli-ci/src/core/planCache.test.ts new file mode 100644 index 00000000..6a65f59e --- /dev/null +++ b/packages/cli-ci/src/core/planCache.test.ts @@ -0,0 +1,292 @@ +// The plan asks Turbo's trusted cache, in its dry run, which tasks of an app's +// large job it holds, and gives the app a large job only where there is work. +// The dry runs here hold the shape Turbo 2.11.13 gives a task when a remote +// cache is named, `cache: { local, remote, status, source, timeSaved }`, seen +// against the cache server the step starts; a Turbo that drops or renames it +// fails these tests, and the plan then gives every app its job. +import assert from 'node:assert/strict'; +import type { PassThrough } from 'node:stream'; +import { test } from 'node:test'; +import { Context } from '@plexus-ms/lib'; +import { app, REPO } from '../testing/checkout.ts'; +import { fakeIo, notThere, type Tree } from '../testing/fakeIo.ts'; +import { hashesOf, outputsOf, plan, readHashes } from './plan.ts'; + +type Status = 'HIT' | 'MISS' | undefined; + +/** A task of a dry run with the cache named: its cache status, or no cache field at all where `status` is undefined. */ +function task(id: string, hash: string, command: string, status: Status, extra: object = {}) { + const [pkg] = id.split('#'); + const cache = + status === 'HIT' + ? { local: false, remote: true, status, source: 'REMOTE', timeSaved: 2119 } + : { local: false, remote: false, status, timeSaved: 0 }; + return { taskId: id, package: pkg, hash, command, ...(status ? { cache } : {}), ...extra }; +} + +/** + * The dry run of `build e2e` for website (a suite), my-app (no suite, from the + * output), solver (a Dockerfile of its own, no suite) and worker (a Dockerfile + * of its own, a suite), with the statuses given. + */ +function dryRun(s: { + website?: Status; + websiteE2e?: Status; + myApp?: Status; + solver?: Status; + worker?: Status; + workerE2e?: Status; + nonexistent?: Status; +}) { + return JSON.stringify({ + tasks: [ + task('@acme/website#build', '0f2a', 'next build', s.website), + task('@acme/website-e2e#e2e', 'e2e1', 'playwright test', s.websiteE2e, { + directory: 'e2e/website', + dependencies: ['@acme/website#build'], + }), + // A task the package does not define: always MISS, never work. + task('@acme/website#e2e', 'e2e2', '', s.nonexistent ?? 'MISS', { directory: 'apps/website' }), + task('@acme/my-app#build', 'c51b', 'next build', s.myApp), + task('@acme/my-app#e2e', 'e2e3', '', s.nonexistent ?? 'MISS', { directory: 'apps/my-app' }), + task('@acme/solver#build', '9e1d', 'make', s.solver), + task('@acme/worker#build', '7a7a', 'make', s.worker), + task('@acme/worker-e2e#e2e', 'e2e4', 'node e2e.js', s.workerE2e, { + directory: 'e2e/worker', + dependencies: ['@acme/worker#build'], + }), + ], + }); +} + +const packages = { + website: '@acme/website', + 'my-app': '@acme/my-app', + solver: '@acme/solver', + worker: '@acme/worker', +}; +const run = { runId: '41', attempt: '1' }; + +/** REPO with worker, an app with a Dockerfile of its own, and a turbow at the root unless `turbow` is false. */ +function checkout(turbow = true): Tree { + const tree = structuredClone(REPO); + const repo = tree.repo as Tree; + (repo.apps as Tree).worker = app('@acme/worker', []); + if (turbow) repo.turbow = '#!/bin/sh\n'; + return tree; +} + +/** What a context narrated so far. */ +function narrated(ctx: Context): string { + const chunks: string[] = []; + for (let chunk = (ctx.io.stderr as PassThrough).read(); chunk !== null; chunk = (ctx.io.stderr as PassThrough).read()) + chunks.push(String(chunk)); + return chunks.join(''); +} + +/** The plan of the four apps for a dry run, the forge's registry holding `holds`; the apps that get a large job. */ +async function large(statuses: Parameters[0], holds: string[] = []): Promise { + const io = fakeIo(checkout(), undefined, { + crane: (_cwd, args) => (holds.includes(args[1] ?? '') ? 'sha256:abc' : notThere('crane')), + }); + const result = await plan(new Context({}, io), '/repo', { + apps: Object.keys(packages), + hashes: hashesOf(dryRun(statuses), packages), + strategy: 'github', + prefix: 'ghcr.io/acme', + run, + }); + return result.legs.filter((l) => l.large).map((l) => l.app); +} + +const ALL_HIT = { + website: 'HIT', + websiteE2e: 'HIT', + myApp: 'HIT', + solver: 'HIT', + worker: 'HIT', + workerE2e: 'HIT', +} as const; +const IMAGES = ['website', 'my-app', 'solver', 'worker'].map( + (a) => `ghcr.io/acme/${a}:build-${{ website: '0f2a', 'my-app': 'c51b', solver: '9e1d', worker: '7a7a' }[a]}`, +); + +test('hashesOf reads whether the cache holds an app’s build and its suite’s e2e; a task without a cache field leaves it unknown', () => { + const [website, myApp] = hashesOf(dryRun({ website: 'HIT', websiteE2e: 'MISS', myApp: 'MISS' }), packages); + assert.deepEqual(website?.cached, { build: true, e2e: false }); + // No suite: there is no e2e to hold, which is no work. + assert.deepEqual(myApp?.cached, { build: false, e2e: true }); + // A Turbo whose dry run gives no cache field for a task: unknown, never a hit. + assert.equal(hashesOf(dryRun({ websiteE2e: 'HIT' }), packages)[0]?.cached, undefined); +}); + +test('an app with a suite gets a large job when its build or its suite’s e2e is a MISS, whatever the registry holds', async () => { + assert.deepEqual(await large(ALL_HIT, IMAGES), []); + assert.deepEqual(await large({ ...ALL_HIT, website: 'MISS' }, IMAGES), ['website']); + assert.deepEqual(await large({ ...ALL_HIT, websiteE2e: 'MISS' }, IMAGES), ['website']); +}); + +test('an app without a suite, built from the output, gets a large job only when its image is missing and its build a MISS', async () => { + // Image present: publish tags it, and its build is not needed. + assert.deepEqual(await large({ ...ALL_HIT, myApp: 'MISS' }, IMAGES), []); + const without = IMAGES.filter((i) => !i.includes('/my-app:')); + // Image missing, build a HIT: publish restores it from the trusted cache. + assert.deepEqual(await large(ALL_HIT, without), []); + // Image missing, build a MISS: its large job builds it into the trusted cache for publish. + assert.deepEqual(await large({ ...ALL_HIT, myApp: 'MISS' }, without), ['my-app']); +}); + +test('an app with a Dockerfile of its own and no suite never gets a large job; with a suite, as any app with one', async () => { + assert.deepEqual(await large({ ...ALL_HIT, solver: 'MISS' }, []).then((l) => l.filter((a) => a === 'solver')), []); + assert.deepEqual(await large({ ...ALL_HIT, workerE2e: 'MISS' }, IMAGES), ['worker']); + assert.deepEqual(await large({ ...ALL_HIT, worker: 'MISS' }, IMAGES), ['worker']); +}); + +test('a task the package does not define is no MISS that asks for a large job', async () => { + assert.deepEqual(await large({ ...ALL_HIT, nonexistent: 'MISS' }, IMAGES), []); +}); + +test('what the plan cannot find out counts as work: every task unknown gives each app whose job’s tasks are needed its job', async () => { + // No cache field anywhere: all unknown. my-app's image is there, so its build is not needed; solver has no suite. + assert.deepEqual(await large({}, IMAGES), ['website', 'worker']); + assert.deepEqual(await large({}, []), ['website', 'my-app', 'worker']); +}); + +test('the outputs: the matrix of the large jobs is the apps with work, publish fans out over every app', async () => { + const io = fakeIo(checkout(), undefined, { crane: () => notThere('crane') }); + const result = await plan(new Context({}, io), '/repo', { + apps: Object.keys(packages), + hashes: hashesOf(dryRun({ ...ALL_HIT, website: 'MISS' }), packages), + strategy: 'github', + prefix: 'ghcr.io/acme', + run, + }); + const outputs = outputsOf(result); + assert.deepEqual( + JSON.parse(outputs.matrix).map((l: { app: string }) => l.app), + ['website'], + ); + assert.deepEqual( + JSON.parse(outputs.apps).map((l: { app: string }) => l.app), + ['website', 'my-app', 'solver', 'worker'], + ); + assert.equal(outputs.deploys, '[]'); + assert.equal(outputs.environment, ''); +}); + +/** A checkout's Io whose turbow answers as `turbow` says: its stdout, its stderr, or a failure. */ +function asking(tree: Tree, turbow: { out?: string; err: string; fails?: boolean }, npx: string = dryRun({})) { + const calls: { command: string; args: string[]; env?: NodeJS.ProcessEnv }[] = []; + const io = fakeIo(tree, undefined, { + mktemp: () => '/scratch/plx-ci-turbo', + chmod: () => '', + rm: () => '', + sh: (_cwd, args, _input, env) => { + calls.push({ command: 'sh', args, env }); + // `sh -c 'exec ./turbow "$@" 2>"$0"' …`: turbow's stderr goes to the file. + const file = args[2] ?? ''; + const parts = file.split('/').filter(Boolean); + const name = parts.pop() ?? ''; + let node = tree; + for (const part of parts) { + node[part] ??= {}; + node = node[part] as Tree; + } + node[name] = turbow.err; + return turbow.fails ? undefined : turbow.out; + }, + npx: (_cwd, args) => { + calls.push({ command: 'npx', args }); + return npx; + }, + }); + return { ctx: new Context({}, io), calls }; +} + +const PLATFORM = { PLX_PLATFORM: 'linux-x64', PATH: '/usr/bin' }; + +test('readHashes asks the trusted cache through turbow, with the Turbo the lockfile has first on its PATH', async () => { + const { ctx, calls } = asking(checkout(), { + out: dryRun(ALL_HIT), + err: 'turbow: the trusted remote cache at http://127.0.0.1:8586, team acme-web\n', + }); + const read = await readHashes(ctx, '/repo', ['website', 'my-app'], PLATFORM); + assert.equal(read.why, ''); + assert.deepEqual(read.hashes[0]?.cached, { build: true, e2e: true }); + const [sh] = calls; + assert.deepEqual(sh?.args, [ + '-c', + 'exec ./turbow "$@" 2>"$0"', + '/scratch/plx-ci-turbo/turbow.err', + 'trusted', + 'run', + 'build', + 'e2e', + '--dry-run=json', + ]); + assert.equal(sh?.env?.PATH, '/scratch/plx-ci-turbo:/usr/bin'); + assert.equal(calls.length, 1, 'no second dry run'); +}); + +test('a plan that cannot ask the cache says why in one line and leaves every status unknown', async () => { + const cases: [string, Tree, Parameters[1], RegExp][] = [ + [ + 'a tenant without the bucket', + checkout(), + { out: dryRun({ website: 'MISS' }), err: 'turbow: without a remote cache: the tenant has no trusted bucket\n' }, + /^the tenant has no trusted bucket$/, + ], + [ + 'a job without the step', + checkout(), + { + fails: true, + err: 'turbow: in a job of the forge, build and e2e need the trusted cache server, and this job started none (PLX_TURBO_TRUSTED is unset); they never use the shared one\n', + }, + /this job started none/, + ], + [ + 'a dry run without cache fields', + checkout(), + { out: dryRun({}), err: 'turbow: the trusted remote cache at http://127.0.0.1:8586, team acme-web\n' }, + /^Turbo’s dry run \(turbo@2\.11\.13\) gave no cache status for @acme\/website#build$/, + ], + [ + 'a checkout without turbow', + checkout(false), + { err: '' }, + /^the checkout has no turbow to name the trusted cache with$/, + ], + ]; + for (const [name, tree, turbow, why] of cases) { + const { ctx } = asking(tree, turbow); + const read = await readHashes(ctx, '/repo', ['website'], PLATFORM); + assert.match(read.why, why, name); + assert.equal(read.hashes[0]?.cached, undefined, name); + assert.equal(read.hashes[0]?.hash, '0f2a', name); + } +}); + +test('the plan says what it asked and which apps get a large job', async () => { + const io = fakeIo(checkout(), undefined, { + crane: (_cwd, args) => (IMAGES.includes(args[1] ?? '') ? 'sha256:abc' : notThere('crane')), + }); + const ctx = new Context({}, io); + await plan(ctx, '/repo', { + apps: ['website', 'my-app'], + hashes: hashesOf(dryRun({ ...ALL_HIT, websiteE2e: 'MISS' }), packages), + strategy: 'github', + prefix: 'ghcr.io/acme', + run, + }); + assert.equal( + narrated(ctx), + [ + 'website: ghcr.io/acme/website:build-0f2a exists; publish tags it', + 'website: the trusted cache holds its build, not its suite’s e2e; a large job', + 'my-app: ghcr.io/acme/my-app:build-c51b exists; publish tags it', + 'my-app: the trusted cache holds its build; no large job', + '', + ].join('\n'), + ); +}); From 455ce0d83468cc7f9995e97754cce7a40866e61b Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:05:58 +0100 Subject: [PATCH 158/194] Test: the plan job asks the trusted cache before its plan and installs nothing; the large jobs are the plan's matrix, skipped where it is empty; publish gets every app and runs on its default success Co-Authored-By: Claude Fable 5.2 --- packages/lib/src/pipeline.test.ts | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index 2dcb6d97..e6a716da 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -84,6 +84,10 @@ test('an app repo’s on_push runs test, e2e per app, then publish and deploy, w assert.deepEqual(needsOf(publish).sort(), ['e2e', 'test']); for (const output of ['apps', 'deploys', 'environment']) assert.equal(publish?.with?.[output], `\${{ needs.e2e.outputs.${output} }}`, output); + // Run on the default `success()`: an e2e job whose matrix was empty, every large job skipped by its `if`, ends + // in success, so publish runs and tags; a large job that failed or was cancelled fails or cancels it, and + // publish is skipped (on_push runs of the workflows this replaced show the first; `needs` documents the second). + assert.equal(publish?.if, undefined); // A newer push cancels test and e2e of the older one, never a publish or a deploy. for (const name of ['test', 'e2e']) assert.equal(jobs[name]?.concurrency?.['cancel-in-progress'], true, name); assert.notEqual(publish?.concurrency?.['cancel-in-progress'], true); @@ -175,3 +179,31 @@ test('_publish-deploy.yml publishes on a small runner with the trusted cache, de ); } }); + +test('_e2e.yml: the plan asks the trusted cache, the large jobs are the apps with work, publish gets every app', () => { + const workflow = reusable('_e2e.yml') as ReturnType & { + on: { workflow_call: { outputs: Record } }; + }; + const { plan, e2e, cleanup } = workflow.jobs; + // The trusted cache, before the plan, and nothing else of a cache. + assert.deepEqual(caches(plan), ['trusted']); + const steps = plan?.steps ?? []; + const cacheAt = steps.findIndex((s) => s.uses?.endsWith('/.github/actions/turbo-cache')); + const planAt = steps.findIndex((s) => /plx-ci plan/.test(s.run ?? '')); + assert.ok(cacheAt >= 0 && planAt > cacheAt, 'the cache step precedes the plan'); + // § 5.3: the plan job builds, checks, tests and installs nothing that could bring an output into its tree. + assert.doesNotMatch(runs(plan), /mise run|pnpm (install|i\b)|turbo run/); + // The large jobs: the plan's matrix, skipped as a job where it is empty, since an empty matrix is no job. + assert.equal(e2e?.if, "${{ needs.plan.outputs.matrix != '[]' }}"); + assert.equal( + (e2e as { strategy?: { matrix?: { include?: string } } }).strategy?.matrix?.include, + '${{ fromJSON(needs.plan.outputs.matrix) }}', + ); + assert.match(cleanup?.if ?? '', /needs\.plan\.outputs\.matrix == '\[\]'/); + const instances = steps.find((s) => /hybrid create-instances/.test(s.run ?? '')); + assert.equal(instances?.env?.MATRIX, '${{ steps.plan.outputs.matrix }}'); + // Publish fans out over every app, the ones without a large job among them. + assert.equal(workflow.on.workflow_call.outputs.apps?.value, '${{ jobs.plan.outputs.apps }}'); + const publish = reusable('_publish-deploy.yml').jobs.publish; + assert.match(publish?.if ?? '', /inputs\.apps != '\[\]'/); +}); From 5bf0526a270203bb84e0aedbef127365ffea40c2 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:07:47 +0100 Subject: [PATCH 159/194] Test: the newborn runs each job with its own cache server; a second run gives no app a large job, a spec gives exactly its app one, a change to one app exactly that app, and the plan only sends HEAD to the trusted server Co-Authored-By: Claude Fable 5.2 --- newborns/pipeline.test.ts | 250 ++++++++++++++++++++++++-------------- 1 file changed, 157 insertions(+), 93 deletions(-) diff --git a/newborns/pipeline.test.ts b/newborns/pipeline.test.ts index 16bdcfcc..7c388ee4 100644 --- a/newborns/pipeline.test.ts +++ b/newborns/pipeline.test.ts @@ -1,33 +1,39 @@ // A newborn app repo through its pipeline: the commands the jobs of its // workflows call (_check.yml, _e2e.yml, _publish-deploy.yml and _deploy.yml), // in the order the jobs run and each job from a fresh clone of the repo's -// origin, with its tools installed as a job installs them. The workflows -// themselves run only on the forge; what of them this file stands in for: +// origin, with its tools installed as a job installs them, and each as a job +// of the forge (GITHUB_ACTIONS=true) with the one cache server its job starts. +// The workflows themselves run only on the forge; what of them this file +// stands in for: // -// test mise run test -// plan plx-ci plan --deploy, in the repo's mise environment, with crane -// e2e per app: mise run build , the suite's Chromium, mise run e2e -// publish per app: plx-ci publish , under the strategy github, -// through this machine's Docker, into a registry on loopback +// test mise run test, with the shared cache +// plan plx-ci plan --deploy, in the repo's mise environment, with crane, +// asking the trusted cache which large jobs have work +// e2e per app the plan gives a large job: mise run build , the +// suite's Chromium, mise run e2e , with the trusted cache +// publish per app: plx-ci publish --context , +// with the trusted cache, without BUILDKIT_HOST, so through this +// machine's Docker, into a registry on loopback // deploy per deploy: plx deploy, over an ssh that runs each line here with // bash, into a directory standing in for the host's /opt/stacks, with // this machine's Docker // -// The repo has one app from app-nextjs, `web`, with its E2E suite. Turbo's -// two remote caches are stood in for by one local cache directory that every -// clone shares (TURBO_CACHE_DIR; turbow runs the verbs uncached-remote, as a -// newborn's PLX_TURBO_* are none): what a later job finds there is what an -// earlier one wrote. The first run builds the app in its e2e job, publishes -// the image from a restore of that output under build- and the commit, -// and deploys it healthy. A second run on the same content runs no task, -// every Turbo task a cache hit, finds the image, builds none, and leaves the -// app running. A change to a spec alone runs the suite again and moves no -// build hash: publish builds no image and the deploy restarts nothing. Needs -// Docker and the network, as the newborns do. +// The caches are the cache servers the step turbo-cache starts, against an S3 +// stand-in with the two buckets (caches.ts). The repo has two apps from +// app-nextjs: `web`, with its E2E suite, and `site`, without one. The first +// run gives both a large job, publishes each image from a restore of the +// output its large job built, and deploys `web` healthy. A second run on the +// same content gives no app a large job, builds no image, and leaves `web` +// running; the plan's requests to the trusted server are HEAD requests only. +// A change to a spec alone gives exactly `web` a large job, which runs its +// suite and no build, and publish builds no image. A change to `site` alone +// gives exactly `site` a large job, and publish builds its image. Needs Docker +// and the network, as the newborns do. import assert from 'node:assert/strict'; import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { basename, join } from 'node:path'; import { after, before, test } from 'node:test'; +import { artifactMethods, type Caches, startCaches } from './caches.ts'; import { born, close, freePort, git, open, put, relock, sh, tryRun } from './helpers.ts'; const BROWSERS = join(import.meta.dirname, '..', 'node_modules', '.cache', 'ms-playwright'); @@ -40,8 +46,14 @@ let origin = ''; let registry = ''; let container = ''; let port = 0; -/** Every job's environment beyond the world's: the caches every clone shares, and where the images go. */ +let caches: Caches | undefined; +/** Every job's environment beyond the world's: a job of the forge, and where the images go. */ let env: Record = {}; +/** What the step announces in a job that starts the shared cache, and in one that starts the trusted cache. */ +let shared: Record = {}; +let trusted: Record = {}; +/** The trusted server's log. */ +let trustedLog: string[] = []; const deployments: string[] = []; /** `git` that must succeed. */ @@ -60,6 +72,13 @@ before(async () => { container = started?.[0] ?? ''; if (!container) throw new Error('docker run printed no container id'); registry = (await sh('docker', ['port', container, '5000/tcp'], here)).trim().split('\n')[0] ?? ''; + // The two caches, each a server with a token of its own, as the step starts them in a job. + caches = await startCaches(here, ['acme-ci-turbo', 'acme-ci-turbo-trusted']); + const [sharedPort, trustedPort] = [await freePort(), await freePort()]; + await caches.serve('acme-ci-turbo', sharedPort, 'a-shared-token'); + trustedLog = await caches.serve('acme-ci-turbo-trusted', trustedPort, 'a-trusted-token'); + shared = { PLX_TURBO_SHARED: `http://127.0.0.1:${sharedPort}`, PLX_TURBO_SHARED_TOKEN: 'a-shared-token' }; + trusted = { PLX_TURBO_TRUSTED: `http://127.0.0.1:${trustedPort}`, PLX_TURBO_TRUSTED_TOKEN: 'a-trusted-token' }; // The ssh of a deploy: every line it is given runs here, with bash. const bin = join(here, 'bin'); mkdirSync(bin); @@ -69,10 +88,13 @@ before(async () => { ); chmodSync(join(bin, 'ssh'), 0o755); env = { - TURBO_CACHE_DIR: join(here, 'turbo-cache'), + GITHUB_ACTIONS: 'true', + // A job announces only the cache it starts. + PLX_TURBO_SHARED: '', + PLX_TURBO_TRUSTED: '', PLAYWRIGHT_BROWSERS_PATH: BROWSERS, IMAGE_PREFIX: `${registry}/acme`, - CI_STRATEGY: 'github', + BUILDKIT_HOST: '', PATH: `${bin}:${process.env.PATH}`, }; port = await freePort(); @@ -80,6 +102,7 @@ before(async () => { const repo = await born(join(here, 'web'), ['repo-turbo'], { tenant: 'acme' }); await born(join(repo, 'apps', 'web'), ['app-nextjs'], { name: '@acme/web', profile: 'stateless' }); await born(join(repo, 'e2e', 'web'), ['e2e-playwright'], { app: '@acme/web' }); + await born(join(repo, 'apps', 'site'), ['app-nextjs'], { name: '@acme/site', profile: 'stateless' }); // Where the app deploys in staging: the operations repo's inventory, as the plan reads it. put(here, { 'operations/inventory/host_vars/app-host.yml': @@ -95,17 +118,20 @@ before(async () => { after(async () => { for (const dir of deployments) await tryRun('docker', ['compose', 'down', '--volumes'], dir); if (container) await tryRun('docker', ['rm', '-f', container], here); - for (const tag of ['web']) + for (const tag of ['web', 'site']) await tryRun('sh', ['-c', `docker image ls -q '${registry}/acme/${tag}' | xargs -r docker image rm -f`], here); + await caches?.stop(); await close(); }); let jobs = 0; -/** A fresh clone of the origin at `sha`, its tools installed: the checkout of one job. */ +/** A fresh clone of the origin at `sha`, named as the forge's repo, its tools installed: the checkout of one job. */ async function checkout(sha: string): Promise { const dir = join(here, 'jobs', String(jobs++)); await gitOk(here, 'clone', '-q', origin, dir); await gitOk(dir, 'checkout', '-q', sha); + // The team of the caches is owner-repo, from origin's URL (turbow). + await gitOk(dir, 'remote', 'set-url', 'origin', 'https://github.com/acme/web.git'); await sh('sh', ['-c', 'mise trust -q && mise install -q'], dir); return dir; } @@ -122,20 +148,33 @@ async function step(dir: string, command: string[], extra: Record [...output.matchAll(/Cached:\s+(\d+) cached, (\d+) total/g)].map((m) => [Number(m[1]), Number(m[2])]); +/** The tasks a Turbo dry run of `task` would run, by id: those whose package has the script. */ +async function planned(dir: string, task: string): Promise { + const out = await step(dir, ['mise', 'exec', '--', 'turbo', 'run', task, '--dry=json'], shared); + const dry = JSON.parse(out.slice(out.indexOf('{'))); + return dry.tasks + .filter((t: { command: string }) => t.command !== '') + .map((t: { taskId: string }) => t.taskId) + .sort(); +} + interface Leg { app: string; hash: string; suite: string; context: string; build: boolean; + large: boolean; } interface Run { test: string; plan: { legs: Leg[]; deploys: { app: string; host: string; image: string }[]; environment: string }; - build: string; - e2e: string; - published: { built: boolean; tags: string[]; digest?: string }; + /** The methods of the plan's requests to the trusted server's artifacts. */ + asked: string[]; + /** The output of each large job, by app. */ + large: Record; + published: Record; deployed: { healthy: boolean; unchanged?: boolean; live?: string }; } @@ -143,34 +182,45 @@ interface Run { async function pipeline(sha: string): Promise { const ci = { GITHUB_SHA: sha, GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'develop' }; const testJob = await checkout(sha); - const test = await step(testJob, ['mise', 'run', 'test']); + const test = await step(testJob, ['mise', 'run', 'test'], shared); // The test job needs no built app (§ 1.5 of the verbs), a suite's app included. assert.equal(existsSync(join(testJob, 'apps', 'web', '.next', 'standalone')), false, 'the test job built the app'); const planned = await checkout(sha); const inventory = join(here, 'operations', 'inventory'); + const before = trustedLog.length; const planOut = await step( planned, ['mise', 'exec', CRANE, '--', 'plx-ci', '--json', 'plan', '--deploy', '--inventory', inventory], - ci, + { ...ci, ...trusted }, ); + const asked = artifactMethods(trustedLog.slice(before)); const plan = JSON.parse(planOut.slice(planOut.indexOf('{\n'))); assert.equal(plan.environment, 'staging'); - const [leg] = plan.legs as Leg[]; - assert.ok(leg, planOut); - const e2eJob = await checkout(sha); - const build = await step(e2eJob, ['mise', 'run', 'build', leg.app], { NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: KEY }); - await step(join(e2eJob, leg.suite), ['mise', 'exec', '--', 'pnpm', 'exec', 'playwright', 'install', 'chromium']); - const e2e = await step(e2eJob, ['mise', 'run', 'e2e', leg.app]); + const large: Run['large'] = {}; + for (const leg of (plan.legs as Leg[]).filter((l) => l.large)) { + const job = await checkout(sha); + const build = await step(job, ['mise', 'run', 'build', leg.app], { + ...trusted, + NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: KEY, + }); + if (leg.suite) + await step(join(job, leg.suite), ['mise', 'exec', '--', 'pnpm', 'exec', 'playwright', 'install', 'chromium']); + const e2e = await step(job, ['mise', 'run', 'e2e', leg.app], trusted); + large[leg.app] = { build, e2e }; + } - const publishJob = await checkout(sha); - const publishOut = await step( - publishJob, - ['mise', 'exec', CRANE, '--', 'plx-ci', '--json', 'publish', leg.app, leg.hash, sha, '--context', leg.context], - { ...ci, NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: KEY }, - ); - const published = JSON.parse(publishOut.slice(publishOut.indexOf('{\n'))); + const published: Run['published'] = {}; + for (const leg of plan.legs as Leg[]) { + const job = await checkout(sha); + const out = await step( + job, + ['mise', 'exec', CRANE, '--', 'plx-ci', '--json', 'publish', leg.app, leg.hash, sha, '--context', leg.context], + { ...ci, ...(leg.build && leg.context === 'output' ? trusted : {}), NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: KEY }, + ); + published[leg.app] = JSON.parse(out.slice(out.indexOf('{\n'))); + } const [target] = plan.deploys; assert.ok(target, planOut); @@ -198,20 +248,24 @@ async function pipeline(sha: string): Promise { appDir, ]); const deployed = JSON.parse(deployOut.slice(deployOut.indexOf('{\n'))); - return { test, plan, build, e2e, published, deployed }; + return { test, plan, asked, large, published, deployed }; } /** The digest the registry holds under `ref`. */ const digestOf = async (ref: string) => (await sh('mise', ['exec', CRANE, '--', 'crane', 'digest', ref], here)).trim(); -/** The tasks a Turbo dry run of `task` would run, by id: those whose package has the script. */ -async function planned(dir: string, task: string): Promise { - const out = await step(dir, ['mise', 'exec', '--', 'turbo', 'run', task, '--dry=json']); - const dry = JSON.parse(out.slice(out.indexOf('{'))); - return dry.tasks - .filter((t: { command: string }) => t.command !== '') - .map((t: { taskId: string }) => t.taskId) - .sort(); +/** The apps the plan gave a large job. */ +const withJob = (run: Run) => run.plan.legs.filter((l) => l.large).map((l) => l.app); + +/** Commits `edit` to a clone of the origin and pushes it; the new commit. */ +async function push(name: string, edit: (dir: string) => void): Promise { + const clone = join(here, name); + await gitOk(here, 'clone', '-q', origin, clone); + edit(clone); + await gitOk(clone, 'add', '-A'); + await gitOk(clone, 'commit', '--no-verify', '--allow-empty', '-q', '-m', name); + await gitOk(clone, 'push', '-q', 'origin', 'HEAD'); + return gitOk(clone, 'rev-parse', 'HEAD'); } test('check and test build no app, a suite’s app included, and e2e builds the app before its suite', async () => { @@ -224,49 +278,48 @@ test('check and test build no app, a suite’s app included, and e2e builds the let first: Run; let firstSha = ''; -test('the first run builds the app in its e2e job, publishes its image from that output, and deploys it healthy', async () => { +test('the first run gives both apps a large job, publishes each image from the output it built, and deploys web healthy', async () => { firstSha = await gitOk(origin, 'rev-parse', 'HEAD'); first = await pipeline(firstSha); - const [leg] = first.plan.legs; - assert.deepEqual(leg && { ...leg, hash: '' }, { + assert.deepEqual(withJob(first), ['site', 'web']); + const web = first.plan.legs.find((l) => l.app === 'web'); + assert.deepEqual(web && { ...web, hash: '' }, { app: 'web', hash: '', runner: 'ubuntu-latest', suite: 'e2e/web', context: 'output', build: true, + large: true, }); - assert.match(first.e2e, /\d+ passed \(/, 'the suite ran'); - assert.equal(first.published.built, true); - const image = `${registry}/acme/web`; - const digest = await digestOf(`${image}:build-${leg?.hash}`); - assert.equal(await digestOf(`${image}:${firstSha}`), digest, 'build- and the commit are one image'); - assert.equal(first.published.digest, digest); - assert.deepEqual(first.plan.deploys, [{ app: 'web', host: 'ssh://deploy@app-host', image: `${image}:${firstSha}` }]); + assert.match(first.large.web?.e2e ?? '', /\d+ passed \(/, 'the suite ran'); + for (const app of ['web', 'site']) { + assert.equal(first.published[app]?.built, true, app); + const image = `${registry}/acme/${app}`; + const hash = first.plan.legs.find((l) => l.app === app)?.hash; + const digest = await digestOf(`${image}:build-${hash}`); + assert.equal(await digestOf(`${image}:${firstSha}`), digest, `${app}: build- and the commit are one image`); + assert.equal(first.published[app]?.digest, digest); + } + assert.deepEqual(first.plan.deploys, [ + { app: 'web', host: 'ssh://deploy@app-host', image: `${registry}/acme/web:${firstSha}` }, + ]); assert.equal(first.deployed.healthy, true, JSON.stringify(first.deployed)); - const page = await fetch(`http://127.0.0.1:${port}/`); - assert.equal(page.status, 200); + assert.equal((await fetch(`http://127.0.0.1:${port}/`)).status, 200); + // The plan only asks: HEAD requests, no artifact read or written. + assert.ok(first.asked.length > 0, 'the plan asked the trusted server'); + assert.deepEqual([...new Set(first.asked)], ['HEAD']); }); -test('a second run on the same content runs no task and builds no image, and the deploy leaves the app running', async () => { - const clone = join(here, 'push-2'); - await gitOk(here, 'clone', '-q', origin, clone); - await gitOk(clone, 'commit', '--no-verify', '--allow-empty', '-q', '-m', 'the same content again'); - await gitOk(clone, 'push', '-q', 'origin', 'HEAD'); - const sha = await gitOk(clone, 'rev-parse', 'HEAD'); +test('a second run on the same content gives no app a large job, runs no task and builds no image, and the deploy leaves web running', async () => { + const sha = await push('push-2', () => {}); const again = await pipeline(sha); - assert.equal(again.plan.legs[0]?.hash, first.plan.legs[0]?.hash); - assert.equal(again.plan.legs[0]?.build, false, 'the registry holds the image'); - for (const [job, output] of [ - ['test', again.test], - ['build', again.build], - ['e2e', again.e2e], - ] as const) { - const runs = summaries(output); - assert.ok(runs.length > 0, `${job}: ${output}`); - for (const [cached, total] of runs) assert.equal(cached, total, `${job} runs a task:\n${output}`); - } - assert.equal(again.published.built, false); + assert.deepEqual(withJob(again), []); + assert.deepEqual([...new Set(again.asked)], ['HEAD']); + const runs = summaries(again.test); + assert.ok(runs.length > 0, again.test); + for (const [cached, total] of runs) assert.equal(cached, total, `the test job runs a task:\n${again.test}`); + for (const app of ['web', 'site']) assert.equal(again.published[app]?.built, false, app); assert.equal( await digestOf(`${registry}/acme/web:${sha}`), await digestOf(`${registry}/acme/web:${firstSha}`), @@ -276,18 +329,29 @@ test('a second run on the same content runs no task and builds no image, and the assert.equal(again.deployed.unchanged, true, JSON.stringify(again.deployed)); }); -test('a change to a spec alone runs the suite again, and builds no image and restarts nothing', async () => { - const clone = join(here, 'push-3'); - await gitOk(here, 'clone', '-q', origin, clone); - const spec = join(clone, 'e2e', 'web', 'specs', 'home.spec.ts'); - writeFileSync(spec, `${readFileSync(spec, 'utf8')}// a spec edited, and nothing else\n`); - await gitOk(clone, 'commit', '--no-verify', '-q', '-am', 'a spec alone'); - await gitOk(clone, 'push', '-q', 'origin', 'HEAD'); - const run = await pipeline(await gitOk(clone, 'rev-parse', 'HEAD')); - assert.equal(run.plan.legs[0]?.hash, first.plan.legs[0]?.hash, 'the build hash did not move'); - assert.equal(run.plan.legs[0]?.build, false); - for (const [cached, total] of summaries(run.build)) assert.equal(cached, total, run.build); - assert.match(run.e2e, /\d+ passed \(/, 'the suite ran again'); - assert.equal(run.published.built, false); +test('a change to a spec alone gives exactly web a large job, which runs its suite and no build, and builds no image', async () => { + const sha = await push('push-3', (dir) => { + const spec = join(dir, 'e2e', 'web', 'specs', 'home.spec.ts'); + writeFileSync(spec, `${readFileSync(spec, 'utf8')}// a spec edited, and nothing else\n`); + }); + const run = await pipeline(sha); + assert.deepEqual(withJob(run), ['web']); + assert.equal(run.plan.legs.find((l) => l.app === 'web')?.hash, first.plan.legs.find((l) => l.app === 'web')?.hash); + for (const [cached, total] of summaries(run.large.web?.build ?? '')) + assert.equal(cached, total, run.large.web?.build); + assert.match(run.large.web?.e2e ?? '', /\d+ passed \(/, 'the suite ran again'); + for (const app of ['web', 'site']) assert.equal(run.published[app]?.built, false, app); + assert.equal(run.deployed.unchanged, true, JSON.stringify(run.deployed)); +}); + +test('a change to site alone gives exactly site a large job, and publish builds its image', async () => { + const sha = await push('push-4', (dir) => { + const page = join(dir, 'apps', 'site', 'src', 'app', 'page.tsx'); + writeFileSync(page, `${readFileSync(page, 'utf8')}// site edited, and nothing else\n`); + }); + const run = await pipeline(sha); + assert.deepEqual(withJob(run), ['site']); + assert.equal(run.published.site?.built, true); + assert.equal(run.published.web?.built, false); assert.equal(run.deployed.unchanged, true, JSON.stringify(run.deployed)); }); From 7c31d379f91a6f2e5591a5271937e45ae382410f Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:09:08 +0100 Subject: [PATCH 160/194] plx-ci plan asks the trusted cache, in its dry run through the repo's turbow, and gives an app a large job only where a task its job needs is a MISS The plan writes matrix=, the apps with a large job, and apps=, every app, which publish fans out over. Where it cannot ask, every status counts as a MISS and it says why in one line. The header says what of Turbo's dry run this rests on, and in which version it was seen. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/commands/plan.ts | 52 +++--- packages/cli-ci/src/core/plan.ts | 231 +++++++++++++++++++++------ 2 files changed, 209 insertions(+), 74 deletions(-) diff --git a/packages/cli-ci/src/commands/plan.ts b/packages/cli-ci/src/commands/plan.ts index ae03f67a..c809c7e3 100644 --- a/packages/cli-ci/src/commands/plan.ts +++ b/packages/cli-ci/src/commands/plan.ts @@ -1,18 +1,22 @@ -// plx-ci plan [--deploy] [apps...]: the build hashes and the look-ups in the -// forge's registry (§ 8 PLX-Delivery), printed as the matrix the e2e jobs and -// the publishes fan out over, one leg per app, each naming the runner of its -// e2e job from the strategy, its suite, and whether publish builds its image -// or tags the one there, and from what. With --deploy, the environment the -// run deploys into and each app's target there, from a checkout of the -// operations repo's inventory. Launches nothing: under hybrid, `plx-ci hybrid -// create-instances` reads the matrix next. Writes matrix=, deploys= and -// environment= to GITHUB_OUTPUT when that is set. Runs in the repo's mise -// environment, which gives it PLX_PLATFORM as it gives it to the build. -// From the environment: CI_STRATEGY; PLX_PLATFORM; IMAGE_PREFIX or -// GITHUB_REPOSITORY, where the images live; GITHUB_RUN_ID and -// GITHUB_RUN_ATTEMPT (they name the instances under hybrid); for --deploy -// GITHUB_EVENT_NAME, GITHUB_REF_NAME and GITHUB_SHA. crane on the PATH, -// logged in to the forge's registry. +// plx-ci plan [--deploy] [apps...]: the build hashes, the look-ups in the +// forge's registry and what the trusted cache holds (§ 8 PLX-Delivery), +// printed as one leg per app: whether it gets a large job, its e2e job, and +// the runner of that job from the strategy, its suite, and whether publish +// builds its image or tags the one there, and from what. The cache is asked +// through the repo's turbow, so in a job of the forge the plan's job starts +// the trusted cache first (core/plan.ts says how, and what it does when it +// cannot ask, in one line). With --deploy, the environment the run deploys +// into and each app's target there, from a checkout of the operations repo's +// inventory. Launches nothing: under hybrid, `plx-ci hybrid create-instances` +// reads the matrix next. Writes to GITHUB_OUTPUT, when that is set, matrix=, +// the legs with a large job, apps=, every leg, which publish fans out over, +// deploys= and environment=. Runs in the repo's mise environment, which gives +// it PLX_PLATFORM as it gives it to the build. From the environment: +// CI_STRATEGY; PLX_PLATFORM; PLX_TURBO_TRUSTED and its token, as turbow reads +// them; IMAGE_PREFIX or GITHUB_REPOSITORY, where the images live; +// GITHUB_RUN_ID and GITHUB_RUN_ATTEMPT (they name the instances under +// hybrid); for --deploy GITHUB_EVENT_NAME, GITHUB_REF_NAME and GITHUB_SHA. +// crane on the PATH, logged in to the forge's registry. // // plx-ci --json plan // plx-ci plan --deploy --inventory operations/inventory @@ -20,7 +24,7 @@ import { appendFileSync } from 'node:fs'; import { resolve } from 'node:path'; import { readDeployTargets, targetsIn } from '@plexus-ms/lib'; import type { Command } from 'commander'; -import { appsOf, environmentOf, plan, readHashes } from '../core/plan.ts'; +import { appsOf, environmentOf, outputsOf, plan, readHashes } from '../core/plan.ts'; import { contextOf } from '../program.ts'; import { imagePrefix, need, settings, withStrategy } from './shared.ts'; @@ -51,9 +55,12 @@ export function register(program: Command): void { const environment = opts.deploy ? environmentOf(env.GITHUB_EVENT_NAME ?? '', env.GITHUB_REF_NAME ?? '', opts.environment) : ''; + const { hashes, why } = await readHashes(ctx, dir, all); + if (why) + ctx.say(`the plan could not ask the trusted cache, so every task it would ask about counts as work: ${why}`); const result = await plan(ctx, dir, { apps: all, - hashes: await readHashes(ctx, dir, all), + hashes, strategy: s.strategy, prefix: imagePrefix(), // Only hybrid names anything after the run: its instances. @@ -73,7 +80,7 @@ export function register(program: Command): void { [ ...r.legs.map( (l) => - `e2e ${l.app} ${l.hash} ${l.suite || '(no suite)'} ${l.runner}; publish ${l.build ? `builds from ${l.context === 'output' ? 'the build output' : 'a pruned context'}` : 'tags'}`, + `${l.large ? `e2e ${l.runner}` : 'no e2e'} ${l.app} ${l.hash} ${l.suite || '(no suite)'}; publish ${l.build ? `builds from ${l.context === 'output' ? 'the build output' : 'a pruned context'}` : 'tags'}`, ), ...r.deploys.map((l) => `deploy ${l.app} ${l.host} ${l.image}`), ].join('\n'), @@ -81,12 +88,9 @@ export function register(program: Command): void { if (env.GITHUB_OUTPUT) appendFileSync( env.GITHUB_OUTPUT, - [ - `matrix=${JSON.stringify(result.legs)}`, - `deploys=${JSON.stringify(result.deploys)}`, - `environment=${result.environment}`, - '', - ].join('\n'), + `${Object.entries(outputsOf(result)) + .map(([name, value]) => `${name}=${value}`) + .join('\n')}\n`, ); }); } diff --git a/packages/cli-ci/src/core/plan.ts b/packages/cli-ci/src/core/plan.ts index b0ec94f6..2344c7f7 100644 --- a/packages/cli-ci/src/core/plan.ts +++ b/packages/cli-ci/src/core/plan.ts @@ -1,25 +1,52 @@ // The plan of a run (§ 8 PLX-Delivery): every app's build hash from one Turbo -// dry run, and a look-up of `build-` in the forge's registry, which -// leaves one leg per app. Every app's leg runs its e2e job, whatever the -// registry holds: a suite or a test file is no input of the app's build, so -// only Turbo's cache in that job knows whether there is anything to run. What -// the registry decides is publish's share of the leg: `build`, the image is -// missing and publish makes it, or the image is there and publish adds the -// commit's tag. A leg also says what publish makes the image from, `output`, -// the directory the app's build leaves (an app from app-nextjs, by its -// marker), or `pruned`, a pruned context its Dockerfile builds itself from (§ -// 4 PLX-Delivery), which publish is handed; and the directory of the app's -// E2E suite, empty for none, for its e2e job's browser. A suite is what -// `mise run e2e ` runs: a package whose e2e task Turbo has wait for the -// app's build, read from the same dry run, of `build` and `e2e`; the e2e -// tasks' hashes are not used. Each leg names the runner of its e2e job, from -// the strategy: the forge's, a large slot, or, under hybrid, the one label of -// an instance `hybrid create-instances` then creates for it. With a deploy -// asked for, the plan also says which environment the run deploys into and -// where each app deploys there, from the operations repo's inventory. The -// plan decides and launches nothing: its result is the matrices the jobs fan -// out over. No test hash is computed and nothing records that an image was -// tested: that publish follows the e2e job is the order of the jobs. +// dry run, a look-up of `build-` in the forge's registry, and, from the +// same dry run with the trusted cache named, whether the cache holds the +// tasks an app's large job would run. That leaves one leg per app, which +// publish fans out over: `build`, the image is missing and publish makes it, +// or the image is there and publish adds the commit's tag; what publish makes +// it from, `output`, the directory the app's build leaves (an app from +// app-nextjs, by its marker), or `pruned`, a pruned context its Dockerfile +// builds itself from (§ 4 PLX-Delivery); the directory of the app's E2E +// suite, empty for none, for the large job's browser; and `large`, whether +// the app gets a large job, its e2e job. A suite is what `mise run e2e ` +// runs: a package whose e2e task Turbo has wait for the app's build. +// +// An app's large job has work when a task it would run is a MISS in the +// trusted cache and its result is needed. The suite's e2e, where the app has a +// suite, is always needed; the app's build output is needed when the app has +// a suite, which starts it, and when the image is missing and is built from +// the output, which publish restores. So an app with a suite gets a large job +// when its build or its suite's e2e is a MISS; one without a suite, built from +// the output, when its image is missing and its build is a MISS; one with a +// Dockerfile of its own and no suite never, since its publish builds itself. +// A task the package does not define (``) is no MISS that asks +// for a job. What the plan cannot find out counts as work: without a turbow +// to name the cache, with the cache `none` or no cache step, with a dry run +// that gives no cache status, every status is unknown and counts as a MISS, +// and the plan says why in one line. A server that does not answer gives a +// MISS for every task in Turbo's dry run, which is work all the same. +// +// The plan asks the cache the way the repo's verbs reach it: through the +// repo's own `./turbow trusted`, which names the server its job announced +// (PLX_TURBO_TRUSTED and its token, the team from origin) in a job of the +// forge, and the shared server elsewhere, as a build there would; with the +// Turbo the lockfile has first on its PATH, run by npx without an install. A +// dry run only asks: it sends a HEAD request per task, beside a status +// request and an empty listing, and restores and writes nothing (seen against +// the cache server the step starts, brunojppb/turbo-cache-server 5.0.4). +// That Turbo's dry run gives each task `cache: { status: 'HIT' | 'MISS' }` +// when a remote cache is named is not in its documentation of `--dry`; it is +// what Turbo 2.11.13 does, and planCache.test.ts holds the shape, so that a +// Turbo that changes it gives every app its job rather than none. +// +// Each leg names the runner of its large job, from the strategy: the forge's, +// a large slot, or, under hybrid, the one label of an instance `hybrid +// create-instances` then creates for it. With a deploy asked for, the plan +// also says which environment the run deploys into and where each app deploys +// there, from the operations repo's inventory. The plan decides and launches +// nothing: its result is the matrices the jobs fan out over. No test hash is +// computed and nothing records that an image was tested: that publish follows +// the e2e jobs is the order of the jobs. // // The hash is the build's own only when the dry run sees what the build sees: // the Turbo the lockfile has, run with no node_modules, and the environment @@ -27,46 +54,67 @@ // app's build hash). Without PLX_PLATFORM the plan refuses: its hash would be // one no build ever has. import type { Context, EnvironmentTargets } from '@plexus-ms/lib'; -import { MARKER_FILE, parseMarkerConfig, UsageError } from '@plexus-ms/lib'; +import { ExecError, MARKER_FILE, parseMarkerConfig, run as step, UsageError, write } from '@plexus-ms/lib'; import { parseAllDocuments } from 'yaml'; import { craneDigest, imageName } from './registry.ts'; import { runnerOf, type Strategy } from './strategy.ts'; -/** One app's build hash, Turbo's hash of its package's build task, and the directory of its E2E suite, empty for none. */ +/** Whether the trusted cache holds an app's build, and its suite's e2e (true where it has no suite: nothing to hold). */ +export interface Cached { + build: boolean; + e2e: boolean; +} + +/** One app's build hash, Turbo's hash of its package's build task, the directory of its E2E suite, and what the cache holds. */ export interface Hash { app: string; hash: string; suite: string; + /** Absent where the dry run said nothing of the cache: every task unknown. */ + cached?: Cached; } /** Turbo's marker for a task whose script the package does not define. */ const NONEXISTENT = ''; +interface DryTask { + taskId: string; + package: string; + hash: string; + command?: string; + directory?: string; + dependencies?: string[]; + cache?: { status?: string }; +} + +/** Whether the dry run says if the cache holds the task. */ +const told = (t: DryTask): boolean => t.cache?.status === 'HIT' || t.cache?.status === 'MISS'; + +/** The tasks of a dry run that exist, and the first of them that has no cache status, if any. */ +function tasksOf(dryRun: string): { tasks: DryTask[]; unknown?: string } { + const tasks = ((JSON.parse(dryRun) as { tasks?: DryTask[] }).tasks ?? []).filter((t) => t.command !== NONEXISTENT); + return { tasks, unknown: tasks.find((t) => !told(t))?.taskId }; +} + /** * The build hashes from Turbo's dry run (`turbo run build e2e --dry-run=json`), - * per app, by its package's name, and the directory of the first package - * whose e2e task waits for that build. + * per app, by its package's name; the directory of the first package whose + * e2e task waits for that build; and whether the cache holds the two, where + * the dry run gives both a cache status. */ export function hashesOf(dryRun: string, packages: Record): Hash[] { - const data = JSON.parse(dryRun) as { - tasks?: { - taskId: string; - package: string; - hash: string; - command?: string; - directory?: string; - dependencies?: string[]; - }[]; - }; - const tasks = (data.tasks ?? []).filter((t) => t.command !== NONEXISTENT); + const { tasks } = tasksOf(dryRun); return Object.entries(packages).flatMap(([app, name]) => { const build = tasks.find((t) => t.package === name && t.taskId.endsWith('#build')); if (!build) return []; const suites = tasks .filter((t) => t.taskId.endsWith('#e2e') && t.dependencies?.includes(build.taskId)) - .map((t) => t.directory ?? '') - .sort(); - return [{ app, hash: build.hash, suite: suites[0] ?? '' }]; + .sort((x, y) => (x.directory ?? '').localeCompare(y.directory ?? '')); + const suite = suites[0]; + const hit = (t: DryTask) => t.cache?.status === 'HIT'; + const known = told(build) && (!suite || told(suite)); + const cached = known ? { cached: { build: hit(build), e2e: suite ? hit(suite) : true } } : {}; + return [{ app, hash: build.hash, suite: suite?.directory ?? '', ...cached }]; }); } @@ -109,13 +157,24 @@ export async function turboOf(ctx: Context, dir: string): Promise { throw new UsageError('pnpm-lock.yaml locks no turbo for the workspace root, which the repo’s verbs run'); } -/** The build hashes and suites of `apps`, from the dry run of the Turbo the lockfile has, in `env`, the repo's mise environment. */ +/** The hashes, and why the plan could not ask the trusted cache, empty where it could. */ +export interface Hashes { + hashes: Hash[]; + why: string; +} + +/** + * The build hashes, suites and cache statuses of `apps`, from one dry run of + * the Turbo the lockfile has, in `env`, the repo's mise environment: through + * the repo's turbow, which names the trusted cache, where the checkout has + * one; else, or where turbow cannot name it, a dry run that asks no cache. + */ export async function readHashes( ctx: Context, dir: string, apps: string[], env: NodeJS.ProcessEnv = process.env, -): Promise { +): Promise { if (!env.PLX_PLATFORM) throw new UsageError( 'PLX_PLATFORM is empty: the plan runs in the repo’s mise environment, as its build does (after `mise install`, or under `mise exec`), or its hashes are ones no build has', @@ -123,8 +182,46 @@ export async function readHashes( const packages: Record = {}; for (const app of apps) packages[app] = await packageName(ctx, dir, app); const turbo = await turboOf(ctx, dir); - const out = await ctx.read('npx', ['--yes', turbo, 'run', 'build', 'e2e', '--dry-run=json'], { cwd: dir, env }); - return hashesOf(out, packages); + const dry = ['run', 'build', 'e2e', '--dry-run=json']; + const unasked = async (why: string): Promise => { + const out = await ctx.read('npx', ['--yes', turbo, ...dry], { cwd: dir, env }); + return { hashes: hashesOf(out, packages).map(({ cached: _, ...hash }) => hash), why }; + }; + try { + await ctx.readFile(`${dir}/turbow`); + } catch { + return unasked('the checkout has no turbow to name the trusted cache with'); + } + // turbow runs `turbo` from the PATH: the lockfile's, through npx, in a directory of its own first. + const shim = ((await ctx.stage(step('mktemp', ['-d', '-t', 'plx-ci-turbo-XXXXXX']))) ?? '').trim(); + const errors = `${shim}/turbow.err`; + await ctx.stage(write(`${shim}/turbo`, `#!/bin/sh\nexec npx --yes ${turbo} "$@"\n`)); + await ctx.stage(step('chmod', ['755', `${shim}/turbo`])); + const said = async () => { + const lines = (await ctx.readFile(errors).catch(() => '')).split('\n'); + return lines.find((l) => l.startsWith('turbow:'))?.replace(/^turbow:\s*/, '') ?? ''; + }; + try { + const out = await ctx.read('sh', ['-c', 'exec ./turbow "$@" 2>"$0"', errors, 'trusted', ...dry], { + cwd: dir, + env: { ...env, PATH: `${shim}:${env.PATH ?? ''}` }, + }); + const line = await said(); + const without = /^without a remote cache: (.*)$/.exec(line)?.[1]; + if (without !== undefined) return { hashes: hashesOf(out, packages).map(({ cached: _, ...h }) => h), why: without }; + const { unknown } = tasksOf(out); + if (unknown !== undefined) + return { + hashes: hashesOf(out, packages), + why: `Turbo’s dry run (${turbo}) gave no cache status for ${unknown}`, + }; + return { hashes: hashesOf(out, packages), why: '' }; + } catch (error) { + if (!(error instanceof ExecError)) throw error; + return unasked((await said()) || `turbow failed: ${error.message.split('\n')[0]}`); + } finally { + await ctx.stage(step('rm', ['-rf', shim])); + } } /** What publish makes an app's image from: the directory its build leaves, or a pruned context its own Dockerfile builds in. */ @@ -165,6 +262,8 @@ export interface Leg { context: ImageContext; /** The forge's registry lacks `build-`: publish builds the image; else it tags the one there. */ build: boolean; + /** The app gets a large job: a task of it is a MISS in the trusted cache, or unknown, and its result is needed. */ + large: boolean; } /** A deploy job: one app, where it deploys in the run's environment, and the image the run publishes. */ @@ -175,7 +274,12 @@ export interface DeployLeg { } /** The runner of each app's e2e job, before the checkout and the registry are read. */ -export function legsOf(apps: string[], hashes: Hash[], strategy: Strategy, run: Run): Omit[] { +export function legsOf( + apps: string[], + hashes: Hash[], + strategy: Strategy, + run: Run, +): Omit[] { return apps.map((app) => { const found = hashes.find((h) => h.app === app); if (!found) throw new UsageError(`no build hash for ${app}; is it an app package of the workspace?`); @@ -214,7 +318,7 @@ export function deployLegsOf( } export interface Plan { - /** One per app: what its e2e job and its publish fan out over. */ + /** One per app: what publish fans out over, and, those with `large`, the large jobs. */ legs: Leg[]; /** The environment the run deploys into, empty for none. */ environment: string; @@ -241,11 +345,11 @@ export async function plan(ctx: Context, dir: string, options: PlanOptions): Pro const ref = `${imageName(prefix, leg.app)}:build-${leg.hash}`; const build = (await craneDigest(ctx, ref)) === undefined; ctx.say(`${leg.app}: ${ref} ${build ? 'is missing; publish builds it' : 'exists; publish tags it'}`); - result.legs.push({ - ...leg, - context: await imageContextOf(ctx, dir, leg.app), - build, - }); + const context = await imageContextOf(ctx, dir, leg.app); + const cached = hashes.find((h) => h.app === leg.app)?.cached; + const large = hasWork({ suite: leg.suite, context, build }, cached); + ctx.say(`${leg.app}: ${holds(leg.suite, cached)}; ${large ? 'a large job' : 'no large job'}`); + result.legs.push({ ...leg, context, build, large }); } if (options.deploy?.environment) { const { environment, targets, sha } = options.deploy; @@ -255,3 +359,30 @@ export async function plan(ctx: Context, dir: string, options: PlanOptions): Pro } return result; } + +/** Whether an app's large job has work (see the top): a task it would run is a MISS, or unknown, and its result is needed. */ +export function hasWork(leg: Pick, cached: Cached | undefined): boolean { + const buildMiss = !cached?.build; + if (leg.suite) return buildMiss || !cached?.e2e; + return leg.context === 'output' && leg.build && buildMiss; +} + +/** What the trusted cache holds of an app, as the plan says it. */ +function holds(suite: string, cached: Cached | undefined): string { + if (!cached) return 'the trusted cache was not asked'; + if (!suite) return `the trusted cache ${cached.build ? 'holds' : 'lacks'} its build`; + if (cached.build && cached.e2e) return 'the trusted cache holds its build and its suite’s e2e'; + if (cached.build) return 'the trusted cache holds its build, not its suite’s e2e'; + if (cached.e2e) return 'the trusted cache holds its suite’s e2e, not its build'; + return 'the trusted cache holds neither its build nor its suite’s e2e'; +} + +/** The outputs of a plan for the workflow: the large jobs' matrix, every app for publish, the deploys, the environment. */ +export function outputsOf(result: Plan): Record<'matrix' | 'apps' | 'deploys' | 'environment', string> { + return { + matrix: JSON.stringify(result.legs.filter((l) => l.large)), + apps: JSON.stringify(result.legs), + deploys: JSON.stringify(result.deploys), + environment: result.environment, + }; +} From 3a5d0cc4b1d09d234bcb6b8367200f247707df12 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:10:02 +0100 Subject: [PATCH 161/194] _e2e.yml: the plan job starts the trusted cache before its plan, the large jobs are the apps with work, and publish gets every app MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The header says why the plan's dry run is within § 5.3, and what a run without work does. The pipeline test leaves out of its § 5.3 check the trial step that installs tooling's own packages into .plx-ci. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/_e2e.yml | 45 ++++++++++++++++++++++++------- packages/lib/src/pipeline.test.ts | 6 +++-- 2 files changed, 39 insertions(+), 12 deletions(-) diff --git a/.github/workflows/_e2e.yml b/.github/workflows/_e2e.yml index dfc14035..30080da3 100644 --- a/.github/workflows/_e2e.yml +++ b/.github/workflows/_e2e.yml @@ -9,19 +9,35 @@ name: _e2e # pinned in the caller's mise.toml) and the repo's verbs; every step here is # one invocation. # -# plan small every app's build hash from one Turbo dry run, its image -# looked up in the forge's registry, the matrix; under -# hybrid, one instance per app +# plan small every app's build hash from one Turbo dry run with the +# trusted cache named, its image looked up in the forge's +# registry, the matrix of the apps with work; under hybrid, +# one instance per app in it # e2e large per app: `mise run build `, the browser of its suite # where it has one, `mise run e2e ` # cleanup small hybrid only: delete what this run launched # -# Every app gets an e2e job, whatever the registry holds: a suite or a test -# file is no input of the app's build, so only Turbo's cache knows whether -# the job has anything to run, and a run on content it has seen replays both -# verbs from the cache. The build runs first, also for an app without a suite, -# so that the trusted cache holds every app's build output for its publish, -# which restores it from there (_publish-deploy.yml). The job neither checks +# An app gets an e2e job where it has work: the plan asks the trusted cache, +# in its dry run, whether it holds the tasks the job would run, and gives the +# job to an app with a suite whose build or suite's e2e is a MISS, and to an +# app without a suite, built from the output, whose image is missing and whose +# build is a MISS; an app with a Dockerfile of its own and no suite gets none +# (plx-ci's core/plan.ts states the rule). What the plan cannot find out, as +# where the cache step announced no server or a pull request from a fork has +# no secrets, counts as work, and its log says why. A run in which no app has +# work has an empty matrix: the e2e job is skipped by its `if`, since a matrix +# with no entry is no job, the workflow still succeeds, and publish runs and +# tags. The build runs first in the job, also for an app without a suite, so +# that the trusted cache holds the build output its publish restores from there +# (_publish-deploy.yml); the workflow's output `apps` is every app, which +# publish fans out over, the ones without an e2e job among them. +# +# The plan job is within § 5.3: it starts the trusted cache alone, and its dry +# run only asks it, a HEAD request per task, restoring and writing nothing; it +# installs no package, runs no verb, check or test, and builds nothing, so no +# output of any cache enters its tree, and its result is hashes and statuses. +# +# The e2e job neither checks # nor tests (the test job did) and reaches the trusted cache alone, from a # fresh checkout, so that nothing the shared cache supplied enters a build # that is written to the trusted cache or shipped. CI is the trusted cache's @@ -113,7 +129,7 @@ on: outputs: apps: description: Every app planned, with its build hash and what its publish does, JSON; what _publish-deploy.yml publishes. - value: ${{ jobs.plan.outputs.matrix }} + value: ${{ jobs.plan.outputs.apps }} deploys: description: With `deploy`, the deploys of the run, JSON, for _publish-deploy.yml; `[]` without an environment. value: ${{ jobs.plan.outputs.deploys }} @@ -139,6 +155,7 @@ jobs: runs-on: ${{ inputs.strategy == 'github' && 'ubuntu-latest' || 'ci-small' }} outputs: matrix: ${{ steps.plan.outputs.matrix }} + apps: ${{ steps.plan.outputs.apps }} deploys: ${{ steps.plan.outputs.deploys }} environment: ${{ steps.plan.outputs.environment }} steps: @@ -157,6 +174,14 @@ jobs: echo "With the service account." fi - uses: actions/checkout@v7 + # The plan asks the trusted cache which large jobs have work; the step + # announces the server to turbow, which the plan asks through. + - name: Start the trusted cache server + uses: $/.github/actions/turbo-cache + with: + cache: trusted + vault: ${{ inputs.vault }} + op-service-account-token: ${{ secrets.op-service-account-token }} # mise, the repo's pins and its [env] for the later steps, PLX_PLATFORM # among them, also in a trial of unreleased tooling, whose plx-ci comes # first on the PATH: on the forge's runners from mise-action; in the diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index e6a716da..55dbdeaa 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -191,8 +191,10 @@ test('_e2e.yml: the plan asks the trusted cache, the large jobs are the apps wit const cacheAt = steps.findIndex((s) => s.uses?.endsWith('/.github/actions/turbo-cache')); const planAt = steps.findIndex((s) => /plx-ci plan/.test(s.run ?? '')); assert.ok(cacheAt >= 0 && planAt > cacheAt, 'the cache step precedes the plan'); - // § 5.3: the plan job builds, checks, tests and installs nothing that could bring an output into its tree. - assert.doesNotMatch(runs(plan), /mise run|pnpm (install|i\b)|turbo run/); + // § 5.3: the plan job builds, checks, tests and installs nothing that could bring an output into its tree; a trial of + // unreleased tooling installs tooling's own packages into .plx-ci, no package of the repo's. + const own = { ...plan, steps: steps.filter((s) => !(s.if ?? '').includes("inputs.tooling-ref != ''")) }; + assert.doesNotMatch(runs(own), /mise run|pnpm (install|i\b)|turbo run/); // The large jobs: the plan's matrix, skipped as a job where it is empty, since an empty matrix is no job. assert.equal(e2e?.if, "${{ needs.plan.outputs.matrix != '[]' }}"); assert.equal( From 8a234bca055a2e6ba015258e044ae1c149994131 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:12:55 +0100 Subject: [PATCH 162/194] Test: a package without an e2e of its own that waits for an app's build is no suite and no work A mutation that counted tasks survived without it. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/core/planCache.test.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/cli-ci/src/core/planCache.test.ts b/packages/cli-ci/src/core/planCache.test.ts index 6a65f59e..3164c947 100644 --- a/packages/cli-ci/src/core/planCache.test.ts +++ b/packages/cli-ci/src/core/planCache.test.ts @@ -47,6 +47,11 @@ function dryRun(s: { }), // A task the package does not define: always MISS, never work. task('@acme/website#e2e', 'e2e2', '', s.nonexistent ?? 'MISS', { directory: 'apps/website' }), + // A package that waits for website's build and has no e2e of its own: no suite, never work. + task('@acme/docs#e2e', 'e2e5', '', s.nonexistent ?? 'MISS', { + directory: 'docs', + dependencies: ['@acme/website#build'], + }), task('@acme/my-app#build', 'c51b', 'next build', s.myApp), task('@acme/my-app#e2e', 'e2e3', '', s.nonexistent ?? 'MISS', { directory: 'apps/my-app' }), task('@acme/solver#build', '9e1d', 'make', s.solver), From 49dbf9dbe68471228d956ffa8df57c2bcd2279d8 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:13:39 +0100 Subject: [PATCH 163/194] Test: a trusted server that does not answer is a plan that could not ask, and Turbo's warning is the line that says why Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/core/planCache.test.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/packages/cli-ci/src/core/planCache.test.ts b/packages/cli-ci/src/core/planCache.test.ts index 3164c947..ff999bdb 100644 --- a/packages/cli-ci/src/core/planCache.test.ts +++ b/packages/cli-ci/src/core/planCache.test.ts @@ -256,6 +256,28 @@ test('a plan that cannot ask the cache says why in one line and leaves every sta { out: dryRun({}), err: 'turbow: the trusted remote cache at http://127.0.0.1:8586, team acme-web\n' }, /^Turbo’s dry run \(turbo@2\.11\.13\) gave no cache status for @acme\/website#build$/, ], + [ + 'a server that does not answer', + checkout(), + { + out: dryRun({ + website: 'MISS', + websiteE2e: 'MISS', + myApp: 'MISS', + solver: 'MISS', + worker: 'MISS', + workerE2e: 'MISS', + }), + // What Turbo 2.11.13 writes when the named server does not answer; every status is then a MISS. + err: [ + 'turbow: the trusted remote cache at http://127.0.0.1:8586, team acme-web', + ' WARNING • Remote caching unavailable (Could not connect to "http://127.0.0.1:8586")', + ' WARNING Remote artifact cache is temporarily unavailable; retrying after a 30-second cooldown', + '', + ].join('\n'), + }, + /^Remote caching unavailable \(Could not connect to "http:\/\/127\.0\.0\.1:8586"\)$/, + ], [ 'a checkout without turbow', checkout(false), From fbdcc4d38d0a0d592aa452c17d8474665aa510da Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:13:54 +0100 Subject: [PATCH 164/194] plx-ci plan says, from Turbo's warning, that the trusted server did not answer, and counts every task as work Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/core/plan.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/cli-ci/src/core/plan.ts b/packages/cli-ci/src/core/plan.ts index 2344c7f7..ed65657d 100644 --- a/packages/cli-ci/src/core/plan.ts +++ b/packages/cli-ci/src/core/plan.ts @@ -24,7 +24,8 @@ // to name the cache, with the cache `none` or no cache step, with a dry run // that gives no cache status, every status is unknown and counts as a MISS, // and the plan says why in one line. A server that does not answer gives a -// MISS for every task in Turbo's dry run, which is work all the same. +// MISS for every task in Turbo's dry run, which is work all the same; the +// plan reads Turbo's warning for its line. // // The plan asks the cache the way the repo's verbs reach it: through the // repo's own `./turbow trusted`, which names the server its job announced @@ -197,10 +198,11 @@ export async function readHashes( const errors = `${shim}/turbow.err`; await ctx.stage(write(`${shim}/turbo`, `#!/bin/sh\nexec npx --yes ${turbo} "$@"\n`)); await ctx.stage(step('chmod', ['755', `${shim}/turbo`])); - const said = async () => { - const lines = (await ctx.readFile(errors).catch(() => '')).split('\n'); - return lines.find((l) => l.startsWith('turbow:'))?.replace(/^turbow:\s*/, '') ?? ''; - }; + const lines = async () => (await ctx.readFile(errors).catch(() => '')).split('\n'); + const said = async () => (await lines()).find((l) => l.startsWith('turbow:'))?.replace(/^turbow:\s*/, '') ?? ''; + // Turbo's own warning where the server it was named does not answer (2.11.13); its statuses are then all MISS. + const unavailable = async () => + (await lines()).find((l) => /Remote caching unavailable/.test(l))?.replace(/^\s*WARNING\s*•?\s*/, ''); try { const out = await ctx.read('sh', ['-c', 'exec ./turbow "$@" 2>"$0"', errors, 'trusted', ...dry], { cwd: dir, @@ -208,7 +210,8 @@ export async function readHashes( }); const line = await said(); const without = /^without a remote cache: (.*)$/.exec(line)?.[1]; - if (without !== undefined) return { hashes: hashesOf(out, packages).map(({ cached: _, ...h }) => h), why: without }; + const why = without ?? (await unavailable()); + if (why !== undefined) return { hashes: hashesOf(out, packages).map(({ cached: _, ...h }) => h), why }; const { unknown } = tasksOf(out); if (unknown !== undefined) return { From 4289b644479d8d757f9c573ccf792b0823b520e4 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:30:56 +0100 Subject: [PATCH 165/194] A test over the callers the templates render; two comments made whole pipeline.test.ts reads every workflow repo-turbo and repo-operations render and the reusable workflows of this repo: every input and secret a caller passes is declared, and every one required is passed. It fails for registry: own put back into on_pr. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/_housekeeping.yml | 4 +- packages/cli-ci/src/core/userData.ts | 10 ++-- packages/lib/src/pipeline.test.ts | 86 ++++++++++++++++++++++++++++ 3 files changed, 93 insertions(+), 7 deletions(-) diff --git a/.github/workflows/_housekeeping.yml b/.github/workflows/_housekeeping.yml index c6e50237..35cb352e 100644 --- a/.github/workflows/_housekeeping.yml +++ b/.github/workflows/_housekeeping.yml @@ -8,8 +8,8 @@ name: _housekeeping # past its death deadline and mail about it; one kept after a missed boot # is spared, mailed about again after seven days, deleted after fourteen # -# The instances are the tenant's, not one app repo's, so the platform repo -# mounts it. +# The instances are the tenant's, not one app repo's, so the operations repo +# mounts it. Outside `hybrid` the workflow does nothing. on: workflow_call: diff --git a/packages/cli-ci/src/core/userData.ts b/packages/cli-ci/src/core/userData.ts index 4fb9f502..a36b6d75 100644 --- a/packages/cli-ci/src/core/userData.ts +++ b/packages/cli-ci/src/core/userData.ts @@ -237,11 +237,11 @@ write_files: # 1: ExecStopPost runs as root (the +) when the container ends for any # reason, a runner that could not start included. The container is the # one a small slot of a runner host starts (ci-runner-slot): the host's - # network and no Docker socket. It - # mounts no cache: the instance runs this one job and is deleted, so - # nothing is shared between jobs, and what the job installs goes with the - # container. Its only mount, _diag, is the host's /opt/runner/_diag, which - # layer 1b reads and which a kept instance's disk keeps. + # network and no Docker socket. It mounts no cache: the instance runs this + # one job and is deleted, so nothing is shared between jobs, and what the + # job installs goes with the container. Its only mount, _diag, is the + # host's /opt/runner/_diag, which layer 1b reads and which a kept instance's + # disk keeps. - path: /etc/systemd/system/plexus-ci-runner.service content: | [Unit] diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index 2dcb6d97..95b1d2f4 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -9,8 +9,11 @@ import assert from 'node:assert/strict'; import { readdirSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import { test } from 'node:test'; +import { type Answers, readTree, render as renderTrees } from '@plexus-ms/cli-template'; import { parse } from 'yaml'; +import { templatesRoot } from './templatesRoot.ts'; import { pathsOf, renderBundled, textOf } from './testing/bundled.ts'; +import { CHOICES, distinct } from './testing/shapes.ts'; const WORKFLOWS = join(import.meta.dirname, '..', '..', '..', '.github', 'workflows'); @@ -175,3 +178,86 @@ test('_publish-deploy.yml publishes on a small runner with the trusted cache, de ); } }); + +// The callers a template renders against the reusable workflows of this repo: actionlint checks this repo's +// own workflows and never a rendered file, and the test setup has no place that lints rendered files, so the +// YAML of both sides is read here. + +interface Declared { + required?: boolean; + default?: unknown; +} +interface Callable { + on: { workflow_call: { inputs?: Record; secrets?: Record } }; +} + +/** What a caller owes and may pass a reusable workflow: its declared inputs and secrets, and the names it requires. */ +function contractOf(name: string): { + inputs: string[]; + secrets: string[]; + required: string[]; + requiredSecrets: string[]; +} { + const { inputs = {}, secrets = {} } = (parse(readFileSync(join(WORKFLOWS, name), 'utf8')) as Callable).on + .workflow_call; + const owed = (declared: Record) => + Object.entries(declared) + .filter(([, d]) => d.required === true && d.default === undefined) + .map(([key]) => key); + return { + inputs: Object.keys(inputs), + secrets: Object.keys(secrets), + required: owed(inputs), + requiredSecrets: owed(secrets), + }; +} + +test('every caller a template renders passes what the reusable workflow declares, and everything it requires', async () => { + const templates = [ + ['repo-turbo', CHOICES['repo-turbo']], + ['repo-operations', CHOICES['repo-operations']], + ] as const; + let callers = 0; + for (const [repo, choices] of templates) { + const alone = [await readTree(join(templatesRoot(), repo))]; + const beside = [...alone, await readTree(join(templatesRoot(), 'updates'))]; + for (const { answers, result } of distinct(choices, (a: Answers) => renderTrees(beside, a))) { + for (const path of pathsOf(result).filter((p) => p.startsWith('.github/workflows/'))) { + const jobs = (parse(textOf(result, path)) as { jobs: Record }).jobs; + for (const [name, job] of Object.entries(jobs)) { + const workflow = /^plexus-ms\/tooling\/\.github\/workflows\/([^@]+)@/.exec(job.uses ?? '')?.[1]; + if (!workflow) continue; + callers++; + const where = `${repo} ${JSON.stringify(answers)}: ${path} job ${name} calls ${workflow}`; + const contract = contractOf(workflow); + const passed = Object.keys(job.with ?? {}); + assert.deepEqual( + passed.filter((key) => !contract.inputs.includes(key)), + [], + `${where} with an input it does not declare`, + ); + assert.deepEqual( + contract.required.filter((key) => !passed.includes(key)), + [], + `${where} without an input it requires`, + ); + if (typeof job.secrets === 'object' && job.secrets !== null) { + const given = Object.keys(job.secrets); + assert.deepEqual( + given.filter((key) => !contract.secrets.includes(key)), + [], + `${where} with a secret it does not declare`, + ); + assert.deepEqual( + contract.requiredSecrets.filter((key) => !given.includes(key)), + [], + `${where} without a secret it requires`, + ); + } else if (job.secrets !== 'inherit') + assert.deepEqual(contract.requiredSecrets, [], `${where} without a secret it requires`); + } + } + } + } + assert.ok(callers > 20, `${callers} callers read`); +}); From b8deb15bdb4ee818f0893cc2bebf28b8e78925be Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:38:57 +0100 Subject: [PATCH 166/194] removeMarkerKeys takes a key's entry out of a marker and leaves every other byte (test) The failing test first: comments and spacing around the key, values over several lines, the last and the only key, the reserved keys, and what it refuses. Co-Authored-By: Claude Opus 5.5 --- packages/lib/src/markerConfig.test.ts | 83 ++++++++++++++++++++++++++- 1 file changed, 82 insertions(+), 1 deletion(-) diff --git a/packages/lib/src/markerConfig.test.ts b/packages/lib/src/markerConfig.test.ts index c686fc1f..01ea48a5 100644 --- a/packages/lib/src/markerConfig.test.ts +++ b/packages/lib/src/markerConfig.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { parseMarkerConfig, RESERVED_KEYS, setMarkerKeys } from './index.ts'; +import { parseMarkerConfig, RESERVED_KEYS, removeMarkerKeys, setMarkerKeys } from './index.ts'; test('parseMarkerConfig reads version, templates and deviations, and every other key as an answer', () => { const text = [ @@ -258,3 +258,84 @@ test('setMarkerKeys sets a key beside a key that is not a scalar', () => { assert.equal(setMarkerKeys(text, { b: 3 }), '---\n[x]: 1\nb: 3\n---\n'); assert.equal(setMarkerKeys(text, { templates: ['t'], c: 4 }), '---\ntemplates: [t]\n[x]: 1\nb: 2\nc: 4\n---\n'); }); + +test('removeMarkerKeys takes out the entry of each key it removes, and every other byte stays: comments, spacing, the body', () => { + const body = ['', '- `PLX-Repo/Verbs`: a reason.', '', '---', 'ci_registry: in the body, not frontmatter.', '']; + const text = [ + '---', + '# Written by hand; plx keeps what it does not remove.', + 'version: "0.131.0" # moved by plx update only', + 'templates:', + ' - repo-turbo # the base', + '', + '# the registry, decided once', + 'ci_registry: own # our own', + '', + "tenant: 'acme'", + 'deviations: [ PLX-Repo/Verbs ] # see below', + '---', + ...body, + ].join('\n'); + assert.equal( + removeMarkerKeys(text, ['ci_registry']), + [ + '---', + '# Written by hand; plx keeps what it does not remove.', + 'version: "0.131.0" # moved by plx update only', + 'templates:', + ' - repo-turbo # the base', + '', + '# the registry, decided once', + '', + "tenant: 'acme'", + 'deviations: [ PLX-Repo/Verbs ] # see below', + '---', + ...body, + ].join('\n'), + 'the comment above the key and the blank lines around it stay; the comment on its line goes with it', + ); + assert.equal(removeMarkerKeys(text, ['absent']), text, 'a key the marker lacks: nothing to take out'); + assert.equal(removeMarkerKeys(text, []), text); +}); + +test('removeMarkerKeys takes out a value written over several lines whole, and nothing after it', () => { + const list = '---\na: 1\nextra:\n - x\n # inside\n - y\n# about b\nb: 2\n---\n'; + assert.equal(removeMarkerKeys(list, ['extra']), '---\na: 1\n# about b\nb: 2\n---\n', 'a block list'); + const block = '---\na: 1\nnote: |\n one\n two\n\nb: 2\n---\n'; + assert.equal(removeMarkerKeys(block, ['note']), '---\na: 1\n\nb: 2\n---\n', 'a block scalar'); + const folded = '---\nnote: >-\n one\n two\nb: 2\n---\n'; + assert.equal(removeMarkerKeys(folded, ['note']), '---\nb: 2\n---\n', 'a folded one'); + const flow = '---\nextra: [1,\n 2] # c\nb: 2\n---\n'; + assert.equal(removeMarkerKeys(flow, ['extra']), '---\nb: 2\n---\n', 'a flow list over two lines'); + const plain = '---\nnote: some\n continued\nb: 2\n---\n'; + assert.equal(removeMarkerKeys(plain, ['note']), '---\nb: 2\n---\n', 'a plain scalar over two lines'); + const map = '---\nextra:\n x: 1\n y: [2]\nb: 2\n---\n'; + assert.equal(removeMarkerKeys(map, ['extra']), '---\nb: 2\n---\n', 'a block mapping'); + const empty = '---\na:\n# about b\nb: 2\n---\n'; + assert.equal(removeMarkerKeys(empty, ['a']), '---\n# about b\nb: 2\n---\n', 'a key without a value'); +}); + +test('removeMarkerKeys takes out the last key and the only key, and keeps the line breaks of the page', () => { + assert.equal(removeMarkerKeys('---\na: 1\nb: [2]\n---\nbody\n', ['b']), '---\na: 1\n---\nbody\n'); + assert.equal(removeMarkerKeys('---\nb:\n - 2\n---\n', ['b']), '---\n---\n', 'the only key'); + assert.equal(removeMarkerKeys('---\r\na: 1\r\nb: 2\r\nc: 3\r\n---\r\n', ['b']), '---\r\na: 1\r\nc: 3\r\n---\r\n'); + assert.equal( + removeMarkerKeys('---\n a: 1\n b: 2\n---\n', ['a', 'b']), + '---\n---\n', + 'two keys of an indented frontmatter', + ); + assert.deepEqual(parseMarkerConfig(removeMarkerKeys('---\nversion: 0.1.0\nx: 1\n---\n', ['x'])).answers, {}); +}); + +test('removeMarkerKeys removes no reserved key, and refuses what it cannot take out without guessing', () => { + for (const key of RESERVED_KEYS) + assert.throws(() => removeMarkerKeys(`---\n${key}: [a]\n---\n`, [key]), new RegExp(`\`${key}\` is reserved`)); + assert.throws(() => removeMarkerKeys('# just prose', ['a']), /no frontmatter/); + assert.throws(() => removeMarkerKeys('---\n{a: 1}\n---\n', ['a']), /block mapping/); + assert.throws(() => removeMarkerKeys('---\na: 1\n...\n---\n', ['a']), /`\.\.\.`/); + assert.throws(() => removeMarkerKeys('---\n? a\n: 1\n---\n', ['a']), /`a` is not written as `a: value`/); + assert.throws(() => removeMarkerKeys('---\n&k a: 1\n---\n', ['a']), /`a` is not written as `a: value`/); + assert.throws(() => removeMarkerKeys('---\na: &x [1]\nb: *x\n---\n', ['a']), /`a` carries the anchor `x`/); + assert.equal(removeMarkerKeys('---\na: &x [1]\nb: *x\n---\n', ['b']), '---\na: &x [1]\n---\n', 'an alias goes'); + assert.equal(removeMarkerKeys('---\na: !!str 1\nb: 2\n---\n', ['a']), '---\nb: 2\n---\n', 'a tagged value goes'); +}); From e9d07d7e4b6f722717ac0a70bcd14fe0877246e0 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:40:06 +0100 Subject: [PATCH 167/194] removeMarkerKeys: a key's entry taken out of a marker by splicing its text The second writer of a marker's keys beside setMarkerKeys, sharing its reading of the frontmatter and its refusals; a reserved key is never removed. Co-Authored-By: Claude Opus 5.5 --- packages/lib/src/index.ts | 1 + packages/lib/src/marker.ts | 81 +++++++++++++++++++++++++++++++------- 2 files changed, 67 insertions(+), 15 deletions(-) diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index 20ee0a4d..4293623c 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -117,6 +117,7 @@ export { parseMarkerConfig, RESERVED_KEYS, reasonGiven, + removeMarkerKeys, setMarkerKeys, splitFrontmatter, } from './marker.ts'; diff --git a/packages/lib/src/marker.ts b/packages/lib/src/marker.ts index 9f70fd92..50679fe9 100644 --- a/packages/lib/src/marker.ts +++ b/packages/lib/src/marker.ts @@ -19,10 +19,11 @@ // sites.ts's to enforce. A marker without `templates` is valid and renders // nothing. // -// The one writer of a marker's keys is `setMarkerKeys`. It never re-serialises -// the frontmatter, which a human wrote: it splices the text of each key it -// sets, so that comments, order, quoting and blank lines, and the body, stay -// as they were. +// The writers of a marker's keys are `setMarkerKeys`, and `removeMarkerKeys` +// for the answers `plx update` takes out (update.ts). Neither re-serialises the +// frontmatter, which a human wrote: each splices the text of each key it sets +// or removes, so that comments, order, quoting and blank lines, and the body, +// stay as they were. import { isDeepStrictEqual } from 'node:util'; import { Document, @@ -175,6 +176,49 @@ export function setMarkerKeys(text: string, keys: Record): stri return text.slice(0, start) + written + text.slice(start + yaml.length); } +/** + * The marker with the entry of each of the given frontmatter keys taken out, + * and every other byte as it was: the key's line, the comment on it, and the + * lines its value continues on, a block list or block scalar whole; the comment + * lines above the key, the blank lines around it and whatever follows its + * value stay. A key the frontmatter lacks leaves the text as it is. A reserved + * key is never removed: it is refused. + * + * Where a splice could change what it does not remove, it throws rather than + * guess, naming the key: what `setMarkerKeys` refuses of the frontmatter, an + * explicit key (`? a`), a key with an anchor or tag of its own, and a value + * carrying an anchor that an alias refers to. + */ +export function removeMarkerKeys(text: string, keys: readonly string[]): string { + const { yaml, start } = frontmatterOf(text); + let written = yaml; + for (const key of keys) { + if (isReserved(key)) throw new Error(`marker: \`${key}\` is reserved, and plx never removes it`); + written = removeKey(written, key); + } + return text.slice(0, start) + written + text.slice(start + yaml.length); +} + +/** + * One key taken out of a frontmatter's YAML by splicing its text: from the + * start of its line to the end of its value's last line. A block value's + * range ends past its last line's line break already; any other value's line + * ends after it, with what comment it holds. + */ +function removeKey(yaml: string, key: string): string { + const { doc, pairs } = blockMapping(yaml); + const pair = pairs.find((p) => nameOf(p) === key); + if (!pair) return yaml; + const { key: keyNode, value } = pair; + const from = lineStart(yaml, keyNode.range[0]); + if (value === null || yaml.slice(from, keyNode.range[0]).trim() !== '') + throw new Error(`marker: \`${key}\` is not written as \`${key}: value\` on a line of its own; remove it by hand`); + refuseShared(doc, value, key, 'remove'); + const end = value.range[1]; + const to = yaml[end - 1] === '\n' && end > keyNode.range[1] ? end : yaml.indexOf('\n', end) + 1 || yaml.length; + return yaml.slice(0, from) + yaml.slice(to); +} + /** How a written value is serialised: on one line however long, flow lists without padding. */ const STYLE = { lineWidth: 0, flowCollectionPadding: false } as const; @@ -185,6 +229,15 @@ const STYLE = { lineWidth: 0, flowCollectionPadding: false } as const; * is always found by `indexOf('\n', …)`. */ function setKey(yaml: string, key: string, value: unknown, eol: string): string { + const { doc, pairs } = blockMapping(yaml); + const pair = pairs.find((p) => nameOf(p) === key); + return pair + ? replaceValue(yaml, doc, pair, key, value, eol) + : insertKey(yaml, pairs, key, doc.createNode(value), eol); +} + +/** A frontmatter's YAML parsed, and its pairs; throws where it is no block mapping a splice can work on. */ +function blockMapping(yaml: string): { doc: Document; pairs: readonly Pair[] } { const doc = parseDocument(yaml); if (doc.errors.length > 0) throw new Error(`frontmatter is not YAML: ${doc.errors[0]?.message}`); const map = doc.contents; @@ -193,11 +246,7 @@ function setKey(yaml: string, key: string, value: unknown, eol: string): string // `...` at a line's start, alone or before a blank, ends a YAML document: a line after it would start another. if (/^\.\.\.(?:[ \t]|\r?$)/m.test(yaml)) throw new Error('frontmatter ends its YAML document early with `...`; remove that line'); - const pairs = map?.items ?? []; - const pair = pairs.find((p) => nameOf(p) === key); - return pair - ? replaceValue(yaml, doc, pair, key, value, eol) - : insertKey(yaml, pairs, key, doc.createNode(value), eol); + return { doc, pairs: (map as YAMLMap.Parsed | null)?.items ?? [] }; } /** @@ -279,19 +328,21 @@ function replaceValue(yaml: string, doc: Document, pair: Pair, key: string, valu } /** - * Throws when the value is an alias (`*x`), or carries an anchor (`&x`) an - * alias elsewhere refers to: setting it would change another key, or a key - * written as the same value as another. + * Throws when the value carries an anchor (`&x`) an alias elsewhere refers + * to, and, setting it, when it is an alias (`*x`): setting it would change + * another key, or a key written as the same value as another, and removing it + * would leave the alias without its anchor. */ -function refuseShared(doc: Document, value: Node, key: string): void { - if (isAlias(value)) throw new Error(`marker: \`${key}\` is an alias of another value; set it by hand`); +function refuseShared(doc: Document, value: Node, key: string, act: 'set' | 'remove' = 'set'): void { + if (act === 'set' && isAlias(value)) + throw new Error(`marker: \`${key}\` is an alias of another value; set it by hand`); const referred = new Set(); visit(doc, { Alias: (_, alias) => void referred.add(alias.source) }); visit(value, { Node: (_, node) => { if (node.anchor && referred.has(node.anchor)) throw new Error( - `marker: \`${key}\` carries the anchor \`${node.anchor}\`, which an alias refers to; set it by hand`, + `marker: \`${key}\` carries the anchor \`${node.anchor}\`, which an alias refers to; ${act} it by hand`, ); }, }); From 53ecd967f3423b5fcaa8c8806cb581981eb9e0d2 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:43:28 +0100 Subject: [PATCH 168/194] plx update removes the answers of questions the taken version no longer asks or reads (test) The failing tests first, through update as the harness runs it: answers removed from the root, a nested and an operations marker, written with comments, odd spacing and values over several lines, with the rest of the marker byte for byte; a key that never was a question, one asked on both sides, one that moved to a nested marker's template, and one never answered stay; the run, the commit and the pull request name each removed key. And end to end with the real templates: the branch passes the doctor's checks of the markers with no hand edit. Co-Authored-By: Claude Opus 5.5 --- packages/dev/src/ship.integration.test.ts | 235 ++++++++++++++++++++++ 1 file changed, 235 insertions(+) diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index 7329ed04..d92711c4 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -58,6 +58,7 @@ import assert from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; import { chmodSync, + cpSync, existsSync, mkdirSync, mkdtempSync, @@ -75,6 +76,8 @@ import { after, test } from 'node:test'; import { apply, Context, + diagnose, + examine, type FetchVersion, isClean, newSite, @@ -280,6 +283,10 @@ const miseToml = (version: string) => /** A template of the fixture refuses to render: it gains a question without a default (`templatesFor`). */ let REQUIRING: string | undefined; +/** What a test adds to a template's manifest at a version: lines below `questions:`, below `reads:`, and at its top level. */ +let ASKED: (template: string, version: string) => { questions?: string[]; reads?: string[]; top?: string[] } = + () => ({}); + /** * The templates of `version` below `root`: the web repo's root (`repo-turbo`), * its app (`app-nextjs`), and the operations repo (`repo-operations`). After @@ -302,13 +309,17 @@ function templatesFor(version: string, root: string): string { template === 'app-nextjs' ? { 'files/layout.txt': `layout of ${version}\n`, policies: ['policies:', ' layout.txt: born-once'] } : undefined; + const asked = ASKED(template, version); const questions = [ ...(template === 'repo-turbo' && version !== '0.1.0' ? [' lint:', ' default: strict'] : []), ...(REQUIRING === template && version !== '0.1.0' ? [' region:', ' type: str'] : []), + ...(asked.questions ?? []), ]; const manifest = [ `name: ${template}`, ...(questions.length ? ['questions:', ...questions] : []), + ...(asked.reads?.length ? ['reads:', ...asked.reads] : []), + ...(asked.top ?? []), ...(born?.policies ?? []), '', ].join('\n'); @@ -358,6 +369,7 @@ const withOrigin = (path: string, name: string) => { function fixture(name: string, kind: 'engine' | 'uncrossed' = 'engine'): void { WS = join(TMP, `ws-${name}`); REQUIRING = undefined; + ASKED = () => ({}); FETCHED = []; FETCHED_INTO = []; FETCH_FAILS = false; @@ -1801,6 +1813,229 @@ test('update: a born-once file the old render holds and a site lacks stays missi ); }); +// ── a version that no longer asks a question ───────────────────────────────── +// At 0.1.0 the web repo's root template asks `registry`, `blocky`, `note`, +// `unanswered` and `moved`, and reads `borrowed`; at 0.2.0 it asks none of them +// but `kept`, which it asks at both, and `moved` has gone to the app's +// template. The app's template asks `app_only` at 0.1.0 only, the operations +// template `registry` at 0.1.0 only. +const asksLess = (template: string, version: string) => { + const old = version === '0.1.0'; + const ask = (name: string, ...fields: string[]) => [` ${name}:`, ...fields.map((f) => ` ${f}`)]; + if (template === 'repo-turbo') + return { + questions: [ + ...(old + ? [ + ...ask('registry', 'default: ghcr'), + ...ask('blocky', 'type: yaml', 'default: []'), + ...ask('note', 'default: ""'), + ...ask('unanswered', 'default: x'), + ...ask('moved', 'default: m'), + ] + : []), + ...ask('kept', 'default: k'), + ], + reads: old ? [' borrowed: {default: b}'] : [], + }; + if (template === 'app-nextjs') return { questions: old ? ask('app_only', 'default: a') : ask('moved', 'default: m') }; + if (template === 'repo-operations') return { questions: old ? ask('registry', 'default: ghcr') : [] }; + return {}; +}; + +/** The web repo's root marker at 0.1.0: answers to questions 0.1.0 asks and 0.2.0 does not, written as a human might. */ +const ROOT_ASKED_LESS = [ + '---', + 'version: 0.1.0', + 'templates: [repo-turbo]', + '# the registry, decided once', + 'registry: own # ours', + 'kept: mine-too', + 'moved: here', + 'borrowed: mine', + 'blocky:', + ' - a', + ' # between', + ' - b', + 'note: |', + ' line one', + ' line two', + '', + 'mine: hand', + 'deviations: [PLX-Repo/Verbs]', + '---', + '', + '- A tenant repo.', + '- `PLX-Repo/Verbs`: registry: own, a reason in the body.', + '', +].join('\n'); + +/** A fixture whose templates ask less at 0.2.0 (`asksLess`), its markers answering what 0.1.0 asks. */ +function askedLess(name: string): { web: string; platform: string } { + fixture(name); + ASKED = asksLess; + versionCut('0.2.0'); + const web = join(WS, 'acme/web'); + put(join(web, 'PLEXUS.md'), ROOT_ASKED_LESS); + put(join(web, 'apps/site/PLEXUS.md'), marker('templates: [app-nextjs]\napp_only: a1\n')); + commit(web, 'answers 0.1.0 asks for'); + git(web, 'push', '--quiet', 'origin', 'develop'); + const platform = join(WS, 'acme/platform'); + put(join(platform, 'PLEXUS.md'), marker('version: 0.1.0\ntemplates: [repo-operations]\nregistry: ghcr\n')); + commit(platform, 'answers 0.1.0 asks for'); + git(platform, 'push', '--quiet', 'origin', 'main'); + return { web, platform }; +} + +test('update: an answer to a question the version no longer asks or reads leaves the marker, and the run and the pull request name it', async () => { + const { web, platform } = askedLess('update-asked-less'); + const { result, error, out } = await runUpdate({ yes: true }, { repo: web }); + assert.equal(error, undefined, out); + assert.deepEqual(result?.conflicted, [], out); + assert.equal( + `${onVersion('acme-web', '0.2.0', 'PLEXUS.md')}\n`, + [ + '---', + 'version: 0.2.0', + 'templates: [repo-turbo]', + '# the registry, decided once', + 'kept: mine-too', + 'moved: here', + '', + 'mine: hand', + 'deviations: [PLX-Repo/Verbs]', + 'lint: strict', + '---', + '', + '- A tenant repo.', + '- `PLX-Repo/Verbs`: registry: own, a reason in the body.', + '', + ].join('\n'), + 'the entries of registry, borrowed, blocky and note gone, every other byte as it was: the comment above, the blank line after, the key that never was a question, the key asked on both sides, the key that moved to the template of a nested marker, deviations, the body', + ); + assert.equal( + onVersion('acme-web', '0.2.0', 'apps/site/PLEXUS.md'), + marker('templates: [app-nextjs]\n').trimEnd(), + "the nested marker's own answer goes too", + ); + for (const [marker, key] of [ + ['PLEXUS.md', 'registry'], + ['PLEXUS.md', 'borrowed'], + ['PLEXUS.md', 'blocky'], + ['PLEXUS.md', 'note'], + ['apps/site/PLEXUS.md', 'app_only'], + ] as const) { + assert.ok(has(out, `removed from ${marker}, since no template asks or reads it at 0.2.0: ${key}`), out); + assert.match(pull('acme-web', '0.2.0', '.body'), new RegExp(`^- \`${key}\` from \`${marker}\`\\.$`, 'm')); + } + for (const key of ['kept', 'moved', 'mine', 'unanswered', 'version', 'templates', 'deviations']) + assert.doesNotMatch(out, new RegExp(`^ *removed from .*: ${key}$`, 'm'), `${key} is not named`); + assert.match( + pull('acme-web', '0.2.0', '.body'), + /^Removed from the markers, since no template asks or reads them at 0\.2\.0:\n- `blocky` from `PLEXUS\.md`\.\n- `borrowed` from `PLEXUS\.md`\.\n- `note` from `PLEXUS\.md`\.\n- `registry` from `PLEXUS\.md`\.\n- `app_only` from `apps\/site\/PLEXUS\.md`\.$/m, + 'one line per marker and key', + ); + assert.match( + git(remote('acme-web'), 'log', '-1', '--format=%B', 'plexus/0.2.0'), + /^Removed from the markers, since no template asks or reads them at 0\.2\.0:\n- PLEXUS\.md: blocky\n- PLEXUS\.md: borrowed\n- PLEXUS\.md: note\n- PLEXUS\.md: registry\n- apps\/site\/PLEXUS\.md: app_only$/m, + 'and the commit', + ); + assert.deepEqual(result?.clean, ['web', 'web/apps/site'], 'a removed answer needs no hand'); + assert.equal(pull('acme-web', '0.2.0', '.draft'), 'false'); + + const ops = await runUpdate({ yes: true }, { repo: platform }); + assert.equal(ops.error, undefined, ops.out); + assert.equal( + onVersion('acme-platform', '0.2.0', 'PLEXUS.md'), + marker('version: 0.2.0\ntemplates: [repo-operations]\n').trimEnd(), + ); + assert.ok(has(ops.out, 'removed from PLEXUS.md, since no template asks or reads it at 0.2.0: registry'), ops.out); +}); + +test('update: a marker that never answered the question, or holds only keys the version still knows, keeps every byte', async () => { + fixture('update-asked-less-unanswered'); + ASKED = asksLess; + versionCut('0.2.0'); + const web = join(WS, 'acme/web'); + const root = marker('version: 0.1.0\ntemplates: [repo-turbo]\n# ours\nkept: k2 # asked at both\nmine: hand\n'); + put(join(web, 'PLEXUS.md'), root); + commit(web, 'answers 0.2.0 still asks for, and a key of our own'); + git(web, 'push', '--quiet', 'origin', 'develop'); + const { error, out } = await runUpdate({ yes: true }, { repo: web }); + assert.equal(error, undefined, out); + assert.equal( + onVersion('acme-web', '0.2.0', 'PLEXUS.md'), + root.replace('version: 0.1.0', 'version: 0.2.0').replace('mine: hand\n', 'mine: hand\nlint: strict\n').trimEnd(), + ); + assert.equal( + onVersion('acme-web', '0.2.0', 'apps/site/PLEXUS.md'), + marker('templates: [app-nextjs]\nmoved: m\n').trimEnd(), + 'the question that moved to its template is answered there by its default', + ); + assert.doesNotMatch(out, /removed from/); + assert.doesNotMatch(pull('acme-web', '0.2.0', '.body'), /^Removed from the markers/m); + assert.doesNotMatch(git(remote('acme-web'), 'log', '-1', '--format=%B', 'plexus/0.2.0'), /^Removed from/m); +}); + +test('update: a repo of the real templates whose version no longer asks a question takes it, and plx doctor passes on the branch with no hand edit', async () => { + fixture('asked-less-doctor'); + // The version the repo is on: this checkout's templates, with a question repo-turbo asks no more. + const before = join(WS, 'before-templates'); + cpSync(templatesRoot(), before, { recursive: true }); + const manifest = join(before, 'repo-turbo', 'template.yml'); + put( + manifest, + read(manifest).replace('\nquestions:\n', '\nquestions:\n old_choice:\n type: str\n default: ghcr\n\n'), + ); + const dir = join(WS, 'acme', 'repo-turbo'); + await newSite(new Context({ yes: true }, { ...realIo(), stderr: new PassThrough() }), { + dir, + templates: ['repo-turbo'], + answers: { tenant: 'acme', old_choice: 'own' }, + plxVersion: '0.1.0', + root: before, + }); + const born = read(join(dir, 'PLEXUS.md')); + assert.match(born, /^old_choice: own$/m); + put(join(dir, 'PLEXUS.md'), born.replace(/^old_choice: own$/m, '# chosen once\nold_choice: own # ours')); + // An app repo: the version lands on develop. + git(dir, 'checkout', '--quiet', '-B', 'develop'); + commit(dir, 'born, an answer commented'); + withOrigin(dir, 'acme-repo-turbo'); + const start = read(join(dir, 'PLEXUS.md')); + + const fetchBefore: FetchVersion = async (_ctx, version) => { + FETCHED.push(version); + return { plxTemplate: PLX_TEMPLATE, templates: before }; + }; + const { result, error, out } = await runUpdate( + { yes: true }, + { repo: dir, plxVersion: CURRENT, templates: templatesRoot(), fetch: fetchBefore, to: CURRENT }, + ); + assert.equal(error, undefined, out); + assert.deepEqual(FETCHED, ['0.1.0'], out); + assert.deepEqual(result?.conflicted, [], out); + assert.equal( + `${onVersion('acme-repo-turbo', CURRENT, 'PLEXUS.md')}\n`, + start.replace('version: 0.1.0', `version: ${CURRENT}`).replace('old_choice: own # ours\n', ''), + 'the answer and its line gone, the comment above it kept, every other byte as it was', + ); + assert.ok(has(out, `removed from PLEXUS.md, since no template asks or reads it at ${CURRENT}: old_choice`), out); + assert.match(pull('acme-repo-turbo', CURRENT, '.body'), /^- `old_choice` from `PLEXUS\.md`\.$/m); + + const human = join(WS, 'human-doctor'); + git(WS, 'clone', '--quiet', '--branch', `plexus/${CURRENT}`, remote('acme-repo-turbo'), human); + const ctx = new Context({ yes: true }, { ...realIo(), stderr: new PassThrough() }); + const { facts } = await examine(ctx, human, CURRENT); + const report = diagnose(facts); + const findings = report.units.flatMap((u) => u.findings.map((f) => `${u.path}: ${f.requirement ?? ''} ${f.problem}`)); + assert.deepEqual( + findings.filter((f) => /PLEXUS\.md|marker|template/.test(f)), + [], + 'the markers pass the checks against the templates of the version', + ); +}); + // ── a version that moves files from one template to another ──────────────── // The real templates on both sides: a repo born from the repo templates of // 0.132.0 (lib's testing/before.ts, "fetched" as the made-up version 0.1.0) From adfb49df136ff868b88ff54979ba4a65fc42906a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:48:09 +0100 Subject: [PATCH 169/194] plx update removes the answers of questions the taken version no longer asks or reads A key of a marker that a template of its scope owns or reads at the version the repo is on, and none does at the version it takes, is taken out of the marker in the splice that writes the defaults and the version. Which keys, is the doctor's own judgement (siteTemplates.ts, now also as data: strayKeys), run over the manifests of each side, so that the update and the doctor's check of the markers cannot disagree. The run, the commit and the pull request name each key removed, a line per marker and key. Where this plx cannot read a manifest of either side, nothing is removed, and the run says so. The doctor end to end now asserts every check but the verbs, which the harness's mise cannot list. Two tests of the harness fail with this commit and pass again with the next two: the move of the PLX-Updates files into the template updates takes pr_reviewers out of repo-turbo, and this removes the answer before the human adds updates, as the release notes say to. Co-Authored-By: Claude Opus 5.5 --- packages/dev/src/ship.integration.test.ts | 5 +- packages/lib/src/doctor.ts | 9 +-- packages/lib/src/pull.ts | 21 ++++- packages/lib/src/siteTemplates.ts | 46 +++++++++-- packages/lib/src/sync.ts | 14 +++- packages/lib/src/take.ts | 32 ++++++-- packages/lib/src/update.ts | 98 +++++++++++++++++++---- 7 files changed, 180 insertions(+), 45 deletions(-) diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index d92711c4..22d60cf3 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -2029,10 +2029,11 @@ test('update: a repo of the real templates whose version no longer asks a questi const { facts } = await examine(ctx, human, CURRENT); const report = diagnose(facts); const findings = report.units.flatMap((u) => u.findings.map((f) => `${u.path}: ${f.requirement ?? ''} ${f.problem}`)); + // The harness's mise lists no tasks of a real mise.toml, so the verbs are not the doctor's to judge here. assert.deepEqual( - findings.filter((f) => /PLEXUS\.md|marker|template/.test(f)), + findings.filter((f) => !f.includes('PLX-Repo/Verbs mise could not list the tasks')), [], - 'the markers pass the checks against the templates of the version', + 'every other check passes, the markers against the templates of the version among them', ); }); diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index ec469988..e511e9dc 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -68,7 +68,6 @@ // plx doctor ~/dev # every Plexus repo beneath, and its apps import { readdir, realpath } from 'node:fs/promises'; import { basename, dirname, join, relative, resolve } from 'node:path'; -import { readTemplate } from './bundled.ts'; import { APP_SERVICE, type Compose, @@ -83,14 +82,13 @@ import { } from './compose.ts'; import { filesWithConflictMarkers } from './conflicts.ts'; import type { Context } from './context.ts'; -import { engine } from './engine.ts'; import { ExecError } from './io.ts'; import { REQUIREMENT_NAME } from './lints.ts'; import { type Declaration, MARKER_FILE, reasonGiven } from './marker.ts'; import { crossedOver, type Directory, hasMarker, isOperations, type Kind } from './model.ts'; import { appsOf, directoryAt, overview } from './overview.ts'; import { findSites, type MarkerSite, siteAnswers } from './sites.ts'; -import { type Bundled, templateFindings } from './siteTemplates.ts'; +import { type Bundled, bundledAt, templateFindings } from './siteTemplates.ts'; import { bundledIndex } from './standardIndex.ts'; import { resolvedAnswers } from './sync.ts'; import { templatesRoot } from './templatesRoot.ts'; @@ -732,10 +730,7 @@ function bundledTemplates(): Promise { bundled ??= (async () => { const root = templatesRoot(); const names = (await readdir(root, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name); - const trees = await Promise.all( - names.sort().map(async (name) => [name, (await readTemplate(root, name)).tree] as const), - ); - return { trees: new Map(trees), render: (await engine()).render }; + return bundledAt(root, names.sort()); })(); return bundled; } diff --git a/packages/lib/src/pull.ts b/packages/lib/src/pull.ts index e193d539..b1a57d0d 100644 --- a/packages/lib/src/pull.ts +++ b/packages/lib/src/pull.ts @@ -366,16 +366,23 @@ const siteIn = (dir: string): string => (dir === '.' ? 'the root' : dir); const KEPT = (version: string) => `Kept although ${version} drops them, since they were edited here`; +const REMOVED = (version: string) => `Removed from the markers, since no template asks or reads them at ${version}`; + +/** The marker of the site at `dir`, relative to the repo. */ +const markerAt = (dir: string): string => (dir === '.' ? MARKER_FILE : `${dir}/${MARKER_FILE}`); + /** * The message of the commit by which a repo takes the version: its subject, * then for each site the paths left conflicted with their markers and the * files the version drops that were edited here, kept without markers, one - * block each. A later run reads the second kind back (`keptIn`), since no - * marker shows them; the first it finds by the detector. + * block each, and one block of the answers removed from the markers, a line + * per marker and key. A later run reads the second kind back (`keptIn`), since + * no marker shows them; the first it finds by the detector. */ export function commitMessage( version: string, sites: readonly { dir: string; conflicts?: readonly string[]; kept?: readonly string[] }[], + removed: Readonly> = {}, ): string { const block = (head: string, paths: readonly string[] | undefined) => paths && paths.length > 0 ? [`${head}:\n${paths.map((p) => `- ${p}`).join('\n')}`] : []; @@ -385,6 +392,10 @@ export function commitMessage( ...block(`Conflicted, committed with their markers, at ${siteIn(s.dir)}`, s.conflicts), ...block(`${KEPT(version)}, at ${siteIn(s.dir)}`, s.kept), ]), + ...block( + REMOVED(version), + Object.entries(removed).flatMap(([dir, keys]) => keys.map((key) => `${markerAt(dir)}: ${key}`)), + ), ].join('\n\n'); } @@ -420,6 +431,8 @@ export interface PullState { conflicts?: Readonly>; /** By site, the edited files the version drops, kept without markers: no hand needed, but a reviewer is told. */ kept?: Readonly>; + /** By the directory of the marker, the answers removed from it: no hand needed, but a reviewer is told. */ + removed?: Readonly>; /** The root marker names the version, and the `plx` pin does not. */ pin?: PinGap; /** The opening run: the lockfile refresh failed. A later run: run `pnpm install` and commit the lockfile. */ @@ -486,6 +499,9 @@ export function pullBody(p: PullState): string { ? `Ready for review: no tracked file holds a conflict marker, the root marker names ${p.version}, and the root \`${MISE_FILE}\` pins plx at it.${settled.length ? `\n\n${settled.join('\n')}` : ''}` : 'Nothing needs a hand: every site merged clean.'; const kept = Object.entries(p.kept ?? {}).filter(([, paths]) => paths.length > 0); + const removed = Object.entries(p.removed ?? {}).flatMap(([dir, keys]) => + keys.map((key) => `- ${code(key)} from ${code(markerAt(dir))}.`), + ); return [ head, ...(kept.length > 0 @@ -495,6 +511,7 @@ export function pullBody(p: PullState): string { .join('\n')}`, ] : []), + ...(removed.length > 0 ? [`${REMOVED(p.version)}:\n${removed.join('\n')}`] : []), `Plexus ${p.version} (§ 1.5 PLX): the templates at ${p.sites.map(site).join(', ')}, the version in the root marker, the lockfile where manifests moved, and the workflow refs.`, p.note, ].join('\n\n'); diff --git a/packages/lib/src/siteTemplates.ts b/packages/lib/src/siteTemplates.ts index 52969318..03f16894 100644 --- a/packages/lib/src/siteTemplates.ts +++ b/packages/lib/src/siteTemplates.ts @@ -40,8 +40,15 @@ // // Each site is rendered once for both, and the root a second time over the // union of templates only where that differs from its own. +// +// The keys of the first kind are also what `plx update` judges by (update.ts): +// an answer that the templates of the version a repo is on own or read, and +// those of the version it takes do not, is one this check would report once +// the repo is on that version, and the update removes it (`strayKeys`). import { join } from 'node:path'; import type { render, Tree } from '@plexus-ms/cli-template'; +import { readTemplate } from './bundled.ts'; +import { engine } from './engine.ts'; import { MARKER_FILE } from './marker.ts'; import { type MarkerSite, siteAnswers } from './sites.ts'; @@ -55,16 +62,42 @@ export interface Bundled { readonly render: typeof render; } +/** The templates `names` below `root`, each read as `plx new` reads it (bundled.ts); rejects naming one it cannot read. */ +export async function bundledAt(root: string, names: readonly string[]): Promise { + const trees = await Promise.all(names.map(async (name) => [name, (await readTemplate(root, name)).tree] as const)); + return { trees: new Map(trees), render: (await engine()).render }; +} + +/** A key of a marker that no template of the marker's scope owns or reads; `dir` is the marker's site. */ +export interface StrayKey { + dir: string; + key: string; +} + /** The findings of the markers among `sites` against `bundled`. */ export function templateFindings( sites: readonly MarkerSite[], bundled: Bundled, rootAnswers?: Record, ): string[] { - const { keys, answers } = judge(sites, bundled, rootAnswers); + const { stray, answers } = judge(sites, bundled, rootAnswers); + const where = (dir: string) => (dir === '.' ? 'a template that a marker of the repo lists' : 'a template it lists'); + const keys = stray.map( + ({ dir, key }) => + `${join(dir, MARKER_FILE)}: \`${key}\` is neither reserved nor a question or read of ${where(dir)}`, + ); return [...unknownNames(sites, bundled), ...keys, ...answers]; } +/** + * The keys of the markers among `sites` that no template of their scope in + * `bundled` owns or reads, the sites in their order and each site's keys in + * the engine's: the findings of the first kind, as data. + */ +export function strayKeys(sites: readonly MarkerSite[], bundled: Bundled): StrayKey[] { + return judge(sites, bundled, undefined).stray; +} + function unknownNames(sites: readonly MarkerSite[], bundled: Bundled): string[] { const held = [...bundled.trees.keys()].sort().map((name) => `\`${name}\``); return sites.flatMap(({ dir, config }) => @@ -82,12 +115,12 @@ function judge( sites: readonly MarkerSite[], bundled: Bundled, rootAnswers: Record | undefined, -): { keys: string[]; answers: string[] } { +): { stray: StrayKey[]; answers: string[] } { const listed = (site: MarkerSite) => site.config?.templates ?? []; const trees = (names: Iterable) => [...names].flatMap((name) => bundled.trees.get(name) ?? []); const rootConfig = sites.find((s) => s.dir === '.')?.config; const everywhere = [...new Set(sites.flatMap(listed))]; - const keys: string[] = []; + const stray: StrayKey[] = []; const answers = new Set(); for (const site of sites) { const { dir, config } = site; @@ -106,12 +139,9 @@ function judge( } const scope = root ? everywhere : mine; const { unused } = own && scope.length === mine.length ? own : bundled.render(trees(scope), given); - const where = root ? 'a template that a marker of the repo lists' : 'a template it lists'; - for (const key of unused) - if (Object.hasOwn(config.answers, key)) - keys.push(`${join(dir, MARKER_FILE)}: \`${key}\` is neither reserved nor a question or read of ${where}`); + for (const key of unused) if (Object.hasOwn(config.answers, key)) stray.push({ dir, key }); } - return { keys, answers: [...answers] }; + return { stray, answers: [...answers] }; } /** diff --git a/packages/lib/src/sync.ts b/packages/lib/src/sync.ts index e7324ef7..c42ce820 100644 --- a/packages/lib/src/sync.ts +++ b/packages/lib/src/sync.ts @@ -41,6 +41,9 @@ // one splice with its defaults, read when the plan is made: a write of its own // before or after would be lost to the other. It is written whether or not the // root renders anything or is merged, since every site of the repo moves to it. +// The answers a caller names for removal (`update`, never `apply`: those no +// template asks any more, update.ts) are taken out in the same splice +// (`removeMarkerKeys`), which leaves every other byte as it was. // // Performing a plan writes the merges, each site's in turn, then the markers. // A conflicted path is left in the file between the engine's markers, or kept @@ -62,7 +65,7 @@ import { loadTemplate, readTemplate } from './bundled.ts'; import type { Context } from './context.ts'; import { type Plan, write } from './effects.ts'; import { engine } from './engine.ts'; -import { MARKER_FILE, setMarkerKeys } from './marker.ts'; +import { MARKER_FILE, removeMarkerKeys, setMarkerKeys } from './marker.ts'; /** Templates, by name below a root, and the answers to render them with. */ export interface Source { @@ -111,6 +114,8 @@ export interface SyncOptions { siblings?: readonly { dir: string; templates: readonly string[]; answers: Answers }[]; /** The version to write into the root marker, which must be among the sites; none: the version is left as it is. */ version?: string; + /** The answers to take out of the markers, by site directory, each among the sites; none: every key stays. */ + remove?: Readonly>; } /** What planning decided for one site. */ @@ -242,13 +247,16 @@ export async function planSync( const dropped: Record = {}; if (options.version !== undefined && !rootEntry) throw new Error('the version goes into the root marker, and the root is not among the sites'); + const strays = Object.keys(options.remove ?? {}).filter((dir) => !rendered.some((r) => r.site.dir === dir)); + if (strays.length > 0) throw new Error(`answers to remove from ${strays.join(', ')}, which is among no site`); for (const entry of rendered) { const { dir, contextOnly } = entry.site; const defaults = contextOnly ? {} : defaultsOf(entry); const keys = { ...defaults, ...(dir === '.' && options.version !== undefined ? { version: options.version } : {}) }; - if (Object.keys(keys).length > 0) { + const removed = options.remove?.[dir] ?? []; + if (Object.keys(keys).length > 0 || removed.length > 0) { const path = join(repo, dir, MARKER_FILE); - markers.push(write(path, setMarkerKeys(await ctx.readFile(path), keys))); + markers.push(write(path, removeMarkerKeys(setMarkerKeys(await ctx.readFile(path), keys), removed))); } if (contextOnly) continue; const plan = await planMerge(join(repo, dir), entry.old, entry.new); diff --git a/packages/lib/src/take.ts b/packages/lib/src/take.ts index 64379fc1..312b7574 100644 --- a/packages/lib/src/take.ts +++ b/packages/lib/src/take.ts @@ -2,8 +2,9 @@ // branch the version lands on (consumers.ts): its sites brought to the // version by the caller's step, the lockfile refreshed where manifests moved, // the hand-owned workflows pinned to the version; then one commit, pushed as -// `plexus/`, whose message names each site's conflicted paths and -// the edited files the version drops, and a pull request against the branch. A conflict is +// `plexus/`, whose message names each site's conflicted paths, the +// edited files the version drops and the answers the step removed from the +// markers, and a pull request against the branch. A conflict is // committed with its markers and reported, and the pull request is opened all // the same, as a draft where the forge offers one, whose body opens with what // needs a hand (pull.ts): that is where it gets resolved. Nothing here aborts @@ -58,11 +59,22 @@ export interface SiteResult { kept?: string[]; } +/** The answers removed from the markers, by the directory of the marker (`.` for the root), each marker's in order. */ +export type Removed = Readonly>; + +/** What the sites' step came to: every site, and the answers it removed from the markers, where it removed any. */ +export interface SitesTaken { + sites: SiteResult[]; + removed?: Removed; +} + /** What one consumer's taking of the version came to, as data: the caller folds it into a summary. */ export interface Taken { rel: string; /** Every site, in the order they were brought to the version. */ sites: SiteResult[]; + /** The answers the sites' step removed from the markers, where it removed any. */ + removed?: Removed; /** The lockfile refresh, where manifests moved; undefined when nothing needed one. */ lockfile?: 'refreshed' | 'failed'; /** Tracked files of the scratch checkout that hold a conflict marker once the sites are updated. */ @@ -90,7 +102,7 @@ export const needsHand = (t: Taken): boolean => * files and markers changed in place, and what became of each. A step that * throws stops the taking before anything is committed. */ -export type SitesStep = (ctx: Context, consumer: Consumer, dir: string) => Promise; +export type SitesStep = (ctx: Context, consumer: Consumer, dir: string) => Promise; /** How a consumer takes the version. */ export interface Take { @@ -112,10 +124,15 @@ export interface Take { */ export async function takeVersion(ctx: Context, consumer: Consumer, dir: string, take: Take): Promise { const base = (await ctx.read('git', ['rev-parse', 'HEAD'], { cwd: dir })).trim(); - const sites = await take.sites(ctx, consumer, dir); + const { sites, removed } = await take.sites(ctx, consumer, dir); const lockfile = await refreshLockfile(ctx, consumer, dir, base); await bumpConsumerRefs(ctx, consumer, dir, take.version); - const taken: Taken = { rel: consumer.rel, sites, ...(lockfile ? { lockfile } : {}) }; + const taken: Taken = { + rel: consumer.rel, + sites, + ...(removed && Object.keys(removed).length > 0 ? { removed } : {}), + ...(lockfile ? { lockfile } : {}), + }; return { ...taken, ...(await openPull(ctx, consumer, dir, base, take, taken)) }; } @@ -206,7 +223,9 @@ async function openPull( run('git', ['add', '-A'], { cwd: dir }), // One commit on the branch, any scratch ones folded in: a later run tells it from a human's by the count. run('git', ['reset', '--quiet', '--soft', base], { cwd: dir }), - run('git', ['commit', '--quiet', '--no-verify', '-m', commitMessage(version, taken.sites)], { cwd: dir }), + run('git', ['commit', '--quiet', '--no-verify', '-m', commitMessage(version, taken.sites, taken.removed)], { + cwd: dir, + }), // An empty expected value: the branch must not exist on origin yet. run( 'git', @@ -241,6 +260,7 @@ async function openPull( ...gap, conflicts: Object.fromEntries(taken.sites.map((s) => [s.dir, s.conflicts ?? []])), kept: Object.fromEntries(taken.sites.map((s) => [s.dir, s.kept ?? []])), + ...(taken.removed ? { removed: taken.removed } : {}), note: `Opened by ${take.opener}${take.why ? `: ${take.why}` : ''}.`, }; if (marked.length > 0) ctx.say(` ${consumer.rel}: conflict markers in ${marked.join(', ')}`); diff --git a/packages/lib/src/update.ts b/packages/lib/src/update.ts index fa5de305..b98bf195 100644 --- a/packages/lib/src/update.ts +++ b/packages/lib/src/update.ts @@ -48,10 +48,30 @@ // `<<<<<<< current` and `>>>>>>> new render`, a file the version drops and // the user edited is kept without markers, named by the commit and the // pull request since nothing in the file shows it, and a born-once file -// the old render holds stays as the user left it. The defaults of questions that became -// applicable and the new `version` are spliced into the markers in one -// write each. Birth commands are never run, and neither is `mise -// install`: tools serve a developer's checkout, not a pull request. +// the old render holds stays as the user left it. The defaults of +// questions that became applicable and the new `version` are spliced +// into the markers, and the answers no template asks any more taken out +// of them, in one write each. Birth commands are never run, and neither +// is `mise install`: tools serve a developer's checkout, not a pull +// request. +// +// An answer no template asks any more is a key of a marker that a template of +// the marker's scope owns or reads at the version the repo is on, and none +// does at the version it takes: the keys `plx doctor` would report of the +// marker once the repo is on that version, judged by its own rule +// (siteTemplates.ts) over each side's manifests, so that the two cannot +// disagree. Left in the marker, it would fail the pull request's own checks, +// and every repo would delete the same line by hand for every question a +// version removes. Only such keys are taken out, never a reserved key, never a +// key no template of the old side knew (a human's, which the doctor reports to +// that human), and nothing else of the marker: its entry goes, a value over +// several lines whole, and every other byte stays (`removeMarkerKeys`). The +// run says each key it takes out, and the commit and the pull request name +// them, a line per marker and key, so that a human who kept one for a reason +// sees it went. The manifests of both sides are read by the running plx, as +// the defaults' check reads the new side's; where it cannot read one, no +// answer is removed from any marker, the run says why, and the doctor reports +// the keys as it would have. `plx apply` removes nothing. // 3. The lockfile where a manifest moved, the workflow refs, one commit on // `plexus/`, and one pull request (take.ts). The `plx` pin is a // line of a template's mise.toml, and nothing writes it apart: where the @@ -109,8 +129,9 @@ import { versionBranch, } from './pull.ts'; import { findSites, type MarkerSite, siteAnswers } from './sites.ts'; -import { planSync, type Source, type Templates } from './sync.ts'; -import { type SiteResult, type Taken, takeVersion } from './take.ts'; +import { bundledAt, strayKeys } from './siteTemplates.ts'; +import { planSync, type Source, type TemplateSides } from './sync.ts'; +import { type Removed, type SitesTaken, type Taken, takeVersion } from './take.ts'; import { COMPENDIUM, compareVersions, isPlexusVersion, preflightForge, UsageError } from './version.ts'; import { type FetchVersion, templatesOf } from './versionTemplates.ts'; @@ -362,20 +383,21 @@ export async function versionOn( * The template step of a version taken (the header's steps 1 and 2), in the * worktree `dir`: every marker that lists at least one template, rendered at * `from` and at `to` and merged, the root rendered for its answers whatever it - * lists, the defaults and the version written into the markers. What became of - * each site is what the merge reported. `templates` yields the two sides; it - * is asked once the step has said which versions it takes, so that a fetch - * follows the line that names them. The maintainers' preview of an unreleased - * version (preview.ts of @plexus-ms/dev) gives the new side as the templates - * of its own checkout. + * lists, the defaults and the version written into the markers and the + * answers no template asks any more taken out. What became of each site is + * what the merge reported. `templates` yields the two sides; it is asked once + * the step has said which versions it takes, so that a fetch follows the line + * that names them. The maintainers' preview of an unreleased version + * (preview.ts of @plexus-ms/dev) gives the new side as the templates of its + * own checkout. */ export async function renderSites( ctx: Context, consumer: Consumer, dir: string, versions: { from: string; to: string }, - templates: () => Promise<{ old: Templates; new: Templates }>, -): Promise { + templates: () => Promise, +): Promise { const sites = await findSites(ctx, dir, 'HEAD'); const sourceOf = (site: MarkerSite): Source => ({ templates: site.config?.templates ?? [], @@ -393,13 +415,16 @@ export async function renderSites( .filter((s) => s.dir !== '.') .map((s) => ({ dir: s.dir, templates: s.config?.templates ?? [], answers: s.config?.answers ?? {} })); ctx.say(`→ ${consumer.rel}: the templates of ${versions.from} and ${versions.to}, merged`); - const plan = await planSync(ctx, dir, await templates(), sides, { + const both = await templates(); + const removed = await askedNoMore(ctx, sites, both, versions); + const plan = await planSync(ctx, dir, both, sides, { labels: { old: `the templates of ${versions.from}`, new: `the templates of ${versions.to}` }, siblings, version: versions.to, + remove: removed, }); await plan.perform(); - return plan.sites.map((s) => { + const results = plan.sites.map((s) => { const rel = s.dir === '.' ? consumer.rel : join(consumer.rel, s.dir); const inRepo = (path: string) => (s.dir === '.' ? path : join(s.dir, path)); const dropped = plan.dropped[s.dir] ?? []; @@ -414,8 +439,47 @@ export async function renderSites( : ` ✓ merged clean: ${rel}`, ); for (const path of kept) ctx.say(` kept although ${versions.to} drops it, since it was edited here: ${path}`); - return { rel, dir: s.dir, outcome: conflicted ? 'conflicted' : 'clean', conflicts, kept }; + return { rel, dir: s.dir, outcome: conflicted ? ('conflicted' as const) : ('clean' as const), conflicts, kept }; }); + for (const [at, keys] of Object.entries(removed)) + for (const key of keys) + ctx.say( + ` ${ctx.dryRun ? 'to be removed' : 'removed'} from ${join(at, MARKER_FILE)}, since no template asks or reads it at ${versions.to}: ${key}`, + ); + return { sites: results, ...(Object.keys(removed).length > 0 ? { removed } : {}) }; +} + +/** + * The answers no template asks any more (the header says which), by the + * directory of the marker, for the markers among `sites` and the templates of + * both sides; none where the running plx cannot read a manifest of either + * side, which the run says. + */ +async function askedNoMore( + ctx: Context, + sites: readonly MarkerSite[], + templates: TemplateSides, + versions: { from: string; to: string }, +): Promise { + const names = [...new Set(sites.flatMap((s) => s.config?.templates ?? []))].sort(); + if (names.length === 0) return {}; + const strayAt = async (root: string, version: string) => { + try { + return strayKeys(sites, await bundledAt(root, names)); + } catch (error) { + ctx.say( + ` ! no answer is removed from the markers: this plx cannot read the templates of ${version}: ${(error as Error).message}`, + ); + return undefined; + } + }; + const before = await strayAt(templates.old.root, versions.from); + const after = before && (await strayAt(templates.new.root, versions.to)); + if (!before || !after) return {}; + const known = new Set(before.map(({ dir, key }) => `${dir}\0${key}`)); + const removed: Record = {}; + for (const { dir, key } of after) if (!known.has(`${dir}\0${key}`)) removed[dir] = [...(removed[dir] ?? []), key]; + return removed; } /** The repo at `path`, which must be generated from the templates, named `name` rather than from a workspace. */ From 14ef0e6ce37876b22a39b8764b55234d8baffdff Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:48:31 +0100 Subject: [PATCH 170/194] An answer to a question the version moved to a template the marker does not list stays (test) The failing test first: the taken version still has the question, so its answer is no answer of a question the version no longer has, and whoever adds that template, as the release notes of such a version say to, finds it in the marker. Co-Authored-By: Claude Opus 5.5 --- packages/dev/src/ship.integration.test.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index 22d60cf3..0402d52e 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -1977,6 +1977,29 @@ test('update: a marker that never answered the question, or holds only keys the assert.doesNotMatch(git(remote('acme-web'), 'log', '-1', '--format=%B', 'plexus/0.2.0'), /^Removed from/m); }); +test('update: an answer to a question the version moved to a template the marker does not list stays, for whoever adds that template', async () => { + fixture('update-moved-away'); + // At 0.1.0 the web root's template asks it, at 0.2.0 only the operations template, which the web repo does not list. + ASKED = (template, version) => + template === (version === '0.1.0' ? 'repo-turbo' : 'repo-operations') + ? { questions: [' elsewhere:', ' default: e'] } + : {}; + versionCut('0.2.0'); + const web = join(WS, 'acme/web'); + put(join(web, 'PLEXUS.md'), marker('version: 0.1.0\ntemplates: [repo-turbo]\nelsewhere: here\n')); + commit(web, 'an answer to a question that moves'); + git(web, 'push', '--quiet', 'origin', 'develop'); + const { error, out } = await runUpdate({ yes: true }, { repo: web }); + assert.equal(error, undefined, out); + assert.equal( + onVersion('acme-web', '0.2.0', 'PLEXUS.md'), + marker('version: 0.2.0\ntemplates: [repo-turbo]\nelsewhere: here\nlint: strict\n').trimEnd(), + 'the version still has the question', + ); + assert.doesNotMatch(out, /removed from/); + assert.doesNotMatch(pull('acme-web', '0.2.0', '.body'), /^Removed from the markers/m); +}); + test('update: a repo of the real templates whose version no longer asks a question takes it, and plx doctor passes on the branch with no hand edit', async () => { fixture('asked-less-doctor'); // The version the repo is on: this checkout's templates, with a question repo-turbo asks no more. From 3ef922a7044c407941e1b69bc94335183f5559c5 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:50:12 +0100 Subject: [PATCH 171/194] An answer to a question the version moved to a template the marker does not list stays The version still has that question: a key some template of the taken version owns or reads, listed by a marker or not, is not removed. The doctor reports it until the template is added, as the release notes of such a version say to, and the answer is then where it was. The doctor and the update read every template below a root with one function (bundledAt). Co-Authored-By: Claude Opus 5.5 --- packages/lib/src/doctor.ts | 8 ++--- packages/lib/src/siteTemplates.ts | 20 +++++++++--- packages/lib/src/update.ts | 52 +++++++++++++++++++++---------- 3 files changed, 53 insertions(+), 27 deletions(-) diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index e511e9dc..d3bca5c3 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -66,7 +66,7 @@ // // plx doctor # this repo and its apps, from anywhere inside it // plx doctor ~/dev # every Plexus repo beneath, and its apps -import { readdir, realpath } from 'node:fs/promises'; +import { realpath } from 'node:fs/promises'; import { basename, dirname, join, relative, resolve } from 'node:path'; import { APP_SERVICE, @@ -727,11 +727,7 @@ let bundled: Promise | undefined; /** The templates this plx bundles, each read from `templatesRoot()`, once per run. */ function bundledTemplates(): Promise { - bundled ??= (async () => { - const root = templatesRoot(); - const names = (await readdir(root, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name); - return bundledAt(root, names.sort()); - })(); + bundled ??= bundledAt(templatesRoot()); return bundled; } diff --git a/packages/lib/src/siteTemplates.ts b/packages/lib/src/siteTemplates.ts index 03f16894..a226d33e 100644 --- a/packages/lib/src/siteTemplates.ts +++ b/packages/lib/src/siteTemplates.ts @@ -44,7 +44,9 @@ // The keys of the first kind are also what `plx update` judges by (update.ts): // an answer that the templates of the version a repo is on own or read, and // those of the version it takes do not, is one this check would report once -// the repo is on that version, and the update removes it (`strayKeys`). +// the repo is on that version, and the update removes it (`strayKeys`), unless +// a template of that version the markers do not list owns or reads it. +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'; @@ -62,9 +64,19 @@ export interface Bundled { readonly render: typeof render; } -/** The templates `names` below `root`, each read as `plx new` reads it (bundled.ts); rejects naming one it cannot read. */ -export async function bundledAt(root: string, names: readonly string[]): Promise { - const trees = await Promise.all(names.map(async (name) => [name, (await readTemplate(root, name)).tree] as const)); +/** + * The templates `names` below `root`, every one there by default, each read + * as `plx new` reads it (bundled.ts); rejects naming one it cannot read. + */ +export async function bundledAt(root: string, names?: readonly string[]): Promise { + const all = async () => + (await readdir(root, { withFileTypes: true })) + .filter((e) => e.isDirectory()) + .map((e) => e.name) + .sort(); + const trees = await Promise.all( + (names ?? (await all())).map(async (name) => [name, (await readTemplate(root, name)).tree] as const), + ); return { trees: new Map(trees), render: (await engine()).render }; } diff --git a/packages/lib/src/update.ts b/packages/lib/src/update.ts index b98bf195..572bed4d 100644 --- a/packages/lib/src/update.ts +++ b/packages/lib/src/update.ts @@ -56,22 +56,26 @@ // request. // // An answer no template asks any more is a key of a marker that a template of -// the marker's scope owns or reads at the version the repo is on, and none -// does at the version it takes: the keys `plx doctor` would report of the -// marker once the repo is on that version, judged by its own rule -// (siteTemplates.ts) over each side's manifests, so that the two cannot -// disagree. Left in the marker, it would fail the pull request's own checks, -// and every repo would delete the same line by hand for every question a -// version removes. Only such keys are taken out, never a reserved key, never a -// key no template of the old side knew (a human's, which the doctor reports to -// that human), and nothing else of the marker: its entry goes, a value over -// several lines whole, and every other byte stays (`removeMarkerKeys`). The -// run says each key it takes out, and the commit and the pull request name -// them, a line per marker and key, so that a human who kept one for a reason -// sees it went. The manifests of both sides are read by the running plx, as -// the defaults' check reads the new side's; where it cannot read one, no -// answer is removed from any marker, the run says why, and the doctor reports -// the keys as it would have. `plx apply` removes nothing. +// the marker's scope owns or reads at the version the repo is on, none does at +// the version it takes, and no template of that version at all does: the keys +// `plx doctor` would report of the marker once the repo is on that version, +// judged by its own rule (siteTemplates.ts) over each side's manifests, so that +// the two cannot disagree, but for a question the version moved to a template +// the markers do not list. That one the version still has, and whoever takes +// such a version adds the template, as its release notes say, and finds the +// answer where it was. Left in the marker, an answer no template asks would +// fail the pull request's own checks, and every repo would delete the same +// line by hand for every question a version removes. Only such keys are taken +// out, never a reserved key, never a key no template of the old side knew (a +// human's, which the doctor reports to that human), and nothing else of the +// marker: its entry goes, a value over several lines whole, and every other +// byte stays (`removeMarkerKeys`). The run says each key it takes out, and the +// commit and the pull request name them, a line per marker and key, so that a +// human who kept one for a reason sees it went. The manifests of both sides +// are read by the running plx, as the defaults' check reads the new side's; +// where it cannot read one, no answer is removed from any marker, the run says +// why, and the doctor reports the keys as it would have. `plx apply` removes +// nothing. // 3. The lockfile where a manifest moved, the workflow refs, one commit on // `plexus/`, and one pull request (take.ts). The `plx` pin is a // line of a template's mise.toml, and nothing writes it apart: where the @@ -477,8 +481,22 @@ async function askedNoMore( const after = before && (await strayAt(templates.new.root, versions.to)); if (!before || !after) return {}; const known = new Set(before.map(({ dir, key }) => `${dir}\0${key}`)); + const candidates = after.filter(({ dir, key }) => !known.has(`${dir}\0${key}`)); + if (candidates.length === 0) return {}; + // A question the version moved to a template no marker lists is one it still has. + let unknown: Set; + try { + const every = await bundledAt(templates.new.root); + const probe = Object.fromEntries(candidates.map(({ key }) => [key, null])); + unknown = new Set(every.render([...every.trees.values()], probe).unused); + } catch (error) { + ctx.say( + ` ! no answer is removed from the markers: this plx cannot read the templates of ${versions.to}: ${(error as Error).message}`, + ); + return {}; + } const removed: Record = {}; - for (const { dir, key } of after) if (!known.has(`${dir}\0${key}`)) removed[dir] = [...(removed[dir] ?? []), key]; + for (const { dir, key } of candidates) if (unknown.has(key)) removed[dir] = [...(removed[dir] ?? []), key]; return removed; } From a430544f63e03f1e5d87699cb57b9c29941e9de9 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:50:51 +0100 Subject: [PATCH 172/194] Where this plx cannot read the templates of the version taken, no answer is removed (test) The path that removes nothing was written with the removal itself (adfb49d), so this test passes from the start: a version whose manifests the running plx cannot read, rendered by that version's own plx-template as every other, keeps every key, and the run says why. Co-Authored-By: Claude Opus 5.5 --- packages/dev/src/ship.integration.test.ts | 59 +++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index 0402d52e..c776a197 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -1977,6 +1977,65 @@ test('update: a marker that never answered the question, or holds only keys the assert.doesNotMatch(git(remote('acme-web'), 'log', '-1', '--format=%B', 'plexus/0.2.0'), /^Removed from/m); }); +/** + * A plx-template of a version whose manifests this plx cannot read: it knows + * the top-level key `future`, which it takes out of each template it is handed + * before it renders as this workspace's does. + */ +function futureEngine(): string { + const path = join(WS, 'future-plx-template.mjs'); + put( + path, + `import { spawnSync } from 'node:child_process'; +import { cpSync, existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { basename, join } from 'node:path'; +const copies = mkdtempSync(join(${JSON.stringify(WS)}, 'future-')); +const args = process.argv.slice(2).map((arg) => { + const manifest = join(arg, 'template.yml'); + if (!existsSync(manifest)) return arg; + const copy = join(copies, basename(arg)); + cpSync(arg, copy, { recursive: true }); + writeFileSync(join(copy, 'template.yml'), readFileSync(manifest, 'utf8').replace(/^future:.*\\n/m, '')); + return copy; +}); +const result = spawnSync(process.execPath, [${JSON.stringify(PLX_TEMPLATE)}, ...args], { stdio: 'inherit' }); +process.exit(result.status ?? 1); +`, + ); + return path; +} + +test('update: where this plx cannot read the templates of the version taken, no answer is removed, and the run says why', async () => { + const { web } = askedLess('update-asked-less-unread'); + const asked = ASKED; + ASKED = (template, version) => ({ + ...asked(template, version), + ...(template === 'repo-turbo' && version === '0.2.0' ? { top: ['future: 1'] } : {}), + }); + const fetch: FetchVersion = async (_ctx, version, into) => { + FETCHED.push(version); + return { plxTemplate: futureEngine(), templates: templatesFor(version, join(into, 'templates')) }; + }; + const { result, error, out } = await runUpdate({ yes: true }, { repo: web, fetch }); + assert.equal(error, undefined, out); + assert.deepEqual(result?.conflicted, [], out); + assert.ok(has(out, '! no answer is removed from the markers: this plx cannot read the templates of 0.2.0: '), out); + assert.doesNotMatch(out, /^ *removed from /m); + assert.equal( + `${onVersion('acme-web', '0.2.0', 'PLEXUS.md')}\n`, + ROOT_ASKED_LESS.replace('version: 0.1.0', 'version: 0.2.0').replace( + 'deviations: [PLX-Repo/Verbs]\n', + 'deviations: [PLX-Repo/Verbs]\nlint: strict\n', + ), + 'every key stays', + ); + assert.equal( + onVersion('acme-web', '0.2.0', 'apps/site/PLEXUS.md'), + marker('templates: [app-nextjs]\napp_only: a1\n').trimEnd(), + ); + assert.doesNotMatch(pull('acme-web', '0.2.0', '.body'), /^Removed from the markers/m); +}); + test('update: an answer to a question the version moved to a template the marker does not list stays, for whoever adds that template', async () => { fixture('update-moved-away'); // At 0.1.0 the web root's template asks it, at 0.2.0 only the operations template, which the web repo does not list. From f21f56721b9712cfe8aefc50d27c345e7138f691 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:51:17 +0100 Subject: [PATCH 173/194] A later run still names the answers removed, but not one the branch holds again (test) The failing test first: the body a later run writes from the branch's tip names the answers plx's commit removed, as it names the kept files, and no longer one somebody put back on the branch. Co-Authored-By: Claude Opus 5.5 --- packages/dev/src/ship.integration.test.ts | 28 +++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index c776a197..a83c2845 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -1952,6 +1952,34 @@ test('update: an answer to a question the version no longer asks or reads leaves assert.ok(has(ops.out, 'removed from PLEXUS.md, since no template asks or reads it at 0.2.0: registry'), ops.out); }); +test('update: a later run still names the answers removed, read from the commit, but no longer one the branch holds again', async () => { + const { web } = askedLess('update-asked-less-later'); + const first = await runUpdate({ yes: true }, { repo: web }); + assert.equal(first.error, undefined, first.out); + const removed = + /^Removed from the markers, since no template asks or reads them at 0\.2\.0:\n- `blocky` from `PLEXUS\.md`\.\n- `borrowed` from `PLEXUS\.md`\.\n- `note` from `PLEXUS\.md`\.\n- `registry` from `PLEXUS\.md`\.\n- `app_only` from `apps\/site\/PLEXUS\.md`\.$/m; + assert.match(pull('acme-web', '0.2.0', '.body'), removed); + + const later = await runUpdate({ yes: true }, { repo: web }); + assert.equal(later.error, undefined, later.out); + assert.match(pull('acme-web', '0.2.0', '.body'), /^Ready for review: /m); + assert.match(pull('acme-web', '0.2.0', '.body'), removed, 'the body a later run writes names them as well'); + + // Somebody puts one back on the branch: it is no longer removed. + const human = join(WS, 'human'); + git(WS, 'clone', '--quiet', '--branch', 'plexus/0.2.0', remote('acme-web'), human); + put(join(human, 'PLEXUS.md'), setMarkerKeys(read(join(human, 'PLEXUS.md')), { registry: 'own' })); + commit(human, 'we keep the registry answered'); + git(human, 'push', '--quiet', 'origin', 'plexus/0.2.0'); + const again = await runUpdate({ yes: true }, { repo: web }); + assert.equal(again.error, undefined, again.out); + assert.doesNotMatch(pull('acme-web', '0.2.0', '.body'), /`registry`/); + assert.match( + pull('acme-web', '0.2.0', '.body'), + /^Removed from the markers, since no template asks or reads them at 0\.2\.0:\n- `blocky` from `PLEXUS\.md`\.\n- `borrowed` from `PLEXUS\.md`\.\n- `note` from `PLEXUS\.md`\.\n- `app_only` from `apps\/site\/PLEXUS\.md`\.$/m, + ); +}); + test('update: a marker that never answered the question, or holds only keys the version still knows, keeps every byte', async () => { fixture('update-asked-less-unanswered'); ASKED = asksLess; From 8b65a13a0298535fbb169597ceb69a0741276a1f Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:51:45 +0100 Subject: [PATCH 174/194] Test: an app has a large job when the e2e of any of its suites is a MISS or unknown; the per-app line says what a MISS may mean; a failing turbow's last line is the plan's; the shim runs the lockfile's Turbo and its directory goes on every path Legs and hashes carry the directories of all of an app's suites, and the browser step installs in each. The fake Io keeps what is written, for the shim to be read back. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/core/plan.test.ts | 14 ++--- packages/cli-ci/src/core/planCache.test.ts | 71 +++++++++++++++++++--- packages/cli-ci/src/testing/fakeIo.ts | 12 +++- packages/lib/src/pipeline.test.ts | 7 ++- 4 files changed, 85 insertions(+), 19 deletions(-) diff --git a/packages/cli-ci/src/core/plan.test.ts b/packages/cli-ci/src/core/plan.test.ts index 1de932f8..b3a64a3c 100644 --- a/packages/cli-ci/src/core/plan.test.ts +++ b/packages/cli-ci/src/core/plan.test.ts @@ -56,9 +56,9 @@ function narrated(ctx: Context): string { test('hashesOf keeps the build hash of each app’s package, and the directory of the suite whose e2e waits for that build', () => { // The rule `mise run e2e ` follows too: Turbo's graph, never a directory's name. assert.deepEqual(hashes, [ - { app: 'website', hash: '0f2a', suite: 'e2e/website' }, - { app: 'my-app', hash: 'c51b', suite: '' }, - { app: 'solver', hash: '9e1d', suite: '' }, + { app: 'website', hash: '0f2a', suites: ['e2e/website'] }, + { app: 'my-app', hash: 'c51b', suites: [] }, + { app: 'solver', hash: '9e1d', suites: [] }, ]); assert.deepEqual(hashesOf(dryRun, { nope: '@acme/nope', stub: '@acme/stub' }), []); }); @@ -73,7 +73,7 @@ test('without a turbow, readHashes runs a plain dry run of build and e2e with th }); const env = { PLX_PLATFORM: 'linux-x64' }; assert.deepEqual(await readHashes(new Context({}, io), '/repo', ['website'], env), { - hashes: [{ app: 'website', hash: '0f2a', suite: 'e2e/website' }], + hashes: [{ app: 'website', hash: '0f2a', suites: ['e2e/website'] }], why: 'the checkout has no turbow to name the trusted cache with', }); assert.deepEqual(seen, [{ cwd: '/repo', args: ['--yes', 'turbo@2.11.13', 'run', 'build', 'e2e', '--dry-run=json'] }]); @@ -151,7 +151,7 @@ test('every app gets a publish leg, and a large job where the plan could not ask app: 'website', hash: '0f2a', runner: 'exo-large-41-website-1', - suite: 'e2e/website', + suites: ['e2e/website'], context: 'output', build: false, // Nothing asked of the trusted cache: its tasks count as work. @@ -162,7 +162,7 @@ test('every app gets a publish leg, and a large job where the plan could not ask app: 'my-app', hash: 'c51b', runner: 'exo-large-41-my-app-1', - suite: '', + suites: [], context: 'output', build: true, large: true, @@ -172,7 +172,7 @@ test('every app gets a publish leg, and a large job where the plan could not ask app: 'solver', hash: '9e1d', runner: 'exo-large-41-solver-1', - suite: '', + suites: [], context: 'pruned', build: true, large: false, diff --git a/packages/cli-ci/src/core/planCache.test.ts b/packages/cli-ci/src/core/planCache.test.ts index ff999bdb..409f818c 100644 --- a/packages/cli-ci/src/core/planCache.test.ts +++ b/packages/cli-ci/src/core/planCache.test.ts @@ -25,13 +25,14 @@ function task(id: string, hash: string, command: string, status: Status, extra: } /** - * The dry run of `build e2e` for website (a suite), my-app (no suite, from the - * output), solver (a Dockerfile of its own, no suite) and worker (a Dockerfile - * of its own, a suite), with the statuses given. + * The dry run of `build e2e` for website (two suites), my-app (no suite, from + * the output), solver (a Dockerfile of its own, no suite) and worker (a + * Dockerfile of its own, a suite), with the statuses given. */ function dryRun(s: { website?: Status; websiteE2e?: Status; + websiteSmoke?: Status; myApp?: Status; solver?: Status; worker?: Status; @@ -45,6 +46,11 @@ function dryRun(s: { directory: 'e2e/website', dependencies: ['@acme/website#build'], }), + // A second suite of website: `mise run e2e website` runs both. + task('@acme/website-smoke#e2e', 'e2e6', 'playwright test', s.websiteSmoke, { + directory: 'e2e/website-smoke', + dependencies: ['@acme/website#build'], + }), // A task the package does not define: always MISS, never work. task('@acme/website#e2e', 'e2e2', '', s.nonexistent ?? 'MISS', { directory: 'apps/website' }), // A package that waits for website's build and has no e2e of its own: no suite, never work. @@ -107,6 +113,7 @@ async function large(statuses: Parameters[0], holds: string[] = [ const ALL_HIT = { website: 'HIT', websiteE2e: 'HIT', + websiteSmoke: 'HIT', myApp: 'HIT', solver: 'HIT', worker: 'HIT', @@ -116,8 +123,12 @@ const IMAGES = ['website', 'my-app', 'solver', 'worker'].map( (a) => `ghcr.io/acme/${a}:build-${{ website: '0f2a', 'my-app': 'c51b', solver: '9e1d', worker: '7a7a' }[a]}`, ); -test('hashesOf reads whether the cache holds an app’s build and its suite’s e2e; a task without a cache field leaves it unknown', () => { - const [website, myApp] = hashesOf(dryRun({ website: 'HIT', websiteE2e: 'MISS', myApp: 'MISS' }), packages); +test('hashesOf reads whether the cache holds an app’s build and the e2e of all its suites; a task without a cache field leaves it unknown', () => { + const [website, myApp] = hashesOf( + dryRun({ website: 'HIT', websiteE2e: 'MISS', websiteSmoke: 'HIT', myApp: 'MISS' }), + packages, + ); + assert.deepEqual(website?.suites, ['e2e/website', 'e2e/website-smoke']); assert.deepEqual(website?.cached, { build: true, e2e: false }); // No suite: there is no e2e to hold, which is no work. assert.deepEqual(myApp?.cached, { build: false, e2e: true }); @@ -125,6 +136,14 @@ test('hashesOf reads whether the cache holds an app’s build and its suite’s assert.equal(hashesOf(dryRun({ websiteE2e: 'HIT' }), packages)[0]?.cached, undefined); }); +test('an app with two suites gets a large job when the e2e of either is a MISS or unknown, and none when both are HITs', async () => { + assert.deepEqual(await large({ ...ALL_HIT, websiteE2e: 'MISS' }, IMAGES), ['website']); + assert.deepEqual(await large({ ...ALL_HIT, websiteSmoke: 'MISS' }, IMAGES), ['website']); + assert.deepEqual(await large({ ...ALL_HIT, websiteSmoke: undefined }, IMAGES), ['website']); + assert.deepEqual(await large({ ...ALL_HIT, websiteE2e: undefined }, IMAGES), ['website']); + assert.deepEqual(await large(ALL_HIT, IMAGES), []); +}); + test('an app with a suite gets a large job when its build or its suite’s e2e is a MISS, whatever the registry holds', async () => { assert.deepEqual(await large(ALL_HIT, IMAGES), []); assert.deepEqual(await large({ ...ALL_HIT, website: 'MISS' }, IMAGES), ['website']); @@ -185,7 +204,10 @@ function asking(tree: Tree, turbow: { out?: string; err: string; fails?: boolean const io = fakeIo(tree, undefined, { mktemp: () => '/scratch/plx-ci-turbo', chmod: () => '', - rm: () => '', + rm: (_cwd, args) => { + calls.push({ command: 'rm', args }); + return ''; + }, sh: (_cwd, args, _input, env) => { calls.push({ command: 'sh', args, env }); // `sh -c 'exec ./turbow "$@" 2>"$0"' …`: turbow's stderr goes to the file. @@ -230,7 +252,7 @@ test('readHashes asks the trusted cache through turbow, with the Turbo the lockf '--dry-run=json', ]); assert.equal(sh?.env?.PATH, '/scratch/plx-ci-turbo:/usr/bin'); - assert.equal(calls.length, 1, 'no second dry run'); + assert.equal(calls.filter((c) => c.command !== 'rm').length, 1, 'no second dry run'); }); test('a plan that cannot ask the cache says why in one line and leaves every status unknown', async () => { @@ -278,6 +300,12 @@ test('a plan that cannot ask the cache says why in one line and leaves every sta }, /^Remote caching unavailable \(Could not connect to "http:\/\/127\.0\.0\.1:8586"\)$/, ], + [ + 'a turbow that fails with words of its own', + checkout(), + { fails: true, err: 'something went wrong first\nboom: the end of it\n' }, + /^turbow failed: boom: the end of it$/, + ], [ 'a checkout without turbow', checkout(false), @@ -310,10 +338,35 @@ test('the plan says what it asked and which apps get a large job', async () => { narrated(ctx), [ 'website: ghcr.io/acme/website:build-0f2a exists; publish tags it', - 'website: the trusted cache holds its build, not its suite’s e2e; a large job', + 'website: in the trusted cache, build HIT, e2e/website MISS, e2e/website-smoke HIT (a MISS: not found, or not answered); a large job', 'my-app: ghcr.io/acme/my-app:build-c51b exists; publish tags it', - 'my-app: the trusted cache holds its build; no large job', + 'my-app: in the trusted cache, build HIT; no large job', '', ].join('\n'), ); }); + +test('the turbo turbow runs is the lockfile’s, and its directory is removed whatever the dry run ended in', async () => { + const cases: [string, Parameters[1]][] = [ + [ + 'asked', + { out: dryRun(ALL_HIT), err: 'turbow: the trusted remote cache at http://127.0.0.1:8586, team acme-web\n' }, + ], + [ + 'a server that does not answer', + { + out: dryRun({}), + err: ' WARNING • Remote caching unavailable (Could not connect to "http://127.0.0.1:8586")\n', + }, + ], + ['a failing turbow', { fails: true, err: 'boom\n' }], + ]; + for (const [name, turbow] of cases) { + const tree = checkout(); + const { ctx, calls } = asking(tree, turbow); + await readHashes(ctx, '/repo', ['website'], PLATFORM); + const shim = ((tree.scratch as Tree)['plx-ci-turbo'] as Tree).turbo; + assert.equal(shim, '#!/bin/sh\nexec npx --yes turbo@2.11.13 "$@"\n', name); + assert.deepEqual(calls.at(-1), { command: 'rm', args: ['-rf', '/scratch/plx-ci-turbo'] }, name); + } +}); diff --git a/packages/cli-ci/src/testing/fakeIo.ts b/packages/cli-ci/src/testing/fakeIo.ts index fea84372..8283e93d 100644 --- a/packages/cli-ci/src/testing/fakeIo.ts +++ b/packages/cli-ci/src/testing/fakeIo.ts @@ -40,7 +40,17 @@ export function fakeIo(tree: Tree, git: FakeExec = () => undefined, other: Recor if (typeof node !== 'string') throw new Error(`no file ${path}`); return node; }, - writeFile: async () => {}, + // A write lands in the tree, where a later read finds it. + writeFile: async (path, content) => { + const parts = path.split('/').filter(Boolean); + const name = parts.pop() ?? ''; + let node = tree; + for (const part of parts) { + node[part] ??= {}; + node = node[part] as Tree; + } + node[name] = content; + }, readDir: async (path) => { const node = at(path); if (typeof node !== 'object') throw new Error(`no directory ${path}`); diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index a48bfde2..6f2e54ae 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -154,9 +154,12 @@ test('_e2e.yml plans, then per app builds the app and runs its suites on a large keyed.map((s) => s.run), ['mise run build "$APP"'], ); - // The suite's browser is installed only for an app that has a suite. + // The suites' browsers are installed only for an app that has a suite. const browser = (e2e?.steps ?? []).find((s) => /playwright install/.test(s.run ?? '')); - assert.equal(browser?.if, "${{ matrix.suite != '' }}"); + assert.equal(browser?.if, "${{ join(matrix.suites, '') != '' }}"); + // In each suite's directory: two suites may pin two Playwrights, whose browsers differ. + assert.equal(browser?.env?.SUITES, "${{ join(matrix.suites, ' ') }}"); + assert.match(browser?.run ?? '', /for suite in \$SUITES; do/); assert.deepEqual(needsOf(jobs.cleanup).sort(), ['e2e', 'plan']); }); From d120d994b6df32b78bbefd7258dda999d104e9f6 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:52:46 +0100 Subject: [PATCH 175/194] A later run still names the answers removed, but not one the branch holds again The body a later run writes is made from the branch's tip and plx's commit, never from the body: the answers the commit names removed are read back from it, as the kept files are, and one the tip's marker holds again is named no more. Co-Authored-By: Claude Opus 5.5 --- packages/lib/src/pull.ts | 45 +++++++++++++++++++++++++++++++++++----- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/packages/lib/src/pull.ts b/packages/lib/src/pull.ts index b1a57d0d..6dd400b2 100644 --- a/packages/lib/src/pull.ts +++ b/packages/lib/src/pull.ts @@ -376,8 +376,9 @@ const markerAt = (dir: string): string => (dir === '.' ? MARKER_FILE : `${dir}/$ * then for each site the paths left conflicted with their markers and the * files the version drops that were edited here, kept without markers, one * block each, and one block of the answers removed from the markers, a line - * per marker and key. A later run reads the second kind back (`keptIn`), since - * no marker shows them; the first it finds by the detector. + * per marker and key. A later run reads the second and the third kind back + * (`keptIn`, `removedIn`), since nothing on the branch shows them; the first + * it finds by the detector. */ export function commitMessage( version: string, @@ -399,6 +400,26 @@ export function commitMessage( ].join('\n\n'); } +/** The answers a commit message of `commitMessage` names removed, by the directory of the marker. */ +function removedIn(message: string): Record { + const removed: Record = {}; + let open = false; + for (const line of message.split('\n')) { + if (/^Removed from the markers, since no template asks or reads them at \S+:$/.test(line)) open = true; + else if (!open) continue; + else { + const named = /^- (.+): (\S+)$/.exec(line); + if (!named?.[1] || !named[2]) { + open = false; + continue; + } + const dir = named[1] === MARKER_FILE ? '.' : named[1].slice(0, -`/${MARKER_FILE}`.length); + removed[dir] = [...(removed[dir] ?? []), named[2]]; + } + } + return removed; +} + /** The kept files a commit message of `commitMessage` names, by site. */ export function keptIn(message: string): Record { const kept: Record = {}; @@ -534,6 +555,8 @@ interface AtTip { pin?: PinGap; /** By site, the edited files the version drops, as plx's commit on the branch names them. */ kept: Record; + /** By the directory of the marker, the answers plx's commit removed that the tip's marker does not hold again. */ + removed: Record; /** No marker, the root marker names the version, and the pin does too. */ ready: boolean; /** Whether the body asks for `pnpm install` and the lockfile. */ @@ -543,8 +566,9 @@ interface AtTip { /** * The version branch's tip, read by hash: the detector over its tracked * files, its sites, every marker it holds that lists at least one template, - * whether its root marker names the version and its `plx` pin too, and the - * kept files plx's commit names (`comparedAt`) that the tip still holds. The lockfile is asked for + * whether its root marker names the version and its `plx` pin too, the kept + * files plx's commit names (`comparedAt`) that the tip still holds, and the + * answers it names removed that the tip's markers do not hold again. The lockfile is asked for * where the tip holds one and the pull request is not ready, or holds commits * beyond the one plx made (somebody resolved by hand), as the forge counts * them. @@ -576,7 +600,16 @@ async function readTip(ctx: Context, consumer: Consumer, version: string, tip: s .map(([dir, paths]) => [dir, paths.filter((p) => files.has(p))] as const) .filter(([, paths]) => paths.length > 0), ); - return { tip, sites, marked, behind, ...(pin ? { pin } : {}), kept, ready, lockfile }; + // An answer somebody has since put back on the branch is no longer removed. + const removed = Object.fromEntries( + Object.entries(removedIn(compared.message)) + .map(([dir, keys]) => { + const answers = held.find((s) => s.dir === dir)?.config?.answers ?? {}; + return [dir, keys.filter((key) => !Object.hasOwn(answers, key))] as const; + }) + .filter(([, keys]) => keys.length > 0), + ); + return { tip, sites, marked, behind, ...(pin ? { pin } : {}), kept, removed, ready, lockfile }; } /** What a later run found at the tip, as the run names it. */ @@ -630,6 +663,7 @@ export async function revisit( behind, ...(pin ? { pin } : {}), kept: at.kept, + removed: at.removed, lockfile: at.lockfile, checked: true, note: REVISITED, @@ -715,6 +749,7 @@ export async function openLate( behind, ...gap, kept: at.kept, + removed: at.removed, lockfile: at.lockfile, checked: true, note: OPENED_LATE, From 420dad725c716befabef38c7d48d837032f5d585 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:53:28 +0100 Subject: [PATCH 176/194] plx apply removes no key; the verb's header and help say what update removes A test holds that apply leaves an answer no template it lists asks any more, which the doctor names to the human. The command's header and help, and the pull request's header, say that update takes such answers out and names them. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/commands/update.ts | 12 +++++++----- packages/lib/src/apply.test.ts | 18 ++++++++++++++++++ packages/lib/src/pull.ts | 5 ++++- 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/packages/cli/src/commands/update.ts b/packages/cli/src/commands/update.ts index 55a9c229..18660152 100644 --- a/packages/cli/src/commands/update.ts +++ b/packages/cli/src/commands/update.ts @@ -1,10 +1,12 @@ // plx update [dir]: this repo takes a version by its step and a schedule (§ 3 // PLX-Updates), as a pull request on `plexus/`: the templates of the // version the repo is on and of the one it takes, rendered and merged at every -// site, the version in the root marker, the lockfile, the workflow refs; how, -// is lib's update.ts. A patch (a hotfix) is taken at once, a -// minor (routine) once the oldest version not taken is as old as the repo's -// interval, a major (a changed contract) only when asked (--now, or --to); +// site, the version in the root marker, the answers no template asks any more +// out of the markers, each named in the run and the pull request, the +// lockfile, the workflow refs; how, is lib's update.ts. A patch (a hotfix) is +// taken at once, a minor (routine) once the oldest version not taken is as old +// as the repo's interval, a major (a changed contract) only when asked (--now, +// or --to); // otherwise the repo rests and says why. The pull request asks the users the // root marker's answer pr_reviewers names for a review, or those --reviewer names // instead (repeatable or comma-separated; an empty one asks nobody), once, @@ -49,7 +51,7 @@ export function register(program: Command): void { program .command('update') .description( - 'take a version as a pull request on plexus/ (the templates merged at every site, the version in the root marker, the lockfile, the workflow refs): a patch at once, a minor at the next scheduled pull (--max-age), a major only when asked; -r in every repo generated from the templates under a directory', + 'take a version as a pull request on plexus/ (the templates merged at every site, the version in the root marker, the answers no template asks any more out of the markers, the lockfile, the workflow refs): a patch at once, a minor at the next scheduled pull (--max-age), a major only when asked; -r in every repo generated from the templates under a directory', ) .argument('[dir]', 'a repo whose root PLEXUS.md names its version; with -r, a directory the repos sit under', '.') .option('-r, --recursive', 'run in every repo generated from the templates under the directory, at any depth') diff --git a/packages/lib/src/apply.test.ts b/packages/lib/src/apply.test.ts index 4425fa09..e5a76fb8 100644 --- a/packages/lib/src/apply.test.ts +++ b/packages/lib/src/apply.test.ts @@ -249,6 +249,24 @@ test('apply deletes the unedited files of a template removed from a site, keeps assert.equal(applied.conflicted, 1); }); +test('apply removes no key from a marker, not even an answer no template it lists asks any more', async () => { + const { repo, templates } = fixture(); + git(repo, 'rm', '-q', '--cached', 'PLEXUS.md'); + write(repo, { + 'PLEXUS.md': both('width: 9\n'), + 'shelf.txt': 'a shelf\n', + 'bench.txt': 'a bench\n', + 'width.txt': '9 wide\n', + }); + git(repo, 'add', '-A'); + git(repo, 'commit', '-q', '-m', 'shelf'); + const dropped = marker(`version: ${VERSION}\ntemplates: [basket]\nfruit: apple\nwidth: 9\n`); + write(repo, { 'PLEXUS.md': dropped }); + await apply(quietContext(), options(repo, templates)); + assert.equal(existsSync(join(repo, 'width.txt')), false, 'the template is dropped'); + assert.equal(text(repo, 'PLEXUS.md'), dropped, "its answer is the human's to remove, as the doctor says"); +}); + test('apply renders a site whose marker is new, from nothing, once git tracks it', async () => { const { repo, templates } = fixture(); write(repo, { 'apps/crate/PLEXUS.md': CRATE }); diff --git a/packages/lib/src/pull.ts b/packages/lib/src/pull.ts index 6dd400b2..c1f4ba24 100644 --- a/packages/lib/src/pull.ts +++ b/packages/lib/src/pull.ts @@ -9,7 +9,10 @@ // when the lockfile did not refresh, that `pnpm install` is to be run after // resolving. Where the forge refuses a draft, the same pull request is // opened as an ordinary one, and the run says so; it needs a hand all the -// same. One that needs none is ready for review. +// same. One that needs none is ready for review. Below what needs a hand, the +// body names what needs none but a reviewer should know, since nothing on the +// branch shows it: the edited files the version drops, kept, and the answers +// `update` removed from the markers, a line per marker and key. // // The branch is never moved by any run, and plx never pushes to it again: it // is the human's from the moment it is on origin. A later run, scheduled or From 2561e6c2f0d4b33f31ebc10c8326546355d900dc Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:54:27 +0100 Subject: [PATCH 177/194] Test: in the newborn web has two suites, and a change to a spec of the second alone gives it a large job that runs both Co-Authored-By: Claude Fable 5.2 --- newborns/pipeline.test.ts | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/newborns/pipeline.test.ts b/newborns/pipeline.test.ts index 7c388ee4..efb1131e 100644 --- a/newborns/pipeline.test.ts +++ b/newborns/pipeline.test.ts @@ -20,13 +20,14 @@ // // The caches are the cache servers the step turbo-cache starts, against an S3 // stand-in with the two buckets (caches.ts). The repo has two apps from -// app-nextjs: `web`, with its E2E suite, and `site`, without one. The first +// app-nextjs: `web`, with two E2E suites, and `site`, without one. The first // run gives both a large job, publishes each image from a restore of the // output its large job built, and deploys `web` healthy. A second run on the // same content gives no app a large job, builds no image, and leaves `web` // running; the plan's requests to the trusted server are HEAD requests only. // A change to a spec alone gives exactly `web` a large job, which runs its -// suite and no build, and publish builds no image. A change to `site` alone +// suites and no build, and publish builds no image; so does a change to a spec +// of its second suite alone. A change to `site` alone // gives exactly `site` a large job, and publish builds its image. Needs Docker // and the network, as the newborns do. import assert from 'node:assert/strict'; @@ -102,6 +103,10 @@ before(async () => { const repo = await born(join(here, 'web'), ['repo-turbo'], { tenant: 'acme' }); await born(join(repo, 'apps', 'web'), ['app-nextjs'], { name: '@acme/web', profile: 'stateless' }); await born(join(repo, 'e2e', 'web'), ['e2e-playwright'], { app: '@acme/web' }); + // A second suite of web: the template names a suite's package after its app, so this one is renamed. + await born(join(repo, 'e2e', 'web2'), ['e2e-playwright'], { app: '@acme/web' }); + const second = join(repo, 'e2e', 'web2', 'package.json'); + writeFileSync(second, readFileSync(second, 'utf8').replace('"@acme/web-e2e"', '"@acme/web-e2e2"')); await born(join(repo, 'apps', 'site'), ['app-nextjs'], { name: '@acme/site', profile: 'stateless' }); // Where the app deploys in staging: the operations repo's inventory, as the plan reads it. put(here, { @@ -161,7 +166,7 @@ async function planned(dir: string, task: string): Promise { interface Leg { app: string; hash: string; - suite: string; + suites: string[]; context: string; build: boolean; large: boolean; @@ -205,8 +210,8 @@ async function pipeline(sha: string): Promise { ...trusted, NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: KEY, }); - if (leg.suite) - await step(join(job, leg.suite), ['mise', 'exec', '--', 'pnpm', 'exec', 'playwright', 'install', 'chromium']); + for (const suite of leg.suites) + await step(join(job, suite), ['mise', 'exec', '--', 'pnpm', 'exec', 'playwright', 'install', 'chromium']); const e2e = await step(job, ['mise', 'run', 'e2e', leg.app], trusted); large[leg.app] = { build, e2e }; } @@ -272,7 +277,7 @@ test('check and test build no app, a suite’s app included, and e2e builds the const dir = await checkout(await gitOk(origin, 'rev-parse', 'HEAD')); await step(dir, ['mise', 'run', 'install']); for (const task of ['check', 'test']) assert.ok(!(await planned(dir, task)).includes('@acme/web#build'), task); - assert.deepEqual(await planned(dir, 'e2e'), ['@acme/web#build', '@acme/web-e2e#e2e']); + assert.deepEqual(await planned(dir, 'e2e'), ['@acme/web#build', '@acme/web-e2e#e2e', '@acme/web-e2e2#e2e']); }); let first: Run; @@ -287,7 +292,7 @@ test('the first run gives both apps a large job, publishes each image from the o app: 'web', hash: '', runner: 'ubuntu-latest', - suite: 'e2e/web', + suites: ['e2e/web', 'e2e/web2'], context: 'output', build: true, large: true, @@ -355,3 +360,15 @@ test('a change to site alone gives exactly site a large job, and publish builds assert.equal(run.published.web?.built, false); assert.equal(run.deployed.unchanged, true, JSON.stringify(run.deployed)); }); + +test('a change to a spec of web’s second suite alone gives web a large job, which runs both suites', async () => { + const sha = await push('push-5', (dir) => { + const spec = join(dir, 'e2e', 'web2', 'specs', 'home.spec.ts'); + writeFileSync(spec, `${readFileSync(spec, 'utf8')}// the second suite's spec edited, and nothing else\n`); + }); + const run = await pipeline(sha); + assert.deepEqual(withJob(run), ['web']); + assert.equal([...(run.large.web?.e2e ?? '').matchAll(/\d+ passed \(/g)].length, 2, 'both suites ran'); + for (const app of ['web', 'site']) assert.equal(run.published[app]?.built, false, app); + assert.equal(run.deployed.unchanged, true, JSON.stringify(run.deployed)); +}); From 64d8d94e87fa1a8338cffd9d0b9d2edb17e4196a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:55:57 +0100 Subject: [PATCH 178/194] plx-ci plan asks the e2e of every suite of an app, and says Turbo's HIT or MISS per task; the large job installs each suite's browser An app with suites has work when its build or the e2e of any of its suites is a MISS or unknown. The per-app line says a MISS is an entry not found or a cache that did not answer, as a server answering 500 gives one without a warning; a failing turbow's last line is the plan's line. The header of _e2e.yml says the plan job installs mise's tools and no package of the repo, and runs the checkout's turbow with the cache's token. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/_e2e.yml | 30 ++++---- packages/cli-ci/src/commands/plan.ts | 2 +- packages/cli-ci/src/core/plan.ts | 101 ++++++++++++++++----------- 3 files changed, 79 insertions(+), 54 deletions(-) diff --git a/.github/workflows/_e2e.yml b/.github/workflows/_e2e.yml index 30080da3..881753eb 100644 --- a/.github/workflows/_e2e.yml +++ b/.github/workflows/_e2e.yml @@ -19,9 +19,10 @@ name: _e2e # # An app gets an e2e job where it has work: the plan asks the trusted cache, # in its dry run, whether it holds the tasks the job would run, and gives the -# job to an app with a suite whose build or suite's e2e is a MISS, and to an -# app without a suite, built from the output, whose image is missing and whose -# build is a MISS; an app with a Dockerfile of its own and no suite gets none +# job to an app with suites whose build or the e2e of any of whose suites is a +# MISS, and to an app without a suite, built from the output, whose image is +# missing and whose build is a MISS; an app with a Dockerfile of its own and +# no suite gets none # (plx-ci's core/plan.ts states the rule). What the plan cannot find out, as # where the cache step announced no server or a pull request from a fork has # no secrets, counts as work, and its log says why. A run in which no app has @@ -34,8 +35,11 @@ name: _e2e # # The plan job is within § 5.3: it starts the trusted cache alone, and its dry # run only asks it, a HEAD request per task, restoring and writing nothing; it -# installs no package, runs no verb, check or test, and builds nothing, so no -# output of any cache enters its tree, and its result is hashes and statuses. +# installs mise's tools (node, plx-ci) and no package of the repo, runs no +# verb, check or test, and builds nothing, so no output of any cache enters +# its tree, and its result is hashes and statuses. It runs the checkout's +# ./turbow, which names the trusted cache, with the server's address and the +# job's token in its environment. # # The e2e job neither checks # nor tests (the test job did) and reaches the trusted cache alone, from a @@ -381,15 +385,17 @@ jobs: APP: ${{ matrix.app }} NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ steps.key.outputs.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }} run: mise run build "$APP" - # Chromium at the version the suite's Playwright pins, into the cache - # the medium and large slots share; with its system libraries on the - # forge's runners (the environment image carries them). - - name: The suite's browser - if: ${{ matrix.suite != '' }} + # Chromium at the version each suite's Playwright pins, in each suite's + # directory, since two suites may pin two versions, whose browsers + # differ; into the cache the medium and large slots share; with its + # system libraries on the forge's runners (the environment image carries + # them). + - name: The suites' browsers + if: ${{ join(matrix.suites, '') != '' }} env: - SUITE: ${{ matrix.suite }} + SUITES: ${{ join(matrix.suites, ' ') }} WITH_DEPS: ${{ runner.environment == 'github-hosted' && 'yes' || '' }} - run: cd "$SUITE" && pnpm exec playwright install ${WITH_DEPS:+--with-deps} chromium + run: for suite in $SUITES; do (cd "$suite" && pnpm exec playwright install ${WITH_DEPS:+--with-deps} chromium); done - name: E2E env: APP: ${{ matrix.app }} diff --git a/packages/cli-ci/src/commands/plan.ts b/packages/cli-ci/src/commands/plan.ts index c809c7e3..86f7384e 100644 --- a/packages/cli-ci/src/commands/plan.ts +++ b/packages/cli-ci/src/commands/plan.ts @@ -80,7 +80,7 @@ export function register(program: Command): void { [ ...r.legs.map( (l) => - `${l.large ? `e2e ${l.runner}` : 'no e2e'} ${l.app} ${l.hash} ${l.suite || '(no suite)'}; publish ${l.build ? `builds from ${l.context === 'output' ? 'the build output' : 'a pruned context'}` : 'tags'}`, + `${l.large ? `e2e ${l.runner}` : 'no e2e'} ${l.app} ${l.hash} ${l.suites.join(' ') || '(no suite)'}; publish ${l.build ? `builds from ${l.context === 'output' ? 'the build output' : 'a pruned context'}` : 'tags'}`, ), ...r.deploys.map((l) => `deploy ${l.app} ${l.host} ${l.image}`), ].join('\n'), diff --git a/packages/cli-ci/src/core/plan.ts b/packages/cli-ci/src/core/plan.ts index ed65657d..815e3309 100644 --- a/packages/cli-ci/src/core/plan.ts +++ b/packages/cli-ci/src/core/plan.ts @@ -6,19 +6,21 @@ // or the image is there and publish adds the commit's tag; what publish makes // it from, `output`, the directory the app's build leaves (an app from // app-nextjs, by its marker), or `pruned`, a pruned context its Dockerfile -// builds itself from (§ 4 PLX-Delivery); the directory of the app's E2E -// suite, empty for none, for the large job's browser; and `large`, whether -// the app gets a large job, its e2e job. A suite is what `mise run e2e ` -// runs: a package whose e2e task Turbo has wait for the app's build. +// builds itself from (§ 4 PLX-Delivery); the directories of the app's E2E +// suites, none or several, for the large job's browsers; and `large`, whether +// the app gets a large job, its e2e job. The suites are what `mise run e2e +// ` runs: the packages whose e2e task Turbo has wait for the app's build. // // An app's large job has work when a task it would run is a MISS in the -// trusted cache and its result is needed. The suite's e2e, where the app has a -// suite, is always needed; the app's build output is needed when the app has -// a suite, which starts it, and when the image is missing and is built from -// the output, which publish restores. So an app with a suite gets a large job -// when its build or its suite's e2e is a MISS; one without a suite, built from -// the output, when its image is missing and its build is a MISS; one with a -// Dockerfile of its own and no suite never, since its publish builds itself. +// trusted cache and its result is needed. The e2e of each of the app's suites +// is always needed; the app's build output is needed when the app has one or +// more suites, which start it, and when the image is missing and is built from +// the output, which publish restores. So an app with suites gets a large job +// when its build or the e2e of any of its suites is a MISS; one without a +// suite, built from the output, when its image is missing and its build is a +// MISS; one with a Dockerfile of its own and no suite never, since its publish +// builds itself. A MISS is Turbo's word: an entry not found, or a cache that +// did not answer for it, and the plan's line for the app says no more. // A task the package does not define (``) is no MISS that asks // for a job. What the plan cannot find out counts as work: without a turbow // to name the cache, with the cache `none` or no cache step, with a dry run @@ -60,19 +62,21 @@ import { parseAllDocuments } from 'yaml'; import { craneDigest, imageName } from './registry.ts'; import { runnerOf, type Strategy } from './strategy.ts'; -/** Whether the trusted cache holds an app's build, and its suite's e2e (true where it has no suite: nothing to hold). */ +/** Whether the trusted cache holds an app's build, and the e2e of every one of its suites (true where it has none). */ export interface Cached { build: boolean; e2e: boolean; } -/** One app's build hash, Turbo's hash of its package's build task, the directory of its E2E suite, and what the cache holds. */ +/** One app's build hash, Turbo's hash of its package's build task, the directories of its E2E suites, and what the cache holds. */ export interface Hash { app: string; hash: string; - suite: string; - /** Absent where the dry run said nothing of the cache: every task unknown. */ + suites: string[]; + /** Absent where the dry run said nothing of the cache for one of these tasks: every one of them unknown. */ cached?: Cached; + /** With `cached`: whether the cache holds each task, `build` and each suite's directory, in that order. */ + hits?: Record; } /** Turbo's marker for a task whose script the package does not define. */ @@ -99,9 +103,10 @@ function tasksOf(dryRun: string): { tasks: DryTask[]; unknown?: string } { /** * The build hashes from Turbo's dry run (`turbo run build e2e --dry-run=json`), - * per app, by its package's name; the directory of the first package whose - * e2e task waits for that build; and whether the cache holds the two, where - * the dry run gives both a cache status. + * per app, by its package's name; the directories of the packages whose e2e + * task waits for that build, its suites, sorted; and whether the cache holds + * the build and each suite's e2e, where the dry run gives every one of them a + * cache status. */ export function hashesOf(dryRun: string, packages: Record): Hash[] { const { tasks } = tasksOf(dryRun); @@ -111,11 +116,15 @@ export function hashesOf(dryRun: string, packages: Record): Hash const suites = tasks .filter((t) => t.taskId.endsWith('#e2e') && t.dependencies?.includes(build.taskId)) .sort((x, y) => (x.directory ?? '').localeCompare(y.directory ?? '')); - const suite = suites[0]; const hit = (t: DryTask) => t.cache?.status === 'HIT'; - const known = told(build) && (!suite || told(suite)); - const cached = known ? { cached: { build: hit(build), e2e: suite ? hit(suite) : true } } : {}; - return [{ app, hash: build.hash, suite: suite?.directory ?? '', ...cached }]; + const known = told(build) && suites.every(told); + const cached = known + ? { + cached: { build: hit(build), e2e: suites.every(hit) }, + hits: Object.fromEntries([['build', hit(build)], ...suites.map((t) => [t.directory ?? t.taskId, hit(t)])]), + } + : {}; + return [{ app, hash: build.hash, suites: suites.map((t) => t.directory ?? ''), ...cached }]; }); } @@ -158,6 +167,9 @@ export async function turboOf(ctx: Context, dir: string): Promise { throw new UsageError('pnpm-lock.yaml locks no turbo for the workspace root, which the repo’s verbs run'); } +/** A hash with nothing known of the cache. */ +const forgotten = ({ cached: _, hits: __, ...hash }: Hash): Hash => hash; + /** The hashes, and why the plan could not ask the trusted cache, empty where it could. */ export interface Hashes { hashes: Hash[]; @@ -186,7 +198,7 @@ export async function readHashes( const dry = ['run', 'build', 'e2e', '--dry-run=json']; const unasked = async (why: string): Promise => { const out = await ctx.read('npx', ['--yes', turbo, ...dry], { cwd: dir, env }); - return { hashes: hashesOf(out, packages).map(({ cached: _, ...hash }) => hash), why }; + return { hashes: hashesOf(out, packages).map(forgotten), why }; }; try { await ctx.readFile(`${dir}/turbow`); @@ -211,7 +223,7 @@ export async function readHashes( const line = await said(); const without = /^without a remote cache: (.*)$/.exec(line)?.[1]; const why = without ?? (await unavailable()); - if (why !== undefined) return { hashes: hashesOf(out, packages).map(({ cached: _, ...h }) => h), why }; + if (why !== undefined) return { hashes: hashesOf(out, packages).map(forgotten), why }; const { unknown } = tasksOf(out); if (unknown !== undefined) return { @@ -221,7 +233,12 @@ export async function readHashes( return { hashes: hashesOf(out, packages), why: '' }; } catch (error) { if (!(error instanceof ExecError)) throw error; - return unasked((await said()) || `turbow failed: ${error.message.split('\n')[0]}`); + // turbow's own words, its last line: the reason it gives, or what failed under it. + const last = (await lines()) + .filter((l) => l.trim() !== '') + .at(-1) + ?.replace(/^turbow:\s*/, ''); + return unasked(`turbow failed: ${last ?? error.message.split('\n')[0]}`); } finally { await ctx.stage(step('rm', ['-rf', shim])); } @@ -259,8 +276,8 @@ export interface Leg { hash: string; /** The runner the app's e2e job asks for. */ runner: string; - /** The directory of the app's E2E suite, empty for none. */ - suite: string; + /** The directories of the app's E2E suites, none for none. */ + suites: string[]; /** What publish makes the image from. */ context: ImageContext; /** The forge's registry lacks `build-`: publish builds the image; else it tags the one there. */ @@ -287,7 +304,7 @@ export function legsOf( const found = hashes.find((h) => h.app === app); if (!found) throw new UsageError(`no build hash for ${app}; is it an app package of the workspace?`); const runner = runnerOf(strategy, 'large', `exo-large-${run.runId}-${app}-${run.attempt}`); - return { app, hash: found.hash, runner, suite: found.suite }; + return { app, hash: found.hash, runner, suites: found.suites }; }); } @@ -349,9 +366,9 @@ export async function plan(ctx: Context, dir: string, options: PlanOptions): Pro const build = (await craneDigest(ctx, ref)) === undefined; ctx.say(`${leg.app}: ${ref} ${build ? 'is missing; publish builds it' : 'exists; publish tags it'}`); const context = await imageContextOf(ctx, dir, leg.app); - const cached = hashes.find((h) => h.app === leg.app)?.cached; - const large = hasWork({ suite: leg.suite, context, build }, cached); - ctx.say(`${leg.app}: ${holds(leg.suite, cached)}; ${large ? 'a large job' : 'no large job'}`); + const found = hashes.find((h) => h.app === leg.app); + const large = hasWork({ suites: leg.suites, context, build }, found?.cached); + ctx.say(`${leg.app}: ${holds(found?.hits)}; ${large ? 'a large job' : 'no large job'}`); result.legs.push({ ...leg, context, build, large }); } if (options.deploy?.environment) { @@ -364,20 +381,22 @@ export async function plan(ctx: Context, dir: string, options: PlanOptions): Pro } /** Whether an app's large job has work (see the top): a task it would run is a MISS, or unknown, and its result is needed. */ -export function hasWork(leg: Pick, cached: Cached | undefined): boolean { +export function hasWork(leg: Pick, cached: Cached | undefined): boolean { const buildMiss = !cached?.build; - if (leg.suite) return buildMiss || !cached?.e2e; + if (leg.suites.length > 0) return buildMiss || !cached?.e2e; return leg.context === 'output' && leg.build && buildMiss; } -/** What the trusted cache holds of an app, as the plan says it. */ -function holds(suite: string, cached: Cached | undefined): string { - if (!cached) return 'the trusted cache was not asked'; - if (!suite) return `the trusted cache ${cached.build ? 'holds' : 'lacks'} its build`; - if (cached.build && cached.e2e) return 'the trusted cache holds its build and its suite’s e2e'; - if (cached.build) return 'the trusted cache holds its build, not its suite’s e2e'; - if (cached.e2e) return 'the trusted cache holds its suite’s e2e, not its build'; - return 'the trusted cache holds neither its build nor its suite’s e2e'; +/** + * What the dry run said of an app's tasks, as the plan says it: Turbo's HIT or + * MISS for each, a MISS being an entry not found, or a cache that did not + * answer for it (a server that answers 500 gives a MISS without a warning). + */ +function holds(hits: Record | undefined): string { + if (!hits) return 'the trusted cache was not asked'; + const said = Object.entries(hits).map(([task, hit]) => `${task} ${hit ? 'HIT' : 'MISS'}`); + const miss = Object.values(hits).includes(false) ? ' (a MISS: not found, or not answered)' : ''; + return `in the trusted cache, ${said.join(', ')}${miss}`; } /** The outputs of a plan for the workflow: the large jobs' matrix, every app for publish, the deploys, the environment. */ From 7b064c59e21c3bfe36a79be3dc2038318989b676 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 00:56:29 +0100 Subject: [PATCH 179/194] Test: a second suite without a cache status leaves the app's statuses unknown A mutation that took the first suite's status for all survived without it. Co-Authored-By: Claude Fable 5.2 --- packages/cli-ci/src/core/planCache.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/cli-ci/src/core/planCache.test.ts b/packages/cli-ci/src/core/planCache.test.ts index 409f818c..67b93d9c 100644 --- a/packages/cli-ci/src/core/planCache.test.ts +++ b/packages/cli-ci/src/core/planCache.test.ts @@ -134,6 +134,8 @@ test('hashesOf reads whether the cache holds an app’s build and the e2e of all assert.deepEqual(myApp?.cached, { build: false, e2e: true }); // A Turbo whose dry run gives no cache field for a task: unknown, never a hit. assert.equal(hashesOf(dryRun({ websiteE2e: 'HIT' }), packages)[0]?.cached, undefined); + // The second suite without a status: the app's statuses are unknown, not a MISS the cache answered. + assert.equal(hashesOf(dryRun({ ...ALL_HIT, websiteSmoke: undefined }), packages)[0]?.cached, undefined); }); test('an app with two suites gets a large job when the e2e of either is a MISS or unknown, and none when both are HITs', async () => { From 8a9f856d58b63bfd55af8f409f14559847559e8c Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 01:46:10 +0100 Subject: [PATCH 180/194] The dry run says which answers would be removed, and removes none (test) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A mutation survived the review: nothing held the dry run's wording. The test asserts "to be removed from …" for each marker and key, never "removed from", nothing pushed, no pull request, and the checkout's marker byte for byte. Red against the mutation that drops "to be". Co-Authored-By: Claude Opus 5.5 --- packages/dev/src/ship.integration.test.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/dev/src/ship.integration.test.ts b/packages/dev/src/ship.integration.test.ts index 443810a1..d277e1dd 100644 --- a/packages/dev/src/ship.integration.test.ts +++ b/packages/dev/src/ship.integration.test.ts @@ -1953,6 +1953,22 @@ test('update: an answer to a question the version no longer asks or reads leaves assert.ok(has(ops.out, 'removed from PLEXUS.md, since no template asks or reads it at 0.2.0: registry'), ops.out); }); +test('update: the dry run says which answers would be removed, and removes none', async () => { + const { web } = askedLess('update-asked-less-dry'); + const { error, out } = await runUpdate({ dryRun: true, yes: true }, { repo: web }); + assert.equal(error, undefined, out); + for (const [marker, key] of [ + ['PLEXUS.md', 'registry'], + ['apps/site/PLEXUS.md', 'app_only'], + ] as const) + assert.ok(has(out, `to be removed from ${marker}, since no template asks or reads it at 0.2.0: ${key}`), out); + assert.doesNotMatch(out, /^ *removed from /m, 'never that it was'); + assert.throws(() => onVersion('acme-web', '0.2.0', 'PLEXUS.md'), 'nothing pushed'); + assert.ok(!fakeLog().some((l) => has(l, 'pr create')), 'no pull request'); + assert.equal(read(join(web, 'PLEXUS.md')), ROOT_ASKED_LESS, 'the checkout keeps every key'); + assert.equal(git(web, 'status', '--porcelain'), '', 'checkout clean'); +}); + test('update: a later run still names the answers removed, read from the commit, but no longer one the branch holds again', async () => { const { web } = askedLess('update-asked-less-later'); const first = await runUpdate({ yes: true }, { repo: web }); From 2ca64183241cdea59805a0ae95a0fd0369fc02f0 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 01:54:53 +0100 Subject: [PATCH 181/194] Test: a suite says what its run needs in run.ts, which an update leaves alone The template's tests render run.ts born once, kept by an update also where the template's own run.ts changes, and added to a suite born before it. The newborn's stateful app refuses to start unless a setting names its own address, and has a worker started from the same output; its suite's run.ts gives the environment, a setting of the server alone, a PostgreSQL setting and the worker, and its specs read the database and wait on the worker. A stateless suite without run.ts runs as one with it as generated; every kill leaves no worker either. Refs PLX-200 Co-Authored-By: Claude Opus 5.5 --- newborns/e2e-playwright.test.ts | 143 ++++++++++++++++++++++--- packages/lib/src/e2ePlaywright.test.ts | 85 ++++++++++++++- 2 files changed, 214 insertions(+), 14 deletions(-) diff --git a/newborns/e2e-playwright.test.ts b/newborns/e2e-playwright.test.ts index c52934e1..2fa73f93 100644 --- a/newborns/e2e-playwright.test.ts +++ b/newborns/e2e-playwright.test.ts @@ -8,15 +8,22 @@ // for an app with a `migrate` or `seed` script and for no other, `migrate` runs // with NODE_ENV=production, then `seed`. An app that needs a database in a repo // without the answer `postgres` fails before anything starts, naming the answer. +// The stateless suites keep their `run.ts` as generated, and a suite without it +// runs as one with it. The stateful suite's `run.ts` says what its app needs: a +// setting that names the server's own address, without which the server refuses +// to start, a secret and a directory for files; a setting of the server alone; a +// PostgreSQL setting; and a second process from the build output, a worker that +// writes into the database. Its specs read the database through DATABASE_URL, +// see the environment, and wait on the worker. // Without Chromium in Playwright's shared cache the run fails, naming the // command that installs it, and that command does. The suite's own `e2e` fails // without the build output and does not build it. Editing a spec moves the // hash of the suite's `e2e` and leaves the app's `build`; editing the app, or // giving it a `migrate` script, moves both. A run killed by SIGINT or SIGKILL // of `mise`, or by SIGKILL of the Playwright runner that started the app, -// leaves no server and no PostgreSQL behind. The repo's own `check`, `plx -// doctor` in it, passes, and says nothing of the suites' files. Created by `plx -// new`; it needs the network. +// leaves no server, no worker and no PostgreSQL behind. The repo's own `check`, +// `plx doctor` in it, passes, and says nothing of the suites' files. Created by +// `plx new`; it needs the network. // // Playwright's shared cache is, for these tests, `node_modules/.cache/ms-playwright` // of this workspace: kept from one run to the next and never the user's. @@ -72,10 +79,12 @@ const EXTRAS: Record void> = { }); }, // The stateful app's migrate and seed as its author writes them, run with the database in DATABASE_URL, and a page - // that reads what they wrote; migrate says which NODE_ENV it ran with. + // that reads what they wrote; migrate says which NODE_ENV it ran with. Its server refuses to start unless ACME_URL + // names its own address; started with ACME_TASK=work it is the worker, which records in the database, a few seconds + // after it started, the ACME_POOL it was given. Its suite's run.ts says all of that, and its specs check it. stateful: (app, suite) => { scripts(app, { - migrate: `echo "migrate saw NODE_ENV=$NODE_ENV" && ${psql('create table greeting (text text not null)')}`, + migrate: `echo "migrate saw NODE_ENV=$NODE_ENV" && ${psql('create table greeting (text text not null); create table worked (pool text not null)')}`, seed: psql("insert into greeting values ('hello from the seed')"), }); put(app, { @@ -86,18 +95,87 @@ const EXTRAS: Record void> = { 'export default async function Greeting() {', ' await connection();', " const sql = ['-Atc', 'select text from greeting'];", - " return

{execFileSync('psql', [process.env.DATABASE_URL ?? '', ...sql], { encoding: 'utf8' }).trim()}

;", + ' return (', + ' <>', + "

{execFileSync('psql', [process.env.DATABASE_URL ?? '', ...sql], { encoding: 'utf8' }).trim()}

", + '

pool {process.env.ACME_POOL}

', + ' ', + ' );', + '}', + '', + ].join('\n'), + 'src/instrumentation.ts': [ + 'export async function register() {', + " if (process.env.NEXT_RUNTIME === 'nodejs') await import('./settings');", + '}', + '', + ].join('\n'), + 'src/settings.ts': [ + "import { execFileSync } from 'node:child_process';", + '', + 'const { ACME_POOL, ACME_TASK, ACME_URL, DATABASE_URL, HOSTNAME, PORT } = process.env;', + "if (ACME_TASK === 'work') {", + " console.log('the worker answers on port', PORT);", + ' setTimeout(() => {', + " const pool = ACME_POOL ?? 'none';", + " execFileSync('psql', [DATABASE_URL ?? '', '-c', \"insert into worked values ('\" + pool + \"')\"]);", + ' }, 3_000);', + "} else if (ACME_URL !== ['http://', HOSTNAME, ':', PORT].join('')) {", + " console.error('the server refuses to start: ACME_URL is', ACME_URL ?? 'unset', 'and not its own address');", + ' process.exit(1);', '}', '', ].join('\n'), }); put(suite, { + 'run.ts': [ + "import type { Needs, Run } from './setup.ts';", + '', + 'export default async function needs(run: Run): Promise {', + ' return {', + " env: { ACME_URL: run.address, ACME_SECRET: 'a secret of the run', ACME_FILES: await run.directory() },", + " server: { env: { ACME_POOL: '20' } },", + ' postgres: { max_connections: 200 },', + " processes: [{ env: { ACME_TASK: 'work' } }],", + ' };', + '}', + '', + ].join('\n'), 'specs/greeting.spec.ts': spec( "test('the page shows what the seed wrote into the migrated database', async ({ page }) => {", " await page.goto('/greeting');", " await expect(page.getByText('hello from the seed')).toBeVisible();", '});', ), + 'specs/needs.spec.ts': [ + "import { execFileSync } from 'node:child_process';", + "import { existsSync } from 'node:fs';", + "import { expect, test } from '@playwright/test';", + '', + 'const sql = (query: string) =>', + " execFileSync('psql', [process.env.DATABASE_URL ?? '', '-Atc', query], { encoding: 'utf8' }).trim();", + '', + "test('a spec reads the database of the run, which has the settings run.ts gave it', () => {", + " expect(sql('select text from greeting')).toBe('hello from the seed');", + " expect(sql('show max_connections')).toBe('200');", + '});', + '', + "test('a spec sees the environment run.ts gave everything', () => {", + ' expect(process.env.ACME_URL).toBe(process.env.PLX_E2E_BASE_URL);', + " expect(process.env.ACME_SECRET).toBe('a secret of the run');", + " expect(existsSync(process.env.ACME_FILES ?? '')).toBe(true);", + '});', + '', + "test('the server has the environment run.ts gave it alone', async ({ page }) => {", + " await page.goto('/greeting');", + " await expect(page.getByText('pool 20')).toBeVisible();", + '});', + '', + "test('a spec waits on the worker, a second process without the environment of the server alone', async () => {", + " await expect.poll(() => sql('select pool from worked'), { timeout: 30_000 }).toBe('none');", + '});', + '', + ].join('\n'), }); }, // An app of the stateless profile with a seed script and no migrate. @@ -198,6 +276,19 @@ describe('a repo with two stateless apps, one name the end of the other, and the assert.equal(existsSync(join(served, '.next', 'cache', 'images')), false, 'the output was served itself'); }); + test('a suite without run.ts runs as one with run.ts as generated', async () => { + const run = tmp('s4'); + try { + rmSync(join(clone, 'e2e', 'less', 'run.ts')); + const ran = await tryRun('mise', ['run', 'e2e', 'less'], clone, { ...SHARED, TMPDIR: run }); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, /\s1 passed \(/); + assert.deepEqual(leftIn(run), []); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + test('passes its own check, plx doctor in it, which says nothing of the suites', async () => { const ran = await tryRun('mise', ['run', 'check'], clone); assert.ok(ran.ok, ran.output); @@ -276,12 +367,31 @@ describe('a repo with the answer postgres, a stateful app, an app with a seed al ); }); - test('passes mise e2e from a fresh clone: migrate in production, then seed, against the database the server gets', async () => { - const ran = await tryRun('mise', ['run', 'e2e', 'stateful'], clone, SHARED); + test('passes mise e2e from a fresh clone: migrate in production, then seed, against the database the server gets, with what run.ts says', async () => { + const run = tmp('s2'); + const ran = await tryRun('mise', ['run', 'e2e', 'stateful'], clone, { ...SHARED, TMPDIR: run }); assert.ok(ran.ok, ran.output); assert.match(ran.output, /migrate saw NODE_ENV=production\b/); assert.match(ran.output, /CREATE TABLE[\s\S]*INSERT 0 1/); - assert.match(ran.output, /\s2 passed \(/); + assert.match(ran.output, /the worker answers on port \d+/); + assert.match(ran.output, /\s6 passed \(/); + assert.deepEqual(leftIn(run), [], 'no copy and no directory of run.ts is left'); + }); + + test('without the setting that names its address the server refuses to start, and the run fails leaving nothing', async () => { + const run = tmp('s3'); + const file = join(clone, 'e2e', 'stateful', 'run.ts'); + try { + put(clone, { 'e2e/stateful/run.ts': readFileSync(file, 'utf8').replace('ACME_URL: run.address, ', '') }); + const ran = await tryRun('mise', ['run', 'e2e', 'stateful'], clone, { ...SHARED, TMPDIR: run }); + assert.equal(ran.ok, false, ran.output); + assert.match(ran.output, /the server refuses to start: ACME_URL is unset/); + assert.match(ran.output, /the server exited with 1 before/); + assert.deepEqual(leftIn(run), []); + assert.deepEqual(await mentioning(run), [], 'no PostgreSQL is left'); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } }); test('an app with a seed script and no migrate gets a database and its seed, and no migrate', async () => { @@ -323,7 +433,7 @@ describe('a repo with the answer postgres, a stateful app, an app with a seed al ], ]; for (const [at, [how, kill]] of kills.entries()) - test(`a run killed by ${how} leaves no server and no PostgreSQL behind`, async () => { + test(`a run killed by ${how} leaves no server, no worker and no PostgreSQL behind`, async () => { // A spec that outlasts the kill; the run's temporary files, the database's cluster among them, are found by TMPDIR. const dir = tmp(`t${at}`); // A spec of its own in each run, so that a run that went on to its end leaves no cache hit for the next. @@ -361,6 +471,15 @@ describe('a repo with the answer postgres, a stateful app, an app with a seed al () => false, ); assert.ok(await answers(), 'the server answers before the kill'); + // The worker is started once the server answers, and may say so after the specs began. + await until('the worker answers', () => /the worker answers on port \d+/.test(run.output()), 60_000); + const workerPort = /the worker answers on port (\d+)/.exec(run.output())?.[1]; + const works = () => + fetch(`http://127.0.0.1:${workerPort}/healthz`).then( + (r) => r.ok, + () => false, + ); + assert.ok(await works(), 'the worker answers before the kill'); assert.ok( (await mentioning(dir)).some((line) => /postgres/.test(line)), 'and its database runs', @@ -368,8 +487,8 @@ describe('a repo with the answer postgres, a stateful app, an app with a seed al await kill(run); await until(`the run ends after ${how}`, () => ended, 120_000); await until( - `after ${how}, the server and the database are gone`, - async () => !(await answers()) && (await mentioning(dir)).length === 0, + `after ${how}, the server, the worker and the database are gone`, + async () => !(await answers()) && !(await works()) && (await mentioning(dir)).length === 0, 30_000, ); } finally { diff --git a/packages/lib/src/e2ePlaywright.test.ts b/packages/lib/src/e2ePlaywright.test.ts index 24e3b97f..f26f5a2e 100644 --- a/packages/lib/src/e2ePlaywright.test.ts +++ b/packages/lib/src/e2ePlaywright.test.ts @@ -1,5 +1,8 @@ import assert from 'node:assert/strict'; +import { join } from 'node:path'; import { test } from 'node:test'; +import { merge, readTree, render as renderTrees, type Tree } from '@plexus-ms/cli-template'; +import { templatesRoot } from './templatesRoot.ts'; import { pathsOf, renderBundled, textOf } from './testing/bundled.ts'; const render = (answers: Record = { app: '@acme/web' }) => renderBundled(['e2e-playwright'], answers); @@ -12,6 +15,7 @@ test('a suite is rendered as a package of its own: its Playwright configuration, 'PLEXUS.md', 'package.json', 'playwright.config.ts', + 'run.ts', 'setup.ts', 'specs/home.spec.ts', 'turbo.json', @@ -54,9 +58,9 @@ test("the marker names the verb that runs the suite: mise e2e at the repo's root assert.doesNotMatch(marker, /mise :e2e/); }); -test('the marker and the spec are written once, the rest is merged', async () => { +test('the marker, the spec and run.ts are written once, the rest is merged', async () => { const result = await render(); - const once = ['PLEXUS.md', 'specs/home.spec.ts']; + const once = ['PLEXUS.md', 'run.ts', 'specs/home.spec.ts']; for (const [path, origin] of result.files) assert.equal(origin.policy, once.includes(path) ? 'born-once' : 'merge', path); }); @@ -76,3 +80,80 @@ test('repo-turbo makes room for suites: e2e/* is a workspace glob, and its packa for (const glob of globs) assert.match(sources ?? '', new RegExp(`"${glob.replace('*', '\\*')}/package\\.json"`), glob); }); + +test("setup.ts says it is generated and that what the run needs goes in run.ts; run.ts says it is the repo's", async () => { + const result = await render(); + const head = (path: string) => textOf(result, path).split('\n').slice(0, 4).join('\n'); + assert.match(head('setup.ts'), /^\/\/ Generated from plexus-ms\/tooling, templates\/e2e-playwright: /); + assert.match(head('setup.ts'), /run\.ts/); + assert.match(head('run.ts'), /the repo's own/); + assert.match(head('run.ts'), /never touched by an update/); +}); + +test('run.ts as generated asks for nothing, and setup.ts names no setting of any app', async () => { + const result = await render({ app: '@acme/shop' }); + assert.match(textOf(result, 'run.ts'), /return \{\};/); + assert.doesNotMatch(textOf(result, 'run.ts'), /@acme\/shop/); + // The names the setup gives values to are its own and Next's, never an app's. + const named = [...textOf(result, 'setup.ts').matchAll(/\b([A-Z][A-Z0-9]*_[A-Z0-9_]+|PORT|HOSTNAME)\b(?=\s*[:=])/g)]; + assert.deepEqual([...new Set(named.map((m) => m[1]))].sort(), [ + 'DATABASE_URL', + 'HOSTNAME', + 'NODE_ENV', + 'PLX_E2E_BASE_URL', + 'PORT', + ]); +}); + +/** The template's render, its own run.ts replaced by `runTs` where given, or left out where null. */ +async function suite( + runTs?: string | null, +): Promise<{ tree: Tree; files: Awaited>['files'] }> { + const template = new Map(await readTree(join(templatesRoot(), 'e2e-playwright'))); + if (runTs === null) { + // The template before it had run.ts: neither the file nor its policy. + template.delete('files/run.ts'); + const manifest = template.get('template.yml'); + assert.ok(manifest); + const text = new TextDecoder().decode(manifest.bytes).replace(/^ {2}run\.ts: born-once\n/m, ''); + template.set('template.yml', { ...manifest, bytes: new TextEncoder().encode(text) }); + } else if (runTs !== undefined) + template.set('files/run.ts', { bytes: new TextEncoder().encode(runTs), mode: 0o100644 }); + const result = await renderTrees([template], { app: '@acme/web' }); + assert.deepEqual(result.errors, []); + return { tree: result.tree, files: result.files }; +} + +const noMerge = async () => { + throw new Error('no file of these merges is merged by content'); +}; + +test("an update leaves an edited run.ts alone, also where the template's own run.ts changes between the versions", async () => { + const [old, next] = [await suite(), await suite('// the next version\nexport default () => ({});\n')]; + const edited = new TextEncoder().encode( + '// the app says what its run needs\nexport default () => ({ env: { A: "b" } });\n', + ); + const current = new Map(old.tree).set('run.ts', { bytes: edited, mode: 0o100644 }); + const merged = await merge( + { old: old.tree, new: next.tree, current, files: { old: old.files, new: next.files } }, + noMerge, + ); + assert.deepEqual(merged.tree.get('run.ts')?.bytes, edited); + assert.deepEqual( + merged.report.filter((entry) => entry.path === 'run.ts'), + [{ path: 'run.ts', outcome: 'kept' }], + ); +}); + +test('a suite born before run.ts existed gets it as generated from its next update', async () => { + const [old, next] = [await suite(null), await suite()]; + const merged = await merge( + { old: old.tree, new: next.tree, current: old.tree, files: { old: old.files, new: next.files } }, + noMerge, + ); + assert.deepEqual(merged.tree.get('run.ts')?.bytes, next.tree.get('run.ts')?.bytes); + assert.deepEqual( + merged.report.filter((entry) => entry.path === 'run.ts'), + [{ path: 'run.ts', outcome: 'added' }], + ); +}); From 3e25ef1645d9b8b5dc0f205964fe2e0686a3087f Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 01:55:40 +0100 Subject: [PATCH 182/194] e2e-playwright: the app says what its run needs in run.ts, the suite's own A suite is born with run.ts, born once, in which the app says what its run needs: environment for migrate, seed, the server, further processes and the specs; environment for the server alone; PostgreSQL's settings; and further processes, each the output's server.js on a port of its own. Its default export is called with the server's address and a way to get a directory the setup removes, once the port is picked and before the database starts. setup.ts stays generated and holds no fact of any app: it hands the specs DATABASE_URL and the environment run.ts gives everything, and ends every process it starts as it ends the server. A suite without run.ts, or with it as generated, runs as before. The headers of setup.ts and run.ts and the suite's marker say which file is the repo's. Refs PLX-200 Co-Authored-By: Claude Opus 5.5 --- .../e2e-playwright/files/PLEXUS.md.jinja | 1 + templates/e2e-playwright/files/run.ts | 7 ++ templates/e2e-playwright/files/setup.ts.jinja | 78 +++++++++++++++---- templates/e2e-playwright/template.yml | 5 +- 4 files changed, 73 insertions(+), 18 deletions(-) create mode 100644 templates/e2e-playwright/files/run.ts diff --git a/templates/e2e-playwright/files/PLEXUS.md.jinja b/templates/e2e-playwright/files/PLEXUS.md.jinja index 05c3813d..faec2be2 100644 --- a/templates/e2e-playwright/files/PLEXUS.md.jinja +++ b/templates/e2e-playwright/files/PLEXUS.md.jinja @@ -1,3 +1,4 @@ - The end-to-end suite of `{{ app }}`: Playwright runs the specs in `specs/` in Chromium against the app's build output, which `setup.ts` starts as the standalone server, after a throwaway PostgreSQL and the app's `migrate` and `seed` where its `package.json` has either. +- What the app's run needs beyond that, settings for the seed, the server and the specs, PostgreSQL's settings and further processes from the build output, goes in `run.ts`, which is the suite's own, like the specs; `setup.ts` is generated, and `plx update` merges it. - It runs with `mise e2e ` at the repo's root, `` being the app's directory name, which builds the app first (the suite's own name is no name the verb takes); the suite's `e2e` script never builds, and fails without the build output. - Chromium comes from Playwright's shared cache, into which `pnpm exec playwright install chromium`, run in this directory, installs it. diff --git a/templates/e2e-playwright/files/run.ts b/templates/e2e-playwright/files/run.ts new file mode 100644 index 00000000..5c99c629 --- /dev/null +++ b/templates/e2e-playwright/files/run.ts @@ -0,0 +1,7 @@ +// This file is the repo's own, written at the suite's birth and never touched by an update: what the app's run needs +// beyond what setup.ts does, as its Needs says; setup.ts calls it once the server's port is picked, before the database. +import type { Needs, Run } from './setup.ts'; + +export default function needs(_run: Run): Needs { + return {}; +} diff --git a/templates/e2e-playwright/files/setup.ts.jinja b/templates/e2e-playwright/files/setup.ts.jinja index 058adb05..b4a72e89 100644 --- a/templates/e2e-playwright/files/setup.ts.jinja +++ b/templates/e2e-playwright/files/setup.ts.jinja @@ -1,5 +1,5 @@ -// The suite's global setup: it starts the app's build output as its image runs it, after a database, migrate and seed -// where the app has them, and hands the specs the address; it never builds: `mise e2e` builds the app before the suite. +// Generated from plexus-ms/tooling, templates/e2e-playwright: edit the template, never this file; run.ts is the repo's. +// The global setup: starts the app's build output, never building it, after a database, migrate and seed where it has them. import { type ChildProcess, spawn } from 'node:child_process'; import { once } from 'node:events'; import { existsSync, readdirSync, readFileSync } from 'node:fs'; @@ -13,6 +13,29 @@ import { chromium } from '@playwright/test'; /** The app this suite tests, by its package name. */ const APP = '{{ app }}'; +/** Environment variables, by name. */ +type Env = Record; + +/** What run.ts is given: what is known only once the run has begun. */ +export interface Run { + /** The server's address, as in http://127.0.0.1:41234: the specs' baseURL. */ + readonly address: string; + /** A new empty directory, removed at the end of the run. */ + directory(): Promise; +} + +/** What run.ts says the app's run needs beyond the database, migrate, seed and the server. */ +export interface Needs { + /** Environment for migrate, seed, the server, every further process and the specs. */ + env?: Env; + /** Environment for the server alone, over `env`. */ + server?: { env?: Env }; + /** Settings of the PostgreSQL server, as in `{ max_connections: 200 }`, where the app has a database. */ + postgres?: Record; + /** Further processes, each the output's server.js beside the server on a port of its own, with `env` under its own. */ + processes?: { env?: Env }[]; +} + export default async function setup(): Promise<() => Promise> { // Through the workspace dependency, never by a relative path. const app = path.dirname(createRequire(import.meta.url).resolve(`${APP}/package.json`)); @@ -42,33 +65,48 @@ export default async function setup(): Promise<() => Promise> { const teardown = async () => { for (const stop of stops.reverse()) await stop(); }; + /** A new directory, removed at the end. */ + const temporary = async () => { + const dir = await mkdtemp(path.join(tmpdir(), 'plx-e2e-')); + stops.push(() => rm(dir, { recursive: true, force: true })); + return dir; + }; + /** The output's server.js, started in `dir` on `port`, ended at the end and with this process. */ + const start = (dir: string, env: NodeJS.ProcessEnv, port: number): ChildProcess => { + // It exits at the end of its stdin, which this process holds, so that it never outlives this process. + const guard = "process.stdin.on('end', () => process.exit()).resume(); require('./server.js');"; + const child = spawn(process.execPath, ['-e', guard], { + cwd: dir, + env: { ...env, PORT: String(port), HOSTNAME: '127.0.0.1' }, + stdio: ['pipe', 'inherit', 'inherit'], + }); + stops.push(() => end(child)); + return child; + }; try { // A copy, since a running server writes into its own directory. - const copy = await mkdtemp(path.join(tmpdir(), 'plx-e2e-')); - stops.push(() => rm(copy, { recursive: true, force: true })); + const copy = await temporary(); await cp(output, copy, { recursive: true, verbatimSymlinks: true }); const server = within(copy); - const env: NodeJS.ProcessEnv = { ...process.env }; + const port = await freePort(); + const address = `http://127.0.0.1:${port}`; + const needs = await needed({ address, directory: temporary }); + const env: NodeJS.ProcessEnv = { ...process.env, ...needs.env }; if (entries.length > 0) { // From the binary the repo pins; migrate runs in the copy as the image runs it, seed in the app as developers do. const { createDatabase, startPostgres } = await import('@plexus-ms/test-postgres'); - const postgres = await startPostgres({ major: Number(major) }); + const postgres = await startPostgres({ major: Number(major), settings: needs.postgres }); stops.push(postgres.stop); env.DATABASE_URL = await createDatabase(postgres.url); if (entries.includes('migrate')) await run(['npm', 'run', 'migrate'], server, { ...env, NODE_ENV: 'production' }); if (entries.includes('seed')) await run(['npm', 'run', 'seed'], app, env); } - const port = await freePort(); - // The server exits at the end of its stdin, which this process holds, so that it never outlives this process. - const guard = "process.stdin.on('end', () => process.exit()).resume(); require('./server.js');"; - const started = spawn(process.execPath, ['-e', guard], { - cwd: server, - env: { ...env, PORT: String(port), HOSTNAME: '127.0.0.1' }, - stdio: ['pipe', 'inherit', 'inherit'], - }); - stops.push(() => end(started)); - const address = `http://127.0.0.1:${port}`; + const started = start(server, { ...env, ...needs.server?.env }, port); await ready(`${address}/healthz`, started); + for (const further of needs.processes ?? []) start(server, { ...env, ...further.env }, await freePort()); + // The specs run in workers that inherit this process's environment. + Object.assign(process.env, needs.env); + if (env.DATABASE_URL) process.env.DATABASE_URL = env.DATABASE_URL; process.env.PLX_E2E_BASE_URL = address; } catch (error) { await teardown(); @@ -77,6 +115,14 @@ export default async function setup(): Promise<() => Promise> { return teardown; } +/** What run.ts says the run needs; nothing where the suite has no run.ts. */ +async function needed(given: Run): Promise { + if (!existsSync(new URL('./run.ts', import.meta.url))) return {}; + const { default: needs } = await import('./run.ts'); + if (typeof needs !== 'function') throw new Error('run.ts exports no function by default, which setup.ts calls'); + return await needs(given); +} + /** * The app's directory in the output, as the app's build recorded it: `relativeAppDir` of the one * `.next/required-server-files.json` the output holds outside `node_modules`. diff --git a/templates/e2e-playwright/template.yml b/templates/e2e-playwright/template.yml index 9a4e2cca..660b576a 100644 --- a/templates/e2e-playwright/template.yml +++ b/templates/e2e-playwright/template.yml @@ -8,7 +8,8 @@ questions: help: "The app this suite tests, by its package name as its package.json gives it (as in @acme/shop): the suite lists it as a workspace dependency and starts its build output" policies: - # The marker and the spec are rendered at birth only: the spec is the author's from then on, and the - # marker's frontmatter is plx's. + # The marker, the spec and run.ts are rendered at birth only: the spec and run.ts, where the app says what + # its run needs, are the author's from then on, and the marker's frontmatter is plx's. setup.ts is merged. PLEXUS.md.jinja: born-once + run.ts: born-once specs/home.spec.ts.jinja: born-once From d83a12845d57247664bed0e1080bd3732f255946 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 02:05:34 +0100 Subject: [PATCH 183/194] The doctor's checks in the order of the pages: PLX-Repo/Hooks before PLX-Repo/Verbs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The contract page states the check of PLX-Repo/Hooks in § 2 and that of PLX-Repo/Verbs in § 3, each in a sentence of its own below its requirements block. CHECKS follows that order, so a repo's findings of the hooks come before those of the verbs, and the hermetic copy of the sentences says what the page says. Co-Authored-By: Claude Opus 5.5 --- packages/lib/src/doctor.test.ts | 12 ++++++------ packages/lib/src/doctor.ts | 2 +- packages/lib/src/testing/doctor-checks.md | 4 +++- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/lib/src/doctor.test.ts b/packages/lib/src/doctor.test.ts index c361dc3a..bae35658 100644 --- a/packages/lib/src/doctor.test.ts +++ b/packages/lib/src/doctor.test.ts @@ -122,21 +122,21 @@ const FAILING: Record Facts; problem: unit: () => repo({ marker: { problem: 'PLEXUS.md: no frontmatter: expected a `---` block at the top' } }), problem: /^PLEXUS\.md: no frontmatter/, }, - 'PLX-Repo/Verbs': { + 'PLX-Repo/Hooks': { unit: (deviations = []) => repo({ - tasks: { names: VERBS.filter((v) => v !== 'build') }, + hk: ['pre-commit'], marker: { declaration: { deviations, body: reasoned(deviations) } }, }), - problem: /^no root mise task `build`: add one, a no-op that passes/, + problem: /^hk\.pkl wires no `pre-push` hook$/, }, - 'PLX-Repo/Hooks': { + 'PLX-Repo/Verbs': { unit: (deviations = []) => repo({ - hk: ['pre-commit'], + tasks: { names: VERBS.filter((v) => v !== 'build') }, marker: { declaration: { deviations, body: reasoned(deviations) } }, }), - problem: /^hk\.pkl wires no `pre-push` hook$/, + problem: /^no root mise task `build`: add one, a no-op that passes/, }, 'PLX-App/Marker': { unit: (d) => app(undefined, {}, d), diff --git a/packages/lib/src/doctor.ts b/packages/lib/src/doctor.ts index d3bca5c3..befc024f 100644 --- a/packages/lib/src/doctor.ts +++ b/packages/lib/src/doctor.ts @@ -388,8 +388,8 @@ interface AppCheck { /** Every requirement doctor checks, by name: what the contract pages list, in their order. */ export const CHECKS: Readonly> = { 'PLX-Repo/Marker': { binds: 'repo', check: repoMarker }, - 'PLX-Repo/Verbs': { binds: 'repo', check: verbs }, 'PLX-Repo/Hooks': { binds: 'repo', check: hooks }, + 'PLX-Repo/Verbs': { binds: 'repo', check: verbs }, 'PLX-App/Marker': { binds: 'app', check: appMarker }, 'PLX-App/Compose': { binds: 'app', check: composeFile }, 'PLX-App/TenantLabel': { binds: 'app', check: onCompose(tenantLabel) }, diff --git a/packages/lib/src/testing/doctor-checks.md b/packages/lib/src/testing/doctor-checks.md index 571d5a32..5af6546c 100644 --- a/packages/lib/src/testing/doctor-checks.md +++ b/packages/lib/src/testing/doctor-checks.md @@ -8,7 +8,9 @@ set to a compendium checkout it reads the pages themselves instead. `plx doctor` checks `PLX-Repo/Marker`. -`plx doctor` checks of `PLX-Repo/Verbs` that `dev`, `build`, `check`, `test` and `e2e` exist as root mise tasks and that no `verify` is left, not what they run, in which order, or whether they pass, and of `PLX-Repo/Hooks` that `hk.pkl` wires a pre-commit hook and a pre-push hook, not what either runs. +`plx doctor` checks of `PLX-Repo/Hooks` that `hk.pkl` wires a pre-commit hook and a pre-push hook, written literally in its `hooks` block, not what either runs. + +`plx doctor` checks of `PLX-Repo/Verbs` that `dev`, `build`, `check`, `test` and `e2e` exist as root mise tasks and that no `verify` is left, not what they run, in which order, or whether they pass. `plx doctor` checks `PLX-App/Marker`. From 815c0191977bbbd8e9ba3ecdb8e2d1ab4146d48b Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 03:14:56 +0100 Subject: [PATCH 184/194] Test: run.ts fails loudly where it is wrong, and every process it asks for is watched A run.ts that never returns fails the run after a minute; one that returns nothing, null, a misspelt field, processes that are no list or a value that is no string, or sets a name of the setup's, fails naming the field. Migrate, seed and the worker check the environment run.ts gives everything; the teardown ends the worker, which says so on SIGTERM, and its port stops answering; a further process that exits before the specs end fails the run, naming its index and its environment's keys and not their values. The marker names migrate among the places env reaches; run.ts names the setup's names and how it may read a variable from outside. Refs PLX-200 Co-Authored-By: Claude Opus 5.5 --- newborns/e2e-playwright.test.ts | 131 ++++++++++++++++++++++--- packages/lib/src/e2ePlaywright.test.ts | 18 ++++ 2 files changed, 138 insertions(+), 11 deletions(-) diff --git a/newborns/e2e-playwright.test.ts b/newborns/e2e-playwright.test.ts index 2fa73f93..99985021 100644 --- a/newborns/e2e-playwright.test.ts +++ b/newborns/e2e-playwright.test.ts @@ -13,8 +13,12 @@ // setting that names the server's own address, without which the server refuses // to start, a secret and a directory for files; a setting of the server alone; a // PostgreSQL setting; and a second process from the build output, a worker that -// writes into the database. Its specs read the database through DATABASE_URL, -// see the environment, and wait on the worker. +// writes into the database. Migrate, seed and the worker see the environment it +// gives everything; its specs read the database through DATABASE_URL, see the +// environment, and wait on the worker, which the teardown ends. A further process +// that exits before the specs end fails the run, naming it. A run.ts that never +// returns, returns what setup.ts does not take, or sets a name of the setup's, +// fails the run with a message that names what is wrong. // Without Chromium in Playwright's shared cache the run fails, naming the // command that installs it, and that command does. The suite's own `e2e` fails // without the build output and does not build it. Editing a spec moves the @@ -84,8 +88,8 @@ const EXTRAS: Record void> = { // after it started, the ACME_POOL it was given. Its suite's run.ts says all of that, and its specs check it. stateful: (app, suite) => { scripts(app, { - migrate: `echo "migrate saw NODE_ENV=$NODE_ENV" && ${psql('create table greeting (text text not null); create table worked (pool text not null)')}`, - seed: psql("insert into greeting values ('hello from the seed')"), + migrate: `echo "migrate saw NODE_ENV=$NODE_ENV and ACME_SECRET=$ACME_SECRET" && ${psql('create table greeting (text text not null); create table worked (pool text not null, secret text not null)')}`, + seed: `echo "seed saw ACME_SECRET=$ACME_SECRET" && ${psql("insert into greeting values ('hello from the seed')")}`, }); put(app, { 'src/app/greeting/page.tsx': [ @@ -113,13 +117,16 @@ const EXTRAS: Record void> = { 'src/settings.ts': [ "import { execFileSync } from 'node:child_process';", '', - 'const { ACME_POOL, ACME_TASK, ACME_URL, DATABASE_URL, HOSTNAME, PORT } = process.env;', + 'const { ACME_POOL, ACME_SECRET, ACME_TASK, ACME_URL, DATABASE_URL, HOSTNAME, PORT } = process.env;', "if (ACME_TASK === 'work') {", " console.log('the worker answers on port', PORT);", + " process.on('SIGTERM', () => console.log('the worker was ended by SIGTERM'));", ' setTimeout(() => {', - " const pool = ACME_POOL ?? 'none';", - " execFileSync('psql', [DATABASE_URL ?? '', '-c', \"insert into worked values ('\" + pool + \"')\"]);", + " const values = [ACME_POOL ?? 'none', ACME_SECRET ?? 'none'].map((value) => \"'\" + value + \"'\").join(', ');", + " execFileSync('psql', [DATABASE_URL ?? '', '-c', 'insert into worked values (' + values + ')']);", ' }, 3_000);', + "} else if (ACME_TASK === 'quit') {", + ' setTimeout(() => process.exit(3), 1_000);', "} else if (ACME_URL !== ['http://', HOSTNAME, ':', PORT].join('')) {", " console.error('the server refuses to start: ACME_URL is', ACME_URL ?? 'unset', 'and not its own address');", ' process.exit(1);', @@ -171,8 +178,8 @@ const EXTRAS: Record void> = { " await expect(page.getByText('pool 20')).toBeVisible();", '});', '', - "test('a spec waits on the worker, a second process without the environment of the server alone', async () => {", - " await expect.poll(() => sql('select pool from worked'), { timeout: 30_000 }).toBe('none');", + "test('a spec waits on the worker, a second process with the environment of everything and not the server alone', async () => {", + " await expect.poll(() => sql('select pool, secret from worked'), { timeout: 30_000 }).toBe('none|a secret of the run');", '});', '', ].join('\n'), @@ -289,6 +296,74 @@ describe('a repo with two stateless apps, one name the end of the other, and the } }); + // Each a run.ts and what the failed run says; each fails before the server starts, and leaves nothing. + const refused: [string, string, RegExp][] = [ + [ + 'returns nothing', + 'export default () => undefined;', + /run\.ts returned undefined, where setup\.ts takes an object/, + ], + ['returns null', 'export default () => null;', /run\.ts returned null, where setup\.ts takes an object/], + [ + 'misspells a field', + 'export default () => ({ evn: {} });', + /run\.ts returned evn, which setup\.ts does not take/, + ], + ['gives processes as no list', 'export default () => ({ processes: {} });', /processes of run\.ts is no list/], + [ + 'gives a value that is no string', + 'export default () => ({ env: { A: 1 } });', + /env\.A of run\.ts is no string/, + ], + [ + 'names DATABASE_URL in env', + "export default () => ({ env: { DATABASE_URL: 'x' } });", + /env\.DATABASE_URL of run\.ts is the setup's to give/, + ], + [ + 'names PORT for the server', + "export default () => ({ server: { env: { PORT: '1' } } });", + /server\.env\.PORT of run\.ts is the setup's to give/, + ], + [ + 'names the base URL for a process', + "export default () => ({ processes: [{ env: { PLX_E2E_BASE_URL: 'x' } }] });", + /processes\[0\]\.env\.PLX_E2E_BASE_URL of run\.ts is the setup's to give/, + ], + [ + 'names NODE_ENV', + "export default () => ({ env: { NODE_ENV: 'test' } });", + /env\.NODE_ENV of run\.ts is the setup's to give/, + ], + ]; + for (const [at, [what, source, message]] of refused.entries()) + test(`a run.ts that ${what} fails the run, saying so`, async () => { + const run = tmp(`r${at}`); + try { + put(clone, { 'e2e/less/run.ts': `${source}\n` }); + const ran = await tryRun('mise', ['run', 'e2e', 'less'], clone, { ...SHARED, TMPDIR: run }); + assert.equal(ran.ok, false, ran.output); + assert.match(ran.output, message); + assert.doesNotMatch(ran.output, /TypeError/); + assert.deepEqual(leftIn(run), []); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + + test('a run.ts that never returns fails the run after a minute, leaving nothing', async () => { + const run = tmp('s5'); + try { + put(clone, { 'e2e/less/run.ts': 'export default () => new Promise(() => {});\n' }); + const ran = await tryRun('mise', ['run', 'e2e', 'less'], clone, { ...SHARED, TMPDIR: run }); + assert.equal(ran.ok, false, ran.output); + assert.match(ran.output, /run\.ts did not return within a minute/); + assert.deepEqual(leftIn(run), []); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + test('passes its own check, plx doctor in it, which says nothing of the suites', async () => { const ran = await tryRun('mise', ['run', 'check'], clone); assert.ok(ran.ok, ran.output); @@ -371,11 +446,44 @@ describe('a repo with the answer postgres, a stateful app, an app with a seed al const run = tmp('s2'); const ran = await tryRun('mise', ['run', 'e2e', 'stateful'], clone, { ...SHARED, TMPDIR: run }); assert.ok(ran.ok, ran.output); - assert.match(ran.output, /migrate saw NODE_ENV=production\b/); + assert.match(ran.output, /migrate saw NODE_ENV=production and ACME_SECRET=a secret of the run\n/); + assert.match(ran.output, /seed saw ACME_SECRET=a secret of the run\n/); assert.match(ran.output, /CREATE TABLE[\s\S]*INSERT 0 1/); - assert.match(ran.output, /the worker answers on port \d+/); assert.match(ran.output, /\s6 passed \(/); assert.deepEqual(leftIn(run), [], 'no copy and no directory of run.ts is left'); + // The worker was still running when the specs ended, and the teardown ended it. + const worker = /the worker answers on port (\d+)/.exec(ran.output)?.[1]; + assert.ok(worker, ran.output); + assert.match(ran.output, /the worker was ended by SIGTERM/); + const answers = await fetch(`http://127.0.0.1:${worker}/healthz`).then( + () => true, + () => false, + ); + assert.equal(answers, false, 'the worker answers no more'); + }); + + test('a further process that exits before the specs end fails the run, saying which and with what', async () => { + const run = tmp('s6'); + const file = join(clone, 'e2e', 'stateful', 'run.ts'); + try { + put(clone, { + 'e2e/stateful/run.ts': readFileSync(file, 'utf8').replace( + "processes: [{ env: { ACME_TASK: 'work' } }]", + "processes: [{ env: { ACME_TASK: 'work' } }, { env: { ACME_TASK: 'quit', ACME_QUEUES: 'q-value' } }]", + ), + }); + const ran = await tryRun('mise', ['run', 'e2e', 'stateful'], clone, { ...SHARED, TMPDIR: run }); + assert.equal(ran.ok, false, ran.output); + assert.match(ran.output, /\s6 passed \(/, 'the specs pass, and the run fails all the same'); + assert.match( + ran.output, + /further process 1 of run\.ts, with ACME_TASK and ACME_QUEUES, exited with 3 before the specs ended/, + ); + assert.deepEqual(leftIn(run), []); + assert.deepEqual(await mentioning(run), [], 'no PostgreSQL is left'); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } }); test('without the setting that names its address the server refuses to start, and the run fails leaving nothing', async () => { @@ -387,6 +495,7 @@ describe('a repo with the answer postgres, a stateful app, an app with a seed al assert.equal(ran.ok, false, ran.output); assert.match(ran.output, /the server refuses to start: ACME_URL is unset/); assert.match(ran.output, /the server exited with 1 before/); + assert.doesNotMatch(ran.output, /q-value/, 'the values of its environment are not shown'); assert.deepEqual(leftIn(run), []); assert.deepEqual(await mentioning(run), [], 'no PostgreSQL is left'); } finally { diff --git a/packages/lib/src/e2ePlaywright.test.ts b/packages/lib/src/e2ePlaywright.test.ts index f26f5a2e..4c73c3a0 100644 --- a/packages/lib/src/e2ePlaywright.test.ts +++ b/packages/lib/src/e2ePlaywright.test.ts @@ -157,3 +157,21 @@ test('a suite born before run.ts existed gets it as generated from its next upda [{ path: 'run.ts', outcome: 'added' }], ); }); + +test("the marker says run.ts is the suite's own, and names every place its env reaches", async () => { + const line = textOf(await render(), 'PLEXUS.md') + .split('\n') + .find((l) => l.includes('`run.ts`')); + assert.ok(line); + for (const place of ['migrate', 'seed', 'server', 'specs', 'further processes']) + assert.match(line, new RegExp(place), place); + assert.match(line, /suite's own/); +}); + +test("run.ts names the setup's names, which it may not set, and what Turbo lets it read", async () => { + const text = textOf(await render(), 'run.ts'); + for (const name of ['DATABASE_URL', 'PORT', 'HOSTNAME', 'PLX_E2E_BASE_URL', 'NODE_ENV']) + assert.match(text, new RegExp(`\\b${name}\\b`), name); + assert.match(text, /turbo\.json/); + assert.match(text, /\$TURBO_EXTENDS\$/); +}); From c977817ef53c1a47aa46e983bef953cd96bcd368 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 03:15:01 +0100 Subject: [PATCH 185/194] e2e-playwright: check what run.ts returns, keep the setup's names, watch further processes setup.ts waits a minute for run.ts and keeps the loop alive until it returns or throws, so a promise that never settles fails the run instead of ending it green. What run.ts returns is checked in a few lines: an unknown field, a field of the wrong kind, a value that is no string, or one of the setup's names (DATABASE_URL, PORT, HOSTNAME, PLX_E2E_BASE_URL, NODE_ENV) in any env fails the run with one message naming it. The teardown fails the run when a further process exited before it, naming its index, its environment's keys and its exit code. run.ts says which names are the setup's and that a variable from outside reaches it only through the suite's turbo.json; the marker names migrate among the places env reaches. Refs PLX-200 Co-Authored-By: Claude Opus 5.5 --- .../e2e-playwright/files/PLEXUS.md.jinja | 2 +- templates/e2e-playwright/files/run.ts | 5 ++ templates/e2e-playwright/files/setup.ts.jinja | 86 +++++++++++++++++-- 3 files changed, 86 insertions(+), 7 deletions(-) diff --git a/templates/e2e-playwright/files/PLEXUS.md.jinja b/templates/e2e-playwright/files/PLEXUS.md.jinja index faec2be2..b369bc31 100644 --- a/templates/e2e-playwright/files/PLEXUS.md.jinja +++ b/templates/e2e-playwright/files/PLEXUS.md.jinja @@ -1,4 +1,4 @@ - The end-to-end suite of `{{ app }}`: Playwright runs the specs in `specs/` in Chromium against the app's build output, which `setup.ts` starts as the standalone server, after a throwaway PostgreSQL and the app's `migrate` and `seed` where its `package.json` has either. -- What the app's run needs beyond that, settings for the seed, the server and the specs, PostgreSQL's settings and further processes from the build output, goes in `run.ts`, which is the suite's own, like the specs; `setup.ts` is generated, and `plx update` merges it. +- What the app's run needs beyond that, environment for migrate, seed, the server, further processes and the specs, environment for the server alone, PostgreSQL's settings and further processes from the build output, goes in `run.ts`, which is the suite's own, like the specs; `setup.ts` is generated, and `plx update` merges it. - It runs with `mise e2e ` at the repo's root, `` being the app's directory name, which builds the app first (the suite's own name is no name the verb takes); the suite's `e2e` script never builds, and fails without the build output. - Chromium comes from Playwright's shared cache, into which `pnpm exec playwright install chromium`, run in this directory, installs it. diff --git a/templates/e2e-playwright/files/run.ts b/templates/e2e-playwright/files/run.ts index 5c99c629..7c25a632 100644 --- a/templates/e2e-playwright/files/run.ts +++ b/templates/e2e-playwright/files/run.ts @@ -2,6 +2,11 @@ // beyond what setup.ts does, as its Needs says; setup.ts calls it once the server's port is picked, before the database. import type { Needs, Run } from './setup.ts'; +/** + * As generated, nothing. DATABASE_URL, PORT, HOSTNAME, PLX_E2E_BASE_URL and NODE_ENV are the setup's to give, and a + * run.ts that sets one fails the run. A variable this file reads from outside the run reaches it only where the suite's + * turbo.json names it for the e2e task, in `env` (hashed) or `passThroughEnv`, after "$TURBO_EXTENDS$". + */ export default function needs(_run: Run): Needs { return {}; } diff --git a/templates/e2e-playwright/files/setup.ts.jinja b/templates/e2e-playwright/files/setup.ts.jinja index b4a72e89..6bf3a0fc 100644 --- a/templates/e2e-playwright/files/setup.ts.jinja +++ b/templates/e2e-playwright/files/setup.ts.jinja @@ -16,6 +16,9 @@ const APP = '{{ app }}'; /** Environment variables, by name. */ type Env = Record; +/** The names the setup gives: the database, the server's port and host, the specs' address, migrate's NODE_ENV. */ +const RESERVED = ['DATABASE_URL', 'PORT', 'HOSTNAME', 'PLX_E2E_BASE_URL', 'NODE_ENV']; + /** What run.ts is given: what is known only once the run has begun. */ export interface Run { /** The server's address, as in http://127.0.0.1:41234: the specs' baseURL. */ @@ -26,7 +29,7 @@ export interface Run { /** What run.ts says the app's run needs beyond the database, migrate, seed and the server. */ export interface Needs { - /** Environment for migrate, seed, the server, every further process and the specs. */ + /** Environment for migrate, seed, the server, every further process and the specs; none of the names RESERVED. */ env?: Env; /** Environment for the server alone, over `env`. */ server?: { env?: Env }; @@ -62,9 +65,24 @@ export default async function setup(): Promise<() => Promise> { }, ); const stops: (() => Promise)[] = []; - const teardown = async () => { + const stopAll = async () => { for (const stop of stops.reverse()) await stop(); }; + // The further processes, which must still run when the specs end. + const further: { index: number; names: string[]; child: ChildProcess }[] = []; + const teardown = async () => { + const exited = further.filter(({ child }) => child.exitCode !== null || child.signalCode !== null); + await stopAll(); + if (exited.length > 0) + throw new Error( + exited + .map( + ({ index, names, child }) => + `further process ${index} of run.ts, with ${names.join(' and ') || 'no env of its own'}, exited with ${child.exitCode ?? child.signalCode} before the specs ended`, + ) + .join('\n'), + ); + }; /** A new directory, removed at the end. */ const temporary = async () => { const dir = await mkdtemp(path.join(tmpdir(), 'plx-e2e-')); @@ -83,6 +101,8 @@ export default async function setup(): Promise<() => Promise> { stops.push(() => end(child)); return child; }; + // Until the setup returns or throws, so that it cannot end unnoticed, and the runner with it, on a promise that never settles. + const alive = setInterval(() => {}, 60_000); try { // A copy, since a running server writes into its own directory. const copy = await temporary(); @@ -103,24 +123,78 @@ export default async function setup(): Promise<() => Promise> { } const started = start(server, { ...env, ...needs.server?.env }, port); await ready(`${address}/healthz`, started); - for (const further of needs.processes ?? []) start(server, { ...env, ...further.env }, await freePort()); + for (const [index, { env: own = {} }] of (needs.processes ?? []).entries()) + further.push({ index, names: Object.keys(own), child: start(server, { ...env, ...own }, await freePort()) }); // The specs run in workers that inherit this process's environment. Object.assign(process.env, needs.env); if (env.DATABASE_URL) process.env.DATABASE_URL = env.DATABASE_URL; process.env.PLX_E2E_BASE_URL = address; } catch (error) { - await teardown(); + await stopAll(); throw error; + } finally { + clearInterval(alive); } return teardown; } -/** What run.ts says the run needs; nothing where the suite has no run.ts. */ +/** What run.ts says the run needs, within a minute; nothing where the suite has no run.ts. */ async function needed(given: Run): Promise { if (!existsSync(new URL('./run.ts', import.meta.url))) return {}; const { default: needs } = await import('./run.ts'); if (typeof needs !== 'function') throw new Error('run.ts exports no function by default, which setup.ts calls'); - return await needs(given); + let timer: NodeJS.Timeout | undefined; + const late = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error('run.ts did not return within a minute')), 60_000); + }); + try { + return checked(await Promise.race([needs(given), late])); + } finally { + clearTimeout(timer); + } +} + +/** What run.ts returned, checked, since nothing type-checks it: the first thing wrong fails the run, named. */ +function checked(needs: unknown): Needs { + const isMap = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value); + const fail = (what: string): never => { + throw new Error(`${what}; Needs in setup.ts says what it takes`); + }; + const only = (at: string, value: Record, names: string[]) => { + for (const name of Object.keys(value)) + if (!names.includes(name)) fail(`run.ts returned ${at}${name}, which setup.ts does not take`); + }; + const env = (at: string, value: unknown) => { + if (value === undefined) return; + if (!isMap(value)) return fail(`${at} of run.ts is no object of names and strings`); + for (const [name, text] of Object.entries(value)) { + if (typeof text !== 'string') fail(`${at}.${name} of run.ts is no string`); + if (RESERVED.includes(name)) + fail(`${at}.${name} of run.ts is the setup's to give, as are ${RESERVED.join(', ')}`); + } + }; + if (!isMap(needs)) + return fail( + `run.ts returned ${needs === null || needs === undefined ? needs : Array.isArray(needs) ? 'a list' : typeof needs}, where setup.ts takes an object`, + ); + only('', needs, ['env', 'server', 'postgres', 'processes']); + env('env', needs.env); + if (needs.server !== undefined) { + if (!isMap(needs.server)) return fail('server of run.ts is no object'); + only('server.', needs.server, ['env']); + env('server.env', needs.server.env); + } + if (needs.postgres !== undefined && !isMap(needs.postgres)) fail('postgres of run.ts is no object of settings'); + if (needs.processes !== undefined) { + if (!Array.isArray(needs.processes)) return fail('processes of run.ts is no list'); + for (const [index, further] of needs.processes.entries()) { + if (!isMap(further)) return fail(`processes[${index}] of run.ts is no object`); + only(`processes[${index}].`, further, ['env']); + env(`processes[${index}].env`, further.env); + } + } + return needs as Needs; } /** From abf86094b2a26c8c4422492c0c919ec7f0120893 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 04:31:51 +0100 Subject: [PATCH 186/194] e2e-playwright: tests for a suite's type check A suite gets a check script that type-checks its specs, setup.ts, run.ts and playwright.config.ts with a tsconfig.json on the app's own base, so that what a spec imports of the app through its exports is read as the app reads it, an ES module or not. The newborn tests: mise check passes as generated (stateless, stateful, the app an ES module) and fails, naming the file, on a type error in a spec, in what run.ts returns, or in a spec that a change of the app no longer fits; the suite's check follows the app's, builds nothing, and its hash moves with the app's source. The lib tests: the files, the pins shared with app-nextjs, the turbo.json, and what plx update does to a suite born before. Red before the template change: the files are missing and mise check passes a spec with a type error. Co-Authored-By: Claude Opus 5.5 --- newborns/e2e-playwright.test.ts | 153 ++++++++++++++++++++++++- packages/lib/src/e2ePlaywright.test.ts | 118 ++++++++++++++++++- 2 files changed, 264 insertions(+), 7 deletions(-) diff --git a/newborns/e2e-playwright.test.ts b/newborns/e2e-playwright.test.ts index 99985021..92882639 100644 --- a/newborns/e2e-playwright.test.ts +++ b/newborns/e2e-playwright.test.ts @@ -25,8 +25,14 @@ // hash of the suite's `e2e` and leaves the app's `build`; editing the app, or // giving it a `migrate` script, moves both. A run killed by SIGINT or SIGKILL // of `mise`, or by SIGKILL of the Playwright runner that started the app, -// leaves no server, no worker and no PostgreSQL behind. The repo's own `check`, -// `plx doctor` in it, passes, and says nothing of the suites' files. Created by +// leaves no server, no worker and no PostgreSQL behind. The repo's own `check` +// passes as generated, also where the app is an ES module, and type-checks each +// suite after its app's check, without building the app; `plx doctor` in it +// says nothing of the suites' files. It reads the app's code a spec imports +// through the app's `exports`, as the app reads it. A type error in a spec, +// also one a change of the app causes, or in what `run.ts` returns fails it, +// naming the file; editing the app or a spec moves the hash of the +// suite's check, and a spec neither the app's check nor its build. Created by // `plx new`; it needs the network. // // Playwright's shared cache is, for these tests, `node_modules/.cache/ms-playwright` @@ -211,6 +217,12 @@ async function newborn( return dir; } +/** + * The suite of `app`'s check, as Turbo names the task in what it prints: a line's prefix on a terminal, the heading of + * its group under GitHub Actions. + */ +const checked = (app: string) => new RegExp(`@acme/${app}-e2e:check`); + /** A new directory for a run's TMPDIR, short, as a database's socket lies in it and a socket's path holds about a hundred bytes. */ function tmp(name: string): string { const dir = join(here, name); @@ -283,7 +295,7 @@ describe('a repo with two stateless apps, one name the end of the other, and the assert.equal(existsSync(join(served, '.next', 'cache', 'images')), false, 'the output was served itself'); }); - test('a suite without run.ts runs as one with run.ts as generated', async () => { + test('a suite without run.ts runs as one with run.ts as generated, and passes its check', async () => { const run = tmp('s4'); try { rmSync(join(clone, 'e2e', 'less', 'run.ts')); @@ -291,6 +303,8 @@ describe('a repo with two stateless apps, one name the end of the other, and the assert.ok(ran.ok, ran.output); assert.match(ran.output, /\s1 passed \(/); assert.deepEqual(leftIn(run), []); + const checked = await tryRun('mise', ['run', 'check'], clone); + assert.ok(checked.ok, checked.output); } finally { await gitOk(clone, 'reset', '-q', '--hard'); } @@ -364,10 +378,135 @@ describe('a repo with two stateless apps, one name the end of the other, and the } }); - test('passes its own check, plx doctor in it, which says nothing of the suites', async () => { + test('passes its own check as generated, which type-checks each suite, and plx doctor in it says nothing of the suites', async () => { const ran = await tryRun('mise', ['run', 'check'], clone); assert.ok(ran.ok, ran.output); assert.doesNotMatch(ran.output, /e2e\/\w+\/\S+:\d+:\d+|Suppression comment/); + for (const suite of ['stateless', 'less']) assert.match(ran.output, checked(suite), suite); + }); + + test('passes its own check as generated where the app is an ES module', async () => { + try { + const manifest = JSON.parse(readFileSync(join(clone, 'apps', 'stateless', 'package.json'), 'utf8')); + put(clone, { 'apps/stateless/package.json': { ...manifest, type: 'module' } }); + const ran = await tryRun('mise', ['run', 'check'], clone); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, checked('stateless')); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + + test('a type error in a spec fails mise check, which names the file', async () => { + try { + const file = join(clone, 'e2e', 'stateless', 'specs', 'home.spec.ts'); + put(clone, { + 'e2e/stateless/specs/home.spec.ts': `${readFileSync(file, 'utf8')}export const n: number = 'one';\n`, + }); + const ran = await tryRun('mise', ['run', 'check'], clone); + assert.equal(ran.ok, false, ran.output); + assert.match(ran.output, /(?:^|: )specs\/home\.spec\.ts\(\d+,\d+\): error TS2322/m); + assert.match(ran.output, /Failed:\s+@acme\/stateless-e2e#check/); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + + // What run.ts returns, wrong in a way the run would refuse (as the refused runs above show), is found by check. + const mistyped: [string, string, RegExp][] = [ + ['a misspelt field', 'return { evn: {} };', /(?:^|: )run\.ts\(\d+,\d+\): error TS2353: .*'evn'/m], + ['a value that is no string', 'return { env: { A: 1 } };', /(?:^|: )run\.ts\(\d+,\d+\): error TS2322/m], + ]; + for (const [what, line, message] of mistyped) + test(`run.ts returning ${what} fails mise check, which names run.ts`, async () => { + try { + const file = join(clone, 'e2e', 'less', 'run.ts'); + const generated = readFileSync(file, 'utf8'); + assert.match(generated, /return \{\};/); + put(clone, { 'e2e/less/run.ts': generated.replace('return {};', line) }); + const ran = await tryRun('mise', ['run', 'check'], clone); + assert.equal(ran.ok, false, ran.output); + assert.match(ran.output, message); + assert.match(ran.output, /Failed:\s+@acme\/less-e2e#check/); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } + }); + + test("the check reads what a spec imports of the app through its exports as the app reads it, an ES module or not, and fails a spec the app's change no longer fits", async () => { + const app = join(clone, 'apps', 'stateless'); + const manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8')); + try { + // A module of the app's, which imports another without an extension, as the app's own code may. + put(app, { + 'src/lib/greet.ts': + "import { tail } from './tail';\n\nexport const greet = (name: string): string => `hello ${name}${tail}`;\n", + 'src/lib/tail.ts': "export const tail: string = '!';\n", + }); + put(clone, { + 'e2e/stateless/specs/greet.spec.ts': [ + "import { greet } from '@acme/stateless/greet';", + "import { expect, test } from '@playwright/test';", + '', + "test('greets', () => {", + " expect(greet('you')).toBe('hello you!');", + '});', + '', + ].join('\n'), + }); + for (const type of [undefined, 'module']) { + put(app, { 'package.json': { ...manifest, type, exports: { './greet': './src/lib/greet.ts' } } }); + const ran = await tryRun('mise', ['run', 'check'], clone); + assert.ok(ran.ok, `${type ?? 'commonjs'}:\n${ran.output}`); + } + // A change of the app's that its own check passes and the spec no longer fits; an error in the app's own code + // fails the app's check first, which the suite's follows. + put(app, { + 'src/lib/greet.ts': + "import { tail } from './tail';\n\nexport const greet = (times: number): string => `hello${tail.repeat(times)}`;\n", + }); + const broken = await tryRun('mise', ['run', 'check'], clone); + assert.equal(broken.ok, false, broken.output); + assert.match(broken.output, /(?:^|: )specs\/greet\.spec\.ts\(\d+,\d+\): error TS2345/m); + assert.match(broken.output, /Failed:\s+@acme\/stateless-e2e#check/); + assert.doesNotMatch(broken.output, /Failed:\s+@acme\/stateless#check/); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + await gitOk(clone, 'clean', '-fdq', '--', 'apps', 'e2e'); + } + }); + + test("the suite's check needs no build and follows the app's check; editing the app or a spec moves it, a spec neither the app's check nor its build", async () => { + const [suite, app] = ['@acme/stateless-e2e#check', '@acme/stateless#check']; + /** Turbo's hashes of the suite's check and what it depends on, with the app's build, by task id. */ + const checks = async () => { + const ran = await tryRun( + 'mise', + ['exec', '--', 'turbo', 'run', 'check', 'build', '--filter=@acme/stateless-e2e...', '--dry=json'], + clone, + ); + assert.ok(ran.ok, ran.output); + const dry = JSON.parse(ran.output.slice(ran.output.indexOf('{'))); + const tasks: { taskId: string; hash: string; dependencies: string[] }[] = dry.tasks; + return { tasks, hash: Object.fromEntries(tasks.map((t) => [t.taskId, t.hash])) }; + }; + try { + const first = await checks(); + assert.deepEqual(first.tasks.find((t) => t.taskId === suite)?.dependencies, [app]); + assert.deepEqual(first.tasks.find((t) => t.taskId === app)?.dependencies, [], "the app's check builds nothing"); + const specFile = join(clone, 'e2e', 'stateless', 'specs', 'home.spec.ts'); + put(clone, { 'e2e/stateless/specs/home.spec.ts': `${readFileSync(specFile, 'utf8')}// edited\n` }); + await gitOk(clone, 'add', '-A'); + const specEdited = await checks(); + assert.notEqual(specEdited.hash[suite], first.hash[suite]); + for (const id of [app, '@acme/stateless#build']) assert.equal(specEdited.hash[id], first.hash[id], id); + const page = join(clone, 'apps', 'stateless', 'src', 'app', 'page.tsx'); + put(clone, { 'apps/stateless/src/app/page.tsx': `${readFileSync(page, 'utf8')}// edited\n` }); + await gitOk(clone, 'add', '-A'); + assert.notEqual((await checks()).hash[suite], specEdited.hash[suite], 'an edit of the app'); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + } }); test("the suite's own e2e fails without the build output, and does not build it", async () => { @@ -442,6 +581,12 @@ describe('a repo with the answer postgres, a stateful app, an app with a seed al ); }); + test("passes mise check from a fresh clone, each suite type-checked, the stateful suite's run.ts and specs included", async () => { + const ran = await tryRun('mise', ['run', 'check'], clone); + assert.ok(ran.ok, ran.output); + for (const suite of ['stateful', 'seeded']) assert.match(ran.output, checked(suite), suite); + }); + test('passes mise e2e from a fresh clone: migrate in production, then seed, against the database the server gets, with what run.ts says', async () => { const run = tmp('s2'); const ran = await tryRun('mise', ['run', 'e2e', 'stateful'], clone, { ...SHARED, TMPDIR: run }); diff --git a/packages/lib/src/e2ePlaywright.test.ts b/packages/lib/src/e2ePlaywright.test.ts index 4c73c3a0..e2ff0c0e 100644 --- a/packages/lib/src/e2ePlaywright.test.ts +++ b/packages/lib/src/e2ePlaywright.test.ts @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import { join } from 'node:path'; import { test } from 'node:test'; -import { merge, readTree, render as renderTrees, type Tree } from '@plexus-ms/cli-template'; +import { gitMergeFile, merge, readTree, render as renderTrees, type Tree } from '@plexus-ms/cli-template'; import { templatesRoot } from './templatesRoot.ts'; import { pathsOf, renderBundled, textOf } from './testing/bundled.ts'; @@ -18,6 +18,7 @@ test('a suite is rendered as a package of its own: its Playwright configuration, 'run.ts', 'setup.ts', 'specs/home.spec.ts', + 'tsconfig.json', 'turbo.json', ]); }); @@ -28,17 +29,53 @@ test('the app is required, and the error carries its help', async () => { assert.match(result.errors[0]?.message ?? '', /package name/); }); -test('the package lists the app as a workspace dependency and has one script, e2e', async () => { +test('the package lists the app as a workspace dependency and has two scripts, check and e2e', async () => { const manifest = JSON.parse(textOf(await render({ app: '@acme/shop' }), 'package.json')); assert.equal(manifest.name, '@acme/shop-e2e'); assert.equal(manifest.private, true); - assert.deepEqual(Object.keys(manifest.scripts), ['e2e']); + assert.deepEqual(Object.keys(manifest.scripts), ['check', 'e2e']); const dependencies = { ...manifest.dependencies, ...manifest.devDependencies }; assert.equal(dependencies['@acme/shop'], 'workspace:*'); assert.ok(dependencies['@playwright/test'], 'Playwright'); assert.ok(dependencies['@plexus-ms/test-postgres'], 'the throwaway PostgreSQL of a stateful app'); }); +/** A JSON file of a template that may hold whole-line comments, as tsconfig.json and turbo.json do. */ +const jsonc = (text: string) => JSON.parse(text.replace(/^\s*\/\/.*$/gm, '')); + +/** The app as app-nextjs renders it. */ +const appRender = () => renderBundled(['app-nextjs'], { tenant: 'acme', name: '@acme/web' }); + +test('check type-checks the suite, running no test, with the TypeScript, the node types and the shared config the app pins', async () => { + const manifest = JSON.parse(textOf(await render(), 'package.json')); + const app = JSON.parse(textOf(await appRender(), 'package.json')); + assert.equal(manifest.scripts.check, 'tsc --noEmit'); + for (const name of ['typescript', '@types/node', '@plexus-ms/config']) + assert.equal(manifest.devDependencies[name], app.devDependencies[name], name); +}); + +test("tsconfig.json extends the app's base, so that what a spec imports of the app is read as the app reads it", async () => { + const config = jsonc(textOf(await render(), 'tsconfig.json')); + assert.equal(config.extends, jsonc(textOf(await appRender(), 'tsconfig.json')).extends); + // The specs, setup.ts, run.ts and playwright.config.ts. + assert.deepEqual(config.include, ['**/*.ts']); + // The setup runs in node; run.ts imports setup.ts by its .ts name, which Playwright resolves. + assert.deepEqual(config.compilerOptions, { allowImportingTsExtensions: true, types: ['node'] }); +}); + +test("the incremental check's record is ignored, so that it is no input of a task", async () => { + assert.match(textOf(await render(), '.gitignore'), /^\*\.tsbuildinfo$/m); +}); + +test("the suite's check depends on the checks of its dependencies, the app's among them; its e2e keeps the root's, its test has none", async () => { + const config = jsonc(textOf(await render(), 'turbo.json')); + assert.deepEqual(config.extends, ['//']); + // What the suite's check reads of the app is the app's source, which only the hash of the app's check carries. + assert.deepEqual(config.tasks.check, { dependsOn: ['^check'] }); + assert.deepEqual(config.tasks.test, { dependsOn: [] }); + assert.equal(config.tasks.e2e, undefined); +}); + test("the spec looks for the app's name, which its page shows", async () => { assert.match(textOf(await render({ app: '@acme/shop' }), 'specs/home.spec.ts'), /toHaveText\('@acme\/shop'\)/); }); @@ -175,3 +212,78 @@ test("run.ts names the setup's names, which it may not set, and what Turbo lets assert.match(text, /turbo\.json/); assert.match(text, /\$TURBO_EXTENDS\$/); }); + +/** The template as it was before a suite was type-checked: no tsconfig.json, one script, no TypeScript of its own. */ +async function untyped(): Promise<{ tree: Tree; files: Awaited>['files'] }> { + const template = new Map(await readTree(join(templatesRoot(), 'e2e-playwright'))); + const file = (text: string) => ({ bytes: new TextEncoder().encode(text), mode: 0o100644 }); + template.delete('files/tsconfig.json'); + template.set('files/.gitignore.jinja', file('/test-results/\n/playwright-report/\n')); + template.set( + 'files/package.json.jinja', + file( + [ + '{', + ' "name": "{{ app }}-e2e",', + ' "private": true,', + ' "type": "module",', + ' "scripts": {', + ' "e2e": "playwright test"', + ' },', + ' "devDependencies": {', + ' "{{ app }}": "workspace:*",', + ' "@playwright/test": "^1.65.1",', + ' "@plexus-ms/test-postgres": "^0.1.0"', + ' }', + '}', + '', + ].join('\n'), + ), + ); + const result = await renderTrees([template], { app: '@acme/web' }); + assert.deepEqual(result.errors, []); + return { tree: result.tree, files: result.files }; +} + +/** An update from the untyped suite to this version's, of `current`, with git's merge of a file both sides changed. */ +async function typed(edit: (tree: Tree) => void = () => {}) { + const [old, next] = [await untyped(), await suite()]; + const current = new Map(old.tree); + edit(current); + const merged = await merge( + { old: old.tree, new: next.tree, current, files: { old: old.files, new: next.files } }, + gitMergeFile, + ); + const text = (path: string) => new TextDecoder().decode(merged.tree.get(path)?.bytes); + return { merged, next, text, outcome: (path: string) => merged.report.find((e) => e.path === path)?.outcome }; +} + +test('a suite born before the type check gets tsconfig.json and the check script from its next update, as this version renders them', async () => { + const { merged, next, text, outcome } = await typed(); + assert.equal(outcome('tsconfig.json'), 'added'); + for (const path of ['tsconfig.json', 'package.json', '.gitignore', 'turbo.json']) + assert.deepEqual(merged.tree.get(path)?.bytes, next.tree.get(path)?.bytes, path); + assert.equal(JSON.parse(text('package.json')).scripts.check, 'tsc --noEmit'); +}); + +test('a suite whose package.json gained a dependency of its own gets the check script, and one conflict among the dependencies', async () => { + // As `pnpm add -D @types/pg` in the suite writes it: the new dependency last, in order. + const { text, outcome } = await typed((tree) => { + const entry = tree.get('package.json'); + assert.ok(entry); + const edited = new TextDecoder() + .decode(entry.bytes) + .replace( + '"@plexus-ms/test-postgres": "^0.1.0"\n', + '"@plexus-ms/test-postgres": "^0.1.0",\n "@types/pg": "^8"\n', + ); + tree.set('package.json', { ...entry, bytes: new TextEncoder().encode(edited) }); + }); + assert.equal(outcome('package.json'), 'conflicted'); + const merged = text('package.json'); + // The scripts merge: check beside e2e, outside any conflict. + assert.match(merged, /"scripts": \{\n {4}"check": "tsc --noEmit",\n {4}"e2e": "playwright test"\n {2}\},/); + const hunks = [...merged.matchAll(/^<<<<<<< current\n([\s\S]*?)^>>>>>>> new render\n/gm)]; + assert.equal(hunks.length, 1, merged); + assert.match(hunks[0]?.[1] ?? '', /"@types\/pg": "\^8"[\s\S]*"@types\/node": "\^24"/); +}); From 58ad4f8224b37ac955aaa7379110f96c76aca531 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 04:32:54 +0100 Subject: [PATCH 187/194] e2e-playwright: a suite's check type-checks its specs, setup.ts, run.ts and what they import of the app tsconfig.json extends @plexus-ms/config/tsconfig-next, the app's own base, with node's types and the .ts imports between run.ts and setup.ts; on the Node base, NodeNext, the app's code a spec imports failed in an ES-module app and in a CommonJS one alike. skipLibCheck skips declaration files only, so the app's source a spec reaches is checked too. typescript, @types/node and @plexus-ms/config at the pins app-nextjs gives the app; *.tsbuildinfo ignored, so that it is no input of a task. turbo.json: the suite's check depends on ^check. With no dependency, an edit of the app's source left its hash unchanged, and a cached pass could outlive a change the specs no longer fit; the app's check builds nothing of the app. Its test keeps none, its e2e the root's ^build. setup.ts imports run.ts by its URL, so that the check reads run.ts against its own Needs and a suite without run.ts passes; the run-time check stays, since e2e runs without check. The marker says how check runs. Co-Authored-By: Claude Opus 5.5 --- templates/e2e-playwright/files/.gitignore.jinja | 1 + templates/e2e-playwright/files/PLEXUS.md.jinja | 1 + templates/e2e-playwright/files/package.json.jinja | 6 +++++- templates/e2e-playwright/files/setup.ts.jinja | 9 ++++++--- templates/e2e-playwright/files/tsconfig.json | 10 ++++++++++ templates/e2e-playwright/files/turbo.json | 6 +++--- 6 files changed, 26 insertions(+), 7 deletions(-) create mode 100644 templates/e2e-playwright/files/tsconfig.json diff --git a/templates/e2e-playwright/files/.gitignore.jinja b/templates/e2e-playwright/files/.gitignore.jinja index 53808aaf..57337032 100644 --- a/templates/e2e-playwright/files/.gitignore.jinja +++ b/templates/e2e-playwright/files/.gitignore.jinja @@ -1,2 +1,3 @@ /test-results/ /playwright-report/ +*.tsbuildinfo diff --git a/templates/e2e-playwright/files/PLEXUS.md.jinja b/templates/e2e-playwright/files/PLEXUS.md.jinja index b369bc31..b0211bab 100644 --- a/templates/e2e-playwright/files/PLEXUS.md.jinja +++ b/templates/e2e-playwright/files/PLEXUS.md.jinja @@ -1,4 +1,5 @@ - The end-to-end suite of `{{ app }}`: Playwright runs the specs in `specs/` in Chromium against the app's build output, which `setup.ts` starts as the standalone server, after a throwaway PostgreSQL and the app's `migrate` and `seed` where its `package.json` has either. - What the app's run needs beyond that, environment for migrate, seed, the server, further processes and the specs, environment for the server alone, PostgreSQL's settings and further processes from the build output, goes in `run.ts`, which is the suite's own, like the specs; `setup.ts` is generated, and `plx update` merges it. - It runs with `mise e2e ` at the repo's root, `` being the app's directory name, which builds the app first (the suite's own name is no name the verb takes); the suite's `e2e` script never builds, and fails without the build output. +- Its `check` type-checks the specs, `setup.ts`, `run.ts` and what they import of the app; `mise check` runs it at the repo's root, given no name. - Chromium comes from Playwright's shared cache, into which `pnpm exec playwright install chromium`, run in this directory, installs it. diff --git a/templates/e2e-playwright/files/package.json.jinja b/templates/e2e-playwright/files/package.json.jinja index 362f5f6c..f8a752e6 100644 --- a/templates/e2e-playwright/files/package.json.jinja +++ b/templates/e2e-playwright/files/package.json.jinja @@ -3,11 +3,15 @@ "private": true, "type": "module", "scripts": { + "check": "tsc --noEmit", "e2e": "playwright test" }, "devDependencies": { "{{ app }}": "workspace:*", "@playwright/test": "^1.65.1", - "@plexus-ms/test-postgres": "^0.1.0" + "@plexus-ms/config": "catalog:plexus", + "@plexus-ms/test-postgres": "^0.1.0", + "@types/node": "^24", + "typescript": "catalog:" } } diff --git a/templates/e2e-playwright/files/setup.ts.jinja b/templates/e2e-playwright/files/setup.ts.jinja index 6bf3a0fc..9edf5307 100644 --- a/templates/e2e-playwright/files/setup.ts.jinja +++ b/templates/e2e-playwright/files/setup.ts.jinja @@ -140,8 +140,11 @@ export default async function setup(): Promise<() => Promise> { /** What run.ts says the run needs, within a minute; nothing where the suite has no run.ts. */ async function needed(given: Run): Promise { - if (!existsSync(new URL('./run.ts', import.meta.url))) return {}; - const { default: needs } = await import('./run.ts'); + const file = new URL('./run.ts', import.meta.url); + if (!existsSync(file)) return {}; + // By its URL, not a literal: the suite's check then reads run.ts on its own, against the Needs it declares, and a + // suite without one passes it. + const { default: needs } = await import(file.href); if (typeof needs !== 'function') throw new Error('run.ts exports no function by default, which setup.ts calls'); let timer: NodeJS.Timeout | undefined; const late = new Promise((_, reject) => { @@ -154,7 +157,7 @@ async function needed(given: Run): Promise { } } -/** What run.ts returned, checked, since nothing type-checks it: the first thing wrong fails the run, named. */ +/** What run.ts returned, checked, since e2e runs without check: the first thing wrong fails the run, named. */ function checked(needs: unknown): Needs { const isMap = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value); diff --git a/templates/e2e-playwright/files/tsconfig.json b/templates/e2e-playwright/files/tsconfig.json new file mode 100644 index 00000000..b46d7b9f --- /dev/null +++ b/templates/e2e-playwright/files/tsconfig.json @@ -0,0 +1,10 @@ +{ + // The suite's check: its files and what they import of the app, on the app's own base, so the app's code is read as + // the app reads it; node's types, and the .ts name by which run.ts imports setup.ts, which Playwright resolves. + "extends": "@plexus-ms/config/tsconfig-next", + "compilerOptions": { + "allowImportingTsExtensions": true, + "types": ["node"] + }, + "include": ["**/*.ts"] +} diff --git a/templates/e2e-playwright/files/turbo.json b/templates/e2e-playwright/files/turbo.json index e7778a3e..9e659286 100644 --- a/templates/e2e-playwright/files/turbo.json +++ b/templates/e2e-playwright/files/turbo.json @@ -1,9 +1,9 @@ { - // A suite has no check or test of its own, and the root's ^build would still build the app it tests for them: - // neither needs a build, so the test job builds no app. Its e2e keeps the root's ^build. + // check follows the checks of the suite's dependencies, whose hashes carry the app's source it reads, and builds no + // app; neither does test (the root's ^build would build it). e2e keeps the root's ^build. "extends": ["//"], "tasks": { - "check": { "dependsOn": [] }, + "check": { "dependsOn": ["^check"] }, "test": { "dependsOn": [] } } } From ba2075a73215a8bc39bb7a4d52f27d953152e51a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 04:33:06 +0100 Subject: [PATCH 188/194] pipeline: tests for keeping a failed suite's results The lib test holds what only a runner evaluates: the large job's last step uploads e2e/*/test-results/ with actions/upload-artifact, pinned by its major, only where the E2E step ran and failed, as one artifact per app and attempt, for five days, nothing where no file is found; neither step continues on error; the header says in one line what is uploaded. The newborn pipeline stands in for the upload step after a failed E2E: web, whose second suite fails, and site, given one suite that fails, each keep their failed suite's results and no other, under the suite's directory, in artifacts named apart, and nothing is published. Red before the workflow change: the large job has no such step. Co-Authored-By: Claude Opus 5.5 --- newborns/pipeline.test.ts | 105 ++++++++++++++++++++++++++---- packages/lib/src/pipeline.test.ts | 45 +++++++++++++ 2 files changed, 139 insertions(+), 11 deletions(-) diff --git a/newborns/pipeline.test.ts b/newborns/pipeline.test.ts index efb1131e..80797007 100644 --- a/newborns/pipeline.test.ts +++ b/newborns/pipeline.test.ts @@ -28,15 +28,53 @@ // A change to a spec alone gives exactly `web` a large job, which runs its // suites and no build, and publish builds no image; so does a change to a spec // of its second suite alone. A change to `site` alone -// gives exactly `site` a large job, and publish builds its image. Needs Docker -// and the network, as the newborns do. +// gives exactly `site` a large job, and publish builds its image. Where a suite +// fails, its large job fails and the run publishes nothing; the step that keeps +// the results, which runs on the forge only after the E2E step failed (its +// shape is packages/lib/src/pipeline.test.ts's), finds in that job's checkout, +// at the path it names, the results of the failed suites and no other, under +// the suite's directory name, in one artifact per app: for `web`, whose second +// suite fails, and for `site`, given one suite that fails. Needs Docker and the +// network, as the newborns do. import assert from 'node:assert/strict'; -import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; import { basename, join } from 'node:path'; import { after, before, test } from 'node:test'; import { artifactMethods, type Caches, startCaches } from './caches.ts'; import { born, close, freePort, git, open, put, relock, sh, tryRun } from './helpers.ts'; +/** The step of _e2e.yml's large job that keeps a failed suite's results: its artifact's name and its path, as written. */ +function uploadStep(): { name: string; path: string } { + const workflow = readFileSync(join(import.meta.dirname, '..', '.github', 'workflows', '_e2e.yml'), 'utf8'); + const step = /^ {6}- name: .*\n(?: {8}.*\n)*? {8}uses: actions\/upload-artifact@.*\n((?: {8,}.*\n)*)/m.exec( + workflow, + )?.[1]; + const value = (key: string) => new RegExp(`^ {10}${key}: (.*)$`, 'm').exec(step ?? '')?.[1] ?? ''; + return { name: value('name'), path: value('path') }; +} + +/** + * The files the upload step's path finds in a job's checkout, as the artifact holds them: below the first wildcard, + * hidden files and the files in hidden directories left out, as the action leaves them out by default. + */ +function upload(job: string, path: string): string[] { + assert.match(path, /^[^*]+\/\*\/[^*]+$/, `the upload step's path, ${path}, is no directory per suite`); + const [base = '', below = ''] = path.split('/*/'); + const found: string[] = []; + const walk = (dir: string, at: string) => { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (entry.name.startsWith('.')) continue; + if (entry.isDirectory()) walk(join(dir, entry.name), `${at}${entry.name}/`); + else found.push(`${at}${entry.name}`); + } + }; + for (const suite of readdirSync(join(job, base))) { + const results = join(job, base, suite, below); + if (existsSync(results)) walk(results, `${suite}/${below.replace(/\/?$/, '/')}`); + } + return found.sort(); +} + const BROWSERS = join(import.meta.dirname, '..', 'node_modules', '.cache', 'ms-playwright'); /** The app's server-actions key, as the vault would hand it to a build: made up. */ const KEY = 'bmV3Ym9ybi1zZXJ2ZXItYWN0aW9ucy1rZXktMzJieXQ='; @@ -177,14 +215,17 @@ interface Run { plan: { legs: Leg[]; deploys: { app: string; host: string; image: string }[]; environment: string }; /** The methods of the plan's requests to the trusted server's artifacts. */ asked: string[]; - /** The output of each large job, by app. */ - large: Record; + /** The output of each large job, by app; where its E2E step failed, the artifact its upload step would make. */ + large: Record; published: Record; deployed: { healthy: boolean; unchanged?: boolean; live?: string }; } -/** The pipeline of a push of `sha` to develop: the jobs of on_push, in their order. */ -async function pipeline(sha: string): Promise { +/** + * The pipeline of a push of `sha` to develop: the jobs of on_push, in their order. With `failing`, a large job may + * fail, and the run ends after the large jobs, since publish needs them all; otherwise every job must pass. + */ +async function pipeline(sha: string, failing = false): Promise { const ci = { GITHUB_SHA: sha, GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'develop' }; const testJob = await checkout(sha); const test = await step(testJob, ['mise', 'run', 'test'], shared); @@ -212,9 +253,20 @@ async function pipeline(sha: string): Promise { }); for (const suite of leg.suites) await step(join(job, suite), ['mise', 'exec', '--', 'pnpm', 'exec', 'playwright', 'install', 'chromium']); - const e2e = await step(job, ['mise', 'run', 'e2e', leg.app], trusted); - large[leg.app] = { build, e2e }; + const ran = await tryRun('mise', ['run', 'e2e', leg.app], job, { ...env, ...trusted }); + assert.ok(ran.ok || failing, `mise run e2e ${leg.app} failed in ${job}:\n${ran.output}`); + // The upload step, which on the forge runs after a failed E2E step alone; matrix.app is the leg's, the attempt the first. + const keep = uploadStep(); + const artifact = ran.ok + ? undefined + : { + name: keep.name.replace('${{ matrix.app }}', leg.app).replace('${{ github.run_attempt }}', '1'), + files: upload(job, keep.path), + }; + large[leg.app] = { build, e2e: ran.output, failed: !ran.ok, artifact }; } + if (Object.values(large).some((job) => job.failed)) + return { test, plan, asked, large, published: {}, deployed: { healthy: false } }; const published: Run['published'] = {}; for (const leg of plan.legs as Leg[]) { @@ -263,10 +315,10 @@ const digestOf = async (ref: string) => (await sh('mise', ['exec', CRANE, '--', const withJob = (run: Run) => run.plan.legs.filter((l) => l.large).map((l) => l.app); /** Commits `edit` to a clone of the origin and pushes it; the new commit. */ -async function push(name: string, edit: (dir: string) => void): Promise { +async function push(name: string, edit: (dir: string) => void | Promise): Promise { const clone = join(here, name); await gitOk(here, 'clone', '-q', origin, clone); - edit(clone); + await edit(clone); await gitOk(clone, 'add', '-A'); await gitOk(clone, 'commit', '--no-verify', '--allow-empty', '-q', '-m', name); await gitOk(clone, 'push', '-q', 'origin', 'HEAD'); @@ -372,3 +424,34 @@ test('a change to a spec of web’s second suite alone gives web a large job, wh for (const app of ['web', 'site']) assert.equal(run.published[app]?.built, false, app); assert.equal(run.deployed.unchanged, true, JSON.stringify(run.deployed)); }); + +test('a failed suite fails its large job, which keeps the failed suites’ results, one artifact per app, and nothing is published', async () => { + /** A spec that fails, as its suite's own. */ + const failing = (what: string) => + `import { expect, test } from '@playwright/test';\n\ntest('${what}', async ({ page }) => {\n await page.goto('/');\n await expect(page.getByRole('heading', { level: 1 })).toHaveText('not the name of the app');\n});\n`; + const sha = await push('push-6', async (dir) => { + put(dir, { 'e2e/web2/specs/fails.spec.ts': failing('the second suite of web fails') }); + // site's first suite, which fails. + await born(join(dir, 'e2e', 'site'), ['e2e-playwright'], { app: '@acme/site' }); + put(dir, { 'e2e/site/specs/fails.spec.ts': failing('the suite of site fails') }); + await relock(dir); + }); + const run = await pipeline(sha, true); + assert.deepEqual(withJob(run), ['site', 'web']); + assert.deepEqual(run.published, {}, 'publish needs every large job'); + const { name, path } = uploadStep(); + assert.equal(path, 'e2e/*/test-results/'); + for (const [app, suite] of [ + ['web', 'web2'], + ['site', 'site'], + ] as const) { + const job = run.large[app]; + assert.equal(job?.failed, true, `${app}: ${job?.e2e}`); + assert.match(job?.e2e ?? '', /\d+ failed/, app); + const artifact = job?.artifact; + assert.equal(artifact?.name, `e2e-${app}-attempt-1`, name); + // Only the failed suite's results, under its directory name; what the passed suite of web left is hidden. + assert.ok((artifact?.files.length ?? 0) > 0, `${app}: nothing to keep`); + for (const file of artifact?.files ?? []) assert.ok(file.startsWith(`${suite}/test-results/`), `${app}: ${file}`); + } +}); diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index 6f2e54ae..0ee7cd78 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -18,12 +18,14 @@ import { CHOICES, distinct } from './testing/shapes.ts'; const WORKFLOWS = join(import.meta.dirname, '..', '..', '..', '.github', 'workflows'); interface Step { + id?: string; name?: string; uses?: string; if?: string; run?: string; with?: Record; env?: Record; + 'continue-on-error'?: unknown; } interface Job { uses?: string; @@ -163,6 +165,49 @@ test('_e2e.yml plans, then per app builds the app and runs its suites on a large assert.deepEqual(needsOf(jobs.cleanup).sort(), ['e2e', 'plan']); }); +// What no machine here can show, since only a runner evaluates `if`, names an artifact and stores it: the shape of the +// step that keeps a failed suite's results. newborns/pipeline.test.ts shows what the step's path finds after a suite +// failed in a newborn, for an app with one suite and one with two. +test('_e2e.yml keeps the results of a failed suite: one upload per app and attempt, only after its E2E step failed, for a few days', () => { + const steps = reusable('_e2e.yml').jobs.e2e?.steps ?? []; + const suiteAt = steps.findIndex((s) => s.run === 'mise run e2e "$APP"'); + const uploads = steps.filter((s) => s.uses?.startsWith('actions/upload-artifact@')); + assert.equal(uploads.length, 1); + const [upload] = uploads; + // The last step, after the suites; pinned by its major, as the job's other actions of GitHub's own are. + assert.ok(suiteAt >= 0 && steps.at(-1) === upload, 'the upload follows the E2E step and ends the job'); + assert.match(upload?.uses ?? '', /^actions\/upload-artifact@v\d+$/); + // Only where the E2E step ran and failed: failure() lifts the default success(), and the step's conclusion is + // `failure` only where it failed, `skipped` where an earlier step failed, `success` on a green run. + const suite = steps[suiteAt]; + assert.equal(suite?.id, 'e2e'); + assert.equal(upload?.if, "${{ failure() && steps.e2e.conclusion == 'failure' }}"); + // The failure stays the job's: neither step continues on error. + for (const step of [suite, upload]) assert.equal(step?.['continue-on-error'], undefined, step?.name); + // Each suite's test-results/ under the suite's directory name: after the wildcard the artifact keeps the path, so + // two suites of one app never meet; the app and the attempt name the artifact, so two apps of a run, or a re-run of + // the job, never do. Hidden files stay out (Playwright's .last-run.json). + assert.equal(upload?.with?.path, 'e2e/*/test-results/'); + assert.equal(upload?.with?.name, 'e2e-${{ matrix.app }}-attempt-${{ github.run_attempt }}'); + assert.equal(upload?.with?.['include-hidden-files'], undefined); + // A suite that failed before Playwright wrote anything (no build output, no browser) uploads nothing, and says nothing. + assert.equal(upload?.with?.['if-no-files-found'], 'ignore'); + assert.equal(upload?.with?.['retention-days'], 5); +}); + +test("the suite's generated config writes its results to test-results/ beside it and no report directory, which the upload would miss", async () => { + const config = textOf(await renderBundled(['e2e-playwright'], { app: '@acme/web' }), 'playwright.config.ts'); + // Playwright's own default for outputDir: test-results beside the package.json; the list reporter writes no file. + assert.doesNotMatch(config, /outputDir/); + assert.match(config, /reporter: 'list'/); +}); + +test("_e2e.yml's header says in one line what a failed suite uploads", () => { + const header = readFileSync(join(WORKFLOWS, '_e2e.yml'), 'utf8').split('\non:')[0] ?? ''; + const lines = header.split('\n').filter((line) => /test-results/.test(line)); + assert.equal(lines.length, 1, header); +}); + test('_publish-deploy.yml publishes on a small runner with the trusted cache, deploys after it, and reads no candidate registry', () => { const { jobs } = reusable('_publish-deploy.yml'); assert.deepEqual(Object.keys(jobs), ['publish', 'display-versions', 'deploy', 'tag-display-version']); From 7b8289d1aea33b556bb7735d618a5acbd658d771 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 04:33:11 +0100 Subject: [PATCH 189/194] _e2e.yml: a failed suite's test-results/ as an artifact of the run The E2E step gets an id, and after it the job uploads e2e/*/test-results/ when failure() && steps.e2e.conclusion == 'failure': not on a green run, not after a failed build, whose E2E step is skipped. The artifact is e2e--attempt-, each suite's results under its directory name; hidden files (Playwright's .last-run.json) stay out, a run with nothing uploads nothing, and it is kept for five days. upload-artifact v7 needs Actions Runner 2.327.1 or newer; the environment image pins 2.338.2. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/_e2e.yml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/.github/workflows/_e2e.yml b/.github/workflows/_e2e.yml index 881753eb..dd6b1c6a 100644 --- a/.github/workflows/_e2e.yml +++ b/.github/workflows/_e2e.yml @@ -17,6 +17,9 @@ name: _e2e # where it has one, `mise run e2e ` # cleanup small hybrid only: delete what this run launched # +# Uploaded: a failed suite's test-results/, what Playwright wrote of its failed +# tests, as an artifact of the run for five days. +# # An app gets an e2e job where it has work: the plan asks the trusted cache, # in its dry run, whether it holds the tasks the job would run, and gives the # job to an app with suites whose build or the e2e of any of whose suites is a @@ -397,9 +400,25 @@ jobs: WITH_DEPS: ${{ runner.environment == 'github-hosted' && 'yes' || '' }} run: for suite in $SUITES; do (cd "$suite" && pnpm exec playwright install ${WITH_DEPS:+--with-deps} chromium); done - name: E2E + id: e2e env: APP: ${{ matrix.app }} run: mise run e2e "$APP" + # Only where the E2E step ran and failed: its conclusion is `skipped` + # where an earlier step failed and `success` on a green run, and + # failure() lifts the default success(); the job stays failed. One + # artifact per app and attempt, which holds each suite's results under + # the suite's directory name. Hidden files stay out, Playwright's + # .last-run.json among them, so a suite that wrote nothing else adds + # nothing, and a run with nothing to keep uploads nothing. + - name: Keep the failed suites' results + if: ${{ failure() && steps.e2e.conclusion == 'failure' }} + uses: actions/upload-artifact@v7 + with: + name: e2e-${{ matrix.app }}-attempt-${{ github.run_attempt }} + path: e2e/*/test-results/ + if-no-files-found: ignore + retention-days: 5 # Hybrid: delete what this run launched, whatever the jobs ended in: an # instance a failed job left, or a runner that never took one. Skipped From 3caf3e34d057c538567d6cc192a9727a0345c869 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 05:33:08 +0100 Subject: [PATCH 190/194] e2e-playwright: tests for the app's alias in the suite's check, and an app whose exports leave out ./package.json The newborn: app code a spec imports through the app's exports, using the app's @/ alias, passes the suite's check; a suite starts an app whose exports name ./greet and not ./package.json, and its spec runs that code. The lib tests: the suite's paths are the app template's, each target through the suite's node_modules link to the app; tsconfig.json says where an app with other aliases adds them, and that update merges it; setup.ts finds the app through node_modules, not through its exports. Red before the change: TS2307 Cannot find module '@/lib/mark' at the app's file, and "Package subpath './package.json' is not defined by exports" from setup.ts. Co-Authored-By: Claude Opus 5.5 --- newborns/e2e-playwright.test.ts | 41 +++++++++++++++++-- packages/lib/src/e2ePlaywright.test.ts | 31 +++++++++++++- .../{tsconfig.json => tsconfig.json.jinja} | 0 3 files changed, 67 insertions(+), 5 deletions(-) rename templates/e2e-playwright/files/{tsconfig.json => tsconfig.json.jinja} (100%) diff --git a/newborns/e2e-playwright.test.ts b/newborns/e2e-playwright.test.ts index 92882639..b8fa4fa6 100644 --- a/newborns/e2e-playwright.test.ts +++ b/newborns/e2e-playwright.test.ts @@ -29,7 +29,8 @@ // passes as generated, also where the app is an ES module, and type-checks each // suite after its app's check, without building the app; `plx doctor` in it // says nothing of the suites' files. It reads the app's code a spec imports -// through the app's `exports`, as the app reads it. A type error in a spec, +// through the app's `exports`, as the app reads it, its `@/` alias included; +// a suite starts an app whose `exports` leave out `./package.json`. A type error in a spec, // also one a change of the app causes, or in what `run.ts` returns fails it, // naming the file; editing the app or a spec moves the hash of the // suite's check, and a spec neither the app's check nor its build. Created by @@ -437,11 +438,13 @@ describe('a repo with two stateless apps, one name the end of the other, and the const app = join(clone, 'apps', 'stateless'); const manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8')); try { - // A module of the app's, which imports another without an extension, as the app's own code may. + // A module of the app's, which imports another without an extension and a third by the app's alias @/, as the + // app's own code may. put(app, { 'src/lib/greet.ts': "import { tail } from './tail';\n\nexport const greet = (name: string): string => `hello ${name}${tail}`;\n", - 'src/lib/tail.ts': "export const tail: string = '!';\n", + 'src/lib/tail.ts': "import { mark } from '@/lib/mark';\n\nexport const tail: string = mark;\n", + 'src/lib/mark.ts': "export const mark = '!';\n", }); put(clone, { 'e2e/stateless/specs/greet.spec.ts': [ @@ -476,6 +479,38 @@ describe('a repo with two stateless apps, one name the end of the other, and the } }); + test("an app whose exports leave out ./package.json is started by its suite, whose spec runs the app's code it imports through them", async () => { + const app = join(clone, 'apps', 'stateless'); + const manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8')); + const run = tmp('s7'); + try { + put(app, { + 'package.json': { ...manifest, exports: { './greet': './src/lib/greet.ts' } }, + 'src/lib/greet.ts': + "import { mark } from '@/lib/mark';\n\nexport const greet = (name: string): string => `hello ${name}${mark}`;\n", + 'src/lib/mark.ts': "export const mark = '!';\n", + }); + put(clone, { + 'e2e/stateless/specs/greet.spec.ts': [ + "import { greet } from '@acme/stateless/greet';", + "import { expect, test } from '@playwright/test';", + '', + "test('greets', () => {", + " expect(greet('you')).toBe('hello you!');", + '});', + '', + ].join('\n'), + }); + const ran = await tryRun('mise', ['run', 'e2e', 'stateless'], clone, { ...SHARED, TMPDIR: run }); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, /\s3 passed \(/); + assert.deepEqual(leftIn(run), []); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + await gitOk(clone, 'clean', '-fdq', '--', 'apps', 'e2e'); + } + }); + test("the suite's check needs no build and follows the app's check; editing the app or a spec moves it, a spec neither the app's check nor its build", async () => { const [suite, app] = ['@acme/stateless-e2e#check', '@acme/stateless#check']; /** Turbo's hashes of the suite's check and what it depends on, with the app's build, by task id. */ diff --git a/packages/lib/src/e2ePlaywright.test.ts b/packages/lib/src/e2ePlaywright.test.ts index e2ff0c0e..c23f341b 100644 --- a/packages/lib/src/e2ePlaywright.test.ts +++ b/packages/lib/src/e2ePlaywright.test.ts @@ -60,7 +60,34 @@ test("tsconfig.json extends the app's base, so that what a spec imports of the a // The specs, setup.ts, run.ts and playwright.config.ts. assert.deepEqual(config.include, ['**/*.ts']); // The setup runs in node; run.ts imports setup.ts by its .ts name, which Playwright resolves. - assert.deepEqual(config.compilerOptions, { allowImportingTsExtensions: true, types: ['node'] }); + const { paths, ...rest } = config.compilerOptions; + assert.deepEqual(rest, { allowImportingTsExtensions: true, types: ['node'] }); +}); + +test("tsconfig.json maps the app's own aliases into the app, through the suite's workspace dependency on it", async () => { + const app = jsonc(textOf(await appRender(), 'tsconfig.json')).compilerOptions.paths; + const suite = jsonc(textOf(await render({ app: '@acme/shop' }), 'tsconfig.json')).compilerOptions.paths; + // Each of the app's targets, relative to the app, as the app's directory is linked into the suite's node_modules. + const mapped = Object.fromEntries( + Object.entries(app as Record).map(([alias, targets]) => [ + alias, + targets.map((target) => target.replace(/^\.\//, './node_modules/@acme/shop/')), + ]), + ); + assert.deepEqual(suite, mapped); + assert.deepEqual(suite, { '@/*': ['./node_modules/@acme/shop/src/*'] }); +}); + +test('tsconfig.json says where a repo puts the aliases of an app that has others, and that the file is merged on update', async () => { + const text = textOf(await render(), 'tsconfig.json'); + assert.match(text, /paths/); + assert.match(text, /plx update merges/); +}); + +test("setup.ts finds the app as Node finds a package, through node_modules, and not through the app's exports", async () => { + const setup = textOf(await render(), 'setup.ts'); + assert.doesNotMatch(setup, /resolve\(`\$\{APP\}\/package\.json`\)/); + assert.match(setup, /'node_modules', APP/); }); test("the incremental check's record is ignored, so that it is no input of a task", async () => { @@ -217,7 +244,7 @@ test("run.ts names the setup's names, which it may not set, and what Turbo lets async function untyped(): Promise<{ tree: Tree; files: Awaited>['files'] }> { const template = new Map(await readTree(join(templatesRoot(), 'e2e-playwright'))); const file = (text: string) => ({ bytes: new TextEncoder().encode(text), mode: 0o100644 }); - template.delete('files/tsconfig.json'); + template.delete('files/tsconfig.json.jinja'); template.set('files/.gitignore.jinja', file('/test-results/\n/playwright-report/\n')); template.set( 'files/package.json.jinja', diff --git a/templates/e2e-playwright/files/tsconfig.json b/templates/e2e-playwright/files/tsconfig.json.jinja similarity index 100% rename from templates/e2e-playwright/files/tsconfig.json rename to templates/e2e-playwright/files/tsconfig.json.jinja From 033cc7f115cddcbfba5ed08791ddd59c8d248df9 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 05:33:13 +0100 Subject: [PATCH 191/194] e2e-playwright: the suite's check resolves the app's alias, and setup.ts finds the app without its exports tsconfig.json (now rendered, for the app's name) maps @/*, as app-nextjs gives it, to ./node_modules//src/*, the suite's workspace link to the app. The template cannot read the app's own tsconfig; an app with other aliases adds them there, as the file says, and plx update merges the file, so those lines stay. setup.ts finds the app's directory as Node finds a package, in node_modules from the suite up, and no longer by resolving /package.json, which fails for an app whose exports leave it out. Co-Authored-By: Claude Opus 5.5 --- templates/e2e-playwright/files/setup.ts.jinja | 20 +++++++++++++++---- .../e2e-playwright/files/tsconfig.json.jinja | 8 +++++++- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/templates/e2e-playwright/files/setup.ts.jinja b/templates/e2e-playwright/files/setup.ts.jinja index 9edf5307..34126add 100644 --- a/templates/e2e-playwright/files/setup.ts.jinja +++ b/templates/e2e-playwright/files/setup.ts.jinja @@ -2,12 +2,12 @@ // The global setup: starts the app's build output, never building it, after a database, migrate and seed where it has them. import { type ChildProcess, spawn } from 'node:child_process'; import { once } from 'node:events'; -import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs'; import { cp, mkdtemp, readFile, rm } from 'node:fs/promises'; -import { createRequire } from 'node:module'; import { createServer } from 'node:net'; import { tmpdir } from 'node:os'; import path from 'node:path'; +import { fileURLToPath } from 'node:url'; import { chromium } from '@playwright/test'; /** The app this suite tests, by its package name. */ @@ -40,8 +40,7 @@ export interface Needs { } export default async function setup(): Promise<() => Promise> { - // Through the workspace dependency, never by a relative path. - const app = path.dirname(createRequire(import.meta.url).resolve(`${APP}/package.json`)); + const app = appDirectory(); const output = path.join(app, '.next', 'standalone'); if (!existsSync(output)) throw new Error( @@ -200,6 +199,19 @@ function checked(needs: unknown): Needs { return needs as Needs; } +/** + * The app's directory, through the workspace dependency and never by a relative path: found as Node finds a package, + * in node_modules from the suite up, and not through the app's exports, which need not export its package.json. + */ +function appDirectory(): string { + for (let dir = path.dirname(fileURLToPath(import.meta.url)); ; dir = path.dirname(dir)) { + const linked = path.join(dir, 'node_modules', APP); + if (existsSync(path.join(linked, 'package.json'))) return realpathSync(linked); + if (path.dirname(dir) === dir) + throw new Error(`${APP} is not installed beside its suite: run pnpm install at the repo's root`); + } +} + /** * The app's directory in the output, as the app's build recorded it: `relativeAppDir` of the one * `.next/required-server-files.json` the output holds outside `node_modules`. diff --git a/templates/e2e-playwright/files/tsconfig.json.jinja b/templates/e2e-playwright/files/tsconfig.json.jinja index b46d7b9f..48c49d03 100644 --- a/templates/e2e-playwright/files/tsconfig.json.jinja +++ b/templates/e2e-playwright/files/tsconfig.json.jinja @@ -4,7 +4,13 @@ "extends": "@plexus-ms/config/tsconfig-next", "compilerOptions": { "allowImportingTsExtensions": true, - "types": ["node"] + "types": ["node"], + // The app's own aliases, as app-nextjs gives them, into the app through the suite's workspace dependency on it, + // for the app's code a spec imports. An app with other paths gives them here too, each target as + // ./node_modules/{{ app }}/; plx update merges this file, so the repo's lines stay. + "paths": { + "@/*": ["./node_modules/{{ app }}/src/*"] + } }, "include": ["**/*.ts"] } From 38c4cf82a265a7cf5db6cdc5330ea8c0ba27ee27 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 05:33:24 +0100 Subject: [PATCH 192/194] _e2e.yml: the header says what a failed suite's artifact holds, and who reads it; the test holds the action's major One sentence: the suite's test-results/, as generated each failed test's error, its spec's source and a snapshot of the page's text, with the repo's own Playwright settings also traces, screenshots and videos, readable by whoever can read the repository, for five days. The lib test asks for each of those, and for actions/upload-artifact@v7 exactly, since a major below v6 runs on Node 20 and the runner floor is v6's. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/_e2e.yml | 7 +++++-- packages/lib/src/pipeline.test.ts | 7 ++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.github/workflows/_e2e.yml b/.github/workflows/_e2e.yml index dd6b1c6a..ce073130 100644 --- a/.github/workflows/_e2e.yml +++ b/.github/workflows/_e2e.yml @@ -17,8 +17,11 @@ name: _e2e # where it has one, `mise run e2e ` # cleanup small hybrid only: delete what this run launched # -# Uploaded: a failed suite's test-results/, what Playwright wrote of its failed -# tests, as an artifact of the run for five days. +# Uploaded where a suite fails, as an artifact of the run for five days and +# readable by whoever can read the repository: the suite's test-results/, as +# generated each failed test's error, its spec's source and a snapshot of the +# page's text, and with the repo's own Playwright settings also traces, +# screenshots and videos. # # An app gets an e2e job where it has work: the plan asks the trusted cache, # in its dry run, whether it holds the tasks the job would run, and gives the diff --git a/packages/lib/src/pipeline.test.ts b/packages/lib/src/pipeline.test.ts index 0ee7cd78..8a5ced48 100644 --- a/packages/lib/src/pipeline.test.ts +++ b/packages/lib/src/pipeline.test.ts @@ -176,7 +176,8 @@ test('_e2e.yml keeps the results of a failed suite: one upload per app and attem const [upload] = uploads; // The last step, after the suites; pinned by its major, as the job's other actions of GitHub's own are. assert.ok(suiteAt >= 0 && steps.at(-1) === upload, 'the upload follows the E2E step and ends the job'); - assert.match(upload?.uses ?? '', /^actions\/upload-artifact@v\d+$/); + // v6 and later run on Node 24 and need Actions Runner 2.327.1, which the environment image passes; the major chosen. + assert.equal(upload?.uses, 'actions/upload-artifact@v7'); // Only where the E2E step ran and failed: failure() lifts the default success(), and the step's conclusion is // `failure` only where it failed, `skipped` where an earlier step failed, `success` on a green run. const suite = steps[suiteAt]; @@ -206,6 +207,10 @@ test("_e2e.yml's header says in one line what a failed suite uploads", () => { const header = readFileSync(join(WORKFLOWS, '_e2e.yml'), 'utf8').split('\non:')[0] ?? ''; const lines = header.split('\n').filter((line) => /test-results/.test(line)); assert.equal(lines.length, 1, header); + // One sentence: as generated, the error, the spec's source and the page's text; with the repo's own settings, more. + const sentence = /^# Uploaded[^.]*\.(?:\n|$)/m.exec(header.replace(/\n# (?=[^\n])/g, ' '))?.[0] ?? ''; + for (const what of ['test-results/', 'page', 'traces', 'screenshots', 'videos', 'read the repository']) + assert.ok(sentence.includes(what), `${what}: ${sentence}`); }); test('_publish-deploy.yml publishes on a small runner with the trusted cache, deploys after it, and reads no candidate registry', () => { From aa4ad975a6bf13e30b407dc0fbb911dbb1a6999d Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 06:09:07 +0100 Subject: [PATCH 193/194] e2e-playwright: tests that a suite's check reads the app's code as the app's own check does The newborn: an app whose tsconfig.json names an alias other than @/* passes the suite's check with no edit of the suite; so does an app with a newer target than the base, which a workspace package it imports needs (a regular expression flag of ES2018), reached by a spec through the app's exports; an edit of the app's tsconfig.json moves the hash of the suite's check. The lib tests: the suite's tsconfig.json extends the app's own through the suite's node_modules link, maps no alias, and sets only its files, noEmit, no build info, no plugin, the .ts imports and node's types. Red before the change: TS2307 Cannot find module '~/lib/mark', and TS1501 at the package's file. The hash moved before as well. Co-Authored-By: Claude Opus 5.5 --- newborns/e2e-playwright.test.ts | 97 ++++++++++++++++++++++++-- packages/lib/src/e2ePlaywright.test.ts | 48 +++++++------ 2 files changed, 117 insertions(+), 28 deletions(-) diff --git a/newborns/e2e-playwright.test.ts b/newborns/e2e-playwright.test.ts index b8fa4fa6..c8d84748 100644 --- a/newborns/e2e-playwright.test.ts +++ b/newborns/e2e-playwright.test.ts @@ -29,11 +29,14 @@ // passes as generated, also where the app is an ES module, and type-checks each // suite after its app's check, without building the app; `plx doctor` in it // says nothing of the suites' files. It reads the app's code a spec imports -// through the app's `exports`, as the app reads it, its `@/` alias included; -// a suite starts an app whose `exports` leave out `./package.json`. A type error in a spec, -// also one a change of the app causes, or in what `run.ts` returns fails it, -// naming the file; editing the app or a spec moves the hash of the -// suite's check, and a spec neither the app's check nor its build. Created by +// through the app's `exports` as the app's own check reads it: the suite's +// `tsconfig.json` extends the app's, so an alias of the app's own and a newer +// target the app's workspace packages need pass with no edit of the suite; a +// suite starts an app whose `exports` leave out `./package.json`. A type error +// in a spec, also one a change of the app causes, or in what `run.ts` returns +// fails it, naming the file; editing the app, its `tsconfig.json` or a spec +// moves the hash of the suite's check, and a spec neither the app's check nor +// its build. Created by // `plx new`; it needs the network. // // Playwright's shared cache is, for these tests, `node_modules/.cache/ms-playwright` @@ -511,6 +514,77 @@ describe('a repo with two stateless apps, one name the end of the other, and the } }); + /** Sets compiler options in the app `stateless`'s tsconfig.json, written as the repo's formatter writes it. */ + async function compilerOptions(app: string, options: Record): Promise { + const config = JSON.parse(readFileSync(join(app, 'tsconfig.json'), 'utf8')); + put(app, { 'tsconfig.json': { ...config, compilerOptions: { ...config.compilerOptions, ...options } } }); + await sh('mise', ['exec', '--', 'biome', 'format', '--write', join(app, 'tsconfig.json')], clone); + } + + /** The app `stateless` exporting `./greet`, which imports `lib` beside it, and a spec of its suite that imports it. */ + function greeting(app: string, manifest: Record, lib: Record): void { + put(app, { 'package.json': { ...manifest, exports: { './greet': './src/lib/greet.ts' } }, ...lib }); + put(clone, { + 'e2e/stateless/specs/greet.spec.ts': [ + "import { greet } from '@acme/stateless/greet';", + "import { expect, test } from '@playwright/test';", + '', + "test('greets', () => {", + " expect(greet('you')).toBe('hello you!');", + '});', + '', + ].join('\n'), + }); + } + + test("an app with an alias of its own, not the template's @/*, passes the suite's check with no edit of the suite", async () => { + const app = join(clone, 'apps', 'stateless'); + const manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8')); + try { + await compilerOptions(app, { paths: { '~/*': ['./src/*'] } }); + greeting(app, manifest, { + 'src/lib/greet.ts': + "import { mark } from '~/lib/mark';\n\nexport const greet = (name: string): string => `hello ${name}${mark}`;\n", + 'src/lib/mark.ts': "export const mark = '!';\n", + }); + const ran = await tryRun('mise', ['run', 'check'], clone); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, checked('stateless')); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + await gitOk(clone, 'clean', '-fdq', '--', 'apps', 'e2e'); + } + }); + + test("an app with a newer target than the base, whose workspace package needs it, passes the suite's check, which reads the package as the app does", async () => { + const app = join(clone, 'apps', 'stateless'); + const manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8')); + try { + // A package of the workspace whose source uses a flag of a regular expression that ES2018 brought. + put(clone, { + 'packages/text/package.json': { name: '@acme/text', private: true, exports: { '.': './src/index.ts' } }, + 'packages/text/src/index.ts': + "export const firstLine = (text: string): string => /^(.*?)$/ms.exec(text)?.[1] ?? '';\n", + }); + await compilerOptions(app, { target: 'ES2022' }); + greeting( + app, + { ...manifest, dependencies: { ...(manifest.dependencies as object), '@acme/text': 'workspace:*' } }, + { + 'src/lib/greet.ts': + "import { firstLine } from '@acme/text';\n\nexport const greet = (name: string): string => firstLine(`hello ${name}!\\nmore`);\n", + }, + ); + await relock(clone); + const ran = await tryRun('mise', ['run', 'check'], clone); + assert.ok(ran.ok, ran.output); + assert.match(ran.output, checked('stateless')); + } finally { + await gitOk(clone, 'reset', '-q', '--hard'); + await gitOk(clone, 'clean', '-fdq', '--', 'apps', 'e2e', 'packages'); + } + }); + test("the suite's check needs no build and follows the app's check; editing the app or a spec moves it, a spec neither the app's check nor its build", async () => { const [suite, app] = ['@acme/stateless-e2e#check', '@acme/stateless#check']; /** Turbo's hashes of the suite's check and what it depends on, with the app's build, by task id. */ @@ -538,7 +612,18 @@ describe('a repo with two stateless apps, one name the end of the other, and the const page = join(clone, 'apps', 'stateless', 'src', 'app', 'page.tsx'); put(clone, { 'apps/stateless/src/app/page.tsx': `${readFileSync(page, 'utf8')}// edited\n` }); await gitOk(clone, 'add', '-A'); - assert.notEqual((await checks()).hash[suite], specEdited.hash[suite], 'an edit of the app'); + const appEdited = await checks(); + assert.notEqual(appEdited.hash[suite], specEdited.hash[suite], 'an edit of the app'); + // The app's tsconfig.json, which the suite's extends. + const config = JSON.parse(readFileSync(join(clone, 'apps', 'stateless', 'tsconfig.json'), 'utf8')); + put(clone, { + 'apps/stateless/tsconfig.json': { + ...config, + compilerOptions: { ...config.compilerOptions, target: 'ES2022' }, + }, + }); + await gitOk(clone, 'add', '-A'); + assert.notEqual((await checks()).hash[suite], appEdited.hash[suite], "an edit of the app's tsconfig.json"); } finally { await gitOk(clone, 'reset', '-q', '--hard'); } diff --git a/packages/lib/src/e2ePlaywright.test.ts b/packages/lib/src/e2ePlaywright.test.ts index c23f341b..1b97f7ae 100644 --- a/packages/lib/src/e2ePlaywright.test.ts +++ b/packages/lib/src/e2ePlaywright.test.ts @@ -54,33 +54,37 @@ test('check type-checks the suite, running no test, with the TypeScript, the nod assert.equal(manifest.devDependencies[name], app.devDependencies[name], name); }); -test("tsconfig.json extends the app's base, so that what a spec imports of the app is read as the app reads it", async () => { - const config = jsonc(textOf(await render(), 'tsconfig.json')); - assert.equal(config.extends, jsonc(textOf(await appRender(), 'tsconfig.json')).extends); - // The specs, setup.ts, run.ts and playwright.config.ts. - assert.deepEqual(config.include, ['**/*.ts']); - // The setup runs in node; run.ts imports setup.ts by its .ts name, which Playwright resolves. - const { paths, ...rest } = config.compilerOptions; - assert.deepEqual(rest, { allowImportingTsExtensions: true, types: ['node'] }); +test("tsconfig.json extends the app's own tsconfig.json, through the suite's workspace link to the app, and maps no alias of its own", async () => { + const config = jsonc(textOf(await render({ app: '@acme/shop' }), 'tsconfig.json')); + // Not the package's name: TypeScript would resolve it through the app's exports, which need not export the file. + assert.equal(config.extends, './node_modules/@acme/shop/tsconfig.json'); + // The app's own options, its paths, target, lib and jsx among them, are the app's; the suite sets only its own. + assert.equal(config.compilerOptions.paths, undefined); + assert.equal(config.compilerOptions.target, undefined); }); -test("tsconfig.json maps the app's own aliases into the app, through the suite's workspace dependency on it", async () => { - const app = jsonc(textOf(await appRender(), 'tsconfig.json')).compilerOptions.paths; - const suite = jsonc(textOf(await render({ app: '@acme/shop' }), 'tsconfig.json')).compilerOptions.paths; - // Each of the app's targets, relative to the app, as the app's directory is linked into the suite's node_modules. - const mapped = Object.fromEntries( - Object.entries(app as Record).map(([alias, targets]) => [ - alias, - targets.map((target) => target.replace(/^\.\//, './node_modules/@acme/shop/')), - ]), - ); - assert.deepEqual(suite, mapped); - assert.deepEqual(suite, { '@/*': ['./node_modules/@acme/shop/src/*'] }); +test("the app's tsconfig.json, which a suite extends, is at the app's root as app-nextjs renders it", async () => { + assert.ok(pathsOf(await appRender()).includes('tsconfig.json')); +}); + +test("tsconfig.json overrides only what is the suite's: its files, no emit and no build info, no editor plugin of the app's, the .ts imports, node's types", async () => { + const config = jsonc(textOf(await render(), 'tsconfig.json')); + // The specs, setup.ts, run.ts and playwright.config.ts; include and exclude are never inherited. + assert.deepEqual(config.include, ['**/*.ts']); + assert.deepEqual(config.exclude, ['node_modules']); + assert.deepEqual(config.compilerOptions, { + noEmit: true, + // tsc 6 reused its build info across a change of the extended config's target alone, both ways (tried). + incremental: false, + plugins: [], + allowImportingTsExtensions: true, + types: ['node'], + }); }); -test('tsconfig.json says where a repo puts the aliases of an app that has others, and that the file is merged on update', async () => { +test('tsconfig.json says whose options it reads, and that plx update merges it', async () => { const text = textOf(await render(), 'tsconfig.json'); - assert.match(text, /paths/); + assert.match(text, /the app's own/); assert.match(text, /plx update merges/); }); From e86604126c77429ce844120f8707697d87f90122 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Tue, 1 Dec 2026 06:09:31 +0100 Subject: [PATCH 194/194] e2e-playwright: the suite's tsconfig.json extends the app's own It extends ./node_modules//tsconfig.json, the app's own config through the suite's workspace link, so the suite's check reads the app's code with the app's aliases, target, lib, jsx and module settings, which TypeScript resolves relative to the config that defines them. The suite sets only its own: include and exclude (never inherited), noEmit, no build info, no editor plugin, the .ts imports and node's types. The mirror of the app template's @/* alias goes. No build info: tsc 6.0.3 reused it across a change of the extended config's target alone, and reported the old result both ways (tried). Not the package's name in extends: that resolves through the app's exports, which need not export tsconfig.json. Co-Authored-By: Claude Opus 5.5 --- .../e2e-playwright/files/tsconfig.json.jinja | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/templates/e2e-playwright/files/tsconfig.json.jinja b/templates/e2e-playwright/files/tsconfig.json.jinja index 48c49d03..6ec6f37d 100644 --- a/templates/e2e-playwright/files/tsconfig.json.jinja +++ b/templates/e2e-playwright/files/tsconfig.json.jinja @@ -1,16 +1,18 @@ { - // The suite's check: its files and what they import of the app, on the app's own base, so the app's code is read as - // the app reads it; node's types, and the .ts name by which run.ts imports setup.ts, which Playwright resolves. - "extends": "@plexus-ms/config/tsconfig-next", + // The suite's check reads the app's code as the app's own check does: it extends the app's own tsconfig.json, its + // aliases, target, lib and jsx included, through the suite's workspace link to the app, and sets only the suite's own. + "extends": "./node_modules/{{ app }}/tsconfig.json", "compilerOptions": { + "noEmit": true, + // No build info: tsc reused it across a change of the app's target alone, and the check is Turbo's to cache. + "incremental": false, + // The app's editor plugins are the app's. + "plugins": [], + // run.ts imports setup.ts by its .ts name, which Playwright resolves; the setup runs in node. plx update merges + // this file, so a line a repo adds stays. "allowImportingTsExtensions": true, - "types": ["node"], - // The app's own aliases, as app-nextjs gives them, into the app through the suite's workspace dependency on it, - // for the app's code a spec imports. An app with other paths gives them here too, each target as - // ./node_modules/{{ app }}/; plx update merges this file, so the repo's lines stay. - "paths": { - "@/*": ["./node_modules/{{ app }}/src/*"] - } + "types": ["node"] }, - "include": ["**/*.ts"] + "include": ["**/*.ts"], + "exclude": ["node_modules"] }