From 332e5cec2992fefb302251962a3ceca38437a110 Mon Sep 17 00:00:00 2001 From: Clawd Date: Sat, 28 Feb 2026 07:26:43 -0800 Subject: Phase 2: Claude integration layer - Add @anthropic-ai/claude-agent-sdk dependency - Implement src/main/claude/phases.ts with phase configs (research/plan/implement) - Implement src/main/claude/index.ts with SDK wrapper - query() integration with session management - Session resume support - Artifact read/write utilities - Phase advancement logic --- src/main/claude/index.ts | 142 ++++++++++++++++++++++++++++++++++++++++++++++ src/main/claude/phases.ts | 104 +++++++++++++++++++++++++++++++++ src/main/db/index.ts | 31 ++++++++++ src/main/db/projects.ts | 38 +++++++++++++ src/main/db/schema.ts | 35 ++++++++++++ src/main/db/sessions.ts | 106 ++++++++++++++++++++++++++++++++++ 6 files changed, 456 insertions(+) create mode 100644 src/main/claude/index.ts create mode 100644 src/main/claude/phases.ts create mode 100644 src/main/db/index.ts create mode 100644 src/main/db/projects.ts create mode 100644 src/main/db/schema.ts create mode 100644 src/main/db/sessions.ts (limited to 'src') diff --git a/src/main/claude/index.ts b/src/main/claude/index.ts new file mode 100644 index 0000000..34a914e --- /dev/null +++ b/src/main/claude/index.ts @@ -0,0 +1,142 @@ +import { query, type SDKMessage, type Query } from "@anthropic-ai/claude-agent-sdk"; +import type { Session } from "../db/sessions"; +import { getPhaseConfig, getNextPhase, getArtifactFilename } from "./phases"; +import type { Phase, UserPermissionMode } from "./phases"; +import { getProject } from "../db/projects"; +import { updateSession } from "../db/sessions"; +import fs from "node:fs"; +import path from "node:path"; + +// Track active queries by session ID +const activeQueries = new Map(); + +function ensureArtifactDir(projectPath: string): void { + const dir = path.join(projectPath, ".claude-flow"); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } +} + +export interface SendMessageOptions { + session: Session; + message: string; + onMessage: (msg: SDKMessage) => void; +} + +export async function sendMessage({ + session, + message, + onMessage, +}: SendMessageOptions): Promise { + const project = getProject(session.project_id); + if (!project) throw new Error("Project not found"); + + ensureArtifactDir(project.path); + + const phaseConfig = getPhaseConfig( + session.phase as Phase, + session.permission_mode as UserPermissionMode + ); + + const q = query({ + prompt: message, + options: { + cwd: project.path, + resume: session.claude_session_id ?? undefined, + tools: phaseConfig.tools, + permissionMode: phaseConfig.permissionMode, + // Add system prompt via extraArgs since there's no direct option + extraArgs: { + "system-prompt": phaseConfig.systemPrompt, + }, + }, + }); + + activeQueries.set(session.id, q); + + try { + for await (const msg of q) { + // Capture session ID from init message + if (msg.type === "system" && msg.subtype === "init") { + if (!session.claude_session_id) { + updateSession(session.id, { claude_session_id: msg.session_id }); + } + } + onMessage(msg); + } + } finally { + activeQueries.delete(session.id); + } +} + +export function interruptSession(sessionId: string): void { + const q = activeQueries.get(sessionId); + if (q) { + q.close(); + activeQueries.delete(sessionId); + } +} + +/** + * Trigger a review: Claude reads the document and addresses user annotations + */ +export async function triggerReview( + session: Session, + onMessage: (msg: SDKMessage) => void +): Promise { + const docName = getArtifactFilename(session.phase as Phase); + const message = `I've updated .claude-flow/${docName} with annotations. Read the file, find all my inline notes (marked with // REVIEW:, // NOTE:, TODO:, or similar), address each one, and update the document accordingly. Do not implement anything yet.`; + + await sendMessage({ session, message, onMessage }); +} + +/** + * Advance to the next phase + */ +export function advancePhase(session: Session): Phase | null { + const nextPhase = getNextPhase(session.phase as Phase); + if (nextPhase) { + updateSession(session.id, { phase: nextPhase }); + } + return nextPhase; +} + +/** + * Read an artifact file from the project's .claude-flow directory + */ +export function readArtifact( + projectPath: string, + filename: string +): string | null { + const filePath = path.join(projectPath, ".claude-flow", filename); + if (fs.existsSync(filePath)) { + return fs.readFileSync(filePath, "utf-8"); + } + return null; +} + +/** + * Write an artifact file to the project's .claude-flow directory + */ +export function writeArtifact( + projectPath: string, + filename: string, + content: string +): void { + const dir = path.join(projectPath, ".claude-flow"); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + fs.writeFileSync(path.join(dir, filename), content, "utf-8"); +} + +/** + * Get the initial message for a phase + */ +export function getPhaseInitialMessage(phase: Phase): string { + return getPhaseConfig(phase).initialMessage; +} + +// Re-export types +export type { SDKMessage } from "@anthropic-ai/claude-agent-sdk"; +export type { Phase, UserPermissionMode } from "./phases"; diff --git a/src/main/claude/phases.ts b/src/main/claude/phases.ts new file mode 100644 index 0000000..d503f3a --- /dev/null +++ b/src/main/claude/phases.ts @@ -0,0 +1,104 @@ +import type { PermissionMode } from "@anthropic-ai/claude-agent-sdk"; + +export type Phase = "research" | "plan" | "implement"; +export type UserPermissionMode = "acceptEdits" | "bypassPermissions"; + +export interface PhaseConfig { + systemPrompt: string; + tools: string[]; + permissionMode: PermissionMode; + initialMessage: string; +} + +export const phaseConfigs: Record = { + research: { + permissionMode: "plan", + tools: ["Read", "Glob", "Grep", "Bash", "Write"], + initialMessage: + "What areas of the codebase should I research? What are you trying to build?", + systemPrompt: `You are in RESEARCH mode. + +Your job is to deeply understand the codebase before any changes are made. + +When the user tells you what to research: +1. Read files thoroughly — understand all intricacies +2. Write your findings to .claude-flow/research.md +3. Format it as clear, readable markdown + +Rules: +- DO NOT make any code changes +- DO NOT modify any files except .claude-flow/research.md +- Be thorough — surface-level reading is not acceptable + +When the user clicks "Review", read .claude-flow/research.md for their annotations and update accordingly. +When the user clicks "Submit", they're ready to move to planning.`, + }, + + plan: { + permissionMode: "plan", + tools: ["Read", "Glob", "Grep", "Write"], + initialMessage: + "I'll create a detailed implementation plan based on my research. Give me a moment...", + systemPrompt: `You are in PLANNING mode. + +Based on the research in .claude-flow/research.md, write a detailed implementation plan. + +Write the plan to .claude-flow/plan.md with: +- Detailed explanation of the approach +- Specific code snippets showing proposed changes +- File paths that will be modified +- Trade-offs and considerations +- A granular TODO list with checkboxes + +Rules: +- DO NOT implement anything +- DO NOT modify any source files +- Only write to .claude-flow/plan.md + +The plan should be detailed enough that implementation becomes mechanical. + +When the user clicks "Review", read .claude-flow/plan.md for their annotations and update accordingly. +When the user clicks "Submit", begin implementation.`, + }, + + implement: { + permissionMode: "acceptEdits", + tools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"], + initialMessage: + "Starting implementation. I'll follow the plan exactly and mark tasks complete as I go.", + systemPrompt: `You are in IMPLEMENTATION mode. The plan has been approved. + +Read .claude-flow/plan.md and execute it: +- Follow the plan exactly +- Mark tasks complete (- [x]) as you finish them +- Run typecheck/lint continuously if available +- Do not add unnecessary comments +- Do not stop until all tasks are complete + +If you encounter issues not covered by the plan, stop and ask.`, + }, +}; + +export function getPhaseConfig( + phase: Phase, + userPermissionMode?: UserPermissionMode +): PhaseConfig { + const config = { ...phaseConfigs[phase] }; + if (phase === "implement" && userPermissionMode) { + config.permissionMode = userPermissionMode; + } + return config; +} + +export function getNextPhase(phase: Phase): Phase | null { + const transitions: Record = { + research: "plan", + plan: "implement", + implement: null, + }; + return transitions[phase]; +} + +export function getArtifactFilename(phase: Phase): string { + return phase === "research" ? "research.md" : "plan.md"; +} diff --git a/src/main/db/index.ts b/src/main/db/index.ts new file mode 100644 index 0000000..a77cdd4 --- /dev/null +++ b/src/main/db/index.ts @@ -0,0 +1,31 @@ +import Database from "better-sqlite3"; +import { app } from "electron"; +import path from "node:path"; +import fs from "node:fs"; +import { initSchema } from "./schema"; + +let db: Database.Database | null = null; + +export function getDb(): Database.Database { + if (db) return db; + + const dbDir = app.getPath("userData"); + if (!fs.existsSync(dbDir)) { + fs.mkdirSync(dbDir, { recursive: true }); + } + + const dbPath = path.join(dbDir, "claude-flow.db"); + db = new Database(dbPath); + db.pragma("journal_mode = WAL"); + db.pragma("foreign_keys = ON"); + + initSchema(db); + return db; +} + +export function closeDb() { + if (db) { + db.close(); + db = null; + } +} diff --git a/src/main/db/projects.ts b/src/main/db/projects.ts new file mode 100644 index 0000000..88ef2f6 --- /dev/null +++ b/src/main/db/projects.ts @@ -0,0 +1,38 @@ +import { getDb } from "./index"; +import { v4 as uuid } from "uuid"; + +export interface Project { + id: string; + name: string; + path: string; + created_at: number; + updated_at: number; +} + +export function listProjects(): Project[] { + return getDb() + .prepare("SELECT * FROM projects ORDER BY updated_at DESC") + .all() as Project[]; +} + +export function getProject(id: string): Project | undefined { + return getDb() + .prepare("SELECT * FROM projects WHERE id = ?") + .get(id) as Project | undefined; +} + +export function createProject(name: string, projectPath: string): Project { + const db = getDb(); + const id = uuid(); + const now = Math.floor(Date.now() / 1000); + + db.prepare( + "INSERT INTO projects (id, name, path, created_at, updated_at) VALUES (?, ?, ?, ?, ?)" + ).run(id, name, projectPath, now, now); + + return { id, name, path: projectPath, created_at: now, updated_at: now }; +} + +export function deleteProject(id: string): void { + getDb().prepare("DELETE FROM projects WHERE id = ?").run(id); +} diff --git a/src/main/db/schema.ts b/src/main/db/schema.ts new file mode 100644 index 0000000..c2093f9 --- /dev/null +++ b/src/main/db/schema.ts @@ -0,0 +1,35 @@ +import Database from "better-sqlite3"; + +export function initSchema(db: Database.Database) { + db.exec(` + CREATE TABLE IF NOT EXISTS projects ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + path TEXT NOT NULL, + created_at INTEGER NOT NULL DEFAULT (unixepoch()), + updated_at INTEGER NOT NULL DEFAULT (unixepoch()) + ); + + CREATE TABLE IF NOT EXISTS sessions ( + id TEXT PRIMARY KEY, + project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE, + name TEXT NOT NULL, + phase TEXT NOT NULL DEFAULT 'research', + claude_session_id TEXT, + permission_mode TEXT NOT NULL DEFAULT 'acceptEdits', + created_at INTEGER NOT NULL DEFAULT (unixepoch()), + updated_at INTEGER NOT NULL DEFAULT (unixepoch()) + ); + + CREATE TABLE IF NOT EXISTS messages ( + id TEXT PRIMARY KEY, + session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, + role TEXT NOT NULL, + content TEXT NOT NULL, + created_at INTEGER NOT NULL DEFAULT (unixepoch()) + ); + + CREATE INDEX IF NOT EXISTS idx_sessions_project ON sessions(project_id); + CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id); + `); +} diff --git a/src/main/db/sessions.ts b/src/main/db/sessions.ts new file mode 100644 index 0000000..684bb9e --- /dev/null +++ b/src/main/db/sessions.ts @@ -0,0 +1,106 @@ +import { getDb } from "./index"; +import { v4 as uuid } from "uuid"; + +export type Phase = "research" | "plan" | "implement"; +export type PermissionMode = "acceptEdits" | "bypassPermissions"; + +export interface Session { + id: string; + project_id: string; + name: string; + phase: Phase; + claude_session_id: string | null; + permission_mode: PermissionMode; + created_at: number; + updated_at: number; +} + +export interface Message { + id: string; + session_id: string; + role: "user" | "assistant"; + content: string; + created_at: number; +} + +export function listSessions(projectId: string): Session[] { + return getDb() + .prepare("SELECT * FROM sessions WHERE project_id = ? ORDER BY updated_at DESC") + .all(projectId) as Session[]; +} + +export function getSession(id: string): Session | undefined { + return getDb() + .prepare("SELECT * FROM sessions WHERE id = ?") + .get(id) as Session | undefined; +} + +export function createSession(projectId: string, name: string): Session { + const db = getDb(); + const id = uuid(); + const now = Math.floor(Date.now() / 1000); + + db.prepare( + `INSERT INTO sessions (id, project_id, name, phase, permission_mode, created_at, updated_at) + VALUES (?, ?, ?, 'research', 'acceptEdits', ?, ?)` + ).run(id, projectId, name, now, now); + + return { + id, + project_id: projectId, + name, + phase: "research", + claude_session_id: null, + permission_mode: "acceptEdits", + created_at: now, + updated_at: now, + }; +} + +export function updateSession( + id: string, + updates: Partial> +): void { + const db = getDb(); + const sets: string[] = []; + const values: any[] = []; + + for (const [key, value] of Object.entries(updates)) { + if (value !== undefined) { + sets.push(`${key} = ?`); + values.push(value); + } + } + + if (sets.length > 0) { + sets.push("updated_at = ?"); + values.push(Math.floor(Date.now() / 1000)); + values.push(id); + db.prepare(`UPDATE sessions SET ${sets.join(", ")} WHERE id = ?`).run(...values); + } +} + +export function deleteSession(id: string): void { + getDb().prepare("DELETE FROM sessions WHERE id = ?").run(id); +} + +// Messages +export function listMessages(sessionId: string): Message[] { + return getDb() + .prepare("SELECT * FROM messages WHERE session_id = ? ORDER BY created_at ASC") + .all(sessionId) as Message[]; +} + +export function addMessage(sessionId: string, role: Message["role"], content: string): Message { + const db = getDb(); + const id = uuid(); + const now = Math.floor(Date.now() / 1000); + + db.prepare( + "INSERT INTO messages (id, session_id, role, content, created_at) VALUES (?, ?, ?, ?, ?)" + ).run(id, sessionId, role, content, now); + + db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, sessionId); + + return { id, session_id: sessionId, role, content, created_at: now }; +} -- cgit v1.2.3