Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(ci): add independent exact-SHA verification runner

Rahman901e200655a4
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 68441db4..64c8ab34 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- `ci` add independent exact-SHA verification runner
- `organization` add internal project flows with callable CRUD
**Fixed**
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index dab0f247..87b411f8 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,5 +1,11 @@
## 2026-09-18 — Keep private viewer routing client-verifiable
+## 2026-09-18 — Independent CI verification pilot
+
+Related URL: https://github.com/rahmanef63/mso
+[before: verification had no standalone structured CI receipt] → [after: an exact-SHA manual runner wraps committed gates with private reports, host/repository locks and fail-closed outcomes]. Batonly tracks migration acceptance. Security/release profiles remain BLOCKED until standalone scanner parity is actually verified; Actions, branch protections and production are not changed. Run `bun run test:ci`; fixtures do not attest product or security acceptance.
+
+
The PR review reproduced a deployment-compatibility regression: a hostname resolving
only to RFC1918, carrier-grade NAT or unique-local IPv6 was blocked by the generic
public-provider SSRF guard before the client's authenticated viewer could mount.
diff --git a/docs/README.md b/docs/README.md
index e79565d6..0f0667a3 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -96,3 +96,7 @@ the current-reference doc.
[Maintenance, factory reset and clean uninstall](./MAINTENANCE.md) · [Extended workspace reference](./reference/WORKSPACE-GUIDE.md)
- [Session screenshots and temporary artifacts](./SESSION-ARTIFACTS.md) — private per-session paths, MCP/CLI reads, quotas and safe retention.
+
+## Independent CI pilot
+
+[SELF-HOSTED-CI.md](./SELF-HOSTED-CI.md) is the current manual-runner reference and Actions migration gap matrix. It does not claim completed security parity or deployment automation.
diff --git a/docs/SELF-HOSTED-CI.md b/docs/SELF-HOSTED-CI.md
new file mode 100644
index 00000000..63b9a68c
--- /dev/null
+++ b/docs/SELF-HOSTED-CI.md
@@ -0,0 +1,80 @@
+# Self-hosted CI — manual verification pilot
+
+**Current implementation: pilot, not a completed GitHub Actions migration.**
+MSO runs repository-owned checks; Batonly tracks delivery evidence. GitHub remains
+source control. No Actions dispatch, service, webhook, schedule, credential export,
+production deployment, or remote status writer is created by this runner.
+
+## Use
+
+From a trusted clean committed repository root with dependencies installed:
+
+```sh
+bun run ci:plan
+bun run ci:verify --sha "$(git rev-parse HEAD)"
+bun run ci:release --sha "$(git rev-parse HEAD)"
+bun run test:ci
+```
+
+`verify` checks native node-pty, installer syntax and existing `scripts/gates.sh`.
+The committed gate remains authoritative for typecheck, lint, coverage, repository/docs
+checks, changelog freshness, strict audit, isolated build and release-browser journeys.
+Do not run this pilot on an untrusted fork as an unattended worker: it is not a sandbox.
+
+`security` and `release` intentionally return BLOCKED until scanner adapters and provider
+evidence are verified. No selected commands execute when a prerequisite is blocked.
+A verify PASS does not imply security parity, deployment approval or production health.
+
+## Evidence and concurrency
+
+Private reports/logs: `${XDG_STATE_HOME:-$HOME/.local/state}/mso-ci/runs/<run-id>/`.
+Directories are 0700 and files 0600. CLI output is statuses/report path, not raw logs.
+Only an environment allowlist reaches child commands; provider credentials and Git hook
+variables are not inherited. Review/redact private logs before any external sharing.
+
+Reports record exact SHA, PASS/FAIL/BLOCKED/NOT_RUN, timings and process outcomes.
+Missing prerequisites, timeout, cancellation and truncated evidence never pass.
+Source SHA and clean state are checked before/after execution. Cooperating invocations
+share a host lock and repository-identity lock and must use the same state root.
+These locks do not control unrelated agents/manual jobs; audit those before heavy work.
+After a crash, verify the recorded process/workflow is gone before removing its exact
+stale lock. There is no automatic takeover of another job's lock.
+
+The runner never attests merged/deployed/verifiedLive/releaseEligible or automatic
+Batonly sync. Those fields stay false/UNSYNCED, even when verification passes.
+A future delivery adapter must verify and persist those separate transitions.
+
+## Migration matrix
+
+| Existing workflow | Standalone replacement / remaining gate |
+| --- | --- |
+| `ci.yml` | Pilot reuses committed gates. Prove full exact-SHA run; preserve dependency monitoring separately. |
+| `codeql.yml` | Reviewed CodeQL bundle, security-extended analysis, existing SARIF validator and exact-SHA upload/read-back. BLOCKED. |
+| `security-core.yml` | Preserve pinned Trivy/OSV/Gitleaks/Semgrep/ShellCheck and `scripts/security-ultimate.sh`; verify standalone adapters. BLOCKED. |
+| `dependency-review.yml` | Explicit base/head dependency delta and vulnerability policy; a lockfile audit alone is not equivalent. BLOCKED. |
+| `security-alerts.yml` | Existing alert inventory through selected private integration; confirm exact-SHA analyses rather than old evidence. BLOCKED. |
+| `scorecard.yml` | Reviewed standalone Scorecard and policy/evidence handling; no unapproved public result publication. BLOCKED. |
+| `dast.yml` | Explicit isolated staging target, pinned ZAP policy, complete evidence. BLOCKED. |
+| `codex-security.yml` | Existing manual paid scan remains separately approval-gated. Never automatically invoked or claimed passed. |
+
+GitHub supports external code scanning and commit statuses independently of Actions:
+- https://docs.github.com/en/code-security/how-tos/find-and-fix-code-vulnerabilities/integrate-with-existing-tools/use-with-existing-ci-system
+- https://docs.github.com/en/rest/commits/statuses
+
+## Batonly and cutover
+
+Use MSO project_mcp_tools/project_mcp_call against the selected Batonly integration.
+Discover exact schemas/project/task identities. Record scope, SHA, results and evidence
+references, not raw logs/secrets. Use expectedVersion/expectedRevision, refresh conflicts,
+read back writes, preserve history, and leave unexecuted checklist items open.
+This pilot has no automatic Batonly writer or dashboard Run/Rerun button.
+
+Do not disable security gates or declare Actions migration complete from this pilot.
+Complete and verify scanner parity, representative pass/fail runs, trusted status
+publication and authenticated triggers before changing required checks/disabling Actions.
+Untrusted forks need a separate secret-free sandbox. Webhooks need signature, replay,
+repository/branch allowlist and commit freshness checks; this CLI is not a webhook API.
+
+Deployment stays on the existing exact-merged-SHA release path with explicit approval,
+build-before-restart, health/browser proof and rollback. Never verify by building in the
+live production directory. A successful CI run is not a deployment receipt.
diff --git a/package.json b/package.json
index 04b76d74..ccdabd29 100644
--- a/package.json
+++ b/package.json
@@ -14,7 +14,7 @@
"typecheck": "tsc --noEmit",
"test": "node scripts/check-test-toolchain.mjs && vitest run",
"coverage": "node scripts/check-test-toolchain.mjs && vitest run --coverage",
- "check": "node scripts/check-cycles.mjs && node scripts/check-architecture.mjs && node scripts/check-docs.mjs && node scripts/gen-comparison.mjs --check && node scripts/check-contrast.mjs && bun scripts/check-skill-flows.mjs && bun run check:instance-literals",
+ "check": "node scripts/check-cycles.mjs && node scripts/check-architecture.mjs && node scripts/check-docs.mjs && node scripts/gen-comparison.mjs --check && node scripts/check-contrast.mjs && bun scripts/check-skill-flows.mjs && bun run check:instance-literals && bun run test:ci",
"audit": "node scripts/audit.mjs",
"verify": "bun run typecheck && bun run lint && bun run coverage && bun run check && bun run audit",
"security:ultimate": "bash scripts/security-ultimate.sh",
@@ -47,7 +47,12 @@
"check:instance-literals": "bun scripts/check-instance-literals.mjs",
"e2e:release": "node scripts/e2e/release.mjs",
"bundle:report": "node scripts/check-bundle.mjs --report-only",
- "bundle:check": "node scripts/check-bundle.mjs"
+ "bundle:check": "node scripts/check-bundle.mjs",
+ "ci:plan": "node scripts/ci/run.mjs --plan",
+ "ci:verify": "node scripts/ci/run.mjs --profile verify",
+ "ci:security": "node scripts/ci/run.mjs --profile security",
+ "ci:release": "node scripts/ci/run.mjs --profile release",
+ "test:ci": "node --test scripts/ci/contract.node.mjs"
},
"dependencies": {
"@anthropic-ai/sdk": "^0.125.0",
diff --git a/scripts/ci/contract.node.mjs b/scripts/ci/contract.node.mjs
new file mode 100644
index 00000000..d1ad92ca
--- /dev/null
+++ b/scripts/ci/contract.node.mjs
@@ -0,0 +1,107 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, rm, readFile, stat, symlink, writeFile, mkdir } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { planFor, verdict, exitFor } from './plan.mjs';
+import { executeStep, childEnvironment } from './process.mjs';
+import { acquireLocks, privateDirectory } from './store.mjs';
+import { runPipeline, inspectRepository } from './runner.mjs';
+const sha = 'a'.repeat(40);
+async function fixture(fn) {
+ const path = await mkdtemp(join(tmpdir(), 'mso-ci-test-'));
+ try { return await fn(path); } finally { await rm(path, { recursive: true, force: true }); }
+}
+const inspect = async () => ({ cwd: '/synthetic', identity: '/synthetic/.git', head: sha });
+const pass = async () => ({ status: 'PASS', exitCode: 0 });
+test('fixed plans reject arbitrary shell/profile input', () => {
+ assert.throws(() => planFor('verify; echo unsafe'));
+ assert.equal(planFor('verify').length, 4);
+ assert.equal(planFor('verify').at(-1).args[0], 'scripts/gates.sh');
+});
+test('security lanes remain visibly blocked, not waived', () => {
+ assert.equal(planFor('security').length, 6);
+ assert(planFor('security').every((step) => step.blocked));
+ assert.equal(planFor('release').length, 10);
+});
+test('empty, partial and not-run evidence never passes', () => {
+ assert.equal(verdict([]), 'BLOCKED');
+ assert.equal(verdict([{ status: 'PASS' }, { status: 'NOT_RUN' }]), 'BLOCKED');
+ assert.equal(verdict([{ status: 'FAIL' }, { status: 'NOT_RUN' }]), 'FAIL');
+ assert.equal(exitFor('BLOCKED'), 2);
+});
+test('child environment does not inherit credentials or Git hook context', () => {
+ const env = childEnvironment({ PATH: '/bin', HOME: '/home/test', GITHUB_TOKEN: 'not-a-token', GIT_DIR: '/wrong', OS_SESSION_SECRET: 'not-a-secret' });
+ assert.equal(env.PATH, '/bin'); assert.equal(env.GITHUB_TOKEN, undefined);
+ assert.equal(env.GIT_DIR, undefined); assert.equal(env.OS_SESSION_SECRET, undefined);
+});
+test('private state refuses a symlink', () => fixture(async (root) => {
+ await mkdir(join(root, 'target'), { mode: 0o700 });
+ await symlink(join(root, 'target'), join(root, 'link'));
+ await assert.rejects(privateDirectory(join(root, 'link')), /owner-private/);
+}));
+test('host lock prevents parallel repositories and releases safely', () => fixture(async (root) => {
+ const release = await acquireLocks(root, '/one/.git', 'one');
+ await assert.rejects(acquireLocks(root, '/two/.git', 'two'), /lock busy/);
+ await release(); const next = await acquireLocks(root, '/two/.git', 'two'); await next();
+}));
+test('real child process success and private logs', () => fixture(async (root) => {
+ const logPath = join(root, 'success.log');
+ const result = await executeStep({ command: process.execPath, args: ['-e', 'console.log("fixture success")'], timeoutMs: 3000 }, { cwd: root, logPath });
+ assert.equal(result.status, 'PASS'); assert.equal((await stat(logPath)).mode & 0o777, 0o600);
+}));
+test('real child nonzero exit fails', () => fixture(async (root) => {
+ const result = await executeStep({ command: process.execPath, args: ['-e', 'process.exit(7)'], timeoutMs: 3000 }, { cwd: root, logPath: join(root, 'fail.log') });
+ assert.equal(result.status, 'FAIL'); assert.equal(result.exitCode, 7);
+}));
+test('timeout is blocked, never success', () => fixture(async (root) => {
+ const result = await executeStep({ command: process.execPath, args: ['-e', 'setInterval(()=>{},1000)'], timeoutMs: 60 }, { cwd: root, logPath: join(root, 'timeout.log') });
+ assert.equal(result.status, 'BLOCKED'); assert.equal(result.timedOut, true);
+}));
+test('log overflow stays bounded and blocks evidence', () => fixture(async (root) => {
+ const logPath = join(root, 'bounded.log');
+ const result = await executeStep({ command: process.execPath, args: ['-e', 'console.log("x".repeat(5000))'], timeoutMs: 3000 }, { cwd: root, logPath, maxBytes: 64 });
+ assert.equal(result.status, 'BLOCKED'); assert.equal(result.logTruncated, true);
+ assert.equal((await stat(logPath)).size, 64);
+}));
+test('cancellation terminates a real child', () => fixture(async (root) => {
+ const controller = new AbortController(); controller.abort();
+ const result = await executeStep({ command: process.execPath, args: ['-e', 'setInterval(()=>{},1000)'], timeoutMs: 3000 }, { cwd: root, logPath: join(root, 'cancel.log'), signal: controller.signal });
+ assert.equal(result.status, 'BLOCKED'); assert.equal(result.cancelled, true);
+}));
+test('synthetic success never asserts release, deployment or Batonly sync', () => fixture(async (root) => {
+ const result = await runPipeline({ repo: root, expectedSha: sha, profile: 'verify', stateRoot: root }, { inspect, execute: pass });
+ assert.equal(result.report.status, 'PASS'); assert.equal(result.report.releaseEligible, false);
+ assert.equal(result.report.deployed, false); assert.equal(result.report.verifiedLive, false);
+ assert.equal(result.report.batonlySync, 'UNSYNCED');
+ const saved = JSON.parse(await readFile(result.reportPath, 'utf8'));
+ assert.equal(saved.commit, sha); assert.equal(saved.steps.length, 4);
+ assert.equal((await stat(result.reportPath)).mode & 0o777, 0o600);
+}));
+test('first failure stops later steps but retains a report', () => fixture(async (root) => {
+ let count = 0;
+ const result = await runPipeline({ repo: root, expectedSha: sha, profile: 'verify', stateRoot: root }, { inspect, execute: async () => { count++; return { status: 'FAIL', exitCode: 1 }; } });
+ assert.equal(count, 1); assert.equal(result.exitCode, 1);
+ assert.deepEqual(result.report.steps.map((s) => s.status), ['FAIL', 'NOT_RUN', 'NOT_RUN', 'NOT_RUN']);
+}));
+test('blocked security never starts commands', () => fixture(async (root) => {
+ let calls = 0;
+ const result = await runPipeline({ repo: root, expectedSha: sha, profile: 'release', stateRoot: root }, { inspect, execute: async () => { calls++; return pass(); } });
+ assert.equal(calls, 0); assert.equal(result.exitCode, 2);
+ assert.equal(result.report.steps.filter((s) => s.status === 'BLOCKED').length, 6);
+}));
+test('preflight failure is persisted', () => fixture(async (root) => {
+ const result = await runPipeline({ repo: root, expectedSha: sha, profile: 'verify', stateRoot: root }, { inspect: async () => { throw new Error('Checkout is dirty'); } });
+ assert.equal(result.report.status, 'BLOCKED');
+ assert.match((await readFile(result.reportPath, 'utf8')), /Checkout is dirty/);
+}));
+test('actual Git preflight rejects wrong SHA and untracked edits', () => fixture(async (root) => {
+ const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+ git('init'); git('config', 'user.email', '[email protected]'); git('config', 'user.name', 'CI fixture');
+ await writeFile(join(root, 'one'), 'one'); git('add', 'one'); git('commit', '-m', 'fixture');
+ const head = git('rev-parse', 'HEAD'); assert.equal((await inspectRepository(root, head)).head, head);
+ await assert.rejects(inspectRepository(root, 'main'), /exact/);
+ await assert.rejects(inspectRepository(root, sha), /does not match/);
+ await writeFile(join(root, 'untracked'), 'two'); await assert.rejects(inspectRepository(root, head), /dirty/);
+}));
diff --git a/scripts/ci/plan.mjs b/scripts/ci/plan.mjs
new file mode 100644
index 00000000..ac59d3ae
--- /dev/null
+++ b/scripts/ci/plan.mjs
@@ -0,0 +1,27 @@
+/** Repository-owned CI policy; no webhook/PR-supplied commands. */
+const step = (id, command, args, timeoutMs) => ({ id, command, args, timeoutMs });
+const verify = [
+ step('native-module', 'node', ['-e', "require('node-pty')"], 30_000),
+ step('installer-bootstrap', 'bash', ['-n', 'scripts/install.sh'], 30_000),
+ step('installer-core', 'bash', ['-n', 'scripts/install-core.sh'], 30_000),
+ step('repository-gates', 'bash', ['scripts/gates.sh'], 30 * 60_000),
+];
+const security = [
+ { id: 'codeql', blocked: 'Local CodeQL bundle, security-extended analysis and exact-SHA SARIF adapter are not yet provisioned.' },
+ { id: 'security-core', blocked: 'Pinned Trivy/OSV/Gitleaks/Semgrep/ShellCheck adapter needs standalone end-to-end verification; preserve scripts/security-ultimate.sh.' },
+ { id: 'dependency-review', blocked: 'Base/head dependency-change review adapter is not yet verified.' },
+ { id: 'security-inventory', blocked: 'Exact-SHA SARIF upload/read-back through the authorized GitHub connection is not yet verified.' },
+ { id: 'scorecard', blocked: 'Standalone OpenSSF Scorecard adapter is not yet verified.' },
+ { id: 'dast', blocked: 'Explicit isolated staging target and ZAP evidence adapter are not yet verified.' },
+];
+export const profiles = Object.freeze(['verify', 'security', 'release']);
+export function planFor(profile) {
+ if (!profiles.includes(profile)) throw new Error('Profile must be verify, security, or release');
+ return structuredClone(profile === 'verify' ? verify : profile === 'security' ? security : [...verify, ...security]);
+}
+export function verdict(steps) {
+ if (steps.some((s) => s.status === 'FAIL')) return 'FAIL';
+ if (!steps.length || steps.some((s) => s.status !== 'PASS')) return 'BLOCKED';
+ return 'PASS';
+}
+export function exitFor(status) { return status === 'PASS' ? 0 : status === 'FAIL' ? 1 : 2; }
diff --git a/scripts/ci/process.mjs b/scripts/ci/process.mjs
new file mode 100644
index 00000000..05369c57
--- /dev/null
+++ b/scripts/ci/process.mjs
@@ -0,0 +1,62 @@
+import { spawn } from 'node:child_process';
+import { openSync, closeSync, writeSync } from 'node:fs';
+export function childEnvironment(source = process.env) {
+ const env = {};
+ for (const key of ['PATH', 'HOME', 'TMPDIR', 'LANG', 'LC_ALL', 'TZ', 'XDG_CACHE_HOME', 'XDG_STATE_HOME']) {
+ if (source[key]) env[key] = source[key];
+ }
+ return { ...env, CI: 'true', NEXT_TELEMETRY_DISABLED: '1' };
+}
+/** Fixed argv, private bounded logs, and whole-process-group timeout/cancellation. */
+export async function executeStep(step, { cwd, logPath, signal, maxBytes = 8 * 1024 * 1024 }) {
+ const started = Date.now();
+ const fd = openSync(logPath, 'wx', 0o600);
+ let bytes = 0, truncated = false, timedOut = false, cancelled = false;
+ try {
+ return await new Promise((resolve, reject) => {
+ const child = spawn(step.command, step.args, {
+ cwd, env: childEnvironment(), shell: false, detached: process.platform !== 'win32',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let finished = false, killTimer;
+ function kill(sig) {
+ try {
+ if (process.platform !== 'win32' && child.pid) process.kill(-child.pid, sig);
+ else child.kill(sig);
+ } catch (error) { if (error.code !== 'ESRCH') throw error; }
+ }
+ function stop() {
+ kill('SIGTERM');
+ killTimer = setTimeout(() => kill('SIGKILL'), 1500);
+ killTimer.unref();
+ }
+ const timer = setTimeout(() => { timedOut = true; stop(); }, step.timeoutMs);
+ const abort = () => { cancelled = true; stop(); };
+ signal?.addEventListener('abort', abort, { once: true });
+ if (signal?.aborted) abort();
+ function output(chunk) {
+ const available = Math.max(0, maxBytes - bytes);
+ const part = chunk.subarray(0, available);
+ if (part.length) writeSync(fd, part);
+ bytes += part.length;
+ if (chunk.length > available) truncated = true;
+ }
+ child.stdout.on('data', output); child.stderr.on('data', output);
+ function cleanup() {
+ clearTimeout(timer); clearTimeout(killTimer);
+ signal?.removeEventListener('abort', abort);
+ }
+ child.on('error', (error) => { if (!finished) { finished = true; cleanup(); reject(error); } });
+ child.on('close', (exitCode, exitSignal) => {
+ if (finished) return;
+ finished = true; cleanup();
+ kill('SIGKILL');
+ resolve({
+ status: timedOut || cancelled || truncated ? 'BLOCKED' : exitCode === 0 ? 'PASS' : 'FAIL',
+ exitCode, signal: exitSignal, timedOut, cancelled, logTruncated: truncated,
+ durationMs: Date.now() - started,
+ });
+ });
+ });
+ } finally { closeSync(fd); }
+}
diff --git a/scripts/ci/run.mjs b/scripts/ci/run.mjs
new file mode 100644
index 00000000..15f65c79
--- /dev/null
+++ b/scripts/ci/run.mjs
@@ -0,0 +1,32 @@
+#!/usr/bin/env node
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+import { parseArgs } from 'node:util';
+import { planFor } from './plan.mjs';
+import { runPipeline } from './runner.mjs';
+try {
+ const { values } = parseArgs({ options: {
+ plan: { type: 'boolean', default: false }, profile: { type: 'string', default: 'verify' },
+ sha: { type: 'string' }, repo: { type: 'string', default: process.cwd() },
+ }, strict: true, allowPositionals: false });
+ const plan = planFor(values.profile);
+ if (values.plan) {
+ console.log(JSON.stringify({ profile: values.profile, steps: plan, autoDeploy: false, githubActionsUsed: false }, null, 2));
+ } else {
+ if (!values.sha) throw new Error('--sha must be the exact committed SHA');
+ const controller = new AbortController();
+ const cancel = () => controller.abort();
+ process.once('SIGINT', cancel); process.once('SIGTERM', cancel);
+ const result = await runPipeline({
+ repo: values.repo, expectedSha: values.sha, profile: values.profile,
+ stateRoot: join(process.env.XDG_STATE_HOME || join(homedir(), '.local/state'), 'mso-ci'), signal: controller.signal,
+ });
+ process.removeListener('SIGINT', cancel); process.removeListener('SIGTERM', cancel);
+ console.log(JSON.stringify({
+ status: result.report.status, commit: result.report.commit ?? null, reportPath: result.reportPath,
+ releaseEligible: result.report.releaseEligible, batonlySync: result.report.batonlySync,
+ steps: result.report.steps.map(({ id, status }) => ({ id, status })), reason: result.report.reason,
+ }, null, 2));
+ process.exitCode = result.exitCode;
+ }
+} catch (error) { console.error(`CI: ${error.message}`); process.exitCode = 2; }
diff --git a/scripts/ci/runner.mjs b/scripts/ci/runner.mjs
new file mode 100644
index 00000000..0a516d6d
--- /dev/null
+++ b/scripts/ci/runner.mjs
@@ -0,0 +1,68 @@
+import { execFileSync } from 'node:child_process';
+import { realpath } from 'node:fs/promises';
+import { join } from 'node:path';
+import { planFor, verdict, exitFor } from './plan.mjs';
+import { executeStep, childEnvironment } from './process.mjs';
+import { createRun, saveReport, acquireLocks } from './store.mjs';
+function git(cwd, ...args) {
+ return execFileSync('git', args, { cwd, encoding: 'utf8', env: childEnvironment(), stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+}
+export async function inspectRepository(repo, expectedSha) {
+ if (!/^[a-f0-9]{40}$/.test(expectedSha)) throw new Error('An exact 40-character commit SHA is required');
+ const cwd = await realpath(repo);
+ if (await realpath(git(cwd, 'rev-parse', '--show-toplevel')) !== cwd) throw new Error('Run from the repository root');
+ const head = git(cwd, 'rev-parse', 'HEAD');
+ if (head !== expectedSha) throw new Error('HEAD does not match the requested SHA');
+ if (git(cwd, 'status', '--porcelain', '--untracked-files=all')) throw new Error('Checkout is dirty; commit or preserve changes before CI');
+ return { cwd, head, identity: await realpath(git(cwd, 'rev-parse', '--path-format=absolute', '--git-common-dir')) };
+}
+/** Trusted local CI only; never executes a webhook-supplied ref. */
+export async function runPipeline({ repo, expectedSha, profile, stateRoot, signal }, deps = {}) {
+ const steps = planFor(profile).map((step) => ({ ...step, status: 'NOT_RUN' }));
+ const run = await createRun(stateRoot);
+ const report = {
+ schemaVersion: 1, runId: run.runId, profile, expectedSha, startedAt: new Date().toISOString(),
+ status: 'BLOCKED', source: 'trusted-local-checkout', githubActionsUsed: false,
+ merged: false, deployed: false, verifiedLive: false, releaseEligible: false,
+ batonlySync: 'UNSYNCED', steps,
+ };
+ const inspect = deps.inspect ?? inspectRepository;
+ const execute = deps.execute ?? executeStep;
+ let release;
+ await saveReport(run.path, report);
+ try {
+ let target = await inspect(repo, expectedSha);
+ release = await acquireLocks(stateRoot, target.identity, run.runId);
+ target = await inspect(repo, expectedSha);
+ report.commit = target.head;
+ for (const step of steps) {
+ if (step.blocked) { step.status = 'BLOCKED'; step.reason = step.blocked; }
+ }
+ if (steps.some((step) => step.status === 'BLOCKED')) {
+ report.reason = 'Security migration incomplete. No selected commands executed; release remains blocked.';
+ } else {
+ for (const step of steps) {
+ if (signal?.aborted) { step.status = 'BLOCKED'; step.reason = 'Cancelled before execution'; break; }
+ await inspect(repo, expectedSha);
+ step.startedAt = new Date().toISOString();
+ await saveReport(run.path, report);
+ Object.assign(step, await execute(step, { cwd: target.cwd, logPath: join(run.path, `${step.id}.log`), signal }));
+ await saveReport(run.path, report);
+ if (step.status !== 'PASS') break;
+ }
+ await inspect(repo, expectedSha);
+ }
+ report.status = verdict(steps);
+ } catch (error) {
+ report.status = 'BLOCKED';
+ report.reason = error.code ? `Runner operation unavailable (${error.code})` : error.message;
+ } finally {
+ if (release) {
+ try { await release(); }
+ catch { report.status = 'BLOCKED'; report.reason = 'Runner lock cleanup failed; owner review required'; }
+ }
+ report.finishedAt = new Date().toISOString();
+ await saveReport(run.path, report);
+ }
+ return { report, reportPath: join(run.path, 'report.json'), exitCode: exitFor(report.status) };
+}
diff --git a/scripts/ci/store.mjs b/scripts/ci/store.mjs
new file mode 100644
index 00000000..7410a588
--- /dev/null
+++ b/scripts/ci/store.mjs
@@ -0,0 +1,53 @@
+import { createHash, randomUUID } from 'node:crypto';
+import { mkdir, lstat, open, writeFile, rename, readFile, unlink, rmdir } from 'node:fs/promises';
+import { join } from 'node:path';
+export async function privateDirectory(path) {
+ await mkdir(path, { recursive: true, mode: 0o700 });
+ const stat = await lstat(path);
+ if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o077) !== 0 || stat.uid !== process.getuid()) {
+ throw new Error('CI state must be an owner-private non-symlink directory');
+ }
+}
+export async function createRun(stateRoot) {
+ await privateDirectory(stateRoot);
+ const root = join(stateRoot, 'runs');
+ await privateDirectory(root);
+ const runId = randomUUID();
+ const path = join(root, runId);
+ await mkdir(path, { mode: 0o700 });
+ return { runId, path };
+}
+export async function saveReport(runPath, report) {
+ const tmp = join(runPath, `.report-${randomUUID()}.tmp`);
+ const handle = await open(tmp, 'wx', 0o600);
+ try { await handle.writeFile(`${JSON.stringify(report, null, 2)}\n`); await handle.sync(); }
+ finally { await handle.close(); }
+ await rename(tmp, join(runPath, 'report.json'));
+}
+export async function acquireLocks(stateRoot, repositoryIdentity, runId) {
+ const root = join(stateRoot, 'locks');
+ await privateDirectory(root);
+ const key = createHash('sha256').update(repositoryIdentity).digest('hex').slice(0, 32);
+ const owned = [];
+ async function release() {
+ for (const path of owned.reverse()) {
+ const owner = JSON.parse(await readFile(join(path, 'owner.json'), 'utf8'));
+ if (owner.runId !== runId) throw new Error('CI lock ownership changed; refusing cleanup');
+ await unlink(join(path, 'owner.json'));
+ await rmdir(path);
+ }
+ }
+ try {
+ for (const name of ['host', `repo-${key}`]) {
+ const path = join(root, name);
+ await mkdir(path, { mode: 0o700 });
+ await writeFile(join(path, 'owner.json'), JSON.stringify({ runId, pid: process.pid }), { flag: 'wx', mode: 0o600 });
+ owned.push(path);
+ }
+ return release;
+ } catch (error) {
+ await release();
+ if (error.code === 'EEXIST') throw new Error('CI runner lock busy; no job started. Stale locks require owner review.');
+ throw error;
+ }
+}