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: retain CoS feedback actions across archive (#7740)

[._.]/ Adam Eivy71fcc846817f
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index e165e9b7cd..c251d496d6 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -31,7 +31,7 @@ import CollapsibleText from '../../ui/CollapsibleText';
import toast from '../../ui/Toast';
import { copyToClipboard } from '../../../lib/clipboard';
import { extractCosTaskType } from '../../../lib/cosTaskType';
-import { isAgentHandoff } from '../../../lib/agentOutcome';
+import { isAgentFeedbackUpdateTarget, isSystemAgent as isSystemAgentRecord } from '../../../lib/cosAgentFeedback';
import AgentResultLine from '../AgentResultLine';
import { DEFAULT_REVIEWER, normalizeReviewers } from '../constants';
import { formatBytes, formatCount, formatDurationMs, formatDateTime, formatTimeOfDay } from '../../../utils/formatters';
@@ -327,14 +327,9 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
const [showFeedbackComment, setShowFeedbackComment] = useState(false);
const [feedbackComment, setFeedbackComment] = useState(agent.feedback?.comment || '');
- // Determine if this is a system agent (health check, etc.)
- const isSystemAgent = agent.taskId?.startsWith('sys-') || agent.id?.startsWith('sys-');
- // Only agents from a manually-filled task form ask for a rating —
- // scheduled/autopilot runs are already auto-evaluated by task-learning.
- const isManualUserAgent = agent.metadata?.taskType === 'user';
// Retired by Resume/Relaunch: this run handed its task to a continuation
// instead of reaching a verdict, so it is neither a success nor a failure.
- const handoff = isAgentHandoff(agent);
+ const isSystemAgent = isSystemAgentRecord(agent);
const inactive = completed || paused;
// Handle feedback submission
@@ -1075,7 +1070,7 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
the rating that covers this work — so it is excluded UNLESS a rating is
already on the record: pre-upgrade handoffs were ratable, and hiding the
block outright would swallow a verdict the user did give. */}
- {completed && !isSystemAgent && isManualUserAgent && !remote && (!handoff || !!feedbackState) && (
+ {isAgentFeedbackUpdateTarget(agent) && !remote && (
<div className="mt-2 pt-1 border-t border-port-border/50">
<div className="flex items-center gap-3 flex-wrap">
<span className="text-xs text-gray-500">Was this helpful?</span>
diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsx
index aca50a9494..bb910b8952 100644
--- a/client/src/components/cos/tabs/AgentsTab.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.jsx
@@ -9,7 +9,7 @@ import RelaunchAgentModal from './RelaunchAgentModal';
import BrailleSpinner from '../../BrailleSpinner';
import InlineConfirmRow from '../../ui/InlineConfirmRow';
import { agentResumeMessage } from '../../../lib/agentResumeOutcome';
-import { isAgentHandoff } from '../../../lib/agentOutcome';
+import { isAgentFeedbackEligible } from '../../../lib/cosAgentFeedback';
import { formatCount } from '../../../utils/formatters';
// What each `resumeAgent` outcome actually did (server modes, agentManagement.js).
@@ -32,18 +32,7 @@ const RESUME_MESSAGES = {
superseded: { queued: 'A later agent now holds this task paused — that pause was left intact' },
};
-// Only agents from a manually-filled task form ask for a rating — scheduled/
-// autopilot runs (taskType 'internal') are already auto-evaluated by
-// task-learning's success/failure tracking. See cosAgentFeedback.js.
-// A run retired by Resume/Relaunch is excluded too — it has no result to rate,
-// and the continuation it handed the task to is the run that asks for the rating.
-// Without this, every provider swap left a permanent entry in the needs-feedback
-// count that nothing the user does can clear (AgentCard hides the buttons).
-const needsAgentFeedback = (agent) => {
- const isSystemAgent = agent.taskId?.startsWith('sys-') || agent.id?.startsWith('sys-');
- const isManualUserAgent = agent.metadata?.taskType === 'user';
- return !isSystemAgent && isManualUserAgent && !isAgentHandoff(agent) && !agent.feedback?.rating;
-};
+const needsAgentFeedback = isAgentFeedbackEligible;
export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, providersLoaded, apps }) {
const { agentId } = useParams();
@@ -64,6 +53,8 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
const [durations, setDurations] = useState(null);
const [searchQuery, setSearchQuery] = useState('');
const [feedbackUpdates, setFeedbackUpdates] = useState({});
+ const [pendingFeedbackAgents, setPendingFeedbackAgents] = useState([]);
+ const [pendingFeedbackCount, setPendingFeedbackCount] = useState(null);
const [confirmingClear, setConfirmingClear] = useState(false);
// Date-based lazy loading for completed agents
@@ -87,6 +78,22 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
api.getCosLearningDurations().then(setDurations).catch(() => {});
}, []);
+ // The durable reference index is the bounded source of truth for feedback
+ // actions. It brings older eligible runs into the filter without walking every
+ // historical date bucket; the response uses the same predicate as the server
+ // queue and supplies a count even when those cards are not otherwise loaded.
+ useEffect(() => {
+ let cancelled = false;
+ api.getCosPendingAgentFeedback({ silent: true })
+ .then((result) => {
+ if (cancelled) return;
+ setPendingFeedbackAgents(Array.isArray(result?.agents) ? result.agents : []);
+ setPendingFeedbackCount(Number.isFinite(result?.count) ? result.count : null);
+ })
+ .catch(() => {});
+ return () => { cancelled = true; };
+ }, []);
+
// Fetch date buckets on mount, with the most recent one hydrated in the SAME
// response. The tab always wants that bucket but can't name its date until the
// bucket list arrives, so asking separately costs a second serial round trip
@@ -174,6 +181,15 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
agent.id === updatedAgent.id ? { ...agent, feedback: updatedAgent.feedback } : agent
));
}
+ setPendingFeedbackAgents(prev => {
+ const wasPending = prev.some(agent => agent.id === updatedAgent?.id);
+ if (wasPending && !needsAgentFeedback(updatedAgent)) {
+ setPendingFeedbackCount(count => (typeof count === 'number' ? Math.max(0, count - 1) : count));
+ }
+ return needsAgentFeedback(updatedAgent)
+ ? prev.map(agent => agent.id === updatedAgent.id ? updatedAgent : agent)
+ : prev.filter(agent => agent.id !== updatedAgent?.id);
+ });
onRefresh();
}, [onRefresh]);
@@ -236,8 +252,11 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
for (const agent of recentCompleted) addAgent(agent);
// Then disk-loaded agents
for (const agent of loadedAgents) addAgent(agent);
+ // Finally the durable pending index, which may contain an older archived
+ // run that has not been loaded through the date-bucket pager yet.
+ for (const agent of pendingFeedbackAgents) addAgent(agent);
return merged.sort((a, b) => new Date(b.completedAt || 0) - new Date(a.completedAt || 0));
- }, [recentCompleted, loadedAgents, feedbackUpdates]);
+ }, [recentCompleted, loadedAgents, pendingFeedbackAgents, feedbackUpdates]);
const totalCount = useMemo(() => {
const indexTotal = dateBuckets.reduce((sum, d) => sum + d.count, 0);
@@ -265,10 +284,14 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
});
}, [allCompleted, feedbackFilter, searchQuery]);
- const needsFeedbackCount = useMemo(
- () => allCompleted.filter(needsAgentFeedback).length,
- [allCompleted]
- );
+ const locallyVisibleNeedsFeedback = allCompleted.filter(needsAgentFeedback).length;
+ // A completion can arrive through the live agent stream just after the
+ // durable-index request resolves. Never let that race hide a newly actionable
+ // run; the server count still carries older archived obligations that are not
+ // in the currently loaded cards.
+ const needsFeedbackCount = pendingFeedbackCount == null
+ ? locallyVisibleNeedsFeedback
+ : Math.max(pendingFeedbackCount, locallyVisibleNeedsFeedback);
const selectedAgent = agents.find(agent => agent.id === agentId) || (focusedAgent?.id === agentId ? focusedAgent : null);
const hasMoreDates = dateBuckets.some(d => !loadedDates.has(d.date));
@@ -340,7 +363,7 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
)}
{/* Completed Agents */}
- {(totalCount > 0 || recentCompleted.length > 0) && (
+ {(totalCount > 0 || recentCompleted.length > 0 || pendingFeedbackAgents.length > 0) && (
<div>
<div className="flex items-center justify-between mb-3">
<h3 className="text-lg font-semibold text-white">
diff --git a/client/src/components/cos/tabs/AgentsTab.test.jsx b/client/src/components/cos/tabs/AgentsTab.test.jsx
index b4eb5f6810..a8da218dcc 100644
--- a/client/src/components/cos/tabs/AgentsTab.test.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.test.jsx
@@ -9,6 +9,7 @@ vi.mock('../../../services/api', () => ({
getCosAgent: vi.fn(),
getCosAgentDates: vi.fn(),
getCosAgentsByDate: vi.fn(),
+ getCosPendingAgentFeedback: vi.fn(),
hydrateCosAgentDescription: vi.fn(async (agent) => agent),
clearCompletedCosAgents: vi.fn(),
resumeCosAgent: vi.fn(),
@@ -107,6 +108,7 @@ beforeEach(() => {
api.getCosLearningDurations.mockResolvedValue({});
api.getCosAgentDates.mockResolvedValue({ dates: [], latest: null });
api.getCosAgentsByDate.mockResolvedValue([]);
+ api.getCosPendingAgentFeedback.mockResolvedValue({ agents: [], count: null });
api.hydrateCosAgentDescription.mockImplementation(async (agent) => agent);
});
@@ -274,6 +276,22 @@ describe('AgentsTab resume routing', () => {
});
describe('AgentsTab feedback review queue', () => {
+ it('renders an older durable pending run and uses its server count', async () => {
+ const archived = completedAgent('agent-archived', 'An older pending run');
+ api.getCosPendingAgentFeedback.mockResolvedValue({ agents: [archived], count: 1 });
+
+ renderTab([]);
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Needs feedback: 1' })).toBeInTheDocument());
+ expect(screen.getByText('An older pending run')).toBeInTheDocument();
+ });
+
+ it('does not hide a live completion that arrives after the index snapshot', async () => {
+ api.getCosPendingAgentFeedback.mockResolvedValue({ agents: [], count: 0 });
+ renderTab([completedAgent('just-finished', 'A just-finished run')]);
+
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Needs feedback: 1' })).toBeInTheDocument());
+ });
+
it('filters loaded completed agents to unrated non-system runs', async () => {
const user = userEvent.setup();
renderTab([
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 5a6fb4f011..655ef423d2 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -122,6 +122,7 @@ grep -i "what you want to do" client/src/lib/README.md
|---|---|
| `a11yKeyboard.js` | `clickableProps(handler, { role?, disabled? })` → `{ role, tabIndex, onKeyDown }` and `onActivateKeyDown(handler)` — make a non-`<button>` element with an `onClick` keyboard-accessible (Enter/Space activation, focusable, `role="button"`). Spread `clickableProps` next to the existing `onClick`. Use instead of hand-rolling `role`/`tabIndex`/`onKeyDown` on clickable `<div>`/`<span>`/`<li>`. Also the shared predicate every app-global key handler consults: `shouldIgnoreGlobalKey(event, { enabledInDialog?, ignoreRepeat?, allowChords? })` — the single "must this handler stand down?" answer (editable target, native Space button activation, ⌘/Ctrl/Alt chord, OS auto-repeat, open `aria-modal` dialog), used by `useKeyboardShortcuts`, `useKeyCapture` AND the voice widget's push-to-talk hotkey so their guard lists can't drift. Add a new guard there, not at one caller. Its parts are exported too: `isEditableTarget(el)`, `isButtonActivation(event)` (true when Space would natively activate the focused button) and `isPressKey(event)` (Enter or Space by either `key` or `code`). Also `isFocusEscapeKey(event)` — the shared "leave this widget" gesture (Shift+Tab backtab) that a key-capturing widget must release to the browser; the Shell terminal's `attachCustomKeyEventHandler` consults it so focus can escape the xterm trap. Plus `noPointerFocusSurfaceProps` — spread on the ROOT of a surface that owns a key globally (a Space-scored drill, the Morse keyer, RapidReader, the OpenWorld HUD); one capture-phase handler stops a mouse click anywhere inside from parking focus on a button and taking that key over via native activation, covering controls added later too. |
| `agentOutcome.js` | Re-export of `server/lib/agentOutcome.js`: `isAgentHandoff(agent)` — `result.resumed === true` — tells a record retired to hand its task to a continuation, a Resume or a provider Relaunch, from one that reached a verdict, and `agentHandoffReason(agent)` gives the line such a card should show. Cards reading `result.success` alone rendered a red "Failed" run for a swap the user made deliberately, and the needs-feedback filter asked them to rate it. Imported rather than copied so the run card and the daily report cannot disagree about whether a swap was a failure. |
+| `cosAgentFeedback.js` | Client mirror of the server-owned CoS feedback eligibility, rating, legacy-update-target, and archive-locator predicates. |
| `agentResumeOutcome.js` | `agentResumeMessage(result, messages, fallback)` — the toast wording for a CoS agent resume/relaunch result. The server answers with a `mode` (what it did to the task) plus `spawned`/`spawnHold` (whether it also STARTED it — a resumed task is force-spawned when a slot is free, and `spawnHold` names the refusal when it isn't). `messages` is keyed by mode as `{ queued, running? }`; a mode with no `running` variant is one that deliberately queues nothing, so it can never be reported as started. Shared by the Resume dialog (`cos/tabs/AgentsTab.jsx`) and `cos/tabs/RelaunchAgentModal.jsx` so neither can say "queued" for a run that already started, or omit the reason it didn't. |
| `appIdentity.js` | `PORTOS_APP_ID` — stable id of the baseline PortOS app. Re-exported from `server/lib/appIdentity.js`; dependency-free so a module reachable from a server test can import it. |
| `applyManuscriptEdits.js` | `applyEditsToContent(content, edits, anchorQuote)` — PREVIEW-ONLY client mirror of the server's accept splice (`server/services/pipeline/manuscriptFix.js`): locate each `find` (nearest the anchor when recurring), drop overlaps, replace bottom-up. Powers the Manuscript editor's whole-manuscript impact preview. |
diff --git a/client/src/lib/cosAgentFeedback.js b/client/src/lib/cosAgentFeedback.js
new file mode 100644
index 0000000000..01c76fda7a
--- /dev/null
+++ b/client/src/lib/cosAgentFeedback.js
@@ -0,0 +1,15 @@
+/**
+ * Client mirror of the server-owned CoS feedback eligibility contract.
+ */
+
+export {
+ FEEDBACK_RATINGS,
+ feedbackArchiveDate,
+ hasValidAgentFeedback,
+ isAgentFeedbackEligible,
+ isAgentFeedbackTarget,
+ isAgentFeedbackUpdateTarget,
+ isFeedbackRating,
+ isManualUserAgent,
+ isSystemAgent,
+} from '../../../server/lib/cosAgentFeedback.js';
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 04701399ff..3cc6ef047f 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -93,6 +93,7 @@ export * from './goalFeatureMap.js';
// === Generic UI / collection utilities ===
export * from './a11yKeyboard.js';
export * from './agentOutcome.js';
+export * from './cosAgentFeedback.js';
export * from './agentResumeOutcome.js';
export * from './appIdentity.js';
export * from './applyManuscriptEdits.js';
diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsx
index b59ef63115..26d9351f0b 100644
--- a/client/src/pages/ChiefOfStaff.test.jsx
+++ b/client/src/pages/ChiefOfStaff.test.jsx
@@ -34,6 +34,7 @@ const api = vi.hoisted(() => ({
// AgentsTab, reached by the mobile-select navigation test below.
getCosAgentDates: vi.fn(),
getCosAgentsByDate: vi.fn(),
+ getCosPendingAgentFeedback: vi.fn(),
}));
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
const socketStub = vi.hoisted(() => ({ connected: false, on: vi.fn(), off: vi.fn(), emit: vi.fn() }));
@@ -122,6 +123,7 @@ beforeEach(() => {
api.getRiggedAvatars.mockResolvedValue({ records: [] });
api.getCosAgentDates.mockResolvedValue({ dates: [] });
api.getCosAgentsByDate.mockResolvedValue([]);
+ api.getCosPendingAgentFeedback.mockResolvedValue({ agents: [], count: null });
localLlm.getLocalLlmStatus.mockResolvedValue({ ollama: { models: [] }, lmstudio: { models: [] } });
localLlm.getToolUseModels.mockResolvedValue({ models: [] });
});
@@ -1038,4 +1040,3 @@ describe('avatar-style registry coverage', () => {
}
});
});
-
diff --git a/client/src/pages/Review.jsx b/client/src/pages/Review.jsx
index 65ed3132ba..34f47e903c 100644
--- a/client/src/pages/Review.jsx
+++ b/client/src/pages/Review.jsx
@@ -56,6 +56,7 @@ const QUEUE_INVALIDATION_EVENTS = [
'brain:classified', // inbox item classified / re-reviewed
'cos:tasks:user:changed', // CoS user-task list changed
'cos:tasks:cos:changed', // CoS internal-task list changed
+ 'cos:agent:completed', // a newly completed run may need feedback
'messages:changed', // draft approved/deleted/status changed
'messages:draft:created', // new draft awaiting review
'messages:draft:sent', // draft sent (resolves a drafts row)
@@ -75,6 +76,7 @@ const QUEUE_SOURCE_CONFIG = {
ask: { icon: MessageCircle, color: 'text-port-accent' },
cos: { icon: Crown, color: 'text-port-accent' },
drafts: { icon: Mail, color: 'text-port-accent' },
+ feedback: { icon: MessageCircle, color: 'text-port-warning' },
health: { icon: Activity, color: 'text-port-warning' },
backup: { icon: DatabaseBackup, color: 'text-port-error' },
threads: { icon: BrainIcon, color: 'text-port-accent-2' },
@@ -296,13 +298,13 @@ export default function Review() {
navigate(`/review/${encodeURIComponent(item.id)}?view=${actionView}`);
};
- const handleQueueResolve = async (item, operation) => {
+ const handleQueueResolve = async (item, operation, input = {}) => {
if (resolvingQueueIds.has(item.id)) return;
setResolvingQueueIds(prev => new Set(prev).add(item.id));
// The helper toasts on failure (default), so don't add a custom catch toast.
const ok = await api.resolveReviewQueueItem(
item.id,
- operation ? { operation } : {},
+ operation ? { operation, ...input } : {},
).then(() => true).catch(() => false);
setResolvingQueueIds(prev => {
const next = new Set(prev);
@@ -735,6 +737,59 @@ function QueueMetaChips({ meta }) {
// Promote-target label for the Ask picker buttons.
const PROMOTE_TARGET_LABEL = { brain: 'Brain', task: 'Task', goal: 'Goal' };
+function FeedbackRatingControls({ id, onSubmit, disabled = false, options = ['positive', 'negative', 'neutral'] }) {
+ const [rating, setRating] = useState('');
+ const [comment, setComment] = useState('');
+ const safeId = String(id || 'feedback').replace(/[^a-zA-Z0-9_-]/g, '-');
+ const ratingId = `feedback-rating-${safeId}`;
+ const commentId = `feedback-comment-${safeId}`;
+ const submit = () => {
+ if (!rating) return;
+ const trimmedComment = comment.trim();
+ onSubmit({ rating, ...(trimmedComment ? { comment: trimmedComment } : {}) });
+ };
+
+ return (
+ <div className="flex items-end gap-2 flex-wrap rounded-md border border-port-border/60 bg-port-bg/40 p-2">
+ <label className="text-xs text-gray-400" htmlFor={ratingId}>
+ Rating (required)
+ <select
+ id={ratingId}
+ value={rating}
+ onChange={(event) => setRating(event.target.value)}
+ disabled={disabled}
+ className="mt-1 block min-h-[36px] rounded border border-port-border bg-port-card px-2 py-1 text-xs text-white focus:outline-none focus-visible:ring-2 focus-visible:ring-port-accent disabled:opacity-50"
+ >
+ <option value="">Choose…</option>
+ {options.map((option) => (
+ <option key={option} value={option}>{option[0].toUpperCase() + option.slice(1)}</option>
+ ))}
+ </select>
+ </label>
+ <label className="min-w-[12rem] flex-1 text-xs text-gray-400" htmlFor={commentId}>
+ Comment (optional)
+ <input
+ id={commentId}
+ value={comment}
+ onChange={(event) => setComment(event.target.value)}
+ maxLength={5000}
+ disabled={disabled}
+ className="mt-1 block min-h-[36px] w-full rounded border border-port-border bg-port-card px-2 py-1 text-xs text-white focus:outline-none focus-visible:ring-2 focus-visible:ring-port-accent disabled:opacity-50"
+ />
+ </label>
+ <button
+ type="button"
+ onClick={submit}
+ disabled={disabled || !rating}
+ className="inline-flex min-h-[36px] items-center gap-1 rounded-md border border-port-success/30 bg-port-success/10 px-2 py-1 text-xs font-medium text-port-success hover:bg-port-success/20 disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ <Check size={14} />
+ Rate
+ </button>
+ </div>
+ );
+}
+
function QueueRow({ item, onSelect, onDrill, onDismiss, onResolve, onPromoteAsk, resolving = false }) {
const config = QUEUE_SOURCE_CONFIG[item.source] || { icon: Inbox, color: 'text-gray-400' };
const Icon = config.icon;
@@ -748,9 +803,10 @@ function QueueRow({ item, onSelect, onDrill, onDismiss, onResolve, onPromoteAsk,
const sourceOperations = !promoteTargets.length && Array.isArray(item.operations)
? item.operations.filter(operation => operation && operation.available !== false)
: [];
+ const rateOperation = sourceOperations.find((operation) => operation.id === 'rate' && operation.input?.type === 'rating');
const inlineActions = item.action
? [{ id: 'resolve', label: item.action }]
- : sourceOperations;
+ : sourceOperations.filter((operation) => operation.id !== 'rate');
return (
<div className={`flex items-start gap-3 p-3 rounded-lg border bg-port-card ${borderTone}`}>
@@ -783,6 +839,14 @@ function QueueRow({ item, onSelect, onDrill, onDismiss, onResolve, onPromoteAsk,
)}
</div>
<div className="flex items-center gap-2 shrink-0 flex-wrap justify-end">
+ {onResolve && rateOperation && (
+ <FeedbackRatingControls
+ id={item.id}
+ options={rateOperation.input.options}
+ disabled={resolving}
+ onSubmit={(input) => onResolve(item, rateOperation.id, input)}
+ />
+ )}
{onResolve && inlineActions.map(action => (
<button
key={action.id}
@@ -1096,8 +1160,8 @@ function ActionDetail({ item, onClose, onResolve, onSaved, onDrill }) {
const localStatus = item.meta?.localStatus || record?.status || item.meta?.status;
const externalState = item.meta?.externalState;
const updateDraft = (patch) => setDraft((previous) => ({ ...previous, ...patch }));
- const resolve = async (operation) => {
- const ok = await onResolve(item, operation);
+ const resolve = async (operation, input = {}) => {
+ const ok = await onResolve(item, operation, input);
if (ok) onClose();
};
@@ -1185,9 +1249,16 @@ function ActionDetail({ item, onClose, onResolve, onSaved, onDrill }) {
{operations.length > 0 && (
<section className="flex flex-wrap gap-2">
{operations.map((operation) => (
- <button key={operation.id} type="button" onClick={() => resolve(operation.id)} className="inline-flex items-center gap-2 rounded bg-port-success/10 border border-port-success/30 px-3 py-2 text-sm text-port-success hover:bg-port-success/20">
- <Check size={14} /> {operation.label}
- </button>
+ operation.input?.type === 'rating'
+ ? <FeedbackRatingControls
+ key={operation.id}
+ id={`detail-${item.id}`}
+ options={operation.input.options}
+ onSubmit={(input) => resolve(operation.id, input)}
+ />
+ : <button key={operation.id} type="button" onClick={() => resolve(operation.id)} className="inline-flex items-center gap-2 rounded bg-port-success/10 border border-port-success/30 px-3 py-2 text-sm text-port-success hover:bg-port-success/20">
+ <Check size={14} /> {operation.label}
+ </button>
))}
</section>
)}
diff --git a/client/src/pages/Review.test.jsx b/client/src/pages/Review.test.jsx
index 7e73eb26fa..2904bd242e 100644
--- a/client/src/pages/Review.test.jsx
+++ b/client/src/pages/Review.test.jsx
@@ -57,6 +57,22 @@ const CREATED_PENDING_ITEM = {
description: 'Created after the completed view loaded.'
};
+const FEEDBACK_ITEM = {
+ id: 'feedback:agent-example',
+ source: 'feedback',
+ sourceLabel: 'CoS run feedback',
+ title: 'Rate completed CoS run',
+ summary: 'Review an example change',
+ timestamp: '2026-08-01T12:00:00.000Z',
+ drillTo: '/cos/agents/agent-example?feedback=needs-feedback',
+ operations: [{
+ id: 'rate',
+ label: 'Rate',
+ available: true,
+ input: { type: 'rating', required: true, options: ['positive', 'negative', 'neutral'] },
+ }],
+};
+
vi.mock('../services/api', () => ({
getReviewItems: vi.fn(() => Promise.resolve([ITEM, SHORT_ITEM, COMPLETED_ITEM])),
getReviewCounts: vi.fn(),
@@ -200,6 +216,23 @@ describe('Review Hub queue-card triage (#3282)', () => {
));
});
+ it('requires a rating before sending the source-owned feedback action', async () => {
+ api.getReviewQueue.mockResolvedValueOnce({ items: [FEEDBACK_ITEM], sources: {} });
+
+ render(<Review />);
+ const rate = await screen.findByRole('button', { name: 'Rate' });
+ expect(rate).toBeDisabled();
+
+ fireEvent.change(screen.getByLabelText('Rating (required)'), { target: { value: 'negative' } });
+ fireEvent.change(screen.getByLabelText('Comment (optional)'), { target: { value: 'Needs a clearer result.' } });
+ fireEvent.click(rate);
+
+ await waitFor(() => expect(api.resolveReviewQueueItem).toHaveBeenCalledWith(
+ FEEDBACK_ITEM.id,
+ { operation: 'rate', rating: 'negative', comment: 'Needs a clearer result.' },
+ ));
+ });
+
it('renders the full markdown behind Show more, height-capped', async () => {
forceOverflow();
render(<Review />);
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index c7dff9a6e6..be256a6800 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -238,6 +238,7 @@ export const getCosAgents = (options) => request('/cos/agents', options);
export const getCosAgentDates = ({ hydrate = false } = {}) =>
request(`/cos/agents/history${hydrate ? '?hydrate=1' : ''}`);
export const getCosAgentsByDate = (date) => request(`/cos/agents/history/${date}`);
+export const getCosPendingAgentFeedback = (options = {}) => request('/cos/agents/feedback/pending', options);
// `lines` caps the transcript TAIL the server hydrates (server default: 1000
// lines / 512 KB). Pass it when the record is wanted for its metadata rather
// than its log.
diff --git a/client/src/services/apiReview.js b/client/src/services/apiReview.js
index 6848d97bcc..629ad89ac8 100644
--- a/client/src/services/apiReview.js
+++ b/client/src/services/apiReview.js
@@ -18,11 +18,17 @@ export const getReviewQueue = ({ view, limit, cursor, ...options } = {}) => {
return request(`/review/queue${query}`, options);
};
// Resolve a single queue row in place (id is `<source>:<rawId>`). Source-owned
-// approvals may pass `operation` (approve/reject); transport options stay out
-// of the JSON body.
-export const resolveReviewQueueItem = (id, { operation, ...options } = {}) => request('/review/queue/resolve', {
+// approvals may pass `operation` (approve/reject); feedback's `rate` operation
+// additionally carries the required rating and optional comment. Transport
+// options stay out of the JSON body.
+export const resolveReviewQueueItem = (id, { operation, rating, comment, ...options } = {}) => request('/review/queue/resolve', {
method: 'POST',
- body: JSON.stringify({ id, ...(operation ? { operation } : {}) }),
+ body: JSON.stringify({
+ id,
+ ...(operation ? { operation } : {}),
+ ...(rating ? { rating } : {}),
+ ...(comment !== undefined ? { comment } : {}),
+ }),
...options
});
// Promote an Ask row's latest assistant answer into Brain, a CoS task, or a
diff --git a/client/src/services/apiReview.test.js b/client/src/services/apiReview.test.js
index f37a5ec250..ccbdc76ea3 100644
--- a/client/src/services/apiReview.test.js
+++ b/client/src/services/apiReview.test.js
@@ -61,4 +61,20 @@ describe('resolveReviewQueueItem', () => {
silent: true,
});
});
+
+ it('keeps feedback rating input in the mutation body', async () => {
+ request.mockResolvedValue({ resolved: true });
+
+ await resolveReviewQueueItem('feedback:agent-1', {
+ operation: 'rate', rating: 'negative', comment: 'Needs a follow-up', silent: true,
+ });
+
+ expect(request).toHaveBeenCalledWith('/review/queue/resolve', {
+ method: 'POST',
+ body: JSON.stringify({
+ id: 'feedback:agent-1', operation: 'rate', rating: 'negative', comment: 'Needs a follow-up',
+ }),
+ silent: true,
+ });
+ });
});
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 4565cafa0d..dcfbd59705 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -7,6 +7,8 @@ PortOS backs up two things together, into a single timestamped snapshot:
Now that PostgreSQL is a **required** dependency (it owns the creative catalog, memory, and a growing set of app-native records — see [Storage Classification Contract](./STORAGE.md)), **the database dump is part of required system state, not an optional extra.** A snapshot that captured `data/` but failed to capture the DB is incomplete, and PortOS surfaces that explicitly.
+The dump includes the machine-local `cos_pending_agent_feedback` reference index. Its source agent archive and metadata remain in the filesystem half of the same snapshot, so restoring both halves preserves pending feedback without exporting it through federation.
+
Implementation: `server/services/backup.js` (snapshot/dump/restore), `server/services/backupScheduler.js` (cron), `server/routes/backup.js` (API), and `server/routes/database.js` (DB export/sync).
## What gets backed up
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 1e8a8acf5e..cce78e9103 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -37,6 +37,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- `memories` / `memory_links` — long-term memory + pgvector similarity.
- `post_runs` / `post_attempts` — normalized MeatSpace POST test, benchmark, and training history. A run owns its planned composition and lifecycle timestamps; attempts carry queryable module/drill, difficulty/config version, correctness/score, latency/completion, hint/confidence, input mode, and scorer provenance, with the compatibility payload retained in JSONB. The complete attempt set is replaced in one transaction and stable client ids make retries idempotent. Migrated from `data/meatspace/post-sessions.json` and `post-training-log.json` by `server/scripts/migratePostRunsToDB.js`; the sources are parked as `.imported` recovery copies. **Intentionally machine-local — never federated** because cognitive-performance history is personal activity data. Adapter: `server/services/postRunStore.js` (legacy JSON only under the dev/test file escape hatch).
- `user_action_events` — the operator-action ledger (#5594, epic #5593): one row per action the HUMAN took in PortOS (queued a CoS task, edited/deleted/approved/force-spawned one, rated an agent run, hit Run Now on a scheduled task, saved settings; phase 3 / #5596 also records event-only creative/Brain pointers, instance-feature toggles, and CoS schedule updates that skip `PUT /api/settings`). The leftover-branch idle detector is a **consumer** of this ledger (plus live git state), not a store of its own. `db-primary` because the value is in querying it — by type, actor, target, and time window — which is exactly what a JSONL append log cannot do. Columns carry the queryable axes (`type`/`actor`/`happened_at`/`target`/`success`) with structured detail in `payload` JSONB and the hook site in `source` JSONB; a unique `(type, dedupe_key)` index plus `ON CONFLICT DO NOTHING` makes a retried request idempotent. Bounded inline after each insert by BOTH a 20,000-row cap and a 90-day age cap — no cron. Credential-shaped payload keys are dropped at write time and their paths listed under `payload.redactedKeys`. **Intentionally machine-local — never federated**: it records what one operator did on one machine, and this ledger has no cross-machine merge contract. This is a store-specific implementation boundary, not a ban on syncing personal records to the user's own machines (ADR [user-controlled federation](./decisions/2026-09-19-user-controlled-federation.md)); guarded in `server/services/sharing/peerSync.test.js`. Deliberately NOT in `auditedTables` — auditing an audit log doubles every row, same rationale as `post_runs`. Adapter: `server/services/userActions.js` (file backend only under the dev/test escape hatch).
+- `cos_pending_agent_feedback` — a bounded, machine-local index of completed manual CoS runs that still need a human rating. It stores only `agent_id` plus the archive date locator; the agent archive remains the source-owned record and the rating is removed from this index only after that archive carries the durable rating. PostgreSQL is authoritative in normal installs (with the documented file backend only for dev/test), the input-gated migration 008 derives existing refs from live state without a seed or provider call, and future completion events enroll new refs. **Intentionally machine-local — never federated**; the DB dump backs it up alongside the agent archive under the filesystem snapshot. Adapter: `server/services/cosAgentFeedbackStore.js`.
- `creative_director_projects` — Creative Director project/treatment/scene/run state, one row per project (`id`/`status`/timestamps as columns, the full record in `data` JSONB). Migrated from the monolithic `data/creative-director-projects.json` in Phase 3 (#997); CD is local-only, so the row carries no sync cursor/tombstone. Adapter: `server/services/creativeDirector/projectsDB.js`.
- `catalog_user_types` — user-defined ingredient types (the registry that defines catalog row semantics), one row per type (`id` PK, the definition in `data` JSONB, `updated_at`/`deleted_at` mirroring the federation LWW clock + tombstone). Migrated from the `data/settings.json` `catalogUserTypes` slice in Phase 4 lead-in (#1001) so type evolution versions/syncs alongside the catalog data it governs. Federates via the catalog sync `catalogTypes` envelope block (wire shape unchanged by the move). Adapter: `server/services/catalogUserTypes/db.js`, dispatched via `store.js`.
- `universes` / `universe_runs` — Universe Builder records (canon bibles, categories, composite sheets, locks, influences, and portable character production packages) one row per universe with the full sanitized record in `data` JSONB and `name`/`schema_version`/`ephemeral`/`updated_at`/`deleted`/`deleted_at` mirrored into columns; render-run history one row per run (local-only, capped 200, never federated). Character production packages carry only versioned voice direction and approved managed-image roles; local profiles, recordings, provider ids, and training artifacts are excluded from the federated wire. Migrated from `data/universes/{id}/index.json` (collectionStore) in Phase 3 Create slice 1 (#1014). **NO `sync_sequence`** — universes federate via the EXISTING `dataSync` snapshot/push model (LWW on the body's `updatedAt`), so the storage swap is invisible to peers (no schema-version bump). The store bumps an in-process mutation epoch on every write that `dataSync` folds into its checksum fingerprint, since a DB edit no longer changes the `data/universes/` directory the fingerprint used to watch. **`universe_runs` is intentionally never federated** — a regenerable render cache under a 200-row *global* cap that two producers would mutually evict, while the durable universe record already syncs (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724). Adapter: `server/services/universeBuilder/db.js`, dispatched via `store.js`. **One universe ships with the product:** `universe-reality` ("Reality"), seeded by `scripts/migrations/395-reality-universe-seed.js` — not by `data.reference/`, because universes are PG rows and `setup-data.js` only copies files. It carries the federated `factual: true` flag (#7616), which marks a world whose people and places are real so the catalog extractor reads captured text as lived record rather than invented story; `factual` is persisted ONLY when true, so every fiction universe keeps its exact on-disk shape and wire checksum, and `PORTOS_SCHEMA_VERSIONS.universes` is 12 so a `factual`-unaware peer cannot strip-then-LWW the flag away. The migration gates on the ABSENCE of any row with that id — tombstone included — so a Reality the user deleted is never resurrected by an upgrade.
diff --git a/server/lib/README.md b/server/lib/README.md
index dd5eed8981..853caab7b6 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -52,6 +52,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `spriteAnimationTracks.js` | The animation-track registry (`ANIMATION_TRACKS`, `WALK_TRACK`, `TRACK_BOUND_TRIPLES`, `AUTHORED_TRACK_FIELDS`) — a zero-import table of per-track frame/fps bounds. |
| `spriteAnimationTrackStore.js` | The EFFECTIVE track table — compiled built-ins plus the user-defined store read from one small JSON config, so sprite schemas stay module-load constants rather than lazily-built. |
| `agentOutcome.js` | Is a completed CoS agent record an OUTCOME, or a HANDOFF to its own continuation? `isAgentHandoff(agent)` — `result.resumed === true`, what `resumeAgent`/`relaunchAgent` stamps when it retires a record and requeues the SAME task, typically because the user swapped providers after a usage limit. Every consumer that read `result.success` as the verdict booked a phantom failure per swap — a red history card, a failed task in the daily report and weekly digest, a dented success rate, a quota-burn denial recorded against "Relaunched by user", a feature agent flipped to `error` — so the rule task-learning already applied lives here once. Reads only `result`, so `completeAgent`'s stats writer can ask it before the record exists. Keyed on a field `resumeAgent` has always written, so archived relaunches reclassify retroactively with no migration. Also carries `agentHandoffReason(agent)` — `metadata.pauseReason` when a continuation was queued, else `result.error`, so an abandoned run is not captioned as a deliberate provider swap — and `isQueuedContinuation(agent)`, the narrower check for a caller about to SKIP its own completion handling because it expects a continuation run to fire it instead: `isAgentHandoff` alone is not proof a continuation exists (a stranded pause retirement also stamps `resumed: true` with nothing requeued), so use this one there. `client/src/lib/agentOutcome.js` re-exports this file rather than copying it. |
+| `cosAgentFeedback.js` | Pure shared eligibility, rating, update-target, and archive-locator predicates for durable CoS feedback actions; mirrored to the client so the queue and Agents tab use the server contract. |
| `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). |
| `agentRunEvents.js` | CoS run lifecycle-event envelope (#4540) — pure half of the append-only ledger in `services/agentRunEventLog.js`. `AGENT_RUN_EVENT_KINDS` (closed vocabulary: spawned, handoff, output, reconnected, paused, resumed, interrupted, pr-verified, orphan-recovered, runner-recovered, finalized), `agentRunEventSchema` (Zod, `.strict()`), `buildRunEvent()` which redacts then mints a CONTENT-derived `eventId` (sha256 of the canonicalized envelope) so a redelivered lifecycle transition dedupes instead of double-counting, `redactRunEventData()` (drops prompt/description/output/result-class keys to a `{ redacted, chars }` stub, scrubs the home-dir prefix out of every remaining string via `scrubHomePath`, runs `redactOutput`, and caps string/array/key/depth per `RUN_EVENT_LIMITS`), and `projectRunStates()` — the clock-free fold that derives current run status from the ordered stream, so replay-after-restart and read-current-status are one code path. Unknown kinds fold as no-ops so a newer install's ledger replays on an older one. |
| `agentRunReconcile.js` | CoS run reconciliation (#4540) — pure diff between a ledger projection (`projectRunStates`) and the durable run record. Closed finding vocabulary `RUN_RECONCILE_FINDINGS` (`record-open`, `record-missing`, `verdict-mismatch`, `ledger-open`), `diffRunRecord()`, `reconcileRunRecords()` with a zero-filled per-kind summary, and `planRunRecordRepair()` — the metadata patch that closes a record the ledger proves is finished. Repairs are one-directional (ledger → record) by design: a record closed while the ledger missed the close is reported, never back-filled, so the stream stays an audit of the record rather than a copy of it. I/O half: `services/agentRunReconciler.js`. |
diff --git a/server/lib/cosAgentFeedback.js b/server/lib/cosAgentFeedback.js
new file mode 100644
index 0000000000..c02aa8e349
--- /dev/null
+++ b/server/lib/cosAgentFeedback.js
@@ -0,0 +1,63 @@
+/**
+ * Shared CoS feedback eligibility rules.
+ *
+ * The queue, pending-feedback store, server submission boundary, and Agents
+ * tab must agree on exactly which completed runs can receive a human rating.
+ * Keep this module pure so the client can re-export the same predicates.
+ */
+
+import { isAgentHandoff } from './agentOutcome.js';
+
+export const FEEDBACK_RATINGS = Object.freeze(['positive', 'negative', 'neutral']);
+
+const FEEDBACK_RATING_SET = new Set(FEEDBACK_RATINGS);
+const DATE_BUCKET_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
+
+export function isFeedbackRating(value) {
+ return FEEDBACK_RATING_SET.has(value);
+}
+
+export function hasValidAgentFeedback(agent) {
+ return isFeedbackRating(agent?.feedback?.rating);
+}
+
+export function isSystemAgent(agent) {
+ return agent?.taskId?.startsWith('sys-') || agent?.id?.startsWith('sys-');
+}
+
+export function isManualUserAgent(agent) {
+ return agent?.metadata?.taskType === 'user';
+}
+
+/** True when a completed record is a valid target, even if already rated. */
+export function isAgentFeedbackTarget(agent) {
+ return agent?.status === 'completed'
+ && !isSystemAgent(agent)
+ && isManualUserAgent(agent)
+ && !isAgentHandoff(agent);
+}
+
+/** True only for an unrated completed manual user run. */
+export function isAgentFeedbackEligible(agent) {
+ return isAgentFeedbackTarget(agent) && !hasValidAgentFeedback(agent);
+}
+
+/**
+ * A legacy handoff may already carry a rating from before handoffs left the
+ * feedback queue. Keep that existing card editable without making an unrated
+ * handoff actionable again.
+ */
+export function isAgentFeedbackUpdateTarget(agent) {
+ return isAgentFeedbackTarget(agent) || (
+ isAgentHandoff(agent)
+ && hasValidAgentFeedback(agent)
+ && !isSystemAgent(agent)
+ && isManualUserAgent(agent)
+ );
+}
+
+/** Return the archive locator encoded by a completed record, if valid. */
+export function feedbackArchiveDate(agent) {
+ const date = typeof agent?.completedAt === 'string' ? agent.completedAt.slice(0, 10) : null;
+ return DATE_BUCKET_PATTERN.test(date || '') ? date : null;
+}
diff --git a/server/lib/cosAgentFeedback.test.js b/server/lib/cosAgentFeedback.test.js
new file mode 100644
index 0000000000..62edaefa12
--- /dev/null
+++ b/server/lib/cosAgentFeedback.test.js
@@ -0,0 +1,55 @@
+import { describe, expect, it } from 'vitest';
+import {
+ FEEDBACK_RATINGS,
+ feedbackArchiveDate,
+ hasValidAgentFeedback,
+ isAgentFeedbackEligible,
+ isAgentFeedbackTarget,
+ isAgentFeedbackUpdateTarget,
+ isFeedbackRating,
+} from './cosAgentFeedback.js';
+
+const completedManual = {
+ id: 'agent-example',
+ status: 'completed',
+ completedAt: '2026-08-01T10:00:00.000Z',
+ metadata: { taskType: 'user' },
+};
+
+describe('CoS feedback eligibility contract', () => {
+ it('accepts only the three source-owned ratings', () => {
+ expect(FEEDBACK_RATINGS).toEqual(['positive', 'negative', 'neutral']);
+ expect(FEEDBACK_RATINGS.every(isFeedbackRating)).toBe(true);
+ expect(isFeedbackRating('helpful')).toBe(false);
+ expect(isFeedbackRating(null)).toBe(false);
+ });
+
+ it.each([
+ ['completed manual run', completedManual, true, true, true],
+ ['already rated run', { ...completedManual, feedback: { rating: 'positive' } }, true, false, true],
+ ['running run', { ...completedManual, status: 'running' }, false, false, false],
+ ['scheduled run', { ...completedManual, metadata: { taskType: 'internal' } }, false, false, false],
+ ['system id', { ...completedManual, id: 'sys-health' }, false, false, false],
+ ['system task', { ...completedManual, taskId: 'sys-health' }, false, false, false],
+ ['unrated handoff run', { ...completedManual, result: { resumed: true } }, false, false, false],
+ ['already rated handoff run', { ...completedManual, result: { resumed: true }, feedback: { rating: 'positive' } }, false, false, true],
+ ['already rated system handoff', { ...completedManual, id: 'sys-health', result: { resumed: true }, feedback: { rating: 'positive' } }, false, false, false],
+ ])('classifies %s', (_label, agent, target, eligible, updateTarget) => {
+ expect(isAgentFeedbackTarget(agent)).toBe(target);
+ expect(isAgentFeedbackEligible(agent)).toBe(eligible);
+ expect(isAgentFeedbackUpdateTarget(agent)).toBe(updateTarget);
+ });
+
+ it('distinguishes valid feedback from an absent or malformed rating', () => {
+ expect(hasValidAgentFeedback({ feedback: { rating: 'neutral' } })).toBe(true);
+ expect(hasValidAgentFeedback({ feedback: { rating: '' } })).toBe(false);
+ expect(hasValidAgentFeedback({ feedback: { rating: 'yes' } })).toBe(false);
+ expect(hasValidAgentFeedback({})).toBe(false);
+ });
+
+ it('uses only a valid completion date as the archive locator', () => {
+ expect(feedbackArchiveDate(completedManual)).toBe('2026-08-01');
+ expect(feedbackArchiveDate({ ...completedManual, completedAt: 'not-a-date' })).toBe(null);
+ expect(feedbackArchiveDate({ ...completedManual, completedAt: null })).toBe(null);
+ });
+});
diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.md
index ea0e56d3eb..4c0fee62c8 100644
--- a/server/lib/db/schema/README.md
+++ b/server/lib/db/schema/README.md
@@ -29,6 +29,7 @@ init-db.sql, each with a one-line reason.
| `post.js` | `postDdl` | MeatSpace POST normalized runs and attempts (machine-local) |
| `commissions.js` | `commissionsDdl` | Creative Commissions + feedback (machine-local) |
| `userActions.js` | `userActionsDdl` | Operator-action ledger — what the human did in the UI (machine-local) |
+| `cosAgentFeedback.js` | `cosAgentFeedbackDdl` | Durable machine-local references to completed manual CoS runs awaiting a rating (agent id + archive locator only) |
| `aiGraph.js` | `aiGraphDdl` | AI provider connection graph — connections, harness bindings, executable route bindings (machine-local) |
| `catalog.js` | `catalogDdl`, `catalogUserTypesDdl` | Catalog scraps/ingredients/tags/media + user-defined types |
| `media.js` | `mediaDdl` | Creative-director / music-video projects, mood boards, media assets |
@@ -45,7 +46,7 @@ init-db.sql, each with a one-line reason.
### Composer (`index.js`)
-- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `post` → `commissions` → `userActions` → `aiGraph`).
+- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `post` → `commissions` → `userActions` → `cosAgentFeedback` → `aiGraph`).
- `buildCatalogDdl()` → phase-2 list (`catalog` → `media` → `catalogUserTypes` →
`universes` → `library` → `pipeline` → `writersRoom` → `lora` → `privacy` → `stackerNews` → `x` →
`beeper` → `audit` DDL → audit triggers).
diff --git a/server/lib/db/schema/cosAgentFeedback.js b/server/lib/db/schema/cosAgentFeedback.js
new file mode 100644
index 0000000000..edd1e31d6e
--- /dev/null
+++ b/server/lib/db/schema/cosAgentFeedback.js
@@ -0,0 +1,10 @@
+// Machine-local references to completed manual CoS runs that still need a user
+// rating. The agent archive remains authoritative for the run and its rating;
+// this table stores only the id plus the date-bucket locator so retention and
+// restart cannot silently erase the action.
+export const cosAgentFeedbackDdl = [
+ `CREATE TABLE IF NOT EXISTS cos_pending_agent_feedback (
+ agent_id TEXT PRIMARY KEY,
+ archive_date TEXT
+ )`,
+];
diff --git a/server/lib/db/schema/index.js b/server/lib/db/schema/index.js
index d7566bb9f8..9a7595a669 100644
--- a/server/lib/db/schema/index.js
+++ b/server/lib/db/schema/index.js
@@ -19,6 +19,7 @@ import { humanActivityDdl } from './humanActivity.js';
import { postDdl } from './post.js';
import { commissionsDdl } from './commissions.js';
import { userActionsDdl } from './userActions.js';
+import { cosAgentFeedbackDdl } from './cosAgentFeedback.js';
import { aiGraphDdl } from './aiGraph.js';
import { catalogDdl, catalogUserTypesDdl } from './catalog.js';
import { mediaDdl } from './media.js';
@@ -42,6 +43,7 @@ export {
postDdl,
commissionsDdl,
userActionsDdl,
+ cosAgentFeedbackDdl,
aiGraphDdl,
catalogDdl,
catalogUserTypesDdl,
@@ -73,6 +75,7 @@ export function buildUpgradeDdl() {
...postDdl,
...commissionsDdl,
...userActionsDdl,
+ ...cosAgentFeedbackDdl,
...aiGraphDdl,
];
}
diff --git a/server/lib/db/schema/schema.test.js b/server/lib/db/schema/schema.test.js
index d0760d58d1..e16608d400 100644
--- a/server/lib/db/schema/schema.test.js
+++ b/server/lib/db/schema/schema.test.js
@@ -25,7 +25,7 @@ import {
} from './index.js';
const DOMAIN_ARRAYS = [
- 'coreDdl', 'tribeDdl', 'humanActivityDdl', 'postDdl', 'commissionsDdl', 'userActionsDdl', 'aiGraphDdl',
+ 'coreDdl', 'tribeDdl', 'humanActivityDdl', 'postDdl', 'commissionsDdl', 'userActionsDdl', 'cosAgentFeedbackDdl', 'aiGraphDdl',
'catalogDdl', 'catalogUserTypesDdl', 'mediaDdl', 'universesDdl',
'libraryDdl', 'pipelineDdl', 'writersRoomDdl', 'loraDdl', 'privacyDdl', 'stackerNewsDdl', 'xDdl',
'beeperDdl', 'mindToolRecipesDdl',
@@ -48,6 +48,7 @@ describe('db/schema barrel + composer (#2832)', () => {
...schema.postDdl,
...schema.commissionsDdl,
...schema.userActionsDdl,
+ ...schema.cosAgentFeedbackDdl,
...schema.aiGraphDdl,
];
expect(buildUpgradeDdl()).toEqual(expected);
diff --git a/server/lib/index.js b/server/lib/index.js
index 95ca6a3277..5dde8ed2ca 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -322,6 +322,7 @@ export * from './zipWriter.js';
// === Process execution ===
export * from './agentGuard/index.js';
export * from './agentOutcome.js';
+export * from './cosAgentFeedback.js';
export * from './agentOutputMarkers.js';
export * from './agentRunEvents.js';
export * from './agentRunReconcile.js';
diff --git a/server/routes/cos.test.js b/server/routes/cos.test.js
index 0b277961ab..a6a1f78ac1 100644
--- a/server/routes/cos.test.js
+++ b/server/routes/cos.test.js
@@ -52,6 +52,7 @@ vi.mock('../services/cos.js', () => ({
getAgents: vi.fn(),
getAgentDates: vi.fn(),
getAgentsByDate: vi.fn(),
+ getPendingAgentFeedback: vi.fn(),
getAgent: vi.fn(),
deleteAgent: vi.fn(),
clearCompletedAgents: vi.fn(),
@@ -1702,6 +1703,23 @@ describe('CoS Routes', () => {
});
});
+ describe('GET /api/cos/agents/feedback/pending', () => {
+ it('returns the durable count and the reconciled eligible agent projection', async () => {
+ cos.getPendingAgentFeedback.mockResolvedValue({
+ count: 1,
+ agents: [{ id: 'agent-001', status: 'completed', metadata: { taskType: 'user' } }],
+ unavailable: [{ agentId: 'agent-old', availability: 'unavailable', unavailableReason: 'deleted' }],
+ });
+
+ const response = await request(app).get('/api/cos/agents/feedback/pending');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toMatchObject({ count: 1 });
+ expect(response.body.agents).toEqual([{ id: 'agent-001', status: 'completed', metadata: { taskType: 'user' } }]);
+ expect(response.body.unavailable).toEqual([{ agentId: 'agent-old', availability: 'unavailable', unavailableReason: 'deleted' }]);
+ });
+ });
+
describe('POST /api/cos/agents/:id/feedback', () => {
it('should submit positive feedback', async () => {
cos.submitAgentFeedback.mockResolvedValue({ success: true });
diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.js
index 52cdcda3ed..1a07b46c8c 100644
--- a/server/routes/cosAgentRoutes.js
+++ b/server/routes/cosAgentRoutes.js
@@ -86,6 +86,18 @@ router.get('/agents/history/:date', asyncHandler(async (req, res) => {
res.json(toAgentListItems(agents));
}));
+// GET /api/cos/agents/feedback/pending - Reconciled durable feedback actions.
+// The queue owns the action mutation; this endpoint feeds the Agents tab with
+// the same live/archive predicate and count without loading every date bucket.
+router.get('/agents/feedback/pending', asyncHandler(async (req, res) => {
+ const pending = await cos.getPendingAgentFeedback({ includeUnavailable: true });
+ res.json({
+ count: pending.count,
+ agents: toAgentListItems(pending.agents),
+ unavailable: pending.unavailable,
+ });
+}));
+
// GET /api/cos/agents/:id - Get agent by ID (transcript hydrated as a capped tail)
router.get('/agents/:id', asyncHandler(async (req, res) => {
const { lines } = validateRequest(agentQuerySchema, req.query);
diff --git a/server/routes/review.js b/server/routes/review.js
index 925dedbdc1..9e1ed0b825 100644
--- a/server/routes/review.js
+++ b/server/routes/review.js
@@ -52,15 +52,27 @@ router.get('/queue', asyncHandler(async (req, res) => {
const resolveQueueSchema = z.object({
id: z.string().min(1).max(500),
- operation: z.enum(['resolve', 'approve', 'reject', 'complete', 'reopen']).optional(),
+ operation: z.enum(['resolve', 'approve', 'reject', 'complete', 'reopen', 'rate']).optional(),
+ rating: z.enum(['positive', 'negative', 'neutral']).optional(),
+ comment: z.string().max(5000).optional(),
+}).superRefine((value, context) => {
+ if (value.operation === 'rate' && !value.rating) {
+ context.addIssue({ code: z.ZodIssueCode.custom, path: ['rating'], message: 'rating is required for the rate operation' });
+ }
+ if (value.operation !== 'rate' && (value.rating !== undefined || value.comment !== undefined)) {
+ context.addIssue({ code: z.ZodIssueCode.custom, path: ['operation'], message: 'rating and comment are only valid for the rate operation' });
+ }
});
// POST /api/review/queue/resolve — accept a single cross-domain queue row in
// place. Source-owned approvals carry an explicit operation so the mutation
// revalidates the owning domain instead of using generic Review completion.
router.post('/queue/resolve', asyncHandler(async (req, res) => {
- const { id, operation } = validateRequest(resolveQueueSchema, req.body);
- const result = operation ? await resolveQueueItem(id, operation) : await resolveQueueItem(id);
+ const { id, operation, rating, comment } = validateRequest(resolveQueueSchema, req.body);
+ const input = { ...(rating ? { rating } : {}), ...(comment !== undefined ? { comment } : {}) };
+ const result = operation
+ ? (Object.keys(input).length ? await resolveQueueItem(id, operation, input) : await resolveQueueItem(id, operation))
+ : await resolveQueueItem(id);
res.json(result);
}));
diff --git a/server/routes/review.test.js b/server/routes/review.test.js
index bf7536131a..0305579a7e 100644
--- a/server/routes/review.test.js
+++ b/server/routes/review.test.js
@@ -85,4 +85,23 @@ describe('POST /api/review/queue/resolve', () => {
expect(response.status).toBe(400);
expect(resolveQueueItem).not.toHaveBeenCalled();
});
+
+ it('requires a rating and forwards it for feedback actions', async () => {
+ const missing = await request(makeApp())
+ .post('/api/review/queue/resolve')
+ .send({ id: 'feedback:agent-1', operation: 'rate' });
+
+ expect(missing.status).toBe(400);
+ expect(resolveQueueItem).not.toHaveBeenCalled();
+
+ resolveQueueItem.mockResolvedValue({ source: 'feedback', id: 'feedback:agent-1', operation: 'rate', resolved: true });
+ const response = await request(makeApp())
+ .post('/api/review/queue/resolve')
+ .send({ id: 'feedback:agent-1', operation: 'rate', rating: 'positive', comment: 'Useful result' });
+
+ expect(response.status).toBe(200);
+ expect(resolveQueueItem).toHaveBeenCalledWith(
+ 'feedback:agent-1', 'rate', { rating: 'positive', comment: 'Useful result' },
+ );
+ });
});
diff --git a/server/scripts/db-migrations/008-cos-agent-feedback-refs.js b/server/scripts/db-migrations/008-cos-agent-feedback-refs.js
new file mode 100644
index 0000000000..2fb864c450
--- /dev/null
+++ b/server/scripts/db-migrations/008-cos-agent-feedback-refs.js
@@ -0,0 +1,37 @@
+/**
+ * Enroll completed manual CoS runs that are still waiting for a rating.
+ *
+ * This is an input-derived migration: state.json is the input, so the migration
+ * is gated on that input and deliberately ships no data.reference seed. It does
+ * not scan the historical archive or call a provider; the pending table is only
+ * an index that makes the action survive state eviction and restart.
+ */
+
+import { existsSync } from 'node:fs';
+import { STATE_FILE, loadState } from '../../services/cosState.js';
+import { feedbackArchiveDate, isAgentFeedbackEligible } from '../../lib/cosAgentFeedback.js';
+
+export function derivePendingFeedbackRefs(state) {
+ return Object.entries(state?.agents || {})
+ .map(([agentId, agent]) => ({ agentId: agent?.id || agentId, agent }))
+ .filter(({ agentId, agent }) => agentId && isAgentFeedbackEligible(agent))
+ .map(({ agentId, agent }) => ({ agentId, archiveDate: feedbackArchiveDate(agent) }));
+}
+
+export async function up(client) {
+ if (!existsSync(STATE_FILE)) {
+ console.log('🧾 CoS feedback refs: state input absent, skipped');
+ return;
+ }
+
+ const refs = derivePendingFeedbackRefs(await loadState());
+ for (const ref of refs) {
+ await client.query(
+ `INSERT INTO cos_pending_agent_feedback (agent_id, archive_date)
+ VALUES ($1, $2)
+ ON CONFLICT (agent_id) DO UPDATE SET archive_date = EXCLUDED.archive_date`,
+ [ref.agentId, ref.archiveDate],
+ );
+ }
+ console.log(`🧾 CoS feedback refs: enrolled ${refs.length} live run${refs.length === 1 ? '' : 's'}`);
+}
diff --git a/server/scripts/db-migrations/008-cos-agent-feedback-refs.test.js b/server/scripts/db-migrations/008-cos-agent-feedback-refs.test.js
new file mode 100644
index 0000000000..687c18f9cc
--- /dev/null
+++ b/server/scripts/db-migrations/008-cos-agent-feedback-refs.test.js
@@ -0,0 +1,59 @@
+import { describe, expect, it, vi } from 'vitest';
+
+const migrationFs = vi.hoisted(() => ({ existsSync: vi.fn() }));
+const migrationState = vi.hoisted(() => ({
+ STATE_FILE: '/tmp/example-cos-state.json',
+ loadState: vi.fn(),
+}));
+
+vi.mock('node:fs', async () => ({
+ ...(await vi.importActual('node:fs')),
+ existsSync: migrationFs.existsSync,
+}));
+
+vi.mock('../../services/cosState.js', () => migrationState);
+
+import { derivePendingFeedbackRefs, up } from './008-cos-agent-feedback-refs.js';
+
+const manualAgent = {
+ id: 'agent-example',
+ status: 'completed',
+ completedAt: '2026-08-01T10:00:00.000Z',
+ metadata: { taskType: 'user' },
+};
+
+describe('db-migration 008 — CoS feedback references', () => {
+ it('derives only unrated manual completed runs and no task prose', () => {
+ expect(derivePendingFeedbackRefs({
+ agents: {
+ keep: manualAgent,
+ rated: { ...manualAgent, id: 'agent-rated', feedback: { rating: 'positive' } },
+ scheduled: { ...manualAgent, id: 'agent-scheduled', metadata: { taskType: 'internal' } },
+ },
+ })).toEqual([{ agentId: 'agent-example', archiveDate: '2026-08-01' }]);
+ });
+
+ it('is input-gated when live state is absent', async () => {
+ migrationFs.existsSync.mockReturnValue(false);
+ migrationState.loadState.mockClear();
+ const query = vi.fn();
+
+ await up({ query });
+
+ expect(migrationState.loadState).not.toHaveBeenCalled();
+ expect(query).not.toHaveBeenCalled();
+ });
+
+ it('writes derived references without reading the archive or calling a provider', async () => {
+ migrationFs.existsSync.mockReturnValue(true);
+ migrationState.loadState.mockResolvedValue({ agents: { [manualAgent.id]: manualAgent } });
+ const query = vi.fn(async () => ({ rows: [] }));
+
+ await up({ query });
+
+ expect(query).toHaveBeenCalledWith(expect.stringContaining('INSERT INTO cos_pending_agent_feedback'), [
+ 'agent-example',
+ '2026-08-01',
+ ]);
+ });
+});
diff --git a/server/scripts/db-migrations/README.md b/server/scripts/db-migrations/README.md
index 5e35cc3375..f4572dc533 100644
--- a/server/scripts/db-migrations/README.md
+++ b/server/scripts/db-migrations/README.md
@@ -67,3 +67,8 @@ export async function up(client) {
- Keep each migration focused on one logical change.
- Prefer `.sql` for plain DDL; reach for `.js` only when you need to read rows,
branch, or transform data.
+
+The CoS feedback reference migration is input-gated: it derives rows from the
+install's existing `state.json` and therefore has no `data.reference` seed. A
+seed would be copied before the migration and could overwrite the meaning of a
+user's existing state.
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 7d2f6a7d89..5be79de7e1 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -246,6 +246,14 @@ CREATE INDEX IF NOT EXISTS idx_user_action_happened ON user_action_events (happe
CREATE INDEX IF NOT EXISTS idx_user_action_type_time ON user_action_events (type, happened_at DESC);
CREATE INDEX IF NOT EXISTS idx_user_action_actor_time ON user_action_events (actor, happened_at DESC);
+-- Machine-local CoS feedback obligations. Only the completed agent id and its
+-- archive date-bucket locator are retained here; prose and ratings stay with
+-- the source agent record and this table never enters federation payloads.
+CREATE TABLE IF NOT EXISTS cos_pending_agent_feedback (
+ agent_id TEXT PRIMARY KEY,
+ archive_date TEXT
+);
+
-- Auto-update updated_at and sync_sequence on content/metadata changes.
-- Skips bump for access-stat-only updates (access_count, last_accessed)
-- to avoid sync noise from read operations.
diff --git a/server/services/cos.js b/server/services/cos.js
index 569fa7858a..ad763673e4 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -67,7 +67,14 @@ 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, getPendingAgentFeedbackCount, extractTaskType } from './cosAgentFeedback.js';
+export {
+ submitAgentFeedback,
+ getFeedbackStats,
+ getPendingAgentFeedback,
+ getPendingAgentFeedbackCount,
+ initializeAgentFeedback,
+ extractTaskType,
+} from './cosAgentFeedback.js';
export { archiveStaleAgents, clearCompletedAgents } from './cosAgentArchive.js';
// Reports and activity (re-export for backward compat with `import * as cos`)
@@ -113,6 +120,7 @@ let daemonStartPromise = null;
// Internal imports for functions used in this module
import { pruneOldAgentArchives, loadAgentIndex } from './cosAgentIndex.js';
import { archiveStaleAgents as _archiveStaleAgents } from './cosAgentArchive.js';
+import { initializeAgentFeedback } from './cosAgentFeedback.js';
import { resolveAgentProviderAndModel } from './agentProviderResolution.js';
// Task generation + evaluation engine (extracted to cosTaskGenerator.js).
@@ -1442,6 +1450,7 @@ async function refillPerpetualForCompletedAgent(agent) {
*/
export async function init() {
await ensureDirectories();
+ initializeAgentFeedback();
// When an agent completes, refill perpetual work then dequeue the next task
cosEvents.on('agent:completed', (agent) => {
diff --git a/server/services/cosAgentFeedback.js b/server/services/cosAgentFeedback.js
index a370f1a716..aa6d9365fd 100644
--- a/server/services/cosAgentFeedback.js
+++ b/server/services/cosAgentFeedback.js
@@ -8,30 +8,31 @@
* (#3450) — callers import from here directly.
*/
-import { existsSync } from 'fs';
-import { join } from 'path';
+import { readFile } from 'node:fs/promises';
+import { join } from 'node:path';
import { cosEvents, emitLog } from './cosEvents.js';
-import { loadState, saveState, withStateLock, AGENTS_DIR } from './cosState.js';
+import { loadState, saveState, withStateLock } from './cosState.js';
import { atomicWrite, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { loadAgentIndex, getAgentDir } from './cosAgentIndex.js';
import { ServerError } from '../lib/errorHandler.js';
import { recordUserAction } from './userActions.js';
-import { isAgentHandoff } from '../lib/agentOutcome.js';
+import {
+ FEEDBACK_RATINGS,
+ feedbackArchiveDate,
+ hasValidAgentFeedback,
+ isAgentFeedbackEligible,
+ isAgentFeedbackTarget,
+ isAgentFeedbackUpdateTarget,
+ isFeedbackRating,
+} from '../lib/cosAgentFeedback.js';
+import {
+ listPendingAgentFeedbackRefs,
+ removePendingAgentFeedbackRef,
+ upsertPendingAgentFeedbackRef,
+} from './cosAgentFeedbackStore.js';
-const isSystemAgent = (agent) =>
- agent.taskId?.startsWith('sys-') || agent.id?.startsWith('sys-');
-
-// Only agents spawned from a manually-filled task form are worth asking the
-// user to rate. Scheduled-task and autopilot runs carry taskType 'internal'
-// and already get an automatic success/failure verdict from task-learning
-// (buildTaskTelemetryContext's outcomeSuccess) — asking for a manual rating
-// on top of that is redundant nagging, not a useful signal.
-const isManualUserAgent = (agent) => agent.metadata?.taskType === 'user';
-
-const FEEDBACK_RATINGS = new Set(['positive', 'negative', 'neutral']);
const ARCHIVE_READ_BATCH_SIZE = 50;
-
-const hasValidFeedback = (agent) => FEEDBACK_RATINGS.has(agent?.feedback?.rating);
+const hasValidFeedback = hasValidAgentFeedback;
// Completed agents are written to their date-bucket archive before they age out
// of live state. Feedback statistics therefore have to read both stores and
@@ -61,24 +62,113 @@ async function loadArchivedAgentsWithFeedback() {
return agents;
}
-// 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() {
+async function readArchivedAgent(agentId, dateBucket) {
+ const metadataPath = join(getAgentDir(agentId, dateBucket), 'metadata.json');
+ const read = await readFile(metadataPath, 'utf8').then(
+ (content) => ({ content }),
+ (error) => ({ error }),
+ );
+ if (read.error) {
+ return { kind: read.error.code === 'ENOENT' ? 'missing' : 'read-failed', metadataPath };
+ }
+ const { content } = read;
+ const raw = safeJSONParse(content, null, { allowArray: false });
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
+ return { kind: 'read-failed', metadataPath };
+ }
+ return {
+ kind: 'found',
+ metadataPath,
+ agent: { ...raw, id: raw.id || raw.agentId || agentId },
+ };
+}
+
+function unavailableFeedbackRef(ref, reason) {
+ return {
+ id: ref.agentId,
+ agentId: ref.agentId,
+ archiveDate: ref.archiveDate || null,
+ availability: 'unavailable',
+ unavailableReason: reason,
+ };
+}
+
+/**
+ * Reconcile the durable references with live state and indexed archive records.
+ * The only broad read here is live state plus the referenced archive files; it
+ * never scans the historical archive looking for work.
+ */
+export async function getPendingAgentFeedback({ includeUnavailable = false } = {}) {
const state = await loadState();
- return Object.values(state.agents)
- .filter(agent =>
- agent.status === 'completed' &&
- !isSystemAgent(agent) &&
- isManualUserAgent(agent) &&
- // A record Resume/Relaunch retired has no result to rate — the continuation
- // it handed the task to is the run that gets rated. Counting it banners a
- // review item the Agents queue then refuses to show rating buttons for, so
- // the banner never clears.
- !isAgentHandoff(agent) &&
- !agent.feedback?.rating)
- .length;
+ const refs = await listPendingAgentFeedbackRefs();
+ const refsById = new Map(refs.map((ref) => [ref.agentId, ref]));
+ const liveById = new Map(Object.entries(state?.agents || {}).map(([id, agent]) => [agent.id || id, agent]));
+
+ // Enrollment is also performed here so a live completion remains discoverable
+ // when an event arrived during a restart window or before the migration ran.
+ for (const [agentId, agent] of liveById) {
+ if (!isAgentFeedbackEligible(agent)) continue;
+ const ref = { agentId, archiveDate: feedbackArchiveDate(agent) };
+ refsById.set(agentId, ref);
+ await upsertPendingAgentFeedbackRef(ref);
+ }
+
+ const idx = refsById.size > 0 ? await loadAgentIndex() : new Map();
+ const agents = [];
+ const unavailable = [];
+
+ for (const ref of refsById.values()) {
+ const live = liveById.get(ref.agentId);
+ if (live) {
+ if (isAgentFeedbackEligible(live)) {
+ agents.push(live);
+ continue;
+ }
+
+ // A rated live record is not actionable, but retain its reference until
+ // the same rating is durable in the archive. This prevents archive
+ // eviction from resurrecting a rating obligation after a partial write.
+ if (isAgentFeedbackTarget(live) && hasValidFeedback(live)) {
+ const archived = await readArchivedAgent(ref.agentId, idx.get(ref.agentId) || ref.archiveDate);
+ if (archived.kind === 'found' && hasValidFeedback(archived.agent)) {
+ await removePendingAgentFeedbackRef(ref.agentId);
+ }
+ continue;
+ }
+
+ await removePendingAgentFeedbackRef(ref.agentId);
+ continue;
+ }
+
+ const archiveDate = idx.get(ref.agentId) || ref.archiveDate;
+ if (!archiveDate) {
+ if (includeUnavailable) unavailable.push(unavailableFeedbackRef(ref, 'deleted'));
+ continue;
+ }
+
+ const archived = await readArchivedAgent(ref.agentId, archiveDate);
+ if (archived.kind === 'read-failed') {
+ // An indexed reference with an unreadable metadata file is not proof that
+ // the run was deleted. Keep it pending and let History show the failure.
+ if (includeUnavailable) unavailable.push(unavailableFeedbackRef({ ...ref, archiveDate }, 'read-failed'));
+ continue;
+ }
+ if (archived.kind === 'missing') {
+ if (includeUnavailable) unavailable.push(unavailableFeedbackRef({ ...ref, archiveDate }, 'deleted'));
+ continue;
+ }
+ if (!isAgentFeedbackTarget(archived.agent) || hasValidFeedback(archived.agent)) {
+ await removePendingAgentFeedbackRef(ref.agentId);
+ continue;
+ }
+ agents.push(archived.agent);
+ }
+
+ return { agents, unavailable, count: agents.length };
+}
+
+export async function getPendingAgentFeedbackCount() {
+ return (await getPendingAgentFeedback()).count;
}
// Submit feedback for a completed agent.
@@ -89,6 +179,16 @@ export async function getPendingAgentFeedbackCount() {
// write inside the CoS state lock would hold the lock across an I/O round trip
// for a log line. The lock's own failures still reject before anything is logged.
export async function submitAgentFeedback(agentId, feedback) {
+ if (!isFeedbackRating(feedback?.rating)) {
+ throw new ServerError(`rating must be one of: ${FEEDBACK_RATINGS.join(', ')}`, {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ });
+ }
+
+ // The durable reference is removed only after the source metadata write. Keep
+ // that small store mutation outside the CoS state lock so a database/file I/O
+ // round trip never serializes unrelated agent state updates.
const result = await withStateLock(async () => {
const state = await loadState();
const feedbackData = {
@@ -100,30 +200,24 @@ export async function submitAgentFeedback(agentId, feedback) {
// Try state first (recently completed agents still in state)
if (state.agents[agentId]) {
const agent = state.agents[agentId];
- if (agent.status !== 'completed') {
+ if (!isAgentFeedbackUpdateTarget(agent)) {
throw new ServerError('Can only submit feedback for completed agents', { status: 400, code: 'INVALID_STATE' });
}
- state.agents[agentId].feedback = feedbackData;
+ state.agents[agentId] = { ...agent, feedback: feedbackData };
await saveState(state);
- // Also update on-disk metadata (derive date bucket from completedAt if archived)
- const dateBucket = agent.completedAt ? agent.completedAt.slice(0, 10) : null;
- const agentDir = getAgentDir(agentId, dateBucket);
- const metaPath = join(agentDir, 'metadata.json');
- if (existsSync(metaPath)) {
- const content = await tryReadFile(metaPath);
- if (content) {
- const raw = safeJSONParse(content, null);
- if (raw) {
- raw.feedback = feedbackData;
- await atomicWrite(metaPath, raw).catch(() => {});
- }
- }
+ // Also update on-disk metadata. The live state write is authoritative for
+ // the current card, but the pending reference is cleared only after the
+ // source archive carries the same rating, so eviction cannot resurrect it.
+ const dateBucket = feedbackArchiveDate(agent);
+ const archived = await readArchivedAgent(agentId, dateBucket);
+ if (archived.kind === 'found') {
+ await atomicWrite(archived.metadataPath, { ...archived.agent, feedback: feedbackData });
}
emitLog('info', `Feedback received for agent ${agentId}: ${feedback.rating}`, { agentId, rating: feedback.rating });
cosEvents.emit('agent:feedback', { agentId, feedback: feedbackData });
- return { success: true, agent: state.agents[agentId], feedbackData };
+ return { success: true, agent: state.agents[agentId], feedbackData, clearPendingRef: archived.kind === 'found' };
}
// Agent not in state — look up from disk via index
@@ -131,22 +225,22 @@ export async function submitAgentFeedback(agentId, feedback) {
const dateStr = idx.get(agentId);
if (!dateStr) throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });
- const metaPath = join(AGENTS_DIR, dateStr, agentId, 'metadata.json');
- const content = await tryReadFile(metaPath);
- if (!content) throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });
-
- const raw = safeJSONParse(content, null);
- if (!raw) throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });
+ const archived = await readArchivedAgent(agentId, dateStr);
+ if (archived.kind !== 'found') throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });
+ if (!isAgentFeedbackUpdateTarget(archived.agent)) {
+ throw new ServerError('Can only submit feedback for completed agents', { status: 400, code: 'INVALID_STATE' });
+ }
- raw.feedback = feedbackData;
- await atomicWrite(metaPath, raw);
+ const updated = { ...archived.agent, feedback: feedbackData };
+ await atomicWrite(archived.metadataPath, updated);
emitLog('info', `Feedback received for agent ${agentId}: ${feedback.rating}`, { agentId, rating: feedback.rating });
cosEvents.emit('agent:feedback', { agentId, feedback: feedbackData });
- return { success: true, agent: { ...raw, id: agentId }, feedbackData };
+ return { success: true, agent: { ...updated, id: agentId }, feedbackData, clearPendingRef: true };
});
- const { feedbackData, ...response } = result;
+ const { feedbackData, clearPendingRef, ...response } = result;
+ if (clearPendingRef) await removePendingAgentFeedbackRef(agentId);
await recordUserAction({
type: 'cos.agent.feedback',
target: agentId,
@@ -223,6 +317,23 @@ export async function getFeedbackStats() {
};
}
+let feedbackEventsInitialized = false;
+
+/** Register future-completion enrollment without doing any cold-start provider work. */
+export function initializeAgentFeedback() {
+ if (feedbackEventsInitialized) return;
+ feedbackEventsInitialized = true;
+ cosEvents.on('agent:completed', (agent) => {
+ if (!isAgentFeedbackEligible(agent)) return;
+ upsertPendingAgentFeedbackRef({
+ agentId: agent.id,
+ archiveDate: feedbackArchiveDate(agent),
+ }).catch((err) => {
+ console.error(`❌ Failed to enroll CoS feedback for ${agent.id}: ${err.message}`);
+ });
+ });
+}
+
// Helper to extract task type from description (mirrors client-side logic)
export function extractTaskType(description) {
if (!description) return 'general';
diff --git a/server/services/cosAgentFeedback.test.js b/server/services/cosAgentFeedback.test.js
index 24fe851f76..e4135aff1e 100644
--- a/server/services/cosAgentFeedback.test.js
+++ b/server/services/cosAgentFeedback.test.js
@@ -39,13 +39,26 @@ vi.mock('../lib/fileUtils.js', async () => {
return makePathsProxy(actual, { dataRoot: ledgerRoot });
});
-import { getFeedbackStats, getPendingAgentFeedbackCount, submitAgentFeedback } from './cosAgentFeedback.js';
+import {
+ getFeedbackStats,
+ getPendingAgentFeedback,
+ getPendingAgentFeedbackCount,
+ initializeAgentFeedback,
+ submitAgentFeedback,
+} from './cosAgentFeedback.js';
+import { cosEvents } from './cosEvents.js';
+import {
+ listPendingAgentFeedbackRefs,
+ resetPendingAgentFeedbackStore,
+} from './cosAgentFeedbackStore.js';
import { listUserActions } from './userActions.js';
describe('getPendingAgentFeedbackCount', () => {
- beforeEach(() => {
+ beforeEach(async () => {
mockCosState.state = { agents: {} };
mockAgentIndex.entries = new Map();
+ resetPendingAgentFeedbackStore();
+ await rm(join(ledgerRoot, 'cos-pending-agent-feedback.json'), { force: true });
});
afterAll(async () => {
@@ -102,6 +115,101 @@ describe('getPendingAgentFeedbackCount', () => {
await expect(getPendingAgentFeedbackCount()).resolves.toBe(0);
});
+ it('enrolls a future completion without reading historical archives', async () => {
+ initializeAgentFeedback();
+ cosEvents.emit('agent:completed', {
+ id: 'agent-future',
+ status: 'completed',
+ completedAt: '2026-08-02T10:00:00.000Z',
+ metadata: { taskType: 'user' },
+ });
+
+ await expect.poll(() => listPendingAgentFeedbackRefs()).toEqual([
+ { agentId: 'agent-future', archiveDate: '2026-08-02' },
+ ]);
+ });
+
+ it('keeps an eligible run actionable after live state is evicted', async () => {
+ const agent = {
+ id: 'agent-archived-pending',
+ status: 'completed',
+ completedAt: '2026-08-03T10:00:00.000Z',
+ metadata: { taskType: 'user', taskDescription: 'Review an example change' },
+ };
+ mockCosState.state.agents = { [agent.id]: agent };
+ await expect(getPendingAgentFeedback()).resolves.toMatchObject({ count: 1, agents: [agent] });
+
+ const dir = join(mockCosState.agentsDir, '2026-08-03', agent.id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(join(dir, 'metadata.json'), JSON.stringify(agent));
+ mockCosState.state = { agents: {} };
+ mockAgentIndex.entries.set(agent.id, '2026-08-03');
+
+ await expect(getPendingAgentFeedback()).resolves.toMatchObject({ count: 1, agents: [agent] });
+ });
+
+ it('retains a deleted reference as unavailable history instead of claiming completion', async () => {
+ const agent = {
+ id: 'agent-deleted',
+ status: 'completed',
+ completedAt: '2026-08-04T10:00:00.000Z',
+ metadata: { taskType: 'user' },
+ };
+ mockCosState.state.agents = { [agent.id]: agent };
+ await getPendingAgentFeedback();
+ mockCosState.state = { agents: {} };
+
+ await expect(getPendingAgentFeedback({ includeUnavailable: true })).resolves.toMatchObject({
+ count: 0,
+ unavailable: [{ agentId: agent.id, unavailableReason: 'deleted' }],
+ });
+ await expect(listPendingAgentFeedbackRefs()).resolves.toEqual([
+ { agentId: agent.id, archiveDate: '2026-08-04' },
+ ]);
+ });
+
+ it('retains a reference when the indexed archive cannot be read', async () => {
+ const agent = {
+ id: 'agent-unreadable',
+ status: 'completed',
+ completedAt: '2026-08-05T10:00:00.000Z',
+ metadata: { taskType: 'user' },
+ };
+ mockCosState.state.agents = { [agent.id]: agent };
+ await getPendingAgentFeedback();
+ mockCosState.state = { agents: {} };
+ mockAgentIndex.entries.set(agent.id, '2026-08-05');
+ await mkdir(join(mockCosState.agentsDir, '2026-08-05', agent.id, 'metadata.json'), { recursive: true });
+
+ await expect(getPendingAgentFeedback({ includeUnavailable: true })).resolves.toMatchObject({
+ count: 0,
+ unavailable: [{ agentId: agent.id, unavailableReason: 'read-failed' }],
+ });
+ await expect(listPendingAgentFeedbackRefs()).resolves.toEqual([
+ { agentId: agent.id, archiveDate: '2026-08-05' },
+ ]);
+ });
+
+ it('clears the reference only after rating the source archive', async () => {
+ const agent = {
+ id: 'agent-source-owned',
+ status: 'completed',
+ completedAt: '2026-08-06T10:00:00.000Z',
+ metadata: { taskType: 'user', taskDescription: 'Fix an example regression' },
+ };
+ const dir = join(mockCosState.agentsDir, '2026-08-06', agent.id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(join(dir, 'metadata.json'), JSON.stringify(agent));
+ mockCosState.state = { agents: {} };
+ mockAgentIndex.entries.set(agent.id, '2026-08-06');
+ await getPendingAgentFeedback();
+
+ await submitAgentFeedback(agent.id, { rating: 'positive' });
+
+ await expect(listPendingAgentFeedbackRefs()).resolves.toEqual([]);
+ await expect(getPendingAgentFeedbackCount()).resolves.toBe(0);
+ });
+
it('aggregates archived feedback and de-duplicates a live copy of the same agent', async () => {
const dateBucket = '2026-08-01';
const archived = [
@@ -177,6 +285,7 @@ describe('submitAgentFeedback records the rating (#5594)', () => {
},
};
mockAgentIndex.entries = new Map();
+ resetPendingAgentFeedbackStore();
await rm(join(ledgerRoot, 'user-action-events.json'), { force: true });
});
diff --git a/server/services/cosAgentFeedbackStore.js b/server/services/cosAgentFeedbackStore.js
new file mode 100644
index 0000000000..c6f846dc47
--- /dev/null
+++ b/server/services/cosAgentFeedbackStore.js
@@ -0,0 +1,101 @@
+/**
+ * Durable references for pending CoS agent feedback.
+ *
+ * PostgreSQL is authoritative in a normal install. The JSON backend exists only
+ * for the documented development/test escape hatch, mirroring the other
+ * machine-local stores without making file storage a supported deployment mode.
+ * The record deliberately contains no task prose or rating.
+ */
+
+import { join } from 'node:path';
+import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+import { createPgFileFacade, resolvePgBackend } from '../lib/pgFileFacade.js';
+
+const pendingFile = () => join(PATHS.data, 'cos-pending-agent-feedback.json');
+const queueFileWrite = createFileWriteQueue();
+
+const normalizeRef = (value) => {
+ if (!value || typeof value.agentId !== 'string' || !value.agentId) return null;
+ return {
+ agentId: value.agentId,
+ archiveDate: typeof value.archiveDate === 'string' && value.archiveDate ? value.archiveDate : null,
+ };
+};
+
+async function readFileRefs() {
+ const raw = await readJSONFile(pendingFile(), [], { allowArray: true, logError: false, strict: true });
+ return (Array.isArray(raw) ? raw : []).map(normalizeRef).filter(Boolean);
+}
+
+function makeFileBackend() {
+ return {
+ name: 'file',
+ list: readFileRefs,
+ upsert: (ref) => queueFileWrite(async () => {
+ const refs = await readFileRefs();
+ const next = normalizeRef(ref);
+ const index = refs.findIndex((entry) => entry.agentId === next.agentId);
+ if (index === -1) refs.push(next);
+ else refs[index] = next;
+ await atomicWrite(pendingFile(), refs);
+ }),
+ remove: (agentId) => queueFileWrite(async () => {
+ const refs = await readFileRefs();
+ const next = refs.filter((entry) => entry.agentId !== agentId);
+ if (next.length !== refs.length) await atomicWrite(pendingFile(), next);
+ }),
+ };
+}
+
+function makePgBackend(db) {
+ return {
+ name: 'postgres',
+ async list() {
+ const { rows } = await db.query(
+ 'SELECT agent_id, archive_date FROM cos_pending_agent_feedback ORDER BY archive_date DESC NULLS LAST, agent_id',
+ );
+ return rows.map((row) => ({ agentId: row.agent_id, archiveDate: row.archive_date || null }));
+ },
+ async upsert(ref) {
+ await db.query(
+ `INSERT INTO cos_pending_agent_feedback (agent_id, archive_date)
+ VALUES ($1, $2)
+ ON CONFLICT (agent_id) DO UPDATE SET archive_date = EXCLUDED.archive_date`,
+ [ref.agentId, ref.archiveDate],
+ );
+ },
+ async remove(agentId) {
+ await db.query('DELETE FROM cos_pending_agent_feedback WHERE agent_id = $1', [agentId]);
+ },
+ };
+}
+
+const backendFacade = createPgFileFacade({
+ makeFile: makeFileBackend,
+ makePg: () => resolvePgBackend({
+ requirement: 'CoS feedback references require PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the file escape hatch)',
+ loadDb: () => import('../lib/db.js'),
+ makePg: makePgBackend,
+ }),
+});
+
+export async function listPendingAgentFeedbackRefs() {
+ return (await backendFacade.getBackend()).list();
+}
+
+export async function upsertPendingAgentFeedbackRef(ref) {
+ const normalized = normalizeRef(ref);
+ if (!normalized) return;
+ await (await backendFacade.getBackend()).upsert(normalized);
+}
+
+export async function removePendingAgentFeedbackRef(agentId) {
+ if (typeof agentId !== 'string' || !agentId) return;
+ await (await backendFacade.getBackend()).remove(agentId);
+}
+
+/** Test seam for suites that swap the file data root between cases. */
+export function resetPendingAgentFeedbackStore() {
+ backendFacade.reset();
+}
diff --git a/server/services/reviewQueue.js b/server/services/reviewQueue.js
index 4cea201011..846b96ccc4 100644
--- a/server/services/reviewQueue.js
+++ b/server/services/reviewQueue.js
@@ -31,6 +31,7 @@ import * as brain from './brain.js';
import * as brainStorage from './brainStorage.js';
import * as askConversations from './askConversations.js';
import * as cosTaskStore from './cosTaskStore.js';
+import * as cosAgentFeedback from './cosAgentFeedback.js';
import * as messageDrafts from './messageDrafts.js';
import * as proactiveAlerts from './proactiveAlerts.js';
import * as backup from './backup.js';
@@ -72,6 +73,7 @@ const ACTION_KINDS = Object.freeze({
threads: 'brain.thread',
todo: 'review.todo',
history: 'review.history',
+ feedback: 'cos.feedback',
});
const OPERATION_LABELS = Object.freeze({
@@ -88,6 +90,7 @@ const OPERATION_LABELS = Object.freeze({
threads: 'Complete',
todo: 'Complete',
history: 'History',
+ feedback: 'Rate',
});
const PRIORITY_ORDER = { HIGH: 0, MEDIUM: 1, LOW: 2 };
@@ -330,6 +333,57 @@ const PRODUCERS = [
};
}
},
+ {
+ source: 'feedback',
+ label: 'CoS run feedback',
+ drillTo: '/cos/agents?feedback=needs-feedback',
+ views: ['today', 'all', 'history'],
+ async gather(limit = REVIEW_QUEUE_SOURCE_READ_LIMIT, ctx = {}) {
+ const pending = await cosAgentFeedback.getPendingAgentFeedback({ includeUnavailable: ctx.view === 'history' });
+ const items = [
+ ...(Array.isArray(pending?.agents) ? pending.agents : []),
+ ...(ctx.view === 'history' && Array.isArray(pending?.unavailable) ? pending.unavailable : []),
+ ];
+ return { items: items.slice(0, limit), truncated: items.length > limit };
+ },
+ map(agent) {
+ const unavailable = agent.availability === 'unavailable';
+ const description = agent.metadata?.taskDescription;
+ return {
+ id: `feedback:${agent.id || agent.agentId}`,
+ title: unavailable ? 'Completed CoS run unavailable for feedback' : 'Rate completed CoS run',
+ summary: unavailable
+ ? 'The source run is no longer available to rate; the action is retained as history.'
+ : (typeof description === 'string' && description.trim()
+ ? description.trim().slice(0, 200)
+ : 'Completed manual CoS run'),
+ timestamp: agent.completedAt || null,
+ severity: 'normal',
+ required: !unavailable,
+ isRecommendation: false,
+ sourceRef: agent.id || agent.agentId,
+ ...(!unavailable
+ ? { drillTo: `/cos/agents/${encodeURIComponent(agent.id || agent.agentId)}?feedback=needs-feedback` }
+ : {}),
+ availability: unavailable ? 'unavailable' : 'available',
+ available: !unavailable,
+ ...(unavailable
+ ? {
+ meta: { unavailableReason: agent.unavailableReason || 'unavailable' },
+ nextAction: 'Unavailable',
+ operations: [],
+ }
+ : {
+ operations: [{
+ id: 'rate',
+ label: 'Rate',
+ available: true,
+ input: { type: 'rating', required: true, options: ['positive', 'negative', 'neutral'] },
+ }],
+ }),
+ };
+ },
+ },
{
source: 'drafts',
label: 'Message drafts',
@@ -832,9 +886,12 @@ const SOURCE_ACTIONS = Object.freeze({
complete: (id) => reviewService.completeItem(id),
reopen: (id) => reviewService.reopenItem(id),
}),
+ feedback: Object.freeze({
+ rate: (id, input) => cosAgentFeedback.submitAgentFeedback(id, input),
+ }),
});
-export async function resolveQueueItem(queueItemId, operation = 'resolve') {
+export async function resolveQueueItem(queueItemId, operation = 'resolve', input = {}) {
const sep = String(queueItemId).indexOf(':');
const source = sep === -1 ? queueItemId : queueItemId.slice(0, sep);
const rawId = sep === -1 ? '' : queueItemId.slice(sep + 1);
@@ -847,7 +904,7 @@ export async function resolveQueueItem(queueItemId, operation = 'resolve') {
code: 'BAD_REQUEST',
});
}
- const result = await resolver(rawId);
+ const result = await resolver(rawId, input);
if (result == null) {
throw new ServerError(`${source} item not found: ${rawId}`, { status: 404, code: 'NOT_FOUND' });
}
diff --git a/server/services/reviewQueue.test.js b/server/services/reviewQueue.test.js
index 267fdf2e80..70b4492de5 100644
--- a/server/services/reviewQueue.test.js
+++ b/server/services/reviewQueue.test.js
@@ -6,6 +6,7 @@ const brain = { getInboxLog: vi.fn(), markInboxDone: vi.fn() };
const brainStorage = { getThreads: vi.fn(), getThreadById: vi.fn(), updateWith: vi.fn() };
const askConversations = { listConversations: vi.fn() };
const cosTaskStore = { getCosTasks: vi.fn(), approveTask: vi.fn() };
+const cosAgentFeedback = { getPendingAgentFeedback: vi.fn(), submitAgentFeedback: vi.fn() };
const messageDrafts = { listDrafts: vi.fn(), approveDraft: vi.fn() };
const proactiveAlerts = { generateAlerts: vi.fn() };
const backup = { getState: vi.fn() };
@@ -26,6 +27,7 @@ vi.mock('./brain.js', () => brain);
vi.mock('./brainStorage.js', () => brainStorage);
vi.mock('./askConversations.js', () => askConversations);
vi.mock('./cosTaskStore.js', () => cosTaskStore);
+vi.mock('./cosAgentFeedback.js', () => cosAgentFeedback);
vi.mock('./messageDrafts.js', () => messageDrafts);
vi.mock('./proactiveAlerts.js', () => proactiveAlerts);
vi.mock('./backup.js', () => backup);
@@ -54,6 +56,8 @@ function resetEmpty() {
brainStorage.updateWith.mockResolvedValue(null);
askConversations.listConversations.mockResolvedValue([]);
cosTaskStore.getCosTasks.mockResolvedValue({ awaitingApproval: [] });
+ cosAgentFeedback.getPendingAgentFeedback.mockResolvedValue({ agents: [], unavailable: [], count: 0 });
+ cosAgentFeedback.submitAgentFeedback.mockResolvedValue({ success: true });
messageDrafts.listDrafts.mockResolvedValue([]);
proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [] });
backup.getState.mockResolvedValue({ status: 'ok', error: null });
@@ -117,6 +121,55 @@ describe('reviewQueue.buildQueue', () => {
});
});
+ it('surfaces pending CoS feedback with a required source-owned Rate operation', async () => {
+ cosAgentFeedback.getPendingAgentFeedback.mockResolvedValue({
+ count: 1,
+ agents: [{
+ id: 'agent-feedback-1',
+ status: 'completed',
+ completedAt: '2026-09-20T10:00:00.000Z',
+ metadata: { taskDescription: 'Review the example change', taskType: 'user' },
+ }],
+ unavailable: [],
+ });
+
+ const queue = await buildQueue({ query: { view: 'all' } });
+ expect(queue.items.find((item) => item.id === 'feedback:agent-feedback-1')).toMatchObject({
+ source: 'feedback',
+ actionKind: 'cos.feedback',
+ drillTo: '/cos/agents/agent-feedback-1?feedback=needs-feedback',
+ required: true,
+ operations: [{
+ id: 'rate',
+ label: 'Rate',
+ available: true,
+ input: { type: 'rating', required: true, options: ['positive', 'negative', 'neutral'] },
+ }],
+ });
+ });
+
+ it('keeps unavailable feedback history rows non-actionable', async () => {
+ cosAgentFeedback.getPendingAgentFeedback.mockResolvedValue({
+ count: 0,
+ agents: [],
+ unavailable: [{
+ id: 'agent-deleted',
+ agentId: 'agent-deleted',
+ availability: 'unavailable',
+ unavailableReason: 'deleted',
+ }],
+ });
+
+ const queue = await buildQueue({ query: { view: 'history' } });
+ expect(queue.items.find((item) => item.id === 'feedback:agent-deleted')).toMatchObject({
+ availability: 'unavailable',
+ available: false,
+ nextAction: 'Unavailable',
+ operations: [],
+ });
+ expect(queue.items.find((item) => item.id === 'feedback:agent-deleted')).not.toHaveProperty('drillTo');
+ });
+
it('projects active Brain commitments and manual todos into the all view', async () => {
brainStorage.getThreads.mockResolvedValue([
{
@@ -716,6 +769,13 @@ describe('reviewQueue.resolveQueueItem', () => {
expect(result).toMatchObject({ source: 'cos', id: 'cos:sys-1', operation: 'approve', resolved: true });
});
+ it('rates feedback rows through the source service and has no generic resolve', async () => {
+ await expect(resolveQueueItem('feedback:agent-1', 'rate', { rating: 'positive' }))
+ .resolves.toMatchObject({ source: 'feedback', operation: 'rate', resolved: true });
+ expect(cosAgentFeedback.submitAgentFeedback).toHaveBeenCalledWith('agent-1', { rating: 'positive' });
+ await expect(resolveQueueItem('feedback:agent-1')).rejects.toMatchObject({ status: 400 });
+ });
+
it('keeps a successful CoS approval successful when legacy cleanup fails', async () => {
cosTaskStore.approveTask.mockResolvedValue({ id: 'sys-1', approvalRequired: false });
reviewService.dismissByReferenceId.mockRejectedValueOnce(new Error('review store down'));