1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
|
# Research: Claude Flow Architecture
## Existing Codebase Analysis
### Template Structure
The starting point is a minimal Electron + Vite + React + better-sqlite3 template:
```
minimal-electron-vite-react-better-sqlite/
├── src/main/
│ ├── index.ts # Electron main process
│ └── preload.ts # IPC bridge (empty)
├── renderer/
│ ├── index.html # Entry HTML
│ └── src/
│ └── main.tsx # React entry ("hi")
├── package.json
├── tsconfig.json
└── vite.config.ts
```
### Key Patterns in Template
**Main Process (`src/main/index.ts`):**
- Uses `app.isPackaged` for dev/prod detection
- Database stored in `app.getPath('userData')` — correct for Electron apps
- Uses WAL mode for SQLite (`journal_mode = WAL`)
- Window created with `contextIsolation: true`, `nodeIntegration: false` — secure defaults
- Preload script path: `path.join(__dirname, 'preload.js')`
**Vite Config:**
- Root is `renderer/` directory
- Base is `./` for file:// loads in production
- Dev server on port 5173 with `strictPort: true`
- Output to `renderer/dist`
**Build/Dev Scripts:**
- `npm run dev` — concurrent Vite + TypeScript watch + Electron
- Uses `wait-on tcp:5173` to wait for Vite before launching Electron
- `@electron/rebuild` handles native module rebuilding
### What's Missing (We Need to Build)
1. IPC handlers for renderer → main communication
2. Proper database layer with migrations
3. React components and state management
4. Claude integration
5. Workflow state machine
---
## Claude Agent SDK Research
### Package Information
The SDK has been renamed from "Claude Code SDK" to "Claude Agent SDK".
**NPM Package:** `@anthropic-ai/claude-agent-sdk`
**Installation:**
```bash
npm install @anthropic-ai/claude-agent-sdk
```
**Authentication:**
- Set `ANTHROPIC_API_KEY` environment variable
- Also supports Bedrock, Vertex AI, Azure via environment flags
### Core API: `query()`
The primary function returns an async generator that streams messages:
```typescript
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Find and fix the bug in auth.py",
options: {
allowedTools: ["Read", "Edit", "Bash"],
permissionMode: "acceptEdits",
cwd: "/path/to/project"
}
})) {
console.log(message);
}
```
### Built-in Tools
| Tool | Purpose |
|------|---------|
| **Read** | Read files (text, images, PDFs, notebooks) |
| **Write** | Create/overwrite files |
| **Edit** | Precise string replacements |
| **Bash** | Run terminal commands |
| **Glob** | Find files by pattern |
| **Grep** | Search file contents with regex |
| **WebSearch** | Search the web |
| **WebFetch** | Fetch/parse web pages |
| **Task** | Spawn subagents |
### Permission Modes
| Mode | Behavior |
|------|----------|
| `default` | Standard permissions, may prompt |
| `acceptEdits` | Auto-approve file edits |
| `bypassPermissions` | Allow everything (dangerous) |
| `plan` | Planning only, no execution |
**Critical for our workflow:**
- **Research/Plan/Annotate phases**: Use `plan` mode or restrict `allowedTools` to read-only
- **Implement phase**: Use `acceptEdits` or `bypassPermissions`
### System Prompts
Can be customized via options:
```typescript
options: {
systemPrompt: "You are in RESEARCH mode. Read files deeply, write findings to research.md. DO NOT modify any source files.",
// OR use preset with append:
systemPrompt: {
type: "preset",
preset: "claude_code",
append: "Additional instructions here..."
}
}
```
### Session Management
Sessions can be resumed using session IDs:
```typescript
// First query captures session ID
let sessionId: string;
for await (const message of query({ prompt: "Read auth module" })) {
if (message.type === "system" && message.subtype === "init") {
sessionId = message.session_id;
}
}
// Resume later with full context
for await (const message of query({
prompt: "Now find all places that call it",
options: { resume: sessionId }
})) {
// Claude remembers the previous conversation
}
```
**Key insight:** Sessions persist to disk by default. We can store the session ID in SQLite and resume later.
### Hooks
Hooks intercept agent behavior at key points:
```typescript
import { query, HookCallback, PreToolUseHookInput } from "@anthropic-ai/claude-agent-sdk";
const blockWrites: HookCallback = async (input, toolUseID, { signal }) => {
const preInput = input as PreToolUseHookInput;
if (["Write", "Edit"].includes(preInput.tool_name)) {
return {
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: "In planning mode - no code changes allowed"
}
};
}
return {};
};
for await (const message of query({
prompt: "...",
options: {
hooks: {
PreToolUse: [{ matcher: "Write|Edit", hooks: [blockWrites] }]
}
}
})) { ... }
```
**Available hook events:**
- `PreToolUse` — Before tool executes (can block/modify)
- `PostToolUse` — After tool executes (can log/transform)
- `Stop` — Agent execution ending
- `SessionStart` / `SessionEnd` — Session lifecycle
- `SubagentStart` / `SubagentStop` — Subagent lifecycle
### Message Types
The query yields different message types:
```typescript
type SDKMessage =
| SDKAssistantMessage // Claude's response (includes tool_use)
| SDKUserMessage // User input
| SDKResultMessage // Final result with usage stats
| SDKSystemMessage // Init message with session_id, tools, etc.
| SDKPartialMessage // Streaming chunks (if enabled)
| SDKStatusMessage // Status updates
| ...
```
**SDKResultMessage** contains:
- `result` — Final text output
- `total_cost_usd` — API cost
- `usage` — Token counts
- `duration_ms` — Total time
- `num_turns` — Conversation turns
### Query Object Methods
The query object has methods for control:
```typescript
const q = query({ prompt: "...", options: { ... } });
// Change settings mid-session
await q.setPermissionMode("acceptEdits");
await q.setModel("opus");
// Get session info
const init = await q.initializationResult();
const commands = await q.supportedCommands();
const models = await q.supportedModels();
// Interrupt/cancel
await q.interrupt();
q.close();
```
---
## Architecture Decisions
### Phase Enforcement Strategy
We have two complementary approaches:
**1. Permission Mode + Allowed Tools:**
```typescript
const phaseConfig = {
research: {
permissionMode: "plan",
allowedTools: ["Read", "Glob", "Grep", "WebSearch", "WebFetch"],
systemPrompt: "You are in RESEARCH mode..."
},
plan: {
permissionMode: "plan",
allowedTools: ["Read", "Glob", "Grep", "Write"], // Write only for plan.md
systemPrompt: "You are in PLANNING mode..."
},
annotate: {
permissionMode: "plan",
allowedTools: ["Read", "Write"], // Only update plan.md
systemPrompt: "You are in ANNOTATION mode..."
},
implement: {
permissionMode: "acceptEdits",
allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"],
systemPrompt: "You are in IMPLEMENTATION mode..."
}
};
```
**2. Hooks for Fine-Grained Control:**
```typescript
const enforcePhaseHook: HookCallback = async (input, toolUseID, { signal }) => {
const { tool_name, tool_input } = input as PreToolUseHookInput;
const phase = getCurrentPhase(); // From app state
if (phase !== "implement" && ["Write", "Edit"].includes(tool_name)) {
const filePath = (tool_input as any).file_path;
// Allow only plan.md/research.md in non-implement phases
if (!filePath.endsWith("plan.md") && !filePath.endsWith("research.md")) {
return {
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: `Cannot modify ${filePath} in ${phase} phase`
}
};
}
}
return {};
};
```
### Session Persistence
**Option A: Use SDK's built-in session persistence**
- Sessions saved to disk automatically
- Store session ID in SQLite
- Resume with `options: { resume: sessionId }`
- Pro: Simpler, full context preserved
- Con: Less control over what's stored
**Option B: Store messages in SQLite ourselves**
- Store each message in our database
- Reconstruct context when resuming
- Pro: Full control, searchable history
- Con: More complex, may lose SDK internal state
**Recommendation:** Use **Option A** (SDK persistence) with session ID in SQLite. We can still store messages for display/search, but rely on SDK for actual context.
### Artifact Management
The blog workflow uses `research.md` and `plan.md` as persistent artifacts.
**Options:**
1. **Store in SQLite** — Searchable, version history, but not editable externally
2. **Store as files in project** — Visible in git, editable in any editor
3. **Both** — Files as source of truth, sync to SQLite for search
**Recommendation:** Store as **files in the project directory** (e.g., `.claude-flow/research.md`, `.claude-flow/plan.md`). This matches the blog workflow where the human edits the plan.md directly.
### IPC Architecture
Electron requires IPC for renderer ↔ main communication:
```typescript
// preload.ts
import { contextBridge, ipcRenderer } from "electron";
contextBridge.exposeInMainWorld("api", {
// Projects
listProjects: () => ipcRenderer.invoke("projects:list"),
createProject: (data) => ipcRenderer.invoke("projects:create", data),
// Sessions
listSessions: (projectId) => ipcRenderer.invoke("sessions:list", projectId),
createSession: (data) => ipcRenderer.invoke("sessions:create", data),
// Claude
sendMessage: (sessionId, message) => ipcRenderer.invoke("claude:send", sessionId, message),
onMessage: (callback) => ipcRenderer.on("claude:message", callback),
setPhase: (sessionId, phase) => ipcRenderer.invoke("claude:setPhase", sessionId, phase),
});
```
---
## Open Questions Resolved
### 1. Claude Code SDK vs CLI
**Answer:** Use the SDK (`@anthropic-ai/claude-agent-sdk`). It provides:
- Programmatic control via TypeScript
- Hooks for intercepting behavior
- Session management
- Streaming messages
### 2. Artifact Storage
**Answer:** Store as files in project directory (`.claude-flow/`) for:
- Editability in any editor (VSCode, etc.)
- Git visibility
- Matches the blog workflow
### 3. Session Context / Compaction
**Answer:** Use SDK's built-in session persistence:
- Store session ID in SQLite
- Resume with `options: { resume: sessionId }`
- SDK handles context compaction automatically
### 4. Multi-file Editing
**Answer:** The SDK handles this natively via the Edit/Write tools. The plan.md should list all files to be modified, and Claude executes them in order during implementation.
---
## Dependencies to Add
```json
{
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "latest",
"better-sqlite3": "12.2.0",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"uuid": "^11.0.0"
},
"devDependencies": {
"@types/uuid": "^10.0.0"
// ... existing devDeps
}
}
```
---
## Summary
The Claude Agent SDK is well-suited for building Claude Flow:
1. **Session management** — Built-in persistence, resume capability
2. **Permission modes** — `plan` mode prevents execution, `acceptEdits` for implementation
3. **Hooks** — Fine-grained control over what Claude can do
4. **Streaming** — Real-time message display in UI
5. **System prompts** — Customizable per phase
The main work is:
- Building the Electron app shell (IPC, windows)
- SQLite layer for projects/sessions
- React UI for chat, artifacts, phase controls
- Wiring everything together with the SDK
|