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
Preserve CoS history with safe recording compression and cleanup (#8855)
[._.]/f9dd78be596b
diff --git a/client/src/components/dataManager/CosStoragePanel.jsx b/client/src/components/dataManager/CosStoragePanel.jsxnew file mode 100644index 0000000000..b092ebb595--- /dev/null+++ b/client/src/components/dataManager/CosStoragePanel.jsx@@ -0,0 +1,110 @@+import { useState, useRef, useEffect } from 'react';+import { useSocketResource } from '../../hooks/useSocketResource';+import { useAsyncAction } from '../../hooks/useAsyncAction';+import { formatBytes, formatCount } from '../../utils/formatters';+import * as api from '../../services/apiSystem';++const EVENTS = ['cos:storage:changed'];+const button = 'rounded border border-port-border px-3 py-2 text-sm disabled:opacity-40';+const input = 'rounded border border-port-border bg-port-bg px-2 py-1 text-sm w-full';++export default function CosStoragePanel({ onMaintenanceComplete }) {+ const resource = useSocketResource(({ signal }) => api.getCosStorage({ silent: true, signal }), { namespace: 'cos', events: EVENTS });+ const [filter, setFilter] = useState({ action: 'compress', olderThanDays: 7, model: '', outcome: 'all' });+ const [preview, setPreview] = useState(null);+ const [draft, setDraft] = useState(null);+ const [confirmed, setConfirmed] = useState(false);+ const generation = useRef(0);+ const job = resource.data?.job;+ const active = job?.state === 'running';+ const completionRef = useRef(null);+ useEffect(() => {+ if (!job?.id || !job.finishedAt || completionRef.current === job.id) return;+ completionRef.current = job.id;+ onMaintenanceComplete?.();+ }, [job?.id, job?.finishedAt, onMaintenanceComplete]);+ const policy = draft || resource.data?.policy;+ const dirty = draft && JSON.stringify(draft) !== JSON.stringify(resource.data?.policy);+ const changeFilter = (patch) => {+ generation.current++;+ setFilter(previous => ({ ...previous, ...patch }));+ setPreview(null);+ setConfirmed(false);+ };+ const [previewAction, previewing] = useAsyncAction(async (offset = 0) => {+ const request = ++generation.current;+ const result = await api.previewCosStorage(filter, offset, { silent: true });+ if (request === generation.current) { setPreview(result); setConfirmed(false); }+ });+ const [runAction, starting] = useAsyncAction(async () => {+ const result = await api.runCosStorage({ token: preview.token, ...(filter.action === 'purge' ? { confirmation: 'PURGE RAW RECORDINGS' } : {}) }, { silent: true });+ resource.updateData(result);+ setPreview(null);+ setConfirmed(false);+ });+ const [saveAction, saving] = useAsyncAction(async () => {+ const result = await api.saveCosStoragePolicy(policy, { silent: true });+ resource.updateData(result);+ setDraft(null);+ });+ const [cancelAction, cancelling] = useAsyncAction(async () => resource.updateData(await api.cancelCosStorage({ silent: true })));+ const [pinAction, pinning] = useAsyncAction(async (row) => {+ await api.pinCosRecording({ date: row.date, id: row.id, pinned: !row.pinned }, { silent: true });+ setPreview(null); // A new preview must reflect the changed protection before execution.+ });++ return (+ <section className="border-t border-port-border p-3 space-y-4" aria-label="CoS recording cleanup">+ <div>+ <h3 className="font-semibold">Recording cleanup</h3>+ <p className="text-sm text-gray-400">Compress raw terminal recordings without losing their contents. Metadata, summaries, prompts, parsed output, feedback and history remain. Active, recent, pinned and resumable runs are protected.</p>+ </div>+ {resource.error && <p role="alert">Storage settings unavailable. <button className={button} onClick={resource.refetch}>Retry</button></p>}+ {policy && (+ <fieldset disabled={saving} className="border border-port-border rounded p-3 space-y-2">+ <legend className="text-sm">Automatic maintenance</legend>+ <div className="grid gap-3 sm:grid-cols-2">+ <div>+ <label className="flex gap-2" htmlFor="cos-auto-compress"><input id="cos-auto-compress" type="checkbox" checked={policy.autoCompress} onChange={e => setDraft({ ...policy, autoCompress: e.target.checked })} />Compress recordings automatically</label>+ <label htmlFor="cos-compress-days">After days</label>+ <input id="cos-compress-days" className={input} type="number" min="1" max="36500" value={policy.compressAfterDays} onChange={e => setDraft({ ...policy, compressAfterDays: Number(e.target.value) })} />+ </div>+ <div>+ <label className="flex gap-2" htmlFor="cos-auto-purge"><input id="cos-auto-purge" type="checkbox" checked={policy.autoPurge} onChange={e => setDraft({ ...policy, autoPurge: e.target.checked })} />Allow permanent raw recording deletion</label>+ <label htmlFor="cos-purge-days">After days (requires retained summary and output)</label>+ <input id="cos-purge-days" className={input} type="number" min="7" max="36500" value={policy.purgeAfterDays} onChange={e => setDraft({ ...policy, purgeAfterDays: Number(e.target.value) })} />+ </div>+ </div>+ <p className="text-xs text-gray-400">Saving enables the selected policy immediately, then checks hourly in small batches while Chief of Staff is running. Disabling a policy stops further files in its automatic run.</p>+ <button className={button} disabled={!dirty || saving} onClick={saveAction}>{saving ? 'Saving…' : 'Save maintenance policy'}</button>+ </fieldset>+ )}+ <div className="grid gap-3 sm:grid-cols-4">+ <div><label htmlFor="cos-storage-action">Action</label><select id="cos-storage-action" className={input} value={filter.action} onChange={e => changeFilter({ action: e.target.value })}><option value="compress">Lossless compression</option><option value="purge">Delete raw recordings</option></select></div>+ <div><label htmlFor="cos-storage-days">Completed at least days ago</label><input id="cos-storage-days" className={input} type="number" min="1" max="36500" value={filter.olderThanDays} onChange={e => changeFilter({ olderThanDays: Number(e.target.value) })} /></div>+ <div><label htmlFor="cos-storage-model">Exact model (blank for all)</label><input id="cos-storage-model" className={input} list="cos-storage-models" value={filter.model} onChange={e => changeFilter({ model: e.target.value })} /><datalist id="cos-storage-models">{preview?.models.map(model => <option key={model} value={model} />)}</datalist></div>+ <div><label htmlFor="cos-storage-outcome">Outcome</label><select id="cos-storage-outcome" className={input} value={filter.outcome} onChange={e => changeFilter({ outcome: e.target.value })}><option value="all">All outcomes</option><option value="success">Successful</option><option value="failure">Unsuccessful</option></select></div>+ </div>+ <button className={button} disabled={previewing || active || starting || saving || dirty} onClick={() => previewAction()}>{previewing ? 'Scanning recordings…' : 'Preview cleanup'}</button>+ {preview && (+ <div className="space-y-3">+ <p className="text-xs text-gray-400">Matching archived runs: {formatBytes(preview.totals.recordingBytes)} recordings · {formatBytes(preview.totals.metadataBytes)} metadata · {formatBytes(preview.totals.outputBytes)} parsed output · {formatBytes(preview.totals.promptBytes)} prompts.</p>+ <p>{formatCount(preview.totals.eligibleRuns)} eligible runs · {formatBytes(preview.totals.eligibleBytes)} raw recording bytes in this batch. Compression savings are measured after verification.</p>+ <p className="text-xs text-gray-400">Up to {formatCount(preview.batchLimit)} runs per manual batch. {formatCount(preview.totals.unreadable)} unreadable runs were left untouched.</p>+ <ul className="text-xs text-gray-400">{Object.entries(preview.reasons).map(([reason, count]) => <li key={reason}>{reason}: {formatCount(count)}</li>)}</ul>+ <div className="overflow-x-auto"><table className="w-full text-xs"><thead><tr><th className="text-left">Run</th><th>Model</th><th>Recording</th><th>Protection</th><th>Actions</th></tr></thead><tbody>+ {preview.rows.map(row => <tr key={row.id} className="border-t border-port-border"><td className="py-2">{row.date}<br />{row.id}</td><td>{row.model}</td><td>{formatBytes(row.bytes)} · {row.state}</td><td>{row.reason || 'Eligible'}</td><td><button className={button} disabled={pinning || active || starting} onClick={() => pinAction(row)}>{row.pinned ? 'Unpin' : 'Pin'}</button>{['plain', 'compressed'].includes(row.state) && <a className="ml-2 text-port-accent" href={`/api/data/cos/storage/recording/${encodeURIComponent(row.date)}/${encodeURIComponent(row.id)}`} download>Download</a>}</td></tr>)}+ </tbody></table></div>+ <div className="flex gap-2"><button className={button} disabled={!preview.offset || previewing} onClick={() => previewAction(Math.max(0, preview.offset - 25))}>Previous runs</button><button className={button} disabled={preview.offset + preview.rows.length >= preview.matching || previewing} onClick={() => previewAction(preview.offset + 25)}>Next runs</button></div>+ {filter.action === 'purge' && <label className="flex gap-2" htmlFor="cos-confirm-purge"><input id="cos-confirm-purge" type="checkbox" checked={confirmed} onChange={e => setConfirmed(e.target.checked)} />Permanently delete eligible raw recordings. I understand they cannot be recovered from history; parsed output and metadata remain.</label>}+ <button className={button} disabled={!preview.totals.eligibleRuns || starting || active || pinning || previewing || saving || dirty || (filter.action === 'purge' && !confirmed)} onClick={runAction}>{filter.action === 'purge' ? 'Delete eligible raw recordings' : 'Compress eligible recordings'}</button>+ </div>+ )}+ {job && <div role="status" className="text-sm border border-port-border rounded p-3">+ {job.action}: {job.state} · {formatCount(job.processed)}/{formatCount(job.total)} processed · {formatBytes(job.reclaimedBytes)} reclaimed · {formatCount(job.skipped)} skipped · {formatCount(job.failed)} failed+ {job.failed > 0 && <p>Some recordings could not be processed. Their history remains; preview again to inspect remaining files.</p>}+ {active && <button className={`${button} ml-2`} disabled={cancelling} onClick={cancelAction}>Cancel maintenance</button>}+ </div>}+ </section>+ );+}diff --git a/client/src/components/dataManager/CosStoragePanel.test.jsx b/client/src/components/dataManager/CosStoragePanel.test.jsxnew file mode 100644index 0000000000..81ab6a0e5d--- /dev/null+++ b/client/src/components/dataManager/CosStoragePanel.test.jsx@@ -0,0 +1,55 @@+import { beforeEach, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import CosStoragePanel from './CosStoragePanel';+import * as api from '../../services/apiSystem';+vi.mock('../../services/apiSystem', () => ({+ getCosStorage: vi.fn(), previewCosStorage: vi.fn(), runCosStorage: vi.fn(),+ cancelCosStorage: vi.fn(), saveCosStoragePolicy: vi.fn(), pinCosRecording: vi.fn(),+}));+vi.mock('../../services/socket', () => ({ default: { connected: true, on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));+const policy = { autoCompress: true, compressAfterDays: 7, autoPurge: false, purgeAfterDays: 90 };+beforeEach(() => {+ vi.clearAllMocks();+ api.getCosStorage.mockResolvedValue({ policy, job: null });+ api.previewCosStorage.mockResolvedValue({ token: 'example-token', models: [], rows: [], reasons: {}, totals: { eligibleRuns: 1, eligibleBytes: 2048, unreadable: 0 }, matching: 0, offset: 0, batchLimit: 1000 });+ api.runCosStorage.mockResolvedValue({ policy, job: { action: 'purge', state: 'running', total: 1, processed: 0, skipped: 0, failed: 0, reclaimedBytes: 0 } });+});+it('requires a fresh preview and explicit deletion consent, then shows progress without clearing history', async () => {+ render(<CosStoragePanel />);+ await screen.findByLabelText('Compress recordings automatically');+ fireEvent.change(screen.getByLabelText('Action'), { target: { value: 'purge' } });+ fireEvent.click(screen.getByRole('button', { name: 'Preview cleanup' }));+ const run = await screen.findByRole('button', { name: 'Delete eligible raw recordings' });+ expect(run).toBeDisabled();+ fireEvent.click(screen.getByLabelText(/Permanently delete eligible raw recordings/));+ expect(run).toBeEnabled();+ fireEvent.change(screen.getByLabelText('Exact model (blank for all)'), { target: { value: 'example-model' } });+ expect(screen.queryByRole('button', { name: 'Delete eligible raw recordings' })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Preview cleanup' }));+ await screen.findByRole('button', { name: 'Delete eligible raw recordings' });+ fireEvent.click(screen.getByLabelText(/Permanently delete eligible raw recordings/));+ fireEvent.click(screen.getByRole('button', { name: 'Delete eligible raw recordings' }));+ await waitFor(() => expect(api.runCosStorage).toHaveBeenCalledWith({ token: 'example-token', confirmation: 'PURGE RAW RECORDINGS' }, { silent: true }));+ expect(await screen.findByRole('button', { name: 'Cancel maintenance' })).toBeEnabled();+ expect(screen.getByText(/Metadata, summaries, prompts/)).toBeInTheDocument();+});+it('gates cleanup while policy changes are unsaved or saving', async () => {+ let resolveSave;+ api.saveCosStoragePolicy.mockReturnValue(new Promise(resolve => { resolveSave = resolve; }));+ render(<CosStoragePanel />);+ await screen.findByLabelText('Compress recordings automatically');+ fireEvent.click(screen.getByLabelText('Allow permanent raw recording deletion'));+ expect(screen.getByRole('button', { name: 'Preview cleanup' })).toBeDisabled();+ fireEvent.click(screen.getByRole('button', { name: 'Save maintenance policy' }));+ expect(screen.getByRole('button', { name: 'Preview cleanup' })).toBeDisabled();+ resolveSave({ policy: { ...policy, autoPurge: true }, job: null });+ await waitFor(() => expect(screen.getByRole('button', { name: 'Preview cleanup' })).toBeEnabled());+});+it('notifies the storage view once when a job completes, including reconnect reconciliation', async () => {+ const complete = vi.fn();+ api.getCosStorage.mockResolvedValue({ policy, job: { id: 'example-job', action: 'compress', state: 'completed', finishedAt: '2026-01-01T00:00:00Z', total: 1, processed: 1, skipped: 0, failed: 0, reclaimedBytes: 1024 } });+ const { rerender } = render(<CosStoragePanel onMaintenanceComplete={complete} />);+ await waitFor(() => expect(complete).toHaveBeenCalledTimes(1));+ rerender(<CosStoragePanel onMaintenanceComplete={complete} />);+ expect(complete).toHaveBeenCalledTimes(1);+});diff --git a/client/src/components/dataManager/DataSelectionPanel.jsx b/client/src/components/dataManager/DataSelectionPanel.jsxindex c4eca40451..9bf5885ee9 100644--- a/client/src/components/dataManager/DataSelectionPanel.jsx+++ b/client/src/components/dataManager/DataSelectionPanel.jsx@@ -64,7 +64,7 @@ export default function DataSelectionPanel({ overview, totalFiles, selected, det<ProgressBar percent={share} tone={kind?.tone ?? 'accent'} track="border" label="Share of data/" className="mt-2" /><div className="mt-3 grid grid-cols-2 gap-x-4 gap-y-3"><Stat label="Of data/">{formatPercent(share, { decimals: share < 10 ? 1 : 0 })}</Stat>- <Stat label="Files">{formatCount(fileCount, { fallback: '0' })}</Stat>+ <Stat label="Files">{formatCount(fileCount, { fallback: 'Unavailable' })}</Stat><Stat label="Kind">{kind ? kind.label : `${formatCount(categories.length)} categories`}</Stat><Stat label="Entries">{itemCount == null ? '—' : formatCount(itemCount)}</Stat></div>diff --git a/client/src/pages/DataManager.jsx b/client/src/pages/DataManager.jsxindex e07bf0d208..2bec6f3b2e 100644--- a/client/src/pages/DataManager.jsx+++ b/client/src/pages/DataManager.jsx@@ -13,6 +13,7 @@ import useMounted from '../hooks/useMounted';import InlineConfirmRow from '../components/ui/InlineConfirmRow';import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';import DataTreemap from '../components/dataManager/DataTreemap';+import CosStoragePanel from '../components/dataManager/CosStoragePanel';import DataSelectionPanel from '../components/dataManager/DataSelectionPanel';import { DATA_KINDS, DATA_KIND_ORDER, HATCH_STYLE, dataKindOf } from '../components/dataManager/dataKinds';@@ -145,7 +146,7 @@ function SizeBar({ size, maxSize, color }) {);}-function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPurge, onConfirmPurge, onCancelPurge, onDeleteItem, deletingItem, confirmingPurge, archiving, purging }) {+function CategoryRow({ onMaintenanceComplete, cat, maxSize, onExpand, expanded, detail, onArchive, onPurge, onConfirmPurge, onCancelPurge, onDeleteItem, deletingItem, confirmingPurge, archiving, purging }) {// Directories with no CATEGORIES entry come back with `classified: false` and// no Archive/Purge flags. Say why the buttons are missing in outcome terms so// the row reads as a deliberate safety stance, not a broken row (#3285).@@ -189,7 +190,7 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPu</div><div className="text-right shrink-0 ml-2"><div className="text-sm font-mono text-white">{formatBytes(cat.size)}</div>- <div className="text-xs text-gray-500">{formatCount(cat.fileCount)} files</div>+ <div className="text-xs text-gray-500">{cat.fileCount == null ? 'File count unavailable — refresh to retry' : `${formatCount(cat.fileCount)} files`}</div></div></button>@@ -199,7 +200,7 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPu{confirmingPurge && !busy ? (<InlineConfirmRowvariant="separator"- question={`Purge all ${formatCount(cat.fileCount)} files (${formatBytes(cat.size)}) in ${cat.label}? This permanently deletes the data and cannot be undone.`}+ question={`Purge ${cat.fileCount == null ? 'all files' : `all ${formatCount(cat.fileCount)} files`} (${formatBytes(cat.size)}) in ${cat.label}? This permanently deletes the data and cannot be undone.`}confirmText="Purge"confirmTitle="Confirm purge"cancelTitle="Cancel purge"@@ -215,7 +216,7 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPuclassName="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium bg-port-accent/10 text-port-accent rounded hover:bg-port-accent/20 transition-colors disabled:opacity-50"><Archive size={12} />- {archiving ? 'Archiving...' : 'Archive'}+ {archiving ? 'Archiving...' : cat.key === 'cos' ? 'Export backup (keeps originals)' : 'Archive'}</button>)}{categoryPurgeable && (busy ? (@@ -245,6 +246,7 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPu</div>)}+ {cat.key === 'cos' && <CosStoragePanel onMaintenanceComplete={onMaintenanceComplete} />}{/* Detail items */}{detail ? (<div className="max-h-64 overflow-auto">@@ -268,7 +270,7 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPu<span className="truncate">{item.name}</span></td><td className="p-2 text-right text-gray-400 font-mono">{formatBytes(item.size)}</td>- <td className="p-2 pr-3 text-right text-gray-500">{item.type === 'directory' ? formatCount(item.fileCount) : '—'}</td>+ <td className="p-2 pr-3 text-right text-gray-500">{item.type === 'directory' ? (item.fileCount == null ? 'Unavailable' : formatCount(item.fileCount)) : '—'}</td>{itemScoped && (<td className="p-2 pr-3 text-right">{item.type === 'directory' ? (@@ -393,14 +395,21 @@ export default function DataManager() {const [confirmPurge, setConfirmPurge] = useState(null);const [deletingItem, setDeletingItem] = useState(null);- const fetchOverview = useCallback(async () => {- const [data, bk] = await Promise.all([+ const overviewRequestRef = useRef(0);+ const overviewReadRef = useRef(null);+ const fetchOverview = useCallback(() => {+ const token = ++overviewRequestRef.current;+ const read = Promise.all([api.getDataOverview().catch(() => null),api.getDataBackups().catch(() => [])- ]);- setOverview(data);- setBackups(bk);- setLoading(false);+ ]).then(([data, bk]) => {+ if (token !== overviewRequestRef.current) return;+ setOverview(data);+ setBackups(bk);+ setLoading(false);+ });+ overviewReadRef.current = read;+ return read.finally(() => { if (overviewReadRef.current === read) overviewReadRef.current = null; });}, []);useEffect(() => { fetchOverview(); }, [fetchOverview]);@@ -452,6 +461,36 @@ export default function DataManager() {if (expandedCatRef.current === key) await loadDetail(key);};+ // A recording job changes this category plus disk space. Re-measure only+ // CoS, preserving unrelated categories and the user's current selection.+ const reconcileCosStorage = useCallback(async () => {+ // Let full reads publish unrelated fields (including new backup exports)+ // before this narrower measurement. A later full read still supersedes it.+ while (overviewReadRef.current) await overviewReadRef.current;+ const token = ++overviewRequestRef.current;+ const detailToken = expandedCatRef.current === 'cos' ? ++detailRequestRef.current : null;+ const refreshed = await api.getDataCategory('cos', { measure: true, silent: true }).catch(() => null);+ if (!refreshed?.measurement || token !== overviewRequestRef.current) return;+ if (expandedCatRef.current === 'cos' && detailToken === detailRequestRef.current) {+ setDetail(refreshed);+ }+ const measurement = refreshed.measurement;+ setOverview(previous => {+ if (!previous) return previous;+ const old = previous.categories.find(category => category.key === 'cos');+ if (!old) return previous;+ return {+ ...previous,+ totalSize: Math.max(0, previous.totalSize - old.size + measurement.size),+ totalFileCount: previous.totalFileCount == null || old.fileCount == null || measurement.fileCount == null+ ? null : previous.totalFileCount - old.fileCount + measurement.fileCount,+ disk: measurement.disk,+ categories: previous.categories.map(category => category.key === 'cos'+ ? { ...category, size: measurement.size, fileCount: measurement.fileCount } : category),+ };+ });+ }, []);+const handleArchive = async (key) => {setArchiving(key);const result = await api.archiveDataCategory(key).catch(() => null);@@ -512,8 +551,8 @@ export default function DataManager() {const looseBytes = Math.max(0, (overview?.totalSize || 0) - categoryBytes);// Older servers omit totalFileCount; the category sum then undercounts only// the files sitting directly in data/.- const totalFiles = overview?.totalFileCount- ?? categories.reduce((sum, c) => sum + (c.fileCount || 0), 0);+ const totalFiles = overview?.totalFileCount !== undefined ? overview.totalFileCount+ : categories.some(c => c.fileCount == null) ? null : categories.reduce((sum, c) => sum + c.fileCount, 0);const presentKinds = DATA_KIND_ORDER.filter((k) => categories.some((c) => dataKindOf(c) === k));const selectedCat = categories.find((c) => c.key === expandedCat) || null;@@ -555,7 +594,7 @@ export default function DataManager() {<div className="flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs"><span className="text-gray-300"><span className="font-mono text-white">{formatBytes(overview?.totalSize || 0)}</span>- {' · '}{formatCount(totalFiles, { fallback: '0' })} files+ {' · '}{totalFiles == null ? 'File count unavailable' : `${formatCount(totalFiles)} files`}{' · '}{formatCount(categories.length, { fallback: '0' })} categories{' · '}{formatCount(backups.length, { fallback: '0' })} backups</span>@@ -589,6 +628,7 @@ export default function DataManager() {detail={expandedCat === cat.key ? detail : null}onExpand={handleExpand}onArchive={handleArchive}+ onMaintenanceComplete={reconcileCosStorage}onPurge={setConfirmPurge}onConfirmPurge={executePurge}onCancelPurge={() => setConfirmPurge(null)}diff --git a/client/src/pages/DataManager.test.jsx b/client/src/pages/DataManager.test.jsxindex bd996371b2..93583f98d1 100644--- a/client/src/pages/DataManager.test.jsx+++ b/client/src/pages/DataManager.test.jsx@@ -1,6 +1,8 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { render, screen, waitFor, fireEvent, act } from '@testing-library/react';import DataManager from './DataManager';+import { formatBytes } from '../utils/formatters';+vi.mock('../components/dataManager/CosStoragePanel', () => ({ default: ({ onMaintenanceComplete }) => <button onClick={onMaintenanceComplete}>Complete recording cleanup</button> }));import socket from '../services/socket';import { getTombstoneSweepStatus } from '../services/api';@@ -436,3 +438,45 @@ describe('DataManager treemap + selection panel', () => {expect(panel).toHaveTextContent('10 GB total');});});++it('shows an unavailable count rather than an empty directory after enumeration failure', async () => {+ getDataOverview.mockResolvedValue({ ...overview, totalFileCount: null, categories: [{ ...overview.categories[0], fileCount: null }] });+ render(<DataManager />);+ await waitFor(() => expect(screen.getByText('File count unavailable — refresh to retry')).toBeInTheDocument());+ expect(screen.queryByText('0 files')).not.toBeInTheDocument();+});++it('does not let an older cleanup measurement overwrite a newer full refresh', async () => {+ const category = { key: 'cos', path: 'data/cos', label: 'Chief of Staff', description: 'Run history', archivable: true, deletable: false, classified: true, size: 4000, fileCount: 20 };+ getDataOverview.mockResolvedValue({ totalSize: 4000, totalFileCount: 20, categories: [category] });+ let resolveMeasurement;+ getDataCategory.mockImplementation((_key, options) => options?.measure+ ? new Promise(resolve => { resolveMeasurement = resolve; })+ : Promise.resolve({ key: 'cos', items: [] }));+ render(<DataManager />);+ await screen.findAllByText('Chief of Staff');+ expandRow('Chief of Staff');+ fireEvent.click(await screen.findByRole('button', { name: 'Complete recording cleanup' }));+ getDataOverview.mockResolvedValue({ totalSize: 8000, totalFileCount: 25, categories: [{ ...category, size: 8000, fileCount: 25 }] });+ fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));+ await waitFor(() => expect(screen.getAllByText(formatBytes(8000)).length).toBeGreaterThan(0));+ await act(async () => resolveMeasurement({ key: 'cos', items: [], measurement: { size: 1000, fileCount: 10, disk: null } }));+ expect(screen.getAllByText(formatBytes(8000)).length).toBeGreaterThan(0);+ expect(screen.queryByText('10 files')).not.toBeInTheDocument();+});+it('prevents an older expanded-detail read from replacing measured cleanup contents', async () => {+ const category = { key: 'cos', path: 'data/cos', label: 'Chief of Staff', description: 'Run history', archivable: true, deletable: false, classified: true, size: 4000, fileCount: 20 };+ getDataOverview.mockResolvedValue({ totalSize: 4000, totalFileCount: 20, categories: [category] });+ let resolveDetail;+ getDataCategory.mockImplementation((_key, options) => options?.measure+ ? Promise.resolve({ key: 'cos', items: [{ name: 'fresh-example.txt', type: 'file', size: 1000 }], measurement: { size: 1000, fileCount: 1, disk: null } })+ : new Promise(resolve => { resolveDetail = resolve; }));+ render(<DataManager />);+ await screen.findAllByText('Chief of Staff');+ expandRow('Chief of Staff');+ fireEvent.click(await screen.findByRole('button', { name: 'Complete recording cleanup' }));+ await screen.findAllByText('fresh-example.txt');+ await act(async () => resolveDetail({ key: 'cos', items: [{ name: 'stale-example.txt', type: 'file', size: 4000 }] }));+ expect(screen.queryByText('stale-example.txt')).not.toBeInTheDocument();+ expect(screen.getAllByText('fresh-example.txt')).toHaveLength(2);+});diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex bff178868c..bb61328f85 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -366,7 +366,7 @@ export const deleteBackupSnapshot = (snapshotId, source, options = {}) => {// Data Managerexport const getDataOverview = () => request('/data');-export const getDataCategory = (key) => request(`/data/${key}`);+export const getDataCategory = (key, options = {}) => request(`/data/${key}${options.measure ? '?measure=1' : ''}`, options);export const archiveDataCategory = (key, opts) => request(`/data/${key}/archive`, { method: 'POST', body: JSON.stringify(opts || {}) });export const purgeDataCategory = (key, opts, options = {}) => request(`/data/${key}`, {method: 'DELETE',@@ -600,3 +600,11 @@ export const getEidoverseDestinations = (options) => request('/eidoverse/travel/export const departEidoverse = (peerId, options) => request('/eidoverse/travel/depart', { method: 'POST', body: JSON.stringify({ peerId }), ...options });export const saveCredential = (id, value, options) => request(`/settings/credentials/${encodeURIComponent(id)}`, { ...options, method: 'PUT', body: JSON.stringify({ value }) });++// CoS raw recordings; metadata, prompts and parsed output are retained.+export const getCosStorage = (options) => request('/data/cos/storage', options);+export const previewCosStorage = (filter, offset = 0, options) => request(`/data/cos/storage/preview?offset=${offset}`, { ...options, method: 'POST', body: JSON.stringify(filter) });+export const runCosStorage = (input, options) => request('/data/cos/storage/run', { ...options, method: 'POST', body: JSON.stringify(input) });+export const cancelCosStorage = (options) => request('/data/cos/storage/cancel', { ...options, method: 'POST' });+export const saveCosStoragePolicy = (policy, options) => request('/data/cos/storage/policy', { ...options, method: 'PUT', body: JSON.stringify(policy) });+export const pinCosRecording = (input, options) => request('/data/cos/storage/pin', { ...options, method: 'PUT', body: JSON.stringify(input) });diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 1501dcb957..55e1606793 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -595,3 +595,40 @@ before manually retiring history.Password-risk acceptance is browser-local, stored for this origin under the versioned `portos-password-risk-v1` key. No API can acknowledge the warning for another browser. Missing or unreadable storage requires consent again; acceptance is not federated or included in instance backups. This is a browser preference, not an app-native record.`passwordRiskRevision` is an optional, opaque machine-local setting in the existing file-primary `data/settings.json` store, alongside authentication configuration. Password changes rotate it so old browser acknowledgements become invalid even if that browser was offline. Its absence means the initial revision, enrolling existing installs without a seed or migration. Generic settings updates cannot replace it; the read-only password-risk endpoint exposes only the revision and whether password protection is enabled.++### CoS raw recording maintenance++CoS historical `metadata.json`, prompts, parsed `output.txt`, feedback and history+indexes have no automatic age expiry. `cosAgentIndex.pruneOldAgentArchives` is a+compatibility no-op. Data Management → Chief of Staff → Recording cleanup offers+verified gzip compression and separately opted-in deletion of **raw terminal+recordings only**. Unknown files, parsed output, prompts and metadata are never+removed by this maintenance. The separate explicit Delete/Clear history actions+remain destructive; they are not storage maintenance.++The existing machine-local CoS config owns `agentStorage` and a bounded+`lastAgentStorageJob` audit. Defaults compress after seven days, with irreversible+deletion off. Migration 416 adopts those defaults for existing config without+converting any recording or overwriting user policy. While CoS is running, hourly maintenance handles+at most 25 eligible runs; manual previews handle at most 1,000 per batch and+expire after 15 minutes. Saving policy reconciles it immediately. No provider+calls occur. A cancellation preserves the original until verified publication.++`raw.txt.gz` is a lossless local asset alternative to `raw.txt`; a same-directory+`raw-storage.json` is **file-primary asset lifecycle metadata**, inseparable from+that archive's pin, checksum and disposition. It is not a new relational history+store. A plain file wins if interrupted publication leaves both forms; a later+maintenance pass verifies and converges them. History and learning consumers keep+reading unchanged metadata/output/prompt files. The download endpoint serves the+available raw or gzip asset without loading it into memory; deleted recordings+return an explicit unavailable response. The flat active-run layout is excluded.++Compression requires an old, completed, state-evicted, unpinned run with regular,+unmodified artifacts and no preserved worktree or known live/resume/pipeline+reference. Deletion additionally requires a retained task summary and nonempty+parsed output. A stale preview is revalidated before publication/deletion. The+raw sidecar and compressed asset stay machine-local; existing peer CoS sync+continues its unchanged allowlist (`metadata.json`, `output.txt`, `prompt.txt`).+Filesystem backups include both gzip assets and their sidecars, and restore keeps+them readable without a conversion. Data Management's backup export keeps its+originals and is distinct from space reclamation.diff --git a/scripts/migrations/416-cos-recording-retention.js b/scripts/migrations/416-cos-recording-retention.jsnew file mode 100644index 0000000000..e216705d0f--- /dev/null+++ b/scripts/migrations/416-cos-recording-retention.js@@ -0,0 +1,20 @@+/**+ * Adopt metadata-preserving CoS retention. No recordings are converted at+ * upgrade: bounded maintenance converts raw.txt to verified raw.txt.gz lazily.+ * Config is migration-owned and must not have a data.reference seed.+ */+import { join } from 'path';+import { readJSONFileStrict } from '../../server/lib/fileUtils.js';+import { writeJsonAtomic } from './_lib.js';++export default {+ async up({ rootDir }) {+ const file = join(rootDir, 'data', 'cos', 'config.json');+ const { ok, value } = await readJSONFileStrict(file, null, { logError: false });+ if (ok && value === null) return { updated: 0 };+ if (!ok || !value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid CoS config; preserving original');+ if (Object.hasOwn(value, 'agentStorage')) return { updated: 0 };+ await writeJsonAtomic(file, { ...value, agentStorage: { autoCompress: true, compressAfterDays: 7, autoPurge: false, purgeAfterDays: 90 } });+ return { updated: 1 };+ },+};diff --git a/scripts/migrations/416-cos-recording-retention.test.js b/scripts/migrations/416-cos-recording-retention.test.jsnew file mode 100644index 0000000000..a8b261bc90--- /dev/null+++ b/scripts/migrations/416-cos-recording-retention.test.js@@ -0,0 +1,23 @@+import { afterAll, expect, it } from 'vitest';+import { mkdtemp, mkdir, readFile, writeFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import migration from './416-cos-recording-retention.js';+const rootDir = await mkdtemp(join(tmpdir(), 'cos-retention-migration-'));+afterAll(() => rm(rootDir, { recursive: true, force: true }));+it('adopts lossless retention without touching archives, overriding choices, or resetting invalid config', async () => {+ expect(await migration.up({ rootDir })).toEqual({ updated: 0 });+ const dir = join(rootDir, 'data', 'cos'); await mkdir(dir, { recursive: true });+ const file = join(dir, 'config.json');+ await writeFile(file, JSON.stringify({ maxConcurrentAgents: 2 }));+ expect(await migration.up({ rootDir })).toEqual({ updated: 1 });+ const value = JSON.parse(await readFile(file, 'utf8'));+ expect(value).toMatchObject({ maxConcurrentAgents: 2, agentStorage: { autoCompress: true, autoPurge: false } });+ value.agentStorage.autoCompress = false;+ await writeFile(file, JSON.stringify(value));+ expect(await migration.up({ rootDir })).toEqual({ updated: 0 });+ expect(JSON.parse(await readFile(file, 'utf8')).agentStorage.autoCompress).toBe(false);+ await writeFile(file, '{broken');+ await expect(migration.up({ rootDir })).rejects.toThrow('Invalid CoS config');+ expect(await readFile(file, 'utf8')).toBe('{broken');+});diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.jsindex 8b662acaf6..f2ea7aa38b 100644--- a/server/lib/socketEventContracts.js+++ b/server/lib/socketEventContracts.js@@ -143,6 +143,11 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({summary: 'Invalidate upcoming tasks after scheduler registration, cancellation or execution.',payloadSchema: { type: 'object', properties: {}, additionalProperties: false },},+ 'cos:storage:changed': {+ direction: 'server-to-client',+ summary: 'Invalidate CoS recording maintenance progress and policy.',+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },+ },'cos:agents:changed': {direction: 'server-to-client',summary: 'Invalidate agent aggregates after deletion or cleanup.',diff --git a/server/routes/dataManager.js b/server/routes/dataManager.jsindex 82c630e0b6..a78ed6c64e 100644--- a/server/routes/dataManager.js+++ b/server/routes/dataManager.js@@ -1,4 +1,5 @@import { Router } from 'express';+import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest, dataPurgeSchema } from '../lib/validation.js';import {@@ -12,6 +13,41 @@ import {const router = Router();+// Lazy service import keeps ordinary storage overview reads out of the CoS graph.+router.get('/cos/storage', asyncHandler(async (req, res) => {+ const service = await import('../services/cosAgentStorage.js');+ res.json(await service.getAgentStorageStatus());+}));+router.put('/cos/storage/policy', asyncHandler(async (req, res) => {+ const service = await import('../services/cosAgentStorage.js');+ res.json(await service.updateAgentStoragePolicy(validateRequest(service.agentStoragePolicySchema, req.body)));+}));+router.post('/cos/storage/preview', asyncHandler(async (req, res) => {+ const service = await import('../services/cosAgentStorage.js');+ const { offset } = validateRequest(z.object({ offset: z.coerce.number().int().min(0).max(10000000).default(0) }), req.query);+ res.json(await service.previewAgentStorage(validateRequest(service.agentStorageFilterSchema, req.body), { offset }));+}));+router.post('/cos/storage/run', asyncHandler(async (req, res) => {+ const service = await import('../services/cosAgentStorage.js');+ const input = validateRequest(z.object({ token: z.string().uuid(), confirmation: z.literal('PURGE RAW RECORDINGS').optional() }).strict(), req.body);+ res.json(await service.startAgentStorage(input));+}));+router.post('/cos/storage/cancel', asyncHandler(async (req, res) => {+ const service = await import('../services/cosAgentStorage.js');+ res.json(await service.cancelAgentStorage());+}));+const recordingLocator = z.object({ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), id: z.string().regex(/^[a-zA-Z0-9_-]+$/) });+router.put('/cos/storage/pin', asyncHandler(async (req, res) => {+ const service = await import('../services/cosAgentStorage.js');+ res.json(await service.pinAgentRecording(validateRequest(recordingLocator.extend({ pinned: z.boolean() }).strict(), req.body)));+}));+router.get('/cos/storage/recording/:date/:id', asyncHandler(async (req, res) => {+ const service = await import('../services/cosAgentStorage.js');+ const { date, id } = validateRequest(recordingLocator, req.params);+ const artifact = await service.getAgentRecordingDownload(date, id);+ res.download(artifact.path, artifact.name);+}));+// GET /api/data — overview of all data categoriesrouter.get('/', asyncHandler(async (req, res) => {const overview = await getDataOverview();@@ -26,7 +62,8 @@ router.get('/backups', asyncHandler(async (req, res) => {// GET /api/data/:category — detailed breakdown of a categoryrouter.get('/:category', asyncHandler(async (req, res) => {- const detail = await getCategoryDetail(req.params.category);+ const { measure } = validateRequest(z.object({ measure: z.literal('1').optional() }), req.query);+ const detail = await getCategoryDetail(req.params.category, { measure: measure === '1' });if (!detail) throw new ServerError('Category not found', { status: 404, code: 'NOT_FOUND' });res.json(detail);}));diff --git a/server/services/cos.js b/server/services/cos.jsindex 5d49400041..397e943621 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -101,7 +101,6 @@ import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner } from './cosTasimport { retryTasksResolvedByInvestigation } from './investigationRetry.js';import { notifyIfPrLeftOrphaned } from './orphanedPrNotifier.js';-const AGENT_ARCHIVE_RETENTION_DAYS = 90;const RESUME_DEQUEUE_DELAY_MS = 500;// CD recovery normally resolves in <100ms; hold start() at most this long so// a stuck recovery doesn't block daemon boot indefinitely.@@ -121,7 +120,7 @@ const RECENT_COMPLETION_GRACE_MS = 60_000;let daemonStartPromise = null;// Internal imports for functions used in this module-import { pruneOldAgentArchives, loadAgentIndex } from './cosAgentIndex.js';+import { loadAgentIndex } from './cosAgentIndex.js';import { archiveStaleAgents as _archiveStaleAgents } from './cosAgentArchive.js';import { initializeAgentFeedback } from './cosAgentFeedback.js';import { resolveAgentProviderAndModel } from './agentProviderResolution.js';@@ -417,10 +416,15 @@ async function runStart() {emitLog('info', `📦 Startup: archived ${archived} stale agent(s) from state`);}- // Prune agent archives older than 90 days- await pruneOldAgentArchives(AGENT_ARCHIVE_RETENTION_DAYS).catch(err =>- console.warn(`⚠️ pruneOldAgentArchives failed: ${err?.message || err}`)- );+ // Lossless raw-recording maintenance; historical records never expire.+ scheduleEvent({+ id: 'cos-recording-maintenance', type: 'interval', intervalMs: 3600000,+ handler: async () => {+ const { runAutomaticAgentStorage } = await import('./cosAgentStorage.js');+ await runAutomaticAgentStorage();+ },+ metadata: { description: 'Compress old CoS raw recordings; retain run history' }+ });// Health check + orphan cleanup (15 min)scheduleEvent({@@ -611,6 +615,7 @@ export async function stop() {// Cancel all scheduled eventscancelEvent('cos-health-check');+ cancelEvent('cos-recording-maintenance');cancelEvent('cos-performance-summary');cancelEvent('cos-learning-insights');cancelEvent('cos-rehabilitation-check');diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex c011b4fd63..644c94bc3d 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -2503,6 +2503,7 @@ describe('pending-merge sweep — own timer, not the evaluation cadence (#3630)'it('cancels the timer with the other CoS jobs on stop()', () => {const stopFn = extractFnBody(COS_SRC, COS_SRC.indexOf('export async function stop'));expect(stopFn).toMatch(/cancelEvent\('cos-health-check'\)/);+ expect(stopFn).toMatch(/cancelEvent\('cos-recording-maintenance'\)/);expect(stopFn).toMatch(/cancelEvent\('cos-pending-merge-sweep'\)/);});diff --git a/server/services/cosAgentIndex.js b/server/services/cosAgentIndex.jsindex 42e1391d2d..6d5cf13daf 100644--- a/server/services/cosAgentIndex.js+++ b/server/services/cosAgentIndex.js@@ -249,37 +249,11 @@ async function migrateAgentsToDateBuckets() {return index;}-// Prune agent archive date buckets older than retentionDays (default 90).-// Removes directories + their index entries. Runs after migration on startup.-export async function pruneOldAgentArchives(retentionDays = 90) {- const idx = await loadAgentIndex();- if (!idx || idx.size === 0) return;-- const cutoff = new Date();- cutoff.setDate(cutoff.getDate() - retentionDays);- const cutoffStr = cutoff.toISOString().slice(0, 10);-- const dateDirPattern = /^\d{4}-\d{2}-\d{2}$/;- const entries = await readdir(AGENTS_DIR, { withFileTypes: true }).catch(() => []);- const oldDates = entries- .filter(e => e.isDirectory() && dateDirPattern.test(e.name) && e.name < cutoffStr)- .map(e => e.name);-- if (oldDates.length === 0) return;-- for (const dateStr of oldDates) {- await rm(join(AGENTS_DIR, dateStr), { recursive: true }).catch(() => {});- }-- // Remove index entries for all old dates in a single pass- const oldDateSet = new Set(oldDates);- let pruned = 0;- for (const [agentId, date] of idx.entries()) {- if (oldDateSet.has(date)) { idx.delete(agentId); pruned++; }- }-- await saveAgentIndex();- console.log(`🗑️ Pruned ${pruned} archived agents older than ${retentionDays} days (${oldDates.length} date buckets)`);+// Compatibility entry point for older callers. Whole-run age deletion is retired:+// metadata, feedback and parsed output are permanent. Raw recording maintenance+// is handled separately by cosAgentStorage, without dropping history indexes.+export async function pruneOldAgentArchives() {+ return { pruned: 0 };}// Get available agent date buckets with counts, sorted descendingdiff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.jsindex 718a2e23eb..71ac5e604c 100644--- a/server/services/cosAgentLifecycle.js+++ b/server/services/cosAgentLifecycle.js@@ -572,14 +572,13 @@ export async function getAgent(agentId, { limit = AGENT_OUTPUT_TAIL_LINES, maxBy// Used by the AgentCard UI to let the user inspect what was pasted into the// TUI / sent to the CLI so the prompt can be iterated on.export async function getAgentPrompt(agentId) {- const state = await loadState();- const agent = state.agents[agentId];+ const agent = await getAgentRecord(agentId);if (!agent) throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });- const agentDir = getAgentDir(agentId, agent.archiveDate);- const promptPath = join(agentDir, 'prompt.txt');+ const date = agent.archiveDate || (agent.status === 'completed' ? agent.completedAt?.slice(0, 10) : null);+ const promptPath = join(getAgentDir(agentId, date), 'prompt.txt');if (!existsSync(promptPath)) throw new ServerError('Prompt file not found', { status: 404, code: 'NOT_FOUND' });const prompt = await readFile(promptPath, 'utf8');- return { prompt, bytes: prompt.length };+ return { prompt, bytes: Buffer.byteLength(prompt) };}// Terminate an agent (will be handled by spawner)diff --git a/server/services/cosAgentLifecycle.test.js b/server/services/cosAgentLifecycle.test.jsindex 3d1cfe813d..06af3d085f 100644--- a/server/services/cosAgentLifecycle.test.js+++ b/server/services/cosAgentLifecycle.test.js@@ -58,10 +58,11 @@ vi.mock('./cosRunnerClient.js', () => ({getActiveAgentsFromRunner: vi.fn().mockResolvedValue([]),}));-import { getAgent, createAgentOutputBatcher, completeAgent, updateAgent, registerAgent, cleanupZombieAgents, filterLiveAgentIds, readAgentRecordOrUnreadable, AGENT_RECORD_UNREADABLE, AGENT_OUTPUT_TAIL_LINES } from './cosAgentLifecycle.js';+import { getAgent, getAgentPrompt, createAgentOutputBatcher, completeAgent, updateAgent, registerAgent, cleanupZombieAgents, filterLiveAgentIds, readAgentRecordOrUnreadable, AGENT_RECORD_UNREADABLE, AGENT_OUTPUT_TAIL_LINES } from './cosAgentLifecycle.js';import { saveState, loadState, readAgentsStateForSafetyCheck } from './cosState.js';import { recordDomainUsage } from './domainUsage.js';import { cosEvents } from './cosEvents.js';+import { loadAgentIndex } from './cosAgentIndex.js';import { getActiveAgentsFromRunner } from './cosRunnerClient.js';import { activeAgents, runnerAgents } from './agentState.js';@@ -79,6 +80,17 @@ describe('cosAgentLifecycle', () => {await rm(mockCosState.agentsDir, { recursive: true, force: true });});+ it('keeps archived prompts readable after state eviction, with UTF-8 byte counts', async () => {+ const id = 'agent-archived-prompt';+ const date = '2026-01-01';+ const dir = join(mockCosState.agentsDir, date, id);+ await mkdir(dir, { recursive: true });+ await writeFile(join(dir, 'metadata.json'), JSON.stringify({ id, status: 'completed', completedAt: `${date}T12:00:00Z` }));+ await writeFile(join(dir, 'prompt.txt'), 'Example café');+ (await loadAgentIndex()).set(id, date);+ await expect(getAgentPrompt(id)).resolves.toEqual({ prompt: 'Example café', bytes: Buffer.byteLength('Example café') });+ });+it('hydrates paused agents with full preserved output from output.txt', async () => {const agentId = 'agent-paused';const pausedAt = '2026-05-25T12:00:00.000Z';diff --git a/server/services/cosAgentStorage.js b/server/services/cosAgentStorage.jsnew file mode 100644index 0000000000..c030df6bb0--- /dev/null+++ b/server/services/cosAgentStorage.js@@ -0,0 +1,300 @@+/** Machine-local maintenance of raw terminal recordings. History is never deleted. */+import { createReadStream } from 'node:fs';+import { lstat, readdir, readFile, rename } from 'node:fs/promises';+import { join } from 'node:path';+import { randomUUID, createHash } from 'node:crypto';+import { createGzip, createGunzip } from 'node:zlib';+import { pipeline } from 'node:stream/promises';+import { Writable, Transform } from 'node:stream';+import { z } from 'zod';+import { atomicWrite, createWriteStreamGuarded, unlinkGuarded } from '../lib/fileUtils.js';+import { ServerError } from '../lib/errorHandler.js';+import { AGENTS_DIR, loadConfig, saveConfig, withConfigLock, withStateLock, readAgentsStateForSafetyCheck } from './cosState.js';+import { cosEvents } from './cosEvents.js';++const DAY = 86400000;+const SAFE_ID = /^[a-zA-Z0-9_-]+$/;+const DATE = /^\d{4}-\d{2}-\d{2}$/;+const TEMP_RECORDING = /^raw\.txt\.gz\.[0-9a-f-]{36}\.tmp$/;+const MANIFEST = 'raw-storage.json';+export const agentStoragePolicySchema = z.object({+ autoCompress: z.boolean().default(true),+ compressAfterDays: z.number().int().min(1).max(36500).default(7),+ autoPurge: z.boolean().default(false),+ purgeAfterDays: z.number().int().min(7).max(36500).default(90),+}).strict();+export const agentStorageFilterSchema = z.object({+ action: z.enum(['compress', 'purge']).default('compress'),+ olderThanDays: z.number().int().min(1).max(36500).default(7),+ model: z.string().max(300).default(''),+ outcome: z.enum(['all', 'success', 'failure']).default('all'),+}).strict();+const previews = new Map();+let job = null;+let controller = null;+const changed = () => cosEvents.emit('storage:changed', {});+const missing = err => { if (err.code === 'ENOENT') return null; throw err; };+const info = path => lstat(path).catch(missing);+const fingerprint = st => st ? `${st.dev}:${st.ino}:${st.size}:${st.mtimeMs}:${st.ctimeMs}` : null;+const json = async path => {+ const st = await lstat(path);+ if (!st.isFile()) throw new Error('Non-regular metadata file');+ return JSON.parse(await readFile(path, 'utf8'));+};+async function manifest(dir) {+ const value = await json(join(dir, MANIFEST)).catch(missing);+ if (value === null) return { version: 1, pinned: false };+ if (value.version !== 1 || typeof value.pinned !== 'boolean') throw new Error('Recording manifest is invalid');+ return value;+}+function location(date, id) {+ if (!DATE.test(date) || !SAFE_ID.test(id)) throw new ServerError('Invalid run locator', { status: 400, code: 'VALIDATION_ERROR' });+ return join(AGENTS_DIR, date, id);+}+async function safeDirectory(date, id) {+ const dir = location(date, id);+ for (const path of [AGENTS_DIR, join(AGENTS_DIR, date), dir]) {+ if (!(await info(path))?.isDirectory()) throw new Error('Recording directory unavailable');+ }+ return dir;+}+async function inspect(date, id, filter, now, liveState) {+ const dir = await safeDirectory(date, id);+ const record = await json(join(dir, 'metadata.json'));+ const storage = await manifest(dir);+ const raw = await info(join(dir, 'raw.txt'));+ const gzip = await info(join(dir, 'raw.txt.gz'));+ const output = await info(join(dir, 'output.txt'));+ const prompt = await info(join(dir, 'prompt.txt'));+ const metadataFile = await info(join(dir, 'metadata.json'));+ const metadata = record.metadata || {};+ const model = String(metadata.model || metadata.modelName || record.model || 'Unknown');+ const success = record.result?.success === true;+ const matches = (!filter.model || model === filter.model) && (filter.outcome === 'all' || (filter.outcome === 'success') === success);+ const completed = Date.parse(record.completedAt);+ const state = liveState || await readAgentsStateForSafetyCheck();+ let reason = null;+ if (!state.trusted || !state.agents) reason = 'Live state unavailable';+ else if (state.agents[id]) reason = 'Still in live state';+ else if (Object.values(state.agents).some(agent => JSON.stringify(agent.metadata || {}).includes(id))) reason = 'Referenced by a live run';+ else if (record.id !== id || record.status !== 'completed' || !Number.isFinite(completed)) reason = 'Not a finalized run';+ else if (storage.pinned) reason = 'Pinned';+ else if (metadata.pipeline || metadata.pipelineId || metadata.resumeSessionId || metadata.resumeFromAgentId || metadata.resumedFromAgentId || record.result?.worktreePreserved) reason = 'Pipeline or resumable run';+ else if (completed > now - Math.max(1, filter.olderThanDays) * DAY) reason = 'Too recent';+ else if ([raw, gzip, output].some(st => st && !st.isFile())) reason = 'Non-regular artifact';+ else if ([raw, gzip, output].some(st => st && st.mtimeMs > now - DAY)) reason = 'Recently modified';+ else if (filter.action === 'compress' && raw && storage.compressionSkippedFingerprint === fingerprint(raw)) reason = 'Compression would not save space';+ else if (filter.action === 'compress' && !raw) reason = 'No uncompressed recording';+ else if (filter.action === 'purge' && !raw && !gzip) reason = 'No recording';+ else if (filter.action === 'purge' && (!output?.size || typeof metadata.taskSummary !== 'string' || !metadata.taskSummary.trim())) reason = 'Missing retained output or summary';+ // Preserved worktrees carry potential resumable work, even after state eviction.+ const worktree = metadata.worktreePath || metadata.worktreeInfo?.path || (metadata.isWorktree && metadata.workspacePath);+ if (!reason && worktree && await info(worktree)) reason = 'Preserved worktree';+ return { dir, storage, raw, gzip, record, matches, row: {+ date, id, model, outcome: success ? 'success' : 'failure', completedAt: record.completedAt,+ retainedBytes: { metadata: metadataFile?.size || 0, output: output?.size || 0, prompt: prompt?.size || 0 },+ bytes: (raw?.size || 0) + (gzip?.size || 0), pinned: storage.pinned,+ state: raw ? 'plain' : gzip ? 'compressed' : storage.disposition === 'purged' ? 'purged' : 'absent',+ eligible: matches && !reason, reason: !matches ? 'Outside filter' : reason,+ fingerprint: `${fingerprint(raw)}|${fingerprint(gzip)}`,+ } };+}+async function* locators() {+ const dates = await readdir(AGENTS_DIR, { withFileTypes: true }).catch(err => { if (err.code === 'ENOENT') return []; throw err; });+ for (const date of dates.sort((a, b) => a.name.localeCompare(b.name))) {+ if (!date.isDirectory() || !DATE.test(date.name)) continue;+ for (const entry of (await readdir(join(AGENTS_DIR, date.name), { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {+ if (entry.isDirectory() && SAFE_ID.test(entry.name)) yield { date: date.name, id: entry.name };+ }+ }+}+export async function getAgentStorageStatus() {+ const config = await loadConfig();+ return { policy: agentStoragePolicySchema.parse(config.agentStorage || {}), job: job ? { ...job } : config.lastAgentStorageJob || null };+}+export async function updateAgentStoragePolicy(input) {+ const policy = agentStoragePolicySchema.parse(input);+ await withConfigLock(async () => {+ const current = await loadConfig();+ await saveConfig({ ...current, agentStorage: policy });+ });+ changed();+ // Reconcile immediately; the same gates are read again between auto-job files.+ void runAutomaticAgentStorage().catch(() => console.error('❌ CoS recording maintenance could not start'));+ return getAgentStorageStatus();+}+export async function previewAgentStorage(input, { limit = 1000, offset = 0 } = {}) {+ const filter = agentStorageFilterSchema.parse(input);+ const now = Date.now();+ const liveState = await readAgentsStateForSafetyCheck();+ const candidates = [];+ const models = new Set();+ let matching = 0;+ const rows = [];+ const reasons = {};+ const totals = { recordingBytes: 0, eligibleBytes: 0, eligibleRuns: 0, scanned: 0, unreadable: 0, metadataBytes: 0, outputBytes: 0, promptBytes: 0 };+ for await (const { date, id } of locators()) {+ const entry = await inspect(date, id, filter, now, liveState).catch(() => null);+ totals.scanned++;+ if (!entry) { totals.unreadable++; continue; }+ const row = entry.row;+ models.add(row.model);+ if (!entry.matches) continue;+ totals.recordingBytes += row.bytes;+ totals.metadataBytes += row.retainedBytes.metadata;+ totals.outputBytes += row.retainedBytes.output;+ totals.promptBytes += row.retainedBytes.prompt;+ if (row.eligible && candidates.length < limit) {+ candidates.push(row);+ totals.eligibleBytes += row.bytes;+ totals.eligibleRuns++;+ } else {+ const reason = row.reason || 'Next batch';+ reasons[reason] = (reasons[reason] || 0) + 1;+ }+ if (matching++ >= offset && rows.length < 25) rows.push(row);+ }+ for (const [key, value] of previews) if (now - value.createdAt > 15 * 60000) previews.delete(key);+ while (previews.size >= 5) previews.delete(previews.keys().next().value);+ const token = randomUUID();+ previews.set(token, { createdAt: now, filter, candidates });+ return { token, filter, totals, reasons, rows, models: [...models].sort(), matching, offset, batchLimit: limit };+}+async function hashStream(stream, signal) {+ const hash = createHash('sha256');+ await pipeline(stream, new Writable({ write(chunk, encoding, done) { hash.update(chunk); done(); } }), { signal });+ return hash.digest('hex');+}+async function compress(entry, signal, revalidate) {+ const source = join(entry.dir, 'raw.txt');+ const target = `${source}.gz`;+ const temporary = `${target}.${randomUUID()}.tmp`;+ // Recover only our reserved, old temporary files after an interrupted process.+ for (const name of await readdir(entry.dir)) {+ if (!TEMP_RECORDING.test(name)) continue;+ const path = join(entry.dir, name);+ const st = await info(path);+ if (st?.isFile() && st.mtimeMs < Date.now() - DAY) await unlinkGuarded(path);+ }+ const hash = createHash('sha256');+ const tap = new Transform({ transform(chunk, encoding, done) { hash.update(chunk); done(null, chunk); } });+ // The old plain file remains authoritative until a verified gzip is published.+ return (async () => {+ await pipeline(createReadStream(source), tap, createGzip(), await createWriteStreamGuarded(temporary, { flags: 'wx' }), { signal });+ const expected = hash.digest('hex');+ const gunzip = createGunzip();+ const verifying = pipeline(createReadStream(temporary), gunzip, { signal });+ const [actual] = await Promise.all([hashStream(gunzip, signal), verifying]);+ if (actual !== expected) throw new Error('Recording verification failed');+ return withStateLock(async () => {+ const fresh = await revalidate();+ if (!fresh || signal.aborted) return 0;+ const zipped = await info(temporary);+ if (zipped.size >= fresh.raw.size) {+ await atomicWrite(join(entry.dir, MANIFEST), { ...fresh.storage, compressionSkippedFingerprint: fingerprint(fresh.raw) });+ return 0;+ }+ await rename(temporary, target);+ await atomicWrite(join(entry.dir, MANIFEST), { ...fresh.storage, disposition: 'compressed', sha256: expected, originalBytes: fresh.raw.size, compressedAt: new Date().toISOString() });+ await unlinkGuarded(source);+ return Math.max(0, fresh.raw.size + (fresh.gzip?.size || 0) - zipped.size);+ });+ })().finally(() => unlinkGuarded(temporary).catch(err => { if (err.code !== 'ENOENT') throw err; }));+}+async function purge(entry, signal, revalidate) {+ return withStateLock(async () => {+ const fresh = await revalidate();+ if (!fresh || signal.aborted) return 0;+ // Persist intent before unlink. A crash leaves an explicit disposition and+ // surviving bytes visible; retries remove only the same allowlisted files.+ await atomicWrite(join(entry.dir, MANIFEST), { ...fresh.storage, disposition: 'purged', purgedAt: new Date().toISOString(), removedFiles: ['raw.txt', 'raw.txt.gz'] });+ let reclaimed = 0;+ return (async () => {+ for (const [name, st] of [['raw.txt', fresh.raw], ['raw.txt.gz', fresh.gzip]]) {+ if (st) { await unlinkGuarded(join(entry.dir, name)); reclaimed += st.size; }+ }+ return reclaimed;+ })().catch(err => { err.reclaimedBytes = reclaimed; throw err; });+ });+}+export async function startAgentStorage({ token, confirmation }, { automatic = false } = {}) {+ if (controller) throw new ServerError('Recording maintenance already running', { status: 409, code: 'CONFLICT' });+ const preview = previews.get(token);+ if (!preview || Date.now() - preview.createdAt > 15 * 60000) throw new ServerError('Preview expired; preview again', { status: 409, code: 'STALE_PREVIEW' });+ if (preview.filter.action === 'purge' && !automatic && confirmation !== 'PURGE RAW RECORDINGS') throw new ServerError('Confirm raw recording deletion', { status: 400, code: 'VALIDATION_ERROR' });+ previews.delete(token);+ controller = new AbortController();+ job = { id: randomUUID(), action: preview.filter.action, state: 'running', total: preview.candidates.length, processed: 0, skipped: 0, failed: 0, reclaimedBytes: 0, startedAt: new Date().toISOString() };+ const signal = controller.signal;+ changed();+ void (async () => {+ for (const candidate of preview.candidates) {+ if (signal.aborted) break;+ const revalidate = async () => {+ if (automatic) {+ const { policy } = await getAgentStorageStatus();+ if (!(preview.filter.action === 'compress' ? policy.autoCompress : policy.autoPurge)) return null;+ if ((preview.filter.action === 'compress' ? policy.compressAfterDays : policy.purgeAfterDays) !== preview.filter.olderThanDays) return null;+ }+ const fresh = await inspect(candidate.date, candidate.id, preview.filter, preview.createdAt);+ return fresh.row.eligible && fresh.row.fingerprint === candidate.fingerprint ? fresh : null;+ };+ await (async () => {+ const entry = await revalidate();+ if (!entry) { job.skipped++; return; }+ const reclaimed = await (preview.filter.action === 'compress' ? compress : purge)(entry, signal, revalidate);+ job.reclaimedBytes += reclaimed;+ if (!reclaimed) job.skipped++;+ })().catch(err => {+ job.reclaimedBytes += err.reclaimedBytes || 0;+ if (!signal.aborted) job.failed++;+ });+ job.processed++;+ changed();+ }+ job.state = signal.aborted ? 'cancelled' : job.failed ? 'completed-with-errors' : 'completed';+ })().catch(() => { job.state = 'failed'; }).finally(async () => {+ job.finishedAt = new Date().toISOString();+ // Small latest-operation audit lives in the existing machine-local config.+ await withConfigLock(async () => {+ const current = await loadConfig();+ await saveConfig({ ...current, lastAgentStorageJob: { ...job } });+ }).catch(() => { job.state = 'audit-write-failed'; });+ controller = null;+ changed();+ });+ return getAgentStorageStatus();+}+export function cancelAgentStorage() {+ controller?.abort();+ return getAgentStorageStatus();+}+export async function pinAgentRecording({ date, id, pinned }) {+ await withStateLock(async () => {+ const dir = await safeDirectory(date, id);+ const value = await manifest(dir);+ await atomicWrite(join(dir, MANIFEST), { ...value, pinned });+ });+ changed();+ return { date, id, pinned };+}+export async function runAutomaticAgentStorage() {+ if (controller) return;+ const { policy } = await getAgentStorageStatus();+ const action = policy.autoPurge ? 'purge' : 'compress';+ if (!policy.autoPurge && !policy.autoCompress) return;+ const preview = await previewAgentStorage({ action, olderThanDays: action === 'purge' ? policy.purgeAfterDays : policy.compressAfterDays }, { limit: 25 });+ if (preview.totals.eligibleRuns) return startAgentStorage({ token: preview.token }, { automatic: true });+ if (policy.autoPurge && policy.autoCompress) {+ const compression = await previewAgentStorage({ action: 'compress', olderThanDays: policy.compressAfterDays }, { limit: 25 });+ if (compression.totals.eligibleRuns) return startAgentStorage({ token: compression.token }, { automatic: true });+ }+}++export async function getAgentRecordingDownload(date, id) {+ const dir = await safeDirectory(date, id);+ for (const name of ['raw.txt', 'raw.txt.gz']) {+ if ((await info(join(dir, name)))?.isFile()) return { path: join(dir, name), name };+ }+ throw new ServerError('Raw recording was purged or was never captured; parsed output remains in run history', { status: 404, code: 'NOT_FOUND' });+}diff --git a/server/services/cosAgentStorage.test.js b/server/services/cosAgentStorage.test.jsnew file mode 100644index 0000000000..60406021c0--- /dev/null+++ b/server/services/cosAgentStorage.test.js@@ -0,0 +1,157 @@+import { afterAll, beforeEach, expect, it, vi } from 'vitest';+import { mkdir, writeFile, readFile, rm, utimes, readdir } from 'node:fs/promises';+import { join } from 'node:path';+import { gunzipSync, gzipSync } from 'node:zlib';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+const fixture = await vi.hoisted(async () => {+ const { mkdtemp } = await import('node:fs/promises');+ const { tmpdir } = await import('node:os');+ const { join } = await import('node:path');+ return { root: await mkdtemp(join(tmpdir(), 'cos-storage-')), state: {}, config: {}, trusted: true, failWrite: false, corruptVerification: false, onWrite: null };+});+vi.mock('./cosState.js', () => ({+ AGENTS_DIR: fixture.root,+ readAgentsStateForSafetyCheck: async () => ({ trusted: fixture.trusted, agents: fixture.state }),+ loadConfig: async () => fixture.config,+ saveConfig: async value => { fixture.config = value; },+ withConfigLock: createFileWriteQueue(), withStateLock: createFileWriteQueue(),+}));+vi.mock('node:fs', async importOriginal => {+ const actual = await importOriginal();+ const { Readable } = await import('node:stream');+ return { ...actual, createReadStream: (path, ...args) => fixture.corruptVerification && String(path).endsWith('.tmp')+ ? Readable.from('invalid gzip') : actual.createReadStream(path, ...args) };+});+vi.mock('../lib/fileUtils.js', async importOriginal => {+ const actual = await importOriginal();+ return { ...actual, createWriteStreamGuarded: async (...args) => {+ if (fixture.failWrite) throw new Error('disk full');+ await fixture.onWrite?.();+ return actual.createWriteStreamGuarded(...args);+ } };+});+vi.mock('./codexSummaryRepair.js', () => ({ repairCodexTaskSummary: async () => null }));+const storage = await import('./cosAgentStorage.js');+const { pruneOldAgentArchives } = await import('./cosAgentIndex.js');+const { default: routes } = await import('../routes/dataManager.js');+const app = express();+app.use(express.json()); app.use('/api/data', routes); app.use(errorMiddleware);+const date = '2001-01-01';+const source = 'Example terminal redraw\n'.repeat(4000);+const runDir = id => join(fixture.root, date, id);+async function seed(id = 'agent-example', metadata = {}) {+ const dir = runDir(id);+ await mkdir(dir, { recursive: true });+ await writeFile(join(dir, 'metadata.json'), JSON.stringify({ id, status: 'completed', completedAt: `${date}T12:00:00Z`, result: { success: true, cost: 0.01 }, metadata: { model: 'example-model', taskSummary: 'Fixed an example defect', ...metadata } }));+ for (const [name, text] of [['raw.txt', source], ['output.txt', 'Retained useful output'], ['prompt.txt', 'Example instructions'], ['evidence.json', '{"keep":true}']]) {+ await writeFile(join(dir, name), text);+ await utimes(join(dir, name), new Date(date), new Date(date));+ }+ return dir;+}+async function settled() {+ await vi.waitFor(async () => expect((await storage.getAgentStorageStatus()).job?.finishedAt).toBeTruthy());+ // Completion's config audit is part of the job boundary.+ await vi.waitFor(() => expect(fixture.config.lastAgentStorageJob).toBeTruthy());+ return (await storage.getAgentStorageStatus()).job;+}+beforeEach(async () => {+ await rm(fixture.root, { recursive: true, force: true }); await mkdir(fixture.root);+ fixture.state = {}; fixture.config = {}; fixture.trusted = true;+ fixture.failWrite = false; fixture.corruptVerification = false; fixture.onWrite = null;+});+afterAll(() => rm(fixture.root, { recursive: true, force: true }));++it('compresses through HTTP, verifies bytes, serves the gzip, and preserves old history and unknown evidence', async () => {+ const dir = await seed();+ const before = await readFile(join(dir, 'metadata.json'), 'utf8');+ await pruneOldAgentArchives(1);+ const preview = await request(app).post('/api/data/cos/storage/preview').send({ action: 'compress' });+ expect(preview.status).toBe(200);+ expect(preview.body.totals.eligibleRuns).toBe(1);+ const started = await request(app).post('/api/data/cos/storage/run').send({ token: preview.body.token });+ expect(started.status).toBe(200);+ const result = await settled();+ expect(result.state).toBe('completed');+ expect(result.reclaimedBytes).toBeGreaterThan(0);+ expect(gunzipSync(await readFile(join(dir, 'raw.txt.gz'))).toString()).toBe(source);+ expect(await readFile(join(dir, 'metadata.json'), 'utf8')).toBe(before);+ expect(await readFile(join(dir, 'output.txt'), 'utf8')).toBe('Retained useful output');+ expect(await readFile(join(dir, 'evidence.json'), 'utf8')).toBe('{"keep":true}');+ const download = await storage.getAgentRecordingDownload(date, 'agent-example');+ expect(download.name).toBe('raw.txt.gz');+ expect((await storage.previewAgentStorage({ action: 'compress' })).totals.eligibleRuns).toBe(0);+});++it('requires purge confirmation and retained evidence, keeps metadata and exposes the purged state', async () => {+ const dir = await seed(); await seed('agent-no-summary', { taskSummary: '' });+ const preview = await storage.previewAgentStorage({ action: 'purge' });+ expect(preview.totals.eligibleRuns).toBe(1);+ expect((await request(app).post('/api/data/cos/storage/run').send({ token: preview.token })).status).toBe(400);+ await storage.startAgentStorage({ token: preview.token, confirmation: 'PURGE RAW RECORDINGS' });+ expect((await settled()).reclaimedBytes).toBe(Buffer.byteLength(source));+ expect(await readFile(join(dir, 'metadata.json'), 'utf8')).toContain('Fixed an example defect');+ expect(await readFile(join(dir, 'prompt.txt'), 'utf8')).toBe('Example instructions');+ expect((await storage.previewAgentStorage({ action: 'purge' })).rows.find(row => row.id === 'agent-example').state).toBe('purged');+ await expect(storage.getAgentRecordingDownload(date, 'agent-example')).rejects.toMatchObject({ status: 404 });+});++it('revalidates stale previews, pins during compression, and fails closed on unreadable live state', async () => {+ const dir = await seed();+ const stale = await storage.previewAgentStorage({});+ fixture.state = { 'agent-example': { status: 'paused' } };+ await storage.startAgentStorage({ token: stale.token });+ expect((await settled()).skipped).toBe(1);+ fixture.state = {}; fixture.config.lastAgentStorageJob = null;+ const preview = await storage.previewAgentStorage({});+ fixture.onWrite = () => storage.pinAgentRecording({ date, id: 'agent-example', pinned: true });+ await storage.startAgentStorage({ token: preview.token });+ expect((await settled()).skipped).toBe(1);+ expect(await readFile(join(dir, 'raw.txt'), 'utf8')).toBe(source);+ fixture.trusted = false;+ expect((await storage.previewAgentStorage({})).totals.eligibleRuns).toBe(0);+});++it.each(['failWrite', 'corruptVerification'])('keeps original recordings and removes temporary output on %s', async failure => {+ const dir = await seed(); fixture[failure] = true;+ const preview = await storage.previewAgentStorage({});+ await storage.startAgentStorage({ token: preview.token });+ expect((await settled()).failed).toBe(1);+ expect(await readFile(join(dir, 'raw.txt'), 'utf8')).toBe(source);+ expect((await readdir(dir)).filter(name => name.endsWith('.tmp'))).toEqual([]);+});++it('recovers a published gzip with its plain source still present and keeps compression defaults non-destructive', async () => {+ const dir = await seed();+ await writeFile(join(dir, 'raw.txt.gz'), gzipSync(source));+ await utimes(join(dir, 'raw.txt.gz'), new Date(date), new Date(date));+ const preview = await storage.previewAgentStorage({});+ await storage.startAgentStorage({ token: preview.token });+ expect((await settled()).state).toBe('completed');+ expect(gunzipSync(await readFile(join(dir, 'raw.txt.gz'))).toString()).toBe(source);+ expect((await storage.getAgentStorageStatus()).policy).toMatchObject({ autoCompress: true, autoPurge: false });+});++it('cancels safely before publication and protects preserved worktrees', async () => {+ const dir = await seed();+ await seed('agent-resumable', { isWorktree: true, workspacePath: fixture.root });+ const preview = await storage.previewAgentStorage({});+ expect(preview.totals.eligibleRuns).toBe(1);+ fixture.onWrite = () => storage.cancelAgentStorage();+ await storage.startAgentStorage({ token: preview.token });+ expect((await settled()).state).toBe('cancelled');+ expect(await readFile(join(dir, 'raw.txt'), 'utf8')).toBe(source);+});++it('rechecks opt-in policy before automatic publication and does no deletion by default', async () => {+ const dir = await seed();+ fixture.config.agentStorage = { autoCompress: true, compressAfterDays: 7, autoPurge: false, purgeAfterDays: 90 };+ fixture.onWrite = () => { fixture.config.agentStorage.autoCompress = false; };+ await storage.runAutomaticAgentStorage();+ expect((await settled()).skipped).toBe(1);+ expect(await readFile(join(dir, 'raw.txt'), 'utf8')).toBe(source);+ expect(await readFile(join(dir, 'metadata.json'), 'utf8')).toContain('example-model');+});diff --git a/server/services/dataManager.js b/server/services/dataManager.jsindex 7a49597c9d..2276120d7b 100644--- a/server/services/dataManager.js+++ b/server/services/dataManager.js@@ -1,4 +1,4 @@-import { readdir, stat, lstat, statfs } from 'fs/promises';+import { readdir, opendir, stat, lstat, statfs } from 'fs/promises';import { join, relative, resolve, isAbsolute } from 'path';import { existsSync } from 'fs';import { execFile } from '../lib/childProcess.js';@@ -225,6 +225,20 @@ export async function resolveCategoryBusy(categoryKey) {// Validate category key contains only safe charactersconst SAFE_NAME = /^[a-z0-9_-]+$/;+// Walk one directory at a time: never buffer an entire tree's path list in a+// child-process stdout pipe. Failed scans stay unknown, distinct from empty.+async function countFiles(dirPath, deadline) {+ if (Date.now() >= deadline) throw new Error('File count timed out');+ let count = 0;+ const directory = await opendir(dirPath);+ for await (const entry of directory) {+ if (Date.now() >= deadline) throw new Error('File count timed out');+ if (entry.isDirectory()) count += await countFiles(join(dirPath, entry.name), deadline);+ else if (entry.isFile()) count++;+ }+ return count;+}+async function getDirSizeAndCount(dirPath, { strict = false } = {}) {if (strict) {const present = await stat(dirPath).then(@@ -245,19 +259,17 @@ async function getDirSizeAndCount(dirPath, { strict = false } = {}) {if (strict) throw err;return '0';}),- execFileAsync('find', [dirPath, '-type', 'f'], { timeout: 30000 })- .then(r => r.stdout.trim().split('\n').filter(Boolean).length)- .catch((err) => {- if (strict) throw err;- return 0;- })+ countFiles(dirPath, Date.now() + 30000).catch((err) => {+ if (strict) throw err;+ return null;+ })]);const kb = typeof duOut === 'string' ? parseInt(duOut.split('\t')[0], 10) : NaN;if (!Number.isFinite(kb) || kb < 0) {if (strict) throw new Error(`Could not parse directory size for ${dirPath}`);- return { size: 0, fileCount: typeof findOut === 'number' ? findOut : 0 };+ return { size: 0, fileCount: findOut };}- const fileCount = typeof findOut === 'number' ? findOut : (parseInt(findOut, 10) || 0);+ const fileCount = findOut;return { size: kb * 1024, fileCount };}@@ -304,7 +316,7 @@ export async function getDataOverview({ strict = false } = {}) {};}-export async function getCategoryDetail(categoryKey) {+export async function getCategoryDetail(categoryKey, { measure = false } = {}) {if (!SAFE_NAME.test(categoryKey)) return null;const dirPath = join(DATA_DIR, categoryKey);if (!existsSync(dirPath)) return null;@@ -333,7 +345,11 @@ export async function getCategoryDetail(categoryKey) {const totalSize = items.reduce((sum, item) => sum + item.size, 0);const busy = await resolveCategoryBusy(categoryKey);- return { key: categoryKey, ...categoryMeta(categoryKey), ...busy, totalSize, items };+ const measurement = measure ? {+ ...await getDirSizeAndCount(dirPath, { strict: true }),+ disk: await statfs(DATA_DIR).then(parseFilesystemStats).catch(() => null),+ } : undefined;+ return { key: categoryKey, ...categoryMeta(categoryKey), ...busy, totalSize, items, ...(measurement && { measurement }) };}export async function archiveCategory(categoryKey, options = {}) {diff --git a/server/services/dataManager.strict.test.js b/server/services/dataManager.strict.test.jsindex 0e9ea56ff4..242c8ec012 100644--- a/server/services/dataManager.strict.test.js+++ b/server/services/dataManager.strict.test.js@@ -4,13 +4,24 @@ import { tmpdir } from 'os';import { join } from 'path';import { makePathsProxy } from '../lib/mockPathsDataRoot.js';-const mocks = vi.hoisted(() => ({ execFile: vi.fn(), statErrorPath: null }));+const mocks = vi.hoisted(() => ({ execFile: vi.fn(), statErrorPath: null, countErrorPath: null, virtualCount: 0 }));const testDataRoot = mkdtempSync(join(tmpdir(), 'datamanager-strict-test-'));vi.mock('fs/promises', async (importOriginal) => {const actual = await importOriginal();return {...actual,+ opendir: vi.fn(async (path, ...args) => {+ if (path === mocks.countErrorPath) throw Object.assign(new Error('enumeration denied'), { code: 'EACCES' });+ if (mocks.virtualCount && String(path).endsWith('cache')) return {+ async *[Symbol.asyncIterator]() {+ for (let index = 0; index < mocks.virtualCount; index++) yield {+ name: `example-${index}-${'x'.repeat(200)}`, isDirectory: () => false, isFile: () => true,+ };+ },+ };+ return actual.opendir(path, ...args);+ }),stat: vi.fn((path, ...args) => {if (path === mocks.statErrorPath) {return Promise.reject(Object.assign(new Error('stat access denied'), { code: 'EACCES' }));@@ -36,7 +47,7 @@ const { getDataOverview } = await import('./dataManager.js');afterAll(() => rmSync(testDataRoot, { recursive: true, force: true }));beforeEach(() => {- mocks.statErrorPath = null;+ mocks.statErrorPath = null; mocks.countErrorPath = null; mocks.virtualCount = 0;rmSync(testDataRoot, { recursive: true, force: true });mkdirSync(join(testDataRoot, 'cache'), { recursive: true });mkdirSync(join(testDataRoot, 'runs'), { recursive: true });@@ -77,3 +88,20 @@ describe('dataManager strict overview', () => {await expect(getDataOverview({ strict: true })).rejects.toThrow('stat access denied');});});++// Regression: an enumeration error is unknown even when size succeeds; a large+// listing never needs to fit in execFile's stdout buffer.+it('counts a large streamed listing and never invokes find', async () => {+ mocks.virtualCount = 10000;+ const overview = await getDataOverview();+ expect(overview.categories.find(c => c.key === 'cache')).toMatchObject({ size: 1024, fileCount: 10000 });+ expect(mocks.execFile.mock.calls.every(([command]) => command === 'du')).toBe(true);+});+it('keeps byte totals with unavailable counts, and rejects enumeration errors in strict mode', async () => {+ mocks.countErrorPath = join(testDataRoot, 'cache');+ mocks.execFile.mockImplementation((command, args, options, callback) => callback(null, { stdout: '1\tdata\n', stderr: '' }));+ const overview = await getDataOverview();+ expect(overview.categories.find(c => c.key === 'cache')).toMatchObject({ size: 1024, fileCount: null });+ expect(overview.totalFileCount).toBeNull();+ await expect(getDataOverview({ strict: true })).rejects.toThrow('enumeration denied');+});diff --git a/server/services/socket.js b/server/services/socket.jsindex fa71d3b3cd..2f2ddee84b 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -515,6 +515,7 @@ function setupCosEventForwarding() {['scheduler:ran', 'cos:scheduler:changed'],['scheduler:cancelled', 'cos:scheduler:changed'],['agents:changed', 'cos:agents:changed'],+ ['storage:changed', 'cos:storage:changed'],['learning:changed', 'cos:learning:changed'],]) {cosEvents.on(source, data => {