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
refactor([issue-1714]): dedupe timestamp parse, DRY legacy fields, cover approveTask in LWW stamp
[._.]/ Adam Eivy17ee41efec6d
diff --git a/server/services/cosTaskClaim.js b/server/services/cosTaskClaim.jsindex 03bf882174..1650018d36 100644--- a/server/services/cosTaskClaim.js+++ b/server/services/cosTaskClaim.js@@ -33,17 +33,25 @@ export const LEASE_DURATION_MS = 30 * 60 * 1000; // 30 minutesexport const CLAIM_METADATA_KEYS = Object.freeze(['claimedBy', 'claimedAt', 'leaseExpiresAt']);/**- * Parse `leaseExpiresAt` (an ISO string after the markdown round-trip, or a- * Date/number in-memory) to epoch ms, or null when absent/unparseable. A null- * here means "no live lease" — never "lease in the past".+ * Parse a timestamp (an ISO string after the markdown round-trip, or an epoch+ * number in-memory) to epoch ms, or null when absent/unparseable. Shared by the+ * lease-expiry reader here and the lease/edit-stamp readers in cosTaskMerge so+ * the three callers don't each re-implement the same absent/NaN guard.*/-function leaseExpiryMs(metadata) {- const raw = metadata?.leaseExpiresAt;+export function parseTimestampMs(raw) {if (raw === undefined || raw === null || raw === '') return null;const ms = typeof raw === 'number' ? raw : Date.parse(raw);return Number.isFinite(ms) ? ms : null;}+/**+ * Parse `leaseExpiresAt` to epoch ms, or null when absent/unparseable. A null+ * here means "no live lease" — never "lease in the past".+ */+function leaseExpiryMs(metadata) {+ return parseTimestampMs(metadata?.leaseExpiresAt);+}+/*** Is there a live (unexpired) lease on this task right now?*/diff --git a/server/services/cosTaskMerge.js b/server/services/cosTaskMerge.jsindex 9f72a90d5d..41e5254efe 100644--- a/server/services/cosTaskMerge.js+++ b/server/services/cosTaskMerge.js@@ -42,7 +42,7 @@* freely re-claimable.*/-import { isLeaseLive, getClaimOwner, CLAIM_METADATA_KEYS } from './cosTaskClaim.js';+import { isLeaseLive, getClaimOwner, CLAIM_METADATA_KEYS, parseTimestampMs } from './cosTaskClaim.js';// Import from taskParser (the lowest task module) rather than cosTaskStore: the// store imports THIS module for mergeTaskLists, so pulling its PRIORITY_VALUES// here would form a circular import. taskParser has no cos-module deps.@@ -67,18 +67,11 @@ const EDIT_STAMP_KEY = 'updatedAt';// 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 ms = parseTimestampMs(task?.metadata?.[EDIT_STAMP_KEY]);+ return ms === null ? -Infinity : ms;};-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;-};+const leaseMs = (metadata) => parseTimestampMs(metadata?.leaseExpiresAt);/*** Pick the authoritative claim metadata for a task present on both sides, ordiff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex 8c191b67e8..af2cd4da9f 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -36,6 +36,11 @@ export const PRIORITY_VALUES = {const CLAIM_KEY_SET = new Set(CLAIM_METADATA_KEYS);+// Legacy fields an `updateTask` patch may carry directly (vs nested under+// `metadata`); they're normalized into `metadata` on write. Listed once so the+// content-edit detector and the normalizer below can't drift apart.+const LEGACY_DIRECT_FIELDS = ['context', 'model', 'provider', 'app'];+/*** 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@@ -44,16 +49,16 @@ const CLAIM_KEY_SET = new Set(CLAIM_METADATA_KEYS);* 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.+ * changes, approval flags, 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.approvalRequired !== undefined || updates.autoApproved !== undefined) return true;+ if (LEGACY_DIRECT_FIELDS.some(f => updates[f] !== 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;@@ -298,10 +303,9 @@ export async function updateTask(taskId, updates, taskType = 'user', { now = Dat...(updates.metadata || {})};// Handle legacy fields that may be passed directly in updates- if (updates.context !== undefined) updatedMetadata.context = updates.context || undefined;- if (updates.model !== undefined) updatedMetadata.model = updates.model || undefined;- if (updates.provider !== undefined) updatedMetadata.provider = updates.provider || undefined;- if (updates.app !== undefined) updatedMetadata.app = updates.app || undefined;+ for (const f of LEGACY_DIRECT_FIELDS) {+ if (updates[f] !== undefined) updatedMetadata[f] = updates[f] || undefined;+ }// Clear blocked/failure metadata when transitioning out of blocked statusif (updates.status && updates.status !== 'blocked' && tasks[taskIndex].status === 'blocked') {@@ -490,7 +494,7 @@ export async function reorderTasks(taskIds) {* fires `dequeueNextTask` off that so the newly approved task can spawn* immediately.*/-export async function approveTask(taskId) {+export async function approveTask(taskId, { now = Date.now() } = {}) {return withStateLock(async () => {const state = await loadState();const filePath = join(ROOT_DIR, state.config.cosTasksFile);@@ -511,11 +515,15 @@ export async function approveTask(taskId) {return { error: 'Task does not require approval' };}- // Update approval flags+ // Update approval flags. Approval is editable content (the merge's+ // contentSignature counts the approval flags), so bump the `updatedAt` LWW+ // stamp (#1714) too — otherwise an approval on one peer would lose a same-status+ // tie to a stale edit on the other instead of winning as the newest edit.tasks[taskIndex] = {...tasks[taskIndex],approvalRequired: false,- autoApproved: true+ autoApproved: true,+ metadata: { ...tasks[taskIndex].metadata, updatedAt: new Date(now).toISOString() }};// Write back to filediff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex 248d12b7ef..1756af9b40 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -342,6 +342,14 @@ describe('cosTaskStore.approveTask', () => {expect(mock.events.some(e => e.name === 'tasks:changed' && e.payload.action === 'approved')).toBe(true);});+ it('bumps the updatedAt LWW stamp on approval (approval is content) (#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: 'need approve', id: 'sys-ap2', approvalRequired: true }, 'internal', { now: T0 });+ const approved = await approveTask('sys-ap2', { now: T1 });+ expect(approved.metadata.updatedAt).toBe(new Date(T1).toISOString());+ });+it('rejects a task that does not require approval', async () => {await addTask({ description: 'auto', id: 'sys-auto', approvalRequired: false }, 'internal');expect((await approveTask('sys-auto')).error).toBe('Task does not require approval');