feat(coder): guard session delete against worktree work loss

Deleting a BooChat session CASCADE-wipes its session_worktrees row, which would silently orphan uncommitted/unpushed/unmerged work in the worktree. Add a pre-DELETE gate: the server reads session_worktrees from the shared DB first (no row = chat-only session = delete immediately, zero round-trip), and for worktree-backed sessions calls a new BooCoder endpoint that runs git on the host (only the host systemd service can see /tmp/booworktrees). checkWorktreeWorkAtRisk reports dirty/unpushed/unmerged via the audited hostExec+shellEscape path; default branch is detected from refs/remotes/origin/HEAD (not the worktree's own branch), never hardcoded. Any at-risk worktree returns 409 with per-worktree RiskReport[]; force=true bypasses the check entirely. Fail-closed: coder unreachable/errored also blocks (force still escapes). The sidebar renders a block dialog distinguishing work-at-risk (Commit/Stash/Force) from couldn't-verify (Cancel/Force only); stash uses -u and re-blocks on remaining commits with an explanatory message. Commit never auto-commits — it routes the user to the session.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-30 22:01:25 +00:00
parent 937920df06
commit 3a26563be2
8 changed files with 448 additions and 9 deletions

View File

@@ -3,7 +3,7 @@ import { z } from 'zod';
import type { Sql } from '../db.js';
import type { Config } from '../config.js';
import type { Broker } from '../services/broker.js';
import type { Session } from '../types/api.js';
import type { Session, WorktreeRiskReport } from '../types/api.js';
import { getSetting } from './settings.js';
const CreateBody = z.object({
@@ -426,10 +426,53 @@ export function registerSessionRoutes(
}
);
app.delete<{ Params: { id: string } }>(
app.delete<{ Params: { id: string }; Querystring: { force?: string } }>(
'/api/sessions/:id',
async (req, reply) => {
const id = req.params.id;
const force = req.query.force === 'true' || req.query.force === '1';
// Session-delete work-loss guard. CASCADE on session_worktrees means the
// DELETE below auto-wipes the worktree row, so the safety check MUST run
// BEFORE it (paths read while the row still exists, pre-CASCADE).
//
// Optimization: read session_worktrees from our own (shared) DB first.
// No row => chat-only session => nothing on disk => delete immediately,
// zero round-trip. Only worktree-backed sessions pay the host git check.
if (!force) {
const worktrees = await sql<{ worktree_path: string }[]>`
SELECT worktree_path FROM session_worktrees WHERE session_id = ${id}
`;
if (worktrees.length > 0) {
// Worktree dirs live on the host; only BooCoder can run git on them.
const origin = process.env.BOOCODER_URL ?? 'http://boocoder:3000';
let reports: WorktreeRiskReport[];
try {
const res = await fetch(`${origin}/api/sessions/${id}/worktree-risk`);
if (!res.ok) {
// Fail-closed: can't verify => don't risk silent loss. Force escapes.
reply.code(409);
return {
error: 'could not verify worktree safety (BooCoder check failed). Use force to delete anyway.',
reports: [] as WorktreeRiskReport[],
};
}
reports = ((await res.json()) as { reports?: WorktreeRiskReport[] }).reports ?? [];
} catch {
// Fail-closed: BooCoder unreachable. Force bypasses this path entirely.
reply.code(409);
return {
error: 'BooCoder unreachable; cannot verify worktree safety. Use force to delete anyway.',
reports: [] as WorktreeRiskReport[],
};
}
if (reports.some((r) => r.atRisk)) {
reply.code(409);
return { error: 'This session has work at risk in its worktree.', reports };
}
}
}
const deleted = await sql<{ project_id: string }[]>`
DELETE FROM sessions WHERE id = ${id} RETURNING project_id
`;

View File

@@ -25,6 +25,20 @@ export interface AvailableProject {
export type SessionStatus = 'open' | 'archived';
// Session-delete work-loss guard. Returned (as `reports`) in the 409 body when
// a delete is blocked because the session's worktree holds work at risk. The
// shape is produced by BooCoder's checkWorktreeWorkAtRisk and passed through
// verbatim; mirrored byte-for-byte in apps/web/src/api/types.ts for the dialog.
export interface WorktreeRiskReport {
worktreePath: string;
branch: string;
dirty: boolean;
unpushed: number; // commits ahead of upstream, or -1 if no upstream
unmerged: number; // commits not in the project default branch
atRisk: boolean;
error?: string;
}
export interface Session {
id: string;
project_id: string;