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
Preserve owned browser shutdown and run-global profile evidence (#11577)
[._.]/545be07ceee7
diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.jsindex 7dbfa3f903..d484efcd7f 100644--- a/scripts/ci-test-plan.js+++ b/scripts/ci-test-plan.js@@ -480,6 +480,7 @@ const WORKSPACE_CACHE_COMMON_INPUTS = new Set(['scripts/lib/vitestTempRootFixture.js', 'scripts/lib/vitestTempRoot.js','scripts/lib/vitestStaleRunRoots.js', 'scripts/lib/dbTestFiles.js','scripts/vitestCiPool.js', 'scripts/vitestTempRootSetup.js', 'server/lib/killWithEscalation.js',+ 'server/test/ownedBrowserDiagnostics.js', 'server/lib/mockPathsDataRoot.js',]);const WORKSPACE_CACHE_SERVER_INPUTS = new Set(['server/package.json', 'server/package-lock.json',diff --git a/scripts/ci-test-plan.test.js b/scripts/ci-test-plan.test.jsindex 8f45f0c898..2d1acc2af7 100644--- a/scripts/ci-test-plan.test.js+++ b/scripts/ci-test-plan.test.js@@ -77,6 +77,7 @@ it('selects checkout-cache contracts only in their installed-dependency runners''scripts/lib/vitestTempRootFixture.js', 'scripts/lib/vitestTempRoot.js','scripts/lib/vitestStaleRunRoots.js', 'scripts/lib/dbTestFiles.js','scripts/vitestCiPool.js', 'scripts/vitestTempRootSetup.js', 'server/lib/killWithEscalation.js',+ 'server/test/ownedBrowserDiagnostics.js', 'server/lib/mockPathsDataRoot.js',];const server = ['server/package.json', 'server/package-lock.json',diff --git a/scripts/lib/workspaceCacheFixture.js b/scripts/lib/workspaceCacheFixture.jsindex e385722d35..4ef8e239f8 100644--- a/scripts/lib/workspaceCacheFixture.js+++ b/scripts/lib/workspaceCacheFixture.js@@ -58,10 +58,12 @@ function checkout(host, name, workspace, configName, dependencies) {link(join(REPO, 'scripts', file), join(parent, 'scripts', file));}if (workspace === 'server') {- mkdirSync(join(root, 'test'), { recursive: true });- // Both server configs load this environment relative to themselves. Copy- // its default export intact so registry setup and teardown still run.- copyFileSync(join(REPO, 'server/test/mediaRegistryEnvironment.js'), join(root, 'test/mediaRegistryEnvironment.js'));+ // Both configs load this environment relative to themselves. Copy its+ // Node-only support closure intact so setup and teardown run in this checkout.+ for (const file of ['test/mediaRegistryEnvironment.js', 'test/ownedBrowserDiagnostics.js', 'lib/mockPathsDataRoot.js']) {+ mkdirSync(dirname(join(root, file)), { recursive: true });+ copyFileSync(join(REPO, 'server', file), join(root, file));+ }}if (workspace === 'client') copyFileSync(join(REPO, 'client/src/test/timeouts.js'), join(root, 'src/test/timeouts.js'));if (workspace === 'server' && configName === 'vitest.config.js') {diff --git a/scripts/vitestTempRoot.test.js b/scripts/vitestTempRoot.test.jsindex d18ac3925f..3117f9e64a 100644--- a/scripts/vitestTempRoot.test.js+++ b/scripts/vitestTempRoot.test.js@@ -2,7 +2,8 @@ import { describe, expect, it } from 'vitest';import { spawn, spawnSync } from 'node:child_process';import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, utimesSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { join, relative } from 'node:path';+import { fileURLToPath } from 'node:url';import { createVitestTempFixture, runWatchConfigRestart } from './lib/vitestTempRootFixture.js';import { STALE_ROOT_AGE_MS, killTestBrowsersUnder, sweepStaleRunRoots, writeOwnerFile } from './lib/vitestStaleRunRoots.js';import { isProcessAlive } from '../server/test/processAlive.js';@@ -34,6 +35,38 @@ describe('real workspace runner temp lifecycle', () => {}});+ it.each(['source-owned', 'outside-repo'])('retains composition provenance after a passing %s worker ends, without changing the global leak failure', mode => {+ const repo = fileURLToPath(new URL('../', import.meta.url));+ const host = mkdtempSync(mode === 'source-owned' ? join(repo, 'server/test/fixtures/provenance-worker-') : join(tmpdir(), 'vrt-'));+ try {+ const { args, options } = createVitestTempFixture(host, 'server', `+ const { channel } = await import('node:diagnostics_channel');+ const { EventEmitter } = await import('node:events');+ const { mkdtempSync } = await import('node:fs');+ const profile = mkdtempSync(join(first, 'portos-composition-browser-'));+ writeFileSync(join(profile, 'fixture'), 'synthetic');+ const observations = channel('portos.composition-browser.lifecycle');+ const child = new EventEmitter();+ observations.publish({ event: 'allocated', profile });+ observations.publish({ event: 'child', profile, child });+ observations.publish({ event: 'remove-start', profile });+ expect(true).toBe(true);+ `);+ const result = spawnSync(process.execPath, args, options);+ expect(result.error).toBeUndefined();+ expect(result.status).toBe(1);+ expect(result.stdout).toMatch(/1 passed/);+ expect(result.stderr).toContain('test temp leak: portos-composition-browser- ×1');+ const owner = mode === 'source-owned' ? relative(repo, join(host, 'fixture/lifecycle.test.js')).split('\\').join('/') : 'unavailable';+ expect(result.stderr).toContain(`owner=${owner}`);+ expect(result.stderr).toContain('fixture-before-global-backstop');+ expect(result.stderr).toContain('removal=pending');+ expect(result.stderr).toContain('observer=ended');+ expect(result.stderr).not.toContain(host);+ expect(readdirSync(host)).toEqual(['fixture']);+ } finally { rmSync(host, { recursive: true, force: true }); }+ }, 25000);+it('reuses config ownership on reimport and reclaims it after interruption, preserving a live owner', async () => {const host = mkdtempSync(join(tmpdir(), 'vrt-'));let child;diff --git a/scripts/vitestTempRootSetup.js b/scripts/vitestTempRootSetup.jsindex cda660766a..21229f534a 100644--- a/scripts/vitestTempRootSetup.js+++ b/scripts/vitestTempRootSetup.js@@ -3,8 +3,9 @@* redirects temp APIs before Vitest creates its module-transform cache.* The server's exclusive capture projects share this single global owner.*/-import { lstatSync, readFileSync, readdirSync, rmSync } from 'node:fs';+import { lstatSync, readdirSync, rmSync } from 'node:fs';import { join } from 'node:path';+import { describeOwnedBrowserObservation, readOwnedBrowserObservations } from '../server/test/ownedBrowserDiagnostics.js';import { OWNER_FILE, killTestBrowsersUnder } from './lib/vitestStaleRunRoots.js';export function setup() {}@@ -36,22 +37,10 @@ const TOOLCHAIN_CACHE_PREFIXES = new Set([]);// Written by server/lib/mockPathsDataRoot.js (`<dir>\t<test file>` per root it-// minted). Kept as a literal here: this setup file imports no server code.+// minted), plus optional bounded composition snapshots. The decoder reaches+// only Node builtins and the existing owner writer, never a service graph.const OWNERS_FILE = '.leak-owners';-function readLeakOwners(root) {- const owners = new Map();- let text = '';- try {- text = readFileSync(join(root, OWNERS_FILE), 'utf8');- } catch { /* no PATHS-mocking suite ran */ }- for (const line of text.split('\n')) {- const [dir, file] = line.split('\t');- if (dir && file) owners.set(dir, file);- }- return owners;-}-export function groupLeakPrefix(name) {return name.replace(/[0-9a-zA-Z]{6,}$/, '') || name;}@@ -96,7 +85,7 @@ export function teardown() {.filter((name) => !TOOLCHAIN_CACHE_PREFIXES.has(groupLeakPrefix(name))).filter((name) => !isEffectivelyEmpty(join(root, name)));- const owners = readLeakOwners(root);+ const { owners, observations, state } = readOwnedBrowserObservations(root);const byPrefix = new Map();for (const name of entries) {const prefix = groupLeakPrefix(name);@@ -109,6 +98,11 @@ export function teardown() {const by = files.size ? ` (created by ${[...files].join(', ')})` : '';console.warn(`⚠️ test temp leak: ${prefix} ×${count}${by}`);}+ const composition = entries.filter(name => name.startsWith('portos-composition-browser-'));+ for (const [index, name] of composition.slice(0, 8).entries()) {+ console.warn(`⚠️ composition profile ${index + 1}: ${describeOwnedBrowserObservation(observations.get(name), state)}`);+ }+ if (composition.length > 8) console.warn(`⚠️ composition profile provenance capped: ${composition.length - 8} additional entries`);if (entries.length) process.exitCode = 1;try {diff --git a/scripts/vitestTempRootSetup.test.js b/scripts/vitestTempRootSetup.test.jsindex 3a732ccb72..130f4acd09 100644--- a/scripts/vitestTempRootSetup.test.js+++ b/scripts/vitestTempRootSetup.test.js@@ -1,6 +1,10 @@-import { mkdirSync, mkdtempSync, rmSync, writeFileSync, existsSync, readFileSync, symlinkSync } from 'node:fs';+import { appendFileSync, statSync, mkdirSync, mkdtempSync, rmSync, writeFileSync, existsSync, readFileSync, symlinkSync } from 'node:fs';import { spawnSync } from 'node:child_process';import { tmpdir } from 'node:os';+import { channel } from 'node:diagnostics_channel';+import { EventEmitter } from 'node:events';+import { fileURLToPath } from 'node:url';+import { observeOwnedBrowsers } from '../server/test/ownedBrowserDiagnostics.js';import { join } from 'node:path';import { afterEach, describe, expect, it, vi } from 'vitest';import { teardown } from './vitestTempRootSetup.js';@@ -17,8 +21,8 @@ describe('vitestTempRootSetup teardown', () => {function runTeardown(populate) {const root = mkdtempSync(join(tmpdir(), 'pvt-teardown-test-'));- populate(root);process.env.PORTOS_TEST_TEMP_ROOT = root;+ populate(root);const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});process.exitCode = undefined;teardown();@@ -85,6 +89,104 @@ describe('vitestTempRootSetup teardown', () => {expect(leaked.exitCode).toBe(1);});+ it('projects exact-child snapshots after observer disposal and preserves a later-appearance leak', () => {+ const observations = channel('portos.composition-browser.lifecycle');+ const leaked = runTeardown(root => {+ const dispose = observeOwnedBrowsers(() => fileURLToPath(import.meta.url));+ const profile = join(root, 'portos-composition-browser-Abc123');+ mkdirSync(profile);+ const child = new EventEmitter();+ const productionClose = vi.fn();+ child.on('close', productionClose);+ observations.publish({ event: 'allocated', profile });+ observations.publish({ event: 'child', profile, child });+ observations.publish({ event: 'remove-start', profile });+ rmSync(profile, { recursive: true });+ observations.publish({ event: 'remove-resolved', profile });+ child.exitCode = 0; // Public status alone does not fabricate a native exit event.+ dispose();+ expect(child.listenerCount('exit')).toBe(0);+ expect(child.listeners('close')).toEqual([productionClose]);+ const ended = readFileSync(join(root, '.leak-owners'), 'utf8');+ child.emit('exit');+ child.emit('close');+ observations.publish({ event: 'remove-rejected', profile, code: 'EACCES' });+ expect(readFileSync(join(root, '.leak-owners'), 'utf8')).toBe(ended);+ // Reusing the environment must not revive the prior observer.+ const disposeNext = observeOwnedBrowsers(() => fileURLToPath(import.meta.url));+ observations.publish({ event: 'child', profile, child });+ expect(child.listenerCount('exit')).toBe(0);+ disposeNext();+ mkdirSync(profile);+ writeFileSync(join(profile, 'later'), 'synthetic later writer');+ });+ expect(leaked.exitCode).toBe(1);+ expect(leaked.removed).toBe(true);+ const report = leaked.warnings.join('\n');+ expect(report).toContain('owner=scripts/vitestTempRootSetup.test.js');+ expect(report).toContain('removal=resolved presentAfterRemoval=false presentAtGlobalGuard=true observer=ended');+ expect(report).toContain('exitObserved=false closeObserved=false exitCode=0 signalCode=none');+ expect(report).not.toContain('Abc123');+ });++ it('caps records, event history and public projection without copying private child or error values', () => {+ const observations = channel('portos.composition-browser.lifecycle');+ const leaked = runTeardown(root => {+ const dispose = observeOwnedBrowsers(() => '/private/owner-sentinel.test.js');+ for (let i = 0; i < 66; i++) {+ const profile = join(root, `portos-composition-browser-${String(i).padStart(6, '0')}`);+ mkdirSync(profile);+ writeFileSync(join(profile, 'private-content-sentinel'), 'private output sentinel');+ observations.publish({ event: 'allocated', profile });+ if (!i) {+ const child = Object.assign(new EventEmitter(), { pid: 987654321, exitCode: 'private-exit-sentinel', signalCode: 'private-signal-sentinel' });+ observations.publish({ event: 'child', profile, child });+ for (let event = 0; event < 30; event++) observations.publish({ event: 'remove-rejected', profile, code: 'private-error-sentinel' });+ }+ }+ dispose();+ const rows = readFileSync(join(root, '.leak-owners'), 'utf8').trim().split('\n');+ expect(rows.every(row => Buffer.byteLength(row + '\n') <= 1024)).toBe(true);+ expect(new Set(rows.map(row => row.split('\t')[0])).size).toBe(65); // 64 profiles + one cap marker+ });+ expect(leaked.exitCode).toBe(1);+ const report = leaked.warnings.join('\n');+ expect(leaked.warnings.filter(line => /composition profile \d+:/.test(line))).toHaveLength(8);+ expect(report).toContain('58 additional entries');+ expect(report).toContain('provenance=capped');+ expect(report).toContain('removal=rejected:other');+ expect(report).toContain('exitCode=other signalCode=other');+ expect(report).toContain('truncated=true');+ expect(report).not.toMatch(/sentinel|987654321|000000/);+ });++ it('reports unavailable or capped evidence rather than stale success after truncated metadata or write failure', () => {+ const observations = channel('portos.composition-browser.lifecycle');+ for (const boundary of ['truncated', 'write-failure', 'byte-cap']) {+ const leaked = runTeardown(root => {+ const profile = join(root, 'portos-composition-browser-Abc123');+ mkdirSync(profile);+ writeFileSync(join(profile, 'data'), 'synthetic');+ if (boundary === 'write-failure') mkdirSync(join(root, '.leak-owners'));+ const dispose = observeOwnedBrowsers(() => fileURLToPath(import.meta.url));+ observations.publish({ event: 'allocated', profile });+ observations.publish({ event: 'remove-resolved', profile });+ dispose();+ if (boundary === 'truncated') appendFileSync(join(root, '.leak-owners'), 'portos-composition-browser-Abc123\tprivate-sentinel\t{"v":1');+ if (boundary === 'byte-cap') {+ writeFileSync(join(root, '.leak-owners'), 'x'.repeat(8 * 1024 * 1024));+ const stop = observeOwnedBrowsers(() => fileURLToPath(import.meta.url));+ observations.publish({ event: 'allocated', profile });+ stop();+ expect(statSync(join(root, '.leak-owners')).size).toBe(8 * 1024 * 1024);+ }+ });+ expect(leaked.exitCode).toBe(1);+ expect(leaked.warnings.join('\n')).toContain(`provenance=${boundary === 'byte-cap' ? 'capped' : 'unavailable'}`);+ expect(leaked.warnings.join('\n')).not.toMatch(/removal=resolved|private-sentinel/);+ }+ });+it('removes leaked cyclic and dangling links without walking or changing their targets', () => {const sandbox = mkdtempSync(join(tmpdir(), 'pvt-link-teardown-'));const root = join(sandbox, 'run');diff --git a/server/lib/README.md b/server/lib/README.mdindex 1b995f5a8a..0ed0e0819a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -771,7 +771,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `dbTestGate.js` | `requireDbOrSkip(label, dbReady, reason)` keeps a missing local test database as a visible skipped suite, but throws when `PORTOS_REQUIRE_DB` is set so CI cannot pass after DB-backed suites disappear. || `gitTestRepo.js` | Shared real-git sandbox for integration tests (#4394): one initialized template (working tree + bare origin) per worker, then `fs.cp` into a fresh temp dir. `makeGitSandbox({ origin })`, `attachBareOrigin(scratch, repo)`, `materializeGitRepo(dest)`, `destroyGitSandbox`, plus `SKIP_HEAVY_INTEGRATION` (`VITEST_FAST=1`). `resetGitSandbox({ scratch, repo, initialHead })` / `resetGitWorktreeSandbox(repo, initialHead)` restore a sandbox in place (branches, worktrees, remote) so a `describe` can build one sandbox in `beforeAll` and reset between tests instead of paying the fs.cp/rm cycle per test (#5902). Every entry point runs `assertTempPath` first, so a path outside `os.tmpdir()` throws instead of `git init`-ing or `rm -rf`-ing a real checkout (#4554). Fixture-local maintenance/GC detachment is disabled so awaited Git operations retain their writers through teardown. Still real git — just not rebuilt from `init`+`commit`+`push` in every `beforeEach`. || `mirrorParity.js` | Source-extraction and comparison primitives for declaration-level contract tests: the vendored `aiToolkit/` copy of `TOOL_USE_RE` (`localModelHeuristics.mirror.test.js`), and the bootstrap sequence's body assertions (`bootstrap*.test.js`). A pure module the browser needs is imported by the client rather than mirrored, so no client↔server copy test should need these: `stripCommentsAndNormalize` (so per-side commentary may diverge but logic may not), `extractDeclaration(src, name)` (balanced `{}`/`()`/`[]` walk over `function` / `async function` / `const`), and `compareDeclaration(serverSrc, clientSrc, name)`. Use these instead of hand-rolling a brace-walker per mirror. Pure — no `vitest` import — so callers own the assertions. |-| `mockPathsDataRoot.js` | Shared Vitest helpers for `PATHS.data → temp dir`, no-peer record creation guards, deterministic federation-identity doubles (`mockTestIdentity`), and `ownTestBodies(it)` → `{ it, drain }`, which owns each test body so teardown can `await drain()` before removing a fixture root — a body left running by Vitest's fail-fast cancellation otherwise recreates the removed root (`test temp leak:`). |+| `mockPathsDataRoot.js` | Best-effort bounded `recordTempRootOwner` sidecar observations and shared Vitest helpers for `PATHS.data → temp dir`, no-peer record creation guards, deterministic federation-identity doubles (`mockTestIdentity`), and `ownTestBodies(it)` → `{ it, drain }`, which owns each test body so teardown can `await drain()` before removing a fixture root — a body left running by Vitest's fail-fast cancellation otherwise recreates the removed root (`test temp leak:`). || `settingsTestUtil.js` | `bindSettingsFile(dataRoot)` → `writeSettingsFile`/`mergeSettingsFile`: direct settings.json disk writes that also drop the `getSettings()` read cache (dynamic-import reset) so a stale cache can't survive a bypass-`save()` write. || `runtimeEnv.js` | `isTestRunner()` — NODE_ENV=test **or** the VITEST env var, so a run that dropped NODE_ENV is still armed. `isVitestRunner()` narrows to a real Vitest worker; `isSmokeBoot()` (`SMOKE_BOOT_ENV`) marks the server boot smoke, whose boot skips schedulers, agent recovery, and external integrations (#8343). Dependency-free and deliberately apart from `db.js`, which used to own it: the lowest-level file primitives need the same answer and must not pull in `pg`, and the many suites spelling `vi.mock('../lib/db.js', () => ({ query }))` used to strip it out of the graph for every other consumer. || `testDataIsolation.js` | Runtime backstop against a test WRITING into the install's real `data/` tree — the filesystem analogue of `db.js`'s row-write guard. `isInsideRealDataRoot(path)` canonicalizes a target through symlinked ancestors (it need not exist yet) and tests containment with `pathSafety.js#isPathAtOrInsideDir`, so a `..` climb, a relative path, a `data-archive` sibling, or a differently-cased spelling on a case-insensitive filesystem can't walk in sideways; the real root is re-derived through `dataRoot.js` rather than read from `PATHS`, so a suite that redirects `PATHS.data` to a temp root can't also redirect the guard. `assertNotRealDataWrite(path, operation)` throws under the test runner from `atomicWrite`, the guarded wrappers in `fileCore.js` (`writeFileGuarded`, `appendFileGuarded`, `copyFileGuarded`, `rmGuarded`, `unlinkGuarded`, `createWriteStreamGuarded`), and `collectionStore`'s record delete; `assertNotNewRealDataDir(dir)` is the create-only variant `ensureDir` uses, since `mkdir -p` on an existing directory mutates nothing. Inert outside the runner — the `isTestRunner()` check precedes every syscall. Services mutating files under `data/` route through these guarded wrappers. Closes the write half of the bug class `testDataIsolation.guards.test.js` covers statically and the two-run probe covers for reads (#6176, after #6171, #6203). |diff --git a/server/lib/mockPathsDataRoot.js b/server/lib/mockPathsDataRoot.jsindex 983d82b3ca..981be1af70 100644--- a/server/lib/mockPathsDataRoot.js+++ b/server/lib/mockPathsDataRoot.js@@ -45,7 +45,7 @@* target the default re-rooting wouldn't produce — it merges last.*/-import { appendFileSync, mkdtempSync, readdirSync, rmSync } from 'fs';+import { appendFileSync, mkdtempSync, readdirSync, rmSync, statSync } from 'fs';import { tmpdir } from 'os';import { basename, isAbsolute, join, relative, sep } from 'path';@@ -64,16 +64,26 @@ export function createTempDataRoot(prefix = 'portos-test-') {* leaked `<prefix>XXXXXX` directory is reported with the test file that minted* it. A random-suffixed name alone cannot identify its creator (#10404).* Best-effort and basename-only: diagnostics must never fail a fixture or put a- * checkout path in a log.+ * checkout path in a log. Optional versioned observations are prevalidated by+ * the owned-browser observer; retain legacy two-column attribution unchanged.+ * The 8 MiB budget admits at most one small concurrent append per worker.*/const TEMP_ROOT_OWNERS_FILE = '.leak-owners';-function recordTempRootOwner(dir) {+export function recordTempRootOwner(dir, { owner, observation } = {}) {try {const runRoot = process.env.PORTOS_TEST_TEMP_ROOT;- const owner = globalThis.__vitest_worker__?.filepath;- if (!runRoot || !owner) return;- appendFileSync(join(runRoot, TEMP_ROOT_OWNERS_FILE), `${basename(dir)}\t${basename(owner)}\n`);- } catch { /* diagnostics only */ }+ const source = owner ?? globalThis.__vitest_worker__?.filepath;+ if (!runRoot || !source) return 'unavailable';+ const file = join(runRoot, TEMP_ROOT_OWNERS_FILE);+ const row = `${basename(dir)}\t${observation ? source : basename(source)}${observation ? `\t${observation}` : ''}\n`;+ if (observation) {+ if (Buffer.byteLength(row) > 1024) return 'capped';+ try { if (statSync(file).size >= 8 * 1024 * 1024) return 'capped'; }+ catch (error) { if (error.code !== 'ENOENT') return 'unavailable'; }+ }+ appendFileSync(file, row);+ return 'written';+ } catch { return 'unavailable'; /* diagnostics only; never recreate a missing run root */ }}/**diff --git a/server/services/htmlComposition/ownedBrowser.js b/server/services/htmlComposition/ownedBrowser.jsindex d912cabe91..c331b089d9 100644--- a/server/services/htmlComposition/ownedBrowser.js+++ b/server/services/htmlComposition/ownedBrowser.js@@ -1,6 +1,7 @@+import { channel } from 'node:diagnostics_channel';import { existsSync } from 'node:fs';import { mkdtemp, rm, access, constants } from 'node:fs/promises';-import { tmpdir } from 'node:os';+import { tmpdir, constants as osConstants } from 'node:os';import { join } from 'node:path';import { spawn } from '../../lib/childProcess.js';import { safeChildProcessOptions } from '../../lib/processEnv.js';@@ -15,6 +16,12 @@ import { createCdpPipeTransport } from './cdpPipe.js';// Chrome launches in testBrowserCleanup.js; production keeps the sandbox.const sandboxArgs = () => (isVitestRunner() && process.getuid?.() === 0 ? ['--no-sandbox'] : []);+// Passive test observers receive only exact owned capabilities. No subscriber+// means no persistence, process inspection, or additional lifecycle work.+const lifecycle = channel('portos.composition-browser.lifecycle');+const observe = (event, profile, details) => {+ if (lifecycle.hasSubscribers) lifecycle.publish({ event, profile, ...details });+};// Raw browser output can hold private paths, so a startup failure names a// recognized cause instead of copying stderr.const ROOT_SANDBOX_REFUSAL = /Running as root without --no-sandbox is not supported/;@@ -83,6 +90,7 @@ export async function launchCompositionBrowser({throw isolationUnavailable('Unknown preview isolation mode');}const profile = await mkdtemp(join(tmpdir(), 'portos-composition-browser-'));+ observe('allocated', profile);let proc;let transport;let startupPipeError;@@ -96,13 +104,30 @@ export async function launchCompositionBrowser({let closing;let profileCleanup;let terminationStarted;+ // Fixed-size observations from this retained child only. Observation+ // timestamps are monotonic milliseconds since ownership began.+ const observedSince = performance.now();+ const observed = { spawnMs: null, exitMs: null, closeMs: null, termMs: null, killMs: null };+ const observedMs = () => Math.round(performance.now() - observedSince);const termination = { term: 'not-attempted', kill: 'not-attempted', error: 'none' };const safeSignalError = error => ['EPERM', 'ESRCH', 'EINVAL', 'ENOSYS'].includes(error?.code) ? error.code : 'other';- const cleanupProfile = () => profileCleanup ??= removeProfile(profile);+ const cleanupProfile = () => {+ if (!profileCleanup) {+ observe('remove-start', profile);+ profileCleanup = removeProfile(profile);+ // Observe settlement without replacing the cached promise or its verdict.+ if (lifecycle.hasSubscribers) profileCleanup.then(+ () => observe('remove-resolved', profile),+ error => observe('remove-rejected', profile, { code: TRANSIENT_RM.has(error?.code) || ['EACCES', 'ENOENT'].includes(error?.code) ? error.code : 'other' }),+ );+ }+ return profileCleanup;+ };let closeResolve;const childClosed = new Promise(resolve => { closeResolve = resolve; });const onExit = () => {exited = true;+ observed.exitMs ??= observedMs();// Chrome helpers may retain inherited stderr after the browser exits.// Release our pipe without signaling unrelated or discovered processes.proc?.stderr?.destroy();@@ -113,6 +138,8 @@ export async function launchCompositionBrowser({};const onClose = () => {closed = true;+ observed.closeMs ??= observedMs();+ proc?.removeListener('error', onError);// A deadline can reject close() before the OS reports exit. Retain ownership// until the eventual close event and remove only this child's profile then.cleanupProfile().catch(error => console.error(`❌ Composition browser profile cleanup failed (${safeSignalError(error)})`));@@ -140,11 +167,13 @@ export async function launchCompositionBrowser({transport?.removeListener('error', onPipeError);if (proc && !closed) {terminationStarted = performance.now();+ const closeStartedMs = observedMs();const tracked = {get exitCode() { return proc.exitCode; },get signalCode() { return proc.signalCode; },kill(name) {const key = name === 'SIGTERM' ? 'term' : 'kill';+ observed[`${key}Ms`] ??= observedMs();termination[key] = 'attempted';try {const accepted = signalChild(name);@@ -162,7 +191,25 @@ export async function launchCompositionBrowser({stillRunning: () => !exited,});await Promise.race([childClosed, new Promise((_, reject) => {- deadline = setTimeout(() => reject(new Error(`Composition browser cleanup exceeded its deadline (exit=${exited}, stdioClosed=${Boolean(proc.stderr?.destroyed)}, term=${termination.term}, kill=${termination.kill}, signalError=${termination.error}, elapsedMs=${Math.round(performance.now() - terminationStarted)})`)), shutdownMs);+ deadline = setTimeout(() => {+ // Never interpolate arbitrary child properties, errors or output.+ // Public status and observed events are separate evidence: accepted+ // signals alone do not establish that the child has exited.+ const exitCode = proc.exitCode == null ? 'none' : Number.isSafeInteger(proc.exitCode) ? proc.exitCode : 'other';+ const signalCode = proc.signalCode == null ? 'none'+ : typeof proc.signalCode === 'string' && Object.hasOwn(osConstants.signals, proc.signalCode) ? proc.signalCode : 'other';+ const facts = {+ exit: exited, stdioClosed: Boolean(proc.stderr?.destroyed),+ term: termination.term, kill: termination.kill, signalError: termination.error,+ elapsedMs: Math.round(performance.now() - terminationStarted),+ spawned, closed, exitCode, signalCode,+ exitListener: proc.listeners('exit').includes(onExit),+ closeListener: proc.listeners('close').includes(onClose),+ errorListener: proc.listeners('error').includes(onError),+ ...observed, closeStartedMs, timeoutMs: observedMs(),+ };+ reject(new Error(`Composition browser cleanup exceeded its deadline (${Object.entries(facts).map(([key, value]) => `${key}=${value ?? 'unobserved'}`).join(', ')})`));+ }, shutdownMs);})]);}} finally {@@ -170,7 +217,6 @@ export async function launchCompositionBrowser({clearTimeout(deadline);// Wait for the process and our pipe to close before removing its profile.if (!proc || closed) {- proc?.removeListener('error', onError);await cleanupProfile();}}@@ -198,10 +244,11 @@ export async function launchCompositionBrowser({proc = spawn(command, args, piped? { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'], env: previewBrowserEnv(), detached: true }: safeChildProcessOptions({ stdio: ['ignore', 'ignore', 'pipe'] }));- proc.once('spawn', () => { spawned = true; });+ proc.once('spawn', () => { spawned = true; observed.spawnMs = observedMs(); });proc.once('exit', onExit);proc.once('close', onClose);proc.on('error', onError);+ observe('child', profile, { child: proc });if (piped) {transport = createCdpPipeTransport(proc);transport.on('error', onPipeError);diff --git a/server/services/htmlComposition/ownedBrowser.test.js b/server/services/htmlComposition/ownedBrowser.test.jsindex 09ebd4494b..c363579ad9 100644--- a/server/services/htmlComposition/ownedBrowser.test.js+++ b/server/services/htmlComposition/ownedBrowser.test.js@@ -1,8 +1,9 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { EventEmitter } from 'node:events';+import { EventEmitter, getEventListeners } from 'node:events';import { PassThrough } from 'node:stream';+import { basename } from 'node:path';import { access, mkdir, rm } from 'node:fs/promises';-import { createOwnedBrowserDiagnostics } from '../../test/ownedBrowserDiagnostics.js';+import { createOwnedBrowserDiagnostics, readOwnedBrowserObservations } from '../../test/ownedBrowserDiagnostics.js';const launch = vi.hoisted(() => ({ spawn: vi.fn() }));vi.mock('node:fs/promises', async original => {@@ -45,7 +46,9 @@ beforeEach(() => {const originalGetuid = Object.getOwnPropertyDescriptor(process, 'getuid');const setUid = uid => Object.defineProperty(process, 'getuid', { value: () => uid, configurable: true, writable: true });afterEach(() => {+ diagnostics.dispose();child.stderr.destroy();+ vi.useRealTimers();vi.restoreAllMocks();vi.unstubAllEnvs();if (originalGetuid) Object.defineProperty(process, 'getuid', originalGetuid);@@ -55,6 +58,10 @@ afterEach(() => {describe('owned composition capture browser lifecycle', () => {it('keeps close pending until removal settles and distinguishes later profile recreation in diagnostics', async () => {const owner = await launchCompositionBrowser();+ // Production ownership plus one shared diagnostic binding, even with both+ // the environment observer and this suite's existing local observer.+ expect(child.listenerCount('exit')).toBe(2);+ expect(child.listenerCount('close')).toBe(2);const remove = rm.getMockImplementation();let release;let started;@@ -71,10 +78,14 @@ describe('owned composition capture browser lifecycle', () => {await removing;const owned = diagnostics.children[0];expect(settled).toBe(false);+ const persisted = () => readOwnedBrowserObservations(process.env.PORTOS_TEST_TEMP_ROOT).observations.get(basename(profile));+ expect(persisted()).toMatchObject({ owner: 'server/services/htmlComposition/ownedBrowser.test.js',+ removal: 'pending', observer: 'active', exit: true, close: true });expect(diagnostics.describe(owned)).toContain('exit=true close=true removal=pending presentAfterRemoval=unknown presentNow=true');release();await closing;expect(diagnostics.describe(owned)).toContain('removal=resolved presentAfterRemoval=false presentNow=false');+ expect(persisted()).toMatchObject({ removal: 'resolved', presentAfterRemoval: false });// A later writer is a negative control, not evidence about Chrome helpers.await mkdir(profile);const report = diagnostics.describe(owned);@@ -97,6 +108,8 @@ describe('owned composition capture browser lifecycle', () => {await expect(owner.close()).rejects.toBe(error);const report = diagnostics.describe(diagnostics.children[0]);expect(report).toContain('removal=rejected:EACCES presentAfterRemoval=true presentNow=true');+ expect(readOwnedBrowserObservations(process.env.PORTOS_TEST_TEMP_ROOT).observations.get(basename(profile)))+ .toMatchObject({ removal: 'rejected:EACCES', presentAfterRemoval: true });expect(report).not.toContain(profile);expect(report).not.toContain(error.message);expect(log).toHaveBeenCalledWith('❌ Composition browser profile cleanup failed (other)');@@ -315,17 +328,87 @@ describe('owned composition capture browser lifecycle', () => {});-it('retains the cleanup deadline failure but removes its owned profile after a late close', async () => {+it.each([+ ['accepted signals without exit', null, null, false],+ ['public exit status without an observed event', 7, null, false],+ ['observed exit with delayed close', null, 'SIGKILL', true],+ ['unexpected child status and error text', '/private/exit-status', '/private/signal-status', false],+])('retains the deadline evidence and late profile ownership for %s', async (_, exitCode, signalCode, emitExit) => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });child.kill = vi.fn(() => true);- const owner = await launchCompositionBrowser({ shutdownMs: 30 });- await expect(owner.close()).rejects.toThrow(/cleanup exceeded its deadline.*term=accepted, kill=accepted, signalError=none/);+ const signalProcess = vi.spyOn(process, 'kill');+ const controller = new AbortController();+ const owner = await launchCompositionBrowser({ signal: controller.signal });+ child.stderr.write('/private/browser-output\n');+ expect(getEventListeners(controller.signal, 'abort')).toHaveLength(1);+ // Separate the ownership clock from the shutdown budget in the snapshot.+ await vi.advanceTimersByTimeAsync(2000);+ let result;+ const timersBeforeClose = vi.getTimerCount();+ const closing = owner.close();+ const settled = closing.then(() => { result = 'resolved'; }, error => { result = error; });+ expect(child.kill).toHaveBeenCalledExactlyOnceWith('SIGTERM');+ await vi.advanceTimersByTimeAsync(999);+ expect(child.kill).toHaveBeenCalledExactlyOnceWith('SIGTERM');+ await vi.advanceTimersByTimeAsync(1);expect(child.kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGTERM', 'SIGKILL']);+ await vi.advanceTimersByTimeAsync(200);+ child.exitCode = exitCode;+ child.signalCode = signalCode;+ if (emitExit) child.emit('exit', exitCode, signalCode);+ const malformed = typeof exitCode === 'string';+ if (malformed) child.emit('error', Object.assign(new Error('/private/error-message'), { code: '/private/error-code' }));+ await vi.advanceTimersByTimeAsync(3799);+ expect(result).toBeUndefined();+ expect(rm).not.toHaveBeenCalled();await expect(access(profile)).resolves.toBeUndefined();- child.signalCode = 'SIGKILL';- child.emit('exit', null, 'SIGKILL');+ await vi.advanceTimersByTimeAsync(1);+ await settled;+ expect(result).toBeInstanceOf(Error);+ const facts = Object.fromEntries(result.message.slice(result.message.indexOf('(') + 1, -1).split(', ').map(field => field.split('=')));+ expect(facts).toEqual({+ exit: String(emitExit), stdioClosed: String(emitExit),+ term: 'accepted', kill: 'accepted', signalError: malformed ? 'other' : 'none', elapsedMs: '5000',+ spawned: 'true', closed: 'false', exitCode: malformed ? 'other' : exitCode === null ? 'none' : String(exitCode),+ signalCode: malformed ? 'other' : signalCode ?? 'none',+ exitListener: String(!emitExit), closeListener: 'true', errorListener: 'true',+ spawnMs: '0', exitMs: emitExit ? '3200' : 'unobserved', closeMs: 'unobserved',+ termMs: '2000', killMs: '3000', closeStartedMs: '2000', timeoutMs: '7000',+ });+ expect(result.message).toMatch(/^Composition browser cleanup exceeded its deadline /);+ for (const privateValue of [profile, '/synthetic/chrome', String(child.pid), endpoint, '/private/']) {+ expect(result.message).not.toContain(privateValue);+ }+ expect(vi.getTimerCount()).toBe(timersBeforeClose);+ expect(signalProcess).not.toHaveBeenCalled();+ expect(child.listenerCount('error')).toBe(1);+ expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0);+ controller.abort();+ expect(child.kill).toHaveBeenCalledTimes(2);+ if (!emitExit) {+ child.exitCode = null;+ child.signalCode = 'SIGKILL';+ child.emit('exit', null, 'SIGKILL');+ }+ expect(child.stderr.destroyed).toBe(true);// Exit alone is insufficient: the child must release inherited stdio first.await expect(access(profile)).resolves.toBeUndefined();+ const remove = rm.getMockImplementation();+ let removalFinished;+ const removed = new Promise(resolve => { removalFinished = resolve; });+ vi.mocked(rm).mockImplementationOnce(async (...args) => {+ await remove(...args);+ removalFinished();+ });child.emit('close', null, 'SIGKILL');- await vi.waitFor(async () => { await expect(access(profile)).rejects.toThrow(); });- await expect(owner.close()).rejects.toThrow('cleanup exceeded its deadline');+ await removed;+ await expect(access(profile)).rejects.toThrow();+ expect(rm).toHaveBeenCalledExactlyOnceWith(profile, { recursive: true, force: true });+ expect(child.listenerCount('exit')).toBe(0);+ expect(child.listenerCount('close')).toBe(0);+ expect(child.listenerCount('error')).toBe(0);+ expect(vi.getTimerCount()).toBe(timersBeforeClose);+ expect(owner.close()).toBe(closing);+ await expect(owner.close()).rejects.toBe(result);+ expect(result.message).toContain('closeMs=unobserved');});diff --git a/server/services/musicVideo/documentRender.browser.test.js b/server/services/musicVideo/documentRender.browser.test.jsindex ccd49629b3..21e56d991e 100644--- a/server/services/musicVideo/documentRender.browser.test.js+++ b/server/services/musicVideo/documentRender.browser.test.js@@ -70,7 +70,7 @@ vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await impconst { findFfmpeg } = await import('../../lib/ffmpeg.js');const { _cleanupTestBrowser, _waitForTestChrome, _testChromeCaptureArgs } = await import('../htmlComposition/testBrowserCleanup.js');-afterAll(() => cleanupTempDataRoots());+afterAll(() => { lifecycle.diagnostics.dispose(); cleanupTempDataRoots(); });const chrome = [process.env.CHROME_PATH, chromium.executablePath(),'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',diff --git a/server/test/mediaRegistryEnvironment.js b/server/test/mediaRegistryEnvironment.jsindex d4f795e88d..a87bb8ee1c 100644--- a/server/test/mediaRegistryEnvironment.js+++ b/server/test/mediaRegistryEnvironment.js@@ -1,3 +1,4 @@+import { observeOwnedBrowsers } from './ownedBrowserDiagnostics.js';import { builtinEnvironments } from 'vitest/runtime';import { mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';@@ -12,21 +13,30 @@ export default {viteEnvironment: 'ssr',async setup(global, options) {const node = await builtinEnvironments.node.setup(global, options);- const prior = process.env.PORTOS_MEDIA_MODELS_FILE;- const root = prior ? null : mkdtempSync(join(tmpdir(), 'portos-suite-media-'));- if (root) process.env.PORTOS_MEDIA_MODELS_FILE = join(root, 'media-models.json');- return {- async teardown() {- try {- if (root) {- if (prior === undefined) delete process.env.PORTOS_MEDIA_MODELS_FILE;- else process.env.PORTOS_MEDIA_MODELS_FILE = prior;- rmSync(root, { recursive: true, force: true });+ const disposeObservations = observeOwnedBrowsers(() => global.__vitest_worker__?.filepath);+ try {+ const prior = process.env.PORTOS_MEDIA_MODELS_FILE;+ const root = prior ? null : mkdtempSync(join(tmpdir(), 'portos-suite-media-'));+ if (root) process.env.PORTOS_MEDIA_MODELS_FILE = join(root, 'media-models.json');+ return {+ async teardown() {+ try {+ disposeObservations();+ if (root) {+ if (prior === undefined) delete process.env.PORTOS_MEDIA_MODELS_FILE;+ else process.env.PORTOS_MEDIA_MODELS_FILE = prior;+ rmSync(root, { recursive: true, force: true });+ }+ } finally {+ await node.teardown(global);}- } finally {- await node.teardown(global);- }- },- };+ },+ };+ } catch (error) {+ // setup can fail before Vitest receives our teardown owner. Preserve that+ // original error while ending any partial diagnostic subscription.+ disposeObservations();+ throw error;+ }},};diff --git a/server/test/ownedBrowserDiagnostics.js b/server/test/ownedBrowserDiagnostics.jsindex 6eb6661449..e3598323d0 100644--- a/server/test/ownedBrowserDiagnostics.js+++ b/server/test/ownedBrowserDiagnostics.js@@ -1,47 +1,239 @@-import { existsSync } from 'node:fs';+import { channel } from 'node:diagnostics_channel';+import { closeSync, existsSync, openSync, readSync } from 'node:fs';+import { basename, dirname, relative, resolve, sep } from 'node:path';+import { constants as osConstants } from 'node:os';+import { fileURLToPath } from 'node:url';+import { recordTempRootOwner } from '../lib/mockPathsDataRoot.js';-// Test-owned lifecycle observations only: never retain browser output or print-// the profile path. A close event does not establish that every helper exited.-export function createOwnedBrowserDiagnostics() {+const lifecycle = channel('portos.composition-browser.lifecycle');+// The environment and transformed test modules can have different module+// caches. The Node channel is shared across those realms; retain one diagnostic+// binding per exact child, even when a local assertion observer also tracks it.+const bindingsKey = Symbol.for('portos.composition-browser.diagnostic-bindings');+const bindings = lifecycle[bindingsKey] ??= new WeakMap();+const repo = fileURLToPath(new URL('../../', import.meta.url));+const BUDGET = 8 * 1024 * 1024;+const events = new Set(['allocated', 'child', 'exit', 'close', 'remove-start', 'remove-resolved', 'remove-rejected']);+const removals = new Set(['not-started', 'pending', 'resolved', ...['ENOTEMPTY', 'EBUSY', 'EPERM', 'EMFILE', 'EACCES', 'ENOENT', 'other'].map(code => `rejected:${code}`)]);+const safeOwner = owner => typeof owner === 'string' && owner.length <= 240+ && /^(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_.-]+\.(?:test|spec)\.[cm]?[jt]sx?$/.test(owner) && !owner.split('/').includes('..');+const ownerFor = filepath => {+ if (typeof filepath !== 'string') return 'unavailable';+ const owner = relative(repo, filepath).split(sep).join('/');+ return safeOwner(owner) ? owner : 'unavailable';+};+const present = profile => { try { return existsSync(profile); } catch { return 'unknown'; } };+const safeSignal = signal => signal == null ? 'none' : typeof signal === 'string' && Object.hasOwn(osConstants.signals, signal) ? signal : 'other';+const safeExit = code => code == null ? 'none' : Number.isSafeInteger(code) && Math.abs(code) <= 2147483647 ? code : 'other';+const elapsed = started => Math.min(86400000, Math.max(0, Math.round(performance.now() - started)));++// One interpretation for both local assertion diagnostics and persisted worker+// observations. Native exit/close events are distinct from a public child status.+export function createOwnedBrowserDiagnostics({ changed = () => {} } = {}) {const children = [];+ const listeners = new Map();+ const subscriber = {};+ const sampleStatus = owned => {+ const child = owned.binding?.child;+ try { if (child) { owned.exitCode = safeExit(child.exitCode); owned.signalCode = safeSignal(child.signalCode); } }+ catch { owned.exitCode = 'other'; owned.signalCode = 'other'; }+ };const observe = (owned, event) => {- if (owned.events.length < 16) owned.events.push(`${event}@${Math.round(performance.now() - owned.started)}ms`);+ const bound = owned.binding;+ sampleStatus(owned);+ if (owned.events.length < 16) owned.events.push(`${event}@${elapsed(owned.started)}ms`);else owned.truncated = true;+ for (const notify of bound?.notifications.values() || [changed]) {+ try { notify(owned); } catch { /* observation must never reject a child event */ }+ }+ };+ const allocate = profile => {+ let owned = children.find(item => item.profile === profile);+ if (!owned) {+ owned = { profile, exited: false, closed: false, removal: 'not-started',+ presentAfterRemoval: 'unknown', events: [], started: performance.now(), truncated: false, observer: 'active', exitCode: 'none', signalCode: 'none' };+ children.push(owned);+ observe(owned, 'allocated');+ }+ return owned;+ };+ const bind = (owned, child) => {+ if (listeners.has(owned) || !child?.once) return;+ let bound = bindings.get(child);+ if (bound && bound.owned.profile !== owned.profile) return;+ if (bound) {+ children[children.indexOf(owned)] = bound.owned;+ owned = bound.owned;+ bound.notifications.set(subscriber, changed);+ listeners.set(owned, bound);+ // This consumer also needs the already-observed facts.+ try { changed(owned); } catch { /* diagnostics only */ }+ return;+ }+ const exit = () => { owned.exited = true; observe(owned, 'exit'); };+ const close = () => { owned.closed = true; observe(owned, 'close'); };+ bound = { child, exit, close, owned, notifications: new Map([[subscriber, changed]]) };+ owned.binding = bound;+ bindings.set(child, bound);+ listeners.set(owned, bound);+ child.once('exit', exit);+ child.once('close', close);+ observe(owned, 'child');+ };+ const removal = (owned, event, code) => {+ if (event === 'remove-start') owned.removal = 'pending';+ else {+ owned.removal = event === 'remove-resolved' ? 'resolved' : `rejected:${code}`;+ if (!removals.has(owned.removal)) owned.removal = 'rejected:other';+ owned.presentAfterRemoval = present(owned.profile);+ }+ observe(owned, event);};return {- children,+ children, allocate, bind, removal,track(child, args) {const arg = args?.find(value => value.startsWith('--user-data-dir=') && value.includes('portos-composition-browser-'));- if (!arg) return;- const owned = { profile: arg.slice('--user-data-dir='.length), exited: false, closed: false,- removal: 'not-started', presentAfterRemoval: 'unknown', events: [], started: performance.now(), truncated: false };- children.push(owned);- child.once('exit', () => { owned.exited = true; observe(owned, 'exit'); });- child.once('close', () => { owned.closed = true; observe(owned, 'close'); });+ if (arg) bind(allocate(arg.slice('--user-data-dir='.length)), child);},async remove(remove, path, ...args) {const owned = children.find(item => item.profile === path);if (!owned) return remove(path, ...args);- owned.removal = 'pending';- observe(owned, 'remove-start');+ removal(owned, 'remove-start');try {const result = await remove(path, ...args);- owned.removal = 'resolved';- owned.presentAfterRemoval = existsSync(path);- observe(owned, 'remove-resolved');+ removal(owned, 'remove-resolved');return result;} catch (error) {- const code = ['ENOTEMPTY', 'EBUSY', 'EPERM', 'EMFILE', 'EACCES', 'ENOENT'].includes(error?.code) ? error.code : 'other';- owned.removal = `rejected:${code}`;- owned.presentAfterRemoval = existsSync(path);- observe(owned, 'remove-rejected');+ removal(owned, 'remove-rejected', error?.code);throw error;}},+ dispose() {+ for (const owned of children) {+ const bound = listeners.get(owned);+ sampleStatus(owned);+ owned.observer = 'ended';+ // Persist this consumer's ending before detaching its notification.+ try { changed(owned); } catch { /* diagnostics only */ }+ bound?.notifications.delete(subscriber);+ if (bound && !bound.notifications.size) {+ bound.child.removeListener('exit', bound.exit);+ bound.child.removeListener('close', bound.close);+ bindings.delete(bound.child);+ }+ }+ listeners.clear();+ },describe(owned) {return `owned lifecycle: exit=${owned.exited} close=${owned.closed} removal=${owned.removal}`- + ` presentAfterRemoval=${owned.presentAfterRemoval} presentNow=${existsSync(owned.profile)}`+ + ` presentAfterRemoval=${owned.presentAfterRemoval} presentNow=${present(owned.profile)}`+ ` events=${owned.events.join(',')} truncated=${owned.truncated}`;},};}++// Installed for the entire worker environment, including collection and suite+// hooks. Only exact profiles directly under this run's root are admitted.+export function observeOwnedBrowsers(getOwner) {+ const runRoot = process.env.PORTOS_TEST_TEMP_ROOT;+ let ended = false;+ let capped = false;+ const owners = new Map();+ const diagnostics = createOwnedBrowserDiagnostics({ changed(owned) {+ const observation = JSON.stringify({ v: 1, exitCode: owned.exitCode, signalCode: owned.signalCode, exit: owned.exited, close: owned.closed,+ removal: owned.removal, presentAfterRemoval: owned.presentAfterRemoval,+ observer: ended ? 'ended' : 'active', events: owned.events, truncated: owned.truncated });+ recordTempRootOwner(owned.profile, { owner: owners.get(owned.profile) || 'unavailable', observation });+ } });+ const receive = message => {+ // A passive observer must never turn a fixture operation into a failure.+ try {+ if (ended || !runRoot || !message || typeof message.profile !== 'string'+ || dirname(resolve(message.profile)) !== resolve(runRoot)+ || !/^portos-composition-browser-[A-Za-z0-9]+$/.test(basename(message.profile))) return;+ let owned = diagnostics.children.find(item => item.profile === message.profile);+ if (message.event === 'allocated' && !owned) {+ if (diagnostics.children.length >= 64) {+ if (!capped) recordTempRootOwner(joinCap(runRoot), { owner: 'unavailable', observation: '{"v":1,"state":"capped"}' });+ capped = true;+ return;+ }+ owners.set(message.profile, ownerFor(getOwner()));+ owned = diagnostics.allocate(message.profile);+ }+ if (!owned) return;+ if (message.event === 'child') diagnostics.bind(owned, message.child);+ if (['remove-start', 'remove-resolved', 'remove-rejected'].includes(message.event)) diagnostics.removal(owned, message.event, message.code);+ } catch { /* unavailable evidence; original fixture verdict remains authoritative */ }+ };+ lifecycle.subscribe(receive);+ return () => {+ if (ended) return;+ ended = true;+ lifecycle.unsubscribe(receive);+ // No waiting for late children/removal: the final snapshot explicitly ends+ // observation. Remove only the two listeners this observer installed.+ try { diagnostics.dispose(); } catch { /* best effort */ }+ };+}+const joinCap = root => resolve(root, '.composition-observer');++// A bounded, privacy-validating decoder, shared by the existing global guard.+// Never accept arbitrary JSON properties or text as public lifecycle facts.+export function readOwnedBrowserObservations(root) {+ const owners = new Map();+ const observations = new Map();+ let state = 'unavailable';+ let fd;+ try {+ fd = openSync(resolve(root, '.leak-owners'), 'r');+ const buffer = Buffer.alloc(BUDGET + 1);+ let bytes = 0;+ while (bytes < buffer.length) {+ const read = readSync(fd, buffer, bytes, buffer.length - bytes, null);+ if (!read) break;+ bytes += read;+ }+ state = bytes >= BUDGET ? 'capped' : 'available';+ const text = buffer.subarray(0, Math.min(bytes, BUDGET)).toString('utf8');+ const lines = text.split('\n');+ const incomplete = !text.endsWith('\n') ? lines.pop()?.split('\t')[0] : undefined;+ for (const line of lines) {+ const columns = line.split('\t');+ const [dir, owner, encoded] = columns;+ if (columns.length > 3 || Buffer.byteLength(line) >= 1024 || (!line.endsWith('}') && encoded)) { observations.delete(dir); continue; }+ if (!dir || basename(dir) !== dir) continue;+ // Keep ordinary two-column owner rows readable, but never print a path.+ if (!encoded) {+ observations.delete(dir);+ if (/^[A-Za-z0-9_.-]{1,240}$/.test(owner) && !['.', '..'].includes(owner)) owners.set(dir, owner);+ continue;+ }+ let value;+ try { value = JSON.parse(encoded); } catch { observations.delete(dir); continue; }+ if (dir === '.composition-observer' && value?.v === 1 && value.state === 'capped') { state = 'capped'; continue; }+ const valid = value?.v === 1+ && safeExit(value.exitCode === 'none' ? null : value.exitCode) === value.exitCode+ && safeSignal(value.signalCode === 'none' ? null : value.signalCode) === value.signalCode+ && typeof value.exit === 'boolean' && typeof value.close === 'boolean'+ && removals.has(value.removal) && [true, false, 'unknown'].includes(value.presentAfterRemoval)+ && ['active', 'ended'].includes(value.observer) && typeof value.truncated === 'boolean'+ && Array.isArray(value.events) && value.events.length <= 16+ && value.events.every(event => typeof event === 'string' && /^(.*)@(\d{1,8})ms$/.test(event)+ && events.has(event.split('@')[0]) && Number(event.match(/@(\d+)ms$/)[1]) <= 86400000)+ && Object.keys(value).sort().join(',') === 'close,events,exit,exitCode,observer,presentAfterRemoval,removal,signalCode,truncated,v';+ if (!valid) { observations.delete(dir); continue; }+ observations.set(dir, { ...value, owner: safeOwner(owner) ? owner : 'unavailable' });+ }+ if (incomplete) observations.delete(incomplete);+ } catch { /* missing or unreadable observations are never cleanup success */ }+ finally { try { if (fd !== undefined) closeSync(fd); } catch { /* diagnostics only */ } }+ return { owners, observations, state };+}++export function describeOwnedBrowserObservation(value, state) {+ if (!value) return `provenance=${state === 'capped' ? 'capped' : 'unavailable'}`;+ return `owner=${value.owner} provenance=${state} snapshot=last-recorded fixture-before-global-backstop exitObserved=${value.exit} closeObserved=${value.close} exitCode=${value.exitCode} signalCode=${value.signalCode}`+ + ` removal=${value.removal} presentAfterRemoval=${value.presentAfterRemoval} presentAtGlobalGuard=true`+ + ` observer=${value.observer} events=${value.events.join(',')} truncated=${value.truncated}`;+}diff --git a/server/vitest.mediaRegistry.test.js b/server/vitest.mediaRegistry.test.jsindex 954000397e..3623d0cf1f 100644--- a/server/vitest.mediaRegistry.test.js+++ b/server/vitest.mediaRegistry.test.js@@ -12,12 +12,38 @@ it.each(['run', 'skip', 'collection-failure'])('isolates boot imports and explicconst consumer = fileURLToPath(new URL('./test/fixtures/mediaRegistryImport.js', import.meta.url));const vitest = fileURLToPath(new URL('./node_modules/vitest/vitest.mjs', import.meta.url));const vitestApi = fileURLToPath(new URL('./node_modules/vitest/dist/index.js', import.meta.url));+ const wrappedEnvironment = join(root, 'environment.mjs');+ writeFileSync(wrappedEnvironment, `+ import environment from ${JSON.stringify(environment)};+ import { channel } from 'node:diagnostics_channel';+ import { writeFileSync } from 'node:fs';+ const lifecycle = channel('portos.composition-browser.lifecycle');+ export default { ...environment, async setup(global, options) {+ const priorSubscriber = lifecycle.hasSubscribers;+ const owner = await environment.setup(global, options);+ return { async teardown() {+ await owner.teardown();+ const child = lifecycle[Symbol.for('portos.synthetic-disposal-child')];+ writeFileSync(child.mark, JSON.stringify({ priorSubscriber, afterSubscriber: lifecycle.hasSubscribers,+ exit: child.listenerCount('exit'), close: child.listenerCount('close') }));+ } };+ } };+ `);const config = join(root, 'vitest.config.mjs');- writeFileSync(config, `export default { test: { environment: ${JSON.stringify(environment)}, setupFiles: [${JSON.stringify(setup)}], maxWorkers: 1, fileParallelism: false } };`);+ writeFileSync(config, `export default { test: { environment: ${JSON.stringify(wrappedEnvironment)}, setupFiles: [${JSON.stringify(setup)}], maxWorkers: 1, fileParallelism: false } };`);for (const name of ['first', 'second']) {writeFileSync(join(root, `${name}.test.mjs`), `import { it, expect } from ${JSON.stringify(vitestApi)};import { readFileSync, writeFileSync } from 'node:fs';+ import { channel } from 'node:diagnostics_channel';+ import { EventEmitter } from 'node:events';+ const lifecycle = channel('portos.composition-browser.lifecycle');+ const child = new EventEmitter();+ child.mark = ${JSON.stringify(join(root, `${name}-disposal.json`))};+ lifecycle[Symbol.for('portos.synthetic-disposal-child')] = child;+ const profile = process.env.PORTOS_TEST_TEMP_ROOT + '/portos-composition-browser-${name}';+ lifecycle.publish({ event: 'allocated', profile });+ lifecycle.publish({ event: 'child', profile, child });import { registry } from ${JSON.stringify(consumer)};writeFileSync(${JSON.stringify(join(root, `${name}.json`))}, JSON.stringify({ path: process.env.PORTOS_MEDIA_MODELS_FILE, registry }));${mode === 'collection-failure' ? 'throw new Error("synthetic collection failure");' : ''}@@ -38,6 +64,10 @@ it.each(['run', 'skip', 'collection-failure'])('isolates boot imports and explicconst result = run();expect(result.status, result.stdout + result.stderr).toBe(mode === 'collection-failure' ? 1 : 0);if (mode === 'collection-failure') expect(result.stderr).toContain('synthetic collection failure');+ for (const name of ['first', 'second']) {+ expect(JSON.parse(readFileSync(join(root, `${name}-disposal.json`), 'utf8')))+ .toEqual({ priorSubscriber: false, afterSubscriber: false, exit: 0, close: 0 });+ }const first = JSON.parse(readFileSync(join(root, 'first.json'), 'utf8'));const second = JSON.parse(readFileSync(join(root, 'second.json'), 'utf8'));expect(first.path).not.toBe(second.path);@@ -54,3 +84,43 @@ it.each(['run', 'skip', 'collection-failure'])('isolates boot imports and explicrmSync(root, { recursive: true, force: true });}});+++it('disposes a partial observation subscription when environment setup fails and preserves its error', () => {+ const root = mkdtempSync(join(tmpdir(), 'media-setup-failure-'));+ try {+ const result = spawnSync(process.execPath, ['--input-type=module', '-e', `+ import assert from 'node:assert/strict';+ import fs from 'node:fs';+ import { syncBuiltinESMExports } from 'node:module';+ import { channel } from 'node:diagnostics_channel';+ import { EventEmitter } from 'node:events';+ const lifecycle = channel('portos.composition-browser.lifecycle');+ const child = new EventEmitter();+ const original = fs.mkdtempSync;+ const failure = new Error('synthetic registry allocation failure');+ fs.mkdtempSync = () => {+ const profile = process.env.PORTOS_TEST_TEMP_ROOT + '/portos-composition-browser-setup';+ lifecycle.publish({ event: 'allocated', profile });+ lifecycle.publish({ event: 'child', profile, child });+ throw failure;+ };+ syncBuiltinESMExports();+ const { default: environment } = await import(${JSON.stringify(new URL('./test/mediaRegistryEnvironment.js', import.meta.url).href)});+ await assert.rejects(environment.setup({ console: {} }, {}), error => error === failure);+ assert.equal(lifecycle.hasSubscribers, false);+ assert.equal(child.listenerCount('exit'), 0);+ assert.equal(child.listenerCount('close'), 0);+ fs.mkdtempSync = original;+ syncBuiltinESMExports();+ const next = await environment.setup({ console: {} }, {});+ assert.equal(lifecycle.hasSubscribers, true);+ await next.teardown();+ assert.equal(lifecycle.hasSubscribers, false);+ `], {+ env: { ...process.env, PORTOS_TEST_TEMP_ROOT: root, PORTOS_MEDIA_MODELS_FILE: '' },+ encoding: 'utf8', timeout: 20000,+ });+ expect(result.status, result.stdout + result.stderr).toBe(0);+ } finally { rmSync(root, { recursive: true, force: true }); }+});