The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.
TypeScript agent-skillsagentic-aiai-agentsai-videobyokclaude-codecodexdeepseek-harnessdsh-plugingenerative-ailocal-firstmcpmotionmotion-graphicsmultimodalopenmotionreverse-engineeringvideo-editingvideo-generationworkbuddy
ci(motion): register manual release controls on the default branch
luogao553be0d80233
diff --git a/.github/gitleaks.toml b/.github/gitleaks.tomlnew file mode 100644index 00000000..12bc986f--- /dev/null+++ b/.github/gitleaks.toml@@ -0,0 +1,8 @@+title = "Motion release credentials policy"+[extend]+useDefault = true++[[allowlists]]+description = "Existing public, write-only OpenMotion analytics identifier; not a management credential"+regexTarget = "secret"+regexes = ['''^phc_u5dHWkwdqN626opkbbjDKk7xNzxR2UsJbdQqx3DncbjU$''']diff --git a/.github/scripts/motion-registry-smoke.mjs b/.github/scripts/motion-registry-smoke.mjsnew file mode 100644index 00000000..679dc28f--- /dev/null+++ b/.github/scripts/motion-registry-smoke.mjs@@ -0,0 +1,107 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { spawn } from 'node:child_process';+import { createInterface } from 'node:readline';+import { access, mkdir, mkdtemp, readFile, readdir, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { runFile, sha256, writeJSON } from '../../scripts/runtime-assets.mjs';++export function consumerEnvironment(work, source = process.env) {+ // Consumer code receives OS basics only, never CI credentials or Agent/browser IPC capabilities.+ const allowed = /^(?:PATH|HOME|USERPROFILE|APPDATA|LOCALAPPDATA|TMPDIR|TMP|TEMP|SystemRoot|windir|ComSpec|PATHEXT|ProgramFiles(?:\(x86\))?|ProgramData|LANG|LC_ALL|TZ)$/i;+ const env = Object.fromEntries(Object.entries(source).filter(([key]) => allowed.test(key)));+ return { ...env, CODEX_HOME: path.join(work, 'codex'), npm_config_cache: path.join(work, 'npm-cache'),+ npm_config_userconfig: path.join(work, 'user.npmrc'), npm_config_globalconfig: path.join(work, 'global.npmrc'),+ npm_config_registry: 'https://registry.npmjs.org/', npm_config_ignore_scripts: 'true',+ OPENMOTION_TELEMETRY: '0', HYPERFRAMES_NO_TELEMETRY: '1' };+}++async function discover(transport, env, version, tools) {+ const child = spawn(transport.command, transport.args, { env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });+ const waiting = new Map(); let sequence = 0;+ const fail = error => { for (const p of waiting.values()) { clearTimeout(p.timer); p.reject(error); } waiting.clear(); };+ child.on('error', fail); child.on('exit', code => fail(new Error('MCP exited: ' + code)));+ child.stderr.resume();+ createInterface({ input: child.stdout }).on('line', line => {+ try { const result = JSON.parse(line), p = waiting.get(result.id); if (p) { waiting.delete(result.id); clearTimeout(p.timer); result.error ? p.reject(new Error('MCP error')) : p.resolve(result.result); } }+ catch { fail(new Error('Invalid MCP JSON')); }+ });+ const rpc = (method, params) => new Promise((resolve, reject) => {+ const id = ++sequence, timer = setTimeout(() => { waiting.delete(id); reject(new Error('MCP timed out: ' + method)); }, 120_000);+ waiting.set(id, { resolve, reject, timer }); child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');+ });+ try {+ const hello = await rpc('initialize', { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'motion-registry-acceptance', version: '1' } });+ assert.equal(hello.serverInfo.version, version);+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');+ assert.deepEqual((await rpc('tools/list', {})).tools.map(t => t.name), tools);+ await rpc('resources/read', { uri: 'motion://workflow/production/start' });+ await rpc('resources/read', { uri: 'motion://engine/SKILL.md' });+ } finally { child.stdin.end(); child.kill(); fail(new Error('MCP session closed')); }+}++export async function registrySmoke(directory) {+ const c = JSON.parse(await readFile(path.join(directory, 'candidate.json')));+ const platform = process.platform + '-' + process.arch;+ assert(['darwin-arm64', 'win32-x64'].includes(platform), 'Use a supported native runner');+ const file = path.join(directory, `registry-${platform}.json`);+ let phase = 'registry-download';+ const checkpoint = async next => { phase = next; await writeJSON(file, { status: 'running', phase, version: c.version, platform, tgzSHA256: c.tgzSHA256 }); };+ await checkpoint(phase);+ try {+ const work = await mkdtemp(path.join(os.tmpdir(), 'om-registry-')), env = consumerEnvironment(work);+ for (const file of ['user.npmrc', 'global.npmrc']) await writeFile(path.join(work, file), '');+ const project = path.join(work, 'project'), host = path.join(work, 'host');+ await mkdir(project); await mkdir(env.CODEX_HOME);+ await writeFile(path.join(env.CODEX_HOME, 'config.toml'), '[mcp_servers.unrelated]\ncommand = "keep-this-server"\n');+ const npm = path.join(path.dirname(process.execPath), process.platform === 'win32' ? 'node_modules/npm/bin/npm-cli.js' : '../lib/node_modules/npm/bin/npm-cli.js');+ const cli = args => runFile(process.execPath, [npm, ...args], { cwd: project, env, timeout: 20 * 60_000 });+ console.log('Fetching the exact version anonymously from the public registry');+ let metadata;+ for (let attempt = 0; attempt < 30; attempt++) {+ const response = await fetch('https://registry.npmjs.org/@openmotion%2fapp/' + c.version, { signal: AbortSignal.timeout(30_000) });+ if (response.ok) { metadata = await response.json(); break; }+ assert.equal(response.status, 404, 'Registry lookup failed');+ await new Promise(resolve => setTimeout(resolve, 10_000));+ }+ assert(metadata, 'Registry version did not become visible'); assert.equal(metadata.dist.integrity, c.integrity);+ const [packed] = JSON.parse(await cli(['pack', `${c.packageName}@${c.version}`, '--ignore-scripts', '--json', '--pack-destination', work]));+ assert.equal(path.basename(packed.filename), packed.filename);+ const tgz = path.join(work, packed.filename), bytes = await readFile(tgz);+ assert.equal(await sha256(tgz), c.tgzSHA256); assert.equal('sha512-' + createHash('sha512').update(bytes).digest('base64'), c.integrity);+ await checkpoint('host-install');+ console.log('Installing the pinned test host in an isolated prefix');+ await cli(['install', '--prefix', host, '--no-save', '--ignore-scripts', '--no-audit', '--no-fund', '@openai/[email protected]']);+ const codex = path.join(host, 'node_modules/@openai/codex/bin/codex.js');+ const home = path.join(work, 'app'), data = path.join(work, 'data'), skills = path.join(project, '.agents/skills');+ const command = ['exec', '--yes', '--package', tgz, '--', 'openmotion'];+ const setup = [...command, 'setup', '--host', 'codex', '--home', home, '--data-dir', data, '--skills-dir', skills, '--codex', codex];+ console.log('Running fresh and repeated setup with isolated data, Skills and host settings');+ await checkpoint('setup');+ const first = JSON.parse(await cli(setup)), second = JSON.parse(await cli(setup));+ assert.equal(first.appRoot, second.appRoot); assert.equal((await readdir(path.join(home, 'apps'))).length, 1);+ assert.match(await readFile(path.join(env.CODEX_HOME, 'config.toml'), 'utf8'), /keep-this-server/);+ const manifest = JSON.parse(await readFile(path.join(directory, 'release-npm.json')));+ for (const skill of manifest.skills) await access(path.join(skills, 'openmotion/skills', skill, 'SKILL.md'));+ console.log('Preparing the checksum-pinned browser, FFmpeg and ffprobe');+ await checkpoint('native-prepare');+ await cli([...command, 'prepare', '--home', home]);+ const installed = JSON.parse(await runFile(process.execPath, [codex, 'mcp', 'get', 'openmotion', '--json'], { cwd: project, env }));+ assert.equal(installed.transport.command, process.execPath); assert.deepEqual(installed.transport.args, [first.launcher]);+ console.log('Checking the actual registered MCP transport and resources');+ await checkpoint('mcp-discovery');+ await discover(installed.transport, env, c.version, manifest.mcp.tools);+ const report = { status: 'passed', platform, version: c.version, sourceCommit: c.sourceCommit, tgzSHA256: c.tgzSHA256,+ node: process.version, codex: '0.166.0', registryColdInstall: 'passed', repeatSetup: 'passed', unrelatedSettings: 'preserved',+ nativePreparation: 'passed', mcpTools: manifest.mcp.tools.length, skills: manifest.skills.length, resources: 'passed',+ realModelTurn: 'not-run', humanPlayback: 'not-run', windowsDesktopAcceptance: 'not-run' };+ await writeJSON(file, report); return report;+ } catch (error) {+ await writeJSON(file, { status: 'failed', phase, platform, version: c.version, tgzSHA256: c.tgzSHA256, error: 'REGISTRY_ACCEPTANCE_FAILED' });+ throw error;+ }+}++if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await registrySmoke(path.resolve(process.argv[2]));diff --git a/.github/scripts/motion-release.mjs b/.github/scripts/motion-release.mjsnew file mode 100644index 00000000..f0749db2--- /dev/null+++ b/.github/scripts/motion-release.mjs@@ -0,0 +1,334 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';+import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { runFile, sha256, writeJSON } from '../../scripts/runtime-assets.mjs';+import { checkReleaseVersion, compareReleaseVersions } from '../../scripts/release-version.mjs';+import { generateInstallGuide } from '../../scripts/install-guide.mjs';+import { publishGuide, storagePlan } from './publish-install-guide.mjs';+import { scanPackage, scanSource } from './motion-scan.mjs';++export const repository = 'nexu-io/html-anything';+export const candidateWorkflow = '.github/workflows/motion-candidate.yml';+export const publicationWorkflow = '.github/workflows/motion-publish-test.yml';+export const recoveryWorkflow = '.github/workflows/motion-publication-recovery.yml';+export const candidateJobName = 'Build immutable candidate';+const exec = promisify(execFile), hashPattern = /^[a-f0-9]{64}$/;+const json = async file => JSON.parse(await readFile(file, 'utf8'));+const integrity = bytes => 'sha512-' + createHash('sha512').update(bytes).digest('base64');++export function releaseInputs(env = process.env) {+ assert.equal(env.GITHUB_REPOSITORY, repository, 'Wrong repository');+ assert.equal(env.GITHUB_EVENT_NAME, 'workflow_dispatch', 'Manual invocation required');+ assert.equal(env.GITHUB_REF, 'refs/heads/main', 'Run the trusted workflow registered on main');+ assert(['publish-test', 'archive-only'].includes(env.MOTION_RELEASE_ACTION), 'Unknown release action');+ const workflow = env.GITHUB_WORKFLOW_REF;+ assert([publicationWorkflow, recoveryWorkflow].some(p => workflow === `${repository}/${p}@refs/heads/main`), 'Require a trusted manual entry');+ if (workflow.includes(recoveryWorkflow)) assert.equal(env.MOTION_RELEASE_ACTION, 'archive-only', 'Recovery never publishes or moves a channel');+ if (env.MOTION_EXPECTED_SHA256) assert.match(env.MOTION_EXPECTED_SHA256, hashPattern);+ assert.equal(env.MOTION_ACCEPTED, 'true', 'Explicit operator acceptance confirmation is required');+ checkReleaseVersion(env.MOTION_VERSION); assert(env.MOTION_VERSION.includes('-test.'), 'Only test versions may use this entry');+ return { action: env.MOTION_RELEASE_ACTION, accepted: true, version: env.MOTION_VERSION, expectedSHA256: env.MOTION_EXPECTED_SHA256 };+}++export async function resolveSource(control, requested, version, run = runFile) {+ const commit = requested || (await run('git', ['rev-parse', 'refs/remotes/origin/feature/motion'], { cwd: control })).trim();+ await validateSource(control, commit, version, run);+ return commit;+}++export async function validateSource(control, commit, version, run = runFile) {+ assert.match(commit || '', /^[a-f0-9]{40}$/, 'Use a full immutable source SHA');+ checkReleaseVersion(version); assert(version.includes('-test.'), 'This workflow builds test versions only');+ await run('git', ['merge-base', '--is-ancestor', commit, 'refs/remotes/origin/feature/motion'], { cwd: control });+}++export async function sealCandidate(build, output, source, env = process.env) {+ const manifest = await json(path.join(build, 'release-npm.json'));+ assert.equal(manifest.commit, (await runFile('git', ['rev-parse', 'HEAD'], { cwd: source })).trim());+ assert.equal(manifest.commit, env.MOTION_SOURCE_SHA); assert.equal(manifest.version, env.MOTION_VERSION);+ assert(manifest.version.includes('-test.') && manifest.templateEnvironment === 'prod');+ assert.match(env.GITHUB_SHA || '', /^[a-f0-9]{40}$/);+ assert.equal(env.GITHUB_WORKFLOW_REF, `${repository}/${candidateWorkflow}@refs/heads/main`);+ assert(/^[1-9]\d*$/.test(env.GITHUB_RUN_ID || '') && /^[1-9]\d*$/.test(env.GITHUB_RUN_ATTEMPT || ''));+ const filename = manifest.installer.url.replace(/^\.\//, '');+ assert.equal(filename, `openmotion-app-${manifest.version}.tgz`);+ await mkdir(output, { recursive: true });+ for (const name of [filename, 'release-npm.json', 'source-scan.json', 'package-scan.json']) await cp(path.join(build, name), path.join(output, name));+ const guide = await generateInstallGuide(path.join(output, filename), output);+ assert.equal(guide.packageName, '@openmotion/app'); assert.equal(guide.commit, env.MOTION_SOURCE_SHA);+ for (const name of ['source-scan.json', 'package-scan.json']) assert.equal((await json(path.join(output, name))).status, 'passed');+ const template = await readFile(new URL('../../docs/templates/release-record.md', import.meta.url), 'utf8');+ assert(template.includes('<!-- CANDIDATE_IDENTITY -->'), 'Acceptance template needs its generated identity marker');+ const identity = { package: `${guide.packageName}@${guide.version}`, sourceCommit: guide.commit,+ workflowCommit: env.GITHUB_SHA, candidateRun: Number(env.GITHUB_RUN_ID), attempt: Number(env.GITHUB_RUN_ATTEMPT),+ tgz: filename, tgzSHA256: await sha256(path.join(output, filename)), applicationSHA256: guide.applicationSHA256, locks: guide.locks,+ templateEnvironment: 'prod' };+ await writeFile(path.join(output, 'acceptance.md'), template.replace('<!-- CANDIDATE_IDENTITY -->', '```json\n' + JSON.stringify(identity, null, 2) + '\n```'));+ const installTemplate = await readFile(new URL('../../docs/templates/candidate-install.md', import.meta.url), 'utf8');+ const values = { VERSION: guide.version, TGZ: filename, SHA256: identity.tgzSHA256, SOURCE_SHA: guide.commit,+ DETAILS_URL: `https://github.com/${repository}/blob/${guide.commit}/docs/npm-installation.md` };+ const instructions = installTemplate.replace(/\{\{([A-Z0-9_]+)\}\}/g, (_, key) => { assert(Object.hasOwn(values, key)); return values[key]; });+ assert(!instructions.includes('{{'), 'Unresolved candidate instructions');+ await writeFile(path.join(output, 'candidate-install.md'), instructions);+ const names = [filename, 'release-npm.json', 'source-scan.json', 'package-scan.json', 'install.md', 'install-record.json', 'acceptance.md', 'candidate-install.md'];+ const files = Object.fromEntries(await Promise.all(names.map(async name => [name, await sha256(path.join(output, name))])));+ const candidate = { schemaVersion: 2, kind: 'motion-candidate', packageName: guide.packageName, version: guide.version,+ sourceCommit: guide.commit, tgz: filename, tgzSHA256: files[filename], integrity: integrity(await readFile(path.join(output, filename))), files,+ workflow: { repository, path: candidateWorkflow, ref: 'refs/heads/main', sha: env.GITHUB_SHA,+ runId: Number(env.GITHUB_RUN_ID), attempt: Number(env.GITHUB_RUN_ATTEMPT) },+ createdAt: new Date().toISOString(), acceptance: 'not-performed' };+ await writeJSON(path.join(output, 'candidate.json'), candidate);+ return candidate;+}++export function validateRun(run, artifact, version) {+ assert.equal(run.event, 'workflow_dispatch'); assert.equal(run.head_branch, 'main');+ assert.equal(run.head_repository?.full_name, repository);+ assert.equal(run.status, 'completed'); assert.equal(run.conclusion, 'success', 'Candidate build must finish successfully');+ assert.equal(run.path.split('@')[0], candidateWorkflow, 'Candidate must come from the registered build workflow');+ assert.equal(artifact.name, `motion-candidate-${version}`);+ assert.equal(artifact.workflow_run?.id, run.id); assert.equal(artifact.expired, false);+ assert.match(artifact.digest || '', /^sha256:[a-f0-9]{64}$/, 'Require the GitHub artifact digest');+ assert(artifact.size_in_bytes > 0 && artifact.size_in_bytes < 150 * 1024 * 1024, 'Unexpected artifact size');+}++async function github(route, fetcher = fetch) {+ const response = await fetcher(`https://api.github.com/repos/${repository}${route}`, { redirect: 'error', signal: AbortSignal.timeout(30_000),+ headers: { Accept: 'application/vnd.github+json', Authorization: `Bearer ${process.env.GH_TOKEN || process.env.GITHUB_TOKEN}`, 'X-GitHub-Api-Version': '2022-11-28' } });+ assert(response.ok, 'GitHub metadata request failed: HTTP ' + response.status);+ return response.json();+}++export function authorizationReceipt(candidate, run, action, observedAt = new Date().toISOString()) {+ const actor = run.triggering_actor?.login || run.actor?.login;+ assert(typeof actor === 'string' && actor.length > 0, 'Require the actual publication operator');+ return { schemaVersion: 1, type: 'manual-workflow-dispatch', publicationRun: run.id, runAttempt: run.run_attempt,+ action, version: candidate.version, tgzSHA256: candidate.tgzSHA256, candidateRun: candidate.workflow,+ actor, acceptanceConfirmed: true, observedAt };+}++export async function recordAuthorization(directory, inputs, fetcher = fetch, env = process.env) {+ const authorized = releaseInputs(env);+ assert.equal(authorized.action, inputs.action); assert.equal(authorized.version, inputs.version);+ const candidate = await verifyDownloaded(directory, inputs.expectedSHA256, inputs.version);+ const run = await github(`/actions/runs/${env.GITHUB_RUN_ID}`, fetcher);+ assert.equal(String(run.id), env.GITHUB_RUN_ID); assert.equal(run.head_branch, 'main'); assert.equal(run.event, 'workflow_dispatch');+ assert.equal(run.head_repository?.full_name, repository); assert.equal(run.head_sha, env.GITHUB_SHA);+ assert.equal(run.path.split('@')[0], env.GITHUB_WORKFLOW_REF.slice(repository.length + 1).split('@')[0]);+ await writeJSON(path.join(directory, 'authorization.json'), authorizationReceipt(candidate, run, inputs.action));+}++async function verifyAuthorization(directory, inputs, env = process.env) {+ const candidate = await verifyDownloaded(directory, inputs.expectedSHA256, inputs.version), authorization = await json(path.join(directory, 'authorization.json'));+ assert.equal(inputs.accepted, true); assert.equal(authorization.schemaVersion, 1);+ assert.equal(authorization.type, 'manual-workflow-dispatch'); assert.equal(authorization.acceptanceConfirmed, true);+ assert.equal(authorization.version, candidate.version); assert.equal(authorization.tgzSHA256, candidate.tgzSHA256);+ assert.equal(authorization.action, inputs.action); assert.deepEqual(authorization.candidateRun, candidate.workflow);+ assert.equal(String(authorization.publicationRun), env.GITHUB_RUN_ID, 'Authorization belongs to another publication run');+ assert(typeof authorization.actor === 'string' && authorization.actor.length > 0);+ return authorization;+}++export async function verifyCandidate(directory, expectedSHA256, run) {+ const candidate = await json(path.join(directory, 'candidate.json'));+ assert.equal(candidate.schemaVersion, 2); assert.equal(candidate.kind, 'motion-candidate'); assert.equal(candidate.packageName, '@openmotion/app');+ checkReleaseVersion(candidate.version); assert(candidate.version.includes('-test.'));+ assert.equal(candidate.tgz, `openmotion-app-${candidate.version}.tgz`); assert.equal(candidate.tgzSHA256, expectedSHA256);+ assert.match(expectedSHA256, hashPattern); assert.match(candidate.sourceCommit, /^[a-f0-9]{40}$/);+ assert.deepEqual(candidate.workflow, { repository, path: candidateWorkflow, ref: 'refs/heads/main', sha: run.head_sha, runId: run.id, attempt: run.run_attempt });+ const names = [candidate.tgz, 'release-npm.json', 'source-scan.json', 'package-scan.json', 'install.md', 'install-record.json', 'acceptance.md', 'candidate-install.md'];+ assert.deepEqual(Object.keys(candidate.files).sort(), names.sort());+ for (const name of names) assert.equal(await sha256(path.join(directory, name)), candidate.files[name], 'Candidate file changed: ' + name);+ assert.equal(await sha256(path.join(directory, candidate.tgz)), expectedSHA256);+ assert.equal(integrity(await readFile(path.join(directory, candidate.tgz))), candidate.integrity);+ const guide = await json(path.join(directory, 'install-record.json'));+ assert.equal(guide.commit, candidate.sourceCommit); assert.equal(guide.version, candidate.version); assert.equal(guide.packageName, candidate.packageName);+ assert.equal(guide.tgzSHA256, expectedSHA256); assert.equal(guide.channel, 'test'); assert.equal(guide.templateEnvironment, 'prod');+ assert.equal(guide.guideSHA256, candidate.files['install.md']); assert.equal(guide.candidate, false);+ const manifest = await json(path.join(directory, 'release-npm.json'));+ assert.equal(manifest.commit, candidate.sourceCommit); assert.equal(manifest.version, candidate.version);+ assert.equal(manifest.installer.sha256, expectedSHA256);+ for (const name of ['source-scan.json', 'package-scan.json']) assert.equal((await json(path.join(directory, name))).status, 'passed');+ return candidate;+}++export async function verifyDownloaded(directory, expectedSHA256, version) {+ const provenance = await json(path.join(directory, 'provenance.json'));+ const candidate = await verifyCandidate(directory, expectedSHA256, { head_sha: provenance.head_sha, id: provenance.runId, run_attempt: provenance.attempt });+ if (version) assert.equal(candidate.version, version, 'Candidate version differs from the accepted version');+ return candidate;+}++export async function platformReports(directory, candidate) {+ const reports = [];+ for (const platform of ['darwin-arm64', 'win32-x64']) {+ const name = `registry-${platform}.json`, report = await json(path.join(directory, name));+ assert.equal(report.status, 'passed'); assert.equal(report.platform, platform);+ assert.equal(report.version, candidate.version); assert.equal(report.tgzSHA256, candidate.tgzSHA256);+ assert.equal(report.sourceCommit, candidate.sourceCommit);+ assert.equal(report.registryColdInstall, 'passed'); assert.equal(report.nativePreparation, 'passed');+ assert.equal(report.repeatSetup, 'passed'); assert.equal(report.resources, 'passed');+ assert.equal(report.mcpTools, 11); assert.equal(report.skills, 5);+ reports.push({ platform, reportSHA256: await sha256(path.join(directory, name)) });+ }+ return reports;+}++export async function findCandidate(version, fetcher = fetch) {+ checkReleaseVersion(version); assert(version.includes('-test.'));+ const name = `motion-candidate-${version}`;+ const result = await github(`/actions/artifacts?name=${encodeURIComponent(name)}&per_page=100`, fetcher);+ assert(result.total_count <= 100, 'Too many matching artifacts; refusing an incomplete lookup');+ const matches = result.artifacts.filter(a => a.name === name && !a.expired);+ assert.equal(matches.length, 1, 'Candidate missing, expired or ambiguous; build a new unique version');+ assert(Number.isSafeInteger(matches[0].workflow_run?.id) && matches[0].workflow_run.id > 0);+ return matches[0];+}++export async function downloadCandidate(version, directory, expectedSHA256, fetcher = fetch) {+ const artifact = await findCandidate(version, fetcher), run = await github(`/actions/runs/${artifact.workflow_run.id}`, fetcher);+ validateRun(run, artifact, version);+ const redirect = await fetcher(`https://api.github.com/repos/${repository}/actions/artifacts/${artifact.id}/zip`, {+ redirect: 'manual', signal: AbortSignal.timeout(30_000), headers: { Authorization: `Bearer ${process.env.GH_TOKEN || process.env.GITHUB_TOKEN}` } });+ assert.equal(redirect.status, 302); const url = new URL(redirect.headers.get('location')); assert.equal(url.protocol, 'https:'); assert(!url.username && !url.password);+ // Signed artifact URLs are fetched without forwarding the GitHub credential.+ const response = await fetcher(url, { redirect: 'error', signal: AbortSignal.timeout(60_000) }); assert(response.ok);+ const bytes = Buffer.from(await response.arrayBuffer()); assert(bytes.length < 150 * 1024 * 1024);+ assert.equal('sha256-' + createHash('sha256').update(bytes).digest('hex'), artifact.digest.replace(':', '-'));+ const work = await mkdtemp(path.join(os.tmpdir(), 'motion-artifact-'));+ try {+ const archive = path.join(work, 'candidate.zip'); await writeFile(archive, bytes);+ const entries = (await runFile('unzip', ['-Z1', archive])).trim().split('\n');+ assert(entries.length === 9 && new Set(entries).size === 9, 'Unexpected candidate artifact files');+ assert(entries.every(name => /^[a-zA-Z0-9._-]+$/.test(name) && name.length < 160), 'Unsafe candidate artifact entry');+ await mkdir(directory, { recursive: true });+ for (const name of entries) {+ const { stdout } = await exec('unzip', ['-p', archive, name], { encoding: 'buffer', maxBuffer: 150 * 1024 * 1024 });+ await writeFile(path.join(directory, name), stdout);+ }+ const candidate = await verifyCandidate(directory, expectedSHA256 || (await json(path.join(directory, 'candidate.json'))).tgzSHA256, run);+ assert.equal(candidate.version, version, 'Artifact version differs from the accepted version');+ await writeJSON(path.join(directory, 'provenance.json'), { runId: run.id, attempt: run.run_attempt, head_sha: run.head_sha, artifactId: artifact.id, digest: artifact.digest });+ return candidate;+ } finally { await rm(work, { recursive: true, force: true }); }+}++export async function registryPackage(candidate, fetcher = fetch) {+ const response = await fetcher('https://registry.npmjs.org/@openmotion%2fapp', { signal: AbortSignal.timeout(30_000) });+ if (response.status === 404) return { version: null, tags: {} };+ assert(response.ok, 'Registry metadata request failed'); const data = await response.json();+ const version = data.versions?.[candidate.version];+ if (version) assert.equal(version.dist.integrity, candidate.integrity, 'Published npm version has different bytes; never overwrite it');+ return { version: version || null, tags: data['dist-tags'] || {} };+}++export async function publishNpm(directory, inputs, { fetcher = fetch, run = runFile, env = process.env } = {}) {+ const candidate = await verifyDownloaded(directory, inputs.expectedSHA256);+ await verifyAuthorization(directory, inputs, env);+ const before = await registryPackage(candidate, fetcher);+ if (inputs.action === 'archive-only') assert(before.version, 'Archive-only requires an existing identical npm version');+ if (inputs.action === 'publish-test' && before.tags.test) assert(compareReleaseVersions(candidate.version, before.tags.test) >= 0, 'A newer npm test version already exists; use snapshot recovery for an identical published version');+ const record = { schemaVersion: 1, version: candidate.version, tgzSHA256: candidate.tgzSHA256, action: inputs.action,+ previousLatest: before.tags.latest ?? null, status: before.version ? 'already-published-identical' : 'publish-started' };+ await writeJSON(path.join(directory, 'npm-publication.json'), record);+ if (!before.version) {+ // OIDC authenticates this publisher; its main SHA is not the prebuilt application's source.+ await run('npm', ['publish', path.join(directory, candidate.tgz), '--access', 'public', '--tag', 'test', '--ignore-scripts', '--provenance=false', '--registry=https://registry.npmjs.org/']);+ record.status = 'published-awaiting-registry'; await writeJSON(path.join(directory, 'npm-publication.json'), record);+ }+ return record;+}++export async function archiveRelease(directory, inputs, config, { run = runFile, fetcher = fetch, env = process.env } = {}) {+ await writeJSON(path.join(directory, 'release-attempt.json'), { action: inputs.action, tgzSHA256: inputs.expectedSHA256, stage: 'verifying-release', runId: env.GITHUB_RUN_ID });+ const candidate = await verifyDownloaded(directory, inputs.expectedSHA256);+ const authorization = await verifyAuthorization(directory, inputs, env);+ const platforms = await platformReports(directory, candidate);+ const record = await json(path.join(directory, 'install-record.json')), plan = storagePlan(record, config);+ assert.equal(candidate.tgzSHA256, inputs.expectedSHA256);+ const registry = await registryPackage(candidate, fetcher); assert(registry.version, 'Exact npm version is not public');+ const npm = await json(path.join(directory, 'npm-publication.json'));+ assert.equal(npm.tgzSHA256, candidate.tgzSHA256);+ assert.equal(registry.tags.latest ?? null, npm.previousLatest, 'npm latest changed unexpectedly; stop and investigate before promoting a guide');+ if (inputs.action === 'publish-test' && registry.tags.test !== candidate.version) {+ assert(registry.tags.test && compareReleaseVersions(registry.tags.test, candidate.version) > 0, 'npm test tag is missing or unexpectedly older; explicit channel recovery is required');+ }+ const prefix = path.posix.dirname(plan.versionKey), work = await mkdtemp(path.join(os.tmpdir(), 'motion-snapshot-'));+ const aws = async (operation, rest) => JSON.parse(await run('aws', ['--endpoint-url', plan.endpoint, '--region', 'auto', 's3api', operation, '--bucket', plan.bucket, ...rest]) || '{}');+ try {+ const get = async key => {+ const file = path.join(work, 'object');+ try { await aws('get-object', ['--key', key, file]); return await readFile(file); }+ catch (error) { if (/NoSuchKey|\(404\)|Not Found/.test(error.message)) return null; throw error; }+ };+ const prior = await get(`${prefix}/release-record.json`);+ let release = { schemaVersion: 2, packageName: candidate.packageName, version: candidate.version, sourceCommit: candidate.sourceCommit,+ tgzSHA256: candidate.tgzSHA256, integrity: candidate.integrity, candidateRun: candidate.workflow,+ authorization, publicationRun: env.GITHUB_RUN_ID,+ platformVerification: platforms, status: 'registry-verified', publishedAt: new Date().toISOString() };+ if (prior) {+ const existing = JSON.parse(prior);+ for (const key of ['packageName', 'version', 'sourceCommit', 'tgzSHA256', 'integrity']) assert.equal(existing[key], release[key], 'Existing release record differs: ' + key);+ release = existing;+ }+ await writeJSON(path.join(directory, 'release-record.json'), release);+ const names = [...Object.keys(candidate.files), 'candidate.json', 'registry-darwin-arm64.json', 'registry-win32-x64.json', 'release-record.json'];+ const objects = [];+ for (const name of names) {+ const file = path.join(directory, name), bytes = await readFile(file), key = `${prefix}/${name}`, existing = await get(key);+ if (existing) assert(existing.equals(bytes), 'Immutable snapshot already has different bytes: ' + name);+ objects.push({ file, bytes, key, existing });+ }+ await writeJSON(path.join(directory, 'release-attempt.json'), { action: inputs.action, version: candidate.version, stage: 'archive-started', runId: env.GITHUB_RUN_ID });+ for (const object of objects) {+ if (!object.existing) await aws('put-object', ['--key', object.key, '--body', object.file, '--if-none-match', '*', '--content-type', object.key.endsWith('.md') ? 'text/markdown; charset=utf-8' : object.key.endsWith('.json') ? 'application/json' : 'application/octet-stream', '--cache-control', 'public, max-age=31536000, immutable']);+ const response = await fetcher(new URL('/' + object.key, plan.publicOrigin), { redirect: 'error', signal: AbortSignal.timeout(30_000), headers: { 'cache-control': 'no-cache' } });+ assert(response.ok, 'Snapshot public readback failed'); assert(Buffer.from(await response.arrayBuffer()).equals(object.bytes), 'Snapshot public bytes differ');+ }+ const promote = inputs.action === 'publish-test' && registry.tags.test === candidate.version;+ const publication = await publishGuide(directory, config, { run, fetcher, promote });+ await writeJSON(path.join(directory, 'release-attempt.json'), { action: inputs.action, version: candidate.version,+ stage: inputs.action === 'archive-only' ? 'archive-only-verified' : !promote || publication.phase === 'superseded' ? 'archived-superseded' : 'test-entry-verified', runId: env.GITHUB_RUN_ID });+ return release;+ } finally { await rm(work, { recursive: true, force: true }); }+}++if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ const [command, directory, extra, final] = process.argv.slice(2);+ if (command === 'source') {+ const commit = await resolveSource(directory, process.env.MOTION_SOURCE_SHA, process.env.MOTION_VERSION);+ const { appendFile } = await import('node:fs/promises');+ await appendFile(process.env.GITHUB_OUTPUT, `source_sha=${commit}\n`);+ }+ else if (command === 'seal') await sealCandidate(directory, extra, final);+ else {+ const inputs = releaseInputs();+ if (command === 'download') {+ const candidate = await downloadCandidate(inputs.version, directory, inputs.expectedSHA256);+ const { appendFile } = await import('node:fs/promises');+ await appendFile(process.env.GITHUB_OUTPUT, `tgz_sha256=${candidate.tgzSHA256}\n`);+ }+ else if (command === 'authorize') await recordAuthorization(directory, inputs);+ else if (command === 'rescan') {+ const c = await verifyDownloaded(directory, inputs.expectedSHA256);+ await validateSource(extra, c.sourceCommit, c.version);+ const work = await mkdtemp(path.join(os.tmpdir(), 'motion-source-verify-'));+ try {+ await runFile('git', ['worktree', 'add', '--detach', work, c.sourceCommit], { cwd: extra });+ await writeJSON(path.join(directory, 'publication-source-scan.json'), await scanSource(work, final));+ await writeJSON(path.join(directory, 'publication-package-scan.json'), await scanPackage(path.join(directory, c.tgz), final));+ } finally { await runFile('git', ['worktree', 'remove', '--force', work], { cwd: extra }).catch(() => {}); }+ } else if (command === 'verify') await verifyDownloaded(directory, inputs.expectedSHA256, inputs.version);+ else if (command === 'npm') await publishNpm(directory, inputs);+ else if (command === 'archive') {+ for (const name of ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY']) assert(process.env[name], 'Missing R2 credential: ' + name);+ await archiveRelease(directory, inputs, { endpoint: process.env.MOTION_R2_ENDPOINT, bucket: process.env.MOTION_R2_BUCKET, publicOrigin: process.env.MOTION_INSTALL_PUBLIC_ORIGIN });+ }+ else throw new Error('Unknown release command');+ }+}diff --git a/.github/scripts/motion-scan.mjs b/.github/scripts/motion-scan.mjsnew file mode 100644index 00000000..53103b0f--- /dev/null+++ b/.github/scripts/motion-scan.mjs@@ -0,0 +1,150 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { createReadStream } from 'node:fs';+import { createGunzip } from 'node:zlib';+import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rm, writeFile, chmod } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { download, runFile, sha256, writeJSON } from '../../scripts/runtime-assets.mjs';++const root = fileURLToPath(new URL('../../', import.meta.url));+export const scannerVersion = '8.30.1';+const scannerHashes = {+ 'linux_x64': '551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb',+ 'darwin_arm64': 'b40ab0ae55c505963e365f271a8d3846efbc170aa17f2607f13df610a9aeb6a5',+};++export async function installScanner(directory) {+ const target = `${process.platform}_${process.arch}`;+ assert(scannerHashes[target], 'Use the supported Linux x64 or Mac arm64 scanner runner');+ await mkdir(directory, { recursive: true });+ const archive = path.join(directory, 'gitleaks.tar.gz');+ await download({ url: `https://github.com/gitleaks/gitleaks/releases/download/v${scannerVersion}/gitleaks_${scannerVersion}_${target}.tar.gz`, sha256: scannerHashes[target] }, archive);+ await runFile('tar', ['-xzf', archive, '-C', directory, 'gitleaks']);+ const binary = path.join(directory, 'gitleaks'); await chmod(binary, 0o755);+ return binary;+}++export function archivePaths(listing) {+ const names = listing.trim().split('\n');+ assert(names.length && names.length < 20_000, 'Archive has too many entries');+ for (const name of names) {+ assert(name && !/[\\\x00-\x1f]/.test(name) && !path.posix.isAbsolute(name) && !/^[a-z]:/i.test(name)+ && !name.split('/').includes('..'), 'Unsafe archive entry');+ }+ return names;+}++export async function unpackChecked(archive, directory, run = runFile) {+ assert((await lstat(archive)).size < 150 * 1024 * 1024, 'Archive exceeds release size limit');+ let expanded = 0;+ for await (const chunk of createReadStream(archive).pipe(createGunzip())) {+ expanded += chunk.length; assert(expanded < 350 * 1024 * 1024, 'Expanded archive exceeds release size limit');+ }+ archivePaths(await run('tar', ['-tzf', archive]));+ const details = (await run('tar', ['-tvzf', archive])).trim().split('\n');+ assert(details.every(line => /^[-d]/.test(line)), 'Archive links and special files are forbidden');+ await mkdir(directory, { recursive: true });+ await run('tar', ['-xzf', archive, '-C', directory]);+}++export function privacyFindings(name, text, kind = 'source') {+ const findings = [], add = rule => findings.push({ path: name, rule });+ // Public DEV routing and synthetic redaction fixtures are intentional, not credentials or employee paths.+ if (name === 'prism-templates.ts' || name === './prism-templates.ts') text = text.replace(/https:\/\/r\.powerformer\.net/g, 'https://dev.example.invalid');+ if (kind === 'source') {+ const fixtures = {+ 'studio/src/components/feedback/projectProvenance.test.ts': /\/Users\/me\/x/g,+ 'studio/src/player/store/previewQualitySlice.test.ts': /\/Users\/a\/film\.mp3/g,+ 'studio/src/telemetry/breadcrumbs.test.ts': /\/Users\/someone\/(?:private\/path\.html|project\.ts)/g,+ };+ if (fixtures[name]) text = text.replace(fixtures[name], '/synthetic/redaction-fixture');+ }+ if (/(?:^|\/)(?:outputs|research|node_modules|\.artifacts|\.motion-data(?:-dev)?)(?:\/|$)/.test(name)+ || /(?:^|\/)(?:\.npmrc|\.DS_Store|id_rsa|id_ed25519)$/.test(name)+ || /\.(?:log|pem|key|p12|pfx)$/.test(name)) add('private-file');+ if (/(?:^|\/)\.env(?:\.|$)/.test(name) && !(kind === 'source' && /(?:^|\/)\.env\.(?:example|development)$/.test(name))) add('environment-file');+ if (/https?:\/\/[^\s"'<>)]*(?:powerformer\.(?:net|com)|feishu\.(?:cn|com)|larksuite\.com)/i.test(text)) add('internal-link');+ if (/\/(?:Users|home)\/[a-zA-Z0-9_.-]+\/|[a-z]:\\Users\\[^\\\s]+\\|\/var\/folders\//i.test(text)) add('personal-path');+ return findings;+}++async function scanTree(directory, kind, binary) {+ const findings = []; let files = 0, bytes = 0;+ const visit = async (dir, prefix = '') => {+ for (const entry of await readdir(dir, { withFileTypes: true })) {+ const name = prefix + entry.name, filename = path.join(dir, entry.name);+ assert(!entry.isSymbolicLink(), 'Release scan does not follow links');+ if (entry.isDirectory()) await visit(filename, name + '/');+ else {+ assert(entry.isFile(), 'Special file in release');+ const data = await readFile(filename); files++; bytes += data.length;+ assert(bytes < 350 * 1024 * 1024 && files < 20_000, 'Expanded release exceeds scan limit');+ findings.push(...privacyFindings(name, data.includes(0) ? '' : data.toString('utf8'), kind));+ }+ }+ };+ await visit(directory);+ const work = await mkdtemp(path.join(os.tmpdir(), 'motion-secrets-'));+ try {+ const report = path.join(work, 'secrets.json'), ignore = path.join(work, 'empty.ignore'); await writeFile(ignore, '');+ const env = { ...process.env }; delete env.GITLEAKS_CONFIG; delete env.GITLEAKS_CONFIG_TOML;+ let failure;+ try { await runFile(binary, ['dir', directory, '--no-banner', '--redact', '--ignore-gitleaks-allow', '--gitleaks-ignore-path', ignore,+ '--config', path.join(root, '.github/gitleaks.toml'), '--report-format', 'json', '--report-path', report], { cwd: work, env }); }+ catch (error) { failure = error; }+ let secrets;+ try { secrets = JSON.parse(await readFile(report, 'utf8')); }+ catch { throw new Error('Credential scanner did not produce a valid report'); }+ for (const hit of secrets) findings.push({ path: path.relative(directory, hit.File), rule: hit.RuleID, line: hit.StartLine });+ assert(!failure || secrets.length, 'Credential scanner failed before completing');+ // Never expose matched values or the scanner's raw stdout/report.+ if (findings.length) throw new Error('Release content rejected: ' + JSON.stringify(findings));+ return { status: 'passed', kind, files, bytes, scanner: `gitleaks-${scannerVersion}`,+ policySHA256: createHash('sha256').update(await readFile(path.join(root, '.github/gitleaks.toml'))).update(await readFile(fileURLToPath(import.meta.url))).digest('hex') };+ } finally { await rm(work, { recursive: true, force: true }); }+}++export async function scanSource(source, binary) {+ const names = (await runFile('git', ['ls-files', '-z'], { cwd: source })).split('\0').filter(Boolean);+ const work = await mkdtemp(path.join(os.tmpdir(), 'motion-source-scan-'));+ try {+ for (const name of names) {+ assert(!name.split('/').includes('..') && !path.isAbsolute(name), 'Unsafe tracked path');+ const file = path.join(source, name); assert((await lstat(file)).isFile(), 'Tracked links are forbidden');+ await mkdir(path.dirname(path.join(work, name)), { recursive: true }); await cp(file, path.join(work, name));+ }+ return await scanTree(work, 'source', binary);+ } finally { await rm(work, { recursive: true, force: true }); }+}++export async function scanPackage(tgz, binary) {+ const work = await mkdtemp(path.join(os.tmpdir(), 'motion-package-scan-'));+ try {+ await unpackChecked(tgz, path.join(work, 'outer'));+ const outer = path.join(work, 'outer/package');+ const pkg = JSON.parse(await readFile(path.join(outer, 'package.json')));+ assert.equal(pkg.name, '@openmotion/app'); assert.equal(pkg.private, false);+ const manifest = JSON.parse(await readFile(path.join(outer, 'payload/release-npm.json')));+ assert.equal(manifest.format, 'npm'); assert.equal(manifest.templateEnvironment, 'prod'); assert.equal(manifest.version, pkg.version);+ const appName = manifest.application.url.replace(/^\.\//, ''); assert.equal(path.basename(appName), appName);+ const appArchive = path.join(outer, 'payload', appName); assert.equal(await sha256(appArchive), manifest.application.sha256);+ await unpackChecked(appArchive, path.join(work, 'application'));+ assert.equal(await sha256(path.join(work, 'application/package-lock.json')), manifest.locks.npm);+ assert.equal(await sha256(path.join(work, 'application/scripts/runtime-lock.json')), manifest.locks.native);+ const applicationPkg = JSON.parse(await readFile(path.join(work, 'application/package.json'))); assert.equal(applicationPkg.version, pkg.version);+ const reports = await Promise.all([scanTree(path.join(work, 'outer'), 'package', binary), scanTree(path.join(work, 'application'), 'package', binary)]);+ return { status: 'passed', version: pkg.version, tgzSHA256: await sha256(tgz), applicationSHA256: manifest.application.sha256, reports };+ } finally { await rm(work, { recursive: true, force: true }); }+}++if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ const [command, input, output, binary] = process.argv.slice(2);+ if (command === 'install') console.log(await installScanner(path.resolve(input)));+ else {+ assert(['source', 'package'].includes(command) && input && output && binary, 'Usage: motion-scan.mjs source|package <input> <report> <gitleaks>');+ await writeJSON(output, await (command === 'source' ? scanSource(path.resolve(input), binary) : scanPackage(path.resolve(input), binary)));+ console.log('Release content scan passed');+ }+}diff --git a/.github/scripts/publish-install-guide.mjs b/.github/scripts/publish-install-guide.mjsnew file mode 100644index 00000000..266b26f2--- /dev/null+++ b/.github/scripts/publish-install-guide.mjs@@ -0,0 +1,83 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { runFile, sha256, writeJSON } from '../../scripts/runtime-assets.mjs';+import { compareReleaseVersions } from '../../scripts/release-version.mjs';++export function storagePlan(record, { endpoint, bucket, publicOrigin }) {+ const api = new URL(endpoint), origin = new URL(publicOrigin);+ assert(api.protocol === 'https:' && api.hostname.endsWith('.r2.cloudflarestorage.com') && api.pathname === '/' && !api.port, 'Require an R2 S3 HTTPS origin');+ for (const url of [api, origin]) assert(url.protocol === 'https:' && !url.username && !url.password && !url.search && !url.hash && url.pathname === '/', 'Require plain HTTPS origins');+ assert(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(bucket || ''), 'Require the configured R2 bucket');+ assert(['test', 'stable'].includes(record.channel), 'Unknown publication channel');+ assert(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-test\.[1-9]\d*(?:\.[1-9]\d*)*)?$/.test(record.version), 'Invalid guide version');+ assert.equal(record.version.includes('-test.'), record.channel === 'test', 'Channel and version differ');+ const prefix = record.channel === 'test' ? 'open-motion/dev' : 'open-motion';+ return { endpoint: api.origin, bucket, publicOrigin: origin.origin, versionKey: `${prefix}/${record.version}/install.md`, legacyVersionKey: `${prefix}/versions/${record.version}/install.md`, fixedKey: `${prefix}/install.md` };+}++export async function publishGuide(directory, config, { run = runFile, fetcher = fetch, promote = true } = {}) {+ const file = path.join(directory, 'install.md'), record = JSON.parse(await readFile(path.join(directory, 'install-record.json'), 'utf8'));+ assert.equal(record.candidate, false, 'Build previews cannot be published');+ assert.equal(await sha256(file), record.guideSHA256, 'Generated guide changed after validation');+ const plan = storagePlan(record, config), expected = await readFile(file);+ const args = ['--endpoint-url', plan.endpoint, '--region', 'auto', 's3api'];+ const aws = async (operation, rest) => JSON.parse(await run('aws', [...args, operation, '--bucket', plan.bucket, ...rest]) || '{}');+ const work = await mkdtemp(path.join(os.tmpdir(), 'motion-install-publish-'));+ try {+ const get = async (key, destination) => {+ try { const response = await aws('get-object', ['--key', key, destination]); return { etag: response.ETag, bytes: await readFile(destination) }; }+ catch (error) { if (/NoSuchKey|\(404\)|Not Found/.test(error.message)) return null; throw error; }+ };+ const verifyPublic = async key => {+ const url = new URL('/' + key, plan.publicOrigin);+ const response = await fetcher(url, { redirect: 'error', signal: AbortSignal.timeout(20_000), headers: { 'cache-control': 'no-cache', 'user-agent': 'OpenMotion-install-publisher' } });+ assert(response.ok, `Public installation guide returned HTTP ${response.status}`);+ assert(Buffer.from(await response.arrayBuffer()).equals(expected), 'Public installation guide bytes differ');+ };+ const put = (key, condition, cache) => aws('put-object', ['--key', key, '--body', file, '--content-type', 'text/markdown; charset=utf-8', '--cache-control', cache, ...condition]);+ const existing = await get(plan.versionKey, path.join(work, 'version.md'));+ const legacy = await get(plan.legacyVersionKey, path.join(work, 'legacy-version.md'));+ if (legacy) assert(legacy.bytes.equals(expected), 'An immutable legacy version already has different installation instructions');+ if (existing) assert(existing.bytes.equals(expected), 'An immutable version already has different installation instructions');+ else await put(plan.versionKey, ['--if-none-match', '*'], 'public, max-age=31536000, immutable');+ await verifyPublic(plan.versionKey);+ if (!promote) {+ const publication = { ...record, ...plan, phase: 'version-verified', promoted: false };+ await writeJSON(path.join(directory, 'publication.json'), publication);+ return publication;+ }+ const previous = await get(plan.fixedKey, path.join(work, 'previous.md'));+ if (previous) {+ assert(previous.etag, 'Existing guide requires an ETag for conditional promotion');+ await writeFile(path.join(directory, 'previous-install.md'), previous.bytes);+ const version = previous.bytes.toString('utf8').match(/^# Install OpenMotion (\S+)\s*$/m)?.[1];+ assert(version, 'Existing default guide has no recognizable version; inspect it before promotion');+ if (compareReleaseVersions(version, record.version) > 0) {+ const publication = { ...record, ...plan, phase: 'superseded', promoted: false, currentVersion: version };+ await writeJSON(path.join(directory, 'publication.json'), publication);+ return publication;+ }+ if (version === record.version) assert(previous.bytes.equals(expected), 'Same-version default guide has different bytes');+ }+ const publication = { ...record, ...plan, previousSHA256: previous ? createHash('sha256').update(previous.bytes).digest('hex') : null,+ previousETag: previous?.etag ?? null, phase: 'before-fixed-promotion' };+ await writeJSON(path.join(directory, 'publication.json'), publication);+ if (!previous?.bytes.equals(expected)) {+ publication.phase = 'fixed-write-attempted'; await writeJSON(path.join(directory, 'publication.json'), publication);+ await put(plan.fixedKey, previous ? ['--if-match', previous.etag] : ['--if-none-match', '*'], 'public, max-age=60, must-revalidate');+ }+ publication.phase = 'fixed-written-public-unverified'; await writeJSON(path.join(directory, 'publication.json'), publication);+ await verifyPublic(plan.fixedKey);+ publication.phase = 'verified'; await writeJSON(path.join(directory, 'publication.json'), publication);+ return publication;+ } finally { await rm(work, { recursive: true, force: true }); }+}+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ assert.equal(process.argv.length, 3, 'Usage: publish-install-guide.mjs <generated-guide-directory>');+ for (const name of ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY']) assert(process.env[name], `Missing publication credential: ${name}`);+ await publishGuide(path.resolve(process.argv[2]), { endpoint: process.env.MOTION_R2_ENDPOINT, bucket: process.env.MOTION_R2_BUCKET, publicOrigin: process.env.MOTION_INSTALL_PUBLIC_ORIGIN });+}diff --git a/.github/workflows/motion-candidate.yml b/.github/workflows/motion-candidate.ymlnew file mode 100644index 00000000..b3e995ce--- /dev/null+++ b/.github/workflows/motion-candidate.yml@@ -0,0 +1,95 @@+name: Motion candidate build+run-name: Motion candidate · ${{ inputs.version }}++on:+ workflow_dispatch:+ inputs:+ version:+ description: 'New test version, e.g. 0.6.4-test.7; build and retain only, never publish'+ type: string+ required: true+ source_sha:+ description: 'Optional reviewed full SHA integrated into feature/motion; empty freezes its current head'+ type: string+ required: false+ default: ''++permissions:+ contents: read++jobs:+ candidate:+ name: Build immutable candidate+ if: github.repository == 'nexu-io/html-anything' && github.ref == 'refs/heads/main'+ runs-on: ubuntu-24.04+ timeout-minutes: 45+ env:+ MOTION_SOURCE_SHA: ${{ inputs.source_sha }}+ MOTION_VERSION: ${{ inputs.version }}+ OPENMOTION_TELEMETRY: '0'+ HYPERFRAMES_BROWSER_PATH: /usr/bin/chromium+ HYPERFRAMES_FFMPEG_PATH: /usr/bin/ffmpeg+ HYPERFRAMES_FFPROBE_PATH: /usr/bin/ffprobe+ steps:+ - uses: actions/[email protected]+ with:+ path: control+ ref: ${{ github.sha }}+ fetch-depth: 0+ persist-credentials: false+ - uses: actions/setup-node@v6+ with:+ node-version: '26.11.1'+ - name: Resolve and freeze the integrated source+ id: source+ run: |+ git -C control fetch origin feature/motion:refs/remotes/origin/feature/motion+ node control/.github/scripts/motion-release.mjs source control+ - uses: actions/[email protected]+ with:+ path: source+ ref: ${{ steps.source.outputs.source_sha }}+ persist-credentials: false+ - name: Scan tracked source before dependency installation+ run: |+ node control/.github/scripts/motion-scan.mjs install "$RUNNER_TEMP/scanner"+ node control/.github/scripts/motion-scan.mjs source source "$RUNNER_TEMP/source-scan.json" "$RUNNER_TEMP/scanner/gitleaks"+ - name: Install rendering test tools+ run: sudo apt-get update -qq && sudo apt-get install -y -qq --no-install-recommends zip unzip chromium ffmpeg fonts-noto-core+ - name: Check the selected source+ working-directory: source+ run: |+ npm ci --no-audit --no-fund+ npm run check+ npm run typecheck:studio+ npm run build:studio+ npm run build:tracking+ node --experimental-strip-types --test tests/tracking.test.ts tests/install.test.ts tests/npm-installer.test.ts tests/npm-package.test.ts tests/test-package.test.ts tests/source-install.test.ts tests/bootstrap.test.ts tests/mcp-registry.test.ts tests/mcp-runtime.test.ts tests/mcp-upgrade.test.ts tests/preview.test.ts tests/phase1.test.ts tests/preview-handoff.test.ts tests/adapters.test.ts tests/package.test.ts tests/recreate-measure.test.ts tests/workflow.test.ts tests/catalog.test.ts tests/prism-templates.test.ts tests/extension-boundary.test.ts tests/connections.test.ts tests/install-guide.test.ts+ npm run test:studio -- --maxWorkers=2+ npm run package:phase1+ archive="$PWD/dist/motion-$(node -p "require('./package.json').version")-phase1.zip"+ node tests/phase1-package.mjs "$archive" "$RUNNER_TEMP/phase1-e2e"+ - name: Build the final prod application tgz once and scan both archives+ env:+ MOTION_SOURCE_SHA: ${{ steps.source.outputs.source_sha }}+ run: |+ node source/scripts/package-npm.mjs "$RUNNER_TEMP/build" "$MOTION_VERSION" --template-env=prod+ cp "$RUNNER_TEMP/source-scan.json" "$RUNNER_TEMP/build/source-scan.json"+ node control/.github/scripts/motion-scan.mjs package "$RUNNER_TEMP/build/openmotion-app-$MOTION_VERSION.tgz" "$RUNNER_TEMP/build/package-scan.json" "$RUNNER_TEMP/scanner/gitleaks"+ node control/.github/scripts/motion-release.mjs seal "$RUNNER_TEMP/build" "$RUNNER_TEMP/candidate" source+ - name: Retain the immutable candidate+ id: artifact+ uses: actions/[email protected]+ with:+ name: motion-candidate-${{ inputs.version }}+ path: ${{ runner.temp }}/candidate/+ retention-days: 30+ if-no-files-found: error+ - name: Show candidate download and tester instructions+ run: |+ node --input-type=module <<'JS'+ import { readFileSync, appendFileSync } from 'node:fs';+ const c = JSON.parse(readFileSync(process.env.RUNNER_TEMP + '/candidate/candidate.json'));+ const run = `https://github.com/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`;+ appendFileSync(process.env.GITHUB_STEP_SUMMARY, `## Candidate ready for acceptance\n\nVersion: ${c.version}\n\nSource: ${c.sourceCommit}\n\nTGZ SHA256: ${c.tgzSHA256}\n\n[Download motion-candidate-${c.version}](${run}#artifacts), extract it and give the folder to your Agent with this instruction:\n\n> Follow candidate-install.md in this folder to install this exact local candidate into an isolated test profile, application home, project data and Skills directory. Complete prepare and verify host loading. Record requested template/edit/export acceptance results in a private copy of acceptance.md; mark unrun checks NOT RUN. Do not publish.\n\nUse candidate-install.md before publication, not the sibling registry install.md. After acceptance, manually open Motion test publication, enter ${c.version} and confirm acceptance. Nothing was published by this build.\n`);+ JSdiff --git a/.github/workflows/motion-publication-recovery.yml b/.github/workflows/motion-publication-recovery.ymlnew file mode 100644index 00000000..42ae95cd--- /dev/null+++ b/.github/workflows/motion-publication-recovery.yml@@ -0,0 +1,32 @@+name: Motion snapshot recovery++on:+ workflow_dispatch:+ inputs:+ version:+ description: 'Exact existing candidate version; the identical package must already be public on npm'+ type: string+ required: true+ accepted:+ description: 'I verified this exact candidate and authorize snapshot-only recovery'+ type: boolean+ required: true+ default: false++permissions:+ contents: read+ actions: read++jobs:+ recover:+ if: github.repository == 'nexu-io/html-anything' && github.ref == 'refs/heads/main'+ permissions:+ contents: read+ actions: read+ id-token: write+ uses: ./.github/workflows/motion-publish-test.yml+ with:+ version: ${{ inputs.version }}+ accepted: ${{ inputs.accepted }}+ archive_only: true+ secrets: inheritdiff --git a/.github/workflows/motion-publish-test.yml b/.github/workflows/motion-publish-test.ymlnew file mode 100644index 00000000..8c5571fa--- /dev/null+++ b/.github/workflows/motion-publish-test.yml@@ -0,0 +1,270 @@+name: Motion test publication+run-name: Motion test publication · ${{ inputs.version }}++on:+ workflow_dispatch:+ inputs:+ version:+ description: 'Exact accepted candidate version, e.g. 0.6.4-test.7; candidate identity is resolved automatically'+ type: string+ required: true+ accepted:+ description: 'I completed the required acceptance for this exact candidate and authorize public test publication'+ type: boolean+ required: true+ default: false+ workflow_call:+ inputs:+ version:+ type: string+ required: true+ accepted:+ type: boolean+ required: true+ archive_only:+ type: boolean+ required: true++permissions:+ contents: read+ actions: read++concurrency:+ group: motion-test-publication+ cancel-in-progress: false++env:+ MOTION_VERSION: ${{ inputs.version }}+ MOTION_ACCEPTED: ${{ inputs.accepted }}+ MOTION_RELEASE_ACTION: ${{ inputs.archive_only && 'archive-only' || 'publish-test' }}++jobs:+ verify:+ if: github.repository == 'nexu-io/html-anything' && github.ref == 'refs/heads/main'+ runs-on: ubuntu-24.04+ timeout-minutes: 15+ outputs:+ artifact_id: ${{ steps.artifact.outputs.artifact-id }}+ tgz_sha256: ${{ steps.download.outputs.tgz_sha256 }}+ steps:+ - uses: actions/[email protected]+ with:+ ref: ${{ github.sha }}+ fetch-depth: 0+ persist-credentials: false+ - uses: actions/setup-node@v6+ with:+ node-version: '26.11.1'+ - name: Verify successful candidate producer and download its immutable artifact+ id: download+ env:+ GH_TOKEN: ${{ github.token }}+ run: node .github/scripts/motion-release.mjs download "$RUNNER_TEMP/candidate"+ - name: Recheck the integrated source and both archives+ env:+ GH_TOKEN: ${{ github.token }}+ MOTION_EXPECTED_SHA256: ${{ steps.download.outputs.tgz_sha256 }}+ run: |+ git fetch origin feature/motion:refs/remotes/origin/feature/motion+ node .github/scripts/motion-scan.mjs install "$RUNNER_TEMP/scanner"+ node .github/scripts/motion-release.mjs rescan "$RUNNER_TEMP/candidate" "$PWD" "$RUNNER_TEMP/scanner/gitleaks"+ - uses: actions/[email protected]+ id: artifact+ with:+ name: verified-candidate-${{ github.run_id }}-${{ github.run_attempt }}+ path: ${{ runner.temp }}/candidate/+ retention-days: 30+ if-no-files-found: error++ npm:+ if: ${{ always() && !cancelled() && needs.verify.result == 'success' }}+ env:+ MOTION_EXPECTED_SHA256: ${{ needs.verify.outputs.tgz_sha256 }}+ needs: verify+ runs-on: ubuntu-24.04+ timeout-minutes: 15+ outputs:+ artifact_id: ${{ steps.artifact.outputs.artifact-id }}+ permissions:+ contents: read+ actions: read+ id-token: write+ steps:+ - uses: actions/[email protected]+ with:+ ref: ${{ github.sha }}+ persist-credentials: false+ - uses: actions/setup-node@v6+ with:+ node-version: '26.11.1'+ registry-url: 'https://registry.npmjs.org'+ - uses: actions/[email protected]+ with:+ artifact-ids: ${{ needs.verify.outputs.artifact_id }}+ github-token: ${{ github.token }}+ run-id: ${{ github.run_id }}+ path: ${{ runner.temp }}/candidate+ - name: Record explicit operator acceptance authorization+ env:+ GH_TOKEN: ${{ github.token }}+ run: node .github/scripts/motion-release.mjs authorize "$RUNNER_TEMP/candidate"+ - name: Publish the accepted bytes with npm trusted publishing, or verify an identical existing version+ run: node .github/scripts/motion-release.mjs npm "$RUNNER_TEMP/candidate"+ - name: Retain npm publication state even after a partial failure+ id: artifact+ if: always()+ uses: actions/[email protected]+ with:+ name: npm-publication-${{ github.run_id }}-${{ github.run_attempt }}+ path: |+ ${{ runner.temp }}/candidate/npm-publication.json+ ${{ runner.temp }}/candidate/authorization.json+ retention-days: 30+ if-no-files-found: warn++ registry-mac:+ if: ${{ always() && !cancelled() && needs.verify.result == 'success' && needs.npm.result == 'success' }}+ env:+ MOTION_EXPECTED_SHA256: ${{ needs.verify.outputs.tgz_sha256 }}+ needs: [verify, npm]+ runs-on: macos-26+ timeout-minutes: 40+ outputs:+ artifact_id: ${{ steps.artifact.outputs.artifact-id }}+ steps:+ - uses: actions/[email protected]+ with:+ ref: ${{ github.sha }}+ persist-credentials: false+ - uses: actions/setup-node@v6+ with:+ node-version: '26.11.1'+ - uses: actions/[email protected]+ with:+ artifact-ids: ${{ needs.verify.outputs.artifact_id }}+ github-token: ${{ github.token }}+ run-id: ${{ github.run_id }}+ path: ${{ runner.temp }}/candidate+ - name: Anonymous exact-version cold installation and native MCP discovery+ shell: bash+ run: |+ node .github/scripts/motion-release.mjs verify "$RUNNER_TEMP/candidate"+ node .github/scripts/motion-registry-smoke.mjs "$RUNNER_TEMP/candidate"+ - uses: actions/[email protected]+ id: artifact+ if: always()+ with:+ name: registry-darwin-arm64-${{ github.run_id }}-${{ github.run_attempt }}+ path: ${{ runner.temp }}/candidate/registry-darwin-arm64.json+ retention-days: 30+ if-no-files-found: warn++ registry-windows:+ if: ${{ always() && !cancelled() && needs.verify.result == 'success' && needs.npm.result == 'success' }}+ env:+ MOTION_EXPECTED_SHA256: ${{ needs.verify.outputs.tgz_sha256 }}+ needs: [verify, npm]+ runs-on: windows-2025+ timeout-minutes: 40+ outputs:+ artifact_id: ${{ steps.artifact.outputs.artifact-id }}+ steps:+ - uses: actions/[email protected]+ with:+ ref: ${{ github.sha }}+ persist-credentials: false+ - uses: actions/setup-node@v6+ with:+ node-version: '26.11.1'+ - uses: actions/[email protected]+ with:+ artifact-ids: ${{ needs.verify.outputs.artifact_id }}+ github-token: ${{ github.token }}+ run-id: ${{ github.run_id }}+ path: ${{ runner.temp }}/candidate+ - name: Anonymous exact-version cold installation and native MCP discovery+ shell: bash+ run: |+ node .github/scripts/motion-release.mjs verify "$RUNNER_TEMP/candidate"+ node .github/scripts/motion-registry-smoke.mjs "$RUNNER_TEMP/candidate"+ - uses: actions/[email protected]+ id: artifact+ if: always()+ with:+ name: registry-win32-x64-${{ github.run_id }}-${{ github.run_attempt }}+ path: ${{ runner.temp }}/candidate/registry-win32-x64.json+ retention-days: 30+ if-no-files-found: warn++ snapshot:+ if: ${{ always() && !cancelled() && needs.verify.result == 'success' && needs.npm.result == 'success' && needs.registry-mac.result == 'success' && needs.registry-windows.result == 'success' }}+ env:+ MOTION_EXPECTED_SHA256: ${{ needs.verify.outputs.tgz_sha256 }}+ MOTION_INSTALL_PUBLIC_ORIGIN: ${{ vars.CLOUDFLARE_R2_RELEASES_PUBLIC_ORIGIN }}+ needs: [verify, npm, registry-mac, registry-windows]+ runs-on: ubuntu-24.04+ timeout-minutes: 15+ steps:+ - uses: actions/[email protected]+ with:+ ref: ${{ github.sha }}+ persist-credentials: false+ - uses: actions/setup-node@v6+ with:+ node-version: '26.11.1'+ - uses: actions/[email protected]+ with:+ artifact-ids: ${{ needs.verify.outputs.artifact_id }}+ github-token: ${{ github.token }}+ run-id: ${{ github.run_id }}+ path: ${{ runner.temp }}/candidate+ - uses: actions/[email protected]+ with:+ artifact-ids: ${{ needs.npm.outputs.artifact_id }}+ github-token: ${{ github.token }}+ run-id: ${{ github.run_id }}+ path: ${{ runner.temp }}/candidate+ - uses: actions/[email protected]+ with:+ artifact-ids: ${{ needs.registry-mac.outputs.artifact_id }}+ github-token: ${{ github.token }}+ run-id: ${{ github.run_id }}+ path: ${{ runner.temp }}/candidate+ - uses: actions/[email protected]+ with:+ artifact-ids: ${{ needs.registry-windows.outputs.artifact_id }}+ github-token: ${{ github.token }}+ run-id: ${{ github.run_id }}+ path: ${{ runner.temp }}/candidate+ - name: Archive exact-version snapshots, verify canonical public bytes, then promote the default guide last+ env:+ AWS_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_RELEASES_AK }}+ AWS_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_RELEASES_SK }}+ AWS_EC2_METADATA_DISABLED: 'true'+ AWS_PAGER: ''+ MOTION_R2_ENDPOINT: ${{ vars.CLOUDFLARE_R2_RELEASES_URL }}+ MOTION_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_RELEASES_BUCKET }}+ MOTION_INSTALL_PUBLIC_ORIGIN: ${{ vars.CLOUDFLARE_R2_RELEASES_PUBLIC_ORIGIN }}+ run: node .github/scripts/motion-release.mjs archive "$RUNNER_TEMP/candidate"+ - name: Retain the attempt, immutable release identity and previous default guide+ if: always()+ uses: actions/[email protected]+ with:+ name: release-record-${{ github.run_id }}-${{ github.run_attempt }}+ path: |+ ${{ runner.temp }}/candidate/release-record.json+ ${{ runner.temp }}/candidate/release-attempt.json+ ${{ runner.temp }}/candidate/publication.json+ ${{ runner.temp }}/candidate/previous-install.md+ retention-days: 30+ if-no-files-found: warn+ - name: Show the exact-version result and default guide status+ if: success()+ run: |+ node --input-type=module <<'JS'+ import { readFileSync, appendFileSync } from 'node:fs';+ const c = JSON.parse(readFileSync(process.env.RUNNER_TEMP + '/candidate/candidate.json'));+ const a = JSON.parse(readFileSync(process.env.RUNNER_TEMP + '/candidate/release-attempt.json'));+ const origin = process.env.MOTION_INSTALL_PUBLIC_ORIGIN;+ appendFileSync(process.env.GITHUB_STEP_SUMMARY, `## Test publication result\n\nVersion: ${c.version}\n\nSource: ${c.sourceCommit}\n\nResult: ${a.stage}\n\n[Exact-version installation guide](${origin}/open-motion/dev/${c.version}/install.md)\n\n[Default test guide](${origin}/open-motion/dev/install.md)\n\nThe default is advanced only after registry/native checks and public readback; a superseded candidate keeps its version snapshot without moving the default. No stable release occurred.\n`);+ JSdiff --git a/.github/workflows/motion-release-checks.yml b/.github/workflows/motion-release-checks.ymlnew file mode 100644index 00000000..1d75d035--- /dev/null+++ b/.github/workflows/motion-release-checks.yml@@ -0,0 +1,29 @@+name: Motion release controls++on:+ pull_request:+ branches: [main]+ push:+ branches: [main]++permissions:+ contents: read++jobs:+ controls:+ runs-on: ubuntu-24.04+ timeout-minutes: 5+ steps:+ - uses: actions/[email protected]+ with:+ persist-credentials: false+ - uses: actions/setup-node@v6+ with:+ node-version: '26.11.1'+ - name: Check standalone release scripts+ run: |+ for script in .github/scripts/*.mjs scripts/runtime-assets.mjs scripts/release-version.mjs scripts/install-guide.mjs; do+ node --check "$script"+ done+ - name: Rehearse release controls without publication credentials or external writes+ run: node --test tests/release-workflows.test.mjs tests/release-scan.test.mjs tests/install-guide.test.tsdiff --git a/docs/install.md b/docs/install.mdnew file mode 100644index 00000000..8e24a319--- /dev/null+++ b/docs/install.md@@ -0,0 +1,46 @@+# Install OpenMotion {{VERSION}}++This guide pins the complete npm application `{{PACKAGE_SPEC}}` on the **{{CHANNEL}}** software channel. It includes MCP, the built Studio and five Skills. The default template environment is **{{TEMPLATE_ENVIRONMENT}}**; a software test version does not select DEV templates.++If you are reading this file in the source repository and see `{{...}}`, it is a template, not a published installation instruction. Do not guess a package name or version.++## Instructions for the Agent++1. Collect OS/CPU, Node.js/npm versions and the current Agent identity together, using the host's supplied context where available. Node.js 22.18+ with npm and the Agent must already be installed. Supported native targets: {{TARGETS}}. Do not claim support for another target from package-download success.+2. Select the current host explicitly: `codex` (Codex), `claude` (Claude Code), `deepseek` (DeepSeek Harness) or `workbuddy` (WorkBuddy). An explicit user selection takes precedence. Do not infer the current host from which CLIs happen to be installed. Ask only when the current host or required profile cannot be established. Configure only that host; preserve projects, credentials and unrelated MCP/Skills settings.+3. For a test candidate, use a separate host profile, application home, project data and Skills directory. Keep those paths and reuse them for prepare and future reconnects. The [platform installation recipes]({{DETAILS_URL}}) describe the actual supported options. Do not run a test candidate into the user's daily profile by default.+4. Choose exactly one setup command below, applying the test isolation paths first when required. Run prepare only after successful setup, with the same application home, and wait for completion before native operations. Follow the selected host's discovery/reload mechanism. Compatible phase-one updates can keep existing connections; reconnect closed or incompatible transports. Confirm the application version, template environment, eleven public Tools and five Skills through that host, including an actual `motion_get_project` call. Registration alone does not prove loading.+5. Report the result and any failed step. Introduce the available capabilities and wait for the user's next request. Installation does not authorize generating a video or calling a paid model.++## Choose the selected host's setup command++The commands below show normal installations. For test candidates, apply the separate configuration/profile, home, data and Skills paths from the [platform recipes]({{DETAILS_URL}}) first. Run only the selected row.++| Current Agent | Setup command | Host-specific selection |+| --- | --- | --- |+| Codex | `npx --yes --package "{{PACKAGE_SPEC}}" openmotion setup --host codex` | Preserve the selected `CODEX_HOME` and Skills root. |+| Claude Code | `npx --yes --package "{{PACKAGE_SPEC}}" openmotion setup --host claude` | Preserve the selected `CLAUDE_CONFIG_DIR` and Skills root. |+| DeepSeek Harness | `npx --yes --package "{{PACKAGE_SPEC}}" openmotion setup --host deepseek --profile PROFILE` | Replace `PROFILE` with the actual selected profile from the host context; do not guess `web` or `desktop`. The standard macOS Desktop CLI is detected even when `dsh` is absent from PATH; use `--dsh` for another executable location. |+| WorkBuddy | `npx --yes --package "{{PACKAGE_SPEC}}" openmotion setup --host workbuddy` | Preserve the selected `WORKBUDDY_CONFIG_DIR` and Skills root. |++Then prepare the same installation:++```sh+npx --yes --package "{{PACKAGE_SPEC}}" openmotion prepare+```++Repeat an explicit `--home` from setup on prepare. Setup installs the selected host's MCP and Skills; a second installer or application/manifest download is unnecessary. Use `openmotion --help`, `setup --help` or `prepare --help` from this exact package for supported options. Inspect installer source or host internals only to investigate a concrete failure; a missing CLI on PATH alone is not a reason to create a wrapper.++## Runtime and environment++Setup copies the checked application into a managed writable directory and installs its locked production npm dependencies. The application and user projects do not run from the temporary npx cache. Prepare or first native use prepares the platform's independent native archives concurrently: browser/FFmpeg/ffprobe separately on macOS, browser/combined media on Windows. It waits for all components and reports a failure if any component fails; successful checked components remain reusable. This is not an offline package.++There is no persisted switch-environment command in this version. Internal DEV testing uses its separately configured installation; merely setting an environment variable while running setup does not configure a later desktop Agent. Do not silently fall back from one environment to another.++## Upgrade, recovery and feedback++Pin this exact version when reproducing an issue. Before an upgrade, back up project data and preserve the same installation/data paths. Compatible phase-one updates retain existing connections and active exports. For an incompatible protocol, finish active exports before updating only this installation's connection and idle backend together; reconnect after setup/prepare. Refresh host discovery for new Tools or Skills, and preserve unrelated settings. Older applications may not read newer data formats: compatible reinstall or backup restoration requires separate verification. Moving a server-side default does not downgrade installed clients.++Include the exact version, OS/CPU, Node/Agent versions, template environment, project/revision, reproduction and redacted logs in a report. Installation, real Agent creation, technical MP4 export and human audiovisual acceptance are separate results.++Release identity: source `{{COMMIT}}`; npm tgz SHA256 `{{TGZ_SHA256}}`. [Source and installation details]({{DETAILS_URL}}).diff --git a/docs/motion-release-activation.md b/docs/motion-release-activation.mdnew file mode 100644index 00000000..3ebcbb63--- /dev/null+++ b/docs/motion-release-activation.md@@ -0,0 +1,37 @@+# Motion release controls on the legacy default branch++This branch retains the legacy HTML Anything application. The Motion application still lives at the root of `feature/motion`. These additions register manual Actions entries on the default branch; they do not replace the application, change package/workspace metadata, merge Motion into main, or publish anything on a push/merge.++## Scope and provenance++The three manual workflows, their runtime helpers, installation/acceptance templates and deterministic tests are copied without modification from reviewed PR [#214](https://github.com/nexu-io/html-anything/pull/214), source commit `de45dadea282214762c7b3123cea7e6b1044f26f`. No private Git history or application files are imported. The extra `Motion release controls` CI job runs only syntax checks and simulated-service tests with read-only permissions; the existing legacy CI remains unchanged.++GitHub requires a manual workflow to exist on the default branch before its Run workflow entry is available. Our controls additionally require execution from `main`; they fetch the Motion application from a reviewed commit integrated into `feature/motion`. See [GitHub manual workflows](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/manually-run-a-workflow).++## Activation order++1. Integrate PR #214 into `feature/motion` after its required checks and review. This registration PR does not merge it.+2. Review and merge this control-only PR into `main`. This makes the entries available without running any candidate build or publication. The normal credential-free CI jobs run on the merge.+3. An npm package maintainer separately configures the GitHub trusted publisher for `@openmotion/app`: owner `nexu-io`, repository `html-anything`, workflow filename `motion-publish-test.yml`, Environment blank, and permission to publish. No stored npm token or independent approval environment is required. See [npm trusted publishers](https://docs.npmjs.com/trusted-publishers/).+4. Reuse the existing R2 Secrets `CLOUDFLARE_R2_RELEASES_AK` and `CLOUDFLARE_R2_RELEASES_SK`, and Variables `CLOUDFLARE_R2_RELEASES_BUCKET`, `CLOUDFLARE_R2_RELEASES_URL` and `CLOUDFLARE_R2_RELEASES_PUBLIC_ORIGIN`. Do not add secret values to source. Only the final storage step receives R2 credentials.++These are separate actions. Preparing or merging the registration does not authorize a package publication, repository rename or product-main cutover.++## Daily operation++1. **Build:** Actions → Motion candidate build → Run workflow → select `main`. Enter a new `X.Y.Z-test.N` version; normally leave `source_sha` empty to freeze the latest `feature/motion` head once. A supplied full SHA must already be integrated into that branch. The build checks/scans source and archives, and retains the exact candidate for 30 days without npm OIDC or R2 credentials.+2. **Download and accept:** Download `motion-candidate-<version>` from the successful run, extract it and give its directory to the Agent: “Follow candidate-install.md, verify candidate.json and the local tgz hash, install the exact local package with an isolated host profile, application home, data and Skills directories, complete prepare, and record actual results in a private copy of acceptance.md. Mark unrun checks NOT RUN. Do not publish.” Keep actual host loading, template/edit/export checks, real Agent creation and human playback separate. Public test software defaults to prod templates; internal DEV packages use a separate process.+3. **Publish:** Only after acceptance, Actions → Motion test publication → Run workflow → select `main`. Enter the exact accepted version and confirm `accepted`. This is the publication authorization, with no later independent approval dialog. Candidate provenance/hashes and scans are checked again; only the accepted tgz is published to npm `test`, then anonymously checked on Mac/Windows before immutable R2 snapshots and the default test guide are updated.++Before npm publication, use the candidate's **local** `candidate-install.md`, not the sibling registry `install.md`. After publication, the moving test guide is `https://releases.open-design.ai/open-motion/dev/install.md`; the immutable guide is `/open-motion/dev/<version>/install.md`. Stable publication is not implemented by these controls, and npm `latest` is not deliberately changed.++## Risk and recovery boundaries++- Registration is a capability change: users who can dispatch the trusted publication workflow can confirm and start a public release. There is no independent approval gate at this stage. Protect workflow edits and restrict operational access; the operator confirmation records intent, not proof of private testing.+- Builds do not publish. The publication form defaults acceptance to false and rejects missing, expired, ambiguous or untrusted candidates, changed bytes and unintegrated source. Do not rebuild a published version or guess among duplicate candidate artifacts.+- npm publication cannot be rolled back atomically with later checks. If native verification or R2 upload fails, npm may already be public while the default guide stays unchanged. Inspect retained records before using Re-run failed jobs; those retries reuse successful producer artifact IDs and never rebuild the candidate.+- Motion snapshot recovery is maintenance only: an exact already published identical version is required; no build, npm publication, tag movement or default-guide access is allowed. Channel rollback and client/data recovery require separate decisions.+- A single publication concurrency group and version/ETag checks protect channel promotion. Operate one release at a time; GitHub does not provide a durable FIFO queue.+- Disabling/removing these workflow registrations later does not undo a published npm version, restore user projects or revoke npm trust. Those are separate operations.++The implementation manual remains on the [reviewed Motion branch](https://github.com/nexu-io/html-anything/blob/de45dadea282214762c7b3123cea7e6b1044f26f/docs/release-workflows.md). Keep the full acceptance record internal. Real hosted workflow dispatch, npm OIDC, registry-native acceptance and R2/CDN writes need a separately authorized rehearsal; passing these control tests does not establish that those external integrations are active.diff --git a/docs/templates/candidate-install.md b/docs/templates/candidate-install.mdnew file mode 100644index 00000000..19072324--- /dev/null+++ b/docs/templates/candidate-install.md@@ -0,0 +1,28 @@+# Install the OpenMotion {{VERSION}} candidate++This is a **local candidate installation guide**. It installs the complete `{{TGZ}}` next to this file, not an unpublished npm registry version. The application, MCP, built Studio and five Skills are embedded. Native browser/FFmpeg/ffprobe and locked npm dependencies still need network access when prepared. Public test software defaults to prod templates.++## Frozen identity++- Version: `{{VERSION}}`+- Source: `{{SOURCE_SHA}}`+- Local file: `{{TGZ}}`+- TGZ SHA256: `{{SHA256}}`++## Instructions for the Agent++1. Read `candidate.json` in this extracted directory. Require its version, source commit, tgz filename and hash to match the identity above. Calculate the local tgz SHA256 before running it. Stop on a missing file or any mismatch; do not substitute npm `test`, `latest` or another candidate.+2. Collect OS/CPU, Node/npm and the actual Agent host once. Apply the supported [isolated platform recipes]({{DETAILS_URL}}): separate the host profile/configuration, application home, project data and Skills directory. Preserve existing projects, credentials, MCP entries and daily Skills. `--home` alone does not isolate host configuration. Ask for a missing host/profile when it cannot be established reliably.+3. Use the **local tgz** with the selected host, with the isolation settings applied first:++ ```sh+ npx --yes --package "./{{TGZ}}" -- openmotion setup --host HOST+ npx --yes --package "./{{TGZ}}" -- openmotion prepare+ ```++ Replace `HOST` with `codex`, `claude`, `deepseek` or `workbuddy`. Carry the explicit `--home`, `--data-dir`, `--skills-dir` and host-specific options from the platform recipe; repeat the same home for prepare. Wait for setup and prepare to finish before native use. Keep using this local package; no sidecar application/manifest download or source build is required.+4. Follow this host's discovery/reload action. Verify the actual application version, prod template environment, eleven MCP Tools, resources and five Skills, including a `motion_get_project` call against the isolated data directory. Registration or installation success alone is not host loading or creative acceptance.+5. Follow the tester's requested acceptance cases in `acceptance.md`: use an independent test project for template creation, editing, save/reopen and MP4 export. Do not modify an existing user project or start a paid provider call without its separate authorization. Retain technical export checks separately from real Agent creation and human audio/video playback.+6. Fill a **private copy** of `acceptance.md` with actual PASS / FAIL / NOT RUN results and evidence. Report failures and retain the generated candidate identity. Do not edit/re-upload the frozen candidate artifact. Do not publish npm, upload a guide or change a tag as part of installation/testing.++The sibling `install.md` is frozen for **after npm publication** and points at the exact registry version. Before publication, use this `candidate-install.md` and local tgz. Successful installation does not authorize release.diff --git a/docs/templates/release-record.md b/docs/templates/release-record.mdnew file mode 100644index 00000000..2f187e6c--- /dev/null+++ b/docs/templates/release-record.md@@ -0,0 +1,52 @@+# Motion candidate acceptance record++The candidate artifact includes this checklist as `acceptance.md` with its package/source/hash identity already filled. Keep the completed copy and attachments internally. Do not attach user material, credentials, internal URLs or the completed record to public artifacts. No manual file hash is required by the release form.++## Generated frozen identity++<!-- CANDIDATE_IDENTITY -->++The release builder replaces this marker. Do not change its generated identity; fill only the tester context and results below. In a source checkout, download the generated checklist from the actual candidate instead.++## Tester context++- Integration PR / source review / artifact expiry:+- Template environment / Resource / locale / catalog publication version:+- Supported OS / CPU / Node / npm / host versions:+- Acceptance owner / reviewer (if used) / release operator:+- Prior accepted compatible version or backup (or none):++## Acceptance matrix++Use PASS / FAIL / NOT RUN and link retained evidence. CI success alone cannot fill this table.++| Check | macOS arm64 | Windows x64 | Evidence / accepted limitation |+| --- | --- | --- | --- |+| Exact candidate tgz fresh install in an isolated host/profile | NOT RUN | NOT RUN | |+| Prepare Chromium, FFmpeg and ffprobe; repeat setup/cache reuse | NOT RUN | NOT RUN | |+| Preserve existing projects/material and unrelated host settings | NOT RUN | NOT RUN | |+| MCP Tools/resources and Skills discovery in the actual host | NOT RUN | NOT RUN | |+| Template list/detail/clone; actual environment and catalog identity | NOT RUN | NOT RUN | |+| Real Agent creation/adaptation, preview, edit, save and reopen | NOT RUN | NOT RUN | |+| MP4 export with required audio, decoded technical verification | NOT RUN | NOT RUN | |+| Normal-speed human visual/audio playback | NOT RUN | NOT RUN | |+| Upgrade from prior usable version and compatible recovery | NOT RUN | NOT RUN | |++## Release decision++- Blockers / accepted non-blocking issues / owner / workaround:+- Public source/package scans, dependency/license review and telemetry state:+- Approved exact version and TGZ SHA256:+- Reviewer / date / explicit release authorization:+- Internal retained record revision / filename (keep this private):+- The release operator enters this exact version in Motion test publication and confirms acceptance before dispatch. No independent approval environment is enabled. Never confirm a failed or incomplete required check.++## Publication follow-up++- Publication run / npm exact version / registry hash and integrity:+- Native registry cold-install report per platform:+- Immutable R2 version / release-record / guide URL and verified hash:+- Default entry / previous entry / final publication phase:+- Failure, recovery or user feedback:++Retain the completed acceptance revision; append publication follow-up separately against the same candidate identity. The public release record contains the manual operator authorization, not the private evidence or its digest. That receipt records explicit operator confirmation, not independent review or proof that every test was performed. Formal publication additionally requires the stable-package checks in the acceptance guide.diff --git a/scripts/install-guide.mjs b/scripts/install-guide.mjsnew file mode 100644index 00000000..7f072eab--- /dev/null+++ b/scripts/install-guide.mjs@@ -0,0 +1,55 @@+import assert from 'node:assert/strict';+import { mkdir, readFile } from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { runFile, sha256, writeAtomic, writeJSON } from './runtime-assets.mjs';+import { checkReleaseVersion } from './release-version.mjs';++export function validateGuideSpec(name, version) {+ assert.match(name || '', /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/, 'Require an npm package name');+ assert(name.length <= 214, 'npm package name is too long');+ checkReleaseVersion(version);+ return version.includes('-test.') ? 'test' : 'stable';+}++export function validateGuideIdentity(pkg, manifest) {+ validateGuideSpec(pkg.name, pkg.version);+ assert.equal(pkg.private, false, 'Only public release candidates may have a public installation guide');+ assert.equal(pkg.version, manifest.version, 'Package and embedded manifest versions differ');+ assert.equal(manifest.schemaVersion, 1, 'Unsupported release manifest');+ assert.equal(manifest.templateEnvironment, 'prod', 'Public guides require prod defaults');+ assert.equal(pkg.bin?.openmotion, 'scripts/npm-installer.mjs', 'Missing Motion entry point');+ assert.match(manifest.commit || '', /^[a-f0-9]{40}$/, 'Require the built source SHA');+ for (const hash of [manifest.application?.sha256, manifest.locks?.npm, manifest.locks?.native]) assert.match(hash || '', /^[a-f0-9]{64}$/, 'Require release checksums');+ const targets = Object.values(manifest.runtime?.targets || {});+ assert(targets.length > 0 && targets.every(t => t.platform && t.arch && t.minimumOS), 'Require native target declarations');+ return pkg.version.includes('-test.') ? 'test' : 'stable';+}++export async function generateInstallGuide(tgz, output, candidate = false) {+ const readEntry = async entry => JSON.parse(await runFile('tar', ['-xOf', path.resolve(tgz), entry]));+ const pkg = await readEntry('package/package.json'), manifest = await readEntry('package/payload/release-npm.json');+ const channel = validateGuideIdentity(pkg, manifest);+ const digest = await sha256(tgz), packageSpec = `${pkg.name}@${pkg.version}`;+ const values = { VERSION: pkg.version, PACKAGE_SPEC: packageSpec, CHANNEL: channel, COMMIT: manifest.commit,+ TEMPLATE_ENVIRONMENT: manifest.templateEnvironment, TGZ_SHA256: digest,+ TARGETS: Object.values(manifest.runtime.targets).map(t => `${t.platform}/${t.arch} (${t.minimumOS}+)`).join(', '),+ DETAILS_URL: `https://github.com/nexu-io/html-anything/blob/${manifest.commit}/docs/npm-installation.md` };+ const template = await readFile(new URL('../docs/install.md', import.meta.url), 'utf8');+ // The repository warning is unnecessary after all release placeholders are resolved.+ const text = (candidate ? '> Build preview only: this candidate is not an approved registry installation entry.\n\n' : '') + template.replace(/^If you are reading this file.*\n\n/m, '').replace(/\{\{([A-Z0-9_]+)\}\}/g, (_, key) => {+ assert(Object.hasOwn(values, key), 'Unknown installation placeholder: ' + key); return values[key];+ });+ assert(!text.includes('{{'), 'Installation guide has unresolved placeholders');+ await mkdir(output, { recursive: true });+ await writeAtomic(path.join(output, 'install.md'), text);+ const record = { schemaVersion: 1, candidate, packageName: pkg.name, version: pkg.version, packageSpec, channel,+ templateEnvironment: manifest.templateEnvironment, commit: manifest.commit, tgzSHA256: digest,+ applicationSHA256: manifest.application.sha256, locks: manifest.locks, guideSHA256: await sha256(path.join(output, 'install.md')) };+ await writeJSON(path.join(output, 'install-record.json'), record);+ return record;+}+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ assert([4, 5].includes(process.argv.length) && (process.argv[4] === undefined || process.argv[4] === '--candidate'), 'Usage: install-guide.mjs <complete-npm.tgz> <output-directory> [--candidate]');+ console.log(JSON.stringify(await generateInstallGuide(process.argv[2], path.resolve(process.argv[3]), process.argv[4] === '--candidate')));+}diff --git a/scripts/release-version.mjs b/scripts/release-version.mjsnew file mode 100644index 00000000..e487f0bc--- /dev/null+++ b/scripts/release-version.mjs@@ -0,0 +1,20 @@+import assert from 'node:assert/strict';++export function checkReleaseVersion(version) {+ assert.match(version, /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-test\.[1-9]\d*(?:\.[1-9]\d*)*)?$/, 'Use MAJOR.MINOR.PATCH or MAJOR.MINOR.PATCH-test.N[.N]');+}++export function compareReleaseVersions(left, right) {+ checkReleaseVersion(left); checkReleaseVersion(right);+ const parts = value => {+ const [core, test] = value.split('-test.');+ return [...core.split('.').map(BigInt), test === undefined ? 1n : 0n, ...(test?.split('.').map(BigInt) || [])];+ };+ const a = parts(left), b = parts(right);+ for (let i = 0; i < Math.max(a.length, b.length); i++) {+ if (a[i] === undefined) return -1;+ if (b[i] === undefined) return 1;+ if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;+ }+ return 0;+}diff --git a/scripts/runtime-assets.mjs b/scripts/runtime-assets.mjsnew file mode 100644index 00000000..35462e57--- /dev/null+++ b/scripts/runtime-assets.mjs@@ -0,0 +1,120 @@+import assert from 'node:assert/strict';+import { createHash, randomUUID } from 'node:crypto';+import { createReadStream, createWriteStream, constants } from 'node:fs';+import { access, copyFile, mkdir, open, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';+import { spawn } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import path from 'node:path';+import { Readable } from 'node:stream';+import { pipeline } from 'node:stream/promises';++export async function sha256(filename) {+ const hash = createHash('sha256');+ for await (const chunk of createReadStream(filename)) hash.update(chunk);+ return hash.digest('hex');+}+export async function download(asset, filename) {+ const url = new URL(asset.url);+ assert(url.protocol === 'https:' && /^[a-f0-9]{64}$/.test(asset.sha256), 'Require HTTPS and a pinned SHA256');+ try { if (await sha256(filename) === asset.sha256) return; } catch (error) { if (error.code !== 'ENOENT') throw error; }+ await mkdir(path.dirname(filename), { recursive: true });+ const temporary = filename + '.part';+ try {+ let current = url, response;+ const signal = AbortSignal.timeout(300_000);+ for (let redirects = 0; redirects <= 5; redirects++) {+ assert.equal(current.protocol, 'https:', 'Runtime redirects must use HTTPS');+ response = await fetch(current, { redirect: 'manual', signal });+ if (response.status < 300 || response.status > 399) break;+ const location = response.headers.get('location');+ await response.body?.cancel();+ assert(location && redirects < 5, 'Invalid or excessive runtime redirects');+ current = new URL(location, current);+ }+ assert(response.ok && response.body, `Download ${url.hostname}${url.pathname}: HTTP ${response.status}`);+ await pipeline(Readable.fromWeb(response.body), createWriteStream(temporary));+ assert.equal(await sha256(temporary), asset.sha256, `SHA256 mismatch: ${url.pathname}`);+ await rename(temporary, filename);+ } finally { await rm(temporary, { force: true }); }+}++export async function runFile(command, args, options = {}) {+ return new Promise((resolve, reject) => {+ const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, timeout: 300_000, ...options });+ let stdout = '', stderr = '';+ child.stdout?.on('data', chunk => { stdout = (stdout + chunk).slice(-4 * 1024 * 1024); });+ child.stderr?.on('data', chunk => { stderr = (stderr + chunk).slice(-16000); });+ child.once('error', reject);+ child.once('close', code => code === 0 ? resolve(stdout) : reject(new Error(`${command} exited ${code}: ${stderr || stdout}`)));+ });+}++export function relativePath(root, filename) {+ assert(typeof filename === 'string' && filename && !/[\\\x00-\x1f]/.test(filename) && !filename.startsWith('/') && !/^[a-z]:/i.test(filename)+ && !filename.split('/').includes('..'), 'Unsafe archive path: ' + filename);+ return path.join(root, filename);+}++export async function canonical(directory) {+ const normalized = path.resolve(directory);+ try { return await realpath(normalized); }+ catch (error) {+ if (error.code !== 'ENOENT') throw error;+ return path.join(await canonical(path.dirname(normalized)), path.basename(normalized));+ }+}++export async function withLock(filename, work) {+ // shortcut: a killed installer leaves its PID lock; verify the process exited before removing it.+ await mkdir(path.dirname(filename), { recursive: true });+ let handle;+ try { handle = await open(filename, 'wx', 0o600); }+ catch (error) {+ if (error.code !== 'EEXIST') throw error;+ throw new Error(`Another OpenMotion install is using ${filename}. Retry after it finishes; after a crash confirm its PID has exited before removing this lock.`);+ }+ try { await handle.writeFile(String(process.pid)); return await work(); }+ finally { await handle.close(); await rm(filename, { force: true }); }+}++export async function obtainAsset(asset, filename, allowLocal = false) {+ assert(/^[a-f0-9]{64}$/.test(asset.sha256), 'Require a pinned SHA256');+ const url = new URL(asset.url);+ if (url.protocol !== 'file:') return download(asset, filename);+ assert(allowLocal, 'Local assets require an explicitly supplied local manifest');+ if (await sha256(filename).catch(error => { if (error.code !== 'ENOENT') throw error; }) === asset.sha256) return;+ await mkdir(path.dirname(filename), { recursive: true });+ const temporary = filename + '.' + randomUUID() + '.part';+ try {+ await copyFile(fileURLToPath(url), temporary);+ assert.equal(await sha256(temporary), asset.sha256, 'SHA256 mismatch: local asset');+ await rename(temporary, filename);+ } finally { await rm(temporary, { force: true }); }+}++export async function extractArchive(filename, directory) {+ const tar = process.platform === 'win32' ? path.join(process.env.SystemRoot, 'System32', 'tar.exe') : 'tar';+ const entries = await runFile(tar, ['-tf', filename]);+ for (const entry of entries.split(/\r?\n/).filter(Boolean)) relativePath(directory, entry);+ await mkdir(directory, { recursive: true });+ await runFile(tar, ['-xf', filename, '-C', directory]);+}++export async function writeJSON(filename, value) {+ return writeAtomic(filename, JSON.stringify(value, null, 2) + '\n');+}++export async function writeAtomic(filename, value) {+ const temporary = filename + '.' + randomUUID() + '.tmp';+ try { await writeFile(temporary, value, { mode: 0o600 }); await rename(temporary, filename); }+ finally { await rm(temporary, { force: true }); }+}++export async function readJSON(filename) {+ try { return JSON.parse(await readFile(filename, 'utf8')); }+ catch (error) { if (error.code === 'ENOENT') return null; throw error; }+}++export async function executable(filename) { await access(filename, constants.X_OK); return filename; }++export function nativeComponents(info) { return info.media ? ['browser', 'media'] : ['browser', 'ffmpeg', 'ffprobe']; }diff --git a/tests/install-guide.test.ts b/tests/install-guide.test.tsnew file mode 100644index 00000000..31c41348--- /dev/null+++ b/tests/install-guide.test.ts@@ -0,0 +1,159 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { mkdtemp, mkdir, readFile, writeFile, rm } from 'node:fs/promises';+import path from 'node:path';+import os from 'node:os';+import { generateInstallGuide, validateGuideSpec, validateGuideIdentity } from '../scripts/install-guide.mjs';+import { publishGuide, storagePlan } from '../.github/scripts/publish-install-guide.mjs';+import { runFile } from '../scripts/runtime-assets.mjs';++const pkg = { name: '@openmotion/app', version: '0.6.4-test.1', private: false, bin: { openmotion: 'scripts/npm-installer.mjs' } };+const manifest = { schemaVersion: 1, version: pkg.version, templateEnvironment: 'prod', commit: 'a'.repeat(40),+ application: { sha256: 'b'.repeat(64) }, locks: { npm: 'c'.repeat(64), native: 'd'.repeat(64) },+ runtime: { targets: { mac: { platform: 'darwin', arch: 'arm64', minimumOS: '26.0' } } } };+const config = { endpoint: 'https://example.r2.cloudflarestorage.com', bucket: 'example-guides', publicOrigin: 'https://download.example.invalid' };+test('installation URLs separate the moving channel entry from the exact immutable version', () => {+ assert.equal(storagePlan({ channel: 'test', version: pkg.version }, config).versionKey, `open-motion/dev/${pkg.version}/install.md`);+ assert.equal(storagePlan({ channel: 'test', version: pkg.version }, config).fixedKey, 'open-motion/dev/install.md');+ assert.equal(storagePlan({ channel: 'stable', version: '0.6.4' }, config).versionKey, 'open-motion/0.6.4/install.md');+ assert.equal(storagePlan({ channel: 'stable', version: '0.6.4' }, config).fixedKey, 'open-motion/install.md');+});+async function fixture(t: any, candidate = false) {+ const root = await mkdtemp(path.join(os.tmpdir(), 'motion-guide-test-')); t.after(() => rm(root, { recursive: true, force: true }));+ await mkdir(path.join(root, 'package/payload'), { recursive: true });+ await writeFile(path.join(root, 'package/package.json'), JSON.stringify(pkg));+ await writeFile(path.join(root, 'package/payload/release-npm.json'), JSON.stringify(manifest));+ const tgz = path.join(root, 'candidate.tgz');+ await runFile('tar', ['-czf', tgz, '-C', root, 'package']);+ const directory = path.join(root, 'guide'), record = await generateInstallGuide(tgz, directory, candidate);+ return { directory, record };+}+const previousGuide = '# Install OpenMotion 0.6.3-test.1\n';+function storage(directory: string, record: any, previous = previousGuide) {+ const plan = storagePlan(record, config), objects = new Map<string, Buffer>(), writes: any[] = [];+ objects.set(plan.fixedKey, Buffer.from(previous));+ const run = async (command: string, args: string[]) => {+ assert.equal(command, 'aws');+ const operation = args[args.indexOf('s3api') + 1], key = args[args.indexOf('--key') + 1];+ if (operation === 'get-object') {+ if (!objects.has(key)) throw new Error('AWS (NoSuchKey)');+ await writeFile(args.at(-1)!, objects.get(key)!); return JSON.stringify({ ETag: '"previous-etag"' });+ }+ assert.equal(operation, 'put-object');+ const bytes = await readFile(args[args.indexOf('--body') + 1]);+ writes.push({ key, args }); objects.set(key, bytes); return JSON.stringify({ ETag: '"new-etag"' });+ };+ const fetcher = async (url: URL) => new Response(objects.get(url.pathname.slice(1)) ?? 'not found', { status: objects.has(url.pathname.slice(1)) ? 200 : 404 });+ return { plan, objects, writes, run, fetcher };+}++test('guide rendering pins the exact npm package, built source and hash while rejecting unresolved or private identities', async t => {+ const { directory, record } = await fixture(t);+ const text = await readFile(path.join(directory, 'install.md'), 'utf8');+ assert(text.includes(`npx --yes --package "${pkg.name}@${pkg.version}"`));+ assert(text.includes(manifest.commit) && text.includes(record.tgzSHA256));+ assert(!text.includes('{{') && !text.includes('see `{{...}}`'));+ assert(text.includes('eleven public Tools') && text.includes('five Skills'));+ for (const host of ['codex', 'claude', 'deepseek', 'workbuddy']) assert(text.includes(`openmotion setup --host ${host}`), host);+ assert(text.includes('--profile PROFILE') && text.includes('Do not infer the current host'));+ assert.equal(record.channel, 'test'); assert.equal(record.candidate, false);+ assert.equal(validateGuideSpec('openmotion', '0.6.4'), 'stable');+ for (const name of ['https://evil.invalid/a', 'x;echo bad', '--script', '@bad/no/extra']) assert.throws(() => validateGuideSpec(name, pkg.version));+ assert.throws(() => validateGuideSpec(pkg.name, 'latest'));+ assert.throws(() => validateGuideIdentity({ ...pkg, private: true }, manifest), /public/);+ assert.throws(() => validateGuideIdentity(pkg, { ...manifest, templateEnvironment: 'dev' }), /prod/);+ assert.throws(() => validateGuideIdentity(pkg, { ...manifest, version: '0.6.4' }), /versions differ/);+});++test('publication verifies the immutable URL before conditional fixed promotion and retains the prior guide', async t => {+ const { directory, record } = await fixture(t), store = storage(directory, record);+ const result = await publishGuide(directory, config, { ...store, fetcher: async (url: URL) => {+ assert.equal(url.search, '', 'Verify the canonical URL that users receive');+ return store.fetcher(url);+ } });+ assert.deepEqual(store.writes.map(x => x.key), [store.plan.versionKey, store.plan.fixedKey]);+ assert(store.writes[0].args.includes('--if-none-match'));+ assert(store.writes[1].args.includes('--if-match') && store.writes[1].args.includes('"previous-etag"'));+ assert(store.writes[1].args.includes('public, max-age=60, must-revalidate'));+ assert.equal(await readFile(path.join(directory, 'previous-install.md'), 'utf8'), previousGuide);+ assert.equal(result.phase, 'verified'); assert(result.previousSHA256);+});++test('an immutable version mismatch or failed public version verification leaves the fixed entry untouched', async t => {+ const { directory, record } = await fixture(t), store = storage(directory, record);+ store.objects.set(store.plan.versionKey, Buffer.from('other release bytes'));+ await assert.rejects(publishGuide(directory, config, store), /immutable/); assert.equal(store.writes.length, 0);+ store.objects.delete(store.plan.versionKey);+ await assert.rejects(publishGuide(directory, config, { ...store, fetcher: async () => new Response('wrong edge bytes') }), /bytes differ/);+ assert.equal(store.objects.get(store.plan.fixedKey)!.toString(), previousGuide);+});++test('short version URLs preserve the bytes of an existing immutable legacy URL', async t => {+ const { directory, record } = await fixture(t), store = storage(directory, record);+ store.objects.set(store.plan.legacyVersionKey, Buffer.from('different instructions'));+ await assert.rejects(publishGuide(directory, config, store), /immutable legacy/);+ assert.equal(store.writes.length, 0);+ const expected = await readFile(path.join(directory, 'install.md'));+ store.objects.set(store.plan.legacyVersionKey, expected);+ await publishGuide(directory, config, store);+ assert(store.objects.get(store.plan.versionKey)!.equals(expected));+ assert(store.objects.get(store.plan.legacyVersionKey)!.equals(expected));+ assert(!store.writes.some(x => x.key === store.plan.legacyVersionKey));+});++test('a post-promotion public failure records the partial state and preserves recovery bytes', async t => {+ const { directory, record } = await fixture(t), store = storage(directory, record);+ await assert.rejects(publishGuide(directory, config, { ...store, fetcher: async (url: URL) => url.pathname.slice(1) === store.plan.versionKey ? store.fetcher(url) : new Response('stale edge bytes') }), /bytes differ/);+ const state = JSON.parse(await readFile(path.join(directory, 'publication.json'), 'utf8'));+ assert.equal(state.phase, 'fixed-written-public-unverified');+ assert.equal(await readFile(path.join(directory, 'previous-install.md'), 'utf8'), previousGuide);+});++test('candidate previews, changed guide bytes and unsafe storage destinations cannot publish', async t => {+ const preview = await fixture(t, true); let calls = 0;+ await assert.rejects(publishGuide(preview.directory, config, { run: async () => { calls++; return '{}'; } }), /previews/); assert.equal(calls, 0);+ const { directory, record } = await fixture(t); await writeFile(path.join(directory, 'install.md'), 'tampered');+ await assert.rejects(publishGuide(directory, config), /changed after validation/);+ for (const endpoint of ['http://example.r2.cloudflarestorage.com', 'https://evil.invalid', 'https://user:[email protected]']) assert.throws(() => storagePlan(record, { ...config, endpoint }));+ assert.throws(() => storagePlan(record, { ...config, bucket: '../other' }));+});++test('archive-only guide publication never accesses the moving default', async t => {+ const { directory, record } = await fixture(t), store = storage(directory, record);+ const result = await publishGuide(directory, config, { ...store, promote: false, run: async (command: string, args: string[]) => {+ assert.notEqual(args[args.indexOf('--key') + 1], store.plan.fixedKey);+ return store.run(command, args);+ } });+ assert.equal(result.promoted, false); assert.equal(result.phase, 'version-verified');+ assert.deepEqual(store.writes.map(x => x.key), [store.plan.versionKey]);+ assert.equal(store.objects.get(store.plan.fixedKey)!.toString(), previousGuide);+});++test('late completion archives its exact version without rolling a newer default back', async t => {+ const { directory, record } = await fixture(t), newer = '# Install OpenMotion 0.6.4-test.10\n';+ const store = storage(directory, record, newer);+ const result = await publishGuide(directory, config, store);+ assert.equal(result.phase, 'superseded'); assert.equal(result.promoted, false);+ assert.deepEqual(store.writes.map(x => x.key), [store.plan.versionKey]);+ assert.equal(store.objects.get(store.plan.fixedKey)!.toString(), newer);+});++test('unrecognized or conflicting same-version defaults require inspection instead of replacement', async t => {+ const { directory, record } = await fixture(t);+ for (const previous of ['unrecognized instructions', `# Install OpenMotion ${record.version}\nchanged`]) {+ const store = storage(directory, record, previous);+ await assert.rejects(publishGuide(directory, config, store), /recognizable version|Same-version/);+ assert.equal(store.objects.get(store.plan.fixedKey)!.toString(), previous);+ assert(!store.writes.some(x => x.key === store.plan.fixedKey));+ }+});++test('PR CI has no publication credentials; publication requires a separate manual accepted workflow', async () => {+ const ci = await readFile(new URL('../.github/workflows/ci.yml', import.meta.url), 'utf8');+ const workflow = await readFile(new URL('../.github/workflows/motion-publish-test.yml', import.meta.url), 'utf8');+ assert(!ci.includes('secrets.') && !ci.includes('publish-install-guide:'));+ assert(workflow.includes('workflow_dispatch:') && !workflow.includes('pull_request:') && !workflow.includes('push:'));+ assert(!workflow.includes('environment:'), 'No independent approval environment is enabled');+ assert(workflow.includes('accepted:') && workflow.includes('default: false'));+ assert(!workflow.split(' snapshot:\n')[0].includes('secrets.'));+});diff --git a/tests/release-fixture.mjs b/tests/release-fixture.mjsnew file mode 100644index 00000000..b4988e20--- /dev/null+++ b/tests/release-fixture.mjs@@ -0,0 +1,46 @@+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { runFile, sha256, writeJSON } from '../scripts/runtime-assets.mjs';+import { sealCandidate, repository, candidateWorkflow, publicationWorkflow, authorizationReceipt } from '../.github/scripts/motion-release.mjs';++export async function candidateFixture(t) {+ const work = await mkdtemp(path.join(os.tmpdir(), 'motion-release-test-'));+ t.after(() => rm(work, { recursive: true, force: true }));+ const root = fileURLToPath(new URL('../', import.meta.url)), build = path.join(work, 'build'), directory = path.join(work, 'candidate');+ const commit = (await runFile('git', ['rev-parse', 'HEAD'], { cwd: root })).trim(), version = '0.6.4-test.99';+ const app = path.join(work, 'app'), pkg = path.join(work, 'package');+ await mkdir(path.join(app, 'scripts'), { recursive: true }); await mkdir(path.join(pkg, 'payload'), { recursive: true }); await mkdir(build);+ await writeJSON(path.join(app, 'package.json'), { version }); await writeJSON(path.join(app, 'package-lock.json'), {});+ await writeJSON(path.join(app, 'scripts/runtime-lock.json'), {});+ const application = path.join(pkg, 'payload', `openmotion-application-${version}.tar.gz`);+ await runFile('tar', ['-czf', application, '-C', app, '.']);+ const manifest = { schemaVersion: 1, version, format: 'npm', templateEnvironment: 'prod', commit,+ application: { url: './' + path.basename(application), sha256: await sha256(application) },+ locks: { npm: await sha256(path.join(app, 'package-lock.json')), native: await sha256(path.join(app, 'scripts/runtime-lock.json')) },+ runtime: { targets: { mac: { platform: 'darwin', arch: 'arm64', minimumOS: '26.0' } } } };+ await writeJSON(path.join(pkg, 'payload/release-npm.json'), manifest);+ await writeJSON(path.join(pkg, 'package.json'), { name: '@openmotion/app', version, private: false, bin: { openmotion: 'scripts/npm-installer.mjs' } });+ const tgz = path.join(build, `openmotion-app-${version}.tgz`);+ await runFile('tar', ['-czf', tgz, '-C', work, 'package']);+ await writeJSON(path.join(build, 'release-npm.json'), { ...manifest, installer: { url: './' + path.basename(tgz), sha256: await sha256(tgz) } });+ for (const name of ['source-scan.json', 'package-scan.json']) await writeJSON(path.join(build, name), { status: 'passed' });+ const env = { MOTION_SOURCE_SHA: commit, MOTION_VERSION: version, GITHUB_SHA: 'b'.repeat(40),+ GITHUB_WORKFLOW_REF: `${repository}/${candidateWorkflow}@refs/heads/main`, GITHUB_RUN_ID: '123', GITHUB_RUN_ATTEMPT: '1' };+ const candidate = await sealCandidate(build, directory, root, env);+ const provenance = { head_sha: env.GITHUB_SHA, runId: 123, attempt: 1 };+ await writeJSON(path.join(directory, 'provenance.json'), provenance);+ const inputs = { action: 'publish-test', version, accepted: true, expectedSHA256: candidate.tgzSHA256 };+ const publicationEnv = { GITHUB_REPOSITORY: repository, GITHUB_EVENT_NAME: 'workflow_dispatch', GITHUB_REF: 'refs/heads/main',+ GITHUB_RUN_ID: '800', GITHUB_SHA: env.GITHUB_SHA, GITHUB_WORKFLOW_REF: `${repository}/${publicationWorkflow}@refs/heads/main`,+ MOTION_VERSION: version, MOTION_ACCEPTED: 'true', MOTION_RELEASE_ACTION: 'publish-test' };+ const authorization = authorizationReceipt(candidate, { id: 800, run_attempt: 1, actor: { login: 'operator' } }, inputs.action);+ await writeJSON(path.join(directory, 'authorization.json'), authorization);+ for (const platform of ['darwin-arm64', 'win32-x64']) await writeJSON(path.join(directory, `registry-${platform}.json`), {+ status: 'passed', platform, version, sourceCommit: commit, tgzSHA256: candidate.tgzSHA256,+ registryColdInstall: 'passed', nativePreparation: 'passed', repeatSetup: 'passed', resources: 'passed', mcpTools: 11, skills: 5,+ });+ await writeJSON(path.join(directory, 'npm-publication.json'), { tgzSHA256: candidate.tgzSHA256, previousLatest: '0.5.0' });+ return { work, root, build, directory, candidate, inputs, provenance, app, pkg, manifest, authorization, env: publicationEnv };+}diff --git a/tests/release-scan.test.mjs b/tests/release-scan.test.mjsnew file mode 100644index 00000000..2aba686c--- /dev/null+++ b/tests/release-scan.test.mjs@@ -0,0 +1,51 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { chmod, mkdtemp, mkdir, readFile, rm, symlink, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { archivePaths, privacyFindings, scanSource, scanPackage, unpackChecked } from '../.github/scripts/motion-scan.mjs';+import { candidateFixture } from './release-fixture.mjs';+import { runFile, sha256, writeJSON } from '../scripts/runtime-assets.mjs';++test('privacy rules reject internal URLs, employee paths and private files without printing their values', () => {+ for (const name of ['.env', 'nested/.env.production', '.npmrc', 'outputs/log.json', 'research/info.md', 'server.key']) assert(privacyFindings(name, '').length);+ assert.equal(privacyFindings('.env.example', 'DUMMY=example').length, 0);+ assert(privacyFindings('.env.example', '', 'package').length);+ const url = 'https://' + 'workspace.' + 'feishu.cn/wiki/private';+ const text = '/' + 'Users/' + 'employee/private/file';+ assert.deepEqual(privacyFindings('README.md', url).map(x => x.rule), ['internal-link']);+ assert.deepEqual(privacyFindings('README.md', text).map(x => x.rule), ['personal-path']);+ assert(!JSON.stringify(privacyFindings('README.md', url)).includes('private'));+ for (const name of ['../escape', '/absolute', 'C:/drive', 'safe/../../outside', 'bad\\file', 'bad\tname']) assert.throws(() => archivePaths(name));+});++async function scanner(t, findings = []) {+ const work = await mkdtemp(path.join(os.tmpdir(), 'motion-scanner-test-')); t.after(() => rm(work, { recursive: true, force: true }));+ const binary = path.join(work, 'scanner');+ const script = `#!/usr/bin/env node\nimport{writeFileSync}from'node:fs'; const args=process.argv.slice(2); if(!args.includes('--redact')||!args.includes('--ignore-gitleaks-allow'))process.exit(2); writeFileSync(args[args.indexOf('--report-path')+1],JSON.stringify(${JSON.stringify(findings)}));process.exit(${findings.length ? 1 : 0});\n`;+ await writeFile(binary, script); await chmod(binary, 0o755); return { work, binary };+}++test('tracked source is scanned without ignore-file bypasses; secret errors expose only rule/path/line', async t => {+ const { work, binary } = await scanner(t, [{ File: 'source.txt', RuleID: 'fixture-secret', StartLine: 1, Secret: 'never-print-this' }]);+ const source = path.join(work, 'source'); await mkdir(source);+ await runFile('git', ['init', '-q', source]); await writeFile(path.join(source, 'source.txt'), 'synthetic fixture');+ await runFile('git', ['add', '.'], { cwd: source });+ await assert.rejects(scanSource(source, binary), error => error.message.includes('fixture-secret') && !error.message.includes('never-print-this'));+ await symlink('source.txt', path.join(source, 'link')); await runFile('git', ['add', 'link'], { cwd: source });+ await assert.rejects(scanSource(source, binary), /Tracked links/);+});++test('the scanner opens the nested application, rejects hidden private content and rejects linked archive entries', async t => {+ const f = await candidateFixture(t), { binary } = await scanner(t);+ assert.equal((await scanPackage(path.join(f.directory, f.candidate.tgz), binary)).status, 'passed');+ await writeFile(path.join(f.app, '.env'), 'EXAMPLE=not-a-real-secret');+ const appArchive = path.join(f.pkg, 'payload', f.manifest.application.url.slice(2));+ await runFile('tar', ['-czf', appArchive, '-C', f.app, '.']);+ await writeJSON(path.join(f.pkg, 'payload/release-npm.json'), { ...f.manifest, application: { ...f.manifest.application, sha256: await sha256(appArchive) } });+ const tgz = path.join(f.work, 'hidden.tgz'); await runFile('tar', ['-czf', tgz, '-C', f.work, 'package']);+ await assert.rejects(scanPackage(tgz, binary), /environment-file/);+ await symlink('package.json', path.join(f.app, 'linked')); const linked = path.join(f.work, 'linked.tar.gz');+ await runFile('tar', ['-czf', linked, '-C', f.app, '.']);+ await assert.rejects(unpackChecked(linked, path.join(f.work, 'extracted')), /links and special/);+});diff --git a/tests/release-workflows.test.mjs b/tests/release-workflows.test.mjsnew file mode 100644index 00000000..01c18606--- /dev/null+++ b/tests/release-workflows.test.mjs@@ -0,0 +1,287 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFile, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { createHash } from 'node:crypto';+import { candidateFixture } from './release-fixture.mjs';+import { releaseInputs, resolveSource, validateSource, validateRun, verifyDownloaded, downloadCandidate, publishNpm, archiveRelease, repository, candidateWorkflow, recoveryWorkflow, publicationWorkflow, candidateJobName, findCandidate, authorizationReceipt, recordAuthorization } from '../.github/scripts/motion-release.mjs';+import { compareReleaseVersions } from '../scripts/release-version.mjs';+import { consumerEnvironment } from '../.github/scripts/motion-registry-smoke.mjs';+import { runFile } from '../scripts/runtime-assets.mjs';++const config = { endpoint: 'https://example.r2.cloudflarestorage.com', bucket: 'example-releases', publicOrigin: 'https://download.example.invalid' };+const valid = { GITHUB_REPOSITORY: repository, GITHUB_EVENT_NAME: 'workflow_dispatch', GITHUB_REF: 'refs/heads/main',+ GITHUB_WORKFLOW_REF: `${repository}/${publicationWorkflow}@refs/heads/main`, MOTION_VERSION: '0.6.4-test.99', MOTION_ACCEPTED: 'true', MOTION_RELEASE_ACTION: 'publish-test', MOTION_EXPECTED_SHA256: 'a'.repeat(64) };+const origin = { id: 123, run_attempt: 1, event: 'workflow_dispatch', head_branch: 'main', head_repository: { full_name: repository }, status: 'completed', conclusion: 'success', path: candidateWorkflow, head_sha: 'b'.repeat(40) };+const artifact = { id: 456, name: 'motion-candidate-0.6.4-test.99', workflow_run: { id: 123 }, expired: false, size_in_bytes: 100, digest: 'sha256:' + 'a'.repeat(64) };+test('manual entry and source selection reject untrusted callers, mutable refs and non-test versions', async () => {+ assert.equal(releaseInputs(valid).action, 'publish-test');+ for (const [key, value] of Object.entries({ GITHUB_REPOSITORY: 'fork/repo', GITHUB_EVENT_NAME: 'push', GITHUB_REF: 'refs/heads/feature/motion', GITHUB_WORKFLOW_REF: `${repository}/evil.yml@refs/heads/main`, MOTION_EXPECTED_SHA256: 'bad', MOTION_ACCEPTED: 'false', MOTION_VERSION: '0.6.4', MOTION_RELEASE_ACTION: 'stable' })) assert.throws(() => releaseInputs({ ...valid, [key]: value }));+ const recovery = { ...valid, GITHUB_WORKFLOW_REF: `${repository}/${recoveryWorkflow}@refs/heads/main` };+ assert.throws(() => releaseInputs(recovery), /Recovery/);+ assert.equal(releaseInputs({ ...recovery, MOTION_RELEASE_ACTION: 'archive-only' }).action, 'archive-only');+ let called = false;+ await validateSource('.', 'a'.repeat(40), '0.6.4-test.7', async (_, args) => { called = true; assert(args.includes('refs/remotes/origin/feature/motion')); }); assert(called);+ for (const [sha, version] of [['main', '0.6.4-test.7'], ['a'.repeat(40), '0.6.4'], ['a'.repeat(40), '0.6.4-test.0']]) await assert.rejects(validateSource('.', sha, version, async () => { throw Error('must not run'); }));+ await assert.rejects(validateSource('.', 'a'.repeat(40), '0.6.4-test.7', async () => { throw Error('not integrated'); }), /not integrated/);+ const resolved = await resolveSource('.', '', '0.6.4-test.7', async (_, args) => args[0] === 'rev-parse' ? 'a'.repeat(40) + '\n' : '');+ assert.equal(resolved, 'a'.repeat(40));+});++test('only a completed successful registered candidate build can supply a version', () => {+ validateRun(origin, artifact, '0.6.4-test.99');+ for (const patch of [{ event: 'pull_request' }, { head_branch: 'feature/motion' }, { path: '.github/workflows/other.yml' }, { head_repository: { full_name: 'fork/repo' } }, { status: 'in_progress' }, { conclusion: 'failure' }]) assert.throws(() => validateRun({ ...origin, ...patch }, artifact, '0.6.4-test.99'));+ for (const patch of [{ expired: true }, { name: 'motion-candidate-0.6.4-test.100' }, { digest: null }, { workflow_run: { id: 999 } }]) assert.throws(() => validateRun(origin, { ...artifact, ...patch }, '0.6.4-test.99'));+});++test('version lookup uses the exact artifact name and rejects missing, expired, ambiguous or incomplete results', async () => {+ const fetcher = async url => {+ const parsed = new URL(url);+ assert.equal(parsed.pathname, '/repos/' + repository + '/actions/artifacts');+ assert.equal(parsed.searchParams.get('name'), artifact.name);+ return Response.json({ total_count: 1, artifacts: [artifact] });+ };+ assert.equal((await findCandidate('0.6.4-test.99', fetcher)).id, artifact.id);+ for (const artifacts of [[], [{ ...artifact, expired: true }], [artifact, { ...artifact, id: 457 }], [{ ...artifact, workflow_run: {} }]]) {+ await assert.rejects(findCandidate('0.6.4-test.99', async () => Response.json({ total_count: artifacts.length, artifacts })));+ }+ await assert.rejects(findCandidate('0.6.4-test.99', async () => Response.json({ total_count: 101, artifacts: [artifact] })), /incomplete/);+});++test('operator authorization requires explicit acceptance and records the actual manual caller without independent approval', async t => {+ const f = await candidateFixture(t);+ const run = { ...origin, id: 800, path: publicationWorkflow, actor: { login: 'operator' }, triggering_actor: { login: 'rerunner' } };+ assert.equal(authorizationReceipt(f.candidate, run, 'publish-test').actor, 'rerunner');+ assert.throws(() => authorizationReceipt(f.candidate, { ...run, actor: {}, triggering_actor: {} }, 'publish-test'));+ const fetcher = async url => { assert(String(url).endsWith('/actions/runs/800')); return Response.json(run); };+ await recordAuthorization(f.directory, f.inputs, fetcher, f.env);+ const record = JSON.parse(await readFile(path.join(f.directory, 'authorization.json')));+ assert.equal(record.publicationRun, 800); assert.equal(record.tgzSHA256, f.candidate.tgzSHA256);+ assert.equal(record.actor, 'rerunner'); assert.equal(record.acceptanceConfirmed, true);+ await assert.rejects(recordAuthorization(f.directory, f.inputs, fetcher, { ...f.env, MOTION_ACCEPTED: 'false' }), /acceptance/);+ for (const patch of [{ id: 801 }, { event: 'push' }, { head_branch: 'feature/motion' }, { head_sha: 'f'.repeat(40) }, { path: candidateWorkflow }, { head_repository: { full_name: 'fork/repo' } }]) {+ await assert.rejects(recordAuthorization(f.directory, f.inputs, async () => Response.json({ ...run, ...patch }), f.env));+ }+});++test('the sealed candidate detects tgz, guide, identity and provenance tampering', async t => {+ const { directory, candidate } = await candidateFixture(t);+ assert.equal((await verifyDownloaded(directory, candidate.tgzSHA256)).version, candidate.version);+ const checklist = await readFile(path.join(directory, 'acceptance.md'), 'utf8');+ assert(checklist.includes(candidate.tgzSHA256) && checklist.includes(candidate.sourceCommit));+ const instructions = await readFile(path.join(directory, 'candidate-install.md'), 'utf8');+ assert(instructions.includes(candidate.tgz) && instructions.includes(candidate.tgzSHA256) && instructions.includes(candidate.sourceCommit));+ assert(instructions.includes('npx --yes --package "./' + candidate.tgz + '"'));+ assert(!instructions.includes('{{'));+ assert(!checklist.includes('<!-- CANDIDATE_IDENTITY -->'));+ await assert.rejects(verifyDownloaded(directory, candidate.tgzSHA256, '0.6.4-test.100'), /version/);+ assert(checklist.includes('NOT RUN'), 'Generated identity must not fabricate human acceptance');+ await assert.rejects(verifyDownloaded(directory, '0'.repeat(64)));+ const file = path.join(directory, 'install.md'), original = await readFile(file);+ await writeFile(file, 'changed'); await assert.rejects(verifyDownloaded(directory, candidate.tgzSHA256), /Candidate file changed/);+ await writeFile(file, original); await writeFile(path.join(directory, 'provenance.json'), JSON.stringify({ head_sha: 'f'.repeat(40), runId: 123, attempt: 1 }));+ await assert.rejects(verifyDownloaded(directory, candidate.tgzSHA256));+});++test('artifact download verifies GitHub ZIP digest and does not forward the credential to the signed URL', async t => {+ const f = await candidateFixture(t), zip = path.join(f.work, 'candidate.zip');+ await runFile('zip', ['-j', zip, ...['candidate.json', ...Object.keys(f.candidate.files)].map(name => path.join(f.directory, name))]);+ const bytes = await readFile(zip), digest = 'sha256:' + createHash('sha256').update(bytes).digest('hex');+ const fetcher = async (url, options) => {+ const value = String(url);+ if (value.endsWith('/actions/runs/123')) return Response.json(origin);+ if (value.includes('/artifacts?')) return Response.json({ total_count: 1, artifacts: [{ ...artifact, digest, size_in_bytes: bytes.length }] });+ if (value.endsWith('/456/zip')) return new Response(null, { status: 302, headers: { location: 'https://signed.example.invalid/candidate' } });+ assert.equal(value, 'https://signed.example.invalid/candidate'); assert.equal(options.headers, undefined);+ return new Response(bytes);+ };+ assert.equal((await downloadCandidate(f.candidate.version, path.join(f.work, 'download'), f.candidate.tgzSHA256, fetcher)).tgzSHA256, f.candidate.tgzSHA256);+ const retryFetcher = (url, options) => String(url).endsWith('/actions/runs/123') ? Response.json({ ...origin, run_attempt: 2, conclusion: 'failure' }) : fetcher(url, options);+ await assert.rejects(downloadCandidate(f.candidate.version, path.join(f.work, 'retry'), undefined, retryFetcher), /success/);+ assert.equal((await downloadCandidate(f.candidate.version, path.join(f.work, 'automatic'), undefined, fetcher)).tgzSHA256, f.candidate.tgzSHA256);+ await assert.rejects(downloadCandidate(f.candidate.version, path.join(f.work, 'corrupt'), f.candidate.tgzSHA256, async (url, options) => String(url).includes('signed.') ? new Response('tampered ZIP') : fetcher(url, options)));+});++function registry(candidate, exists = true, tag = candidate.version, latest = '0.5.0') {+ return () => Response.json({ versions: exists ? { [candidate.version]: { dist: { integrity: candidate.integrity } } } : {}, 'dist-tags': { test: tag, latest } });+}++test('npm publishes only new exact bytes; identical retry and archive-only never write, mismatches fail', async t => {+ const f = await candidateFixture(t); let calls = 0;+ assert.notEqual(f.candidate.sourceCommit, f.candidate.workflow.sha, 'Application and workflow source identities are independent');+ const run = async (command, args) => { calls++; assert.equal(command, 'npm'); assert(args.includes('--ignore-scripts') && args.includes('test')); assert(args.includes('--provenance=false'), 'Do not attest the publication main SHA as the prebuilt application source'); assert.equal(args[1], path.join(f.directory, f.candidate.tgz)); };+ await publishNpm(f.directory, f.inputs, { run, fetcher: registry(f.candidate, false), env: f.env }); assert.equal(calls, 1);+ await publishNpm(f.directory, f.inputs, { run, fetcher: registry(f.candidate), env: f.env });+ await assert.rejects(publishNpm(f.directory, f.inputs, { run, fetcher: registry({ ...f.candidate, integrity: 'different' }), env: f.env }), /different bytes/); assert.equal(calls, 1);+ await writeFile(path.join(f.directory, 'authorization.json'), JSON.stringify({ ...f.authorization, action: 'archive-only' }));+ await publishNpm(f.directory, { ...f.inputs, action: 'archive-only' }, { run, fetcher: registry(f.candidate), env: f.env }); assert.equal(calls, 1);+ await assert.rejects(publishNpm(f.directory, { ...f.inputs, action: 'archive-only' }, { run, fetcher: registry(f.candidate, false), env: f.env }), /existing identical/);+});++test('a stale candidate or authorization from another run cannot publish or move npm test backward', async t => {+ const f = await candidateFixture(t); let calls = 0;+ const run = async () => { calls++; };+ await assert.rejects(publishNpm(f.directory, f.inputs, { run, env: f.env, fetcher: registry(f.candidate, false, '0.6.4-test.100') }), /newer npm test/);+ await assert.rejects(publishNpm(f.directory, f.inputs, { run, env: { GITHUB_RUN_ID: '801' }, fetcher: registry(f.candidate, false) }), /another publication run/);+ await writeFile(path.join(f.directory, 'authorization.json'), JSON.stringify({ ...f.authorization, tgzSHA256: '0'.repeat(64) }));+ await assert.rejects(publishNpm(f.directory, f.inputs, { run, env: f.env, fetcher: registry(f.candidate, false) }));+ assert.equal(calls, 0);+});++test('test version ordering handles numeric suffixes, stable versions and unsafe numeric widths', () => {+ for (const [a, b] of [['0.6.4-test.10', '0.6.4-test.9'], ['0.6.4', '0.6.4-test.99'], ['0.6.5-test.1', '0.6.4'], ['0.6.4-test.1.2', '0.6.4-test.1'], ['0.6.4-test.9007199254740993', '0.6.4-test.9007199254740992']]) {+ assert.equal(compareReleaseVersions(a, b), 1); assert.equal(compareReleaseVersions(b, a), -1);+ }+ assert.equal(compareReleaseVersions('0.6.4-test.1', '0.6.4-test.1'), 0);+ assert.throws(() => compareReleaseVersions('latest', '0.6.4'));+});++test('partial publication retries use the retained producer artifact IDs across attempts', async () => {+ const workflow = await readFile(new URL('../.github/workflows/motion-publish-test.yml', import.meta.url), 'utf8');+ const jobs = Object.fromEntries(workflow.split('\njobs:\n')[1].split(/(?=^ [\w-]+:\n)/m).filter(s => s.trim()).map(s => [s.match(/^ ([\w-]+):\n/)[1], s]));+ const producers = ['verify', 'npm', 'registry-mac', 'registry-windows'];+ const render = (value, attempt) => value.replaceAll('${{ github.run_id }}', '800').replaceAll('${{ github.run_attempt }}', String(attempt));+ for (const id of producers) {+ assert(jobs[id], 'A platform needs its own retained output: ' + id);+ assert(jobs[id].includes('artifact_id: ${{ steps.artifact.outputs.artifact-id }}'), 'Expose the actual uploaded artifact ID');+ assert(jobs[id].includes(' id: artifact\n'));+ }+ for (const id of ['npm', 'registry-mac', 'registry-windows', 'snapshot']) {+ assert(jobs[id].includes('if: ${{ always() && !cancelled() && needs.verify.result'), 'Successful retained producers must still supply partial retry consumers: ' + id);+ }+ const downloads = id => [...jobs[id].matchAll(/artifact-ids: \$\{\{ needs\.([\w-]+)\.outputs\.artifact_id \}\}/g)].map(m => m[1]);+ assert.deepEqual(downloads('npm'), ['verify']);+ assert.deepEqual(downloads('registry-mac'), ['verify']);+ assert.deepEqual(downloads('registry-windows'), ['verify']);+ assert.deepEqual(downloads('snapshot'), producers);+ assert(jobs.snapshot.includes('needs: [verify, npm, registry-mac, registry-windows]'));+ assert(jobs.npm.includes(' actions: read\n'), 'The credentialed npm job needs only read access to input artifacts');+ for (const job of Object.values(jobs)) {+ for (const step of job.split(/(?=^ - )/m).filter(s => s.includes('uses: actions/download-artifact@'))) {+ assert(step.includes('github-token: ${{ github.token }}') && step.includes('run-id: ${{ github.run_id }}'), 'Resolve exact IDs through the run-scoped REST API');+ assert(!step.includes('github.run_attempt'), 'A consumer must not guess the producing attempt');+ }+ }+ for (const rerun of [[], ['registry-mac'], ['registry-windows'], ['registry-mac', 'registry-windows'], ['npm', 'registry-mac', 'registry-windows'], producers]) {+ const stored = new Map(), outputs = {};+ for (const [index, id] of producers.entries()) {+ const name = jobs[id].match(/ name: ([^\n]+)/)[1];+ const oldID = String(100 + index); stored.set(oldID, render(name, 1)); outputs[id] = oldID;+ if (rerun.includes(id)) { const newID = String(200 + index); stored.set(newID, render(name, 2)); outputs[id] = newID; }+ }+ for (const id of downloads('snapshot')) {+ assert(stored.has(outputs[id]), 'The exact producer artifact remains available');+ assert.equal(stored.get(outputs[id]).endsWith(rerun.includes(id) ? '-2' : '-1'), true);+ }+ }+});++test('daily build and publication are separate manual entries without an independent environment gate', async () => {+ const build = await readFile(new URL('../.github/workflows/motion-candidate.yml', import.meta.url), 'utf8');+ const workflow = await readFile(new URL('../.github/workflows/motion-publish-test.yml', import.meta.url), 'utf8');+ const recovery = await readFile(new URL('../.github/workflows/motion-publication-recovery.yml', import.meta.url), 'utf8');+ const header = workflow.split('\njobs:\n')[0];+ assert(build.includes('workflow_dispatch:') && build.includes('version:') && build.includes('source_sha:'));+ assert(build.includes('name: ' + candidateJobName) && build.includes('ref: ${{ steps.source.outputs.source_sha }}'));+ assert(build.includes('name: motion-candidate-${{ inputs.version }}') && build.includes('candidate-install.md'));+ assert(!build.includes('concurrency:') && !build.includes('secrets.') && !build.includes('id-token:'));+ assert(header.includes('version:') && header.includes('accepted:') && header.includes('default: false'));+ for (const manualField of ['candidate_run_id:', 'source_sha:', 'tgz_sha256:', 'acceptance_sha256:', 'approved:', 'action:']) assert(!header.includes(manualField));+ assert(!workflow.includes(' candidate:') && !workflow.includes('environment:'));+ assert(header.includes('group: motion-test-publication') && header.includes('cancel-in-progress: false'));+ assert(workflow.includes('motion-release.mjs authorize') && workflow.includes('authorization.json'));+ assert(workflow.includes('MOTION_EXPECTED_SHA256: ${{ needs.verify.outputs.tgz_sha256 }}'));+ assert(recovery.includes('version:') && recovery.includes('accepted:') && recovery.includes('archive_only: true'));+ assert(recovery.includes('uses: ./.github/workflows/motion-publish-test.yml') && !recovery.includes('source_sha:'));+});++function storage(candidate) {+ const objects = new Map([['open-motion/dev/install.md', Buffer.from('# Install OpenMotion 0.6.4-test.1\n')]]), writes = [], reads = [];+ let failKey;+ const run = async (command, args) => {+ assert.equal(command, 'aws'); const op = args[args.indexOf('s3api') + 1], key = args[args.indexOf('--key') + 1];+ if (op === 'get-object') { reads.push(key); if (!objects.has(key)) throw Error('NoSuchKey'); await writeFile(args.at(-1), objects.get(key)); return JSON.stringify({ ETag: '"etag"' }); }+ assert.equal(op, 'put-object'); if (key === failKey) throw Error('simulated upload interruption');+ assert(args.includes('--if-none-match') || args.includes('--if-match'));+ if (args.includes('--if-none-match')) assert(!objects.has(key));+ objects.set(key, await readFile(args[args.indexOf('--body') + 1])); writes.push(key); return '{}';+ };+ const fetcher = async url => String(url).includes('registry.npmjs.org') ? registry(candidate)() : new Response(objects.get(new URL(url).pathname.slice(1)) || '', { status: objects.has(new URL(url).pathname.slice(1)) ? 200 : 404 });+ return { objects, writes, reads, run, fetcher, env: { GITHUB_RUN_ID: '800' }, fail: key => { failKey = key; } };+}++test('interrupted archive resumes identical snapshots, verifies the exact public URLs, and updates the moving guide last', async t => {+ const f = await candidateFixture(t), store = storage(f.candidate), prefix = `open-motion/dev/${f.candidate.version}`;+ store.fail(prefix + '/install-record.json');+ await assert.rejects(archiveRelease(f.directory, f.inputs, config, store), /interruption/);+ assert.equal(store.objects.get('open-motion/dev/install.md').toString(), '# Install OpenMotion 0.6.4-test.1\n');+ store.fail(null); await archiveRelease(f.directory, f.inputs, config, store);+ assert.equal(store.writes.at(-1), 'open-motion/dev/install.md');+ assert.equal(await readFile(path.join(f.directory, 'previous-install.md'), 'utf8'), '# Install OpenMotion 0.6.4-test.1\n');+ const before = store.writes.length; await archiveRelease(f.directory, f.inputs, config, store); assert.equal(store.writes.length, before);+ store.objects.set(prefix + '/release-npm.json', Buffer.from('different snapshot'));+ await assert.rejects(archiveRelease(f.directory, f.inputs, config, store), /Immutable snapshot/);+});++test('archive-only never reads or writes the moving entry, and failed platform acceptance blocks all storage calls', async t => {+ const f = await candidateFixture(t), store = storage(f.candidate);+ await writeFile(path.join(f.directory, 'authorization.json'), JSON.stringify({ ...f.authorization, action: 'archive-only' }));+ await archiveRelease(f.directory, { ...f.inputs, action: 'archive-only' }, config, store);+ assert(!store.reads.includes('open-motion/dev/install.md') && !store.writes.includes('open-motion/dev/install.md'));+ await writeFile(path.join(f.directory, 'registry-win32-x64.json'), JSON.stringify({ status: 'failed' }));+ const before = store.reads.length; await assert.rejects(archiveRelease(f.directory, f.inputs, config, store)); assert.equal(store.reads.length, before);+});++test('a superseded npm candidate still keeps immutable snapshots and never advances the moving guide', async t => {+ const f = await candidateFixture(t), store = storage(f.candidate);+ await archiveRelease(f.directory, f.inputs, config, { ...store, fetcher: url => String(url).includes('registry.npmjs.org') ? registry(f.candidate, true, '0.6.4-test.100')() : store.fetcher(url) });+ assert(store.objects.has(`open-motion/dev/${f.candidate.version}/install.md`));+ assert(!store.reads.includes('open-motion/dev/install.md') && !store.writes.includes('open-motion/dev/install.md'));+ const attempt = JSON.parse(await readFile(path.join(f.directory, 'release-attempt.json')));+ assert.equal(attempt.stage, 'archived-superseded');+});++test('a missing or regressed npm test tag cannot be misreported as a newer superseding release', async t => {+ const f = await candidateFixture(t), store = storage(f.candidate);+ for (const tag of [undefined, '0.6.4-test.1']) {+ await assert.rejects(archiveRelease(f.directory, f.inputs, config, { ...store,+ fetcher: () => Response.json({ versions: { [f.candidate.version]: { dist: { integrity: f.candidate.integrity } } }, 'dist-tags': { test: tag, latest: '0.5.0' } }) }), /explicit channel recovery/);+ }+ assert.equal(store.writes.length, 0);+});++test('an unexpected npm latest change stops promotion and consumer processes cannot inherit publication credentials', async t => {+ const f = await candidateFixture(t), store = storage(f.candidate);+ await assert.rejects(archiveRelease(f.directory, f.inputs, config, { ...store, fetcher: registry(f.candidate, true, f.candidate.version, f.candidate.version) }), /latest changed/);+ assert.equal(store.writes.length, 0);+ const env = consumerEnvironment('/isolated', { PATH: '/bin', NODE_AUTH_TOKEN: 'example', GITHUB_TOKEN: 'example', AWS_ACCESS_KEY_ID: 'example', ACTIONS_ID_TOKEN_REQUEST_URL: 'example', BROWSER_USE_ACCESS_PIPE_PATH: '/ipc', CODEX_APP_TOOLS_PIPE_PATH: '/ipc', NODE_OPTIONS: '--require=untrusted', npm_config_registry: 'https://private.invalid' });+ assert(!env.NODE_AUTH_TOKEN && !env.GITHUB_TOKEN && !env.AWS_ACCESS_KEY_ID && !env.ACTIONS_ID_TOKEN_REQUEST_URL);+ assert(!env.BROWSER_USE_ACCESS_PIPE_PATH && !env.CODEX_APP_TOOLS_PIPE_PATH && !env.NODE_OPTIONS);+ assert.equal(env.npm_config_registry, 'https://registry.npmjs.org/');+});++test('no-publication rehearsal carries one accepted candidate through npm and storage using simulated services only', async t => {+ const f = await candidateFixture(t), store = storage(f.candidate);+ const run = { ...origin, id: 800, path: publicationWorkflow, actor: { login: 'operator' } };+ const github = async url => { assert(String(url).endsWith('/actions/runs/800')); return Response.json(run); };+ await writeFile(path.join(f.directory, 'authorization.json'), '{}');+ let npmWrites = 0, published = false;+ const npm = { env: f.env, fetcher: () => registry(f.candidate, published)(), run: async (command, args) => {+ assert.equal(command, 'npm'); assert.equal(args[1], path.join(f.directory, f.candidate.tgz));+ npmWrites++; published = true;+ } };+ await assert.rejects(publishNpm(f.directory, f.inputs, npm));+ assert.equal(npmWrites, 0, 'No authorization means no registry write');+ await recordAuthorization(f.directory, f.inputs, github, f.env);+ await publishNpm(f.directory, f.inputs, npm);+ await archiveRelease(f.directory, f.inputs, config, store);+ assert.equal(npmWrites, 1);+ const release = JSON.parse(store.objects.get(`open-motion/dev/${f.candidate.version}/release-record.json`));+ assert.equal(release.schemaVersion, 2); assert.equal(release.authorization.actor, 'operator');+ assert.equal(release.authorization.acceptanceConfirmed, true);+ assert.equal(release.tgzSHA256, f.candidate.tgzSHA256);+ assert.equal(store.writes.at(-1), 'open-motion/dev/install.md');+ await publishNpm(f.directory, f.inputs, npm);+ await archiveRelease(f.directory, f.inputs, config, store);+ assert.equal(npmWrites, 1, 'Retry never repacks or republishes the accepted bytes');+});