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
make PM2 standardization opt-in instead of firing on every app import
[._.]/ Adam Eivy767a4f8ded16
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 98c870c090..e60d72b2df 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -26,6 +26,9 @@## Changed+- Adding an app no longer writes a PM2 config into the project on its own. Importing a directory ran the PM2 standardizer the instant detection finished — dropping an `ecosystem.config.cjs` into the repo, commenting the ports out of its `.env` and Vite config, and cutting a git backup branch — before you had even saved the app. Only iOS/macOS/Swift/Xcode projects were exempt, so Docker stacks, Python services, static sites, and anything else you start another way all got a PM2 config they will never use, plus an LLM call nobody asked for. Standardizing is now a button in the Add App wizard that says what it will rewrite, and it is still available later from the Apps list. The wizard also shows the standardizer's live per-step detail while it runs (including the "no git repository, backup skipped" case) instead of one undifferentiated row.+- Standardizing an app is now refused server-side for apps PortOS never runs under PM2, and for PortOS itself. The rule previously lived only in which buttons happened to render, so the socket and HTTP entry points would happily standardize an iOS app — or rewrite PortOS's own `ecosystem.config.cjs`, the canonical source of its port map, from an LLM analysis. The Standardize button on an app's Overview tab is now hidden for PortOS too, matching the Archive button beside it.+- The fork-aware self-update flow is now documented on its own page (`docs/SELF_UPDATE.md`) and indexed in the docs README. It explains why release polling always queries upstream while the update itself pulls from your own origin, what the `FORK_SYNC_REQUIRED` and `FORK_DIVERGED` responses mean, and what each of the three fork-specific update buttons does — previously this only existed as a terse note in the repo's agent instructions.- The README now matches what PortOS actually is. Its feature list had drifted behind roughly a year of surfaces — Sprites, Game asset binding, the 3D image-to-mesh page, Authors, Story Builder, LoRA training, the Pipeline's editorial/continuity/voice-fingerprint checks, the Privacy Center (vault, organizations, change-of-address, data brokers), the activity timeline, SongBook, iMessage/Signal/X, Workspaces, Flows, the local-LLM playground, and the public API surface were all missing. Several stated facts were also wrong: React 18 (it's 19), 117 curated genome markers (116), six agent skill templates (seven), five POST domains (six — the whole Cognitive domain was unlisted), a provider roster missing Grok Build, Cursor Agent and OpenCode, and a contributing note claiming PortOS has "no auth" when an optional instance password has shipped for some time.- The setup scripts now require Node 22 instead of 18. Vite 8 needs ^20.19 || >=22.12, so a v18 machine passed the version gate and then failed several minutes later at the client build with a much less obvious error. The README's stated requirement was updated to match.diff --git a/PLAN.md b/PLAN.mdindex 50cb8906fa..7c2daf7fd3 100644--- a/PLAN.md+++ b/PLAN.md@@ -353,3 +353,7 @@ is not reliably announced.### Give the foundation gate's structure repair the same rollback ownership as the arc gate- [ ] `restoreArcState` now takes an exact mutation manifest (`{ episodeEdits }`) so a rollback restores only the episode synopses the resolver reported writing, instead of every episode that differs from the pre-resolve snapshot. The arc gate passes one (`server/services/pipeline/seriesAutopilot/childRuns.js`, via `createArcMutationLedger`); the foundation gate's structure repair does not, so its three rollbacks (`server/services/pipeline/foundationJudge.js` ~lines 1914, 1928, 1947) still revert any episode idea-stage difference — including a write that landed from elsewhere during the repair. Its exposure window is *longer* than the arc gate's: one resolve plus up to `MAX_STRUCTURE_CORRECTION_PASSES` correct/verify pairs. **The call to make:** it already holds each `resolveVerifyIssues` result (`trackedResolve`), so accumulate `resolvedEpisodeEdits()` across the repair's resolves on the same shared ledger and pass `ledger.since(snapshot)` at those three sites. Do NOT touch `restoreFoundationState`'s own `restoreArcState` call (~line 1709) — it verifies restore fidelity by diffing episodes wholesale via `mismatchedFoundationFields`, so the manifest-free contract is correct there, and that split is what the doc comment on `restoreArcState` records. Deferred from the arc-gate fix to keep that change to the gate whose defect was observed; needs its own regression coverage in `foundationJudge.rollback.test.js`. Surfaced by the /simplify altitude and reuse reviews.++### Classify non-Node app types so the standardize offer knows what it is looking at++- [ ] `streamingDetect.js` emits `vite+express` / `vite` / `single-node-server` / `nextjs`, the four Apple types, or `unknown` (the initialized default, ~line 1096) — there is no `python`, `go`, `docker`, or `static`. `usesPm2()` is the negation of `NON_PM2_TYPES` (the four Apple types), so *everything unrecognized is treated as a PM2 app*: a Python service, Docker stack, Go binary, or static site all come back `unknown` and are still offered PM2 standardization in the Add App wizard. That matters because the standardizer's prompt opens with "You are analyzing a **Node.js** application" (`server/services/pm2Standardizer.js`) — on a Python repo it doesn't fail, it confidently writes a Node ecosystem config. The auto-fire is gone (standardizing is now an explicit button whose copy says "skip it for Docker stacks, static sites, or anything you start another way"), so this is no longer a data-loss path, but the prose is doing a type check's job. **The call to make:** don't widen `NON_PM2_TYPES` — its three other consumers (`appDeployer.js`'s `deploy.sh`, `SlashDoPanel.jsx`'s `isSwiftApp`, `apps.js`'s `xed .` editor launch) mean "Apple", not "not PM2". Teach `streamingDetect` to classify `python` / `go` / `docker` / `static` from marker files (`pyproject.toml`/`requirements.txt`, `go.mod`, `docker-compose.yml` with no package.json, `index.html` with no server) so `unknown` stops being the catch-all, then add a positive `isStandardizable(type)` predicate over the Node types and gate both the wizard card and `standardizeRefusalFor()` on it. Note `type` is persisted on the app record, so an existing `unknown` app keeps that type until re-detected — the predicate must stay permissive for `unknown` or offer a re-detect. Surfaced by the /simplify altitude review on the opt-in-standardization change.diff --git a/client/src/components/apps/tabs/OverviewTab.jsx b/client/src/components/apps/tabs/OverviewTab.jsxindex c485fa320b..54475f5b7f 100644--- a/client/src/components/apps/tabs/OverviewTab.jsx+++ b/client/src/components/apps/tabs/OverviewTab.jsx@@ -312,7 +312,9 @@ export default function OverviewTab({ app, onRefresh }) {<Image size={14} />{detectingIcon ? 'Scanning...' : 'Detect Icon'}</button>- {!NON_PM2_TYPES.has(app.type) && (+ {/* PortOS's own ecosystem.config.cjs is the canonical PORTS source —+ it is never regenerated from an LLM analysis (the server refuses too). */}+ {!NON_PM2_TYPES.has(app.type) && app.id !== api.PORTOS_APP_ID && (<buttononClick={handleStandardize}disabled={isOperating}diff --git a/client/src/pages/CreateApp.jsx b/client/src/pages/CreateApp.jsxindex 6e6ff86bb9..6aa2200310 100644--- a/client/src/pages/CreateApp.jsx+++ b/client/src/pages/CreateApp.jsx@@ -16,8 +16,7 @@ const DETECTION_STEPS_PM2 = [{ id: 'config', label: 'Checking configs' },{ id: 'pm2', label: 'Checking PM2' },{ id: 'readme', label: 'Reading README' },- { id: 'icon', label: 'Detecting app icon' },- { id: 'standardize', label: 'Standardizing PM2 config' }+ { id: 'icon', label: 'Detecting app icon' }];const DETECTION_STEPS_NON_PM2 = [@@ -29,6 +28,40 @@ const DETECTION_STEPS_NON_PM2 = [{ id: 'icon', label: 'Detecting app icon' }];+// The steps `runStandardizeFlow` emits. Standardization is its own flow, not a+// detection step — see handleStandardize for why it stays out of that sequence.+const STANDARDIZE_STEPS = [+ { id: 'analyze', label: 'Analyzing configuration' },+ { id: 'backup', label: 'Creating git backup' },+ { id: 'apply', label: 'Writing ecosystem.config.cjs' }+];++const stepIconFor = (step) => {+ if (!step) return <Circle size={16} className="text-gray-600" />;+ if (step.status === 'running') return <Loader size={16} className="text-port-accent animate-spin" />;+ if (step.status === 'done') return <CheckCircle size={16} className="text-port-success" />;+ if (step.status === 'error') return <AlertCircle size={16} className="text-port-error" />;+ if (step.status === 'skipped') return <Circle size={16} className="text-gray-500" />;+ return <Circle size={16} className="text-gray-600" />;+};++/** Progress rows for a step sequence — shared by detection and standardization. */+const StepRows = ({ defs, state }) => defs.map(({ id, label }) => {+ const step = state[id];+ return (+ <div key={id} className="flex items-center gap-2 text-sm">+ {stepIconFor(step)}+ <span className={step?.status === 'running' ? 'text-port-accent' :+ step?.status === 'done' ? 'text-white' : 'text-gray-500'}>+ {label}+ </span>+ {step?.data?.message && (+ <span className="text-gray-500 text-xs ml-2 truncate">{step.data.message}</span>+ )}+ </div>+ );+});+export default function CreateApp() {const navigate = useNavigate();const socketRef = useRef(null);@@ -64,7 +97,9 @@ export default function CreateApp() {// Standardization stateconst [standardizing, setStandardizing] = useState(false);+ const [standardizeSteps, setStandardizeSteps] = useState({});const [standardizeResult, setStandardizeResult] = useState(null);+ const [standardizeError, setStandardizeError] = useState(null);const [activeProvider, setActiveProvider] = useState(null);// Fetch active provider and default directory on mount@@ -128,10 +163,7 @@ export default function CreateApp() {// Standardization socket eventssocketRef.current.on('standardize:step', ({ step, status, data }) => {- // Map standardize steps to our step display- const stepMap = { analyze: 'standardize', backup: 'standardize', apply: 'standardize' };- const displayStep = stepMap[step] || 'standardize';- setSteps(prev => ({ ...prev, [displayStep]: { status: status === 'done' ? 'running' : status, data } }));+ setStandardizeSteps(prev => ({ ...prev, [step]: { status, data } }));setDetectionLog(prev => [...prev, { step: `standardize:${step}`, status, ...data }]);});@@ -139,10 +171,9 @@ export default function CreateApp() {setStandardizing(false);if (success && result) {setStandardizeResult(result);- setSteps(prev => ({ ...prev, standardize: { status: 'done', data: { message: 'PM2 config standardized' } } }));toast.success(`PM2 config standardized${result.backupBranch ? ` (backup: ${result.backupBranch})` : ''}`);} else {- setSteps(prev => ({ ...prev, standardize: { status: 'error', data: { message: err || 'Standardization failed' } } }));+ setStandardizeError(err || 'Standardization failed');if (err) toast.error(`Standardization failed: ${err}`);}});@@ -154,14 +185,23 @@ export default function CreateApp() {const isNonPm2 = NON_PM2_TYPES.has(appType);- // Auto-trigger standardization after detection completes (skip for non-PM2 apps)- useEffect(() => {- if (detected && activeProvider && repoPath && !standardizing && !standardizeResult && !isNonPm2) {- setStandardizing(true);- setSteps(prev => ({ ...prev, standardize: { status: 'running', data: { message: 'Analyzing configuration...' } } }));- socketRef.current?.emit('standardize:start', { repoPath, providerId: activeProvider.id });- }- }, [detected, activeProvider, repoPath, standardizing, standardizeResult, isNonPm2]);+ const clearStandardize = () => {+ setStandardizing(false);+ setStandardizeSteps({});+ setStandardizeResult(null);+ setStandardizeError(null);+ };++ // Standardization is opt-in: the user asks for it here. It used to fire on its+ // own the moment detection finished, which wrote an `ecosystem.config.cjs` into+ // any imported directory — including apps PortOS won't run under PM2 at all —+ // before the app record was even saved.+ const handleStandardize = () => {+ if (!activeProvider) return;+ clearStandardize();+ setStandardizing(true);+ socketRef.current?.emit('standardize:start', { repoPath, providerId: activeProvider.id });+ };// Start streaming detectionconst handleImport = () => {@@ -173,8 +213,7 @@ export default function CreateApp() {setDetectionLog([]);setDetected(false);setPm2Status(null);- setStandardizing(false);- setStandardizeResult(null);+ clearStandardize();socketRef.current.emit('detect:start', { path: repoPath });};@@ -231,18 +270,7 @@ export default function CreateApp() {setIcon('package');setAppIconPath(null);setError(null);- setStandardizing(false);- setStandardizeResult(null);- };-- const getStepIcon = (stepId) => {- const step = steps[stepId];- if (!step) return <Circle size={16} className="text-gray-600" />;- if (step.status === 'running') return <Loader size={16} className="text-port-accent animate-spin" />;- if (step.status === 'done') return <CheckCircle size={16} className="text-port-success" />;- if (step.status === 'error') return <AlertCircle size={16} className="text-port-error" />;- if (step.status === 'skipped') return <Circle size={16} className="text-gray-500" />;- return <Circle size={16} className="text-gray-600" />;+ clearStandardize();};// The status rail only has something to show once detection has started or@@ -447,20 +475,7 @@ export default function CreateApp() {{detecting && (<div className="bg-port-card border border-port-border rounded-xl p-4 space-y-2"><h3 className="text-xs font-medium uppercase tracking-wide text-gray-500">Detecting</h3>- {(isNonPm2 ? DETECTION_STEPS_NON_PM2 : DETECTION_STEPS_PM2).map(({ id, label }) => (- <div key={id} className="flex items-center gap-2 text-sm">- {getStepIcon(id)}- <span className={steps[id]?.status === 'running' ? 'text-port-accent' :- steps[id]?.status === 'done' ? 'text-white' : 'text-gray-500'}>- {label}- </span>- {steps[id]?.data?.message && (- <span className="text-gray-500 text-xs ml-2 truncate">- {steps[id].data.message}- </span>- )}- </div>- ))}+ <StepRows defs={isNonPm2 ? DETECTION_STEPS_NON_PM2 : DETECTION_STEPS_PM2} state={steps} /></div>)}@@ -488,6 +503,44 @@ export default function CreateApp() {</Banner>)}+ {/* Standardize PM2 config — opt-in, because it rewrites the repo */}+ {detected && !isNonPm2 && !standardizeResult && (+ <div className="bg-port-card border border-port-border rounded-xl p-4 space-y-3">+ <h3 className="text-xs font-medium uppercase tracking-wide text-gray-500">Optional</h3>+ <p className="text-sm text-white flex items-center gap-2">+ <Wrench size={14} aria-hidden="true" /> Standardize PM2 config+ </p>+ <p className="text-xs text-gray-500">+ Writes an <code className="bg-port-bg px-1 rounded">ecosystem.config.cjs</code> into this+ project and moves its ports there (a git backup branch is created first). Only do this for+ apps you want PortOS to run under PM2 — skip it for Docker stacks, static sites, or anything+ you start another way. You can run it later from the Apps list.+ </p>+ {standardizing ? (+ <div className="space-y-2">+ <StepRows defs={STANDARDIZE_STEPS} state={standardizeSteps} />+ </div>+ ) : (+ <button+ type="button"+ onClick={handleStandardize}+ disabled={!activeProvider}+ className="w-full px-4 py-2 bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors disabled:opacity-50 text-sm"+ >+ Standardize PM2 config+ </button>+ )}+ {!activeProvider && (+ <Banner tone="warning" icon={AlertCircle}>+ Needs an LLM provider — none is configured.+ </Banner>+ )}+ {standardizeError && (+ <Banner tone="error" icon={AlertCircle}>{standardizeError}</Banner>+ )}+ </div>+ )}+{/* Standardization Result */}{standardizeResult && (<Banner tone="success" size="md">@@ -507,15 +560,6 @@ export default function CreateApp() {</Banner>)}- {/* No Provider Warning */}- {detected && !activeProvider && !standardizing && !standardizeResult && !isNonPm2 && (- <div className="p-3 bg-port-border/50 border border-port-border rounded-lg">- <p className="text-xs text-gray-400">- <span className="text-port-warning">⚠</span> No LLM provider configured. PM2 standardization skipped.- </p>- </div>- )}-{/* Detection Log */}{detectionLog.length > 0 && (<div>diff --git a/client/src/pages/CreateApp.test.jsx b/client/src/pages/CreateApp.test.jsxnew file mode 100644index 0000000000..26171c6143--- /dev/null+++ b/client/src/pages/CreateApp.test.jsx@@ -0,0 +1,84 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { act, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { MemoryRouter } from 'react-router';++// One fake socket shared by the test and the component: `on` records the+// component's handlers so a test can drive `detect:*` / `standardize:*` frames.+const handlers = {};+const emit = vi.fn();+const fakeSocket = {+ on: vi.fn((event, fn) => { handlers[event] = fn; }),+ emit,+ disconnect: vi.fn(),+};++vi.mock('socket.io-client', () => ({ io: vi.fn(() => fakeSocket) }));++vi.mock('../services/api', () => ({+ getActiveProvider: vi.fn(() => Promise.resolve({ id: 'provider-1', name: 'Example Provider' })),+ getDirectories: vi.fn(() => Promise.resolve({ currentPath: '/srv/example-app', directories: [] })),+ createApp: vi.fn(() => Promise.resolve({ id: 'app-1' })),+}));++vi.mock('../components/ui/Toast', () => ({+ default: { success: vi.fn(), error: vi.fn(), loading: vi.fn(), dismiss: vi.fn(), custom: vi.fn() }+}));++import CreateApp from './CreateApp';++/** Render the wizard and drive detection to completion for the given app type. */+const detectApp = async (result = { type: 'node', name: 'Example App' }) => {+ render(<MemoryRouter><CreateApp /></MemoryRouter>);+ // Let the mount effects (provider + default directory) settle.+ await act(async () => {});+ await act(async () => {+ handlers['detect:complete']({ success: true, result });+ });+};++const standardizeEmits = () => emit.mock.calls.filter(([event]) => event === 'standardize:start');++describe('CreateApp — PM2 standardization is opt-in', () => {+ beforeEach(() => {+ emit.mockClear();+ for (const key of Object.keys(handlers)) delete handlers[key];+ });++ it('does not write an ecosystem config on its own when detection completes', async () => {+ await detectApp();++ // The wizard used to fire this automatically, dropping an+ // ecosystem.config.cjs into any imported repo — PM2-managed or not.+ expect(standardizeEmits()).toHaveLength(0);+ expect(screen.getByRole('button', { name: 'Standardize PM2 config' })).toBeEnabled();+ });++ it('standardizes only once the user asks for it', async () => {+ const user = userEvent.setup();+ await detectApp();++ await user.click(screen.getByRole('button', { name: 'Standardize PM2 config' }));++ expect(standardizeEmits()).toEqual([+ ['standardize:start', { repoPath: '/srv/example-app', providerId: 'provider-1' }]+ ]);+ });++ it('offers no standardization for app types PortOS never runs under PM2', async () => {+ await detectApp({ type: 'ios-native', name: 'Example iOS App' });++ expect(screen.queryByRole('button', { name: 'Standardize PM2 config' })).toBeNull();+ expect(standardizeEmits()).toHaveLength(0);+ });++ it('disables the action when no LLM provider is configured', async () => {+ const api = await import('../services/api');+ api.getActiveProvider.mockResolvedValueOnce(null);++ await detectApp();++ expect(screen.getByRole('button', { name: 'Standardize PM2 config' })).toBeDisabled();+ expect(screen.getByText(/Needs an LLM provider/)).toBeInTheDocument();+ });+});diff --git a/server/routes/standardize.js b/server/routes/standardize.jsindex 76d4955a54..c333db6875 100644--- a/server/routes/standardize.js+++ b/server/routes/standardize.js@@ -5,23 +5,36 @@ import * as appsService from '../services/apps.js';const router = Router();-// POST /api/standardize/analyze - Analyze app and generate standardization plan-router.post('/analyze', asyncHandler(async (req, res) => {- const { repoPath, appId, providerId } = req.body;-- // Get path from appId if provided- let path = repoPath;- if (!path && appId) {+/**+ * Resolve the repo to standardize from `repoPath` or `appId`.+ *+ * An `appId` also gets the precondition check: standardization rewrites the+ * target repo, so an app PortOS never runs under PM2 (and PortOS itself) is+ * refused here rather than relying on the button being hidden in the UI.+ */+async function resolveStandardizeTarget({ repoPath, appId }) {+ if (repoPath) return repoPath;++ if (appId) {const app = await appsService.getAppById(appId);if (!app) {throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });}- path = app.repoPath;+ const refusal = pm2Standardizer.standardizeRefusalFor(app);+ if (refusal) {+ throw new ServerError(refusal, { status: 400, code: 'NOT_STANDARDIZABLE' });+ }+ return app.repoPath;}- if (!path) {- throw new ServerError('Either repoPath or appId is required', { status: 400, code: 'MISSING_PATH' });- }+ throw new ServerError('Either repoPath or appId is required', { status: 400, code: 'MISSING_PATH' });+}++// POST /api/standardize/analyze - Analyze app and generate standardization plan+router.post('/analyze', asyncHandler(async (req, res) => {+ const { repoPath, appId, providerId } = req.body;++ const path = await resolveStandardizeTarget({ repoPath, appId });console.log(`🔧 Analyzing PM2 standardization for: ${path}`);@@ -40,19 +53,7 @@ router.post('/analyze', asyncHandler(async (req, res) => {router.post('/apply', asyncHandler(async (req, res) => {const { repoPath, appId, plan, overwriteEcosystem = false } = req.body;- // Get path from appId if provided- let path = repoPath;- if (!path && appId) {- const app = await appsService.getAppById(appId);- if (!app) {- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });- }- path = app.repoPath;- }-- if (!path) {- throw new ServerError('Either repoPath or appId is required', { status: 400, code: 'MISSING_PATH' });- }+ const path = await resolveStandardizeTarget({ repoPath, appId });if (!plan) {throw new ServerError('Standardization plan is required', { status: 400, code: 'MISSING_PLAN' });@@ -87,18 +88,7 @@ router.get('/template', asyncHandler(async (req, res) => {router.post('/backup', asyncHandler(async (req, res) => {const { repoPath, appId } = req.body;- let path = repoPath;- if (!path && appId) {- const app = await appsService.getAppById(appId);- if (!app) {- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });- }- path = app.repoPath;- }-- if (!path) {- throw new ServerError('Either repoPath or appId is required', { status: 400, code: 'MISSING_PATH' });- }+ const path = await resolveStandardizeTarget({ repoPath, appId });const result = await pm2Standardizer.createGitBackup(path);diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.jsindex cebf627aee..76c0f062dd 100644--- a/server/services/pm2Standardizer.js+++ b/server/services/pm2Standardizer.js@@ -8,6 +8,8 @@ import { spawn } from 'child_process';import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';import { runPromptThroughProvider } from '../lib/promptRunner.js';import { getReservedPorts, getAllApps } from './apps.js';+import { PORTOS_APP_ID } from '../lib/appIdentity.js';+import { usesPm2 } from './streamingDetect.js';import { getListeningPorts } from '../lib/platform.js';const execAsync = promisify(exec);@@ -29,6 +31,30 @@ const VITE_DEFAULT_PORTS = [5173, 5174];// 5553–5561 block and the Vite defaults.const REASSIGN_FROM = 6000;+/**+ * Why an app must not be standardized, or `null` when it may be.+ *+ * Standardizing rewrites files in the target repo — it writes an+ * `ecosystem.config.cjs` and comments the ports out of `.env`/vite config — so+ * the "is this even a PM2 app?" question has to be answered before the flow+ * starts, not by whichever button happened to be rendered. Every entry point+ * that resolves an app record (the `app:standardize` socket handler and the+ * `/api/standardize/*` routes) runs this check; the Add App wizard has only a+ * repoPath, so it gates in the UI instead.+ *+ * @param {object} app The app record.+ * @returns {string|null} Refusal reason, or null if standardization is allowed.+ */+export function standardizeRefusalFor(app) {+ if (app?.id === PORTOS_APP_ID) {+ return 'PortOS manages its own ecosystem.config.cjs — that file is the canonical PORTS source and is not regenerated from an LLM analysis';+ }+ if (!usesPm2(app?.type)) {+ return `${app?.type} apps are not run under PM2, so there is no ecosystem config to standardize`;+ }+ return null;+}+const isPortKey = (key) => /(^|_)PORT$/i.test(key);/**diff --git a/server/services/pm2Standardizer.test.js b/server/services/pm2Standardizer.test.jsindex d8a2972864..9d1876ad22 100644--- a/server/services/pm2Standardizer.test.js+++ b/server/services/pm2Standardizer.test.js@@ -6,8 +6,29 @@ import {reassignCollidingPorts,runStandardizeFlow,applyStandardization,+ standardizeRefusalFor,PORTOS_ECOSYSTEM_MARKER} from './pm2Standardizer.js';+import { PORTOS_APP_ID } from '../lib/appIdentity.js';++describe('standardizeRefusalFor', () => {+ it('allows a PM2-managed app', () => {+ expect(standardizeRefusalFor({ id: 'app-1', type: 'vite+express' })).toBeNull();+ });++ it('refuses app types PortOS never runs under PM2', () => {+ // Standardizing writes an ecosystem.config.cjs into the repo, so the check+ // belongs here rather than only in whichever button happened to render.+ for (const type of ['ios-native', 'macos-native', 'xcode', 'swift']) {+ expect(standardizeRefusalFor({ id: 'app-1', type })).toMatch(/not run under PM2/);+ }+ });++ it('refuses PortOS itself — its ecosystem.config.cjs is the canonical PORTS source', () => {+ expect(standardizeRefusalFor({ id: PORTOS_APP_ID, type: 'vite+express' }))+ .toMatch(/manages its own ecosystem\.config\.cjs/);+ });+});describe('reassignCollidingPorts', () => {it('moves a process off a taken port and rewrites both env.PORT and --port args', () => {diff --git a/server/services/socket.js b/server/services/socket.jsindex aa540545b9..2cf073fa50 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -509,6 +509,12 @@ export function initSocket(io) {return;}+ const refusal = pm2Standardizer.standardizeRefusalFor(app);+ if (refusal) {+ socket.emit('app:standardize:error', { appId: app.id, message: refusal });+ return;+ }+const inFlight = findConflictingOperation(app);if (inFlight) {socket.emit('app:standardize:error', {diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex 84370d49d9..affe1dd1a5 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -17,7 +17,7 @@ vi.mock('./cosEvents.js', () => ({ cosEvents: { on: vi.fn() }, emitLog: vi.fn()vi.mock('./apps.js', () => ({ appsEvents: { on: vi.fn() }, getAppById: vi.fn(), resolvePm2HomeForProcess: vi.fn(), updateApp: vi.fn() }));vi.mock('../lib/errorHandler.js', () => ({ errorEvents: { on: vi.fn() } }));vi.mock('./autoFixer.js', () => ({ handleErrorRecovery: vi.fn() }));-vi.mock('./pm2Standardizer.js', () => ({ analyzeApp: vi.fn(), createGitBackup: vi.fn(), applyStandardization: vi.fn(), runStandardizeFlow: vi.fn() }));+vi.mock('./pm2Standardizer.js', () => ({ analyzeApp: vi.fn(), createGitBackup: vi.fn(), applyStandardization: vi.fn(), runStandardizeFlow: vi.fn(), standardizeRefusalFor: vi.fn(() => null) }));vi.mock('./notifications.js', () => ({ notificationEvents: { on: vi.fn() } }));vi.mock('./agentPersonalities.js', () => ({ agentPersonalityEvents: { on: vi.fn() } }));vi.mock('./platformAccounts.js', () => ({ platformAccountEvents: { on: vi.fn() } }));@@ -70,6 +70,7 @@ import { audioGenEvents } from './audioGen/events.js';import { detachSocketSessions } from './shell.js';import * as shellService from './shell.js';import { updateApp as runAppUpdate } from './appUpdater.js';+import { analyzeApp, standardizeRefusalFor } from './pm2Standardizer.js';// Build a minimal fake socket with per-event handler capturefunction makeSocket(id = 'sock-1') {@@ -672,6 +673,24 @@ describe('socket.js — initSocket', () => {await flush();});+ it('refuses to standardize an app the standardizer rejects, before any analysis runs', async () => {+ // Standardizing rewrites the target repo (writes ecosystem.config.cjs), so+ // the precondition is enforced here — not left to the button being hidden.+ const socket = makeSocket('app-op-refusal');+ io.connect(socket);++ vi.mocked(getAppById).mockResolvedValueOnce({ id: 'app-ios', name: 'iOS App', type: 'ios-native', repoPath: '/srv/ios-app' });+ vi.mocked(standardizeRefusalFor).mockReturnValueOnce('ios-native apps are not run under PM2');++ await socket.handlers['app:standardize']({ appId: 'app-ios' });+ await flush();++ expect(socket.emitted.some(([ev, payload]) => (+ ev === 'app:standardize:error' && payload.message.includes('not run under PM2')+ ))).toBe(true);+ expect(vi.mocked(analyzeApp)).not.toHaveBeenCalled();+ });+it('buffers steps so a client that connects mid-operation rehydrates the log', async () => {const socket = makeSocket('app-op-buffer');io.connect(socket);