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
fix: move automated recovery warnings into brain threads
[._.]/ Adam Eivyec9640e77544
diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.jsindex 0aeb441f5b..09e59a1c45 100644--- a/server/services/agentCompletionCleanup.js+++ b/server/services/agentCompletionCleanup.js@@ -43,6 +43,7 @@ import { cleanupAgentWorktree, spawnMergeRecoveryTask, releaseRetryHold } from 'import { PR_CREATION, resolvePrCompletion, resolvePrCreation } from '../lib/prDisposition.js';import { resolvePrOpenedBy, PR_OPENED_BY } from '../lib/slashdoInvocation.js';import { isPublicReviewRestrictedProfile, publicReviewPostureForProfile } from '../lib/agentExecutionProfiles.js';+import { ensureTaskThread } from './brainTaskThreads.js';const ROOT_DIR = PATHS.root;@@ -540,20 +541,17 @@ async function reportWorktreeCleanupWarnings({ agentId, task, cleanupWarnings })const currentAgent = await getAgentForResult(agentId).catch(() => null);await updateAgent(agentId, { result: { ...currentAgent?.result, warnings: cleanupWarnings } });- const { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');const appName = task?.metadata?.appName || task?.metadata?.app || 'PortOS';- await addNotification({- type: NOTIFICATION_TYPES.AGENT_WARNING,- title: `Agent cleanup issue: ${appName}`,- description: cleanupWarnings.join('\n'),- priority: PRIORITY_LEVELS.HIGH,- link: '/cos/agents',- metadata: { agentId, taskId: task?.id, warnings: cleanupWarnings }+ void spawnMergeRecoveryTask(cleanupWarnings, agentId, task, appName, currentAgent?.metadata?.sourceWorkspace).then(recoveryTask => {+ const recoveryTaskId = recoveryTask?.id || recoveryTask;+ return ensureTaskThread({+ taskId: recoveryTaskId,+ title: `Agent cleanup issue: ${appName}`,+ nextAction: 'Let the recovery task resolve the cleanup warning, then verify the worktree.',+ notes: cleanupWarnings.join('\n'),+ priority: 'high',+ });}).catch(err => {- emitLog('warn', `Failed to create cleanup warning notification: ${err.message}`, { agentId });- });-- void spawnMergeRecoveryTask(cleanupWarnings, agentId, task, appName, currentAgent?.metadata?.sourceWorkspace).catch(err => {emitLog('warn', `Failed to spawn merge recovery task: ${err.message}`, { agentId, taskId: task?.id });});}diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.jsindex f3398abefd..e4578e0af1 100644--- a/server/services/agentCompletionCleanup.test.js+++ b/server/services/agentCompletionCleanup.test.js@@ -27,7 +27,7 @@ vi.mock('./git.js', () => ({ push: vi.fn(), getRepoBranches: vi.fn(), generatePRvi.mock('./codeReview.js', () => ({ resolveReviewLoopOptions: vi.fn().mockResolvedValue({}) }));vi.mock('./agentWorktreeCleanup.js', () => ({cleanupAgentWorktree: vi.fn().mockResolvedValue([]),- spawnMergeRecoveryTask: vi.fn().mockResolvedValue({}),+ spawnMergeRecoveryTask: vi.fn().mockResolvedValue({ id: 'recovery-1' }),releaseRetryHold: vi.fn().mockResolvedValue({}),}));vi.mock('./notifications.js', () => ({@@ -35,6 +35,7 @@ vi.mock('./notifications.js', () => ({NOTIFICATION_TYPES: { PLAN_QUESTION: 'plan_question', AGENT_WARNING: 'agent_warning' },PRIORITY_LEVELS: { MEDIUM: 'medium', HIGH: 'high' },}));+vi.mock('./brainTaskThreads.js', () => ({ ensureTaskThread: vi.fn().mockResolvedValue({}) }));vi.mock('./creativeDirector/completionHook.js', () => ({ handleCreativeDirectorCompletion: vi.fn().mockResolvedValue({}) }));vi.mock('./taskPromptService.js', () => ({ getStagePrompt: vi.fn().mockResolvedValue('do stage work in {appName}') }));@@ -47,6 +48,7 @@ import { promptOpensOwnPr } from './promptSections/completion.js';import * as git from './git.js';import * as jira from './jira.js';import { addNotification } from './notifications.js';+import { ensureTaskThread } from './brainTaskThreads.js';import { updateAgent } from './cosAgentLifecycle.js';import { handleCreativeDirectorCompletion } from './creativeDirector/completionHook.js';@@ -665,9 +667,9 @@ describe.each(['runner', 'spawner'])('%s completion side effects', (path) => {cleanupAgentWorktree.mockResolvedValueOnce(warnings);await complete({ appName: 'Example App' });expect(updateAgent).toHaveBeenCalledWith('a1', { result: { success: true, warnings } });- expect(addNotification).toHaveBeenCalledWith(expect.objectContaining({- type: 'agent_warning', title: 'Agent cleanup issue: Example App',- description: warnings[0], priority: 'high', metadata: { agentId: 'a1', taskId: 't', warnings },+ expect(addNotification).not.toHaveBeenCalled();+ expect(ensureTaskThread).toHaveBeenCalledWith(expect.objectContaining({+ title: 'Agent cleanup issue: Example App', notes: warnings[0], priority: 'high',}));expect(spawnMergeRecoveryTask).toHaveBeenCalledWith(warnings, 'a1', expect.objectContaining({ id: 't' }), 'Example App', '/example/repo');});diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.jsindex 2866702c7c..a70915c53d 100644--- a/server/services/agentRepoStateVerification.js+++ b/server/services/agentRepoStateVerification.js@@ -45,6 +45,7 @@ import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';import { resolveTaskTargetBranch } from '../lib/taskTargetBranch.js';import { leavesPrForHuman, resolvePrCompletion } from '../lib/prDisposition.js';import { probePrForBranch } from './prProbe.js';+import { ensureTaskThread } from './brainTaskThreads.js';import {REPO_STATE_ISSUES,REPO_STATE_SKIPS,@@ -320,7 +321,15 @@ export async function verifyAgentRepoState({ agentId, task, agentState, success,return null;});- await notifyRepoStateDivergence({ agentId, task, branchName, issues, appId }).catch(() => {});+ if (recoveryTaskId) {+ await ensureTaskThread({+ taskId: recoveryTaskId,+ title: `${RECOVERY_TASK_PREFIX} Finish incomplete cleanup for branch ${branchName}`,+ nextAction: 'Let the recovery task finish, then verify the branch and worktree are clean.',+ notes: issues.map(issue => issue.message).join('\n'),+ priority: 'high',+ }).catch(err => emitLog('warn', `Failed to create repo-state Brain thread for ${branchName}: ${err.message}`, { agentId, branchName }));+ }return { verified: false, skipReason: null, issues, observed, recoveryTaskId };}@@ -405,25 +414,3 @@ async function fileRepoStateRecoveryTask({ agentId, task, branchName, sourceWorkemitLog('info', `🔧 Filed repo-state recovery task for ${branchName} (${issues.length} issue(s))`, { agentId, branchName, appName });return created?.id || null;}--/**- * Surface the divergence alongside the auto-filed task, so a repeatedly-diverging- * app is visible rather than only inferable from a growing recovery queue.- *- * Deduped on the branch (the way `orphanedPrNotifier` dedupes on the PR url) —- * `addTask` collapses repeats on its side, and a notification card per audit- * would otherwise stack for a branch nothing manages to fix.- */-async function notifyRepoStateDivergence({ agentId, task, branchName, issues, appId }) {- const { addNotification, exists, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');- if (await exists(NOTIFICATION_TYPES.AGENT_WARNING, 'branchName', branchName)) return;- const appName = task?.metadata?.appName || appId || 'PortOS';- await addNotification({- type: NOTIFICATION_TYPES.AGENT_WARNING,- title: `Repo state not clean after agent: ${appName}`,- description: `Branch ${branchName}\n${issues.map(i => `• ${i.message}`).join('\n')}`,- priority: PRIORITY_LEVELS.HIGH,- link: '/cos/agents',- metadata: { agentId, taskId: task?.id, branchName, issues: issues.map(i => i.code) },- });-}diff --git a/server/services/agentRepoStateVerification.test.js b/server/services/agentRepoStateVerification.test.jsindex ca9f383613..f7119d9fdf 100644--- a/server/services/agentRepoStateVerification.test.js+++ b/server/services/agentRepoStateVerification.test.js@@ -45,11 +45,13 @@ vi.mock('./notifications.js', () => ({NOTIFICATION_TYPES: { AGENT_WARNING: 'agent_warning' },PRIORITY_LEVELS: { HIGH: 'high' },}));+vi.mock('./brainTaskThreads.js', () => ({ ensureTaskThread: vi.fn().mockResolvedValue({}) }));vi.mock('../lib/execGit.js', () => ({ execGit: vi.fn() }));vi.mock('fs', () => ({ existsSync: vi.fn().mockReturnValue(false) }));import { verifyAgentRepoState, REPO_STATE_REMEDIATIONS } from './agentRepoStateVerification.js';import { addTask, getAllTasks } from './cos.js';+import { ensureTaskThread } from './brainTaskThreads.js';import { listWorktrees } from './worktreeManager.js';import { listRemoteHeads } from './branchReconcile.js';import { hasBranchMergeEvidence, resolveForgeForRepo } from './git.js';@@ -162,7 +164,9 @@ describe('verifyAgentRepoState — divergent runs', () => {expect(payload.context).toContain(`git worktree remove ${WORKTREE}`);expect(payload.context).toContain(`git branch -d ${BRANCH}`);expect(payload.context).toContain(`touch ONLY ${BRANCH}`);- expect(addNotification).toHaveBeenCalledTimes(1);+ expect(ensureTaskThread).toHaveBeenCalledWith(expect.objectContaining({+ taskId: 'task-recovery-1', priority: 'high',+ }));});it('finds a worktree git still tracks even when the directory is gone', async () => {@@ -198,14 +202,11 @@ describe('verifyAgentRepoState — divergent runs', () => {expect(result.recoveryTaskId).toBeNull();});- it('does not stack a second notification for a branch already flagged', async () => {+ it('still ensures the existing recovery task has a Brain thread', async () => {existsSync.mockReturnValue(true);- notificationExists.mockResolvedValue(true);-await run({ prExpected: false });- expect(notificationExists).toHaveBeenCalledWith('agent_warning', 'branchName', BRANCH);- expect(addNotification).not.toHaveBeenCalled();+ expect(ensureTaskThread).toHaveBeenCalledWith(expect.objectContaining({ taskId: 'task-recovery-1' }));});});diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex 8e8970461d..09de6b7ecd 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -1184,7 +1184,7 @@ export async function spawnMergeRecoveryTask(cleanupWarnings, agentId, task, appif (isMergeFail) {const defaultBr = await git.getDefaultBranch(sourceWorkspace).catch(() => null) || 'main';- addTask({+ const recoveryTask = await addTask({description: `${RECOVERY_TASK_PREFIX} Resolve merge conflict and clean up stale branch ${staleBranch} in ${appName}`,priority: 'HIGH',app: appId,@@ -1198,8 +1198,10 @@ export async function spawnMergeRecoveryTask(cleanupWarnings, agentId, task, appuseWorktree: false,}, 'user').catch(err => {emitLog('warn', `Failed to create merge recovery task: ${err.message}`, { agentId, staleBranch });+ return null;});emitLog('info', `🔧 Auto-created merge recovery task for stale branch ${staleBranch}`, { agentId, appName });+ return recoveryTask;} else {// PR/MR creation failed — spawn an agent to investigate and retry. Pick gh vs// glab based on the repo's forge so the recovery agent gets commands that@@ -1218,7 +1220,7 @@ export async function spawnMergeRecoveryTask(cleanupWarnings, agentId, task, app? `glab mr create --source-branch ${staleBranch} --target-branch ${targetBase} --title '...' --description '...'`: `gh pr create --head ${staleBranch} --base ${targetBase} --title '...' --body '...'`;- addTask({+ const recoveryTask = await addTask({description: `${RECOVERY_TASK_PREFIX} Investigate and retry failed ${reqWord} for branch ${staleBranch} in ${appName}`,priority: 'HIGH',app: appId,@@ -1231,7 +1233,9 @@ export async function spawnMergeRecoveryTask(cleanupWarnings, agentId, task, appuseWorktree: false,}, 'user').catch(err => {emitLog('warn', `Failed to create ${reqWord} recovery task: ${err.message}`, { agentId, staleBranch });+ return null;});emitLog('info', `🔧 Auto-created ${reqWord} recovery task for branch ${staleBranch}`, { agentId, appName, cli });+ return recoveryTask;}}diff --git a/server/services/brainTaskThreads.js b/server/services/brainTaskThreads.jsnew file mode 100644index 0000000000..5538e7708c--- /dev/null+++ b/server/services/brainTaskThreads.js@@ -0,0 +1,22 @@+/** Bridge CoS tasks into the Brain bullet journal without creating noise. */++import * as brainStorage from './brainStorage.js';++const TASK_REF_KIND = 'cos.task';++export async function ensureTaskThread({ taskId, title, nextAction, notes, priority = 'normal' }) {+ if (!taskId || !title) return null;+ const threads = await brainStorage.getThreads();+ const existing = threads.find(thread => thread.status !== 'archived'+ && thread.refs?.some(ref => ref?.kind === TASK_REF_KIND && ref?.id === taskId));+ if (existing) return existing;+ return brainStorage.createThread({+ title,+ status: 'open',+ priority,+ nextAction: nextAction || 'Review the task in CoS',+ notes: notes || '',+ refs: [{ kind: TASK_REF_KIND, id: taskId, label: title }],+ source: 'cos',+ });+}diff --git a/server/services/orphanedPrNotifier.js b/server/services/orphanedPrNotifier.jsindex 4d23d1e71b..fde89a0cc0 100644--- a/server/services/orphanedPrNotifier.js+++ b/server/services/orphanedPrNotifier.js@@ -25,6 +25,7 @@import { addNotification, exists as notificationExists, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';import { TIMED_COOLDOWN_BLOCKED_CATEGORIES } from '../lib/taskBlockCategories.js';+import { ensureTaskThread } from './brainTaskThreads.js';/*** Raise a notification when a task that was going to merge a PR gets blocked.@@ -63,5 +64,12 @@ export async function notifyIfPrLeftOrphaned({ task, previousStatus } = {}) {link: prUrl,metadata: { taskId: task.id, prUrl, prBranch: task.metadata?.reviewLoopPRBranch },});+ await ensureTaskThread({+ taskId: task.id,+ title: 'PR left open: its merge follow-up was blocked',+ nextAction: 'Fix the blocked merge follow-up or land the pull request manually.',+ notes: `${prUrl}\n${why}`,+ priority: 'high',+ });return true;}diff --git a/server/services/orphanedPrNotifier.test.js b/server/services/orphanedPrNotifier.test.jsindex 6e4d69733a..f0d9fa1dc0 100644--- a/server/services/orphanedPrNotifier.test.js+++ b/server/services/orphanedPrNotifier.test.js@@ -14,9 +14,11 @@ vi.mock('./notifications.js', () => ({NOTIFICATION_TYPES: { AGENT_WARNING: 'agent_warning' },PRIORITY_LEVELS: { HIGH: 'high' },}));+vi.mock('./brainTaskThreads.js', () => ({ ensureTaskThread: vi.fn().mockResolvedValue({}) }));import { notifyIfPrLeftOrphaned } from './orphanedPrNotifier.js';import { addNotification, exists } from './notifications.js';+import { ensureTaskThread } from './brainTaskThreads.js';const PR_URL = 'https://github.com/example-org/example-repo/pull/9';@@ -53,6 +55,7 @@ describe('notifyIfPrLeftOrphaned', () => {}));// The block's own explanation is what tells the user how to unstick it.expect(addNotification.mock.calls[0][0].description).toContain("didn't resolve");+ expect(ensureTaskThread).toHaveBeenCalledWith(expect.objectContaining({ taskId: 'sys-rl-1', priority: 'high' }));});// ~12 sites set `status: 'blocked'`; a follow-up blocked by max-retries or a