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
feat: paginate remaining privacy + digital-twin list endpoints (#2535)
Adam Eivy037a94896ccf
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d1370b7323..594c4e0757 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -89,3 +89,4 @@- **[issue-2616] Add type-level consecutive-failure backoff with auto-park + notification; count unparseable agent output as failure.** The agent engine had no failure memory at the task-*type* level, so a permanently-broken scheduled type (or one whose instances all fail) re-queued on schedule forever — burning provider quota with no backoff, auto-disable, or notification (`failureCount` lived only in per-instance metadata; ROTATION types had no cadence gate at all, returning `shouldRun: true` unconditionally). A new per-type failure ledger now lives on the schedule execution record (`consecutiveFailures`/`lastFailureAt`/`lastErrorCategory`, per app + global) — persisted alongside `lastRun`, so it survives restarts as per-install runtime state (additive, backward-compatible, never synced). `shouldRunTask` applies an escalating failure cooldown (`2^n × base`, capped at a day) to *all* cadence types including ROTATION, so a failing type slows down instead of re-queuing every tick; after 5 consecutive failures the type auto-parks (indefinitely, for every cadence type) and fires a user-facing `AGENT_WARNING` notification naming the type, app, and last error category. A success resets the counter and lifts the park; a manual "Run now" or a config change (`updateTaskInterval`) clears the ledger to unpark. Separately, an LLM run that exits 0 but whose `.agent-done` output is unparseable — previously recorded as a benign completed success, invisible to any failure accounting — now feeds a failure signal into the ledger via the pure `resolveTypeFailureSignal` (an `unparseable-response` hook reason, or a thrown output hook, counts as a failure regardless of exit code; benign hook reasons like `no-proposal`/`duplicate` defer to the exit code). The existing per-instance retry ladder (`MAX_TASK_RETRIES`/`MAX_TOTAL_SPAWNS`) is unchanged. New unit tests cover the backoff math, ledger increment/reset/auto-park/notify/unpark, the ROTATION cooldown/park gates, and the unparseable-as-failure decision.- **[issue-2535] Paginate the creative-catalog + media list endpoints with the shared `paginateArray` helper.** The primary index `GET`s for creativeDirector (`/`), storyBuilder (`/`), universeBuilder (`/`), moodBoard (`/`), videoTimeline (`/projects`), and loras (`/`) returned unbounded arrays. Each now opts into pagination the moment a client sends `limit`/`offset`, mirroring the `brainCrud` precedent: `isPaginationRequested(req.query)` gates a bounded `{ items, total, limit, offset }` envelope (via the existing `paginateArray` in `server/lib/validation.js`, `defaultLimit: 50`, `maxLimit: 500`), while a request with no pagination params still returns the full array byte-for-byte — so every current client (none of which pass those params to these routes) is unaffected and no client change is required. New route tests assert both the default array and the paginated envelope for each domain (moodBoard gains its first route test). Refs #2535 — CoS tasks (the `?full=1` default-paginated slice) already shipped; privacy vault/orgs/changes/brokers and digital-twin documents remain.+- **[issue-2535] Paginate the remaining privacy + digital-twin list endpoints, completing the sweep.** The last unbounded index `GET`s flagged by #2535 — privacy `/vault`, `/orgs`, `/changes`, `/brokers`, `/broker-cases`, and digital-twin `/documents` — now opt into the shared `paginateArray` envelope exactly like the creative-catalog routes shipped in #2636: `isPaginationRequested(req.query)` gates a bounded `{ items, total, limit, offset }` response (`defaultLimit: 50`, `maxLimit: 500`) the moment a client passes `limit`/`offset`, while a param-less request returns the full array byte-for-byte, so no client change is required. Because the four privacy list-query schemas are `.strict()` (they'd reject unknown keys), a local `paginationQueryFields` fragment (`limit`/`offset` as passthrough strings — `parsePagination` does the parse+clamp) is spread into `privacyVaultListQuerySchema`, `privacyOrgListQuerySchema`, `privacyBrokerListQuerySchema`, and `privacyBrokerCaseListQuerySchema` in `privacyValidation.js`; the `/orgs` handler strips `limit`/`offset` before passing filters to `listOrgs` so pagination never leaks into the service query. New route tests cover the vault/orgs/changes/broker-cases envelopes (filters preserved) and the digital-twin documents envelope. This closes the remaining slice of #2535 (the CoS-tasks default-paginated shape and the creative-catalog/media routes shipped previously).diff --git a/server/lib/privacyValidation.js b/server/lib/privacyValidation.jsindex 7c795e3e92..d7aeba42b5 100644--- a/server/lib/privacyValidation.js+++ b/server/lib/privacyValidation.js@@ -32,6 +32,18 @@ export const PRIVACY_VAULT_STATUSES = Object.freeze(['current', 'previous']);// ISO calendar date (DATE column) — nullable to clear.const isoDateSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'expected YYYY-MM-DD').nullable().optional();+// Opt-in pagination query params (?limit=&offset=) spread into the .strict()+// list-query schemas below so the paginateArray envelope can be requested+// without the strict guard rejecting the keys. Kept as passthrough strings —+// parsePagination (validation.js) does the parseInt + clamp, so garbage falls+// back to the default page rather than 400-ing. Defined locally (not imported+// from validation.js) to avoid a circular import: validation.js re-exports this+// module. Mirror any change into validation.js's parsePagination contract.+const paginationQueryFields = {+ limit: z.string().optional(),+ offset: z.string().optional(),+};+const rejectSensitiveScans = (val, ctx) => {if (val.useForScans === true && PRIVACY_SENSITIVE_TYPES.includes(val.type)) {ctx.addIssue({@@ -71,6 +83,7 @@ export const privacyVaultUpdateSchema = z.object({export const privacyVaultListQuerySchema = z.object({type: z.enum(PRIVACY_VAULT_TYPES).optional(),+ ...paginationQueryFields,}).strict();export const privacyVaultIdParamsSchema = z.object({@@ -130,6 +143,7 @@ export const privacyOrgListQuerySchema = z.object({trust: z.enum(PRIVACY_ORG_TRUST_LEVELS).optional(),status: z.enum(PRIVACY_ORG_STATUSES).optional(),category: z.enum(PRIVACY_ORG_CATEGORIES).optional(),+ ...paginationQueryFields,}).strict();export const privacyOrgIdParamsSchema = z.object({@@ -219,11 +233,13 @@ export const privacyBrokerListQuerySchema = z.object({(v) => (v === undefined ? undefined : v === 'true' || v === true),z.boolean().optional(),),+ ...paginationQueryFields,}).strict();// GET /api/privacy/broker-cases?state=foundexport const privacyBrokerCaseListQuerySchema = z.object({state: z.enum(PRIVACY_BROKER_CASE_STATES).optional(),+ ...paginationQueryFields,}).strict();// POST /api/privacy/brokers/refresh — no body; empty object.diff --git a/server/routes/digital-twin/documents.js b/server/routes/digital-twin/documents.jsindex 3e1484e1c3..dd30492bec 100644--- a/server/routes/digital-twin/documents.js+++ b/server/routes/digital-twin/documents.js@@ -11,7 +11,7 @@import { Router } from 'express';import * as digitalTwinService from '../../services/digital-twin.js';import { asyncHandler, ServerError } from '../../lib/errorHandler.js';-import { validateRequest } from '../../lib/validation.js';+import { validateRequest, isPaginationRequested, paginateArray } from '../../lib/validation.js';import {createDocumentInputSchema,updateDocumentInputSchema,@@ -21,11 +21,14 @@ const router = Router();/*** GET /api/digital-twin/documents- * List all digital twin documents+ * List all digital twin documents. Backward-compatible full array by default;+ * opt into a bounded `{ items, total, limit, offset }` envelope with+ * `?limit=`/`?offset=`.*/router.get('/documents', asyncHandler(async (req, res) => {const documents = await digitalTwinService.getDocuments();- res.json(documents);+ if (!isPaginationRequested(req.query)) return res.json(documents);+ res.json(paginateArray(documents, req.query, { defaultLimit: 50, maxLimit: 500 }));}));/**diff --git a/server/routes/digital-twin/index.test.js b/server/routes/digital-twin/index.test.jsindex 6cc635f636..6793006f9b 100644--- a/server/routes/digital-twin/index.test.js+++ b/server/routes/digital-twin/index.test.js@@ -68,6 +68,19 @@ describe('Digital Twin Routes', () => {expect(res.body).toHaveLength(2);});+ it('GET /documents returns a bounded envelope when pagination is requested (#2535)', async () => {+ digitalTwinService.getDocuments.mockResolvedValue(+ Array.from({ length: 5 }, (_, i) => ({ id: `doc-${i}` })),+ );+ const res = await request(app).get('/api/digital-twin/documents?limit=2&offset=1');+ expect(res.status).toBe(200);+ expect(res.body.items).toHaveLength(2);+ expect(res.body.items[0].id).toBe('doc-1');+ expect(res.body.total).toBe(5);+ expect(res.body.limit).toBe(2);+ expect(res.body.offset).toBe(1);+ });+it('GET /documents/:id returns 404 for an unknown doc', async () => {digitalTwinService.getDocumentById.mockResolvedValue(null);const res = await request(app).get('/api/digital-twin/documents/nope');diff --git a/server/routes/privacy.js b/server/routes/privacy.jsindex 0e3f7acc36..50d93e85db 100644--- a/server/routes/privacy.js+++ b/server/routes/privacy.js@@ -10,7 +10,7 @@import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest } from '../lib/validation.js';+import { validateRequest, isPaginationRequested, paginateArray } from '../lib/validation.js';import {privacyVaultCreateSchema,privacyVaultUpdateSchema,@@ -88,7 +88,9 @@ router.get('/status', asyncHandler(async (_req, res) => {router.get('/vault', asyncHandler(async (req, res) => {const { type } = validateRequest(privacyVaultListQuerySchema, req.query);- res.json(await listVaultRecords({ type }));+ const records = await listVaultRecords({ type });+ if (!isPaginationRequested(req.query)) return res.json(records);+ res.json(paginateArray(records, req.query, { defaultLimit: 50, maxLimit: 500 }));}));router.post('/vault', asyncHandler(async (req, res) => {@@ -122,8 +124,10 @@ router.post('/vault/:id/reveal', asyncHandler(async (req, res) => {// ─── Trusted Organizations registry (issue #2141) ──────────────────────────router.get('/orgs', asyncHandler(async (req, res) => {- const filters = validateRequest(privacyOrgListQuerySchema, req.query);- res.json(await listOrgs(filters));+ const { limit, offset, ...filters } = validateRequest(privacyOrgListQuerySchema, req.query);+ const orgs = await listOrgs(filters);+ if (!isPaginationRequested(req.query)) return res.json(orgs);+ res.json(paginateArray(orgs, req.query, { defaultLimit: 50, maxLimit: 500 }));}));router.post('/orgs', asyncHandler(async (req, res) => {@@ -170,8 +174,10 @@ router.put('/orgs/:id/holdings', asyncHandler(async (req, res) => {// ─── Change-of-address events + inventory workflow (issue #2143) ────────────-router.get('/changes', asyncHandler(async (_req, res) => {- res.json(await listChangeEvents());+router.get('/changes', asyncHandler(async (req, res) => {+ const events = await listChangeEvents();+ if (!isPaginationRequested(req.query)) return res.json(events);+ res.json(paginateArray(events, req.query, { defaultLimit: 50, maxLimit: 500 }));}));router.post('/changes', asyncHandler(async (req, res) => {@@ -203,7 +209,9 @@ router.post('/changes/:id/orgs/:orgId/draft-email', asyncHandler(async (req, resrouter.get('/brokers', asyncHandler(async (req, res) => {const { enabled } = validateRequest(privacyBrokerListQuerySchema, req.query);- res.json(await listBrokers({ enabled }));+ const brokers = await listBrokers({ enabled });+ if (!isPaginationRequested(req.query)) return res.json(brokers);+ res.json(paginateArray(brokers, req.query, { defaultLimit: 50, maxLimit: 500 }));}));// User-triggered refresh (never at boot) — pulls BADBOOL + CA registry, never@@ -223,7 +231,9 @@ router.put('/brokers/:id', asyncHandler(async (req, res) => {router.get('/broker-cases', asyncHandler(async (req, res) => {const { state } = validateRequest(privacyBrokerCaseListQuerySchema, req.query);- res.json(await listBrokerCases({ state }));+ const cases = await listBrokerCases({ state });+ if (!isPaginationRequested(req.query)) return res.json(cases);+ res.json(paginateArray(cases, req.query, { defaultLimit: 50, maxLimit: 500 }));}));// Force a case due for recheck NOW (case drawer "Re-check" control, #2146).diff --git a/server/routes/privacy.test.js b/server/routes/privacy.test.jsindex 2745304a94..b358fd5b9f 100644--- a/server/routes/privacy.test.js+++ b/server/routes/privacy.test.js@@ -114,6 +114,59 @@ describe('GET /api/privacy/vault', () => {});});+// Opt-in pagination (#2535): full array by default, bounded envelope with+// ?limit/?offset. Verified once here for the vault; the orgs/changes/brokers/+// broker-cases + digital-twin routes share the same paginateArray helper.+describe('GET /api/privacy/* pagination', () => {+ it('vault returns a bounded envelope when limit/offset are passed', async () => {+ service.listVaultRecords.mockResolvedValueOnce(+ Array.from({ length: 5 }, (_, i) => ({ id: `r${i}`, type: 'email' })),+ );+ const res = await request(makeApp()).get('/api/privacy/vault?limit=2&offset=1');+ expect(res.status).toBe(200);+ expect(res.body.items).toHaveLength(2);+ expect(res.body.items[0].id).toBe('r1');+ expect(res.body.total).toBe(5);+ expect(res.body.limit).toBe(2);+ expect(res.body.offset).toBe(1);+ });++ it('vault stays a plain array when no pagination param is passed', async () => {+ const res = await request(makeApp()).get('/api/privacy/vault');+ expect(Array.isArray(res.body)).toBe(true);+ });++ it('orgs strips pagination params before filtering the service', async () => {+ const res = await request(makeApp()).get('/api/privacy/orgs?trust=trusted&limit=1');+ expect(res.status).toBe(200);+ expect(orgService.listOrgs).toHaveBeenCalledWith({ trust: 'trusted' });+ expect(res.body.limit).toBe(1);+ expect(Array.isArray(res.body.items)).toBe(true);+ });++ it('broker-cases paginates while preserving the state filter', async () => {+ brokerService.listBrokerCases.mockResolvedValueOnce(+ Array.from({ length: 3 }, (_, i) => ({ id: `case-${i}`, state: 'found' })),+ );+ const res = await request(makeApp()).get('/api/privacy/broker-cases?state=found&limit=2');+ expect(res.status).toBe(200);+ expect(brokerService.listBrokerCases).toHaveBeenCalledWith({ state: 'found' });+ expect(res.body.items).toHaveLength(2);+ expect(res.body.total).toBe(3);+ });++ it('changes paginates the change-event feed', async () => {+ changeService.listChangeEvents.mockResolvedValueOnce(+ Array.from({ length: 4 }, (_, i) => ({ id: `chg-${i}` })),+ );+ const res = await request(makeApp()).get('/api/privacy/changes?limit=1&offset=2');+ expect(res.status).toBe(200);+ expect(res.body.items).toHaveLength(1);+ expect(res.body.items[0].id).toBe('chg-2');+ expect(res.body.total).toBe(4);+ });+});+describe('POST /api/privacy/vault', () => {it('creates a record from a valid body', async () => {const res = await request(makeApp()).post('/api/privacy/vault')