Files
fusion/packages/dashboard/src/cli-chat.ts
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

334 lines
13 KiB
TypeScript

/**
* CLI-backed chat session runner (CLI Agent Executor, U12).
*
* When a chat session selects a cli-agent executor (`ChatSession.cliExecutorAdapterId`),
* the chat is driven by a long-lived CLI agent process instead of the standard
* model-provider path. This runner is the server-side bridge between that CLI
* session and the durable chat transcript:
*
* - It spawns (or resumes) a `CliSessionManager` session with purpose "chat",
* cwd = the configured working directory (or the project root), persisting the
* native session id back onto the chat session for resume.
* - Composer messages route through the inject path (FIFO, serialized by the
* manager's write queue). While the session is busy, sends queue; the flush
* decision re-fetches authoritative session state from the store rather than
* trusting a cached/streamed busy flag (the stale-isGenerating learning,
* docs/solutions/logic-errors/queued-chat-message-flush-trusts-stale-isgenerating.md).
* - Adapter transcript telemetry events map to `chat_messages` rows at
* user/assistant/tool-summary granularity. Fine-grained tool noise
* (toolActivity, outputProgress, idle) stays in the terminal and is NOT
* persisted — the durable transcript is the readable conversation, not the
* raw scrollback.
*
* Secret hygiene: the shared `redactSecrets` pass runs on transcript text
* BEFORE persistence. Durable chat rows must not become a secret store — CLI
* agents routinely print bearer tokens and env dumps. See the test block in
* packages/dashboard/src/__tests__/chat-cli-sessions.test.ts for the
* characterized coverage of what `redactSecrets` catches and its known gaps.
*
* This module owns no PTY/adapter internals directly: it depends on narrow
* interfaces (`ChatStoreLike`, `CliSessionManagerLike`) so it is unit-testable
* with mocked PTY/adapters per the U12 constraints.
*/
import { redactSecrets } from "@fusion/core";
import type {
ChatMessage,
ChatMessageCreateInput,
ChatSession,
} from "@fusion/core";
// ── Narrow dependency interfaces (testable seams) ──────────────────────────
/** The slice of ChatStore this runner needs. */
export interface ChatStoreLike {
getSession(id: string): Promise<ChatSession | undefined> | ChatSession | undefined;
addMessage(sessionId: string, input: ChatMessageCreateInput): Promise<ChatMessage> | ChatMessage;
setCliExecutorAdapterId(id: string, adapterId: string | null): Promise<ChatSession | undefined> | ChatSession | undefined;
setCliSessionFile?(id: string, cliSessionFile: string | null): Promise<void> | void;
}
/** A durable cli_sessions record (subset used here). */
export interface CliSessionLike {
id: string;
nativeSessionId: string | null;
agentState: string;
}
/** The slice of CliSessionManager this runner needs. */
export interface CliSessionManagerLike {
spawn(options: {
adapterId: string;
projectId: string;
purpose: "chat";
chatSessionId: string;
worktreePath?: string | null;
resume?: { sessionId: string; nativeSessionId: string };
}): Promise<CliSessionLike>;
inject(sessionId: string, text: string): Promise<void>;
/** Authoritative, freshly-read session record (used for flush decisions). */
getSession(sessionId: string): CliSessionLike | undefined;
}
/**
* Sanitized telemetry event shape (mirrors engine's SanitizedTelemetryEvent,
* duplicated as a structural type to avoid a dashboard→engine import edge).
*/
export interface ChatTelemetryEvent {
kind:
| "sessionStart"
| "busy"
| "waitingOnInput"
| "done"
| "idle"
| "toolActivity"
| "outputProgress"
| "transcript";
text?: string;
nativeSessionId?: string;
/** Transcript role hint when the adapter distinguishes turns. */
role?: "user" | "assistant";
/** A tool-summary line (one human-readable line, not raw tool noise). */
toolSummary?: string;
}
/** Busy-equivalent states: composer sends must queue, not flush. */
const BUSY_STATES = new Set(["starting", "busy", "waitingOnInput"]);
export interface CliChatSessionRunnerOptions {
store: ChatStoreLike;
manager: CliSessionManagerLike;
}
/**
* Maps one CLI-backed chat session to its durable transcript and brokers
* composer injection with FIFO queueing.
*/
export class CliChatSessionRunner {
private readonly store: ChatStoreLike;
private readonly manager: CliSessionManagerLike;
/** chatSessionId → live cli session id. */
private readonly cliSessionByChat = new Map<string, string>();
/** chatSessionId → FIFO queue of composer texts awaiting a flush. */
private readonly queue = new Map<string, string[]>();
/** chatSessionId → assistant text being accumulated across transcript chunks. */
private readonly assistantBuffer = new Map<string, string>();
constructor(opts: CliChatSessionRunnerOptions) {
this.store = opts.store;
this.manager = opts.manager;
}
/**
* Ensure a live CLI session exists for the chat, spawning (or resuming via a
* persisted native session id) as needed. Returns the cli session id.
*/
async ensureSession(
chatSessionId: string,
opts: { projectId: string; worktreePath?: string | null },
): Promise<string> {
const existing = this.cliSessionByChat.get(chatSessionId);
if (existing) return existing;
const chat = await this.store.getSession(chatSessionId);
if (!chat) throw new Error(`Unknown chat session: ${chatSessionId}`);
const adapterId = chat.cliExecutorAdapterId;
if (!adapterId) {
throw new Error(`Chat session ${chatSessionId} has no cli-agent executor`);
}
// Resume if we previously recorded a native session id (cliSessionFile-style
// linkage; here the native id lives on the cli_sessions record).
const resumeNative = chat.cliSessionFile; // native session id persisted on the chat
const cli = await this.manager.spawn({
adapterId,
projectId: opts.projectId,
purpose: "chat",
chatSessionId,
worktreePath: opts.worktreePath ?? null,
...(resumeNative
? { resume: { sessionId: chatSessionId, nativeSessionId: resumeNative } }
: {}),
});
this.cliSessionByChat.set(chatSessionId, cli.id);
return cli.id;
}
/**
* Send a composer message. If the underlying CLI session is busy (per a
* freshly re-fetched store record — never a cached flag), the text is queued
* with a visible queued state instead of injected. Returns whether the
* message was injected immediately (`"sent"`) or queued (`"queued"`).
*
* The user message is persisted to the transcript immediately in both cases
* so the conversation reflects intent regardless of timing.
*/
async send(chatSessionId: string, text: string): Promise<"sent" | "queued"> {
const cliSessionId = this.cliSessionByChat.get(chatSessionId);
if (!cliSessionId) throw new Error(`No live CLI session for chat ${chatSessionId}`);
// Persist the user's message immediately (redacted — users can paste tokens too).
await this.store.addMessage(chatSessionId, {
role: "user",
content: redactSecrets(text),
metadata: { source: "cli-agent", origin: "composer" },
});
if (this.isBusy(cliSessionId)) {
this.enqueue(chatSessionId, text);
return "queued";
}
await this.manager.inject(cliSessionId, text);
return "sent";
}
/**
* Authoritative busy check: re-reads the session record from the manager/store
* so flush decisions never trust a stale SSE/cached `isGenerating` flag.
*/
private isBusy(cliSessionId: string): boolean {
const record = this.manager.getSession(cliSessionId);
if (!record) return false;
return BUSY_STATES.has(record.agentState);
}
private enqueue(chatSessionId: string, text: string): void {
const q = this.queue.get(chatSessionId) ?? [];
q.push(text);
this.queue.set(chatSessionId, q);
}
/** Number of composer messages currently queued for a chat (UI indicator). */
queuedCount(chatSessionId: string): number {
return this.queue.get(chatSessionId)?.length ?? 0;
}
/**
* Attempt to flush one queued composer message. Called when the session
* reports `done`. Re-fetches authoritative state before injecting — if the
* session turned busy again between the SSE event and this call, the flush
* is skipped and the message stays queued (the stale-isGenerating learning).
*/
async flushNext(chatSessionId: string): Promise<boolean> {
const cliSessionId = this.cliSessionByChat.get(chatSessionId);
if (!cliSessionId) return false;
const q = this.queue.get(chatSessionId);
if (!q || q.length === 0) return false;
// Authoritative re-fetch — do NOT trust a cached/streamed flag here.
if (this.isBusy(cliSessionId)) return false;
const text = q.shift()!;
if (q.length === 0) this.queue.delete(chatSessionId);
await this.manager.inject(cliSessionId, text);
return true;
}
/**
* Map a sanitized adapter telemetry event to transcript persistence.
*
* Granularity (KTD): only user / assistant / tool-summary land in
* chat_messages. `toolActivity`, `outputProgress`, and `idle` are terminal
* noise and are dropped here. `redactSecrets` runs on all persisted text.
*
* - `busy` → starts a new assistant turn (flushes any prior buffer).
* - `transcript` (role assistant or unspecified) → accumulates assistant text.
* - `transcript` (role user) → a user-echo turn (rare; adapters that surface it).
* - `transcript` with `toolSummary` → a single tool-summary row (no raw noise).
* - `done` → flushes the accumulated assistant turn, then tries a queue flush.
*
* Returns the chat_messages rows it created (for tests / SSE fan-out is the
* store's responsibility via `chat:message:added`).
*/
async handleTelemetry(
chatSessionId: string,
event: ChatTelemetryEvent,
): Promise<ChatMessage[]> {
const created: ChatMessage[] = [];
// Persist the native session id for resume the first time we learn it.
if (event.nativeSessionId) {
const chat = await this.store.getSession(chatSessionId);
if (chat && chat.cliSessionFile !== event.nativeSessionId) {
// Reuse cliSessionFile column as the native-session linkage (KTD:
// cliSessionFile-style column or session metadata). setCliSessionFile is
// internal plumbing; we route through the public setter on the runner's
// store slice when available, else fall through.
await (this.store as { setCliSessionFile?: (id: string, v: string) => Promise<void> | void }).setCliSessionFile?.(
chatSessionId,
event.nativeSessionId,
);
}
}
switch (event.kind) {
case "busy": {
// New assistant turn begins — flush any stale buffer defensively.
await this.flushAssistantBuffer(chatSessionId, created);
this.assistantBuffer.set(chatSessionId, "");
break;
}
case "transcript": {
if (event.toolSummary) {
// One readable tool-summary row. Raw per-call tool noise never reaches here.
const row = await this.store.addMessage(chatSessionId, {
role: "assistant",
content: redactSecrets(event.toolSummary),
metadata: { source: "cli-agent", kind: "tool-summary" },
});
created.push(row);
break;
}
const text = event.text ?? "";
if (event.role === "user") {
// Adapter-surfaced user echo — persist as a user row (deduped by caller).
const row = await this.store.addMessage(chatSessionId, {
role: "user",
content: redactSecrets(text),
metadata: { source: "cli-agent", origin: "transcript" },
});
created.push(row);
break;
}
// Default: assistant transcript text — accumulate across chunks.
const buf = this.assistantBuffer.get(chatSessionId) ?? "";
this.assistantBuffer.set(chatSessionId, buf + text);
break;
}
case "done": {
await this.flushAssistantBuffer(chatSessionId, created);
// Session idle → attempt to flush one queued composer message.
await this.flushNext(chatSessionId);
break;
}
// Terminal-only noise — intentionally NOT persisted to the transcript.
case "toolActivity":
case "outputProgress":
case "idle":
case "sessionStart":
case "waitingOnInput":
break;
}
return created;
}
/** Persist the accumulated assistant turn as one row, if non-empty. */
private async flushAssistantBuffer(chatSessionId: string, into: ChatMessage[]): Promise<void> {
const buf = this.assistantBuffer.get(chatSessionId);
if (buf == null) return;
this.assistantBuffer.delete(chatSessionId);
const trimmed = buf.trim();
if (trimmed.length === 0) return;
const row = await this.store.addMessage(chatSessionId, {
role: "assistant",
content: redactSecrets(trimmed),
metadata: { source: "cli-agent" },
});
into.push(row);
}
}