Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
bound task descriptions in CoS agent listings so the Agents page loads on a slow link
[._.]/ Adam Eivy091e21ec60f1
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex c2ad8a14cb..3b5c20c152 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -77,14 +77,38 @@ function normalizeDescriptionToMarkdown(text) {// `line-clamp` can't clamp this — MarkdownOutput emits block children — so it// uses CollapsibleText's max-height variant, which measures the real overflow// instead of guessing from a character count.-function TaskDescription({ id, text }) {+// The listing bounds `metadata.taskDescription` (server/lib/cosAgentListProjection.js),+// which is exactly what the clamped preview needs and 68% less to download. The+// rest arrives only if the reader opens it — `onExpand` fires once per mount, so+// collapsing and re-opening never re-fetches.+function TaskDescription({ agent, remote }) {+ const preview = agent.metadata?.taskDescription || agent.taskId;+ const [hydrated, setHydrated] = useState(null);+ const text = hydrated ?? preview;const md = useMemo(() => normalizeDescriptionToMarkdown(text), [text]);+ // `!remote` for the same reason the transcript fetch below carries it: a peer's+ // agent id means nothing to THIS instance's /cos/agents/:id, so hydrating it+ // would either 404 or read a local run that happens to share the id.+ const clipped = Boolean(agent.metadata?.taskDescriptionTruncated) && !remote;++ const hydrate = useCallback(async () => {+ const full = await api.hydrateCosAgentDescription(agent);+ setHydrated(full.metadata?.taskDescription ?? null);+ }, [agent]);if (!text) return null;return (<div className="mb-2">- <CollapsibleText id={`agent-desc-${id}`} className="text-sm">+ {/* `forceToggle` because a clipped preview is LOSSY, not merely clamped:+ the toggle is the only route to text the browser never received, so it+ must not depend on the preview happening to overflow its height cap. */}+ <CollapsibleText+ id={`agent-desc-${agent.id}`}+ className="text-sm"+ forceToggle={clipped}+ onExpand={clipped ? hydrate : null}+ ><MarkdownOutput content={md} /></CollapsibleText></div>@@ -741,7 +765,7 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,onOpenPrompt={openPromptModal}pid={agent.pid}/>- <TaskDescription id={agent.id} text={agent.metadata?.taskDescription || agent.taskId} />+ <TaskDescription agent={agent} remote={remote} />{/* JIRA ticket info */}{agent.metadata?.jiraTicketId && (diff --git a/client/src/components/cos/tabs/AgentCard.test.jsx b/client/src/components/cos/tabs/AgentCard.test.jsxindex 616582a88d..cd51f7a47a 100644--- a/client/src/components/cos/tabs/AgentCard.test.jsx+++ b/client/src/components/cos/tabs/AgentCard.test.jsx@@ -11,6 +11,7 @@ vi.mock('../../../services/api', () => ({getCosAgentPrompt: vi.fn(),getCosAgentStats: vi.fn(() => new Promise(() => {})),addCosTask: vi.fn(),+ hydrateCosAgentDescription: vi.fn(async (a) => a),}));vi.mock('../../ui/Toast', () => ({@@ -835,3 +836,52 @@ describe('AgentCard branch posture badges', () => {expect(screen.queryByText('Read-only')).not.toBeInTheDocument();});});++// The listing bounds `metadata.taskDescription` — see server/lib/cosAgentListProjection.js.+// The card must still be able to show the whole thing, without every row paying+// for it on load.+describe('AgentCard truncated task description', () => {+ const longAgent = {+ ...agent,+ metadata: {+ ...agent.metadata,+ taskDescription: 'The preview the listing carried',+ taskDescriptionTruncated: true,+ taskDescriptionLength: 54000,+ },+ };++ it('renders the preview without fetching, then hydrates the rest on expand', async () => {+ const user = userEvent.setup();+ api.hydrateCosAgentDescription.mockResolvedValue({+ ...longAgent,+ metadata: { ...longAgent.metadata, taskDescription: 'The preview the listing carried, and the rest of it', taskDescriptionTruncated: false },+ });++ render(<MemoryRouter><AgentCard agent={longAgent} liveOutputs={{}} /></MemoryRouter>);++ expect(screen.getByText('The preview the listing carried')).toBeInTheDocument();+ expect(api.hydrateCosAgentDescription).not.toHaveBeenCalled();++ await user.click(screen.getAllByRole('button', { name: /Show more/ })[0]);++ await waitFor(() => {+ expect(screen.getByText('The preview the listing carried, and the rest of it')).toBeInTheDocument();+ });+ expect(api.hydrateCosAgentDescription).toHaveBeenCalledTimes(1);+ });++ // The control: an untruncated description must never cost a round trip, which+ // is the whole point of the flag.+ it('never fetches for a description the listing carried whole', async () => {+ const user = userEvent.setup();+ const whole = { ...agent, metadata: { ...agent.metadata, taskDescription: 'Example task '.repeat(40) } };++ render(<MemoryRouter><AgentCard agent={whole} liveOutputs={{}} /></MemoryRouter>);++ const toggle = screen.queryAllByRole('button', { name: /Show more/ })[0];+ if (toggle) await user.click(toggle);++ expect(api.hydrateCosAgentDescription).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsxindex cf96aeb6f9..aca50a9494 100644--- a/client/src/components/cos/tabs/AgentsTab.jsx+++ b/client/src/components/cos/tabs/AgentsTab.jsx@@ -87,23 +87,20 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, papi.getCosLearningDurations().then(setDurations).catch(() => {});}, []);- // Fetch date buckets on mount and auto-load the most recent date+ // 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+ // before any archived card can paint — the whole visible delay on a slow link.useEffect(() => {let cancelled = false;(async () => {- const result = await api.getCosAgentDates().catch(() => ({ dates: [] }));+ const result = await api.getCosAgentDates({ hydrate: true }).catch(() => ({ dates: [] }));if (cancelled) return;const dates = result.dates || [];setDateBuckets(dates);-- // Auto-load the most recent date- if (dates.length > 0) {- const firstDate = dates[0].date;- const agents = await api.getCosAgentsByDate(firstDate).catch(() => []);- if (cancelled) return;- setLoadedAgents(agents);- setLoadedDates(new Set([firstDate]));- }+ if (!result.latest) return;+ setLoadedAgents(result.latest.agents || []);+ setLoadedDates(new Set([result.latest.date]));})();return () => { cancelled = true; };}, []);@@ -151,13 +148,23 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, ponRefresh();}, [onRefresh]);- const handleResumeClick = (agent) => {- setResumingAgent(agent);- };+ // ResumeAgentModal builds a NEW task prompt out of `metadata.taskDescription`,+ // and the listing carries a bounded copy of it (server/lib/cosAgentListProjection.js).+ // Hydrate BEFORE opening, or a long description would be resumed clipped —+ // silently, since the dialog shows exactly what it would send. The await costs+ // nothing for the >90% of runs the listing carried whole (no request is made),+ // and one small `?lines=1` read for the rest; opening on the preview and+ // swapping the text in later would leave a window where Submit ships the+ // clipped copy, which is the failure this exists to prevent.+ const handleResumeClick = useCallback(async (agent) => {+ setResumingAgent(await api.hydrateCosAgentDescription(agent));+ }, []);// A stalled RUNNING agent (a CLI parked on a provider usage limit) moves to a// different provider/model in one step. The dialog owns the call and the- // outcome message — see RelaunchAgentModal.+ // outcome message — see RelaunchAgentModal. No hydration here: relaunch sends+ // provider/model/effort/app and a note, never the description, and the dialog+ // fetches the rest itself if the reader expands it.const handleRelaunchClick = useCallback((agent) => setRelaunchingAgent(agent), []);const handleFeedbackChange = useCallback((updatedAgent) => {@@ -241,6 +248,10 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, preturn indexTotal + stateOnlyCount;}, [dateBuckets, recentCompleted, loadedAgents]);+ // Search runs over what the listing carries. `metadata.taskDescription` is+ // bounded at AGENT_LIST_DESCRIPTION_CHARS server-side, which leaves over 90% of+ // real records whole — only a pasted-prompt description is clipped, and its+ // opening 2000 characters are what a reader searches for anyway.const filteredCompleted = useMemo(() => {const q = searchQuery.trim().toLowerCase();return allCompleted.filter(a => {diff --git a/client/src/components/cos/tabs/AgentsTab.test.jsx b/client/src/components/cos/tabs/AgentsTab.test.jsxindex 71d9e68b33..b4eb5f6810 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(),+ hydrateCosAgentDescription: vi.fn(async (agent) => agent),clearCompletedCosAgents: vi.fn(),resumeCosAgent: vi.fn(),relaunchCosAgent: vi.fn(),@@ -104,8 +105,9 @@ const renderTab = (agents, onRefresh = vi.fn(), initialEntry = '/cos/agents') =>beforeEach(() => {vi.clearAllMocks();api.getCosLearningDurations.mockResolvedValue({});- api.getCosAgentDates.mockResolvedValue({ dates: [] });+ api.getCosAgentDates.mockResolvedValue({ dates: [], latest: null });api.getCosAgentsByDate.mockResolvedValue([]);+ api.hydrateCosAgentDescription.mockImplementation(async (agent) => agent);});// A relaunch is offered only on a RUNNING agent — it is the recovery for a run@@ -315,10 +317,10 @@ describe('AgentsTab feedback review queue', () => {it('removes an archived run from the queue immediately after feedback', async () => {const user = userEvent.setup();const onRefresh = vi.fn();- api.getCosAgentDates.mockResolvedValue({ dates: [{ date: '2026-07-13', count: 1 }] });- api.getCosAgentsByDate.mockResolvedValue([- completedAgent('archived', 'Archived task'),- ]);+ api.getCosAgentDates.mockResolvedValue({+ dates: [{ date: '2026-07-13', count: 1 }],+ latest: { date: '2026-07-13', agents: [completedAgent('archived', 'Archived task')] },+ });renderTab([], onRefresh);await act(async () => {});@@ -342,3 +344,67 @@ it('opens an agent deep link even after it has left the recent agent list', asynexpect(await screen.findByTestId('agent-archived-example')).toBeInTheDocument();expect(api.getCosAgent).toHaveBeenCalledWith('archived-example', { silent: true });});++// The archive list and its newest bucket arrive together: the tab cannot name the+// date it needs until the bucket list answers, so asking separately costs a+// second serial round trip before any archived card can paint.+describe('AgentsTab archive loading', () => {+ it('paints the newest bucket from the bucket-list response, with no follow-up request', async () => {+ api.getCosAgentDates.mockResolvedValue({+ dates: [{ date: '2026-07-13', count: 1 }, { date: '2026-07-12', count: 4 }],+ latest: { date: '2026-07-13', agents: [completedAgent('archived', 'Archived task')] },+ });++ renderTab([]);++ await screen.findByText('Archived task');+ expect(api.getCosAgentDates).toHaveBeenCalledWith({ hydrate: true });+ expect(api.getCosAgentsByDate).not.toHaveBeenCalled();+ });++ it('loads an older bucket on demand, one request per date', async () => {+ const user = userEvent.setup();+ api.getCosAgentDates.mockResolvedValue({+ dates: [{ date: '2026-07-13', count: 1 }, { date: '2026-07-12', count: 1 }],+ latest: { date: '2026-07-13', agents: [completedAgent('archived', 'Archived task')] },+ });+ api.getCosAgentsByDate.mockResolvedValue([completedAgent('older', 'Older task')]);++ renderTab([]);+ await screen.findByText('Archived task');+ await user.click(screen.getByRole('button', { name: /Load/ }));++ await screen.findByText('Older task');+ expect(api.getCosAgentsByDate).toHaveBeenCalledWith('2026-07-12');+ });+});++// Resume and Relaunch build a NEW task prompt out of the description, so a copy+// the listing clipped would silently ship a truncated task.+describe('AgentsTab hydrates a clipped description before reusing it', () => {+ const clipped = {+ id: 'agent-paused',+ taskId: 'task-abc',+ status: 'paused',+ startedAt: '2026-07-13T09:00:00.000Z',+ metadata: { taskDescription: 'Half-finished', taskDescriptionTruncated: true },+ };++ it('hands the resume dialog the full description, not the listing preview', async () => {+ const user = userEvent.setup();+ api.hydrateCosAgentDescription.mockResolvedValue({+ ...clipped,+ metadata: { ...clipped.metadata, taskDescription: 'Half-finished work, in full', taskDescriptionTruncated: false },+ });+ api.resumeCosAgent.mockResolvedValue({ success: true, taskId: 'task-abc', mode: 'requeued' });++ renderTab([clipped]);+ await act(async () => {});+ await user.click(screen.getByRole('button', { name: 'Resume agent-paused' }));+ await user.click(await screen.findByRole('button', { name: 'Submit resume' }));++ await waitFor(() => expect(api.resumeCosAgent).toHaveBeenCalled());+ expect(api.hydrateCosAgentDescription).toHaveBeenCalledWith(clipped);+ expect(api.resumeCosAgent.mock.calls[0][1].description).toBe('[Resume] Half-finished work, in full');+ });+});diff --git a/client/src/components/cos/tabs/RelaunchAgentModal.jsx b/client/src/components/cos/tabs/RelaunchAgentModal.jsxindex d5041a0f32..5c417596d2 100644--- a/client/src/components/cos/tabs/RelaunchAgentModal.jsx+++ b/client/src/components/cos/tabs/RelaunchAgentModal.jsx@@ -1,4 +1,4 @@-import { useMemo, useState } from 'react';+import { useCallback, useMemo, useState } from 'react';import { RefreshCw, Loader2, X } from 'lucide-react';import * as api from '../../../services/api';import toast from '../../ui/Toast';@@ -44,7 +44,17 @@ const RELAUNCH_MESSAGES = {*/export default function RelaunchAgentModal({ agent, providers, providersLoaded = true, apps, onDone, onClose }) {const currentProvider = agent?.metadata?.providerId || agent?.metadata?.provider || '';- const taskDescription = agent?.metadata?.taskDescription || agent?.taskId || 'Current task';+ // The listing bounds this text (server/lib/cosAgentListProjection.js). The+ // dialog only DISPLAYS it — the relaunch call sends provider/model/effort/app+ // and a note, never the description — so the rest is fetched only if the reader+ // opens it, instead of blocking this dialog on a request.+ const [hydrated, setHydrated] = useState(null);+ const clipped = Boolean(agent?.metadata?.taskDescriptionTruncated);+ const taskDescription = hydrated || agent?.metadata?.taskDescription || agent?.taskId || 'Current task';+ const hydrateDescription = useCallback(async () => {+ const full = await api.hydrateCosAgentDescription(agent);+ setHydrated(full.metadata?.taskDescription ?? null);+ }, [agent]);const [formData, setFormData] = useState(() => {// Seeded from the stalled run so the dialog opens on what it was using —@@ -128,6 +138,8 @@ export default function RelaunchAgentModal({ agent, providers, providersLoaded =className="text-white"expandedContent={taskDescription}expandedClassName="max-h-48 overflow-y-auto whitespace-pre-wrap"+ forceToggle={clipped}+ onExpand={clipped ? hydrateDescription : null}/><div className="text-sm text-gray-400 mt-2">This stops the running agent and restarts the same task on the worktree it leavesdiff --git a/client/src/components/ui/CollapsibleText.jsx b/client/src/components/ui/CollapsibleText.jsxindex 84d54eed62..fa2da670db 100644--- a/client/src/components/ui/CollapsibleText.jsx+++ b/client/src/components/ui/CollapsibleText.jsx@@ -1,4 +1,4 @@-import { Children, useState, useRef, useEffect } from 'react';+import { Children, useCallback, useState, useRef, useEffect } from 'react';import { ChevronDown, ChevronUp } from 'lucide-react';// Tailwind scans source for literal class names, so the clamp variants must@@ -71,6 +71,12 @@ const CLAMP_CLASS = {* notification). Without the `|| expanded` term that in-flight callback can* measure the now-unclamped element, see no overflow, and drop the toggle.*+ * `onExpand` fires the first time the reader opens the preview, for content the+ * caller only fetches on demand — a card whose listing payload carries a+ * truncated copy hydrates the rest here rather than downloading it for every row+ * up front. It is called once per mount, not on every toggle, so re-collapsing+ * and re-expanding never re-fetches.+ ** `id` is required: it wires the toggle's `aria-controls` to the content it expands.*/@@ -87,12 +93,25 @@ export default function CollapsibleText({lines = 2,expandedContent = null,expandedClassName = '',- forceToggle = false+ forceToggle = false,+ onExpand = null}) {const [expanded, setExpanded] = useState(false);const [isOverflowing, setIsOverflowing] = useState(false);const ref = useRef(null);const innerRef = useRef(null);+ const expandedOnceRef = useRef(false);++ // `onExpand` is deliberately NOT fired from inside the `setExpanded` updater:+ // React may invoke an updater more than once (StrictMode double-invoke), and a+ // hydration fetch must not ride a function the renderer is free to replay.+ const open = useCallback(() => {+ if (!expandedOnceRef.current) {+ expandedOnceRef.current = true;+ onExpand?.();+ }+ setExpanded(true);+ }, [onExpand]);// An empty list or an empty string is *no* children, not "children that// happen to be blank" — a caller doing `<CollapsibleText text={fallback}>// {items.map(…)}</CollapsibleText>` over an empty list must get the text@@ -140,7 +159,7 @@ export default function CollapsibleText({// Measured live rather than read off `isOverflowing`: a descendant with// `autoFocus` takes focus during commit, before the passive measure// effect has run, so the state flag is still false on that first focus.- onFocus={() => { if (ref.current && overflows(ref.current)) setExpanded(true); }}+ onFocus={() => { if (ref.current && overflows(ref.current)) open(); }}><div ref={innerRef}>{children}</div></div>@@ -166,7 +185,7 @@ export default function CollapsibleText({{(isOverflowing || expanded || forceToggle) && (<buttontype="button"- onClick={() => setExpanded(v => !v)}+ onClick={() => (expanded ? setExpanded(false) : open())}className="flex items-center gap-0.5 mt-0.5 text-xs text-port-accent hover:text-port-accent/80 transition-colors"aria-expanded={expanded}aria-controls={id}diff --git a/client/src/components/ui/CollapsibleText.test.jsx b/client/src/components/ui/CollapsibleText.test.jsxindex 89597ff742..222bf15bc2 100644--- a/client/src/components/ui/CollapsibleText.test.jsx+++ b/client/src/components/ui/CollapsibleText.test.jsx@@ -356,4 +356,35 @@ describe('CollapsibleText children (max-height) variant', () => {expect(screen.getByRole('button', { name: /Show less/ })).toBeInTheDocument();});++ // The hook a caller uses to fetch content it deliberately did not download for+ // every collapsed row — see AgentCard's clipped task description.+ it('calls onExpand the first time the reader opens it, and not again', () => {+ const onExpand = vi.fn();+ forceOverflow();+ render(<CollapsibleText id="c12" text={'long '.repeat(500)} onExpand={onExpand} />);++ expect(onExpand).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: /Show more/ }));+ expect(onExpand).toHaveBeenCalledTimes(1);++ fireEvent.click(screen.getByRole('button', { name: /Show less/ }));+ fireEvent.click(screen.getByRole('button', { name: /Show more/ }));+ expect(onExpand).toHaveBeenCalledTimes(1);+ });++ // The children path expands on focus too, and that is a genuine open — content+ // reached by tabbing into the preview must be hydrated like any other.+ it('calls onExpand when focus expands the capped children', () => {+ const onExpand = vi.fn();+ forceOverflow();+ render(+ <CollapsibleText id="c13" onExpand={onExpand}>+ <a href="/somewhere">buried link</a>+ </CollapsibleText>+ );++ fireEvent.focus(screen.getByRole('link', { name: 'buried link' }));+ expect(onExpand).toHaveBeenCalledTimes(1);+ });});diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.jsindex 5f12907695..2181943be2 100644--- a/client/src/services/apiAgents.js+++ b/client/src/services/apiAgents.js@@ -201,9 +201,39 @@ export const deleteOrchestrationProfile = (id, options = {}) => request(`/settinexport const getCosHealth = () => request('/cos/health');export const forceHealthCheck = (options = {}) => request('/cos/health/check', { method: 'POST', ...options });export const getCosAgents = (options) => request('/cos/agents', options);-export const getCosAgentDates = () => request('/cos/agents/history');+// `hydrate` also returns the newest bucket as `latest: { date, agents }`, so the+// Agents tab reaches its first archived card in ONE round trip instead of+// waiting for this response to name the date it must then ask for.+export const getCosAgentDates = ({ hydrate = false } = {}) =>+ request(`/cos/agents/history${hydrate ? '?hydrate=1' : ''}`);export const getCosAgentsByDate = (date) => request(`/cos/agents/history/${date}`);-export const getCosAgent = (id, options) => request(`/cos/agents/${id}`, 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.+export const getCosAgent = (id, { lines, ...options } = {}) =>+ request(`/cos/agents/${id}${lines ? `?lines=${lines}` : ''}`, options);++// Agent LIST responses bound `metadata.taskDescription` (see+// `server/lib/cosAgentListProjection.js`), which is fine for a clamped card but+// NOT for anything that reuses the text — Resume and Relaunch build a new task+// prompt out of it, so a clipped copy would silently ship a truncated task.+// Callers in those paths hydrate first; the record comes back unchanged when it+// was never clipped (the common case) or when the read fails, so this is safe to+// call unconditionally and never blocks the action on a network blip.+export const hydrateCosAgentDescription = async (agent) => {+ if (!agent?.id || !agent.metadata?.taskDescriptionTruncated) return agent;+ // `lines: 1` because this read wants ONE metadata field: the default hydrates a+ // 1000-line / 512 KB transcript tail, which would cost far more than the+ // description it came for. The card's Show-output path asks for the real tail+ // separately, when the reader opens it.+ const full = await getCosAgent(agent.id, { lines: 1, silent: true }).catch(() => null);+ const taskDescription = full?.metadata?.taskDescription;+ if (typeof taskDescription !== 'string') return agent;+ return {+ ...agent,+ metadata: { ...agent.metadata, taskDescription, taskDescriptionTruncated: false }+ };+};export const pauseCosAgent = (id, reason, options = {}) => request(`/cos/agents/${id}/pause`, {method: 'POST',body: JSON.stringify({ reason }),diff --git a/client/src/services/apiAgents.test.js b/client/src/services/apiAgents.test.jsindex 7220e05d10..b58694f3ba 100644--- a/client/src/services/apiAgents.test.js+++ b/client/src/services/apiAgents.test.js@@ -1,5 +1,5 @@import { afterEach, expect, it, vi } from 'vitest';-import { startMaintenanceRun } from './apiAgents';+import { startMaintenanceRun, getCosAgentDates, hydrateCosAgentDescription } from './apiAgents';// Exercise the real API wrapper through HTTP serialization: mocking the wrapper// in the form test cannot catch a selected mode being dropped before POST.@@ -16,3 +16,53 @@ it.each([expect(options.method).toBe('POST');expect(JSON.parse(options.body)).toEqual({ appId: 'example', providerId: 'codex', model: 'example-model', effort: null, ...choices });});++// Listing responses bound `metadata.taskDescription` (server/lib/cosAgentListProjection.js).+// Anything that REUSES that text — Resume, Relaunch — has to get the whole thing.+const okJson = (body) => vi.fn().mockResolvedValue({ ok: true, status: 200, json: async () => body });++it('hydrates a clipped description from the agent record, clearing the flag', async () => {+ const fetchMock = okJson({ id: 'agent-1', metadata: { taskDescription: 'the whole thing' } });+ vi.stubGlobal('fetch', fetchMock);++ const hydrated = await hydrateCosAgentDescription({+ id: 'agent-1',+ metadata: { taskDescription: 'the whol', taskDescriptionTruncated: true, model: 'opus' },+ });++ // `lines=1`: the default hydrates a 1000-line transcript tail this read has no+ // use for, which would cost more than the description it came for.+ expect(fetchMock.mock.calls[0][0]).toContain('/cos/agents/agent-1?lines=1');+ expect(hydrated.metadata.taskDescription).toBe('the whole thing');+ expect(hydrated.metadata.taskDescriptionTruncated).toBe(false);+ expect(hydrated.metadata.model).toBe('opus');+});++it('never fetches for a description the listing carried whole', async () => {+ const fetchMock = okJson({});+ vi.stubGlobal('fetch', fetchMock);++ const agent = { id: 'agent-1', metadata: { taskDescription: 'short' } };+ expect(await hydrateCosAgentDescription(agent)).toBe(agent);+ expect(fetchMock).not.toHaveBeenCalled();+});++// A blip must not block the action — the caller gets the preview it already had+// rather than an exception in a click handler.+it('falls back to the clipped record when the hydration read fails', async () => {+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('offline')));++ const agent = { id: 'agent-1', metadata: { taskDescription: 'preview', taskDescriptionTruncated: true } };+ expect(await hydrateCosAgentDescription(agent)).toBe(agent);+});++it('asks for the newest bucket alongside the bucket list when hydrating', async () => {+ const fetchMock = okJson({ dates: [], latest: null });+ vi.stubGlobal('fetch', fetchMock);++ await getCosAgentDates({ hydrate: true });+ expect(fetchMock.mock.calls[0][0]).toContain('/cos/agents/history?hydrate=1');++ await getCosAgentDates();+ expect(fetchMock.mock.calls[1][0]).not.toContain('hydrate');+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 9491d61de5..ebd9543182 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -60,6 +60,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME`, `doneSentinelName(agentId)` → the per-instance filename `.agent-done-<agentId>` (worktree-less agents share one workspace, so a shared name lets concurrent runs clobber — and finalize on — each other's signal), `doneSentinelPath(workspacePath, agentId)` → the single path every producer and consumer resolves, `doneSentinelAgentId(filename)` → its inverse (`''` for the bare unscoped name, `null` for a non-sentinel), so the stale-sentinel sweep in `services/agentSentinelSweep.js` matches leftovers to runs the same way the producer named them, + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). `PROGRAMMATIC_OUTPUT_COMPLETION_HEADING` names the briefing section that prints this run's absolute sentinel path — a task-type hook renders its prompt before spawn, so it points the agent at that section by name rather than at a filename it cannot know. || `persistentMind.js` | Pure persistent-CoS-mind runtime state: default-off durable shape, normalization, FIFO-message/self-wake selection, interrupted-wake requeue, accepted-route fingerprints/receipts, image-work rollback guard, bounded exponential backoff, watchdog staleness, and next-wake projection. || `persistentMindCapabilities.js` | Default-off persistent-mind action grants plus bounded typed CoS-task, private-Eidoverse, and self-cleanup contracts (app/provider/model/effort, PR completion policy, the optional exact provider/model task allowlist, and mind-owned context scopes). |+| `cosAgentListProjection.js` | What a CoS agent LIST response may carry. `toAgentListItem` / `toAgentListItems` drop the transcript and bound `metadata.taskDescription` to `AGENT_LIST_DESCRIPTION_CHARS` (2000, on a clause boundary via `textUtils.clampToCharLimit`), stamping `taskDescriptionTruncated` + the original `taskDescriptionLength` so the UI can hydrate the rest from `GET /api/cos/agents/:id`. That one field was 68% of the Agents tab payload — p50 is 75 characters but a pasted-prompt description runs past 50 KB, and `GET /api/cos/agents` sits on the first-paint critical path of every `/cos/*` tab and re-reads every 30s. Applied at the ROUTE layer only: `getAgents`/`getAgentsByDate` also feed the weekly digest and CoS reports, which need the whole text. || `cosToolContracts.js` | Provider-neutral `portos_tool` catalog/call schema version, request-id and per-turn bounds, catalog query formats, and Persistent Mind tool-call shape. || `persistentMindIssues.js` | Persistent-mind forge-issue contracts: bounded list/file schemas, the required-both dispatch axes, the closed category-label vocabulary with its lazily-created colors, the `persistent-mind` attribution label, and the title key the duplicate guard compares on. || `persistentMindTrajectory.js` | Pure persistent-mind trajectory vocabulary, sequence cursor parsing, replay projection, provenance-tagged rollup validation, bounded strictly-allowlisted per-provider-call execution receipts (route, run id, elapsed time, outcome, usage that stays `unknown` rather than zero) with their safe public projection, and hard-budget context assembly with explicit empty/missing/failed/stale summary states. |diff --git a/server/lib/cosAgentListProjection.js b/server/lib/cosAgentListProjection.jsnew file mode 100644index 0000000000..e918215364--- /dev/null+++ b/server/lib/cosAgentListProjection.js@@ -0,0 +1,51 @@+// What a CoS agent LIST response is allowed to carry.+//+// The Agents tab renders every card from two list reads — `GET /api/cos/agents`+// (state-resident runs, on the first-paint critical path of EVERY /cos/* tab and+// re-read by the 30s poll) and `GET /api/cos/agents/history/:date` (one archived+// date bucket). Both used to ship each agent's `metadata.taskDescription` whole,+// and that one field is the payload: measured over a real install's five most+// recent buckets it was 1.7 MB of a 2.35 MB response — 68% — while the state+// listing alone was 570 KB for 56 runs. The distribution is why: p50 is 75+// characters and p75 is 447, but the tail runs past 50 KB, because a CoS task+// description can be a whole pasted prompt. A handful of records pay for+// everyone, on every poll, over whatever link the user is on.+//+// The card never shows that text in full anyway — it renders through+// `CollapsibleText`, clamped to a few lines until the reader asks for more. So+// the listing carries a preview and stamps `taskDescriptionTruncated`; the+// client hydrates the full text from `GET /api/cos/agents/:id` at the two places+// it actually matters (expanding the description, and opening Resume/Relaunch,+// which build a new task prompt out of it).+//+// The cap is deliberately generous rather than tight. At 2000 characters over+// 90% of records are untouched, so the tab's client-side search and the+// task-type classifier behind the duration estimate keep seeing whole+// descriptions for every normal run, and the response still shrinks by ~65%.+//+// This is a ROUTE projection, not a service one: `getAgents` / `getAgentsByDate`+// also feed the weekly digest and CoS reports, which need the whole text.+import { clampToCharLimit } from './textUtils.js';++export const AGENT_LIST_DESCRIPTION_CHARS = 2000;++/**+ * Project one agent record into its list shape: no transcript, and a bounded+ * task description that says so when it was clipped.+ */+export function toAgentListItem(agent) {+ const { output, ...rest } = agent;+ const description = rest.metadata?.taskDescription;+ const { text, truncated } = clampToCharLimit(description, AGENT_LIST_DESCRIPTION_CHARS);+ if (!truncated) return rest;+ return {+ ...rest,+ metadata: {+ ...rest.metadata,+ taskDescription: text,+ taskDescriptionTruncated: true+ }+ };+}++export const toAgentListItems = (agents) => agents.map(toAgentListItem);diff --git a/server/lib/cosAgentListProjection.test.js b/server/lib/cosAgentListProjection.test.jsnew file mode 100644index 0000000000..779b0088aa--- /dev/null+++ b/server/lib/cosAgentListProjection.test.js@@ -0,0 +1,60 @@+import { describe, it, expect } from 'vitest';+import { toAgentListItem, toAgentListItems, AGENT_LIST_DESCRIPTION_CHARS } from './cosAgentListProjection.js';++const agent = (overrides = {}) => ({+ id: 'agent-001',+ status: 'completed',+ taskId: 'task-1',+ output: ['line one', 'line two'],+ metadata: { taskDescription: 'Fix the thing', model: 'opus', taskApp: 'portos' },+ ...overrides+});++describe('toAgentListItem', () => {+ it('drops the transcript from every listing row', () => {+ expect(toAgentListItem(agent())).not.toHaveProperty('output');+ });++ it('leaves a normal description whole and unflagged', () => {+ const item = toAgentListItem(agent());+ expect(item.metadata.taskDescription).toBe('Fix the thing');+ expect(item.metadata.taskDescriptionTruncated).toBeUndefined();+ });++ it('bounds an over-long description and flags it as clipped', () => {+ // A pasted-prompt description: the case the whole projection exists for.+ const long = 'Refactor the queue. '.repeat(5000);+ const item = toAgentListItem(agent({ metadata: { taskDescription: long } }));++ expect(item.metadata.taskDescription.length).toBeLessThanOrEqual(AGENT_LIST_DESCRIPTION_CHARS);+ expect(long.startsWith(item.metadata.taskDescription.trim())).toBe(true);+ expect(item.metadata.taskDescriptionTruncated).toBe(true);+ });++ it('does not mutate the record it projects — the service copy still feeds the digest whole', () => {+ const long = 'x'.repeat(AGENT_LIST_DESCRIPTION_CHARS + 500);+ const source = agent({ metadata: { taskDescription: long } });+ toAgentListItem(source);+ expect(source.metadata.taskDescription).toHaveLength(long.length);+ expect(source.output).toHaveLength(2);+ });++ it('keeps every other metadata field', () => {+ const long = 'y'.repeat(AGENT_LIST_DESCRIPTION_CHARS + 1);+ const item = toAgentListItem(agent({ metadata: { taskDescription: long, model: 'opus', taskApp: 'portos' } }));+ expect(item.metadata.model).toBe('opus');+ expect(item.metadata.taskApp).toBe('portos');+ });++ it('survives a record with no metadata at all', () => {+ expect(toAgentListItem({ id: 'agent-002' })).toEqual({ id: 'agent-002' });+ });+});++describe('toAgentListItems', () => {+ it('projects every row', () => {+ const items = toAgentListItems([agent(), agent({ id: 'agent-002' })]);+ expect(items).toHaveLength(2);+ expect(items.every(i => !('output' in i))).toBe(true);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 65b47bedad..1cdae23086 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -36,6 +36,7 @@ export * as cosValidation from './cosValidation.js';// check treats an identical identity as a re-export rather than a clash.export * from './cronFields.js';export * from './cronValidation.js';+export * from './cosAgentListProjection.js';export * from './cosToolContracts.js';export * as creativeCommissionValidation from './creativeCommissionValidation.js';// The generation-key spec creativeCommissionValidation.js builds its Zod schemadiff --git a/server/routes/apps/agents.js b/server/routes/apps/agents.jsindex 16dee19078..6e975044b4 100644--- a/server/routes/apps/agents.js+++ b/server/routes/apps/agents.js@@ -7,6 +7,7 @@import { Router } from 'express';import * as cos from '../../services/cos.js';import { asyncHandler } from '../../lib/errorHandler.js';+import { toAgentListItems } from '../../lib/cosAgentListProjection.js';import { parsePagination } from '../../lib/validation.js';import { loadApp } from './shared.js';@@ -51,8 +52,12 @@ router.get('/:id/agents', loadApp, asyncHandler(async (req, res) => {const succeeded = combined.filter(a => a.status === 'completed').length;const failed = combined.filter(a => a.status === 'failed' || a.status === 'error').length;+ // Same listing projection as `GET /api/cos/agents`: no transcripts, and a+ // bounded task description. This response can carry up to 500 records, and the+ // App page's table renders the description as a two-line clamped link label —+ // it never reuses the text, so nothing here needs hydration.res.json({- agents: combined,+ agents: toAgentListItems(combined),summary: { total: combined.length, running, succeeded, failed }});}));diff --git a/server/routes/apps/agents.test.js b/server/routes/apps/agents.test.jsnew file mode 100644index 0000000000..e70324cc82--- /dev/null+++ b/server/routes/apps/agents.test.js@@ -0,0 +1,64 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../../lib/testHelper.js';+import agentRoutes from './agents.js';++vi.mock('../../services/apps.js', () => ({+ getAppById: vi.fn(),+}));+vi.mock('../../services/cos.js', () => ({+ getAgents: vi.fn(),+ getAgentDates: vi.fn(),+ getAgentsByDate: vi.fn(),+}));++import * as appsService from '../../services/apps.js';+import * as cos from '../../services/cos.js';++const APP = { id: 'app-001', name: 'Widget' };++const agentFor = (id, overrides = {}) => ({+ id,+ status: 'completed',+ output: [{ line: 'a transcript line' }],+ metadata: { taskApp: APP.id, taskDescription: 'Fix the widget' },+ ...overrides,+});++describe('GET /api/apps/:id/agents', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use('/api/apps', agentRoutes);+ vi.clearAllMocks();+ appsService.getAppById.mockResolvedValue(APP);+ cos.getAgents.mockResolvedValue([]);+ cos.getAgentDates.mockResolvedValue([]);+ cos.getAgentsByDate.mockResolvedValue([]);+ });++ // This response carries up to 500 records; shipping each one's transcript and+ // whole pasted-prompt description is the same payload problem the CoS Agents+ // tab had. The table here renders the description as a clamped link label and+ // never reuses the text, so the bounded copy is all it needs.+ it('projects the combined list: no transcripts, bounded descriptions', async () => {+ const long = 'Refactor the queue. '.repeat(5000);+ cos.getAgents.mockResolvedValue([agentFor('agent-running', { status: 'running' })]);+ cos.getAgentDates.mockResolvedValue([{ date: '2026-07-13', count: 1 }]);+ cos.getAgentsByDate.mockResolvedValue([+ agentFor('agent-done', { metadata: { taskApp: APP.id, taskDescription: long } }),+ ]);++ const response = await request(app).get('/api/apps/app-001/agents');++ expect(response.status).toBe(200);+ expect(response.body.agents).toHaveLength(2);+ expect(response.body.agents.every(a => !('output' in a))).toBe(true);+ const archived = response.body.agents.find(a => a.id === 'agent-done');+ expect(archived.metadata.taskDescription.length).toBeLessThan(long.length);+ expect(archived.metadata.taskDescriptionTruncated).toBe(true);+ // The summary counts still read the real statuses, not the projection.+ expect(response.body.summary).toMatchObject({ total: 2, running: 1, succeeded: 1 });+ });+});diff --git a/server/routes/cos.test.js b/server/routes/cos.test.jsindex fe51faeba9..211bbc3c2a 100644--- a/server/routes/cos.test.js+++ b/server/routes/cos.test.js@@ -597,6 +597,34 @@ describe('CoS Routes', () => {});});+ describe('GET /api/cos/agents listing projection', () => {+ it('strips the transcript and bounds a pasted-prompt description', async () => {+ const long = 'Refactor the queue. '.repeat(5000);+ cos.getAgents.mockResolvedValue([+ { id: 'agent-001', status: 'completed', output: ['a', 'b'], metadata: { taskDescription: long, model: 'opus' } }+ ]);++ const response = await request(app).get('/api/cos/agents');++ expect(response.status).toBe(200);+ expect(response.body[0]).not.toHaveProperty('output');+ expect(response.body[0].metadata.taskDescription.length).toBeLessThan(long.length);+ expect(response.body[0].metadata.taskDescriptionTruncated).toBe(true);+ expect(response.body[0].metadata.model).toBe('opus');+ });++ it('leaves a normal description unflagged so the client never hydrates for nothing', async () => {+ cos.getAgents.mockResolvedValue([+ { id: 'agent-001', status: 'running', metadata: { taskDescription: 'Fix the thing' } }+ ]);++ const response = await request(app).get('/api/cos/agents');++ expect(response.body[0].metadata.taskDescription).toBe('Fix the thing');+ expect(response.body[0].metadata.taskDescriptionTruncated).toBeUndefined();+ });+ });+describe('GET /api/cos/agents/history', () => {it('should return available date buckets', async () => {cos.getAgentDates.mockResolvedValue([@@ -609,6 +637,37 @@ describe('CoS Routes', () => {expect(response.status).toBe(200);expect(response.body.dates).toHaveLength(2);expect(response.body.dates[0]).toEqual({ date: '2026-02-25', count: 5 });+ expect(response.body).not.toHaveProperty('latest');+ expect(cos.getAgentsByDate).not.toHaveBeenCalled();+ });++ it('?hydrate=1 also returns the newest bucket, so the tab needs one round trip', async () => {+ cos.getAgentDates.mockResolvedValue([+ { date: '2026-02-25', count: 5 },+ { date: '2026-02-24', count: 3 }+ ]);+ cos.getAgentsByDate.mockResolvedValue([+ { id: 'agent-001', status: 'completed', output: ['a'], metadata: { taskDescription: 'Short' } }+ ]);++ const response = await request(app).get('/api/cos/agents/history?hydrate=1');++ expect(response.status).toBe(200);+ expect(cos.getAgentsByDate).toHaveBeenCalledWith('2026-02-25');+ expect(response.body.latest.date).toBe('2026-02-25');+ expect(response.body.latest.agents).toHaveLength(1);+ // The hydrated bucket goes through the same listing projection.+ expect(response.body.latest.agents[0]).not.toHaveProperty('output');+ });++ it('hydrates to null on an install with no archived runs', async () => {+ cos.getAgentDates.mockResolvedValue([]);++ const response = await request(app).get('/api/cos/agents/history?hydrate=1');++ expect(response.status).toBe(200);+ expect(response.body.latest).toBeNull();+ expect(cos.getAgentsByDate).not.toHaveBeenCalled();});});diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.jsindex a2d33d4184..52cdcda3ed 100644--- a/server/routes/cosAgentRoutes.js+++ b/server/routes/cosAgentRoutes.js@@ -8,6 +8,7 @@ import * as cos from '../services/cos.js';// Lifecycle transitions go through the facade (#3450), not the `cos.js` barrel.import * as agentOrchestrator from '../services/agentOrchestrator.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { toAgentListItems } from '../lib/cosAgentListProjection.js';import { validateRequest, resumeCosAgentSchema, relaunchCosAgentSchema } from '../lib/validation.js';const router = Router();@@ -36,7 +37,8 @@ router.post('/health/check', asyncHandler(async (req, res) => {}));// GET /api/cos/agents - Get state-resident agents (running + recently completed, auto-cleans zombies)-// Strips output arrays from listing — output is loaded on demand via GET /agents/:id+// Output arrays and over-long task descriptions are stripped from every listing+// here — both are loaded on demand via GET /agents/:id. See cosAgentListProjection.js.router.get('/agents', asyncHandler(async (req, res) => {// Zombie cleanup probes the standalone runner and can wait up to its// transport timeout when that optional process is restarting or offline.@@ -47,13 +49,31 @@ router.get('/agents', asyncHandler(async (req, res) => {console.error(`🧹 Background zombie cleanup failed: ${err.message}`);});const agents = await cos.getAgents();- res.json(agents.map(({ output, ...rest }) => rest));+ res.json(toAgentListItems(agents));}));// GET /api/cos/agents/history - Get available date buckets with counts+//+// `?hydrate=1` also returns the newest bucket's agents. The Agents tab always+// wants them, but it cannot ask for them until this response names the date —+// so without this the tab pays two SERIAL round trips before a single archived+// card appears, which is the whole visible delay on a high-latency link.+// It stays opt-in because hydrating reads a whole date bucket off disk, which a+// caller that only wants the counts should not pay for.+const historyQuerySchema = z.object({ hydrate: z.literal('1').optional() });+router.get('/agents/history', asyncHandler(async (req, res) => {+ const { hydrate } = validateRequest(historyQuerySchema, req.query);const dates = await cos.getAgentDates();- res.json({ dates });+ if (!hydrate) return res.json({ dates });+ // `latest: null` is the answer for an install with no archived runs at all —+ // distinct from a bucket that read back empty, which the client must not+ // mistake for "not hydrated" and re-request.+ const latestDate = dates[0]?.date;+ const latest = latestDate+ ? { date: latestDate, agents: toAgentListItems(await cos.getAgentsByDate(latestDate)) }+ : null;+ res.json({ dates, latest });}));// GET /api/cos/agents/history/:date - Get completed agents for a date@@ -63,7 +83,7 @@ router.get('/agents/history/:date', asyncHandler(async (req, res) => {throw new ServerError('Invalid date format (expected YYYY-MM-DD)', { status: 400, code: 'VALIDATION_ERROR' });}const agents = await cos.getAgentsByDate(date);- res.json(agents);+ res.json(toAgentListItems(agents));}));// GET /api/cos/agents/:id - Get agent by ID (transcript hydrated as a capped tail)diff --git a/server/services/socket.js b/server/services/socket.jsindex e68c8c30cc..678aa94b56 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -1,4 +1,5 @@import { cosEvents } from './cosEvents.js';+import { toAgentListItem } from '../lib/cosAgentListProjection.js';import { appsEvents } from './apps.js';import { errorEvents, sanitizeContext } from '../lib/errorHandler.js';import { handleErrorRecovery } from './autoFixer.js';@@ -353,10 +354,17 @@ function setupCosEventForwarding() {cosEvents.on('maintenance:updated', (data) => broadcastToCos('cos:maintenance:updated', data));- // Agent events- cosEvents.on('agent:spawned', (data) => broadcastToCos('cos:agent:spawned', data));- cosEvents.on('agent:updated', (data) => broadcastToCos('cos:agent:updated', data));- cosEvents.on('agent:completed', (data) => broadcastToCos('cos:agent:completed', data));+ // Agent events. These three carry a whole agent RECORD, and every consumer —+ // the CoS agents list, the task-update hook, the peer relay — treats it as a+ // list row. So they leave through the same projection as `GET /api/cos/agents`:+ // no transcript (that is the separate `agent:output` stream) and a bounded task+ // description. Without it the socket refills the very list the listing+ // projection just shrank, and ships a 50 KB pasted prompt to every subscriber —+ // including, through the relay, a peer. Projected HERE rather than at the emit+ // because the server-side `cosEvents` listeners need the whole record.+ cosEvents.on('agent:spawned', (data) => broadcastToCos('cos:agent:spawned', toAgentListItem(data)));+ cosEvents.on('agent:updated', (data) => broadcastToCos('cos:agent:updated', toAgentListItem(data)));+ cosEvents.on('agent:completed', (data) => broadcastToCos('cos:agent:completed', toAgentListItem(data)));cosEvents.on('agent:output', (data) => broadcastToCos('cos:agent:output', data));cosEvents.on('agent:btw', (data) => broadcastToCos('cos:agent:btw', data));cosEvents.on('persistent-mind:status', (data) => broadcastToCos('cos:mind:status', data));diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex 9b65b614bd..8047a43d55 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -279,6 +279,38 @@ describe('socket.js — initSocket', () => {expect(socket.emitted).toContainEqual(['cos:tasks:changed', payload]);});+ // The three agent-record events leave through the same listing projection as+ // `GET /api/cos/agents`. Without it the socket refills the CoS agents list with+ // unprojected rows — transcript and whole pasted prompt — moments after the+ // HTTP listing shrank it, and relays that payload on to every peer.+ it.each(['agent:spawned', 'agent:updated', 'agent:completed'])(+ 'projects the agent record before broadcasting %s',+ (event) => {+ const socket = makeSocket(`agent-projection-${event}`);+ createdSockets.push(socket);+ io.connect(socket);+ socket.handlers['cos:subscribe']();++ const long = 'Refactor the queue. '.repeat(5000);+ const listener = cosEvents.on.mock.calls.find(([name]) => name === event)?.[1];+ listener({+ id: 'agent-001',+ taskId: 'task-1',+ status: 'running',+ output: [{ line: 'a transcript line' }],+ metadata: { taskDescription: long, model: 'opus' }+ });++ const [, broadcast] = socket.emitted.find(([name]) => name === `cos:${event}`);+ expect(broadcast).not.toHaveProperty('output');+ expect(broadcast.metadata.taskDescription.length).toBeLessThan(long.length);+ expect(broadcast.metadata.taskDescriptionTruncated).toBe(true);+ // The fields every consumer routes on survive the projection.+ expect(broadcast).toMatchObject({ id: 'agent-001', taskId: 'task-1', status: 'running' });+ expect(broadcast.metadata.model).toBe('opus');+ }+ );+// ===========================================================================// broadcast: two subscribed sockets both receive the event// Tested via the subscription ack — the internal Set membership is observable