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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: reclaim interrupted pregate report directories (#9804)
[._.]/ Adam Eivy69ea2ec25ad9
diff --git a/scripts/lib/vitestStaleRunRoots.js b/scripts/lib/vitestStaleRunRoots.jsindex 30661271c1..c48ad0bd6d 100644--- a/scripts/lib/vitestStaleRunRoots.js+++ b/scripts/lib/vitestStaleRunRoots.js@@ -1,16 +1,16 @@/**- * Owner-aware sweep of `pvt-*` run-scoped temp roots (#9113).+ * Owner-aware sweep of run-scoped temp roots (#9113, #9804).*- * `vitest.config.js` mints one root per run and stamps `.owner.pid` in it. A+ * Workspace configs and the CI launcher stamp `.owner.pid` in each root. A* killed run never reaches `teardown()` in `runTempRoot.js`, so its root is* left behind; the next config load calls `sweepStaleRunRoots()` to reclaim- * it. A recorded owner that is provably gone frees the root immediately, an+ * it for the caller's exact prefix (default `pvt-`). A recorded owner that is provably gone frees the root immediately, an* owner that is alive keeps it however old it is (a >6h run must not be swept* from under itself), and a root whose owner cannot be determined falls back* to the conservative 6h age rule.*/import { execFileSync } from 'node:child_process';-import { readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { lstatSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';export const OWNER_FILE = '.owner.pid';@@ -68,7 +68,11 @@ function readOwner(path) {}}-export function sweepStaleRunRoots(tmpRoot, { now = Date.now(), probe = isOwnerAlive } = {}) {+export function sweepStaleRunRoots(tmpRoot, { prefix = 'pvt-', now = Date.now(), probe = isOwnerAlive } = {}) {+ // Require an exact directory-name prefix, never a path or an empty match.+ if (typeof prefix !== 'string' || !/^[a-zA-Z0-9-]+-$/.test(prefix)) {+ throw new Error('Owned temp prefix must be a nonempty name ending in a hyphen');+ }let names;try {names = readdirSync(tmpRoot);@@ -76,10 +80,10 @@ export function sweepStaleRunRoots(tmpRoot, { now = Date.now(), probe = isOwnerAreturn; // unreadable tmp dir — skip rather than fail config load}for (const name of names) {- if (!name.startsWith('pvt-')) continue;+ if (!name.startsWith(prefix)) continue;const path = join(tmpRoot, name);try {- const stat = statSync(path);+ const stat = lstatSync(path);if (!stat.isDirectory()) continue;const owner = readOwner(path);const alive = owner ? probe(owner) : null;diff --git a/scripts/run-ci-tests.js b/scripts/run-ci-tests.jsindex 297409efe4..437f9e0349 100644--- a/scripts/run-ci-tests.js+++ b/scripts/run-ci-tests.js@@ -6,8 +6,9 @@ import { tmpdir } from 'node:os';import { stripVTControlCharacters } from 'node:util';import { dirname, join } from 'path';import { fileURLToPath } from 'url';-import { prepareCliSpawn } from '../server/lib/bufferedSpawn.js';+import { killProcessTree, prepareCliSpawn } from '../server/lib/bufferedSpawn.js';import { isDirectlyInvoked } from './lib/directInvocation.js';+import { sweepStaleRunRoots, writeOwnerFile } from './lib/vitestStaleRunRoots.js';import { writeStepEnv, writeStepSummary } from './lib/githubOutput.js';const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..');@@ -170,12 +171,15 @@ export function structuredFailureDiagnostics(reportPath) {* stderr live (so a long CI job keeps showing progress) while also retaining* a bounded tail of the combined output for post-run crash detection.*- * @returns {Promise<{status: number, output: string, error?: Error}>}+ * @returns {Promise<{status: number, output: string, interrupted?: NodeJS.Signals, error?: Error}>}*/export async function runNpm(scope, script, extraArgs) {- const reportDir = mkdtempSync(join(tmpdir(), 'portos-vitest-'));+ const hostRoot = tmpdir();+ sweepStaleRunRoots(hostRoot, { prefix: 'portos-vitest-' });+ const reportDir = mkdtempSync(join(hostRoot, 'portos-vitest-'));const reportPath = join(reportDir, 'failures.json');try {+ writeOwnerFile(reportDir);return await runNpmWithReport(scope, script, extraArgs, reportPath);} finally {rmSync(reportDir, { recursive: true, force: true });@@ -190,7 +194,25 @@ function runNpmWithReport(scope, script, extraArgs, reportPath) {// Windows checkout. See server/lib/bufferedSpawn.js.const { command, args: spawnArgs } = prepareCliSpawn('npm', args);return new Promise((resolve) => {- const child = spawn(command, spawnArgs, { env: process.env, cwd: repoRoot });+ // npm is a launcher, not the entire test tree. Give this invocation its+ // own POSIX group; Windows killProcessTree uses taskkill /T instead.+ const processGroup = process.platform !== 'win32';+ const child = spawn(command, spawnArgs, { env: process.env, cwd: repoRoot, detached: processGroup });+ let interrupted;+ let escalation;+ let spawnError;+ const cancel = (signal) => {+ if (interrupted) return;+ interrupted = signal;+ killProcessTree(child, signal, { processGroup });+ escalation = setTimeout(() => {+ killProcessTree(child, 'SIGKILL', { processGroup });+ }, 2000);+ };+ const onSigint = () => cancel('SIGINT');+ const onSigterm = () => cancel('SIGTERM');+ process.on('SIGINT', onSigint);+ process.on('SIGTERM', onSigterm);let output = '';const tee = (stream, chunk) => {stream.write(chunk);@@ -198,10 +220,20 @@ function runNpmWithReport(scope, script, extraArgs, reportPath) {};child.stdout.on('data', (chunk) => tee(process.stdout, chunk));child.stderr.on('data', (chunk) => tee(process.stderr, chunk));- child.on('error', (error) => resolve({ status: 1, output, error }));+ // A spawn error also emits close. Settle only there, after the pipes close.+ child.on('error', (error) => { spawnError = error; });child.on('close', (code) => {- if (code !== 0) console.error(structuredFailureDiagnostics(reportPath));- resolve({ status: code ?? 1, output });+ clearTimeout(escalation);+ if (interrupted) {+ // npm may close before a descendant that detached its stdio. Finish+ // the owned group as well, including children that ignored SIGTERM.+ killProcessTree(child, 'SIGKILL', { processGroup });+ }+ process.removeListener('SIGINT', onSigint);+ process.removeListener('SIGTERM', onSigterm);+ const status = interrupted ? (interrupted === 'SIGINT' ? 130 : 143) : code ?? 1;+ if (status !== 0) console.error(structuredFailureDiagnostics(reportPath));+ resolve({ status, output, ...(interrupted ? { interrupted } : {}), ...(spawnError ? { error: spawnError } : {}) });});});}@@ -216,6 +248,7 @@ async function spawnNpm(scope, script, extraArgs, label) {return 1;}if (result.status === 0) return 0;+ if (result.interrupted) return result.status;const plan = planCrashRetry(scope, result.output);if (!plan.retry) {diff --git a/scripts/run-ci-tests.test.js b/scripts/run-ci-tests.test.jsindex bd8977065b..64861821e3 100644--- a/scripts/run-ci-tests.test.js+++ b/scripts/run-ci-tests.test.js@@ -1,5 +1,5 @@-import { spawnSync } from 'node:child_process';-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { spawn, spawnSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { afterEach, describe, expect, it } from 'vitest';@@ -16,8 +16,19 @@ import {shardArgs,toRunnerPath,} from './run-ci-tests.js';+import { killProcessTree } from '../server/lib/bufferedSpawn.js';+import { OWNER_FILE, STALE_ROOT_AGE_MS } from './lib/vitestStaleRunRoots.js';import { workflowJobs } from './lib/workflowJobs.js';+// Keep nested Vitest's own scratch under its separately owned pvt-* root,+// just like the workspace configs; reporter diagnostics stay outside it.+const FIXTURE_CONFIG = `+ import { bootstrapVitestTempRoot } from ${JSON.stringify(new URL('./lib/vitestTempRoot.js', import.meta.url).href)};+ bootstrapVitestTempRoot();+ export default { test: { globals: true, maxWorkers: 1, testTimeout: 60000,+ globalSetup: [${JSON.stringify(new URL('./vitestTempRootSetup.js', import.meta.url).href)}] } };+`;+const WORKFLOW = readFileSync(join(import.meta.dirname, '..', '.github', 'workflows', 'ci.yml'), 'utf8');describe('shardArgs', () => {@@ -255,20 +266,25 @@ describe('structured failure diagnostics', () => {it('recovers a real bail failure with default and GitHub reporters even if their summary is incomplete', () => {const fixture = mkdtempSync(join(tmpdir(), 'portos-diagnostics-'));try {+ const host = join(fixture, 'host');+ mkdirSync(host);const report = join(fixture, 'report.json');writeFileSync(join(fixture, 'fixture.test.js'),"test('synthetic assertion diagnostic', () => { expect(1, 'synthetic mismatch').toBe(2); });");writeFileSync(join(fixture, 'vitest.config.mjs'),- 'export default { test: { globals: true, maxWorkers: 1 } };');+ FIXTURE_CONFIG);const runnerUrl = new URL('./run-ci-tests.js', import.meta.url).href;const args = ['--config', join(fixture, 'vitest.config.mjs'), '--root', fixture, './fixture.test.js'];+ const env = { ...process.env, NODE_ENV: 'test', TMPDIR: host, TMP: host, TEMP: host, NODE_DISABLE_COMPILE_CACHE: '1' };+ delete env.PORTOS_TEST_TEMP_ROOT;const result = spawnSync(process.execPath, ['--input-type=module', '-e',`import { runNpm } from ${JSON.stringify(runnerUrl)};const result = await runNpm('server', 'test:ci:related', ${JSON.stringify(args)});process.exitCode = result.status;`,- ], { encoding: 'utf8', timeout: 30_000, env: { ...process.env, NODE_ENV: 'test' } });+ ], { encoding: 'utf8', timeout: 30_000, env });expect(result.error).toBeUndefined();expect(result.status).toBe(1);+ expect(readdirSync(host)).toEqual([]);expect(result.stdout).toContain('Test Files');expect(result.stdout).toContain('Tests');expect(result.stderr).toContain('Failed Tests');@@ -287,3 +303,160 @@ describe('structured failure diagnostics', () => {}}, 35_000);});++describe('report launcher subprocess lifecycle (#9804)', () => {+ const runnerUrl = new URL('./run-ci-tests.js', import.meta.url).href;++ function launch(host, name, { blocking = false } = {}) {+ const fixture = join(host, name);+ mkdirSync(fixture);+ const ready = join(fixture, 'ready.json');+ writeFileSync(join(fixture, 'vitest.config.mjs'),+ FIXTURE_CONFIG);+ writeFileSync(join(fixture, 'fixture.test.js'), blocking ? `+ import { spawn, execFileSync } from 'node:child_process';+ import { renameSync, writeFileSync } from 'node:fs';+ test('blocking fixture', async () => {+ // A descendant that ignores graceful signals must be escalated too.+ const descendant = spawn(process.execPath, ['-e',+ "process.on('SIGTERM', () => {}); process.on('SIGINT', () => {}); setInterval(() => {}, 1000); process.send('ready');"],+ { stdio: ['ignore', 'ignore', 'ignore', 'ipc'] });+ await new Promise(resolve => descendant.once('message', resolve));+ writeFileSync(${JSON.stringify(ready + '.tmp')}, JSON.stringify({ worker: process.pid, descendant: descendant.pid,+ group: process.platform === 'win32' ? null : Number(execFileSync('ps', ['-o', 'pgid=', '-p', String(process.pid)], { encoding: 'utf8' }).trim()) }));+ renameSync(${JSON.stringify(ready + '.tmp')}, ${JSON.stringify(ready)});+ await new Promise(() => {});+ });` : "test('success fixture', () => { expect(true).toBe(true); });");+ const args = ['--config', join(fixture, 'vitest.config.mjs'), '--root', fixture, './fixture.test.js'];+ const env = { ...process.env, TMPDIR: host, TMP: host, TEMP: host, NODE_ENV: 'test', NODE_DISABLE_COMPILE_CACHE: '1' };+ delete env.PORTOS_TEST_TEMP_ROOT;+ const child = spawn(process.execPath, ['--input-type=module', '-e', `+ import { runNpm } from ${JSON.stringify(runnerUrl)};+ const result = await runNpm('server', 'test:ci:related', ${JSON.stringify(args)});+ process.exitCode = result.status;`], { env, stdio: ['ignore', 'pipe', 'pipe'] });+ let output = '';+ child.stdout.on('data', chunk => { output += chunk; });+ child.stderr.on('data', chunk => { output += chunk; });+ const closed = new Promise((resolve, reject) => {+ const timeout = setTimeout(() => {+ if (existsSync(ready)) {+ const pids = JSON.parse(readFileSync(ready, 'utf8'));+ if (pids.group) killProcessTree({ pid: pids.group }, 'SIGKILL', { processGroup: true });+ }+ killProcessTree(child, 'SIGKILL');+ reject(Error('report launcher exceeded its subprocess budget'));+ }, 40000);+ child.once('error', error => { clearTimeout(timeout); reject(error); });+ child.once('close', (code, signal) => {+ clearTimeout(timeout);+ resolve({ code, signal, output });+ });+ });+ return { child, closed, ready };+ }++ async function waitFor(check, message) {+ const deadline = Date.now() + 15000;+ while (!check()) {+ if (Date.now() > deadline) throw Error(message);+ await new Promise(resolve => setTimeout(resolve, 25));+ }+ }++ function ownedRoot(host, pid) {+ return readdirSync(host).filter(name => name.startsWith('portos-vitest-'))+ .map(name => join(host, name))+ .filter(root => existsSync(join(root, OWNER_FILE)))+ .find(root => readFileSync(join(root, OWNER_FILE), 'utf8').startsWith(`${pid} `));+ }++ function alive(pid) {+ try { process.kill(pid, 0); return true; }+ catch (error) { if (error.code === 'ESRCH') return false; throw error; }+ }++ // Windows cannot deliver POSIX SIGINT/SIGTERM to a Node process; ordinary+ // outcomes and recovery below still exercise its real npm.cmd boundary.+ describe.skipIf(process.platform === 'win32')('graceful signals', () => {+ for (const signal of ['SIGINT', 'SIGTERM']) {+ it(`${signal} fails the stage, stops descendants, and removes the report root`, async () => {+ const host = mkdtempSync(join(tmpdir(), 'rcl-'));+ let run;+ let pids;+ try {+ run = launch(host, 'cancel', { blocking: true });+ await waitFor(() => existsSync(run.ready), 'test worker did not start');+ pids = JSON.parse(readFileSync(run.ready, 'utf8'));+ expect(ownedRoot(host, run.child.pid)).toBeTruthy();+ run.child.kill(signal);+ const result = await run.closed;+ expect(result.code, result.output).toBe(signal === 'SIGINT' ? 130 : 143);+ expect(ownedRoot(host, run.child.pid)).toBeUndefined();+ await waitFor(() => !alive(pids.worker) && !alive(pids.descendant), 'owned test processes survived cancellation');+ } finally {+ run?.child.kill('SIGKILL');+ if (pids) {+ if (pids.group) killProcessTree({ pid: pids.group }, 'SIGKILL', { processGroup: true });+ else for (const pid of [pids.worker, pids.descendant]) killProcessTree({ pid }, 'SIGKILL');+ }+ rmSync(host, { recursive: true, force: true });+ }+ }, 35000);+ }+ });++ it('recovers a killed owner on the next successful launch while preserving a concurrent old live root and host entries', async () => {+ const host = mkdtempSync(join(tmpdir(), 'rcl-'));+ const runs = [];+ const descendants = [];+ try {+ const old = new Date(Date.now() - STALE_ROOT_AGE_MS * 2);+ for (const name of ['unrelated-old', 'portos-vitest-legacy-old', 'portos-vitest-legacy-fresh']) {+ mkdirSync(join(host, name));+ if (name.endsWith('-old')) utimesSync(join(host, name), old, old);+ }+ const live = launch(host, 'live', { blocking: true });+ runs.push(live);+ await waitFor(() => existsSync(live.ready), 'live worker did not start');+ const livePids = JSON.parse(readFileSync(live.ready, 'utf8'));+ descendants.push(livePids.worker, livePids.descendant);+ const liveRoot = ownedRoot(host, live.child.pid);+ expect(liveRoot).toBeTruthy();+ utimesSync(liveRoot, old, old);+ const doomed = launch(host, 'doomed', { blocking: true });+ runs.push(doomed);+ await waitFor(() => existsSync(doomed.ready), 'doomed worker did not start');+ const doomedPids = JSON.parse(readFileSync(doomed.ready, 'utf8'));+ descendants.push(doomedPids.worker, doomedPids.descendant);+ const deadRoot = ownedRoot(host, doomed.child.pid);+ expect(deadRoot).toBeTruthy();+ // Abruptly kill only this fixture's launcher/tree. Its finally cannot run.+ if (process.platform === 'win32') killProcessTree(doomed.child, 'SIGKILL');+ else {+ doomed.child.kill('SIGKILL');+ killProcessTree({ pid: doomedPids.group }, 'SIGKILL', { processGroup: true });+ }+ await doomed.closed;+ expect(existsSync(deadRoot)).toBe(true);+ const next = launch(host, 'success');+ runs.push(next);+ const result = await next.closed;+ expect(result.code, result.output).toBe(0);+ expect(ownedRoot(host, next.child.pid)).toBeUndefined();+ expect(existsSync(deadRoot)).toBe(false);+ expect(existsSync(liveRoot)).toBe(true);+ expect(alive(live.child.pid)).toBe(true);+ expect(existsSync(join(host, 'unrelated-old'))).toBe(true);+ expect(existsSync(join(host, 'portos-vitest-legacy-old'))).toBe(false);+ expect(existsSync(join(host, 'portos-vitest-legacy-fresh'))).toBe(true);+ } finally {+ for (const run of runs) {+ if (process.platform === 'win32') killProcessTree(run.child, 'SIGKILL');+ else run.child.kill('SIGTERM');+ }+ for (const pid of descendants) killProcessTree({ pid }, 'SIGKILL');+ await Promise.allSettled(runs.map(run => run.closed));+ rmSync(host, { recursive: true, force: true });+ }+ }, 65000);+});diff --git a/server/test/staleRunRoots.test.js b/server/test/staleRunRoots.test.jsindex 976696e765..8949f61e26 100644--- a/server/test/staleRunRoots.test.js+++ b/server/test/staleRunRoots.test.js@@ -17,16 +17,18 @@ const makeRoot = (name, { owner, ageMs = 0 } = {}) => {return root;};-describe('sweepStaleRunRoots (#9113)', () => {+describe.each(['pvt-', 'portos-vitest-'])('sweepStaleRunRoots (%s)', (prefix) => {it('removes a fresh root immediately when its owner is dead, keeps a live owner however old, and ages out pid-less roots at 6h', () => {- const dead = makeRoot('pvt-dead', { owner: '111 1000' });- const live = makeRoot('pvt-live', { owner: '222 1000', ageMs: STALE_ROOT_AGE_MS * 2 });- const noPidFresh = makeRoot('pvt-nopid-fresh');- const noPidOld = makeRoot('pvt-nopid-old', { ageMs: STALE_ROOT_AGE_MS + 60_000 });- const garbageOld = makeRoot('pvt-garbage', { owner: 'not a pid', ageMs: STALE_ROOT_AGE_MS + 60_000 });+ const dead = makeRoot(prefix + 'dead', { owner: '111 1000' });+ const live = makeRoot(prefix + 'live', { owner: '222 1000', ageMs: STALE_ROOT_AGE_MS * 2 });+ const noPidFresh = makeRoot(prefix + 'nopid-fresh');+ const noPidOld = makeRoot(prefix + 'nopid-old', { ageMs: STALE_ROOT_AGE_MS + 60_000 });+ const garbageOld = makeRoot(prefix + 'garbage', { owner: 'not a pid', ageMs: STALE_ROOT_AGE_MS + 60_000 });const other = makeRoot('unrelated-old', { ageMs: STALE_ROOT_AGE_MS * 2 });- sweepStaleRunRoots(host, { probe: ({ pid }) => pid === 222 });+ const otherPrefix = makeRoot(prefix === 'pvt-' ? 'portos-vitest-dead' : 'pvt-dead', { owner: '111 1000' });++ sweepStaleRunRoots(host, { prefix, probe: ({ pid }) => pid === 222 });expect(existsSync(dead)).toBe(false);expect(existsSync(live)).toBe(true);@@ -34,20 +36,21 @@ describe('sweepStaleRunRoots (#9113)', () => {expect(existsSync(noPidOld)).toBe(false);expect(existsSync(garbageOld)).toBe(false);expect(existsSync(other)).toBe(true);+ expect(existsSync(otherPrefix)).toBe(true);});it('falls back to the age rule when liveness is undeterminable (probe returns null)', () => {- const fresh = makeRoot('pvt-unknown-fresh', { owner: '5 1' });- const old = makeRoot('pvt-unknown-old', { owner: '5 1', ageMs: STALE_ROOT_AGE_MS + 60_000 });- sweepStaleRunRoots(host, { probe: () => null });+ const fresh = makeRoot(prefix + 'unknown-fresh', { owner: '5 1' });+ const old = makeRoot(prefix + 'unknown-old', { owner: '5 1', ageMs: STALE_ROOT_AGE_MS + 60_000 });+ sweepStaleRunRoots(host, { prefix, probe: () => null });expect(existsSync(fresh)).toBe(true);expect(existsSync(old)).toBe(false);});it('keeps a root owned by this very process (real probe, real owner file)', () => {- const root = makeRoot('pvt-self');+ const root = makeRoot(prefix + 'self');writeOwnerFile(root);- sweepStaleRunRoots(host);+ sweepStaleRunRoots(host, { prefix });expect(existsSync(root)).toBe(true);});});