Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

cache the review store, archive stale items, and batch bulk-status events (#6853)

[._.]/ Adam Eivyaa688fd74a87
diff --git a/client/src/components/ReviewHubCard.jsx b/client/src/components/ReviewHubCard.jsx
index 671534ef1b..0efc7c8f83 100644
--- a/client/src/components/ReviewHubCard.jsx
+++ b/client/src/components/ReviewHubCard.jsx
@@ -14,11 +14,13 @@ export default function ReviewHubCard() {
socket.on('review:item:created', refresh);
socket.on('review:item:updated', refresh);
socket.on('review:item:deleted', refresh);
+ socket.on('review:items:bulk-updated', refresh);
return () => {
socket.off('review:item:created', refresh);
socket.off('review:item:updated', refresh);
socket.off('review:item:deleted', refresh);
+ socket.off('review:items:bulk-updated', refresh);
};
}, []);
diff --git a/client/src/components/ReviewHubCard.test.jsx b/client/src/components/ReviewHubCard.test.jsx
new file mode 100644
index 0000000000..a2652ae745
--- /dev/null
+++ b/client/src/components/ReviewHubCard.test.jsx
@@ -0,0 +1,97 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { act, render, screen } from '@testing-library/react';
+
+const api = vi.hoisted(() => ({
+ getReviewCounts: vi.fn()
+}));
+
+const socket = vi.hoisted(() => ({
+ on: vi.fn(),
+ off: vi.fn(),
+ emit: vi.fn()
+}));
+
+vi.mock('../services/api', () => api);
+vi.mock('../services/socket', () => ({ default: socket }));
+vi.mock('react-router', () => ({
+ Link: ({ children, to, ...props }) => <a href={to} {...props}>{children}</a>
+}));
+
+import ReviewHubCard from './ReviewHubCard';
+
+// Invokes the handler the component registered for `event` via socket.on,
+// the same pattern as client/src/hooks/useNotifications.test.jsx.
+function deliver(event, payload) {
+ const handler = socket.on.mock.calls.find(([name]) => name === event)?.[1];
+ expect(handler).toBeTypeOf('function');
+ handler(payload);
+}
+
+const ZERO_COUNTS = { total: 0, alert: 0, todo: 0, briefing: 0, cos: 0 };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.getReviewCounts.mockResolvedValue(ZERO_COUNTS);
+});
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('ReviewHubCard', () => {
+ it('subscribes to every review socket event, including the bulk-update event, on mount', async () => {
+ render(<ReviewHubCard />);
+ await act(async () => { await Promise.resolve(); });
+
+ const events = socket.on.mock.calls.map(([name]) => name);
+ expect(events).toEqual(expect.arrayContaining([
+ 'review:item:created',
+ 'review:item:updated',
+ 'review:item:deleted',
+ 'review:items:bulk-updated'
+ ]));
+ });
+
+ it('renders the all-caught-up state when there are no pending items', async () => {
+ render(<ReviewHubCard />);
+ expect(await screen.findByText('All caught up!')).toBeInTheDocument();
+ });
+
+ it('renders the total badge and per-type breakdown once counts resolve', async () => {
+ api.getReviewCounts.mockResolvedValue({ total: 3, alert: 1, todo: 1, briefing: 0, cos: 1 });
+ render(<ReviewHubCard />);
+
+ expect(await screen.findByText('3')).toBeInTheDocument();
+ expect(screen.getByText('1 alert')).toBeInTheDocument();
+ expect(screen.getByText('1 todo')).toBeInTheDocument();
+ expect(screen.getByText('1 CoS')).toBeInTheDocument();
+ });
+
+ it('refetches counts exactly once when a review:items:bulk-updated event arrives', async () => {
+ render(<ReviewHubCard />);
+ await act(async () => { await Promise.resolve(); });
+ expect(api.getReviewCounts).toHaveBeenCalledTimes(1); // the initial mount fetch
+
+ api.getReviewCounts.mockResolvedValue({ total: 5, alert: 0, todo: 5, briefing: 0, cos: 0 });
+ await act(async () => {
+ deliver('review:items:bulk-updated', { ids: ['a', 'b'], status: 'dismissed', updatedAt: new Date().toISOString() });
+ await Promise.resolve();
+ });
+
+ expect(api.getReviewCounts).toHaveBeenCalledTimes(2);
+ expect(await screen.findByText('5')).toBeInTheDocument();
+ });
+
+ it('unsubscribes every review event, including the bulk-update event, on unmount', async () => {
+ const { unmount } = render(<ReviewHubCard />);
+ await act(async () => { await Promise.resolve(); });
+
+ unmount();
+
+ const offEvents = socket.off.mock.calls.map(([name]) => name);
+ expect(offEvents).toEqual(expect.arrayContaining([
+ 'review:item:created',
+ 'review:item:updated',
+ 'review:item:deleted',
+ 'review:items:bulk-updated'
+ ]));
+ });
+});
diff --git a/client/src/pages/Review.jsx b/client/src/pages/Review.jsx
index 71675c4ce5..e8f7a05ee5 100644
--- a/client/src/pages/Review.jsx
+++ b/client/src/pages/Review.jsx
@@ -144,15 +144,23 @@ export default function Review() {
const handleDeleted = (item) => {
setItems(prev => prev.filter(i => i.id !== item.id));
};
+ // Bulk status change ("Mark all read" / "Complete all") — one state
+ // update for every affected id instead of N per-item events.
+ const handleBulkUpdated = ({ ids, status, updatedAt }) => {
+ const idSet = new Set(ids);
+ setItems(prev => prev.map(i => idSet.has(i.id) ? { ...i, status, updatedAt } : i));
+ };
socket.on('review:item:created', handleCreated);
socket.on('review:item:updated', handleUpdated);
socket.on('review:item:deleted', handleDeleted);
+ socket.on('review:items:bulk-updated', handleBulkUpdated);
return () => {
socket.off('review:item:created', handleCreated);
socket.off('review:item:updated', handleUpdated);
socket.off('review:item:deleted', handleDeleted);
+ socket.off('review:items:bulk-updated', handleBulkUpdated);
};
}, [fetchItems]);
diff --git a/client/src/pages/Review.test.jsx b/client/src/pages/Review.test.jsx
index 5679904703..684dc4e61b 100644
--- a/client/src/pages/Review.test.jsx
+++ b/client/src/pages/Review.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
// A CoS action body is arbitrary agent-authored markdown — thousands of words,
// its own heading outline, and raw technical payloads. This is the shape that
@@ -66,6 +66,7 @@ vi.mock('react-router', () => ({
}));
import Review from './Review';
+import socket from '../services/socket';
// jsdom reports 0 for scrollHeight/clientHeight, so nothing measures as
// overflowing unless we force it.
@@ -175,3 +176,35 @@ describe('Review Hub queue-card triage (#3282)', () => {
expect(document.querySelectorAll(`[id="review-item-body-action-queue-${ITEM.id}"]`)).toHaveLength(1);
});
});
+
+describe('Review Hub bulk status updates (#6853)', () => {
+ it('applies a review:items:bulk-updated event to every affected item in one update', async () => {
+ render(<Review />);
+ await waitFor(() => expect(actionQueueBody()).toBeTruthy());
+ await waitFor(() => expect(document.getElementById(`review-item-body-action-queue-${SHORT_ITEM.id}`)).toBeTruthy());
+
+ const handler = socket.on.mock.calls.find(([name]) => name === 'review:items:bulk-updated')?.[1];
+ expect(handler).toBeTypeOf('function');
+
+ act(() => {
+ handler({ ids: [ITEM.id, SHORT_ITEM.id], status: 'dismissed', updatedAt: new Date().toISOString() });
+ });
+
+ // Both items are no longer pending, so — in the same render — both drop
+ // out of the Action Queue, which is built from pendingItems.
+ await waitFor(() => {
+ expect(actionQueueBody()).toBeFalsy();
+ expect(document.getElementById(`review-item-body-action-queue-${SHORT_ITEM.id}`)).toBeFalsy();
+ });
+ });
+
+ it('subscribes to and unsubscribes from review:items:bulk-updated', async () => {
+ const { unmount } = render(<Review />);
+ await waitFor(() => expect(actionQueueBody()).toBeTruthy());
+
+ expect(socket.on.mock.calls.some(([name]) => name === 'review:items:bulk-updated')).toBe(true);
+
+ unmount();
+ expect(socket.off.mock.calls.some(([name]) => name === 'review:items:bulk-updated')).toBe(true);
+ });
+});
diff --git a/server/services/review.js b/server/services/review.js
index 155ae6baf0..daffef4014 100644
--- a/server/services/review.js
+++ b/server/services/review.js
@@ -5,7 +5,7 @@
* Aggregates items requiring user attention into a single hub.
*/
-import { readFile, readdir } from 'fs/promises';
+import { readFile, readdir, stat } from 'fs/promises';
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { EventEmitter } from 'events';
@@ -15,6 +15,10 @@ import { GOAL_FIDELITY_HOLD_EVENT, formatGoalFidelitySummary } from '../lib/goal
const DATA_DIR = join(PATHS.data, 'review');
const ITEMS_FILE = join(DATA_DIR, 'items.json');
+// Cold storage for completed/dismissed items retention moves out of items.json
+// (see `applyRetention` below) — same file-backed record kind, split by age,
+// inside the existing `data/review/` directory rather than a new data store.
+const ARCHIVE_FILE = join(DATA_DIR, 'archive.json');
export const reviewEvents = new EventEmitter();
@@ -22,8 +26,35 @@ export const reviewEvents = new EventEmitter();
const ITEM_TYPES = ['alert', 'todo', 'briefing', 'cos'];
const ITEM_STATUSES = ['pending', 'completed', 'dismissed'];
+// Retention: on a daily debounce, move completed/dismissed items older than
+// this out of items.json and into archive.json (see `applyRetention`).
+const RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1000;
+const RETENTION_AGE_MS = 30 * 24 * 60 * 60 * 1000;
+const ARCHIVE_ELIGIBLE_STATUSES = new Set(['completed', 'dismissed']);
+
+// Module-level cache of the parsed items.json, keyed on file identity (mtime +
+// size) rather than an in-process "loaded" flag: `dataManager.js` registers
+// `review` as archivable/deletable, so `data/review/` can be archived or
+// deleted out from under this process while it runs, and a flag-based cache
+// would keep serving a since-deleted file's contents forever. `saveItems`
+// re-stats after every write and seeds the cache directly from what it just
+// wrote, so a read immediately following a write is a cache hit, not a re-parse.
+//
+// Every mutation path below (createItem/updateItemStatus/bulkUpdateStatus/
+// updateItem/deleteItem/updateStatusByReferenceId) mutates the array/items
+// returned by `loadItems()` in place and then immediately calls `saveItems`
+// with that same array — never mutates without saving. That invariant is what
+// makes it safe for `loadItems()` to hand back the cached array/objects
+// directly instead of deep-cloning on every read: a caller either treats it as
+// read-only, or mutates it and persists the result in the same call, which
+// `saveItems` then adopts as the new cache. Keep that invariant true for any
+// new mutation path.
+let itemsCache = null; // { mtimeMs, size, items }
+let lastRetentionAt = 0; // 0 so the first save after boot always evaluates retention
+
/**
- * Load all review items from file
+ * Load all review items from file, reusing the cached parse when the file's
+ * mtime/size haven't changed since the last read.
*/
// STRICT (#4115): `getPendingCounts()` reduces this list into the Review Hub's
// total/alert/todo/briefing/cos tiles, so a swallowed unreadable read reports a
@@ -31,22 +62,85 @@ const ITEM_STATUSES = ['pending', 'completed', 'dismissed'];
// read-modify-write (createItem/status updates → `saveItems`), where an
// unreadable file collapsing to `[]` would destroy every stored review item.
async function loadItems() {
- return readJSONFile(ITEMS_FILE, [], { strict: true });
+ const stats = await stat(ITEMS_FILE).catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+
+ if (!stats) {
+ itemsCache = null;
+ return [];
+ }
+
+ if (itemsCache && itemsCache.mtimeMs === stats.mtimeMs && itemsCache.size === stats.size) {
+ return itemsCache.items;
+ }
+
+ const items = await readJSONFile(ITEMS_FILE, [], { strict: true });
+ itemsCache = { mtimeMs: stats.mtimeMs, size: stats.size, items };
+ return items;
}
/**
- * Save items to file atomically
+ * Load the archived (retired) items. Never cached — only read from the
+ * history views (`getItems` for a completed/dismissed/unfiltered query,
+ * and `createItem`'s duplicate-alert check when the live scan misses).
+ */
+async function loadArchive() {
+ return readJSONFile(ARCHIVE_FILE, [], { strict: true });
+}
+
+/**
+ * Move completed/dismissed items older than `RETENTION_AGE_MS` out of
+ * items.json and into archive.json, at most once per `RETENTION_INTERVAL_MS`.
+ * Writes the archive FIRST and only then returns the trimmed list for
+ * `saveItems` to persist — so a crash between the two writes can duplicate an
+ * item across both files (harmless, self-heals on the next read) but can
+ * never lose one.
+ */
+async function applyRetention(items) {
+ const now = Date.now();
+ if (now - lastRetentionAt < RETENTION_INTERVAL_MS) return items;
+ lastRetentionAt = now;
+
+ const cutoff = now - RETENTION_AGE_MS;
+ const remaining = [];
+ const toArchive = [];
+ for (const item of items) {
+ const eligible = ARCHIVE_ELIGIBLE_STATUSES.has(item.status) && new Date(item.updatedAt).getTime() < cutoff;
+ (eligible ? toArchive : remaining).push(item);
+ }
+
+ if (toArchive.length === 0) return items;
+
+ const archive = await loadArchive();
+ await atomicWrite(ARCHIVE_FILE, [...archive, ...toArchive]);
+ console.log(`📦 Review items archived: ${toArchive.length}`);
+ return remaining;
+}
+
+/**
+ * Save items to file atomically, applying retention first and re-priming the
+ * read cache from what was actually written.
*/
async function saveItems(items) {
await ensureDir(DATA_DIR);
- await atomicWrite(ITEMS_FILE, items);
+ const retained = await applyRetention(items);
+ await atomicWrite(ITEMS_FILE, retained);
+ const stats = await stat(ITEMS_FILE).catch(() => null);
+ itemsCache = stats ? { mtimeMs: stats.mtimeMs, size: stats.size, items: retained } : null;
}
/**
- * Get all review items, sorted by type then creation date (newest first)
+ * Get all review items, sorted by type then creation date (newest first).
+ * A completed/dismissed or unfiltered query also merges in archive.json —
+ * archive never holds a pending item, so a pending-only query skips it.
*/
export async function getItems({ status, type } = {}) {
let items = await loadItems();
+ if (!status || ARCHIVE_ELIGIBLE_STATUSES.has(status)) {
+ items = items.concat(await loadArchive());
+ }
if (status) items = items.filter(i => i.status === status);
if (type) items = items.filter(i => i.type === type);
return items.sort((a, b) => {
@@ -81,14 +175,19 @@ export async function createItem({ type, title, description = '', metadata = {}
const items = await loadItems();
- // Prevent duplicate alerts for same reference within 24 hours
+ // Prevent duplicate alerts for same reference within 24 hours. Archive only
+ // ever holds items >=30 days old, so it can never actually match this 24h
+ // window in practice — but check it anyway rather than silently narrowing
+ // the dedup window the day an item crosses into archive.json. Only
+ // consulted when the live scan misses, so the common case (no dedup match,
+ // or a live match) never touches the archive file.
if (type === 'alert' && metadata?.referenceId) {
const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000;
- const duplicate = items.find(i =>
+ const isDuplicate = (i) =>
i.type === 'alert' &&
i.metadata?.referenceId === metadata.referenceId &&
- new Date(i.createdAt).getTime() > oneDayAgo
- );
+ new Date(i.createdAt).getTime() > oneDayAgo;
+ const duplicate = items.find(isDuplicate) ?? (await loadArchive()).find(isDuplicate);
if (duplicate) return duplicate;
}
@@ -155,6 +254,10 @@ export async function dismissItem(id) {
* Concurrent per-item POSTs race on saveItems and silently drop updates;
* this endpoint handles the "Complete All" / "Dismiss All" cases atomically.
* Pass `ids` to target specific items, or omit to target every pending item.
+ * Emits ONE `items:bulk-updated` event carrying every affected id rather than
+ * one `item:updated` per item — "Mark all read" over N pending items used to
+ * fan out N socket broadcasts, each triggering a full counts re-parse on
+ * every connected dashboard client.
*/
export async function bulkUpdateStatus({ ids, status }) {
if (!ITEM_STATUSES.includes(status)) {
@@ -179,7 +282,7 @@ export async function bulkUpdateStatus({ ids, status }) {
await saveItems(items);
console.log(`📋 Review items bulk-${status}: ${updated.length}`);
- for (const item of updated) reviewEvents.emit('item:updated', item);
+ reviewEvents.emit('items:bulk-updated', { ids: updated.map(i => i.id), status, updatedAt: now });
return updated;
}
diff --git a/server/services/review.test.js b/server/services/review.test.js
index d357c87ccc..700ae7d2c1 100644
--- a/server/services/review.test.js
+++ b/server/services/review.test.js
@@ -1,14 +1,13 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { readFile, readdir } from 'fs/promises';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { readFile, readdir, stat } from 'fs/promises';
import { atomicWrite } from '../lib/fileUtils.js';
vi.mock('fs/promises', () => ({
readFile: vi.fn(),
- readdir: vi.fn()
+ readdir: vi.fn(),
+ stat: vi.fn()
}));
-const emit = vi.fn();
-const reviewEvents = { emit };
const registeredHandlers = {};
const cosEvents = {
on: vi.fn((event, handler) => { registeredHandlers[event] = handler; })
@@ -26,9 +25,9 @@ tryReadFile: vi.fn().mockResolvedValue(null),
reports: '/test/data/cos/reports',
root: '/test'
},
- readJSONFile: vi.fn(async (_path, fallback) => {
+ readJSONFile: vi.fn(async (path, fallback) => {
try {
- return JSON.parse(await readFile());
+ return JSON.parse(await readFile(path));
} catch {
return fallback;
}
@@ -43,12 +42,26 @@ const {
dismissItem,
updateItem,
deleteItem,
- getBriefing
+ getBriefing,
+ bulkUpdateStatus,
+ reviewEvents
} = await import('./review.js');
+// `stat()` backs review.js's module-level items.json cache, which persists
+// across every test in this file (it is process/module state, not a vitest
+// mock). The default implementation below returns a fresh, never-repeating
+// value on every call, so — absent a test explicitly overriding it — every
+// `loadItems()` call in this file is a guaranteed cache MISS and re-reads via
+// `readFile`, exactly matching this suite's pre-caching expectations. Tests
+// that exercise the cache itself override `stat` locally to hold a value
+// steady (a hit) or change it (a miss/invalidation).
+let statCounter = 0;
+const freshStat = () => Promise.resolve({ mtimeMs: ++statCounter, size: statCounter });
+
describe('review service', () => {
beforeEach(() => {
vi.clearAllMocks();
+ stat.mockImplementation(freshStat);
});
describe('createItem', () => {
@@ -304,4 +317,201 @@ describe('review service', () => {
expect(atomicWrite).not.toHaveBeenCalled();
});
});
+
+ describe('items.json read cache', () => {
+ it('parses the file once across two consecutive getPendingCounts calls with no write between', async () => {
+ stat.mockResolvedValue({ mtimeMs: 811001, size: 1 });
+ readFile.mockResolvedValueOnce(JSON.stringify([{ id: 'a', type: 'todo', status: 'pending' }]));
+
+ const first = await getPendingCounts();
+ const second = await getPendingCounts();
+
+ expect(first.total).toBe(1);
+ expect(second.total).toBe(1);
+ expect(readFile).toHaveBeenCalledTimes(1);
+ });
+
+ it('detects an external rewrite (changed mtime/size) and re-parses', async () => {
+ stat.mockResolvedValueOnce({ mtimeMs: 812001, size: 100 });
+ readFile.mockResolvedValueOnce(JSON.stringify([{ id: 'a', type: 'todo', status: 'pending' }]));
+ const first = await getPendingCounts();
+ expect(first.total).toBe(1);
+
+ // A different process rewrote items.json — stat now reports a new identity.
+ stat.mockResolvedValueOnce({ mtimeMs: 812002, size: 140 });
+ readFile.mockResolvedValueOnce(JSON.stringify([
+ { id: 'a', type: 'todo', status: 'pending' },
+ { id: 'b', type: 'alert', status: 'pending' }
+ ]));
+ const second = await getPendingCounts();
+
+ expect(second.total).toBe(2);
+ expect(readFile).toHaveBeenCalledTimes(2);
+ });
+
+ it('treats a missing items.json as an empty, cache-cleared list', async () => {
+ const enoent = Object.assign(new Error('ENOENT'), { code: 'ENOENT' });
+ stat.mockRejectedValueOnce(enoent);
+
+ const whileMissing = await getPendingCounts();
+ expect(whileMissing.total).toBe(0);
+ expect(readFile).not.toHaveBeenCalled();
+
+ // The file reappears — the cleared cache must not keep reporting the
+ // pre-deletion (or pre-existence) state.
+ stat.mockResolvedValueOnce({ mtimeMs: 813001, size: 1 });
+ readFile.mockResolvedValueOnce(JSON.stringify([{ id: 'a', type: 'todo', status: 'pending' }]));
+ const afterRecreate = await getPendingCounts();
+ expect(afterRecreate.total).toBe(1);
+ });
+
+ it('reflects a write in the very next read without a second parse', async () => {
+ stat.mockResolvedValueOnce({ mtimeMs: 814001, size: 1 }); // loadItems() inside createItem
+ readFile.mockResolvedValueOnce('[]');
+ stat.mockResolvedValueOnce({ mtimeMs: 814002, size: 2 }); // saveItems' post-write stat
+ stat.mockResolvedValueOnce({ mtimeMs: 814002, size: 2 }); // getPendingCounts' loadItems — same identity
+
+ await createItem({ type: 'todo', title: 'First item' });
+ const counts = await getPendingCounts();
+
+ expect(counts.total).toBe(1);
+ // Only createItem's own cache-miss read — getPendingCounts hit the
+ // cache saveItems seeded from the write, not a re-parse.
+ expect(readFile).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('getItems merges archive.json', () => {
+ it('includes archive for completed/dismissed and unfiltered queries, but not a pending-only query', async () => {
+ stat.mockResolvedValue({ mtimeMs: 816001, size: 1 });
+ const liveItems = [
+ { id: 'live-pending', type: 'todo', status: 'pending', createdAt: '2026-01-01T00:00:00Z' },
+ { id: 'live-completed', type: 'todo', status: 'completed', createdAt: '2026-01-02T00:00:00Z' }
+ ];
+ const archivedItems = [
+ { id: 'archived-completed', type: 'todo', status: 'completed', createdAt: '2025-01-01T00:00:00Z' }
+ ];
+ readFile.mockImplementation((path) =>
+ Promise.resolve(String(path).endsWith('archive.json') ? JSON.stringify(archivedItems) : JSON.stringify(liveItems)));
+
+ const completedView = await getItems({ status: 'completed' });
+ expect(completedView.map(i => i.id).sort()).toEqual(['archived-completed', 'live-completed']);
+
+ const allView = await getItems({});
+ expect(allView.map(i => i.id).sort()).toEqual(['archived-completed', 'live-completed', 'live-pending']);
+
+ const pendingView = await getItems({ status: 'pending' });
+ expect(pendingView.map(i => i.id)).toEqual(['live-pending']);
+ });
+ });
+
+ describe('createItem duplicate check reaches the archive', () => {
+ it('finds a duplicate alert in archive.json when the live scan misses', async () => {
+ stat.mockResolvedValue({ mtimeMs: 817001, size: 1 });
+ // Synthetic fixture: a real archived item is always >=30 days old and
+ // could never actually land inside this 24h dedup window. This exists
+ // to prove createItem's duplicate check reaches archive.json at all
+ // when the live scan misses — not to model a realistic timestamp.
+ const archivedAlert = {
+ id: 'archived-1',
+ type: 'alert',
+ status: 'dismissed',
+ metadata: { referenceId: 'ref-archived' },
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString()
+ };
+ readFile.mockImplementation((path) =>
+ Promise.resolve(String(path).endsWith('archive.json') ? JSON.stringify([archivedAlert]) : '[]'));
+
+ const item = await createItem({
+ type: 'alert',
+ title: 'New alert for same ref',
+ metadata: { referenceId: 'ref-archived' }
+ });
+
+ expect(item.id).toBe('archived-1');
+ expect(atomicWrite).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('retention', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('moves completed/dismissed items older than 30 days into archive.json and keeps pending/recent items in items.json', async () => {
+ vi.useFakeTimers();
+ // Push the clock far enough ahead that the 24h retention-interval gate
+ // is guaranteed open, however recently an earlier test in this file
+ // triggered a save — `lastRetentionAt` is module state shared across
+ // the whole file, not reset between tests.
+ vi.setSystemTime(Date.now() + 1000 * 60 * 60 * 24 * 400);
+
+ const now = Date.now();
+ const old = new Date(now - 31 * 24 * 60 * 60 * 1000).toISOString();
+ const recent = new Date(now - 1 * 24 * 60 * 60 * 1000).toISOString();
+ const fixture = [
+ { id: 'p1', type: 'todo', status: 'pending', metadata: {}, createdAt: old, updatedAt: old },
+ { id: 'c-old', type: 'todo', status: 'completed', metadata: {}, createdAt: old, updatedAt: old },
+ { id: 'd-old', type: 'alert', status: 'dismissed', metadata: {}, createdAt: old, updatedAt: old },
+ { id: 'c-recent', type: 'todo', status: 'completed', metadata: {}, createdAt: recent, updatedAt: recent }
+ ];
+
+ stat.mockResolvedValue({ mtimeMs: 815001, size: 1 });
+ readFile.mockImplementation((path) =>
+ Promise.resolve(String(path).endsWith('archive.json') ? '[]' : JSON.stringify(fixture)));
+
+ await createItem({ type: 'todo', title: 'trigger a save' });
+
+ expect(atomicWrite).toHaveBeenCalledTimes(2);
+ const [archivePath, archiveData] = atomicWrite.mock.calls[0];
+ const [itemsPath, itemsData] = atomicWrite.mock.calls[1];
+
+ expect(archivePath).toMatch(/archive\.json$/);
+ expect(archiveData.map(i => i.id).sort()).toEqual(['c-old', 'd-old']);
+
+ expect(itemsPath).toMatch(/items\.json$/);
+ const survivingIds = itemsData.map(i => i.id);
+ expect(survivingIds).toEqual(expect.arrayContaining(['p1', 'c-recent']));
+ expect(survivingIds).not.toEqual(expect.arrayContaining(['c-old']));
+ expect(survivingIds).not.toEqual(expect.arrayContaining(['d-old']));
+
+ // getPendingCounts must still be correct post-retention, and served
+ // from the cache saveItems just seeded rather than a fresh parse.
+ const counts = await getPendingCounts();
+ expect(counts.total).toBe(2); // p1 + the new item createItem just added
+ expect(readFile).toHaveBeenCalledTimes(2); // items.json once + archive.json once — no third parse
+ });
+ });
+
+ describe('bulkUpdateStatus events', () => {
+ it('emits exactly one items:bulk-updated event and zero per-item item:updated events', async () => {
+ const emitSpy = vi.spyOn(reviewEvents, 'emit');
+ try {
+ stat.mockResolvedValue({ mtimeMs: 818001, size: 1 });
+ const items = [
+ { id: 'a', status: 'pending', metadata: {} },
+ { id: 'b', status: 'pending', metadata: {} },
+ { id: 'c', status: 'completed', metadata: {} }
+ ];
+ readFile.mockResolvedValue(JSON.stringify(items));
+
+ const updated = await bulkUpdateStatus({ status: 'dismissed' });
+
+ expect(updated).toHaveLength(2);
+ const bulkCalls = emitSpy.mock.calls.filter(([event]) => event === 'items:bulk-updated');
+ const perItemCalls = emitSpy.mock.calls.filter(([event]) => event === 'item:updated');
+ expect(bulkCalls).toHaveLength(1);
+ expect(perItemCalls).toHaveLength(0);
+ expect(bulkCalls[0][1]).toEqual({
+ ids: expect.arrayContaining(['a', 'b']),
+ status: 'dismissed',
+ updatedAt: expect.any(String)
+ });
+ expect(bulkCalls[0][1].ids).toHaveLength(2);
+ } finally {
+ emitSpy.mockRestore();
+ }
+ });
+ });
});
diff --git a/server/services/socket.js b/server/services/socket.js
index e74b3ae669..e68c8c30cc 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -529,6 +529,11 @@ function setupReviewEventForwarding() {
reviewEvents.on('item:deleted', (data) => {
if (ioInstance) ioInstance.emit('review:item:deleted', data?.metadata?.privateSecurity ? { id: data.id, metadata: { privateSecurity: true } } : data);
});
+ // Bulk status changes ("Mark all read" / "Complete all") carry only ids, a
+ // status and a timestamp — nothing to redact.
+ reviewEvents.on('items:bulk-updated', (data) => {
+ if (ioInstance) ioInstance.emit('review:items:bulk-updated', data);
+ });
}
// Set up update event forwarding (idempotent — safe if called more than once)