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(apps): expand leftover install-root token so Apps Git finds checkout (#6498)

atomanticagent899a14ec37db
diff --git a/README.md b/README.md
index 97df766bf9..bcebd8b818 100644
--- a/README.md
+++ b/README.md
@@ -389,7 +389,7 @@ npm run pm2:save # Save the process list for start
### Apps (`data/apps.json`)
Each registered app includes:
- **name** — Display name in the dashboard
-- **repoPath** — Absolute path to project directory
+- **repoPath** — Absolute path; seed token __PORTOS_ROOT__ expanded by setup:data / load
- **uiPort / apiPort** — Port numbers for quick access links
- **startCommands** — Commands to start the app (used by PM2)
- **pm2ProcessNames** — PM2 process identifiers for status tracking
diff --git a/scripts/lib/rewriteAppsPortosRoot.js b/scripts/lib/rewriteAppsPortosRoot.js
new file mode 100644
index 0000000000..62e6324dd6
--- /dev/null
+++ b/scripts/lib/rewriteAppsPortosRoot.js
@@ -0,0 +1,26 @@
+/**
+ * Expand `__PORTOS_ROOT__` inside `data/apps.json` to the live checkout path.
+ * Shared by `scripts/setup-data.js` so fresh seeds and existing data/ trees
+ * both get the rewrite (idempotent).
+ */
+import { existsSync, readFileSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import {
+ containsPortosRootToken,
+ expandPortosRootToken,
+ PORTOS_ROOT_TOKEN,
+} from '../../server/lib/portosRootPlaceholder.js';
+
+/**
+ * @param {string} dataDir Absolute path to the install's `data/` directory
+ * @param {string} rootDir Absolute PortOS checkout path that replaces the token
+ * @returns {{ rewritten: boolean, appsFile: string }}
+ */
+export function rewriteAppsPortosRoot(dataDir, rootDir) {
+ const appsFile = join(dataDir, 'apps.json');
+ if (!existsSync(appsFile)) return { rewritten: false, appsFile };
+ const content = readFileSync(appsFile, 'utf8');
+ if (!containsPortosRootToken(content)) return { rewritten: false, appsFile };
+ writeFileSync(appsFile, expandPortosRootToken(content, rootDir));
+ return { rewritten: true, appsFile, token: PORTOS_ROOT_TOKEN, rootDir };
+}
diff --git a/scripts/lib/rewriteAppsPortosRoot.test.js b/scripts/lib/rewriteAppsPortosRoot.test.js
new file mode 100644
index 0000000000..c2a781b794
--- /dev/null
+++ b/scripts/lib/rewriteAppsPortosRoot.test.js
@@ -0,0 +1,54 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { rewriteAppsPortosRoot } from './rewriteAppsPortosRoot.js';
+
+describe('rewriteAppsPortosRoot', () => {
+ let dataDir;
+
+ beforeEach(() => {
+ dataDir = mkdtempSync(join(tmpdir(), 'portos-apps-root-'));
+ });
+
+ afterEach(() => {
+ rmSync(dataDir, { recursive: true, force: true });
+ });
+
+ it('rewrites leftover placeholders in an existing data/apps.json', () => {
+ writeFileSync(join(dataDir, 'apps.json'), JSON.stringify({
+ apps: {
+ 'portos-default': {
+ repoPath: '__PORTOS_ROOT__',
+ appIconPath: '__PORTOS_ROOT__/client/public/portos-logo.png',
+ },
+ },
+ }, null, 2));
+
+ const result = rewriteAppsPortosRoot(dataDir, '/opt/PortOS');
+ expect(result.rewritten).toBe(true);
+
+ const parsed = JSON.parse(readFileSync(join(dataDir, 'apps.json'), 'utf8'));
+ expect(parsed.apps['portos-default'].repoPath).toBe('/opt/PortOS');
+ expect(parsed.apps['portos-default'].appIconPath)
+ .toBe('/opt/PortOS/client/public/portos-logo.png');
+ });
+
+ it('is a no-op when placeholders are already expanded', () => {
+ const body = JSON.stringify({
+ apps: { 'portos-default': { repoPath: '/opt/PortOS' } },
+ });
+ writeFileSync(join(dataDir, 'apps.json'), body);
+
+ const result = rewriteAppsPortosRoot(dataDir, '/opt/PortOS');
+ expect(result.rewritten).toBe(false);
+ expect(readFileSync(join(dataDir, 'apps.json'), 'utf8')).toBe(body);
+ });
+
+ it('is a no-op when apps.json is missing', () => {
+ expect(rewriteAppsPortosRoot(dataDir, '/opt/PortOS')).toEqual({
+ rewritten: false,
+ appsFile: join(dataDir, 'apps.json'),
+ });
+ });
+});
diff --git a/scripts/setup-data.js b/scripts/setup-data.js
index 16fc5fd808..937c5f0cb2 100644
--- a/scripts/setup-data.js
+++ b/scripts/setup-data.js
@@ -5,6 +5,7 @@ import { fileURLToPath } from 'url';
import { md5, buildPromptDriftTables } from './migrations/_lib.js';
import { MIGRATION_OWNED_PATHS } from './lib/migrationOwnedPaths.js';
+import { rewriteAppsPortosRoot } from './lib/rewriteAppsPortosRoot.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const rootDir = join(__dirname, '..');
@@ -41,21 +42,24 @@ if (existsSync(legacyMigrationsDir) && readdirSync(legacyMigrationsDir).length =
console.log('🧹 Removed orphan data/migrations/ directory');
}
+/**
+ * Expand `__PORTOS_ROOT__` in data/apps.json to this checkout's absolute path.
+ * Idempotent: no-op when the file is missing or already expanded. Runs for both
+ * fresh seeds and existing data/ trees (partial copies / restored volumes can
+ * leave the literal token in place — that breaks Apps → Git checkout detection).
+ */
+const rewritePortosRootPlaceholder = () => {
+ const { rewritten, token, rootDir: expandedRoot } = rewriteAppsPortosRoot(dataDir, rootDir);
+ if (rewritten) {
+ console.log(`📍 Expanded ${token} in apps.json → ${expandedRoot}`);
+ }
+};
+
if (!existsSync(dataDir)) {
console.log('📁 Creating data directory from data.reference...');
mkdirSync(dataDir, { recursive: true });
cpSync(referenceDir, dataDir, { recursive: true, filter: (src) => !migrationOwnedSeeds.has(src) });
-
- // Replace __PORTOS_ROOT__ placeholder with actual install path in apps.json
- const appsFile = join(dataDir, 'apps.json');
- if (existsSync(appsFile)) {
- const content = readFileSync(appsFile, 'utf8');
- if (content.includes('__PORTOS_ROOT__')) {
- writeFileSync(appsFile, content.replace(/__PORTOS_ROOT__/g, rootDir));
- console.log(`📍 Set PortOS repoPath to ${rootDir}`);
- }
- }
-
+ rewritePortosRootPlaceholder();
console.log('✅ Data directory created');
} else {
// Ensure all subdirectories and files exist without overwriting existing files
@@ -81,6 +85,7 @@ if (!existsSync(dataDir)) {
};
ensureSampleContent(referenceDir, dataDir);
+ rewritePortosRootPlaceholder();
console.log('✅ Data directory already exists, ensured subdirectories and files');
}
diff --git a/server/lib/README.md b/server/lib/README.md
index d576c63f83..f08b5790d4 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -269,6 +269,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `fileCore.js` | Cross-cutting filesystem primitives (`atomicWrite`, `writeFileGuarded`, `appendFileGuarded`, `copyFileGuarded`, `rmGuarded`, `unlinkGuarded`, `createWriteStreamGuarded`, directory helpers, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers. |
| `fileUtils.js` | Backward-compatible facade re-exporting the focused file utility modules so existing deep imports need no caller changes. |
| `portosEnv.js` | Single server-side helper for PortOS's own `.env` (`PORTOS_ENV_PATH` anchored to `installRoot` per #1947, `parseEnvContents`, `readPortosEnvValue`, `upsertPortosEnvLine` + `upsertEnvLine`), with replacer-function guard for `$`-patterns and `process.env` wins precedence; `scripts/lib/envFile.js` stays as the zero-dependency boundary copy. |
+| `portosRootPlaceholder.js` | Expand leftover `__PORTOS_ROOT__` tokens in apps registry fields (`repoPath`, `appIconPath`, etc.) so a partial/restored `data/` tree cannot leave Apps → Git looking for a non-existent checkout. `PORTOS_ROOT_TOKEN`, `expandPortosRootToken`, `expandPortosRootInApp`, `containsPortosRootToken`. Used by `services/apps.js` on load and by `scripts/setup-data.js` / `scripts/lib/rewriteAppsPortosRoot.js` when seeding or rewriting `data/apps.json`. |
| `secretText.js` | `scrubSecretTokens(text)` — replace credential-SHAPED substrings (prefixed API keys, GitHub/Slack tokens, JWTs, AWS key ids, pasted Bearer headers, 48+-char hex) with `[REDACTED]` in free text bound for an LLM provider or a world-readable artifact; `scrubSecretTokensDeep(value)` walks arrays/plain objects and scrubs every string value. Value-side counterpart to the operator-action ledger's key-based `redactPayload` and `commandSecurity.js#redactOutput`'s JSON patterns; conservative so prose, 40-hex git SHAs, and short ids survive. |
| `homePath.js` | `scrubHomePath(value)` — replace the running user's home-directory prefix with `~` anywhere in a string, so `/Users/<name>/…` never embeds the OS username in anything a user pastes into a bug report. Non-strings pass through; a root-user container reporting `/` as home is left alone (substituting on it would rewrite every separator in every path). Zero-dependency by design: `agentRunEvents.js` re-exports it for the CoS ledger, and `scripts/doctor.js` imports it statically because it must load from a bare checkout with no `node_modules` (`scripts/pre-install-entrypoints.test.js` enforces that). |
| `jsonIo.js` | JSON/JSONL parsing and file IO, strict read sentinels, append/read/write helpers, and `createCachedStore` — a TTL-cached mutable JSON document with serialized `save`/`mutate`; its `load()` is strict (#4115) so a corrupt file rejects instead of being overwritten by the next `mutate`. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 7f025219a4..045ff6cf3e 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -253,6 +253,7 @@ export * as fileUtils from './fileUtils.js';
export * from './fileWriteQueue.js';
export * from './forgeIssueState.js';
export * from './portosEnv.js';
+export * from './portosRootPlaceholder.js';
export * from './homePath.js';
export * from './jsonIo.js';
export * from './settingsStore.js';
diff --git a/server/lib/portosRootPlaceholder.js b/server/lib/portosRootPlaceholder.js
new file mode 100644
index 0000000000..d872b301c0
--- /dev/null
+++ b/server/lib/portosRootPlaceholder.js
@@ -0,0 +1,55 @@
+/**
+ * `data.reference/apps.json` ships `__PORTOS_ROOT__` in fields like `repoPath`
+ * and `appIconPath` so the seed is install-agnostic. `scripts/setup-data.js`
+ * expands the token when seeding `data/`, and `server/services/apps.js`
+ * re-expands on load so a partial/restored `data/` that still carries the
+ * literal token cannot leave Apps → Git stuck on "Checkout not found".
+ */
+
+export const PORTOS_ROOT_TOKEN = '__PORTOS_ROOT__';
+
+/**
+ * Replace every `__PORTOS_ROOT__` occurrence in a string with `root`.
+ * Non-strings and strings without the token are returned unchanged.
+ *
+ * @param {unknown} value
+ * @param {string} root Absolute install/checkout path
+ * @returns {unknown}
+ */
+export function expandPortosRootToken(value, root) {
+ if (typeof value !== 'string' || !value.includes(PORTOS_ROOT_TOKEN)) return value;
+ return value.split(PORTOS_ROOT_TOKEN).join(root);
+}
+
+/**
+ * Expand `__PORTOS_ROOT__` in every top-level string field of an app record.
+ *
+ * @param {Record<string, unknown>|null|undefined} app
+ * @param {string} root Absolute install/checkout path
+ * @returns {{ app: Record<string, unknown>|null|undefined, changed: boolean }}
+ */
+export function expandPortosRootInApp(app, root) {
+ if (!app || typeof app !== 'object' || Array.isArray(app)) {
+ return { app, changed: false };
+ }
+ let changed = false;
+ const next = { ...app };
+ for (const [key, value] of Object.entries(next)) {
+ const expanded = expandPortosRootToken(value, root);
+ if (expanded !== value) {
+ next[key] = expanded;
+ changed = true;
+ }
+ }
+ return { app: next, changed };
+}
+
+/**
+ * True when `text` still carries the unresolved install-root token.
+ *
+ * @param {unknown} text
+ * @returns {boolean}
+ */
+export function containsPortosRootToken(text) {
+ return typeof text === 'string' && text.includes(PORTOS_ROOT_TOKEN);
+}
diff --git a/server/lib/portosRootPlaceholder.test.js b/server/lib/portosRootPlaceholder.test.js
new file mode 100644
index 0000000000..b7db8d0c33
--- /dev/null
+++ b/server/lib/portosRootPlaceholder.test.js
@@ -0,0 +1,45 @@
+import { describe, it, expect } from 'vitest';
+import {
+ PORTOS_ROOT_TOKEN,
+ expandPortosRootToken,
+ expandPortosRootInApp,
+ containsPortosRootToken,
+} from './portosRootPlaceholder.js';
+
+describe('portosRootPlaceholder', () => {
+ it('expands the token and leaves other strings alone', () => {
+ expect(expandPortosRootToken(`${PORTOS_ROOT_TOKEN}/icon.png`, '/opt/PortOS'))
+ .toBe('/opt/PortOS/icon.png');
+ expect(expandPortosRootToken('/already/real', '/opt/PortOS')).toBe('/already/real');
+ expect(expandPortosRootToken(42, '/opt/PortOS')).toBe(42);
+ });
+
+ it('expands every top-level string field on an app record', () => {
+ const { app, changed } = expandPortosRootInApp({
+ repoPath: PORTOS_ROOT_TOKEN,
+ appIconPath: `${PORTOS_ROOT_TOKEN}/client/public/portos-logo.png`,
+ name: 'PortOS',
+ nested: { path: PORTOS_ROOT_TOKEN },
+ }, '/mock/root');
+
+ expect(changed).toBe(true);
+ expect(app.repoPath).toBe('/mock/root');
+ expect(app.appIconPath).toBe('/mock/root/client/public/portos-logo.png');
+ expect(app.name).toBe('PortOS');
+ // Nested objects are left alone — apps.json only uses the token at top level.
+ expect(app.nested).toEqual({ path: PORTOS_ROOT_TOKEN });
+ });
+
+ it('reports unchanged when no token is present', () => {
+ const input = { repoPath: '/custom/checkout', name: 'Other' };
+ const { app, changed } = expandPortosRootInApp(input, '/mock/root');
+ expect(changed).toBe(false);
+ expect(app).toEqual(input);
+ });
+
+ it('detects the token', () => {
+ expect(containsPortosRootToken(`x${PORTOS_ROOT_TOKEN}`)).toBe(true);
+ expect(containsPortosRootToken('/real')).toBe(false);
+ expect(containsPortosRootToken(null)).toBe(false);
+ });
+});
diff --git a/server/services/apps.js b/server/services/apps.js
index d832c13573..ebf3419894 100644
--- a/server/services/apps.js
+++ b/server/services/apps.js
@@ -2,6 +2,10 @@ import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import EventEmitter from 'events';
import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import {
+ containsPortosRootToken,
+ expandPortosRootInApp,
+} from '../lib/portosRootPlaceholder.js';
import { PORTOS_APP_ID } from '../lib/appIdentity.js';
import { NON_PM2_TYPES, usesPm2, isDesktopType } from './streamingDetect.js';
import { listProcessesStrict } from './pm2.js';
@@ -102,6 +106,18 @@ async function loadApps() {
data.apps = {};
}
+ // Safety net: expand leftover `__PORTOS_ROOT__` tokens from a partial
+ // data.reference copy (setup-data only rewrote them on first create historically).
+ // Persist so Apps → Git stops looking for `__PORTOS_ROOT__/.git`.
+ let placeholderDirty = false;
+ for (const [id, app] of Object.entries(data.apps)) {
+ const { app: expanded, changed } = expandPortosRootInApp(app, PATHS.root);
+ if (changed) {
+ data.apps[id] = expanded;
+ placeholderDirty = true;
+ }
+ }
+
// Ensure PortOS baseline app is always present and up-to-date
const baseline = buildPortosApp();
if (!data.apps[PORTOS_APP_ID]) {
@@ -110,7 +126,7 @@ async function loadApps() {
console.log('📦 Seeded baseline PortOS app into apps registry');
} else {
// Reconcile: merge new baseline fields into existing entry (preserves user overrides)
- let dirty = false;
+ let dirty = placeholderDirty;
for (const [key, value] of Object.entries(baseline)) {
if (!(key in data.apps[PORTOS_APP_ID])) {
data.apps[PORTOS_APP_ID][key] = value;
@@ -125,9 +141,17 @@ async function loadApps() {
dirty = true;
}
}
+ // A literal `__PORTOS_ROOT__` is not a real user override — force repoPath
+ // to the live checkout. Concrete custom paths are preserved (expand left them).
+ if (containsPortosRootToken(data.apps[PORTOS_APP_ID].repoPath)) {
+ data.apps[PORTOS_APP_ID].repoPath = baseline.repoPath;
+ dirty = true;
+ }
if (dirty) {
await atomicWrite(APPS_FILE, data);
- console.log('📦 Reconciled PortOS baseline app with latest fields');
+ console.log(placeholderDirty
+ ? '📦 Expanded __PORTOS_ROOT__ placeholders and reconciled PortOS baseline app'
+ : '📦 Reconciled PortOS baseline app with latest fields');
}
}
diff --git a/server/services/apps.test.js b/server/services/apps.test.js
index fb92dc95bd..d0c33ca46a 100644
--- a/server/services/apps.test.js
+++ b/server/services/apps.test.js
@@ -37,7 +37,7 @@ vi.mock('./pm2.js', () => ({
import { atomicWrite, readJSONFile } from '../lib/fileUtils.js';
import { listProcessesStrict } from './pm2.js';
import { resetExecutionHistory } from './taskSchedule.js';
-import { annotateExpectedExit, createApp, deleteApp, getAppStatuses, getAppStatusSummary, getDesktopProcessNames, getReservedPorts, invalidateCache, PORTOS_APP_ID, resolvePm2HomeForProcess, updateApp, updateAppTaskTypeOverride } from './apps.js';
+import { annotateExpectedExit, createApp, deleteApp, getAllApps, getAppStatuses, getAppStatusSummary, getDesktopProcessNames, getReservedPorts, invalidateCache, PORTOS_APP_ID, resolvePm2HomeForProcess, updateApp, updateAppTaskTypeOverride } from './apps.js';
describe('pr-watcher cooldown reset', () => {
beforeEach(() => {
@@ -782,3 +782,80 @@ describe('getAppStatuses', () => {
expect(portos.degraded).toBeUndefined();
});
});
+
+describe('__PORTOS_ROOT__ placeholder expansion on load', () => {
+ beforeEach(() => {
+ invalidateCache();
+ vi.clearAllMocks();
+ });
+
+ it('expands and persists placeholder repoPath and appIconPath', async () => {
+ readJSONFile.mockResolvedValue({
+ apps: {
+ [PORTOS_APP_ID]: {
+ name: 'PortOS',
+ repoPath: '__PORTOS_ROOT__',
+ appIconPath: '__PORTOS_ROOT__/client/public/portos-logo.png',
+ type: 'express',
+ pm2ProcessNames: ['portos-server'],
+ },
+ },
+ });
+
+ const apps = await getAllApps();
+ const portos = apps.find((app) => app.id === PORTOS_APP_ID);
+ expect(portos.repoPath).toBe('/mock/root');
+ expect(portos.appIconPath).toBe('/mock/root/client/public/portos-logo.png');
+
+ expect(atomicWrite).toHaveBeenCalled();
+ const persisted = atomicWrite.mock.calls.at(-1)[1];
+ expect(persisted.apps[PORTOS_APP_ID].repoPath).toBe('/mock/root');
+ expect(persisted.apps[PORTOS_APP_ID].appIconPath).toBe('/mock/root/client/public/portos-logo.png');
+ expect(JSON.stringify(persisted)).not.toContain('__PORTOS_ROOT__');
+ });
+
+ it('preserves a concrete user-overridden repoPath', async () => {
+ readJSONFile.mockResolvedValue({
+ apps: {
+ [PORTOS_APP_ID]: {
+ name: 'PortOS',
+ repoPath: '/custom/portos/checkout',
+ type: 'express',
+ pm2ProcessNames: ['portos-server'],
+ },
+ },
+ });
+
+ const apps = await getAllApps();
+ const portos = apps.find((app) => app.id === PORTOS_APP_ID);
+ expect(portos.repoPath).toBe('/custom/portos/checkout');
+ });
+
+ it('expands placeholders on non-PortOS app records too', async () => {
+ readJSONFile.mockResolvedValue({
+ apps: {
+ [PORTOS_APP_ID]: {
+ name: 'PortOS',
+ repoPath: '/mock/root',
+ type: 'express',
+ pm2ProcessNames: ['portos-server'],
+ },
+ 'other-app': {
+ name: 'Other',
+ repoPath: '__PORTOS_ROOT__/../sibling',
+ appIconPath: '__PORTOS_ROOT__/icon.png',
+ type: 'node',
+ },
+ },
+ });
+
+ const apps = await getAllApps();
+ const other = apps.find((app) => app.id === 'other-app');
+ expect(other.repoPath).toBe('/mock/root/../sibling');
+ expect(other.appIconPath).toBe('/mock/root/icon.png');
+
+ const persisted = atomicWrite.mock.calls.at(-1)[1];
+ expect(persisted.apps['other-app'].repoPath).toBe('/mock/root/../sibling');
+ expect(persisted.apps['other-app'].appIconPath).toBe('/mock/root/icon.png');
+ });
+});