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

require approval on auto-fix tasks spawned from raw crashes and orphan retries

[._.]/ Adam Eivyec00b5ad0d42
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a8bcf9188a..a4be3d79cd 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -113,3 +113,4 @@
- **[issue-1846] Replaced vacuous inline-copy tests with coverage of real production logic** — `subAgentSpawner.test.js` had four `describe` blocks that re-implemented production logic inline and tested the copies, so the real code could regress while the suite stayed green: an inline `ERROR_PATTERNS`/`categorizeError`, an inline `resolveFailedTaskStatus` (which omitted the `MAX_TOTAL_SPAWNS` short-circuit and `compaction` metadata that the real `resolveFailedTaskUpdate` has), and stub `exitCodeMessages`/`buildSpawnArgs` literals exported from no production module. The error-classification and retry-decision blocks now live in `agentErrorAnalysis.test.js` against the real exported `ERROR_PATTERNS` (via `analyzeAgentFailure`) and a new pure `resolveFailedTaskDecision` helper extracted from `resolveFailedTaskUpdate` (the async wrapper delegates to it and just stamps timestamps + creates the investigation task — behavior-preserving); the exit-code block is replaced by a new `agentRunTracking.test.js` covering the real `extractErrorFromOutput` mapping; and the redundant spawn-args stub is dropped since `agentCliSpawning.test.js` already covers the real `buildCliSpawnConfig`. The genuine imported-helper tests (`isTruthyMeta`/`isFalsyMeta`/`applyAppWorktreeDefault`) are kept. (#1846)
- **[issue-1876] Consolidated four private XML-entity decoders into a shared `server/lib/xmlEntities.js`** — `decodeXmlEntities`/`decodeEntities`/inline `stripHtml` had drifted into near-identical copies across `appleHealthXmlParser.js`, `claudeChangelog.js`, `pinterestFeed.js`, `feeds.js`, and `messageGmailSync.js`, so an entity-handling fix had to be applied in up to five places. The most complete implementation (named + decimal `&#NN;` + hex `&#xNN;` via a single double-decode-safe pass, out-of-range-tolerant) is promoted to a shared, barrel-registered helper that also takes an optional extra-named-entity map (`{ nbsp: ' ', zwnj: '' }`) for the mail-specific entities Gmail's HTML-to-text needs; every call site now imports it. Behavior-preserving (each site's existing tests pass on the shared single-pass decoder); covered by a new `xmlEntities.test.js`. (#1876)
- **[issue-1847] Added tests for four sync-critical pure modules that shipped without one** — `server/lib/lwwTimestamp.js` (the last-writer-wins polarity behind every cross-instance merge), `server/lib/pgTimestamp.js` (`mirrorTimestamp`'s TIMESTAMPTZ bind-safety guards), `server/lib/agentGuard/index.js` (`agentGuardEnv`'s PATH-prepend + `PORTOS_REAL_PM2` pm2-kill shim), and the previously-untested `providerSchema`/`validate` exports of `server/lib/aiToolkit/validation.js`. Coverage hits the real branch points: `parseTsMs` non-string/unparseable returns, `compareNewerWins`/`compareEarlierWins` tie + unparseable-side + ISO-vs-non-ISO + antisymmetry; `mirrorTimestamp` calendar-rollover normalization, year-0000 rejection, ±expanded-year rejection, 0001/9999 bounds; `agentGuardEnv` guard-dir-first PATH order, `Path` fallback, real-pm2 resolution, plus the `bin/pm2` bash shim's actual block behavior (spawns the shim with a stub real-pm2 to assert `pm2 kill`/`startup`/`unstartup` and `delete/stop/restart all` are blocked case-insensitively while scoped/read-only commands pass through, and the no-pm2-found 127 path); `providerSchema` endpoint `''`/`null`→undefined coercion, id slug regex + 80-char max, `numCtx` 512–1048576 bounds, and `validate`'s `{path, message}` error shape. Tests only. (#1847)
+- **[self-improvement] CoS's auto-approved error-investigation tasks now require human review, matching the rest of the codebase's error-driven task creators** — two task creators auto-approved an unsupervised agent to start editing code from thin diagnostic evidence: `autoFixer.js`'s `createAutoFixTask` (triggered by `severity: 'critical'` or `canAutoFix`, covering bare `uncaughtException`/`unhandledRejection` — no repro steps, no live process state, since the process already crashed) and `agentManagement.js`'s orphan-retry investigation task (triggered after repeated agent-orphaning, an infra/process-flakiness signal rather than a diagnosed code bug). Every other error-driven task creator (`createAIProviderInvestigationTask`, `handleErrorRecovery`, `agentErrorAnalysis.js`'s `createInvestigationTask`) already required approval first; these two were the outliers, and both shipped with zero test coverage for this branch. CoS's own `learning.json` history bears this out — this task class runs rarely and has a materially worse success rate than the reviewed-first paths. Flipped both to `approvalRequired: true` and added coverage for the previously-untested branches (approval flag, trigger conditions, skip paths, dedupe).
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index bbcaa3aac2..14df8edb65 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -653,7 +653,11 @@ Once the issue is resolved, reset the original task to pending.`;
description,
priority: 'HIGH',
context: `Auto-generated from repeated orphan failures for task ${taskId}`,
- approvalRequired: false // Auto-approved for orphan issues
+ // Requires approval, matching every other error-driven task creator
+ // (autoFixer.js, agentErrorAnalysis.js) — repeated orphaning is an
+ // infra/process-flakiness signal, not a diagnosed code bug, so an
+ // unsupervised agent shouldn't be turned loose on the codebase from it.
+ approvalRequired: true
}, 'internal').catch(err => {
emitLog('error', `Failed to create investigation task: ${err.message}`, { taskId, error: err.message });
});
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 0f47b88322..d3563b2ed2 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -172,6 +172,27 @@ describe('handleOrphanedTask — duplicate-investigation guard', () => {
);
expect(addTask).not.toHaveBeenCalled();
});
+
+ it('requires approval on the investigation task once orphan retries are exhausted', async () => {
+ // orphanRetryCount: 2 -> retryCount 3 hits MAX_ORPHAN_RETRIES, tripping the
+ // "else" branch that blocks the task and spawns an investigation task.
+ const exhaustedTask = {
+ id: 'task-foo',
+ status: 'in_progress',
+ taskType: 'user',
+ description: 'Original work',
+ metadata: { orphanRetryCount: 2, totalSpawnCount: 2 }
+ };
+ const getTaskById = vi.fn().mockResolvedValue(exhaustedTask);
+
+ await handleOrphanedTask('task-foo', 'agent-orphaned', getTaskById);
+
+ expect(addTask).toHaveBeenCalledTimes(1);
+ expect(addTask.mock.calls[0][0]).toMatchObject({
+ description: expect.stringContaining('[Auto-Fix] Investigate repeated agent orphaning'),
+ approvalRequired: true,
+ });
+ });
});
describe('pauseAgent', () => {
diff --git a/server/services/autoFixer.js b/server/services/autoFixer.js
index c34b2ada18..8fc7650361 100644
--- a/server/services/autoFixer.js
+++ b/server/services/autoFixer.js
@@ -385,12 +385,14 @@ async function createAutoFixTask(error) {
// Build context for the agent
const context = buildErrorContext(error);
- // Create task in CoS system tasks
+ // Create task in CoS system tasks. Requires approval, matching every other
+ // error-driven task creator in this file — a crash alone isn't enough
+ // signal to let an agent edit code unsupervised.
const taskData = {
description: `Fix critical error: ${error.message}`,
priority: 'HIGH',
context,
- approvalRequired: false // Auto-approve for auto-fix tasks
+ approvalRequired: true
};
const task = await addTask(taskData, 'internal');
diff --git a/server/services/autoFixer.test.js b/server/services/autoFixer.test.js
index 183c934879..f0a0b2ea65 100644
--- a/server/services/autoFixer.test.js
+++ b/server/services/autoFixer.test.js
@@ -269,3 +269,70 @@ describe('autoFixer — defer + noteFallbackHandled', () => {
expect(cos.addTask).toHaveBeenCalledTimes(1);
});
});
+
+function emitCriticalError(overrides = {}) {
+ errorEvents.emit('error', {
+ code: 'UNCAUGHT_EXCEPTION',
+ message: 'boom',
+ severity: 'critical',
+ canAutoFix: true,
+ timestamp: Date.now(),
+ ...overrides,
+ });
+}
+
+describe('autoFixer — generic critical-error auto-fix path', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ cos.addTask.mockClear();
+ cos.isRunning.mockReturnValue(true);
+ _resetAutoFixerForTests();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ _resetAutoFixerForTests();
+ });
+
+ it('requires approval — a bare crash is too thin a signal for an unsupervised agent to patch code', async () => {
+ emitCriticalError({ message: 'Cannot read properties of undefined', stack: 'Error: boom\n at foo (file.js:1:1)' });
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(cos.addTask).toHaveBeenCalledTimes(1);
+ expect(cos.addTask.mock.calls[0][0]).toMatchObject({
+ description: 'Fix critical error: Cannot read properties of undefined',
+ approvalRequired: true,
+ });
+ });
+
+ it('triggers on canAutoFix even when severity is not critical', async () => {
+ emitCriticalError({ code: 'SOME_ERROR', message: 'recoverable-ish failure', severity: 'error' });
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(cos.addTask).toHaveBeenCalledTimes(1);
+ expect(cos.addTask.mock.calls[0][0]).toMatchObject({ approvalRequired: true });
+ });
+
+ it('does not fire for a non-critical error that is not marked auto-fixable', async () => {
+ emitCriticalError({ code: 'VALIDATION_ERROR', message: 'bad input', severity: 'error', canAutoFix: false });
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(cos.addTask).not.toHaveBeenCalled();
+ });
+
+ it('does not fire when CoS is not running', async () => {
+ cos.isRunning.mockReturnValue(false);
+ emitCriticalError();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(cos.addTask).not.toHaveBeenCalled();
+ });
+
+ it('dedupes identical critical errors within the window', async () => {
+ emitCriticalError();
+ emitCriticalError();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(cos.addTask).toHaveBeenCalledTimes(1);
+ });
+});