# 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>
279 lines
9.6 KiB
TypeScript
279 lines
9.6 KiB
TypeScript
/**
|
|
* FNXC:SqliteFinalRemoval 2026-06-26-09:30:
|
|
* SQLite Database class body DELETED (VAL-REMOVAL-005).
|
|
*
|
|
* The full ~5900-line SQLite `Database` class (schema SQL, 130 migrations,
|
|
* PRAGMA configuration, FTS5 virtual tables/triggers, VACUUM/WAL-checkpoint
|
|
* maintenance, integrity-check offload, schema-compat fingerprinting) was the
|
|
* legacy synchronous data layer. The runtime now uses PostgreSQL via the
|
|
* async `AsyncDataLayer` (Drizzle) for ALL production data access. The SQLite
|
|
* path was only reachable in non-backend mode (test fixtures / one-time
|
|
* migrator), and the migrator uses the low-level `DatabaseSync` from
|
|
* `sqlite-adapter.ts` directly — it never needed this class.
|
|
*
|
|
* This module now re-exports the pure JSON/schema utilities that ~55 production
|
|
* files import (extracted to `db-helpers.ts`) and provides a stub `Database`
|
|
* class whose methods throw. The stub preserves the public type shape so the
|
|
* satellite stores' sync else-branches (dead in backend mode) and the
|
|
* quarantined test files continue to type-check under `tsc --noEmit` while
|
|
* their SQLite runtime code is removed in lockstep.
|
|
*
|
|
* What is KEPT for the one-time SQLite→PostgreSQL migration tool:
|
|
* - `sqlite-adapter.ts` (`DatabaseSync`)
|
|
* - `sqlite-validation.ts`
|
|
* - `sqlite-migrator.ts` (migration tool; lives in the migrator package)
|
|
*
|
|
* What is GONE: every PRAGMA, ATTACH DATABASE, FTS5 probe, VACUUM, WAL
|
|
* checkpoint, integrity_check, and `sqlite3` CLI offload code path.
|
|
*/
|
|
|
|
// Re-export the pure utilities so existing `from "./db.js"` importers keep working.
|
|
export {
|
|
toJson,
|
|
toJsonNullable,
|
|
fromJson,
|
|
isSqliteLockError,
|
|
sleepSync,
|
|
normalizeTaskComments,
|
|
SCHEMA_VERSION,
|
|
ProjectIdentityConflictError,
|
|
} from "./db-helpers.js";
|
|
export type { Statement, VacuumResult, ProjectIdentity } from "./db-helpers.js";
|
|
|
|
import type { Statement, VacuumResult, ProjectIdentity } from "./db-helpers.js";
|
|
import type { PluginOnSchemaInit } from "./plugin-types.js";
|
|
|
|
/**
|
|
* No-op stub for the legacy SQLite `probeFts5` runtime capability probe.
|
|
*
|
|
* FNXC:SqliteFinalRemoval 2026-06-26-09:30:
|
|
* FTS5 is removed. Always returns false. Retained only because central-db.ts
|
|
* and archive-db.ts historically imported it; their stubs no longer call it.
|
|
*/
|
|
export function probeFts5(): boolean {
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* No-op stub for the legacy `isFts5CorruptionError` classifier.
|
|
* FTS5 is removed; there is no FTS5 corruption to classify.
|
|
*/
|
|
export function isFts5CorruptionError(_error: unknown): boolean {
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* No-op stub for the test-only in-memory DB snapshot hook.
|
|
*
|
|
* FNXC:SqliteFinalRemoval 2026-06-26-09:30:
|
|
* The migrated-DB snapshot harness (store-test-helpers.ts /
|
|
* db-snapshot-helper.ts) amortized `db.init()` cost across in-memory SQLite
|
|
* DBs in tests. With the SQLite `Database` class body deleted, the snapshot
|
|
* has no consumer; this stub accepts the call so quarantined test fixtures
|
|
* that still reference it continue to type-check and run their setup without
|
|
* throwing. The snapshot bytes are discarded.
|
|
*/
|
|
export function setInMemoryTemplateSnapshot(_snapshot: Uint8Array | null): void {
|
|
// No-op: SQLite in-memory snapshot harness removed with the Database class.
|
|
}
|
|
|
|
/**
|
|
* Stub for the legacy schema-compat table schema map.
|
|
*
|
|
* FNXC:SqliteFinalRemoval 2026-06-26-09:30:
|
|
* The schema-compatibility fingerprint was a SQLite-only self-heal mechanism
|
|
* (PRAGMA table_info reconciliation). PostgreSQL uses Drizzle's migration
|
|
* history and `information_schema`-based validation instead. Returns an empty
|
|
* map; no production code imports this (only comments reference it).
|
|
*/
|
|
export function getSchemaSqlTableSchemas(): Map<string, Map<string, string>> {
|
|
return new Map();
|
|
}
|
|
export function getSchemaCompatibilityTableSchemas(): Map<string, Map<string, string>> {
|
|
return new Map();
|
|
}
|
|
export const MIGRATION_ONLY_TABLE_SCHEMAS: Record<string, Record<string, string>> = {};
|
|
export const SCHEMA_COMPAT_FINGERPRINT = "";
|
|
|
|
/**
|
|
* No-op stubs for the legacy SQLite file-integrity helpers.
|
|
* PostgreSQL health checks live in `postgres/postgres-health.ts`.
|
|
*/
|
|
export function quickCheckSqliteFile(_dbPath: string): { ok: boolean; verified: boolean; errors?: string[] } {
|
|
return { ok: true, verified: false };
|
|
}
|
|
export async function integrityCheckSqliteFileAsync(
|
|
_dbPath: string,
|
|
): Promise<{ ok: boolean; errors?: string[] }> {
|
|
return { ok: true };
|
|
}
|
|
|
|
// ── Stub Database class ──────────────────────────────────────────────
|
|
|
|
const SQLITE_REMOVED_MESSAGE =
|
|
"SQLite Database class body has been removed (VAL-REMOVAL-005). " +
|
|
"The runtime uses PostgreSQL via AsyncDataLayer. This sync SQLite path is " +
|
|
"unreachable in backend mode; if you hit this, a non-backend-mode caller " +
|
|
"was not migrated.";
|
|
|
|
function throwSqliteRemoved(): never {
|
|
throw new Error(SQLITE_REMOVED_MESSAGE);
|
|
}
|
|
|
|
/**
|
|
* Stub `Database` class.
|
|
*
|
|
* FNXC:SqliteFinalRemoval 2026-06-26-09:30:
|
|
* The ~5900-line SQLite `Database` class body (constructor, schema SQL, 130
|
|
* migrations, PRAGMA/FTS5/VACUUM/WAL/integrity-check code) is DELETED. This
|
|
* stub preserves the public method signatures so the satellite stores' sync
|
|
* else-branches and quarantined test files continue to type-check under
|
|
* `tsc --noEmit`. Every method throws because the SQLite runtime is gone;
|
|
* production runs in backend mode (PostgreSQL) and never reaches these.
|
|
*/
|
|
export class Database {
|
|
corruptionDetected = false;
|
|
integrityCheckErrors: string[] = [];
|
|
integrityCheckPending = false;
|
|
integrityCheckLastRunAt: string | null = null;
|
|
|
|
/** Stub: preserves the constructor signature for type-compat only. */
|
|
constructor(
|
|
private readonly dbPath: string = ":memory:",
|
|
_options?: { inMemory?: boolean; busyTimeoutMs?: number; lockRecoveryWindowMs?: number; lockRecoveryDelayMs?: number },
|
|
) {}
|
|
|
|
get path(): string {
|
|
return this.dbPath;
|
|
}
|
|
|
|
static recoverIfCorrupt(_fusionDir: string): {
|
|
status: "absent" | "healthy" | "unverified" | "recovered" | "failed";
|
|
corruptBackupPath?: string;
|
|
recoveredPath?: string;
|
|
errors?: string[];
|
|
} {
|
|
return { status: "absent" };
|
|
}
|
|
|
|
init(): void {
|
|
throwSqliteRemoved();
|
|
}
|
|
|
|
/**
|
|
* Stub for the legacy SQLite plugin onSchemaInit hook runner.
|
|
*
|
|
* FNXC:SqliteFinalRemoval 2026-06-26-09:30:
|
|
* Plugin schema-init against the SQLite DB is removed. The PostgreSQL
|
|
* backend runs plugin schema init via the async data layer. This stub is
|
|
* reachable only through `taskStore.getDatabase()` which throws in backend
|
|
* mode; it preserves the signature for the engine plugin-runner's type-check.
|
|
*/
|
|
async runPluginSchemaInits(
|
|
_hooks: Array<{ pluginId: string; hook: PluginOnSchemaInit }>,
|
|
): Promise<void> {
|
|
throwSqliteRemoved();
|
|
}
|
|
|
|
prepare(_sql: string): Statement {
|
|
throwSqliteRemoved();
|
|
}
|
|
exec(_sql: string): void {
|
|
throwSqliteRemoved();
|
|
}
|
|
transaction<T>(_fn: () => T, _options?: { mode?: "deferred" | "immediate" }): T {
|
|
throwSqliteRemoved();
|
|
}
|
|
transactionImmediate<T>(_fn: () => T): T {
|
|
throwSqliteRemoved();
|
|
}
|
|
close(): void {
|
|
// No-op: nothing to close (no SQLite handle was ever opened).
|
|
}
|
|
serializeSnapshot(): Uint8Array {
|
|
throwSqliteRemoved();
|
|
}
|
|
get fts5Available(): boolean {
|
|
return false;
|
|
}
|
|
rebuildFts5Index(): boolean {
|
|
return false;
|
|
}
|
|
optimizeFts5(_mode?: "optimize" | "merge"): boolean {
|
|
return false;
|
|
}
|
|
getFtsIndexBytes(): number | null {
|
|
return null;
|
|
}
|
|
getTaskRowCount(): number {
|
|
throwSqliteRemoved();
|
|
}
|
|
checkFts5Integrity(): boolean {
|
|
return false;
|
|
}
|
|
integrityCheck(): { ok: true } | { ok: false; errors: string[] } {
|
|
return { ok: true };
|
|
}
|
|
refreshIntegrityCheck(): { ok: true } | { ok: false; errors: string[] } {
|
|
return { ok: true };
|
|
}
|
|
recoverDatabase(_outputPath: string): boolean {
|
|
return false;
|
|
}
|
|
vacuum(): VacuumResult {
|
|
throwSqliteRemoved();
|
|
}
|
|
dropOrphanRecoveryTables(): number {
|
|
return 0;
|
|
}
|
|
pruneOperationalLogs(_retentionMs: number): { deletedByTable: Record<string, number>; deletedTotal: number } {
|
|
return { deletedByTable: {}, deletedTotal: 0 };
|
|
}
|
|
walCheckpoint(_mode?: "PASSIVE" | "TRUNCATE"): { busy: number; log: number; checkpointed: number } {
|
|
return { busy: 0, log: 0, checkpointed: 0 };
|
|
}
|
|
getProjectIdentity(): ProjectIdentity | undefined {
|
|
throwSqliteRemoved();
|
|
}
|
|
setProjectIdentity(_identity: ProjectIdentity, _options?: { force?: boolean }): void {
|
|
throwSqliteRemoved();
|
|
}
|
|
clearProjectIdentity(): void {
|
|
throwSqliteRemoved();
|
|
}
|
|
getLastModified(): number {
|
|
throwSqliteRemoved();
|
|
}
|
|
bumpLastModified(): void {
|
|
throwSqliteRemoved();
|
|
}
|
|
getBootstrappedAt(): number | null {
|
|
throwSqliteRemoved();
|
|
}
|
|
getSchemaVersion(): number {
|
|
throwSqliteRemoved();
|
|
}
|
|
getPath(): string {
|
|
return this.dbPath;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Stub factory matching the legacy `createDatabase` signature.
|
|
* Returns a Database stub instance (never initialized).
|
|
*/
|
|
export function createDatabase(fusionDir: string, _options?: { inMemory?: boolean }): Database {
|
|
return new Database(fusionDir);
|
|
}
|
|
|
|
/**
|
|
* FNXC:SqliteFinalRemoval 2026-06-26-09:30:
|
|
* Legacy sync project-identity readers. Production now uses the
|
|
* `readProjectIdentity` / `writeProjectIdentity` in `project-identity.ts`
|
|
* (which uses the low-level `DatabaseSync` for the local anchor file),
|
|
* re-exported from index.ts. These db.ts versions are kept as stubs only
|
|
* for backward-compat with any internal caller that imports from "./db.js"
|
|
* directly; they delegate to the project-identity module.
|
|
*/
|
|
export { readProjectIdentity, writeProjectIdentity } from "./project-identity.js";
|