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
feat(cos): name the apps holding leftover branches in the idle-branch insight
Adam Eivy904b43677e1a
diff --git a/client/src/components/cos/ActionableInsightsBanner.jsx b/client/src/components/cos/ActionableInsightsBanner.jsxindex 0eb5451281..47809caff1 100644--- a/client/src/components/cos/ActionableInsightsBanner.jsx+++ b/client/src/components/cos/ActionableInsightsBanner.jsx@@ -13,10 +13,22 @@ import {ChevronDown,X,Zap,- Unlock+ Unlock,+ GitBranch,+ Play} from 'lucide-react';import * as api from '../../services/api';import ProvenanceChip from '../ui/ProvenanceChip';+import { timeAgo } from '../../utils/formatters';++// One app's leftover branches as a single line — "4 branches · 3 NEEDS_PR · 1+// MERGED". Busiest state first so the row reads the same across refreshes.+export const formatBranchSummary = ({ leftoverCount, states }) => [+ `${leftoverCount} branch${leftoverCount === 1 ? '' : 'es'}`,+ ...Object.entries(states || {})+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))+ .map(([state, count]) => `${count} ${state}`),+].join(' · ');// The chip answers "why am I seeing this?" the same way the taste-identity and// health surfaces do — but the honesty distinction the feature exists to enforce@@ -101,8 +113,19 @@ export default function ActionableInsightsBanner({ insights, onTaskUnblocked, onconst [dismissed, setDismissed] = useState([]);const [expanded, setExpanded] = useState({});const [approvingTaskId, setApprovingTaskId] = useState(null);+ const [reconcilingAppId, setReconcilingAppId] = useState(null);+ const [queuedAppIds, setQueuedAppIds] = useState([]);const navigate = useNavigate();+ // The insight only clears once branch-reconcile has actually RUN, so the card+ // outlives the request — the button has to say it already went out, or the+ // operator queues the same app again on every glance.+ const reconcileButton = (app) => (+ reconcilingAppId === app.appId ? { label: 'Queuing…', disabled: true }+ : queuedAppIds.includes(app.appId) ? { label: 'Queued', disabled: true }+ : { label: 'Run Now', disabled: false }+ );+const handleDismiss = (type) => {setDismissed(prev => [...prev, type]);};@@ -117,6 +140,17 @@ export default function ActionableInsightsBanner({ insights, onTaskUnblocked, onsetExpanded(prev => ({ ...prev, [insight.type]: !prev[insight.type] }));return;}+ // Leftover branches: one app can be reconciled straight from the banner;+ // several have to be named first, because "Run Now" is per-app and the+ // operator can't pick one they were never shown.+ if (insight.type === 'leftover-branches' && insight.apps?.length > 0) {+ if (insight.apps.length === 1) {+ handleRunReconcile(insight.apps[0]);+ return;+ }+ setExpanded(prev => ({ ...prev, [insight.type]: !prev[insight.type] }));+ return;+ }if (insight.action?.route) {navigate(insight.action.route);}@@ -134,6 +168,18 @@ export default function ActionableInsightsBanner({ insights, onTaskUnblocked, ononRefresh?.();};+ const handleRunReconcile = async (app) => {+ setReconcilingAppId(app.appId);+ const result = await api.triggerCosOnDemandTask('branch-reconcile', app.appId, { silent: true }).catch(err => {+ toast.error(err.message);+ return null;+ });+ setReconcilingAppId(null);+ if (!result?.success) return;+ setQueuedAppIds(prev => [...prev, app.appId]);+ toast.success(`Queued branch-reconcile for ${app.appName}`);+ };+const handleUnblockTask = async (taskId, taskType) => {const result = await api.updateCosTask(taskId, { status: 'pending', type: taskType }, { silent: true }).catch(err => {toast.error(err.message);@@ -167,6 +213,17 @@ export default function ActionableInsightsBanner({ insights, onTaskUnblocked, onconst isExpanded = expanded[primaryInsight.type];const hasBlockedTasks = primaryInsight.type === 'blocked' && primaryInsight.tasks?.length > 0;const approvalTask = primaryInsight.type === 'approval' ? primaryInsight.tasks?.[0] : null;+ const leftoverApps = primaryInsight.type === 'leftover-branches' ? (primaryInsight.apps || []) : [];+ // One app is actionable from the card itself; several have to be listed first.+ const singleLeftoverApp = leftoverApps.length === 1 ? leftoverApps[0] : null;+ const expandsLeftoverApps = leftoverApps.length > 1;+ const expandsInPlace = hasBlockedTasks || expandsLeftoverApps;+ const primaryButton = approvalTask && approvingTaskId === approvalTask.id+ ? { label: 'Approving…', disabled: true }+ : singleLeftoverApp ? reconcileButton(singleLeftoverApp)+ : expandsLeftoverApps ? { label: isExpanded ? 'Collapse' : `View ${leftoverApps.length} Apps`, disabled: false }+ : hasBlockedTasks ? { label: isExpanded ? 'Collapse' : 'View Tasks', disabled: false }+ : { label: primaryInsight.action?.label, disabled: false };return (<div className={`${styles.bg} border ${styles.border} rounded-lg p-3 mb-4 transition-all`}>@@ -216,6 +273,44 @@ export default function ActionableInsightsBanner({ insights, onTaskUnblocked, on</div>)}+ {/* Expanded per-app leftover branches — names the app, what kind of+ leftovers it holds, and runs branch-reconcile for that app alone. */}+ {expandsLeftoverApps && isExpanded && (+ <div className="mt-2 space-y-1.5">+ {leftoverApps.map(app => (+ <div+ key={app.appId}+ className="flex flex-wrap items-center gap-x-2 gap-y-1 bg-black/20 rounded px-2 py-1.5"+ title={app.branches?.length ? `Leftover branches: ${app.branches.join(', ')}` : undefined}+ >+ <GitBranch size={11} className="shrink-0 text-gray-500" />+ <span className="text-xs text-gray-300 truncate">{app.appName}</span>+ <span className="text-xs text-gray-500 shrink-0">{formatBranchSummary(app)}</span>+ <span className="flex-1 text-xs text-gray-600 truncate text-right">+ last run {timeAgo(app.lastUserReconcileAt)}+ </span>+ <button+ onClick={() => handleRunReconcile(app)}+ disabled={reconcileButton(app).disabled}+ className="flex items-center gap-1 px-2 py-1 text-xs font-medium bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded transition-colors shrink-0 min-h-[28px] disabled:opacity-50"+ title={`Queue branch-reconcile for ${app.appName}`}+ >+ <Play size={11} />+ {reconcileButton(app).label}+ </button>+ </div>+ ))}+ {primaryInsight.action?.route && (+ <button+ onClick={() => navigate(primaryInsight.action.route)}+ className="text-xs text-gray-500 hover:text-gray-300 underline"+ >+ Open the branch-reconcile schedule+ </button>+ )}+ </div>+ )}+{/* Additional insights indicator */}{remainingCount > 0 && (<div className="flex items-center gap-1 mt-1.5 text-xs text-gray-500">@@ -230,13 +325,11 @@ export default function ActionableInsightsBanner({ insights, onTaskUnblocked, on{primaryInsight.action && (<buttononClick={() => handleAction(primaryInsight)}- disabled={Boolean(approvalTask && approvingTaskId === approvalTask.id)}- className="flex items-center gap-1 px-2.5 py-1.5 text-xs font-medium bg-white/10 hover:bg-white/20 text-white rounded transition-colors min-h-[32px]"+ disabled={primaryButton.disabled}+ className="flex items-center gap-1 px-2.5 py-1.5 text-xs font-medium bg-white/10 hover:bg-white/20 text-white rounded transition-colors min-h-[32px] disabled:opacity-50">- {approvalTask && approvingTaskId === approvalTask.id- ? 'Approving…'- : hasBlockedTasks ? (isExpanded ? 'Collapse' : 'View Tasks') : primaryInsight.action.label}- {hasBlockedTasks+ {primaryButton.label}+ {expandsInPlace? (isExpanded ? <ChevronDown size={12} /> : <ChevronRight size={12} />): !approvalTask && <ChevronRight size={12} />}diff --git a/client/src/components/cos/ActionableInsightsBanner.test.jsx b/client/src/components/cos/ActionableInsightsBanner.test.jsxindex f2485820ba..20bb1771df 100644--- a/client/src/components/cos/ActionableInsightsBanner.test.jsx+++ b/client/src/components/cos/ActionableInsightsBanner.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { render, screen, fireEvent, waitFor, within } from '@testing-library/react';import { MemoryRouter, useLocation } from 'react-router';import { insightProvenance } from './ActionableInsightsBanner';@@ -35,7 +35,7 @@ describe('ActionableInsightsBanner insightProvenance', () => {// parent trigger that refetches CoS data refreshes the banner for free. These// tests pin the prop-driven render, the null/empty gating, and the unblock path// calling `onRefresh` up instead of owning its own poll.-const api = vi.hoisted(() => ({ updateCosTask: vi.fn(), approveCosTask: vi.fn() }));+const api = vi.hoisted(() => ({ updateCosTask: vi.fn(), approveCosTask: vi.fn(), triggerCosOnDemandTask: vi.fn() }));vi.mock('../../services/api', () => api);vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));@@ -146,4 +146,63 @@ describe('ActionableInsightsBanner (presentational)', () => {await waitFor(() => expect(onRefresh).toHaveBeenCalledTimes(1));expect(onTaskUnblocked).toHaveBeenCalledWith('t1');});+ // The card used to report a bare total and send "Run Now" to the schedule page,+ // which left the operator to guess WHICH app was holding the branches. These+ // pin the per-app breakdown and the per-app trigger that replaced that guess.+ const leftoverInsight = (apps) => ({+ type: 'leftover-branches', priority: 'medium', icon: 'AlertTriangle',+ title: `${apps.reduce((n, a) => n + a.leftoverCount, 0)} leftover branches across ${apps.length} apps, agents idle. Run branch-reconcile?`,+ action: { label: 'Run Now', route: '/cos/schedule?task=branch-reconcile' },+ apps,+ count: apps.reduce((n, a) => n + a.leftoverCount, 0),+ });++ it('expands leftover branches into per-app rows and reconciles one named app', async () => {+ api.triggerCosOnDemandTask.mockResolvedValue({ success: true, request: { id: 'r1' } });+ renderBanner({+ insights: [leftoverInsight([+ { appId: 'app-acme', appName: 'Acme', leftoverCount: 4, states: { NEEDS_PR: 3, MERGED: 1 }, branches: ['claim/one'], lastUserReconcileAt: null },+ { appId: 'app-beta', appName: 'Beta', leftoverCount: 2, states: { WIP: 2 }, branches: [], lastUserReconcileAt: null },+ ])],+ });++ fireEvent.click(screen.getByText('View 2 Apps'));+ expect(screen.getByText('Acme')).toBeInTheDocument();+ expect(screen.getByText('Beta')).toBeInTheDocument();+ expect(screen.getByText('4 branches · 3 NEEDS_PR · 1 MERGED')).toBeInTheDocument();++ // Scope the click to Beta's row — an index into a text-matched list would+ // silently assert against the wrong app.+ const betaRow = screen.getByText('Beta').closest('div');+ fireEvent.click(within(betaRow).getByRole('button', { name: /Run Now/ }));+ await waitFor(() =>+ expect(api.triggerCosOnDemandTask).toHaveBeenCalledWith('branch-reconcile', 'app-beta', { silent: true }),+ );+ // The card outlives the request (the insight only clears once reconcile+ // actually runs), so the sent request has to stay visible or the operator+ // queues the same app again on every glance.+ await waitFor(() => expect(within(betaRow).getByRole('button', { name: 'Queued' })).toBeDisabled());+ expect(within(screen.getByText('Acme').closest('div')).getByRole('button', { name: /Run Now/ })).toBeEnabled();+ });++ it('runs branch-reconcile straight from the card when a single app is named', async () => {+ api.triggerCosOnDemandTask.mockResolvedValue({ success: true, request: { id: 'r1' } });+ renderBanner({+ insights: [{+ ...leftoverInsight([+ { appId: 'app-acme', appName: 'Acme', leftoverCount: 4, states: { NEEDS_PR: 4 }, branches: [], lastUserReconcileAt: null },+ ]),+ title: '4 leftover branches on Acme, agents idle. Run branch-reconcile?',+ }],+ }, { withLocation: true });++ fireEvent.click(screen.getByRole('button', { name: /Run Now/ }));+ await waitFor(() =>+ expect(api.triggerCosOnDemandTask).toHaveBeenCalledWith('branch-reconcile', 'app-acme', { silent: true }),+ );+ // It runs the task rather than navigating away to a page that would not say+ // which app to pick.+ expect(screen.getByTestId('location')).toHaveTextContent('/');+ expect(screen.getByTestId('location')).not.toHaveTextContent('/cos/schedule');+ });});diff --git a/server/routes/cosInsightRoutes.js b/server/routes/cosInsightRoutes.jsindex 297905bbd1..ddc623a912 100644--- a/server/routes/cosInsightRoutes.js+++ b/server/routes/cosInsightRoutes.js@@ -134,22 +134,38 @@ router.get('/actionable-insights', asyncHandler(async (req, res) => {});}- // 4b. Leftover idle branches (#5596) — propose-only; Run Now deep-links to the schedule.+ // 4b. Leftover idle branches (#5596). The detector never enacts; the card is+ // where the operator does. It therefore has to name WHICH apps are holding the+ // branches — a bare total plus a link to the schedule page left them to guess+ // which app to run branch-reconcile for, so `apps` carries the per-app+ // breakdown the banner expands into per-app Run Now buttons.if (Array.isArray(leftoverFindings) && leftoverFindings.length > 0) {- const leftoverCount = leftoverFindings.reduce((sum, finding) => sum + finding.leftoverCount, 0);- const first = leftoverFindings[0];- const single = leftoverFindings.length === 1;+ const apps = leftoverFindings.map(({ appId, appName, leftoverCount, states, branches, lastUserReconcileAt }) => ({+ appId,+ appName: appName || appId,+ leftoverCount,+ states: states || {},+ branches: branches || [],+ lastUserReconcileAt: lastUserReconcileAt || null+ }));+ const leftoverCount = apps.reduce((sum, app) => sum + app.leftoverCount, 0);+ const first = apps[0];+ const single = apps.length === 1;+ const branchLabel = (n) => `${n} leftover branch${n === 1 ? '' : 'es'}`;insights.push({type: 'leftover-branches',priority: 'medium',icon: 'AlertTriangle',title: single- ? `${first.leftoverCount} leftover branches on ${first.appId}, agents idle. Run branch-reconcile?`- : `${leftoverCount} leftover branches across ${leftoverFindings.length} apps, agents idle. Run branch-reconcile?`,- description: first.lastUserReconcileAt- ? `Last manual reconcile ${first.lastUserReconcileAt}. Propose a Run Now — never enact.`- : 'No manual reconcile in the last 14 days. Propose a Run Now — never enact.',- action: { label: 'Run Now', route: '/cos/schedule' },+ ? `${branchLabel(first.leftoverCount)} on ${first.appName}, agents idle. Run branch-reconcile?`+ : `${branchLabel(leftoverCount)} across ${apps.length} apps, agents idle. Run branch-reconcile?`,+ description: single+ ? `${first.lastUserReconcileAt+ ? `Last manual reconcile on ${String(first.lastUserReconcileAt).slice(0, 10)}`+ : 'No manual reconcile in the last 14 days'}. Run Now queues branch-reconcile for ${first.appName}.`+ : apps.map(app => `${app.appName} (${app.leftoverCount})`).join(' · '),+ action: { label: 'Run Now', route: '/cos/schedule?task=branch-reconcile' },+ apps,count: leftoverCount});}diff --git a/server/routes/cosInsightRoutes.test.js b/server/routes/cosInsightRoutes.test.jsindex 5441e7232d..ad189c717d 100644--- a/server/routes/cosInsightRoutes.test.js+++ b/server/routes/cosInsightRoutes.test.js@@ -166,7 +166,8 @@ describe('CoS Insight Routes', () => {cos.getPendingAgentFeedbackCount.mockResolvedValue(0);productivity.getOptimalTimeInfo.mockResolvedValue({ hasData: false });detectIdleLeftoverBranches.mockResolvedValueOnce([{- appId: 'app-acme', leftoverCount: 3, lastUserReconcileAt: null, agentsIdle: true,+ appId: 'app-acme', appName: 'Acme', leftoverCount: 3, states: { NEEDS_PR: 3 },+ branches: ['claim/one'], lastUserReconcileAt: null, agentsIdle: true,}]);const response = await request(app).get('/api/cos/actionable-insights');@@ -176,12 +177,42 @@ describe('CoS Insight Routes', () => {type: 'leftover-branches',priority: 'medium',icon: 'AlertTriangle',- title: '3 leftover branches on app-acme, agents idle. Run branch-reconcile?',- action: { label: 'Run Now', route: '/cos/schedule' },+ title: '3 leftover branches on Acme, agents idle. Run branch-reconcile?',+ // The deep link opens the branch-reconcile task itself, not the bare page.+ action: { label: 'Run Now', route: '/cos/schedule?task=branch-reconcile' },+ apps: [{+ appId: 'app-acme', appName: 'Acme', leftoverCount: 3,+ states: { NEEDS_PR: 3 }, branches: ['claim/one'], lastUserReconcileAt: null,+ }],count: 3,}));});+ // A bare cross-app total ("20 branches across 6 apps") left the operator with+ // no way to know which app to run branch-reconcile for — the card now names+ // every app and carries the per-app rows the banner runs from.+ it('names each app holding leftover branches in the multi-app card', async () => {+ cos.getAllTasks.mockResolvedValue({+ user: { grouped: { pending: [], blocked: [] } },+ cos: { awaitingApproval: [], grouped: { pending: [], blocked: [] } }+ });+ taskLearning.getLearningInsights.mockResolvedValue({ skippedTypes: [] });+ cos.runHealthCheck.mockResolvedValue({ issues: [] });+ cos.getPendingAgentFeedbackCount.mockResolvedValue(0);+ productivity.getOptimalTimeInfo.mockResolvedValue({ hasData: false });+ detectIdleLeftoverBranches.mockResolvedValueOnce([+ { appId: 'app-acme', appName: 'Acme', leftoverCount: 4, states: { NEEDS_PR: 4 }, branches: [], lastUserReconcileAt: null, agentsIdle: true },+ { appId: 'app-beta', appName: 'Beta', leftoverCount: 1, states: { WIP: 1 }, branches: [], lastUserReconcileAt: '2026-08-28T10:00:00.000Z', agentsIdle: true },+ ]);++ const response = await request(app).get('/api/cos/actionable-insights');++ const insight = response.body.insights.find(i => i.type === 'leftover-branches');+ expect(insight.title).toBe('5 leftover branches across 2 apps, agents idle. Run branch-reconcile?');+ expect(insight.description).toBe('Acme (4) · Beta (1)');+ expect(insight.apps.map(app => app.appId)).toEqual(['app-acme', 'app-beta']);+ });+// The health insight filtered on a `severity` field runHealthCheck never// writes, so a PM2 process that failed to auto-restart banner'd at the same// muted `medium` priority as a memory warning.diff --git a/server/services/userActionDetectors.js b/server/services/userActionDetectors.jsindex b4fe158268..9e3206e84e 100644--- a/server/services/userActionDetectors.js+++ b/server/services/userActionDetectors.js@@ -21,6 +21,8 @@ import { listUserActions } from './userActions.js';export const LEFTOVER_BRANCH_LOOKBACK_DAYS = 14;export const LEFTOVER_BRANCH_CACHE_TTL_MS = 60_000;+/** Branch names carried per app so the banner can name a few without unbounded payload growth. */+export const LEFTOVER_BRANCH_SAMPLE_LIMIT = 6;let leftoverCache = { at: 0, findings: null };@@ -38,6 +40,13 @@ const lastManualReconcile = (events, appId) => {return match?.happenedAt ?? null;};+/** `{ NEEDS_PR: 2, MERGED: 1 }` — what KIND of leftovers an app is holding. */+const countByState = (rows) => rows.reduce((counts, row) => {+ const state = row.state || 'UNKNOWN';+ counts[state] = (counts[state] || 0) + 1;+ return counts;+}, {});+async function computeIdleLeftoverBranches({now,getIds,@@ -53,7 +62,7 @@ async function computeIdleLeftoverBranches({const apps = [...(await getApps())];if (!apps.some((app) => app.id === PORTOS_APP_ID)) {- apps.unshift({ id: PORTOS_APP_ID, repoPath: portosRoot });+ apps.unshift({ id: PORTOS_APP_ID, name: 'PortOS', repoPath: portosRoot });}const from = new Date(now - LEFTOVER_BRANCH_LOOKBACK_DAYS * 24 * 60 * 60 * 1000).toISOString();@@ -74,13 +83,16 @@ async function computeIdleLeftoverBranches({try {const defaultBranch = await getDefault(repoPath);const inputs = await gather(repoPath, { defaultBranch, activeAgentIds: [] });- const leftoverCount = classify(inputs)- .filter((row) => !row.liveOwnerReason)- .length;- if (leftoverCount === 0) continue;+ const leftovers = classify(inputs).filter((row) => !row.liveOwnerReason);+ if (leftovers.length === 0) continue;findings.push({appId: app.id,- leftoverCount,+ // The operator thinks in app NAMES, not registry ids — the insight card+ // has to answer "which app do I run this for?" without a second lookup.+ appName: app.name || app.id,+ leftoverCount: leftovers.length,+ states: countByState(leftovers),+ branches: leftovers.slice(0, LEFTOVER_BRANCH_SAMPLE_LIMIT).map((row) => row.branch).filter(Boolean),lastUserReconcileAt: lastManualReconcile(triggers, app.id),agentsIdle: true,});@@ -88,12 +100,13 @@ async function computeIdleLeftoverBranches({console.error(`❌ leftover-branch detector: skipped ${app.id}: ${error.message}`);}}- return findings;+ // Worst offender first: the card names one app up front and lists the rest.+ return findings.sort((a, b) => b.leftoverCount - a.leftoverCount);}/*** @param {object} [deps] injectable for tests. Passing deps bypasses the TTL cache.- * @returns {Promise<Array<{appId: string, leftoverCount: number, lastUserReconcileAt: string|null, agentsIdle: true}>>}+ * @returns {Promise<Array<{appId: string, appName: string, leftoverCount: number, states: Record<string, number>, branches: string[], lastUserReconcileAt: string|null, agentsIdle: true}>>}*/export async function detectIdleLeftoverBranches(deps = null) {const useCache = deps == null;diff --git a/server/services/userActionDetectors.test.js b/server/services/userActionDetectors.test.jsindex f05d604ca7..c0fd221c6b 100644--- a/server/services/userActionDetectors.test.js+++ b/server/services/userActionDetectors.test.js@@ -20,8 +20,8 @@ const deps = (overrides = {}) => ({now: Date.parse('2026-09-02T12:00:00.000Z'),getActiveAgentIds: () => [],getActiveApps: async () => [- { id: 'portos-default', repoPath: '/tmp/portos' },- { id: 'app-acme', repoPath: '/tmp/acme' },+ { id: 'portos-default', name: 'PortOS', repoPath: '/tmp/portos' },+ { id: 'app-acme', name: 'Acme', repoPath: '/tmp/acme' },],getDefaultBranch: async () => 'main',gatherBranchState: async (repoPath) => (repoPath === '/tmp/acme' ? [leftoverInput()] : []),@@ -50,12 +50,38 @@ describe('detectIdleLeftoverBranches', () => {const findings = await detectIdleLeftoverBranches(deps());expect(findings).toEqual([{appId: 'app-acme',+ // The insight card names the app the operator knows, not the registry id.+ appName: 'Acme',leftoverCount: 1,+ states: { NEEDS_PR: 1 },+ branches: ['claim/issue-1'],lastUserReconcileAt: '2026-08-28T10:00:00.000Z',agentsIdle: true,}]);});+ // The card leads with one app by name, so the busiest one has to sort first —+ // otherwise "N branches on <app>" points at whichever app the registry listed+ // first rather than the one actually worth reconciling.+ it('reports the app with the most leftover branches first, with its state mix', async () => {+ const findings = await detectIdleLeftoverBranches(deps({+ gatherBranchState: async (repoPath) => (repoPath === '/tmp/acme'+ ? [leftoverInput()]+ : [leftoverInput({ branch: 'claim/a' }), leftoverInput({ branch: 'claim/b' }), leftoverInput({ branch: 'claim/c' })]),+ classifyBranches: (inputs) => inputs.map((input) => ({+ ...input,+ state: input.branch === 'claim/c' ? 'MERGED' : 'NEEDS_PR',+ })),+ }));+ expect(findings.map((finding) => finding.appId)).toEqual(['portos-default', 'app-acme']);+ expect(findings[0]).toMatchObject({+ appName: 'PortOS',+ leftoverCount: 3,+ states: { NEEDS_PR: 2, MERGED: 1 },+ branches: ['claim/a', 'claim/b', 'claim/c'],+ });+ });+it('returns nothing while any agent is still running', async () => {const gatherBranchState = async () => { throw new Error('must not gather while agents run'); };await expect(detectIdleLeftoverBranches(deps({