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-1714]): newest-edit-wins LWW for federated CoS task content
[._.]/ Adam Eivy58262a1e8e79
diff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.jsindex 6d9b94d26b..54568bb94f 100644--- a/server/lib/peerSyncValidation.js+++ b/server/lib/peerSyncValidation.js@@ -340,6 +340,11 @@ const peerCosTaskEntrySchema = z.object({// undefined — the receiver's markdown generator does Object.entries(metadata)// and would otherwise throw, failing the whole file merge (the merge layer// also defends, but normalizing at the boundary is cheaper + clearer).+ //+ // The newest-edit-wins stamp (`metadata.updatedAt`, #1714) rides here verbatim:+ // it lives in metadata (not a top-level entry field) so it survives the TASKS.md+ // markdown round-trip the receiver re-reads, and is already covered by the+ // permissive value schema + the listHash's `JSON.stringify(metadata)`.metadata: z.record(z.string().min(1).max(120), z.any()).optional().default({}),}).strict();export const peerCosTasksSchema = z.object({diff --git a/server/services/cosTaskMerge.js b/server/services/cosTaskMerge.jsindex a8c147e685..9f72a90d5d 100644--- a/server/services/cosTaskMerge.js+++ b/server/services/cosTaskMerge.js@@ -55,6 +55,24 @@ const STATUS_RANK = Object.freeze({ completed: 4, blocked: 3, in_progress: 2, peconst statusRank = (status) => STATUS_RANK[status] || 0;const isTerminalStatus = (status) => status === 'completed' || status === 'blocked';+// The metadata key carrying a task's content-edit timestamp (#1714). Stamped in+// cosTaskStore's write paths on every content edit and used here as the+// same-status LWW key. Excluded from the content signature (it's the edit *key*,+// not content) the same way claim metadata is.+const EDIT_STAMP_KEY = 'updatedAt';++// Epoch ms of a task's content-edit stamp (`metadata.updatedAt`), or -Infinity+// when absent/unparseable. -Infinity (not 0) so ANY real stamp beats a legacy+// task that predates the field — an older peer that never stamps always loses a+// same-status tie to a peer that did ("absent = oldest"), and two un-stamped+// sides compare equal and fall through to the deterministic comparator.+const updatedAtMs = (task) => {+ const raw = task?.metadata?.[EDIT_STAMP_KEY];+ if (raw === undefined || raw === null || raw === '') return -Infinity;+ const ms = typeof raw === 'number' ? raw : Date.parse(raw);+ return Number.isFinite(ms) ? ms : -Infinity;+};+const leaseMs = (metadata) => {const raw = metadata?.leaseExpiresAt;if (raw === undefined || raw === null || raw === '') return null;@@ -96,24 +114,29 @@ function claimTriple(task) {/*** Choose the content base for a task on both sides. Higher lifecycle status wins- * (rule 2). On a SAME-status tie the two sides can still differ in editable- * content — priority, description, approval flags — and "keep local" would be- * side-dependent, so machine A (local=A) and machine B (local=B) would each keep- * their own value and never reconcile. Break the tie with a deterministic,- * side-independent comparator so both peers converge on the same record:- * higher priority, then lexicographically-greater description, then a stable- * JSON tiebreak on the remaining comparable fields.+ * (rule 2). On a SAME-status tie, newest-EDIT wins via the per-task `updatedAt`+ * stamp (#1714): the side whose content was edited most recently is authoritative.+ * The stamp is threaded through cosTaskStore's write paths, so a same-status+ * content edit (priority/description/approval/metadata) on one machine carries a+ * larger `updatedAt` and is adopted by the other. This is symmetric — machine A+ * compares (A,B) and machine B compares (B,A), both prefer the larger stamp, so+ * they converge on the SAME record regardless of which side initiates the sweep.*- * NOTE: with no per-task edit timestamp this converges but cannot guarantee- * *newest-edit* wins (it can prefer a stale higher-priority value over a fresh- * lower one). That's the conventional LWW trade-off; a real `updatedAt` edit- * key is the proper upgrade (tracked in #1714). Convergence is the- * load-bearing property here — a sync that never reconciles is worse.+ * When the stamps tie (equal, or both absent on legacy/older-peer tasks) we fall+ * back to a deterministic, side-independent comparator — higher priority, then a+ * canonical content signature — so a content edit still converges even with no+ * usable timestamp. Convergence is the load-bearing property; `updatedAt` just+ * upgrades the tiebreak from "deterministic" to "deterministic AND newest-wins"+ * whenever a real stamp is present.*/function pickContentBase(local, remote) {const lr = statusRank(local.status);const rr = statusRank(remote.status);if (rr !== lr) return rr > lr ? remote : local;+ // Same lifecycle status: newest content edit wins (absent stamp = oldest).+ const lu = updatedAtMs(local);+ const ru = updatedAtMs(remote);+ if (lu !== ru) return ru > lu ? remote : local;const lp = PRIORITY_VALUES[local.priority] || 0;const rp = PRIORITY_VALUES[remote.priority] || 0;if (lp !== rp) return rp > lp ? remote : local;@@ -139,7 +162,11 @@ function contentSignature(task) {const md = (task.metadata && typeof task.metadata === 'object') ? task.metadata : {};const nonClaim = {};for (const key of Object.keys(md).sort()) {- if (CLAIM_METADATA_KEYS.includes(key)) continue;+ // Exclude claim metadata (resolved separately by lease) AND the edit stamp+ // (it's the LWW key consumed in pickContentBase before we ever reach the+ // signature — including it here would just re-introduce a timestamp into the+ // "content" comparison the signature is meant to isolate).+ if (CLAIM_METADATA_KEYS.includes(key) || key === EDIT_STAMP_KEY) continue;nonClaim[key] = md[key];}return JSON.stringify([diff --git a/server/services/cosTaskMerge.test.js b/server/services/cosTaskMerge.test.jsindex cf166b7bb2..7a25bb901e 100644--- a/server/services/cosTaskMerge.test.js+++ b/server/services/cosTaskMerge.test.js@@ -160,6 +160,49 @@ describe('mergeTaskLists', () => {expect(fromA.metadata.context).toBe(fromB.metadata.context);});+ it('newest-edit-wins: larger updatedAt wins a same-status tie, regardless of initiator', () => {+ // Same pending status; the fresher edit (larger updatedAt) is authoritative+ // even though it carries the LOWER priority — the #1714 upgrade over the+ // pure-deterministic tiebreak, which would have preferred the stale HIGH.+ const fresh = task('task-1', 'pending', { priority: 'LOW', priorityValue: 1, metadata: { updatedAt: future(5000) } });+ const stale = task('task-1', 'pending', { priority: 'HIGH', priorityValue: 3, metadata: { updatedAt: past(5000) } });+ const [fromFresh] = mergeTaskLists([fresh], [stale], { now: NOW });+ const [fromStale] = mergeTaskLists([stale], [fresh], { now: NOW });+ expect(fromFresh.priority).toBe('LOW');+ expect(fromStale.priority).toBe('LOW');+ expect(fromFresh.metadata.updatedAt).toBe(fresh.metadata.updatedAt);+ });++ it('treats an absent updatedAt as oldest, so a stamped edit beats an un-stamped (legacy) copy', () => {+ const stamped = task('task-1', 'pending', { description: 'edited on a new peer', metadata: { updatedAt: past(1000) } });+ const legacy = task('task-1', 'pending', { description: 'untouched on an old peer' });+ const [fromStamped] = mergeTaskLists([stamped], [legacy], { now: NOW });+ const [fromLegacy] = mergeTaskLists([legacy], [stamped], { now: NOW });+ expect(fromStamped.description).toBe('edited on a new peer');+ expect(fromLegacy.description).toBe('edited on a new peer');+ });++ it('falls back to the deterministic comparator when both stamps tie (or are absent)', () => {+ // Equal updatedAt on both sides → newest-wins can't decide → priority breaks it.+ const sameStamp = future(0);+ const a = [task('task-1', 'pending', { priority: 'HIGH', priorityValue: 3, metadata: { updatedAt: sameStamp } })];+ const b = [task('task-1', 'pending', { priority: 'MEDIUM', priorityValue: 2, metadata: { updatedAt: sameStamp } })];+ const [fromA] = mergeTaskLists(a, b, { now: NOW });+ const [fromB] = mergeTaskLists(b, a, { now: NOW });+ expect(fromA.priority).toBe('HIGH');+ expect(fromB.priority).toBe('HIGH');+ });++ it('does not let updatedAt override a lifecycle status advance (rank still wins first)', () => {+ // A stale-stamped completed task still beats a freshly-stamped in_progress one:+ // status rank is checked before updatedAt, so completion always converges.+ const completedStale = task('task-1', 'completed', { metadata: { updatedAt: past(10_000) } });+ const inProgressFresh = task('task-1', 'in_progress', { metadata: { updatedAt: future(10_000), ...liveClaim('instance-A') } });+ const [merged] = mergeTaskLists([inProgressFresh], [completedStale], { now: NOW });+ expect(merged.status).toBe('completed');+ expect(merged.metadata.claimedBy).toBeUndefined(); // terminal → claim dropped+ });+it('treats metadata with different key order as identical (no spurious winner flip)', () => {const a = [task('task-1', 'pending', { metadata: { app: 'X', context: 'Y' } })];const b = [task('task-1', 'pending', { metadata: { context: 'Y', app: 'X' } })];diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex bba4392be3..8c191b67e8 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -34,6 +34,34 @@ export const PRIORITY_VALUES = {'LOW': 1};+const CLAIM_KEY_SET = new Set(CLAIM_METADATA_KEYS);++/**+ * Does an `updateTask` patch change a task's EDITABLE CONTENT (vs only its+ * claim/lease metadata)? Used to decide whether to bump the `updatedAt` LWW stamp+ * (#1714). A claim-only write — most importantly the periodic lease-renewal+ * heartbeat (`buildRenewal`, which passes only claim keys and no status) — must+ * NOT bump the stamp: a heartbeat is not a content edit, and letting it advance+ * `updatedAt` would make a lease-renewing peer spuriously win same-status content+ * ties over the other peer's genuine edit. Status transitions, priority/description+ * changes, legacy `context`/`app`/… fields, and any non-claim metadata key all+ * count as content edits.+ */+function isContentEdit(updates) {+ if (!updates || typeof updates !== 'object') return false;+ if (updates.status !== undefined) return true;+ if (updates.description !== undefined) return true;+ if (updates.priority !== undefined) return true;+ if (updates.context !== undefined || updates.model !== undefined+ || updates.provider !== undefined || updates.app !== undefined) return true;+ if (updates.metadata && typeof updates.metadata === 'object') {+ for (const key of Object.keys(updates.metadata)) {+ if (!CLAIM_KEY_SET.has(key)) return true;+ }+ }+ return false;+}+/*** Get user tasks from TASKS.md*/@@ -114,7 +142,7 @@ export async function getTaskById(taskId) {* submitted task starts instantly instead of waiting for the next evaluation* interval.*/-export async function addTask(taskData, taskType = 'user', { raw = false, ignoreTaskId = null } = {}) {+export async function addTask(taskData, taskType = 'user', { raw = false, ignoreTaskId = null, now = Date.now() } = {}) {return withStateLock(async () => {const state = await loadState();const filePath = taskType === 'user'@@ -197,6 +225,13 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignoreif (taskData.jiraTicketUrl) metadata.jiraTicketUrl = taskData.jiraTicketUrl;if (taskData.screenshots?.length > 0) metadata.screenshots = taskData.screenshots;if (taskData.attachments?.length > 0) metadata.attachments = taskData.attachments;+ // Content-edit timestamp for cross-peer newest-edit-wins LWW (#1714). Stamped+ // at creation so a freshly-added task always carries a stamp; the merge treats+ // an absent stamp as oldest, so this also keeps a stamped task from losing a+ // same-status tie to a legacy peer's un-stamped copy. `now` is injectable so+ // the markdown output stays deterministic under test. Raw tasks (pre-built by+ // the caller) keep whatever stamp they arrive with.+ metadata.updatedAt = new Date(now).toISOString();// Create the new tasknewTask = {@@ -236,7 +271,7 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore/*** Update an existing task*/-export async function updateTask(taskId, updates, taskType = 'user') {+export async function updateTask(taskId, updates, taskType = 'user', { now = Date.now() } = {}) {return withStateLock(async () => {const state = await loadState();const filePath = taskType === 'user'@@ -288,6 +323,14 @@ export async function updateTask(taskId, updates, taskType = 'user') {}}+ // Bump the content-edit stamp (#1714) on a genuine content change so the peer's+ // claim-aware merge can resolve a same-status edit by newest-edit-wins. Skipped+ // for claim-only writes (lease-renewal heartbeats) — see isContentEdit. `now` is+ // injectable for deterministic test output.+ if (isContentEdit(updates)) {+ updatedMetadata.updatedAt = new Date(now).toISOString();+ }+// Clean undefined values from metadataObject.keys(updatedMetadata).forEach(key => {if (updatedMetadata[key] === undefined) delete updatedMetadata[key];diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex 557f2b4b62..248d12b7ef 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -211,6 +211,12 @@ describe('cosTaskStore.addTask', () => {const { tasks } = await getUserTasks();expect(tasks[0].description).toBe('second');});++ it('stamps a content-edit timestamp (updatedAt) from the injectable clock (#1714)', async () => {+ const NOW = Date.parse('2026-06-25T12:00:00.000Z');+ const created = await addTask({ description: 'stamped', id: 'task-stamp' }, 'user', { now: NOW });+ expect(created.metadata.updatedAt).toBe(new Date(NOW).toISOString());+ });});describe('cosTaskStore.updateTask', () => {@@ -260,6 +266,33 @@ describe('cosTaskStore.updateTask', () => {expect(renewed.metadata.leaseExpiresAt).toBe('2026-01-01T01:00:00.000Z');});+ it('bumps updatedAt on a content edit from the injectable clock (#1714)', async () => {+ const T0 = Date.parse('2026-06-25T00:00:00.000Z');+ const T1 = Date.parse('2026-06-25T06:00:00.000Z');+ await addTask({ description: 'edit me', id: 'task-edit' }, 'user', { now: T0 });+ const updated = await updateTask('task-edit', { priority: 'HIGH' }, 'user', { now: T1 });+ expect(updated.metadata.updatedAt).toBe(new Date(T1).toISOString());+ });++ it('does NOT bump updatedAt on a claim-only lease renewal (heartbeat) (#1714)', async () => {+ const T0 = Date.parse('2026-06-25T00:00:00.000Z');+ const T1 = Date.parse('2026-06-25T06:00:00.000Z');+ const T2 = Date.parse('2026-06-25T12:00:00.000Z');+ await addTask({ description: 'beat', id: 'task-beat' }, 'user', { now: T0 });+ // Claiming the task is a content edit (status change) → stamp advances to T1.+ await updateTask('task-beat', {+ status: 'in_progress',+ metadata: { claimedBy: 'a', claimedAt: '2026-01-01T00:00:00.000Z', leaseExpiresAt: '2026-01-01T00:30:00.000Z' }+ }, 'user', { now: T1 });+ // A pure heartbeat (claim-only metadata, no status) must NOT advance the stamp,+ // or a lease-renewing peer would spuriously win same-status content ties.+ const renewed = await updateTask('task-beat', {+ metadata: { claimedBy: 'a', claimedAt: '2026-01-01T00:00:00.000Z', leaseExpiresAt: '2026-01-01T01:00:00.000Z' }+ }, 'user', { now: T2 });+ expect(renewed.metadata.leaseExpiresAt).toBe('2026-01-01T01:00:00.000Z');+ expect(renewed.metadata.updatedAt).toBe(new Date(T1).toISOString());+ });+it('returns an error object when the file is missing', async () => {const result = await updateTask('task-x', { status: 'completed' }, 'user');expect(result.error).toBe('Task file not found');