Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

ci: trace impact commands and the runner handoff (#13500)

Adam Eivyf19ef5c80016
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 6c935045f0..adb82e7493 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -34,6 +34,8 @@ jobs:
name: Plan test impact
runs-on: ubuntu-latest
timeout-minutes: 10
+ env:
+ PORTOS_CI_IMPACT_DIAGNOSTICS: ${{ runner.temp }}/portos-ci-impact
# Still live despite the removed push trigger: a called workflow inherits
# the caller's event, and release.yml calls this one from a push.
if: github.event_name != 'push' || !contains(github.event.head_commit.message, '[skip ci]')
@@ -95,13 +97,13 @@ jobs:
# A red impact job keeps CI Gate red; skipped test jobs are not evidence.
# Re-running this run is GitHub's writer-only, exact-SHA release control.
- name: Require maintainer release for Dependabot
- run: node scripts/ci-dependabot-admission.js
+ run: node scripts/ci-impact-diagnostics.js admission -- node scripts/ci-dependabot-admission.js
# Reads the base commit off HEAD^1 rather than the event payload, so a
# depth-2 clone is enough for every three-dot diff downstream. Exports
# CI_BASE_SHA to the rest of the job.
- name: Resolve the pull-request diff base
- run: node scripts/ci-base-sha.js
+ run: node scripts/ci-impact-diagnostics.js base -- node scripts/ci-base-sha.js
# Before any reviewer — human or model — reads this diff. Pattern
# matching over the added lines only: invisible Unicode and compressed or
@@ -109,14 +111,14 @@ jobs:
# approving it, so a hit fails the run rather than being reported. Every
# other job needs this one, so the whole suite stops here.
- name: Scan the diff for hidden content
- run: node scripts/scan-diff-hidden-content.js
+ run: node scripts/ci-impact-diagnostics.js hidden-content -- node scripts/scan-diff-hidden-content.js
# Linux resolves `./Foo.js` only as spelled; macOS and Windows do not. A
# pregate attestation lets a macOS run stand in for the Linux test jobs,
# so the one Linux-only failure it cannot see is checked here, on every
# pull request, before any job is skipped on its strength.
- name: Check relative imports match the tracked path case
- run: node scripts/check-import-case.js
+ run: node scripts/ci-impact-diagnostics.js import-case -- node scripts/check-import-case.js
- name: Select affected test surfaces
id: plan
@@ -140,7 +142,7 @@ jobs:
CI_PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
CI_PR_AUTHOR: ${{ github.event.pull_request.user.login }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- run: node scripts/ci-test-plan.js
+ run: node scripts/ci-impact-diagnostics.js plan -- node scripts/ci-test-plan.js
# The Node-minimum job proves the lockfiles install and the runtime gate
# loads on the oldest supported Node. Only these files can change that
@@ -151,12 +153,14 @@ jobs:
env:
CI_EVENT: ${{ github.event_name }}
run: |
+ node scripts/ci-impact-diagnostics.js node-minimum -- bash --noprofile --norc -e -o pipefail -s <<'PORTOS_IMPACT_SCRIPT'
pattern='^((server/|client/|autofixer/)?(package(-lock)?\.json|\.npmrc)|\.nvmrc|scripts/checkNodeVersion(\.test)?\.js|scripts/lib/directInvocation\.js|scripts/node-version-drift\.test\.js|\.github/workflows/ci\.yml)$'
if [ "$CI_EVENT" != pull_request ] || git diff --name-only "$CI_BASE_SHA"...HEAD | grep -qE "$pattern"; then
echo run=true >> "$GITHUB_OUTPUT"
else
echo run=false >> "$GITHUB_OUTPUT"
fi
+ PORTOS_IMPACT_SCRIPT
- name: Publish plan summary
env:
@@ -182,6 +186,7 @@ jobs:
SUITE_REASONS: ${{ steps.plan.outputs.suite_reasons }}
ATTESTATION: ${{ steps.plan.outputs.attestation }}
run: |
+ node scripts/ci-impact-diagnostics.js summary -- bash --noprofile --norc -e -o pipefail -s <<'PORTOS_IMPACT_SCRIPT'
{
echo "### CI impact plan"
echo
@@ -203,6 +208,7 @@ jobs:
echo "- Suite selection reasons: \`${SUITE_REASONS}\`"
echo "- Pregate attestation: \`${ATTESTATION}\`"
} >> "$GITHUB_STEP_SUMMARY"
+ PORTOS_IMPACT_SCRIPT
# `autofixer/` is a real install target — its own package.json, its own
# tracked lockfile, its own .npmrc — installed by `npm run setup` and by
@@ -224,11 +230,17 @@ jobs:
# scripts/trusted-rebuilds.js deliberately lists no rebuilds for this
# workspace, because nothing it depends on ships a native addon.
- name: Install autofixer dependencies
- run: npm ci --prefix autofixer
+ run: node scripts/ci-impact-diagnostics.js autofixer-install -- npm ci --prefix autofixer
# Same reason: the entry-point syntax check must not ride a skippable job.
- name: Check server entry-point syntax
- run: node --check server/index.js
+ run: node scripts/ci-impact-diagnostics.js syntax -- node --check server/index.js
+
+ # This precedes checkout post-actions and runner finalization; it cannot
+ # attest that the hosted runner acknowledged the completed job.
+ - name: Record impact process settlement
+ if: always()
+ run: node scripts/ci-impact-diagnostics.js settlement
prompt-history:
name: Shipped prompt history
diff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.md
index 7d6fd66c8d..d3a147426e 100644
--- a/docs/GITHUB_ACTIONS.md
+++ b/docs/GITHUB_ACTIONS.md
@@ -1406,3 +1406,68 @@ git push
2. Update installation and build commands for your project structure
3. For monorepos, add package.json update steps for each workspace
4. Update the changelog file path pattern if different
+
+### Impact job command and finalization evidence
+
+The `impact` job records the fixed stages `admission`, `base`, `hidden-content`,
+`import-case`, `plan`, `node-minimum`, `summary`, `autofixer-install`, and `syntax`
+through `scripts/ci-impact-diagnostics.js`. Each stage logs its start and direct
+child `exit`/`close` status and elapsed milliseconds. Its original stdout, GitHub
+command files, environment inputs and nonzero status pass through; a signal or
+spawn failure remains a failure. No additional provider calls or retries occur.
+
+A random marker inherited only by that stage's command lets Linux `/proc` scans
+count surviving same-user owned processes after close and at the final
+`always()` checkpoint. The scan is limited to 4,096 process entries and one second
+per snapshot. Public evidence contains only fixed stage names, numeric statuses,
+signals, elapsed time, counts and coverage. Markers, PIDs, host paths, environment
+values and raw command lines are not published. Private per-stage records stay
+under the runner's temporary directory; they are not uploaded as artifacts.
+
+`coverage=partial|unavailable`, missing records, or missing events mean unknown,
+not clean. Even complete coverage is a point-in-time observation of processes
+that retained their inherited marker; it cannot prove the absence of work that
+removed its marker. Nonzero owned counts are evidence to investigate, not
+permission to kill a process. The observer signals/deletes nothing and does not
+claim to repair an orphan. A settlement change needs a reproduced owner and a
+causal negative control first.
+
+The final checkpoint precedes checkout post-actions and the runner's own
+finalization. Interpret the first unconfirmed boundary in order: stage start →
+command exit → command close → owned-process snapshot → checkout post-action →
+runner `Complete job` → overall job result. A successful repository checkpoint
+cannot attest the later runner/result-service handoff. Keep the ten-minute impact
+timeout, fail-closed `CI Gate`, and real-job-timeout exclusion in cancel recovery.
+
+#### Retained investigation: #13500
+
+The [original attempt-1 impact job](https://github.com/atomantic/PortOS/actions/runs/40115698658/job/120936398030)
+ran head `9ce1866c45a5ae517b81a82bdc31e3cf4af395e9` on merge `47b63aa` with
+base `8b8ffd5e847a6dca5e5c10a479338c94d561195a`. Its planner ran
+17:21:02.180–17:21:02.977 UTC on 2026-10-24. Checkout post-cleanup and job output
+publication ended by 17:21:04.175; the final retained log line begins runner orphan
+cleanup. The job was cancelled at 17:34:22 with the ten-minute timeout annotation.
+
+Initial API reads returned no steps and some reads failed with HTTP 502. Fresh
+reads during this investigation returned successful conclusions for every step,
+including `Complete job`, completed at 17:21:04. That later evidence narrows the
+first unconfirmed boundary to completion of the runner/job-result handoff; the
+log line alone had left orphan cleanup unconfirmed. The API's successful timeline
+record does not prove the overall job result was accepted.
+
+The matching [runner v2.338.0 finalizer](https://github.com/actions/runner/blob/v2.338.0/src/Runner.Worker/JobExtension.cs)
+performs orphan inspection before completing the `Complete job` context. The
+[runner job completion path](https://github.com/actions/runner/blob/v2.338.0/src/Runner.Worker/JobRunner.cs)
+then drains its reporting queue and submits job completion. These source paths
+identify possible boundaries, not a demonstrated cause in this job. No retained
+runner transport trace or matching public GitHub Status incident establishes
+which operation failed. Neither a repository-created orphan nor a specific
+upstream incident has been proved.
+
+The [existing attempt-2 impact job](https://github.com/atomantic/PortOS/actions/runs/40115698658/job/120941724098)
+passed at the same head from 17:44:31–17:44:48. That is non-reproduction, not a
+cause-specific fix. The request to rerun attempt 1 with debugging was refused
+because it was no longer the current attempt; no further rerun was started.
+Preserve attempt 1. Future recurrence needs the fixed-stage evidence plus the
+runner's completion/queue/transport diagnostics, with sensitive fields redacted,
+before changing lifecycle behavior or attributing a GitHub incident.
diff --git a/scripts/check-import-case.test.js b/scripts/check-import-case.test.js
index 4ca92ac042..fd31ecbedb 100644
--- a/scripts/check-import-case.test.js
+++ b/scripts/check-import-case.test.js
@@ -139,7 +139,7 @@ describe('checkImportCase against a repository', () => {
it('is wired into the impact job before any job can be skipped on an attestation', () => {
const workflow = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', '.github', 'workflows', 'ci.yml'), 'utf8');
const impact = workflow.slice(workflow.indexOf('\n impact:\n'), workflow.indexOf('\n prompt-history:\n'));
- expect(impact).toContain('run: node scripts/check-import-case.js');
+ expect(impact).toContain('run: node scripts/ci-impact-diagnostics.js import-case -- node scripts/check-import-case.js');
expect(impact.indexOf('node scripts/check-import-case.js')).toBeLessThan(impact.indexOf('node scripts/ci-test-plan.js'));
});
});
diff --git a/scripts/ci-base-sha.test.js b/scripts/ci-base-sha.test.js
index 0d9552229c..a510e0452c 100644
--- a/scripts/ci-base-sha.test.js
+++ b/scripts/ci-base-sha.test.js
@@ -262,8 +262,8 @@ describe('ci.yml autofixer workspace install', () => {
// could skip that job; the impact job is the one that always runs, so the
// install and the `node --check` of the entry point moved there.
// Named, so the loop below is never vacuously green on a deleted step.
- expect(jobs.impact).toMatch(/- name: Install autofixer dependencies\n {8}run: npm ci --prefix autofixer/);
- expect(jobs.impact).toMatch(/- name: Check server entry-point syntax\n {8}run: node --check server\/index\.js/);
+ expect(jobs.impact).toMatch(/- name: Install autofixer dependencies\n {8}run: node scripts\/ci-impact-diagnostics\.js autofixer-install -- npm ci --prefix autofixer/);
+ expect(jobs.impact).toMatch(/- name: Check server entry-point syntax\n {8}run: node scripts\/ci-impact-diagnostics\.js syntax -- node --check server\/index\.js/);
// Shards are separate checkouts and run ../autofixer tests, which import
// express from autofixer/node_modules, so they install it too.
expect(jobs.server).toMatch(/- name: Install autofixer dependencies\n {8}run: npm ci --prefix autofixer/);
@@ -277,7 +277,7 @@ describe('ci.yml autofixer workspace install', () => {
// the hole straight back. It is cheap enough to pay on every plan.
for (const [id, body] of installers) {
const step = body.match(
- /- name: Install autofixer dependencies\n(?<between>(?: {8}.*\n)*?) {8}run: npm ci --prefix autofixer/,
+ /- name: Install autofixer dependencies\n(?<between>(?: {8}.*\n)*?) {8}run: (?:node scripts\/ci-impact-diagnostics\.js autofixer-install -- )?npm ci --prefix autofixer/,
);
expect(step, id).not.toBeNull();
expect(step.groups.between, id).not.toMatch(/^ {8}if:/m);
diff --git a/scripts/ci-impact-diagnostics.js b/scripts/ci-impact-diagnostics.js
new file mode 100644
index 0000000000..d41736dc0b
--- /dev/null
+++ b/scripts/ci-impact-diagnostics.js
@@ -0,0 +1,150 @@
+#!/usr/bin/env node
+
+import { spawn } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { performance } from 'node:perf_hooks';
+import { isDirectlyInvoked } from './lib/directInvocation.js';
+import { writeStepSummary } from './lib/githubOutput.js';
+
+export const IMPACT_STAGES = ['admission', 'base', 'hidden-content', 'import-case', 'plan', 'node-minimum', 'summary', 'autofixer-install', 'syntax'];
+const OWNER_KEY = 'PORTOS_CI_IMPACT_OWNER';
+const validToken = value => typeof value === 'string' && /^[\da-f-]{36}$/.test(value);
+const codeValue = value => Number.isInteger(value) && value >= 0 && value <= 255 ? value : null;
+const signalValue = value => /^SIG[A-Z0-9]{1,12}$/.test(value ?? '') ? value : null;
+
+// Observe same-user Linux processes without reading argv or publishing identity.
+// An inherited nonce establishes attribution; a missing/unreadable snapshot is
+// unknown, never zero. Processes that deliberately clear their env are not covered.
+export function scanImpactOwners(tokens, { procRoot = '/proc', platform = process.platform, uid = process.getuid?.(), budgetMs = 1000 } = {}) {
+ const counts = Object.fromEntries(tokens.map(token => [token, 0]));
+ let coverage = 'complete';
+ const start = performance.now();
+ if (platform !== 'linux' || !Number.isInteger(uid) || tokens.some(token => !validToken(token))) return { coverage: 'unavailable', counts: {} };
+ try {
+ const pids = readdirSync(procRoot).filter(name => /^\d+$/.test(name));
+ if (pids.length > 4096) return { coverage: 'unavailable', counts: {} };
+ for (const pid of pids) {
+ if (performance.now() - start > budgetMs) { coverage = 'partial'; break; }
+ const dir = join(procRoot, pid);
+ try {
+ if (statSync(dir).uid !== uid) continue;
+ const before = readFileSync(join(dir, 'stat'), 'utf8');
+ const fields = before.slice(before.lastIndexOf(')') + 2).split(' ');
+ if (fields.length < 20 || !/^\d+$/.test(fields[19])) { coverage = 'partial'; continue; }
+ if (['Z', 'X'].includes(fields[0])) continue;
+ const env = readFileSync(join(dir, 'environ'));
+ const after = readFileSync(join(dir, 'stat'), 'utf8');
+ if (before.slice(before.lastIndexOf(')') + 2).split(' ')[19] !== after.slice(after.lastIndexOf(')') + 2).split(' ')[19]) {
+ coverage = 'partial'; continue;
+ }
+ for (const token of tokens) {
+ const marker = Buffer.from(`${OWNER_KEY}=${token}\0`);
+ const index = env.indexOf(marker);
+ if (index === 0 || (index > 0 && env[index - 1] === 0)) counts[token]++;
+ }
+ } catch (error) {
+ // Disappearance during the snapshot is normal. Permission/I/O gaps are not.
+ if (!['ENOENT', 'ESRCH'].includes(error.code)) coverage = 'partial';
+ }
+ }
+ return { coverage, counts };
+ } catch { return { coverage: 'unavailable', counts: {} }; }
+}
+
+function persist(root, stage, value) {
+ try {
+ mkdirSync(root, { recursive: true, mode: 0o700 });
+ const path = join(root, `${stage}.json`);
+ writeFileSync(`${path}.tmp`, JSON.stringify(value), { mode: 0o600 });
+ renameSync(`${path}.tmp`, path);
+ return true;
+ } catch { return false; }
+}
+
+function evidence(stage, boundary, values, log = console.log) {
+ log(`CI impact ${JSON.stringify({ stage, boundary, ...values })}`);
+}
+
+// Child output and GitHub command files pass through unchanged. These records
+// observe the direct command's events; they do not claim runner/job completion.
+export async function observeImpactStage(stage, command, args, {
+ root = process.env.PORTOS_CI_IMPACT_DIAGNOSTICS, env = process.env,
+ scan = scanImpactOwners, log = console.log,
+} = {}) {
+ if (!IMPACT_STAGES.includes(stage) || !command) throw Error('Invalid impact stage invocation.');
+ const token = randomUUID();
+ const startedAt = Date.now();
+ const start = performance.now();
+ const elapsedMs = () => Math.round(performance.now() - start);
+ const state = { stage, token, startedAt, exit: null, close: null };
+ const save = () => evidence(stage, 'persist', { recorded: persist(root, stage, state) }, log);
+ save();
+ evidence(stage, 'start', { elapsedMs: 0 }, log);
+ const child = spawn(command, args, { env: { ...env, [OWNER_KEY]: token }, stdio: 'inherit', shell: false });
+ const result = await new Promise(resolve => {
+ child.once('error', () => evidence(stage, 'spawn-error', { elapsedMs: elapsedMs() }, log));
+ child.once('exit', (code, signal) => {
+ state.exit = { code: codeValue(code), signal: signalValue(signal), elapsedMs: elapsedMs() };
+ save();
+ evidence(stage, 'exit', state.exit, log);
+ });
+ child.once('close', (code, signal) => {
+ state.close = { code: codeValue(code), signal: signalValue(signal), elapsedMs: elapsedMs() };
+ const snapshot = scan([token]);
+ state.ownedAfterClose = { coverage: snapshot.coverage, count: snapshot.counts[token] ?? null };
+ save();
+ evidence(stage, 'close', { ...state.close, owned: state.ownedAfterClose.count, coverage: snapshot.coverage }, log);
+ resolve({ code: codeValue(code), signal: signalValue(signal) });
+ });
+ });
+ return result;
+}
+
+export function reportImpactSettlement(root, { scan = scanImpactOwners, log = console.log, summary = writeStepSummary } = {}) {
+ const records = IMPACT_STAGES.map(stage => {
+ try {
+ const path = join(root, `${stage}.json`);
+ if (statSync(path).size > 4096) throw Error('oversized');
+ const record = JSON.parse(readFileSync(path, 'utf8'));
+ if (record.stage !== stage || !validToken(record.token)) throw Error('invalid');
+ return record;
+ } catch { return { stage }; }
+ });
+ const tokens = records.map(record => record.token).filter(Boolean);
+ const snapshot = scan(tokens);
+ const lines = ['### Impact command settlement', '', 'This checkpoint precedes checkout post-actions and runner finalization.'];
+ for (const record of records) {
+ const row = {
+ recorded: Boolean(record.token),
+ exit: codeValue(record.exit?.code), close: codeValue(record.close?.code),
+ signal: signalValue(record.close?.signal),
+ owned: record.token ? snapshot.counts[record.token] ?? null : null,
+ coverage: record.token ? snapshot.coverage : 'unavailable',
+ };
+ evidence(record.stage, 'settlement', row, log);
+ lines.push(`- ${record.stage}: recorded=${row.recorded}; exit=${row.exit}; close=${row.close}; signal=${row.signal}; owned=${row.owned}; coverage=${row.coverage}.`);
+ }
+ lines.push('', 'Unknown/missing evidence is not proof of settlement. No processes were signalled or deleted.');
+ try { summary(lines.join('\n')); }
+ catch { evidence('settlement', 'summary-unavailable', {}, log); }
+ return records;
+}
+
+async function main() {
+ const [stage, separator, command, ...args] = process.argv.slice(2);
+ if (stage === 'settlement' && separator === undefined) {
+ reportImpactSettlement(process.env.PORTOS_CI_IMPACT_DIAGNOSTICS);
+ return;
+ }
+ if (separator !== '--') throw Error('Invalid impact stage invocation.');
+ const result = await observeImpactStage(stage, command, args);
+ // A signal/spawn failure must stay red; never infer success from a null code.
+ process.exitCode = result.code ?? 1;
+}
+
+if (isDirectlyInvoked(import.meta.url)) main().catch(() => {
+ console.error('CI impact diagnostics invocation failed.');
+ process.exitCode = 1;
+});
diff --git a/scripts/ci-impact-diagnostics.test.js b/scripts/ci-impact-diagnostics.test.js
new file mode 100644
index 0000000000..a7d3394d23
--- /dev/null
+++ b/scripts/ci-impact-diagnostics.test.js
@@ -0,0 +1,163 @@
+import { spawnSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { connect } from 'node:net';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { afterEach, describe, expect, it } from 'vitest';
+import { IMPACT_STAGES, observeImpactStage, reportImpactSettlement, scanImpactOwners } from './ci-impact-diagnostics.js';
+import { workflowJobs } from './lib/workflowJobs.js';
+
+const roots = [];
+const root = () => {
+ const dir = mkdtempSync(join(tmpdir(), 'impact-diagnostics-'));
+ roots.push(dir);
+ return dir;
+};
+afterEach(() => roots.splice(0).forEach(dir => rmSync(dir, { recursive: true, force: true })));
+const launcher = fileURLToPath(new URL('./ci-impact-diagnostics.js', import.meta.url));
+
+it('preserves command output, failure status, and GitHub command files through the actual CLI', () => {
+ const dir = root();
+ const output = join(dir, 'output');
+ const result = spawnSync(process.execPath, [launcher, 'plan', '--', process.execPath, '-e', `
+ require('node:fs').appendFileSync(process.env.GITHUB_OUTPUT, 'server_files=["example.test.js"]\\n');
+ console.log('original-output'); process.exitCode = 17;
+ `], { encoding: 'utf8', timeout: 10_000, env: { ...process.env, PORTOS_CI_IMPACT_DIAGNOSTICS: dir, GITHUB_OUTPUT: output } });
+ expect(result.error).toBeUndefined();
+ expect(result.status, result.stderr).toBe(17);
+ expect(result.stdout).toContain('original-output');
+ expect(readFileSync(output, 'utf8')).toBe('server_files=["example.test.js"]\n');
+ const record = JSON.parse(readFileSync(join(dir, 'plan.json'), 'utf8'));
+ expect(record).toMatchObject({ stage: 'plan', exit: { code: 17 }, close: { code: 17 } });
+ expect(record.exit.elapsedMs).toBeLessThanOrEqual(record.close.elapsedMs);
+ expect(result.stdout).not.toContain(record.token);
+});
+
+it('retains interrupted and missing evidence as unknown, and redacts persisted untrusted metadata', () => {
+ const dir = root();
+ const token = randomUUID();
+ writeFileSync(join(dir, 'plan.json'), JSON.stringify({
+ stage: 'plan', token, exit: { code: 0 }, close: null,
+ privatePath: '/home/example-private/secret', rawCommand: 'SECRET_SENTINEL',
+ }));
+ writeFileSync(join(dir, 'syntax.json'), '{broken');
+ const lines = [];
+ const summaries = [];
+ reportImpactSettlement(dir, {
+ scan: () => ({ coverage: 'partial', counts: {} }),
+ log: line => lines.push(line), summary: text => summaries.push(text),
+ });
+ const rows = lines.map(line => JSON.parse(line.slice('CI impact '.length)));
+ expect(rows.find(row => row.stage === 'plan')).toMatchObject({ recorded: true, exit: 0, close: null, owned: null, coverage: 'partial' });
+ expect(rows.find(row => row.stage === 'syntax')).toMatchObject({ recorded: false, owned: null, coverage: 'unavailable' });
+ const publicText = [...lines, ...summaries].join('\n');
+ for (const secret of [token, '/home/example-private', 'SECRET_SENTINEL']) expect(publicText).not.toContain(secret);
+});
+
+it('does not turn a spawn failure or signal into a successful command', async () => {
+ const dir = root();
+ const lines = [];
+ const options = { root: dir, log: line => lines.push(line) };
+ const missing = await observeImpactStage('plan', join(dir, 'missing'), [], options);
+ expect(missing).toEqual({ code: null, signal: null });
+ expect(lines.some(line => line.includes('spawn-error'))).toBe(true);
+ const result = spawnSync(process.execPath, [launcher, 'syntax', '--', process.execPath, '-e', 'process.kill(process.pid, "SIGTERM")'], {
+ encoding: 'utf8', timeout: 10_000, env: { ...process.env, PORTOS_CI_IMPACT_DIAGNOSTICS: dir },
+ });
+ expect(result.error).toBeUndefined();
+ expect(result.status).not.toBe(0);
+});
+
+describe('ownership snapshot', () => {
+ it('matches an exact inherited nonce, excludes zombies/unrelated work, and reports unreadable scans', () => {
+ const dir = root();
+ const token = randomUUID();
+ const put = (pid, env, state = 'S') => {
+ const path = join(dir, String(pid));
+ mkdirSync(path);
+ writeFileSync(join(path, 'stat'), `${pid} (private command) ${state} ${Array(18).fill('0').join(' ')} 123 0 0\n`);
+ writeFileSync(join(path, 'environ'), env);
+ };
+ put(1, `SECRET_SENTINEL=x\0PORTOS_CI_IMPACT_OWNER=${token}\0`);
+ put(2, `PORTOS_CI_IMPACT_OWNER=${randomUUID()}\0`);
+ put(3, `PORTOS_CI_IMPACT_OWNER=${token}\0`, 'Z');
+ put(4, `OTHER_PORTOS_CI_IMPACT_OWNER=${token}\0`);
+ const options = { procRoot: dir, platform: 'linux', uid: statSync(dir).uid };
+ expect(scanImpactOwners([token], options)).toEqual({ coverage: 'complete', counts: { [token]: 1 } });
+ expect(scanImpactOwners([token], { ...options, budgetMs: -1 }).coverage).toBe('partial');
+ expect(scanImpactOwners([token], { ...options, procRoot: join(dir, 'missing') })).toEqual({ coverage: 'unavailable', counts: {} });
+ expect(scanImpactOwners([token], { ...options, platform: 'darwin' }).coverage).toBe('unavailable');
+ });
+
+ // A successful direct exit must not hide a reparented descendant. The
+ // fixture settles only its own socket-controlled child; no process is killed.
+ it.skipIf(process.platform !== 'linux')('detects owned work surviving its stage, then its real settlement', async () => {
+ const dir = root();
+ const socket = join(dir, 'owned.sock');
+ const worker = `
+ const server = require('node:net').createServer(connection => {
+ connection.end(); server.close();
+ });
+ server.listen(${JSON.stringify(socket)}, () => process.send('ready'));
+ `;
+ const parent = `
+ const child = require('node:child_process').spawn(process.execPath, ['-e', ${JSON.stringify(worker)}], {
+ detached: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'], env: process.env,
+ });
+ child.once('message', () => { child.disconnect(); child.unref(); });
+ `;
+ try {
+ const result = await observeImpactStage('plan', process.execPath, ['-e', parent], { root: dir, log: () => {} });
+ expect(result).toEqual({ code: 0, signal: null });
+ const record = JSON.parse(readFileSync(join(dir, 'plan.json'), 'utf8'));
+ expect(record.ownedAfterClose.count).toBe(1);
+ const lines = [];
+ reportImpactSettlement(dir, { log: line => lines.push(line), summary: () => {} });
+ expect(lines.find(line => line.includes('"stage":"plan"'))).toContain('"owned":1');
+ } finally {
+ await new Promise((resolve, reject) => {
+ const connection = connect(socket);
+ connection.once('error', reject);
+ connection.once('close', resolve);
+ connection.resume();
+ });
+ }
+ const record = JSON.parse(readFileSync(join(dir, 'plan.json'), 'utf8'));
+ let snapshot;
+ const deadline = Date.now() + 5000;
+ do {
+ snapshot = scanImpactOwners([record.token]);
+ if (snapshot.counts[record.token] === 0) break;
+ await new Promise(resolve => setTimeout(resolve, 10));
+ } while (Date.now() < deadline);
+ expect(snapshot.counts[record.token]).toBe(0);
+ });
+});
+
+it('observes every repository stage before runner finalization while retaining the existing deadline and gate', () => {
+ const jobs = workflowJobs(readFileSync(new URL('../.github/workflows/ci.yml', import.meta.url), 'utf8'));
+ for (const stage of IMPACT_STAGES) expect(jobs.impact).toContain(`node scripts/ci-impact-diagnostics.js ${stage} -- `);
+ expect(jobs.impact).toMatch(/timeout-minutes: 10\n/);
+ expect(jobs.impact).toContain('if: always()\n run: node scripts/ci-impact-diagnostics.js settlement');
+ expect(jobs.impact).not.toMatch(/continue-on-error/);
+ expect(jobs.gate).toContain('CI_GATE_RESULT_IMPACT: ${{ needs.impact.result }}');
+ // Exercise both actual heredoc scripts; a malformed delimiter can silently
+ // swallow a shell command or change which GitHub outputs reach later jobs.
+ if (process.platform === 'win32') return;
+ const dir = root();
+ for (const stage of ['node-minimum', 'summary']) {
+ const script = jobs.impact.match(new RegExp(` (node scripts/ci-impact-diagnostics\\.js ${stage} -- [^\\n]+\\n[\\s\\S]*? PORTOS_IMPACT_SCRIPT)\\n`))?.[1];
+ expect(script, stage).toBeTruthy();
+ const result = spawnSync('bash', ['--noprofile', '--norc', '-e', '-o', 'pipefail', '-s'], {
+ input: script.split('\n').map(line => line.slice(line.startsWith(' ') ? 10 : 0)).join('\n'),
+ cwd: fileURLToPath(new URL('../', import.meta.url)), encoding: 'utf8', timeout: 10_000,
+ env: { ...process.env, CI_EVENT: 'workflow_dispatch', PORTOS_CI_IMPACT_DIAGNOSTICS: dir,
+ GITHUB_OUTPUT: join(dir, 'output'), GITHUB_STEP_SUMMARY: join(dir, 'summary') },
+ });
+ expect(result.status, result.stderr).toBe(0);
+ }
+ expect(readFileSync(join(dir, 'output'), 'utf8')).toBe('run=true\n');
+ expect(readFileSync(join(dir, 'summary'), 'utf8')).toContain('### CI impact plan');
+});
diff --git a/scripts/ci-test-plan.test.js b/scripts/ci-test-plan.test.js
index 0664e59068..25ba3601e5 100644
--- a/scripts/ci-test-plan.test.js
+++ b/scripts/ci-test-plan.test.js
@@ -2561,7 +2561,7 @@ describe('pregate attestation', () => {
const jobs = workflowJobs(readFileSync(join(repo, '.github/workflows/ci.yml'), 'utf8'));
// Reading statuses needs the scope; nothing in the impact job may write one.
expect(jobs.impact).toMatch(/\n permissions:\n contents: read\n statuses: read\n/);
- const planStep = jobs.impact.slice(jobs.impact.indexOf('id: plan'), jobs.impact.indexOf('run: node scripts/ci-test-plan.js'));
+ const planStep = jobs.impact.slice(jobs.impact.indexOf('id: plan'), jobs.impact.indexOf('run: node scripts/ci-impact-diagnostics.js plan -- node scripts/ci-test-plan.js'));
for (const line of [
"CI_EVENT_NAME: ${{ github.event_name }}",
'CI_REPOSITORY: ${{ github.repository }}',
diff --git a/scripts/pre-install-entrypoints.test.js b/scripts/pre-install-entrypoints.test.js
index 857c4c918c..2ff23a4fb7 100644
--- a/scripts/pre-install-entrypoints.test.js
+++ b/scripts/pre-install-entrypoints.test.js
@@ -26,6 +26,7 @@ const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
/** Run by the CI `impact` job before any dependency install. */
const PRE_INSTALL_ENTRYPOINTS = [
+ 'scripts/ci-impact-diagnostics.js',
'scripts/ci-dependabot-admission.js',
'scripts/ci-base-sha.js',
'scripts/ci-test-plan.js',