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

perf: bound agent history pages with a completion-order archive index (#7968)

[._.]/ Adam Eivyb453a4280e7b
diff --git a/scripts/lib/migrationOwnedPaths.js b/scripts/lib/migrationOwnedPaths.js
index 51e7c3a64c..6ee952b3b7 100644
--- a/scripts/lib/migrationOwnedPaths.js
+++ b/scripts/lib/migrationOwnedPaths.js
@@ -35,4 +35,9 @@ export const MIGRATION_OWNED_PATHS = new Set([
// authored (or peer-inherited) work; a shipped seed would land first and the
// migration would rewrite shipped defaults where their ledger should be.
'eidoverse/foundations.json',
+ // Migration 406 derives the CoS archive's completion-order projection from the
+ // install's own agent metadata. A shipped seed would land first (setup-data
+ // runs before migrations) and the backfill would then merge this install's
+ // runs into another machine's rows.
+ 'cos/agents/index.order.json',
]);
diff --git a/scripts/migrations/406-cos-agent-completion-order-index.js b/scripts/migrations/406-cos-agent-completion-order-index.js
new file mode 100644
index 0000000000..844416888f
--- /dev/null
+++ b/scripts/migrations/406-cos-agent-completion-order-index.js
@@ -0,0 +1,99 @@
+/**
+ * Backfill the CoS archive's completion-order projection.
+ *
+ * `data/cos/agents/index.json` records only agentId → YYYY-MM-DD, so paging the
+ * completed-run history had to read every `metadata.json` in each day it visited
+ * just to order it — a busy day paid that read again for every page inside it —
+ * and the pending-feedback badge read one archive record per reference to produce
+ * a single number. The sidecar written here (`index.order.json`) carries each
+ * archived run's completion timestamp plus a completed / still-needs-feedback
+ * bitfield, so both readers answer from memory and hydrate only the rows they
+ * return.
+ *
+ * Gated on the presence of its INPUT (`index.json`), never on the absence of its
+ * output: `setup-data.js` runs first, so an output-absence gate plus a shipped
+ * seed is how #6182 replaced a user's records with defaults. This path therefore
+ * ships no `data.reference/` seed and is declared in `migrationOwnedPaths.js`.
+ *
+ * Re-running is safe and cheap: unchanged entries are skipped, rows the index no
+ * longer owns are pruned, and nothing is written when neither happened. The
+ * runtime repairs whatever this misses — an unreadable record, an archive
+ * imported from a peer later — by re-reading that one day and backfilling it.
+ */
+
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { atomicWrite } from '../../server/lib/fileUtils.js';
+import {
+ decodeCompletionOrder,
+ encodeCompletionOrder,
+ projectArchivedAgent,
+ sameCompletionProjection,
+} from '../../server/lib/cosAgentCompletionOrder.js';
+
+const AGENTS_REL = join('data', 'cos', 'agents');
+const INDEX_FILE = 'index.json';
+const ORDER_FILE = 'index.order.json';
+const DATE_BUCKET = /^\d{4}-\d{2}-\d{2}$/;
+// Matches the archive reader's fan-out so a long-lived install does not open
+// every metadata file at once.
+const READ_BATCH_SIZE = 50;
+
+const readJSON = async (path) => {
+ const raw = await readFile(path, 'utf-8').catch(() => null);
+ if (raw === null) return null;
+ try { return JSON.parse(raw); } catch { return null; }
+};
+
+export default {
+ async up({ rootDir }) {
+ const agentsDir = join(rootDir, AGENTS_REL);
+ const index = await readJSON(join(agentsDir, INDEX_FILE));
+ if (index === null) return { projected: 0, reason: 'no-index' };
+ if (typeof index !== 'object' || Array.isArray(index)) {
+ console.warn('⚠️ CoS archive: index.json is not an id→date map — skipping completion-order backfill');
+ return { projected: 0, reason: 'unexpected-shape' };
+ }
+
+ const existing = await readJSON(join(agentsDir, ORDER_FILE));
+ const projections = decodeCompletionOrder(existing);
+ const owned = Object.entries(index)
+ .filter(([agentId, date]) => agentId && typeof date === 'string' && DATE_BUCKET.test(date));
+
+ let projected = 0;
+ let unreadable = 0;
+ for (let i = 0; i < owned.length; i += READ_BATCH_SIZE) {
+ const batch = await Promise.all(owned.slice(i, i + READ_BATCH_SIZE).map(async ([agentId, date]) => {
+ const metadata = await readJSON(join(agentsDir, date, agentId, 'metadata.json'));
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return null;
+ return [agentId, projectArchivedAgent(metadata)];
+ }));
+ for (const entry of batch) {
+ if (!entry) { unreadable += 1; continue; }
+ if (sameCompletionProjection(projections.get(entry[0]), entry[1])) continue;
+ projections.set(entry[0], entry[1]);
+ projected += 1;
+ }
+ }
+
+ const ownedIds = new Set(owned.map(([agentId]) => agentId));
+ let pruned = 0;
+ for (const agentId of projections.keys()) {
+ if (ownedIds.has(agentId)) continue;
+ projections.delete(agentId);
+ pruned += 1;
+ }
+
+ // A decodable file that needs no change is left alone; an absent or
+ // unrecognized one is (re)written even when empty, so the next boot reads a
+ // valid document instead of re-deriving nothing.
+ if (projected === 0 && pruned === 0 && existing !== null && decodeCompletionOrder(existing).size === projections.size) {
+ return { projected: 0, pruned: 0, unreadable };
+ }
+
+ await atomicWrite(join(agentsDir, ORDER_FILE), encodeCompletionOrder(projections));
+ const suffix = unreadable > 0 ? `, ${unreadable} unreadable archive(s) left for the runtime to repair` : '';
+ console.log(`📇 CoS archive: projected completion order for ${projected} run(s)${suffix}`);
+ return { projected, pruned, unreadable };
+ },
+};
diff --git a/scripts/migrations/406-cos-agent-completion-order-index.test.js b/scripts/migrations/406-cos-agent-completion-order-index.test.js
new file mode 100644
index 0000000000..81a9cc41d1
--- /dev/null
+++ b/scripts/migrations/406-cos-agent-completion-order-index.test.js
@@ -0,0 +1,102 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { mkdtemp, mkdir, readFile, rm, stat, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration from './406-cos-agent-completion-order-index.js';
+import { decodeCompletionOrder } from '../../server/lib/cosAgentCompletionOrder.js';
+
+const AGENTS_REL = join('data', 'cos', 'agents');
+
+let rootDir;
+
+const agentsDir = () => join(rootDir, AGENTS_REL);
+const orderPath = () => join(agentsDir(), 'index.order.json');
+
+const archived = (id, day, overrides = {}) => ({
+ id,
+ status: 'completed',
+ completedAt: `${day}T09:30:00.000Z`,
+ metadata: { taskType: 'user', taskDescription: `Example run ${id}` },
+ ...overrides,
+});
+
+const seed = async (records) => {
+ await mkdir(agentsDir(), { recursive: true });
+ const index = {};
+ for (const record of records) {
+ const day = record.completedAt.slice(0, 10);
+ index[record.id] = day;
+ const dir = join(agentsDir(), day, record.id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(join(dir, 'metadata.json'), JSON.stringify(record));
+ }
+ await writeFile(join(agentsDir(), 'index.json'), JSON.stringify(index));
+ return index;
+};
+
+const readProjections = async () => decodeCompletionOrder(JSON.parse(await readFile(orderPath(), 'utf-8')));
+
+afterEach(async () => {
+ if (rootDir) await rm(rootDir, { recursive: true, force: true });
+ rootDir = null;
+});
+
+describe('migration 406 — CoS archive completion-order projection', () => {
+ it('projects every indexed archive, recording completion order and feedback eligibility', async () => {
+ rootDir = await mkdtemp(join(tmpdir(), 'portos-migration-406-'));
+ await seed([
+ archived('agent-open', '2026-04-01'),
+ archived('agent-rated', '2026-04-01', { feedback: { rating: 'positive', comment: null, submittedAt: '2026-04-02T00:00:00.000Z' } }),
+ archived('agent-scheduled', '2026-04-02', { metadata: { taskType: 'internal' } }),
+ ]);
+
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ projected: 3, pruned: 0, unreadable: 0 });
+
+ const projections = await readProjections();
+ expect(projections.get('agent-open')).toEqual({
+ completedAt: '2026-04-01T09:30:00.000Z', completed: true, feedbackEligible: true,
+ });
+ // A rated run and a scheduled (non-user) run both order a page, but neither
+ // is still an answerable feedback ask.
+ expect(projections.get('agent-rated').feedbackEligible).toBe(false);
+ expect(projections.get('agent-scheduled')).toEqual({
+ completedAt: '2026-04-02T09:30:00.000Z', completed: true, feedbackEligible: false,
+ });
+ });
+
+ it('gates on the presence of its INPUT, never the absence of its output', async () => {
+ rootDir = await mkdtemp(join(tmpdir(), 'portos-migration-406-'));
+ await mkdir(agentsDir(), { recursive: true });
+
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ projected: 0, reason: 'no-index' });
+ await expect(stat(orderPath())).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it('re-runs without rewriting, and drops a projection the index no longer owns', async () => {
+ rootDir = await mkdtemp(join(tmpdir(), 'portos-migration-406-'));
+ const index = await seed([archived('agent-kept', '2026-04-03'), archived('agent-gone', '2026-04-03')]);
+ await migration.up({ rootDir });
+ const firstWrite = (await stat(orderPath())).mtimeMs;
+
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ projected: 0, pruned: 0 });
+ expect((await stat(orderPath())).mtimeMs).toBe(firstWrite);
+
+ delete index['agent-gone'];
+ await writeFile(join(agentsDir(), 'index.json'), JSON.stringify(index));
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ projected: 0, pruned: 1 });
+ expect([...(await readProjections()).keys()]).toEqual(['agent-kept']);
+ });
+
+ it('leaves an unreadable archive for the runtime to repair instead of guessing at it', async () => {
+ rootDir = await mkdtemp(join(tmpdir(), 'portos-migration-406-'));
+ await seed([archived('agent-readable', '2026-04-04')]);
+ await mkdir(join(agentsDir(), '2026-04-04', 'agent-broken'), { recursive: true });
+ await writeFile(join(agentsDir(), '2026-04-04', 'agent-broken', 'metadata.json'), '{ truncated');
+ await writeFile(join(agentsDir(), 'index.json'), JSON.stringify({
+ 'agent-readable': '2026-04-04', 'agent-broken': '2026-04-04',
+ }));
+
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ projected: 1, unreadable: 1 });
+ expect([...(await readProjections()).keys()]).toEqual(['agent-readable']);
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index af2f69d300..4b35db2e4c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -52,6 +52,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `spriteAnimationTracks.js` | The animation-track registry (`ANIMATION_TRACKS`, `WALK_TRACK`, `TRACK_BOUND_TRIPLES`, `AUTHORED_TRACK_FIELDS`) — a zero-import table of per-track frame/fps bounds. |
| `spriteAnimationTrackStore.js` | The EFFECTIVE track table — compiled built-ins plus the user-defined store read from one small JSON config, so sprite schemas stay module-load constants rather than lazily-built. |
| `agentOutcome.js` | Is a completed CoS agent record an OUTCOME, or a HANDOFF to its own continuation? `isAgentHandoff(agent)` — `result.resumed === true`, what `resumeAgent`/`relaunchAgent` stamps when it retires a record and requeues the SAME task, typically because the user swapped providers after a usage limit. Every consumer that read `result.success` as the verdict booked a phantom failure per swap — a red history card, a failed task in the daily report and weekly digest, a dented success rate, a quota-burn denial recorded against "Relaunched by user", a feature agent flipped to `error` — so the rule task-learning already applied lives here once. Reads only `result`, so `completeAgent`'s stats writer can ask it before the record exists. Keyed on a field `resumeAgent` has always written, so archived relaunches reclassify retroactively with no migration. Also carries `agentHandoffReason(agent)` — `metadata.pauseReason` when a continuation was queued, else `result.error`, so an abandoned run is not captioned as a deliberate provider swap — and `isQueuedContinuation(agent)`, the narrower check for a caller about to SKIP its own completion handling because it expects a continuation run to fire it instead: `isAgentHandoff` alone is not proof a continuation exists (a stranded pause retirement also stamps `resumed: true` with nothing requeued), so use this one there. `client/src/lib/agentOutcome.js` re-exports this file rather than copying it. |
+| `cosAgentCompletionOrder.js` | Wire format + projection rule for the CoS archive completion-order sidecar (`data/cos/agents/index.order.json`). `projectArchivedAgent` reduces an archived record to its completion timestamp plus a completed / still-needs-feedback bitfield; `encodeCompletionOrder` / `decodeCompletionOrder` round-trip the versioned document, decoding anything unrecognized as empty so the readers repair it by re-reading the day. Shared by the runtime index and the one-shot backfill migration so the two cannot drift. |
| `cosAgentFeedback.js` | Pure shared eligibility, rating, update-target, and archive-locator predicates for durable CoS feedback actions; mirrored to the client so the queue and Agents tab use the server contract. |
| `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). |
| `agentRunEvents.js` | CoS run lifecycle-event envelope (#4540) — pure half of the append-only ledger in `services/agentRunEventLog.js`. `AGENT_RUN_EVENT_KINDS` (closed vocabulary: spawned, handoff, output, reconnected, paused, resumed, interrupted, pr-verified, orphan-recovered, runner-recovered, finalized), `agentRunEventSchema` (Zod, `.strict()`), `buildRunEvent()` which redacts then mints a CONTENT-derived `eventId` (sha256 of the canonicalized envelope) so a redelivered lifecycle transition dedupes instead of double-counting, `redactRunEventData()` (drops prompt/description/output/result-class keys to a `{ redacted, chars }` stub, scrubs the home-dir prefix out of every remaining string via `scrubHomePath`, runs `redactOutput`, and caps string/array/key/depth per `RUN_EVENT_LIMITS`), and `projectRunStates()` — the clock-free fold that derives current run status from the ordered stream, so replay-after-restart and read-current-status are one code path. Unknown kinds fold as no-ops so a newer install's ledger replays on an older one. |
diff --git a/server/lib/cosAgentCompletionOrder.js b/server/lib/cosAgentCompletionOrder.js
new file mode 100644
index 0000000000..3272b405e1
--- /dev/null
+++ b/server/lib/cosAgentCompletionOrder.js
@@ -0,0 +1,85 @@
+/**
+ * Wire format for the CoS archive's completion-order projection.
+ *
+ * `data/cos/agents/index.json` maps agentId → YYYY-MM-DD and nothing else, so
+ * ordering a page of completed runs meant reading every `metadata.json` in each
+ * visited day. The sidecar this module encodes carries the two facts the readers
+ * actually need — when a run completed, and whether its archived record is still
+ * an unrated feedback target — so pagination and the feedback badge answer from
+ * memory and hydrate only the rows they return.
+ *
+ * Pure so the runtime index (`server/services/cosAgentCompletionIndex.js`) and
+ * the one-shot backfill (`scripts/migrations/406-…`) cannot drift on the
+ * encoding or on what "eligible" means.
+ *
+ * The projection is DERIVED: every entry is rebuildable from the metadata it
+ * describes, so an absent, truncated, or unrecognized-version file decodes to an
+ * empty map rather than an error, and the readers fall back to reading the day.
+ */
+
+import { hasValidAgentFeedback, isAgentFeedbackTarget } from './cosAgentFeedback.js';
+
+/** Bumped when the encoded tuple changes shape; an unknown version decodes as absent. */
+export const COMPLETION_ORDER_VERSION = 1;
+
+// A compact bitfield rather than named keys: this file carries one entry per
+// archived run, and a 10k-run install pays for every byte of key repetition.
+export const COMPLETION_FLAG_COMPLETED = 1;
+export const COMPLETION_FLAG_FEEDBACK_ELIGIBLE = 2;
+
+/**
+ * Project one archived metadata record down to what the readers need. `status`
+ * defaults to `completed` exactly as the archive reader does, so a record
+ * written before the field was persisted is not misfiled as non-completed.
+ */
+export function projectArchivedAgent(agent) {
+ const record = { ...agent, status: agent?.status || 'completed' };
+ return {
+ completedAt: typeof record.completedAt === 'string' ? record.completedAt : null,
+ completed: record.status === 'completed',
+ feedbackEligible: isAgentFeedbackTarget(record) && !hasValidAgentFeedback(record),
+ };
+}
+
+/** True when two projections say the same thing — the write-skip check. */
+export function sameCompletionProjection(a, b) {
+ return !!a && !!b && a.completedAt === b.completedAt
+ && a.completed === b.completed && a.feedbackEligible === b.feedbackEligible;
+}
+
+/** Encode an agentId → projection Map into the on-disk document. */
+export function encodeCompletionOrder(projections) {
+ const entries = {};
+ for (const [agentId, entry] of projections) {
+ entries[agentId] = [
+ entry.completedAt || null,
+ (entry.completed ? COMPLETION_FLAG_COMPLETED : 0)
+ | (entry.feedbackEligible ? COMPLETION_FLAG_FEEDBACK_ELIGIBLE : 0),
+ ];
+ }
+ return { version: COMPLETION_ORDER_VERSION, entries };
+}
+
+/**
+ * Decode the on-disk document. Anything unrecognized — a missing file, a
+ * truncated write, a document a NEWER install wrote — yields an empty map, which
+ * the readers repair by re-reading the days they visit.
+ */
+export function decodeCompletionOrder(raw) {
+ const projections = new Map();
+ if (!raw || typeof raw !== 'object' || raw.version !== COMPLETION_ORDER_VERSION) return projections;
+ const encoded = raw.entries;
+ if (!encoded || typeof encoded !== 'object' || Array.isArray(encoded)) return projections;
+ for (const [agentId, value] of Object.entries(encoded)) {
+ if (!Array.isArray(value) || value.length < 2) continue;
+ const [completedAt, flags] = value;
+ if (completedAt !== null && typeof completedAt !== 'string') continue;
+ if (!Number.isInteger(flags)) continue;
+ projections.set(agentId, {
+ completedAt: completedAt || null,
+ completed: (flags & COMPLETION_FLAG_COMPLETED) !== 0,
+ feedbackEligible: (flags & COMPLETION_FLAG_FEEDBACK_ELIGIBLE) !== 0,
+ });
+ }
+ return projections;
+}
diff --git a/server/lib/cosAgentCompletionOrder.test.js b/server/lib/cosAgentCompletionOrder.test.js
new file mode 100644
index 0000000000..7cf0fb2ddf
--- /dev/null
+++ b/server/lib/cosAgentCompletionOrder.test.js
@@ -0,0 +1,71 @@
+/**
+ * The cross-version contract for the archive's completion-order sidecar (#7968).
+ * Nothing above this module can pin it: the pagination and feedback suites only
+ * ever meet a document this same code wrote, so a document written by a NEWER
+ * install — or a write truncated mid-flight — is exercised only here.
+ */
+import { describe, expect, it } from 'vitest';
+import {
+ COMPLETION_ORDER_VERSION,
+ decodeCompletionOrder,
+ encodeCompletionOrder,
+ projectArchivedAgent,
+ sameCompletionProjection,
+} from './cosAgentCompletionOrder.js';
+
+const projection = (overrides = {}) => ({
+ completedAt: '2026-05-06T08:00:00.000Z', completed: true, feedbackEligible: true, ...overrides,
+});
+
+describe('completion-order projection', () => {
+ it('records completion order and whether the run is still an answerable feedback ask', () => {
+ const base = { id: 'agent-example', status: 'completed', completedAt: '2026-05-06T08:00:00.000Z', metadata: { taskType: 'user' } };
+ expect(projectArchivedAgent(base)).toEqual(projection());
+ expect(projectArchivedAgent({ ...base, feedback: { rating: 'neutral' } }).feedbackEligible).toBe(false);
+ expect(projectArchivedAgent({ ...base, metadata: { taskType: 'internal' } }).feedbackEligible).toBe(false);
+ expect(projectArchivedAgent({ ...base, status: 'running' })).toMatchObject({ completed: false, feedbackEligible: false });
+ // Archives written before `status` was persisted read as completed, matching
+ // the archive reader — otherwise they would silently drop out of history.
+ expect(projectArchivedAgent({ ...base, status: undefined }).completed).toBe(true);
+ // A completed record with no timestamp still orders (last within its day).
+ expect(projectArchivedAgent({ ...base, completedAt: undefined }).completedAt).toBeNull();
+ });
+});
+
+describe('completion-order document', () => {
+ it('round-trips every projection through the compact encoding', () => {
+ const source = new Map([
+ ['agent-a', projection()],
+ ['agent-b', projection({ feedbackEligible: false })],
+ ['agent-c', projection({ completedAt: null, completed: false, feedbackEligible: false })],
+ ]);
+ expect(decodeCompletionOrder(encodeCompletionOrder(source))).toEqual(source);
+ });
+
+ it('decodes a document from an unrecognized version as absent rather than misreading it', () => {
+ const encoded = encodeCompletionOrder(new Map([['agent-a', projection()]]));
+ expect(decodeCompletionOrder({ ...encoded, version: COMPLETION_ORDER_VERSION + 1 }).size).toBe(0);
+ expect(decodeCompletionOrder({ ...encoded, version: undefined }).size).toBe(0);
+ expect(decodeCompletionOrder(null).size).toBe(0);
+ expect(decodeCompletionOrder({ version: COMPLETION_ORDER_VERSION, entries: [] }).size).toBe(0);
+ });
+
+ it('skips a malformed row instead of admitting it with invented values', () => {
+ const decoded = decodeCompletionOrder({
+ version: COMPLETION_ORDER_VERSION,
+ entries: {
+ 'agent-ok': ['2026-05-06T08:00:00.000Z', 3],
+ 'agent-short': ['2026-05-06T08:00:00.000Z'],
+ 'agent-bad-flags': ['2026-05-06T08:00:00.000Z', 'eligible'],
+ 'agent-bad-stamp': [1746518400000, 3],
+ },
+ });
+ expect([...decoded.keys()]).toEqual(['agent-ok']);
+ });
+
+ it('treats an unknown id as different from every projection, so a first write is never skipped', () => {
+ expect(sameCompletionProjection(undefined, projection())).toBe(false);
+ expect(sameCompletionProjection(projection(), projection())).toBe(true);
+ expect(sameCompletionProjection(projection(), projection({ feedbackEligible: false }))).toBe(false);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index f46c5927a0..158840ea26 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -325,6 +325,7 @@ export * from './zipWriter.js';
// === Process execution ===
export * from './agentGuard/index.js';
export * from './agentOutcome.js';
+export * from './cosAgentCompletionOrder.js';
export * from './cosAgentFeedback.js';
export * from './agentOutputMarkers.js';
export * from './agentRunEvents.js';
diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.js
index 3a8d5fd248..6b60d351d7 100644
--- a/server/routes/cosAgentRoutes.js
+++ b/server/routes/cosAgentRoutes.js
@@ -101,20 +101,23 @@ router.get('/agents/history/:date', asyncHandler(async (req, res) => {
// GET /api/cos/agents/feedback/pending - Reconciled durable feedback actions.
// The queue owns the action mutation; this endpoint feeds the Agents tab with
// the same live/archive predicate and count without loading every date bucket.
+//
+// The scalar badge and the paged list answer from the completion-order
+// eligibility projection and hydrate only the rows they return; the unpaged
+// form is the one that also reconciles the durable references and reports the
+// archives it could not read.
router.get('/agents/feedback/pending', asyncHandler(async (req, res) => {
const { limit, cursor, countOnly } = validateRequest(z.object({
countOnly: z.literal('1').optional(),
limit: z.coerce.number().int().min(1).max(100).optional(),
cursor: z.string().max(512).optional(),
}), req.query);
- const pending = await cos.getPendingAgentFeedback({ includeUnavailable: true });
- if (countOnly) return res.json({ count: pending.count });
+ if (countOnly) return res.json({ count: await cos.getPendingAgentFeedbackCount() });
if (limit) {
- const ordered = pending.agents.sort((a, b) => a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
- const remaining = ordered.filter(agent => !cursor || agent.id < cursor);
- return res.json({ items: toAgentListItems(remaining.slice(0, limit)), total: pending.count,
- nextCursor: remaining.length > limit ? remaining[limit - 1].id : null });
+ const page = await cos.getPendingAgentFeedbackPage({ limit, cursor });
+ return res.json({ ...page, items: toAgentListItems(page.items) });
}
+ const pending = await cos.getPendingAgentFeedback({ includeUnavailable: true });
res.json({
count: pending.count,
agents: toAgentListItems(pending.agents),
diff --git a/server/services/cos.js b/server/services/cos.js
index abb27be6db..e73036f1a9 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -74,6 +74,7 @@ export {
getFeedbackStats,
getPendingAgentFeedback,
getPendingAgentFeedbackCount,
+ getPendingAgentFeedbackPage,
initializeAgentFeedback,
extractTaskType,
} from './cosAgentFeedback.js';
diff --git a/server/services/cosAgentArchive.js b/server/services/cosAgentArchive.js
index 304f7c7dc9..a994545104 100644
--- a/server/services/cosAgentArchive.js
+++ b/server/services/cosAgentArchive.js
@@ -15,7 +15,7 @@ import { join } from 'path';
import { cosEvents } from './cosEvents.js';
import { loadState, saveState, withStateLock, AGENTS_DIR } from './cosState.js';
import { atomicWrite, ensureDir, tryReadFile } from '../lib/fileUtils.js';
-import { loadAgentIndex, saveAgentIndex } from './cosAgentIndex.js';
+import { loadAgentIndex, saveAgentIndex, recordArchivedAgentOrder } from './cosAgentIndex.js';
// Archive stale completed agents from state.json.
// Completed agents are already persisted to per-agent metadata files on disk
@@ -37,6 +37,7 @@ export async function archiveStaleAgents() {
if (staleIds.length === 0) return { archived: 0 };
const idx = await loadAgentIndex();
+ const archived = [];
for (const id of staleIds) {
// Ensure agent is persisted to date-bucketed disk before removing from state
@@ -70,12 +71,16 @@ export async function archiveStaleAgents() {
}
idx.set(id, dateStr);
+ archived.push({ ...agent, id });
}
delete state.agents[id];
}
await saveState(state);
+ // Ordered before `saveAgentIndex`, which prunes the projection to the ids
+ // the index owns.
+ await recordArchivedAgentOrder(archived);
await saveAgentIndex();
console.log(`📦 Archived ${staleIds.length} stale agents from state.json (retained on disk)`);
cosEvents.emit('agents:changed', { action: 'auto-archive', archived: staleIds.length });
diff --git a/server/services/cosAgentCompletionIndex.js b/server/services/cosAgentCompletionIndex.js
new file mode 100644
index 0000000000..589ee3c63f
--- /dev/null
+++ b/server/services/cosAgentCompletionIndex.js
@@ -0,0 +1,121 @@
+/**
+ * CoS Agent Completion-Order Index
+ *
+ * The on-disk home and in-process cache for the archive's completion-order
+ * projection (`data/cos/agents/index.order.json`). The wire format, the
+ * projection rule, and what "still needs feedback" means live in the pure
+ * `lib/cosAgentCompletionOrder.js` so the one-shot backfill migration cannot
+ * drift from the runtime.
+ *
+ * Why a sidecar rather than a new shape for `index.json`: an older install, a
+ * rollback, and the federation import path all keep reading the legacy id→date
+ * map unchanged and simply find this file absent. It is DERIVED state, so a
+ * missing or unreadable file is never an error — `getCompletedAgentPage` falls
+ * back to reading the day and backfills what it learns.
+ *
+ * The keyspace is a subset of the legacy index's: `saveAgentIndex()` prunes every
+ * id the index no longer owns, so deletion, retention pruning, and the
+ * clear-completed sweep need no call site of their own.
+ */
+
+import { join } from 'node:path';
+import { AGENTS_DIR } from './cosState.js';
+import { atomicWrite, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+import {
+ decodeCompletionOrder,
+ encodeCompletionOrder,
+ sameCompletionProjection,
+} from '../lib/cosAgentCompletionOrder.js';
+
+export { COMPLETION_ORDER_VERSION, projectArchivedAgent } from '../lib/cosAgentCompletionOrder.js';
+
+/** Relative to `data/cos/agents/`; also the path the backfill migration writes. */
+export const COMPLETION_ORDER_FILENAME = 'index.order.json';
+
+const orderFilePath = () => join(AGENTS_DIR, COMPLETION_ORDER_FILENAME);
+const queueWrite = createFileWriteQueue();
+
+let orderIndex = null;
+let orderIndexPromise = null;
+
+// Derived state: a failed write costs the next reader one day-read, never the
+// caller's operation, so the error is reported here and swallowed.
+function flush() {
+ return queueWrite(async () => {
+ if (!orderIndex) return;
+ await ensureDir(AGENTS_DIR);
+ await atomicWrite(orderFilePath(), encodeCompletionOrder(orderIndex));
+ }).catch((err) => {
+ console.error(`❌ Failed to save agent completion-order index: ${err.message}`);
+ });
+}
+
+/** Lazily read the projection. Absent / corrupt / future-version all read as empty. */
+export async function loadCompletionOrderIndex() {
+ if (orderIndex) return orderIndex;
+ if (orderIndexPromise) return orderIndexPromise;
+
+ orderIndexPromise = (async () => {
+ const content = await tryReadFile(orderFilePath());
+ orderIndex = decodeCompletionOrder(safeJSONParse(content ?? 'null', null));
+ return orderIndex;
+ })().catch((err) => {
+ orderIndexPromise = null;
+ throw err;
+ });
+
+ return orderIndexPromise;
+}
+
+/**
+ * Upsert projections for archived runs. Takes `[agentId, projection]` pairs so a
+ * batch — an archive sweep, or a day backfilled after a federation import —
+ * costs one write. Returns how many entries actually changed.
+ */
+export async function recordArchivedCompletions(pairs) {
+ if (!pairs || pairs.length === 0) return 0;
+ const index = await loadCompletionOrderIndex();
+ let changed = 0;
+ for (const [agentId, entry] of pairs) {
+ if (typeof agentId !== 'string' || !agentId || !entry) continue;
+ if (sameCompletionProjection(index.get(agentId), entry)) continue;
+ index.set(agentId, entry);
+ changed += 1;
+ }
+ if (changed > 0) await flush();
+ return changed;
+}
+
+/** Clear the eligibility bit once a run has been rated. No-op for an unknown id. */
+export async function markCompletionFeedbackResolved(agentId) {
+ const index = await loadCompletionOrderIndex();
+ const entry = index.get(agentId);
+ if (!entry?.feedbackEligible) return false;
+ index.set(agentId, { ...entry, feedbackEligible: false });
+ await flush();
+ return true;
+}
+
+/**
+ * Drop every projection the legacy index no longer owns. Called from
+ * `saveAgentIndex()`, which every delete / retention-prune / clear-completed
+ * path already goes through.
+ */
+export async function pruneCompletionOrderIndex(validIds) {
+ const index = await loadCompletionOrderIndex();
+ let pruned = 0;
+ for (const agentId of index.keys()) {
+ if (validIds.has(agentId)) continue;
+ index.delete(agentId);
+ pruned += 1;
+ }
+ if (pruned > 0) await flush();
+ return pruned;
+}
+
+/** Test seam for suites that swap AGENTS_DIR between cases. */
+export function resetCompletionOrderIndex() {
+ orderIndex = null;
+ orderIndexPromise = null;
+}
diff --git a/server/services/cosAgentFeedback.js b/server/services/cosAgentFeedback.js
index aa6d9365fd..70d8ea1020 100644
--- a/server/services/cosAgentFeedback.js
+++ b/server/services/cosAgentFeedback.js
@@ -14,6 +14,12 @@ import { cosEvents, emitLog } from './cosEvents.js';
import { loadState, saveState, withStateLock } from './cosState.js';
import { atomicWrite, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { loadAgentIndex, getAgentDir } from './cosAgentIndex.js';
+import {
+ loadCompletionOrderIndex,
+ markCompletionFeedbackResolved,
+ projectArchivedAgent,
+ recordArchivedCompletions,
+} from './cosAgentCompletionIndex.js';
import { ServerError } from '../lib/errorHandler.js';
import { recordUserAction } from './userActions.js';
import {
@@ -94,18 +100,19 @@ function unavailableFeedbackRef(ref, reason) {
}
/**
- * Reconcile the durable references with live state and indexed archive records.
- * The only broad read here is live state plus the referenced archive files; it
- * never scans the historical archive looking for work.
+ * The durable references to consider, paired with live state.
+ *
+ * Enrollment happens here rather than only on the `agent:completed` event so a
+ * live completion stays discoverable when the event arrived during a restart
+ * window or before the migration ran — every reader of the pending set needs
+ * that, so it belongs on the one path all of them take.
*/
-export async function getPendingAgentFeedback({ includeUnavailable = false } = {}) {
+async function collectPendingFeedbackRefs() {
const state = await loadState();
const refs = await listPendingAgentFeedbackRefs();
const refsById = new Map(refs.map((ref) => [ref.agentId, ref]));
const liveById = new Map(Object.entries(state?.agents || {}).map(([id, agent]) => [agent.id || id, agent]));
- // Enrollment is also performed here so a live completion remains discoverable
- // when an event arrived during a restart window or before the migration ran.
for (const [agentId, agent] of liveById) {
if (!isAgentFeedbackEligible(agent)) continue;
const ref = { agentId, archiveDate: feedbackArchiveDate(agent) };
@@ -113,9 +120,23 @@ export async function getPendingAgentFeedback({ includeUnavailable = false } = {
await upsertPendingAgentFeedbackRef(ref);
}
+ return { refsById, liveById };
+}
+
+/**
+ * Reconcile the durable references with live state and indexed archive records.
+ * The only broad read here is live state plus the referenced archive files; it
+ * never scans the historical archive looking for work.
+ */
+export async function getPendingAgentFeedback({ includeUnavailable = false } = {}) {
+ const { refsById, liveById } = await collectPendingFeedbackRefs();
+
const idx = refsById.size > 0 ? await loadAgentIndex() : new Map();
const agents = [];
const unavailable = [];
+ // This path already paid for the archive read, so hand what it learned to the
+ // eligibility projection the scalar/paged readers answer from.
+ const learned = [];
for (const ref of refsById.values()) {
const live = liveById.get(ref.agentId);
@@ -157,6 +178,7 @@ export async function getPendingAgentFeedback({ includeUnavailable = false } = {
if (includeUnavailable) unavailable.push(unavailableFeedbackRef({ ...ref, archiveDate }, 'deleted'));
continue;
}
+ if (idx.has(ref.agentId)) learned.push([ref.agentId, projectArchivedAgent(archived.agent)]);
if (!isAgentFeedbackTarget(archived.agent) || hasValidFeedback(archived.agent)) {
await removePendingAgentFeedbackRef(ref.agentId);
continue;
@@ -164,11 +186,86 @@ export async function getPendingAgentFeedback({ includeUnavailable = false } = {
agents.push(archived.agent);
}
+ if (learned.length > 0) await recordArchivedCompletions(learned);
return { agents, unavailable, count: agents.length };
}
+/**
+ * Which pending references are still actionable, resolved WITHOUT reading the
+ * archive: a live record answers from state, an archived one from the
+ * completion-order projection. Only a reference the projection has never seen —
+ * a fresh federation import, or an install that has not run the backfill — costs
+ * one metadata read, and that read teaches the projection so the next call is
+ * free. Deliberately read-only apart from live enrollment: the scalar badge and
+ * the paged list must not reconcile the durable store, which
+ * `getPendingAgentFeedback` owns.
+ */
+async function resolveEligiblePendingFeedback() {
+ const { refsById, liveById } = await collectPendingFeedbackRefs();
+ if (refsById.size === 0) return [];
+ const idx = await loadAgentIndex();
+ const order = await loadCompletionOrderIndex();
+ const eligible = [];
+ const learned = [];
+
+ for (const ref of refsById.values()) {
+ const live = liveById.get(ref.agentId);
+ if (live) {
+ if (isAgentFeedbackEligible(live)) eligible.push({ agentId: ref.agentId, agent: live });
+ continue;
+ }
+
+ const archiveDate = idx.get(ref.agentId) || ref.archiveDate;
+ if (!archiveDate) continue;
+
+ // The projection's keyspace is the index's, so consult it only for an id the
+ // index still owns — anything else would be learned and immediately pruned.
+ const indexed = idx.has(ref.agentId);
+ const projected = indexed ? order.get(ref.agentId) : null;
+ if (projected) {
+ if (projected.feedbackEligible) eligible.push({ agentId: ref.agentId, archiveDate });
+ continue;
+ }
+
+ const archived = await readArchivedAgent(ref.agentId, archiveDate);
+ if (archived.kind !== 'found') continue;
+ if (indexed) learned.push([ref.agentId, projectArchivedAgent(archived.agent)]);
+ if (isAgentFeedbackTarget(archived.agent) && !hasValidFeedback(archived.agent)) {
+ eligible.push({ agentId: ref.agentId, archiveDate, agent: archived.agent });
+ }
+ }
+
+ if (learned.length > 0) await recordArchivedCompletions(learned);
+ return eligible;
+}
+
export async function getPendingAgentFeedbackCount() {
- return (await getPendingAgentFeedback()).count;
+ return (await resolveEligiblePendingFeedback()).length;
+}
+
+/**
+ * One bounded page of pending feedback, newest agent id first — the same order
+ * and cursor the route used when it sliced the fully-hydrated list. Only the
+ * returned rows are read off disk.
+ */
+export async function getPendingAgentFeedbackPage({ limit = 25, cursor } = {}) {
+ const eligible = await resolveEligiblePendingFeedback();
+ const remaining = eligible
+ .filter((entry) => !cursor || entry.agentId < cursor)
+ .sort((a, b) => (a.agentId < b.agentId ? 1 : a.agentId > b.agentId ? -1 : 0));
+
+ const items = [];
+ for (const entry of remaining.slice(0, limit)) {
+ if (entry.agent) { items.push(entry.agent); continue; }
+ const archived = await readArchivedAgent(entry.agentId, entry.archiveDate);
+ if (archived.kind === 'found') items.push(archived.agent);
+ }
+
+ return {
+ items,
+ total: eligible.length,
+ nextCursor: remaining.length > limit ? remaining[limit - 1].agentId : null,
+ };
}
// Submit feedback for a completed agent.
@@ -241,6 +338,9 @@ export async function submitAgentFeedback(agentId, feedback) {
const { feedbackData, clearPendingRef, ...response } = result;
if (clearPendingRef) await removePendingAgentFeedbackRef(agentId);
+ // A rated archive is no longer an eligible target; clearing the projected bit
+ // keeps the scalar badge correct without re-reading the record.
+ await markCompletionFeedbackResolved(agentId);
await recordUserAction({
type: 'cos.agent.feedback',
target: agentId,
diff --git a/server/services/cosAgentFeedback.test.js b/server/services/cosAgentFeedback.test.js
index e4135aff1e..c702302663 100644
--- a/server/services/cosAgentFeedback.test.js
+++ b/server/services/cosAgentFeedback.test.js
@@ -43,9 +43,12 @@ import {
getFeedbackStats,
getPendingAgentFeedback,
getPendingAgentFeedbackCount,
+ getPendingAgentFeedbackPage,
initializeAgentFeedback,
submitAgentFeedback,
} from './cosAgentFeedback.js';
+import { encodeCompletionOrder } from '../lib/cosAgentCompletionOrder.js';
+import { resetCompletionOrderIndex } from './cosAgentCompletionIndex.js';
import { cosEvents } from './cosEvents.js';
import {
listPendingAgentFeedbackRefs,
@@ -323,3 +326,81 @@ describe('submitAgentFeedback records the rating (#5594)', () => {
expect(await listUserActions({ type: 'cos.agent.feedback' })).toEqual([]);
});
});
+
+/**
+ * The scalar badge and the paged list answer from the completion-order
+ * eligibility projection (#7968). Each case here leaves the archive record OFF
+ * disk: a reader that still scans pending metadata to decide eligibility cannot
+ * produce these answers.
+ */
+describe('pending feedback served from the eligibility projection', () => {
+ const orderFile = () => join(mockCosState.agentsDir, 'index.order.json');
+
+ const seedProjection = async (entries) => {
+ await mkdir(mockCosState.agentsDir, { recursive: true });
+ await writeFile(orderFile(), JSON.stringify(encodeCompletionOrder(new Map(entries))));
+ resetCompletionOrderIndex();
+ };
+
+ // Enroll a durable reference the way a live completion does, then evict the
+ // live record so only the archive side remains.
+ const enrollThenEvict = async (agents) => {
+ mockCosState.state.agents = Object.fromEntries(agents.map((agent) => [agent.id, agent]));
+ await getPendingAgentFeedback();
+ mockCosState.state = { agents: {} };
+ for (const agent of agents) mockAgentIndex.entries.set(agent.id, agent.completedAt.slice(0, 10));
+ };
+
+ const pendingAgent = (id, completedAt) => ({
+ id, status: 'completed', completedAt, metadata: { taskType: 'user', taskDescription: `Example run ${id}` },
+ });
+
+ beforeEach(async () => {
+ mockCosState.state = { agents: {} };
+ mockAgentIndex.entries = new Map();
+ resetPendingAgentFeedbackStore();
+ resetCompletionOrderIndex();
+ await rm(join(ledgerRoot, 'cos-pending-agent-feedback.json'), { force: true });
+ await rm(orderFile(), { force: true });
+ });
+
+ afterAll(async () => {
+ await rm(mockCosState.agentsDir, { recursive: true, force: true });
+ });
+
+ it('counts an eligible archived run without reading its metadata', async () => {
+ const agent = pendingAgent('agent-projected-open', '2026-08-10T10:00:00.000Z');
+ await enrollThenEvict([agent]);
+ await seedProjection([[agent.id, { completedAt: agent.completedAt, completed: true, feedbackEligible: true }]]);
+
+ await expect(getPendingAgentFeedbackCount()).resolves.toBe(1);
+ });
+
+ it('stops counting a run the projection records as already rated', async () => {
+ const agent = pendingAgent('agent-projected-rated', '2026-08-11T10:00:00.000Z');
+ await enrollThenEvict([agent]);
+ await seedProjection([[agent.id, { completedAt: agent.completedAt, completed: true, feedbackEligible: false }]]);
+
+ await expect(getPendingAgentFeedbackCount()).resolves.toBe(0);
+ });
+
+ it('pages newest id first and hydrates only the rows it returns', async () => {
+ const agents = ['agent-page-a', 'agent-page-b', 'agent-page-c']
+ .map((id, i) => pendingAgent(id, `2026-08-12T1${i}:00:00.000Z`));
+ await enrollThenEvict(agents);
+ await seedProjection(agents.map((agent) => [agent.id,
+ { completedAt: agent.completedAt, completed: true, feedbackEligible: true }]));
+ // Only the row the page returns exists on disk — `total` still sees all three,
+ // which a reader that hydrated the whole list up front could not report.
+ const newest = agents.at(-1);
+ const dir = join(mockCosState.agentsDir, newest.completedAt.slice(0, 10), newest.id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(join(dir, 'metadata.json'), JSON.stringify(newest));
+
+ await expect(getPendingAgentFeedbackPage({ limit: 1 })).resolves.toMatchObject({
+ items: [newest],
+ total: 3,
+ nextCursor: newest.id,
+ });
+ });
+});
diff --git a/server/services/cosAgentIndex.completionOrder.test.js b/server/services/cosAgentIndex.completionOrder.test.js
new file mode 100644
index 0000000000..f0777bcc27
--- /dev/null
+++ b/server/services/cosAgentIndex.completionOrder.test.js
@@ -0,0 +1,174 @@
+/**
+ * The completion-order projection's reason to exist: a page of completed runs
+ * must cost the rows it returns, not the size of the day it returns them from
+ * (#7968). Every case here counts the actual filesystem work — a regression to
+ * "read the whole day, then sort it" shows up as a day scan that a warm index
+ * must never perform.
+ */
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdir, writeFile, rm } from 'node:fs/promises';
+import { join } from 'node:path';
+
+const fixture = await vi.hoisted(async () => {
+ const { mkdtemp } = await import('node:fs/promises');
+ const { tmpdir } = await import('node:os');
+ const { join: joinPath } = await import('node:path');
+ return await mkdtemp(joinPath(tmpdir(), 'cos-completion-order-'));
+});
+
+// Counts the two reads that separate "bounded page" from "scan the day":
+// one metadata.json per returned row, and a readdir of the date bucket.
+const io = vi.hoisted(() => ({ metadata: 0, dayScans: 0 }));
+
+vi.mock('./cosState.js', () => ({ AGENTS_DIR: fixture }));
+vi.mock('./codexSummaryRepair.js', () => ({ repairCodexTaskSummary: vi.fn(async () => null) }));
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ const dateBucket = /[\\/]\d{4}-\d{2}-\d{2}$/;
+ return {
+ ...actual,
+ readFile: async (path, ...rest) => {
+ if (String(path).endsWith('metadata.json')) io.metadata += 1;
+ return actual.readFile(path, ...rest);
+ },
+ readdir: async (path, ...rest) => {
+ if (dateBucket.test(String(path))) io.dayScans += 1;
+ return actual.readdir(path, ...rest);
+ },
+ };
+});
+
+import { encodeCompletionOrder } from '../lib/cosAgentCompletionOrder.js';
+
+// Both modules under test memoize their index for the process, so each case
+// re-imports them after vi.resetModules() rather than sharing a warm singleton
+// across fixtures.
+
+const DAY = '2026-03-04';
+const DAY_SIZE = 10000;
+// Only the newest slice is written to disk, so a day scan cannot masquerade as a
+// bounded read: the projection alone has to order the other 9,940 runs.
+const ON_DISK = 60;
+
+const agentIdAt = (i) => `agent-${String(i).padStart(5, '0')}`;
+const completedAtAt = (i) => new Date(Date.parse(`${DAY}T00:00:00.000Z`) + i * 1000).toISOString();
+const recordAt = (i) => ({
+ id: agentIdAt(i),
+ status: 'completed',
+ completedAt: completedAtAt(i),
+ metadata: { taskType: 'user', taskDescription: `Synthetic run ${i}` },
+});
+
+async function writeArchive(record, day = DAY) {
+ const dir = join(fixture, day, record.id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(join(dir, 'metadata.json'), JSON.stringify(record));
+}
+
+async function seedBusyDay() {
+ await rm(fixture, { recursive: true, force: true });
+ await mkdir(join(fixture, DAY), { recursive: true });
+ const index = {};
+ const projections = new Map();
+ for (let i = 0; i < DAY_SIZE; i += 1) {
+ index[agentIdAt(i)] = DAY;
+ projections.set(agentIdAt(i), { completedAt: completedAtAt(i), completed: true, feedbackEligible: true });
+ }
+ await writeFile(join(fixture, 'index.json'), JSON.stringify(index));
+ await writeFile(join(fixture, 'index.order.json'), JSON.stringify(encodeCompletionOrder(projections)));
+ for (let i = DAY_SIZE - ON_DISK; i < DAY_SIZE; i += 1) await writeArchive(recordAt(i));
+}
+
+beforeEach(() => {
+ io.metadata = 0;
+ io.dayScans = 0;
+ vi.resetModules();
+});
+
+afterAll(() => rm(fixture, { recursive: true, force: true }));
+
+describe('bounded paging over a busy archive day (#7968)', () => {
+ it('reads one metadata record per returned row and never scans the day', async () => {
+ await seedBusyDay();
+ const index = await import('./cosAgentIndex.js');
+
+ const first = await index.getCompletedAgentPage({ limit: 25 });
+ expect(first.items.map((agent) => agent.id))
+ .toEqual(Array.from({ length: 25 }, (_, n) => agentIdAt(DAY_SIZE - 1 - n)));
+ expect(first.total).toBe(DAY_SIZE);
+ // limit + 1: the extra row is what proves another page exists.
+ expect(io.metadata).toBeLessThanOrEqual(26);
+ expect(io.dayScans).toBe(0);
+
+ io.metadata = 0;
+ const second = await index.getCompletedAgentPage({ limit: 25, cursor: first.nextCursor });
+ expect(second.items.map((agent) => agent.id))
+ .toEqual(Array.from({ length: 25 }, (_, n) => agentIdAt(DAY_SIZE - 26 - n)));
+ expect(io.metadata).toBeLessThanOrEqual(26);
+ expect(io.dayScans).toBe(0);
+ });
+
+ it('refills a page past an archive that went missing, without skipping or duplicating a row', async () => {
+ await seedBusyDay();
+ // Erase two records inside the first page's window — the projection still
+ // orders them, so the page must fall through to the next ordered rows.
+ await rm(join(fixture, DAY, agentIdAt(DAY_SIZE - 5)), { recursive: true, force: true });
+ await rm(join(fixture, DAY, agentIdAt(DAY_SIZE - 6)), { recursive: true, force: true });
+ const index = await import('./cosAgentIndex.js');
+
+ const page = await index.getCompletedAgentPage({ limit: 25 });
+ const ids = page.items.map((agent) => agent.id);
+ expect(new Set(ids).size).toBe(25);
+ expect(ids).not.toContain(agentIdAt(DAY_SIZE - 5));
+ expect(ids).not.toContain(agentIdAt(DAY_SIZE - 6));
+ expect(ids.at(-1)).toBe(agentIdAt(DAY_SIZE - 27));
+ expect(io.dayScans).toBe(0);
+ });
+});
+
+describe('projection maintenance', () => {
+ it('reads a federation-imported day once, then answers from the projection it learned', async () => {
+ await rm(fixture, { recursive: true, force: true });
+ await mkdir(fixture, { recursive: true });
+ await writeFile(join(fixture, 'index.json'), '{}');
+ for (let i = 0; i < 3; i += 1) await writeArchive(recordAt(i), '2026-03-05');
+ const index = await import('./cosAgentIndex.js');
+ // The peer receiver unions ids into the legacy map and knows nothing about
+ // completion order — the imported day must still be listed, not skipped.
+ await index.addAgentArchivesToIndex(
+ Array.from({ length: 3 }, (_, i) => ({ agentId: agentIdAt(i), date: '2026-03-05' })),
+ );
+
+ const first = await index.getCompletedAgentPage({ limit: 25 });
+ expect(first.items.map((agent) => agent.id)).toEqual([agentIdAt(2), agentIdAt(1), agentIdAt(0)]);
+ expect(io.dayScans).toBe(1);
+
+ io.dayScans = 0;
+ const again = await index.getCompletedAgentPage({ limit: 25 });
+ expect(again.items.map((agent) => agent.id)).toEqual(first.items.map((agent) => agent.id));
+ expect(io.dayScans).toBe(0);
+ });
+
+ it('drops a projection whose id the archive index no longer owns', async () => {
+ await rm(fixture, { recursive: true, force: true });
+ await mkdir(fixture, { recursive: true });
+ await writeFile(join(fixture, 'index.json'), '{}');
+ for (let i = 0; i < 2; i += 1) await writeArchive(recordAt(i), '2026-03-06');
+ const index = await import('./cosAgentIndex.js');
+ const order = await import('./cosAgentCompletionIndex.js');
+ await index.addAgentArchivesToIndex(
+ Array.from({ length: 2 }, (_, i) => ({ agentId: agentIdAt(i), date: '2026-03-06' })),
+ );
+ await index.getCompletedAgentPage({ limit: 25 });
+ expect([...(await order.loadCompletionOrderIndex()).keys()].sort()).toEqual([agentIdAt(0), agentIdAt(1)]);
+
+ // Every delete / retention prune / clear-completed path ends in saveAgentIndex.
+ (await index.loadAgentIndex()).delete(agentIdAt(0));
+ await index.saveAgentIndex();
+
+ expect([...(await order.loadCompletionOrderIndex()).keys()]).toEqual([agentIdAt(1)]);
+ expect((await index.getCompletedAgentPage({ limit: 25 })).items.map((agent) => agent.id))
+ .toEqual([agentIdAt(1)]);
+ });
+});
+
diff --git a/server/services/cosAgentIndex.js b/server/services/cosAgentIndex.js
index a6984e29c8..42e1391d2d 100644
--- a/server/services/cosAgentIndex.js
+++ b/server/services/cosAgentIndex.js
@@ -16,6 +16,12 @@ import { join } from 'path';
import { AGENTS_DIR } from './cosState.js';
import { atomicWrite, ensureDir, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { repairCodexTaskSummary } from './codexSummaryRepair.js';
+import {
+ loadCompletionOrderIndex,
+ projectArchivedAgent,
+ pruneCompletionOrderIndex,
+ recordArchivedCompletions,
+} from './cosAgentCompletionIndex.js';
const INDEX_FILE = join(AGENTS_DIR, 'index.json');
@@ -63,6 +69,25 @@ export async function saveAgentIndex() {
await atomicWrite(INDEX_FILE, obj).catch(err => {
console.error(`❌ Failed to save agent index: ${err.message}`);
});
+ // The completion-order projection is a subset of this keyspace, so every
+ // delete / retention prune / clear-completed sweep drops its rows here rather
+ // than in a call site of its own.
+ await pruneCompletionOrderIndex(new Set(agentIndex.keys()));
+}
+
+/**
+ * Record the completion-order projection for runs that just landed in the
+ * archive. Archive sites call this right after `idx.set(...)` and before
+ * `saveAgentIndex()`, which would otherwise prune an entry whose id the legacy
+ * index does not yet own.
+ */
+export async function recordArchivedAgentOrder(agents) {
+ const pairs = [];
+ for (const agent of agents) {
+ const agentId = agent?.id;
+ if (typeof agentId === 'string' && agentId) pairs.push([agentId, projectArchivedAgent(agent)]);
+ }
+ return recordArchivedCompletions(pairs);
}
/**
@@ -286,6 +311,23 @@ export async function getAgentIdsForDates(dates) {
return byDate;
}
+// Read one archived record from its date bucket, normalized the way every
+// archive reader expects: the transcript is dropped (it is hydrated on demand by
+// GET /agents/:id), a missing id falls back to the directory name, and a record
+// written before `status` was persisted reads as completed.
+async function readArchivedAgentMetadata(date, agentDirName, { repairSummaries = true } = {}) {
+ const agentDir = join(AGENTS_DIR, date, agentDirName);
+ const content = await tryReadFile(join(agentDir, 'metadata.json'));
+ if (!content) return null;
+ const raw = safeJSONParse(content, null);
+ if (!raw) return null;
+ const { output, ...rest } = raw;
+ const agent = { ...rest, id: raw.id || raw.agentId || agentDirName, status: raw.status || 'completed' };
+ const repaired = repairSummaries && await repairCodexTaskSummary(agentDir, agent);
+ if (repaired) agent.metadata = { ...agent.metadata, taskSummary: repaired };
+ return agent;
+}
+
// Get completed agents for a specific date bucket
export async function getAgentsByDate(date, { repairSummaries = true } = {}) {
const dateDir = join(AGENTS_DIR, date);
@@ -300,17 +342,8 @@ export async function getAgentsByDate(date, { repairSummaries = true } = {}) {
for (let i = 0; i < agentDirs.length; i += BATCH_SIZE) {
const batch = agentDirs.slice(i, i + BATCH_SIZE);
const reads = batch.map(async (entry) => {
- const metaPath = join(dateDir, entry.name, 'metadata.json');
- const content = await tryReadFile(metaPath);
- if (!content) return;
- const raw = safeJSONParse(content, null);
- if (!raw) return;
- const id = raw.id || raw.agentId || entry.name;
- const { output, ...rest } = raw;
- const agent = { ...rest, id, status: raw.status || 'completed' };
- const repaired = repairSummaries && await repairCodexTaskSummary(join(dateDir, entry.name), agent);
- if (repaired) agent.metadata = { ...agent.metadata, taskSummary: repaired };
- agents.push(agent);
+ const agent = await readArchivedAgentMetadata(date, entry.name, { repairSummaries });
+ if (agent) agents.push(agent);
});
await Promise.allSettled(reads);
}
@@ -318,30 +351,103 @@ export async function getAgentsByDate(date, { repairSummaries = true } = {}) {
return agents.sort((a, b) => new Date(b.completedAt || 0) - new Date(a.completedAt || 0));
}
-
-// Cursor order is archive day, completion timestamp, then id. Only visit the
-// cursor's day and older days until one extra record proves another page exists.
-// Legacy archives store ordering metadata per record, so one visited day must
-// still be read to sort it; no transcript or unrelated older day is hydrated.
+/**
+ * One bounded page of completed runs, newest first.
+ *
+ * The cursor is still `archive day | completion timestamp | id`, byte-identical
+ * to what the route round-trips, so a page taken before this projection existed
+ * still resolves after it. What changed is where the ordering comes from: the
+ * completion-order projection holds every archived run's timestamp in memory, so
+ * a warm index answers a page with at most `limit + 1` metadata reads however
+ * many runs share the day — instead of re-reading the whole day for every page
+ * inside it.
+ *
+ * A day that still owns an unprojected id (a fresh federation import, an install
+ * that has not run the backfill) is read in full exactly as before, and only if
+ * the walk actually reaches it; that read backfills the projection so the next
+ * page skips it. The legacy id→date index stays authoritative for WHICH archived
+ * runs exist — it already is for `total`, `getAgentDir`, and every feedback and
+ * report reader — so an archive directory missing from it is repaired by the
+ * date-bucket migration, not discovered here.
+ */
export async function getCompletedAgentPage({ liveAgents = [], limit = 25, cursor } = {}) {
const idx = await loadAgentIndex();
+ const order = await loadCompletionOrderIndex();
const live = liveAgents.filter(agent => agent.status === 'completed');
+ const liveById = new Map(live.map(agent => [agent.id, agent]));
const dayOf = agent => (agent.completedAt || agent.startedAt || '1970-01-01').slice(0, 10);
- const keyOf = (agent, day) => `${day}|${agent.completedAt || ''}|${agent.id}`;
- const days = [...new Set([...idx.values(), ...live.map(dayOf)])].sort().reverse();
+ const keyOf = (day, completedAt, id) => `${day}|${completedAt || ''}|${id}`;
+ const cursorDay = cursor ? cursor.slice(0, 10) : null;
+
+ // Group every candidate by archive day WITHOUT touching disk. A day owning an
+ // id the projection does not know is FLAGGED, not read — the walk below pays
+ // for it only if the requested page actually reaches that day.
+ const byDay = new Map();
+ const dayBucket = (day) => {
+ let bucket = byDay.get(day);
+ if (!bucket) byDay.set(day, bucket = { entries: new Map(), unprojected: false });
+ return bucket;
+ };
+ for (const [agentId, day] of idx) {
+ if (liveById.has(agentId)) continue; // the live record is fresher — added below
+ const projected = order.get(agentId);
+ if (!projected) { dayBucket(day).unprojected = true; continue; }
+ if (!projected.completed) continue;
+ dayBucket(day).entries.set(agentId, { id: agentId, day, key: keyOf(day, projected.completedAt, agentId) });
+ }
+ for (const agent of live) {
+ const day = idx.get(agent.id) || dayOf(agent);
+ dayBucket(day).entries.set(agent.id, { id: agent.id, day, agent, key: keyOf(day, agent.completedAt, agent.id) });
+ }
+
const total = new Set([...idx.keys(), ...live.map(agent => agent.id)]).size;
- const items = [];
- for (const day of days) {
- if (cursor && day > cursor.slice(0, 10)) continue;
- const records = new Map((await getAgentsByDate(day, { repairSummaries: false })).map(agent => [agent.id, agent]));
- for (const agent of live) if ((idx.get(agent.id) || dayOf(agent)) === day) records.set(agent.id, agent);
- const candidates = [...records.values()].filter(agent => agent.status === 'completed')
- .map(agent => ({ agent, key: keyOf(agent, day) }))
- .filter(entry => !cursor || entry.key < cursor)
- .sort((a, b) => a.key < b.key ? 1 : a.key > b.key ? -1 : 0);
- items.push(...candidates.slice(0, limit + 1 - items.length));
- if (items.length > limit) break;
+ const days = [...byDay.keys()].sort().reverse();
+ const newestFirst = (a, b) => (a.key < b.key ? 1 : a.key > b.key ? -1 : 0);
+
+ const hydrateDay = async (day, bucket) => {
+ bucket.unprojected = false;
+ const learned = [];
+ for (const agent of await getAgentsByDate(day, { repairSummaries: false })) {
+ learned.push([agent.id, projectArchivedAgent(agent)]);
+ const existing = bucket.entries.get(agent.id);
+ if (existing) { existing.agent ||= agent; continue; }
+ if (agent.status !== 'completed' || !idx.has(agent.id)) continue;
+ bucket.entries.set(agent.id, { id: agent.id, day, agent, key: keyOf(day, agent.completedAt, agent.id) });
+ }
+ await recordArchivedCompletions(learned);
+ };
+
+ let dayCursor = 0;
+ let queued = [];
+ const queueNextDay = async () => {
+ while (queued.length === 0 && dayCursor < days.length) {
+ const day = days[dayCursor++];
+ if (cursorDay && day > cursorDay) continue;
+ const bucket = byDay.get(day);
+ if (bucket.unprojected) await hydrateDay(day, bucket);
+ queued = [...bucket.entries.values()].filter(entry => !cursor || entry.key < cursor).sort(newestFirst);
+ }
+ return queued.length > 0;
+ };
+
+ // limit + 1 rows prove whether another page exists. A row whose metadata went
+ // missing or unparseable between the index read and now is skipped and refilled
+ // from the same ordered queue, so a corrupt archive shortens no page.
+ const selected = [];
+ while (selected.length <= limit && (queued.length > 0 || await queueNextDay())) {
+ const batch = queued.splice(0, limit + 1 - selected.length);
+ const hydrated = await Promise.all(batch.map(async (entry) => (entry.agent ? entry : {
+ ...entry,
+ agent: await readArchivedAgentMetadata(entry.day, entry.id, { repairSummaries: false }),
+ })));
+ for (const entry of hydrated) {
+ if (entry.agent?.status === 'completed') selected.push(entry);
+ }
}
- return { items: items.slice(0, limit).map(entry => entry.agent), total,
- nextCursor: items.length > limit ? items[limit - 1].key : null };
+
+ return {
+ items: selected.slice(0, limit).map(entry => entry.agent),
+ total,
+ nextCursor: selected.length > limit ? selected[limit - 1].key : null,
+ };
}
diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.js
index 72e766984c..718a2e23eb 100644
--- a/server/services/cosAgentLifecycle.js
+++ b/server/services/cosAgentLifecycle.js
@@ -20,7 +20,7 @@ import { atomicWrite, ensureDir, readFileTail, safeJSONParse, tryReadFile } from
import { runnerEntryShieldsRunningRecord } from '../lib/runnerAgentLiveness.js';
import { recordDomainUsage } from './domainUsage.js';
import { repairCodexTaskSummary } from './codexSummaryRepair.js';
-import { loadAgentIndex, saveAgentIndex, getAgentDir } from './cosAgentIndex.js';
+import { loadAgentIndex, saveAgentIndex, getAgentDir, recordArchivedAgentOrder } from './cosAgentIndex.js';
import { isAgentHandoff } from '../lib/agentOutcome.js';
export async function registerAgent(agentId, taskId, metadata = {}) {
@@ -137,6 +137,9 @@ async function archiveCompletedAgent(agentId, agent) {
// is cheap (a small map, atomically written) and repairs exactly that.
const idx = await loadAgentIndex();
idx.set(agentId, dateStr);
+ // Project the completion order BEFORE saving: `saveAgentIndex` prunes the
+ // projection to the ids the index owns, so recording after it is a no-op.
+ await recordArchivedAgentOrder([{ ...agent, id: agentId }]);
await saveAgentIndex();
}
@@ -746,6 +749,7 @@ export async function cleanupZombieAgents() {
// Persist zombie-cleaned agents to date-bucketed dirs and update index
const idx = await loadAgentIndex();
+ const archived = [];
for (const agentId of cleaned) {
const agent = state.agents[agentId];
const dateStr = agent.completedAt?.slice(0, 10);
@@ -775,7 +779,9 @@ export async function cleanupZombieAgents() {
}
idx.set(agentId, dateStr);
+ archived.push({ ...agent, id: agentId });
}
+ await recordArchivedAgentOrder(archived);
await saveAgentIndex();
console.log(`🧹 Cleaned up ${cleaned.length} zombie agents: ${cleaned.join(', ')}`);