Skip to content

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

feat([issue-1650]): federate completed CoS agent history across full-sync peers

[._.]/ Adam Eivyb5e6e005ec33
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7a316d784f..0f036c99fc 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,6 +10,7 @@
## Federation
+- **[issue-1650] Completed Chief-of-Staff agent history now mirrors across full-sync peers.** Each paired machine's CoS history tab becomes a complete replica: a full-sync peer advertises its date-bucketed completed-agent archives (the metadata, transcript, and prompt for every finished agent), and the other machine receiver-pulls any it's missing on the ~60s sweep, verifies each file against its advertised hash before writing, then updates its history index so the arrivals appear. Archives are immutable once an agent finishes, so this is safe append-only replication — nothing is overwritten or merged. It runs only for peers explicitly flagged full-sync; a non-full-sync peer is unaffected. Live/running agents, their terminals, and worktrees stay machine-local as before. (Task-list and claim-metadata federation is tracked separately.) (`server/services/sharing/peerSync.js`, `server/routes/peerSync.js`, `server/services/cosAgents.js`)
- **[issue-1645] Writers Room folders and writing-sprint exercises now federate across peers.** Following works (#1644/#1565), the library's folders and exercise sessions replicate over the per-record peer-sync push pipeline with full last-writer-wins + tombstone semantics. Both tables gained soft-delete columns (`deleted`/`deleted_at`) so a deletion propagates as a tombstone the merge keeps until garbage-collected — the LWW model never propagates a hard delete, so omitting a record would let an out-of-date peer resurrect it. New record kinds `writersRoomFolder` / `writersRoomExercise` are wired through the schema-version gate, wire sanitizer, conflict journal (with restore), peer-sync subscribe/push/merge, tombstone GC, auto-subscribe-on-create, the Instances sync-category toggles, and both storage backends. Exercises predate federation and carry no `updatedAt`, so the wire sanitizer derives a stable LWW key from their existing `startedAt`/`finishedAt`. (`server/services/writersRoom/`, `server/services/sharing/peerSync.js`, `scripts/migrations/139-…`)
## Editorial checks
diff --git a/docs/plans/2026-06-25-cos-history-federation.md b/docs/plans/2026-06-25-cos-history-federation.md
new file mode 100644
index 0000000000..706b44fa89
--- /dev/null
+++ b/docs/plans/2026-06-25-cos-history-federation.md
@@ -0,0 +1,61 @@
+# Federate CoS completed-agent history across peers (issue #1650, partial ship)
+
+## Context
+
+Issue **#1650** is the last code child of epic **#1561** (full-sync federated node pairs). Today **none of `data/cos/` is in any sync category** — CoS agent history is fully machine-local. #1563 already shipped the safety prerequisites (instance provenance on every agent via `instanceId`, plus a task claim/lease protocol). #1650's remaining acceptance criterion is to **replicate completed-agent history archives so the CoS history UI mirrors on both machines**, gated behind full-sync peer mode (#1562) so a non-full-sync peer is unaffected.
+
+Completed agents archive to `data/cos/agents/<YYYY-MM-DD>/<agentId>/` (`metadata.json`, `output.txt`, `prompt.txt`) with a type-level `data/cos/agents/index.json` (`server/services/cosAgents.js`). This is a **directory tree of immutable, append-only files** (an archive never changes after completion; agentIds are globally unique) — so it belongs on the **asset-federation pull path**, not the `dataSync.js` snapshot path, and needs **no merge** (byte replication + union).
+
+**Scope decision (confirmed with user):** ship **history federation only** this PR. The issue's second deliverable — task-list + claim-metadata federation — needs a claim-aware per-task LWW merge of live-mutated markdown (a naive byte copy would clobber claims and re-introduce the double-spawn hazard) and is split to a **follow-up issue**. This PR therefore **Refs #1650 (not Closes)**; #1650 stays open for the task-merge piece; epic #1561 advances but is not closed.
+
+## Reference implementation — mirror, don't invent
+
+The **Writers Room draft-body federation** (`peerSync.js:2531-2598`) is the precise structural template: nested paths (not flat basenames), a dedicated manifest, a dedicated pull worker (`pullMissingWorkBodies` / `pullOneWorkBody`), sha256 integrity verification before write, and `peerDraftBodyManifestEntrySchema` (`peerSyncValidation.js:214`). The **media-library sweep** (`syncMediaLibraryFromPeer`, `peerSync.js:2868`) is the template for the receiver-side sweep loop: full-sync gate, re-entrancy guard, schema-ahead gentle-skip, diff → pull → re-diff, and **hash-withhold on partial** (`peerSync.js:2940-2948`). Reuse `fetchCappedAssetBuffer` (`peerSync.js:2488`), `inflightKey`/`inflightPulls`, `peerBaseUrl`, `peerFetch`, `atomicWrite`, `ensureDir`, `createHash`.
+
+## Implementation
+
+### 1. Sender — manifest builder (`server/services/sharing/peerSync.js`)
+Add a CoS-history block mirroring the media-library block (after ~`peerSync.js:2828`):
+- `buildCosHistoryManifest()` → `{ schemaVersion: PORTOS_SCHEMA_VERSIONS.cosHistory, manifestHash, entries }`. Walk `data/cos/agents/<date>/<agentId>/`, hashing each of `metadata.json` / `output.txt` / `prompt.txt` that exist. Entry shape: `{ date, agentId, file, sha256 }`. Skip the flat (running-agent) dirs and `index.json`; only date-bucketed completed archives. Sort entries deterministically (date, agentId, file) and `manifestHash = sha256` over `date:agentId:file:sha256` lines (mirrors `peerSync.js:2824`). Cap at a constant (e.g. `COS_HISTORY_MANIFEST_CAP = 100_000`) with a log on truncation (no silent caps).
+- Segment patterns: `DATE_RE = /^\d{4}-\d{2}-\d{2}$/`, an agentId pattern, and a `file ∈ {metadata.json, output.txt, prompt.txt}` allowlist — used by both the builder and the byte route.
+
+### 2. Sender — routes (`server/routes/peerSync.js`)
+- `GET /api/peer-sync/cos-history-manifest` → `buildCosHistoryManifest()` (mirror `/library-manifest`, `peerSync.js:159`).
+- `GET /api/peer-sync/cos-agent-archive?date=&agentId=&file=` → validate all three segments against the allowlists, resolve under `PATHS.cos/agents`, and `res.sendFile(absPath)` (sets content-length, which `fetchCappedAssetBuffer` requires). **Dedicated validated route, not a broadened static mount** — avoids exposing the whole `data/cos` tree (state.json, worktrees) and gives explicit path-segment validation (the "parse-not-existsSync" guard). 404 on missing/invalid.
+
+### 3. Receiver — sweep + pull (`server/services/sharing/peerSync.js`)
+- `syncCosHistoryFromPeer(peer)` — clone of `syncMediaLibraryFromPeer` (`peerSync.js:2868`): `peer.fullSync !== true` → skip; per-peer re-entrancy guard (`cosHistorySweepInFlight`); fetch manifest, Zod-validate, schema-ahead gentle-skip; unchanged-manifestHash short-circuit with `FORCE_REVALIDATE_EVERY`; `diffCosHistoryManifestAgainstLocal` → `pullMissingCosArchives` → re-diff; **withhold `lastCosHistoryManifestHash` on partial pull**.
+- `diffCosHistoryManifestAgainstLocal(entries)` — re-validate every segment, resolve local path under `PATHS.cos/agents`, return entries whose local file is absent or hash-mismatched.
+- `pullMissingCosArchives` / `pullOneCosArchiveFile` — clone of `pullMissingWorkBodies`/`pullOneWorkBody` (`peerSync.js:2538`): fetch via `fetchCappedAssetBuffer` (cap `COS_ARCHIVE_PULL_MAX_BYTES = 64 * 1024 * 1024`; log+skip oversized transcripts), verify bytes hash to advertised `sha256`, `ensureDir` + `atomicWrite` to `<date>/<agentId>/<file>`, emit `peerSyncEvents 'asset-arrived'`.
+- After pulled files land, **merge the receiver's `index.json`** so the history UI lists them: add an exported `addAgentArchivesToIndex(pairs)` to `cosAgents.js` that updates the lazy `agentIndex` map (`cosAgents.js:22`) + persists via `saveAgentIndex` — call it through a dynamic import (mirror `reconcileMediaLibraryIndex`, `peerSync.js:2846`) to keep cosAgents out of peerSync's static graph. Union/merge, never overwrite.
+- `syncCosHistoryWithAllPeers()` — clone of `syncMediaLibraryWithAllPeers` (`peerSync.js:2961`), filtering `fullSync && enabled` peers.
+
+### 4. Periodic driver (`server/services/sharing/index.js`)
+Call `syncCosHistoryWithAllPeers()` inside the existing 60s media-library `tick` (`sharing/index.js:42`) — one extra best-effort call, same try/catch boundary (PTY/timer boundary rule).
+
+### 5. Schema version + coverage guards (`server/lib/schemaVersions.js`)
+- Add `cosHistory: 1` to `PORTOS_SCHEMA_VERSIONS` (with the same explanatory comment style as `mediaLibrary`, `schemaVersions.js:334`).
+- Add `'cosHistory'` to `NON_RECORD_SCHEMA_CATEGORIES` (`schemaVersions.js:400`) — it's a receiver-pull manifest, not a record push.
+- **Per memory `project_new_schema_version_coverage_guards`: a new key trips 3 iteration guards.** Before pushing, grep + run all three: peerSync `NON_RECORD` coverage test, dataSync `OUT_OF_BAND` test, and the `schemaVersions` test. Add `cosHistory` to whichever allowlists those guards enumerate.
+
+### 6. Validation schema (`server/lib/peerSyncValidation.js`)
+- `peerCosHistoryManifestEntrySchema` (strict: `date` regex, `agentId` pattern, `file` enum, `sha256` hex64) and `peerCosHistoryManifestSchema = z.object({ schemaVersion, manifestHash, entries: z.array(...).max(100_000) }).strict()` — mirror `peerLibraryManifestSchema` (`peerSyncValidation.js:264`) and `peerDraftBodyManifestEntrySchema` (`:214`). Adding exports to an existing barreled file needs no README/barrel change.
+
+## What stays machine-local (do NOT federate)
+Live PTY buffers, in-flight `spawningTasks` Set, `pausedAgents` (`agentState.js`), worktree working dirs (`data/cos/worktrees/`), and `state.json` running-agent slots (`cosState.js`). Only the **date-bucketed completed archives** federate.
+
+## Tests
+- New `server/services/sharing/cosHistorySync.test.js` (or extend `peerSync.test.js`): `buildCosHistoryManifest` shape + deterministic hash; `syncCosHistoryFromPeer` skips a non-full-sync peer; schema-ahead gentle-skip; hash-withhold on partial pull; `diffCosHistoryManifestAgainstLocal` rejects path-traversal segments; index merge is a union.
+- `server/routes/peerSync.test.js`: the two new routes (manifest shape; archive byte route validates segments + 404s on traversal/missing).
+- Run the schemaVersions coverage trio (step 5).
+- `cd server && npm test` for the affected suites.
+
+## Verification (end-to-end)
+- `cd server && npm test -- peerSync cosHistory schemaVersions peerSyncValidation` — all green.
+- Manual two-instance check (described in #1650 acceptance): on peer A (full-sync ↔ B) let a CoS agent complete; within ~60s the archive + index entry appear on B and the agent shows in B's CoS history UI; confirm a **non**-full-sync peer pulls nothing.
+
+## Disposition (Phase 5–7)
+- Changelog: `.changelog/NEXT.md` under a **`## Federation`** heading — user-facing line, lead with `[issue-1650]`.
+- PR body: **`Refs #1650`** (partial), and **file a follow-up issue** (label `plan`, `Part of #1561`) for task-list + claim-metadata federation, referenced as plain `#<n>`.
+- Ship via `/do:pr --no-merge --review-with=claude,codex,ollama`; gate the merge on a `clean` aggregate status; `--merge` (rebase) per saved default.
+- Leave #1650 **open**; after merge, re-evaluate epic #1561 (still `epic-open` — 1563 open, 1650 open).
diff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.js
index 9304385808..bf4c1b8144 100644
--- a/server/lib/peerSyncValidation.js
+++ b/server/lib/peerSyncValidation.js
@@ -282,6 +282,34 @@ export const peerLibraryManifestSchema = z.object({
assets: z.array(peerAssetManifestEntrySchema).max(100_000),
}).strict();
+// --- Completed-agent CoS history federation (#1650) ----------------------
+// A full-sync peer advertises its date-bucketed completed-agent archives at
+// GET /api/peer-sync/cos-history-manifest; a receiver (only for peers it flags
+// fullSync) diffs the entries vs local disk and receiver-pulls the missing
+// archive files. Archives live at data/cos/agents/<date>/<agentId>/<file> —
+// nested paths, NOT flat basenames — so each entry carries the path segments,
+// validated here AND re-scrubbed in the service before any FS op (the
+// "parse-not-existsSync" guard). Exported so the service + byte route share one
+// source of truth for the allowlists.
+export const COS_ARCHIVE_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
+// agentIds are `agent-<id>` — alphanumerics, `_` and `-` only. NO dots, so a
+// `..` traversal can't form, and NO slash. Capped well above any real id.
+export const COS_AGENT_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
+// The exact set of files an archive holds (cosAgents.js). A fixed enum is the
+// tightest possible filename allowlist.
+export const COS_ARCHIVE_FILES = Object.freeze(['metadata.json', 'output.txt', 'prompt.txt']);
+const peerCosHistoryManifestEntrySchema = z.object({
+ date: z.string().regex(COS_ARCHIVE_DATE_RE),
+ agentId: z.string().regex(COS_AGENT_ID_RE),
+ file: z.enum(['metadata.json', 'output.txt', 'prompt.txt']),
+ sha256: hex64,
+}).strict();
+export const peerCosHistoryManifestSchema = z.object({
+ schemaVersion: z.number().int().min(0).max(1_000_000),
+ manifestHash: hex64,
+ entries: z.array(peerCosHistoryManifestEntrySchema).max(300_000),
+}).strict();
+
export const peerPullMetadataSchema = z.object({
// Backfill tries every online peer; no per-peer scoping field today.
// .trim() so a stray-whitespace filename (' a.png ') normalizes to the real
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 0e96518bd8..87241453f3 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -351,6 +351,18 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// can't route (directoryForAssetKind returns null) — and does NOT require a
// bump on its own.
mediaLibrary: 1,
+ // v1 = completed-agent CoS history federation (#1650, part of epic #1561). NOT
+ // a record kind — it's the wire contract for the archive manifest a full-sync
+ // peer advertises at GET /api/peer-sync/cos-history-manifest. The receiver-pull
+ // sweep (syncCosHistoryFromPeer) reads the sender's advertised `schemaVersion`
+ // and GENTLY SKIPS (logs, no reject) a sender ahead of its local `cosHistory` —
+ // same posture as `mediaLibrary` above, because a history sweep is best-effort
+ // background convergence, not an authoritative record transfer. The archive
+ // BYTES (metadata.json / output.txt / prompt.txt) are version-agnostic; only
+ // the MANIFEST envelope shape is gated, so the FIRST incompatible
+ // manifest-shape change (new required entry field, segment semantics) MUST bump
+ // this to 2.
+ cosHistory: 1,
// NOTE: `videoHistory` is intentionally NOT listed here. The version gate
// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the
// comparator walks the union of keys), so declaring a brand-new key would
@@ -413,12 +425,16 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({
* it and GENTLY SKIPS a sender ahead of its local version (see
* syncMediaLibraryFromPeer) — there is no push to gate, so it has no entry in
* RECORD_KIND_SCHEMA_CATEGORIES by design.
+ * - `cosHistory` (#1650): the completed-agent CoS history archive manifest a
+ * full-sync peer advertises at GET /api/peer-sync/cos-history-manifest. Same
+ * receiver-pull shape as `mediaLibrary` (see syncCosHistoryFromPeer) — no push
+ * to gate, so no RECORD_KIND_SCHEMA_CATEGORIES entry.
*
* Do NOT add a real record-push category here to silence the guard — that would
* leave its push transfers ungated (silent cross-install corruption). Only
* genuinely non-push categories belong.
*/
-export const NON_RECORD_SCHEMA_CATEGORIES = Object.freeze(new Set(['mediaLibrary']));
+export const NON_RECORD_SCHEMA_CATEGORIES = Object.freeze(new Set(['mediaLibrary', 'cosHistory']));
/**
* Lazy-read the current PortOS version from the ROOT package.json so a
diff --git a/server/routes/peerSync.js b/server/routes/peerSync.js
index baee66dba6..a879d035dc 100644
--- a/server/routes/peerSync.js
+++ b/server/routes/peerSync.js
@@ -23,7 +23,10 @@
*/
import { Router } from 'express';
+import { join } from 'path';
+import { existsSync } from 'fs';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { PATHS } from '../lib/fileUtils.js';
import {
validateRequest,
peerSubscribeSchema,
@@ -31,6 +34,9 @@ import {
peerSyncRecordSchema,
peerSyncNowSchema,
peerPullMetadataSchema,
+ COS_ARCHIVE_DATE_RE,
+ COS_AGENT_ID_RE,
+ COS_ARCHIVE_FILES,
} from '../lib/validation.js';
import {
listPeerSubscriptions,
@@ -42,6 +48,7 @@ import {
pullRecordFromPeer,
syncNowForPeer,
buildMediaLibraryManifest,
+ buildCosHistoryManifest,
ERR_NOT_FOUND,
ERR_VALIDATION,
ERR_SCHEMA_VERSION_AHEAD,
@@ -160,6 +167,39 @@ router.get('/library-manifest', asyncHandler(async (_req, res) => {
res.json(await buildMediaLibraryManifest());
}));
+// --- GET /cos-history-manifest --- advertise this instance's completed-agent
+// CoS history archives (#1650) so a full-sync peer can diff + receiver-pull
+// missing archive files.
+//
+// Returns `{ schemaVersion, manifestHash, entries: [{ date, agentId, file,
+// sha256 }] }` over data/cos/agents/<date>/<agentId>/{metadata,output,prompt}.
+// Unauthenticated like every peer-sync route (Tailnet-only per the threat
+// model); the receiver gates the PULL on its own `fullSync` flag.
+router.get('/cos-history-manifest', asyncHandler(async (_req, res) => {
+ res.json(await buildCosHistoryManifest());
+}));
+
+// --- GET /cos-agent-archive --- stream ONE completed-agent archive file so a
+// full-sync peer can receiver-pull it (#1650). Archives are nested
+// (<date>/<agentId>/<file>), so unlike media bytes they are NOT served by a
+// broad static mount — each segment is validated against the same allowlists the
+// manifest uses (the "parse-not-existsSync" guard) before resolving under
+// PATHS.cos/agents and streaming with res.sendFile (which sets Content-Length,
+// required by the receiver's fetchCappedAssetBuffer). 404 on any invalid/missing.
+router.get('/cos-agent-archive', asyncHandler(async (req, res) => {
+ const date = typeof req.query.date === 'string' ? req.query.date : '';
+ const agentId = typeof req.query.agentId === 'string' ? req.query.agentId : '';
+ const file = typeof req.query.file === 'string' ? req.query.file : '';
+ if (!COS_ARCHIVE_DATE_RE.test(date) || !COS_AGENT_ID_RE.test(agentId) || !COS_ARCHIVE_FILES.includes(file)) {
+ throw new ServerError('invalid archive path', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const abs = join(PATHS.cos, 'agents', date, agentId, file);
+ if (!existsSync(abs)) {
+ throw new ServerError('archive not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.sendFile(abs);
+}));
+
// --- GET /record --- return ONE record's push payload so a peer can PULL it.
//
// The mirror of the sender's /push: a peer that's behind on this record fetches
diff --git a/server/routes/peerSync.test.js b/server/routes/peerSync.test.js
index f53d857f04..783d37a519 100644
--- a/server/routes/peerSync.test.js
+++ b/server/routes/peerSync.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import express from 'express';
import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
@@ -13,6 +13,7 @@ vi.mock('../services/sharing/peerSync.js', () => ({
pullRecordFromPeer: vi.fn(),
syncNowForPeer: vi.fn(),
buildMediaLibraryManifest: vi.fn(),
+ buildCosHistoryManifest: vi.fn(),
ERR_NOT_FOUND: 'PEER_SYNC_SUBSCRIPTION_NOT_FOUND',
ERR_VALIDATION: 'PEER_SYNC_SUBSCRIPTION_VALIDATION',
ERR_SCHEMA_VERSION_AHEAD: 'PEER_SYNC_SCHEMA_VERSION_AHEAD',
@@ -32,6 +33,10 @@ import * as svc from '../services/sharing/peerSync.js';
import * as integritySvc from '../services/sharing/integrity.js';
import * as sidecarSvc from '../services/sharing/sidecarSync.js';
import peerSyncRoutes from './peerSync.js';
+import { PATHS } from '../lib/fileUtils.js';
+import { mkdir, writeFile, rm } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
const buildApp = () => {
const app = express();
@@ -529,6 +534,62 @@ describe('peer-sync routes', () => {
});
});
+ describe('GET /api/peer-sync/cos-history-manifest (#1650)', () => {
+ it('200 with the completed-agent history manifest', async () => {
+ const manifest = {
+ schemaVersion: 1,
+ manifestHash: 'c'.repeat(64),
+ entries: [{ date: '2026-06-20', agentId: 'agent-abc', file: 'metadata.json', sha256: 'd'.repeat(64) }],
+ };
+ svc.buildCosHistoryManifest.mockResolvedValue(manifest);
+ const res = await request(buildApp()).get('/api/peer-sync/cos-history-manifest');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual(manifest);
+ expect(svc.buildCosHistoryManifest).toHaveBeenCalled();
+ });
+ });
+
+ describe('GET /api/peer-sync/cos-agent-archive (#1650)', () => {
+ let tmp;
+ let originalCos;
+ beforeEach(async () => {
+ originalCos = PATHS.cos;
+ tmp = join(tmpdir(), `portos-cos-route-${process.pid}-${Math.random().toString(36).slice(2)}`);
+ PATHS.cos = tmp;
+ await mkdir(join(tmp, 'agents', '2026-06-20', 'agent-abc'), { recursive: true });
+ await writeFile(join(tmp, 'agents', '2026-06-20', 'agent-abc', 'metadata.json'), '{"id":"agent-abc"}');
+ });
+ afterEach(async () => {
+ PATHS.cos = originalCos;
+ await rm(tmp, { recursive: true, force: true });
+ });
+
+ it('streams a valid archive file', async () => {
+ const res = await request(buildApp())
+ .get('/api/peer-sync/cos-agent-archive?date=2026-06-20&agentId=agent-abc&file=metadata.json');
+ expect(res.status).toBe(200);
+ expect(res.text).toBe('{"id":"agent-abc"}');
+ });
+
+ it('400s on a non-allowlisted file', async () => {
+ const res = await request(buildApp())
+ .get('/api/peer-sync/cos-agent-archive?date=2026-06-20&agentId=agent-abc&file=state.json');
+ expect(res.status).toBe(400);
+ });
+
+ it('400s on path-traversal segments (never reaches the FS)', async () => {
+ const res = await request(buildApp())
+ .get('/api/peer-sync/cos-agent-archive?date=..%2F..%2Fetc&agentId=agent-abc&file=metadata.json');
+ expect(res.status).toBe(400);
+ });
+
+ it('404s when the archive file does not exist', async () => {
+ const res = await request(buildApp())
+ .get('/api/peer-sync/cos-agent-archive?date=2026-06-20&agentId=agent-zzz&file=output.txt');
+ expect(res.status).toBe(404);
+ });
+ });
+
describe('GET /api/peer-sync/integrity', () => {
it('200 with available:false when peer is not found', async () => {
integritySvc.getPeerIntegrity.mockResolvedValue({
diff --git a/server/services/cosAgents.indexMerge.test.js b/server/services/cosAgents.indexMerge.test.js
new file mode 100644
index 0000000000..cfd139bc9c
--- /dev/null
+++ b/server/services/cosAgents.indexMerge.test.js
@@ -0,0 +1,69 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdir, rm, writeFile, readFile } from 'fs/promises';
+import { join } from 'path';
+
+// Isolated file so cosAgents' lazy agentIndex singleton starts clean (a shared
+// file would carry the cache across describes). cosState is mocked to point
+// AGENTS_DIR at a tmpdir so addAgentArchivesToIndex (#1650 receiver hook) never
+// touches the real data/cos/agents index.
+const mockCosState = vi.hoisted(() => ({
+ agentsDir: `${process.env.TMPDIR || '/tmp'}/portos-cos-indexmerge-${process.pid}`,
+}));
+
+vi.mock('./cosState.js', () => ({
+ AGENTS_DIR: mockCosState.agentsDir,
+ loadState: vi.fn(),
+ saveState: vi.fn(),
+ withStateLock: async (fn) => fn(),
+}));
+vi.mock('./domainUsage.js', () => ({ recordDomainUsage: vi.fn(async () => {}) }));
+
+import { addAgentArchivesToIndex, loadAgentIndex } from './cosAgents.js';
+
+const INDEX_FILE = join(mockCosState.agentsDir, 'index.json');
+
+describe('addAgentArchivesToIndex (#1650)', () => {
+ beforeEach(async () => {
+ await rm(mockCosState.agentsDir, { recursive: true, force: true });
+ await mkdir(mockCosState.agentsDir, { recursive: true });
+ // Seed an empty index so loadAgentIndex takes the read path (not migration).
+ await writeFile(INDEX_FILE, '{}');
+ });
+ afterEach(async () => {
+ await rm(mockCosState.agentsDir, { recursive: true, force: true });
+ });
+
+ it('unions new pairs, is idempotent, rejects invalid, and persists', async () => {
+ expect(await addAgentArchivesToIndex([
+ { agentId: 'agent-x', date: '2026-06-20' },
+ { agentId: 'agent-y', date: '2026-06-21' },
+ ])).toBe(2);
+
+ // Re-adding the same pair is a no-op.
+ expect(await addAgentArchivesToIndex([{ agentId: 'agent-x', date: '2026-06-20' }])).toBe(0);
+
+ // Invalid entries are skipped: empty id, malformed date, empty object.
+ expect(await addAgentArchivesToIndex([
+ { agentId: '', date: '2026-06-20' },
+ { agentId: 'agent-z', date: 'not-a-date' },
+ {},
+ ])).toBe(0);
+
+ // A genuinely new pair still lands.
+ expect(await addAgentArchivesToIndex([{ agentId: 'agent-w', date: '2026-06-22' }])).toBe(1);
+
+ const idx = await loadAgentIndex();
+ expect(idx.get('agent-x')).toBe('2026-06-20');
+ expect(idx.get('agent-w')).toBe('2026-06-22');
+ expect(idx.has('agent-z')).toBe(false);
+
+ const onDisk = JSON.parse(await readFile(INDEX_FILE, 'utf8'));
+ expect(onDisk['agent-y']).toBe('2026-06-21');
+ expect(onDisk['agent-z']).toBeUndefined();
+ });
+
+ it('returns 0 for a non-array / empty input', async () => {
+ expect(await addAgentArchivesToIndex(null)).toBe(0);
+ expect(await addAgentArchivesToIndex([])).toBe(0);
+ });
+});
diff --git a/server/services/cosAgents.js b/server/services/cosAgents.js
index b720a8a330..b545693ebc 100644
--- a/server/services/cosAgents.js
+++ b/server/services/cosAgents.js
@@ -63,6 +63,31 @@ async function saveAgentIndex() {
});
}
+/**
+ * Merge a batch of {agentId, date} pairs into the agent index. Used by the
+ * peer-sync CoS-history receiver (#1650): after pulling a peer's completed-agent
+ * archives onto local disk, the date-bucket index must learn the new agentIds so
+ * the history UI lists them. Idempotent union — re-registering an existing entry
+ * is a no-op, and only valid YYYY-MM-DD-bucketed pairs are accepted. Returns the
+ * number of NEW entries added.
+ */
+export async function addAgentArchivesToIndex(pairs) {
+ if (!Array.isArray(pairs) || pairs.length === 0) return 0;
+ const idx = await loadAgentIndex();
+ let added = 0;
+ for (const pair of pairs) {
+ const agentId = pair?.agentId;
+ const date = pair?.date;
+ if (typeof agentId !== 'string' || !agentId) continue;
+ if (typeof date !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(date)) continue;
+ if (idx.get(agentId) === date) continue; // already indexed at this bucket
+ idx.set(agentId, date);
+ added += 1;
+ }
+ if (added > 0) await saveAgentIndex();
+ return added;
+}
+
// Resolve the correct directory for an agent (running = flat, completed = date bucket)
function getAgentDir(agentId, dateString) {
if (dateString) return join(AGENTS_DIR, dateString, agentId);
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index dc277a1fa2..326d81864a 100644
--- a/server/services/dataSync.pipelineUniverse.test.js
+++ b/server/services/dataSync.pipelineUniverse.test.js
@@ -1118,6 +1118,11 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {
// Versioned for the manifest envelope and gated by syncMediaLibraryFromPeer's
// gentle skip-if-ahead; declared non-record in NON_RECORD_SCHEMA_CATEGORIES.
'mediaLibrary',
+ // Completed-agent CoS history (#1650) → its own receiver-pull endpoint
+ // (GET /api/peer-sync/cos-history-manifest), NOT the file-snapshot transfer.
+ // Versioned for the manifest envelope and gated by syncCosHistoryFromPeer's
+ // gentle skip-if-ahead; declared non-record in NON_RECORD_SCHEMA_CATEGORIES.
+ 'cosHistory',
]);
const covered = new Set(Object.values(dataSync.getSnapshotCategorySchemaKeys()).flat());
for (const key of Object.keys(PORTOS_SCHEMA_VERSIONS)) {
diff --git a/server/services/sharing/cosHistorySync.test.js b/server/services/sharing/cosHistorySync.test.js
new file mode 100644
index 0000000000..25bd51e911
--- /dev/null
+++ b/server/services/sharing/cosHistorySync.test.js
@@ -0,0 +1,220 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdir, rm, writeFile, readdir } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { createHash } from 'crypto';
+
+// Completed-agent CoS history federation (#1650). We exercise peerSync.js's
+// cos-history functions against a tmpdir-redirected PATHS.cos, stubbing the
+// network (peerFetch) and the peer registry (instances). cosAgents.js is mocked
+// so the receiver's index merge is a spy — it must NEVER touch the real
+// data/cos/agents index. The heavy record-graph modules are mocked exactly as
+// peerSync.test.js does, purely so importing peerSync.js stays cheap + offline.
+
+import { PATHS } from '../../lib/fileUtils.js';
+
+vi.mock('../instances.js', () => ({
+ UNKNOWN_INSTANCE_ID: 'unknown',
+ DEFAULT_SYNC_CATEGORIES: {},
+ getInstanceId: vi.fn().mockResolvedValue('test-instance'),
+ getPeers: vi.fn().mockResolvedValue([]),
+ enqueueReciprocalSync: vi.fn().mockResolvedValue({ ok: true }),
+}));
+vi.mock('../universeBuilder.js', async () => ({ getUniverse: vi.fn(), mergeUniversesFromSync: vi.fn(), listUniverses: vi.fn() }));
+vi.mock('../pipeline/series.js', async () => ({ getSeries: vi.fn(), mergeSeriesFromSync: vi.fn(), listSeries: vi.fn() }));
+vi.mock('../pipeline/issues.js', async () => ({ listIssues: vi.fn(), mergeIssuesFromSync: vi.fn() }));
+vi.mock('../pipeline/manuscriptReview.js', async () => ({ getReview: vi.fn(), mergeReviewFromSync: vi.fn() }));
+vi.mock('../pipeline/reverseOutline.js', async () => ({ getStoredOutline: vi.fn(), mergeOutlineFromSync: vi.fn() }));
+vi.mock('../mediaCollections.js', async () => ({
+ getCollection: vi.fn(), listCollections: vi.fn(), findCollectionByUniverseId: vi.fn(),
+ findCollectionBySeriesId: vi.fn(), mergeMediaCollectionsFromSync: vi.fn(),
+}));
+vi.mock('../mediaAssetIndex/index.js', () => ({ reconcileMediaAssets: vi.fn().mockResolvedValue(undefined) }));
+vi.mock('../../lib/peerHttpClient.js', async () => ({ peerFetch: vi.fn() }));
+// cosAgents is dynamic-imported by the receiver to merge the agentId→date index.
+// Spy it so the merge is observable AND can't write the real data/cos index.
+vi.mock('../cosAgents.js', () => ({ addAgentArchivesToIndex: vi.fn().mockResolvedValue(0) }));
+
+import {
+ buildCosHistoryManifest,
+ diffCosHistoryManifestAgainstLocal,
+ syncCosHistoryFromPeer,
+} from './peerSync.js';
+import { getPeers } from '../instances.js';
+import { peerFetch } from '../../lib/peerHttpClient.js';
+import { addAgentArchivesToIndex } from '../cosAgents.js';
+
+const sha = (s) => createHash('sha256').update(s).digest('hex');
+
+function byteRes(content) {
+ const buf = Buffer.from(content);
+ return {
+ ok: true,
+ headers: new Headers({ 'content-length': String(buf.length) }),
+ arrayBuffer: async () => buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength),
+ };
+}
+function manifestRes(obj) {
+ return { ok: true, headers: { get: () => null }, json: async () => obj };
+}
+
+const PEER = { instanceId: 'peer-1', name: 'P1', address: '10.0.0.2', port: 5555, fullSync: true, enabled: true };
+
+let tmp;
+let originalCos;
+
+beforeEach(async () => {
+ originalCos = PATHS.cos;
+ tmp = join(tmpdir(), `portos-cos-history-${process.pid}-${Math.random().toString(36).slice(2)}`);
+ PATHS.cos = tmp;
+ await mkdir(join(tmp, 'agents'), { recursive: true });
+ vi.mocked(peerFetch).mockReset();
+ vi.mocked(getPeers).mockResolvedValue([PEER]);
+ vi.mocked(addAgentArchivesToIndex).mockClear();
+});
+
+afterEach(async () => {
+ PATHS.cos = originalCos;
+ await rm(tmp, { recursive: true, force: true });
+});
+
+async function seedArchive(date, agentId, files) {
+ const dir = join(tmp, 'agents', date, agentId);
+ await mkdir(dir, { recursive: true });
+ for (const [name, content] of Object.entries(files)) {
+ await writeFile(join(dir, name), content);
+ }
+}
+
+describe('buildCosHistoryManifest', () => {
+ it('hashes each archive file, skips index.json + flat running dirs, is deterministic', async () => {
+ await seedArchive('2026-06-20', 'agent-abc', {
+ 'metadata.json': '{"id":"agent-abc"}',
+ 'output.txt': 'line1\nline2\n',
+ 'prompt.txt': 'do the thing',
+ });
+ // Noise that must be excluded: the type-level index, and a flat (running) dir.
+ await writeFile(join(tmp, 'agents', 'index.json'), '{"agent-abc":"2026-06-20"}');
+ await mkdir(join(tmp, 'agents', 'agent-running'), { recursive: true });
+ await writeFile(join(tmp, 'agents', 'agent-running', 'metadata.json'), '{}');
+
+ const m = await buildCosHistoryManifest();
+ expect(m.schemaVersion).toBe(1);
+ expect(m.manifestHash).toMatch(/^[a-f0-9]{64}$/);
+ expect(m.entries).toHaveLength(3);
+ const files = m.entries.map((e) => e.file).sort();
+ expect(files).toEqual(['metadata.json', 'output.txt', 'prompt.txt']);
+ expect(m.entries.every((e) => e.date === '2026-06-20' && e.agentId === 'agent-abc')).toBe(true);
+ expect(m.entries.find((e) => e.file === 'output.txt').sha256).toBe(sha('line1\nline2\n'));
+ // Deterministic: a second build over the same disk yields the same hash.
+ const again = await buildCosHistoryManifest();
+ expect(again.manifestHash).toBe(m.manifestHash);
+ });
+
+ it('returns an empty manifest when no archives exist', async () => {
+ const m = await buildCosHistoryManifest();
+ expect(m.entries).toHaveLength(0);
+ expect(m.schemaVersion).toBe(1);
+ });
+});
+
+describe('diffCosHistoryManifestAgainstLocal', () => {
+ it('flags absent + hash-mismatched files, leaves present-matching alone', async () => {
+ await seedArchive('2026-06-20', 'agent-abc', { 'metadata.json': 'GOOD' });
+ const entries = [
+ { date: '2026-06-20', agentId: 'agent-abc', file: 'metadata.json', sha256: sha('GOOD') }, // present+match
+ { date: '2026-06-20', agentId: 'agent-abc', file: 'output.txt', sha256: sha('B') }, // absent
+ ];
+ const missing = await diffCosHistoryManifestAgainstLocal(entries);
+ expect(missing.map((e) => e.file)).toEqual(['output.txt']);
+
+ // A locally-present file whose hash differs is also missing.
+ const mismatch = await diffCosHistoryManifestAgainstLocal([
+ { date: '2026-06-20', agentId: 'agent-abc', file: 'metadata.json', sha256: sha('STALE') },
+ ]);
+ expect(mismatch).toHaveLength(1);
+ });
+
+ it('silently rejects path-traversal segments before any FS op', async () => {
+ const evil = [
+ { date: '../../etc', agentId: 'agent-abc', file: 'metadata.json', sha256: sha('x') },
+ { date: '2026-06-20', agentId: '../../secrets', file: 'metadata.json', sha256: sha('x') },
+ { date: '2026-06-20', agentId: 'agent-abc', file: '../../../etc/passwd', sha256: sha('x') },
+ ];
+ expect(await diffCosHistoryManifestAgainstLocal(evil)).toEqual([]);
+ });
+});
+
+describe('syncCosHistoryFromPeer', () => {
+ it('skips a non-full-sync peer (no network)', async () => {
+ const r = await syncCosHistoryFromPeer({ ...PEER, fullSync: false });
+ expect(r).toEqual({ pulled: 0, skipped: 'not-fullsync' });
+ expect(peerFetch).not.toHaveBeenCalled();
+ });
+
+ it('gently skips a sender whose manifest schema is ahead', async () => {
+ vi.mocked(peerFetch).mockResolvedValue(manifestRes({ schemaVersion: 999, manifestHash: sha('x'), entries: [] }));
+ const r = await syncCosHistoryFromPeer(PEER);
+ expect(r).toEqual({ pulled: 0, skipped: 'schema-ahead' });
+ });
+
+ it('pulls missing archive files, writes them, and merges the index', async () => {
+ const meta = '{"id":"agent-abc"}';
+ const out = 'transcript\n';
+ const prompt = 'sys prompt';
+ const entries = [
+ { date: '2026-06-20', agentId: 'agent-abc', file: 'metadata.json', sha256: sha(meta) },
+ { date: '2026-06-20', agentId: 'agent-abc', file: 'output.txt', sha256: sha(out) },
+ { date: '2026-06-20', agentId: 'agent-abc', file: 'prompt.txt', sha256: sha(prompt) },
+ ];
+ const byFile = { 'metadata.json': meta, 'output.txt': out, 'prompt.txt': prompt };
+ vi.mocked(peerFetch).mockImplementation(async (url) => {
+ if (url.includes('cos-history-manifest')) {
+ return manifestRes({ schemaVersion: 1, manifestHash: sha('m'), entries });
+ }
+ const file = decodeURIComponent(url.match(/file=([^&]+)/)[1]);
+ return byteRes(byFile[file]);
+ });
+
+ const r = await syncCosHistoryFromPeer(PEER);
+ expect(r).toEqual({ pulled: 3, missing: 0 });
+ const dir = join(tmp, 'agents', '2026-06-20', 'agent-abc');
+ expect(existsSync(join(dir, 'metadata.json'))).toBe(true);
+ expect(existsSync(join(dir, 'output.txt'))).toBe(true);
+ expect(existsSync(join(dir, 'prompt.txt'))).toBe(true);
+ // Index merge fired with the landed (date, agentId) pairs.
+ expect(addAgentArchivesToIndex).toHaveBeenCalledTimes(1);
+ const pairs = vi.mocked(addAgentArchivesToIndex).mock.calls[0][0];
+ expect(pairs).toContainEqual({ date: '2026-06-20', agentId: 'agent-abc' });
+ });
+
+ it('withholds the manifest hash on a partial pull (corrupt byte) so it retries', async () => {
+ const meta = 'META';
+ const out = 'OUT';
+ const entries = [
+ { date: '2026-06-20', agentId: 'agent-abc', file: 'metadata.json', sha256: sha(meta) },
+ { date: '2026-06-20', agentId: 'agent-abc', file: 'output.txt', sha256: sha(out) },
+ ];
+ vi.mocked(peerFetch).mockImplementation(async (url) => {
+ if (url.includes('cos-history-manifest')) {
+ return manifestRes({ schemaVersion: 1, manifestHash: sha('m2'), entries });
+ }
+ const file = decodeURIComponent(url.match(/file=([^&]+)/)[1]);
+ // output.txt arrives corrupted → hash mismatch → discarded → stays missing.
+ return byteRes(file === 'output.txt' ? 'CORRUPT' : meta);
+ });
+
+ const first = await syncCosHistoryFromPeer(PEER);
+ expect(first).toEqual({ pulled: 1, missing: 1 });
+ expect(existsSync(join(tmp, 'agents', '2026-06-20', 'agent-abc', 'metadata.json'))).toBe(true);
+ expect(existsSync(join(tmp, 'agents', '2026-06-20', 'agent-abc', 'output.txt'))).toBe(false);
+
+ // Hash was NOT recorded, so a second identical sweep re-fetches the manifest
+ // (not short-circuited as 'unchanged') and re-attempts the still-missing file.
+ vi.mocked(peerFetch).mockClear();
+ await syncCosHistoryFromPeer(PEER);
+ const fetchedManifest = vi.mocked(peerFetch).mock.calls.some(([u]) => u.includes('cos-history-manifest'));
+ expect(fetchedManifest).toBe(true);
+ });
+});
diff --git a/server/services/sharing/index.js b/server/services/sharing/index.js
index 38fcc3bb3b..0bd0ac091f 100644
--- a/server/services/sharing/index.js
+++ b/server/services/sharing/index.js
@@ -12,7 +12,7 @@ import { join } from 'path';
import { attachAllWatchers, attachWatcher, detachWatcher, shutdownAllWatchers, listAttachedWatchers } from './watcher.js';
import { sharingEvents } from './importer.js';
import { installSubscriptionListener } from './subscriptions.js';
-import { installPeerSyncListener, uninstallPeerSyncListener, peerSyncEvents, syncMediaLibraryWithAllPeers } from './peerSync.js';
+import { installPeerSyncListener, uninstallPeerSyncListener, peerSyncEvents, syncMediaLibraryWithAllPeers, syncCosHistoryWithAllPeers } from './peerSync.js';
import { hasSubscriptionAdapter } from './recordEvents.js';
import { initAnnotationsSync } from './annotationsSync.js';
@@ -23,11 +23,12 @@ export { pullSidecarForImage, backfillMissingSidecars } from './sidecarSync.js';
let initialized = false;
let io = null;
-// Standalone media-library federation sweep (#1566). A low-frequency timer pulls
-// each full-sync peer's library bytes; an unchanged library short-circuits on the
-// manifestHash, so the steady-state tick is one cheap manifest fetch per peer.
-// Period is deliberately slower than the 30s peer health probe — media changes
-// less often and a sweep can move large bytes.
+// Standalone full-sync library sweeps (#1566 media, #1650 CoS history). A
+// low-frequency timer pulls each full-sync peer's standalone bytes; an unchanged
+// manifest short-circuits on the manifestHash, so the steady-state tick is one
+// cheap manifest fetch per peer per category. Period is deliberately slower than
+// the 30s peer health probe — these change less often and a sweep can move large
+// bytes.
const MEDIA_LIBRARY_SWEEP_INTERVAL_MS = 60_000;
const MEDIA_LIBRARY_SWEEP_INITIAL_DELAY_MS = 20_000; // let boot settle before the first sweep
let mediaLibraryTimer = null;
@@ -35,15 +36,20 @@ let mediaLibraryKickoff = null;
function startMediaLibrarySweep() {
// Timer callbacks run OUTSIDE the request lifecycle — an uncaught throw here
- // crashes the process (CLAUDE.md). syncMediaLibraryWithAllPeers already catches
- // per-peer; this guards a synchronous throw before the awaits begin.
+ // crashes the process (CLAUDE.md). Each sweep already catches per-peer; this
+ // guards a synchronous throw before the awaits begin.
const tick = () => {
try {
syncMediaLibraryWithAllPeers().catch((err) => {
console.error(`❌ sharing: media-library sweep failed: ${err.message}`);
});
+ // Completed-agent CoS history (#1650) rides the same cadence — independent
+ // best-effort sweep, separate per-peer catch so one can't sink the other.
+ syncCosHistoryWithAllPeers().catch((err) => {
+ console.error(`❌ sharing: cos-history sweep failed: ${err.message}`);
+ });
} catch (err) {
- console.error(`❌ sharing: media-library sweep threw synchronously: ${err.message}`);
+ console.error(`❌ sharing: full-sync sweep threw synchronously: ${err.message}`);
}
};
mediaLibraryKickoff = setTimeout(() => {
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 68476c6cec..fc831fe15a 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -63,7 +63,7 @@ import {
getPortosVersion,
} from '../../lib/schemaVersions.js';
import { getInstanceId, getPeers, enqueueReciprocalSync, UNKNOWN_INSTANCE_ID } from '../instances.js';
-import { peerSyncPushSchema, peerLibraryManifestSchema } from '../../lib/validation.js';
+import { peerSyncPushSchema, peerLibraryManifestSchema, peerCosHistoryManifestSchema, COS_ARCHIVE_DATE_RE, COS_AGENT_ID_RE, COS_ARCHIVE_FILES } from '../../lib/validation.js';
import { instanceEvents } from '../instanceEvents.js';
import { getUniverse, mergeUniversesFromSync } from '../universeBuilder.js';
import { getSeries, mergeSeriesFromSync } from '../pipeline/series.js';
@@ -3021,6 +3021,263 @@ export async function syncMediaLibraryWithAllPeers() {
}
}
+// --- Completed-agent CoS history federation (#1650) ---------------------
+//
+// For a declared full-sync peer pair we mirror the STANDALONE completed-agent
+// archive tree (data/cos/agents/<YYYY-MM-DD>/<agentId>/{metadata,output,prompt})
+// so each peer's CoS history UI is a complete replica. Archives are immutable
+// once written (an agent never re-completes; agentIds are globally unique), so
+// this is pure append/union byte replication — no merge, no conflict.
+//
+// Shape mirrors the media-library sweep (#1566): the sender advertises a
+// content-addressed manifest at GET /api/peer-sync/cos-history-manifest; a
+// receiver (only for peers it flags fullSync) fetches it, diffs vs local disk,
+// receiver-pulls the missing archive files via the nested-path byte route
+// (GET /api/peer-sync/cos-agent-archive), then merges the lightweight
+// agentId→date index so the history UI lists the arrivals. The pull/integrity
+// path mirrors the Writers Room draft-body pull (nested paths, sha256-verified).
+//
+// Running-agent state (state.json slots), live PTY buffers, the in-flight
+// spawningTasks guard, and worktree working dirs are deliberately NOT federated
+// — only the date-bucketed COMPLETED archives.
+
+// Resolved at CALL TIME (not module load) so a redirected PATHS — the test
+// tmpdir pattern, consistent with mediaLibraryDirs reading PATHS live — is honored.
+function cosAgentsDir() {
+ return join(PATHS.cos, 'agents');
+}
+
+// Cap so a pathologically large history can't build an unbounded manifest. Each
+// agent contributes up to 3 files; 300k entries ≈ 100k agents, far beyond any
+// realistic single-user history. When exceeded we LOG + truncate (CLAUDE.md "no
+// silent caps"). Kept in sync with the `entries` cap in peerCosHistoryManifestSchema.
+const COS_HISTORY_MANIFEST_CAP = 300_000;
+// The manifest JSON itself (not the archive bytes — those ride the per-file cap).
+const COS_HISTORY_MANIFEST_MAX_BYTES = 32 * 1024 * 1024;
+// Per-archive-file hard cap. Agent transcripts (output.txt) can be large; 64MB is
+// generous while still bounding a hostile/runaway peer. An oversized file is
+// logged + skipped (it stays "missing" and is retried, never silently dropped).
+const COS_ARCHIVE_PULL_MAX_BYTES = 64 * 1024 * 1024;
+
+/**
+ * Build the completed-agent history manifest this instance advertises to
+ * full-sync peers. Walks data/cos/agents/<date>/<agentId>/, hashing each of the
+ * three archive files that exist, and stamps a `manifestHash` over the sorted
+ * entries so a receiver can short-circuit an unchanged history.
+ *
+ * @returns {Promise<{ schemaVersion:number, manifestHash:string, entries:Array }>}
+ */
+export async function buildCosHistoryManifest() {
+ const root = cosAgentsDir();
+ const entries = [];
+ let truncated = false;
+ // Top level: date buckets only. Skip index.json and any flat (running-agent)
+ // dirs — only date-bucketed dirs hold COMPLETED archives.
+ const dates = (await readdir(root).catch(() => [])).filter((d) => COS_ARCHIVE_DATE_RE.test(d));
+ outer: for (const date of dates.sort()) {
+ const dateDir = join(root, date);
+ const agentIds = (await readdir(dateDir).catch(() => [])).filter((a) => COS_AGENT_ID_RE.test(a));
+ for (const agentId of agentIds.sort()) {
+ const agentDir = join(dateDir, agentId);
+ for (const file of COS_ARCHIVE_FILES) {
+ const full = join(agentDir, file);
+ if (!existsSync(full)) continue;
+ const sha256 = await sha256File(full).catch(() => null);
+ if (!sha256) continue;
+ if (entries.length >= COS_HISTORY_MANIFEST_CAP) { truncated = true; break outer; }
+ entries.push({ date, agentId, file, sha256 });
+ }
+ }
+ }
+ if (truncated) {
+ console.log(`⚠️ peerSync: cos-history manifest hit the ${COS_HISTORY_MANIFEST_CAP}-entry cap — truncating (some archives won't federate; pagination is a follow-up)`);
+ }
+ // Deterministic order so the manifestHash converges across machines regardless
+ // of readdir order. (date, agentId already sorted above; sort by file too.)
+ entries.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1
+ : a.agentId < b.agentId ? -1 : a.agentId > b.agentId ? 1
+ : a.file < b.file ? -1 : a.file > b.file ? 1 : 0));
+ const manifestHash = createHash('sha256')
+ .update(entries.map((e) => `${e.date}:${e.agentId}:${e.file}:${e.sha256}`).join('\n'))
+ .digest('hex');
+ return { schemaVersion: PORTOS_SCHEMA_VERSIONS.cosHistory, manifestHash, entries };
+}
+
+/**
+ * Receiver-side: return the manifest entries whose local archive file is absent
+ * or hash-mismatched. Re-validates every path segment (belt-and-suspenders
+ * against a future refactor that bypasses the Zod schema) before any FS op.
+ */
+export async function diffCosHistoryManifestAgainstLocal(manifestEntries) {
+ if (!Array.isArray(manifestEntries)) return [];
+ const root = cosAgentsDir();
+ const missing = [];
+ for (const entry of manifestEntries) {
+ if (!isPlainObject(entry)) continue;
+ const { date, agentId, file, sha256 } = entry;
+ if (!COS_ARCHIVE_DATE_RE.test(date || '') || !COS_AGENT_ID_RE.test(agentId || '') || !COS_ARCHIVE_FILES.includes(file)) continue;
+ const full = join(root, date, agentId, file);
+ if (!existsSync(full)) { missing.push(entry); continue; }
+ const localHash = await sha256File(full).catch(() => null);
+ if (localHash !== sha256) missing.push(entry);
+ }
+ return missing;
+}
+
+// Receiver-side state — mirrors the media-library sweep's bookkeeping.
+const lastCosHistoryManifestHash = new Map(); // peerInstanceId → manifestHash
+const cosHistoryUnchangedSkips = new Map(); // peerInstanceId → count
+const cosHistorySweepInFlight = new Set(); // peerInstanceId
+
+async function pullMissingCosArchives(senderInstanceId, missing) {
+ if (!isStr(senderInstanceId) || !Array.isArray(missing) || missing.length === 0) return [];
+ const peer = await findPeerById(senderInstanceId);
+ if (!peer) {
+ console.log(`⚠️ peerSync: can't pull cos archives — peer ${senderInstanceId} not in registry`);
+ return [];
+ }
+ const base = peerBaseUrl(peer);
+ const landed = [];
+ for (const entry of missing) {
+ const pair = await pullOneCosArchiveFile(peer, base, entry).catch((err) => {
+ console.log(`⚠️ peerSync: cos-archive pull ${entry?.agentId}/${entry?.file} from ${peer.name || senderInstanceId} failed: ${err.message}`);
+ return null;
+ });
+ if (pair) landed.push(pair);
+ }
+ return landed;
+}
+
+async function pullOneCosArchiveFile(peer, base, entry) {
+ const { date, agentId, file, sha256 } = entry || {};
+ // Re-validate segments here even though the diff already did.
+ if (!COS_ARCHIVE_DATE_RE.test(date || '') || !COS_AGENT_ID_RE.test(agentId || '') || !COS_ARCHIVE_FILES.includes(file)) return null;
+ const safeLabel = `${date}/${agentId}/${file}`;
+ const key = inflightKey(peer.instanceId, 'cos-archive', safeLabel);
+ if (inflightPulls.has(key)) return null;
+ inflightPulls.add(key);
+ try {
+ const url = `${base}/api/peer-sync/cos-agent-archive?date=${encodeURIComponent(date)}&agentId=${encodeURIComponent(agentId)}&file=${encodeURIComponent(file)}`;
+ // allowEmpty: output.txt / prompt.txt can legitimately be 0 bytes.
+ const buffer = await fetchCappedAssetBuffer(peer, url, safeLabel, COS_ARCHIVE_PULL_MAX_BYTES, { allowEmpty: true });
+ if (!buffer) return null;
+ // Integrity: discard a corrupt/wrong download instead of writing it.
+ const bufHash = createHash('sha256').update(buffer).digest('hex');
+ if (bufHash !== sha256) {
+ console.log(`⚠️ peerSync: cos archive ${safeLabel} hash mismatch — discarding (got ${bufHash.slice(0, 8)}, want ${String(sha256).slice(0, 8)})`);
+ return null;
+ }
+ const destDir = join(cosAgentsDir(), date, agentId);
+ await ensureDir(destDir);
+ await atomicWrite(join(destDir, file), buffer);
+ peerSyncEvents.emit('asset-arrived', { filename: safeLabel, kind: 'cos-archive', peerId: peer.instanceId });
+ console.log(`📥 peerSync: pulled cos archive ${safeLabel} from ${peer.name || peer.instanceId} (${buffer.length} bytes)`);
+ return { date, agentId };
+ } finally {
+ inflightPulls.delete(key);
+ }
+}
+
+/**
+ * Receiver-pull the standalone completed-agent history from ONE full-sync peer.
+ * Best-effort + idempotent (every guard returns rather than throws), mirroring
+ * syncMediaLibraryFromPeer. No-op for a non-full-sync peer.
+ *
+ * @param {object} peer a peer entry from getPeers()
+ * @returns {Promise<{ pulled:number, skipped?:string, missing?:number }>}
+ */
+export async function syncCosHistoryFromPeer(peer) {
+ if (!isPlainObject(peer) || peer.fullSync !== true || !isStr(peer.instanceId)) {
+ return { pulled: 0, skipped: 'not-fullsync' };
+ }
+ if (cosHistorySweepInFlight.has(peer.instanceId)) return { pulled: 0, skipped: 'in-flight' };
+ cosHistorySweepInFlight.add(peer.instanceId);
+ try {
+ const url = `${peerBaseUrl(peer)}/api/peer-sync/cos-history-manifest`;
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), ASSET_PULL_TIMEOUT_MS);
+ const res = await peerFetch(url, { signal: controller.signal, maxBytes: COS_HISTORY_MANIFEST_MAX_BYTES }, peer)
+ .finally(() => clearTimeout(timeoutId))
+ .catch(() => null);
+ if (!res || !res.ok) return { pulled: 0, skipped: 'unreachable' };
+ const declaredLen = Number(res.headers?.get?.('content-length'));
+ if (Number.isFinite(declaredLen) && declaredLen > COS_HISTORY_MANIFEST_MAX_BYTES) {
+ console.log(`⚠️ peerSync: cos-history manifest from ${peer.name || peer.instanceId} too large (${declaredLen} > ${COS_HISTORY_MANIFEST_MAX_BYTES}) — skipping`);
+ return { pulled: 0, skipped: 'too-large' };
+ }
+ const body = await res.json().catch(() => null);
+ const parsed = peerCosHistoryManifestSchema.safeParse(body);
+ if (!parsed.success) {
+ console.log(`⚠️ peerSync: cos-history manifest from ${peer.name || peer.instanceId} failed validation — skipping`);
+ return { pulled: 0, skipped: 'invalid' };
+ }
+ const manifest = parsed.data;
+ // Schema gate — GENTLE skip (not reject): wait for the local PortOS to
+ // upgrade rather than mis-pull against a manifest shape we can't read.
+ if (manifest.schemaVersion > PORTOS_SCHEMA_VERSIONS.cosHistory) {
+ console.log(`⏸️ peerSync: ${peer.name || peer.instanceId} cos-history manifest is schema v${manifest.schemaVersion} > local v${PORTOS_SCHEMA_VERSIONS.cosHistory} — skipping until this instance updates`);
+ return { pulled: 0, skipped: 'schema-ahead' };
+ }
+ // Unchanged short-circuit, with a periodic forced re-diff so a LOCAL file
+ // loss self-heals even while the REMOTE manifest stays put.
+ if (lastCosHistoryManifestHash.get(peer.instanceId) === manifest.manifestHash) {
+ const skips = (cosHistoryUnchangedSkips.get(peer.instanceId) || 0) + 1;
+ if (skips < FORCE_REVALIDATE_EVERY) {
+ cosHistoryUnchangedSkips.set(peer.instanceId, skips);
+ return { pulled: 0, skipped: 'unchanged' };
+ }
+ cosHistoryUnchangedSkips.set(peer.instanceId, 0); // forced re-diff — fall through
+ }
+ const missing = await diffCosHistoryManifestAgainstLocal(manifest.entries);
+ if (missing.length === 0) {
+ lastCosHistoryManifestHash.set(peer.instanceId, manifest.manifestHash);
+ return { pulled: 0 };
+ }
+ const requested = missing.length;
+ const landed = await pullMissingCosArchives(peer.instanceId, missing);
+ // Merge the agentId→date index so the CoS history UI lists the arrivals.
+ // Dynamic import keeps cosAgents out of peerSync's static graph (mirrors
+ // reconcileMediaLibraryIndex). Idempotent union, never overwrites.
+ if (landed.length > 0) {
+ const mod = await import('../cosAgents.js').catch(() => null);
+ if (mod?.addAgentArchivesToIndex) {
+ await mod.addAgentArchivesToIndex(landed).catch((err) => {
+ console.log(`⚠️ peerSync: cos-history index merge failed: ${err.message}`);
+ });
+ }
+ }
+ // Re-diff: a resolved pull does NOT mean every byte landed (peer dropped,
+ // 404, size-cap reject) — this is the authoritative signal.
+ const stillMissing = await diffCosHistoryManifestAgainstLocal(manifest.entries);
+ const pulled = requested - stillMissing.length;
+ if (stillMissing.length === 0) {
+ lastCosHistoryManifestHash.set(peer.instanceId, manifest.manifestHash);
+ console.log(`📥 peerSync: cos-history sweep from ${peer.name || peer.instanceId} — pulled ${pulled} archive file(s)`);
+ } else {
+ // Partial pull — do NOT record the hash, so the next tick re-diffs and
+ // retries the still-missing files instead of being marked done.
+ console.log(`⚠️ peerSync: cos-history sweep from ${peer.name || peer.instanceId} — pulled ${pulled}/${requested}, ${stillMissing.length} still missing; retrying next tick`);
+ }
+ return { pulled, missing: stillMissing.length };
+ } finally {
+ cosHistorySweepInFlight.delete(peer.instanceId);
+ }
+}
+
+/**
+ * Periodic driver: sweep completed-agent history from every full-sync peer.
+ * Each peer's sweep is independent + best-effort.
+ */
+export async function syncCosHistoryWithAllPeers() {
+ const peers = await getPeers().catch(() => []);
+ const fullSyncPeers = peers.filter((p) => p?.fullSync === true && p?.enabled !== false && isStr(p.instanceId));
+ for (const peer of fullSyncPeers) {
+ await syncCosHistoryFromPeer(peer).catch((err) => {
+ console.log(`⚠️ peerSync: cos-history sweep for ${peer.name || peer.instanceId} failed: ${err.message}`);
+ });
+ }
+}
+
// --- Listener install + debounced trigger -------------------------------
const pendingTimers = new Map(); // subId → Timeout