Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-1712]): federate the live CoS task list + claim metadata across full-sync peers
[._.]/ Adam Eivyf529da108c3a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0f036c99fc..90ce7f4665 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -11,6 +11,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-1712] The live Chief-of-Staff task list now mirrors across full-sync peers — so two machines never both spawn the same task.** Completing the CoS federation started in #1650, each paired machine now sees the other's live backlog and, crucially, its claims: when one machine claims a task to work it, the other learns of that claim on the ~60s sweep and yields instead of spawning a duplicate agent. Because both machines edit the task files live, the backlogs are merged per task rather than copied over each other — a task you've just claimed is never clobbered by a peer's stale copy, completions converge so a finished task stops showing as in-progress on the other machine, and an expired claim (from a crashed machine) becomes freely re-claimable. It runs only for peers explicitly flagged full-sync; a non-full-sync peer is unaffected. Live terminals, in-flight spawns, and worktrees stay machine-local. (`server/services/sharing/peerSync.js`, `server/services/cosTaskMerge.js`, `server/services/cosTaskStore.js`, `server/routes/peerSync.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 checksdiff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.jsindex 2336c82185..0aef4df40f 100644--- a/server/lib/peerSyncValidation.js+++ b/server/lib/peerSyncValidation.js@@ -310,6 +310,43 @@ export const peerCosHistoryManifestSchema = z.object({entries: z.array(peerCosHistoryManifestEntrySchema).max(150_000),}).strict();+// --- Live CoS task-list + claim-metadata federation (#1712) --------------+// A full-sync peer advertises its live task backlog (both the user TASKS.md and+// the internal COS-TASKS.md) at GET /api/peer-sync/cos-tasks; a receiver (only+// for peers it flags fullSync) runs a claim-aware per-task LWW merge into its own+// task files (see cosTaskStore.mergePeerTasks). Unlike the cos-history archives+// this is NOT byte replication — both peers mutate the files live and each task+// carries claim/lease metadata (#1563), so the merge unions by id and respects+// `leaseExpiresAt` so a peer's fresh claim is never clobbered.+//+// Each entry mirrors a parsed task (taskParser.parseTasksMarkdown output) plus a+// `taskType` discriminator telling the receiver which file it belongs in.+// `metadata` is permissive (task metadata shapes vary — context, reviewers[],+// screenshots[], claim fields) and is re-escaped/re-parsed safely on the+// receiver's next file read, so we only bound the key length + entry count here.+// `.strict()` on the entry rejects a smuggled extra top-level field; the metadata+// record stays open.+const TASK_STATUSES = ['pending', 'in_progress', 'blocked', 'completed'];+const TASK_PRIORITIES = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];+const peerCosTaskEntrySchema = z.object({+ id: z.string().trim().min(1).max(200),+ taskType: z.enum(['user', 'internal']),+ status: z.enum(TASK_STATUSES),+ priority: z.enum(TASK_PRIORITIES),+ description: z.string().max(20_000),+ approvalRequired: z.boolean().optional(),+ autoApproved: z.boolean().optional(),+ metadata: z.record(z.string().min(1).max(120), z.any()).optional(),+}).strict();+export const peerCosTasksSchema = z.object({+ schemaVersion: z.number().int().min(0).max(1_000_000),+ listHash: hex64,+ // A pathological backlog can't force unbounded merge work; the sender logs ++ // truncates beyond its own cap (kept under the byte cap the receiver enforces+ // on the response). 50k is far beyond any realistic single-user backlog.+ tasks: z.array(peerCosTaskEntrySchema).max(50_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 realdiff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 87241453f3..33cfa5a406 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -363,6 +363,21 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// manifest-shape change (new required entry field, segment semantics) MUST bump// this to 2.cosHistory: 1,+ // v1 = live CoS task-list + claim-metadata federation (#1712, second half of+ // #1650, part of epic #1561). NOT a record kind — it's the wire contract for+ // the task payload a full-sync peer advertises at GET /api/peer-sync/cos-tasks.+ // Unlike the immutable, append-only `cosHistory` archives (pure byte+ // replication), the task files (data/COS-TASKS.md / data/TASKS.md) are mutated+ // live by BOTH peers and carry `claimedBy`/`claimedAt`/`leaseExpiresAt` (#1563),+ // so they ride a claim-aware per-task LWW merge (syncCosTasksFromPeer →+ // cosTaskStore.mergePeerTasks), not the asset path. The receiver reads the+ // sender's advertised `schemaVersion` and GENTLY SKIPS (logs, no reject) a+ // sender ahead of its local `cosTasks` — same posture as `mediaLibrary` /+ // `cosHistory`, because a task sweep is best-effort background convergence, not+ // an authoritative record transfer. Only the payload envelope + task-entry+ // shape is gated; the FIRST incompatible change (new required entry field, new+ // claim semantics) MUST bump this to 2.+ cosTasks: 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@@ -429,12 +444,16 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({* 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.+ * - `cosTasks` (#1712): the live CoS task-list + claim-metadata payload a+ * full-sync peer advertises at GET /api/peer-sync/cos-tasks. Receiver-pull ++ * claim-aware per-task merge (see syncCosTasksFromPeer) — 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', 'cosHistory']));+export const NON_RECORD_SCHEMA_CATEGORIES = Object.freeze(new Set(['mediaLibrary', 'cosHistory', 'cosTasks']));/*** Lazy-read the current PortOS version from the ROOT package.json so adiff --git a/server/routes/peerSync.js b/server/routes/peerSync.jsindex a879d035dc..bee07c8980 100644--- a/server/routes/peerSync.js+++ b/server/routes/peerSync.js@@ -49,6 +49,7 @@ import {syncNowForPeer,buildMediaLibraryManifest,buildCosHistoryManifest,+ buildCosTasksPayload,ERR_NOT_FOUND,ERR_VALIDATION,ERR_SCHEMA_VERSION_AHEAD,@@ -179,6 +180,20 @@ router.get('/cos-history-manifest', asyncHandler(async (_req, res) => {res.json(await buildCosHistoryManifest());}));+// --- GET /cos-tasks --- advertise this instance's LIVE task backlog (#1712) so+// a full-sync peer can run a claim-aware per-task merge into its own task files.+//+// Returns `{ schemaVersion, listHash, tasks: [{ id, taskType, status, priority,+// description, metadata, ... }] }` over the user (TASKS.md) + internal+// (COS-TASKS.md) backlogs. Unlike the cos-history archives this is a MERGE+// source, not byte replication — the task metadata carries claim/lease fields+// (#1563) the receiver respects so a peer's fresh claim is never clobbered.+// Unauthenticated like every peer-sync route (Tailnet-only per the threat model);+// the receiver gates the MERGE on its own `fullSync` flag.+router.get('/cos-tasks', asyncHandler(async (_req, res) => {+ res.json(await buildCosTasksPayload());+}));+// --- 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 adiff --git a/server/routes/peerSync.test.js b/server/routes/peerSync.test.jsindex 783d37a519..3090df695d 100644--- a/server/routes/peerSync.test.js+++ b/server/routes/peerSync.test.js@@ -14,6 +14,7 @@ vi.mock('../services/sharing/peerSync.js', () => ({syncNowForPeer: vi.fn(),buildMediaLibraryManifest: vi.fn(),buildCosHistoryManifest: vi.fn(),+ buildCosTasksPayload: 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',@@ -549,6 +550,21 @@ describe('peer-sync routes', () => {});});+ describe('GET /api/peer-sync/cos-tasks (#1712)', () => {+ it('200 with the live task-list + claim-metadata payload', async () => {+ const payload = {+ schemaVersion: 1,+ listHash: 'e'.repeat(64),+ tasks: [{ id: 'task-a', taskType: 'user', status: 'pending', priority: 'MEDIUM', description: 'd', metadata: {} }],+ };+ svc.buildCosTasksPayload.mockResolvedValue(payload);+ const res = await request(buildApp()).get('/api/peer-sync/cos-tasks');+ expect(res.status).toBe(200);+ expect(res.body).toEqual(payload);+ expect(svc.buildCosTasksPayload).toHaveBeenCalled();+ });+ });+describe('GET /api/peer-sync/cos-agent-archive (#1650)', () => {let tmp;let originalCos;diff --git a/server/services/cosTaskMerge.js b/server/services/cosTaskMerge.jsnew file mode 100644index 0000000000..5e9214a960--- /dev/null+++ b/server/services/cosTaskMerge.js@@ -0,0 +1,162 @@+/**+ * CoS Task Merge — claim-aware per-task LWW for cross-peer federation (#1712)+ *+ * The second half of #1650: where the completed-agent HISTORY federates as pure+ * append-only byte replication, the live task files (data/COS-TASKS.md /+ * data/TASKS.md) are the opposite — BOTH full-sync peers mutate them, and each+ * task carries claim/lease metadata (`claimedBy`/`claimedAt`/`leaseExpiresAt`+ * from #1563). A naive whole-file last-writer-wins would clobber a peer's fresh+ * claim and re-introduce the exact double-spawn hazard the lease exists to+ * prevent. So a peer's task list is merged into the local one per task, not+ * copied over it.+ *+ * Pure + side-effect-free: `mergeTaskLists(local, remote, { now })` takes two+ * arrays of parsed tasks (taskParser.parseTasksMarkdown shape) and returns the+ * merged array. Persistence + the wire fetch live in the callers+ * (cosTaskStore.mergePeerTasks, peerSync.syncCosTasksFromPeer).+ *+ * Merge rules (run identically on BOTH peers so they converge to the same+ * result regardless of which side initiates the sweep):+ *+ * 1. Union by id. A task present on only one side is kept as-is — that's how+ * each peer learns the other's backlog. (Deletes do NOT propagate, matching+ * PortOS's LWW-per-id model everywhere else — a task is "removed" by moving+ * it to `completed`, never by dropping the line; an omitted id would just+ * resurrect from the peer on the next sweep. See cosTaskStore.deleteTask.)+ *+ * 2. For a task on BOTH sides, choose the CONTENT by lifecycle rank: a task+ * only ever advances pending → in_progress → (completed|blocked), so the+ * higher-ranked status is the newer truth and wins. This makes completion+ * converge: once either peer marks a task done, the other adopts it instead+ * of holding it `in_progress` forever (a live claim alone can't carry that+ * signal — the owner strips the claim when it completes).+ *+ * 3. Resolve the CLAIM metadata independently of content via the live lease:+ * a side holding an unexpired lease is authoritative (the other peer must+ * see that claim so its spawn guard yields). If BOTH hold a live lease (the+ * sub-second claim race the lease only narrows, never eliminates), break the+ * tie deterministically — later `leaseExpiresAt`, then smaller `claimedBy` —+ * so both peers pick the SAME owner and the loser yields on its next spawn+ * guard. A claim is never kept on a terminal (completed/blocked) task —+ * that mirrors cosTaskStore's release-on-transition so a finished task is+ * freely re-claimable.+ */++import { isLeaseLive, getClaimOwner, CLAIM_METADATA_KEYS } from './cosTaskClaim.js';++// Lifecycle rank — higher wins the content tiebreak (rule 2). Each status has a+// distinct rank so two DIFFERENT statuses never tie (full convergence); the only+// genuine tie is same-status-both-sides, where the content is already equivalent.+const STATUS_RANK = Object.freeze({ completed: 4, blocked: 3, in_progress: 2, pending: 1 });+const statusRank = (status) => STATUS_RANK[status] || 0;+const isTerminalStatus = (status) => status === 'completed' || status === 'blocked';++const PRIORITY_VALUES = Object.freeze({ CRITICAL: 4, HIGH: 3, MEDIUM: 2, LOW: 1 });++const leaseMs = (metadata) => {+ const raw = metadata?.leaseExpiresAt;+ if (raw === undefined || raw === null || raw === '') return null;+ const ms = typeof raw === 'number' ? raw : Date.parse(raw);+ return Number.isFinite(ms) ? ms : null;+};++/**+ * Pick the authoritative claim metadata for a task present on both sides, or+ * null when neither side holds a live lease. Returns just the claim triple+ * (claimedBy/claimedAt/leaseExpiresAt), never the full task.+ */+function resolveClaim(local, remote, now) {+ const localLive = isLeaseLive(local.metadata, now);+ const remoteLive = isLeaseLive(remote.metadata, now);+ if (localLive && remoteLive) {+ // Both claimed — deterministic, side-independent winner so the two peers+ // converge on one owner. Later lease wins (the most-recently-renewed claim+ // is the live worker); exact-tie falls back to the smaller claimedBy.+ const lExp = leaseMs(local.metadata) ?? 0;+ const rExp = leaseMs(remote.metadata) ?? 0;+ if (lExp !== rExp) return claimTriple(lExp > rExp ? local : remote);+ const lOwner = getClaimOwner(local.metadata) || '';+ const rOwner = getClaimOwner(remote.metadata) || '';+ return claimTriple(lOwner <= rOwner ? local : remote);+ }+ if (localLive) return claimTriple(local);+ if (remoteLive) return claimTriple(remote);+ return null;+}++function claimTriple(task) {+ const out = {};+ for (const key of CLAIM_METADATA_KEYS) {+ if (task.metadata?.[key] !== undefined) out[key] = task.metadata[key];+ }+ return out;+}++/**+ * Merge one task that exists on both sides into a single record.+ */+function mergeOne(local, remote, now) {+ // (rule 2) content base by lifecycle rank — higher status wins; tie keeps+ // local (same status ⇒ equivalent lifecycle state, local is the receiver).+ const base = statusRank(remote.status) > statusRank(local.status) ? remote : local;++ // (rule 3) claim metadata resolved separately so a live claim propagates even+ // when content came from the other side.+ const claim = resolveClaim(local, remote, now);++ // Strip any claim keys from the base's metadata, then re-apply the resolved+ // live claim — unless the merged status is terminal, where a claim must never+ // linger (mirrors cosTaskStore release-on-transition).+ const metadata = { ...(base.metadata || {}) };+ for (const key of CLAIM_METADATA_KEYS) delete metadata[key];+ if (claim && !isTerminalStatus(base.status)) Object.assign(metadata, claim);++ return { ...base, metadata };+}++/**+ * Normalize a record adopted wholesale from the peer (a remote-only task, or a+ * merged record sourced from the remote side) so downstream consumers that key+ * on `priorityValue` / `section` stay correct. Re-derives `priorityValue` from+ * the (authoritative) `priority` string and drops the transient `section` so the+ * generator re-buckets it by status.+ */+function normalizeAdopted(task) {+ return {+ ...task,+ priorityValue: PRIORITY_VALUES[task.priority] || 2,+ };+}++/**+ * Merge a peer's task list into the local one. Pure: returns a new array, never+ * mutates the inputs. `now` is injectable for deterministic tests.+ *+ * @param {Array} localTasks parsed local tasks (taskParser shape)+ * @param {Array} remoteTasks parsed peer tasks (same shape; wire-validated)+ * @returns {Array} merged tasks+ */+export function mergeTaskLists(localTasks, remoteTasks, { now = Date.now() } = {}) {+ const local = Array.isArray(localTasks) ? localTasks : [];+ const remote = Array.isArray(remoteTasks) ? remoteTasks : [];+ const remoteById = new Map();+ for (const r of remote) {+ if (r && typeof r.id === 'string' && r.id) remoteById.set(r.id, r);+ }++ const merged = [];+ const seen = new Set();+ for (const l of local) {+ if (!l || typeof l.id !== 'string' || !l.id) continue;+ seen.add(l.id);+ const r = remoteById.get(l.id);+ if (!r) { merged.push(l); continue; }+ merged.push(normalizeAdopted(mergeOne(l, r, now)));+ }+ // Remote-only tasks — adopt so the backlog replicates both directions.+ for (const r of remote) {+ if (!r || typeof r.id !== 'string' || !r.id || seen.has(r.id)) continue;+ merged.push(normalizeAdopted(r));+ }+ return merged;+}diff --git a/server/services/cosTaskMerge.test.js b/server/services/cosTaskMerge.test.jsnew file mode 100644index 0000000000..a70ed8a87a--- /dev/null+++ b/server/services/cosTaskMerge.test.js@@ -0,0 +1,140 @@+import { describe, it, expect } from 'vitest';+import { mergeTaskLists } from './cosTaskMerge.js';+import { LEASE_DURATION_MS } from './cosTaskClaim.js';++const NOW = Date.parse('2026-06-25T12:00:00.000Z');+const future = (ms) => new Date(NOW + ms).toISOString();+const past = (ms) => new Date(NOW - ms).toISOString();++// Minimal parsed-task factory (taskParser shape).+function task(id, status = 'pending', overrides = {}) {+ return {+ id,+ status,+ priority: overrides.priority || 'MEDIUM',+ priorityValue: 2,+ description: overrides.description || `desc ${id}`,+ metadata: overrides.metadata || {},+ ...overrides,+ };+}++// A live claim by `owner` (lease in the future).+const liveClaim = (owner, leaseMs = LEASE_DURATION_MS) => ({+ claimedBy: owner,+ claimedAt: past(1000),+ leaseExpiresAt: future(leaseMs),+});++describe('mergeTaskLists', () => {+ it('unions: keeps local-only and adopts remote-only tasks', () => {+ const local = [task('task-a')];+ const remote = [task('task-b')];+ const merged = mergeTaskLists(local, remote, { now: NOW });+ expect(merged.map((t) => t.id).sort()).toEqual(['task-a', 'task-b']);+ });++ it('adopts a remote-only task and re-derives priorityValue from its priority', () => {+ const remote = [task('task-x', 'pending', { priority: 'CRITICAL', priorityValue: 999 })];+ const [merged] = mergeTaskLists([], remote, { now: NOW });+ expect(merged.id).toBe('task-x');+ expect(merged.priorityValue).toBe(4); // CRITICAL+ });++ it('higher lifecycle status wins for a shared task with no live claims', () => {+ const local = [task('task-1', 'in_progress')];+ const remote = [task('task-1', 'completed')];+ const [merged] = mergeTaskLists(local, remote, { now: NOW });+ expect(merged.status).toBe('completed');+ });++ it('keeps the higher local status over a lower remote status', () => {+ const local = [task('task-1', 'completed')];+ const remote = [task('task-1', 'pending')];+ const [merged] = mergeTaskLists(local, remote, { now: NOW });+ expect(merged.status).toBe('completed');+ });++ it("propagates a remote peer's live claim onto a locally-unclaimed task (gates cross-machine spawn)", () => {+ const local = [task('task-1', 'pending')];+ const remote = [task('task-1', 'in_progress', { metadata: liveClaim('instance-B') })];+ const [merged] = mergeTaskLists(local, remote, { now: NOW });+ expect(merged.status).toBe('in_progress');+ expect(merged.metadata.claimedBy).toBe('instance-B');+ expect(merged.metadata.leaseExpiresAt).toBe(remote[0].metadata.leaseExpiresAt);+ });++ it("never clobbers the local peer's own live claim with a remote pending copy", () => {+ const local = [task('task-1', 'in_progress', { metadata: liveClaim('instance-A') })];+ const remote = [task('task-1', 'pending')]; // peer hasn't seen the claim yet+ const [merged] = mergeTaskLists(local, remote, { now: NOW });+ expect(merged.status).toBe('in_progress');+ expect(merged.metadata.claimedBy).toBe('instance-A');+ });++ it('both-claimed race converges to the later-lease owner', () => {+ const local = [task('task-1', 'in_progress', { metadata: liveClaim('instance-A', LEASE_DURATION_MS) })];+ const remote = [task('task-1', 'in_progress', { metadata: liveClaim('instance-B', LEASE_DURATION_MS * 2) })];+ // Run BOTH directions — the winner must be identical regardless of initiator.+ const [fromA] = mergeTaskLists(local, remote, { now: NOW });+ const [fromB] = mergeTaskLists(remote, local, { now: NOW });+ expect(fromA.metadata.claimedBy).toBe('instance-B');+ expect(fromB.metadata.claimedBy).toBe('instance-B');+ });++ it('both-claimed equal-lease race breaks the tie deterministically by smaller claimedBy', () => {+ const lease = future(LEASE_DURATION_MS);+ const a = { claimedBy: 'instance-A', claimedAt: past(1000), leaseExpiresAt: lease };+ const b = { claimedBy: 'instance-B', claimedAt: past(1000), leaseExpiresAt: lease };+ const local = [task('task-1', 'in_progress', { metadata: a })];+ const remote = [task('task-1', 'in_progress', { metadata: b })];+ const [fromA] = mergeTaskLists(local, remote, { now: NOW });+ const [fromB] = mergeTaskLists(remote, local, { now: NOW });+ expect(fromA.metadata.claimedBy).toBe('instance-A');+ expect(fromB.metadata.claimedBy).toBe('instance-A');+ });++ it('drops claim metadata when the merged status is terminal', () => {+ // Remote completed (claim already released); local still in_progress with a+ // stale live claim. Completed wins, and a terminal task carries no claim.+ const local = [task('task-1', 'in_progress', { metadata: liveClaim('instance-A') })];+ const remote = [task('task-1', 'completed')];+ const [merged] = mergeTaskLists(local, remote, { now: NOW });+ expect(merged.status).toBe('completed');+ expect(merged.metadata.claimedBy).toBeUndefined();+ expect(merged.metadata.leaseExpiresAt).toBeUndefined();+ });++ it('treats an expired remote lease as not-claimed (re-claimable)', () => {+ const expired = { claimedBy: 'instance-B', claimedAt: past(LEASE_DURATION_MS * 2), leaseExpiresAt: past(1000) };+ const local = [task('task-1', 'pending')];+ const remote = [task('task-1', 'pending', { metadata: expired })];+ const [merged] = mergeTaskLists(local, remote, { now: NOW });+ // No live lease either side → no live claim applied.+ expect(merged.metadata.claimedBy).toBeUndefined();+ });++ it('preserves non-claim metadata of the winning content side', () => {+ const local = [task('task-1', 'pending', { metadata: { context: 'local ctx' } })];+ const remote = [task('task-1', 'in_progress', { metadata: { context: 'remote ctx', ...liveClaim('instance-B') } })];+ const [merged] = mergeTaskLists(local, remote, { now: NOW });+ expect(merged.metadata.context).toBe('remote ctx');+ expect(merged.metadata.claimedBy).toBe('instance-B');+ });++ it('does not mutate the input arrays/objects', () => {+ const localMeta = { context: 'x' };+ const local = [task('task-1', 'pending', { metadata: localMeta })];+ const remote = [task('task-1', 'in_progress', { metadata: liveClaim('instance-B') })];+ mergeTaskLists(local, remote, { now: NOW });+ expect(localMeta).toEqual({ context: 'x' });+ expect(local[0].status).toBe('pending');+ });++ it('tolerates non-array / malformed inputs', () => {+ expect(mergeTaskLists(null, null, { now: NOW })).toEqual([]);+ expect(mergeTaskLists([task('a')], undefined, { now: NOW }).map((t) => t.id)).toEqual(['a']);+ // Entries missing an id are skipped, not adopted.+ expect(mergeTaskLists([{ status: 'pending' }], [], { now: NOW })).toEqual([]);+ });+});diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex 735700cc97..bba4392be3 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -20,6 +20,7 @@ import { REVIEW_STOP_MODES, normalizeReviewers } from '../lib/validation.js';import { loadState, withStateLock, ROOT_DIR } from './cosState.js';import { cosEvents } from './cosEvents.js';import { CLAIM_METADATA_KEYS } from './cosTaskClaim.js';+import { mergeTaskLists } from './cosTaskMerge.js';// First non-empty line of a string. Used by addTask dedup: stored descriptions// are flattened to a single line by generateTasksMarkdown, so the comparison@@ -316,6 +317,51 @@ export async function updateTask(taskId, updates, taskType = 'user') {});}+/**+ * Merge a full-sync peer's task list into one local task file (#1712).+ *+ * The receiver side of CoS task federation: `syncCosTasksFromPeer` fetches the+ * peer's live backlog and hands the tasks for ONE file (user vs internal) here.+ * The read-merge-write runs under `withStateLock` so it serializes against the+ * spawn path's claim writes (agentLifecycle → updateTask, also lock-held) — the+ * merge always sees, and merges against, the freshest persisted claim metadata.+ *+ * Idempotent + write-skipping: the claim-aware merge (cosTaskMerge) is pure and+ * deterministic, so we compare the GENERATED markdown before/after (not the raw+ * file bytes — pre-existing formatting drift shouldn't force a write) and only+ * persist + emit `tasks:changed` when the merge actually changed something.+ *+ * @param {'user'|'internal'} taskType which file to merge into+ * @param {Array} remoteTasks peer tasks for this file (wire-validated)+ * @param {{ now?: number }} [opts] injectable clock for deterministic tests+ * @returns {Promise<{ changed: boolean, count?: number }>}+ */+export async function mergePeerTasks(taskType, remoteTasks, { now = Date.now() } = {}) {+ return withStateLock(async () => {+ const state = await loadState();+ const filePath = taskType === 'user'+ ? join(ROOT_DIR, state.config.userTasksFile)+ : join(ROOT_DIR, state.config.cosTasksFile);++ const localTasks = existsSync(filePath)+ ? parseTasksMarkdown(await readFile(filePath, 'utf-8'))+ : [];++ const merged = mergeTaskLists(localTasks, remoteTasks, { now });++ const includeApprovalFlags = taskType === 'internal';+ const localMarkdown = generateTasksMarkdown(localTasks, includeApprovalFlags);+ const mergedMarkdown = generateTasksMarkdown(merged, includeApprovalFlags);+ // Nothing the peer sent changed our state — skip the write (and the event+ // that would wake the scheduler) so a steady-state sweep is a pure no-op.+ if (mergedMarkdown === localMarkdown) return { changed: false };++ await writeFile(filePath, mergedMarkdown);+ cosEvents.emit('tasks:changed', { type: taskType, action: 'peer-merged' });+ return { changed: true, count: merged.length };+ });+}+/*** Delete a task*/diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex 804052d642..efa6034b6c 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -60,7 +60,8 @@ import {updateTask,deleteTask,reorderTasks,- approveTask+ approveTask,+ mergePeerTasks} from './cosTaskStore.js';const USER_FILE = '/root/TASKS.md';@@ -347,3 +348,56 @@ describe('addTask — first-line dedup (source guards)', () => {expect(fnBody).toMatch(/taskData\.app\s*\|\|\s*null/);});});++// Receiver side of CoS task federation (#1712). Runs the REAL cosTaskMerge+// against the in-memory file map so the read-merge-write round-trip + write-skip+// are covered end-to-end (the merge rules themselves are unit-tested in+// cosTaskMerge.test.js).+describe('cosTaskStore.mergePeerTasks', () => {+ const NOW = Date.parse('2026-06-25T12:00:00.000Z');+ const future = (ms) => new Date(NOW + ms).toISOString();++ it('adopts a remote-only task into the file and emits tasks:changed', async () => {+ await addTask({ description: 'local task', priority: 'LOW', id: 'task-local' }, 'user');+ mock.events = [];+ const remote = [{ id: 'task-remote', taskType: 'user', status: 'pending', priority: 'HIGH', description: 'peer task', metadata: {} }];+ const res = await mergePeerTasks('user', remote, { now: NOW });+ expect(res.changed).toBe(true);+ const after = await getUserTasks();+ expect(after.tasks.map(t => t.id).sort()).toEqual(['task-local', 'task-remote']);+ expect(mock.events.some(e => e.name === 'tasks:changed' && e.payload.action === 'peer-merged')).toBe(true);+ });++ it('is a no-op (no write, no event) when the peer payload changes nothing', async () => {+ await addTask({ description: 'same', priority: 'MEDIUM', id: 'task-same' }, 'user');+ mock.events = [];+ const writeSpy = (await import('fs/promises')).writeFile;+ writeSpy.mockClear();+ const remote = [{ id: 'task-same', taskType: 'user', status: 'pending', priority: 'MEDIUM', description: 'same', metadata: {} }];+ const res = await mergePeerTasks('user', remote, { now: NOW });+ expect(res).toEqual({ changed: false });+ expect(writeSpy).not.toHaveBeenCalled();+ expect(mock.events.some(e => e.name === 'tasks:changed')).toBe(false);+ });++ it("never clobbers the local peer's live claim with a remote pending copy", async () => {+ // Local task is claimed + in_progress (this instance is working it).+ await addTask({ description: 'claimed work', id: 'task-c', priority: 'HIGH' }, 'user');+ await updateTask('task-c', { status: 'in_progress', metadata: { claimedBy: 'instance-A', claimedAt: future(-1000), leaseExpiresAt: future(60_000) } }, 'user');+ // Peer still thinks it's pending + unclaimed.+ const remote = [{ id: 'task-c', taskType: 'user', status: 'pending', priority: 'HIGH', description: 'claimed work', metadata: {} }];+ await mergePeerTasks('user', remote, { now: NOW });+ const after = await getUserTasks();+ const merged = after.tasks.find(t => t.id === 'task-c');+ expect(merged.status).toBe('in_progress');+ expect(merged.metadata.claimedBy).toBe('instance-A');+ });++ it('creates the file when it does not exist yet and the peer has tasks', async () => {+ const remote = [{ id: 'sys-x', taskType: 'internal', status: 'pending', priority: 'MEDIUM', description: 'new', metadata: {} }];+ const res = await mergePeerTasks('internal', remote, { now: NOW });+ expect(res.changed).toBe(true);+ const after = await getCosTasks();+ expect(after.tasks.map(t => t.id)).toContain('sys-x');+ });+});diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex 326d81864a..1b5d8c3ada 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -1123,6 +1123,12 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {// Versioned for the manifest envelope and gated by syncCosHistoryFromPeer's// gentle skip-if-ahead; declared non-record in NON_RECORD_SCHEMA_CATEGORIES.'cosHistory',+ // Live CoS task list + claim metadata (#1712) → its own receiver-pull+ // endpoint (GET /api/peer-sync/cos-tasks) with a claim-aware per-task merge,+ // NOT the file-snapshot transfer. Versioned for the payload envelope and+ // gated by syncCosTasksFromPeer's gentle skip-if-ahead; declared non-record+ // in NON_RECORD_SCHEMA_CATEGORIES.+ 'cosTasks',]);const covered = new Set(Object.values(dataSync.getSnapshotCategorySchemaKeys()).flat());for (const key of Object.keys(PORTOS_SCHEMA_VERSIONS)) {diff --git a/server/services/sharing/cosTasksSync.test.js b/server/services/sharing/cosTasksSync.test.jsnew file mode 100644index 0000000000..d1f89e355d--- /dev/null+++ b/server/services/sharing/cosTasksSync.test.js@@ -0,0 +1,146 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { createHash } from 'crypto';++// Live CoS task-list + claim-metadata federation (#1712). We exercise+// peerSync.js's cos-tasks functions with the network (peerFetch), peer registry+// (instances), and the CoS task store all mocked. cosTaskStore is a spy so the+// receiver merge is observable AND can never touch the real data/TASKS.md —+// buildCosTasksPayload reads its getUserTasks/getCosTasks, syncCosTasksFromPeer+// calls its mergePeerTasks. The heavy record-graph modules are mocked exactly as+// cosHistorySync.test.js does, purely so importing peerSync.js stays offline.++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() }));+// cosTaskStore is dynamic-imported by both the sender (getUserTasks/getCosTasks)+// and the receiver (mergePeerTasks). Spy it so the wire build + merge are+// observable AND can't read/write the real task files.+vi.mock('../cosTaskStore.js', () => ({+ getUserTasks: vi.fn().mockResolvedValue({ tasks: [] }),+ getCosTasks: vi.fn().mockResolvedValue({ tasks: [] }),+ mergePeerTasks: vi.fn().mockResolvedValue({ changed: false }),+}));++import {+ buildCosTasksPayload,+ syncCosTasksFromPeer,+} from './peerSync.js';+import { getPeers } from '../instances.js';+import { peerFetch } from '../../lib/peerHttpClient.js';+import { getUserTasks, getCosTasks, mergePeerTasks } from '../cosTaskStore.js';++const sha = (s) => createHash('sha256').update(s).digest('hex');++function payloadRes(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 };++function task(id, status = 'pending', overrides = {}) {+ return { id, status, priority: 'MEDIUM', priorityValue: 2, description: `d ${id}`, metadata: {}, ...overrides };+}++beforeEach(() => {+ vi.mocked(peerFetch).mockReset();+ vi.mocked(getPeers).mockResolvedValue([PEER]);+ vi.mocked(getUserTasks).mockReset().mockResolvedValue({ tasks: [] });+ vi.mocked(getCosTasks).mockReset().mockResolvedValue({ tasks: [] });+ vi.mocked(mergePeerTasks).mockReset().mockResolvedValue({ changed: false });+});++describe('buildCosTasksPayload', () => {+ it('unions user + internal tasks with a taskType discriminator and a deterministic listHash', async () => {+ vi.mocked(getUserTasks).mockResolvedValue({ tasks: [task('task-a', 'pending')] });+ vi.mocked(getCosTasks).mockResolvedValue({ tasks: [task('sys-b', 'in_progress', { metadata: { claimedBy: 'i1' } })] });+ const p = await buildCosTasksPayload();+ expect(p.schemaVersion).toBe(1);+ expect(p.listHash).toMatch(/^[a-f0-9]{64}$/);+ expect(p.tasks).toHaveLength(2);+ const user = p.tasks.find((t) => t.id === 'task-a');+ const internal = p.tasks.find((t) => t.id === 'sys-b');+ expect(user.taskType).toBe('user');+ expect(internal.taskType).toBe('internal');+ expect(internal.metadata.claimedBy).toBe('i1');+ // Deterministic: same disk → same hash.+ const again = await buildCosTasksPayload();+ expect(again.listHash).toBe(p.listHash);+ });++ it('listHash flips when claim metadata changes (re-triggers a merge)', async () => {+ vi.mocked(getCosTasks).mockResolvedValue({ tasks: [task('sys-b', 'in_progress')] });+ const before = (await buildCosTasksPayload()).listHash;+ vi.mocked(getCosTasks).mockResolvedValue({ tasks: [task('sys-b', 'in_progress', { metadata: { claimedBy: 'i1', leaseExpiresAt: 'x' } })] });+ const after = (await buildCosTasksPayload()).listHash;+ expect(after).not.toBe(before);+ });++ it('returns an empty payload when there are no tasks', async () => {+ const p = await buildCosTasksPayload();+ expect(p.tasks).toEqual([]);+ expect(p.schemaVersion).toBe(1);+ });+});++describe('syncCosTasksFromPeer', () => {+ it('skips a non-full-sync peer (no network)', async () => {+ const r = await syncCosTasksFromPeer({ ...PEER, fullSync: false });+ expect(r).toEqual({ merged: 0, skipped: 'not-fullsync' });+ expect(peerFetch).not.toHaveBeenCalled();+ });++ it('gently skips a sender whose payload schema is ahead', async () => {+ vi.mocked(peerFetch).mockResolvedValue(payloadRes({ schemaVersion: 999, listHash: sha('x'), tasks: [] }));+ const r = await syncCosTasksFromPeer(PEER);+ expect(r).toEqual({ merged: 0, skipped: 'schema-ahead' });+ expect(mergePeerTasks).not.toHaveBeenCalled();+ });++ it('skips a malformed payload (failed validation)', async () => {+ vi.mocked(peerFetch).mockResolvedValue(payloadRes({ schemaVersion: 1, listHash: 'not-hex', tasks: [] }));+ const r = await syncCosTasksFromPeer(PEER);+ expect(r).toEqual({ merged: 0, skipped: 'invalid' });+ });++ it('merges both task files, splitting entries by taskType', async () => {+ const tasks = [+ { id: 'task-a', taskType: 'user', status: 'pending', priority: 'MEDIUM', description: 'd' },+ { id: 'sys-b', taskType: 'internal', status: 'in_progress', priority: 'HIGH', description: 'd', metadata: { claimedBy: 'peer-1' } },+ ];+ vi.mocked(peerFetch).mockResolvedValue(payloadRes({ schemaVersion: 1, listHash: sha('m'), tasks }));+ vi.mocked(mergePeerTasks).mockResolvedValue({ changed: true, count: 1 });++ const r = await syncCosTasksFromPeer(PEER);+ expect(r).toEqual({ merged: 2 });+ expect(mergePeerTasks).toHaveBeenCalledTimes(2);+ const calls = vi.mocked(mergePeerTasks).mock.calls;+ const userCall = calls.find(([type]) => type === 'user');+ const internalCall = calls.find(([type]) => type === 'internal');+ expect(userCall[1].map((t) => t.id)).toEqual(['task-a']);+ expect(internalCall[1].map((t) => t.id)).toEqual(['sys-b']);+ });++ it('short-circuits an unchanged backlog on the second identical sweep', async () => {+ vi.mocked(peerFetch).mockResolvedValue(payloadRes({ schemaVersion: 1, listHash: sha('stable'), tasks: [] }));+ await syncCosTasksFromPeer(PEER); // first sweep records the hash+ vi.mocked(mergePeerTasks).mockClear();+ const r = await syncCosTasksFromPeer(PEER); // second identical sweep+ expect(r).toEqual({ merged: 0, skipped: 'unchanged' });+ expect(mergePeerTasks).not.toHaveBeenCalled();+ });+});diff --git a/server/services/sharing/index.js b/server/services/sharing/index.jsindex 0bd0ac091f..754ac1d75f 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, syncCosHistoryWithAllPeers } from './peerSync.js';+import { installPeerSyncListener, uninstallPeerSyncListener, peerSyncEvents, syncMediaLibraryWithAllPeers, syncCosHistoryWithAllPeers, syncCosTasksWithAllPeers } from './peerSync.js';import { hasSubscriptionAdapter } from './recordEvents.js';import { initAnnotationsSync } from './annotationsSync.js';@@ -48,6 +48,12 @@ function startMediaLibrarySweep() {syncCosHistoryWithAllPeers().catch((err) => {console.error(`❌ sharing: cos-history sweep failed: ${err.message}`);});+ // Live CoS task list + claim metadata (#1712) — the second half of #1650.+ // Same cadence; independent best-effort claim-aware merge so a peer's fresh+ // claim gates spawns across machines. Separate catch keeps it isolated.+ syncCosTasksWithAllPeers().catch((err) => {+ console.error(`❌ sharing: cos-tasks sweep failed: ${err.message}`);+ });} catch (err) {console.error(`❌ sharing: full-sync sweep threw synchronously: ${err.message}`);}diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 585ba9cae9..611fe8d948 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, peerCosHistoryManifestSchema, COS_ARCHIVE_DATE_RE, COS_AGENT_ID_RE, COS_ARCHIVE_FILES } from '../../lib/validation.js';+import { peerSyncPushSchema, peerLibraryManifestSchema, peerCosHistoryManifestSchema, peerCosTasksSchema, 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';@@ -3309,6 +3309,200 @@ export async function syncCosHistoryWithAllPeers() {}}+// === Live CoS task-list + claim-metadata federation (#1712) ================+//+// The second half of #1650. Where the completed-agent HISTORY above federates as+// pure append-only byte replication, the LIVE task files (data/COS-TASKS.md /+// data/TASKS.md) are mutated by BOTH peers and carry claim/lease metadata (#1563),+// so they ride a claim-aware per-task LWW MERGE — never a byte/whole-file copy+// that would clobber a peer's fresh claim and re-open the double-spawn hazard.+//+// Transport mirrors the cos-history sweep's receiver-pull shape: the sender+// advertises its backlog at GET /api/peer-sync/cos-tasks; a receiver (only for+// peers it flags fullSync) fetches it, version-gates it, short-circuits on an+// unchanged listHash, and merges per task into its own files via+// cosTaskStore.mergePeerTasks (dynamic import — keeps the CoS task graph out of+// peerSync's static import chain, mirroring reconcileCosHistoryIndex's import of+// cosAgents). The merge itself is the pure cosTaskMerge module.+//+// Running-agent state (state.json slots), live PTY buffers, the in-flight+// spawningTasks guard, and worktree working dirs are deliberately NOT federated —+// only the task RECORDS + their claim metadata.++// The task payload JSON (not bytes — there are none). Generous vs any real+// single-user backlog; the build truncates beyond the entry cap and the receiver+// rejects an over-cap response on its content-length check.+const COS_TASKS_ENTRY_CAP = 50_000;+const COS_TASKS_MAX_BYTES = 32 * 1024 * 1024;++// Reduce a parsed task to its wire entry: the fields the receiver's merge ++// markdown round-trip need, plus the `taskType` discriminator telling it which+// file the task belongs in. Metadata rides verbatim (claim fields included);+// the receiver re-escapes/re-parses it safely on its next file read.+function taskToWireEntry(task, taskType) {+ const entry = {+ id: task.id,+ taskType,+ status: task.status,+ priority: task.priority,+ description: task.description,+ metadata: isPlainObject(task.metadata) ? task.metadata : {},+ };+ if (typeof task.approvalRequired === 'boolean') entry.approvalRequired = task.approvalRequired;+ if (typeof task.autoApproved === 'boolean') entry.autoApproved = task.autoApproved;+ return entry;+}++/**+ * Build the live task payload this instance advertises to full-sync peers.+ * Unions the user (TASKS.md) and internal (COS-TASKS.md) backlogs, stamps a+ * `listHash` over the sorted entries so a receiver can short-circuit an+ * unchanged backlog, and caps the entry count (logs + truncates beyond it).+ *+ * Dynamic import of cosTaskStore keeps the CoS task graph out of peerSync's+ * static import chain (mirrors reconcileCosHistoryIndex).+ *+ * @returns {Promise<{ schemaVersion:number, listHash:string, tasks:Array }>}+ */+export async function buildCosTasksPayload() {+ const empty = { schemaVersion: PORTOS_SCHEMA_VERSIONS.cosTasks, listHash: createHash('sha256').update('').digest('hex'), tasks: [] };+ const mod = await import('../cosTaskStore.js').catch(() => null);+ if (!mod?.getUserTasks || !mod?.getCosTasks) return empty;+ const [userRes, cosRes] = await Promise.all([+ mod.getUserTasks().catch(() => null),+ mod.getCosTasks().catch(() => null),+ ]);+ let entries = [+ ...((userRes?.tasks || []).map((t) => taskToWireEntry(t, 'user'))),+ ...((cosRes?.tasks || []).map((t) => taskToWireEntry(t, 'internal'))),+ ];+ if (entries.length > COS_TASKS_ENTRY_CAP) {+ console.log(`⚠️ peerSync: cos-tasks payload hit the ${COS_TASKS_ENTRY_CAP}-entry cap — truncating (some tasks won't federate this tick)`);+ entries = entries.slice(0, COS_TASKS_ENTRY_CAP);+ }+ // Deterministic order so the listHash converges across machines regardless of+ // file/section order. Hash the lifecycle-relevant fields (incl. claim metadata)+ // so a claim/renewal/status change flips the hash and re-triggers a merge,+ // while pure reordering does not.+ entries.sort((a, b) => (a.taskType < b.taskType ? -1 : a.taskType > b.taskType ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0));+ const listHash = createHash('sha256')+ .update(entries.map((e) => `${e.taskType}:${e.id}:${e.status}:${e.priority}:${JSON.stringify(e.metadata || {})}`).join('\n'))+ .digest('hex');+ return { schemaVersion: PORTOS_SCHEMA_VERSIONS.cosTasks, listHash, tasks: entries };+}++// Receiver-side bookkeeping — mirrors the cos-history sweep.+const lastCosTasksListHash = new Map(); // peerInstanceId → listHash+const cosTasksUnchangedSkips = new Map(); // peerInstanceId → count+const cosTasksSweepInFlight = new Set(); // peerInstanceId++/**+ * Apply a peer's task payload into the LOCAL task files via a claim-aware merge.+ * Splits the entries by taskType and hands each file's tasks to+ * cosTaskStore.mergePeerTasks (which runs the pure merge under the state lock).+ * Returns the number of files actually changed.+ */+async function mergeCosTasksFromPayload(tasks) {+ const mod = await import('../cosTaskStore.js').catch(() => null);+ if (!mod?.mergePeerTasks) return 0;+ const user = [];+ const internal = [];+ for (const t of Array.isArray(tasks) ? tasks : []) {+ if (t?.taskType === 'internal') internal.push(t);+ else if (t?.taskType === 'user') user.push(t);+ }+ let changed = 0;+ // Always merge BOTH files (even when one side is empty) so a task the peer+ // resolved/removed from a file converges — an empty list still merges (union+ // keeps local-only tasks, so it never wipes the local backlog).+ const userRes = await mod.mergePeerTasks('user', user).catch((err) => {+ console.log(`⚠️ peerSync: cos-tasks user merge failed: ${err.message}`); return null;+ });+ if (userRes?.changed) changed++;+ const internalRes = await mod.mergePeerTasks('internal', internal).catch((err) => {+ console.log(`⚠️ peerSync: cos-tasks internal merge failed: ${err.message}`); return null;+ });+ if (internalRes?.changed) changed++;+ return changed;+}++/**+ * Receiver-pull the live task backlog from ONE full-sync peer and merge it.+ * Best-effort + idempotent (every guard returns rather than throws), mirroring+ * syncCosHistoryFromPeer. No-op for a non-full-sync peer.+ *+ * @param {object} peer a peer entry from getPeers()+ * @returns {Promise<{ merged:number, skipped?:string }>}+ */+export async function syncCosTasksFromPeer(peer) {+ if (!isPlainObject(peer) || peer.fullSync !== true || !isStr(peer.instanceId)) {+ return { merged: 0, skipped: 'not-fullsync' };+ }+ if (cosTasksSweepInFlight.has(peer.instanceId)) return { merged: 0, skipped: 'in-flight' };+ cosTasksSweepInFlight.add(peer.instanceId);+ try {+ const url = `${peerBaseUrl(peer)}/api/peer-sync/cos-tasks`;+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), ASSET_PULL_TIMEOUT_MS);+ const res = await peerFetch(url, { signal: controller.signal, maxBytes: COS_TASKS_MAX_BYTES }, peer)+ .finally(() => clearTimeout(timeoutId))+ .catch(() => null);+ if (!res || !res.ok) return { merged: 0, skipped: 'unreachable' };+ const declaredLen = Number(res.headers?.get?.('content-length'));+ if (Number.isFinite(declaredLen) && declaredLen > COS_TASKS_MAX_BYTES) {+ console.log(`⚠️ peerSync: cos-tasks payload from ${peer.name || peer.instanceId} too large (${declaredLen} > ${COS_TASKS_MAX_BYTES}) — skipping`);+ return { merged: 0, skipped: 'too-large' };+ }+ const body = await res.json().catch(() => null);+ const parsed = peerCosTasksSchema.safeParse(body);+ if (!parsed.success) {+ console.log(`⚠️ peerSync: cos-tasks payload from ${peer.name || peer.instanceId} failed validation — skipping`);+ return { merged: 0, skipped: 'invalid' };+ }+ const payload = parsed.data;+ // Schema gate — GENTLE skip (not reject): wait for the local PortOS to+ // upgrade rather than mis-merge against a payload shape we can't read.+ if (payload.schemaVersion > PORTOS_SCHEMA_VERSIONS.cosTasks) {+ console.log(`⏸️ peerSync: ${peer.name || peer.instanceId} cos-tasks payload is schema v${payload.schemaVersion} > local v${PORTOS_SCHEMA_VERSIONS.cosTasks} — skipping until this instance updates`);+ return { merged: 0, skipped: 'schema-ahead' };+ }+ // Unchanged short-circuit, with a periodic forced re-merge so a LOCAL task+ // loss self-heals even while the REMOTE backlog stays put. Unlike cos-history+ // the merge depends on TIME (lease expiry), so the forced re-merge also lets+ // an expired remote claim become re-claimable locally without a remote change.+ if (lastCosTasksListHash.get(peer.instanceId) === payload.listHash) {+ const skips = (cosTasksUnchangedSkips.get(peer.instanceId) || 0) + 1;+ if (skips < FORCE_REVALIDATE_EVERY) {+ cosTasksUnchangedSkips.set(peer.instanceId, skips);+ return { merged: 0, skipped: 'unchanged' };+ }+ cosTasksUnchangedSkips.set(peer.instanceId, 0); // forced re-merge — fall through+ }+ const changed = await mergeCosTasksFromPayload(payload.tasks);+ lastCosTasksListHash.set(peer.instanceId, payload.listHash);+ if (changed > 0) {+ console.log(`📥 peerSync: cos-tasks sweep from ${peer.name || peer.instanceId} — merged ${changed} task file(s)`);+ }+ return { merged: changed };+ } finally {+ cosTasksSweepInFlight.delete(peer.instanceId);+ }+}++/**+ * Periodic driver: merge the live task backlog from every full-sync peer.+ * Each peer's sweep is independent + best-effort.+ */+export async function syncCosTasksWithAllPeers() {+ 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 syncCosTasksFromPeer(peer).catch((err) => {+ console.log(`⚠️ peerSync: cos-tasks sweep for ${peer.name || peer.instanceId} failed: ${err.message}`);+ });+ }+}+// --- Listener install + debounced trigger -------------------------------const pendingTimers = new Map(); // subId → Timeout