Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add npm run preflight, AGENTS.md and issue and pull request templates

Nguyen Xuan An84e8d382d638
diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml
new file mode 100644
index 00000000..96204516
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug.yml
@@ -0,0 +1,54 @@
+name: Bug report
+description: Something renders wrong, throws, crashes or runs slower than it should.
+labels: [bug]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Search [open issues](https://github.com/codepawl/67.js/issues?q=is%3Aissue) first. A security problem goes to [email protected], not here ([SECURITY.md](https://github.com/codepawl/67.js/blob/main/SECURITY.md)).
+ Leave out local paths, tokens and personal data: issues are public.
+ - type: dropdown
+ id: surface
+ attributes:
+ label: Where it happens
+ options:
+ - Library in my app (import from @codepawlhq/67js)
+ - MCP server, driven by an agent
+ - Render job or video export
+ - The site or the docs
+ - Other
+ validations:
+ required: true
+ - type: textarea
+ id: what-happened
+ attributes:
+ label: What happened
+ description: What you saw, and what you expected instead. Paste the full error text and attach a screenshot when it is about the look.
+ validations:
+ required: true
+ - type: textarea
+ id: steps
+ attributes:
+ label: Steps to reproduce
+ description: The smallest code, scene recipe or MCP tool call that shows it. A recipe JSON or a short script is ideal.
+ render: js
+ validations:
+ required: true
+ - type: input
+ id: version
+ attributes:
+ label: 67js version
+ description: Run `npm ls @codepawlhq/67js` or `npx 67js-mcp --version`.
+ placeholder: 0.16.0
+ validations:
+ required: true
+ - type: textarea
+ id: environment
+ attributes:
+ label: Environment
+ description: Operating system, browser and version, GPU, Node version. For the MCP server, also the agent client and the flags you start it with (`--backend`, `--memory`).
+ placeholder: |
+ Windows 11, Chrome 142, RTX 3060, Node 24
+ Claude Code, npx 67js-mcp --backend gpu --memory 192
+ validations:
+ required: true
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 00000000..50621697
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,8 @@
+blank_issues_enabled: false
+contact_links:
+ - name: Report a security problem
+ url: https://github.com/codepawl/67.js/blob/main/SECURITY.md
+ about: Email [email protected]. Do not open a public issue for a vulnerability.
+ - name: Guide and API reference
+ url: https://67js.codepawl.com/docs
+ about: How to install 67js, build scenes and drive the MCP server.
diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml
new file mode 100644
index 00000000..5ecfc4d1
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature.yml
@@ -0,0 +1,38 @@
+name: Feature request
+description: Something 67js or its MCP tools should be able to do.
+labels: [enhancement]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Check [ROADMAP.md](https://github.com/codepawl/67.js/blob/main/ROADMAP.md) and the [open issues](https://github.com/codepawl/67.js/issues) first.
+ - type: textarea
+ id: why
+ attributes:
+ label: Why
+ description: What you are trying to make, and where 67js stops you today. A picture of the result you want helps.
+ validations:
+ required: true
+ - type: textarea
+ id: scope
+ attributes:
+ label: Scope
+ description: What the change would cover, such as a new option, a new MCP tool field or a new addon. Say what it should not cover.
+ validations:
+ required: true
+ - type: textarea
+ id: done-when
+ attributes:
+ label: Done when
+ description: How we will know it works, as a checklist.
+ placeholder: |
+ - [ ] An agent can ... in one tool call
+ - [ ] A test covers ...
+ validations:
+ required: true
+ - type: checkboxes
+ id: contribute
+ attributes:
+ label: Contribution
+ options:
+ - label: I would like to open the pull request for this myself.
diff --git a/.github/ISSUE_TEMPLATE/question.yml b/.github/ISSUE_TEMPLATE/question.yml
new file mode 100644
index 00000000..905aae07
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/question.yml
@@ -0,0 +1,20 @@
+name: Question
+description: How do I do something with 67js or its MCP server?
+labels: [question]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ The [guide](https://67js.codepawl.com/guide.md), the [MCP reference](https://github.com/codepawl/67.js/blob/main/docs/mcp.md) and [llms.txt](https://67js.codepawl.com/llms.txt) answer most questions. An agent can read them too.
+ - type: textarea
+ id: question
+ attributes:
+ label: Question
+ description: What you want to do and what you tried. Include code or the tool call when you have one.
+ validations:
+ required: true
+ - type: input
+ id: version
+ attributes:
+ label: 67js version
+ placeholder: 0.16.0
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
new file mode 100644
index 00000000..3091fac4
--- /dev/null
+++ b/.github/pull_request_template.md
@@ -0,0 +1,17 @@
+## What changed
+
+<!-- One or two sentences: what a user or an agent can do now, or what got better. -->
+
+Closes #
+
+## How I checked it
+
+- [ ] `npm run preflight` passed
+- [ ] `changes/<issue>.md` added (skip for CI, docs or test-only changes)
+- [ ] The guide in `docs/` describes the change
+
+<!-- Checks that need a GPU or a person (CONTRIBUTING.md#checks). Name the ones you ran and what you saw, or say why you could not. -->
+
+## Size or tool cost
+
+<!-- Delete this section unless a bundle or an MCP tool grew. Say why it is worth the bytes; the line goes in changes/<issue>.size.md. -->
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 00000000..fbcdbd49
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,63 @@
+# 67js for coding agents
+
+Read this before you change code in this repository. [CONTRIBUTING.md](CONTRIBUTING.md) has the full rules; this file is the short path.
+To build scenes with 67js rather than change it, use the MCP server and the skills in `skills/` instead ([README](README.md#for-agents)).
+
+## Layout
+
+- `src/` is the library, one flat folder. `src/agent-*.js` and `src/mcp*` are the MCP tool surface.
+- `bin/67js-mcp.mjs` starts the MCP server. `packages/` holds the addon packages.
+- `tests/` holds the Node tests, one `*.test.js` per area. `scripts/` holds the build, smoke and gate scripts.
+- `docs/` holds one guide per feature. `skills/` holds the agent skills that ship with the package.
+- `changes/` holds one changelog note per pull request. `artifacts/` is ignored output for screenshots and logs.
+
+## Set up
+
+```sh
+npm ci
+```
+
+Node 20.19 or later, Node 24 on CI. Chrome is needed for the smoke scripts and the MCP tests.
+
+## Before you open a pull request
+
+```sh
+npm run preflight
+```
+
+It runs the gates of the `Test` workflow that apply to the files your branch changed: protected files, the change note, links,
+tool schemas, size, tool cost, the build, the unit tests with coverage and the coverage gate. It keeps going after a failure,
+writes each log to `artifacts/preflight/`, prints only the tail of a failing log and ends with one line per check and its fix.
+`--skip-tests` skips the slow test pass while you iterate, and `--json` adds a machine-readable summary.
+Run the full preflight once before you push. A green preflight means the `test` check should pass.
+
+For one test file: `node --test tests/<area>.test.js`.
+
+## Rules that fail a pull request
+
+- Add `changes/<issue>.md` with one bullet when you change `src/`, `bin/`, `packages/` or `skills/` ([changes/README.md](changes/README.md)).
+- Never edit `CHANGELOG.md`, `bench/size/budgets.json`, `bench/size/baseline.json` or `bench/tool-cost-budgets.json`. Maintainers reset them at release.
+- A bundle that grows past its allowance needs a line in `changes/<issue>.size.md` that says why the bytes are worth it ([bench/size/README.md](bench/size/README.md)). The same file accepts tool cost growth ([bench/tool-cost/README.md](bench/tool-cost/README.md)).
+- Coverage may not drop. Write the tests in the same commit as the code.
+- Never weaken or skip a test to make it pass. Find why it fails.
+
+## Code
+
+- Descriptive full names, one statement per line, small functions, comments only for a reason the code does not show.
+- No new runtime dependency in the core. Optional features go in an addon.
+- Scene builders are deterministic for the same seed; tests compare geometry byte for byte.
+- Validate input at the public boundary and throw an error that says what failed and what to pass instead. Agents read these errors.
+- MCP tools accept no arbitrary code and no remote asset URLs ([SECURITY.md](SECURITY.md)). Keep every count and size bounded.
+- Update the guide in `docs/` for the feature you change.
+
+## Checks a person or a GPU runs
+
+Shaders, lighting, skinning, glTF and the frame path need real pixels. `npm run preflight` names the ones that may apply to your
+change; the table in [CONTRIBUTING.md](CONTRIBUTING.md#checks) says when each one is needed. Say in the pull request which ones you
+ran and what you saw. If you cannot run one, say that instead.
+
+## Working etiquette
+
+- One change per pull request, on a branch from `main`. Merge `main` into it before you push again.
+- Stop only processes you started, by their PID. Other jobs may share the machine.
+- Issues and pull requests are public. Keep local paths, tokens and personal data out of them.
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 00000000..43c994c2
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1 @@
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 00000000..a939eed7
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,21 @@
+# Code of conduct
+
+67js is built by people and by the agents they run. Both are welcome here, and the same rules hold for both.
+
+## Expected
+
+- Be kind and specific. Criticise code and results, not people.
+- Assume good faith, and ask when something is unclear.
+- Keep issues and pull requests on topic. One problem or one change each.
+- Check that an agent's issue or pull request is correct before you post it. You answer for what your agent posts.
+
+## Not accepted
+
+- Harassment, insults, slurs, or sexual content.
+- Posting someone's private information.
+- Spam, including mass-generated issues, comments or pull requests that nobody checked.
+
+## Enforcement
+
+Maintainers may edit, hide or close any issue, comment or pull request that breaks these rules, and may block an account that keeps breaking them.
+Report a problem to [email protected]. Reports are kept private.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 1baa8d86..4563f9d1 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,6 +1,8 @@
# Contributing to 67js
This file covers setup, the checks a change must pass, the code style and the release flow.
+Coding agents can start with [AGENTS.md](AGENTS.md), the short version. Everyone follows the [code of conduct](CODE_OF_CONDUCT.md).
+To ask a question or report a bug, see [SUPPORT.md](SUPPORT.md).
## Set up
@@ -14,16 +16,18 @@ The tests are in `tests/` and the guides are in `docs/`.
## Make a change
-1. For a large feature, open an issue first, so that we agree on the design before you write it.
+1. For a large feature, open an issue first with the feature form, so that we agree on the design before you write it. Issues labelled `good first issue` are a good place to start.
2. Create a branch from `main`.
3. Write the change and its tests in the same commit.
4. Update the guide in `docs/` that describes the feature.
5. Add `changes/<issue-or-branch>.md` with your changelog bullet (format in `changes/README.md`). Do not edit `CHANGELOG.md`: two pull requests that edit it conflict on GitHub.
-6. Open a pull request that says what changed and how you checked it.
+6. Open a pull request. The template asks what changed and how you checked it.
## Checks
-Run these before you open a pull request:
+Run `npm run preflight` before you open a pull request. It runs every check below that applies to the files you changed, plus the size, tool cost and coverage gates, keeps going after a failure and ends with one line per check and how to fix it. Logs go to `artifacts/preflight/`. `--skip-tests` skips the slow test pass while you iterate.
+
+The checks it runs, if you want one alone:
1. Run `npm test`. All Node tests must pass.
2. Run `npm run check:links` if you changed a Markdown or HTML file. It finds links that point at no file.
@@ -35,7 +39,7 @@ Run `npm run smoke` or the `smoke:*` script for the area that you changed, and l
A change to skinning, glTF loading, poses or IK also needs `npm run smoke:character`, which takes a real character through the MCP server. Run `npm run prepare:release` first.
Screenshots and other output go to `artifacts/`, which Git ignores.
-Every pull request runs `npm audit`, `npm run size`, `npm run tool-cost`, `npm test` (with coverage, six shards; Node runs each file in its own process), `prepare:release`, `smoke:package` and `smoke:mcp-package` in the `Test` workflow. `smoke:mcp-package` draws through the MCP server on SwiftShader in Chrome. `npm run size` compares every bundle with `origin/main`. If a bundle grows past its allowance (64 bytes gzip for core and the scenes, 2% for the npm archive), add `changes/<issue>.size.md` with the line `- entry:core: <why it is worth the bytes>` and say why in the pull request. Never edit `bench/size/budgets.json` or `baseline.json` in a pull request. `bench/size/README.md` has the details.
+Every pull request runs `npm audit`, `npm run size`, `npm run tool-cost`, `npm test` (with coverage, eight shards; Node runs each file in its own process), `prepare:release`, `smoke:package` and `smoke:mcp-package` in the `Test` workflow. `smoke:mcp-package` draws through the MCP server on SwiftShader in Chrome. `npm run size` compares every bundle with `origin/main`. If a bundle grows past its allowance (64 bytes gzip for core and the scenes, 2% for the npm archive), add `changes/<issue>.size.md` with the line `- entry:core: <why it is worth the bytes>` and say why in the pull request. Never edit `bench/size/budgets.json` or `baseline.json` in a pull request. `bench/size/README.md` has the details.
`npm run tool-cost` does the same for what the MCP tools cost an agent. If a tool schema grows by more than 64 bytes, a typical result by more than 128 bytes, or the schema total by more than 128 bytes, first move rare detail into `scene_capabilities` or a shared schema. If the growth is worth it, add a line to `changes/<issue>.size.md`, such as `- tool:scene_create: <why it is worth the bytes>`, `- tool-total: <why>` or `- result:scene_capabilities: <why>`. Never edit `bench/tool-cost-budgets.json` in a pull request. `bench/tool-cost/README.md` has the details.
diff --git a/README.md b/README.md
index 195e7dbc..136cd5b1 100644
--- a/README.md
+++ b/README.md
@@ -161,6 +161,8 @@ They compare matching scenes on the same hardware. They do not show a general sp
## Contributing
Read [CONTRIBUTING.md](https://github.com/codepawl/67.js/blob/main/CONTRIBUTING.md) before you open a pull request. It covers setup, checks, code style and the release flow.
+Coding agents start with [AGENTS.md](https://github.com/codepawl/67.js/blob/main/AGENTS.md), and `npm run preflight` runs the pull request checks locally.
+Questions and bug reports: [SUPPORT.md](https://github.com/codepawl/67.js/blob/main/SUPPORT.md).
## Credits
diff --git a/SUPPORT.md b/SUPPORT.md
new file mode 100644
index 00000000..7dff0adb
--- /dev/null
+++ b/SUPPORT.md
@@ -0,0 +1,26 @@
+# Getting help
+
+## Read first
+
+- The [guide](https://67js.codepawl.com/guide.md) covers install, scenes, materials, animation and export.
+- The [MCP reference](docs/mcp.md) lists every tool, its limits and its errors.
+- [llms.txt](https://67js.codepawl.com/llms.txt) is the same guide as plain text for an agent.
+- The skills [build-67js-scene](skills/build-67js-scene/SKILL.md) and [render-67js-media](skills/render-67js-media/SKILL.md) teach an agent the MCP tools.
+
+## Ask or report
+
+Open an [issue](https://github.com/codepawl/67.js/issues/new/choose) and pick the form that fits: a bug, a feature or a question.
+A bug report that has the version, the environment and the smallest recipe or script that shows the problem gets fixed first.
+
+Issues are public. Leave out local paths, tokens and personal data.
+
+## Security
+
+Email [email protected] and do not open a public issue. [SECURITY.md](SECURITY.md) has the details.
+
+## Common problems
+
+- **The MCP server cannot find Chrome.** Install Chrome, or pass `--browser <path to a Chromium executable>`.
+- **No GPU, or the GPU backend fails.** Start the server with `--backend cpu`. It is slower.
+- **Render jobs fail at once.** Render jobs need `--jobs <absolute output folder>`, and MP4 needs FFmpeg on `PATH` or `--ffmpeg <path>`.
+- **The server runs out of memory.** Change `--memory` (32 to 384) or split the scene. `npx 67js-mcp --help` lists every flag.
diff --git a/package.json b/package.json
index 40808847..7b366f43 100644
--- a/package.json
+++ b/package.json
@@ -130,6 +130,7 @@
"test:isolated": "node scripts/test-each-file.mjs",
"test:coverage": "node --test --experimental-test-coverage --test-coverage-exclude=\"tests/**\" --test-coverage-exclude=\"scripts/**\" --test-coverage-exclude=\"build/**\"",
"coverage:gate": "node scripts/coverage-gate.mjs",
+ "preflight": "node scripts/preflight.mjs",
"smoke": "node scripts/smoke.mjs",
"smoke:scenes": "node scripts/smoke-scenes.mjs",
"smoke:vegetation-impostors": "node scripts/smoke-vegetation-impostors.mjs",
diff --git a/scripts/preflight.mjs b/scripts/preflight.mjs
new file mode 100644
index 00000000..fe3ef705
--- /dev/null
+++ b/scripts/preflight.mjs
@@ -0,0 +1,241 @@
+// Runs the pull request gates of the `Test` workflow on this checkout, picked by the files the branch changed, and ends with
+// one summary line per check and how to fix each failure. Made for people and coding agents alike: every check runs even
+// after one fails, full logs go to artifacts/preflight/, and only the tail of a failing log is printed.
+// Usage: npm run preflight every check that applies to the changed files
+// npm run preflight -- --skip-tests skip the unit tests and the coverage gate (the slowest part)
+// npm run preflight -- --json print the summary as JSON after the logs
+// npm run preflight -- --base <ref> compare with another ref than origin/main
+import { spawn, spawnSync } from 'node:child_process';
+import { createWriteStream, mkdirSync, readFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const root = fileURLToPath(new URL('..', import.meta.url));
+const logFolder = join(root, 'artifacts', 'preflight');
+const failingLogTailLines = 30;
+
+// Files a pull request must never edit. Each one is reset by a maintainer at release time.
+export const PROTECTED_FILES = Object.freeze({
+ 'CHANGELOG.md': 'Add a changes/<issue>.md note instead (changes/README.md). Two pull requests that edit CHANGELOG.md conflict.',
+ 'bench/size/budgets.json': 'Accept a size increase with a changes/<issue>.size.md line instead (bench/size/README.md).',
+ 'bench/size/baseline.json': 'Accept a size increase with a changes/<issue>.size.md line instead (bench/size/README.md).',
+ 'bench/tool-cost-budgets.json': 'Accept a tool cost increase with a changes/<issue>.size.md line instead (bench/tool-cost/README.md).',
+});
+
+const userFacingPattern = /^(src|bin|packages|skills)\//;
+const shippedCodePattern = /^(src|bin|packages)\/|^package(-lock)?\.json$|^vite\.lib\.config\.js$|^scripts\/build-mcp\.mjs$/;
+const toolCodePattern = /^(src\/agent-|src\/mcp|bin\/)|^scripts\/(build-mcp|measure-tool-cost|check-tool-cost)/;
+const linkedTextPattern = /\.(md|html)$/;
+
+// Checks a GPU or a person's eyes must run. CONTRIBUTING.md lists them; these patterns only point out the ones that may apply.
+const MANUAL_CHECKS = Object.freeze([
+ { pattern: /shader|light|material|environment|shadow|tone|fog|sky/, command: 'npm run reference', reason: 'shaders, lighting or materials' },
+ { pattern: /skin|gltf|pose|retarget|skeleton|(^|[-/])ik[-.]/, command: 'npm run smoke:character', reason: 'skinning, glTF, poses or IK' },
+ { pattern: /^src\/(agent-|mcp)|^bin\//, command: 'npm run smoke:mcp', reason: 'MCP tools or the preview' },
+ { pattern: /^src\/(renderer|frame|render)/, command: 'npm run benchmark:runtime', reason: 'the frame path' },
+]);
+
+function isNewChangeNote(path) {
+ return path.startsWith('changes/') && path.endsWith('.md') && path !== 'changes/README.md';
+}
+
+// Decides which checks apply to a list of changed paths. Pure, so tests can call it without git.
+export function planChecks(changedPaths, { skipTests = false } = {}) {
+ const paths = changedPaths.map(path => path.replace(/\\/g, '/'));
+ const changesShippedCode = paths.some(path => shippedCodePattern.test(path));
+ const changesToolCode = paths.some(path => toolCodePattern.test(path));
+ const checks = [];
+
+ const protectedEdits = paths.filter(path => path in PROTECTED_FILES);
+ checks.push({
+ name: 'protected files',
+ kind: 'inline',
+ failure: protectedEdits.length ? protectedEdits.map(path => `${path}: ${PROTECTED_FILES[path]}`).join('\n') : null,
+ fix: 'Revert the edits named above: git checkout origin/main -- <file>',
+ });
+
+ const needsNote = paths.some(path => userFacingPattern.test(path));
+ const hasNote = paths.some(path => isNewChangeNote(path) && !path.endsWith('.size.md'));
+ checks.push({
+ name: 'change note',
+ kind: 'inline',
+ skipped: needsNote ? null : 'no change under src/, bin/, packages/ or skills/',
+ failure: needsNote && !hasNote ? 'The branch changes shipped code but adds no changes/<issue>.md.' : null,
+ fix: 'Add changes/<issue>.md with one bullet, such as "- `bar` takes a `foo` option (#123)" (changes/README.md).',
+ });
+
+ checks.push(linkedTextCheck(paths));
+ checks.push({
+ name: 'tool schemas',
+ command: ['npm', 'run', 'check:tool-schemas'],
+ skipped: changesToolCode ? null : 'no MCP tool code changed',
+ fix: 'Fix the schema the report names; every client profile must accept it (scripts/check-tool-schemas.mjs).',
+ });
+ checks.push({
+ name: 'size',
+ command: ['npm', 'run', 'size'],
+ skipped: changesShippedCode ? null : 'no shipped code changed',
+ fix: 'Shrink the change, or add "- entry:<name>: <why it is worth the bytes>" to changes/<issue>.size.md (bench/size/README.md).',
+ });
+ checks.push({
+ name: 'tool cost',
+ command: ['npm', 'run', 'tool-cost'],
+ skipped: changesToolCode ? null : 'no MCP tool code changed',
+ fix: 'Move rare detail into scene_capabilities or a shared schema, or add "- tool:<name>: <why>" to changes/<issue>.size.md (bench/tool-cost/README.md).',
+ });
+
+ const testSkip = skipTests ? 'skipped with --skip-tests' : null;
+ checks.push({
+ name: 'build library',
+ command: ['npm', 'run', 'build:lib'],
+ skipped: testSkip,
+ fix: 'Fix the build error in the log; the MCP tests need build/.',
+ });
+ checks.push({
+ name: 'unit tests and coverage',
+ command: ['npm', 'run', 'test:coverage', '--', '--test-reporter=dot', '--test-reporter-destination=stdout', '--test-reporter=lcov', '--test-reporter-destination=coverage/lcov.info'],
+ skipped: testSkip,
+ fix: 'Run the failing file alone with node --test tests/<file>.test.js. Never weaken a test to make it pass.',
+ });
+ checks.push({
+ name: 'coverage gate',
+ command: ['npm', 'run', 'coverage:gate', '--', 'coverage'],
+ skipped: testSkip,
+ dependsOn: 'unit tests and coverage',
+ fix: 'Add tests for the new code. coverage-baseline.json may only go up.',
+ });
+ return checks;
+}
+
+function linkedTextCheck(paths) {
+ const changesLinkedText = paths.some(path => linkedTextPattern.test(path));
+ return {
+ name: 'links',
+ command: ['npm', 'run', 'check:links'],
+ skipped: changesLinkedText ? null : 'no Markdown or HTML changed',
+ fix: 'Fix or remove each link the report names.',
+ };
+}
+
+export function manualChecksFor(changedPaths) {
+ const paths = changedPaths.map(path => path.replace(/\\/g, '/'));
+ return MANUAL_CHECKS.filter(check => paths.some(path => check.pattern.test(path)));
+}
+
+function git(args) {
+ const result = spawnSync('git', args, { cwd: root, encoding: 'utf8' });
+ return result.status === 0 ? result.stdout.trim() : null;
+}
+
+function changedPathsSince(baseRef) {
+ const mergeBase = git(['merge-base', baseRef, 'HEAD']) ?? baseRef;
+ const committedAndStaged = git(['diff', '--name-only', mergeBase]) ?? '';
+ const untracked = git(['ls-files', '--others', '--exclude-standard']) ?? '';
+ const lines = `${committedAndStaged}\n${untracked}`.split('\n').filter(Boolean);
+ return [...new Set(lines)].sort();
+}
+
+function logPathFor(check) {
+ return join(logFolder, `${check.name.replace(/\W+/g, '-')}.log`);
+}
+
+function runCommand(check) {
+ return new Promise(resolvePromise => {
+ const logPath = logPathFor(check);
+ const log = createWriteStream(logPath);
+ const [program, ...args] = check.command;
+ const child = spawn(program, args, { cwd: root, shell: process.platform === 'win32', env: process.env });
+ child.stdout.pipe(log, { end: false });
+ child.stderr.pipe(log, { end: false });
+ child.on('close', code => {
+ log.end(() => resolvePromise({ code, logPath }));
+ });
+ });
+}
+
+function tailOf(path, lineCount) {
+ const lines = readFileSync(path, 'utf8').trimEnd().split(/\r?\n/);
+ return lines.slice(-lineCount).join('\n');
+}
+
+async function runChecks(checks) {
+ const results = [];
+ for (const check of checks) {
+ const dependency = check.dependsOn && results.find(result => result.name === check.dependsOn);
+ if (check.skipped) {
+ results.push({ name: check.name, status: 'skip', detail: check.skipped });
+ } else if (dependency && dependency.status !== 'ok') {
+ results.push({ name: check.name, status: 'skip', detail: `${check.dependsOn} did not pass` });
+ } else if (check.kind === 'inline') {
+ results.push(check.failure
+ ? { name: check.name, status: 'fail', detail: check.failure, fix: check.fix }
+ : { name: check.name, status: 'ok' });
+ } else {
+ process.stdout.write(`… ${check.name}: ${check.command.join(' ')}\n`);
+ const startedAt = Date.now();
+ const { code, logPath } = await runCommand(check);
+ const seconds = Math.round((Date.now() - startedAt) / 1000);
+ const log = logPath.slice(root.length).replace(/\\/g, '/');
+ if (code === 0) {
+ results.push({ name: check.name, status: 'ok', detail: `${seconds} s`, log });
+ } else {
+ process.stdout.write(`\n--- last ${failingLogTailLines} lines of ${log} ---\n${tailOf(logPath, failingLogTailLines)}\n---\n\n`);
+ results.push({ name: check.name, status: 'fail', detail: `exit ${code} after ${seconds} s`, log, fix: check.fix });
+ }
+ }
+ }
+ return results;
+}
+
+function printSummary(results, manualChecks) {
+ const marks = { ok: 'ok ', fail: 'FAIL', skip: 'skip' };
+ console.log('\nPreflight summary');
+ for (const result of results) {
+ const detail = result.detail ? ` (${result.detail.split('\n')[0]})` : '';
+ console.log(`${marks[result.status]} ${result.name}${detail}`);
+ if (result.status === 'fail') {
+ for (const line of result.detail.split('\n').slice(1)) console.log(` ${line}`);
+ if (result.log) console.log(` log: ${result.log}`);
+ console.log(` fix: ${result.fix}`);
+ }
+ }
+ if (manualChecks.length) {
+ console.log('\nNot run here, may apply (they need a GPU or a person, see CONTRIBUTING.md):');
+ for (const check of manualChecks) console.log(` ${check.command} for ${check.reason}`);
+ }
+}
+
+function valueAfter(args, flag) {
+ const index = args.indexOf(flag);
+ return index < 0 ? null : args[index + 1];
+}
+
+async function main(args) {
+ const baseRef = valueAfter(args, '--base') ?? 'origin/main';
+ if (baseRef === 'origin/main' && git(['fetch', '--quiet', 'origin', 'main']) === null) {
+ console.warn('Could not fetch origin/main; comparing with the local copy, which may be stale.');
+ }
+ if (git(['rev-parse', '--verify', '--quiet', `${baseRef}^{commit}`]) === null) {
+ console.error(`The base ref ${baseRef} does not exist. Fetch it, or pass --base <ref>.`);
+ process.exit(2);
+ }
+ mkdirSync(logFolder, { recursive: true });
+ mkdirSync(join(root, 'coverage'), { recursive: true });
+
+ const changedPaths = changedPathsSince(baseRef);
+ console.log(`${changedPaths.length} files changed since ${baseRef}.`);
+ const checks = planChecks(changedPaths, { skipTests: args.includes('--skip-tests') });
+ const results = await runChecks(checks);
+ const manualChecks = manualChecksFor(changedPaths);
+ printSummary(results, manualChecks);
+ if (args.includes('--json')) {
+ console.log(JSON.stringify({ base: baseRef, results, manualChecks: manualChecks.map(check => check.command) }, null, 2));
+ }
+ const failed = results.some(result => result.status === 'fail');
+ console.log(failed ? '\nPreflight failed. The Test workflow would fail the same way.' : '\nPreflight passed.');
+ process.exit(failed ? 1 : 0);
+}
+
+if (import.meta.url === pathToFileURL(resolve(process.argv[1] ?? '')).href) {
+ await main(process.argv.slice(2));
+}
diff --git a/tests/preflight.test.js b/tests/preflight.test.js
new file mode 100644
index 00000000..2749a52d
--- /dev/null
+++ b/tests/preflight.test.js
@@ -0,0 +1,54 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { manualChecksFor, planChecks } from '../scripts/preflight.mjs';
+
+function checkNamed(checks, name) {
+ return checks.find(check => check.name === name);
+}
+
+test('a docs-only change runs the link check and skips the code gates', () => {
+ const checks = planChecks(['docs/guide.md']);
+ assert.equal(checkNamed(checks, 'links').skipped, null);
+ assert.match(checkNamed(checks, 'size').skipped, /no shipped code/);
+ assert.match(checkNamed(checks, 'tool cost').skipped, /no MCP tool code/);
+ assert.match(checkNamed(checks, 'change note').skipped, /no change under/);
+});
+
+test('a source change without a change note fails the note check', () => {
+ const checks = planChecks(['src/camera.js']);
+ assert.match(checkNamed(checks, 'change note').failure, /changes\/<issue>\.md/);
+ assert.equal(checkNamed(checks, 'size').skipped, null);
+});
+
+test('a size note alone does not count as a change note', () => {
+ const checks = planChecks(['src/camera.js', 'changes/700.size.md']);
+ assert.ok(checkNamed(checks, 'change note').failure);
+ const withNote = planChecks(['src/camera.js', 'changes/700.size.md', 'changes/700.md']);
+ assert.equal(checkNamed(withNote, 'change note').failure, null);
+});
+
+test('editing a protected file fails with the alternative', () => {
+ const checks = planChecks(['CHANGELOG.md', 'bench/size/budgets.json']);
+ const failure = checkNamed(checks, 'protected files').failure;
+ assert.match(failure, /CHANGELOG\.md: Add a changes/);
+ assert.match(failure, /budgets\.json: Accept a size increase/);
+});
+
+test('MCP tool code runs the schema and tool cost checks', () => {
+ const checks = planChecks(['src\\agent-scene.js', 'changes/700.md']);
+ assert.equal(checkNamed(checks, 'tool schemas').skipped, null);
+ assert.equal(checkNamed(checks, 'tool cost').skipped, null);
+});
+
+test('--skip-tests skips the build, the tests and the coverage gate', () => {
+ const checks = planChecks(['src/camera.js'], { skipTests: true });
+ for (const name of ['build library', 'unit tests and coverage', 'coverage gate']) {
+ assert.match(checkNamed(checks, name).skipped, /--skip-tests/);
+ }
+});
+
+test('manual GPU checks are pointed out by the files they cover', () => {
+ const commands = manualChecksFor(['src/cascaded-shadows.js', 'src/gltf-loader.js']).map(check => check.command);
+ assert.deepEqual(commands, ['npm run reference', 'npm run smoke:character']);
+ assert.deepEqual(manualChecksFor(['docs/guide.md']), []);
+});