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(cos): per-repo gh auth + recovery tasks no longer stall improvement queue

Adam Eivy8a9af42bacd2
diff --git a/server/services/agentCompletion.js b/server/services/agentCompletion.js
index 4c3d3f3dcf..636266cc7e 100644
--- a/server/services/agentCompletion.js
+++ b/server/services/agentCompletion.js
@@ -10,6 +10,7 @@ import { getConfig } from './cos.js';
import { startAppCooldown, markAppReviewCompleted } from './appActivity.js';
import { emitLog } from './cosEvents.js';
import { extractAndStoreMemories } from './memoryExtractor.js';
+import { isRecoveryTask } from './recoveryTasks.js';
/**
* Process post-completion tasks: memory extraction and app cooldown.
@@ -36,6 +37,15 @@ export async function processAgentCompletion(agentId, task, success, outputBuffe
// Handle app cooldown
const appId = task.metadata?.app;
if (appId) {
+ // Recovery tasks are administrative — they retry a failed merge/PR for an
+ // already-reviewed agent run. Bumping the cooldown for them pushes sibling
+ // improvement tasks for the same app another full window into the future,
+ // which is exactly the queue-stalling we're trying to prevent.
+ if (isRecoveryTask(task)) {
+ emitLog('info', `Skipping cooldown bump for recovery task on app ${appId}`, { appId, taskId: task.id });
+ return;
+ }
+
const config = await getConfig();
const cooldownMs = config.appReviewCooldownMs || 3600000;
diff --git a/server/services/agentCompletion.test.js b/server/services/agentCompletion.test.js
new file mode 100644
index 0000000000..dda8fc787e
--- /dev/null
+++ b/server/services/agentCompletion.test.js
@@ -0,0 +1,89 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock dependencies before importing the module under test
+vi.mock('./cosAgents.js', () => ({
+ updateAgent: vi.fn().mockResolvedValue(undefined)
+}));
+vi.mock('./cos.js', () => ({
+ getConfig: vi.fn().mockResolvedValue({ appReviewCooldownMs: 1800000 })
+}));
+vi.mock('./appActivity.js', () => ({
+ startAppCooldown: vi.fn().mockResolvedValue(undefined),
+ markAppReviewCompleted: vi.fn().mockResolvedValue(undefined)
+}));
+vi.mock('./cosEvents.js', () => ({
+ emitLog: vi.fn()
+}));
+vi.mock('./memoryExtractor.js', () => ({
+ extractAndStoreMemories: vi.fn().mockResolvedValue({ created: 0, pendingApproval: 0 })
+}));
+
+import { processAgentCompletion } from './agentCompletion.js';
+import * as appActivity from './appActivity.js';
+
+describe('processAgentCompletion - cooldown handling for recovery tasks', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('bumps cooldown for normal app improvement tasks', async () => {
+ const task = {
+ id: 'sys-abc',
+ description: '[App Improvement: PortOS] Code Quality Review',
+ metadata: { app: 'portos-default' }
+ };
+ await processAgentCompletion('agent-1', task, true, 'output text...');
+
+ expect(appActivity.markAppReviewCompleted).toHaveBeenCalledWith('portos-default', 1, 1);
+ expect(appActivity.startAppCooldown).toHaveBeenCalledWith('portos-default', 1800000);
+ });
+
+ it('does NOT bump cooldown when task.metadata.isRecovery is true', async () => {
+ const task = {
+ id: 'task-xyz',
+ description: '[Recovery] Investigate and retry failed PR for branch foo',
+ metadata: { app: 'portos-default', isRecovery: true }
+ };
+ await processAgentCompletion('agent-2', task, true, 'output');
+
+ expect(appActivity.markAppReviewCompleted).not.toHaveBeenCalled();
+ expect(appActivity.startAppCooldown).not.toHaveBeenCalled();
+ });
+
+ it('does NOT bump cooldown when description starts with [Recovery] (back-compat)', async () => {
+ // Existing in-flight tasks created before isRecovery metadata was added
+ const task = {
+ id: 'task-legacy',
+ description: '[Recovery] Resolve merge conflict and clean up stale branch foo in BarnHub',
+ metadata: { app: 'barnhub-app-id' } // no isRecovery flag
+ };
+ await processAgentCompletion('agent-3', task, true, 'output');
+
+ expect(appActivity.markAppReviewCompleted).not.toHaveBeenCalled();
+ expect(appActivity.startAppCooldown).not.toHaveBeenCalled();
+ });
+
+ it('still bumps cooldown when description merely mentions recovery (not at start)', async () => {
+ const task = {
+ id: 'sys-mentions',
+ description: 'Improve test coverage and document the [Recovery] flow',
+ metadata: { app: 'some-app' }
+ };
+ await processAgentCompletion('agent-4', task, true, 'output');
+
+ expect(appActivity.markAppReviewCompleted).toHaveBeenCalled();
+ expect(appActivity.startAppCooldown).toHaveBeenCalled();
+ });
+
+ it('skips cooldown logic entirely for tasks without an app', async () => {
+ const task = {
+ id: 'task-no-app',
+ description: 'Generic user task',
+ metadata: {}
+ };
+ await processAgentCompletion('agent-5', task, true, 'output');
+
+ expect(appActivity.markAppReviewCompleted).not.toHaveBeenCalled();
+ expect(appActivity.startAppCooldown).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index b4b0332433..21ef13e72c 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -25,6 +25,7 @@ import { detectConflicts } from './taskConflict.js';
import { createWorktree, removeWorktree } from './worktreeManager.js';
import * as jiraService from './jira.js';
import * as git from './git.js';
+import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';
import { analyzeAgentFailure, resolveFailedTaskUpdate } from './agentErrorAnalysis.js';
import { createAgentRun, completeAgentRun, checkForTaskCommit } from './agentRunTracking.js';
import { buildAgentPrompt, getAppWorkspace, getAppDataForTask, createJiraTicketForTask } from './agentPromptBuilder.js';
@@ -1181,12 +1182,17 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, d
return warnings;
}
- emitLog('error', `🌳 PR creation failed for ${worktreeBranch}: ${reason}`, { agentId, branchName: worktreeBranch });
+ const authHint = prResult?.ghAccount
+ ? ` (gh authed as ${prResult.ghAccount} for ${prResult.ghOwner})`
+ : prResult?.ghOwner
+ ? ` (no gh account matches owner ${prResult.ghOwner} — fell back to active user)`
+ : '';
+ emitLog('error', `🌳 PR creation failed for ${worktreeBranch}${authHint}: ${reason}`, { agentId, branchName: worktreeBranch, ghAccount: prResult?.ghAccount, ghOwner: prResult?.ghOwner });
warnings.push(`PR creation failed for branch ${worktreeBranch}: ${reason}. Worktree preserved for manual PR creation.`);
return warnings;
}
- emitLog('success', `🌳 Created PR: ${prResult.url}`, { agentId, branchName: worktreeBranch });
+ emitLog('success', `🌳 Created PR: ${prResult.url} (gh authed as ${prResult.ghAccount || 'active user'})`, { agentId, branchName: worktreeBranch, ghAccount: prResult.ghAccount, ghOwner: prResult.ghOwner });
const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {
emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });
@@ -1237,9 +1243,10 @@ export async function spawnMergeRecoveryTask(cleanupWarnings, agentId, task, app
if (isMergeFail) {
addTask({
- description: `[Recovery] Resolve merge conflict and clean up stale branch ${staleBranch} in ${appName}`,
+ description: `${RECOVERY_TASK_PREFIX} Resolve merge conflict and clean up stale branch ${staleBranch} in ${appName}`,
priority: 'HIGH',
app: appId,
+ isRecovery: true,
context: `An agent failed to auto-merge branch "${staleBranch}" back to main in ${sourceWorkspace}. `
+ `Resolve this by: (1) checking if the branch's changes are already on main (superseded by other commits), `
+ `and if so, delete the branch with "git branch -D ${staleBranch}"; `
@@ -1254,9 +1261,10 @@ export async function spawnMergeRecoveryTask(cleanupWarnings, agentId, task, app
} else {
// PR creation failed — spawn an agent to investigate and retry
addTask({
- description: `[Recovery] Investigate and retry failed PR for branch ${staleBranch} in ${appName}`,
+ description: `${RECOVERY_TASK_PREFIX} Investigate and retry failed PR for branch ${staleBranch} in ${appName}`,
priority: 'HIGH',
app: appId,
+ isRecovery: true,
context: `An agent pushed branch "${staleBranch}" to ${sourceWorkspace} but automated PR creation failed. `
+ `Investigate by: (1) checking if a PR already exists for this branch: "gh pr list --head ${staleBranch}"; `
+ `(2) if no PR exists, review the branch changes and create one: "gh pr create --head ${staleBranch} --base main --title '...' --body '...'"; `
diff --git a/server/services/cos.js b/server/services/cos.js
index 897eecce77..564749bf6e 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -966,6 +966,10 @@ async function queueEligibleImprovementTasks(state, cosTaskData) {
// Also skip task types where a user-terminated blocked task exists (user intentionally killed it)
const existingTasks = cosTaskData.tasks || [];
const existingTaskTypes = new Set();
+ // Apps that already have *any* pending/in_progress improvement task. We cap each
+ // app at one queued improvement at a time to avoid a fan-out where multiple
+ // improvement types pile up faster than the per-app cooldown can drain them.
+ const appsWithPendingImprovement = new Set();
for (const task of existingTasks) {
const isActive = task.status === 'pending' || task.status === 'in_progress';
@@ -979,6 +983,9 @@ async function queueEligibleImprovementTasks(state, cosTaskData) {
existingTaskTypes.add(appId ? `app:${appId}:${analysisType}` : analysisType);
}
}
+ if (isActive && task.metadata?.app && !task.metadata?.isRecovery) {
+ appsWithPendingImprovement.add(task.metadata.app);
+ }
}
let queued = 0;
@@ -986,6 +993,14 @@ async function queueEligibleImprovementTasks(state, cosTaskData) {
// Queue eligible improvement tasks for all managed apps (including PortOS)
const apps = await getActiveApps().catch(() => []);
for (const app of apps) {
+ // One pending improvement per app at a time — sibling types must wait
+ // until the current task drains, otherwise they queue faster than they
+ // can run (per-project concurrency limit + cooldown after each completion).
+ if (appsWithPendingImprovement.has(app.id)) {
+ emitLog('debug', `App ${app.name} already has a pending improvement task — skipping queue`);
+ continue;
+ }
+
// Check if app is on cooldown
const onCooldown = await isAppOnCooldown(app.id, state.config.appReviewCooldownMs);
if (onCooldown) continue;
@@ -1019,6 +1034,7 @@ async function queueEligibleImprovementTasks(state, cosTaskData) {
emitLog('info', `Queued improvement task: ${nextType} for ${app.name}`, { taskId: newTask.id, appId: app.id });
existingTaskTypes.add(taskKey);
+ appsWithPendingImprovement.add(app.id);
queued++;
// Only queue one task per app per evaluation to avoid flooding
@@ -2142,6 +2158,7 @@ export async function addTask(taskData, taskType = 'user', { raw = false } = {})
if (taskData.model) metadata.model = taskData.model;
if (taskData.provider) metadata.provider = taskData.provider;
if (taskData.app) metadata.app = taskData.app;
+ if (taskData.isRecovery === true) metadata.isRecovery = true;
if (taskData.createJiraTicket) metadata.createJiraTicket = true;
// Boolean flags: persist both true and false so users can explicitly override defaults.
// The string round-trip ('false' from TASKS.md) is handled by isTruthyMeta/isFalsyMeta.
diff --git a/server/services/git.js b/server/services/git.js
index 4004b4f6e3..a708c5281a 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -323,8 +323,85 @@ export async function checkout(dir, branchName) {
return { success: true, branch: branchName };
}
+/**
+ * Parse the GitHub owner login from a remote URL.
+ * Returns null for non-github.com remotes or unparseable inputs.
+ * Examples:
+ * [email protected]:atomantic/PortOS.git → 'atomantic'
+ * https://github.com/atomantic/PortOS → 'atomantic'
+ */
+export function parseGitHubOwnerFromRemote(url) {
+ if (!url) return null;
+ const ssh = url.match(/^git@github\.com:([^/]+)\/[^/]+?(?:\.git)?$/);
+ if (ssh) return ssh[1];
+ const https = url.match(/^https?:\/\/github\.com\/([^/]+)\/[^/]+?(?:\.git)?$/);
+ if (https) return https[1];
+ return null;
+}
+
+/**
+ * Pick which logged-in gh account should auth against a repo owned by `ownerLogin`.
+ * Case-insensitive exact match; returns null if no logged-in account matches the owner.
+ */
+export function pickGhAccountForOwner(ownerLogin, availableAccounts) {
+ if (!ownerLogin || !availableAccounts?.length) return null;
+ const lower = ownerLogin.toLowerCase();
+ return availableAccounts.find(a => a.toLowerCase() === lower) || null;
+}
+
+function spawnGh(args, options = {}) {
+ return new Promise((resolve) => {
+ const child = spawn('gh', args, { shell: false, windowsHide: true, ...options });
+ let stdout = '', stderr = '';
+ child.stdout.on('data', (d) => { stdout += d.toString(); });
+ child.stderr.on('data', (d) => { stderr += d.toString(); });
+ child.on('close', (code) => resolve({ code, stdout, stderr }));
+ child.on('error', () => resolve({ code: -1, stdout: '', stderr: '' }));
+ });
+}
+
+async function listGhAccounts() {
+ const { stdout, stderr } = await spawnGh(['auth', 'status', '-h', 'github.com']);
+ // gh writes status to stderr in older versions, stdout in newer — search both.
+ const text = `${stdout}\n${stderr}`;
+ const accounts = [];
+ const re = /Logged in to github\.com account (\S+)/g;
+ let m;
+ while ((m = re.exec(text))) accounts.push(m[1]);
+ return accounts;
+}
+
+async function getGhTokenForAccount(login) {
+ const { code, stdout } = await spawnGh(['auth', 'token', '-u', login, '-h', 'github.com']);
+ return code === 0 ? stdout.trim() : null;
+}
+
+/**
+ * Resolve the right gh auth env for a given repo directory.
+ * Auto-detects the owner from `origin`, picks the matching logged-in gh account,
+ * and returns an env override pinning `GH_TOKEN` so gh doesn't depend on
+ * `~/.config/gh/hosts.yml`'s mutable `user:` field.
+ * Falls back to ambient env when no match is possible.
+ */
+export async function resolveGhEnvForRepo(dir) {
+ const remote = await execGitSafe(['remote', 'get-url', 'origin'], dir);
+ const owner = parseGitHubOwnerFromRemote(remote.stdout?.trim());
+ if (!owner) return { env: process.env, owner: null, account: null };
+
+ const accounts = await listGhAccounts();
+ const account = pickGhAccountForOwner(owner, accounts);
+ if (!account) return { env: process.env, owner, account: null };
+
+ const token = await getGhTokenForAccount(account);
+ if (!token) return { env: process.env, owner, account };
+
+ return { env: { ...process.env, GH_TOKEN: token }, owner, account };
+}
+
/**
* Create a pull request using the `gh` CLI.
+ * Auto-pins gh identity to the account whose login matches the repo's owner
+ * (so PR creation works correctly when multiple gh accounts are logged in).
* Fails gracefully if `gh` is not installed.
* @param {string} dir - Working directory (repo root)
* @param {object} options - PR options
@@ -332,12 +409,14 @@ export async function checkout(dir, branchName) {
* @param {string} options.body - PR description
* @param {string} options.base - Base branch (target)
* @param {string} options.head - Head branch (source)
- * @returns {Promise<{success: boolean, url?: string, error?: string}>}
+ * @returns {Promise<{success: boolean, url?: string, error?: string, ghAccount?: string|null, ghOwner?: string|null}>}
*/
export async function createPR(dir, { title, body, base, head }) {
+ const { env, owner, account } = await resolveGhEnvForRepo(dir);
+
return new Promise((resolve) => {
const args = ['pr', 'create', '--title', title, '--body', body || '', '--base', base, '--head', head];
- const child = spawn('gh', args, { cwd: dir, shell: false, windowsHide: true });
+ const child = spawn('gh', args, { cwd: dir, env, shell: false, windowsHide: true });
let stdout = '';
let stderr = '';
@@ -348,14 +427,14 @@ export async function createPR(dir, { title, body, base, head }) {
child.on('close', (code) => {
if (code === 0) {
const url = stdout.trim();
- resolve({ success: true, url });
+ resolve({ success: true, url, ghAccount: account, ghOwner: owner });
} else {
- resolve({ success: false, error: stderr || `gh exited with code ${code}` });
+ resolve({ success: false, error: stderr || `gh exited with code ${code}`, ghAccount: account, ghOwner: owner });
}
});
child.on('error', (err) => {
- resolve({ success: false, error: `gh not available: ${err.message}` });
+ resolve({ success: false, error: `gh not available: ${err.message}`, ghAccount: account, ghOwner: owner });
});
});
}
diff --git a/server/services/git.test.js b/server/services/git.test.js
index aab0178cfd..cc609d28fa 100644
--- a/server/services/git.test.js
+++ b/server/services/git.test.js
@@ -1,5 +1,54 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { createPR, extractAgentSummary } from './git.js';
+import { createPR, extractAgentSummary, parseGitHubOwnerFromRemote, pickGhAccountForOwner } from './git.js';
+
+describe('parseGitHubOwnerFromRemote', () => {
+ it('parses SSH urls (with and without .git suffix)', () => {
+ expect(parseGitHubOwnerFromRemote('[email protected]:atomantic/PortOS.git')).toBe('atomantic');
+ expect(parseGitHubOwnerFromRemote('[email protected]:atomantic/PortOS')).toBe('atomantic');
+ });
+
+ it('parses HTTPS urls (with and without .git suffix)', () => {
+ expect(parseGitHubOwnerFromRemote('https://github.com/atomantic/PortOS.git')).toBe('atomantic');
+ expect(parseGitHubOwnerFromRemote('https://github.com/atomantic/PortOS')).toBe('atomantic');
+ expect(parseGitHubOwnerFromRemote('http://github.com/atomantic/PortOS')).toBe('atomantic');
+ });
+
+ it('returns null for non-github hosts', () => {
+ expect(parseGitHubOwnerFromRemote('[email protected]:foo/bar.git')).toBeNull();
+ expect(parseGitHubOwnerFromRemote('https://bitbucket.org/foo/bar')).toBeNull();
+ });
+
+ it('returns null for empty or null input', () => {
+ expect(parseGitHubOwnerFromRemote('')).toBeNull();
+ expect(parseGitHubOwnerFromRemote(null)).toBeNull();
+ expect(parseGitHubOwnerFromRemote(undefined)).toBeNull();
+ });
+
+ it('returns null for malformed urls', () => {
+ expect(parseGitHubOwnerFromRemote('github.com:atomantic/PortOS')).toBeNull();
+ expect(parseGitHubOwnerFromRemote('[email protected]:noslash')).toBeNull();
+ });
+});
+
+describe('pickGhAccountForOwner', () => {
+ it('matches owner to account case-insensitively', () => {
+ expect(pickGhAccountForOwner('atomantic', ['atomantic', 'ClawedCode'])).toBe('atomantic');
+ expect(pickGhAccountForOwner('Atomantic', ['atomantic', 'ClawedCode'])).toBe('atomantic');
+ expect(pickGhAccountForOwner('clawedcode', ['atomantic', 'ClawedCode'])).toBe('ClawedCode');
+ expect(pickGhAccountForOwner('CLAWEDCODE', ['atomantic', 'ClawedCode'])).toBe('ClawedCode');
+ });
+
+ it('returns null when no account matches the owner', () => {
+ expect(pickGhAccountForOwner('someorg', ['atomantic', 'ClawedCode'])).toBeNull();
+ });
+
+ it('returns null with empty inputs', () => {
+ expect(pickGhAccountForOwner('atomantic', [])).toBeNull();
+ expect(pickGhAccountForOwner('atomantic', null)).toBeNull();
+ expect(pickGhAccountForOwner(null, ['atomantic'])).toBeNull();
+ expect(pickGhAccountForOwner('', ['atomantic'])).toBeNull();
+ });
+});
describe('createPR', () => {
beforeEach(() => {
diff --git a/server/services/recoveryTasks.js b/server/services/recoveryTasks.js
new file mode 100644
index 0000000000..972a431547
--- /dev/null
+++ b/server/services/recoveryTasks.js
@@ -0,0 +1,13 @@
+/**
+ * Shared markers for "recovery" tasks — administrative agents auto-spawned
+ * to retry a failed merge or PR creation. Centralized so detection and
+ * creation stay in sync.
+ */
+
+export const RECOVERY_TASK_PREFIX = '[Recovery]';
+
+export function isRecoveryTask(task) {
+ if (!task) return false;
+ if (task.metadata?.isRecovery === true) return true;
+ return typeof task.description === 'string' && task.description.startsWith(RECOVERY_TASK_PREFIX);
+}