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
split this install's federation identity out of services/instances.js (#6836)
[._.]/ Adam Eivybd17285bce1a
diff --git a/server/lib/README.md b/server/lib/README.mdindex 02768be1d6..e41527f4e4 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -607,7 +607,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `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). 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` and no-peer record creation guards. |+| `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. || `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/importScoping.test.js b/server/lib/importScoping.test.jsindex b2903fa05d..89ac567b87 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -25,7 +25,7 @@import { describe, it, expect } from 'vitest';import { existsSync, readdirSync, readFileSync } from 'fs';-import { dirname, join, resolve } from 'path';+import { dirname, join, relative, resolve, sep } from 'path';import { fileURLToPath } from 'url';import { staticImportClosure, staticImportSpecifiers } from './staticImportGraph.js';@@ -78,6 +78,16 @@ const NARROWED = ['needs only the pure pipelineStages.js identity leaf'],['services/cosTaskIntake.js', 'lib/validation.js','needs SWARM_COUNT_* and the reviewer normalizers, which cosValidation.js / reviewerConfig.js declare'],+ ['services/brainStorage.js', 'services/instances.js',+ 'needs getInstanceId, which instanceIdentity.js declares'],+ ['services/memoryDB.js', 'services/instances.js',+ 'needs getInstanceId, which instanceIdentity.js declares'],+ ['services/worktreeManager.js', 'services/instances.js',+ 'needs getInstanceId, which instanceIdentity.js declares'],+ ['services/catalogDB/ingredients.js', 'services/instances.js',+ 'needs getInstanceId, which instanceIdentity.js declares'],+ ['routes/systemHealth.js', 'services/instances.js',+ 'needs getInstanceId, which instanceIdentity.js declares'],];describe('narrowed imports stay narrow (#6009)', () => {@@ -101,6 +111,7 @@ describe('narrowed imports stay narrow (#6009)', () => {expect(reaches('lib/llmRoutePin.js', 'lib/textUtils.js')).toBe(true);expect(reaches('lib/slashdoInvocation.js', 'lib/providerVendors.js')).toBe(true);expect(reaches('services/voice/tools/pipeline.js', 'lib/pipelineStages.js')).toBe(true);+ expect(reaches('services/instances.js', 'services/instanceIdentity.js')).toBe(true);});// And a control on the other side: the barrels themselves still reach what@@ -133,6 +144,35 @@ describe('Tailcat shared owners stay independent of forwarding (#6570)', () => {});});+// This install's federation identity moved out of services/instances.js into+// its own leaf (#6836) so a one-line id read no longer statically loads the+// peer-orchestration closure — the Tailscale status parser, the+// federated-media probe, and the socket relay — that instances.js pulls in.+describe('instance identity stays a leaf (#6836)', () => {+ it('reaches no server/services/* module besides itself', () => {+ const closure = staticImportClosure(abs('services/instanceIdentity.js')).files;+ const servicesLeaks = [...closure]+ .filter((file) => file !== abs('services/instanceIdentity.js'))+ .filter((file) => relative(SERVER_DIR, file).startsWith(`services${sep}`));+ expect(servicesLeaks, `instanceIdentity.js must stay a leaf — also reaches: ${servicesLeaks.map((f) => relative(SERVER_DIR, f)).join(', ')}`).toEqual([]);+ });++ it('reaches none of the peer-orchestration modules the pre-split id read used to drag in', () => {+ const closure = staticImportClosure(abs('services/instanceIdentity.js')).files;+ expect(closure.has(abs('lib/tailscale.js'))).toBe(false);+ expect(closure.has(abs('lib/peerHttpClient.js'))).toBe(false);+ expect(closure.has(abs('services/peerSocketRelay.js'))).toBe(false);+ expect(closure.has(abs('services/federatedMediaConsumer.js'))).toBe(false);+ });++ // Positive control: without this, a broken resolver could make the leaf+ // closure look empty and the negatives above would pass vacuously.+ it('still reaches the file I/O + mutex helpers it declares', () => {+ expect(reaches('services/instanceIdentity.js', 'lib/fileUtils.js')).toBe(true);+ expect(reaches('services/instanceIdentity.js', 'lib/asyncMutex.js')).toBe(true);+ });+});+/*** Deferred imports (#6156).*@@ -340,7 +380,18 @@ describe('deferred imports stay deferred (#6156)', () => {// `validation.js`'s flat re-export, per the #6617 note above), so the new leaf// contributes +1 to each of those ~230 closures and pulls in nothing new.// Measured against current main: 103,076 -> 103,308. Restore the ~1.5k allowance.-const MAX_STATIC_INSTANTIATIONS = 104808;+//+// #6836 is the opposite shape — a DECREASE, not a new leaf's small additive+// cost: this install's federation identity (UNKNOWN_INSTANCE_ID, ensureSelf,+// getSelf, getInstanceId, ensureInstanceId, updateSelf, the data/instances.json+// file I/O + mutex) moved out of services/instances.js into the dependency-free+// services/instanceIdentity.js leaf above. The 22 callers that only needed an+// id read no longer statically load instances.js's peer-orchestration closure+// (the Tailscale status parser, the federated-media probe, the socket relay,+// ~30 modules). Measured against current main: 103,462 -> 101,702 (-1,760);+// suites whose closure reaches services/instances.js: 181 -> 33. Lower the+// ceiling to the new measured total plus the standard ~1.5k allowance.+const MAX_STATIC_INSTANTIATIONS = 103202;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);@@ -392,6 +443,22 @@ const closureSize = (entry) => {return seen.size;};+// Same memoized walk as closureSize, but stops the moment it finds `target`+// instead of counting the whole closure — used by the #6836 reach-count test+// below, which only needs a yes/no per file, not a total.+const closureReaches = (entry, target) => {+ const seen = new Set();+ const stack = [entry];+ while (stack.length) {+ const file = stack.pop();+ if (file === target) return true;+ if (seen.has(file)) continue;+ seen.add(file);+ for (const dep of resolvedDeps(file)) if (!seen.has(dep)) stack.push(dep);+ }+ return false;+};+describe('server suite import budget (#6156)', () => {it('memoized closure walk agrees with staticImportClosure', () => {// A spread of entry points: two modules this PR touched, one heavy suite,@@ -419,6 +486,23 @@ describe('server suite import budget (#6156)', () => {`Static module instantiations across the server suite rose to ${total.toLocaleString()}. Something added an eager import into a heavy subtree from a widely-reached module — narrow it, defer it with a call-site await import(), or raise the budget deliberately. See the "Import scoping" section of server/AGENTS.md.`,).toBeLessThanOrEqual(MAX_STATIC_INSTANTIATIONS);}, 60_000);++ // #6836: before the identity leaf split, 181 of these files' closures reached+ // services/instances.js — for most of them (the 22 direct identity-only+ // callers plus everything downstream of the 46 test doubles) only because a+ // static id-read reachability chain touched it, not because the suite+ // actually exercises peer orchestration. Reuses the same memoized dep cache+ // as the instantiation-count walk above, so the extra pass costs a graph+ // traversal, not re-parsing.+ it('keeps fewer than 60 server test files statically reaching services/instances.js', () => {+ const files = serverTestFiles();+ const target = abs('services/instances.js');+ const reachingCount = files.filter((file) => closureReaches(file, target)).length;+ expect(+ reachingCount,+ `${reachingCount} server test files still statically reach services/instances.js (was 181 before #6836's instanceIdentity.js leaf split). If this crept back up, check for a caller that only needs identity (getInstanceId/ensureInstanceId/getSelf/ensureSelf/updateSelf/UNKNOWN_INSTANCE_ID) re-widening its import back onto instances.js instead of instanceIdentity.js.`,+ ).toBeLessThan(60);+ }, 60_000);});// The shared compiler must remain usable without loading project mutations.diff --git a/server/lib/mockPathsDataRoot.js b/server/lib/mockPathsDataRoot.jsindex 50ad26ac7b..9c409bfaf1 100644--- a/server/lib/mockPathsDataRoot.js+++ b/server/lib/mockPathsDataRoot.js@@ -30,6 +30,9 @@* - `createTempDataRoot()` — returns `{ tempRoot }` allocated under os.tmpdir().* - `mockNoPeers(actual?, overrides?)` — shared `instances.js` mock guard* for record-creating tests that should never auto-subscribe to live peers.+ * - `mockTestIdentity(overrides?)` — shared `instanceIdentity.js` mock guard+ * with deterministic self-identity values (id/name), for suites that+ * double the federation identity leaf instead of the real data file.* - `mockNoPeerSync(actual?, overrides?)` — shared `peerSync.js` mock guard* that makes fire-and-forget record auto-subscribe a clean no-op in tests.*@@ -165,18 +168,45 @@ export function makePathsProxy(actual, { dataRoot, extraOverrides = null, overri* record creation. In tests, that background path can outlive local fileUtils* mocks and read the real peer registry unless `getPeers` is explicitly* guarded. Pass the real module as `actual` when a suite needs the other- * exports, and pass `overrides` for test-specific exports like getInstanceId.+ * exports, and pass `overrides` for test-specific peer exports.+ *+ * Identity (`getInstanceId`, `UNKNOWN_INSTANCE_ID`, …) is NOT this helper's+ * concern since #6836 split it into `services/instanceIdentity.js` — use+ * `mockTestIdentity()` below for a suite that needs to double identity too.*/export function mockNoPeers(actual = {}, overrides = {}) {return {- UNKNOWN_INSTANCE_ID: 'unknown',- getInstanceId: () => Promise.resolve('test-instance'),...actual,getPeers: () => Promise.resolve([]),...overrides,};}+/**+ * Build an `instanceIdentity.js` mock with deterministic test values.+ *+ * Sibling to `mockNoPeers()` — this install's federation identity moved to+ * its own leaf module (#6836) so a caller that only needs an id read no+ * longer statically loads the peer-orchestration closure. A suite that+ * doubles `services/instances.js` AND relies on identity values from that+ * double (directly, or via `mockNoPeers(actual, overrides)`'s old identity+ * defaults) must add a sibling `vi.mock('.../instanceIdentity.js', () =>+ * mockTestIdentity({ ...the identity overrides it used... }))` — see+ * `server/AGENTS.md` "Narrowing an import must not step around a barrel a+ * suite mocks."+ */+export function mockTestIdentity(overrides = {}) {+ return {+ UNKNOWN_INSTANCE_ID: 'unknown',+ getInstanceId: () => Promise.resolve('test-instance'),+ ensureInstanceId: () => Promise.resolve('test-instance'),+ getSelf: () => Promise.resolve({ instanceId: 'test-instance', name: 'test-instance' }),+ ensureSelf: () => Promise.resolve({ instanceId: 'test-instance', name: 'test-instance' }),+ updateSelf: () => Promise.resolve({ instanceId: 'test-instance', name: 'test-instance' }),+ ...overrides,+ };+}+/*** Build a `sharing/peerSync.js` mock that disables peer fan-out for suites* that load the peer-sync module graph (directly or via sharing/index.js).diff --git a/server/lib/peerHttpClient.js b/server/lib/peerHttpClient.jsindex 1963df5f16..66a0717257 100644--- a/server/lib/peerHttpClient.js+++ b/server/lib/peerHttpClient.js@@ -34,17 +34,19 @@ export function peerAuthHeaders(peer) {}// Our own federation instance id, memoized after the first successful read.-// Resolved through a DYNAMIC import because `services/instances.js` imports-// this module — a static import back would close an evaluation-order cycle.-// A failed/absent identity yields no header at all rather than the+// Resolved through a dynamic import of the identity leaf (#6836): harmless to+// static-import now (services/instanceIdentity.js is a leaf with no edge back+// to this module — the old cycle ran through services/instances.js, which+// still imports peerFetch), kept lazy here to match this file's peer-registry+// call shape. A failed/absent identity yields no header at all rather than the// `UNKNOWN_INSTANCE_ID` sentinel, so a receiver sees "unidentified" instead of// a bogus id it would then fail to resolve in its peer registry.let cachedSelfInstanceId = null;async function selfInstanceHeader() {if (!cachedSelfInstanceId) {- const instances = await import('../services/instances.js').catch(() => null);- const id = await instances?.getInstanceId?.().catch(() => null);- if (typeof id === 'string' && id && id !== instances?.UNKNOWN_INSTANCE_ID) cachedSelfInstanceId = id;+ const instanceIdentity = await import('../services/instanceIdentity.js').catch(() => null);+ const id = await instanceIdentity?.getInstanceId?.().catch(() => null);+ if (typeof id === 'string' && id && id !== instanceIdentity?.UNKNOWN_INSTANCE_ID) cachedSelfInstanceId = id;}return cachedSelfInstanceId ? { 'X-PortOS-Instance-Id': cachedSelfInstanceId } : {};}diff --git a/server/lib/peerHttpClient.test.js b/server/lib/peerHttpClient.test.jsindex ae61085e6a..dcd0e25436 100644--- a/server/lib/peerHttpClient.test.js+++ b/server/lib/peerHttpClient.test.js@@ -71,7 +71,7 @@ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));// import of the instances service; stub it so the header assertions don't// depend on (or create) a real instance identity on disk.let selfInstanceId = 'self-instance-id';-vi.mock('../services/instances.js', () => ({+vi.mock('../services/instanceIdentity.js', () => ({getInstanceId: async () => selfInstanceId,UNKNOWN_INSTANCE_ID: 'unknown',}));diff --git a/server/routes/health.test.js b/server/routes/health.test.jsindex efda007887..2e56096bda 100644--- a/server/routes/health.test.js+++ b/server/routes/health.test.js@@ -4,7 +4,7 @@ import express from 'express';import { request } from '../lib/testHelper.js';import systemHealthRoutes from './systemHealth.js';import { listProcesses } from '../services/pm2.js';-import { getSelf } from '../services/instances.js';+import { getSelf } from '../services/instanceIdentity.js';import { isAuthEnabled } from '../services/auth.js';import { checkGhHealth } from '../services/github.js';import { getBuildIdentity } from '../lib/buildIdentity.js';@@ -31,7 +31,7 @@ vi.mock('../lib/memoryStats.js', () => ({// companion-app identity fields on GET /health are deterministic. Mocking auth.js// directly also sidesteps its module-load `settingsEvents.on(...)` side effect,// which the partial settings.js mock below does not provide.-vi.mock('../services/instances.js', () => ({+vi.mock('../services/instanceIdentity.js', () => ({getSelf: vi.fn().mockResolvedValue({ instanceId: 'test-instance-id', name: 'Example Instance' })}));diff --git a/server/routes/instances.js b/server/routes/instances.jsindex 79312ad7f9..405aef4991 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -7,6 +7,7 @@import { Router } from 'express';import { z } from 'zod';import * as instances from '../services/instances.js';+import { getSelf, updateSelf } from '../services/instanceIdentity.js';import { getSyncStatus, syncWithPeer } from '../services/syncOrchestrator.js';import { getFullSyncCoverageForPeer } from '../services/sharing/peerSync.js';import { provisionTailscaleCert } from '../services/certProvisioner.js';@@ -123,7 +124,7 @@ const reciprocalSyncSchema = z.object({// GET /api/instances — list self + all peersrouter.get('/', asyncHandler(async (req, res) => {const [self, peers, syncStatus] = await Promise.all([- instances.getSelf(),+ getSelf(),instances.getPeers(),getSyncStatus({ includeChecksums: true })]);@@ -208,7 +209,7 @@ router.post('/provision-cert', asyncHandler(async (req, res) => {// GET /api/instances/self — get this instance's identityrouter.get('/self', asyncHandler(async (req, res) => {- const self = await instances.getSelf();+ const self = await getSelf();res.json(self);}));@@ -222,7 +223,7 @@ const updateSelfSchema = z.object({});router.put('/self', asyncHandler(async (req, res) => {const data = updateSelfSchema.parse(req.body);- const updated = await instances.updateSelf(data.name, { defaultPeerFullSync: data.defaultPeerFullSync });+ const updated = await updateSelf(data.name, { defaultPeerFullSync: data.defaultPeerFullSync });if (!updated) throw new ServerError('Self identity not initialized', { status: 500 });res.json(updated);}));@@ -244,7 +245,7 @@ router.post('/peers/announce', asyncHandler(async (req, res) => {host: data.host});- const self = await instances.getSelf();+ const self = await getSelf();res.status(result.created ? 201 : 200).json({self: { instanceId: self?.instanceId, name: self?.name },// Strip our locally-stored proxy credential before echoing the matcheddiff --git a/server/routes/instances.test.js b/server/routes/instances.test.jsindex ab9e0e9a60..8747fbc5d6 100644--- a/server/routes/instances.test.js+++ b/server/routes/instances.test.js@@ -15,6 +15,13 @@ vi.mock('../services/instances.js', () => ({sanitizePeerForClient: vi.fn((peer) => peer),getAssignableInstances: vi.fn(),}));+// This suite's routes/instances.js import pulls getSelf/updateSelf from the+// identity leaf (#6836) — double it too so an untested route (e.g. GET /+// self-view) can never fall through to a real data/instances.json read.+vi.mock('../services/instanceIdentity.js', () => ({+ getSelf: vi.fn(),+ updateSelf: vi.fn(),+}));vi.mock('../services/sharing/peerSync.js', () => ({getFullSyncCoverageForPeer: vi.fn(),}));diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex 3de407fc47..afcc0c1a59 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import express from 'express';import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';-import { mockNoPeers, mockNoPeerSync } from '../lib/mockPathsDataRoot.js';+import { mockNoPeers, mockTestIdentity, mockNoPeerSync } from '../lib/mockPathsDataRoot.js';const fileStore = new Map();@@ -33,6 +33,10 @@ tryReadFile: vi.fn().mockResolvedValue(null),// Both mocks needed: vitest.setup.js's global `instances.js` mock uses importOriginal, which leaves the per-file `peerSync.js` mock unable to suppress the createSeries dynamic-import hoist error alone.vi.mock('../services/instances.js', () => mockNoPeers());+// Deterministic identity (#6836) — also keeps the real instanceIdentity.js+// module (whose dataPath() call this file's exhaustive fileUtils mock can't+// serve) from ever loading in this suite's route graph.+vi.mock('../services/instanceIdentity.js', () => mockTestIdentity());vi.mock('../services/sharing/peerSync.js', () => mockNoPeerSync());let uuidCounter = 0;diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex 40a2e31a02..bd7f437a47 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -4,7 +4,7 @@ import { statfs } from 'fs/promises';import { listProcesses } from '../services/pm2.js';import * as apps from '../services/apps.js';import * as cos from '../services/cos.js';-import { getSelf } from '../services/instances.js';+import { getSelf } from '../services/instanceIdentity.js';import { checkHealth } from '../lib/db.js';import { getCurrentVersion } from '../services/updateChecker.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';diff --git a/server/routes/universeBuilder/index.test.js b/server/routes/universeBuilder/index.test.jsindex 678b91dd58..b5d62f0e25 100644--- a/server/routes/universeBuilder/index.test.js+++ b/server/routes/universeBuilder/index.test.js@@ -3,7 +3,7 @@ import express from 'express';import { request } from '../../lib/testHelper.js';import { errorMiddleware } from '../../lib/errorHandler.js';import { enqueueJob } from '../../services/mediaJobQueue/index.js';-import { mockNoPeers, mockNoPeerSync } from '../../lib/mockPathsDataRoot.js';+import { mockNoPeers, mockTestIdentity, mockNoPeerSync } from '../../lib/mockPathsDataRoot.js';import * as canonSvc from '../../services/universeCanon.js';const fileStore = new Map();@@ -95,6 +95,10 @@ vi.mock('../../services/universeStyleReference.js', () => ({// Both mocks needed: vitest.setup.js's global `instances.js` mock uses importOriginal, which leaves the per-file `peerSync.js` mock unable to suppress the createUniverse dynamic-import hoist error alone.vi.mock('../../services/instances.js', () => mockNoPeers());+// Deterministic identity (#6836) — also keeps the real instanceIdentity.js+// module (whose dataPath() call this file's exhaustive fileUtils mock can't+// serve) from ever loading in this suite's route graph.+vi.mock('../../services/instanceIdentity.js', () => mockTestIdentity());vi.mock('../../services/sharing/peerSync.js', () => mockNoPeerSync());let uuidCounter = 0;diff --git a/server/services/agentLifecycle.blockAndBail.test.js b/server/services/agentLifecycle.blockAndBail.test.jsindex 22edada229..803438bf10 100644--- a/server/services/agentLifecycle.blockAndBail.test.js+++ b/server/services/agentLifecycle.blockAndBail.test.js@@ -119,7 +119,7 @@ vi.mock('./agentErrorAnalysis.js', () => ({analyzeAgentFailure: vi.fn().mockReturnValue({ category: 'startup-failure', actionable: false }),}));vi.mock('./appActivity.js', () => ({ releaseAppReviewMarker: vi.fn().mockResolvedValue(undefined) }));-vi.mock('./instances.js', () => ({ ensureInstanceId: vi.fn().mockResolvedValue('instance-1') }));+vi.mock('./instanceIdentity.js', () => ({ ensureInstanceId: vi.fn().mockResolvedValue('instance-1') }));vi.mock('./toolStateMachine.js', () => ({createToolExecution: vi.fn(() => ({ id: 'exec-1' })),startExecution: vi.fn(),diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex c5e36dee5d..54ee44260d 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -74,7 +74,7 @@ import { formatPublicReviewInputPrompt } from '../lib/modelAbuseGuard.js';import { validatePublicReviewModel } from './modelAbuseGuard.js';import { loadPublicReviewSpawnInput } from './publicReviewSpawnInput.js';import { releaseAppReviewMarker } from './appActivity.js';-import { ensureInstanceId } from './instances.js';+import { ensureInstanceId } from './instanceIdentity.js';import { isClaimableBy, buildClaim, buildRelease, getClaimOwner, getTargetInstance, isTargetedElsewhere } from './cosTaskClaim.js';import { resolveForgeTokenEnv } from './forgeAuth.js';import { runnerAgents, pausedAgents, consumePausedAgentExit, spawningTasks, useRunner, isTruthyMeta } from './agentState.js';diff --git a/server/services/agentLifecycle.postureGate.test.js b/server/services/agentLifecycle.postureGate.test.jsindex 6af21615af..761c726191 100644--- a/server/services/agentLifecycle.postureGate.test.js+++ b/server/services/agentLifecycle.postureGate.test.js@@ -125,7 +125,7 @@ vi.mock('./agentErrorAnalysis.js', () => ({analyzeAgentFailure: vi.fn().mockReturnValue({ category: 'startup-failure', actionable: false }),}));vi.mock('./appActivity.js', () => ({ releaseAppReviewMarker: vi.fn().mockResolvedValue(undefined) }));-vi.mock('./instances.js', () => ({ ensureInstanceId: vi.fn().mockResolvedValue('instance-1') }));+vi.mock('./instanceIdentity.js', () => ({ ensureInstanceId: vi.fn().mockResolvedValue('instance-1') }));vi.mock('./toolStateMachine.js', () => ({createToolExecution: vi.fn(() => ({ id: 'exec-1' })),startExecution: vi.fn(),diff --git a/server/services/agentLifecycle.spawnViaRunner.test.js b/server/services/agentLifecycle.spawnViaRunner.test.jsindex 9cc8651498..5059ebd11b 100644--- a/server/services/agentLifecycle.spawnViaRunner.test.js+++ b/server/services/agentLifecycle.spawnViaRunner.test.js@@ -105,7 +105,7 @@ vi.mock('./agentErrorAnalysis.js', () => ({analyzeAgentFailure: vi.fn().mockReturnValue({ category: 'startup-failure', actionable: false }),}));vi.mock('./appActivity.js', () => ({ releaseAppReviewMarker: vi.fn().mockResolvedValue(undefined) }));-vi.mock('./instances.js', () => ({ ensureInstanceId: vi.fn().mockResolvedValue('instance-1') }));+vi.mock('./instanceIdentity.js', () => ({ ensureInstanceId: vi.fn().mockResolvedValue('instance-1') }));vi.mock('./toolStateMachine.js', () => ({createToolExecution: vi.fn(() => ({ id: 'exec-1' })),startExecution: vi.fn(),diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex 9061380b32..0baeaad6d0 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -772,9 +772,9 @@ describe('runAgentSpawn source — permanent provider-config failure blocks the// record) BEFORE the agent is registered — otherwise two peers spawn for the// same task. These orderings live inside runAgentSpawn with no behavioral seam.describe('runAgentSpawn source — instance provenance + claim ordering (#1563)', () => {- it('imports the identity resolver from the instances service', () => {+ it('imports the identity resolver from the instance identity leaf', () => {expect(AGENT_LIFECYCLE_SRC).toMatch(- /import\s*\{\s*ensureInstanceId\s*\}\s*from\s*'\.\/instances\.js';/+ /import\s*\{\s*ensureInstanceId\s*\}\s*from\s*'\.\/instanceIdentity\.js';/);});diff --git a/server/services/audioGen/remote.test.js b/server/services/audioGen/remote.test.jsindex e711679caf..156aadba08 100644--- a/server/services/audioGen/remote.test.js+++ b/server/services/audioGen/remote.test.js@@ -31,6 +31,9 @@ vi.mock('../federatedMediaConsumer.js', () => ({vi.mock('../instances.js', () => ({getPeers: vi.fn(async () => federation.peers),+}));++vi.mock('../instanceIdentity.js', () => ({// Used to derive the consumer's own half of a content-addressed asset id, so it// can ask the peer whether bytes are already staged before re-sending them.getInstanceId: vi.fn(async () => 'consumer-instance'),diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 4222ad23cc..f27537cb9d 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -116,7 +116,8 @@ import { recoverStuckAutopilots } from './pipeline/seriesAutopilot.js';import { recoverInFlightProjects } from './creativeDirector/recovery.js';import { recoverInterruptedModels as recoverInterruptedThreejsModels } from './threejsModels/index.js';import { recoverInterruptedModels as recoverInterruptedImageTo3dModels } from './imageTo3d/models.js';-import { ensureSelf, startPolling } from './instances.js';+import { startPolling } from './instances.js';+import { ensureSelf } from './instanceIdentity.js';import { initSyncLog } from './brainSyncLog.js';import { backfillOriginInstanceId, brainCollectionStores } from './brainStorage.js';import { initSyncOrchestrator } from './syncOrchestrator.js';diff --git a/server/services/brain.js b/server/services/brain.jsindex e62ec1cb73..67b154de0f 100644--- a/server/services/brain.js+++ b/server/services/brain.js@@ -10,7 +10,7 @@import * as storage from './brainStorage.js';import { brainEvents } from './brainStorage.js';-import { getInstanceId, ensureInstanceId, UNKNOWN_INSTANCE_ID } from './instances.js';+import { getInstanceId, ensureInstanceId, UNKNOWN_INSTANCE_ID } from './instanceIdentity.js';import { getActiveProvider, getProviderById } from './providers.js';import { buildPrompt } from './promptService.js';import { validate } from '../lib/validation.js';diff --git a/server/services/brain.test.js b/server/services/brain.test.jsindex 0cf68bcada..0cda3197e8 100644--- a/server/services/brain.test.js+++ b/server/services/brain.test.js@@ -115,7 +115,7 @@ tryReadFile: vi.fn().mockResolvedValue(null),// recoverStuckClassifications() resolves this instance's id to skip peer-origin// entries; stub it to a stable id.-vi.mock('./instances.js', () => ({+vi.mock('./instanceIdentity.js', () => ({getInstanceId: () => Promise.resolve('local-instance'),ensureInstanceId: () => Promise.resolve('local-instance'),UNKNOWN_INSTANCE_ID: 'unknown',diff --git a/server/services/brainStorage.js b/server/services/brainStorage.jsindex f40d118b50..61435f6728 100644--- a/server/services/brainStorage.js+++ b/server/services/brainStorage.js@@ -38,7 +38,7 @@ import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import EventEmitter from 'events';import { atomicWrite, ensureDir, readJSONFile, safeJSONParse, safeDate, PATHS } from '../lib/fileUtils.js';-import { getInstanceId } from './instances.js';+import { getInstanceId } from './instanceIdentity.js';import * as brainSyncLog from './brainSyncLog.js';import { createCollectionStore } from '../lib/collectionStore.js';import { linkIsRepo, normalizeRepoLinkFields } from '../lib/repoLinkFields.js';diff --git a/server/services/brainStorage.test.js b/server/services/brainStorage.test.jsindex 705ef20e6f..90963a788d 100644--- a/server/services/brainStorage.test.js+++ b/server/services/brainStorage.test.js@@ -21,7 +21,7 @@ vi.mock('../lib/fileUtils.js', async () => {});// getInstanceId is used by create()/backfill; stub to a stable id.-vi.mock('./instances.js', () => ({+vi.mock('./instanceIdentity.js', () => ({getInstanceId: () => Promise.resolve('local-instance'),}));diff --git a/server/services/catalogDB.exportSlice.test.js b/server/services/catalogDB.exportSlice.test.jsindex af1685f729..16254f077d 100644--- a/server/services/catalogDB.exportSlice.test.js+++ b/server/services/catalogDB.exportSlice.test.js@@ -87,8 +87,8 @@ vi.mock('../lib/db.js', () => ({arrayToPgvector: vi.fn(),}));-// instances.getInstanceId is pulled in transitively by catalogDB — stub it.-vi.mock('./instances.js', () => ({ getInstanceId: vi.fn(async () => 'inst-1') }));+// instanceIdentity.getInstanceId is pulled in transitively by catalogDB — stub it.+vi.mock('./instanceIdentity.js', () => ({ getInstanceId: vi.fn(async () => 'inst-1') }));const catalogDB = await import('./catalogDB.js');diff --git a/server/services/catalogDB.ingredientTimestamps.test.js b/server/services/catalogDB.ingredientTimestamps.test.jsindex f33c51690c..b74c473c55 100644--- a/server/services/catalogDB.ingredientTimestamps.test.js+++ b/server/services/catalogDB.ingredientTimestamps.test.js@@ -26,8 +26,8 @@ vi.mock('../lib/db.js', () => ({arrayToPgvector: vi.fn(),}));-// instances.getInstanceId is pulled in transitively by catalogDB — stub it.-vi.mock('./instances.js', () => ({ getInstanceId: vi.fn(async () => 'inst-1') }));+// instanceIdentity.getInstanceId is pulled in transitively by catalogDB — stub it.+vi.mock('./instanceIdentity.js', () => ({ getInstanceId: vi.fn(async () => 'inst-1') }));const catalogDB = await import('./catalogDB.js');diff --git a/server/services/catalogDB.registry.test.js b/server/services/catalogDB.registry.test.jsindex 117a752b34..82f0ed3af8 100644--- a/server/services/catalogDB.registry.test.js+++ b/server/services/catalogDB.registry.test.js@@ -52,7 +52,7 @@ vi.mock('../lib/db.js', () => ({arrayToPgvector: vi.fn((a) => a),}));-vi.mock('./instances.js', () => ({+vi.mock('./instanceIdentity.js', () => ({getInstanceId: vi.fn(async () => 'inst-test'),}));diff --git a/server/services/catalogDB.tags.test.js b/server/services/catalogDB.tags.test.jsindex 15b8aec3bd..a5b9b4f982 100644--- a/server/services/catalogDB.tags.test.js+++ b/server/services/catalogDB.tags.test.js@@ -51,7 +51,7 @@ vi.mock('../lib/db.js', () => ({arrayToPgvector: vi.fn((a) => a),}));-vi.mock('./instances.js', () => ({ getInstanceId: vi.fn(async () => 'inst-test') }));+vi.mock('./instanceIdentity.js', () => ({ getInstanceId: vi.fn(async () => 'inst-test') }));import { query } from '../lib/db.js';import { normalizeTags, upsertTagFromPeer } from './catalogDB.js';diff --git a/server/services/catalogDB/ingredients.js b/server/services/catalogDB/ingredients.jsindex bded91a692..d2ebd7bcfb 100644--- a/server/services/catalogDB/ingredients.js+++ b/server/services/catalogDB/ingredients.js@@ -13,7 +13,7 @@ import {currentPayloadSchemaVersion,defaultTagsForType,} from '../../lib/catalogTypes.js';-import { getInstanceId } from '../instances.js';+import { getInstanceId } from '../instanceIdentity.js';import {newIngredientId,newRevisionId,diff --git a/server/services/catalogDB/scraps.js b/server/services/catalogDB/scraps.jsindex bdf47d5f23..4e29acdd53 100644--- a/server/services/catalogDB/scraps.js+++ b/server/services/catalogDB/scraps.js@@ -8,7 +8,7 @@import { query, withTransaction, arrayToPgvector } from '../../lib/db.js';import { chunkRawText } from '../../lib/catalogChunking.js';-import { getInstanceId } from '../instances.js';+import { getInstanceId } from '../instanceIdentity.js';import { newScrapId, rowToScrap } from './shared.js';// `{ client }` is optional — when supplied, the INSERT runs on the caller'sdiff --git a/server/services/catalogDBMedia.test.js b/server/services/catalogDBMedia.test.jsindex e8f68e1bed..6e4b02bad4 100644--- a/server/services/catalogDBMedia.test.js+++ b/server/services/catalogDBMedia.test.js@@ -49,8 +49,8 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {};});-// instances.getInstanceId is pulled in transitively by catalogDB — stub it.-vi.mock('./instances.js', () => ({ getInstanceId: vi.fn(async () => 'inst-1') }));+// instanceIdentity.getInstanceId is pulled in transitively by catalogDB — stub it.+vi.mock('./instanceIdentity.js', () => ({ getInstanceId: vi.fn(async () => 'inst-1') }));const catalogDB = await import('./catalogDB.js');diff --git a/server/services/catalogDBRevisions.test.js b/server/services/catalogDBRevisions.test.jsindex 4c8e6f33c8..e7efb40290 100644--- a/server/services/catalogDBRevisions.test.js+++ b/server/services/catalogDBRevisions.test.js@@ -83,7 +83,7 @@ vi.mock('../lib/db.js', () => ({arrayToPgvector: vi.fn((a) => a),}));-vi.mock('./instances.js', () => ({+vi.mock('./instanceIdentity.js', () => ({getInstanceId: vi.fn(async () => 'inst-test'),}));diff --git a/server/services/cos.js b/server/services/cos.jsindex c3ea9dc71a..7fee8e33d1 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -85,7 +85,7 @@ export { runHealthCheck, getHealthStatus };import { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks } from './cosTaskStore.js';export { getPendingTaskIds } from './cosTaskStore.js';export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks };-import { ensureInstanceId } from './instances.js';+import { ensureInstanceId } from './instanceIdentity.js';import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner, getSkipReason } from './cosTaskClaim.js';import { retryTasksResolvedByInvestigation } from './investigationRetry.js';import { notifyIfPrLeftOrphaned } from './orphanedPrNotifier.js';diff --git a/server/services/cosPriority2Parity.test.js b/server/services/cosPriority2Parity.test.jsindex ec91bb096c..c27bb814a0 100644--- a/server/services/cosPriority2Parity.test.js+++ b/server/services/cosPriority2Parity.test.js@@ -41,7 +41,7 @@ vi.mock('./domainUsage.js', async (importActual) => ({...(await importActual()),getDomainBudgetStatus: async () => ({ exceeded: null, budget: {}, usage: {} }),}));-vi.mock('./instances.js', async (importActual) => ({+vi.mock('./instanceIdentity.js', async (importActual) => ({...(await importActual()),ensureInstanceId: async () => 'instance-a',}));diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 19adf63703..4f3b9f5381 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -55,7 +55,7 @@ import { classifySafetyKind, requiresSafetyApproval } from './taskLearning/safetimport { isRecoveryTask } from './recoveryTasks.js';import { getCodeReviewDefaults } from './codeReview.js';import { getSkipReason } from './cosTaskClaim.js';-import { ensureInstanceId } from './instances.js';+import { ensureInstanceId } from './instanceIdentity.js';import { PR_COMPLETION_VALUES } from '../lib/prDisposition.js';import { resolveTrackerFilingBlock } from '../lib/workTracker.js';import {diff --git a/server/services/creativeDirector/local.test.js b/server/services/creativeDirector/local.test.jsindex 808c1d5227..8e805cb94f 100644--- a/server/services/creativeDirector/local.test.js+++ b/server/services/creativeDirector/local.test.js@@ -1,4 +1,4 @@-vi.mock('../instances.js', () => ({ ensureInstanceId: vi.fn(async () => 'example-owner'), getInstanceId: vi.fn(async () => 'example-owner') }));+vi.mock('../instanceIdentity.js', () => ({ ensureInstanceId: vi.fn(async () => 'example-owner'), getInstanceId: vi.fn(async () => 'example-owner') }));import { describe, it, expect, vi, beforeEach } from 'vitest';// Mocks declared before importing the module under test.diff --git a/server/services/creativeDirector/projectsDB.js b/server/services/creativeDirector/projectsDB.jsindex 3c8211dae4..43b253374f 100644--- a/server/services/creativeDirector/projectsDB.js+++ b/server/services/creativeDirector/projectsDB.js@@ -34,7 +34,7 @@ export async function listProjectsByCommissionId(commissionId) {export async function createProject(input) {const seeded = { ...input };if (input.workspace === 'video') {- const { ensureInstanceId } = await import('../instances.js');+ const { ensureInstanceId } = await import('../instanceIdentity.js');seeded.videoOwnerInstanceId = await ensureInstanceId();}return store.createProject(seeded, async ({ id }) => {diff --git a/server/services/creativeDirector/projectsDB.test.js b/server/services/creativeDirector/projectsDB.test.jsindex 403cb20eaa..34eb442af4 100644--- a/server/services/creativeDirector/projectsDB.test.js+++ b/server/services/creativeDirector/projectsDB.test.js@@ -1,4 +1,4 @@-vi.mock('../instances.js', () => ({ ensureInstanceId: vi.fn(async () => 'example-owner'), getInstanceId: vi.fn(async () => 'example-owner') }));+vi.mock('../instanceIdentity.js', () => ({ ensureInstanceId: vi.fn(async () => 'example-owner'), getInstanceId: vi.fn(async () => 'example-owner') }));/*** Postgres-backed round-trip for the Creative Director DB store.*diff --git a/server/services/creativeDirector/projectsFile.js b/server/services/creativeDirector/projectsFile.jsindex 226d833432..2d4c470767 100644--- a/server/services/creativeDirector/projectsFile.js+++ b/server/services/creativeDirector/projectsFile.js@@ -31,7 +31,7 @@ export async function listProjectsByCommissionId(commissionId) {export async function createProject(input) {const seeded = { ...input };if (input.workspace === 'video') {- const { ensureInstanceId } = await import('../instances.js');+ const { ensureInstanceId } = await import('../instanceIdentity.js');seeded.videoOwnerInstanceId = await ensureInstanceId();}return store.createProject(seeded, async ({ id }) => {diff --git a/server/services/creativeDirector/projectsFile.test.js b/server/services/creativeDirector/projectsFile.test.jsindex ea23583892..8e741ab5a2 100644--- a/server/services/creativeDirector/projectsFile.test.js+++ b/server/services/creativeDirector/projectsFile.test.js@@ -1,4 +1,4 @@-vi.mock('../instances.js', () => ({ ensureInstanceId: vi.fn(async () => 'example-owner'), getInstanceId: vi.fn(async () => 'example-owner') }));+vi.mock('../instanceIdentity.js', () => ({ ensureInstanceId: vi.fn(async () => 'example-owner'), getInstanceId: vi.fn(async () => 'example-owner') }));/*** Creative Director file-backend federation merge (#1564) — soft-delete,* LWW merge, tombstone prune, and the conflict-journal + base-hash wiring.diff --git a/server/services/creativeDirector/sceneRunner.backend.test.js b/server/services/creativeDirector/sceneRunner.backend.test.jsindex 876c84ca29..5a07789b5f 100644--- a/server/services/creativeDirector/sceneRunner.backend.test.js+++ b/server/services/creativeDirector/sceneRunner.backend.test.js@@ -21,7 +21,7 @@ vi.mock('../mediaJobQueue/index.js', () => ({getJob: vi.fn(() => null),mediaJobEvents: { on: vi.fn(), off: vi.fn() },}));-vi.mock('../instances.js', () => ({ getInstanceId: vi.fn(async () => 'example-owner') }));+vi.mock('../instanceIdentity.js', () => ({ getInstanceId: vi.fn(async () => 'example-owner') }));vi.mock('./videoSources.js', () => ({ assertVideoSourcesAvailable: vi.fn() }));vi.mock('../settings.js', () => ({getSettings: vi.fn(),diff --git a/server/services/creativeDirector/sourceRevisionPersistence.test.js b/server/services/creativeDirector/sourceRevisionPersistence.test.jsindex 10050c6708..85d5e3d9e0 100644--- a/server/services/creativeDirector/sourceRevisionPersistence.test.js+++ b/server/services/creativeDirector/sourceRevisionPersistence.test.js@@ -1,4 +1,4 @@-vi.mock('../instances.js', () => ({ ensureInstanceId: vi.fn(async () => 'example-owner'), getInstanceId: vi.fn(async () => 'example-owner') }));+vi.mock('../instanceIdentity.js', () => ({ ensureInstanceId: vi.fn(async () => 'example-owner'), getInstanceId: vi.fn(async () => 'example-owner') }));import { describe, it, expect, vi } from 'vitest';const state = vi.hoisted(() => ({ project: null, writes: 0 }));diff --git a/server/services/creativeDirector/stopProject.test.js b/server/services/creativeDirector/stopProject.test.jsindex 618b0d6118..bcd0e5ad28 100644--- a/server/services/creativeDirector/stopProject.test.js+++ b/server/services/creativeDirector/stopProject.test.js@@ -14,7 +14,7 @@ vi.mock('./local.js', () => ({updatePlanStep: (...a) => updatePlanStepMock(...a),}));-vi.mock('../instances.js', () => ({ getInstanceId: async () => 'example-owner' }));+vi.mock('../instanceIdentity.js', () => ({ getInstanceId: async () => 'example-owner' }));const getActiveAgentsMock = vi.fn(() => []);const killAgentMock = vi.fn(async () => ({ success: true }));diff --git a/server/services/creativeDirector/videoAssembly.test.js b/server/services/creativeDirector/videoAssembly.test.jsindex 89933e0707..4a55e8291a 100644--- a/server/services/creativeDirector/videoAssembly.test.js+++ b/server/services/creativeDirector/videoAssembly.test.js@@ -17,7 +17,7 @@ vi.mock('./local.js', () => ({mutateVideoProject: async (_id, mutate) => { const outcome = mutate(structuredClone(state.project)); if (!outcome.skipPersist) state.project = outcome.project; return outcome; },}));vi.mock('../videoGen/local.js', () => ({ loadHistory: async () => state.history, mutateVideoHistory: async mutate => { state.history = mutate(state.history); return state.history; } }));-vi.mock('../instances.js', () => ({ getInstanceId: async () => 'example-owner' }));+vi.mock('../instanceIdentity.js', () => ({ getInstanceId: async () => 'example-owner' }));vi.mock('./videoSources.js', () => ({ assertVideoSourcesAvailable: async () => {} }));vi.mock('../mediaCollections.js', () => ({ addItem: async (_id, item) => { state.collection.push(item); } }));vi.mock('../tracks/index.js', () => ({ getTrack: async id => state.tracks.find(track => track.id === id) }));diff --git a/server/services/creativeDirector/videoExecution.js b/server/services/creativeDirector/videoExecution.jsindex e4c0dfed06..ebb4ac3de0 100644--- a/server/services/creativeDirector/videoExecution.js+++ b/server/services/creativeDirector/videoExecution.js@@ -82,7 +82,7 @@ async function resolveChoices(project) {export async function getVideoExecutionPreview(projectId) {const { getProject } = await import('./local.js');- const { getInstanceId } = await import('../instances.js');+ const { getInstanceId } = await import('../instanceIdentity.js');const project = await getProject(projectId);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });const owner = await getInstanceId();@@ -115,7 +115,7 @@ export async function getVideoExecutionPreview(projectId) {async function ownedMutation(projectId, mutate) {const { mutateVideoProject } = await import('./local.js');- const { getInstanceId } = await import('../instances.js');+ const { getInstanceId } = await import('../instanceIdentity.js');const owner = await getInstanceId();return mutateVideoProject(projectId, project => { assertVideoOwner(project, owner); return mutate(project); });}@@ -244,7 +244,7 @@ export async function settleVideoAttempt(projectId, attemptId, patch) {/** Checked at the worker boundary, after the queue wait and immediately before provider work. */export async function assertVideoAttemptDispatch(projectId, attemptId, { jobId } = {}) {const { getProject } = await import('./local.js');- const { getInstanceId } = await import('../instances.js');+ const { getInstanceId } = await import('../instanceIdentity.js');const project = await getProject(projectId);assertVideoOwner(project, await getInstanceId());const execution = project.videoExecution;diff --git a/server/services/creativeDirector/videoExecution.test.js b/server/services/creativeDirector/videoExecution.test.jsindex 085bd03eeb..8e866c9d9a 100644--- a/server/services/creativeDirector/videoExecution.test.js+++ b/server/services/creativeDirector/videoExecution.test.js@@ -8,7 +8,7 @@ vi.mock('./local.js', () => ({return output;}),}));-vi.mock('../instances.js', () => ({ getInstanceId: vi.fn(async () => 'example-owner') }));+vi.mock('../instanceIdentity.js', () => ({ getInstanceId: vi.fn(async () => 'example-owner') }));vi.mock('../settings.js', () => ({ getSettings: vi.fn(async () => state.settings) }));vi.mock('./videoSources.js', () => ({ assertVideoSourcesAvailable: vi.fn(async () => {}) }));vi.mock('./agentBridge.js', () => ({ getStageAssignment: vi.fn(async () => ({ providerId: 'example-agent', provider: 'example-agent', model: 'example-model' })) }));diff --git a/server/services/creativeDirector/videoReview.js b/server/services/creativeDirector/videoReview.jsindex d201e2466a..717fcb6b52 100644--- a/server/services/creativeDirector/videoReview.js+++ b/server/services/creativeDirector/videoReview.js@@ -1,6 +1,6 @@import { assertVideoOwner, applyVideoReviewAction, videoReviewStages } from '../../lib/creativeDirectorVideoReview.js';import { ServerError } from '../../lib/errorHandler.js';-import { getInstanceId } from '../instances.js';+import { getInstanceId } from '../instanceIdentity.js';import { getProject, mutateVideoProject } from './local.js';export async function getVideoReview(projectId) {diff --git a/server/services/creativeDirector/videoReview.test.js b/server/services/creativeDirector/videoReview.test.jsindex e1b7ac406e..40c1fe6408 100644--- a/server/services/creativeDirector/videoReview.test.js+++ b/server/services/creativeDirector/videoReview.test.js@@ -8,7 +8,7 @@ vi.mock('./local.js', () => ({return result;}),}));-vi.mock('../instances.js', () => ({ getInstanceId: vi.fn(async () => 'example-owner') }));+vi.mock('../instanceIdentity.js', () => ({ getInstanceId: vi.fn(async () => 'example-owner') }));vi.mock('./completionHook.js', () => ({ startCreativeDirectorProject: mocks.start }));vi.mock('./videoSources.js', () => ({ assertVideoSourcesAvailable: vi.fn() }));import { getVideoReview, reviewVideo, videoReviewAllowsDispatch } from './videoReview.js';diff --git a/server/services/eidoverseTravel.test.js b/server/services/eidoverseTravel.test.jsindex 3406b24e42..d7665f66a4 100644--- a/server/services/eidoverseTravel.test.js+++ b/server/services/eidoverseTravel.test.js@@ -3,7 +3,8 @@ import express from 'express';import { once } from 'node:events';const mocks = vi.hoisted(() => ({ peers: [], feature: true, protocol: true, connections: [], admission: vi.fn() }));-vi.mock('./instances.js', () => ({ getPeers: async () => mocks.peers, getInstanceId: async () => 'origin-instance', UNKNOWN_INSTANCE_ID: 'unknown' }));+vi.mock('./instances.js', () => ({ getPeers: async () => mocks.peers }));+vi.mock('./instanceIdentity.js', () => ({ getInstanceId: async () => 'origin-instance', UNKNOWN_INSTANCE_ID: 'unknown' }));vi.mock('./instanceFeatures.js', () => ({ getInstanceFeatures: async () => ({ features: [{ id: 'eidoverse', enabled: mocks.feature }] }) }));vi.mock('./eidoverseHost.js', () => ({ ensureEidoverseHost: async () => ({ protocol: 'http', port: 5563, running: true }) }));vi.mock('./eidoverseWorld.js', () => ({ supportsEidoverseGuestEntry: async () => mocks.protocol, getEidoverseWorldStatus: async () => ({ setup: { installed: true, runtimeStatus: 'online', worldDataReady: true }, cos: { enabled: true } }), admitEidoverseGuest: (...args) => mocks.admission(...args) }));diff --git a/server/services/eidoverseWorld.js b/server/services/eidoverseWorld.jsindex aea1d8000d..989ba4c596 100644--- a/server/services/eidoverseWorld.js+++ b/server/services/eidoverseWorld.js@@ -18,7 +18,7 @@ import { createMutex } from '../lib/asyncMutex.js';import { ServerError } from '../lib/errorHandler.js';import { eidoverseLabelCapabilities, normalizeEidoverseLabelAliases } from '../lib/eidoverseWorldLabels.js';import { canonicalStringify } from '../lib/objects.js';-import { getSelf, ensureSelf, getInstanceId } from './instances.js';+import { getSelf, ensureSelf, getInstanceId } from './instanceIdentity.js';import { getInstanceFeatures } from './instanceFeatures.js';import { getEidoverseStatus, EIDOVERSE_PORT } from './eidoverse.js';import { getCurrentVersion } from './updateChecker.js';diff --git a/server/services/eidoverseWorld.runtime.test.js b/server/services/eidoverseWorld.runtime.test.jsindex edd463f552..68c5321eab 100644--- a/server/services/eidoverseWorld.runtime.test.js+++ b/server/services/eidoverseWorld.runtime.test.js@@ -49,10 +49,13 @@ vi.mock('../lib/fileUtils.js', async (importActual) => {});vi.mock('./instances.js', () => ({+ getPeers: vi.fn(async () => []),+}));++vi.mock('./instanceIdentity.js', () => ({getSelf: vi.fn(async () => mocks.self),ensureSelf: vi.fn(async () => mocks.self),getInstanceId: vi.fn(async () => mocks.self?.instanceId ?? 'unknown-instance'),- getPeers: vi.fn(async () => []),}));vi.mock('./apps.js', () => ({diff --git a/server/services/federatedMedia/inputAssets.js b/server/services/federatedMedia/inputAssets.jsindex 17ab90b2ed..4e39d8ea51 100644--- a/server/services/federatedMedia/inputAssets.js+++ b/server/services/federatedMedia/inputAssets.js@@ -195,7 +195,7 @@ function createInputAssetStager({ requestJson, emitStatus }) {// this module, and a static edge to the peer registry would drag it (and// its settings/DB dependencies) into every route suite's module graph.// Same reason remoteSubmission.js defers the same import.- const { getInstanceId } = await import('../instances.js');+ const { getInstanceId } = await import('../instanceIdentity.js');const assetId = federatedMediaAssetId(await getInstanceId(), digest);// Ask before sending. The id is fully derivable from our own instance id anddiff --git a/server/services/idealoomLists.boundary.test.js b/server/services/idealoomLists.boundary.test.jsindex c79c986679..898260164f 100644--- a/server/services/idealoomLists.boundary.test.js+++ b/server/services/idealoomLists.boundary.test.js@@ -34,7 +34,7 @@ vi.mock('../lib/fileUtils.js', async () => {return makePathsProxy(actual, { dataRoot: () => getTempRoot() });});-vi.mock('./instances.js', () => ({+vi.mock('./instanceIdentity.js', () => ({getInstanceId: () => Promise.resolve('local-instance'),}));diff --git a/server/services/imageGen/remote.test.js b/server/services/imageGen/remote.test.jsindex ae88c1be49..d281290bd3 100644--- a/server/services/imageGen/remote.test.js+++ b/server/services/imageGen/remote.test.js@@ -41,6 +41,9 @@ vi.mock('../federatedMediaConsumer.js', () => ({vi.mock('../instances.js', () => ({getPeers: vi.fn(async () => federation.peers),+}));++vi.mock('../instanceIdentity.js', () => ({// Used to derive the consumer's own half of a content-addressed asset id, so it// can ask the peer whether bytes are already staged before re-sending them.getInstanceId: vi.fn(async () => 'consumer-instance'),diff --git a/server/services/instanceIdentity.js b/server/services/instanceIdentity.jsnew file mode 100644index 0000000000..9ff82979ae--- /dev/null+++ b/server/services/instanceIdentity.js@@ -0,0 +1,137 @@+/**+ * Instance Identity+ *+ * Owns this install's federation identity — the local instanceId/name pair —+ * plus the data/instances.json file I/O and its mutex, which this module and+ * services/instances.js (peer orchestration) both read and write through.+ *+ * This module is a leaf on purpose. Most callers across the server only need+ * to read this install's own id (getInstanceId/ensureInstanceId/getSelf), not+ * manage peers. Before this split, that one-line id read statically loaded+ * services/instances.js's entire peer-orchestration closure — the Tailscale+ * status parser (lib/tailscale.js), the federated-media probe+ * (services/federatedMediaConsumer.js), and the peer socket relay+ * (services/peerSocketRelay.js) — a 30+ module closure paid by every test+ * suite that imports any of the 22 identity-only callers (brain, memory,+ * catalog, CoS, and more). See issue #6836.+ *+ * Import rule: this module stays a leaf. It may import only+ * `lib/fileUtils.js`, `lib/asyncMutex.js`, `node:os`, and `node:crypto` — no+ * other `server/services/*` module, and nothing that reaches the peer stack.+ * `server/lib/importScoping.test.js` enforces this.+ */++import os from 'node:os';+import crypto from 'node:crypto';+import { dataPath, readJSONFile, ensureDir, PATHS, atomicWrite } from '../lib/fileUtils.js';+import { createMutex } from '../lib/asyncMutex.js';++const INSTANCES_FILE = dataPath('instances.json');++// Sentinel returned by getInstanceId() and stamped onto sender/peer fields when+// the local identity hasn't been initialized yet. Every consumer that fans+// instance-keyed state out to peers (sharing/annotationsSync.flushAll,+// mediaAnnotations.mergePeerAnnotations, manifest builders) must refuse this+// value — without that guard, every uninitialized peer would collide in the+// same bucket and clobber each other on merge.+export const UNKNOWN_INSTANCE_ID = 'unknown';++const withLock = createMutex();++// Default data shape+const DEFAULT_DATA = {+ self: null,+ peers: []+};++// --- File I/O ---++// STRICT (#4115): every mutation runs through `withData`, which writes whatever+// this read returned straight back. Swallowing an unreadable instances.json into+// DEFAULT_DATA therefore hands `ensureSelf` an identity-less record — it mints a+// BRAND-NEW instanceId and `saveData` persists it over the real file, rotating+// this node's federation identity and wiping every peer. ENOENT (never+// federated) stays the trustworthy first-run empty.+export async function loadData() {+ return await readJSONFile(INSTANCES_FILE, DEFAULT_DATA, { strict: true });+}++async function saveData(data) {+ await ensureDir(PATHS.data);+ await atomicWrite(INSTANCES_FILE, data);+}++export async function withData(fn) {+ return withLock(async () => {+ const data = await loadData();+ const result = await fn(data);+ await saveData(data);+ return result;+ });+}++// --- Self Identity ---++export async function ensureSelf() {+ return withData(async (data) => {+ if (!data.self) {+ data.self = {+ instanceId: crypto.randomUUID(),+ name: os.hostname()+ };+ console.log(`🌐 Instance identity created: ${data.self.name} (${data.self.instanceId})`);+ }+ return data.self;+ });+}++export async function getSelf() {+ const data = await loadData();+ return data.self;+}++let cachedInstanceId = null;+export async function getInstanceId() {+ if (!cachedInstanceId) {+ const id = (await getSelf())?.instanceId;+ if (id) cachedInstanceId = id;+ return id ?? UNKNOWN_INSTANCE_ID;+ }+ return cachedInstanceId;+}++/**+ * Resolve this machine's real federation instance id, creating the local+ * identity on the cold path. `getInstanceId()` returns the+ * `UNKNOWN_INSTANCE_ID` sentinel (and never throws) before the identity exists+ * — which can happen on a boot-time always-on auto-start that runs before the+ * startup chain's `ensureSelf()` does. Callers that stamp the id onto durable+ * records (agent provenance, worktree metadata) or compare it for cross-machine+ * task claims (#1563) must never persist/compare the sentinel, so this creates+ * (or loads) the real identity before returning. The warm path is the cheap+ * cached `getInstanceId()` read; `ensureSelf()` only runs the once.+ */+export async function ensureInstanceId() {+ let instanceId = await getInstanceId();+ if (instanceId === UNKNOWN_INSTANCE_ID) {+ instanceId = (await ensureSelf())?.instanceId || instanceId;+ }+ return instanceId;+}++export async function updateSelf(name, { defaultPeerFullSync } = {}) {+ return withData(async (data) => {+ if (!data.self) return null;+ if (typeof name === 'string' && name.trim()) {+ data.self.name = name.trim();+ console.log(`🌐 Instance name updated: ${data.self.name}`);+ }+ // The default full-sync ("mirror everything") mode applied to NEW peers as+ // they're added. Existing peers are untouched — this only seeds addPeer.+ if (typeof defaultPeerFullSync === 'boolean') {+ data.self.defaultPeerFullSync = defaultPeerFullSync;+ console.log(`🌐 New-peer full-sync default: ${defaultPeerFullSync ? 'on' : 'off'}`);+ }+ return data.self;+ });+}diff --git a/server/services/instanceIdentity.test.js b/server/services/instanceIdentity.test.jsnew file mode 100644index 0000000000..b5d8015ec7--- /dev/null+++ b/server/services/instanceIdentity.test.js@@ -0,0 +1,165 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';++// Source of instanceIdentity.js, for a source-level assertion that doesn't+// execute the module (avoids the vitest worker-teardown console-RPC flake+// that running the identity-creation path under resetModules + fake timers+// can trigger). Split out of instances.test.js by #6836, which moved this+// module's self-identity + file-I/O implementation out of services/instances.js.+const INSTANCE_IDENTITY_SRC = readFileSync(+ fileURLToPath(new URL('./instanceIdentity.js', import.meta.url)), 'utf8'+);++// Mock dependencies before importing the module+vi.mock('fs/promises', () => ({+ writeFile: vi.fn().mockResolvedValue(undefined),+ rename: vi.fn().mockResolvedValue(undefined)+}));++vi.mock('../lib/fileUtils.js', async (importOriginal) => ({+ ...(await importOriginal()),+ tryReadFile: vi.fn().mockResolvedValue(null),+ dataPath: (name) => `/mock/data/${name}`,+ readJSONFile: vi.fn(),+ ensureDir: vi.fn().mockResolvedValue(undefined),+ atomicWrite: vi.fn().mockResolvedValue(undefined),+ PATHS: { data: '/mock/data' }+}));++vi.mock('../lib/asyncMutex.js', () => ({+ createMutex: () => (fn) => fn()+}));++import { readJSONFile } from '../lib/fileUtils.js';+import {+ ensureSelf,+ getSelf,+ getInstanceId,+ ensureInstanceId,+ updateSelf,+} from './instanceIdentity.js';++describe('instanceIdentity.js', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ readJSONFile.mockResolvedValue({ self: null, peers: [] });+ });++ describe('ensureSelf', () => {+ it('should create identity when none exists', async () => {+ readJSONFile.mockResolvedValue({ self: null, peers: [] });++ const self = await ensureSelf();++ expect(self).toEqual({+ instanceId: expect.any(String),+ name: expect.any(String)+ });+ expect(self.instanceId).toMatch(/^[0-9a-f-]{36}$/);+ });++ it('should return existing identity without creating a new one', async () => {+ const existing = { instanceId: 'existing-id', name: 'my-host' };+ readJSONFile.mockResolvedValue({ self: existing, peers: [] });++ const self = await ensureSelf();++ expect(self).toEqual(existing);+ });+ });++ describe('getSelf', () => {+ it('should return self from data', async () => {+ const selfData = { instanceId: 'abc', name: 'host1' };+ readJSONFile.mockResolvedValue({ self: selfData, peers: [] });++ const result = await getSelf();++ expect(result).toEqual(selfData);+ });++ it('should return null when no self exists', async () => {+ readJSONFile.mockResolvedValue({ self: null, peers: [] });++ const result = await getSelf();++ expect(result).toBeNull();+ });+ });++ describe('getInstanceId', () => {+ it('should return "unknown" when no self exists', async () => {+ readJSONFile.mockResolvedValue({ self: null, peers: [] });++ const id = await getInstanceId();++ expect(id).toBe('unknown');+ });++ it('should return instanceId from self', async () => {+ readJSONFile.mockResolvedValue({+ self: { instanceId: 'test-id-123', name: 'host' },+ peers: []+ });++ const id = await getInstanceId();++ expect(id).toBe('test-id-123');+ });+ });++ // ensureInstanceId's runtime behavior is exercised transitively by the+ // agentLifecycle / cos / worktreeManager suites that call it. Here we assert+ // its structure at the source level — running the identity-creation path in+ // this suite (which uses resetModules + fake timers) can leave a console log+ // pending over the worker RPC at teardown and flake the whole run.+ describe('ensureInstanceId (#1563)', () => {+ it('is exported', () => {+ expect(INSTANCE_IDENTITY_SRC).toMatch(/export async function ensureInstanceId\(\)/);+ });++ it('reads getInstanceId, guards the unknown sentinel, and falls back to ensureSelf on the cold path', () => {+ const start = INSTANCE_IDENTITY_SRC.indexOf('export async function ensureInstanceId');+ const body = INSTANCE_IDENTITY_SRC.slice(start, start + 600);+ const getIdx = body.indexOf('await getInstanceId()');+ const guardIdx = body.indexOf('=== UNKNOWN_INSTANCE_ID');+ const ensureIdx = body.indexOf('await ensureSelf()');+ expect(getIdx, 'must read getInstanceId()').toBeGreaterThan(-1);+ expect(guardIdx, 'must guard on the UNKNOWN_INSTANCE_ID sentinel').toBeGreaterThan(getIdx);+ expect(ensureIdx, 'must fall back to ensureSelf() on the sentinel').toBeGreaterThan(guardIdx);+ });+ });++ describe('updateSelf', () => {+ it('should update name when self exists', async () => {+ readJSONFile.mockResolvedValue({+ self: { instanceId: 'abc', name: 'old-name' },+ peers: []+ });++ const result = await updateSelf('new-name');++ expect(result).toEqual({ instanceId: 'abc', name: 'new-name' });+ });++ it('should return null when no self exists', async () => {+ readJSONFile.mockResolvedValue({ self: null, peers: [] });++ const result = await updateSelf('name');++ expect(result).toBeNull();+ });++ // Moved from instances.test.js's "fullSync (full-mirror) peer mode" block+ // (#6836) — it exercises updateSelf's defaultPeerFullSync field, which+ // instances.js's addPeer reads to seed a new peer's fullSync default, but+ // the function itself lives here now.+ it('persists the new-peer full-sync default', async () => {+ readJSONFile.mockResolvedValue({ self: { instanceId: 'me', name: 'box' }, peers: [] });+ const self = await updateSelf(undefined, { defaultPeerFullSync: true });+ expect(self.defaultPeerFullSync).toBe(true);+ expect(self.name).toBe('box'); // name untouched when omitted+ });+ });+});diff --git a/server/services/instances.js b/server/services/instances.jsindex a4fc512adc..6dec3f6873 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -1,15 +1,16 @@/*** Instances Service*- * Manages PortOS federation — self identity, peer registration, health probing, and query proxying.+ * Manages PortOS peer orchestration — peer registration, health probing,+ * query proxying, and reciprocal sync. This install's own federation identity+ * (instanceId/name) and the data/instances.json file I/O + mutex live in+ * services/instanceIdentity.js; this module is a consumer of that leaf.* Data persists to data/instances.json.*/-import os from 'os';import net from 'net';import crypto from 'crypto';-import { dataPath, readJSONFile, ensureDir, PATHS, atomicWrite } from '../lib/fileUtils.js';-import { createMutex } from '../lib/asyncMutex.js';+import { loadData, withData, UNKNOWN_INSTANCE_ID, getInstanceId, getSelf } from './instanceIdentity.js';import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';import { canonicalStringify } from '../lib/objects.js';import { instanceEvents } from './instanceEvents.js';@@ -32,7 +33,6 @@ import {formatProbeDiagnosticLog,} from '../lib/peerProbeDiagnostics.js';-const INSTANCES_FILE = dataPath('instances.json');const PROBE_TIMEOUT_MS = 5000;const POLL_INTERVAL_MS = 30000;const INITIAL_PROBE_DELAY_MS = 2000;@@ -41,14 +41,6 @@ const INITIAL_PROBE_DELAY_MS = 2000;// user just has to connect Tailscale, no manual "sync now" required.const TAILSCALE_RECHECK_MS = 60_000;-// Sentinel returned by getInstanceId() and stamped onto sender/peer fields when-// the local identity hasn't been initialized yet. Every consumer that fans-// instance-keyed state out to peers (sharing/annotationsSync.flushAll,-// mediaAnnotations.mergePeerAnnotations, manifest builders) must refuse this-// value — without that guard, every uninitialized peer would collide in the-// same bucket and clobber each other on merge.-export const UNKNOWN_INSTANCE_ID = 'unknown';-// Backoff tiers for consecutive probe failures (in ms)// 30s → 1m → 5m → 15m → 1h → 24hconst BACKOFF_TIERS_MS = [@@ -60,7 +52,6 @@ const BACKOFF_TIERS_MS = [86_400_000 // tier 5: 24 hours (max)];-const withLock = createMutex();let pollTimer = null;// Set while we're waiting for Tailscale to connect before starting the real// probe loop (see startPolling). Kept separate from pollTimer so stopPolling can@@ -177,87 +168,6 @@ export function sanitizePeerForClient(peer) {return { ...safePeer, auth, syncCategories: resolveEffectiveCategories(peer, { masterSwitch: false }) };}-// Default data shape-const DEFAULT_DATA = {- self: null,- peers: []-};--// --- File I/O -----// STRICT (#4115): every mutation runs through `withData`, which writes whatever-// this read returned straight back. Swallowing an unreadable instances.json into-// DEFAULT_DATA therefore hands `ensureSelf` an identity-less record — it mints a-// BRAND-NEW instanceId and `saveData` persists it over the real file, rotating-// this node's federation identity and wiping every peer. ENOENT (never-// federated) stays the trustworthy first-run empty.-async function loadData() {- return await readJSONFile(INSTANCES_FILE, DEFAULT_DATA, { strict: true });-}--async function saveData(data) {- await ensureDir(PATHS.data);- await atomicWrite(INSTANCES_FILE, data);-}--async function withData(fn) {- return withLock(async () => {- const data = await loadData();- const result = await fn(data);- await saveData(data);- return result;- });-}--// --- Self Identity -----export async function ensureSelf() {- return withData(async (data) => {- if (!data.self) {- data.self = {- instanceId: crypto.randomUUID(),- name: os.hostname()- };- console.log(`🌐 Instance identity created: ${data.self.name} (${data.self.instanceId})`);- }- return data.self;- });-}--export async function getSelf() {- const data = await loadData();- return data.self;-}--let cachedInstanceId = null;-export async function getInstanceId() {- if (!cachedInstanceId) {- const id = (await getSelf())?.instanceId;- if (id) cachedInstanceId = id;- return id ?? UNKNOWN_INSTANCE_ID;- }- return cachedInstanceId;-}--/**- * Resolve this machine's real federation instance id, creating the local- * identity on the cold path. `getInstanceId()` returns the- * `UNKNOWN_INSTANCE_ID` sentinel (and never throws) before the identity exists- * — which can happen on a boot-time always-on auto-start that runs before the- * startup chain's `ensureSelf()` does. Callers that stamp the id onto durable- * records (agent provenance, worktree metadata) or compare it for cross-machine- * task claims (#1563) must never persist/compare the sentinel, so this creates- * (or loads) the real identity before returning. The warm path is the cheap- * cached `getInstanceId()` read; `ensureSelf()` only runs the once.- */-export async function ensureInstanceId() {- let instanceId = await getInstanceId();- if (instanceId === UNKNOWN_INSTANCE_ID) {- instanceId = (await ensureSelf())?.instanceId || instanceId;- }- return instanceId;-}-/*** The instances this install can direct a CoS task at (#4520): this machine* plus every peer that can actually RECEIVE the task. Two filters, both of@@ -288,23 +198,6 @@ export async function getAssignableInstances() {return assignable;}-export async function updateSelf(name, { defaultPeerFullSync } = {}) {- return withData(async (data) => {- if (!data.self) return null;- if (typeof name === 'string' && name.trim()) {- data.self.name = name.trim();- console.log(`🌐 Instance name updated: ${data.self.name}`);- }- // The default full-sync ("mirror everything") mode applied to NEW peers as- // they're added. Existing peers are untouched — this only seeds addPeer.- if (typeof defaultPeerFullSync === 'boolean') {- data.self.defaultPeerFullSync = defaultPeerFullSync;- console.log(`🌐 New-peer full-sync default: ${defaultPeerFullSync ? 'on' : 'off'}`);- }- return data.self;- });-}-// --- Peer CRUD ---export async function getPeers() {diff --git a/server/services/instances.test.js b/server/services/instances.test.jsindex 7488a1f311..8763131712 100644--- a/server/services/instances.test.js+++ b/server/services/instances.test.js@@ -1,11 +1,4 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { readFileSync } from 'node:fs';-import { fileURLToPath } from 'node:url';--// Source of instances.js, for source-level assertions that don't execute the-// module (avoids the vitest worker-teardown console-RPC flake that running the-// identity-creation path under resetModules + fake timers can trigger).-const INSTANCES_SRC = readFileSync(fileURLToPath(new URL('./instances.js', import.meta.url)), 'utf8');// This suite tests the real instances.js implementation — cancel the global// vitest.setup.js mock so the real getPeers (and all other exports) are used.@@ -68,10 +61,6 @@ import { getTailscaleStatus } from '../lib/tailscale.js';import { instanceEvents } from './instanceEvents.js';import { connectToPeer, disconnectFromPeer } from './peerSocketRelay.js';import {- ensureSelf,- getSelf,- getInstanceId,- updateSelf,getPeers,getAssignableInstances,addPeer,@@ -107,113 +96,7 @@ describe('instances.js', () => {vi.unstubAllGlobals();});- // --- Self Identity ----- describe('ensureSelf', () => {- it('should create identity when none exists', async () => {- readJSONFile.mockResolvedValue({ self: null, peers: [] });-- const self = await ensureSelf();-- expect(self).toEqual({- instanceId: expect.any(String),- name: expect.any(String)- });- expect(self.instanceId).toMatch(/^[0-9a-f-]{36}$/);- });-- it('should return existing identity without creating a new one', async () => {- const existing = { instanceId: 'existing-id', name: 'my-host' };- readJSONFile.mockResolvedValue({ self: existing, peers: [] });-- const self = await ensureSelf();-- expect(self).toEqual(existing);- });- });-- describe('getSelf', () => {- it('should return self from data', async () => {- const selfData = { instanceId: 'abc', name: 'host1' };- readJSONFile.mockResolvedValue({ self: selfData, peers: [] });-- const result = await getSelf();-- expect(result).toEqual(selfData);- });-- it('should return null when no self exists', async () => {- readJSONFile.mockResolvedValue({ self: null, peers: [] });-- const result = await getSelf();-- expect(result).toBeNull();- });- });-- describe('getInstanceId', () => {- it('should return "unknown" when no self exists', async () => {- readJSONFile.mockResolvedValue({ self: null, peers: [] });-- const id = await getInstanceId();-- expect(id).toBe('unknown');- });-- it('should return instanceId from self', async () => {- readJSONFile.mockResolvedValue({- self: { instanceId: 'test-id-123', name: 'host' },- peers: []- });-- const id = await getInstanceId();-- expect(id).toBe('test-id-123');- });- });-- // ensureInstanceId's runtime behavior is exercised transitively by the- // agentLifecycle / cos / worktreeManager suites that call it. Here we assert- // its structure at the source level — running the identity-creation path in- // this suite (which uses resetModules + fake timers) can leave a console log- // pending over the worker RPC at teardown and flake the whole run.- describe('ensureInstanceId (#1563)', () => {- it('is exported', () => {- expect(INSTANCES_SRC).toMatch(/export async function ensureInstanceId\(\)/);- });-- it('reads getInstanceId, guards the unknown sentinel, and falls back to ensureSelf on the cold path', () => {- const start = INSTANCES_SRC.indexOf('export async function ensureInstanceId');- const body = INSTANCES_SRC.slice(start, start + 600);- const getIdx = body.indexOf('await getInstanceId()');- const guardIdx = body.indexOf('=== UNKNOWN_INSTANCE_ID');- const ensureIdx = body.indexOf('await ensureSelf()');- expect(getIdx, 'must read getInstanceId()').toBeGreaterThan(-1);- expect(guardIdx, 'must guard on the UNKNOWN_INSTANCE_ID sentinel').toBeGreaterThan(getIdx);- expect(ensureIdx, 'must fall back to ensureSelf() on the sentinel').toBeGreaterThan(guardIdx);- });- });-- describe('updateSelf', () => {- it('should update name when self exists', async () => {- readJSONFile.mockResolvedValue({- self: { instanceId: 'abc', name: 'old-name' },- peers: []- });-- const result = await updateSelf('new-name');-- expect(result).toEqual({ instanceId: 'abc', name: 'new-name' });- });-- it('should return null when no self exists', async () => {- readJSONFile.mockResolvedValue({ self: null, peers: [] });-- const result = await updateSelf('name');-- expect(result).toBeNull();- });- });+ // --- Self Identity is services/instanceIdentity.test.js (#6836) ---// --- Assignable instances (#4520) ---@@ -1239,13 +1122,8 @@ describe('instances.js', () => {expect(body.fullSync).toBe(false);expect(body.syncCategories).toEqual({}); // valid object so the receiver schema parses});-- it('updateSelf persists the new-peer full-sync default', async () => {- readJSONFile.mockResolvedValue({ self: { instanceId: 'me', name: 'box' }, peers: [] });- const self = await updateSelf(undefined, { defaultPeerFullSync: true });- expect(self.defaultPeerFullSync).toBe(true);- expect(self.name).toBe('box'); // name untouched when omitted- });+ // updateSelf itself (including the defaultPeerFullSync field this block's+ // addPeer tests rely on) is covered by instanceIdentity.test.js (#6836).});// --- Probing ---diff --git a/server/services/mediaAnnotations.js b/server/services/mediaAnnotations.jsindex b6c75b75e2..9bc599d3e9 100644--- a/server/services/mediaAnnotations.js+++ b/server/services/mediaAnnotations.js@@ -9,7 +9,7 @@ import { join } from 'path';import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { isValidKey } from '../lib/mediaItemKey.js';-import { getInstanceId, UNKNOWN_INSTANCE_ID } from './instances.js';+import { getInstanceId, UNKNOWN_INSTANCE_ID } from './instanceIdentity.js';import { resolveLocalAuthorName } from './sharing/annotationIdentity.js';const STATE_PATH = join(PATHS.data, 'media-annotations.json');diff --git a/server/services/mediaAnnotations.test.js b/server/services/mediaAnnotations.test.jsindex f01827a2ed..968c2d779a 100644--- a/server/services/mediaAnnotations.test.js+++ b/server/services/mediaAnnotations.test.js@@ -15,9 +15,9 @@ tryReadFile: vi.fn().mockResolvedValue(null),readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(toPosix(path)) ? fileStore.get(toPosix(path)) : fallback)),}));-// Stable identity for tests — bypass the disk-backed instances service.+// Stable identity for tests — bypass the disk-backed instance identity leaf.const LOCAL_INSTANCE = 'local-instance-id';-vi.mock('./instances.js', () => ({+vi.mock('./instanceIdentity.js', () => ({getInstanceId: vi.fn(async () => LOCAL_INSTANCE),UNKNOWN_INSTANCE_ID: 'unknown',}));diff --git a/server/services/memoryDB.db.test.js b/server/services/memoryDB.db.test.jsindex 4f7090667d..eb289926c1 100644--- a/server/services/memoryDB.db.test.js+++ b/server/services/memoryDB.db.test.js@@ -28,7 +28,7 @@import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';import { checkHealth, ensureSchema, close, query } from '../lib/db.js';import { requireDbOrSkip } from '../lib/dbTestGate.js';-import { mockNoPeers, mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';+import { mockNoPeers, mockTestIdentity, mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';import { DEFAULT_MEMORY_CONFIG } from './memoryConfig.js';// Keep every filesystem side effect this module graph can reach (notifications@@ -44,10 +44,9 @@ vi.mock('../lib/fileUtils.js', async () => {// booted (a fresh worktree has no instance file and would get the 'unknown'// sentinel).const TEST_INSTANCE_ID = '00000000-0000-4000-8000-0000000c0ffe';-vi.mock('./instances.js', async (importOriginal) => {- const actual = await importOriginal();- return mockNoPeers(actual, { getInstanceId: () => Promise.resolve(TEST_INSTANCE_ID) });-});+vi.mock('./instances.js', async (importOriginal) => mockNoPeers(await importOriginal()));+vi.mock('./instanceIdentity.js', () =>+ mockTestIdentity({ getInstanceId: () => Promise.resolve(TEST_INSTANCE_ID) }));const memoryDB = await import('./memoryDB.js');diff --git a/server/services/memoryDB.js b/server/services/memoryDB.jsindex 30d89dd774..01a9ddddf7 100644--- a/server/services/memoryDB.js+++ b/server/services/memoryDB.js@@ -13,7 +13,7 @@ import { query, withTransaction, pgvectorToArray, arrayToPgvector } from '../libimport { cosEvents } from './cosEvents.js';import * as notifications from './notifications.js';import { DEFAULT_MEMORY_CONFIG, generateSummary, decrementAgentPendingApproval } from './memoryConfig.js';-import { getInstanceId } from './instances.js';+import { getInstanceId } from './instanceIdentity.js';const protectedMindMemoryTags = Object.values(PERSISTENT_MIND_MEMORY_PROTECTION_TAGS);diff --git a/server/services/peerUsage.js b/server/services/peerUsage.jsindex 1cc86029fe..bfd0d0c731 100644--- a/server/services/peerUsage.js+++ b/server/services/peerUsage.js@@ -141,13 +141,15 @@ function sanitizeDigest(raw) {const withLock = createMutex();/**- * This machine's federation identity. Dynamically imported so `dataSync` →- * `peerUsage` doesn't drag `services/instances.js` (peer socket relay,- * federated-media consumer, tailscale) into dataSync's module-load path — the- * same reason dataSync defers `sharing/peerSync.js`.+ * This machine's federation identity, read from the identity leaf+ * (services/instanceIdentity.js, #6836) rather than services/instances.js —+ * that module still drags the peer socket relay / federated-media consumer /+ * tailscale into dataSync's module-load path, the same reason dataSync defers+ * `sharing/peerSync.js`. Kept as a dynamic import to match that call shape,+ * though the leaf itself would no longer need the deferral.*/async function readSelfIdentity() {- const { getSelf, UNKNOWN_INSTANCE_ID } = await import('./instances.js');+ const { getSelf, UNKNOWN_INSTANCE_ID } = await import('./instanceIdentity.js');const self = await getSelf().catch(() => null);const instanceId = isNonEmptyStr(self?.instanceId) && self.instanceId !== UNKNOWN_INSTANCE_ID? self.instanceIddiff --git a/server/services/peerUsage.test.js b/server/services/peerUsage.test.jsindex 0c478ed039..712512086b 100644--- a/server/services/peerUsage.test.js+++ b/server/services/peerUsage.test.js@@ -9,13 +9,13 @@ vi.mock('../lib/fileUtils.js', async () => {});// peerUsage resolves this machine's identity through a dynamic import of-// instances.js (kept off dataSync's module graph); the digest itself is-// whatever usage.js currently holds.+// instanceIdentity.js (#6836; kept off dataSync's module graph); the digest+// itself is whatever usage.js currently holds.const self = { instanceId: 'inst-self', name: 'Workshop' };// importActual so UNKNOWN_INSTANCE_ID stays the REAL sentinel — a hand-written// copy here would let the real one drift and silently stop being filtered.-vi.mock('./instances.js', async () => ({- ...(await vi.importActual('./instances.js')),+vi.mock('./instanceIdentity.js', async () => ({+ ...(await vi.importActual('./instanceIdentity.js')),getSelf: vi.fn(async () => self),}));diff --git a/server/services/sharing/annotationsSync.js b/server/services/sharing/annotationsSync.jsindex 145f357f76..cdd65ca940 100644--- a/server/services/sharing/annotationsSync.js+++ b/server/services/sharing/annotationsSync.js@@ -14,7 +14,7 @@ import { listBuckets } from './buckets.js';import { buildManifest, writeManifest, annotationManifestFilename, readManifest, listManifestFilenames } from './manifest.js';import { getProducedByVersion } from './version.js';import { PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';-import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instances.js';+import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instanceIdentity.js';import { resolveBucketSourceName } from './annotationIdentity.js';import { onLocalAnnotationChange, listLocalAuthorAnnotations } from '../mediaAnnotations.js';diff --git a/server/services/sharing/annotationsSync.test.js b/server/services/sharing/annotationsSync.test.jsindex 474e1042bb..5527aa86c6 100644--- a/server/services/sharing/annotationsSync.test.js+++ b/server/services/sharing/annotationsSync.test.js@@ -32,7 +32,7 @@ vi.mock('./buckets.js', () => ({listBuckets: vi.fn(async () => []),}));-vi.mock('../instances.js', () => ({+vi.mock('../instanceIdentity.js', () => ({getInstanceId: vi.fn(async () => 'local-instance'),UNKNOWN_INSTANCE_ID: 'unknown',}));diff --git a/server/services/sharing/cosHistorySync.test.js b/server/services/sharing/cosHistorySync.test.jsindex ab81315004..9142344904 100644--- a/server/services/sharing/cosHistorySync.test.js+++ b/server/services/sharing/cosHistorySync.test.js@@ -15,12 +15,15 @@ import { createHash } from 'crypto';import { PATHS } from '../../lib/fileUtils.js';vi.mock('../instances.js', () => ({- UNKNOWN_INSTANCE_ID: 'unknown',DEFAULT_SYNC_CATEGORIES: {},- getInstanceId: vi.fn().mockResolvedValue('test-instance'),getPeers: vi.fn().mockResolvedValue([]),enqueueReciprocalSync: vi.fn().mockResolvedValue({ ok: true }),}));++vi.mock('../instanceIdentity.js', () => ({+ UNKNOWN_INSTANCE_ID: 'unknown',+ getInstanceId: vi.fn().mockResolvedValue('test-instance'),+}));vi.mock('../universeBuilder.js', async () => ({ getUniverse: vi.fn(), mergeUniversesFromSync: vi.fn(), listUniverses: vi.fn() }));vi.mock('../pipeline/series.js', async () => ({ getSeries: vi.fn(), mergeSeriesFromSync: vi.fn(), listSeries: vi.fn() }));vi.mock('../pipeline/issues.js', async () => ({ listIssues: vi.fn(), mergeIssuesFromSync: vi.fn() }));diff --git a/server/services/sharing/cosTasksSync.test.js b/server/services/sharing/cosTasksSync.test.jsindex 8712a90249..36d5c8c70a 100644--- a/server/services/sharing/cosTasksSync.test.js+++ b/server/services/sharing/cosTasksSync.test.js@@ -10,12 +10,15 @@ import { createHash } from 'crypto';// cosHistorySync.test.js does, purely so importing peerSync.js stays offline.vi.mock('../instances.js', () => ({- UNKNOWN_INSTANCE_ID: 'unknown',DEFAULT_SYNC_CATEGORIES: {},- getInstanceId: vi.fn().mockResolvedValue('test-instance'),getPeers: vi.fn().mockResolvedValue([]),enqueueReciprocalSync: vi.fn().mockResolvedValue({ ok: true }),}));++vi.mock('../instanceIdentity.js', () => ({+ UNKNOWN_INSTANCE_ID: 'unknown',+ getInstanceId: vi.fn().mockResolvedValue('test-instance'),+}));vi.mock('../universeBuilder.js', async () => ({ getUniverse: vi.fn(), mergeUniversesFromSync: vi.fn(), listUniverses: vi.fn() }));vi.mock('../pipeline/series.js', async () => ({ getSeries: vi.fn(), mergeSeriesFromSync: vi.fn(), listSeries: vi.fn() }));vi.mock('../pipeline/issues.js', async () => ({ listIssues: vi.fn(), mergeIssuesFromSync: vi.fn() }));diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.jsindex 1a4515c906..b27efac2ab 100644--- a/server/services/sharing/exporter.js+++ b/server/services/sharing/exporter.js@@ -31,7 +31,7 @@ import { getStoredOutline } from '../pipeline/reverseOutline.js';import { getUniverse } from '../universeBuilder.js';import { findCollectionByUniverseId, findCollectionBySeriesId } from '../mediaCollections.js';import { getJob } from '../mediaJobQueue/index.js';-import { getInstanceId } from '../instances.js';+import { getInstanceId } from '../instanceIdentity.js';import { getSettings } from '../settings.js';import { getProducedByVersion } from './version.js';import { PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex b135333995..693237f732 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -40,7 +40,7 @@ import { insertUniverseWithId, updateUniverse, getUniverse } from '../universeBuimport { applyLegacySeriesCanonToUniverse } from '../pipeline/migrateSeriesCanon.js';import { findOrCreateUniverseCollection, findOrCreateSeriesCollection, addItem as addCollectionItem, ERR_DUPLICATE as COLLECTION_ERR_DUPLICATE } from '../mediaCollections.js';import { adoptImportedSubscription, withReexportSuppressed } from './subscriptions.js';-import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instances.js';+import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instanceIdentity.js';import { mergePeerAnnotations } from '../mediaAnnotations.js';import { isStr, preserveLegacyCharacterFields } from '../../lib/storyBible.js';import { isPlainObject } from '../../lib/objects.js';diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex cac4094237..bd09e5981b 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -13,7 +13,7 @@ import { mkdtempSync, rmSync, writeFileSync, existsSync, mkdirSync, readFileSyncimport { tmpdir } from 'os';import { join } from 'path';import { createHash } from 'crypto';-import { makePathsProxy, mockNoPeerSync, mockNoPeers } from '../../lib/mockPathsDataRoot.js';+import { makePathsProxy, mockNoPeerSync, mockNoPeers, mockTestIdentity } from '../../lib/mockPathsDataRoot.js';const fileUtilsMock = vi.hoisted(() => ({ atomicWrite: vi.fn(), realAtomicWrite: null }));@@ -43,11 +43,11 @@ const fileUtilsActual = await vi.importActual('../../lib/fileUtils.js');fileUtilsMock.realAtomicWrite = fileUtilsActual.atomicWrite;fileUtilsMock.atomicWrite.mockImplementation((...args) => fileUtilsMock.realAtomicWrite(...args));-// Stub instances.getInstanceId so the exporter doesn't try to read the+// Stub instanceIdentity.getInstanceId so the exporter doesn't try to read the// real identity.json. Returns a fixed id for assertions.-vi.mock('../instances.js', () => mockNoPeers({}, {+vi.mock('../instances.js', () => mockNoPeers());+vi.mock('../instanceIdentity.js', () => mockTestIdentity({getInstanceId: () => Promise.resolve('test-instance-id'),- UNKNOWN_INSTANCE_ID: 'unknown',}));vi.mock('./peerSync.js', () => mockNoPeerSync());diff --git a/server/services/sharing/integrity.test.js b/server/services/sharing/integrity.test.jsindex dea52c1032..09b761d62d 100644--- a/server/services/sharing/integrity.test.js+++ b/server/services/sharing/integrity.test.js@@ -13,9 +13,13 @@ vi.mock('../../lib/peerUrl.js', async () => ({// Mock instances.js — peer list is controlled per test.vi.mock('../instances.js', async () => ({+ getPeers: vi.fn(),+}));++// Mock instanceIdentity.js — deterministic local id for manifest assertions.+vi.mock('../instanceIdentity.js', async () => ({UNKNOWN_INSTANCE_ID: 'unknown',getInstanceId: vi.fn().mockResolvedValue('local-instance'),- getPeers: vi.fn(),}));// Mock peerSync.js — we test integrity.js logic, not asset hashing.diff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.jsindex 43ae392561..1d1223a445 100644--- a/server/services/sharing/manifest.js+++ b/server/services/sharing/manifest.js@@ -23,7 +23,7 @@ import { isPlainObject } from '../../lib/objects.js';import { SHARING_SCHEMA_VERSION, getProducedByVersion } from './version.js';import { isStr } from '../../lib/storyBible.js';import { universeCollectionNameFor, seriesCollectionNameFor } from '../mediaCollections.js';-import { UNKNOWN_INSTANCE_ID } from '../instances.js';+import { UNKNOWN_INSTANCE_ID } from '../instanceIdentity.js';export const MANIFEST_KIND = Object.freeze(['series', 'universe', 'media', 'media-annotations']);diff --git a/server/services/sharing/peerPullAuthorization.js b/server/services/sharing/peerPullAuthorization.jsindex 676775939b..4b1e2c5469 100644--- a/server/services/sharing/peerPullAuthorization.js+++ b/server/services/sharing/peerPullAuthorization.js@@ -38,7 +38,7 @@import { ServerError } from '../../lib/errorHandler.js';import { findPeerById, peerAllowsOutbound, peerOutboundEligible, peerAllowsCategoryPull, peerHasCategory } from './peerSyncShared.js';import { getSettings } from '../settings.js';-import { UNKNOWN_INSTANCE_ID } from '../instances.js';+import { UNKNOWN_INSTANCE_ID } from '../instanceIdentity.js';// Lower-cased because Node/Express normalize incoming header names. The// outbound spelling (`X-PortOS-Instance-Id`) lives in lib/peerHttpClient.js.diff --git a/server/services/sharing/peerPullAuthorization.test.js b/server/services/sharing/peerPullAuthorization.test.jsindex 273841c8f4..b48fe34573 100644--- a/server/services/sharing/peerPullAuthorization.test.js+++ b/server/services/sharing/peerPullAuthorization.test.js@@ -1,8 +1,10 @@import { describe, it, expect, beforeEach, vi } from 'vitest';-// `instances.js` pulls in the socket relay / Tailscale graph; the only things-// this module and `peerSyncShared` need from it are `getPeers` and the-// UNKNOWN_INSTANCE_ID sentinel. Mocking it lets the REAL `findPeerById` /+// `instances.js` pulls in the socket relay / Tailscale graph; the only thing+// this module and `peerSyncShared` need from it is `getPeers` (the+// UNKNOWN_INSTANCE_ID sentinel this module reads now comes from the real,+// unmocked `instanceIdentity.js` leaf — #6836 — a pure constant, so reading+// it for real costs nothing). Mocking instances.js lets the REAL `findPeerById` /// `peerAllowsOutbound` / `peerHasCategory` run — which is the point: the test// asserts pull agrees with push because both use those same predicates.const peers = [];diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 8402ee802d..b94eeda53e 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -26,7 +26,8 @@ import { RESPONSE_TOO_LARGE } from '../../lib/httpClient.js';import { withAbortTimeout } from '../../lib/abortTimeout.js';import { flushBaseHashes, withBaseHashFlushBatch } from '../../lib/conflictJournal.js';import { recordEvents, registerSubscriptionAdapter } from './recordEvents.js';-import { getInstanceId, getPeers, enqueueReciprocalSync, UNKNOWN_INSTANCE_ID } from '../instances.js';+import { getPeers, enqueueReciprocalSync } from '../instances.js';+import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instanceIdentity.js';import { peerSyncPushSchema } from '../../lib/validation.js';import { instanceEvents } from '../instanceEvents.js';import { getIssue } from '../pipeline/issues.js';diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex d12333d2c1..5106929d8a 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -4,7 +4,7 @@ import { join } from 'path';import { tmpdir } from 'os';// We test peerSync.js by stubbing the external dependencies:-// - getPeers / getInstanceId from services/instances+// - getPeers from services/instances, getInstanceId from services/instanceIdentity// - merge*FromSync + getUniverse + getSeries + issue lookup/list helpers// - peerFetch (network)// All other logic (subscription store, asset manifest, diff, cursor advance)@@ -13,19 +13,23 @@ import { tmpdir } from 'os';import { PATHS } from '../../lib/fileUtils.js';import { RECORD_KIND_SCHEMA_CATEGORIES, PORTOS_SCHEMA_VERSIONS, NON_RECORD_SCHEMA_CATEGORIES } from '../../lib/schemaVersions.js';-// instances.js mock: aligns with mockNoPeers() contract (getPeers → [], getInstanceId-// → 'test-instance' by default) while keeping vi.fn() wrappers so per-test-// overrides via vi.mocked(getPeers).mockResolvedValue([...]) still work.-// A plain mockNoPeers() call would return static functions that vi.mocked()-// cannot spy on — so we construct vi.fn() variants here and match the same defaults.+// instances.js / instanceIdentity.js mocks: align with mockNoPeers() /+// mockTestIdentity() (#6836 split identity out of instances.js) while keeping+// vi.fn() wrappers so per-test overrides via vi.mocked(getPeers)+// .mockResolvedValue([...]) still work. A plain mockNoPeers()/mockTestIdentity()+// call would return static functions that vi.mocked() cannot spy on — so we+// construct vi.fn() variants here and match the same defaults.vi.mock('../instances.js', () => ({- UNKNOWN_INSTANCE_ID: 'unknown',DEFAULT_SYNC_CATEGORIES: {},- getInstanceId: vi.fn().mockResolvedValue('test-instance'),getPeers: vi.fn().mockResolvedValue([]),enqueueReciprocalSync: vi.fn().mockResolvedValue({ ok: true }),}));+vi.mock('../instanceIdentity.js', () => ({+ UNKNOWN_INSTANCE_ID: 'unknown',+ getInstanceId: vi.fn().mockResolvedValue('test-instance'),+}));+vi.mock('../universeBuilder.js', async () => ({getUniverse: vi.fn(),mergeUniversesFromSync: vi.fn(),@@ -225,7 +229,8 @@ import {__drainForTests,} from './peerSync.js';-import { getInstanceId, getPeers } from '../instances.js';+import { getPeers } from '../instances.js';+import { getInstanceId } from '../instanceIdentity.js';import { getUniverse, mergeUniversesFromSync, listUniverses } from '../universeBuilder.js';import { getSeries, mergeSeriesFromSync, listSeries } from '../pipeline/series.js';import { getIssue, listAllIssues, listIssues, listIssuesForSeries, mergeIssuesFromSync } from '../pipeline/issues.js';diff --git a/server/services/sharing/peerSyncPush.js b/server/services/sharing/peerSyncPush.jsindex 881fafc2b2..4cd7e3e3d2 100644--- a/server/services/sharing/peerSyncPush.js+++ b/server/services/sharing/peerSyncPush.js@@ -20,7 +20,7 @@ import {buildPortosMeta,formatVersionGap,} from '../../lib/schemaVersions.js';-import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instances.js';+import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instanceIdentity.js';import { getUniverse } from '../universeBuilder.js';import { getSeries } from '../pipeline/series.js';import { listIssuesForSeries } from '../pipeline/issues.js';diff --git a/server/services/sharing/peerSyncReceive.js b/server/services/sharing/peerSyncReceive.jsindex 054c6af227..db224cbe4c 100644--- a/server/services/sharing/peerSyncReceive.js+++ b/server/services/sharing/peerSyncReceive.js@@ -19,7 +19,7 @@ import {formatVersionGap,getPortosVersion,} from '../../lib/schemaVersions.js';-import { UNKNOWN_INSTANCE_ID } from '../instances.js';+import { UNKNOWN_INSTANCE_ID } from '../instanceIdentity.js';import { getUniverse, mergeUniversesFromSync } from '../universeBuilder.js';import { getSeries, mergeSeriesFromSync } from '../pipeline/series.js';import { mergeIssuesFromSync } from '../pipeline/issues.js';diff --git a/server/services/sharing/sidecarSync.test.js b/server/services/sharing/sidecarSync.test.jsindex e99882c6d3..2613a00592 100644--- a/server/services/sharing/sidecarSync.test.js+++ b/server/services/sharing/sidecarSync.test.js@@ -10,11 +10,14 @@ vi.mock('../../lib/peerHttpClient.js', async () => ({peerSocketOptions: {},}));-// Mock instances.js so backfillMissingSidecars can be tested without live peers.+// Mock instances.js / instanceIdentity.js so backfillMissingSidecars can be+// tested without live peers.vi.mock('../instances.js', async () => ({+ getPeers: vi.fn(),+}));+vi.mock('../instanceIdentity.js', async () => ({UNKNOWN_INSTANCE_ID: 'unknown',getInstanceId: vi.fn().mockResolvedValue('test-instance'),- getPeers: vi.fn(),}));// Mock peerUrl so base URL generation is deterministic in tests.diff --git a/server/services/sharing/stateConcurrency.test.js b/server/services/sharing/stateConcurrency.test.jsindex d0c0048dcb..ae47a8a807 100644--- a/server/services/sharing/stateConcurrency.test.js+++ b/server/services/sharing/stateConcurrency.test.js@@ -2,7 +2,7 @@ import { afterAll, beforeEach, expect, it, vi } from 'vitest';import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';-import { makePathsProxy, mockNoPeers, mockNoPeerSync } from '../../lib/mockPathsDataRoot.js';+import { makePathsProxy, mockNoPeers, mockTestIdentity, mockNoPeerSync } from '../../lib/mockPathsDataRoot.js';const tempRoot = mkdtempSync(join(tmpdir(), 'sharing-state-concurrency-'));const bucketPath = join(tempRoot, 'bucket');@@ -10,8 +10,9 @@ const exportRecord = vi.fn();vi.mock('../../lib/fileUtils.js', async () =>makePathsProxy(await vi.importActual('../../lib/fileUtils.js'), { dataRoot: tempRoot }));vi.mock('./exporter.js', () => ({ exportSeries: exportRecord, exportUniverse: exportRecord }));-vi.mock('../instances.js', () => mockNoPeers({}, {- getInstanceId: async () => 'local-instance', UNKNOWN_INSTANCE_ID: 'unknown',+vi.mock('../instances.js', () => mockNoPeers());+vi.mock('../instanceIdentity.js', () => mockTestIdentity({+ getInstanceId: async () => 'local-instance',}));vi.mock('./peerSync.js', () => mockNoPeerSync());vi.mock('../mediaJobQueue/index.js', () => ({ getJob: () => null }));diff --git a/server/services/sharing/subscriptions.js b/server/services/sharing/subscriptions.jsindex 3905062137..c10316037e 100644--- a/server/services/sharing/subscriptions.js+++ b/server/services/sharing/subscriptions.js@@ -38,7 +38,7 @@ import {// stable; the canonical implementation now lives in recordEvents.js.export { withReexportSuppressed };import { subscriptionFilename, legacySubscriptionFilename } from './manifest.js';-import { getInstanceId } from '../instances.js';+import { getInstanceId } from '../instanceIdentity.js';// Re-export from the canonical source so other modules can import the// filename helper from either side without forcing a manifest.js import.diff --git a/server/services/sharing/subscriptions.test.js b/server/services/sharing/subscriptions.test.jsindex 88d47d55a4..9d40aef924 100644--- a/server/services/sharing/subscriptions.test.js+++ b/server/services/sharing/subscriptions.test.js@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { mkdtempSync, rmSync, mkdirSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-import { mockNoPeerSync, mockNoPeers } from '../../lib/mockPathsDataRoot.js';+import { mockNoPeerSync, mockNoPeers, mockTestIdentity } from '../../lib/mockPathsDataRoot.js';// Universe builder evaluates PATHS.data at module top, so allocate a stable// temp dir before any service imports. beforeEach wipes + reseeds inside.@@ -23,9 +23,9 @@ vi.mock('../../lib/fileUtils.js', async () => {},});});-vi.mock('../instances.js', () => mockNoPeers({}, {+vi.mock('../instances.js', () => mockNoPeers());+vi.mock('../instanceIdentity.js', () => mockTestIdentity({getInstanceId: () => Promise.resolve('inst-test'),- UNKNOWN_INSTANCE_ID: 'unknown',}));vi.mock('./peerSync.js', () => mockNoPeerSync());vi.mock('../mediaJobQueue/index.js', () => ({ getJob: () => null }));diff --git a/server/services/sharing/watcher.js b/server/services/sharing/watcher.jsindex be8ca5ba64..636dba8605 100644--- a/server/services/sharing/watcher.js+++ b/server/services/sharing/watcher.js@@ -19,7 +19,7 @@ import { join, basename, sep } from 'path';import { processManifest, processBacklog, handleUnshare, sharingEvents } from './importer.js';import { getBucket, listBuckets, ensureBucketLayout } from './buckets.js';import { isManifestPruning, pruneBucketManifests } from './manifest.js';-import { getInstanceId } from '../instances.js';+import { getInstanceId } from '../instanceIdentity.js';const watchers = new Map(); // bucketId → chokidar instanceconst backlogQueues = new Map(); // bucketId → { running: Promise, queued: Promise|null }diff --git a/server/services/sharing/watcher.test.js b/server/services/sharing/watcher.test.jsindex 6f5eb54262..43d2b0def0 100644--- a/server/services/sharing/watcher.test.js+++ b/server/services/sharing/watcher.test.js@@ -12,7 +12,7 @@ vi.mock('./buckets.js', () => ({ensureBucketLayout: vi.fn().mockResolvedValue(undefined),}));vi.mock('./manifest.js', () => ({ isManifestPruning: vi.fn(), pruneBucketManifests: vi.fn() }));-vi.mock('../instances.js', () => ({ getInstanceId: vi.fn() }));+vi.mock('../instanceIdentity.js', () => ({ getInstanceId: vi.fn() }));import { watch } from 'chokidar';import { processBacklog, processManifest, handleUnshare } from './importer.js';diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex 62004fd5ec..0759baf88e 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -11,7 +11,8 @@ import { join } from 'path';import { readJSONFile, ensureDir, PATHS, dataPath, atomicWrite, writeFileGuarded } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';import { instanceEvents } from './instanceEvents.js';-import { getPeers, resolveEffectiveCategories, updatePeer, getInstanceId, UNKNOWN_INSTANCE_ID } from './instances.js';+import { getPeers, resolveEffectiveCategories, updatePeer } from './instances.js';+import { getInstanceId, UNKNOWN_INSTANCE_ID } from './instanceIdentity.js';import { peerBaseUrl } from '../lib/peerUrl.js';import { peerFetch } from '../lib/peerHttpClient.js';import * as brainSync from './brainSync.js';diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.jsindex fb431b3b6e..59a8aab0f4 100644--- a/server/services/syncOrchestrator.test.js+++ b/server/services/syncOrchestrator.test.js@@ -8,6 +8,9 @@ vi.mock('./instances.js', async () => ({...(await vi.importActual('./instances.js')),getPeers: vi.fn(),updatePeer: vi.fn().mockResolvedValue(undefined),+}));+vi.mock('./instanceIdentity.js', () => ({+ UNKNOWN_INSTANCE_ID: 'unknown',// forPeer scoping resolves our own instanceId; the orchestrator catches a// throw/UNKNOWN and just omits the query param, so the default mock returns// a stable id to exercise the scoped path.@@ -323,9 +326,9 @@ describe('syncOrchestrator', () => {it('omits forPeer when our instanceId is UNKNOWN (older/uninitialized install)', async () => {const dataSync = await import('./dataSync.js');- const instances = await import('./instances.js');+ const instanceIdentity = await import('./instanceIdentity.js');dataSync.getSupportedCategories.mockReturnValue(['universe', 'character']);- instances.getInstanceId.mockResolvedValueOnce('unknown'); // === UNKNOWN_INSTANCE_ID+ instanceIdentity.getInstanceId.mockResolvedValueOnce('unknown'); // === UNKNOWN_INSTANCE_IDconst peerWithCats = { ...mockPeer, syncCategories: { universe: true, character: true } };mockFetch.mockResolvedValue({ ok: true, json: async () => ({ checksum: 'x', data: null }) });await syncWithPeer(peerWithCats);diff --git a/server/services/videoGen/remote.test.js b/server/services/videoGen/remote.test.jsindex 7a7f0b6853..8fe3f18068 100644--- a/server/services/videoGen/remote.test.js+++ b/server/services/videoGen/remote.test.js@@ -42,6 +42,9 @@ vi.mock('../federatedMediaConsumer.js', () => ({vi.mock('../instances.js', () => ({getPeers: vi.fn(async () => federation.peers),+}));++vi.mock('../instanceIdentity.js', () => ({// Used to derive the consumer's own half of a content-addressed asset id, so it// can ask the peer whether bytes are already staged before re-sending them.getInstanceId: vi.fn(async () => 'consumer-instance'),diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex f49897f587..8d0c0fb4d5 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -20,7 +20,7 @@ import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';import { forkRemoteName, normalizeForkHead } from '../lib/forkHead.js';import { isHumanClaimWorktree, worktreeAgentId, worktreeOwnershipReason } from '../lib/worktreeOwnership.js';-import { ensureInstanceId } from './instances.js';+import { ensureInstanceId } from './instanceIdentity.js';export { isHumanClaimWorktree } from '../lib/worktreeOwnership.js';diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex 16974a831d..f563bff2e6 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -21,7 +21,7 @@ vi.mock('fs/promises', () => ({// adoptWorktree ensures the worktrees root exists before moving a tree into it.mkdir: vi.fn().mockResolvedValue(undefined),}));-vi.mock('./instances.js', () => ({ ensureInstanceId: vi.fn().mockResolvedValue('instance-1') }));+vi.mock('./instanceIdentity.js', () => ({ ensureInstanceId: vi.fn().mockResolvedValue('instance-1') }));const getDefaultBranchMock = vi.fn().mockResolvedValue('main');const hasBranchMergeEvidenceMock = vi.fn().mockResolvedValue(false);vi.mock('./git.js', () => ({