# 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>
Even Realities Glasses Plugin (Fusion)
@fusion-plugin-examples/even-realities-glasses is a standalone Fusion plugin that provides a task-centric card workflow for Even Realities glasses.
Scope (v1)
- Quick capture text into new tasks
- Polling-based task transition notifications
- Selected task workflow actions from glasses
Out of scope in v1: missions, roadmaps, search, multi-project routing, cloud/remote deployment orchestration.
Install (workspace local)
From repo root:
pnpm install
pnpm --filter @fusion-plugin-examples/even-realities-glasses build
pnpm --filter @fusion-plugin-examples/even-realities-glasses test
Required settings
fusionApiBaseUrl(defaulthttp://localhost:4040)fusionApiToken(required Bearer token)apiKey(required for plugin routes)glassesDeviceId(optional identifier)companionWebhookUrl(optional companion endpoint base URL for card push, e.g.https://companion.example)pollingIntervalSeconds(default 30, min 5)notifyOnColumns(default["in-review"])quickCaptureDefaultColumn(defaulttriage)enableAgentActions(defaulttrue)
Quick capture
Use POST /quick-capture for one-gesture glasses capture (POST /tasks is still the general-purpose route).
Pipeline:
- Strip leading wake phrase (
hey fusion,fusion,ok fusion,note,task,capture) - Strip filler tokens (
um,uh,er,like,you know) and transcript punctuation noise - Split first sentence into title + description (title capped at 80 chars; overflow moved into description)
- Resolve column from request
columnor plugin settingquickCaptureDefaultColumn(fallbacktriage)
Example:
curl -X POST http://localhost:4040/api/plugins/fusion-plugin-even-realities-glasses/quick-capture \
-H "Authorization: Bearer <apiKey>" \
-H "Content-Type: application/json" \
-d '{"text":"hey fusion, file a bug about the merge gate"}'
Agent actions
All action routes require Authorization: Bearer <apiKey> and enableAgentActions=true.
Endpoints
| Method | Path |
|---|---|
| POST | /actions/start-work |
| POST | /actions/request-review |
| POST | /actions/approve-plan |
| POST | /actions/accept-review |
| POST | /actions/return-to-agent |
| POST | /actions/retry |
Request body:
{ "taskId": "FN-123" }
Success response:
{
"task": { "id": "FN-123" },
"card": { "kind": "task", "taskId": "FN-123" }
}
Error envelope:
{ "error": "message" }
Status mapping:
401: missing/wrong API key403:enableAgentActionsdisabled400: invalid input (for example emptytaskId)404: task not found409: action not allowed for current column/status500: unexpected internal error
Preconditions and mutations:
| Action | Allowed preconditions | Mutation |
|---|---|---|
start-work |
column ∈ {triage, todo} and status not in {planning, needs-replan, awaiting-approval, awaiting-user-review} |
moveTask(id, "in-progress") |
request-review |
column === "in-progress" |
moveTask(id, "in-review") |
approve-plan |
column === "triage" and status === "awaiting-approval" |
moveTask(id, "todo") then updateTask(id, { status: undefined }) |
accept-review |
column === "in-review" |
updateTask(id, { status: null, assigneeUserId: null }) |
return-to-agent |
column === "in-review" |
updateTask(id, { assigneeUserId: null, status: null, assignedAgentId: null }) then moveTask(id, "todo") |
retry (in-review branch) |
column === "in-review" and status ∈ {failed, stuck-killed} |
updateTask(id, { status: null, error: null, stuckKillCount: 0, mergeRetries: 0 }) |
retry (triage/planning branch) |
column === "triage" and (status ∈ {failed, planning, needs-replan} or (stuckKillCount ?? 0) > 0) |
updateTask(id, { status: "needs-replan", error: null, worktree: null, branch: null, baseBranch: null, baseCommitSha: null, stuckKillCount: 0, recoveryRetryCount: null, nextRecoveryAt: null }) |
retry (general failed branch) |
status ∈ {failed, stuck-killed} and not covered by branches above |
updateTask(id, { status: null, error: null, worktree: null, branch: null, baseBranch: null, baseCommitSha: null, stuckKillCount: 0, recoveryRetryCount: null, nextRecoveryAt: null }) then moveTask(id, "todo") |
Example:
curl -X POST http://localhost:4040/api/plugins/fusion-plugin-even-realities-glasses/actions/start-work \
-H "Authorization: Bearer <apiKey>" \
-H "Content-Type: application/json" \
-d '{"taskId":"FN-123"}'
Known limitations (v1)
startWorkdoes not allocate a worktree directly. Tasks can enterin-progresswithworktree: null; executorcreateWorktreeflow allocates on first dispatch.approvePlanperforms move-then-clear; re-fetched responses may presenttask.status == null.retrytriage/planning branch does not delete on-diskPROMPT.mdand does not run dashboard retry step-reset / branch-inspection logic.
Notifications
Notifications are produced by polling taskStore.listTasks({ includeArchived: false }) on pollingIntervalSeconds and diffing against persisted snapshot rows in even_realities_seen_tasks.
Diff reasons:
new-task(task first seen in a watched column)entered-column(task moved into a watched column)left-column(task moved out of a watched column)completed(supported by diff engine; currently disabled in notifier v1)
Snapshot rows survive plugin restarts, so previously-seen tasks are not re-notified after reload.
Notification endpoints
| Method | Path | Description |
|---|---|---|
| GET | /notifications |
Read pending events (limit, optional drain=true) with rendered cards |
| POST | /notifications/ack |
Ack events by taskIds |
| POST | /notifications/poll-now |
Force immediate poll and return emitted events |
Example:
curl -X GET "http://localhost:4040/api/plugins/fusion-plugin-even-realities-glasses/notifications?limit=25" \
-H "Authorization: Bearer <apiKey>"
Security notes
- Uses
Authorization: Bearer <token>for all API requests. - Prefer local/self-hosted Fusion instances and avoid exposing dashboard APIs to public networks.
- Treat
fusionApiTokenas secret material and rotate regularly.
Board/task card endpoints (merged canonical surface)
All companion-facing routes use Authorization: Bearer <apiKey> and are hosted under:
/api/plugins/fusion-plugin-even-realities-glasses
| Method | Path | Description |
|---|---|---|
| GET | /board/cards |
Card deck projection for selected columns (columns, max) |
| GET | /board |
Board summary counts and status |
| GET | /tasks/:id/cards |
Single-task card deck |
Transport path (implemented)
Production transport uses WebhookGlassesTransport.
pushCard()POSTs cards to${companionWebhookUrl}/cards/statusreportsconnected, transport mode, webhook config presence,lastPushAt,lastActionAt, andlastErrorPOST /reconnectforces disconnect/connect on the transport state machinePOST /transport/actionsingests companion actions (start-work,request-review,quick-capture) into plugin action handlers
If companionWebhookUrl is unset, the plugin still serves authenticated routes and polling notifications, but card push remains degraded with connected=false and a status error until configured.