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

feat: persist shared/derived port edits via per-process-targeted ecosystem rewrite

Adam Eivy6761b217b7bf
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0b5c3ef350..488cd12afb 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -22,3 +22,4 @@
- Scheduled-task descriptions in the Automation UI no longer fall back to a raw dasherized label. `claim-work` (the single-source work-tracker router), `code-reviewer-a`/`code-reviewer-b`, and `do-replan` now show real one-line descriptions instead of "claim work" / "code reviewer a", which read as orphaned/legacy tasks. A parity guard test now keeps the description map in sync with the task-type list.
- PM2 standardization no longer assigns ports that are already in use. The analysis now feeds the AI the set of listening/reserved ports (plus the common Vite defaults 5173/5174) to avoid, and a deterministic post-pass reassigns any port that still collides into the 6000–6099 range — so standardizing an app never lands on a port another app already holds.
- Editing an app's ports now persists. Port fields are derived from `ecosystem.config.cjs`, so saving only updated PortOS's registry while PM2 kept the old ports and the next config refresh reverted the change. Saving a changed port now rewrites the matching value in the app's `ecosystem.config.cjs` (the source of truth). Restart the app for the new port to take effect.
+- Editing a **shared or derived** port now persists too. When two port fields resolve to the same literal (e.g. the prod UI is served by the API, so `uiPort === apiPort`), the value-keyed rewrite couldn't tell them apart and the edit returned a 422. The PUT route now falls back to a **per-process-label-targeted** rewrite: it locates the specific process block in `ecosystem.config.cjs` and rewrites only the touched label's port (`api`/`ui`/`devUi`), leaving the sibling field — and any same-valued unrelated number — untouched. Edits to ports that live only under a process's `env`/`args` (no top-level field) persist as well. The 422 is now reserved for the genuinely unpersistable case (the literal isn't in the config — e.g. computed entirely at runtime).
diff --git a/server/routes/apps.js b/server/routes/apps.js
index 17eefb2bc8..ebefc5049f 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -15,7 +15,7 @@ import { validateRequest, appSchema, appUpdateSchema, sanitizeTaskMetadata, docu
import * as git from '../services/git.js';
import { parseCronToNextRun } from '../services/eventScheduler.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { parseEcosystemFromPath, usesPm2, writeEcosystemPorts } from '../services/streamingDetect.js';
+import { parseEcosystemFromPath, usesPm2, writeEcosystemPorts, writeEcosystemPortsByProcess } from '../services/streamingDetect.js';
import { checkViteHost, findViteConfig, rewriteAllowedHosts } from '../lib/viteAllowedHosts.js';
import { detectAppIcon, getIconContentType, isUsableSvg } from '../services/appIconDetect.js';
import { hasDeployScript } from '../services/appDeployer.js';
@@ -484,17 +484,20 @@ router.put('/:id', asyncHandler(async (req, res, next) => {
const { processes: cfgProcs } = await parseEcosystemFromPath(existing.repoPath);
const LABEL_BY_KEY = { apiPort: 'api', uiPort: 'ui', devUiPort: 'devUi' };
const currentPort = {};
+ const procNameByKey = {}; // which process block owns each label (for targeted rewrites)
for (const proc of cfgProcs || []) {
for (const [key, label] of Object.entries(LABEL_BY_KEY)) {
if (currentPort[key] === undefined && Number.isInteger(proc.ports?.[label])) {
currentPort[key] = proc.ports[label];
+ procNameByKey[key] = proc.name;
}
}
}
// Count current values so a value-keyed rewrite never fires on a number
// shared by another port field (e.g. uiPort derived from apiPort, both
// 6000) — that would rewrite every occurrence and clobber the field the
- // user didn't touch. Such a change is unpersistable by value alone.
+ // user didn't touch. Such a value can't be split by value alone; it falls
+ // through to the per-process-label-targeted rewrite below.
const valueCounts = new Map();
for (const key of PORT_KEYS) {
const v = currentPort[key];
@@ -506,13 +509,14 @@ router.put('/:id', asyncHandler(async (req, res, next) => {
const changedKeys = PORT_KEYS.filter(key =>
Number.isInteger(currentPort[key]) && Number.isInteger(data[key]) && data[key] !== currentPort[key]);
const remap = [];
- const unpersistable = [];
+ const targetedEdits = []; // shared-value keys: rewritten by process + label
for (const key of changedKeys) {
const oldPort = currentPort[key]; // guaranteed integer by the filter above
- // Value shared with another field (can't disambiguate by value) → can't
- // safely write it to the config without clobbering the other field.
- if (valueCounts.get(oldPort) > 1) {
- unpersistable.push(key);
+ // Value shared with another field (can't disambiguate by value): target
+ // the specific process block + label so the edit lands on exactly the
+ // port the user touched, not every occurrence of the shared literal.
+ if (valueCounts.get(oldPort) > 1 && procNameByKey[key]) {
+ targetedEdits.push({ processName: procNameByKey[key], label: LABEL_BY_KEY[key], oldPort, newPort: data[key] });
continue;
}
remap.push([oldPort, data[key]]);
@@ -523,13 +527,25 @@ router.put('/:id', asyncHandler(async (req, res, next) => {
console.log(`🔧 Updated ${result.file} ports for ${existing.name}: ${remap.map(([o, n]) => `${o}→${n}`).join(', ')} (restart the app to apply)`);
}
+ // Shared-value edits: rewrite the specific process block + label. Runs after
+ // the value-keyed pass so both touch the freshest on-disk content.
+ const targeted = targetedEdits.length > 0
+ ? await writeEcosystemPortsByProcess(existing.repoPath, targetedEdits)
+ : { changed: false, unapplied: [] };
+ if (targeted.changed) {
+ console.log(`🔧 Updated ${targeted.file} ports for ${existing.name}: ${targetedEdits.map(e => `${e.label} ${e.oldPort}→${e.newPort}`).join(', ')} (restart the app to apply)`);
+ }
+
// Honesty gate: if the user changed a port we could NOT write to the
// source-of-truth config, reject the whole update rather than persist a
// registry value PM2 will contradict (and the next refresh will revert).
- // `!result.changed` catches remap pairs whose literal wasn't found.
- if (changedKeys.length > 0 && (unpersistable.length > 0 || (remap.length > 0 && !result.changed))) {
+ // `!result.changed` catches value-keyed remap pairs whose literal wasn't
+ // found; `targeted.unapplied` catches process/label edits that didn't match.
+ const valueKeyedFailed = remap.length > 0 && !result.changed;
+ const targetedFailed = (targeted.unapplied || []).length > 0;
+ if (changedKeys.length > 0 && (valueKeyedFailed || targetedFailed)) {
throw new ServerError(
- `Could not persist port change to ${existing.name}'s ecosystem config — the port is shared with another field, derived from process config, or not a literal value. Edit the ecosystem.config.cjs directly to change this port.`,
+ `Could not persist port change to ${existing.name}'s ecosystem config — the port is derived from process config or is not a literal value. Edit the ecosystem.config.cjs directly to change this port.`,
{ status: 422, code: 'PORT_NOT_PERSISTABLE' }
);
}
diff --git a/server/routes/apps.test.js b/server/routes/apps.test.js
index aa3fc52bf4..c29ed1c426 100644
--- a/server/routes/apps.test.js
+++ b/server/routes/apps.test.js
@@ -36,6 +36,7 @@ vi.mock('../services/history.js', () => ({
vi.mock('../services/streamingDetect.js', () => ({
parseEcosystemFromPath: vi.fn(),
writeEcosystemPorts: vi.fn().mockResolvedValue({ file: 'ecosystem.config.cjs', changed: true }),
+ writeEcosystemPortsByProcess: vi.fn().mockResolvedValue({ file: 'ecosystem.config.cjs', changed: true, applied: [], unapplied: [] }),
usesPm2: vi.fn((type) => !new Set(['ios-native', 'macos-native', 'xcode', 'swift']).has(type)),
NON_PM2_TYPES: new Set(['ios-native', 'macos-native', 'xcode', 'swift'])
}));
@@ -289,18 +290,41 @@ describe('Apps Routes', () => {
expect(streamingDetect.writeEcosystemPorts).not.toHaveBeenCalled();
});
- it('rejects (422) a port change that cannot be written to the config, leaving the registry untouched', async () => {
- // uiPort derived from apiPort — both 6000. Changing only uiPort can't be
- // value-rewritten without clobbering apiPort, so the request must fail
- // rather than persist a registry value PM2 will contradict.
+ it('persists a shared-value port change via the per-process-targeted rewrite', async () => {
+ // uiPort and apiPort both 6000 in the same process block. A value-keyed
+ // rewrite can't split them, so the route targets the specific process +
+ // label (ui) instead — the edit now persists rather than 422.
const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000 };
appsService.getAppById.mockResolvedValue(mockApp);
- streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'a', ports: { api: 6000, ui: 6000 } }] });
+ streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'srv', ports: { api: 6000, ui: 6000 } }] });
+ appsService.updateApp.mockResolvedValue({ ...mockApp, uiPort: 7000 });
const response = await request(app).put('/api/apps/app-001').send({ uiPort: 7000 });
- expect(response.status).toBe(422);
+ expect(response.status).toBe(200);
+ // Value-keyed writer skipped (shared value); targeted writer used instead.
expect(streamingDetect.writeEcosystemPorts).not.toHaveBeenCalled();
+ expect(streamingDetect.writeEcosystemPortsByProcess).toHaveBeenCalledWith(
+ process.cwd(),
+ [{ processName: 'srv', label: 'ui', oldPort: 6000, newPort: 7000 }]
+ );
+ expect(appsService.updateApp).toHaveBeenCalled();
+ });
+
+ it('rejects (422) a shared-value port change the targeted rewrite cannot apply', async () => {
+ // Shared value, but the targeted rewrite finds no matching literal to
+ // change (e.g. derived from a const the block doesn't contain) → 422.
+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000 };
+ appsService.getAppById.mockResolvedValue(mockApp);
+ streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'srv', ports: { api: 6000, ui: 6000 } }] });
+ streamingDetect.writeEcosystemPortsByProcess.mockResolvedValueOnce({
+ file: 'ecosystem.config.cjs', changed: false, applied: [],
+ unapplied: [{ processName: 'srv', label: 'ui', oldPort: 6000, newPort: 7000 }]
+ });
+
+ const response = await request(app).put('/api/apps/app-001').send({ uiPort: 7000 });
+
+ expect(response.status).toBe(422);
expect(appsService.updateApp).not.toHaveBeenCalled();
});
diff --git a/server/services/streamingDetect.js b/server/services/streamingDetect.js
index 09432f2304..1d809e6012 100644
--- a/server/services/streamingDetect.js
+++ b/server/services/streamingDetect.js
@@ -514,6 +514,151 @@ function commentRanges(content) {
return ranges;
}
+/**
+ * Replace every match of `re` in `str` with `${prefix}${replacement}`, EXCEPT
+ * matches whose port number falls inside a comment. `re` must have its port
+ * number as the final capture run so we can locate where the digits begin: a
+ * value living only in a comment (`// PORT: 5173`) must NOT count as a rewrite,
+ * or the writer would report changed:true while the executable config is
+ * untouched, recreating the apps.json-vs-PM2 mismatch the write-back prevents.
+ */
+function replaceOutsideComments(str, re, replacement) {
+ const ranges = commentRanges(str);
+ return str.replace(re, (full, prefix, offset) => {
+ const numStart = offset + prefix.length;
+ return ranges.some(([s, e]) => numStart >= s && numStart < e) ? full : `${prefix}${replacement}`;
+ });
+}
+
+/**
+ * Find the `{ start, end }` brace-matched region of the app block whose
+ * `name:` equals `processName`. Mirrors the block-scan parseEcosystemConfig
+ * uses, so a per-process rewrite targets exactly the block the parser derived
+ * that process's ports from. Returns the first match (parser semantics) or null.
+ */
+function findAppBlock(content, processName) {
+ const re = /\{\s*name\s*:\s*['"]([^'"]+)['"]/g;
+ let m;
+ while ((m = re.exec(content)) !== null) {
+ if (m[1] !== processName) continue;
+ const end = findMatchingBrace(content, m.index);
+ if (end >= 0) return { start: m.index, end };
+ }
+ return null;
+}
+
+/**
+ * Within a single app block, rewrite the port literal that belongs to `label`
+ * (`api`/`ui`/`devUi`) from `oldP` → `newP`, leaving sibling labels alone.
+ *
+ * The key insight that makes per-label targeting safe inside one block: `PORT`
+ * maps to exactly ONE label per process (api OR ui, decided by process name) —
+ * the two never collide in the same block. So when two labels share a literal
+ * value, they either live in different blocks (block scoping splits them) or in
+ * an explicit `ports: { api: N, ui: N }` map (the label KEY splits them). The
+ * value-keyed rewriter can't disambiguate either; this one can.
+ *
+ * Sources rewritten per label mirror parseEcosystemConfig's derivation AND the
+ * PM2 runtime env (so the config the parser reads and the env PM2 launches with
+ * both move together):
+ * - api → `ports: { api: N }`, env `PORT`, `PORT: … || N` fallback, `port:`
+ * - ui → `ports: { ui|devUi: N }`, env `VITE_PORT`, `--port N`, and env
+ * `PORT` ONLY when the block has no `ports:` object (a UI-named
+ * process whose bare `PORT` IS the UI port).
+ *
+ * @returns {{ block: string, changed: boolean }}
+ */
+function rewriteLabelInBlock(block, label, oldP, newP) {
+ // Swap the matched digits to a sentinel first, then resolve the sentinel to
+ // the new value — so a label whose old/new values overlap another source in
+ // the same block can't chain. Each prefix capture group is preserved, so only
+ // the number changes (no whitespace artifact).
+ const ph = 'PORT_TGT_PLACEHOLDER';
+ const NUM = `${oldP}\\b`;
+ const hasPortsObj = /\bports\s*:\s*\{/.test(block);
+
+ let pats;
+ if (label === 'api') {
+ pats = [
+ `(\\bapi\\s*:\\s*)${NUM}`, // ports: { api: N }
+ `(['"\`]?\\bPORT\\b['"\`]?\\s*:\\s*[^,}\\n]*?\\|\\|\\s*['"]?)${NUM}`, // PORT: … || N (fallback)
+ `(['"\`]?\\bPORT\\b['"\`]?\\s*:\\s*)${NUM}`, // env PORT: N
+ `(\\bport\\s*:\\s*)${NUM}`, // port: N
+ ];
+ } else {
+ // ui / devUi share on-disk sources (devUi is a parse-time relabel of ui).
+ pats = [
+ `(\\b(?:ui|devUi)\\s*:\\s*)${NUM}`, // ports: { ui|devUi: N }
+ `(['"\`]?\\bVITE_PORT\\b['"\`]?\\s*:\\s*)${NUM}`, // env VITE_PORT: N
+ `(--port\\s+)${NUM}`, // args --port N
+ ];
+ // Bare PORT is the UI port only when there's no explicit ports object (a
+ // ports object means env is metadata-only and PORT belongs to the api).
+ if (!hasPortsObj) pats.push(`(['"\`]?\\bPORT\\b['"\`]?\\s*:\\s*)${NUM}`);
+ }
+
+ let out = block;
+ for (const p of pats) {
+ out = replaceOutsideComments(out, new RegExp(p, 'g'), ph);
+ }
+ const changed = out.includes(ph);
+ out = out.split(ph).join(String(newP));
+ return { block: out, changed };
+}
+
+/**
+ * Per-process-label-targeted port rewrite — the disambiguating counterpart to
+ * the value-keyed `rewriteEcosystemPorts`. Each edit names the process and the
+ * label (`api`/`ui`/`devUi`) to change, so a value shared by two labels (e.g.
+ * prod UI served by the API where `uiPort === apiPort`, or an explicit
+ * `ports: { api: N, ui: N }` map) is rewritten on exactly the one the user
+ * touched. Pure (no I/O) for unit-testability.
+ *
+ * @param {string} content
+ * @param {Array<{processName:string,label:string,oldPort:number,newPort:number}>} edits
+ * @returns {{ content: string, applied: Array, unapplied: Array }}
+ */
+export function rewriteEcosystemPortsByProcess(content, edits) {
+ const valid = (edits || []).filter(e =>
+ e && typeof e.processName === 'string' && typeof e.label === 'string' &&
+ Number.isInteger(e.oldPort) && Number.isInteger(e.newPort) &&
+ e.oldPort > 0 && e.newPort > 0 && e.oldPort !== e.newPort);
+ if (valid.length === 0) return { content, applied: [], unapplied: [] };
+
+ const applied = [];
+ const unapplied = [];
+
+ // Group edits by process so a block is sliced once even when several labels
+ // in it change (e.g. apiPort + uiPort that currently share a value).
+ const byProcess = new Map();
+ for (const e of valid) {
+ if (!byProcess.has(e.processName)) byProcess.set(e.processName, []);
+ byProcess.get(e.processName).push(e);
+ }
+
+ const blocks = [];
+ for (const [name, es] of byProcess) {
+ const range = findAppBlock(content, name);
+ if (!range) { es.forEach(e => unapplied.push(e)); continue; }
+ blocks.push({ range, edits: es });
+ }
+ // Rewrite back-to-front so each splice keeps earlier blocks' offsets valid.
+ blocks.sort((a, b) => b.range.start - a.range.start);
+
+ let out = content;
+ for (const blk of blocks) {
+ let inner = out.slice(blk.range.start, blk.range.end + 1);
+ for (const e of blk.edits) {
+ const r = rewriteLabelInBlock(inner, e.label, e.oldPort, e.newPort);
+ inner = r.block;
+ (r.changed ? applied : unapplied).push(e);
+ }
+ out = out.slice(0, blk.range.start) + inner + out.slice(blk.range.end + 1);
+ }
+
+ return { content: out, applied, unapplied };
+}
+
/**
* Rewrite port literals in an ecosystem.config content string per a remap of
* old → new port numbers. Pure (no I/O) so it's unit-testable.
@@ -550,18 +695,8 @@ export function rewriteEcosystemPorts(content, remap) {
// Port-ish env keys: PORT, FOO_PORT, VITE_PORT (and quoted variants), plus `port:`.
const KEY = `(?:[A-Za-z][A-Za-z0-9_]*_PORT|PORT|port)`;
- // Replace `re` everywhere EXCEPT inside comments — `re` must have its port
- // number as the last capture group so we know where the digits start. A port
- // value living only in a comment (`// PORT: 5173`) must NOT count as a rewrite,
- // or writeEcosystemPorts would report changed:true while the executable config
- // is untouched, recreating the apps.json-vs-PM2 mismatch this prevents.
- const replaceOutsideComments = (str, re, phI) => {
- const ranges = commentRanges(str);
- return str.replace(re, (full, prefix, offset) => {
- const numStart = offset + prefix.length;
- return ranges.some(([s, e]) => numStart >= s && numStart < e) ? full : `${prefix}${phI}`;
- });
- };
+ // replaceOutsideComments (module scope) skips matches whose port number sits
+ // inside a comment, so a commented `// PORT: 5173` never counts as a rewrite.
let out = content;
@@ -637,6 +772,32 @@ export async function writeEcosystemPorts(repoPath, remap) {
return { file: null, changed: false };
}
+/**
+ * Persist a per-process-label-targeted port remap to an app's on-disk ecosystem
+ * config (`.cjs` preferred, then `.js`). The disambiguating counterpart to
+ * writeEcosystemPorts: use this when a port value is shared by two labels (e.g.
+ * `ports: { api: N, ui: N }`) and only one was edited. Returns
+ * `{ file, changed, applied, unapplied }`; `unapplied` lists edits whose process
+ * block or label literal wasn't found (caller decides whether that's a failure).
+ *
+ * @param {string} repoPath
+ * @param {Array<{processName:string,label:string,oldPort:number,newPort:number}>} edits
+ */
+export async function writeEcosystemPortsByProcess(repoPath, edits) {
+ for (const name of ECOSYSTEM_CONFIG_FILENAMES) {
+ const filePath = join(repoPath, name);
+ if (!existsSync(filePath)) continue;
+ const content = await readFile(filePath, 'utf-8');
+ const { content: updated, applied, unapplied } = rewriteEcosystemPortsByProcess(content, edits);
+ if (updated !== content) {
+ await atomicWrite(filePath, updated);
+ return { file: name, changed: true, applied, unapplied };
+ }
+ return { file: name, changed: false, applied, unapplied };
+ }
+ return { file: null, changed: false, applied: [], unapplied: edits || [] };
+}
+
/**
* Stream detection results to a socket as each step completes
*/
diff --git a/server/services/streamingDetect.test.js b/server/services/streamingDetect.test.js
index e54996aa4d..4f4751c13a 100644
--- a/server/services/streamingDetect.test.js
+++ b/server/services/streamingDetect.test.js
@@ -2,7 +2,7 @@ import { describe, it, expect, afterEach } from 'vitest';
import { mkdtempSync, writeFileSync, readFileSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
-import { parseEcosystemConfig, rewriteEcosystemPorts, writeEcosystemPorts } from './streamingDetect.js';
+import { parseEcosystemConfig, rewriteEcosystemPorts, rewriteEcosystemPortsByProcess, writeEcosystemPorts } from './streamingDetect.js';
describe('parseEcosystemConfig', () => {
it('captures arbitrary *_PORT env vars and labels them by camelCased stem', () => {
@@ -411,6 +411,141 @@ module.exports = { apps: [{ name: 'x', script: 's.js', env: { PORT: PORTS.API }
});
});
+describe('rewriteEcosystemPortsByProcess', () => {
+ it('splits a shared value (prod UI served by API, uiPort === apiPort) — rewrites only the touched label', () => {
+ // Single process: bare PORT 6000 is BOTH the api port and (since no
+ // dedicated ui process) the derived ui port. Changing only ui must NOT
+ // touch the api — but here there's only one PORT literal and it IS the api,
+ // so a ui edit on a process that has no ui-specific literal is unapplied.
+ const content = `module.exports = { apps: [
+ { name: 'srv', script: 's.js', env: { PORT: 6000 } }
+] };
+`;
+ // Change the api port — the shared literal moves with it.
+ const r = rewriteEcosystemPortsByProcess(content, [
+ { processName: 'srv', label: 'api', oldPort: 6000, newPort: 7000 },
+ ]);
+ expect(r.applied).toHaveLength(1);
+ expect(r.unapplied).toHaveLength(0);
+ expect(parseEcosystemConfig(r.content).processes[0].ports.api).toBe(7000);
+ });
+
+ it('disambiguates an explicit ports: { api: N, ui: N } map sharing one value', () => {
+ // Both api and ui are literally 6000 in the same block. A value-keyed
+ // rewrite can't split them; the label KEY can.
+ const content = `module.exports = { apps: [
+ { name: 'srv', script: 's.js', ports: { api: 6000, ui: 6000 }, env: { PORT: 6000 } }
+] };
+`;
+ const r = rewriteEcosystemPortsByProcess(content, [
+ { processName: 'srv', label: 'ui', oldPort: 6000, newPort: 7000 },
+ ]);
+ expect(r.applied).toHaveLength(1);
+ expect(r.unapplied).toHaveLength(0);
+ const ports = parseEcosystemConfig(r.content).processes[0].ports;
+ expect(ports.ui).toBe(7000);
+ expect(ports.api).toBe(6000); // untouched — the api literal stays
+ });
+
+ it('rewrites a port that lives only under processes[] (no top-level field)', () => {
+ const content = `module.exports = { apps: [
+ { name: 'srv-api', script: 's.js', env: { PORT: 5555 } },
+ { name: 'srv-ui', script: 'npx', args: 'vite --host --port 5556', env: { VITE_PORT: 5556 } }
+] };
+`;
+ const r = rewriteEcosystemPortsByProcess(content, [
+ { processName: 'srv-ui', label: 'ui', oldPort: 5556, newPort: 7001 },
+ ]);
+ expect(r.applied).toHaveLength(1);
+ expect(r.content).toContain('--port 7001');
+ expect(r.content).toContain('VITE_PORT: 7001');
+ expect(r.content).toContain('PORT: 5555'); // sibling api block untouched
+ });
+
+ it('targets only the named process when two blocks share a port value', () => {
+ const content = `module.exports = { apps: [
+ { name: 'a', script: 's.js', env: { PORT: 6000 } },
+ { name: 'b', script: 's.js', env: { PORT: 6000 } }
+] };
+`;
+ const r = rewriteEcosystemPortsByProcess(content, [
+ { processName: 'b', label: 'api', oldPort: 6000, newPort: 7000 },
+ ]);
+ expect(r.applied).toHaveLength(1);
+ const procs = parseEcosystemConfig(r.content).processes;
+ expect(procs.find(p => p.name === 'a').ports.api).toBe(6000); // untouched
+ expect(procs.find(p => p.name === 'b').ports.api).toBe(7000);
+ });
+
+ it('applies multiple labels in the same block (api + ui that shared a value)', () => {
+ const content = `module.exports = { apps: [
+ { name: 'srv', script: 's.js', ports: { api: 6000, ui: 6000 } }
+] };
+`;
+ const r = rewriteEcosystemPortsByProcess(content, [
+ { processName: 'srv', label: 'api', oldPort: 6000, newPort: 7000 },
+ { processName: 'srv', label: 'ui', oldPort: 6000, newPort: 7001 },
+ ]);
+ expect(r.applied).toHaveLength(2);
+ const ports = parseEcosystemConfig(r.content).processes[0].ports;
+ expect(ports.api).toBe(7000);
+ expect(ports.ui).toBe(7001);
+ });
+
+ it('rewrites the devUi (Vite) port via the ui label', () => {
+ // With a sibling api process, the parser relabels the Vite port ui → devUi.
+ const content = `module.exports = { apps: [
+ { name: 'srv', script: 's.js', env: { PORT: 5555 } },
+ { name: 'srv-ui', script: 'npx', args: 'vite', env: { VITE_PORT: 5556 } }
+] };
+`;
+ const r = rewriteEcosystemPortsByProcess(content, [
+ { processName: 'srv-ui', label: 'ui', oldPort: 5556, newPort: 7002 },
+ ]);
+ expect(r.applied).toHaveLength(1);
+ expect(parseEcosystemConfig(r.content).processes.find(p => p.name === 'srv-ui').ports.devUi).toBe(7002);
+ });
+
+ it('reports an edit as unapplied when the process name is not found', () => {
+ const content = `module.exports = { apps: [{ name: 'srv', script: 's.js', env: { PORT: 6000 } }] };`;
+ const r = rewriteEcosystemPortsByProcess(content, [
+ { processName: 'ghost', label: 'api', oldPort: 6000, newPort: 7000 },
+ ]);
+ expect(r.applied).toHaveLength(0);
+ expect(r.unapplied).toHaveLength(1);
+ expect(r.content).toBe(content);
+ });
+
+ it('reports an edit as unapplied when the label has no literal in the block', () => {
+ // api-only process; a ui edit finds nothing to rewrite there.
+ const content = `module.exports = { apps: [{ name: 'srv', script: 's.js', ports: { api: 6000 } }] };`;
+ const r = rewriteEcosystemPortsByProcess(content, [
+ { processName: 'srv', label: 'ui', oldPort: 9999, newPort: 7000 },
+ ]);
+ expect(r.applied).toHaveLength(0);
+ expect(r.unapplied).toHaveLength(1);
+ expect(r.content).toBe(content);
+ });
+
+ it('does not rewrite a port that appears only in a comment', () => {
+ const content = `module.exports = { apps: [{ name: 'srv', script: 's.js', env: { /* old PORT: 5173 */ PORT: 4000 } }] };`;
+ const r = rewriteEcosystemPortsByProcess(content, [
+ { processName: 'srv', label: 'api', oldPort: 5173, newPort: 7000 },
+ ]);
+ expect(r.applied).toHaveLength(0);
+ expect(r.unapplied).toHaveLength(1);
+ expect(r.content).toBe(content);
+ });
+
+ it('is a no-op for empty / identity edits', () => {
+ const content = `module.exports = { apps: [{ name: 'srv', script: 's.js', env: { PORT: 6000 } }] };`;
+ expect(rewriteEcosystemPortsByProcess(content, []).content).toBe(content);
+ expect(rewriteEcosystemPortsByProcess(content, [
+ { processName: 'srv', label: 'api', oldPort: 6000, newPort: 6000 },
+ ]).content).toBe(content);
+ });
+});
+
describe('writeEcosystemPorts', () => {
let dir;
afterEach(() => { if (dir) rmSync(dir, { recursive: true, force: true }); dir = null; });