Files
fusion/docs
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
..

Fusion Documentation

← Back to repository root

Fusion is an AI-orchestrated task board that turns ideas into reviewed, merged code using a structured workflow: planning → todo → in-progress → in-review → done.

Fusion Dashboard Overview

Quick Start

Start the local dashboard with pnpm dev dashboard, then create your first task from the board or CLI.

For a full walkthrough (installation, onboarding, first task, and daily workflow basics):

➡️ Getting Started

Documentation Index

Getting Started

Guide Description
Getting Started Installation, first-run, first task, and daily workflow basics
Dashboard Guide Board/list views, left/right sidebar navigation, Artifacts, Import Tasks, chat, workflow selection/editor, terminal, git manager, files, planning, and UI tools
CLI Reference Complete fn command reference with subcommands, flags, and examples
Remote Access Operator runbook for Tailscale/Cloudflare setup, tokenized login links, security caveats, and troubleshooting
Native Shell Connection Guide Canonical mobile/desktop shell onboarding, profile management, QR/manual setup, and remote handoff behavior

Task & Project Management

Guide Description
Task Management Task creation modes, lifecycle, prompt specs, comments, archiving, and GitHub integration
Todo View Canonical guide for the experimental Todo View, including enablement, usage, API routes, and storage
Missions Mission hierarchy, planning flow, activation, progress tracking, and autopilot behavior
Goals Refinement Gate Evidence gate for activating the conditional post-v1 goals refinement slice only after real usage pain is documented
Goals Refinement Evidence Pack Structured observation template and two-observation threshold for conditional Slice 4 activation requests
Research Research runs, provider setup, dashboard/CLI usage, findings, exports, and task integration
Research View UX Spec Canonical layout and capability-state messaging spec for the Research dashboard view (FN-4138, informs FN-4134/FN-4135)
Workflow Steps Workflow overview, built-in workflow catalog, per-task selection, runtime semantics, reusable quality gates, templates, phases, and execution results
Workflow Editor Visual workflow editor guide for opening, viewing, authoring, validating, importing/exporting, custom fields/columns/settings, and tuning workflows
Custom Workflow Reliability Acceptance Map End-to-end reliability acceptance criteria for custom workflow authoring, selection, execution, recovery, restart durability, and deferred journeys
Custom Non-Coding Workflows MVP Spec MVP framing for user-authored non-coding workflows, lifecycle mapping, metrics, and risk checklist
Task Evaluations Eval scoring contract, evidence persistence, score categories, and evaluation pipeline
Multi-Project Central registry architecture, project management, isolation modes, and migration paths

Configuration & Agents

| Settings Reference | Global/project settings, workflow setting values, model/fallback lane hierarchy, defaults, and API endpoints | | MCP | Model Context Protocol server configuration, secret references, validation, CLI, dashboard, and import/export workflows | | Agents | Agent management, presets, prompts, heartbeat behavior, spawning, and mailbox workflows | | Planner Oversight (see Settings Reference, Dashboard Guide, Architecture) | Workflow-native oversight levels (off/observe/steer/autonomous), per-task overrides, notification verbosity, the human-confirmation gate on merge/PR and destructive actions, and the Task Detail overseer controls/Intervention Timeline |

Architecture & Development

Guide Description
Architecture System architecture, package layout, storage model, and engine execution flow
Secrets Store (SecretsStore) Core encrypted secret subsystem overview: scopes, AES-256-GCM at-rest model, policy semantics, and public store API surface
Dashboard Real-Time Canonical event-stream architecture contract (shared /api/events bus + dedicated stream boundaries), with project/node scoping, reconnect/cleanup behavior, and realtime pitfalls
Storage Storage architecture, migration, archive system, and SQLite schema
DAG Architecture Deliverables Milestone A DAG architecture documents plus Milestone B prototype scaffold docs (schema migration plan, DagCoordinator design, implementation checklist)
Dev Server Module Audit Analysis of parallel dashboard dev-server module families, production wiring, and consolidation guidance
Shared Mesh Replication Protocol Canonical multi-leader replication/write-coordination contract (versioning, quorum, leases/fencing, queue/replay, reconciliation, and degraded-read semantics)
Signals Connectors HMAC-signed external signal connectors for setup, payload mapping, and security notes across Sentry, Datadog, PagerDuty, and generic webhooks
Multi-Project Sequencing and Dependency Analysis Sequencing guidance for FN-3448/FN-3449/FN-3503/FN-3182, including identity boundaries and recommended board dependency edges
Contributing Local development setup, testing, release flow, and contributor conventions
Docker Container builds, deployment, and persistence configuration
Code Signing macOS and Windows code signing configuration for release binaries
Diagnostics Engine diagnostic logging subsystems, structured log keys, and key diagnostic points catalog
Sandbox Backends Pluggable sandbox backends for executor command isolation (bubblewrap, spawn-based)
Secrets Encrypted secrets storage, per-secret access policies, scopes, and agent tool wiring
Testing Full testing lanes, worker fanout guidance, test taxonomy, and file organization
Real iOS Safari Acceptance Surface Provisioning runbook and harness usage for terminal verification gates on physical or cloud real-iOS Safari
Solutions Catalog Documented solutions to past problems (bugs, architecture patterns, best practices) organized by category
Localization Contributing Guide Conventions for contributing translations, locale file structure, and i18n tooling
Mobile Capacitor/PWA mobile development setup and workflow

Plugins

Guide Description
Plugin Management End-user guide for discovering, installing, enabling, configuring, updating, uninstalling, and troubleshooting Fusion plugins
Plugin Authoring Developer guide for building Fusion plugins (manifest, SDK hooks, routes, UI/runtime contributions)
Even Realities Glasses Plugin Task-focused Even Realities glasses bridge with quick capture, polling notifications, and agent actions
Reports Plugin Reports plugin rendering, export, standalone HTML generation, and section configuration
Even Realities Plugin API Even Realities plugin API endpoint reference and test coverage matrix
Memory Plugin Contract Pluggable memory backend architecture, interface contract, and migration strategy
Compound Engineering Plugin CE workflow dashboard surface: artifact hub, interactive sessions, work→board bridge, and bidirectional sync
External Plugin Authoring Step-by-step guide for authoring plugins using an installed fn CLI (no monorepo access needed)
External Plugin Proof-Point Runbook Repeatable release-validation runbook for proving an external plugin runs against a published Fusion CLI build

Audit Reports

Report Description
Test Feedback-Loop Baseline Weekly FN-6612 signal-per-second baseline for gate/test wall-time, slowest files, and quarantine trends
Test Value Audit Heuristic test-value audit generated by scripts/test-value-audit.mjs to support human deletion and review decisions
Test Velocity Baseline Weekly feedback-loop velocity baseline for merge-gate, boot-smoke, changed-test, and quarantine metrics
UX Audit Report Comprehensive UX audit with prioritized recommendations for dashboard improvements
Codebase Improvement Audit Evidence-based technical debt and reliability gap audit with prioritized recommendations
Gap Analysis System completeness analysis comparing Fusion to Paperclip feature set
Agent Sandbox Research Research on agent isolation, capability enforcement, and sandboxing approaches
Even Realities Integration Research (FN-3737) Research summary and recommended integration topology for Even Realities glasses + Fusion
Agent Gap Analysis Gap analysis for agent Paperclip integration
pi-autoresearch Analysis for Fusion Port Upstream architecture/license analysis and Fusion integration mapping for autoresearch capabilities
pi-autoresearch Audit vs Fusion Research Audit comparing Fusion's research subsystem against upstream pi-autoresearch capabilities and parity gaps (FN-4136)
Research Hardening Preflight Baseline Verified research subsystem baseline, lifecycle contracts, and hardening pressure points
Test Audit Report Test coverage and effectiveness audit with recommendations
Skipped Test Inventory Current intentional test-skip inventory and reconciliation status for older skip follow-ups
Dev Server Module Boundary Audit Boundary/ownership audit for parallel dev-server-* vs devserver-* dashboard modules and FN-2212 prioritization guidance
spawn_agent Approval Evaluation (FN-3973) Decision to keep fn_spawn_agent under generic action-gate governance rather than durable agent provisioning policy
Task Lineage Reconciliation Notes Historical task-ID reuse patterns, confidence semantics for commit attribution, and reconciliation methodology (FN-3953, FN-3998)
Dashboard Load Performance SQLite index analysis and optimization for dashboard boot path queries
CLI Printing Press Plugin Design Architecture design for the CLI printing press bundled plugin (FN-3762)
CLI Printing Press Research Upstream cli-printing-press analysis and Fusion integration mapping (FN-3761)
Research vs Experiment Session Naming Decision Naming decision record: hybrid approach retaining research_* for cited-search/synthesis and adding experiment_session_* for upstream parity (FN-4223)
Experiment Executor Design Experiment executor architecture: lifecycle, run state machine, and worktree isolation model
Experiment Finalize Flow Experiment finalize contract: branch grouping, dry-run planning, and session completion semantics
Experiment Session Model Experiment session data model: state transitions, iteration tracking, and persisted run state
Experiment Session MVP Spec MVP specification for the experiment session feature: scope, invariants, and delivery milestones
Sandbox Options Research (FN-4635) Pluggable sandbox options research: threat model, backend evaluation, and spawn-based isolation design
Triage Duplicate Detection Postmortem Postmortem on duplicate task detection gaps and scheduler dedup hardening
Multi-Node Runtime Readiness (FN-4814) Runtime readiness assessment for multi-node distributed coordination
Distributed Multi-Node Coordination Gap (FN-4819) Gap analysis for distributed multi-node agent coordination and cross-node task assignment
Cross-Node Assignment Wake Contract (FN-4824) Contract specification for cross-node task assignment wake signaling
Multi-Node Coordination Validation Findings (FN-4820) Validation findings from multi-node coordination testing and edge-case analysis
Secrets Sync Auth Parity Review (FN-4886) Review of node secrets sync API authentication parity and security boundaries
Test Speed Audit (FN-5048) Measured baseline test performance, offender list, and optimization priorities
Soft-Delete Verification Matrix Authoritative checklist for the FN-5105 → FN-5143 soft-delete stream: scenario × layer coverage
Self-Healing Backward Move Audit Audit of self-healing backward-move safety checks and edge-case validation
Workflow Policy Ownership Map U1 characterization map classifying production merge, retry, scheduling, and recovery policy branches before workflow-policy migration cutover
Test-Speed Baseline (2026-06-03) Measured per-file test timing baseline and optimization targets (successor to FN-5048 audit)
ACP Runtime Contract Agent Client Protocol plugin launch/readiness contract and failure taxonomy
ACP MCP Passthrough & Permission Forwarding Upstream Sponsorship (FN-6475) Ready-to-file upstream sponsorship for claude-code-cli-acp ACP session/new.mcpServers passthrough and permission-gate traversal; Route A remains NOT GO until proven
Mission Completion Gate Contract Decision record for mission completion gate invariants and acceptance flow

| Lost-Work Tasks Incident (2026-05-23) | Incident catalog of 9 lost-work tasks from no-op finalize and reuse-handoff bugs | | GitLab Parity Inventory (FN-7421) | Implementation map for first-class GitLab support: import, linked issue tracking, comments, auth/settings UI, CLI/extension, and Command Center surfaces to mirror or explicitly exclude | | Dashboard Theme & UI Plugin System Proposal (2026-07-01) | Feasibility-spike proposal for a controlled dashboard theme/UI shell extension point sharing one backend source of truth |

External Resources

Suggested Reading Paths

  • New user: Getting Started → Dashboard Guide → Task Management
  • Workflow author: Dashboard Guide → Workflow Editor → Workflow Steps → Settings Reference
  • Power user / automation owner: Settings Reference → Workflow Steps → Agents → Planner Oversight (Settings Reference § Workflow Settings)
  • Maintainer / contributor: Architecture → Multi-Project → Contributing