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
Refuse Autofixer repairs when required inputs are unavailable (#11564)
[._.]/95358a402dd0
diff --git a/autofixer/server.js b/autofixer/server.jsindex 6b32bb3957..618bcfd675 100644--- a/autofixer/server.js+++ b/autofixer/server.js@@ -159,8 +159,12 @@ async function saveSession(sessionId, prompt, output, metadata, patch) {// Get error logs for a processasync function getProcessLogs(processName) {- const { stdout: errLogs } = await execPm2(['logs', processName, '--lines', '100', '--nostream', '--err']).catch(() => ({ stdout: '' }));- const { stdout: outLogs } = await execPm2(['logs', processName, '--lines', '50', '--nostream', '--out']).catch(() => ({ stdout: '' }));+ const { stdout: errLogs } = await execPm2(['logs', processName, '--lines', '100', '--nostream', '--err']).catch(() => {+ throw new Error(`PM2 stderr logs unavailable for ${processName.replace(/[\r\n]/g, ' ').slice(0, 120)} — skipping repair`);+ });+ const { stdout: outLogs } = await execPm2(['logs', processName, '--lines', '50', '--nostream', '--out']).catch(() => {+ throw new Error(`PM2 stdout logs unavailable for ${processName.replace(/[\r\n]/g, ' ').slice(0, 120)} — skipping repair`);+ });return { errLogs, outLogs };}diff --git a/autofixer/server.test.js b/autofixer/server.test.jsnew file mode 100644index 0000000000..796ac3c016--- /dev/null+++ b/autofixer/server.test.js@@ -0,0 +1,89 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const harness = vi.hoisted(() => ({+ apps: vi.fn(), pm2: vi.fn(), list: vi.fn(), provider: vi.fn(),+}));+vi.mock('./shared.js', () => ({+ DATA_DIR: '/example/data', AUTOFIXER_DIR: '/example/autofixer', INDEX_FILE: '/example/index.json',+ loadApps: harness.apps, execPm2: harness.pm2, listProcessesStrict: harness.list,+}));+vi.mock('fs/promises', () => ({+ readFile: vi.fn(async file => file.endsWith('index.json') ? '[]' : '{}'),+ writeFile: vi.fn(async () => {}), mkdir: vi.fn(async () => {}), access: vi.fn(async () => {}),+}));+vi.mock('../server/lib/agentGuard/index.js', () => ({ agentGuardEnv: () => ({}) }));+vi.mock('../server/lib/cliProviderRun.js', () => ({+ pickCliProvider: () => ({ provider: { id: 'example-cli' } }),+ runCliProviderPrompt: harness.provider,+}));+vi.mock('./sandbox.js', () => ({+ sanitizeChildEnv: () => ({}), collectSecretEnvValues: () => [],+ buildFixPrompt: ({ errorLogs, outputLogs }) => JSON.stringify({ errorLogs, outputLogs }),+ restrictedToolArgs: () => [], isGitRepo: async () => true,+ createDisposableWorktree: async () => ({ path: '/example/worktree' }),+ collectWorktreeDiff: async () => '', removeWorktree: vi.fn(),+ validateProposedDiff: () => ({ ok: false, reason: 'No changes', files: [] }),+ applyDiffToLive: vi.fn(), revertDiffFromLive: vi.fn(), runVerifyCommand: vi.fn(),+}));++let errorLog;+let progressLog;+beforeEach(() => {+ vi.resetModules();+ vi.useFakeTimers();+ vi.spyOn(process, 'on').mockReturnValue(process);+ errorLog = vi.spyOn(console, 'error').mockImplementation(() => {});+ progressLog = vi.spyOn(console, 'log').mockImplementation(() => {});+ harness.apps.mockReset().mockResolvedValue([{ id: 'example', name: 'Example app', repoPath: '/example/repo', pm2ProcessNames: ['example-process'] }]);+ harness.list.mockReset().mockResolvedValue([{ name: 'example-process', pm2_env: { status: 'errored' } }]);+ harness.pm2.mockReset().mockResolvedValue({ stdout: '' });+ harness.provider.mockReset().mockResolvedValue({ error: 'Example agent stopped', exitCode: 1 });+});+afterEach(() => {+ vi.clearAllTimers();+ vi.useRealTimers();+ vi.restoreAllMocks();+});+const start = async () => {+ await import('./server.js');+ await vi.advanceTimersByTimeAsync(0);+};+const nextCycle = () => vi.advanceTimersByTimeAsync(15 * 60 * 1000);++describe('Autofixer daemon repair input boundary', () => {+ it.each(['--err', '--out'])('refuses repair after failed %s collection and recovers next cycle', async stream => {+ harness.pm2.mockImplementation(async args => {+ if (args.includes(stream)) throw new Error('private command output and path');+ return { stdout: '' };+ });+ await start();+ expect(harness.provider).not.toHaveBeenCalled();+ const diagnostic = errorLog.mock.calls.flat().join('\n');+ expect(diagnostic).toContain(`PM2 ${stream === '--err' ? 'stderr' : 'stdout'} logs unavailable for example-process`);+ expect(diagnostic).not.toContain('private command output and path');+ harness.pm2.mockResolvedValue({ stdout: '' });+ await nextCycle();+ expect(harness.provider).toHaveBeenCalledOnce();+ expect(JSON.parse(harness.provider.mock.calls[0][0].prompt)).toEqual({ errorLogs: '', outputLogs: '' });+ });++ it('reports registry failure without a false empty-installation message and retries', async () => {+ harness.apps.mockRejectedValueOnce(Object.assign(new Error('App registry unavailable'), { code: 'APPS_UNAVAILABLE' }));+ await start();+ expect(errorLog.mock.calls.flat().join('\n')).toContain('App registry unavailable');+ expect(progressLog.mock.calls.flat().join('\n')).not.toContain('No apps registered');+ expect(harness.pm2).not.toHaveBeenCalled();+ expect(harness.provider).not.toHaveBeenCalled();+ await nextCycle();+ expect(harness.provider).toHaveBeenCalledOnce();+ });++ it('treats a successfully empty registry as an empty installation', async () => {+ harness.apps.mockResolvedValue([]);+ await start();+ expect(progressLog.mock.calls.flat().join('\n')).toContain('No apps registered');+ expect(errorLog).not.toHaveBeenCalled();+ expect(harness.list).not.toHaveBeenCalled();+ expect(harness.provider).not.toHaveBeenCalled();+ });+});diff --git a/autofixer/shared.js b/autofixer/shared.jsindex 52309ed303..85777f5f2e 100644--- a/autofixer/shared.js+++ b/autofixer/shared.js@@ -70,7 +70,13 @@ export const INDEX_FILE = join(AUTOFIXER_DIR, 'index.json');// Load apps from PortOSexport async function loadApps() {- const data = await readFile(APPS_FILE, 'utf8').catch(() => '{"apps":{}}');- const parsed = JSON.parse(data);- return Object.entries(parsed.apps || {}).map(([id, app]) => ({ id, ...app }));+ try {+ const parsed = JSON.parse(await readFile(APPS_FILE, 'utf8'));+ return Object.entries(parsed.apps || {}).map(([id, app]) => ({ id, ...app }));+ } catch (error) {+ // A not-yet-created registry remains a valid empty installation.+ if (error.code === 'ENOENT') return [];+ // File paths, parser excerpts and read errors may contain private data.+ throw Object.assign(new Error('App registry unavailable'), { code: 'APPS_UNAVAILABLE' });+ }}diff --git a/autofixer/shared.test.js b/autofixer/shared.test.jsindex babf741b24..e529c090ca 100644--- a/autofixer/shared.test.js+++ b/autofixer/shared.test.js@@ -6,7 +6,7 @@ import { fileURLToPath } from 'url';import { createRequire } from 'module';// loadApps() reads a fixed on-disk path, so the read is faked to keep the-// fallback assertions independent of whether this install has a data/apps.json.+// availability assertions independent of whether this install has a data/apps.json.const readFileMock = vi.hoisted(() => vi.fn());vi.mock('fs/promises', async (importOriginal) => ({...(await importOriginal()),@@ -107,6 +107,16 @@ describeShared('autofixer/shared — loadApps', () => {await expect(shared.loadApps()).resolves.toEqual([]);});+ it.each(['EACCES', 'EIO'])('reports %s without exposing the underlying error', async (code) => {+ readFileMock.mockRejectedValue(Object.assign(new Error('private example path or content'), { code }));+ await expect(shared.loadApps()).rejects.toMatchObject({ message: 'App registry unavailable', code: 'APPS_UNAVAILABLE' });+ });++ it('preserves a successfully read empty app registry', async () => {+ readFileMock.mockResolvedValue('{"apps":{}}');+ await expect(shared.loadApps()).resolves.toEqual([]);+ });+it('flattens the apps map into records carrying their id', async () => {readFileMock.mockResolvedValue(JSON.stringify({apps: { 'example-app': { pm2ProcessNames: ['example-api'], repoPath: '/srv/example' } },diff --git a/autofixer/ui.js b/autofixer/ui.jsindex 92534b3cd3..7ad76f61bb 100644--- a/autofixer/ui.js+++ b/autofixer/ui.js@@ -243,6 +243,14 @@ app.get('/logs', async (req, res) => {});});+// Registry failures reach every consumer (apps, process controls and staged+// fixes) through Express's error boundary, before any mutation can run.+app.use((error, req, res, next) => {+ if (error.code !== 'APPS_UNAVAILABLE') return next(error);+ console.error(`❌ [Autofixer UI] App registry unavailable`);+ res.status(503).json({ error: 'App registry unavailable', code: 'APPS_UNAVAILABLE' });+});+// Serve HTTPS with the same Tailscale cert the main PortOS server uses when one// is present, so the sidebar's `${window.location.protocol}//<host>:5560` link// (which inherits https:// on a cert-enabled install) hits a matching listener.diff --git a/autofixer/ui.test.js b/autofixer/ui.test.jsindex 6d07d039c8..7205d903cb 100644--- a/autofixer/ui.test.js+++ b/autofixer/ui.test.js@@ -4,11 +4,11 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { hashPassword, hashToken } from '../lib/portosAuthCore.js';-const harness = vi.hoisted(() => ({ routes: new Map(), gates: [], auth: null, execPm2: vi.fn() }));+const harness = vi.hoisted(() => ({ routes: new Map(), gates: [], auth: null, execPm2: vi.fn(), loadApps: vi.fn() }));vi.mock('express', () => {const express = () => ({use: (handler) => harness.gates.push(handler),- get: () => {},+ get: (path, ...handlers) => harness.routes.set(path, handlers),post: (path, ...handlers) => harness.routes.set(path, handlers),});express.json = () => (_req, _res, next) => next();@@ -24,7 +24,7 @@ vi.mock('../lib/tailscale-https.js', () => ({vi.mock('./shared.js', () => ({PM2_BIN: 'example-pm2', DATA_DIR: 'unused', AUTOFIXER_DIR: 'unused', INDEX_FILE: 'unused',execPm2: harness.execPm2, listProcessesStrict: vi.fn(),- loadApps: async () => [{ pm2ProcessNames: ['example-process'] }],+ loadApps: harness.loadApps,}));const PASSWORD = 'example-password';@@ -35,6 +35,7 @@ beforeAll(async () => { passwordHash = await hashPassword(PASSWORD, SALT); }, 30beforeEach(async () => {dataDir = await mkdtemp(join(tmpdir(), 'autofixer-authority-'));harness.execPm2.mockReset().mockResolvedValue({ stdout: 'ok', stderr: '' });+ harness.loadApps.mockReset().mockResolvedValue([{ pm2ProcessNames: ['example-process'] }]);harness.gates.length = 0;harness.routes.clear();});@@ -65,7 +66,7 @@ const mutate = async (action, address = '192.0.2.10', headers = {}) => {const req = { path: `/api/${action}/example-process`, params: { process: 'example-process' },headers, socket: { remoteAddress: address } };const res = response();- for (const handler of [...harness.gates, ...harness.routes.get(`/api/${action}/:process`)]) {+ for (const handler of [...harness.gates.filter(handler => handler.length !== 4), ...harness.routes.get(`/api/${action}/:process`)]) {let nexted = false;await handler(req, res, () => { nexted = true; });if (!nexted) break;@@ -74,12 +75,26 @@ const mutate = async (action, address = '192.0.2.10', headers = {}) => {};describe('Autofixer process-control authority', () => {+ it('returns sanitized unavailability for app reads and blocks controls before PM2', async () => {+ await loadUi();+ harness.loadApps.mockRejectedValue(Object.assign(new Error('App registry unavailable'), { code: 'APPS_UNAVAILABLE' }));+ const errorBoundary = harness.gates.find(handler => handler.length === 4);+ for (const path of ['/api/apps', '/api/restart/:process', '/api/stop/:process']) {+ const handler = harness.routes.get(path).at(-1);+ const res = response();+ await handler({ params: { process: 'example-process' } }, res).catch(error => errorBoundary(error, {}, res, vi.fn()));+ expect(res.statusCode).toBe(503);+ expect(res.body).toEqual({ error: 'App registry unavailable', code: 'APPS_UNAVAILABLE' });+ }+ expect(harness.execPm2).not.toHaveBeenCalled();+ });+it('gates both staged patch actions before touching session files', async () => {await loadUi();for (const action of ['apply', 'discard']) {const req = { path: `/api/fixes/autofixer_example_123/${action}`, params: { session: 'autofixer_example_123' }, headers: {}, socket: { remoteAddress: '192.0.2.10' } };const res = response();- for (const handler of [...harness.gates, ...harness.routes.get(`/api/fixes/:session/${action}`)]) {+ for (const handler of [...harness.gates.filter(handler => handler.length !== 4), ...harness.routes.get(`/api/fixes/:session/${action}`)]) {let nexted = false;await handler(req, res, () => { nexted = true; });if (!nexted) break;