Files
fusion/packages/dashboard/app/hooks/useNodeSettingsSync.ts
gsxdsm c15c78feeb feat: migrate storage from SQLite to PostgreSQL (#1793)
# Migrate storage from SQLite to PostgreSQL — full dashboard cutover

Migrates Fusion's storage layer to the embedded PostgreSQL
`AsyncDataLayer` (the default backend) and **completes the
satellite-store + feature cutover** so every dashboard and Command
Center surface works in PG mode.

## Status — every surface works in embedded-PG mode

Verified live against a running embedded-Postgres dashboard (all
**200**, zero 5xx) and gate-tested (**23 files / 99 tests** on embedded
PG, plus engine-core 294 and ci-shape 63 in the blocking merge gate;
core/engine/cli/dashboard typecheck clean).

| Area | Surfaces | State |
|---|---|---|
| Satellite stores | workflows, todos, insights, research, missions,
goals, mailbox | ✅ |
| Views | artifacts, documents, evals | ✅ |
| Command Center | activity, productivity, team, tokens, tools,
**workflows**, **github**, **signals**, **plugin-activations**, **live**
(all 10) | ✅ |
| Run execution | insight generation, research run execution | ✅
(store-path; AI step needs a provider) |
| Live updates | SSE push for mission/research/insight events | ✅ |
| Workflow editing | create / update / delete / select (+ id counter) |
✅ |
| Engine | mission autopilot, incident-signal ingestion, regression
storm-guard, agent wake-on-message | ✅ |
| Core | tasks, agents, secrets, automations, memory, chat, usage, PRs,
git | ✅ |

## Approach

Each satellite store gets an `Async<Store>` wrapper exposing the sync
store's method names over the existing `async-*-store.ts` helpers;
`get<Store>Store()` returns a `Sync | Async` union; consumers `await`
(harmless on sync), and engine/CLI paths that can't convert use
`instanceof Sync` graceful fallback. Analytics aggregators branch on
`"ping" in dbOrLayer` to run schema-qualified raw SQL over `project.*`
(snake_case) in PG. Executors/orchestrators/autopilot are
await-converted to drive the union store; the async store wrappers
extend `EventEmitter` so SSE live-push fires in both backends.

Not-yet-ported capabilities degrade gracefully (never 500) and are
individually called out in commits.

## Sync with main

The branch is kept continuously merged with `main` (currently through
FN-7845, 2026-07-12); the earlier "final rebase deferred" note no longer
applies. Use **Create a merge commit** (or squash) to land it — GitHub's
rebase-merge cannot replay a merge-maintained branch.

## Residual Review Findings

Multi-agent code review of the PostgreSQL satellite-store ports (U1–U5)
applied 3 safe fixes (see `fix(review): apply autofix feedback`). The
following are **real but gated** — recorded here as follow-up work
rather than auto-applied. All are SQLite→PostgreSQL
**concurrency/atomicity regressions**: the sync stores were immune only
by SQLite's single-writer, single-threaded-handler execution; the async
ports open multi-await read-modify-write windows. **Reachability is low
today** because the execution engines that generate concurrent same-run
mutations (insight run executor, research orchestrator/dispatcher) are
`instanceof`-gated to sync mode in PG. No process-crash class survived
(all engine fallbacks correctly guard the sync store).

- **[P1] Research `appendResearchEvent` dual-write is non-atomic**
(`packages/core/src/async-research-store.ts`, corroborated: adversarial
+ reliability). The `research_run_events` insert (own transaction) and
the `run.events` jsonb update are separate writes — a crash between
them, or two concurrent appends, splits the table count from the jsonb
array. **Fix:** perform the seq-insert and the jsonb update in one
`layer.transactionImmediate`.
- **[P1] Research run terminal-reversion via stale full-row persist**
(`async-research-store.ts` `persistResearchRun`/`updateResearchStatus`).
Concurrent `PATCH /runs/:id/status` + `POST /runs/:id/events` can revert
a terminal run to `running` by overwriting the whole row, bypassing the
transition guard. **Fix:** scoped column `UPDATE`s with a `WHERE status
…` guard, or optimistic version column.
- **[P2] `updateResearchRun`/`updateInsightRun` read-then-write TOCTOU**
— concurrent PATCHes last-writer-wins on the lifecycle merge. **Fix:**
`SELECT … FOR UPDATE` / enclosing transaction.
- **[P2] `upsertRun`/`createRunOrThrowConflict` check-then-create race**
(`async-insight-store.ts`) — two callers can each create an "active"
run. **Fix:** partial unique index on `(projectId, trigger) WHERE status
IN ('pending','running')`.
- **[P3] `createResearchRetryRun` return-value divergence** — sync
returns the pre-update `queued` snapshot; async returns the reloaded
`retry_waiting` run (persisted state is identical). Pick one side for
cross-backend parity.
- **[P2/perf] Mission `getMissionWithHierarchy`/`getMissionHealth` N+1
fan-out** — O(milestones×slices) sequential round-trips hold one pool
slot per request; can starve the pool for large hierarchies. **Fix:**
batched/joined reads.
- **Testing gaps:** no PG-mode concurrency tests (interleaved
status/event mutations), no sync↔async parity assertion for the
lifecycle-error codes, and no mission status/health rollup parity test
vs the sync `MissionStore`.

~~Out of scope (deferred): AI run *execution* (insight/research) +
mission autopilot + live SSE mission events remain sync-gated/degraded
in PG mode.~~ **Since ported** — insight/research run execution, mission
autopilot, and SSE live push all run on the async layer now, which also
makes the concurrency findings above genuinely reachable; they remain
open follow-ups.







---

## Update — 2026-07-12: production-readiness hardening & live acceptance

Everything below landed on this branch since the description above was
written:

**Production blockers from review — fixed**
- `recoverStaleTransitionPending` ported to the async layer (backend
moves write + clear the crash-safe marker; startup/maintenance sweeps no
longer throw).
- Lost-update class fixed: `atomicWriteTaskJson`/`WithAudit` write
changed columns only (full-row upserts silently resurrected stale fields
across concurrent store instances — the "task stuck unplanned forever"
bug).
- First-boot **auto-migration**: booting the PG backend over a project
with a legacy `fusion.db` migrates it automatically (loud failure,
SQLite kept as backup), and the dashboard shows a one-time **"your data
was migrated" banner** with the backup paths and a Need-help Discord
link.
- `pg_dump`/`pg_restore` discovered from common install locations for
embedded-mode backups.
- The PG suite is part of the blocking merge gate (`test:pg-gate`).

**Multi-project isolation (PR #2007, merged into this branch)**
- `project_id` partition key on tasks / archived tasks / config,
`taskProjectScope` threaded through every scan/claim/count, per-project
config rows, layer bound to the project at startup.
- Review P1 follow-up: the shared cold-storage `archive.archived_tasks`
table is also partitioned and all archived-board reads/counts/searches
are scoped.
- Schema drift self-heal generalized to schema-qualified columns so
existing databases upgrade in place.

**Other changes**
- Node settings sync **removed** in PG mode (409
`settings-sync-disabled-postgres`) — nodes share state by connecting to
the same database; auth sync kept (per-machine file).
- Perf (review findings): `listTasks` pushes column filter + ORDER BY +
LIMIT/OFFSET into SQL; `getConversation` capped to the most recent 200
messages.
- Fixed a false "operator action required" pause-abort log fired on
every successfully auto-merged task.

**Live acceptance — PASSED (2026-07-12)**
A sandboxed instance (isolated HOME, embedded PG, real Opus executor)
ran a task through the complete cycle: create → triage (AI spec) →
execute → in-review → AI squash-merge landed on the project's `main` →
done. A write+read sweep of every data surface (settings, comments,
documents, attachments + artifact bridge + artifact edit, chat with real
generation, goals, missions, agent mail, secrets, workflows, memory, CC
analytics) was green on embedded PG.

**Known remaining work**
- The per-project `config` PK re-key has no upgrade path for
pre-isolation embedded-PG databases (needs a real `DROP
CONSTRAINT`/re-key migration; fresh databases are fine).
- `pg_dump`/`pg_restore` binaries are not yet bundled in release
artifacts (PATH/common-location discovery only).
- The satellite-store concurrency findings listed above.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Phil Larson <hello@phillarson.xyz>
Co-authored-by: fusion-merge <fusion-merge@local>
2026-07-13 19:07:58 -07:00

416 lines
13 KiB
TypeScript

import { useState, useEffect, useCallback, useRef } from "react";
import { useTranslation } from "react-i18next";
import {
fetchNodeSettingsSyncStatus,
pushNodeSettings,
pullNodeSettings,
syncNodeAuth,
type NodeSettingsSyncStatus,
type NodeSettingsSyncResult,
type NodeAuthSyncResult,
} from "../api-node";
// ── Sync State Utilities ───────────────────────────────────────────────────────
/** Derived sync state computed from raw sync status data */
export type SyncState = "synced" | "pending" | "diff" | "error" | "never-synced";
/** Computed sync status with derived state for UI consumption */
export interface ComputedNodeSyncStatus {
syncState: SyncState;
lastSyncAt: string | null;
diffCount: number;
}
/**
* Compute the derived sync state from raw NodeSettingsSyncStatus data.
* - never-synced: lastSyncAt is null (never been synced)
* - error: remote node is unreachable
* - diff: there are differences between local and remote
* - synced: no differences and lastSyncAt is set
* - pending: lastSyncAt is set, remote is reachable, but we don't have diff data yet
*/
export function computeSyncState(status: NodeSettingsSyncStatus): ComputedNodeSyncStatus {
const { lastSyncAt, remoteReachable, diff } = status;
const workflowDiffCount = Object.values(diff.workflowSettings)
.reduce((total, keys) => total + keys.length, 0);
const diffCount = diff.global.length + diff.project.length + workflowDiffCount;
if (lastSyncAt === null) {
return { syncState: "never-synced", lastSyncAt, diffCount: 0 };
}
if (!remoteReachable) {
return { syncState: "error", lastSyncAt, diffCount };
}
if (diffCount > 0) {
return { syncState: "diff", lastSyncAt, diffCount };
}
return { syncState: "synced", lastSyncAt, diffCount: 0 };
}
/**
* Format a relative time string from an ISO timestamp.
* Returns "Synced Xm ago", "Synced Xh ago", "Synced Xd ago", or "Never synced".
*
* FNXC:RelativeTime 2026-06-17-20:48:
* FN-6618 keeps node settings sync timestamps local because the user-facing contract is the prefixed `Synced … ago` / `Never synced` state copy, not a generic relative-time label.
*/
export function formatRelativeTime(isoTimestamp: string | null): string {
if (isoTimestamp === null) {
return "Never synced";
}
const date = new Date(isoTimestamp);
if (Number.isNaN(date.getTime())) {
return "Never synced";
}
const now = Date.now();
const diffMs = now - date.getTime();
const diffSec = Math.floor(diffMs / 1000);
const diffMin = Math.floor(diffSec / 60);
const diffHr = Math.floor(diffMin / 60);
const diffDay = Math.floor(diffHr / 24);
if (diffMin < 1) {
return "Synced just now";
}
if (diffMin < 60) {
return `Synced ${diffMin}m ago`;
}
if (diffHr < 24) {
return `Synced ${diffHr}h ago`;
}
return `Synced ${diffDay}d ago`;
}
/** Get the CSS color variable for a sync state */
export function getSyncStateColor(state: SyncState): string {
switch (state) {
case "synced":
return "var(--color-success)";
case "pending":
return "var(--color-warning)";
case "diff":
return "var(--color-warning)";
case "error":
return "var(--color-error)";
case "never-synced":
return "var(--text-muted)";
}
}
export interface UseNodeSettingsSyncResult {
/** Per-node sync status keyed by nodeId */
syncStatusMap: Record<string, NodeSettingsSyncStatus>;
/** Loading state — true ONLY during initial load, false during background polling */
loading: boolean;
/** Per-node loading states for push/pull/auth actions */
actionLoading: Record<string, boolean>;
/** Error if any */
error: string | null;
/** Manually refresh sync status for all tracked nodes */
refresh: () => Promise<void>;
/** Start tracking a node for sync status polling */
trackNode: (nodeId: string) => void;
/** Stop tracking a node */
untrackNode: (nodeId: string) => void;
/** Push local settings to a remote node */
pushSettings: (nodeId: string) => Promise<NodeSettingsSyncResult>;
/** Pull settings from a remote node */
pullSettings: (nodeId: string) => Promise<NodeSettingsSyncResult>;
/** Sync auth credentials with a remote node */
syncAuth: (nodeId: string) => Promise<NodeAuthSyncResult>;
/** Get auth sync state for a specific node */
getAuthSyncState: (nodeId: string) => "match" | "differs" | "not-synced" | undefined;
/** Get per-provider auth match details for a specific node */
getAuthProviders: (nodeId: string) => Record<string, "match" | "differs"> | undefined;
}
const POLL_INTERVAL_MS = 30_000; // 30 seconds
/**
* Hook for managing per-node settings synchronization state.
*
* Automatically polls sync status for all tracked nodes every 30 seconds.
* Stops polling when component unmounts.
*
* Loading behavior: `loading` is true only during the initial fetch.
* Background polling updates do NOT set `loading` to true, so the UI
* keeps previously loaded data visible during refreshes. This prevents
* skeleton flicker and scroll position resets during periodic updates (FN-1734).
*/
export function useNodeSettingsSync(): UseNodeSettingsSyncResult {
const { t } = useTranslation("app");
const [syncStatusMap, setSyncStatusMap] = useState<Record<string, NodeSettingsSyncStatus>>({});
const [loading, setLoading] = useState(false);
const [actionLoading, setActionLoading] = useState<Record<string, boolean>>({});
const [error, setError] = useState<string | null>(null);
// Track which nodes are being monitored
const trackedNodesRef = useRef<Set<string>>(new Set());
// Track if initial load is complete
const initialLoadCompleteRef = useRef(false);
// Abort controller for cancelling in-flight requests
const abortRef = useRef<AbortController | null>(null);
// Polling interval ref
const intervalRef = useRef<NodeJS.Timeout | null>(null);
/**
* Fetch sync status for a single node and update state.
* Does NOT set loading=true (called during polling and initial fetch).
*/
const fetchNodeStatus = useCallback(async (nodeId: string, _isInitial: boolean): Promise<void> => {
try {
const status = await fetchNodeSettingsSyncStatus(nodeId);
setSyncStatusMap((prev) => ({
...prev,
[nodeId]: status,
}));
setError(null);
} catch (err) {
/*
FNXC:PostgresCutover 2026-07-10:
Node settings sync is disabled on the PostgreSQL backend (nodes share the
database); the sync-status route answers 409 with
code "settings-sync-disabled-postgres". Treat that as a quiet steady
state: stop tracking the node so polling ceases, keep the status map
empty (no sync chips render), and surface no error banner. Explicit
push/pull clicks still show the server's explanatory 409 message.
*/
if ((err as { status?: number } | null)?.status === 409) {
trackedNodesRef.current.delete(nodeId);
return;
}
// Keep stale data visible during polling failures
console.error(`Failed to fetch sync status for node ${nodeId}:`, err);
setError(err instanceof Error ? err.message : t("nodeSync.error.failedToFetchStatus", "Failed to fetch sync status"));
}
}, [t]);
/**
* Refresh sync status for all tracked nodes.
* Sets loading=true only for initial fetch, not for background refreshes.
*/
const refresh = useCallback(async () => {
const trackedNodes = Array.from(trackedNodesRef.current);
if (trackedNodes.length === 0) return;
// Cancel any in-flight requests
if (abortRef.current) {
abortRef.current.abort();
}
abortRef.current = new AbortController();
const isInitial = !initialLoadCompleteRef.current;
if (isInitial) {
setLoading(true);
}
setError(null);
try {
// Fetch status for all tracked nodes concurrently
const results = await Promise.allSettled(
trackedNodes.map((nodeId) => fetchNodeStatus(nodeId, isInitial))
);
// Mark initial load complete
initialLoadCompleteRef.current = true;
// Check if any failed
const failures = results.filter((r) => r.status === "rejected");
if (failures.length > 0) {
setError(t("nodeSync.error.someRequestsFailed", "Some sync status requests failed"));
}
} catch (err) {
if (err instanceof Error && err.name === "AbortError") {
return;
}
setError(err instanceof Error ? err.message : t("nodeSync.error.failedToFetchStatus", "Failed to fetch sync status"));
initialLoadCompleteRef.current = true;
} finally {
setLoading(false);
}
}, [fetchNodeStatus, t]);
/**
* Start polling sync status for all tracked nodes.
*/
const startPolling = useCallback(() => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
intervalRef.current = setInterval(() => {
void refresh();
}, POLL_INTERVAL_MS);
}, [refresh]);
/**
* Stop polling.
*/
const stopPolling = useCallback(() => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
}, []);
// Initial fetch and polling setup
useEffect(() => {
void refresh();
startPolling();
return () => {
stopPolling();
if (abortRef.current) {
abortRef.current.abort();
}
};
}, [refresh, startPolling, stopPolling]);
/**
* Start tracking a node for sync status polling.
* Immediately fetches status for the newly tracked node.
*/
const trackNode = useCallback((nodeId: string) => {
if (trackedNodesRef.current.has(nodeId)) return;
trackedNodesRef.current.add(nodeId);
void fetchNodeStatus(nodeId, !initialLoadCompleteRef.current);
}, [fetchNodeStatus]);
/**
* Stop tracking a node.
* Removes its entry from syncStatusMap and stops polling for it.
*/
const untrackNode = useCallback((nodeId: string) => {
trackedNodesRef.current.delete(nodeId);
setSyncStatusMap((prev) => {
const next = { ...prev };
delete next[nodeId];
return next;
});
// If no more tracked nodes, stop polling
if (trackedNodesRef.current.size === 0) {
stopPolling();
}
}, [stopPolling]);
/**
* Push local settings to a remote node.
* Sets per-node actionLoading during the call, updates syncStatusMap on completion.
*/
const pushSettings = useCallback(async (nodeId: string): Promise<NodeSettingsSyncResult> => {
setActionLoading((prev) => ({ ...prev, [nodeId]: true }));
setError(null);
try {
const result = await pushNodeSettings(nodeId);
// Refresh sync status after push
void fetchNodeStatus(nodeId, false);
if (!result.success && result.error) {
setError(result.error);
}
return result;
} catch (err) {
const message = err instanceof Error ? err.message : t("nodeSync.error.pushFailed", "Push settings failed");
setError(message);
throw err;
} finally {
setActionLoading((prev) => {
const next = { ...prev };
delete next[nodeId];
return next;
});
}
}, [fetchNodeStatus, t]);
/**
* Pull settings from a remote node.
* Sets per-node actionLoading during the call, updates syncStatusMap on completion.
*/
const pullSettings = useCallback(async (nodeId: string): Promise<NodeSettingsSyncResult> => {
setActionLoading((prev) => ({ ...prev, [nodeId]: true }));
setError(null);
try {
const result = await pullNodeSettings(nodeId);
// Refresh sync status after pull
void fetchNodeStatus(nodeId, false);
if (!result.success && result.error) {
setError(result.error);
}
return result;
} catch (err) {
const message = err instanceof Error ? err.message : t("nodeSync.error.pullFailed", "Pull settings failed");
setError(message);
throw err;
} finally {
setActionLoading((prev) => {
const next = { ...prev };
delete next[nodeId];
return next;
});
}
}, [fetchNodeStatus, t]);
/**
* Sync auth credentials with a remote node.
* Sets per-node actionLoading during the call.
*/
const syncAuth = useCallback(async (nodeId: string): Promise<NodeAuthSyncResult> => {
setActionLoading((prev) => ({ ...prev, [nodeId]: true }));
setError(null);
try {
return await syncNodeAuth(nodeId);
} catch (err) {
const message = err instanceof Error ? err.message : t("nodeSync.error.authSyncFailed", "Auth sync failed");
setError(message);
throw err;
} finally {
setActionLoading((prev) => {
const next = { ...prev };
delete next[nodeId];
return next;
});
}
}, [t]);
/**
* Get auth sync state for a specific node.
*/
const getAuthSyncState = useCallback(
(nodeId: string): "match" | "differs" | "not-synced" | undefined => {
const status = syncStatusMap[nodeId];
return status?.authMatch;
},
[syncStatusMap],
);
/**
* Get per-provider auth match details for a specific node.
*/
const getAuthProviders = useCallback(
(nodeId: string): Record<string, "match" | "differs"> | undefined => {
const status = syncStatusMap[nodeId];
return status?.authDiff;
},
[syncStatusMap],
);
return {
syncStatusMap,
loading,
actionLoading,
error,
refresh,
trackNode,
untrackNode,
pushSettings,
pullSettings,
syncAuth,
getAuthSyncState,
getAuthProviders,
};
}