Files
fusion/plugins/fusion-plugin-dependency-graph
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
..
2026-07-13 10:32:12 -07:00
2026-07-13 10:32:12 -07:00

fusion-plugin-dependency-graph

Plugin-provided top-level Graph dashboard view for Fusion.

Host registration and bundled loading

The dependency graph view is registered as a bundled plugin view in the dashboard. This means:

  • registerBundledPluginViews() (called at dashboard startup) registers the view component in the static plugin view registry under key plugin:fusion-plugin-dependency-graph:graph.
  • The view component is resolved via a literal-specifier lazy import (import("@fusion-plugin-examples/dependency-graph/dashboard-view")) — this is critical for Vite/esbuild to emit a production chunk.
  • In Vite dev/build and Vitest, @fusion-plugin-examples/dependency-graph/dashboard-view is aliased to plugins/fusion-plugin-dependency-graph/src/dashboard-view.tsx (source, not dist/). This avoids stale dist artifacts breaking the dashboard view.
  • The App.tsx graph route resolves to the bundled view via isPluginViewRegistered fallback, so the graph view works even when the plugin is not installed/loaded through the PluginLoader API (e.g. fresh DB).
  • The canonical route ID is plugin:fusion-plugin-dependency-graph:graph.

Rendering approach

  • Filtering: includes triage, todo, in-progress, in-review; excludes done, archived
  • Graph build: edges are resolved only from task.dependencies as source=dependent, target=dependency
  • Orphan dependency handling: if a visible task depends on an excluded/missing dependency (for example done/archived after filtering), the missing edge is silently dropped and graph rendering continues without broken connectors
  • Auto-layout: Sugiyama-style layered layout (computeAutoLayout) groups nodes by dependency depth; both vertical and horizontal orientations use measured per-node card heights to compute stacked offsets (preventing card overlap), and orientation still flips responsively (height > width or width < 768) so depth flows left-to-right on tall/narrow viewports
  • Edge drawing: SVG bezier curves from source bottom-center to target top-center, with vertical mode anchoring source tails to each node's measured rendered height and arrowheads showing dependent → dependency direction
  • Interaction: drag-to-pan canvas background, scroll/two-finger pan, Ctrl/Cmd-wheel zoom, pinch-to-zoom with stationary midpoint, drag-to-reposition nodes, keyboard shortcuts, zoom toolbar, reset, and fit-to-graph
  • Zoomed navigation reachability: pan clamping now scales with the full rendered graph bounds (min/max node extents) at the active zoom level, so zooming in no longer traps off-screen content behind fixed viewport-only limits
  • Fit-to-graph: computes node bounding box from both minimum and maximum node coordinates (including negative auto-layout origins) with layout node dimensions and applies zoom/pan so the graph fits in viewport with padding
  • Initial auto-fit: when no saved scoped positions exist, the first non-empty render auto-fits once; subsequent updates preserve user navigation state
  • Position persistence: dragged node positions are stored per project in browser localStorage and restored on reload
  • Animated transitions: fit/reset operations animate transform (var(--transition-normal)), while continuous drag/wheel/pinch stays transition-free for responsiveness
  • Node rendering: each graph node renders the real dashboard TaskCard via GraphTaskNode (no duplicated card markup)
  • Task detail integration: a primary non-drag click on a graph node surface opens the native dashboard task detail modal exactly once through host context (openTaskDetail), matching board/list behavior
  • In-progress behavior: steps are visible by default and active-task glow (agent-active) is preserved because node cards reuse TaskCard directly
  • Active-state indicator bar: active nodes render a compact top bar (.graph-task-active-indicator) with the current execution status label (for example Executing, Planning) and pulsing --in-progress emphasis
  • Current-step highlighting: active nodes set data-current-step for valid native step indices so CSS selectors highlight the currently executing .card-step-item and pulse its step dot
  • Zoom-out differentiation: .graph-task-node--active adds amplified glow and subtle scale/border tint so active nodes remain distinguishable at reduced zoom levels
  • In-review visual treatment: in-review nodes get a static .graph-task-node--in-review left accent in --in-review to distinguish waiting-review work from active execution nodes
  • Graph node classes: .graph-task-node, .graph-task-node--active, .graph-task-node--in-review, .graph-task-node--highlighted, .graph-task-node--dimmed, .graph-node--highlighted, and .graph-node--dimmed are available for graph-specific layering/highlight states while card internals remain owned by TaskCard.css
  • Graph edge classes: .graph-edge--highlighted and .graph-edge--dimmed are applied during dependency-chain emphasis states
  • Drag behavior: graph nodes pass disableDrag={true} to TaskCard so card-level HTML5 drag does not conflict with canvas pan/zoom

Position persistence

  • Canonical base key: fusion-plugin-dependency-graph:positions
  • Storage key format: kb:${projectId}:fusion-plugin-dependency-graph:positions (falls back to fusion-plugin-dependency-graph:positions when no project is selected)
  • Read path: positions load on graph mount and whenever projectId changes, then merge with fresh auto-layout so new tasks still receive layout defaults
  • Write path: positions persist on drag end only (not on every drag frame), filtered to currently visible tasks for stale cleanup
  • Reset behavior: Fit to graph / Reset view clear persisted positions and re-apply auto-layout
  • Implementation detail: the plugin now reuses dashboard projectStorage helpers (getScopedItem / setScopedItem / removeScopedItem) instead of duplicating scoped localStorage logic

Dependency chain highlighting

  • Hover a node to highlight the full transitive upstream + downstream chain for that task.
  • Click a node to persist selection highlighting until the same node is clicked again or the canvas pane is clicked; this same click also opens task detail once through the host detail callback.
  • Priority: hover state overrides selected state; when hover leaves, selected highlighting reappears.
  • Dimming: when a chain is active, unrelated nodes and edges are dimmed.
  • Neutral state: when nothing is hovered/selected, no highlight/dim classes are applied.
  • Drag suppression: drag movements above the node drag threshold suppress the post-drag click, preventing accidental detail opens on pointer release.
  • Edge rule: an edge is highlighted only when both its source and target nodes are in the active chain.

Controls

Toolbar (bottom-right)

  • Zoom in (ZoomIn) — button + Ctrl+= / Cmd+=
  • Zoom out (ZoomOut) — button + Ctrl+- / Cmd+-
  • Zoom percent label — live readout (for example 100%, 75%, 250%)
  • Fit to graph (Maximize) — button + Ctrl+Shift+F / Cmd+Shift+F
  • Reset view (RotateCcw) — button + Ctrl+0 / Cmd+0

Additional keyboard behavior

  • Escape resets to default view (zoom=1, pan=0,0)
  • Shortcuts are suppressed when focus is inside input, textarea, select, or contentEditable elements

All controls are rendered as floating .btn-icon actions in the bottom-right corner, with mobile-friendly 44px touch targets in the @media (max-width: 768px) override.