# 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>
181 lines
7.6 KiB
TypeScript
181 lines
7.6 KiB
TypeScript
import { build } from "esbuild";
|
|
import { cp, mkdir, rm, stat } from "node:fs/promises";
|
|
import { join } from "node:path";
|
|
import { buildCore, buildDashboard, buildDashboardClient, buildEngine, desktopDeployDir, packageRoot, stageDesktopDeploy, workspaceRoot } from "./workspace-tools";
|
|
const dashboardRoot = join(workspaceRoot, "packages", "dashboard");
|
|
const dashboardClientDir = join(dashboardRoot, "dist", "client");
|
|
const dashboardRegistryManifestSource = join(dashboardRoot, "src", "registry-manifest.json");
|
|
const dashboardRegistryManifestDist = join(dashboardRoot, "dist", "registry-manifest.json");
|
|
const desktopDistDir = join(packageRoot, "dist");
|
|
const desktopClientDistDir = join(desktopDistDir, "client");
|
|
// FNXC:DesktopBuild 2026-06-25-09:45:
|
|
// Every workspace @fusion/* package and native (.node) module must stay external
|
|
// to the Electron main/preload bundles — they resolve from node_modules at runtime.
|
|
// @fusion/engine was missing here, so esbuild followed local-runtime.ts's dynamic
|
|
// `import("@fusion/engine")` and tried to bundle engine's transitive node-pty
|
|
// (@homebridge/node-pty-prebuilt-multiarch) native binaries, failing with
|
|
// "No loader is configured for .node files" and breaking every desktop release build.
|
|
/*
|
|
* FNXC:SqliteFinalRemoval 2026-06-24-16:10:
|
|
* Removed better-sqlite3 from externals — the data path no longer uses
|
|
* better-sqlite3 (SQLite is accessed via node:sqlite/bun:sqlite in the adapter,
|
|
* and PostgreSQL is the production backend).
|
|
*/
|
|
const sharedExternals = [
|
|
"electron",
|
|
"@fusion/core",
|
|
"@fusion/dashboard",
|
|
"@fusion/engine",
|
|
];
|
|
const mainExternals = sharedExternals;
|
|
const preloadExternals = sharedExternals;
|
|
|
|
async function ensureDashboardBuild(): Promise<void> {
|
|
// FNXC:DesktopBuild 2026-07-01-11:35:
|
|
// Windows release packaging invokes only `@fusion/desktop build` before electron-builder.
|
|
// Build the dashboard server dist and copy registry-manifest.json here so the packaged
|
|
// embedded runtime never depends on a separate `@fusion/dashboard build` workflow step.
|
|
console.log("[desktop:build] Building dashboard server runtime...");
|
|
await buildDashboard();
|
|
await cp(dashboardRegistryManifestSource, dashboardRegistryManifestDist);
|
|
|
|
console.log("[desktop:build] Building dashboard client for file:// desktop loading...");
|
|
await buildDashboardClient();
|
|
|
|
try {
|
|
await stat(dashboardClientDir);
|
|
} catch {
|
|
throw new Error(`Dashboard client assets not found: ${dashboardClientDir}`);
|
|
}
|
|
|
|
try {
|
|
await stat(dashboardRegistryManifestDist);
|
|
} catch {
|
|
throw new Error(`Dashboard registry manifest not found: ${dashboardRegistryManifestDist}`);
|
|
}
|
|
}
|
|
|
|
async function buildElectronEntrypoints(): Promise<void> {
|
|
console.log("[desktop:build] Bundling Electron main/preload with esbuild...");
|
|
|
|
await Promise.all([
|
|
build({
|
|
entryPoints: [join(packageRoot, "src", "main.ts")],
|
|
outfile: join(desktopDistDir, "main.js"),
|
|
bundle: true,
|
|
format: "esm",
|
|
platform: "node",
|
|
target: "node22",
|
|
sourcemap: true,
|
|
// FNXC:DesktopBuild 2026-07-01-07:31:
|
|
// Windows Electron main output is ESM, but electron-updater loads CJS deps
|
|
// such as fs-extra/graceful-fs that dynamically require built-ins. Keep all
|
|
// npm packages external so Node/Electron evaluates those CJS modules natively
|
|
// instead of esbuild emitting a __require("fs") trap in dist/main.js.
|
|
packages: "external",
|
|
external: mainExternals,
|
|
logLevel: "info",
|
|
}),
|
|
build({
|
|
entryPoints: [join(packageRoot, "src", "preload.ts")],
|
|
outfile: join(desktopDistDir, "preload.js"),
|
|
bundle: true,
|
|
// Preload scripts must be CommonJS — Electron loads them via the
|
|
// sandboxed Node context, not as ESM. With format:"esm" the
|
|
// contextBridge calls silently no-op and window.fusionShell /
|
|
// window.fusionAPI stay undefined, which made the dashboard fall
|
|
// through to "can't reach the Fusion backend" and the launch gate
|
|
// always bypass.
|
|
format: "cjs",
|
|
platform: "node",
|
|
target: "node22",
|
|
sourcemap: true,
|
|
packages: "external",
|
|
external: preloadExternals,
|
|
logLevel: "info",
|
|
}),
|
|
]);
|
|
}
|
|
|
|
async function copyDashboardClient(): Promise<void> {
|
|
console.log("[desktop:build] Copying dashboard client into desktop dist/client...");
|
|
await cp(dashboardClientDir, desktopClientDistDir, { recursive: true });
|
|
}
|
|
|
|
// FNXC:DesktopBuild 2026-07-01-19:45:
|
|
// Compile the workspace @fusion/* packages the embedded "Local" runtime imports
|
|
// at runtime (@fusion/core, @fusion/engine) so `@fusion/desktop build` alone
|
|
// produces a complete, packageable tree — no separate root `pnpm build` required.
|
|
// engine/dist and core/dist are tsc-emitted + gitignored; without this the
|
|
// desktop-windows.yml workflow_dispatch build shipped an empty engine/dist and
|
|
// the packaged app crashed on Local mode with ERR_MODULE_NOT_FOUND for
|
|
// ...app.asar/node_modules/@fusion/engine. Core must build before engine
|
|
// (engine depends on @fusion/core). Dashboard + its runtime plugins + plugin-sdk
|
|
// are already built by ensureDashboardBuild().
|
|
async function ensureEmbeddedRuntimeBuild(): Promise<void> {
|
|
console.log("[desktop:build] Building @fusion/core and @fusion/engine runtime dist...");
|
|
await buildCore();
|
|
await buildEngine();
|
|
}
|
|
|
|
// FNXC:DesktopPackaging 2026-07-03-15:25:
|
|
// Guard the packaged Electron closure so a missing preload/main/renderer asset
|
|
// fails the build instead of shipping and crashing on a user's machine (field
|
|
// report Issue 5: preload was missing from the packaged unpacked layout).
|
|
// `preload.js` in particular is silent when absent — the contextBridge never
|
|
// installs window.fusionShell/fusionAPI and the app dead-ends on "can't reach
|
|
// the Fusion backend". Assert the required files in BOTH the source `dist/`
|
|
// (esbuild output) and the staged `deploy/dist/` (what electron-builder packs
|
|
// into app.asar), since only the latter reflects what ships.
|
|
const REQUIRED_PACKAGED_ASSETS = ["main.js", "preload.js", join("client", "index.html")];
|
|
|
|
async function verifyPackagedArtifacts(): Promise<void> {
|
|
console.log("[desktop:build] Verifying required packaged assets are present...");
|
|
const stagedDistDir = join(desktopDeployDir, "dist");
|
|
const roots: Array<{ label: string; dir: string }> = [
|
|
{ label: "dist", dir: desktopDistDir },
|
|
{ label: "deploy/dist", dir: stagedDistDir },
|
|
];
|
|
const missing: string[] = [];
|
|
for (const { label, dir } of roots) {
|
|
for (const asset of REQUIRED_PACKAGED_ASSETS) {
|
|
try {
|
|
await stat(join(dir, asset));
|
|
} catch {
|
|
missing.push(`${label}/${asset}`);
|
|
}
|
|
}
|
|
}
|
|
if (missing.length > 0) {
|
|
throw new Error(
|
|
`Desktop packaging is missing required Electron assets: ${missing.join(", ")}. ` +
|
|
`Refusing to ship an incomplete app.asar.`,
|
|
);
|
|
}
|
|
}
|
|
|
|
async function main(): Promise<void> {
|
|
await rm(desktopDistDir, { recursive: true, force: true });
|
|
await mkdir(desktopDistDir, { recursive: true });
|
|
|
|
await ensureEmbeddedRuntimeBuild();
|
|
await ensureDashboardBuild();
|
|
await buildElectronEntrypoints();
|
|
await copyDashboardClient();
|
|
|
|
// FNXC:DesktopPackaging 2026-07-01-21:15:
|
|
// Stage the complete flat production closure last (after all dist exists) so
|
|
// electron-builder can package it via --projectDir instead of its pnpm collector,
|
|
// which drops `deduped` subtrees and left the embedded runtime missing deps.
|
|
await stageDesktopDeploy();
|
|
|
|
await verifyPackagedArtifacts();
|
|
|
|
console.log("[desktop:build] Desktop build complete");
|
|
}
|
|
|
|
void main().catch((error) => {
|
|
console.error("[desktop:build] Build failed", error);
|
|
process.exitCode = 1;
|
|
});
|