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: make the server boot smoke hermetic (#8343)
[._.]/ Adam Eivy0976663fa8b9
diff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.mdindex c0d4995b76..06a0f52bd8 100644--- a/docs/GITHUB_ACTIONS.md+++ b/docs/GITHUB_ACTIONS.md@@ -416,7 +416,11 @@ The selected work is split across parallel jobs:- **Server tests** — full, related, or explicit feature test files. Smoke-bootsthe server on the same job when server source changed (the smoke path uses the- file backend under `NODE_ENV=test` and does not need Postgres). The install+ file backend under `NODE_ENV=test` and does not need Postgres). The smoke is+ hermetic (#8343): `scripts/smoke-boot.js` boots against a disposable install+ root seeded like a fresh install, with an allowlisted environment and+ `PORTOS_SMOKE_BOOT=1` so no scheduler, agent recovery, or peer sync starts —+ `npm run smoke` behaves the same on a clean checkout and on a live install. The installand the native-addon rebuild are skipped when a `server/node_modules` cache isrestored and its trusted-rebuild mark checks out. This job also runs`npm ci --prefix autofixer` — uncached and never skipped, because resolvingdiff --git a/scripts/lib/migrationOwnedPaths.js b/scripts/lib/migrationOwnedPaths.jsindex 6ee952b3b7..4edc8bae2c 100644--- a/scripts/lib/migrationOwnedPaths.js+++ b/scripts/lib/migrationOwnedPaths.js@@ -3,11 +3,13 @@* and that must therefore ship no `data.reference/` seed.** The enforcement is the seed's ABSENCE, asserted by the sibling test. The- * filter this list drives in `scripts/setup-data.js` (its one consumer) is- * defense in depth for a seed someone re-adds. Full rationale — and the+ * seed filter below — used by `scripts/setup-data.js` and the boot smoke's+ * disposable install (`scripts/smoke-boot.js`) — is defense in depth for a+ * seed someone re-adds. Full rationale — and the* silent data loss a seed causes here — is in* `scripts/migrations/340-cos-config-seed-repair.js`.*/+import { join } from 'path';/** Paths relative to `data/` (and to `data.reference/`), always posix-spelled. */export const MIGRATION_OWNED_PATHS = new Set([@@ -41,3 +43,15 @@ export const MIGRATION_OWNED_PATHS = new Set([// runs into another machine's rows.'cos/agents/index.order.json',]);++/**+ * A `cpSync` filter for seeding `data/` from `referenceDir`: true for every+ * source path except a migration-owned one.+ *+ * @param {string} referenceDir absolute path to the `data.reference/` being copied+ * @returns {(srcPath: string) => boolean}+ */+export function isSeedableReferencePath(referenceDir) {+ const owned = new Set([...MIGRATION_OWNED_PATHS].map((relPath) => join(referenceDir, ...relPath.split('/'))));+ return (srcPath) => !owned.has(srcPath);+}diff --git a/scripts/setup-data.js b/scripts/setup-data.jsindex e240169db5..afe00de831 100644--- a/scripts/setup-data.js+++ b/scripts/setup-data.js@@ -4,7 +4,7 @@ import { dirname, join } from 'path';import { fileURLToPath } from 'url';import { md5, buildPromptDriftTables } from './migrations/_lib.js';-import { MIGRATION_OWNED_PATHS } from './lib/migrationOwnedPaths.js';+import { isSeedableReferencePath } from './lib/migrationOwnedPaths.js';import { mergeJsonStarter } from './lib/mergeJsonStarter.js';import { rewriteAppsPortosRoot } from './lib/rewriteAppsPortosRoot.js';@@ -19,9 +19,7 @@ const referenceDir = join(rootDir, 'data.reference');// present, no-op, and leave shipped defaults where the user's settings were.// See scripts/migrations/340-cos-config-seed-repair.js for the case that// prompted it.-const migrationOwnedSeeds = new Set(- [...MIGRATION_OWNED_PATHS].map((relPath) => join(referenceDir, ...relPath.split('/'))),-);+const isSeedable = isSeedableReferencePath(referenceDir);console.log('📁 Setting up data directory...');@@ -59,7 +57,7 @@ const rewritePortosRootPlaceholder = () => {if (!existsSync(dataDir)) {console.log('📁 Creating data directory from data.reference...');mkdirSync(dataDir, { recursive: true });- cpSync(referenceDir, dataDir, { recursive: true, filter: (src) => !migrationOwnedSeeds.has(src) });+ cpSync(referenceDir, dataDir, { recursive: true, filter: isSeedable });rewritePortosRootPlaceholder();console.log('✅ Data directory created');} else {@@ -68,7 +66,7 @@ if (!existsSync(dataDir)) {const items = readdirSync(srcDir);for (const item of items) {const srcPath = join(srcDir, item);- if (migrationOwnedSeeds.has(srcPath)) continue;+ if (!isSeedable(srcPath)) continue;const destPath = join(destDir, item);const stat = statSync(srcPath);diff --git a/scripts/smoke-boot.js b/scripts/smoke-boot.jsindex 607573f36c..13b047c9e9 100644--- a/scripts/smoke-boot.js+++ b/scripts/smoke-boot.js@@ -4,12 +4,47 @@// class of bug where top-level initialization code throws (e.g. chaining// .catch on a sync function that returns undefined), which is invisible to// unit tests that import service modules in isolation.+//+// The child is a HERMETIC boot (#8343). Run from an install that holds real+// runtime data, a smoke that inherited the parent environment read that+// install's records and armed its configured background services. So the+// child gets:+// - a disposable install root (PORTOS_DATA_ROOT) seeded like a fresh install+// — a copy of the shipped `data.reference/` plus the `data/` that+// `scripts/setup-data.js` would seed from it — and the disposable-root+// marker `server/lib/dataRoot.js` requires before a worktree may honor the pin;+// - HOME / TMPDIR inside that root, so nothing reads or writes user config;+// - an allowlisted environment — no provider keys, tokens, database+// credentials, or test escape hatches from the parent;+// - a test-only database name, so even a reachable Postgres is never the+// install's real one;+// - PORTOS_SMOKE_BOOT=1, which makes boot skip schedulers, agent+// spawning/recovery, crash-recovery passes, peer polling/sync, and other+// external integrations (SMOKE_BOOT_DISABLED_STEPS in bootstrapSequence.js).+// The root is removed on every exit path, success or failure.import { spawn } from 'child_process';+import { cpSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';import { fileURLToPath } from 'url';import { dirname, join } from 'path';+import { DATA_ROOT_ENV, DISPOSABLE_ROOT_MARKER } from '../server/lib/dataRoot.js';+import { SMOKE_BOOT_ENV } from '../server/lib/runtimeEnv.js';+import { isDirectlyInvoked } from './lib/directInvocation.js';+import { isSeedableReferencePath } from './lib/migrationOwnedPaths.js';+import { rewriteAppsPortosRoot } from './lib/rewriteAppsPortosRoot.js';const __dirname = dirname(fileURLToPath(import.meta.url));+const CODE_ROOT = join(__dirname, '..');+const SERVER_ENTRY = join(CODE_ROOT, 'server', 'index.js');++/** Ends in `_test`, so `server/lib/db.js` treats it as a test database. */+export const SMOKE_DATABASE = 'portos_smoke_test';++// Only what a Node process needs to start and spawn helpers on each platform.+// Everything else — provider API keys, PORTOS_API_TOKEN, PG* credentials,+// TEST_DB_OK, MEMORY_BACKEND, a leaked PORTOS_DATA_ROOT — stays behind.+const PASSTHROUGH_ENV = ['PATH', 'Path', 'PATHEXT', 'SystemRoot', 'SYSTEMROOT', 'windir', 'ComSpec', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TZ', 'CI'];// Parse SMOKE_WINDOW_MS safely: ignore missing/empty/non-numeric values so a// bad env var can't silently reduce the window to 0ms (which would always pass).@@ -17,70 +52,134 @@ const parseMs = (v, fallback) => {const n = Number(v);return Number.isFinite(n) && n > 0 ? n : fallback;};-const SMOKE_WINDOW_MS = parseMs(process.env.SMOKE_WINDOW_MS, 4000);-// Match server/index.js's 10s graceful-shutdown budget so we don't SIGKILL a-// healthy server that's still closing Socket.IO + HTTP + DB.-const SHUTDOWN_GRACE_MS = parseMs(process.env.SMOKE_SHUTDOWN_GRACE_MS, 10000);-const POST_SIGKILL_MS = parseMs(process.env.SMOKE_POST_SIGKILL_MS, 2000);-const SERVER_ENTRY = join(__dirname, '..', 'server', 'index.js');--// Use dedicated ports so a running PortOS instance doesn't collide.-// Preserve pre-existing NODE_OPTIONS (e.g. --max-old-space-size from CI)-// and append our flags instead of replacing.-const existingNodeOpts = process.env.NODE_OPTIONS ? `${process.env.NODE_OPTIONS} ` : '';-const env = {- ...process.env,- PORT: process.env.SMOKE_PORT ?? '55559',- PORTOS_HTTP_PORT: process.env.SMOKE_HTTP_PORT ?? '55557',- NODE_ENV: 'test',- NODE_OPTIONS: `${existingNodeOpts}--unhandled-rejections=strict`-};-const child = spawn(process.execPath, [SERVER_ENTRY], {- env,- stdio: ['ignore', 'pipe', 'pipe'],- windowsHide: true-});+/**+ * Create the disposable install root: marker, private home and temp dirs, a+ * physical copy of the shipped `data.reference/` (boot migrations read it from+ * the install root; a copy, never a link, so nothing the child writes can land+ * in the checkout), and `data/` seeded from it exactly as setup-data seeds a+ * fresh install — so boot migrations see the tree a real first boot sees.+ */+export function createSmokeRoot({ codeRoot = CODE_ROOT, tmpBase = tmpdir() } = {}) {+ const root = realpathSync(mkdtempSync(join(tmpBase, 'portos-smoke-')));+ try {+ writeFileSync(join(root, DISPOSABLE_ROOT_MARKER), 'Disposable PortOS boot-smoke root; deleted when the smoke exits.\n');+ for (const dir of ['home', 'tmp']) mkdirSync(join(root, dir));+ const referenceDir = join(root, 'data.reference');+ const dataDir = join(root, 'data');+ cpSync(join(codeRoot, 'data.reference'), referenceDir, { recursive: true, dereference: true });+ cpSync(referenceDir, dataDir, { recursive: true, filter: isSeedableReferencePath(referenceDir) });+ rewriteAppsPortosRoot(dataDir, codeRoot);+ } catch (err) {+ rmSync(root, { recursive: true, force: true });+ throw err;+ }+ return root;+}-let firstErr = '';-let crashed = false;-let exitCode = null;+/** The child's complete environment — built from an allowlist, never a spread. */+export function buildSmokeEnv({ root, parentEnv = process.env }) {+ const env = {};+ for (const key of PASSTHROUGH_ENV) {+ if (parentEnv[key] !== undefined) env[key] = parentEnv[key];+ }+ const home = join(root, 'home');+ const tmp = join(root, 'tmp');+ // Preserve pre-existing NODE_OPTIONS (e.g. --max-old-space-size from CI)+ // and append our flags instead of replacing.+ const existingNodeOpts = parentEnv.NODE_OPTIONS ? `${parentEnv.NODE_OPTIONS} ` : '';+ return {+ ...env,+ NODE_ENV: 'test',+ [SMOKE_BOOT_ENV]: '1',+ [DATA_ROOT_ENV]: root,+ HOME: home,+ USERPROFILE: home,+ TMPDIR: tmp,+ TMP: tmp,+ TEMP: tmp,+ PGDATABASE: SMOKE_DATABASE,+ // Loopback only, on dedicated ports so a running PortOS instance doesn't+ // collide and nothing on the network can reach the throwaway server.+ HOST: '127.0.0.1',+ PORT: parentEnv.SMOKE_PORT ?? '55559',+ PORTOS_HTTP_PORT: parentEnv.SMOKE_HTTP_PORT ?? '55557',+ NODE_OPTIONS: `${existingNodeOpts}--unhandled-rejections=strict`+ };+}-child.stdout.on('data', (d) => process.stdout.write(`[smoke] ${d}`));-child.stderr.on('data', (d) => {- const s = d.toString();- if (!firstErr) firstErr = s;- process.stderr.write(`[smoke err] ${s}`);-});-child.on('exit', (code) => { crashed = true; exitCode = code; });+function runSmoke() {+ const SMOKE_WINDOW_MS = parseMs(process.env.SMOKE_WINDOW_MS, 4000);+ // Match server/index.js's 10s graceful-shutdown budget so we don't SIGKILL a+ // healthy server that's still closing Socket.IO + HTTP + DB.+ const SHUTDOWN_GRACE_MS = parseMs(process.env.SMOKE_SHUTDOWN_GRACE_MS, 10000);+ const POST_SIGKILL_MS = parseMs(process.env.SMOKE_POST_SIGKILL_MS, 2000);-// After the boot window either fail (child exited early) or send SIGTERM,-// wait for the child to actually terminate, and fall back to SIGKILL if it-// ignores SIGTERM.-setTimeout(() => {- if (crashed) {- console.error(`❌ Server crashed during ${SMOKE_WINDOW_MS}ms boot window (exit ${exitCode}).`);- if (firstErr) console.error('First error:\n' + firstErr);- process.exit(1);+ let root = null;+ let child = null;+ // Every exit path — success, crash, timeout, signal, a throw during setup —+ // goes through process.exit, so one synchronous 'exit' hook removes the root.+ process.on('exit', () => {+ if (child && child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');+ if (root) rmSync(root, { recursive: true, force: true, maxRetries: 3 });+ });+ for (const signal of ['SIGINT', 'SIGTERM']) {+ process.once(signal, () => {+ console.error(`❌ Smoke interrupted by ${signal}.`);+ process.exit(1);+ });}- console.log(`✅ Server survived ${SMOKE_WINDOW_MS}ms boot window.`);- let shutdownTimer = null;- let forceKillTimer = null;- child.once('exit', () => {- if (shutdownTimer) clearTimeout(shutdownTimer);- if (forceKillTimer) clearTimeout(forceKillTimer);- process.exit(0);+ root = createSmokeRoot();+ child = spawn(process.execPath, [SERVER_ENTRY], {+ cwd: root,+ env: buildSmokeEnv({ root }),+ stdio: ['ignore', 'pipe', 'pipe'],+ windowsHide: true+ });++ let firstErr = '';+ let crashed = false;+ let exitCode = null;++ child.stdout.on('data', (d) => process.stdout.write(`[smoke] ${d}`));+ child.stderr.on('data', (d) => {+ const s = d.toString();+ if (!firstErr) firstErr = s;+ process.stderr.write(`[smoke err] ${s}`);});- child.kill('SIGTERM');- shutdownTimer = setTimeout(() => {- console.warn(`⚠️ Child ignored SIGTERM after ${SHUTDOWN_GRACE_MS}ms — sending SIGKILL.`);- child.kill('SIGKILL');- // If the child still doesn't exit after SIGKILL, it's an orphan risk in CI.- // Fail the smoke instead of silently exiting 0.- forceKillTimer = setTimeout(() => {- console.error(`❌ Child did not terminate after SIGKILL (${POST_SIGKILL_MS}ms).`);+ child.on('exit', (code) => { crashed = true; exitCode = code; });++ // After the boot window either fail (child exited early) or send SIGTERM,+ // wait for the child to actually terminate, and fall back to SIGKILL if it+ // ignores SIGTERM.+ setTimeout(() => {+ if (crashed) {+ console.error(`❌ Server crashed during ${SMOKE_WINDOW_MS}ms boot window (exit ${exitCode}).`);+ if (firstErr) console.error('First error:\n' + firstErr);process.exit(1);- }, POST_SIGKILL_MS);- }, SHUTDOWN_GRACE_MS);-}, SMOKE_WINDOW_MS);+ }+ console.log(`✅ Server survived ${SMOKE_WINDOW_MS}ms boot window.`);++ let shutdownTimer = null;+ let forceKillTimer = null;+ child.once('exit', () => {+ if (shutdownTimer) clearTimeout(shutdownTimer);+ if (forceKillTimer) clearTimeout(forceKillTimer);+ process.exit(0);+ });+ child.kill('SIGTERM');+ shutdownTimer = setTimeout(() => {+ console.warn(`⚠️ Child ignored SIGTERM after ${SHUTDOWN_GRACE_MS}ms — sending SIGKILL.`);+ child.kill('SIGKILL');+ // If the child still doesn't exit after SIGKILL, it's an orphan risk in CI.+ // Fail the smoke instead of silently exiting 0.+ forceKillTimer = setTimeout(() => {+ console.error(`❌ Child did not terminate after SIGKILL (${POST_SIGKILL_MS}ms).`);+ process.exit(1);+ }, POST_SIGKILL_MS);+ }, SHUTDOWN_GRACE_MS);+ }, SMOKE_WINDOW_MS);+}++if (isDirectlyInvoked(import.meta.url)) runSmoke();diff --git a/scripts/smoke-boot.test.js b/scripts/smoke-boot.test.jsnew file mode 100644index 0000000000..5e4cb6150f--- /dev/null+++ b/scripts/smoke-boot.test.js@@ -0,0 +1,97 @@+/**+ * The boot smoke's isolation contract (#8343). Running the real smoke is too+ * slow for the suite (CI runs it as its own step), so these pin the two halves+ * a regression would silently undo: the child environment is an allowlist, and+ * the disposable root is seeded like a fresh install, resolvable from a+ * worktree, and never left behind by a failed setup.+ */+import { describe, it, expect, afterEach } from 'vitest';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { buildSmokeEnv, createSmokeRoot, SMOKE_DATABASE } from './smoke-boot.js';+import { DATA_ROOT_ENV, resolveInstallRoot } from '../server/lib/dataRoot.js';++const scratch = [];+const tempDir = (prefix) => {+ const dir = mkdtempSync(join(tmpdir(), prefix));+ scratch.push(dir);+ return dir;+};++afterEach(() => {+ delete process.env[DATA_ROOT_ENV];+ while (scratch.length) rmSync(scratch.pop(), { recursive: true, force: true });+});++describe('buildSmokeEnv', () => {+ it('passes no provider key, token, database credential, or escape hatch to the child', () => {+ const root = join(tmpdir(), 'portos-smoke-example');+ const env = buildSmokeEnv({+ root,+ parentEnv: {+ PATH: '/usr/bin',+ NODE_OPTIONS: '--max-old-space-size=4096',+ ANTHROPIC_API_KEY: 'sk-example',+ OPENAI_API_KEY: 'sk-example',+ PORTOS_API_TOKEN: 'token-example',+ PGPASSWORD: 'secret-example',+ PGDATABASE: 'portos',+ TEST_DB_OK: '1',+ MEMORY_BACKEND: 'postgres',+ PORTOS_DATA_ROOT: '/srv/live-install',+ HOME: '/home/example'+ }+ });++ for (const key of ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'PORTOS_API_TOKEN', 'PGPASSWORD', 'TEST_DB_OK', 'MEMORY_BACKEND']) {+ expect(env, key).not.toHaveProperty(key);+ }+ expect(env).toMatchObject({+ PATH: '/usr/bin',+ NODE_ENV: 'test',+ PORTOS_SMOKE_BOOT: '1',+ [DATA_ROOT_ENV]: root,+ HOME: join(root, 'home'),+ TMPDIR: join(root, 'tmp'),+ PGDATABASE: SMOKE_DATABASE,+ HOST: '127.0.0.1',+ NODE_OPTIONS: '--max-old-space-size=4096 --unhandled-rejections=strict'+ });+ expect(SMOKE_DATABASE).toMatch(/_test$/);+ });+});++describe('createSmokeRoot', () => {+ const buildCodeRoot = () => {+ const codeRoot = tempDir('portos-smoke-code-');+ const reference = join(codeRoot, 'data.reference');+ mkdirSync(join(reference, 'private'), { recursive: true });+ writeFileSync(join(reference, 'providers.json'), '{"providers":{}}\n');+ writeFileSync(join(reference, 'apps.json'), '{"apps":{"portos-default":{"repoPath":"__PORTOS_ROOT__"}}}\n');+ // Migration-owned: setup-data never seeds it, so neither may the smoke.+ writeFileSync(join(reference, 'private', 'api-keys.json'), '{}\n');+ return codeRoot;+ };++ it('seeds a fresh-install tree that a worktree-executing server resolves to', () => {+ const codeRoot = buildCodeRoot();+ const root = createSmokeRoot({ codeRoot, tmpBase: tempDir('portos-smoke-base-') });++ expect(existsSync(join(root, 'data.reference', 'providers.json'))).toBe(true);+ expect(existsSync(join(root, 'data', 'providers.json'))).toBe(true);+ expect(existsSync(join(root, 'data', 'private', 'api-keys.json'))).toBe(false);+ expect(JSON.parse(readFileSync(join(root, 'data', 'apps.json'), 'utf8')).apps['portos-default'].repoPath).toBe(codeRoot);+ for (const dir of ['home', 'tmp']) expect(existsSync(join(root, dir)), dir).toBe(true);++ process.env[DATA_ROOT_ENV] = root;+ expect(resolveInstallRoot(join(codeRoot, 'data', 'cos', 'worktrees', 'claim-issue-1'))).toBe(root);+ });++ it('removes its partial tree when seeding fails', () => {+ const codeRoot = tempDir('portos-smoke-code-'); // no data.reference/+ const tmpBase = tempDir('portos-smoke-base-');+ expect(() => createSmokeRoot({ codeRoot, tmpBase })).toThrow();+ expect(readdirSync(tmpBase)).toEqual([]);+ });+});diff --git a/server/index.js b/server/index.jsindex e8afd0b473..6e72ec6002 100644--- a/server/index.js+++ b/server/index.js@@ -10,6 +10,7 @@ import { certPaths } from '../lib/certPaths.js';import { getBuildId, getStampedIndexHtml } from './lib/buildId.js';import { getBuildIdentity } from './lib/buildIdentity.js';import { PORTS } from './lib/ports.js';+import { isSmokeBoot } from './lib/runtimeEnv.js';import alertsRoutes from './routes/alerts.js';import appleHealthRoutes from './routes/appleHealth.js';@@ -523,6 +524,9 @@ getBuildIdentity().catch((err) => console.error(`❌ Build identity probe failedrunBootSequence({ io, httpServer, localHttpServer, httpsEnabled, port: PORT, host: HOST, spawnerReady });// Opt-in listener only: restores host configuration without generating tokens.-import('./services/fleetLlmHost.js').then(({ startFleetLlmHost }) => startFleetLlmHost())- .catch(() => console.error('❌ Dedicated model host listener could not start; open AI Providers → Model host setup.'));+// The boot smoke (#8343) opens no listener beyond the API server it probes.+if (!isSmokeBoot()) {+ import('./services/fleetLlmHost.js').then(({ startFleetLlmHost }) => startFleetLlmHost())+ .catch(() => console.error('❌ Dedicated model host listener could not start; open AI Providers → Model host setup.'));+}registerShutdownHandlers({ io, httpServer, localHttpServer });diff --git a/server/lib/README.md b/server/lib/README.mdindex 62997ba53f..e4159401bc 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -322,7 +322,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `comparisonModelScope.js` | `catalogSlugForProviderModel(id)` / `providerCatalogSlugs(inventory)` — map provider model ids (Bedrock region prefixes, gateway namespaces, effort/quantization suffixes, dashed versions) onto canonical model identities for scoping shipped reference-price rows to models PortOS can dispatch. Pure. || `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record loop — the peer:online convergence push and every base-hash-evicting `pruneTombstoned*` loop — collapses N `sync_base_hashes.json` rewrites into one terminal write (depth-counted, so concurrent batches merge too; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned, so those paths don't let the side store grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). The base-hash file is read STRICT (`readJSONFileStrict`): a present-but-unreadable `sync_base_hashes.json` latches `_persistBlocked` — `flushBaseHashes()` no-ops so the file is preserved, `maybeJournalBeforeOverwrite` journals every overwrite fail-closed, `detectConflict` reports `baseUnavailable`, and `isBaseHashPersistBlocked()` exposes the latch to the conflict-journal status payload (#7260). Local-only — never crosses the wire. || `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), `catalogEnvelopeHasLiveRows()` (shared live-row versus tombstone gate for catalog transfers), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |-| `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `resolveCodeRootForModule(moduleUrl)` is the single source of truth for the "two directories above this file" depth assumption — `paths.js`'s `CODE_ROOT` and `services/userActions.js`'s data-root guard both derive through it so they cannot silently drift apart. `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |+| `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `resolveCodeRootForModule(moduleUrl)` is the single source of truth for the "two directories above this file" depth assumption — `paths.js`'s `CODE_ROOT` and `services/userActions.js`'s data-root guard both derive through it so they cannot silently drift apart. `DATA_ROOT_ENV` is the env-var name constant. The one pin a worktree-executing process honors is a DISPOSABLE root — one carrying `DISPOSABLE_ROOT_MARKER` (`isDisposableRoot(dir)`), which the boot smoke creates (#8343); a live install never carries it. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. || `downloadPreflight.js` | Free-disk preflight + resumable weight download. `assessDownloadPreflight({ destPath, expectedBytes })` → `{ freeBytes, requiredBytes, headroomBytes, verdict: ok\|tight\|insufficient }`; `assertDownloadFits` throws typed `DISK_INSUFFICIENT` (507) when the volume cannot hold the payload. `streamResumableDownload` Range-resumes a `.partial` on transport failure, discards it on user cancel, and verifies a published sha256 before rename. `sweepOrphanedPartials(dirs, { maxAgeMs })` unlinks leftover `.partial` (+ `.partial.etag`) files older than 7 days (default) and skips recent/in-flight dests; missing dirs are a no-op. `probeRemoteSize` / `siblingDownloadMeta` / `verifyDownloadHash` are the size+digest helpers the four weight-download entry points share. `createDownloadSlot({ codePrefix, idleStallEnvVar, exclusive, keepPartialOnCancel })` is the one transfer-slot registry a weight download claims before its first await — in-flight map, abort controller carrying a cancel/stall reason, typed `<PREFIX>_DOWNLOAD_IN_FLIGHT`/`_STALLED`/`_CANCELLED` errors, a per-chunk progress throttle, and an `isInFlight(path)` predicate covering the dest, its `.partial`, and shards under a claimed directory. Call it at module scope only. `isAnyDownloadInFlight` answers for every registered slot at once, which is how the orphaned-partial GC protects live transfers. || `agentInstructionsFile.js` | The `AGENTS.md` + bridge `CLAUDE.md` pair a repo carries (#4852). `writeAgentInstructions(repoPath, content)` writes the body to `AGENTS.md` and the one-line `@AGENTS.md` import beside it — use it in scaffolders instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)`, since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: `AGENT_INSTRUCTIONS_FILENAME`, `CLAUDE_BRIDGE_FILENAME`, `AGENT_INSTRUCTIONS_IMPORT`. || `scaffoldSnippets.js` | Shared generated-project source snippets: `CORS_SNIPPET` provides dependency-free Express CORS middleware for the Express, PortOS, and Vite scaffold generators. |@@ -698,7 +698,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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, and deterministic federation-identity doubles (`mockTestIdentity`). || `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. 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. |+| `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). || `testHelper.js` | Test helpers: `request()` (supertest-style HTTP) + `mockJsonResponse`/`mockTextResponse` (fetch `Response` mocks with `.text()`, `.json()`, and a `headers.get` content-type), `startLoopbackServer(app)`/`closeLoopbackServer(server)`/`waitForAbort(signal)` for tests that need a real socket (raw disconnects, SSE streaming) that `request()`'s run-to-completion fetch harness can't model, plus the source-scan pair `collectServerSources()` / `readServerSource(rel)` (and `SERVER_DIR`) used by the whole-tree guard suites — `spawnCwd.test.js` (#3193) and `cliChildEnv.test.js` (#3194). Those guards overlap deliberately, so they share one definition of "a source file"; change the ignore rules here and both move together. Cross-platform trio: `posixPath(v)` normalizes a RECEIVED path before comparing it to a POSIX-spelled literal (no-op on POSIX — never normalize the expectation, which would hide a genuinely wrong path), and `resolveTestPython()` returns an interpreter that actually runs, probing by execution because Windows ships a `python` Store-alias stub that exists but fails; `null` when there is none, for `describe.skipIf`; `pinPlatform(value)` pins `process.platform` and returns a restore that reinstates the ORIGINAL descriptor (deleting the pin when there was none) — it carries the one hazard every hand-rolled pin had to rediscover: never pin above an import that loads a native addon, which picks its prebuilt binary off the platform at load time (#4085). Python-shelling suites also take their two nested budgets from here: `PY_TEST_TIMEOUT_MS` (vitest per-test, passed as `it()`'s third argument — a real interpreter's wall time tracks machine load, not the assertion, so a ~4s case crosses the tight global 10s `testTimeout` on a contended full-suite worker) and the strictly smaller `PY_SUBPROCESS_TIMEOUT_MS` (every `execFileSync` spawn's own `timeout`, so a hung interpreter trips the spawn guard first and names the command instead of producing a bare vitest timeout; a subprocess allowance ABOVE the vitest budget is dead intent — vitest always wins). |diff --git a/server/lib/dataRoot.js b/server/lib/dataRoot.jsindex aae52f132f..5edc28ba3a 100644--- a/server/lib/dataRoot.js+++ b/server/lib/dataRoot.js@@ -15,12 +15,26 @@* worktree-rooted process so callers (boot migrations) can skip work that* assumes the real install tree instead of crashing.*/+import { existsSync } from 'fs';import { dirname, isAbsolute, join, resolve as resolvePath, sep } from 'path';import { fileURLToPath } from 'url';/** Env var a real launch sets to pin the install root (see ecosystem.config.cjs). */export const DATA_ROOT_ENV = 'PORTOS_DATA_ROOT';+/**+ * Marker file that declares an install root DISPOSABLE — a throwaway tree a+ * harness created for one process (the server boot smoke, #8343) and deletes+ * afterwards. Such a root holds no live data, so it is the one pin a+ * worktree-executing process may honor: the leak-safety rule below exists to+ * keep worktree code off the LIVE install, and a live install never carries+ * this marker.+ */+export const DISPOSABLE_ROOT_MARKER = '.portos-disposable-root';++/** True when `rootDir` carries the disposable-root marker. */+export const isDisposableRoot = (rootDir) => existsSync(join(rootDir, DISPOSABLE_ROOT_MARKER));+/*** The executing checkout's root, derived from a caller's `import.meta.url`* (two directories up from wherever that module physically lives). Single@@ -69,19 +83,22 @@ export function resolveInstallRoot(fallbackRoot) {// data. When the fallback (the executing location) is itself a worktree, ignore// the override and stay on the worktree path — where the migration backstop// safely skips and PATHS.data points at the worktree's own (empty) tree.- if (isWorktreeRoot(fallbackRoot)) return fallbackRoot;+ //+ // The single exception is a pin to a DISPOSABLE root (marker file above): it+ // holds no live data by construction, so honoring it from a worktree is what+ // lets `npm run smoke` stay hermetic there too instead of writing into the+ // worktree's own `data/`.const override = process.env[DATA_ROOT_ENV];- if (typeof override === 'string' && override.trim() !== '') {- const trimmed = override.trim();- const resolved = isAbsolute(trimmed) ? trimmed : resolvePath(trimmed);- // Symmetric leak-safety: never let the data root resolve INTO a worktree,- // whether the worktree path came from the executing location (above) or a- // misconfigured override. A worktree has no runtime data/ tree, so honoring- // such an override would strand the real process on an empty tree.- if (isWorktreeRoot(resolved)) return fallbackRoot;- return resolved;- }- return fallbackRoot;+ if (typeof override !== 'string' || override.trim() === '') return fallbackRoot;+ const trimmed = override.trim();+ const resolved = isAbsolute(trimmed) ? trimmed : resolvePath(trimmed);+ // Symmetric leak-safety: never let the data root resolve INTO a worktree,+ // whether the worktree path came from the executing location (below) or a+ // misconfigured override. A worktree has no runtime data/ tree, so honoring+ // such an override would strand the real process on an empty tree.+ if (isWorktreeRoot(resolved)) return fallbackRoot;+ if (isWorktreeRoot(fallbackRoot) && !isDisposableRoot(resolved)) return fallbackRoot;+ return resolved;}/**diff --git a/server/lib/dataRoot.test.js b/server/lib/dataRoot.test.jsindex 4f1ec5bbf6..bb983959a7 100644--- a/server/lib/dataRoot.test.js+++ b/server/lib/dataRoot.test.js@@ -1,6 +1,8 @@import { describe, it, expect, afterEach, vi } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';import { join, sep } from 'path';-import { DATA_ROOT_ENV, resolveInstallRoot, isWorktreeRoot } from './dataRoot.js';+import { DATA_ROOT_ENV, DISPOSABLE_ROOT_MARKER, resolveInstallRoot, isWorktreeRoot } from './dataRoot.js';const REAL_ROOT = join(sep, 'Users', 'me', 'PortOS');@@ -58,6 +60,30 @@ describe('resolveInstallRoot', () => {const worktreeFallback = join(REAL_ROOT, 'data', 'cos', 'worktrees', 'agent-abc');expect(resolveInstallRoot(worktreeFallback)).toBe(worktreeFallback);});++ describe('disposable roots (boot smoke, #8343)', () => {+ let disposable;+ afterEach(() => {+ if (disposable) rmSync(disposable, { recursive: true, force: true });+ disposable = undefined;+ });+ const worktreeFallback = join(REAL_ROOT, 'data', 'cos', 'worktrees', 'claim-issue-1');++ it('lets a worktree-executing process honor a pin to a marked disposable root', () => {+ // Without this the smoke, run from a worktree, would boot on the+ // worktree's own data/ instead of its throwaway tree.+ disposable = mkdtempSync(join(tmpdir(), 'portos-dataroot-test-'));+ writeFileSync(join(disposable, DISPOSABLE_ROOT_MARKER), '');+ process.env[DATA_ROOT_ENV] = disposable;+ expect(resolveInstallRoot(worktreeFallback)).toBe(disposable);+ });++ it('still refuses an UNMARKED pin from a worktree — the live install carries no marker', () => {+ disposable = mkdtempSync(join(tmpdir(), 'portos-dataroot-test-'));+ process.env[DATA_ROOT_ENV] = disposable;+ expect(resolveInstallRoot(worktreeFallback)).toBe(worktreeFallback);+ });+ });});describe('isWorktreeRoot', () => {diff --git a/server/lib/runtimeEnv.js b/server/lib/runtimeEnv.jsindex 9e9624b5b8..8b2aa71619 100644--- a/server/lib/runtimeEnv.js+++ b/server/lib/runtimeEnv.js@@ -39,8 +39,8 @@ export function isTestRunner() {* escape hatch (see AGENTS.md "Storage backend policy"), and `scripts/* smoke-boot.js` sets it on the real `server/index.js` boot specifically so* CI can smoke-test the server without Postgres. That smoke-booted server- * legitimately writes its own runtime files into the real `data/` tree — the- * exact thing `lib/testDataIsolation.js`'s write guard exists to catch a+ * legitimately writes its own runtime files into its (disposable, #8343)+ * `data/` tree — the exact thing `lib/testDataIsolation.js`'s write guard exists to catch a* *test suite* doing. Only `process.env.VITEST` (set by every Vitest worker,* never by a bare `node` invocation) tells the two apart, so the write guard* gates on this, not `isTestRunner()`.@@ -50,3 +50,22 @@ export function isTestRunner() {export function isVitestRunner() {return process.env.VITEST != null;}++/** Env var `scripts/smoke-boot.js` sets on the server it boots (#8343). */+export const SMOKE_BOOT_ENV = 'PORTOS_SMOKE_BOOT';++/**+ * Is this process the server boot smoke?+ *+ * The smoke proves `server/index.js` boots and stays up; it must not DO+ * anything while up. Boot consults this to skip the autonomous work a real+ * install arms at startup — schedulers, CoS agent spawning/recovery, crash+ * recovery passes, peer polling/sync, share watchers, local-LLM backend+ * startup, the fleet model host. `NODE_ENV=test` cannot carry that meaning:+ * it only selects the file storage backend.+ *+ * @returns {boolean}+ */+export function isSmokeBoot() {+ return process.env[SMOKE_BOOT_ENV] === '1';+}diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 5fecab1f8e..3e2a21fd2f 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -22,7 +22,7 @@* queue an AI provider call. Boot only loads on-disk state and ARMS schedulers;* every scheduler here is off by default or user-configured.*/-import { isTestRunner } from '../lib/runtimeEnv.js';+import { isTestRunner, isSmokeBoot } from '../lib/runtimeEnv.js';import { readPortosEnvValue } from '../lib/portosEnv.js';import { join } from 'path';import { resolveInstallRoot } from '../lib/dataRoot.js';@@ -52,7 +52,8 @@ import {runDbAndCatalogMigrations,warmMandatoryStores,initCosAfterSpawner,- armCommissionScheduler+ armCommissionScheduler,+ gateStepsForSmokeBoot} from './bootstrapSequence.js';import { ensureBackendProvider, getBackend as getLocalLlmBackend } from './localLlm.js';@@ -232,7 +233,13 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD// The ORDER these run in is `runPreRouteSequence`'s contract (see// bootstrapSequence.js); this object is only the "what".- return runPreRouteSequence({+ //+ // Under the boot smoke (#8343) the steps that would start local-LLM backends,+ // the auto-fixer, or the CoS spawner (runner connection + agent recovery) are+ // no-ops — see SMOKE_BOOT_DISABLED_STEPS.+ const smokeBoot = isSmokeBoot();+ if (smokeBoot) console.log('🧪 Smoke boot: startup jobs, agent recovery, and external integrations are disabled');+ return runPreRouteSequence(gateStepsForSmokeBoot({// Apply pending data migrations BEFORE the AI toolkit reads stage-config.json// and providers.json. Without this, a plain pull-and-restart (no update.sh)// leaves new prompt stages and other shipped data changes unregistered —@@ -357,7 +364,7 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD// The CoS agent spawner (event wiring + orphan cleanup), initialized// explicitly now that the runner registration + task learning are ready.startSpawner: initSpawner- });+ }, 'preRoute', smokeBoot));};/**@@ -861,7 +868,7 @@ const announceListening = ({ io, httpServer, localHttpServer, httpsEnabled, port* the background and any fatal step exits the process itself).*/export const runBootSequence = ({ io, httpServer, localHttpServer, httpsEnabled, port, host, spawnerReady }) =>- runPostRouteSequence({+ runPostRouteSequence(gateStepsForSmokeBoot({startBackgroundServices: () => startBackgroundServices({ spawnerReady, io }),// Instance identity + sync log come up before requests are accepted, so a@@ -915,7 +922,7 @@ export const runBootSequence = ({ io, httpServer, localHttpServer, httpsEnabled,// that won't load is a real breakage) but never the backfill itself.loadSeriesCoverBackfill: async () => (await import('../scripts/backfillSeriesCoverImages.js')).backfillSeriesCoverImages,- startListening: () => httpServer.listen(port, host, () => runPostListenSequence({+ startListening: () => httpServer.listen(port, host, () => runPostListenSequence(gateStepsForSmokeBoot({announceListening: () => announceListening({ io, httpServer, localHttpServer, httpsEnabled, port }),// Process-level safety net, wired with the io instance so unhandled// failures also surface in the UI.@@ -932,8 +939,8 @@ export const runBootSequence = ({ io, httpServer, localHttpServer, httpsEnabled,.catch((err) => logBootstrapFailure('⚠️ tailcat serve restore failed', err, console.warn));},initSyncOrchestrator- }))- });+ }, 'postListen', isSmokeBoot())))+ }, 'postRoute', isSmokeBoot()));// Run an async close but resolve anyway after `ms` — so a close that never// settles (e.g. a WebSocket-upgraded socket the server no longer tracks, or adiff --git a/server/services/bootstrapSequence.js b/server/services/bootstrapSequence.jsindex d72bf79570..2490487d76 100644--- a/server/services/bootstrapSequence.js+++ b/server/services/bootstrapSequence.js@@ -32,6 +32,38 @@ const logFailure = (label) => (err) => console.error(`❌ ${label}: ${err?.messa/** Same, but keeping the stack — used where a failure is worth a full trace. */const logFailureWithStack = (label) => (err) => console.error(`❌ ${label}: ${err?.stack ?? err}`);+/**+ * Steps the server boot smoke (`scripts/smoke-boot.js`, #8343) replaces with+ * no-ops, per phase. The smoke proves boot survives; these are the steps that+ * would make it DO something — arm schedulers, spawn or recover CoS agents,+ * replay crash recovery, watch share buckets, poll or sync peers, start a local+ * LLM backend. Everything else (migrations, toolkit construction, store+ * checks, the media queue, the DB gate, listen) still runs, because a throw in+ * any of those is exactly what the smoke exists to catch.+ */+export const SMOKE_BOOT_DISABLED_STEPS = Object.freeze({+ preRoute: Object.freeze(['ensureLocalLlmBackend', 'initAutoFixer', 'startSpawner']),+ postRoute: Object.freeze([+ 'startBackgroundServices',+ 'recoverStuckClassifications',+ 'recoverInterruptedRepoClones',+ 'initSharing',+ 'recoverCreativeDirectorProjects'+ ]),+ postListen: Object.freeze(['startPolling', 'initSyncOrchestrator'])+});++/**+ * Return `steps` with the phase's smoke-disabled steps swapped for no-ops when+ * `smokeBoot` is set; otherwise `steps` unchanged.+ */+export const gateStepsForSmokeBoot = (steps, phase, smokeBoot) => {+ if (!smokeBoot) return steps;+ const disabled = SMOKE_BOOT_DISABLED_STEPS[phase];+ if (!disabled) throw new Error(`Unknown boot phase: ${phase}`);+ return { ...steps, ...Object.fromEntries(disabled.map((name) => [name, () => undefined])) };+};+/*** Pre-route boot ordering (`bootstrapServices`).*diff --git a/server/services/bootstrapSequence.test.js b/server/services/bootstrapSequence.test.jsindex af394a06dd..1c0679df58 100644--- a/server/services/bootstrapSequence.test.js+++ b/server/services/bootstrapSequence.test.js@@ -28,7 +28,8 @@ import {warmMandatoryStores,runDatabasePhase,runPostRouteSequence,- runPostListenSequence+ runPostListenSequence,+ gateStepsForSmokeBoot} from './bootstrapSequence.js';const __dirname = dirname(fileURLToPath(import.meta.url));@@ -105,6 +106,22 @@ describe('runPreRouteSequence — pre-route boot order', () => {]);});+ it('under the boot smoke (#8343), migrates and builds the toolkit but starts no local LLM, auto-fixer, or spawner', async () => {+ const recorder = createRecorder();+ const { spawnerReady } = await runPreRouteSequence(gateStepsForSmokeBoot(buildDeps(recorder), 'preRoute', true));+ await spawnerReady;+ expect(recorder.calls).toEqual([+ 'applyDataMigrations',+ 'loadUsage',+ 'verifyCollections',+ 'createToolkit',+ 'registerToolkitShims',+ 'warmProviders',+ 'registerRunners',+ 'initTaskLearning'+ ]);+ });+it('returns the constructed toolkit and a spawner promise', async () => {const recorder = createRecorder();const { aiToolkit, spawnerReady } = await runPreRouteSequence(buildDeps(recorder));@@ -535,6 +552,28 @@ describe('runPostRouteSequence — post-route boot order', () => {expect(deps.onFatal).not.toHaveBeenCalled();});+ it('under the boot smoke (#8343), arms no background services and replays no recovery, but still listens', async () => {+ const recorder = createRecorder();+ const deps = buildDeps(recorder);+ await runPostRouteSequence(gateStepsForSmokeBoot(deps, 'postRoute', true));+ expect(recorder.calls).toEqual([+ 'ensureSelf',+ 'initSyncLog',+ 'initMediaJobQueue',+ 'initMediaJobDependentHooks',+ 'runDatabasePhase',+ 'loadSeriesCoverBackfill',+ 'backfillSeriesCoverImages',+ 'startListening'+ ]);+ expect(deps.onFatal).not.toHaveBeenCalled();+ });++ it('leaves every step in place outside the boot smoke', () => {+ const deps = buildDeps(createRecorder());+ expect(gateStepsForSmokeBoot(deps, 'postRoute', false)).toBe(deps);+ });+it('arms the background services synchronously, before the chain awaits anything', () => {const recorder = createRecorder();const promise = runPostRouteSequence(buildDeps(recorder));@@ -706,6 +745,12 @@ describe('runPostListenSequence — inside the listen callback', () => {]);});+ it('under the boot smoke (#8343), never starts peer polling or sync', async () => {+ const recorder = createRecorder();+ await runPostListenSequence(gateStepsForSmokeBoot(buildDeps(recorder), 'postListen', true));+ expect(recorder.calls).toEqual(['announceListening', 'setupProcessErrorHandlers', 'backfillOriginInstanceId']);+ });+it('does not start peer polling until origin tags are backfilled', async () => {const recorder = createRecorder();const gate = deferred();@@ -773,6 +818,15 @@ describe('boot source contract', () => {expect(SEQUENCE).not.toMatch(/\bimport\s/);});+ it('bootstrap.js gates every boot phase on the smoke flag (#8343)', () => {+ // Dropping one of these leaves the smoke arming that phase's schedulers,+ // agent recovery, or peer sync against whatever install it booted from.+ for (const phase of ['preRoute', 'postRoute', 'postListen']) {+ expect(BOOTSTRAP, `bootstrap.js never gates the ${phase} phase for the boot smoke`)+ .toMatch(new RegExp(`'${phase}', (smokeBoot|isSmokeBoot\\(\\))\\)`));+ }+ });+it('bootstrap.js delegates its ordering to the tested sequence module', () => {expect(BOOTSTRAP).toMatch(/from '\.\/bootstrapSequence\.js'/);for (const fn of ['runPreRouteSequence', 'runPostRouteSequence', 'runPostListenSequence', 'runDatabasePhase']) {