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: expose staged Autofixer patches and promotion controls (#9945)

[._.]/ Adam Eivy157ee83f77d7
diff --git a/autofixer/stagedFixes.js b/autofixer/stagedFixes.js
new file mode 100644
index 0000000000..a7c9f9a7fe
--- /dev/null
+++ b/autofixer/stagedFixes.js
@@ -0,0 +1,70 @@
+import { readFile, writeFile, rename } from 'fs/promises';
+import { join } from 'path';
+import { validateProposedDiff, applyDiffToLive, revertDiffFromLive } from './sandbox.js';
+
+// Session metadata is the authority for patch disposition. The history index is
+// append-only from the daemon's perspective, so UI actions never overwrite it.
+export function createStagedFixStore({ root, loadApps, execPm2 }) {
+ let tail = Promise.resolve();
+ const sessionDir = (id) => typeof id === 'string' && /^autofixer_[A-Za-z0-9_-]+$/.test(id)
+ ? join(root, 'sessions', id) : null;
+ const metadata = async (id) => {
+ const dir = sessionDir(id);
+ if (!dir) return null;
+ return readFile(join(dir, 'metadata.json'), 'utf8').then(JSON.parse).catch(() => null);
+ };
+ const read = async (id) => {
+ const record = await metadata(id);
+ if (!record || record.sessionId !== id || record.staged !== true) {
+ return { status: 404, error: 'No staged fix found' };
+ }
+ const patch = await readFile(join(sessionDir(id), 'fix.patch'), 'utf8').catch(() => null);
+ if (!patch) return { status: 404, error: 'Staged patch is unavailable' };
+ return { record, patch };
+ };
+ const perform = async (id, action) => {
+ const fix = await read(id);
+ if (fix.error) return fix;
+ const { record, patch } = fix;
+ let disposition = 'discarded';
+ if (action === 'apply') {
+ const app = (await loadApps()).find(app => app.id === record.appId
+ && app.repoPath === record.repoPath && app.pm2ProcessNames?.includes(record.processName));
+ if (!app) return { status: 409, error: 'The original registered app or process has changed' };
+ const validation = validateProposedDiff(patch, { maxBytes: 200 * 1024 });
+ if (!validation.ok) return { status: 409, error: validation.reason };
+ const applied = await applyDiffToLive(app.repoPath, patch, root);
+ if (!applied.ok) return { status: 409, error: applied.error };
+ const restart = await execPm2(['restart', record.processName]).catch(error => ({ error: error.message }));
+ if (restart.error) {
+ const rollback = await revertDiffFromLive(app.repoPath, patch, root);
+ // A failed rollback must not advertise this patch as safe to apply again.
+ if (rollback.error) {
+ await save(id, { ...record, staged: false, disposition: 'recovery-required', error: rollback.error });
+ }
+ return { status: 500, error: `Restart failed: ${restart.error}${rollback.error ? '; rollback failed — inspect the checkout' : '; patch rolled back'}` };
+ }
+ disposition = 'applied';
+ }
+ const updated = { ...record, staged: false, promoted: disposition === 'applied', disposition };
+ await save(id, updated);
+ return { success: true, disposition };
+ };
+ const save = async (id, record) => {
+ const destination = join(sessionDir(id), 'metadata.json');
+ await writeFile(`${destination}.tmp`, JSON.stringify(record, null, 2));
+ await rename(`${destination}.tmp`, destination);
+ };
+ return {
+ read,
+ mutate: (id, action) => {
+ const run = tail.then(() => perform(id, action));
+ tail = run.catch(() => {});
+ return run;
+ },
+ decorateHistory: async (history) => Promise.all(history.map(async entry => {
+ const record = await metadata(entry.sessionId);
+ return record ? { ...entry, staged: record.staged, promoted: record.promoted, disposition: record.disposition } : entry;
+ })),
+ };
+}
diff --git a/autofixer/stagedFixes.test.js b/autofixer/stagedFixes.test.js
new file mode 100644
index 0000000000..a33564a652
--- /dev/null
+++ b/autofixer/stagedFixes.test.js
@@ -0,0 +1,56 @@
+import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, mkdir, writeFile, readFile, rm } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { execFileSync } from 'child_process';
+import { createStagedFixStore } from './stagedFixes.js';
+let root, repo, store, restart;
+const id = 'autofixer_example_123';
+const patch = 'diff --git a/example.txt b/example.txt\nindex 3367afd..3e75765 100644\n--- a/example.txt\n+++ b/example.txt\n@@ -1 +1 @@\n-old\n+new\n';
+beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), 'autofixer-staged-'));
+ repo = join(root, 'repo');
+ await mkdir(repo);
+ execFileSync('git', ['init', '-q'], { cwd: repo });
+ await writeFile(join(repo, 'example.txt'), 'old\n');
+ await mkdir(join(root, 'sessions', id), { recursive: true });
+ await writeFile(join(root, 'sessions', id, 'metadata.json'), JSON.stringify({
+ sessionId: id, appId: 'example', repoPath: repo, processName: 'example-process', staged: true,
+ }));
+ await writeFile(join(root, 'sessions', id, 'fix.patch'), patch);
+ restart = vi.fn().mockResolvedValue({ stdout: 'ok' });
+ store = createStagedFixStore({ root, execPm2: restart,
+ loadApps: async () => [{ id: 'example', repoPath: repo, pm2ProcessNames: ['example-process'] }] });
+});
+afterEach(async () => { await rm(root, { recursive: true, force: true }); });
+describe('staged repair lifecycle', () => {
+ it('shows the proposal, applies its actual git patch once, and persists history disposition', async () => {
+ expect((await store.read(id)).patch).toBe(patch);
+ const results = await Promise.all([store.mutate(id, 'apply'), store.mutate(id, 'apply')]);
+ expect(results.map(result => result.status || 200)).toEqual([200, 404]);
+ expect(await readFile(join(repo, 'example.txt'), 'utf8')).toBe('new\n');
+ expect(restart).toHaveBeenCalledExactlyOnceWith(['restart', 'example-process']);
+ expect(await store.decorateHistory([{ sessionId: id, staged: true }])).toEqual([
+ { sessionId: id, staged: false, promoted: true, disposition: 'applied' },
+ ]);
+ });
+ it('rejects a stale patch without changing files or restarting', async () => {
+ await writeFile(join(repo, 'example.txt'), 'newer edit\n');
+ expect((await store.mutate(id, 'apply')).status).toBe(409);
+ expect(await readFile(join(repo, 'example.txt'), 'utf8')).toBe('newer edit\n');
+ expect(restart).not.toHaveBeenCalled();
+ });
+ it('rolls back on restart failure and retains the staged proposal', async () => {
+ restart.mockRejectedValue(new Error('example restart failure'));
+ expect((await store.mutate(id, 'apply')).status).toBe(500);
+ expect(await readFile(join(repo, 'example.txt'), 'utf8')).toBe('old\n');
+ expect((await store.read(id)).patch).toBe(patch);
+ });
+ it('discards without applying and rejects traversal IDs', async () => {
+ expect((await store.read('../outside')).status).toBe(404);
+ expect(await store.mutate(id, 'discard')).toEqual({ success: true, disposition: 'discarded' });
+ expect((await store.read(id)).status).toBe(404);
+ expect(await readFile(join(repo, 'example.txt'), 'utf8')).toBe('old\n');
+ expect(restart).not.toHaveBeenCalled();
+ });
+});
diff --git a/autofixer/ui.js b/autofixer/ui.js
index 26e44d3cbf..92534b3cd3 100644
--- a/autofixer/ui.js
+++ b/autofixer/ui.js
@@ -6,7 +6,8 @@ import { fileURLToPath } from 'url';
import { createTailscaleServers, watchCertReload } from '../lib/tailscale-https.js';
import { certPaths } from '../lib/certPaths.js';
import { createSidecarAuthGate } from '../lib/sidecarAuthGate.js';
-import { PM2_BIN, execPm2, listProcessesStrict, DATA_DIR, INDEX_FILE, loadApps } from './shared.js';
+import { createStagedFixStore } from './stagedFixes.js';
+import { PM2_BIN, execPm2, listProcessesStrict, DATA_DIR, AUTOFIXER_DIR, INDEX_FILE, loadApps } from './shared.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -19,10 +20,12 @@ const PORT = process.env.PORT || 5560;
const UI_TEMPLATE_FILE = join(__dirname, 'ui.template.html');
const UI_HTML = await readFile(UI_TEMPLATE_FILE, 'utf8');
+const stagedFixes = createStagedFixStore({ root: AUTOFIXER_DIR, loadApps, execPm2 });
+
// Load autofixer history
async function loadHistory() {
const data = await readFile(INDEX_FILE, 'utf8').catch(() => '[]');
- return JSON.parse(data);
+ return stagedFixes.decorateHistory(JSON.parse(data));
}
// Reads honour the optional instance password. Process mutations additionally
@@ -56,6 +59,18 @@ app.get('/api/history', async (req, res) => {
res.json(history);
});
+// Staged patches are data on reads; applying/discarding requires host authority.
+app.get('/api/fixes/:session', async (req, res) => {
+ const result = await stagedFixes.read(req.params.session);
+ res.status(result.status || 200).json(result);
+});
+for (const action of ['apply', 'discard']) {
+ app.post(`/api/fixes/:session/${action}`, auth.requireHostControl, async (req, res) => {
+ const result = await stagedFixes.mutate(req.params.session, action);
+ res.status(result.status || 200).json(result);
+ });
+}
+
// API: Get PM2 status
//
// `listProcessesStrict()` returns `null` when the read itself FAILED (vs `[]`
diff --git a/autofixer/ui.template.html b/autofixer/ui.template.html
index f0215e31f1..b7254e91f8 100644
--- a/autofixer/ui.template.html
+++ b/autofixer/ui.template.html
@@ -881,9 +881,45 @@
const resultEl = document.createElement('div');
const succeeded = h.success === true;
resultEl.classList.add('result', succeeded ? 'success' : 'failed');
- resultEl.textContent = succeeded ? 'Fixed successfully' : 'Fix failed';
+ resultEl.textContent = h.staged ? 'Staged for review' : h.disposition === 'discarded' ? 'Discarded' : h.promoted ? 'Applied and restarted' : h.disposition === 'recovery-required' ? 'Recovery required — inspect checkout' : succeeded ? 'Fix produced' : 'Fix failed';
item.append(timeEl, processEl, resultEl);
+ if (h.staged) {
+ const view = document.createElement('button');
+ view.textContent = 'Review patch';
+ view.addEventListener('click', async () => {
+ view.disabled = true;
+ const res = await apiFetch('/api/fixes/' + encodeURIComponent(h.sessionId)).catch(() => null);
+ view.disabled = false;
+ if (!res) return;
+ const fix = await res.json();
+ if (!res.ok) { showToast(fix.error || 'Unable to load patch', 'error'); return; }
+ view.remove();
+ const diff = document.createElement('pre');
+ diff.textContent = fix.patch;
+ diff.style.cssText = 'white-space:pre-wrap;overflow-wrap:anywhere;max-height:24rem;overflow:auto';
+ item.appendChild(diff);
+ const controls = [];
+ for (const action of ['apply', 'discard']) {
+ const button = document.createElement('button');
+ button.textContent = action === 'apply' ? 'Apply and restart' : 'Discard';
+ controls.push(button);
+ button.addEventListener('click', async () => {
+ controls.forEach(control => { control.disabled = true; });
+ const result = await apiFetch('/api/fixes/' + encodeURIComponent(h.sessionId) + '/' + action, { method: 'POST' }).catch(() => null);
+ controls.forEach(control => { control.disabled = false; });
+ if (!result) { showToast('Action failed — check connection', 'error'); return; }
+ const body = await result.json();
+ if (!result.ok) { showToast(body.error || 'Action failed', 'error'); return; }
+ resultEl.textContent = body.disposition === 'applied' ? 'Applied and restarted' : 'Discarded';
+ controls.forEach(control => control.remove());
+ if (body.disposition === 'applied') fetchStatus();
+ });
+ item.appendChild(button);
+ }
+ });
+ item.appendChild(view);
+ }
historyPanel.appendChild(item);
});
}
diff --git a/autofixer/ui.test.js b/autofixer/ui.test.js
index 714f8e6c14..6d07d039c8 100644
--- a/autofixer/ui.test.js
+++ b/autofixer/ui.test.js
@@ -22,7 +22,7 @@ vi.mock('../lib/tailscale-https.js', () => ({
watchCertReload: vi.fn(),
}));
vi.mock('./shared.js', () => ({
- PM2_BIN: 'example-pm2', DATA_DIR: 'unused', INDEX_FILE: 'unused',
+ PM2_BIN: 'example-pm2', DATA_DIR: 'unused', AUTOFIXER_DIR: 'unused', INDEX_FILE: 'unused',
execPm2: harness.execPm2, listProcessesStrict: vi.fn(),
loadApps: async () => [{ pm2ProcessNames: ['example-process'] }],
}));
@@ -74,6 +74,20 @@ const mutate = async (action, address = '192.0.2.10', headers = {}) => {
};
describe('Autofixer process-control authority', () => {
+ 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}`)]) {
+ let nexted = false;
+ await handler(req, res, () => { nexted = true; });
+ if (!nexted) break;
+ }
+ expect(res.statusCode).toBe(403);
+ expect(res.body.code).toBe('HOST_CONTROL_FORBIDDEN');
+ }
+ });
it('refuses remote, forged forwarding, and remote dev-proxy callers before PM2', async () => {
await loadUi();
for (const action of ['restart', 'stop']) {
diff --git a/client/src/components/settings/AutofixerTab.jsx b/client/src/components/settings/AutofixerTab.jsx
index a652600ee0..35500c04a4 100644
--- a/client/src/components/settings/AutofixerTab.jsx
+++ b/client/src/components/settings/AutofixerTab.jsx
@@ -1,3 +1,5 @@
+import { useEffect, useState } from 'react';
+import { getSettings, updateSettings } from '../../services/api';
import { Wrench } from 'lucide-react';
import FeatureProviderPicker from '../FeatureProviderPicker';
@@ -7,6 +9,28 @@ import FeatureProviderPicker from '../FeatureProviderPicker';
* (`settings.autofixer`) from the shared data file in its own process.
*/
export function AutofixerTab() {
+ const [autoPromote, setAutoPromote] = useState(false);
+ const [verifyCommand, setVerifyCommand] = useState('');
+ const [loaded, setLoaded] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState('');
+ useEffect(() => {
+ let active = true;
+ getSettings({ silent: true }).then(settings => {
+ if (!active) return;
+ setAutoPromote(settings.autofixer?.autoPromote === true);
+ setVerifyCommand(settings.autofixer?.verifyCommand || '');
+ setLoaded(true);
+ }).catch(() => { if (active) setError('Unable to load Autofixer settings.'); });
+ return () => { active = false; };
+ }, []);
+ const save = async () => {
+ setSaving(true);
+ setError('');
+ await updateSettings({ autofixer: { autoPromote, verifyCommand } }, { silent: true })
+ .catch(() => setError('Unable to save Autofixer settings.'));
+ setSaving(false);
+ };
return (
<div className="space-y-6">
<div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">
@@ -16,13 +40,34 @@ export function AutofixerTab() {
</div>
<p className="text-sm text-gray-400 mb-4">
When a monitored process crashes, the Autofixer runs this AI provider to read the logs,
- edit the offending files, and restart the process. Only agentic CLI providers are listed —
+ propose a fix in an isolated checkout. Fixes are staged for review by default; apply or discard
+ them in the Autofixer History tab. Automatic application and restart require the toggle below.
+ Only agentic CLI providers are listed —
the fixer needs file-edit and shell access, which API chat providers can't do.
</p>
<FeatureProviderPicker
featureKey="autofixer"
hint="Defaults to Claude Code when unset. Configure providers under AI Providers."
/>
+ <div className="mt-6 space-y-3">
+ <label className="flex items-center gap-2 text-sm">
+ <input type="checkbox" checked={autoPromote} disabled={!loaded || saving}
+ onChange={event => setAutoPromote(event.target.checked)} />
+ Apply fixes automatically
+ </label>
+ <p className="text-xs text-port-warning">Automatically applies validated patches to the live checkout and restarts the process.</p>
+ <label className="block text-sm">
+ Verify command
+ <input className="mt-1 block w-full bg-port-bg border border-port-border rounded p-2"
+ value={verifyCommand} maxLength={500} disabled={!loaded || saving}
+ onChange={event => setVerifyCommand(event.target.value)} placeholder="npm test" />
+ </label>
+ <p className="text-xs text-gray-400">Optional command run in the isolated checkout before staging or automatic application.</p>
+ <button className="px-3 py-2 bg-port-accent rounded text-white" disabled={!loaded || saving} onClick={save}>
+ {saving ? 'Saving…' : 'Save promotion settings'}
+ </button>
+ {error && <p role="alert" className="text-port-error text-sm">{error}</p>}
+ </div>
</div>
</div>
);
diff --git a/client/src/components/settings/AutofixerTab.test.jsx b/client/src/components/settings/AutofixerTab.test.jsx
new file mode 100644
index 0000000000..a3a62bc3fc
--- /dev/null
+++ b/client/src/components/settings/AutofixerTab.test.jsx
@@ -0,0 +1,27 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { AutofixerTab } from './AutofixerTab';
+import { getSettings, updateSettings } from '../../services/api';
+vi.mock('../../services/api', () => ({ getSettings: vi.fn(), updateSettings: vi.fn() }));
+vi.mock('../FeatureProviderPicker', () => ({ default: () => null }));
+afterEach(() => { cleanup(); vi.resetAllMocks(); });
+describe('Autofixer promotion settings', () => {
+ it('loads saved settings and saves the edited promotion options', async () => {
+ getSettings.mockResolvedValue({ autofixer: { autoPromote: true, verifyCommand: 'npm test' } });
+ updateSettings.mockResolvedValue({ autofixer: { autoPromote: false, verifyCommand: '' } });
+ render(<AutofixerTab />);
+ await waitFor(() => expect(screen.getByLabelText('Apply fixes automatically')).toBeChecked());
+ expect(screen.getByLabelText('Verify command')).toHaveValue('npm test');
+ fireEvent.click(screen.getByLabelText('Apply fixes automatically'));
+ fireEvent.change(screen.getByLabelText('Verify command'), { target: { value: '' } });
+ fireEvent.click(screen.getByText('Save promotion settings'));
+ await waitFor(() => expect(updateSettings).toHaveBeenCalledWith({ autofixer: { autoPromote: false, verifyCommand: '' } }, { silent: true }));
+ });
+ it('keeps controls disabled when settings cannot load', async () => {
+ getSettings.mockRejectedValue(new Error('unavailable'));
+ render(<AutofixerTab />);
+ await screen.findByRole('alert');
+ expect(screen.getByText('Save promotion settings')).toBeDisabled();
+ expect(updateSettings).not.toHaveBeenCalled();
+ });
+});
diff --git a/docs/features/autofixer.md b/docs/features/autofixer.md
index 6202adef47..152d6730e0 100644
--- a/docs/features/autofixer.md
+++ b/docs/features/autofixer.md
@@ -1,6 +1,6 @@
# Autofixer Integration
-Autonomous crash detection and repair using Claude CLI.
+Autonomous crash detection and isolated repair using the configured CLI provider. Validated fixes are staged by default; the live app stays unchanged until the operator applies a patch.
## Architecture
@@ -11,7 +11,7 @@ Autonomous crash detection and repair using Claude CLI.
## Features
1. **Crash Detection**: Polls PM2 every 15 minutes for `errored` status on registered apps
-2. **Auto-Fix**: Invokes Claude CLI with crash context (error logs, app info) to diagnose and repair
+2. **Isolated repair**: Invokes the CLI provider selected in Settings → Autofixer with crash context, validates the patch, and optionally runs the configured verify command
3. **Session History**: Stores fix attempts with prompts, outputs, and success/failure status
4. **Cooldown**: 30-minute cooldown per process to prevent repeated fix loops
5. **Log Streaming**: Real-time SSE log streaming from any PM2 process
@@ -34,11 +34,15 @@ Autonomous crash detection and repair using Claude CLI.
Port 5560 provides:
- Process sidebar with live status indicators
- SSE-powered log viewer with pause/clear controls
-- History tab showing fix attempts with success/failure status
+- History tab showing staged fixes per app, patch diffs, and Apply and restart / Discard actions
+- Apply and Discard require an operator session, or a genuine local connection when no password is configured
- Links back to PortOS Dashboard
## Configuration
+Settings → Autofixer offers **Apply fixes automatically** (off by default) and an optional **Verify command**, run in the isolated checkout before a fix is staged or applied. Enabling automatic application applies validated patches to the live checkout and restarts the process. Manual application checks that the patch still applies and rolls it back if restart fails. Discard retires the proposal while retaining its history artifact.
+
+
| Setting | Value |
|---------|-------|
| UI Port | 5560 |
diff --git a/server/routes/settings.js b/server/routes/settings.js
index c45d0d4dc1..dd4f8c82ad 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -674,8 +674,14 @@ router.put('/', asyncHandler(async (req, res) => {
previousBeeperIntervalMinutes = current?.beeper?.intervalMinutes;
previousBeeperConnection = JSON.stringify([current?.beeper?.baseUrl, current?.beeper?.allowNonLoopbackBaseUrl]);
previousBeeperGates = JSON.stringify([current?.instanceFeatures?.beeper, current?.instanceFeatureGroups?.comms]);
+ // Provider picker and promotion controls save independent keys in this
+ // slice. Merge while holding the settings write queue to retain both.
+ const next = { ...current, ...settingsPatch };
+ if (settingsPatch.autofixer !== undefined) {
+ next.autofixer = { ...current.autofixer, ...settingsPatch.autofixer };
+ }
return preserveExternallyOwnedKeys(
- mergeFederationSlice({ ...current, ...settingsPatch }, current),
+ mergeFederationSlice(next, current),
current,
);
}, { actor: 'user' });
diff --git a/server/routes/settings.test.js b/server/routes/settings.test.js
index 73c805c241..c0a5555721 100644
--- a/server/routes/settings.test.js
+++ b/server/routes/settings.test.js
@@ -1444,3 +1444,16 @@ it('generic settings updates cannot replace the password-risk revision', async (
expect(res.status).toBe(200);
expect(store.passwordRiskRevision).toBe('current-revision');
});
+
+describe('autofixer settings slice', () => {
+ it('round-trips promotion options without losing provider selection on independent saves', async () => {
+ const app = buildApp();
+ expect((await request(app).put('/api/settings').send({ autofixer: { providerId: 'example-cli', model: 'example-model' } })).status).toBe(200);
+ expect((await request(app).put('/api/settings').send({ autofixer: { autoPromote: true, verifyCommand: 'npm test' } })).status).toBe(200);
+ expect((await request(app).put('/api/settings').send({ autofixer: { model: 'another-model' } })).status).toBe(200);
+ const loaded = await request(app).get('/api/settings');
+ expect(loaded.body.autofixer).toEqual({ providerId: 'example-cli', model: 'another-model', autoPromote: true, verifyCommand: 'npm test' });
+ expect((await request(app).put('/api/settings').send({ autofixer: { autoPromote: 'true' } })).status).toBe(400);
+ expect((await request(app).get('/api/settings')).body.autofixer).toEqual(loaded.body.autofixer);
+ });
+});