Skip to content

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

feat([issue-1835]): add opt-in limit/offset pagination to brain & CoS list endpoints

[._.]/ Adam Eivy9734abd00854
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 71b39e3e2c..0d9da84efc 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,3 +1,7 @@
+## Brain & CoS API
+
+- **[issue-1835] Brain & CoS list endpoints now support opt-in `limit`/`offset` pagination** — `GET /api/brain/people|projects|ideas|admin|memories` and `GET /api/cos/tasks` previously returned their entire backing store with no bound, while sibling endpoints (`GET /api/brain/links`, `GET /api/memory`) already exposed pagination envelopes. Each of these endpoints now accepts `limit`/`offset` query params: when neither is present they return the exact same shape as before (raw array for the brain collections; the `{ user, cos }` grouped structure for tasks), so every existing client keeps working; when a pagination param is passed they return a bounded `{ <collection>, total, limit, offset }` envelope (tasks window each source's `tasks` array and add a `pagination` block). `limit` defaults to 50 and is clamped to 500. Shared `isPaginationRequested` / `paginateArray` helpers were added to `server/lib/validation.js` alongside the existing `parsePagination`. (#1835)
+
## Security
- **Resolved active `npm audit` CVEs in the kokoro-js → protobufjs chain and the client `ws` transitive** — the server's `[email protected]` pulled `protobufjs <=7.6.0` (GHSA-wcpc-wj8m-hjx6 DoS, GHSA-f38q-mgvj-vph7), and the stale `protobufjs: 7.5.9` override sat *inside* the vulnerable range. Pinned `kokoro-js` to `1.2.0` (the audit-stated fix, still within the code's documented `^1.2.x` compatibility window — `KokoroTTS`/`TextSplitterStream` exports unchanged) and bumped the `protobufjs` override to `7.6.3` in root + `server/package.json`. On the client, `engine.io-client` nested its own `[email protected]` (GHSA-96hv-2xvq-fx4p memory-exhaustion DoS) that the root `ws: 8.21.0` override couldn't reach; added `ws: 8.21.0` to `client/package.json` overrides. Both `npm audit` runs now report 0 vulnerabilities for these chains. (#1823)
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 45d684a131..8dc1a1e825 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -417,6 +417,34 @@ export function parsePagination(query, { defaultLimit = 50, maxLimit = 200 } = {
return { limit, offset };
}
+/**
+ * Did the caller explicitly ask for pagination? True when either `limit` or
+ * `offset` is present in the query string. Lets a list endpoint stay
+ * backward-compatible (return the full array when neither is set) while opting
+ * into a bounded `{ items, total, limit, offset }` envelope the moment a client
+ * passes a pagination param.
+ * @param {object} query - req.query object
+ * @returns {boolean}
+ */
+export function isPaginationRequested(query) {
+ return query?.limit !== undefined || query?.offset !== undefined;
+}
+
+/**
+ * Slice an array into a bounded page using the same limit/offset parsing as
+ * `parsePagination`. Returns the page plus the metadata needed to render the
+ * envelope every paginated PortOS list endpoint shares.
+ * @param {Array} items - the full list (already filtered/sorted by the caller)
+ * @param {object} query - req.query object
+ * @param {object} options - { defaultLimit, maxLimit }
+ * @returns {{ items: Array, total: number, limit: number, offset: number }}
+ */
+export function paginateArray(items, query, options = {}) {
+ const list = Array.isArray(items) ? items : [];
+ const { limit, offset } = parsePagination(query, options);
+ return { items: list.slice(offset, offset + limit), total: list.length, limit, offset };
+}
+
// =============================================================================
// SHARING (cross-network share buckets via cloud-synced folders)
// =============================================================================
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index 2d039c490d..434ba8fd50 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -23,10 +23,55 @@ import {
storyboardShotSchema,
storyboardSceneSchema,
restoreRequestSchema,
- subdirFilterSchema
+ subdirFilterSchema,
+ isPaginationRequested,
+ paginateArray
} from './validation.js';
describe('validation.js', () => {
+ describe('isPaginationRequested', () => {
+ it('is false when neither limit nor offset is present', () => {
+ expect(isPaginationRequested({})).toBe(false);
+ expect(isPaginationRequested({ status: 'active' })).toBe(false);
+ expect(isPaginationRequested(undefined)).toBe(false);
+ });
+
+ it('is true when limit or offset is present (even at zero / empty string)', () => {
+ expect(isPaginationRequested({ limit: '10' })).toBe(true);
+ expect(isPaginationRequested({ offset: '0' })).toBe(true);
+ expect(isPaginationRequested({ limit: '0' })).toBe(true);
+ expect(isPaginationRequested({ offset: '' })).toBe(true);
+ });
+ });
+
+ describe('paginateArray', () => {
+ const items = [1, 2, 3, 4, 5];
+
+ it('windows the array and reports the full total', () => {
+ expect(paginateArray(items, { limit: '2', offset: '1' })).toEqual({
+ items: [2, 3],
+ total: 5,
+ limit: 2,
+ offset: 1
+ });
+ });
+
+ it('clamps limit to maxLimit and falls back to defaultLimit when invalid', () => {
+ expect(paginateArray(items, { limit: '999' }, { defaultLimit: 50, maxLimit: 3 })).toMatchObject({
+ items: [1, 2, 3],
+ limit: 3
+ });
+ expect(paginateArray(items, { limit: '-1' }, { defaultLimit: 4, maxLimit: 100 })).toMatchObject({
+ items: [1, 2, 3, 4],
+ limit: 4
+ });
+ });
+
+ it('tolerates a non-array input by treating it as empty', () => {
+ expect(paginateArray(null, { limit: '5' })).toEqual({ items: [], total: 0, limit: 5, offset: 0 });
+ });
+ });
+
describe('featureProviderConfigSchema', () => {
it('accepts a providerId + model', () => {
const result = featureProviderConfigSchema.safeParse({ providerId: 'codex', model: 'gpt-5' });
diff --git a/server/routes/brain.test.js b/server/routes/brain.test.js
index 16ec5516e3..9e216f85a4 100644
--- a/server/routes/brain.test.js
+++ b/server/routes/brain.test.js
@@ -380,7 +380,7 @@ describe('Brain Routes', () => {
// ===========================================================================
describe('GET /api/brain/people', () => {
- it('should return all people', async () => {
+ it('should return all people as a raw array when no pagination params are passed', async () => {
brainService.getPeople.mockResolvedValue([
{ id: 'people-001', name: 'John' },
{ id: 'people-002', name: 'Jane' }
@@ -389,8 +389,43 @@ describe('Brain Routes', () => {
const response = await request(app).get('/api/brain/people');
expect(response.status).toBe(200);
+ expect(Array.isArray(response.body)).toBe(true);
expect(response.body).toHaveLength(2);
});
+
+ it('should return a bounded envelope when limit/offset are passed', async () => {
+ brainService.getPeople.mockResolvedValue([
+ { id: 'people-001', name: 'John' },
+ { id: 'people-002', name: 'Jane' },
+ { id: 'people-003', name: 'Jim' }
+ ]);
+
+ const response = await request(app).get('/api/brain/people?limit=1&offset=1');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({
+ people: [{ id: 'people-002', name: 'Jane' }],
+ total: 3,
+ limit: 1,
+ offset: 1
+ });
+ });
+
+ it('should treat limit=0 as a pagination request and clamp to the default limit', async () => {
+ brainService.getPeople.mockResolvedValue([
+ { id: 'people-001', name: 'John' },
+ { id: 'people-002', name: 'Jane' }
+ ]);
+
+ const response = await request(app).get('/api/brain/people?limit=0');
+
+ expect(response.status).toBe(200);
+ // limit=0 is invalid → falls back to the default (50), so all rows return
+ // inside the envelope (not the raw array, since pagination was requested).
+ expect(response.body.people).toHaveLength(2);
+ expect(response.body.total).toBe(2);
+ expect(response.body.limit).toBe(50);
+ });
});
describe('GET /api/brain/people/:id', () => {
@@ -634,8 +669,23 @@ describe('Brain Routes', () => {
const response = await request(app).get('/api/brain/memories');
expect(response.status).toBe(200);
+ expect(Array.isArray(response.body)).toBe(true);
expect(response.body).toHaveLength(2);
});
+
+ it('should return a bounded envelope when limit/offset are passed', async () => {
+ brainService.getMemoryEntries.mockResolvedValue([
+ { id: 'mem-001', title: 'Morning jog' },
+ { id: 'mem-002', title: 'Dinner with family' },
+ { id: 'mem-003', title: 'Late-night idea' }
+ ]);
+
+ const response = await request(app).get('/api/brain/memories?limit=2');
+
+ expect(response.status).toBe(200);
+ expect(response.body.memories).toHaveLength(2);
+ expect(response.body).toMatchObject({ total: 3, limit: 2, offset: 0 });
+ });
});
describe('GET /api/brain/memories/:id', () => {
diff --git a/server/routes/brainCrud.js b/server/routes/brainCrud.js
index 266b77116b..eba0cf522c 100644
--- a/server/routes/brainCrud.js
+++ b/server/routes/brainCrud.js
@@ -8,7 +8,7 @@
import { Router } from 'express';
import * as brainService from '../services/brain.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { validateRequest } from '../lib/validation.js';
+import { validateRequest, isPaginationRequested, paginateArray } from '../lib/validation.js';
import { partialWithoutDefaults } from '../lib/zodCompat.js';
import {
peopleInputSchema,
@@ -26,7 +26,11 @@ const router = Router();
router.get('/people', asyncHandler(async (req, res) => {
const people = await brainService.getPeople();
- res.json(people);
+ if (!isPaginationRequested(req.query)) {
+ return res.json(people);
+ }
+ const { items, total, limit, offset } = paginateArray(people, req.query, { defaultLimit: 50, maxLimit: 500 });
+ res.json({ people: items, total, limit, offset });
}));
router.get('/people/:id', asyncHandler(async (req, res) => {
@@ -68,7 +72,11 @@ router.get('/projects', asyncHandler(async (req, res) => {
const { status } = req.query;
const filters = status ? { status } : undefined;
const projects = await brainService.getProjects(filters);
- res.json(projects);
+ if (!isPaginationRequested(req.query)) {
+ return res.json(projects);
+ }
+ const { items, total, limit, offset } = paginateArray(projects, req.query, { defaultLimit: 50, maxLimit: 500 });
+ res.json({ projects: items, total, limit, offset });
}));
router.get('/projects/:id', asyncHandler(async (req, res) => {
@@ -110,7 +118,11 @@ router.get('/ideas', asyncHandler(async (req, res) => {
const { status } = req.query;
const filters = status ? { status } : undefined;
const ideas = await brainService.getIdeas(filters);
- res.json(ideas);
+ if (!isPaginationRequested(req.query)) {
+ return res.json(ideas);
+ }
+ const { items, total, limit, offset } = paginateArray(ideas, req.query, { defaultLimit: 50, maxLimit: 500 });
+ res.json({ ideas: items, total, limit, offset });
}));
router.get('/ideas/:id', asyncHandler(async (req, res) => {
@@ -152,7 +164,11 @@ router.get('/admin', asyncHandler(async (req, res) => {
const { status } = req.query;
const filters = status ? { status } : undefined;
const adminItems = await brainService.getAdminItems(filters);
- res.json(adminItems);
+ if (!isPaginationRequested(req.query)) {
+ return res.json(adminItems);
+ }
+ const { items, total, limit, offset } = paginateArray(adminItems, req.query, { defaultLimit: 50, maxLimit: 500 });
+ res.json({ admin: items, total, limit, offset });
}));
router.get('/admin/:id', asyncHandler(async (req, res) => {
@@ -192,7 +208,11 @@ router.delete('/admin/:id', asyncHandler(async (req, res) => {
router.get('/memories', asyncHandler(async (req, res) => {
const memories = await brainService.getMemoryEntries();
- res.json(memories);
+ if (!isPaginationRequested(req.query)) {
+ return res.json(memories);
+ }
+ const { items, total, limit, offset } = paginateArray(memories, req.query, { defaultLimit: 50, maxLimit: 500 });
+ res.json({ memories: items, total, limit, offset });
}));
router.get('/memories/:id', asyncHandler(async (req, res) => {
diff --git a/server/routes/cos.test.js b/server/routes/cos.test.js
index 1984f6fe7a..d26b980648 100644
--- a/server/routes/cos.test.js
+++ b/server/routes/cos.test.js
@@ -239,6 +239,36 @@ describe('CoS Routes', () => {
expect(response.body).toHaveProperty('user');
expect(response.body).toHaveProperty('cos');
});
+
+ it('should bound each source and add a pagination block when limit/offset are passed', async () => {
+ const mockTasks = {
+ user: {
+ tasks: [{ id: 'u1' }, { id: 'u2' }, { id: 'u3' }],
+ grouped: { pending: [{ id: 'u1' }] }
+ },
+ cos: {
+ tasks: [{ id: 'c1' }, { id: 'c2' }],
+ grouped: {}
+ }
+ };
+ cos.getAllTasks.mockResolvedValue(mockTasks);
+
+ const response = await request(app).get('/api/cos/tasks?limit=1&offset=1');
+
+ expect(response.status).toBe(200);
+ // Inner task arrays are windowed...
+ expect(response.body.user.tasks).toEqual([{ id: 'u2' }]);
+ expect(response.body.cos.tasks).toEqual([{ id: 'c2' }]);
+ // ...but grouped buckets keep reflecting the full set.
+ expect(response.body.user.grouped).toEqual({ pending: [{ id: 'u1' }] });
+ expect(response.body.pagination).toEqual({
+ limit: 1,
+ offset: 1,
+ userTotal: 3,
+ cosTotal: 2,
+ total: 5
+ });
+ });
});
describe('POST /api/cos/tasks', () => {
diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.js
index 0e9ca955a7..2e695374d1 100644
--- a/server/routes/cosTaskRoutes.js
+++ b/server/routes/cosTaskRoutes.js
@@ -21,6 +21,8 @@ import {
normalizeReviewers,
LOCAL_LLM_REVIEWERS,
DEFAULT_REVIEWERS,
+ isPaginationRequested,
+ parsePagination,
} from '../lib/validation.js';
const enhanceTaskSchema = z.object({
@@ -71,10 +73,30 @@ const SLASHDO_COMMANDS = {
const router = Router();
-// GET /api/cos/tasks - Get all tasks
+// GET /api/cos/tasks - Get all tasks (user + internal), grouped by source.
+//
+// Backward-compatible by default: with no pagination params it returns the full
+// `{ user, cos }` structure every existing consumer expects. When a client
+// passes `limit`/`offset`, each source's `tasks` array is bounded to that window
+// (the `grouped` buckets still reflect the full set) and a `pagination` block is
+// added so the caller can page without pulling an unbounded list.
router.get('/tasks', asyncHandler(async (req, res) => {
const tasks = await cos.getAllTasks();
- res.json(tasks);
+ if (!isPaginationRequested(req.query)) {
+ return res.json(tasks);
+ }
+ const { limit, offset } = parsePagination(req.query, { defaultLimit: 50, maxLimit: 500 });
+ const sliceSource = (src) => {
+ const list = Array.isArray(src?.tasks) ? src.tasks : [];
+ return { ...src, tasks: list.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;
+ res.json({
+ user: sliceSource(tasks?.user),
+ cos: sliceSource(tasks?.cos),
+ pagination: { limit, offset, userTotal, cosTotal, total: userTotal + cosTotal }
+ });
}));
// GET /api/cos/tasks/user - Get user tasks