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: archive old completed CoS tasks into PostgreSQL so the task files stay small

Adam Eivye0cde36b7cd1
diff --git a/docs/API.md b/docs/API.md
index ea61b7a9b4..3bc4462b7d 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -269,7 +269,7 @@ Context tools remain read-only. Semantic reads and writes are independent, defau
| POST | `/cos/tools/call` | Execute one schema-validated semantic tool with server-derived authority and idempotency |
| GET | `/cos/tools/calls/:requestId` | Read a retained normalized tool result |
| PUT | `/cos/config` | Update configuration |
-| GET | `/cos/tasks` | Bounded task list: all non-completed tasks plus the first 25 completed (`completedCount`, `completedNextCursor`); `view=queue`, `view=completed` (paged), `view=full` (raw unbounded store) |
+| GET | `/cos/tasks` | Bounded task list: all non-completed tasks plus the first 25 completed (`completedCount`, `completedNextCursor`); `view=queue`, `view=completed` (paged), `view=full` (everything the task files hold: the open queue plus the recent completed window; completed tasks older than that move to the archive and page through `view=completed`) |
| GET | `/cos/tasks/:id` | One task as stored plus the queue it lives in: `{ task, source: 'user' \| 'internal' }`; 404 when unknown |
| POST | `/cos/evaluate` | Force task evaluation |
| GET | `/cos/health` | Get health status |
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 8bac21d81c..16594885e1 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -351,7 +351,7 @@ a snapshot as a complete recovery point.
Now that PostgreSQL is a **required** dependency (it owns the creative catalog, memory, and a growing set of app-native records — see [Storage Classification Contract](./STORAGE.md)), **the database dump is part of required system state, not an optional extra.** A snapshot that captured `data/` but failed to capture the DB is incomplete, and PortOS surfaces that explicitly.
-The dump includes the machine-local `cos_pending_agent_feedback` reference index and `review_queue_triage` presentation markers. The queue's source records remain in their owning stores; restoring the dump therefore preserves snooze/dismissal decisions without exporting them through federation or duplicating source payloads.
+The dump includes the machine-local `cos_pending_agent_feedback` reference index, the `cos_task_archive` completed-task history (the only copy once a task leaves `TASKS.md` / `COS-TASKS.md`), and `review_queue_triage` presentation markers. The queue's source records remain in their owning stores; restoring the dump therefore preserves snooze/dismissal decisions without exporting them through federation or duplicating source payloads.
Implementation: `server/services/backup.js` (snapshot/dump/restore), `server/services/backupScheduler.js` (cron), `server/routes/backup.js` (API), and `server/routes/database.js` (DB export/sync).
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 0474c15f7e..8cca6dff1f 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -153,7 +153,9 @@ does not recover nonempty output or general failed saves; those still require th
**When to use.** The payload is long externally-editable prose; the domain syncs through iCloud/file-sync outside PortOS; or forcing the record through the app DB would break an existing sync boundary.
-**CoS task queues** (`data/TASKS.md`, `data/COS-TASKS.md`, or configured paths) remain file-primary because direct Markdown editing and watcher-driven updates are supported inputs. `cosTaskStore.js` caches parsed snapshots by file stamp and lazily indexes task IDs; single-task reads clone only the matching record, without grouping or copying either backlog. Store writes invalidate the snapshot and index together; external changes are detected on the next read. This optimization changes no persisted format, config key, or peer payload, so existing installs upgrade without an import or migration. PostgreSQL would permit per-row writes, but a future migration must explicitly replace the direct-edit/watch contract, import both configured sources without losing task metadata/order, and retain recovery copies before switching authority. Merely storing the complete Markdown blob in PostgreSQL would retain whole-queue parsing and rewriting.
+**CoS task queues** (`data/TASKS.md`, `data/COS-TASKS.md`, or configured paths) are being moved to PostgreSQL in two steps. Direct Markdown editing and the file watcher are no longer supported inputs, so nothing about the files has to stay human-readable or watcher-compatible; that contract is retired (decision 2026-10-20, [plan](./plans/2026-10-20-cos-task-queue-to-postgres.md)). Step one is the completed-task archive below. Step two moves the open queue into per-row storage, replaces the file watcher (`taskWatcher.js`) with events emitted at the write, and keeps the Markdown files as a one-time import with a recovery copy. Until step two lands the open queue and a recent window of completed tasks remain in the files, and `cosTaskStore.js` still caches parsed snapshots by file stamp and lazily indexes task IDs; single-task reads clone only the matching record, without grouping or copying either backlog. Merely storing the complete Markdown blob in PostgreSQL would retain whole-queue parsing and rewriting, so step two is per-row.
+
+`cos_task_archive` (`db-primary`, **machine-local, never federated**) holds completed tasks older than the recent window, with their full records, prompt bodies included. Those prompts were ~99% of the two files (tens of MB on a busy install), and every full-queue read cloned all of it. `archiveCompletedTasks()` runs in the 15-minute CoS health check: a completed task leaves the file once it is at least 3 days past its `completedAt`/`updatedAt` (undated tasks count as oldest) AND beyond the newest 100 completed per queue, at most 300 per queue per tick. The archive write lands first and is idempotent, so a crash before the file rewrite leaves a harmless duplicate the next sweep removes. Reads fall through: the completed-history pages, the queue/bare views' `completedCount`, `getTaskById`/`findTaskWithSource` and `deleteTask` consult the archive when the files miss, and `character.syncTaskXP` includes archived summaries so a task archived before an XP sync still earns it. Peers advertise and merge only what their own files hold, and `mergePeerTasks` skips an incoming completed task this machine already archived so a peer cannot resurrect it. No migration or seed: the table is additive (`ensureSchema` and `init-db.sql`), an absent archive is the correct empty state, and the first sweeps drain an existing backlog. Backed up by the Postgres dump. Adapter: `server/services/cosTaskArchive.js` (file backend only under the dev/test escape hatch).
**Private security assessments** reuse the existing Review Hub item store for report prose and CoS agent archives for local source/transcripts. They add no store format or database migration. The source inventory stays in run memory; interruption before report validation requires a new assessment. Assessment tasks and all their archive files are excluded from peer federation, and shared socket notifications carry no report prose. Reports follow existing local backup and Review Hub retention; temporary sandbox homes are removed after completion. See [the assessment design and research](research/2026-09-06-private-security-models.md).
diff --git a/docs/plans/2026-10-20-cos-task-queue-to-postgres.md b/docs/plans/2026-10-20-cos-task-queue-to-postgres.md
new file mode 100644
index 0000000000..f2a8f5ef3a
--- /dev/null
+++ b/docs/plans/2026-10-20-cos-task-queue-to-postgres.md
@@ -0,0 +1,70 @@
+# CoS task queue to PostgreSQL
+
+Approved 2026-10-20. Supersedes the "file-primary because direct editing and
+watchers are supported inputs" position in `docs/STORAGE.md`.
+
+## Context
+
+`data/TASKS.md` and `data/COS-TASKS.md` reached ~33 MB and ~29 MB on a busy
+install (~3,100 tasks, nearly all completed, none ever pruned). The bulk is the
+`prompt` field: a finished task keeps its full slashdo command text (one entry is
+2.3 MB, several are ~500 KB). Every full-queue read (`getAllTasks`, `getCosTasks`)
+clones that parse tree, ~100 MB per clone, and a cold parse of both files holds
+~430 MB resident. That was a measured driver of `portos-server` reaching PM2's
+4 GiB RSS ceiling and restarting mid-agent-spawn (97 logged restarts, 12 in one
+day). Agent status and activity also contend on a single `withStateLock` queue
+that rewrites whole files.
+
+The only reason the queues stayed file-primary was that hand-editing the Markdown
+and watcher-driven updates were supported inputs. The owner has retired that
+contract: nobody needs to edit these files by hand. With it gone, nothing about
+the data fits a file better than a table, and the repo already requires every
+install and federated peer to run PostgreSQL.
+
+## Step one: completed-task archive (this change)
+
+- Table `cos_task_archive (source, task_id, description, completed_at, archived_at,
+ task jsonb)`, key `(source, task_id COLLATE "C")`. `COLLATE "C"` matches the
+ JavaScript code-unit order every consumer already uses for newest-id-first paging.
+- `archiveCompletedTasks()` in the 15-minute CoS health check moves a completed
+ task out of the file when it is at least 3 days past its stamp (undated = oldest)
+ AND beyond the newest 100 completed per queue, at most 300 per queue per tick.
+ Archive write first (idempotent), then the file rewrite, all under the same
+ state lock as every task write: a crash leaves a duplicate, never a loss.
+- Reads fall through when the file misses: completed-history pages (merged across
+ file window and archive, file copy wins), `completedCount`, a selected archived
+ task in the queue view, `getTaskById`/`findTaskWithSource`, `deleteTask`.
+- Consumers audited for old-completed reads: `screenshotsGc` ignores terminal tasks;
+ the PR-reviewer-failure lookup only needs a recent marker; `character.syncTaskXP`
+ would lose XP for a task archived before a sync, so it also reads archived
+ summaries (id + description, no prompt bodies).
+- Federation: the archive is machine-local. Peers advertise and merge only their
+ own files; `mergePeerTasks` drops an incoming completed task this machine already
+ archived so a peer cannot resurrect it.
+- No migration or seed. The table is additive; the first sweeps drain the existing
+ backlog (300 per queue per tick, ~90 minutes for a ~1,600-task queue). Backup is
+ the Postgres dump.
+
+## Step two: the open queue (next)
+
+- Per-row storage for open tasks, replacing whole-file read-modify-write: concurrent
+ agents update their own row instead of queueing on one file.
+- Writers emit `tasks:*` events at the write; `taskWatcher.js` (chokidar over both
+ files, snapshot diffing) and the file-stamp parse cache go away.
+- `mergePeerTasks` / `buildCosTasksPayload` keep their claim-aware per-task LWW
+ semantics over rows.
+- Migration imports both configured Markdown sources without losing task metadata
+ or order, retains a recovery copy of each file, and gates on the presence of the
+ input (the files), never on the absence of the output.
+- The Markdown files become a one-time import input only.
+
+## Verification
+
+- Store tests cover the sweep (age floor, newest-N floor, oldest-first under the
+ limit, idempotence, crash between archive and rewrite), the fall-through reads,
+ delete, and the no-resurrection merge; each was checked to fail with its behavior
+ removed. The file backend is covered in `cosTaskArchive.test.js`, the Postgres
+ backend in `cosTaskArchive.db.test.js` (`npm run test:db`).
+- After deployment: `data/TASKS.md` / `COS-TASKS.md` shrink to the open queue plus
+ the recent window; steady-state server RSS and the `readTaskFile` clone volume
+ drop; the Tasks page still pages through full history.
diff --git a/docs/plans/README.md b/docs/plans/README.md
index 563b90d322..4cf778c7cc 100644
--- a/docs/plans/README.md
+++ b/docs/plans/README.md
@@ -15,6 +15,10 @@ Index of plans other docs point at:
the CI/test latency audit and the six changes behind the test memo, the
resource suites in pregate, and the pregate attestation CI honors.
+- [2026-10-20 — CoS task queue to PostgreSQL](./2026-10-20-cos-task-queue-to-postgres.md):
+ why `TASKS.md` / `COS-TASKS.md` outgrew their files, the completed-task archive
+ (step one) and the per-row open queue that replaces the file watcher (step two).
+
These are point-in-time design records, not living docs — they are not updated
to track implementation drift. For current behavior, see the code, `CLAUDE.md`,
and the topic docs elsewhere under `docs/`.
diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.md
index c855c3d8a9..bbe7016205 100644
--- a/server/lib/db/schema/README.md
+++ b/server/lib/db/schema/README.md
@@ -30,6 +30,7 @@ init-db.sql, each with a one-line reason.
| `commissions.js` | `commissionsDdl` | Creative Commissions + feedback (machine-local) |
| `userActions.js` | `userActionsDdl` | Operator-action ledger — what the human did in the UI (machine-local) |
| `reviewQueueTriage.js` | `reviewQueueTriageDdl` | Machine-local Review Hub presentation markers — snooze, optional dismissal, and delivery generation keyed by canonical action identity |
+| `cosTaskArchive.js` | `cosTaskArchiveDdl` | Machine-local archive of completed CoS tasks (full records, prompts included) moved out of `TASKS.md` / `COS-TASKS.md` |
| `cosAgentFeedback.js` | `cosAgentFeedbackDdl` | Durable machine-local references to completed manual CoS runs awaiting a rating (agent id + archive locator only) |
| `aiGraph.js` | `aiGraphDdl` | AI provider connection graph — connections, harness bindings, executable route bindings (machine-local) |
| `peerExecution.js` | `peerExecutionDdl` | Receiver-local permanent execution consumption and generation floors; no grants or federation |
@@ -51,7 +52,7 @@ init-db.sql, each with a one-line reason.
### Composer (`index.js`)
-- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `post` → `commissions` → `userActions` → `reviewQueueTriage` → `cosAgentFeedback` → `aiGraph` → `peerExecution`).
+- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `post` → `commissions` → `userActions` → `reviewQueueTriage` → `cosAgentFeedback` → `cosTaskArchive` → `aiGraph` → `peerExecution`).
- `buildCatalogDdl()` → phase-2 list (`catalog` → `media` → `catalogUserTypes` →
`universes` → `library` → `pipeline` → `writersRoom` → `lora` → `privacy` → `stackerNews` → `x` →
`beeper` → `audit` DDL → audit triggers → `syncFeed` DDL → sync-feed triggers).
diff --git a/server/lib/db/schema/cosTaskArchive.js b/server/lib/db/schema/cosTaskArchive.js
new file mode 100644
index 0000000000..daf1d3d27f
--- /dev/null
+++ b/server/lib/db/schema/cosTaskArchive.js
@@ -0,0 +1,16 @@
+// Machine-local archive of completed CoS tasks. The task files keep the open
+// queue plus a recent window of completed tasks; everything older lives here,
+// prompt bodies included (they are what made TASKS.md / COS-TASKS.md tens of MB).
+// `description` is a light projection so scans that only need titles never
+// detoast the JSONB. Never enters federation payloads.
+export const cosTaskArchiveDdl = [
+ `CREATE TABLE IF NOT EXISTS cos_task_archive (
+ source TEXT NOT NULL CHECK (source IN ('user', 'internal')),
+ task_id TEXT COLLATE "C" NOT NULL,
+ description TEXT NOT NULL DEFAULT '',
+ completed_at TIMESTAMPTZ,
+ archived_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ task JSONB NOT NULL,
+ PRIMARY KEY (source, task_id)
+ )`,
+];
diff --git a/server/lib/db/schema/index.js b/server/lib/db/schema/index.js
index e9b36e2280..893d194e71 100644
--- a/server/lib/db/schema/index.js
+++ b/server/lib/db/schema/index.js
@@ -21,6 +21,7 @@ import { commissionsDdl } from './commissions.js';
import { userActionsDdl } from './userActions.js';
import { reviewQueueTriageDdl } from './reviewQueueTriage.js';
import { cosAgentFeedbackDdl } from './cosAgentFeedback.js';
+import { cosTaskArchiveDdl } from './cosTaskArchive.js';
import { aiGraphDdl } from './aiGraph.js';
import { peerExecutionDdl } from './peerExecution.js';
import { catalogDdl, catalogUserTypesDdl, catalogPendingAppliesDdl } from './catalog.js';
@@ -50,6 +51,7 @@ export {
userActionsDdl,
reviewQueueTriageDdl,
cosAgentFeedbackDdl,
+ cosTaskArchiveDdl,
aiGraphDdl,
peerExecutionDdl,
catalogDdl,
@@ -90,6 +92,7 @@ export function buildUpgradeDdl() {
...userActionsDdl,
...reviewQueueTriageDdl,
...cosAgentFeedbackDdl,
+ ...cosTaskArchiveDdl,
...aiGraphDdl,
...peerExecutionDdl,
];
diff --git a/server/lib/db/schema/schema.test.js b/server/lib/db/schema/schema.test.js
index a07d80b724..f3af0bea3d 100644
--- a/server/lib/db/schema/schema.test.js
+++ b/server/lib/db/schema/schema.test.js
@@ -25,7 +25,7 @@ import {
} from './index.js';
const DOMAIN_ARRAYS = [
- 'coreDdl', 'tribeDdl', 'humanActivityDdl', 'postDdl', 'commissionsDdl', 'userActionsDdl', 'reviewQueueTriageDdl', 'cosAgentFeedbackDdl', 'aiGraphDdl', 'peerExecutionDdl',
+ 'coreDdl', 'tribeDdl', 'humanActivityDdl', 'postDdl', 'commissionsDdl', 'userActionsDdl', 'reviewQueueTriageDdl', 'cosAgentFeedbackDdl', 'cosTaskArchiveDdl', 'aiGraphDdl', 'peerExecutionDdl',
'catalogDdl', 'catalogIdentityDdl', 'catalogUserTypesDdl', 'mediaDdl', 'universesDdl',
'libraryDdl', 'pipelineDdl', 'writersRoomDdl', 'loraDdl', 'privacyDdl', 'stackerNewsDdl', 'xDdl',
'beeperDdl', 'mindToolRecipesDdl',
@@ -50,6 +50,7 @@ describe('db/schema barrel + composer (#2832)', () => {
...schema.userActionsDdl,
...schema.reviewQueueTriageDdl,
...schema.cosAgentFeedbackDdl,
+ ...schema.cosTaskArchiveDdl,
...schema.aiGraphDdl,
...schema.peerExecutionDdl,
];
diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.js
index 81e50bc0ee..146f141a78 100644
--- a/server/routes/cosTaskRoutes.js
+++ b/server/routes/cosTaskRoutes.js
@@ -170,7 +170,9 @@ const router = Router();
// With no params it returns a bounded `{ user, cos }` projection: all non-completed
// tasks plus grouped/derived lists, and only the first page of completed history
// (+ `completedCount`/`completedNextCursor`; page on with `view=completed`).
-// `view=full` returns the raw unbounded store. When a client passes
+// `view=full` returns everything the task files hold (open queue + the recent completed
+// window); older completed tasks live in the archive and page through `view=completed`.
+// When a client passes
// `limit`/`offset`, each source is reduced to a *genuinely bounded* shape: the
// windowed `tasks` slice plus scalar metadata only. The full-set derived
// collections (`grouped`, `autoApproved`, `awaitingApproval`) are dropped from
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index e6a4e62ccf..0708e0b4ba 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -342,6 +342,19 @@ CREATE TABLE IF NOT EXISTS cos_pending_agent_feedback (
archive_date TEXT
);
+-- Machine-local archive of completed CoS tasks moved out of TASKS.md /
+-- COS-TASKS.md. Full task records (prompt bodies included) live in `task`;
+-- `description` is a light projection. Never enters federation payloads.
+CREATE TABLE IF NOT EXISTS cos_task_archive (
+ source TEXT NOT NULL CHECK (source IN ('user', 'internal')),
+ task_id TEXT COLLATE "C" NOT NULL,
+ description TEXT NOT NULL DEFAULT '',
+ completed_at TIMESTAMPTZ,
+ archived_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ task JSONB NOT NULL,
+ PRIMARY KEY (source, task_id)
+);
+
-- Auto-update updated_at and sync_sequence on content/metadata changes.
-- Skips bump for access-stat-only updates (access_count, last_accessed)
-- to avoid sync noise from read operations.
diff --git a/server/services/character.js b/server/services/character.js
index 59abe7b0fc..5aa2a5b585 100644
--- a/server/services/character.js
+++ b/server/services/character.js
@@ -18,6 +18,7 @@ import path from 'path';
import { atomicWrite, ensureDir, readJSONFile, PATHS, sleep } from '../lib/fileUtils.js';
import * as jiraService from './jira.js';
import { getAllTasks } from './cosTaskStore.js';
+import { listArchivedSummaries } from './cosTaskArchive.js';
import { getBirthDateStrict } from './meatspace.js';
import { getCharacterSkills } from './characterSkills.js';
import { getCharacterMetrics } from './characterMetrics.js';
@@ -587,7 +588,13 @@ export async function syncJiraXP() {
export async function syncTaskXP() {
const { user: userTasks, cos: cosTasks } = await getAllTasks();
- const completed = [...(userTasks.tasks || []), ...(cosTasks.tasks || [])].filter(t => t.status === 'completed');
+ // Completed tasks past the file window live in the archive; one that finished
+ // before this sync ran must still earn its XP, so include them by summary.
+ const archived = await listArchivedSummaries();
+ const completed = [
+ ...[...(userTasks.tasks || []), ...(cosTasks.tasks || [])].filter(t => t.status === 'completed'),
+ ...archived,
+ ];
const { saved, result } = await mutateCharacter((character) => {
character.syncedTaskIds ??= [];
diff --git a/server/services/character.test.js b/server/services/character.test.js
index d23f906a28..ef69e61c82 100644
--- a/server/services/character.test.js
+++ b/server/services/character.test.js
@@ -9,7 +9,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
const store = vi.hoisted(() => ({
value: null, birthDate: null, readable: true, beforeWrite: null,
jira: { instances: {}, projects: [], tickets: [], beforeTickets: null },
- tasks: { user: { tasks: [] }, cos: { tasks: [] }, before: null },
+ tasks: { user: { tasks: [] }, cos: { tasks: [] }, before: null, archived: [] },
}));
vi.mock('../lib/fileUtils.js', () => ({
@@ -56,6 +56,9 @@ vi.mock('./cosTaskStore.js', () => ({
return { user: store.tasks.user, cos: store.tasks.cos };
},
}));
+vi.mock('./cosTaskArchive.js', () => ({
+ listArchivedSummaries: async () => store.tasks.archived,
+}));
vi.mock('./characterSkills.js', () => ({
getCharacterSkills: vi.fn(async () => FAKE_SKILLS),
}));
@@ -570,7 +573,7 @@ describe('Character mutation queue (#9817)', () => {
store.birthDate = null;
store.beforeWrite = null;
store.jira = { instances: {}, projects: [], tickets: [], beforeTickets: null };
- store.tasks = { user: { tasks: [] }, cos: { tasks: [] }, before: null };
+ store.tasks = { user: { tasks: [] }, cos: { tasks: [] }, before: null, archived: [] };
});
afterEach(() => { store.beforeWrite = null; });
@@ -712,6 +715,23 @@ describe('Character mutation queue (#9817)', () => {
expect(store.value.xp).toBe(125);
});
+ it('syncTaskXP also grants XP for completed tasks that have already left the task files', async () => {
+ store.tasks.user = { tasks: [{ id: 't1', status: 'completed', title: 'In the file window' }] };
+ store.tasks.archived = [
+ { source: 'user', id: 't0', description: 'Archived before any sync' },
+ { source: 'internal', id: 't1', description: 'Same id as a file task' },
+ ];
+ store.value.syncedTaskIds = ['t0'];
+ const result = await characterService.syncTaskXP();
+
+ // t0 was already synced; t1 appears in both places but is granted once.
+ expect(result.taskCount).toBe(1);
+ expect(store.value.syncedTaskIds.sort()).toEqual(['t0', 't1']);
+ store.tasks.archived = [{ source: 'user', id: 't9', description: 'Archived and unsynced' }];
+ expect((await characterService.syncTaskXP()).taskCount).toBe(1);
+ expect(store.value.syncedTaskIds).toContain('t9');
+ });
+
it('syncJiraXP does not double-grant a ticket synced during discovery, and keeps a racing edit', async () => {
store.jira = {
instances: { main: {} },
diff --git a/server/services/cos.js b/server/services/cos.js
index 966464172a..a3957a38c7 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -93,7 +93,7 @@ export { runHealthCheck, getHealthStatus };
// backward compat with `import * as cos` and the cos route handlers. The store
// emits `tasks:changed`; init() below turns that into tryImmediateSpawn /
// dequeueNextTask so the spawn-side logic stays here, not in the store.
-import { firstLine, getUserTasks, getCosTasks, getAllTasks, getTaskView, getTasks, getTaskById, findTaskWithSource, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks } from './cosTaskStore.js';
+import { firstLine, getUserTasks, getCosTasks, getAllTasks, getTaskView, getTasks, getTaskById, findTaskWithSource, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks, archiveCompletedTasks } from './cosTaskStore.js';
export { getPendingTaskIds } from './cosTaskStore.js';
export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTaskView, getTasks, getTaskById, findTaskWithSource, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks };
import { ensureInstanceId } from './instanceIdentity.js';
@@ -480,8 +480,13 @@ async function bootDaemon(state) {
if (swept.reaped > 0) {
emitLog('info', `🧹 Auto-expired ${swept.reaped} resolved failure task(s) (${swept.staleBlocks} block(s), ${swept.investigations} investigation(s))`);
}
+ // Completed tasks past the recent window leave the task files for the
+ // archive table; the files stay small enough for every poller to read.
+ await archiveCompletedTasks().catch((err) => {
+ console.warn(`⚠️ archiveCompletedTasks failed: ${err?.message || err}`);
+ });
},
- metadata: { description: 'CoS health check + orphan cleanup + agent archival + failure-artifact reaper' }
+ metadata: { description: 'CoS health check + orphan cleanup + agent archival + failure-artifact reaper + completed-task archive' }
});
// Performance summary (10 min)
diff --git a/server/services/cosTaskArchive.db.test.js b/server/services/cosTaskArchive.db.test.js
new file mode 100644
index 0000000000..c6ed417b76
--- /dev/null
+++ b/server/services/cosTaskArchive.db.test.js
@@ -0,0 +1,62 @@
+/**
+ * Postgres round-trip for the completed-task archive. The file backend's
+ * contract is pinned without a database in cosTaskArchive.test.js; what needs a
+ * real Postgres is the part only Postgres enforces: the (source, task_id) key,
+ * the source CHECK, the JSONB round-trip, and `COLLATE "C"` ordering matching
+ * JavaScript's code-unit comparison.
+ *
+ * Runs via `npm run test:db` (→ `portos_test`) ONLY. Skips cleanly when no
+ * database is reachable.
+ */
+import { afterAll, beforeEach, describe, expect, it } from 'vitest';
+import { checkHealth, close, ensureSchema, query } from '../lib/db.js';
+import { requireDbOrSkip } from '../lib/dbTestGate.js';
+import { __makePgCosTaskArchiveBackend } from './cosTaskArchive.js';
+
+const health = await checkHealth().catch(() => ({ connected: false }));
+if (health.connected) await ensureSchema();
+const runDb = requireDbOrSkip('services/cosTaskArchive.db.test', health.connected, 'disposable PostgreSQL unavailable');
+const backend = __makePgCosTaskArchiveBackend({ query });
+const task = (id, extra = {}) => ({ id, description: `Example ${id}`, status: 'completed', metadata: { updatedAt: '2026-10-01T00:00:00.000Z', prompt: `Prompt ${id}` }, ...extra });
+
+beforeEach(async () => { if (runDb) await query('DELETE FROM cos_task_archive'); });
+afterAll(async () => { if (runDb) await query('DELETE FROM cos_task_archive'); if (health.connected) await close(); });
+
+describe.skipIf(!runDb)('cos_task_archive (postgres backend)', () => {
+ it('round-trips a full record, upserts by (source, id) and keeps sources apart', async () => {
+ await backend.archive('user', [task('task-a')]);
+ await backend.archive('internal', [task('task-a', { description: 'Internal twin' })]);
+ await backend.archive('user', [task('task-a', { description: 'Edited' })]);
+ expect(await backend.get('task-a', 'user')).toEqual({ source: 'user', task: expect.objectContaining({ description: 'Edited', metadata: expect.objectContaining({ prompt: 'Prompt task-a' }) }) });
+ expect((await backend.get('task-a', 'internal')).task.description).toBe('Internal twin');
+ expect(await backend.count('user')).toBe(1);
+ const { rows } = await query("SELECT completed_at FROM cos_task_archive WHERE source = 'user' AND task_id = 'task-a'");
+ expect(rows[0].completed_at.toISOString()).toBe('2026-10-01T00:00:00.000Z');
+ });
+
+ it('pages newest id first in code-unit order with a strict before cursor', async () => {
+ await backend.archive('user', ['task-b', 'task-a', 'task-C', 'task-d'].map((id) => task(id)));
+ expect((await backend.list('user', { offset: 0, limit: 10 })).map((t) => t.id)).toEqual(['task-d', 'task-b', 'task-a', 'task-C']);
+ expect((await backend.list('user', { before: 'task-b', offset: 0, limit: 2 })).map((t) => t.id)).toEqual(['task-a', 'task-C']);
+ expect((await backend.list('user', { offset: 1, limit: 2 })).map((t) => t.id)).toEqual(['task-b', 'task-a']);
+ });
+
+ it('reports archived ids, projects summaries without bodies, and deletes by source', async () => {
+ await backend.archive('user', [task('task-a'), task('task-b')]);
+ expect(await backend.existingIds('user', ['task-a', 'task-z'])).toEqual(new Set(['task-a']));
+ expect(await backend.existingIds('user', [])).toEqual(new Set());
+ expect(await backend.summaries()).toContainEqual({ source: 'user', id: 'task-a', description: 'Example task-a' });
+ expect(await backend.remove('task-a', 'internal')).toBe(false);
+ expect(await backend.remove('task-a', 'user')).toBe(true);
+ });
+
+ it('looks an id up user-first when both queues archived the same id', async () => {
+ await backend.archive('internal', [task('task-shared', { description: 'Internal copy' })]);
+ await backend.archive('user', [task('task-shared', { description: 'User copy' })]);
+ expect(await backend.get('task-shared', null)).toMatchObject({ source: 'user', task: { description: 'User copy' } });
+ });
+
+ it('refuses an unknown source', async () => {
+ await expect(backend.archive('elsewhere', [task('task-a')])).rejects.toThrow();
+ });
+});
diff --git a/server/services/cosTaskArchive.js b/server/services/cosTaskArchive.js
new file mode 100644
index 0000000000..a923e980d6
--- /dev/null
+++ b/server/services/cosTaskArchive.js
@@ -0,0 +1,180 @@
+/**
+ * Machine-local archive of completed CoS tasks.
+ *
+ * `TASKS.md` / `COS-TASKS.md` keep the open queue plus a recent window of
+ * completed tasks; older completed tasks move here with their full records
+ * (prompt bodies were ~99% of those files). PostgreSQL is authoritative in a
+ * normal install; the JSON backend exists only for the documented
+ * development/test escape hatch. Never federated: peers advertise and merge
+ * only what their own task files hold.
+ *
+ * Task ids sort with JavaScript's code-unit order everywhere (`byIdDesc` in
+ * cosTaskStore), so the table's key column is `COLLATE "C"` to match.
+ */
+
+import { join } from 'node:path';
+import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+import { createPgFileFacade, resolvePgBackend } from '../lib/pgFileFacade.js';
+
+const SOURCES = ['user', 'internal'];
+const archiveFile = () => join(PATHS.data, 'cos-task-archive.json');
+const queueFileWrite = createFileWriteQueue();
+
+const completedAtOf = (task) => {
+ const stamp = Date.parse(task?.metadata?.completedAt || task?.metadata?.updatedAt || '');
+ return Number.isFinite(stamp) ? new Date(stamp).toISOString() : null;
+};
+const descriptionOf = (task) => (typeof task?.description === 'string' ? task.description : '');
+const byIdDesc = (a, b) => (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
+
+async function readFileArchive() {
+ const raw = await readJSONFile(archiveFile(), {}, { logError: false, strict: true });
+ return Object.fromEntries(SOURCES.map((source) => [source, raw?.[source] && typeof raw[source] === 'object' ? raw[source] : {}]));
+}
+
+function makeFileBackend() {
+ return {
+ name: 'file',
+ archive: (source, tasks) => queueFileWrite(async () => {
+ const archive = await readFileArchive();
+ for (const task of tasks) archive[source][task.id] = task;
+ await atomicWrite(archiveFile(), archive);
+ }),
+ async get(taskId, source) {
+ const archive = await readFileArchive();
+ for (const candidate of source ? [source] : SOURCES) {
+ if (archive[candidate][taskId]) return { source: candidate, task: archive[candidate][taskId] };
+ }
+ return null;
+ },
+ async existingIds(source, ids) {
+ const archive = await readFileArchive();
+ return new Set(ids.filter((id) => archive[source][id]));
+ },
+ async list(source, { before, offset, limit }) {
+ const archive = await readFileArchive();
+ return Object.values(archive[source])
+ .filter((task) => before == null || task.id < before)
+ .sort(byIdDesc)
+ .slice(offset, offset + limit);
+ },
+ async count(source) {
+ return Object.keys((await readFileArchive())[source]).length;
+ },
+ async summaries() {
+ const archive = await readFileArchive();
+ return SOURCES.flatMap((source) => Object.values(archive[source]).map((task) => ({ source, id: task.id, description: descriptionOf(task) })));
+ },
+ remove: (taskId, source) => queueFileWrite(async () => {
+ const archive = await readFileArchive();
+ let removed = false;
+ for (const candidate of source ? [source] : SOURCES) {
+ if (archive[candidate][taskId]) { delete archive[candidate][taskId]; removed = true; }
+ }
+ if (removed) await atomicWrite(archiveFile(), archive);
+ return removed;
+ }),
+ };
+}
+
+/** The PostgreSQL backend over a `{ query }` handle. Exported so the DB suite can drive it directly. */
+export function __makePgCosTaskArchiveBackend(db) {
+ return {
+ name: 'postgres',
+ async archive(source, tasks) {
+ for (const task of tasks) {
+ await db.query(
+ `INSERT INTO cos_task_archive (source, task_id, description, completed_at, task)
+ VALUES ($1, $2, $3, $4, $5::jsonb)
+ ON CONFLICT (source, task_id) DO UPDATE
+ SET description = EXCLUDED.description, completed_at = EXCLUDED.completed_at, task = EXCLUDED.task`,
+ [source, task.id, descriptionOf(task), completedAtOf(task), JSON.stringify(task)],
+ );
+ }
+ },
+ async get(taskId, source) {
+ const { rows } = await db.query(
+ // User queue first, matching findTaskWithSource's file precedence on an id collision.
+ `SELECT source, task FROM cos_task_archive WHERE task_id = $1 AND ($2::text IS NULL OR source = $2)
+ ORDER BY (source = 'user') DESC LIMIT 1`,
+ [taskId, source],
+ );
+ return rows[0] ? { source: rows[0].source, task: rows[0].task } : null;
+ },
+ async existingIds(source, ids) {
+ if (ids.length === 0) return new Set();
+ const { rows } = await db.query('SELECT task_id FROM cos_task_archive WHERE source = $1 AND task_id = ANY($2::text[])', [source, ids]);
+ return new Set(rows.map((row) => row.task_id));
+ },
+ async list(source, { before, offset, limit }) {
+ const { rows } = await db.query(
+ `SELECT task FROM cos_task_archive WHERE source = $1 AND ($2::text IS NULL OR task_id < $2)
+ ORDER BY task_id DESC LIMIT $3 OFFSET $4`,
+ [source, before ?? null, limit, offset],
+ );
+ return rows.map((row) => row.task);
+ },
+ async count(source) {
+ const { rows } = await db.query('SELECT count(*)::int AS n FROM cos_task_archive WHERE source = $1', [source]);
+ return rows[0].n;
+ },
+ async summaries() {
+ const { rows } = await db.query('SELECT source, task_id, description FROM cos_task_archive');
+ return rows.map((row) => ({ source: row.source, id: row.task_id, description: row.description }));
+ },
+ async remove(taskId, source) {
+ const { rowCount } = await db.query('DELETE FROM cos_task_archive WHERE task_id = $1 AND ($2::text IS NULL OR source = $2)', [taskId, source]);
+ return rowCount > 0;
+ },
+ };
+}
+
+const backendFacade = createPgFileFacade({
+ makeFile: makeFileBackend,
+ makePg: () => resolvePgBackend({
+ requirement: 'The CoS task archive requires PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the file escape hatch)',
+ loadDb: () => import('../lib/db.js'),
+ makePg: __makePgCosTaskArchiveBackend,
+ }),
+});
+const backend = async () => backendFacade.getBackend();
+
+/** Upsert full task records for one source. Idempotent: a retried sweep rewrites the same rows. */
+export async function archiveTasks(source, tasks) {
+ if (!SOURCES.includes(source) || tasks.length === 0) return;
+ await (await backend()).archive(source, tasks);
+}
+
+/** One archived task as `{ source, task }`, or null. Omit `source` to search both. */
+export async function getArchivedTask(taskId, source = null) {
+ return (await backend()).get(taskId, source);
+}
+
+/** The subset of `ids` already archived for `source`. */
+export async function getArchivedIds(source, ids) {
+ return (await backend()).existingIds(source, ids);
+}
+
+/** Up to `limit` archived tasks newest id first, strictly before `before`, skipping `offset`. */
+export async function listArchivedTasks(source, { before = null, offset = 0, limit = 25 } = {}) {
+ return (await backend()).list(source, { before, offset, limit });
+}
+
+export async function countArchivedTasks(source) {
+ return (await backend()).count(source);
+}
+
+/** `{ source, id, description }` for every archived task, without the prompt bodies. */
+export async function listArchivedSummaries() {
+ return (await backend()).summaries();
+}
+
+export async function deleteArchivedTask(taskId, source = null) {
+ return (await backend()).remove(taskId, source);
+}
+
+/** Test seam for suites that swap the file data root between cases. */
+export function __resetCosTaskArchive() {
+ backendFacade.reset();
+}
diff --git a/server/services/cosTaskArchive.test.js b/server/services/cosTaskArchive.test.js
new file mode 100644
index 0000000000..ab4ebba0ef
--- /dev/null
+++ b/server/services/cosTaskArchive.test.js
@@ -0,0 +1,72 @@
+/**
+ * File backend of the completed-task archive (the dev/test escape hatch). The
+ * PostgreSQL backend is covered by cosTaskArchive.db.test.js against the same
+ * contract: newest-id-first paging, a strict `before` cursor, upsert by
+ * (source, id), and light summaries without prompt bodies.
+ */
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { rmSync } from 'node:fs';
+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';
+
+const { makeProxy, cleanup, tempRoot } = mockPathsDataRoot({ prefix: 'cos-task-archive-test-' });
+vi.mock('../lib/fileUtils.js', async () => makeProxy(await vi.importActual('../lib/fileUtils.js')));
+
+const {
+ archiveTasks, countArchivedTasks, deleteArchivedTask, getArchivedIds, getArchivedTask,
+ listArchivedSummaries, listArchivedTasks, __resetCosTaskArchive,
+} = await import('./cosTaskArchive.js');
+
+const task = (id, extra = {}) => ({ id, description: `Example ${id}`, status: 'completed', priority: 'MEDIUM', metadata: { prompt: `Prompt for ${id}` }, ...extra });
+
+beforeEach(() => {
+ rmSync(`${tempRoot}/cos-task-archive.json`, { force: true });
+ __resetCosTaskArchive();
+});
+afterAll(cleanup);
+
+describe('cosTaskArchive (file backend)', () => {
+ it('round-trips a full record per source and upserts by id', async () => {
+ await archiveTasks('user', [task('task-a')]);
+ await archiveTasks('internal', [task('sys-a')]);
+ await archiveTasks('user', [task('task-a', { description: 'Edited' })]);
+ expect(await getArchivedTask('task-a')).toEqual({ source: 'user', task: expect.objectContaining({ description: 'Edited', metadata: { prompt: 'Prompt for task-a' } }) });
+ expect(await getArchivedTask('sys-a', 'internal')).toMatchObject({ source: 'internal' });
+ expect(await getArchivedTask('sys-a', 'user')).toBeNull();
+ expect(await countArchivedTasks('user')).toBe(1);
+ });
+
+ it('pages newest id first with a strict before cursor, in code-unit order', async () => {
+ await archiveTasks('user', ['task-b', 'task-a', 'task-C', 'task-d'].map((id) => task(id)));
+ expect((await listArchivedTasks('user', { limit: 10 })).map((t) => t.id)).toEqual(['task-d', 'task-b', 'task-a', 'task-C']);
+ expect((await listArchivedTasks('user', { before: 'task-b', limit: 2 })).map((t) => t.id)).toEqual(['task-a', 'task-C']);
+ expect(await listArchivedTasks('user', { before: 'task-C', limit: 5 })).toEqual([]);
+ expect((await listArchivedTasks('user', { offset: 1, limit: 2 })).map((t) => t.id)).toEqual(['task-b', 'task-a']);
+ });
+
+ it('reports which ids are archived, summaries without prompt bodies, and deletes by source', async () => {
+ await archiveTasks('user', [task('task-a'), task('task-b')]);
+ await archiveTasks('internal', [task('sys-a')]);
+ expect(await getArchivedIds('user', ['task-a', 'task-z', 'sys-a'])).toEqual(new Set(['task-a']));
+ expect(await getArchivedIds('user', [])).toEqual(new Set());
+ const summaries = await listArchivedSummaries();
+ expect(summaries).toHaveLength(3);
+ expect(summaries).toContainEqual({ source: 'internal', id: 'sys-a', description: 'Example sys-a' });
+ expect(JSON.stringify(summaries)).not.toContain('Prompt for');
+ expect(await deleteArchivedTask('sys-a', 'user')).toBe(false);
+ expect(await deleteArchivedTask('sys-a')).toBe(true);
+ expect(await countArchivedTasks('internal')).toBe(0);
+ });
+
+ it('looks an id up user-first when both queues archived the same id', async () => {
+ await archiveTasks('internal', [task('task-shared', { description: 'Internal copy' })]);
+ await archiveTasks('user', [task('task-shared', { description: 'User copy' })]);
+ expect(await getArchivedTask('task-shared')).toMatchObject({ source: 'user', task: { description: 'User copy' } });
+ expect(await getArchivedTask('task-shared', 'internal')).toMatchObject({ source: 'internal' });
+ });
+
+ it('ignores an unknown source and an empty batch', async () => {
+ await archiveTasks('elsewhere', [task('task-a')]);
+ await archiveTasks('user', []);
+ expect(await countArchivedTasks('user')).toBe(0);
+ });
+});
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index d441a6d91f..9aee8657e4 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -39,6 +39,7 @@ import { hasActiveTaskOwner } from './agentState.js';
import { cosEvents } from './cosEvents.js';
import { CLAIM_METADATA_KEYS } from './cosTaskClaim.js';
import { mergeTaskLists } from './cosTaskMerge.js';
+import { archiveTasks, countArchivedTasks, deleteArchivedTask, getArchivedIds, getArchivedTask, listArchivedTasks } from './cosTaskArchive.js';
import { buildQueuedTask } from './cosTaskIntake.js';
import { canChallenge, getChallengeCount, buildChallengePatch, buildChallengeResolutionPatch, classifyRecheckOutcome, MAX_CHALLENGES_PER_TASK } from './cosChallenge.js';
import { runLocalCodeReview, getCodeReviewDefaults } from './codeReview.js';
@@ -341,11 +342,18 @@ function sourceShape(type, filePath, tasks, { exists = true } = {}) {
async function readQueueView(selected) {
const read = async (type) => {
const filePath = await resolveSourceFile(type);
- if (!filePath) return { ...sourceShape(type, filePath, [], { exists: false }), completedCount: 0 };
+ const archivedCount = await countArchivedTasks(type);
+ if (!filePath) return { ...sourceShape(type, filePath, [], { exists: false }), completedCount: archivedCount };
const snapshot = await readTaskSnapshot(filePath);
const { open, completed } = snapshotPartitions(snapshot);
const refs = selected === undefined ? open : snapshot.tasks.filter((task) => !isCompleted(task) || task.id === selected);
- return { ...sourceShape(type, filePath, structuredClone(refs)), completedCount: completed.length };
+ const tasks = structuredClone(refs);
+ // A selected historical task that has aged out of the file lives in the archive.
+ if (selected !== undefined && !refs.some((task) => task.id === selected)) {
+ const archived = await getArchivedTask(selected, type);
+ if (archived) tasks.push(archived.task);
+ }
+ return { ...sourceShape(type, filePath, tasks), completedCount: completed.length + archivedCount };
};
const [user, cos] = await Promise.all([read('user'), read('internal')]);
return { user, cos };
@@ -355,36 +363,61 @@ async function readQueueView(selected) {
async function readBareView() {
const read = async (type) => {
const filePath = await resolveSourceFile(type);
- if (!filePath) return { ...sourceShape(type, filePath, [], { exists: false }), completedCount: 0, completedNextCursor: null };
- const { open, completed } = snapshotPartitions(await readTaskSnapshot(filePath));
- const firstPage = completed.slice(0, COMPLETED_FIRST_PAGE);
- const shape = sourceShape(type, filePath, structuredClone([...open, ...firstPage]));
+ const { open, completed } = filePath ? snapshotPartitions(await readTaskSnapshot(filePath)) : { open: [], completed: [] };
+ const page = await pageCompleted(type, completed, { limit: COMPLETED_FIRST_PAGE });
+ const shape = sourceShape(type, filePath, [...structuredClone(open), ...page.items], { exists: Boolean(filePath) });
// Completed rows leave `grouped`; only the page inside `tasks` carries them.
- return { ...shape, grouped: { ...shape.grouped, completed: [] }, completedCount: completed.length,
- completedNextCursor: completed.length > COMPLETED_FIRST_PAGE ? firstPage[firstPage.length - 1].id : null };
+ return { ...shape, grouped: { ...shape.grouped, completed: [] }, completedCount: page.total, completedNextCursor: page.nextCursor };
};
const [user, cos] = await Promise.all([read('user'), read('internal')]);
return { user, cos };
}
+/**
+ * One page of completed history from ONE source, newest id first, merged from
+ * the file's recent window and the archive. A task caught between archive and
+ * file removal exists in both; the file copy wins. `completedRefs` are snapshot
+ * references (newest first); only the returned page is cloned.
+ */
+async function pageCompleted(type, completedRefs, { cursor = null, limit }) {
+ const fileRemaining = cursor ? completedRefs.filter((task) => task.id < cursor) : completedRefs;
+ const filePage = fileRemaining.slice(0, limit + 1);
+ const fileIds = new Set(filePage.map((task) => task.id));
+ const archivedPage = (await listArchivedTasks(type, { before: cursor, limit: limit + 1 })).filter((task) => !fileIds.has(task.id));
+ const merged = [...filePage, ...archivedPage].sort(byIdDesc).slice(0, limit + 1);
+ const items = merged.slice(0, limit);
+ const total = completedRefs.length + await countArchivedTasks(type);
+ return {
+ items: items.map((task) => (fileIds.has(task.id) ? structuredClone(task) : task)),
+ total,
+ nextCursor: merged.length > limit ? items[limit - 1].id : null,
+ };
+}
+
/** One page of completed history from ONE source, newest id first. */
async function readCompletedView({ source, cursor, limit }) {
const type = source === 'internal' ? 'internal' : 'user';
const filePath = await resolveSourceFile(type);
- if (!filePath) return { items: [], total: 0, nextCursor: null };
- const { completed } = snapshotPartitions(await readTaskSnapshot(filePath));
- const remaining = cursor ? completed.filter((task) => task.id < cursor) : completed;
- return { items: structuredClone(remaining.slice(0, limit)), total: completed.length,
- nextCursor: remaining.length > limit ? remaining[limit - 1].id : null };
+ const completed = filePath ? snapshotPartitions(await readTaskSnapshot(filePath)).completed : [];
+ return pageCompleted(type, completed, { cursor, limit });
}
-/** Legacy limit/offset window: the slice and scalar metadata only. */
+/**
+ * Legacy limit/offset window over each queue's tasks: the file's tasks in file
+ * order, then the archived completed tasks newest id first. The slice and scalar
+ * metadata only.
+ */
async function readWindowView({ offset, limit }) {
const read = async (type) => {
const filePath = await resolveSourceFile(type);
- if (!filePath) return { meta: { file: filePath, exists: false, type }, tasks: [], total: 0 };
- const snapshot = await readTaskSnapshot(filePath);
- return { meta: { file: filePath, exists: true, type }, tasks: structuredClone(snapshot.tasks.slice(offset, offset + limit)), total: snapshot.tasks.length };
+ const fileTasks = filePath ? (await readTaskSnapshot(filePath)).tasks : [];
+ const fileSlice = structuredClone(fileTasks.slice(offset, offset + limit));
+ const archivedWanted = limit - fileSlice.length;
+ const archived = archivedWanted > 0
+ ? await listArchivedTasks(type, { offset: Math.max(0, offset - fileTasks.length), limit: archivedWanted })
+ : [];
+ const total = fileTasks.length + await countArchivedTasks(type);
+ return { meta: { file: filePath, exists: Boolean(filePath), type }, tasks: [...fileSlice, ...archived], total };
};
const [user, cos] = await Promise.all([read('user'), read('internal')]);
return {
@@ -493,7 +526,9 @@ export async function findTaskWithSource(taskId) {
const cosTask = await findTaskInFile(join(ROOT_DIR, config.cosTasksFile), taskId);
if (cosTask) return { task: cosTask, source: 'internal' };
- return null;
+ // Completed history older than the file window lives in the archive.
+ const archived = await getArchivedTask(taskId);
+ return archived ? { task: archived.task, source: archived.source } : null;
}
// Legacy shape: the source overwrites the record's `taskType`. Callers that
@@ -810,7 +845,19 @@ async function writeTaskUpdateLocked(taskId, updates, taskType, { now, suppressD
let tasks = await readTaskFile(filePath);
- const taskIndex = tasks.findIndex(t => t.id === taskId);
+ let taskIndex = tasks.findIndex(t => t.id === taskId);
+ // A history item the archive sweep moved out of the file can still be edited or
+ // reopened: pull it back, apply the update, and drop the archive row only once
+ // the file write lands. An early return below leaves the archive untouched.
+ let restoredFromArchive = false;
+ if (taskIndex === -1) {
+ const archived = await getArchivedTask(taskId, taskType);
+ if (archived) {
+ tasks.push(archived.task);
+ taskIndex = tasks.length - 1;
+ restoredFromArchive = true;
+ }
+ }
if (taskIndex === -1) {
console.log(`⚠️ updateTask: task ${taskId} not found in ${filePath} (taskType=${taskType}, parsed ${tasks.length} tasks, status update: ${updates.status || 'none'})`);
return { error: 'Task not found' };
@@ -946,6 +993,7 @@ async function writeTaskUpdateLocked(taskId, updates, taskType, { now, suppressD
const includeApprovalFlags = taskType === 'internal';
const markdown = generateTasksMarkdown(tasks, includeApprovalFlags);
await writeTaskFile(filePath, markdown);
+ if (restoredFromArchive) await deleteArchivedTask(taskId, taskType);
// `transition.action` distinguishes the two flips that must WAKE the scheduler
// from an ordinary edit. A blocked → pending flip is a revive: the task is newly
@@ -1035,7 +1083,15 @@ export async function mergePeerTasks(taskType, remoteTasks, { now = Date.now() }
? await readTaskFile(filePath)
: [];
- const merged = mergeTaskLists(localTasks, remoteTasks, { now });
+ // A peer's file still holds completed tasks this machine has archived; merging
+ // them back would resurrect history the sweep already moved out of the file.
+ const remoteCompletedIds = remoteTasks.filter((task) => task?.status === 'completed').map((task) => task.id);
+ const archivedIds = await getArchivedIds(taskType, remoteCompletedIds);
+ const incoming = archivedIds.size === 0
+ ? remoteTasks
+ : remoteTasks.filter((task) => !(task?.status === 'completed' && archivedIds.has(task.id)));
+
+ const merged = mergeTaskLists(localTasks, incoming, { now });
const includeApprovalFlags = taskType === 'internal';
const localMarkdown = generateTasksMarkdown(localTasks, includeApprovalFlags);
@@ -1085,24 +1141,23 @@ export async function deleteTask(taskId, taskType = 'user') {
? join(ROOT_DIR, state.config.userTasksFile)
: join(ROOT_DIR, state.config.cosTasksFile);
- if (!existsSync(filePath)) {
- return { error: 'Task file not found' };
+ let deletedFromFile = false;
+ if (existsSync(filePath)) {
+ const tasks = await readTaskFile(filePath);
+ if (tasks.some(t => t.id === taskId)) {
+ const includeApprovalFlags = taskType === 'internal';
+ await writeTaskFile(filePath, generateTasksMarkdown(tasks.filter(t => t.id !== taskId), includeApprovalFlags));
+ deletedFromFile = true;
+ }
}
- let tasks = await readTaskFile(filePath);
-
- const taskToDelete = tasks.find(t => t.id === taskId);
- if (!taskToDelete) {
- return { error: 'Task not found' };
+ // The archive copy goes too: during the sweep's archive-then-rewrite window a
+ // task lives in both stores, and a file-only delete would leave it in history.
+ const deletedFromArchive = await deleteArchivedTask(taskId, taskType);
+ if (!deletedFromFile && !deletedFromArchive) {
+ return { error: existsSync(filePath) ? 'Task not found' : 'Task file not found' };
}
- tasks = tasks.filter(t => t.id !== taskId);
-
- // Write back to file
- const includeApprovalFlags = taskType === 'internal';
- const markdown = generateTasksMarkdown(tasks, includeApprovalFlags);
- await writeTaskFile(filePath, markdown);
-
cosEvents.emit('tasks:changed', { type: taskType, action: 'deleted', taskId });
return { success: true, taskId };
});
@@ -1309,6 +1364,66 @@ export async function sweepResolvedFailureTasks({
return { reaped, staleBlocks, investigations };
}
+// ── Completed-task archive ──────────────────────────────────────────────────
+//
+// TASKS.md / COS-TASKS.md grew to tens of MB because every finished task keeps
+// its full prompt, and every full-queue read clones all of it. Completed tasks
+// past the recent window move to `cos_task_archive`; the files keep the open
+// queue plus that window, which is what dedup, retry bookkeeping and the PR
+// reviewer-failure lookup actually consult.
+const ARCHIVE_AFTER_MS = 3 * 24 * 60 * 60 * 1000;
+const ARCHIVE_KEEP_NEWEST = 100;
+// Bounds how long one sweep holds the state lock; a first run over a large
+// backlog drains across several ticks.
+const ARCHIVE_SWEEP_LIMIT = 300;
+
+// Undated tasks sort as oldest: they predate the stamps current writers add.
+const completionStamp = (task) => {
+ const stamp = Date.parse(task.metadata?.completedAt || task.metadata?.updatedAt || '');
+ return Number.isFinite(stamp) ? stamp : 0;
+};
+
+/** Completed tasks old enough, and beyond the newest few, to leave the file. Oldest first. */
+function selectArchivable(tasks, { now, afterMs, keepNewest, limit }) {
+ const completed = tasks.filter(isCompleted).sort((a, b) => completionStamp(b) - completionStamp(a) || byIdDesc(a, b));
+ return completed
+ .slice(keepNewest)
+ .filter((task) => completionStamp(task) <= now - afterMs)
+ .reverse()
+ .slice(0, limit);
+}
+
+/**
+ * Move aged completed tasks out of the task files into the archive. The archive
+ * write lands first and is idempotent, so a crash before the file rewrite leaves
+ * a harmless duplicate that the next sweep removes. Runs under the same lock as
+ * every task write.
+ */
+export async function archiveCompletedTasks({
+ now = Date.now(),
+ afterMs = ARCHIVE_AFTER_MS,
+ keepNewest = ARCHIVE_KEEP_NEWEST,
+ limit = ARCHIVE_SWEEP_LIMIT,
+} = {}) {
+ let archived = 0;
+ for (const type of ['user', 'internal']) {
+ archived += await withStateLock(async () => {
+ const filePath = await resolveSourceFile(type);
+ if (!filePath) return 0;
+ const snapshot = await readTaskSnapshot(filePath);
+ const selected = selectArchivable(snapshot.tasks, { now, afterMs, keepNewest, limit });
+ if (selected.length === 0) return 0;
+ await archiveTasks(type, structuredClone(selected));
+ const leaving = new Set(selected.map((task) => task.id));
+ await writeTaskFile(filePath, generateTasksMarkdown(snapshot.tasks.filter((task) => !leaving.has(task.id)), type === 'internal'));
+ cosEvents.emit('tasks:changed', { type, action: 'archived' });
+ return selected.length;
+ });
+ }
+ if (archived > 0) console.log(`🗄️ Archived ${archived} completed task(s) out of the task files`);
+ return { archived };
+}
+
/**
* Reorder user tasks based on an array of task IDs
*/
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index ec04205b86..08ebf042a2 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -40,7 +40,9 @@ const mock = vi.hoisted(() => ({
reviewDefaults: { lmstudioModel: 'default-lmstudio', ollamaModel: 'default-ollama' },
reviewCalls: [],
// Captures cross-peer LI execution verdicts consumed by mergePeerTasks (#2779).
- liVerdicts: []
+ liVerdicts: [],
+ // In-memory stand-in for the cos_task_archive table, per source.
+ archive: { user: new Map(), internal: new Map() }
}));
// existsSync is driven by the in-memory file map; readFileSync stays real so
@@ -105,6 +107,34 @@ vi.mock('./cos.js', () => ({
updateTask: (...args) => updateTask(...args),
}));
+// The archive adapter is a PostgreSQL/JSON store; this suite mocks the filesystem
+// wholesale, so it gets an in-memory table with the same ordering and `before`
+// cursor semantics as the real adapter.
+vi.mock('./cosTaskArchive.js', () => {
+ const sources = ['user', 'internal'];
+ const byIdDesc = (a, b) => (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
+ return {
+ archiveTasks: vi.fn(async (source, tasks) => { for (const task of tasks) mock.archive[source].set(task.id, task); }),
+ getArchivedTask: vi.fn(async (taskId, source = null) => {
+ for (const candidate of source ? [source] : sources) {
+ if (mock.archive[candidate].has(taskId)) return { source: candidate, task: structuredClone(mock.archive[candidate].get(taskId)) };
+ }
+ return null;
+ }),
+ getArchivedIds: vi.fn(async (source, ids) => new Set(ids.filter((id) => mock.archive[source].has(id)))),
+ listArchivedTasks: vi.fn(async (source, { before = null, offset = 0, limit = 25 } = {}) => [...mock.archive[source].values()]
+ .filter((task) => before == null || task.id < before).sort(byIdDesc).slice(offset, offset + limit).map((task) => structuredClone(task))),
+ countArchivedTasks: vi.fn(async (source) => mock.archive[source].size),
+ listArchivedSummaries: vi.fn(async () => sources.flatMap((source) => [...mock.archive[source].values()]
+ .map((task) => ({ source, id: task.id, description: task.description || '' })))),
+ deleteArchivedTask: vi.fn(async (taskId, source = null) => {
+ let removed = false;
+ for (const candidate of source ? [source] : sources) removed = mock.archive[candidate].delete(taskId) || removed;
+ return removed;
+ }),
+ };
+});
+
vi.mock('./cosEvents.js', () => ({
emitLog: vi.fn(),
cosEvents: { emit: (name, payload) => mock.events.push({ name, payload }) }
@@ -149,6 +179,8 @@ import {
isReapableBlockedFailure,
isReapableInvestigation,
sweepResolvedFailureTasks,
+ archiveCompletedTasks,
+ findTaskWithSource,
reconcileLegacyForgeMaintenanceTasks,
DEFAULT_FAILURE_TASK_MAX_AGE_MS,
__resetTaskCache
@@ -171,6 +203,7 @@ beforeEach(() => {
mock.afterWrite = null;
mock.files = new Map();
mock.mtimes = new Map();
+ mock.archive = { user: new Map(), internal: new Map() };
mock.parseCalls = 0;
// The parse cache is module-level state; a leftover entry from the previous
// test would answer for a path this test just re-created from scratch.
@@ -2937,3 +2970,174 @@ it('round-trips the server-owned audit disposition contract through persisted ta
const reloaded = await getTaskById(created.id);
expect(reloaded.metadata).toMatchObject({ analysisType: 'security', auditDispositionVersion: '1', fileIssues: 'false' });
});
+
+// Completed-task archive. TASKS.md / COS-TASKS.md keep the open queue plus a recent
+// window of completed tasks; older completed tasks move to the archive with their
+// full records. The fake archive above mirrors the real adapter's contract.
+describe('cosTaskStore completed-task archive', () => {
+ const DAY = 86_400_000;
+ const CLOCK = Date.parse('2026-10-20T12:00:00Z');
+ const id = (n) => `task-example-${String(n).padStart(4, '0')}`;
+ const done = (n, ageDays, extra = {}) => ({
+ id: id(n), description: `Example task ${n}`, status: 'completed', priority: 'MEDIUM',
+ metadata: { updatedAt: new Date(CLOCK - ageDays * DAY).toISOString(), prompt: `Prompt body ${n}.` }, ...extra,
+ });
+ const pending = (n) => ({ id: id(n), description: `Example task ${n}`, status: 'pending', priority: 'MEDIUM', metadata: {} });
+ const writeUser = (tasks) => mock.files.set(USER_FILE, generateTasksMarkdown(tasks));
+ const fileIds = (file = USER_FILE) => parseTasksMarkdown(mock.files.get(file)).map((task) => task.id);
+ const archiveIds = (source = 'user') => [...mock.archive[source].keys()].sort();
+
+ describe('archiveCompletedTasks', () => {
+ it('moves only completed tasks past both the age and newest-N floor, with their full records', async () => {
+ writeUser([pending(1), done(2, 10), done(3, 9), done(4, 8), done(5, 1), done(6, 0)]);
+ // keepNewest 1 leaves the 1-day-old task rank-eligible, so only the age floor keeps it.
+ const res = await archiveCompletedTasks({ now: CLOCK, keepNewest: 1 });
+ expect(res).toEqual({ archived: 3 });
+ expect(archiveIds()).toEqual([id(2), id(3), id(4)]);
+ expect(mock.archive.user.get(id(2)).metadata.prompt).toBe('Prompt body 2.');
+ expect(fileIds().sort()).toEqual([id(1), id(5), id(6)]);
+ expect(mock.events.some((e) => e.name === 'tasks:changed' && e.payload.action === 'archived')).toBe(true);
+ });
+
+ it('keeps the newest completed tasks however old they are, and treats undated tasks as oldest', async () => {
+ writeUser([done(1, 30), done(2, 20), done(3, 10), done(4, 5), { ...done(5, 0), metadata: {} }]);
+ expect(await archiveCompletedTasks({ now: CLOCK, keepNewest: 4 })).toEqual({ archived: 1 });
+ expect(archiveIds()).toEqual([id(5)]);
+ });
+
+ it('drains the oldest first under the per-sweep limit and is idempotent once drained', async () => {
+ writeUser([done(1, 40), done(2, 30), done(3, 20), done(4, 10), done(5, 5)]);
+ expect(await archiveCompletedTasks({ now: CLOCK, keepNewest: 0, limit: 2 })).toEqual({ archived: 2 });
+ expect(archiveIds()).toEqual([id(1), id(2)]);
+ expect(await archiveCompletedTasks({ now: CLOCK, keepNewest: 0, limit: 10 })).toEqual({ archived: 3 });
+ expect(fileIds()).toEqual([]);
+ expect(await archiveCompletedTasks({ now: CLOCK, keepNewest: 0 })).toEqual({ archived: 0 });
+ });
+
+ it('leaves a duplicate, never a loss, when the file rewrite dies after the archive write', async () => {
+ writeUser([done(1, 10), done(2, 9)]);
+ mock.atomicFailure = new Error('disk full');
+ await expect(archiveCompletedTasks({ now: CLOCK, keepNewest: 0 })).rejects.toThrow('disk full');
+ expect(archiveIds()).toEqual([id(1), id(2)]);
+ expect(fileIds().sort()).toEqual([id(1), id(2)]);
+ mock.atomicFailure = null;
+ expect(await archiveCompletedTasks({ now: CLOCK, keepNewest: 0 })).toEqual({ archived: 2 });
+ expect(fileIds()).toEqual([]);
+ expect(archiveIds()).toEqual([id(1), id(2)]);
+ });
+
+ it('does nothing when a task file does not exist', async () => {
+ expect(await archiveCompletedTasks({ now: CLOCK })).toEqual({ archived: 0 });
+ });
+ });
+
+ describe('reads fall through to the archive', () => {
+ const seedSplit = () => {
+ // Archive holds the oldest ids, the file holds the recent window.
+ for (const n of [1, 2, 3, 4]) mock.archive.user.set(id(n), done(n, 20));
+ writeUser([pending(9), done(5, 1), done(6, 1), done(7, 0)]);
+ };
+
+ it('pages completed history across the file window and the archive, newest id first', async () => {
+ seedSplit();
+ const first = await getTaskView({ kind: 'completed', source: 'user', limit: 5 });
+ expect(first.items.map((task) => task.id)).toEqual([id(7), id(6), id(5), id(4), id(3)]);
+ expect(first.total).toBe(7);
+ expect(first.nextCursor).toBe(id(3));
+ const second = await getTaskView({ kind: 'completed', source: 'user', cursor: first.nextCursor, limit: 5 });
+ expect(second.items.map((task) => task.id)).toEqual([id(2), id(1)]);
+ expect(second.nextCursor).toBeNull();
+ });
+
+ it('counts archived history in the queue and bare views, and returns a selected archived task', async () => {
+ seedSplit();
+ const queue = await getTaskView({ kind: 'queue', selected: id(2) });
+ expect(queue.user.completedCount).toBe(7);
+ expect(queue.user.tasks.map((task) => task.id).sort()).toEqual([id(2), id(9)]);
+ expect(queue.user.tasks.find((task) => task.id === id(2)).metadata.prompt).toBe('Prompt body 2.');
+ const bare = await getTaskView({ kind: 'bare' });
+ expect(bare.user.completedCount).toBe(7);
+ expect(bare.user.completedNextCursor).toBeNull();
+ expect(bare.user.tasks.map((task) => task.id)).toHaveLength(8);
+ });
+
+ it('finds an archived task by id, preferring the file copy and the user queue', async () => {
+ seedSplit();
+ const found = await findTaskWithSource(id(2));
+ expect(found).toMatchObject({ source: 'user', task: { id: id(2), status: 'completed' } });
+ expect(await getTaskById(id(2))).toMatchObject({ id: id(2), taskType: 'user' });
+ mock.archive.user.set(id(5), { ...done(5, 20), description: 'stale archived copy' });
+ expect((await getTaskById(id(5))).description).toBe('Example task 5');
+ expect(await getTaskById(id(99))).toBeNull();
+ });
+
+ it('deletes an archived task and reports an unknown one as not found', async () => {
+ seedSplit();
+ expect(await deleteTask(id(2), 'user')).toEqual({ success: true, taskId: id(2) });
+ expect(archiveIds()).toEqual([id(1), id(3), id(4)]);
+ expect(await deleteTask(id(2), 'user')).toEqual({ error: 'Task not found' });
+ });
+ });
+
+ describe('archived tasks stay usable', () => {
+ it('reopens an archived task: pulls it back into the file, applies the edit, and drops the archive row', async () => {
+ mock.archive.user.set(id(1), done(1, 20));
+ writeUser([pending(2)]);
+ const result = await updateTask(id(1), { status: 'pending', description: 'Reopened task' }, 'user', { now: CLOCK });
+ expect(result).toMatchObject({ id: id(1), status: 'pending', description: 'Reopened task' });
+ expect(fileIds().sort()).toEqual([id(1), id(2)]);
+ expect(archiveIds()).toEqual([]);
+ expect(mock.events.some((e) => e.name === 'tasks:changed' && e.payload.type === 'user')).toBe(true);
+ });
+
+ it('keeps the archive row when the update is refused before the file write', async () => {
+ mock.archive.user.set(id(1), done(1, 20));
+ writeUser([pending(2)]);
+ const result = await updateTask(id(1), { status: 'pending' }, 'user', { now: CLOCK, expectedStatus: 'blocked' });
+ expect(result).toMatchObject({ statusChanged: true });
+ expect(archiveIds()).toEqual([id(1)]);
+ expect(fileIds()).toEqual([id(2)]);
+ });
+
+ it('still reports an id that is in neither store as not found', async () => {
+ writeUser([pending(2)]);
+ expect(await updateTask(id(9), { status: 'pending' }, 'user', { now: CLOCK })).toEqual({ error: 'Task not found' });
+ });
+
+ it('deletes both copies of a task caught between the archive write and the file rewrite', async () => {
+ mock.archive.user.set(id(1), done(1, 20));
+ writeUser([pending(2), done(1, 20)]);
+ expect(await deleteTask(id(1), 'user')).toEqual({ success: true, taskId: id(1) });
+ expect(fileIds()).toEqual([id(2)]);
+ expect(archiveIds()).toEqual([]);
+ });
+
+ it('deletes an archived task even when its task file is gone', async () => {
+ mock.archive.user.set(id(1), done(1, 20));
+ expect(await deleteTask(id(1), 'user')).toEqual({ success: true, taskId: id(1) });
+ expect(await deleteTask(id(1), 'user')).toEqual({ error: 'Task file not found' });
+ });
+
+ it('windows by offset across the file tasks, then the archive newest first, with a combined total', async () => {
+ for (const n of [1, 2, 3, 4]) mock.archive.user.set(id(n), done(n, 20));
+ writeUser([pending(9), done(5, 1)]);
+ const first = await getTaskView({ kind: 'window', offset: 0, limit: 3 });
+ expect(first.user.tasks.map((task) => task.id)).toEqual([id(9), id(5), id(4)]);
+ expect(first.totals.user).toBe(6);
+ const second = await getTaskView({ kind: 'window', offset: 3, limit: 5 });
+ expect(second.user.tasks.map((task) => task.id)).toEqual([id(3), id(2), id(1)]);
+ const fileOnly = await getTaskView({ kind: 'window', offset: 0, limit: 1 });
+ expect(fileOnly.user.tasks.map((task) => task.id)).toEqual([id(9)]);
+ });
+ });
+
+ it('does not let a peer resurrect a completed task this machine archived', async () => {
+ mock.archive.user.set(id(1), done(1, 20));
+ writeUser([pending(2)]);
+ const wire = (task) => ({ id: task.id, taskType: 'user', status: task.status, priority: task.priority, description: task.description, metadata: task.metadata });
+ const res = await mergePeerTasks('user', [wire(done(1, 20)), wire(done(3, 1)), wire(pending(4))], { now: CLOCK });
+ expect(res.changed).toBe(true);
+ // The archived completion stays out; an unarchived completion and a new open task still adopt.
+ expect(fileIds().sort()).toEqual([id(2), id(3), id(4)]);
+ });
+});
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 7d8c7973d5..e9cc32c979 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -4579,14 +4579,17 @@ describe('peerSync', () => {
// must not ride the federation layer at all (ADR
// 2026-08-08-privacy-records-machine-local), and a peer has no use for a
// record of a button someone pressed on another install.
+ // - cosTaskArchive is the completed-task history moved out of TASKS.md /
+ // COS-TASKS.md: prompt bodies and run notes for ONE machine. Peers merge only
+ // the tasks their own files hold, never this table.
// This guard pins that decision: federating any of them later is a conscious
// act — wire the kind AND update this assertion + the ADR together.
- const localOnlyKinds = ['tribe', 'tribePerson', 'tribeTouchpoint', 'tribeMemoryLink', 'tribeIdentity', 'universeRun', 'humanActivityEvent', 'userActionEvent'];
+ const localOnlyKinds = ['tribe', 'tribePerson', 'tribeTouchpoint', 'tribeMemoryLink', 'tribeIdentity', 'universeRun', 'humanActivityEvent', 'userActionEvent', 'cosTaskArchive'];
for (const kind of localOnlyKinds) {
expect(PEER_SUBSCRIBABLE_KINDS).not.toContain(kind);
expect(RECORD_KIND_SCHEMA_CATEGORIES[kind]).toBeUndefined();
}
- const localOnlyCategories = ['tribe', 'tribePeople', 'tribeTouchpoints', 'tribeMemoryLinks', 'tribeIdentities', 'universeRuns', 'humanActivityEvents', 'userActionEvents'];
+ const localOnlyCategories = ['tribe', 'tribePeople', 'tribeTouchpoints', 'tribeMemoryLinks', 'tribeIdentities', 'universeRuns', 'humanActivityEvents', 'userActionEvents', 'cosTaskArchive'];
for (const category of localOnlyCategories) {
expect(PORTOS_SCHEMA_VERSIONS[category]).toBeUndefined();
expect(NON_RECORD_SCHEMA_CATEGORIES.has(category)).toBe(false);