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
perf: select CoS task views before cloning archived prompts (#9677)
[._.]/ Adam Eivy0660792822ac
diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.jsindex 97a063e01f..d0c9934555 100644--- a/server/routes/cosTaskRoutes.js+++ b/server/routes/cosTaskRoutes.js@@ -132,8 +132,6 @@ async function preparePlanOnlyTask(taskData, knownApp = null) {const router = Router();-const COMPLETED_FIRST_PAGE = 25;-// GET /api/cos/tasks - Get all tasks (user + internal), grouped by source.//// Settled for the spawn window (lib/cosSpawnWindow.js): an agent registers as@@ -142,8 +140,8 @@ const COMPLETED_FIRST_PAGE = 25;// too. Settling HERE rather than in `getAllTasks()` keeps the dispatch readers// (task generation, retry revival, dedup) on the raw truth they need, while// every API consumer gets an honest queue depth without knowing the window-// exists. `cos.getAgents()` is free at this point — `getAllTasks()` has already-// warmed the same `loadState()` snapshot it reads.+// exists. The bounded views (`cos.getTaskView`) select from the parsed snapshot+// before cloning; only `view=full` pays for the whole store.//// With no params it returns a bounded `{ user, cos }` projection: all non-completed// tasks plus grouped/derived lists, and only the first page of completed history@@ -162,70 +160,51 @@ router.get('/tasks', asyncHandler(async (req, res) => {selected: z.string().max(512).optional(),cursor: z.string().max(512).optional(),}), req.query);- const [allTasks, agents] = await Promise.all([- cos.getAllTasks(),- cos.getAgents().catch(() => []),- ]);- const runningAgents = runningAgentsByTaskId(agents);- const tasks = {- ...allTasks,- user: settleTaskSourceSpawnWindow(allTasks?.user, runningAgents),- cos: settleTaskSourceSpawnWindow(allTasks?.cos, runningAgents),- };+ const settleView = (view, runningAgents) => ({+ ...view,+ user: settleTaskSourceSpawnWindow(view?.user, runningAgents),+ cos: settleTaskSourceSpawnWindow(view?.cos, runningAgents),+ });+ // The bounded views select inside the store BEFORE cloning, so a queue refresh+ // never copies archived prompt bodies (#9677). Settlement runs on the selection.+ const agentsPromise = cos.getAgents().catch(() => []);if (query.view === 'completed') {- const source = query.source === 'internal' ? tasks.cos : tasks.user;- const completed = (source?.tasks || []).filter(task => task.status === 'completed')- .sort((a, b) => a.id < b.id ? 1 : a.id > b.id ? -1 : 0);- const remaining = completed.filter(task => !query.cursor || task.id < query.cursor);const { limit } = validateRequest(z.object({ limit: z.coerce.number().int().min(1).max(100).default(25) }), req.query);- return res.json({ items: remaining.slice(0, limit), total: completed.length,- nextCursor: remaining.length > limit ? remaining[limit - 1].id : null });+ return res.json(await cos.getTaskView({ kind: 'completed', source: query.source, cursor: query.cursor, limit }));}if (query.view === 'queue') {+ const [view, agents] = await Promise.all([cos.getTaskView({ kind: 'queue', selected: query.selected }), agentsPromise]);+ const tasks = settleView(view, runningAgentsByTaskId(agents));+ // `tasks` stays whole (open queue + the selected historical task); the derived+ // lists shrink to id/status summaries.const queueSource = source => {if (!source) return source;- const keep = task => task.status !== 'completed' || task.id === query.selected;- return { ...source, tasks: (source.tasks || []).filter(keep),- completedCount: (source.tasks || []).filter(task => task.status === 'completed').length,- grouped: Object.fromEntries(Object.entries(source.grouped || {}).map(([key, rows]) => [key, rows.filter(keep).map(task => ({ id: task.id, status: task.status, spawning: task.spawning }))])),- autoApproved: source.autoApproved?.filter(keep).map(task => ({ id: task.id })), awaitingApproval: source.awaitingApproval?.filter(keep).map(task => ({ id: task.id })) };+ return { ...source,+ grouped: Object.fromEntries(Object.entries(source.grouped || {}).map(([key, rows]) => [key, rows.map(task => ({ id: task.id, status: task.status, spawning: task.spawning }))])),+ autoApproved: source.autoApproved?.map(task => ({ id: task.id })), awaitingApproval: source.awaitingApproval?.map(task => ({ id: task.id })) };};return res.json({ user: queueSource(tasks.user), cos: queueSource(tasks.cos) });}if (!isPaginationRequested(req.query)) {- if (query.view === 'full') return res.json(tasks);+ if (query.view === 'full') {+ const [allTasks, agents] = await Promise.all([cos.getAllTasks(), agentsPromise]);+ return res.json(settleView(allTasks, runningAgentsByTaskId(agents)));+ }// Bare form: bounded projection. Every non-completed task stays whole; the// completed history (96% of the bytes on a long-lived install, and once// more inside `grouped`) shrinks to the first `view=completed` page plus// `completedCount`. `view=full` is the raw-store escape hatch.- const boundSource = source => {- if (!source) return source;- const isDone = task => task.status === 'completed';- const list = source.tasks || [];- const firstPage = list.filter(isDone).sort((a, b) => a.id < b.id ? 1 : a.id > b.id ? -1 : 0).slice(0, COMPLETED_FIRST_PAGE);- const completedCount = list.filter(isDone).length;- return { ...source, tasks: [...list.filter(task => !isDone(task)), ...firstPage], completedCount,- completedNextCursor: completedCount > COMPLETED_FIRST_PAGE ? firstPage[firstPage.length - 1].id : null,- grouped: Object.fromEntries(Object.entries(source.grouped || {}).map(([key, rows]) => [key, rows.filter(task => !isDone(task))])),- autoApproved: source.autoApproved?.filter(task => !isDone(task)), awaitingApproval: source.awaitingApproval?.filter(task => !isDone(task)) };- };- return res.json({ ...tasks, user: boundSource(tasks.user), cos: boundSource(tasks.cos) });+ const [view, agents] = await Promise.all([cos.getTaskView({ kind: 'bare' }), agentsPromise]);+ return res.json(settleView(view, runningAgentsByTaskId(agents)));}const { limit, offset } = parsePagination(req.query, { defaultLimit: 50, maxLimit: 500 });- const sliceSource = (src) => {- if (!src || typeof src !== 'object') return { tasks: [] };- // Strip the full-set derived collections so the response is actually bounded;- // keep only scalar metadata (file/exists/type) + the windowed task slice.- const { tasks: list, grouped, autoApproved, awaitingApproval, ...meta } = src;- const arr = Array.isArray(list) ? list : [];- return { ...meta, tasks: arr.slice(offset, offset + limit) };- };- const userTotal = Array.isArray(tasks?.user?.tasks) ? tasks.user.tasks.length : 0;- const cosTotal = Array.isArray(tasks?.cos?.tasks) ? tasks.cos.tasks.length : 0;+ const [view, agents] = await Promise.all([cos.getTaskView({ kind: 'window', offset, limit }), agentsPromise]);+ const runningAgents = runningAgentsByTaskId(agents);+ const { totals } = view;res.json({- user: sliceSource(tasks?.user),- cos: sliceSource(tasks?.cos),- pagination: { limit, offset, userTotal, cosTotal, total: userTotal + cosTotal }+ user: settleTaskSourceSpawnWindow(view.user, runningAgents),+ cos: settleTaskSourceSpawnWindow(view.cos, runningAgents),+ pagination: { limit, offset, userTotal: totals.user, cosTotal: totals.cos, total: totals.user + totals.cos }});}));diff --git a/server/routes/cosTaskRoutes.test.js b/server/routes/cosTaskRoutes.test.jsindex 8bb1aaf93d..3be388efa7 100644--- a/server/routes/cosTaskRoutes.test.js+++ b/server/routes/cosTaskRoutes.test.js@@ -43,6 +43,7 @@ vi.mock('../services/cos.js', () => ({addTask: vi.fn(),updateTask: vi.fn(),getAllTasks: vi.fn(),+ getTaskView: vi.fn(),getAgents: vi.fn(),getUserTasks: vi.fn(),getCosTasks: vi.fn(),@@ -487,8 +488,10 @@ describe('GET /api/cos/tasks — the spawn window (lib/cosSpawnWindow.js)', () =grouped: { pending: [{ id: 'user/42', status: 'pending' }, { id: 'user/43', status: 'pending' }], in_progress: [] },});+ const store = () => ({ user: source(), cos: { tasks: [], grouped: { pending: [], in_progress: [] } } });beforeEach(() => {- cos.getAllTasks.mockResolvedValue({ user: source(), cos: { tasks: [], grouped: { pending: [], in_progress: [] } } });+ cos.getAllTasks.mockResolvedValue(store());+ cos.getTaskView.mockResolvedValue(store());});it('regroups a task its agent already holds and stamps it spawning', async () => {@@ -516,6 +519,68 @@ describe('GET /api/cos/tasks — the spawn window (lib/cosSpawnWindow.js)', () =});});+// The bounded views select inside the store (#9677): the route only picks the+// reader, settles the spawn window on what came back, and shapes the response.+// The real selection/cursor contracts are pinned against the store's own reader+// in services/cosTaskStore.test.js.+describe('GET /api/cos/tasks — bounded view routing (#9677)', () => {+ const live = (taskId) => ({ id: `agent-${taskId}`, taskId, status: 'running', startedAt: new Date().toISOString() });+ const open = () => ({ tasks: [{ id: 'user/1', status: 'pending' }],+ grouped: { pending: [{ id: 'user/1', status: 'pending' }], in_progress: [], completed: [] },+ file: 'TASKS.md', exists: true, type: 'user' });+ const empty = { tasks: [], grouped: {}, exists: false };++ it('bare view reads the bounded reader, never the raw store, and settles the selection', async () => {+ cos.getTaskView.mockResolvedValue({ user: { ...open(), completedCount: 40, completedNextCursor: 'user/09' }, cos: empty });+ cos.getAgents.mockResolvedValue([live('user/1')]);+ const res = await request(buildApp()).get('/api/cos/tasks');+ expect(cos.getTaskView).toHaveBeenCalledWith({ kind: 'bare' });+ expect(cos.getAllTasks).not.toHaveBeenCalled();+ expect(res.body.user).toMatchObject({ completedCount: 40, completedNextCursor: 'user/09' });+ expect(res.body.user.grouped.in_progress.map(t => t.id)).toEqual(['user/1']);+ });++ it('queue view summarizes the derived lists and forwards the selected id', async () => {+ cos.getTaskView.mockResolvedValue({ user: { ...open(), completedCount: 9,+ grouped: { pending: [{ id: 'user/1', status: 'pending', description: 'x' }], completed: [{ id: 'user/old', status: 'completed', description: 'y' }] } }, cos: empty });+ cos.getAgents.mockResolvedValue([live('user/1')]);+ const res = await request(buildApp()).get('/api/cos/tasks?view=queue&selected=user/old');+ expect(cos.getTaskView).toHaveBeenCalledWith({ kind: 'queue', selected: 'user/old' });+ expect(res.body.user.completedCount).toBe(9);+ expect(res.body.user.grouped).toEqual({+ pending: [], in_progress: [{ id: 'user/1', status: 'pending', spawning: true }],+ completed: [{ id: 'user/old', status: 'completed' }],+ });+ });++ it('completed view validates the page size and passes source/cursor through', async () => {+ cos.getTaskView.mockResolvedValue({ items: [], total: 0, nextCursor: null });+ const res = await request(buildApp()).get('/api/cos/tasks?view=completed&source=internal&cursor=c9&limit=10');+ expect(res.body).toEqual({ items: [], total: 0, nextCursor: null });+ expect(cos.getTaskView).toHaveBeenCalledWith({ kind: 'completed', source: 'internal', cursor: 'c9', limit: 10 });+ expect((await request(buildApp()).get('/api/cos/tasks?view=completed&limit=101')).status).toBe(400);+ });++ it('limit/offset keeps the legacy shape with true totals and settles the window', async () => {+ cos.getTaskView.mockResolvedValue({ user: { file: 'TASKS.md', exists: true, type: 'user', tasks: [{ id: 'user/1', status: 'pending' }] },+ cos: { file: 'COS.md', exists: true, type: 'internal', tasks: [] }, totals: { user: 7, cos: 3 } });+ cos.getAgents.mockResolvedValue([live('user/1')]);+ const res = await request(buildApp()).get('/api/cos/tasks?limit=1&offset=2');+ expect(cos.getTaskView).toHaveBeenCalledWith({ kind: 'window', offset: 2, limit: 1 });+ expect(res.body.pagination).toEqual({ limit: 1, offset: 2, userTotal: 7, cosTotal: 3, total: 10 });+ expect(res.body.user.tasks[0]).toMatchObject({ id: 'user/1', spawning: true });+ expect(res.body.user.grouped).toBeUndefined();+ });++ it('view=full stays the raw store, settled', async () => {+ cos.getAllTasks.mockResolvedValue({ user: open(), cos: empty });+ cos.getAgents.mockResolvedValue([live('user/1')]);+ const res = await request(buildApp()).get('/api/cos/tasks?view=full');+ expect(cos.getTaskView).not.toHaveBeenCalled();+ expect(res.body.user.tasks[0]).toMatchObject({ id: 'user/1', spawning: true });+ });+});+// The agent-facing half of the calibration loop (`lib/goalFidelityCalibration.js`).// A follow-up investigator that overturned a fidelity finding POSTs here; the// route's whole job is to keep the gap vocabulary honest and to never turn adiff --git a/server/services/cos.js b/server/services/cos.jsindex 3be38f76ea..13193b1153 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -93,9 +93,9 @@ export { runHealthCheck, getHealthStatus };// backward compat with `import * as cos` and the cos route handlers. The store// emits `tasks:changed`; init() below turns that into tryImmediateSpawn /// dequeueNextTask so the spawn-side logic stays here, not in the store.-import { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks } from './cosTaskStore.js';+import { firstLine, getUserTasks, getCosTasks, getAllTasks, getTaskView, getTasks, getTaskById, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks } from './cosTaskStore.js';export { getPendingTaskIds } from './cosTaskStore.js';-export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks };+export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTaskView, getTasks, getTaskById, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks };import { ensureInstanceId } from './instanceIdentity.js';import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner } from './cosTaskClaim.js';import { retryTasksResolvedByInvestigation } from './investigationRetry.js';diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex 3893d89f6a..9999cf7e5f 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -270,6 +270,123 @@ export async function getAllTasks() {return { user: userTasks, cos: cosTasks };}+// ── Bounded task views (#9677) ──────────────────────────────────────────────+//+// `GET /api/cos/tasks` returns the open queue plus at most one page of completed+// history, yet `getAllTasks()` structured-clones every archived prompt body from+// BOTH sources first. These readers select from the private snapshot and clone+// only what the response carries. Nothing returned here aliases the cache.+const COMPLETED_FIRST_PAGE = 25;+const byIdDesc = (a, b) => (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);+const isCompleted = (task) => task.status === 'completed';++// Per-snapshot derivations, dropped with the snapshot on any stamp/write change.+function snapshotPartitions(snapshot) {+ if (!snapshot.partitions) {+ const open = [];+ const completed = [];+ for (const task of snapshot.tasks) (isCompleted(task) ? completed : open).push(task);+ completed.sort(byIdDesc);+ snapshot.partitions = { open, completed };+ }+ return snapshot.partitions;+}++async function resolveSourceFile(type) {+ const { config } = await loadState();+ const filePath = join(ROOT_DIR, type === 'internal' ? config.cosTasksFile : config.userTasksFile);+ return existsSync(filePath) ? filePath : null;+}++// Shape of getUserTasks()/getCosTasks() over an already-selected task subset.+// Callers pass CLONED tasks; grouped/derived lists share those clones. A missing+// file keeps getCosTasks()'s shape: no derived lists.+function sourceShape(type, filePath, tasks, { exists = true } = {}) {+ const shape = { tasks, grouped: groupTasksByStatus(tasks), file: filePath, exists, type };+ if (type === 'internal' && exists) {+ shape.autoApproved = getAutoApprovedTasks(tasks);+ shape.awaitingApproval = getAwaitingApprovalTasks(tasks);+ }+ return shape;+}++/**+ * Open queue (every non-completed task, plus the `selected` historical task)+ * for both sources. `completedCount` carries the archived total.+ */+async function readQueueView(selected) {+ const read = async (type) => {+ const filePath = await resolveSourceFile(type);+ if (!filePath) return { ...sourceShape(type, filePath, [], { exists: false }), completedCount: 0 };+ const snapshot = await readTaskSnapshot(filePath);+ const { open, completed } = snapshotPartitions(snapshot);+ const refs = selected === undefined ? open : snapshot.tasks.filter((task) => !isCompleted(task) || task.id === selected);+ return { ...sourceShape(type, filePath, structuredClone(refs)), completedCount: completed.length };+ };+ const [user, cos] = await Promise.all([read('user'), read('internal')]);+ return { user, cos };+}++/** Open queue plus the first completed page; completed history stays archived. */+async function readBareView() {+ const read = async (type) => {+ const filePath = await resolveSourceFile(type);+ if (!filePath) return { ...sourceShape(type, filePath, [], { exists: false }), completedCount: 0, completedNextCursor: null };+ const { open, completed } = snapshotPartitions(await readTaskSnapshot(filePath));+ const firstPage = completed.slice(0, COMPLETED_FIRST_PAGE);+ const shape = sourceShape(type, filePath, structuredClone([...open, ...firstPage]));+ // Completed rows leave `grouped`; only the page inside `tasks` carries them.+ return { ...shape, grouped: { ...shape.grouped, completed: [] }, completedCount: completed.length,+ completedNextCursor: completed.length > COMPLETED_FIRST_PAGE ? firstPage[firstPage.length - 1].id : null };+ };+ const [user, cos] = await Promise.all([read('user'), read('internal')]);+ return { user, cos };+}++/** One page of completed history from ONE source, newest id first. */+async function readCompletedView({ source, cursor, limit }) {+ const type = source === 'internal' ? 'internal' : 'user';+ const filePath = await resolveSourceFile(type);+ if (!filePath) return { items: [], total: 0, nextCursor: null };+ const { completed } = snapshotPartitions(await readTaskSnapshot(filePath));+ const remaining = cursor ? completed.filter((task) => task.id < cursor) : completed;+ return { items: structuredClone(remaining.slice(0, limit)), total: completed.length,+ nextCursor: remaining.length > limit ? remaining[limit - 1].id : null };+}++/** Legacy limit/offset window: the slice and scalar metadata only. */+async function readWindowView({ offset, limit }) {+ const read = async (type) => {+ const filePath = await resolveSourceFile(type);+ if (!filePath) return { meta: { file: filePath, exists: false, type }, tasks: [], total: 0 };+ const snapshot = await readTaskSnapshot(filePath);+ return { meta: { file: filePath, exists: true, type }, tasks: structuredClone(snapshot.tasks.slice(offset, offset + limit)), total: snapshot.tasks.length };+ };+ const [user, cos] = await Promise.all([read('user'), read('internal')]);+ return {+ user: { ...user.meta, tasks: user.tasks },+ cos: { ...cos.meta, tasks: cos.tasks },+ totals: { user: user.total, cos: cos.total },+ };+}++/**+ * Read-only, bounded task view for the HTTP layer. `kind`:+ * - 'queue' { selected? } open tasks (+ the selected historical one) + completedCount+ * - 'bare' open tasks + first completed page (+ completedCount/completedNextCursor)+ * - 'completed' { source, cursor?, limit } one source's page → { items, total, nextCursor }+ * - 'window' { offset, limit } legacy slice → { user, cos, totals }+ * Sources come back unsettled for the spawn window; `getAllTasks()` stays the raw+ * truth for scheduler readers and `view=full`.+ */+export async function getTaskView({ kind, ...options }) {+ if (kind === 'queue') return readQueueView(options.selected);+ if (kind === 'bare') return readBareView();+ if (kind === 'completed') return readCompletedView(options);+ if (kind === 'window') return readWindowView(options);+ throw new Error(`Unknown task view: ${kind}`);+}+/*** Lightweight live-activity input. Derive once per task-file snapshot, so a* three-second poll never clones prompts or groups completed history.diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex 5113612daa..04c75a30dd 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -101,6 +101,7 @@ import {getUserTasks,getCosTasks,getAllTasks,+ getTaskView,getPendingTaskIds,getTaskDiagnostics,getTasks,@@ -368,6 +369,145 @@ describe('cosTaskStore parsed-task cache (#3497)', () => {});});+// Bounded task views (#9677). The HTTP queue/bare/completed/window reads select+// from the parsed snapshot BEFORE cloning, so archived prompt bodies are never+// copied for a response that does not carry them. Each view is checked against a+// projection of the raw getAllTasks() truth (the contract the route used to build+// itself) plus the instrumented size of what was actually cloned.+describe('cosTaskStore.getTaskView (#9677)', () => {+ const PROMPT = Array(400).fill('Archived prompt body.').join(' ');+ const row = (type, n, status, extra = {}) => ({+ id: `task-${type}-${String(n).padStart(4, '0')}`, description: `Example ${type} task ${n}`, status, priority: 'MEDIUM',+ metadata: { prompt: status === 'completed' ? PROMPT : 'Open prompt.' }, ...extra+ });+ const seed = (completedPerSource = 60) => {+ const archived = (type) => Array.from({ length: completedPerSource }, (_, n) => row(type, n, 'completed'));+ mock.files.set(USER_FILE, generateTasksMarkdown([+ row('user', 1000, 'pending'), ...archived('user'), row('user', 1001, 'in_progress'), row('user', 1002, 'blocked'),+ ]));+ mock.files.set(COS_FILE, generateTasksMarkdown([+ row('cos', 1000, 'pending', { approvalRequired: false, autoApproved: true }), ...archived('cos'),+ row('cos', 1001, 'pending', { approvalRequired: true, autoApproved: false }),+ ]));+ };+ const desc = (a, b) => (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);+ const withSpy = async (fn) => {+ const clone = vi.spyOn(globalThis, 'structuredClone');+ try {+ const result = await fn();+ const cloned = clone.mock.calls.reduce((sum, [value]) => sum + JSON.stringify(value).length, 0);+ return { result, cloned };+ } finally { clone.mockRestore(); }+ };++ it('bare view equals the raw store minus archived rows beyond the first page, and clones only that page', async () => {+ seed();+ const raw = await getAllTasks();+ const { result, cloned } = await withSpy(() => getTaskView({ kind: 'bare' }));+ for (const key of ['user', 'cos']) {+ const all = raw[key];+ const open = all.tasks.filter(t => t.status !== 'completed');+ const page = all.tasks.filter(t => t.status === 'completed').sort(desc).slice(0, 25);+ expect(result[key]).toEqual({+ ...all, tasks: [...open, ...page], completedCount: 60, completedNextCursor: page[24].id,+ grouped: { ...all.grouped, completed: [] },+ ...(key === 'cos' ? { autoApproved: all.autoApproved, awaitingApproval: all.awaitingApproval } : {}),+ });+ }+ const rawBytes = JSON.stringify(raw).length;+ // 2 sources x (4 open + 25 page) of 120 rows: well under half the raw payload.+ expect(cloned).toBeLessThan(rawBytes * 0.3);+ console.log(`bounded bare clone: ${cloned} of ${rawBytes} bytes`);+ });++ it('queue view clones no archived prompt unless one is selected, then exactly that row', async () => {+ seed();+ const raw = await getAllTasks();+ const queue = await withSpy(() => getTaskView({ kind: 'queue' }));+ expect(queue.result.user.tasks.map(t => t.id)).toEqual(['task-user-1000', 'task-user-1001', 'task-user-1002']);+ expect(queue.result.user.completedCount).toBe(60);+ expect(queue.result.user.grouped.completed).toEqual([]);+ expect(queue.result.cos.awaitingApproval.map(t => t.id)).toEqual(['task-cos-1001']);+ expect(queue.cloned).toBeLessThan(JSON.stringify(raw.user.tasks.slice(0, 4)).length * 4);+ expect(JSON.stringify(queue.result)).not.toContain('Archived prompt body');++ const picked = await getTaskView({ kind: 'queue', selected: 'task-user-0007' });+ // File order is kept: the selected archived row stays where the file put it.+ expect(picked.user.tasks.map(t => t.id)).toEqual(raw.user.tasks.filter(t => t.status !== 'completed' || t.id === 'task-user-0007').map(t => t.id));+ expect(picked.user.grouped.completed.map(t => t.id)).toEqual(['task-user-0007']);+ expect(picked.user.tasks.find(t => t.id === 'task-user-0007')).toEqual(raw.user.tasks.find(t => t.id === 'task-user-0007'));+ expect(picked.cos.tasks.every(t => t.status !== 'completed')).toBe(true);+ });++ it('completed view reads one source, pages by cursor, and clones just the page', async () => {+ seed();+ const raw = await getAllTasks();+ const expectedIds = raw.cos.tasks.filter(t => t.status === 'completed').sort(desc).map(t => t.id);+ const first = await withSpy(() => getTaskView({ kind: 'completed', source: 'internal', limit: 10 }));+ expect(first.result.items.map(t => t.id)).toEqual(expectedIds.slice(0, 10));+ expect(first.result).toMatchObject({ total: 60, nextCursor: expectedIds[9] });+ expect(first.cloned).toBeLessThan(JSON.stringify(raw.cos.tasks).length / 5);+ const next = await getTaskView({ kind: 'completed', source: 'internal', limit: 10, cursor: first.result.nextCursor });+ expect(next.items.map(t => t.id)).toEqual(expectedIds.slice(10, 20));+ const tail = await getTaskView({ kind: 'completed', source: 'user', limit: 100, cursor: 'task-user-0003' });+ expect(tail).toMatchObject({ total: 60, nextCursor: null });+ expect(tail.items.map(t => t.id)).toEqual(['task-user-0002', 'task-user-0001', 'task-user-0000']);+ });++ it('window view slices in file order with true totals and scalar metadata only', async () => {+ seed();+ const raw = await getAllTasks();+ const { result, cloned } = await withSpy(() => getTaskView({ kind: 'window', offset: 2, limit: 3 }));+ expect(result.user).toEqual({ file: USER_FILE, exists: true, type: 'user', tasks: raw.user.tasks.slice(2, 5) });+ expect(result.cos.tasks).toEqual(raw.cos.tasks.slice(2, 5));+ expect(result.totals).toEqual({ user: raw.user.tasks.length, cos: raw.cos.tasks.length });+ expect(cloned).toBeLessThan(JSON.stringify(raw).length / 10);+ });++ it('missing files keep the getUserTasks/getCosTasks shape', async () => {+ const raw = await getAllTasks();+ const bare = await getTaskView({ kind: 'bare' });+ expect(bare.user).toMatchObject({ tasks: [], exists: false, type: 'user', completedCount: 0, completedNextCursor: null });+ expect(bare.cos.autoApproved).toBeUndefined();+ expect(raw.cos.autoApproved).toBeUndefined();+ expect((await getTaskView({ kind: 'queue' })).cos.completedCount).toBe(0);+ expect(await getTaskView({ kind: 'completed', source: 'user', limit: 5 })).toEqual({ items: [], total: 0, nextCursor: null });+ expect((await getTaskView({ kind: 'window', offset: 0, limit: 5 })).totals).toEqual({ user: 0, cos: 0 });+ });++ it('never leaks the cache: caller mutation, internal writes and same-size external edits', async () => {+ seed(30);+ const first = await getTaskView({ kind: 'bare' });+ first.user.tasks[0].description = 'mutated in place';+ first.user.tasks.push({ id: 'ghost' });+ first.user.grouped.pending.length = 0;+ const page = await getTaskView({ kind: 'completed', source: 'user', limit: 5 });+ page.items[0].metadata.prompt = 'poisoned';++ const again = await getTaskView({ kind: 'bare' });+ expect(again.user.tasks.find(t => t.id === 'ghost')).toBeUndefined();+ expect(again.user.tasks[0].description).toBe('Example user task 1000');+ expect(again.user.grouped.pending).toHaveLength(1);+ expect((await getTaskView({ kind: 'completed', source: 'user', limit: 5 })).items[0].metadata.prompt).toBe(PROMPT);++ // Internal write: the derived partitions drop with the snapshot.+ await updateTask('task-user-1000', { status: 'completed' }, 'user');+ const written = await getTaskView({ kind: 'queue' });+ expect(written.user.tasks.map(t => t.id)).toEqual(['task-user-1001', 'task-user-1002']);+ expect(written.user.completedCount).toBe(31);++ // External same-size edit with a moved stamp (a peer/editor flips a status).+ const text = mock.files.get(USER_FILE);+ mock.files.set(USER_FILE, text.replace('- [~] #task-user-1001', '- [x] #task-user-1001'));+ mock.mtimes.set(USER_FILE, mock.mtimes.get(USER_FILE) + 5000);+ const external = await getTaskView({ kind: 'queue' });+ expect(external.user.tasks.map(t => t.id)).toEqual(['task-user-1002']);+ expect(external.user.completedCount).toBe(32);+ mock.files.delete(USER_FILE);+ expect((await getTaskView({ kind: 'bare' })).user.exists).toBe(false);+ });+});+describe('cosTaskStore.getAllTasks / getTasks / getTaskById', () => {it('getTasks aliases getUserTasks', () => {expect(getTasks).toBe(getUserTasks);