# 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>
303 lines
9.7 KiB
JavaScript
303 lines
9.7 KiB
JavaScript
#!/usr/bin/env node
|
||
|
||
/*
|
||
FNXC:PostgresCutover 2026-07-05-13:00:
|
||
Ported from the sqlite3 CLI on .fusion/fusion.db to the PostgreSQL backend
|
||
(scripts/lib/backend-db.mjs). Same heuristics; task rows and the
|
||
active/archived duplicate join now come from the project/archive schemas.
|
||
*/
|
||
import { execFileSync } from "node:child_process";
|
||
import { existsSync, readFileSync, statSync } from "node:fs";
|
||
import path from "node:path";
|
||
import { openBackend, rowsOf } from "./lib/backend-db.mjs";
|
||
|
||
function parseArgs(argv) {
|
||
const args = { projectRoot: process.cwd(), json: false };
|
||
for (let i = 0; i < argv.length; i += 1) {
|
||
const arg = argv[i];
|
||
if (arg === "--project-root") {
|
||
args.projectRoot = path.resolve(argv[i + 1] ?? process.cwd());
|
||
i += 1;
|
||
} else if (arg === "--json") {
|
||
args.json = true;
|
||
}
|
||
}
|
||
return args;
|
||
}
|
||
|
||
function run(command, args, options = {}) {
|
||
return execFileSync(command, args, {
|
||
encoding: "utf8",
|
||
stdio: ["ignore", "pipe", "pipe"],
|
||
...options,
|
||
}).trim();
|
||
}
|
||
|
||
function resolveMainRef(projectRoot) {
|
||
try {
|
||
run("git", ["rev-parse", "--verify", "origin/main"], { cwd: projectRoot });
|
||
return "origin/main";
|
||
} catch {
|
||
return "main";
|
||
}
|
||
}
|
||
|
||
function normalizeTitle(text) {
|
||
return String(text ?? "")
|
||
.replace(/^#\s+/, "")
|
||
.replace(/^Task:\s*/i, "")
|
||
.replace(/^[A-Z]+-\d+\s*[:-]\s*/i, "")
|
||
.replace(/\s*\[via:[^\]]+\]\s*$/i, "")
|
||
.replace(/[“”]/g, '"')
|
||
.replace(/[’]/g, "'")
|
||
.replace(/\s+/g, " ")
|
||
.trim()
|
||
.toLowerCase();
|
||
}
|
||
|
||
function firstHeading(promptText) {
|
||
const line = String(promptText ?? "").split(/\r?\n/).find((entry) => entry.trim().startsWith("#"));
|
||
if (!line) return null;
|
||
return line.replace(/^#+\s*/, "").trim();
|
||
}
|
||
|
||
const STOP_WORDS = new Set([
|
||
"the", "and", "with", "from", "that", "this", "into", "over", "under", "after", "before", "while",
|
||
"your", "their", "have", "has", "had", "make", "task", "tasks", "agent", "dashboard", "api", "via",
|
||
"fix", "add", "create", "update", "investigate", "restore", "support", "allow", "keep", "show", "same",
|
||
]);
|
||
|
||
function significantTokens(text) {
|
||
return new Set(
|
||
normalizeTitle(text)
|
||
.split(/[^a-z0-9]+/)
|
||
.filter((token) => token.length >= 4 && !STOP_WORDS.has(token)),
|
||
);
|
||
}
|
||
|
||
function tokenOverlap(left, right) {
|
||
const leftTokens = significantTokens(left);
|
||
const rightTokens = significantTokens(right);
|
||
if (leftTokens.size === 0 || rightTokens.size === 0) {
|
||
return { shared: [], ratio: 1 };
|
||
}
|
||
const shared = [...leftTokens].filter((token) => rightTokens.has(token));
|
||
const ratio = shared.length / Math.max(leftTokens.size, rightTokens.size);
|
||
return { shared, ratio };
|
||
}
|
||
|
||
function readJson(filePath) {
|
||
return JSON.parse(readFileSync(filePath, "utf8"));
|
||
}
|
||
|
||
function extractHistoricalCreatedAt(taskJson) {
|
||
const candidates = [];
|
||
if (Array.isArray(taskJson?.history)) {
|
||
for (const entry of taskJson.history) {
|
||
if (!entry || typeof entry !== "object") continue;
|
||
if (typeof entry.createdAt === "string") candidates.push(entry.createdAt);
|
||
if (typeof entry.timestamp === "string") candidates.push(entry.timestamp);
|
||
}
|
||
}
|
||
if (taskJson?.history && typeof taskJson.history === "object" && !Array.isArray(taskJson.history)) {
|
||
if (typeof taskJson.history.createdAt === "string") candidates.push(taskJson.history.createdAt);
|
||
if (typeof taskJson.history.timestamp === "string") candidates.push(taskJson.history.timestamp);
|
||
}
|
||
return candidates.sort()[0] ?? null;
|
||
}
|
||
|
||
function getLatestTaskCommit(projectRoot, mainRef, taskId) {
|
||
try {
|
||
const output = run(
|
||
"git",
|
||
["log", mainRef, "--format=%H%x09%cI%x09%s%x09%(trailers:key=Fusion-Task-Id,valueonly)", "--all"],
|
||
{ cwd: projectRoot },
|
||
);
|
||
if (!output) return null;
|
||
for (const line of output.split("\n")) {
|
||
const [sha, committedAt, subject, trailer] = line.split("\t");
|
||
if ((trailer ?? "").trim() === taskId) {
|
||
return { sha, committedAt, subject };
|
||
}
|
||
}
|
||
return null;
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
async function buildReport(projectRoot) {
|
||
const tasksDir = path.join(projectRoot, ".fusion", "tasks");
|
||
const mainRef = resolveMainRef(projectRoot);
|
||
|
||
if (!existsSync(tasksDir)) {
|
||
throw new Error(`Tasks directory not found: ${tasksDir}`);
|
||
}
|
||
|
||
const backend = await openBackend(projectRoot);
|
||
let activeTasks;
|
||
let archivedDupes;
|
||
try {
|
||
const { asyncLayer, sql } = backend;
|
||
activeTasks = rowsOf(await asyncLayer.db.execute(sql`
|
||
SELECT id, title, created_at AS "createdAt", updated_at AS "updatedAt", "column" AS "columnName"
|
||
FROM project."tasks"
|
||
ORDER BY id
|
||
`));
|
||
try {
|
||
archivedDupes = rowsOf(await asyncLayer.db.execute(sql`
|
||
SELECT t.id AS id, t.title AS "activeTitle", a.archived_at AS "archivedAt"
|
||
FROM project."tasks" t
|
||
INNER JOIN archive."archived_tasks" a ON a.id = t.id
|
||
ORDER BY t.id
|
||
`));
|
||
} catch {
|
||
archivedDupes = [];
|
||
}
|
||
} finally {
|
||
await backend.shutdown().catch(() => {});
|
||
}
|
||
|
||
const candidates = [];
|
||
let historyUnavailableCount = 0;
|
||
|
||
for (const task of activeTasks) {
|
||
const taskDir = path.join(tasksDir, task.id);
|
||
const taskJsonPath = path.join(taskDir, "task.json");
|
||
const promptPath = path.join(taskDir, "PROMPT.md");
|
||
const signals = [];
|
||
|
||
let taskJson = null;
|
||
if (existsSync(taskJsonPath)) {
|
||
taskJson = readJson(taskJsonPath);
|
||
const historicalCreatedAt = extractHistoricalCreatedAt(taskJson);
|
||
if (historicalCreatedAt && historicalCreatedAt < task.createdAt) {
|
||
signals.push({
|
||
type: "history-created-before-db-createdAt",
|
||
detail: `history createdAt ${historicalCreatedAt} < db createdAt ${task.createdAt}`,
|
||
});
|
||
}
|
||
if (!historicalCreatedAt) {
|
||
historyUnavailableCount += 1;
|
||
}
|
||
}
|
||
|
||
if (existsSync(promptPath)) {
|
||
const prompt = readFileSync(promptPath, "utf8");
|
||
const heading = firstHeading(prompt);
|
||
if (heading) {
|
||
const normalizedHeading = normalizeTitle(heading);
|
||
const normalizedTitleText = normalizeTitle(task.title);
|
||
if (
|
||
normalizedTitleText &&
|
||
normalizedHeading &&
|
||
normalizedTitleText !== normalizedHeading &&
|
||
!normalizedHeading.includes(normalizedTitleText) &&
|
||
!normalizedTitleText.includes(normalizedHeading)
|
||
) {
|
||
signals.push({
|
||
type: "prompt-heading-mismatch",
|
||
detail: `db title="${task.title}" vs prompt heading="${heading}"`,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
const commit = getLatestTaskCommit(projectRoot, mainRef, task.id);
|
||
if (commit) {
|
||
const overlap = tokenOverlap(task.title, commit.subject.replace(/^.*?:\s*/, ""));
|
||
if (overlap.ratio === 0) {
|
||
signals.push({
|
||
type: "commit-subject-mismatch",
|
||
detail: `${commit.sha.slice(0, 9)} ${commit.subject}`,
|
||
committedAt: commit.committedAt,
|
||
});
|
||
}
|
||
}
|
||
|
||
if (signals.length > 0) {
|
||
candidates.push({
|
||
id: task.id,
|
||
title: task.title,
|
||
createdAt: task.createdAt,
|
||
updatedAt: task.updatedAt,
|
||
column: task.columnName,
|
||
taskDirExists: existsSync(taskDir),
|
||
taskDirMtime: existsSync(taskDir) ? statSync(taskDir).mtime.toISOString() : null,
|
||
signals,
|
||
});
|
||
}
|
||
}
|
||
|
||
for (const duplicate of archivedDupes) {
|
||
const existing = candidates.find((candidate) => candidate.id === duplicate.id);
|
||
const signal = {
|
||
type: "active-archive-duplicate-id",
|
||
detail: `active task shares ID with archivedTasks row (archivedAt ${duplicate.archivedAt})`,
|
||
};
|
||
if (existing) {
|
||
existing.signals.push(signal);
|
||
} else {
|
||
candidates.push({
|
||
id: duplicate.id,
|
||
title: duplicate.activeTitle,
|
||
createdAt: null,
|
||
updatedAt: null,
|
||
column: "active+archived",
|
||
taskDirExists: existsSync(path.join(tasksDir, duplicate.id)),
|
||
taskDirMtime: existsSync(path.join(tasksDir, duplicate.id)) ? statSync(path.join(tasksDir, duplicate.id)).mtime.toISOString() : null,
|
||
signals: [signal],
|
||
});
|
||
}
|
||
}
|
||
|
||
candidates.sort((a, b) => a.id.localeCompare(b.id));
|
||
|
||
return {
|
||
projectRoot,
|
||
tasksDir,
|
||
mainRef,
|
||
scannedActiveTasks: activeTasks.length,
|
||
candidateCount: candidates.length,
|
||
historyUnavailableCount,
|
||
candidates,
|
||
};
|
||
}
|
||
|
||
function toMarkdown(report) {
|
||
const lines = [];
|
||
lines.push("# Task ID collision audit report");
|
||
lines.push("");
|
||
lines.push(`- Project root: \
|
||
\`${report.projectRoot}\``);
|
||
lines.push(`- Git ref used for commit checks: \
|
||
\`${report.mainRef}\``);
|
||
lines.push(`- Active tasks scanned: **${report.scannedActiveTasks}**`);
|
||
lines.push(`- Candidates flagged: **${report.candidateCount}**`);
|
||
lines.push(`- Tasks without usable \`task.json.history\` signal: **${report.historyUnavailableCount}**`);
|
||
lines.push("");
|
||
|
||
if (report.candidates.length === 0) {
|
||
lines.push("No candidates flagged by the configured heuristics.");
|
||
return lines.join("\n");
|
||
}
|
||
|
||
for (const candidate of report.candidates) {
|
||
lines.push(`## ${candidate.id} — ${candidate.title}`);
|
||
lines.push(`- Column: ${candidate.column}`);
|
||
if (candidate.createdAt) lines.push(`- DB createdAt: ${candidate.createdAt}`);
|
||
if (candidate.updatedAt) lines.push(`- DB updatedAt: ${candidate.updatedAt}`);
|
||
if (candidate.taskDirMtime) lines.push(`- Task dir mtime: ${candidate.taskDirMtime}`);
|
||
for (const signal of candidate.signals) {
|
||
lines.push(`- [${signal.type}] ${signal.detail}`);
|
||
}
|
||
lines.push("");
|
||
}
|
||
|
||
return lines.join("\n");
|
||
}
|
||
|
||
const args = parseArgs(process.argv.slice(2));
|
||
const report = await buildReport(args.projectRoot);
|
||
process.stdout.write(args.json ? `${JSON.stringify(report, null, 2)}\n` : `${toMarkdown(report)}\n`);
|