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

feat: surface pending CoS feedback

[._.]/ Adam Eivy6f30f9222cc0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0b09fc20f1..68ad0fe83d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -28,6 +28,8 @@
- CoS agents whose deliverable is a **commit** are no longer scored as failures. The idle reaper's "did this agent do anything?" gate read only *uncommitted* changes, so a `/do:release` or `/do:pr` run that committed, pushed, and opened its PR — leaving a clean tree *because it succeeded* — was recorded as `idle-no-changes` and retried. Two consecutive release runs on 2026-08-08 each did their whole job (cut the release commit, opened the release PR, then repaired it against review findings) and were both reported failed, holding the release for two days. The gate now counts commits made inside the run window as evidence of work, alongside a dirty tree. The report-shaped half of the same problem (`/do:review`, `/do:scan`, `/do:plan-task`, `/do:replan`, whose deliverable lands outside the repo) is tracked in #3636, and the unsatisfiable `[task-<id>]` success criterion one layer up in #3637.
+- **CoS now brings recent unrated completed runs back to you.** The feedback queue was durable but easy to miss once a completion notification disappeared. Tasks now surface an actionable reminder that opens the Agents tab directly in its shareable “Needs feedback” filter, so a quick rating can actually improve future routing and task quality.
+
- Green merge-only PRs are drained on a real 30-minute cadence again. The pending-merge sweep had moved onto the CoS evaluation pass, but evaluation is event-driven — there is no evaluation timer — so on a quiet install it ran roughly once per PortOS restart, and the `MAX_PENDING_MERGE_TICKS` escape hatch counted restarts instead of the six hours it documents. The sweep now owns a `cos-pending-merge-sweep` interval job registered and cancelled with the other CoS timers, gated on the same "CoS auto-run is `execute` and not paused" switch. It stays decoupled from the `pr-watcher` task type, so leaving that task disabled still can't strand a queued merge, and `POST /api/cos/evaluate` still drains opportunistically.
- An agent that merely *prints* a provider banner no longer benches a healthy provider. The immediate-fallback detector stamped every match as provider chrome, so a CoS agent that quoted Antigravity's account-eligibility banner — investigating that failure mode, `cat`-ing a prior run's transcript, grepping for it — sidelined the provider for the full cooldown across every subsequently dequeued task, not just its own run. The banner is now promoted to provider provenance only when it opens its own line behind nothing but TUI gutter chrome, the shape the CLI actually renders; a quoted mention still fails that one run and routes it to a fallback, but is no longer treated as evidence about the provider's health. Real banners arriving as the run's own terminal output bench exactly as before.
diff --git a/client/src/components/cos/ActionableInsightsBanner.jsx b/client/src/components/cos/ActionableInsightsBanner.jsx
index 55da404365..9a5f35c619 100644
--- a/client/src/components/cos/ActionableInsightsBanner.jsx
+++ b/client/src/components/cos/ActionableInsightsBanner.jsx
@@ -8,6 +8,7 @@ import {
Brain,
Newspaper,
ListTodo,
+ MessageSquare,
ChevronRight,
ChevronDown,
X,
@@ -52,6 +53,7 @@ const ICON_MAP = {
Brain,
Newspaper,
ListTodo,
+ MessageSquare,
Zap
};
diff --git a/client/src/components/cos/ActionableInsightsBanner.test.jsx b/client/src/components/cos/ActionableInsightsBanner.test.jsx
index 92e6434c5a..f2485820ba 100644
--- a/client/src/components/cos/ActionableInsightsBanner.test.jsx
+++ b/client/src/components/cos/ActionableInsightsBanner.test.jsx
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
-import { MemoryRouter } from 'react-router';
+import { MemoryRouter, useLocation } from 'react-router';
import { insightProvenance } from './ActionableInsightsBanner';
// The banner stamps each surfaced insight with a provenance chip. The honesty
@@ -11,7 +11,7 @@ import { insightProvenance } from './ActionableInsightsBanner';
// regress back to a single hardcoded level.
describe('ActionableInsightsBanner insightProvenance', () => {
it('marks direct-count insight types as data-backed', () => {
- for (const type of ['approval', 'blocked', 'health', 'briefing', 'tasks']) {
+ for (const type of ['approval', 'blocked', 'health', 'agent-feedback', 'briefing', 'tasks']) {
expect(insightProvenance(type).level).toBe('data-backed');
}
});
@@ -41,10 +41,16 @@ vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } })
const ActionableInsightsBanner = (await import('./ActionableInsightsBanner')).default;
-const renderBanner = (props) =>
+const LocationDisplay = () => {
+ const location = useLocation();
+ return <output data-testid="location">{`${location.pathname}${location.search}`}</output>;
+};
+
+const renderBanner = (props, { withLocation = false } = {}) =>
render(
<MemoryRouter>
<ActionableInsightsBanner {...props} />
+ {withLocation && <LocationDisplay />}
</MemoryRouter>,
);
@@ -76,6 +82,18 @@ describe('ActionableInsightsBanner (presentational)', () => {
expect(api.updateCosTask).not.toHaveBeenCalled();
});
+ it('navigates feedback reminders to the URL-backed review queue', () => {
+ renderBanner({
+ insights: [{
+ type: 'agent-feedback', priority: 'medium', icon: 'MessageSquare', title: '1 completed run needs feedback',
+ action: { label: 'Review runs', route: '/cos/agents?feedback=needs-feedback' },
+ }],
+ }, { withLocation: true });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Review runs' }));
+ expect(screen.getByTestId('location')).toHaveTextContent('/cos/agents?feedback=needs-feedback');
+ });
+
it('hides insights the user dismisses', () => {
renderBanner({
insights: [
diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsx
index d8d69ede41..202f559eae 100644
--- a/client/src/components/cos/tabs/AgentsTab.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.jsx
@@ -1,4 +1,5 @@
import { useState, useEffect, useMemo, useCallback } from 'react';
+import { useSearchParams } from 'react-router';
import { Trash2, Search, X, ChevronDown, MessageSquare } from 'lucide-react';
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
@@ -13,10 +14,10 @@ const needsAgentFeedback = (agent) => {
};
export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, apps }) {
+ const [searchParams, setSearchParams] = useSearchParams();
const [resumingAgent, setResumingAgent] = useState(null);
const [durations, setDurations] = useState(null);
const [searchQuery, setSearchQuery] = useState('');
- const [feedbackFilter, setFeedbackFilter] = useState('all');
const [feedbackUpdates, setFeedbackUpdates] = useState({});
const [confirmingClear, setConfirmingClear] = useState(false);
@@ -26,6 +27,16 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a
const [loadedDates, setLoadedDates] = useState(new Set()); // dates already fetched
const [loadingMore, setLoadingMore] = useState(false);
+ // Filter selection is URL-backed so actionable insights can open the exact
+ // review queue and the filtered state remains bookmarkable/shareable.
+ const feedbackFilter = searchParams.get('feedback') === 'needs-feedback' ? 'needs-feedback' : 'all';
+ const setFeedbackFilter = useCallback((filter) => {
+ const next = new URLSearchParams(searchParams);
+ if (filter === 'needs-feedback') next.set('feedback', filter);
+ else next.delete('feedback');
+ setSearchParams(next, { replace: true });
+ }, [searchParams, setSearchParams]);
+
// Fetch duration estimates for progress indicators
useEffect(() => {
api.getCosLearningDurations().then(setDurations).catch(() => {});
diff --git a/client/src/components/cos/tabs/AgentsTab.test.jsx b/client/src/components/cos/tabs/AgentsTab.test.jsx
index e2ed34d413..d562b63dcf 100644
--- a/client/src/components/cos/tabs/AgentsTab.test.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.test.jsx
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { act } from 'react';
+import { MemoryRouter } from 'react-router';
vi.mock('../../../services/api', () => ({
getCosLearningDurations: vi.fn(),
@@ -49,14 +50,16 @@ const completedAgent = (id, description, extra = {}) => ({
...extra,
});
-const renderTab = (agents, onRefresh = vi.fn()) => render(
- <AgentsTab
- agents={agents}
- onRefresh={onRefresh}
- liveOutputs={{}}
- providers={[]}
- apps={[]}
- />
+const renderTab = (agents, onRefresh = vi.fn(), initialEntry = '/cos/agents') => render(
+ <MemoryRouter initialEntries={[initialEntry]}>
+ <AgentsTab
+ agents={agents}
+ onRefresh={onRefresh}
+ liveOutputs={{}}
+ providers={[]}
+ apps={[]}
+ />
+ </MemoryRouter>
);
beforeEach(() => {
@@ -85,6 +88,18 @@ describe('AgentsTab feedback review queue', () => {
expect(needsFeedback).toHaveAttribute('aria-pressed', 'true');
});
+ it('opens the feedback queue directly from the URL', async () => {
+ renderTab([
+ completedAgent('unrated', 'Unrated task'),
+ completedAgent('rated', 'Rated task', { feedback: { rating: 'positive' } }),
+ ], vi.fn(), '/cos/agents?feedback=needs-feedback');
+ await act(async () => {});
+
+ expect(screen.getByText('Unrated task')).toBeInTheDocument();
+ expect(screen.queryByText('Rated task')).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Needs feedback: 1' })).toHaveAttribute('aria-pressed', 'true');
+ });
+
it('removes an archived run from the queue immediately after feedback', async () => {
const user = userEvent.setup();
const onRefresh = vi.fn();
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.md
index 8f3f950b9d..73ff69749a 100644
--- a/docs/features/chief-of-staff.md
+++ b/docs/features/chief-of-staff.md
@@ -21,7 +21,7 @@ Autonomous agent manager that watches task files, spawns sub-agents, and maintai
6. **Self-Improvement**: Can analyze performance and suggest prompt/config improvements
7. **Script Generation**: Creates automation scripts for repetitive tasks
8. **Report Generation**: Daily summaries of completed work
-9. **Durable Agent Feedback**: Completion notifications accept quick ratings, while the Agents tab keeps a filterable queue of loaded runs that still need feedback after a notification expires. Feedback details can be attached to helpful, unhelpful, or neutral ratings so learning has actionable context.
+9. **Durable Agent Feedback**: Completion notifications accept quick ratings, while the Agents tab keeps a filterable queue of loaded runs that still need feedback after a notification expires. Recent unrated completed runs are also surfaced as a CoS insight that links directly to the URL-backed review filter. Feedback details can be attached to helpful, unhelpful, or neutral ratings so learning has actionable context.
10. **Learning-Aligned ETAs**: Pending tasks and active agents resolve their estimates from the same metadata-first task-learning bucket that records outcomes, including archived scheduled-agent metadata, instead of inferring a potentially different category from task text.
## Task File Format
diff --git a/server/routes/cosInsightRoutes.js b/server/routes/cosInsightRoutes.js
index c890caf446..23bb6beca5 100644
--- a/server/routes/cosInsightRoutes.js
+++ b/server/routes/cosInsightRoutes.js
@@ -49,12 +49,13 @@ router.get('/productivity/calendar', asyncHandler(async (req, res) => {
// GET /api/cos/actionable-insights - Get prioritized action items requiring user attention
// Surfaces the most important things to address right now across all CoS subsystems
router.get('/actionable-insights', asyncHandler(async (req, res) => {
- const [tasksData, learningSummary, healthCheck, notificationsModule, optimalTimeInfo] = await Promise.all([
+ const [tasksData, learningSummary, healthCheck, notificationsModule, optimalTimeInfo, pendingFeedbackCount] = await Promise.all([
cos.getAllTasks().catch(err => { console.error(`❌ Failed to load tasks: ${err.message}`); return { user: null, cos: null }; }),
taskLearning.getLearningInsights().catch(err => { console.error(`❌ Failed to load learning insights: ${err.message}`); return null; }),
cos.runHealthCheck().catch(err => { console.error(`❌ Failed to run health check: ${err.message}`); return { issues: [] }; }),
import('../services/notifications.js').catch(err => { console.error(`❌ Failed to load notifications: ${err.message}`); return null; }),
- productivity.getOptimalTimeInfo().catch(() => ({ hasData: false }))
+ productivity.getOptimalTimeInfo().catch(() => ({ hasData: false })),
+ cos.getPendingAgentFeedbackCount().catch(err => { console.error(`❌ Failed to load pending agent feedback: ${err.message}`); return 0; })
]);
const notificationsData = notificationsModule ? await notificationsModule.getNotifications({ unreadOnly: true, limit: 10 }).catch(() => []) : [];
@@ -111,7 +112,22 @@ router.get('/actionable-insights', asyncHandler(async (req, res) => {
});
}
- // 4. Learning failures (skipped task types)
+ // 4. Recent completed agents without feedback. The count comes directly from
+ // state-resident completed agents, which keeps this 30s-polled endpoint cheap
+ // and avoids treating older archived history as an urgent review interruption.
+ if (pendingFeedbackCount > 0) {
+ insights.push({
+ type: 'agent-feedback',
+ priority: 'medium',
+ icon: 'MessageSquare',
+ title: `${pendingFeedbackCount} completed run${pendingFeedbackCount > 1 ? 's' : ''} need feedback`,
+ description: 'Your ratings help CoS learn which work and providers are useful.',
+ action: { label: 'Review runs', route: '/cos/agents?feedback=needs-feedback' },
+ count: pendingFeedbackCount
+ });
+ }
+
+ // 5. Learning failures (skipped task types)
const skippedTypes = learningSummary?.skippedTypes || [];
if (skippedTypes.length > 0) {
insights.push({
@@ -125,7 +141,7 @@ router.get('/actionable-insights', asyncHandler(async (req, res) => {
});
}
- // 5. Unread notifications (briefings, reviews, etc.)
+ // 6. Unread notifications (briefings, reviews, etc.)
const briefingNotifs = notificationsData.filter(n => n.type === 'briefing_ready');
if (briefingNotifs.length > 0) {
insights.push({
@@ -139,7 +155,7 @@ router.get('/actionable-insights', asyncHandler(async (req, res) => {
});
}
- // 6. Pending user tasks (informational)
+ // 7. Pending user tasks (informational)
const pendingUserTasks = tasksData.user?.grouped?.pending || [];
if (pendingUserTasks.length > 0 && insights.length < 4) {
insights.push({
@@ -153,7 +169,7 @@ router.get('/actionable-insights', asyncHandler(async (req, res) => {
});
}
- // 7. Peak productivity time (proactive suggestion)
+ // 8. Peak productivity time (proactive suggestion)
// Show when it's a peak hour AND there are pending tasks to work on
const totalPendingTasks = pendingUserTasks.length + (tasksData.cos?.grouped?.pending?.length || 0);
if (optimalTimeInfo?.hasData && optimalTimeInfo.isOptimal && totalPendingTasks > 0 && insights.length < 5) {
diff --git a/server/routes/cosInsightRoutes.test.js b/server/routes/cosInsightRoutes.test.js
index 81a385172e..25bd66fa18 100644
--- a/server/routes/cosInsightRoutes.test.js
+++ b/server/routes/cosInsightRoutes.test.js
@@ -6,6 +6,7 @@ import insightRoutes from './cosInsightRoutes.js';
vi.mock('../services/cos.js', () => ({
getAllTasks: vi.fn(),
runHealthCheck: vi.fn(),
+ getPendingAgentFeedbackCount: vi.fn(),
getTodayActivity: vi.fn(),
getRecentTasks: vi.fn()
}));
@@ -60,6 +61,7 @@ describe('CoS Insight Routes', () => {
app.use(express.json());
app.use('/api/cos', insightRoutes);
vi.clearAllMocks();
+ cos.getPendingAgentFeedbackCount.mockResolvedValue(0);
});
describe('GET /api/cos/productivity', () => {
@@ -134,6 +136,7 @@ describe('CoS Insight Routes', () => {
});
taskLearning.getLearningInsights.mockResolvedValue({ skippedTypes: [] });
cos.runHealthCheck.mockResolvedValue({ issues: [] });
+ cos.getPendingAgentFeedbackCount.mockResolvedValue(2);
productivity.getOptimalTimeInfo.mockResolvedValue({ hasData: false });
const response = await request(app).get('/api/cos/actionable-insights');
@@ -146,6 +149,11 @@ describe('CoS Insight Routes', () => {
action: { label: 'Approve' },
tasks: [{ id: 'a1', description: 'Approve me' }],
});
+ expect(response.body.insights).toContainEqual(expect.objectContaining({
+ type: 'agent-feedback',
+ count: 2,
+ action: { label: 'Review runs', route: '/cos/agents?feedback=needs-feedback' }
+ }));
});
it('should handle errors gracefully in parallel calls', async () => {
diff --git a/server/services/cos.js b/server/services/cos.js
index a630e10260..8d924fedff 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -55,7 +55,7 @@ export { cosEvents, emitLog };
// Callers ask `agentOrchestrator.js` for those (#3450).
export { registerAgent, updateAgent, completeAgent, appendAgentOutput, getAgents, getAgent, getAgentRecord, getAgentPrompt, terminateAgent, sendBtwToAgent, cleanupZombieAgents, deleteAgent } from './cosAgentLifecycle.js';
export { getAgentDates, getAgentsByDate, pruneOldAgentArchives } from './cosAgentIndex.js';
-export { submitAgentFeedback, getFeedbackStats, extractTaskType } from './cosAgentFeedback.js';
+export { submitAgentFeedback, getFeedbackStats, getPendingAgentFeedbackCount, extractTaskType } from './cosAgentFeedback.js';
export { archiveStaleAgents, clearCompletedAgents } from './cosAgentArchive.js';
// Reports and activity (re-export for backward compat with `import * as cos`)
diff --git a/server/services/cosAgentFeedback.js b/server/services/cosAgentFeedback.js
index 098920ac02..38e60d53b2 100644
--- a/server/services/cosAgentFeedback.js
+++ b/server/services/cosAgentFeedback.js
@@ -16,6 +16,20 @@ import { atomicWrite, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { loadAgentIndex, getAgentDir } from './cosAgentIndex.js';
import { ServerError } from '../lib/errorHandler.js';
+const isSystemAgent = (agent) =>
+ agent.taskId?.startsWith('sys-') || agent.id?.startsWith('sys-');
+
+// Count completed user-facing agents that are still retained in live CoS state
+// and have not received a rating. Archived history is intentionally excluded:
+// actionable insights refresh every 30s, so this remains a cheap, exact count
+// of the recent runs a user can immediately review in the Agents queue.
+export async function getPendingAgentFeedbackCount() {
+ const state = await loadState();
+ return Object.values(state.agents)
+ .filter(agent => agent.status === 'completed' && !isSystemAgent(agent) && !agent.feedback?.rating)
+ .length;
+}
+
// Submit feedback for a completed agent
export async function submitAgentFeedback(agentId, feedback) {
return withStateLock(async () => {
diff --git a/server/services/cosAgentFeedback.test.js b/server/services/cosAgentFeedback.test.js
new file mode 100644
index 0000000000..1e266119bf
--- /dev/null
+++ b/server/services/cosAgentFeedback.test.js
@@ -0,0 +1,47 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const mockCosState = vi.hoisted(() => ({
+ // Use $TMPDIR (falls back to /tmp) rather than a hardcoded /private/tmp — the
+ // latter exists on macOS (where /tmp symlinks to it) but not on Linux CI.
+ agentsDir: `${process.env.TMPDIR || '/tmp'}/portos-cos-feedback-test-${process.pid}`,
+ state: null
+}));
+
+vi.mock('./cosState.js', () => ({
+ AGENTS_DIR: mockCosState.agentsDir,
+ loadState: vi.fn(async () => mockCosState.state),
+ saveState: vi.fn(),
+ withStateLock: async (fn) => fn()
+}));
+
+import { getPendingAgentFeedbackCount } from './cosAgentFeedback.js';
+
+describe('getPendingAgentFeedbackCount', () => {
+ beforeEach(() => {
+ mockCosState.state = { agents: {} };
+ });
+
+ it('counts only unrated completed non-system agents for the feedback insight', async () => {
+ mockCosState.state.agents = {
+ 'agent-unrated': { id: 'agent-unrated', status: 'completed', completedAt: '2026-08-01T10:00:00.000Z' },
+ 'agent-rated': { id: 'agent-rated', status: 'completed', feedback: { rating: 'positive' } },
+ 'agent-system': { id: 'agent-system', taskId: 'sys-health-check', status: 'completed' },
+ 'agent-running': { id: 'agent-running', status: 'running' }
+ };
+
+ await expect(getPendingAgentFeedbackCount()).resolves.toBe(1);
+ });
+
+ it('excludes system agents identified by id as well as taskId', async () => {
+ mockCosState.state.agents = {
+ 'sys-nightly-sweep': { id: 'sys-nightly-sweep', status: 'completed' },
+ 'agent-real': { id: 'agent-real', status: 'completed' }
+ };
+
+ await expect(getPendingAgentFeedbackCount()).resolves.toBe(1);
+ });
+
+ it('returns 0 when nothing is awaiting a rating', async () => {
+ await expect(getPendingAgentFeedbackCount()).resolves.toBe(0);
+ });
+});