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
Recover owned non-browser processes after interrupted test runs (#11736)
[._.]/adbee9779ae8
diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.mdindex 05ad385791..14c323a90e 100644--- a/docs/CONTRIBUTING.md+++ b/docs/CONTRIBUTING.md@@ -105,6 +105,15 @@ to the config file, including the server's derived capture projects, so sharedThey are reused across runs and removed with their checkout; temporary testroots retain their separate teardown lifecycle. CI caches the same owned paths.+Interrupted test runs reclaim individually identified processes under their run+roots, including non-browser fixtures. Linux reads same-user `/proc` records;+macOS uses the existing `/usr/bin/python3` with standard-library `ctypes` to read+NUL-delimited arguments and selected test environment fields. No Python install+is performed. If that optional reader is unavailable, macOS retains the legacy+browser-profile cleanup only. Process identity, caller ancestry and run-owner+liveness are rechecked before termination and escalation; unrelated process+groups are never signalled. Unknown ownership is left alone.+The npm Vite/Vitest commands, PM2's `portos-ui` launcher, and subprocess fixturesuse `--configLoader runner` to load ESM configs without writing bundles into shared`node_modules/.vite-temp`.diff --git a/scripts/lib/darwinTestProcesses.py b/scripts/lib/darwinTestProcesses.pynew file mode 100644index 0000000000..00ce84ed57--- /dev/null+++ b/scripts/lib/darwinTestProcesses.py@@ -0,0 +1,89 @@+"""Structured, same-user process metadata; stdout is a private pipe, never a log."""+import ctypes+import json+import os+import struct+import sys+++def snapshot():+ libc = ctypes.CDLL(None, use_errno=True)+ libproc = ctypes.CDLL('/usr/lib/libproc.dylib', use_errno=True)+ layout = struct.Struct('=12I16s32s6I2Q')++ def identity(pid):+ buf = ctypes.create_string_buffer(layout.size)+ if libproc.proc_pidinfo(pid, 3, 0, buf, layout.size) != layout.size:+ return None+ values = layout.unpack(buf.raw)+ if values[3] != pid or values[5] != os.getuid():+ return None+ return {'pid': pid, 'ppid': values[4], 'start': f'{values[-2]}:{values[-1]}'}++ requested = json.load(sys.stdin)+ if requested is None:+ size = libproc.proc_listpids(1, 0, None, 0)+ if size <= 0 or size > 16 * 1024 * 1024:+ raise ValueError('process inventory unavailable')+ pids = (ctypes.c_int * (size // 4 + 256))()+ count = libproc.proc_listpids(1, 0, pids, ctypes.sizeof(pids))+ if count <= 0 or count >= ctypes.sizeof(pids):+ raise ValueError('incomplete process inventory')+ requested = list(pids[:count // 4])+ result = []+ metadata_reads = 0+ for pid in requested:+ if not isinstance(pid, int) or pid <= 1:+ continue+ before = identity(pid)+ if before is None:+ continue+ # Keep ancestry even when arguments are unavailable. Missing ownership+ # evidence must never become permission to signal a process.+ record = dict(before)+ try:+ mib = (ctypes.c_int * 3)(1, 49, pid) # CTL_KERN / KERN_PROCARGS2+ length = ctypes.c_size_t()+ if libc.sysctl(mib, 3, None, ctypes.byref(length), None, 0) != 0:+ raise ValueError('arguments unavailable')+ if length.value < 4 or length.value > 4 * 1024 * 1024:+ raise ValueError('invalid argument length')+ buf = ctypes.create_string_buffer(length.value)+ if libc.sysctl(mib, 3, buf, ctypes.byref(length), None, 0) != 0:+ raise ValueError('arguments unavailable')+ data = buf.raw[:length.value]+ argc = struct.unpack_from('i', data)[0]+ if not 0 < argc < 65536:+ raise ValueError('invalid argument count')+ pos = data.index(b'\0', 4) + 1+ while data[pos] == 0:+ pos += 1+ args = []+ for _ in range(argc):+ end = data.index(b'\0', pos)+ args.append(data[pos:end].decode('utf-8', errors='strict'))+ pos = end + 1+ env = {}+ for entry in data[pos:].split(b'\0'):+ key, separator, value = entry.partition(b'=')+ if separator and key in (b'PORTOS_TEST_TEMP_ROOT', b'TMPDIR', b'VITEST', b'NODE_ENV'):+ name = key.decode()+ if name in env:+ raise ValueError('duplicate ownership field')+ env[name] = value.decode('utf-8', errors='strict')+ record.update(args=args, env=env)+ metadata_reads += 1+ except (ValueError, IndexError, UnicodeError):+ pass+ if identity(pid) == before:+ result.append(record)+ if metadata_reads == 0:+ raise ValueError('structured metadata unavailable')+ return result+++try:+ print(json.dumps(snapshot()))+except Exception:+ # No argv, environment, or OS error payload may escape through diagnostics.+ sys.exit(1)diff --git a/scripts/lib/testOwnedProcesses.js b/scripts/lib/testOwnedProcesses.jsnew file mode 100644index 0000000000..f1c87c327e--- /dev/null+++ b/scripts/lib/testOwnedProcesses.js@@ -0,0 +1,115 @@+import { execFileSync } from 'node:child_process';+import { readFileSync, readdirSync, statSync } from 'node:fs';+import { dirname, isAbsolute, join, relative, sep } from 'node:path';+import { fileURLToPath } from 'node:url';++const ownershipKeys = new Set(['PORTOS_TEST_TEMP_ROOT', 'TMPDIR', 'VITEST', 'NODE_ENV']);++function legacyBrowserProcesses(pids, exec) {+ try {+ const output = exec('ps', [...(pids ? ['-p', pids.join(',')] : ['-A']), '-ww', '-o', 'pid=,ppid=,uid=,lstart=,args='], {+ encoding: 'utf8', timeout: 5000, maxBuffer: 16 * 1024 * 1024,+ stdio: ['ignore', 'pipe', 'ignore'], env: { ...process.env, LC_ALL: 'C' },+ });+ return output.split('\n').flatMap(line => {+ const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3}\s+\w{3}\s+\d+\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(.*)$/.exec(line);+ if (!match || Number(match[3]) !== process.getuid()) return [];+ // Compatibility only: this is the pre-existing browser flag rule. Flat+ // ps text is never used to infer generic argv or environment ownership.+ const profile = /(?:^|\s)--user-data-dir=(\S+)/.exec(match[5])?.[1];+ return [{ pid: Number(match[1]), ppid: Number(match[2]), start: `legacy:${match[4]}`,+ args: profile ? [`--user-data-dir=${profile}`] : [], env: {} }];+ });+ } catch { return null; }+}++function linuxIdentity(pid) {+ const path = `/proc/${pid}`;+ if (statSync(path).uid !== process.getuid()) return null;+ const stat = readFileSync(join(path, 'stat'), 'utf8');+ const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');+ if (fields[0] === 'Z') return null;+ return { pid, ppid: Number(fields[1]), start: fields[19] };+}++function linuxProcess(pid) {+ try {+ const before = linuxIdentity(pid);+ if (!before) return null;+ let metadata = {};+ try {+ const args = readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').filter(Boolean);+ const env = {};+ for (const entry of readFileSync(`/proc/${pid}/environ`, 'utf8').split('\0')) {+ const equals = entry.indexOf('=');+ const key = entry.slice(0, equals);+ if (equals < 0 || !ownershipKeys.has(key)) continue;+ if (Object.hasOwn(env, key)) throw Error('duplicate ownership field');+ env[key] = entry.slice(equals + 1);+ }+ metadata = { args, env };+ } catch { /* retain ancestry without claiming ownership */ }+ const after = linuxIdentity(pid);+ return after?.start === before.start && after.ppid === before.ppid ? { ...before, ...metadata } : null;+ } catch { return null; }+}++// The Darwin reader uses the existing system Python, with no installation or+// cache. Missing capabilities fail closed; raw metadata never reaches a log.+export function readTestProcesses(pids = null, { platform = process.platform, exec } = {}) {+ try {+ const execute = exec ?? execFileSync;+ if (platform === 'darwin') {+ try {+ const reader = join(dirname(fileURLToPath(import.meta.url)), 'darwinTestProcesses.py');+ return JSON.parse(execute('/usr/bin/python3', ['-I', '-S', reader], {+ input: JSON.stringify(pids), encoding: 'utf8', timeout: 5000,+ maxBuffer: 16 * 1024 * 1024, stdio: ['pipe', 'pipe', 'ignore'],+ }));+ } catch { return legacyBrowserProcesses(pids, execute); }+ }+ if (platform !== 'linux') return null;+ const ids = pids ?? readdirSync('/proc').filter(name => /^\d+$/.test(name)).map(Number);+ return ids.map(linuxProcess).filter(Boolean);+ } catch { return null; }+}++function rootUnder(path, parent, prefix) {+ if (typeof path !== 'string' || !isAbsolute(path) || path.includes('\0')) return null;+ const rel = relative(parent, path);+ if (!rel || isAbsolute(rel) || rel === '..' || rel.startsWith(`..${sep}`)) return null;+ const name = rel.split(sep)[0];+ return name.startsWith(prefix) ? join(parent, name) : null;+}++export function testProcessRoot({ args = [], env = {} }, parent, prefix) {+ const roots = new Set();+ if (env.NODE_ENV === 'test' || env.VITEST === 'true') {+ const root = rootUnder(env.PORTOS_TEST_TEMP_ROOT ?? env.TMPDIR, parent, prefix);+ if (root && (env.PORTOS_TEST_TEMP_ROOT === undefined || root === env.PORTOS_TEST_TEMP_ROOT)) roots.add(root);+ }+ for (let index = 0; index < args.length; index++) {+ const arg = args[index];+ // Script text is data, even when it happens to be an absolute path.+ if (['--eval', '--print', '--command'].includes(arg) || /^-[A-Za-z]*[ecp][A-Za-z]*$/.test(arg)) { index++; continue; }+ const root = rootUnder(arg.startsWith('--user-data-dir=') ? arg.slice(16) : arg, parent, prefix);+ if (root) roots.add(root);+ }+ return roots.size === 1 ? [...roots][0] : null;+}++export function processAncestors(records, pid = process.pid) {+ const parents = new Map(records.map(record => [record.pid, record.ppid]));+ const ancestors = new Set([1, pid, process.ppid]);+ const visited = new Set();+ while (pid > 1) {+ if (visited.has(pid)) return null;+ visited.add(pid);+ const parent = parents.get(pid);+ if (!Number.isSafeInteger(parent) || parent < 1 || parent === pid) return null;+ if (parent === 1) return ancestors;+ ancestors.add(parent);+ pid = parent;+ }+ return ancestors;+}diff --git a/scripts/lib/vitestStaleRunRoots.js b/scripts/lib/vitestStaleRunRoots.jsindex cdbcc48849..c85d39582f 100644--- a/scripts/lib/vitestStaleRunRoots.js+++ b/scripts/lib/vitestStaleRunRoots.js@@ -11,7 +11,8 @@*/import { execFileSync } from 'node:child_process';import { lstatSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';-import { isAbsolute, join, relative, sep } from 'node:path';+import { basename, dirname, join } from 'node:path';+import { processAncestors, readTestProcesses, testProcessRoot } from './testOwnedProcesses.js';import { killWithEscalation } from '../../server/lib/killWithEscalation.js';export const OWNER_FILE = '.owner.pid';@@ -63,110 +64,108 @@ export function isOwnerAlive({ pid, startMs }) {function readOwner(path) {try {const [pid, startMs] = readFileSync(join(path, OWNER_FILE), 'utf8').trim().split(/\s+/).map(Number);- return Number.isInteger(pid) && pid > 0 ? { pid, startMs } : null;+ return Number.isSafeInteger(pid) && pid > 0 && Number.isFinite(startMs) && startMs >= 0 ? { pid, startMs } : null;} catch {return null;}}-/**- * `[{ pid, profile }]` for every running process started with a- * `--user-data-dir` (a test Chrome and its helpers). Empty on win32 or when- * `ps` is unavailable: the sweep is best-effort and never fails a run.- */-export function listProfileProcesses() {- if (process.platform === 'win32') return [];- let out;+function rootIsOrphaned(root, probe, now) {try {- out = execFileSync('ps', ['-A', '-ww', '-o', 'pid=,args='], {- encoding: 'utf8', windowsHide: true, maxBuffer: 64 * 1024 * 1024,- stdio: ['ignore', 'pipe', 'ignore'], env: { ...process.env, LC_ALL: 'C' },- });- } catch {- return [];- }- const found = [];- for (const line of out.split('\n')) {- const match = /^\s*(\d+)\s+(.*)$/.exec(line);- const profile = match && /(?:^|\s)--user-data-dir=(\S+)/.exec(match[2])?.[1];- if (profile && Number(match[1]) !== process.pid) found.push({ pid: Number(match[1]), profile });- }- return found;+ const stat = lstatSync(root);+ if (!stat.isDirectory() || stat.isSymbolicLink()) return false;+ const owner = readOwner(root);+ const alive = owner ? probe(owner) : null;+ return alive === false || (alive === null && now - stat.mtimeMs > STALE_ROOT_AGE_MS);+ } catch (error) { return error.code === 'ENOENT'; }}-const isPidAlive = pid => {- try { process.kill(pid, 0); return true; } catch (err) { return err.code === 'EPERM'; }-};+function ownedSnapshot(parent, prefix, read) {+ const records = read();+ if (!Array.isArray(records)) return null;+ const ancestors = processAncestors(records);+ if (!ancestors) return null;+ const owned = records.flatMap(record => {+ if (!Number.isSafeInteger(record.pid) || record.pid <= 1 || typeof record.start !== 'string' || !record.start) return [];+ const root = testProcessRoot(record, parent, prefix);+ return root && !ancestors.has(record.pid) ? [{ pid: record.pid, start: record.start, root }] : [];+ });+ return { ancestors, owned };+}-// SIGTERM now, SIGKILL after a grace window if the pid is still there.-export function terminatePid(pid) {- killWithEscalation({ exitCode: null, signalCode: null, kill: signal => { try { return process.kill(pid, signal); } catch { return false; } } },- { label: 'Orphaned test browser', stillRunning: () => isPidAlive(pid), delayMs: 2000 });+function stillOwned(record, snapshot, parent, prefix, read) {+ const current = read([...snapshot.ancestors, record.pid]);+ if (!Array.isArray(current)) return false;+ const ancestors = processAncestors(current);+ const live = current.find(item => item.pid === record.pid);+ return ancestors && !ancestors.has(record.pid) && live?.start === record.start+ && testProcessRoot(live, parent, prefix) === record.root;}-// First path segment of `path` below `root`, or null when it is not inside.-function segmentUnder(root, path) {- const rel = relative(root, path);- if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return null;- return rel.split(sep)[0];+export function terminatePid(record, { valid, kill = (pid, signal) => process.kill(pid, signal) }) {+ const signal = kind => {+ if (!valid()) return false;+ try { kill(record.pid, kind); return true; } catch { return false; }+ };+ return killWithEscalation({ exitCode: null, signalCode: null, kill: signal },+ { label: 'Orphaned test process', stillRunning: valid, delayMs: 2000 });}-/**- * Kill every process whose browser profile lives under `root` (a run's own- * temp root, at run exit). Synchronous SIGKILL by default, so it is safe in- * an `exit` handler. Returns the number of processes signalled.- */-export function killTestBrowsersUnder(root, { listProcesses = listProfileProcesses, kill = pid => process.kill(pid, 'SIGKILL') } = {}) {+/** Only individually proven processes are signalled; an unowned group member is never collateral cleanup. */+export function killTestProcessesUnder(root, { read = readTestProcesses, probe = isOwnerAlive,+ kill = (pid, signal) => process.kill(pid, signal) } = {}) {+ let rootExists = true;+ try { if (!lstatSync(root).isDirectory()) return 0; } catch (error) {+ if (error.code !== 'ENOENT') return 0;+ rootExists = false;+ }+ const parent = dirname(root);+ const prefix = basename(root);+ const snapshot = ownedSnapshot(parent, prefix, read);+ if (!snapshot) return 0;+ const owner = readOwner(root);+ if (rootExists && !owner) return 0;+ if (owner) {+ const startMs = snapshot.ancestors.has(owner.pid) ? readProcessStartMs(owner.pid) : null;+ const verifiedOwner = startMs !== null && Number.isFinite(owner.startMs)+ && Math.abs(startMs - owner.startMs) <= START_TOLERANCE_MS;+ if (!verifiedOwner && probe(owner) !== false) return 0;+ }let killed = 0;- for (const { pid, profile } of listProcesses()) {- if (segmentUnder(root, profile) === null) continue;- try { kill(pid); killed++; } catch { /* already gone */ }+ for (const record of snapshot.owned) {+ if (record.root !== root || !stillOwned(record, snapshot, parent, prefix, read)) continue;+ try { kill(record.pid, 'SIGKILL'); killed++; } catch { /* already gone */ }}return killed;}-/**- * A test Chrome outlives an interrupted run (#10840): its profile sits in a- * run root whose owner is gone (or was removed with it), and the browser keeps- * burning a core. Kill every process whose `--user-data-dir` is under such a- * `<prefix>` root in `tmpRoot`. A live owner keeps its browsers; an unknown- * owner keeps them until the root is old enough to sweep.- */-export function sweepOrphanedTestBrowsers(tmpRoot, { prefix = 'pvt-', now = Date.now(), probe = isOwnerAlive, listProcesses = listProfileProcesses, terminate = terminatePid } = {}) {- const verdicts = new Map();- const orphaned = name => {- if (verdicts.has(name)) return verdicts.get(name);- const path = join(tmpRoot, name);- let verdict;- try {- const stat = lstatSync(path);- const owner = readOwner(path);- const alive = owner ? probe(owner) : null;- verdict = alive === false || (alive === null && now - stat.mtimeMs > STALE_ROOT_AGE_MS);- } catch (err) {- // The root was removed while its browser kept running.- verdict = err?.code === 'ENOENT';- }- verdicts.set(name, verdict);- return verdict;- };+export function sweepOrphanedTestProcesses(tmpRoot, { prefix = 'pvt-', now = Date.now(), probe = isOwnerAlive,+ read = readTestProcesses, terminate = terminatePid } = {}) {+ const snapshot = ownedSnapshot(tmpRoot, prefix, read);+ if (!snapshot) return { killed: 0, inspected: false, preserved: new Set() };+ const preserved = new Set();let killed = 0;- for (const { pid, profile } of listProcesses()) {- const name = segmentUnder(tmpRoot, profile);- if (!name?.startsWith(prefix) || !orphaned(name)) continue;- try { terminate(pid); killed++; } catch { /* already gone */ }+ for (const record of snapshot.owned) {+ const valid = () => stillOwned(record, snapshot, tmpRoot, prefix, read)+ && rootIsOrphaned(record.root, probe, Date.now());+ if (!rootIsOrphaned(record.root, probe, now) || !valid()) { preserved.add(record.root); continue; }+ try { terminate(record, { valid }); killed++; } catch { /* already gone */ }}- if (killed) console.warn(`🧹 Stopped ${killed} test browser process${killed === 1 ? '' : 'es'} left running by an interrupted test run`);- return killed;+ if (killed) console.warn(`🧹 Stopped ${killed} test process${killed === 1 ? '' : 'es'} left running by an interrupted test run`);+ return { killed, inspected: true, preserved };}-export function sweepStaleRunRoots(tmpRoot, { prefix = 'pvt-', now = Date.now(), probe = isOwnerAlive, listProcesses = listProfileProcesses, terminate = terminatePid } = {}) {+// Retain the established import boundary while callers adopt the broader name.+export const killTestBrowsersUnder = killTestProcessesUnder;++export function sweepStaleRunRoots(tmpRoot, { prefix = 'pvt-', now = Date.now(), probe = isOwnerAlive, read = readTestProcesses, terminate = terminatePid } = {}) {// 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');}- // Browsers first: a root swept below no longer names its owner.- sweepOrphanedTestBrowsers(tmpRoot, { prefix, now, probe, listProcesses, terminate });+ // Keep ownership evidence when the platform cannot inspect processes.+ const { inspected, preserved } = sweepOrphanedTestProcesses(tmpRoot, { prefix, now, probe, read, terminate });+ if (!inspected && process.platform !== 'win32') return;let names;try {names = readdirSync(tmpRoot);@@ -176,9 +175,10 @@ export function sweepStaleRunRoots(tmpRoot, { prefix = 'pvt-', now = Date.now(),for (const name of names) {if (!name.startsWith(prefix)) continue;const path = join(tmpRoot, name);+ if (preserved.has(path)) continue;try {const stat = lstatSync(path);- if (!stat.isDirectory()) continue;+ if (!stat.isDirectory() || stat.isSymbolicLink()) continue;const owner = readOwner(path);const alive = owner ? probe(owner) : null;if (alive === true) continue;diff --git a/scripts/lib/vitestTempRoot.js b/scripts/lib/vitestTempRoot.jsindex d7cdb41585..1a44f0ae21 100644--- a/scripts/lib/vitestTempRoot.js+++ b/scripts/lib/vitestTempRoot.js@@ -1,7 +1,7 @@import { existsSync, mkdirSync, mkdtempSync } from 'node:fs';import { tmpdir } from 'node:os';import { basename, join } from 'node:path';-import { OWNER_FILE, killTestBrowsersUnder, sweepStaleRunRoots, writeOwnerFile } from './vitestStaleRunRoots.js';+import { OWNER_FILE, killTestProcessesUnder, sweepStaleRunRoots, writeOwnerFile } from './vitestStaleRunRoots.js';// Vitest sets these in every pool worker; the enclosing main process owns the root.const inVitestWorker = () => Boolean(process.env.VITEST_POOL_ID || process.env.VITEST_WORKER_ID);@@ -23,15 +23,15 @@ function restoreInheritedRootOwnership(root) {}/**- * The owner of a run root stops every test browser still running under it+ * The owner of a run root stops every test process still running under it* when it exits or is interrupted (#10840), so an aborted run cannot strand a- * Chrome whose worker died. A signal is re-raised once the sweep runs unless+ * child whose worker died. A signal is re-raised once the sweep runs unless* another listener (Vitest's own) is there to handle it.*/-function killRootBrowsersOnExit(root) {+function killRootProcessesOnExit(root) {if (process.platform === 'win32') return;const sweep = () => {- try { killTestBrowsersUnder(root); } catch { /* best effort at exit */ }+ try { killTestProcessesUnder(root); } catch { /* best effort at exit */ }};process.once('exit', sweep);for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {@@ -52,7 +52,7 @@ export function bootstrapVitestTempRoot() {root = mkdtempSync(join(hostRoot, 'pvt-'));writeOwnerFile(root);process.env.PORTOS_TEST_TEMP_ROOT = root;- killRootBrowsersOnExit(root);+ killRootProcessesOnExit(root);} else {restoreInheritedRootOwnership(root);}diff --git a/scripts/testOwnedProcessRecovery.test.js b/scripts/testOwnedProcessRecovery.test.jsnew file mode 100644index 0000000000..a7a885c55e--- /dev/null+++ b/scripts/testOwnedProcessRecovery.test.js@@ -0,0 +1,151 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { spawn, spawnSync } from 'node:child_process';+import { lstatSync, mkdtempSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { killTestProcessesUnder, sweepStaleRunRoots, writeOwnerFile } from './lib/vitestStaleRunRoots.js';+import { readTestProcesses, testProcessRoot } from './lib/testOwnedProcesses.js';+import { isProcessAlive } from '../server/test/processAlive.js';++afterEach(() => vi.useRealTimers());++describe('test process ownership boundaries', () => {+ it.skipIf(process.platform === 'win32')('retains only legacy browser ownership when the optional Darwin reader is unavailable', () => {+ const exec = vi.fn((command) => {+ if (command !== 'ps') throw Error('reader unavailable');+ return `900001 1 ${process.getuid()} Fri Oct 16 12:00:00 2026 chrome --user-data-dir=/tmp/example/pvt-browser/profile\n`+ + `900002 1 ${process.getuid()} Fri Oct 16 12:00:00 2026 node /tmp/example/pvt-script/file.js PORTOS_TEST_TEMP_ROOT=/tmp/example/pvt-env NODE_ENV=test\n`;+ });+ const records = readTestProcesses(null, { platform: 'darwin', exec });+ expect(records.map(record => testProcessRoot(record, '/tmp/example', 'pvt-'))).toEqual(['/tmp/example/pvt-browser', null]);+ expect(exec.mock.calls[1][1]).not.toContain('-E');+ });++ it('accepts exact structured fields and path arguments, never assignment-like script or environment text', () => {+ const parent = join(tmpdir(), 'synthetic-parent');+ const root = join(parent, 'pvt-owned');+ expect(testProcessRoot({ env: { NODE_ENV: 'test', PORTOS_TEST_TEMP_ROOT: root } }, parent, 'pvt-')).toBe(root);+ expect(testProcessRoot({ env: { NODE_ENV: 'test', PORTOS_TEST_TEMP_ROOT: `${root}/nested` } }, parent, 'pvt-')).toBeNull();+ expect(testProcessRoot({ args: ['sh', `${root}/fixture.sh`] }, parent, 'pvt-')).toBe(root);+ expect(testProcessRoot({ args: ['node', '-e', `--user-data-dir=${root}/profile`],+ env: { OTHER: `PORTOS_TEST_TEMP_ROOT=${root} NODE_ENV=test` } }, parent, 'pvt-')).toBeNull();+ expect(testProcessRoot({ args: ['node', '-e', root], env: { NODE_ENV: 'test', TMPDIR: `${parent}/unrelated` } }, parent, 'pvt-')).toBeNull();+ for (const option of ['-lc', '-xc', '-pe']) {+ expect(testProcessRoot({ args: ['sh', option, `${root}/script; echo text`] }, parent, 'pvt-')).toBeNull();+ }+ expect(testProcessRoot({ args: ['chrome', `--user-data-dir=${root}/profile`] }, parent, 'pvt-')).toBe(root);+ });++ it('refuses reused identities, caller ancestors and ownership changes before delayed escalation', () => {+ vi.useFakeTimers();+ const host = mkdtempSync(join(tmpdir(), 'recovery-race-'));+ const root = join(host, 'pvt-owned'); mkdirSync(root);+ writeFileSync(join(root, '.owner.pid'), '999999 0\n');+ const target = { pid: 900001, ppid: 1, start: 'original', args: [], env: { NODE_ENV: 'test', PORTOS_TEST_TEMP_ROOT: root } };+ const ancestors = [{ ...target, pid: process.pid, ppid: process.ppid, start: 'caller' },+ { pid: process.ppid, ppid: 1, start: 'parent' }];+ const read = () => [...ancestors, target];+ const kill = vi.spyOn(process, 'kill').mockImplementation(() => true);+ let ownerAlive = false;+ try {+ sweepStaleRunRoots(host, { read, probe: () => ownerAlive });+ expect(kill).toHaveBeenCalledExactlyOnceWith(target.pid, 'SIGTERM');+ target.start = 'reused';+ vi.advanceTimersByTime(2000);+ expect(kill).toHaveBeenCalledTimes(1);+ mkdirSync(root); writeFileSync(join(root, '.owner.pid'), '999999 0\n');+ target.start = 'next';+ sweepStaleRunRoots(host, { read, probe: () => ownerAlive });+ expect(kill).toHaveBeenCalledTimes(2);+ mkdirSync(root); writeOwnerFile(root); ownerAlive = true;+ vi.advanceTimersByTime(2000);+ expect(kill).toHaveBeenCalledTimes(2);+ expect(killTestProcessesUnder(root, { read: () => ancestors, probe: () => true, kill })).toBe(0);+ expect(killTestProcessesUnder(root, { read: () => [target], kill })).toBe(0);+ writeFileSync(join(root, '.owner.pid'), '900009 0\n');+ expect(killTestProcessesUnder(root, { read, probe: () => true, kill })).toBe(0);+ expect(killTestProcessesUnder(root, { read, probe: () => null, kill })).toBe(0);+ rmSync(join(root, '.owner.pid'));+ expect(killTestProcessesUnder(root, { read, kill })).toBe(0);+ writeFileSync(join(root, '.owner.pid'), 'malformed');+ expect(killTestProcessesUnder(root, { read, kill })).toBe(0);+ const link = join(host, 'pvt-linked');+ symlinkSync(root, link, process.platform === 'win32' ? 'junction' : 'dir');+ target.env.PORTOS_TEST_TEMP_ROOT = link;+ sweepStaleRunRoots(host, { read, probe: () => false });+ expect(kill).toHaveBeenCalledTimes(2);+ expect(lstatSync(link).isSymbolicLink()).toBe(true);+ } finally { kill.mockRestore(); rmSync(host, { recursive: true, force: true }); }+ });+});++describe.skipIf(process.platform === 'win32')('real interrupted-run recovery', () => {+ it('reaps environment-only and script-path children while preserving unrelated and live-owner processes', async () => {+ const host = mkdtempSync(join(tmpdir(), 'recovery-owned-'));+ const children = [];+ const launch = async (args, env = {}) => {+ const child = spawn(args[0], args.slice(1), { env: { PATH: process.env.PATH, ...env }, detached: true, stdio: ['pipe', 'pipe', 'ignore'] });+ children.push(child);+ await new Promise((resolve, reject) => {+ const timeout = setTimeout(() => reject(Error('synthetic child readiness timed out')), 5000);+ child.once('error', reject);+ child.stdout.once('data', () => { clearTimeout(timeout); resolve(); });+ });+ return child;+ };+ const code = "process.on('SIGTERM',()=>{}); process.stdout.write('ready'); setInterval(()=>{},1000)";+ try {+ const dead = join(host, 'pvt-dead'); const live = join(host, 'pvt-live');+ mkdirSync(dead); mkdirSync(live); writeOwnerFile(live);+ const owner = spawnSync(process.execPath, ['-e', ''], { stdio: 'ignore' });+ writeFileSync(join(dead, '.owner.pid'), `${owner.pid} 0\n`);+ const environmentOnly = await launch([process.execPath, '-e', code], { NODE_ENV: 'test', PORTOS_TEST_TEMP_ROOT: dead });+ const script = join(dead, 'fixture.sh'); writeFileSync(script, 'echo ready\nread answer\n');+ const argumentOnly = await launch(['/bin/sh', script]);+ const unrelated = await launch([process.execPath, '-e', code], { OTHER: `PORTOS_TEST_TEMP_ROOT=${dead} NODE_ENV=test` });+ const ownedLive = await launch([process.execPath, '-e', code], { NODE_ENV: 'test', PORTOS_TEST_TEMP_ROOT: live });+ const inspected = readTestProcesses([environmentOnly.pid, argumentOnly.pid, unrelated.pid]);+ expect(inspected?.map(record => testProcessRoot(record, host, 'pvt-'))).toEqual([dead, dead, null]);+ sweepStaleRunRoots(host);+ await vi.waitFor(() => {+ expect(isProcessAlive(environmentOnly.pid)).toBe(false);+ expect(isProcessAlive(argumentOnly.pid)).toBe(false);+ }, { timeout: 5000 });+ expect(isProcessAlive(unrelated.pid)).toBe(true);+ expect(isProcessAlive(ownedLive.pid)).toBe(true);+ expect(killTestProcessesUnder(live)).toBe(1);+ await vi.waitFor(() => expect(isProcessAlive(ownedLive.pid)).toBe(false));+ } finally {+ await Promise.all(children.map(child => new Promise(resolve => {+ if (child.exitCode !== null || child.signalCode !== null) return resolve();+ child.once('close', resolve); child.kill('SIGKILL');+ })));+ rmSync(host, { recursive: true, force: true });+ }+ }, 15000);++ it('the run owner exit hook stops its non-browser child', async () => {+ const host = mkdtempSync(join(tmpdir(), 'recovery-exit-'));+ let childPid;+ try {+ const module = fileURLToPath(new URL('./lib/vitestTempRoot.js', import.meta.url));+ const env = { ...process.env, TMPDIR: host, TMP: host, TEMP: host };+ delete env.PORTOS_TEST_TEMP_ROOT; delete env.VITEST_POOL_ID; delete env.VITEST_WORKER_ID;+ const owner = spawnSync(process.execPath, ['--input-type=module', '-e', `+ import { bootstrapVitestTempRoot } from ${JSON.stringify(module)};+ import { spawn } from 'node:child_process';+ bootstrapVitestTempRoot();+ const child = spawn(process.execPath, ['-e', "process.send('ready'); setInterval(()=>{},1000)"], { env: { ...process.env, NODE_ENV: 'test' }, detached: true, stdio: ['ignore','ignore','ignore','ipc'] });+ child.once('message', () => { process.stdout.write(String(child.pid)); child.disconnect(); child.unref(); });+ `], { env, encoding: 'utf8', timeout: 15000 });+ childPid = Number(owner.stdout);+ expect(owner.status).toBe(0);+ expect(childPid).toBeGreaterThan(1);+ await vi.waitFor(() => expect(isProcessAlive(childPid)).toBe(false));+ } finally {+ if (childPid > 1 && isProcessAlive(childPid)) process.kill(childPid, 'SIGKILL');+ rmSync(host, { recursive: true, force: true });+ }+ }, 20000);+});diff --git a/scripts/vitestTempRootSetup.js b/scripts/vitestTempRootSetup.jsindex 52f28af9e6..0e3649d448 100644--- a/scripts/vitestTempRootSetup.js+++ b/scripts/vitestTempRootSetup.js@@ -6,7 +6,7 @@import { lstatSync, readdirSync, rmSync } from 'node:fs';import { join } from 'node:path';import { describeOwnedBrowserObservation, describeStageFixtureRoot, readOwnedBrowserObservations } from '../server/test/ownedBrowserDiagnostics.js';-import { OWNER_FILE, killTestBrowsersUnder } from './lib/vitestStaleRunRoots.js';+import { OWNER_FILE, killTestProcessesUnder } from './lib/vitestStaleRunRoots.js';export function setup() {}@@ -70,9 +70,9 @@ export function isEffectivelyEmpty(path) {export function teardown() {const root = process.env.PORTOS_TEST_TEMP_ROOT;if (!root) return;- // A browser a suite failed to tear down would outlive the run (#10840).- const browsers = process.platform === 'win32' ? 0 : killTestBrowsersUnder(root);- if (browsers) console.warn(`⚠️ test browser leak: stopped ${browsers} process${browsers === 1 ? '' : 'es'} still running under the run temp root`);+ // A process a suite failed to tear down would outlive the run (#10840).+ const processes = process.platform === 'win32' ? 0 : killTestProcessesUnder(root);+ if (processes) console.warn(`⚠️ test process leak: stopped ${processes} process${processes === 1 ? '' : 'es'} still running under the run temp root`);let entries;try {entries = readdirSync(root);