Skip to content

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

fix([issue-1947]): pin data root via PORTOS_DATA_ROOT so worktree-booted servers don't crash migrations

[._.]/ Adam Eivy5b21cbea313f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8af667c9a4..3152e7598d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -87,6 +87,7 @@
## Internal
+- **[issue-1947] Boot migrations no longer crash when a server is booted from inside a CoS agent worktree** — every path in the boot-migration chain derived its data root from where the executing file lives (`import.meta.url`), so a `node server/index.js` launched from inside a CoS agent's git worktree (`data/cos/worktrees/agent-*/`) resolved `data/`/`data.reference/` to the worktree's checkout, which has no gitignored runtime tree — boot migrations then crashed on ENOENT (observed: migration 005 writing `data/prompts/stages/pipeline-arc-overview.md`). Two fixes: (1) a durable `PORTOS_DATA_ROOT` env var (new `server/lib/dataRoot.js` `resolveInstallRoot`), pinned at real launch in `ecosystem.config.cjs`, that lets a process pin its install root explicitly instead of inferring it from the executing file — now preferred over the derived path in `PATHS` (`server/lib/fileUtils.js`), `server/index.js`'s migration call, and `scripts/run-migrations.js`; falls back to the derived path when unset (backward compatible). (2) a defensive backstop in `runMigrations` — `isWorktreeRoot()` detects a `data/cos/worktrees/`-rooted path and skips the migration pass with a single-line warning instead of crashing (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). (Closes #1947)
- **[issue-1848] Strengthened weak truthiness test assertions** — replaced `toBeTruthy()` checks that would pass on wrong values with concrete value/shape assertions: `autobiography.test.js` now asserts the next-prompt object shape and round-trippable ISO-8601 timestamps for `createdAt`/`updatedAt`/`lastPromptAt`/`followUpsGeneratedAt` (with `updatedAt`/`lastPromptAt` proven strictly newer than the seeded old values); `storyBuilder.test.js` asserts `getSeries()` returns the matching `series.id` and `lockedAt` is a valid ISO timestamp; `commandSecurity.test.js` anchors the allowlist against known-safe membership (`git`/`gh`/`node`/`npm`/`pm2`/`ls`/`cat`/`echo`) and asserts dangerous commands stay absent, replacing the self-referential array-vs-Set check; and `fileUtils.test.js`'s visualTemplates resolution now asserts the returned path carries the `data/templates/` segment + unique basename. (#1848)
- **[issue-1842] Replaced magic numbers with canonical constants** — consolidated the duplicated chars-per-token estimate (`Math.ceil(len / 4)`) onto the canonical `estimateTokens()` / `CHARS_PER_TOKEN` from `server/lib/contextBudget.js` at the usage-recording (`server/index.js`, `services/agentRunTracking.js`) and digital-twin-export (×5) sites, and dropped the shadow `estimateTokens` in `services/memoryEmbeddings.js` (now re-exported from `contextBudget` so existing importers are unaffected; `truncateToTokens` uses `CHARS_PER_TOKEN` too). The CoS runner port `5558` was a raw literal in `cos-runner/index.js`, `services/cosRunnerClient.js`, and `services/apps.js`; the importable `server/lib/ports.js` mirror (previously only API/API_LOCAL/UI) now carries the remaining static ecosystem ports (CDP, CDP_HEALTH, `COS`, AUTOFIXER, AUTOFIXER_UI) and those sites use `PORTS.COS` (and `PORTS.CDP`/`AUTOFIXER`/`AUTOFIXER_UI` for the sibling app definitions that were also literals). The CoS runner's kill/cleanup `setTimeout` literals are now named (`SIGKILL_GRACE_MS`, `ORPHAN_CLEANUP_DELAY_MS`, `SHUTDOWN_DRAIN_MS`) and the server's graceful-shutdown force-exit timeout is `GRACEFUL_SHUTDOWN_TIMEOUT_MS`. Behavior-preserving. (#1842)
- **[issue-1840] Adopted canonical client hooks/utils + deduped `countWords`** — replaced hand-rolled duplicates of existing helpers across the codebase. `countWords` was re-implemented in `server/lib/issueLength.js` and `server/services/writersRoom/local.js`; both now import the new canonical `server/lib/textUtils.js` (the client `formatters.js` mirror is documented against it). Six services that open-coded `mkdir(dir, { recursive: true })` now use `lib/fileUtils.js` `ensureDir` (which swallows the spurious Windows EEXIST/EPERM the raw call doesn't). The `logs` and `openclaw` SSE routes route their response-header boilerplate through `openSseStream`, and `X-Accel-Buffering: no` moved into the shared `SSE_HEADERS` (so every SSE consumer disables proxy buffering). On the client, ~44 `new Date(x).toLocaleString()` display sites now use the canonical `formatDateTime` for consistent date formatting, and several hand-rolled single-armed-row delete confirmations / saving-flag patterns adopt the `useConfirmDelete` / `useAsyncAction` hooks. (#1840)
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index ea14c5cc8d..68a6a42cc5 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -8,7 +8,12 @@ const IS_WIN = process.platform === 'win32';
// Shared env inherited by all apps (merged into each app's env)
const BASE_ENV = {
NODE_ENV: 'development',
- TZ: 'UTC' // All log timestamps and Date operations in UTC
+ TZ: 'UTC', // All log timestamps and Date operations in UTC
+ // Pin the install root explicitly so data-root resolution never derives it
+ // from the executing file's location. A server/agent booted from inside a CoS
+ // git worktree (data/cos/worktrees/agent-*) would otherwise resolve `data/`
+ // to the worktree's nonexistent tree and crash boot migrations (#1947).
+ PORTOS_DATA_ROOT: __dirname
};
// Read a couple of machine-local settings from .env (pm2 doesn't auto-load it
diff --git a/scripts/run-migrations.js b/scripts/run-migrations.js
index b4cc29eb18..64b25647fa 100644
--- a/scripts/run-migrations.js
+++ b/scripts/run-migrations.js
@@ -2,9 +2,13 @@
import { readdir, readFile, writeFile, mkdir, rename } from 'fs/promises';
import { join, dirname, resolve } from 'path';
import { fileURLToPath, pathToFileURL } from 'url';
+import { resolveInstallRoot, isWorktreeRoot } from '../server/lib/dataRoot.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
-const DEFAULT_ROOT_DIR = join(__dirname, '..');
+// Prefer an explicit PORTOS_DATA_ROOT env var over the executing-file location
+// so a process booted from inside a CoS agent git worktree still resolves to
+// the real install (#1947). Falls back to the derived path when unset.
+const DEFAULT_ROOT_DIR = resolveInstallRoot(join(__dirname, '..'));
const DEFAULT_MIGRATIONS_DIR = join(__dirname, 'migrations');
const appliedFilePath = (rootDir) => join(rootDir, 'data', 'migrations.applied.json');
@@ -82,6 +86,16 @@ export async function runMigrations({
rootDir = DEFAULT_ROOT_DIR,
migrationsDir = DEFAULT_MIGRATIONS_DIR,
} = {}) {
+ // Backstop for #1947: a process booted from inside a CoS agent git worktree
+ // (data/cos/worktrees/agent-*) has no gitignored data/ runtime tree, so
+ // migrations that read/write data/ or data.reference/ crash on ENOENT. A
+ // worktree checkout has no business running its own migration pass — skip it
+ // with a clear warning instead of crashing boot.
+ if (isWorktreeRoot(rootDir)) {
+ console.warn(`⚠️ Skipping migrations: rootDir is a CoS agent worktree checkout (${rootDir}) — no data/ tree to migrate`);
+ return 0;
+ }
+
const appliedFile = appliedFilePath(rootDir);
// Ensure data/ exists so we can persist applied state (migrationsDir
diff --git a/scripts/run-migrations.test.js b/scripts/run-migrations.test.js
index 45ebd9955c..3b2e4230eb 100644
--- a/scripts/run-migrations.test.js
+++ b/scripts/run-migrations.test.js
@@ -110,6 +110,63 @@ export const md5 = (s) => s;
});
});
+describe('runMigrations worktree backstop (#1947)', () => {
+ let baseDir;
+ let migrationsDir;
+ let warnSpy;
+ let logSpy;
+
+ beforeEach(() => {
+ baseDir = mkdtempSync(join(tmpdir(), 'run-migrations-wt-'));
+ migrationsDir = join(baseDir, 'migrations');
+ mkdirSync(migrationsDir, { recursive: true });
+ // A migration that WOULD fail if it ran against a worktree checkout — it
+ // writes into data/ which doesn't exist there. The guard must skip before
+ // this runs.
+ writeFileSync(join(migrationsDir, '001-fixture.js'), `
+import { writeFileSync } from 'fs';
+import { join } from 'path';
+export default {
+ async up({ rootDir }) {
+ writeFileSync(join(rootDir, 'data', 'fixture-marker.txt'), 'ran');
+ }
+};
+`);
+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ rmSync(baseDir, { recursive: true, force: true });
+ warnSpy.mockRestore();
+ logSpy.mockRestore();
+ });
+
+ it('skips the migration pass when rootDir is a CoS agent worktree checkout', async () => {
+ // A worktree checkout root lives under data/cos/worktrees/<agent> and has
+ // no data/ runtime tree — running migrations there crashes on ENOENT.
+ const worktreeRoot = join(baseDir, 'data', 'cos', 'worktrees', 'agent-test');
+ mkdirSync(worktreeRoot, { recursive: true });
+
+ const ran = await runMigrations({ rootDir: worktreeRoot, migrationsDir });
+
+ expect(ran).toBe(0);
+ expect(existsSync(join(worktreeRoot, 'data'))).toBe(false); // never created
+ expect(existsSync(join(worktreeRoot, 'data', 'migrations.applied.json'))).toBe(false);
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('CoS agent worktree'));
+ });
+
+ it('still runs migrations for a normal (non-worktree) rootDir', async () => {
+ const realRoot = join(baseDir, 'install');
+ mkdirSync(join(realRoot, 'data'), { recursive: true });
+
+ const ran = await runMigrations({ rootDir: realRoot, migrationsDir });
+
+ expect(ran).toBe(1);
+ expect(existsSync(join(realRoot, 'data', 'fixture-marker.txt'))).toBe(true);
+ });
+});
+
describe('listPendingMigrations', () => {
let rootDir;
let dataDir;
diff --git a/server/index.js b/server/index.js
index 36f1e470c1..99fbd7246b 100644
--- a/server/index.js
+++ b/server/index.js
@@ -3,6 +3,7 @@ import { Server } from 'socket.io';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { PATHS } from './lib/fileUtils.js';
+import { resolveInstallRoot } from './lib/dataRoot.js';
import { PORTS } from './lib/ports.js';
import { estimateTokens } from './lib/contextBudget.js';
import { existsSync } from 'fs';
@@ -239,7 +240,11 @@ const DATA_REFERENCE_DIR = join(__dirname, '..', 'data.reference');
// existing installs hit "Stage X not found" until the user manually runs
// `npm run migrations` or `npm run update`. Idempotent and cheap when the
// applied-list is already current.
-await runMigrations({ rootDir: join(__dirname, '..') }).catch(err => {
+// Prefer PORTOS_DATA_ROOT (set at real launch in ecosystem.config.cjs) over the
+// import.meta.url-derived path so a server booted from inside a CoS agent
+// worktree still resolves to the real install; runMigrations also skips a
+// worktree-rooted path as a backstop (#1947).
+await runMigrations({ rootDir: resolveInstallRoot(join(__dirname, '..')) }).catch(err => {
// Log the full stack (or stringified err for non-Error throws) so failures
// during boot are diagnosable without rerunning under a debugger.
console.error(`❌ Migration run failed at startup: ${err?.stack ?? err}`);
diff --git a/server/lib/README.md b/server/lib/README.md
index 548f17f679..792f6bf443 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -113,6 +113,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `saveOneNow` / `listIds` / `loadAll` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. Per-id write queue means writes to different records don't serialize; `saveOneNow` is for callers already inside a collection write queue. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. **Type-index `config` slot** holds cross-record state (see the `TypeIndexConfig` typedef + header convention): `{ runs?: [], featureFlags?: {}, lockPolicies?: {} }` — `runs` is the shipped slot (universeBuilder's capped history log), the other two are reserved names; consumers may add their own keys but should reuse a reserved name when it fits and document the shape next to the consumer. `saveTypeIndex({ config })` shallow-merges `config` one level deep (a patched `runs` replaces the whole array), so a read-modify-write of a slot must load → mutate a copy → write inside `queueTypeIndexWrite(fn)`. |
| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from every `pruneTombstoned*` path — universe/series/issue/collection) so the side store doesn't grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |
| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |
+| `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |
| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |
| `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. |
| `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. |
diff --git a/server/lib/dataRoot.js b/server/lib/dataRoot.js
new file mode 100644
index 0000000000..d60bb86f47
--- /dev/null
+++ b/server/lib/dataRoot.js
@@ -0,0 +1,65 @@
+/**
+ * Data-root resolution + worktree-checkout detection.
+ *
+ * PortOS derives its "install root" (the directory that contains `data/`,
+ * `data.reference/`, `scripts/`) from where the executing file lives
+ * (`import.meta.url`). That silently breaks when a process boots from inside a
+ * CoS agent's git worktree (`data/cos/worktrees/agent-<id>`): the checkout only
+ * contains git-tracked files, so the gitignored `data/` runtime tree is empty,
+ * and boot migrations resolve against a nonexistent path and crash (#1947).
+ *
+ * `resolveInstallRoot()` lets a real launch pin the root explicitly via the
+ * `PORTOS_DATA_ROOT` env var, independent of the executing file's location, so
+ * even a process booted from inside a worktree still resolves to the real
+ * install. `isWorktreeRoot()` is the defensive backstop: detect a
+ * worktree-rooted process so callers (boot migrations) can skip work that
+ * assumes the real install tree instead of crashing.
+ */
+import { isAbsolute, resolve as resolvePath, sep } from 'path';
+
+/** Env var a real launch sets to pin the install root (see ecosystem.config.cjs). */
+export const DATA_ROOT_ENV = 'PORTOS_DATA_ROOT';
+
+/**
+ * Resolve the PortOS install root (the parent of `data/` and `data.reference/`).
+ *
+ * Prefers an explicit `PORTOS_DATA_ROOT` env var (set at real process launch)
+ * over the caller's `import.meta.url`-derived fallback, so a process booted
+ * from inside a git worktree still resolves to the real install. Returns
+ * `fallbackRoot` unchanged when the env var is unset or blank — preserving the
+ * existing behavior for installs that never set it (backward compatible).
+ *
+ * @param {string} fallbackRoot absolute path derived from the caller's location
+ * @returns {string} the install root to use
+ */
+export function resolveInstallRoot(fallbackRoot) {
+ const override = process.env[DATA_ROOT_ENV];
+ if (typeof override === 'string' && override.trim() !== '') {
+ const trimmed = override.trim();
+ return isAbsolute(trimmed) ? trimmed : resolvePath(trimmed);
+ }
+ return fallbackRoot;
+}
+
+/**
+ * True when `rootDir` is a CoS agent worktree checkout rather than the real
+ * install — its path lives under `data/cos/worktrees/`. Such a checkout has no
+ * gitignored `data/` runtime tree, so boot migrations (and any pass that
+ * assumes the real install's `data/`/`data.reference/`) must skip it instead of
+ * crashing on ENOENT.
+ *
+ * We key ONLY on the `data/cos/worktrees/` path segment, not on "does `data/`
+ * exist" — a worktree checkout still ships `data/.gitkeep`, and a genuinely
+ * fresh real install legitimately has an empty `data/` on first boot (the
+ * migration runner creates it), so a presence check would false-positive on
+ * fresh installs and skip their migrations.
+ *
+ * @param {string} rootDir candidate install root
+ * @returns {boolean}
+ */
+export function isWorktreeRoot(rootDir) {
+ if (typeof rootDir !== 'string' || rootDir === '') return false;
+ const normalized = resolvePath(rootDir);
+ const segment = `${sep}${['data', 'cos', 'worktrees'].join(sep)}`;
+ return normalized.includes(`${segment}${sep}`) || normalized.endsWith(segment);
+}
diff --git a/server/lib/dataRoot.test.js b/server/lib/dataRoot.test.js
new file mode 100644
index 0000000000..05046867a9
--- /dev/null
+++ b/server/lib/dataRoot.test.js
@@ -0,0 +1,66 @@
+import { describe, it, expect, afterEach } from 'vitest';
+import { join, sep } from 'path';
+import { DATA_ROOT_ENV, resolveInstallRoot, isWorktreeRoot } from './dataRoot.js';
+
+const REAL_ROOT = join(sep, 'Users', 'me', 'PortOS');
+
+afterEach(() => {
+ delete process.env[DATA_ROOT_ENV];
+});
+
+describe('resolveInstallRoot', () => {
+ it('returns the fallback when PORTOS_DATA_ROOT is unset (backward compatible)', () => {
+ delete process.env[DATA_ROOT_ENV];
+ expect(resolveInstallRoot(REAL_ROOT)).toBe(REAL_ROOT);
+ });
+
+ it('returns the fallback when PORTOS_DATA_ROOT is blank', () => {
+ process.env[DATA_ROOT_ENV] = ' ';
+ expect(resolveInstallRoot(REAL_ROOT)).toBe(REAL_ROOT);
+ });
+
+ it('prefers an absolute PORTOS_DATA_ROOT over the fallback', () => {
+ const pinned = join(sep, 'srv', 'portos');
+ process.env[DATA_ROOT_ENV] = pinned;
+ expect(resolveInstallRoot(REAL_ROOT)).toBe(pinned);
+ });
+
+ it('resolves a relative PORTOS_DATA_ROOT to an absolute path', () => {
+ process.env[DATA_ROOT_ENV] = 'some/rel';
+ const out = resolveInstallRoot(REAL_ROOT);
+ expect(out).toBe(join(process.cwd(), 'some', 'rel'));
+ expect(out).not.toBe(REAL_ROOT);
+ });
+
+ it('pins the real root even when the fallback is a worktree path', () => {
+ process.env[DATA_ROOT_ENV] = REAL_ROOT;
+ const worktreeFallback = join(REAL_ROOT, 'data', 'cos', 'worktrees', 'agent-abc');
+ expect(resolveInstallRoot(worktreeFallback)).toBe(REAL_ROOT);
+ });
+});
+
+describe('isWorktreeRoot', () => {
+ it('detects a CoS agent worktree checkout by path segment', () => {
+ const worktree = join(REAL_ROOT, 'data', 'cos', 'worktrees', 'agent-3afe1ffb');
+ expect(isWorktreeRoot(worktree)).toBe(true);
+ });
+
+ it('detects a nested path under a worktree checkout', () => {
+ const nested = join(REAL_ROOT, 'data', 'cos', 'worktrees', 'agent-x', 'server');
+ expect(isWorktreeRoot(nested)).toBe(true);
+ });
+
+ it('treats the real install root as NOT a worktree (fresh install safe)', () => {
+ expect(isWorktreeRoot(REAL_ROOT)).toBe(false);
+ });
+
+ it('does not false-positive on an unrelated data/ path', () => {
+ expect(isWorktreeRoot(join(REAL_ROOT, 'data', 'cos', 'agents'))).toBe(false);
+ });
+
+ it('returns false for empty or non-string input', () => {
+ expect(isWorktreeRoot('')).toBe(false);
+ expect(isWorktreeRoot(undefined)).toBe(false);
+ expect(isWorktreeRoot(null)).toBe(false);
+ });
+});
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index db473ece94..80cc86ab6a 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -13,6 +13,7 @@ import { join, dirname, basename, extname, resolve as resolvePath, sep as PATH_S
import { fileURLToPath } from 'url';
import { homedir } from 'os';
import { ServerError } from './errorHandler.js';
+import { resolveInstallRoot } from './dataRoot.js';
// Promisified execFile — shared so callers (e.g. backup's pg_dump probing)
// don't each re-wrap it. Returns { stdout, stderr }.
@@ -23,6 +24,12 @@ const IS_WIN = process.platform === 'win32';
const __lib_filename = fileURLToPath(import.meta.url);
const __lib_dirname = dirname(__lib_filename);
+// Install root (parent of data/, data.reference/). Prefer an explicit
+// PORTOS_DATA_ROOT env var over the import.meta.url-derived path so a process
+// booted from inside a CoS agent git worktree still resolves to the real
+// install (#1947). Falls back to the derived path when the env var is unset.
+const INSTALL_ROOT = resolveInstallRoot(join(__lib_dirname, '../..'));
+
/**
* MIME types that could execute scripts when served inline — force Content-Disposition: attachment
*/
@@ -32,67 +39,67 @@ export const RISKY_MIME_TYPES = new Set(['text/html', 'image/svg+xml', 'applicat
* Base directories relative to project root
*/
export const PATHS = {
- root: join(__lib_dirname, '../..'),
- data: join(__lib_dirname, '../../data'),
- cos: join(__lib_dirname, '../../data/cos'),
- brain: join(__lib_dirname, '../../data/brain'),
- digitalTwin: join(__lib_dirname, '../../data/digital-twin'),
- health: join(__lib_dirname, '../../data/health'),
- runs: join(__lib_dirname, '../../data/runs'),
- memory: join(__lib_dirname, '../../data/cos/memory'),
- cosAgents: join(__lib_dirname, '../../data/cos/agents'), // CoS sub-agents
- scripts: join(__lib_dirname, '../../data/cos/scripts'),
- reports: join(__lib_dirname, '../../data/cos/reports'),
+ root: INSTALL_ROOT,
+ data: join(INSTALL_ROOT, 'data'),
+ cos: join(INSTALL_ROOT, 'data/cos'),
+ brain: join(INSTALL_ROOT, 'data/brain'),
+ digitalTwin: join(INSTALL_ROOT, 'data/digital-twin'),
+ health: join(INSTALL_ROOT, 'data/health'),
+ runs: join(INSTALL_ROOT, 'data/runs'),
+ memory: join(INSTALL_ROOT, 'data/cos/memory'),
+ cosAgents: join(INSTALL_ROOT, 'data/cos/agents'), // CoS sub-agents
+ scripts: join(INSTALL_ROOT, 'data/cos/scripts'),
+ reports: join(INSTALL_ROOT, 'data/cos/reports'),
// AI Agent Personalities data
- agentPersonalities: join(__lib_dirname, '../../data/agents'),
- meatspace: join(__lib_dirname, '../../data/meatspace'),
- calendar: join(__lib_dirname, '../../data/calendar'),
- messages: join(__lib_dirname, '../../data/messages'),
- screenshots: join(__lib_dirname, '../../data/screenshots'),
- uploads: join(__lib_dirname, '../../data/uploads'),
- cosAttachments: join(__lib_dirname, '../../data/cos/attachments'),
- worktrees: join(__lib_dirname, '../../data/cos/worktrees'),
- repos: join(__lib_dirname, '../../data/repos'),
- browserProfile: join(__lib_dirname, '../../data/browser-profile'),
+ agentPersonalities: join(INSTALL_ROOT, 'data/agents'),
+ meatspace: join(INSTALL_ROOT, 'data/meatspace'),
+ calendar: join(INSTALL_ROOT, 'data/calendar'),
+ messages: join(INSTALL_ROOT, 'data/messages'),
+ screenshots: join(INSTALL_ROOT, 'data/screenshots'),
+ uploads: join(INSTALL_ROOT, 'data/uploads'),
+ cosAttachments: join(INSTALL_ROOT, 'data/cos/attachments'),
+ worktrees: join(INSTALL_ROOT, 'data/cos/worktrees'),
+ repos: join(INSTALL_ROOT, 'data/repos'),
+ browserProfile: join(INSTALL_ROOT, 'data/browser-profile'),
browserDownloads: join(homedir(), 'Downloads'),
- digests: join(__lib_dirname, '../../data/cos/digests'),
- promptSkills: join(__lib_dirname, '../../data/prompts/skills'),
- promptSkillsJobs: join(__lib_dirname, '../../data/prompts/skills/jobs'),
- decisions: join(__lib_dirname, '../../data/cos/decisions'),
- telegram: join(__lib_dirname, '../../data/telegram'),
- templates: join(__lib_dirname, '../../data/prompts/templates'),
+ digests: join(INSTALL_ROOT, 'data/cos/digests'),
+ promptSkills: join(INSTALL_ROOT, 'data/prompts/skills'),
+ promptSkillsJobs: join(INSTALL_ROOT, 'data/prompts/skills/jobs'),
+ decisions: join(INSTALL_ROOT, 'data/cos/decisions'),
+ telegram: join(INSTALL_ROOT, 'data/telegram'),
+ templates: join(INSTALL_ROOT, 'data/prompts/templates'),
// Visual template assets (e.g. the character reference-sheet layout PNG used
// as the init-image anchor by the universe-builder character sheet renderer).
// Distinct from `templates` above, which is the legacy prompt-template dir.
// Files here are shipped via data.reference/templates/ on first install.
- visualTemplates: join(__lib_dirname, '../../data/templates'),
- settings: join(__lib_dirname, '../../data/settings'),
- missions: join(__lib_dirname, '../../data/cos/missions'),
- tools: join(__lib_dirname, '../../data/tools'),
- images: join(__lib_dirname, '../../data/images'),
+ visualTemplates: join(INSTALL_ROOT, 'data/templates'),
+ settings: join(INSTALL_ROOT, 'data/settings'),
+ missions: join(INSTALL_ROOT, 'data/cos/missions'),
+ tools: join(INSTALL_ROOT, 'data/tools'),
+ images: join(INSTALL_ROOT, 'data/images'),
// Uploaded multi-reference inputs for FLUX.2 multi-ref edits. Sibling of
// `images/` rather than a subdir so the gallery's flat `.png` enumeration
// never surfaces them, and so a future per-render cleanup pass can drop
// the whole dir without touching the gallery.
- imageRefs: join(__lib_dirname, '../../data/image-refs'),
- loras: join(__lib_dirname, '../../data/loras'),
+ imageRefs: join(INSTALL_ROOT, 'data/image-refs'),
+ loras: join(INSTALL_ROOT, 'data/loras'),
// Per-character LoRA training datasets (collectionStore layout:
// lora-datasets/<id>/index.json + lora-datasets/<id>/images/*.png).
// Machine-local like `loras/` — datasets never federate.
- loraDatasets: join(__lib_dirname, '../../data/lora-datasets'),
+ loraDatasets: join(INSTALL_ROOT, 'data/lora-datasets'),
// LoRA training run artifacts (checkpoints/samples/cache per run). Run
// RECORDS live in Postgres (lora_training_runs); only artifacts live here.
- trainingRuns: join(__lib_dirname, '../../data/training-runs'),
- videos: join(__lib_dirname, '../../data/videos'),
- videoThumbnails: join(__lib_dirname, '../../data/video-thumbnails'),
+ trainingRuns: join(INSTALL_ROOT, 'data/training-runs'),
+ videos: join(INSTALL_ROOT, 'data/videos'),
+ videoThumbnails: join(INSTALL_ROOT, 'data/video-thumbnails'),
// Persisted audio renders (voice-over lines). Kept distinct from
// the in-memory voice-agent synthesis path in services/voice/ — that path
// streams WAV over Socket.IO without ever touching disk.
- audio: join(__lib_dirname, '../../data/audio'),
+ audio: join(INSTALL_ROOT, 'data/audio'),
// Uploaded + (eventually) generated background music tracks. Separate from
// `audio/` so the user can browse + reuse a track across issues without
// walking through the VO-line filenames.
- music: join(__lib_dirname, '../../data/music'),
+ music: join(INSTALL_ROOT, 'data/music'),
// Extracted assets from third-party imports (ChatGPT export images/audio/
// PDFs). Served read-only at `/data/brain-imports/...` so the Memory
// conversation viewer can render inline `![](url)` images and asset links.
@@ -100,8 +107,8 @@ export const PATHS = {
// asset referenced from multiple conversations is stored once. The transcript
// archive JSON lives one level up (data/brain/imports/<source>/) and is NOT
// served — only this assets subtree is.
- brainImportAssets: join(__lib_dirname, '../../data/brain/imports/assets'),
- slashdo: join(__lib_dirname, '../../lib/slashdo')
+ brainImportAssets: join(INSTALL_ROOT, 'data/brain/imports/assets'),
+ slashdo: join(INSTALL_ROOT, 'lib/slashdo')
};
/**
diff --git a/server/lib/index.js b/server/lib/index.js
index 1d0c0b011d..2b97b3c61f 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -108,6 +108,7 @@ export * from './collectionStore.js';
export * from './conflictJournal.js';
export * from './createKeyCachedQueue.js';
export * from './createNewestWinsGuard.js';
+export * from './dataRoot.js';
export * from './fileUtils.js';
export * from './fileWriteQueue.js';
export * from './schemaVersions.js';