devbrief-mcp 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +100 -2
  2. package/dist/cli.js +195 -0
  3. package/dist/http-server.js +369 -0
  4. package/dist/mcp-server.js +735 -0
  5. package/dist/seed.js +343 -0
  6. package/dist/store.js +173 -0
  7. package/dist/templates.js +87 -0
  8. package/dist/types.js +1 -0
  9. package/dist/web/assets/abnfDiagram-VCTEODGH-B2j10h8Z.js +1 -0
  10. package/dist/web/assets/architectureDiagram-5GKGNRK7-C-97t_WC.js +36 -0
  11. package/dist/web/assets/blockDiagram-I7D4REHJ-B1wmSvJ-.js +129 -0
  12. package/dist/web/assets/c4Diagram-7LVT6UL2-BuZ8Dzzj.js +38 -0
  13. package/dist/web/assets/channel-DGQoaVvy.js +1 -0
  14. package/dist/web/assets/chunk-2Q5K7J3B-Cz-oZyi0.js +1 -0
  15. package/dist/web/assets/chunk-5VM5RSS4-CHFUUttN.js +15 -0
  16. package/dist/web/assets/chunk-F27PBJKO-D1d230nE.js +1 -0
  17. package/dist/web/assets/chunk-IMKFNOWR-r6QAwJ0-.js +231 -0
  18. package/dist/web/assets/chunk-JWPE2WC7-8-XUMl1m.js +1 -0
  19. package/dist/web/assets/chunk-POPQ4Y6H-J55ju-YY.js +1 -0
  20. package/dist/web/assets/chunk-SVP7TREG-DsEkVYFO.js +88 -0
  21. package/dist/web/assets/chunk-TICWLB2K-B_QJFB3X.js +206 -0
  22. package/dist/web/assets/chunk-XXDRQBXY-CVRknODf.js +1 -0
  23. package/dist/web/assets/classDiagram-ZZMXUADV-ByRvOEx9.js +1 -0
  24. package/dist/web/assets/classDiagram-v2-VYDZK3BY-ByRvOEx9.js +1 -0
  25. package/dist/web/assets/cose-bilkent-JH36ORCC-DovNKgH7.js +1 -0
  26. package/dist/web/assets/cynefin-OW5HDTMX-4IjjtMsI.js +178 -0
  27. package/dist/web/assets/cynefinDiagram-5FMLGOSQ-CAIrugpJ.js +62 -0
  28. package/dist/web/assets/cytoscape.esm-Bw5aGq32.js +332 -0
  29. package/dist/web/assets/d3-scale-4DPf7zan.js +1 -0
  30. package/dist/web/assets/dagre-GXQ25YYZ-oCo1_CKk.js +4 -0
  31. package/dist/web/assets/diagram-S7CK7UJ4-vxgYHzMD.js +30 -0
  32. package/dist/web/assets/diagram-UQ7AKVKN-DGyJZedP.js +41 -0
  33. package/dist/web/assets/diagram-VSXAHHWV-Gtpn92yT.js +3 -0
  34. package/dist/web/assets/diagram-VX7I27RA-DWtLgOl5.js +24 -0
  35. package/dist/web/assets/diagram-Z3DM3KII-h8C5YYSs.js +24 -0
  36. package/dist/web/assets/ebnfDiagram-PWID7BFC-CXPuqK6Q.js +1 -0
  37. package/dist/web/assets/erDiagram-RLTQ6QDP-BEd3G-5B.js +99 -0
  38. package/dist/web/assets/flowDiagram-HODETNUW-DCoauWYX.js +168 -0
  39. package/dist/web/assets/ganttDiagram-EL5Y4UJY-BlSOsqZR.js +292 -0
  40. package/dist/web/assets/gitGraphDiagram-WWUBYQGX-C1Zsl4Vp.js +106 -0
  41. package/dist/web/assets/index-DyEXWSrB.js +527 -0
  42. package/dist/web/assets/index-DzwD7JbQ.css +1 -0
  43. package/dist/web/assets/infoDiagram-27XIBGKW-5b3qrK4l.js +2 -0
  44. package/dist/web/assets/ishikawaDiagram-5VMMS53U-e0QpYiRp.js +70 -0
  45. package/dist/web/assets/journeyDiagram-3NMN7TZE-DYNXpoSv.js +139 -0
  46. package/dist/web/assets/kanban-definition-UXKFOSKX-BUFsfQKA.js +89 -0
  47. package/dist/web/assets/katex-C5jXJg4s.js +257 -0
  48. package/dist/web/assets/layout-C-L2dpvG.js +1 -0
  49. package/dist/web/assets/mindmap-definition-YA3MSWOX-DzW4faO9.js +96 -0
  50. package/dist/web/assets/pegDiagram-XKGWAZYB-CivnBowC.js +1 -0
  51. package/dist/web/assets/pieDiagram-E7YTZNPT-nc4YfrSU.js +39 -0
  52. package/dist/web/assets/quadrantDiagram-AXDQQJYC-KgrALlVw.js +7 -0
  53. package/dist/web/assets/railroadDiagram-O6MQD6OU-DDnsxxdp.js +1 -0
  54. package/dist/web/assets/requirementDiagram-BXWQKSXE-DUoPfHSP.js +84 -0
  55. package/dist/web/assets/sankeyDiagram-P5KCCOFB-DZaK5328.js +40 -0
  56. package/dist/web/assets/sequenceDiagram-WJ2MYXX4-D68Zb3If.js +162 -0
  57. package/dist/web/assets/sizeCapture-INFHLROL-Byc4EKyy.js +1 -0
  58. package/dist/web/assets/stateDiagram-D77RDMKH-DDeKszRm.js +1 -0
  59. package/dist/web/assets/stateDiagram-v2-MP3YSRHH-83UQkfHN.js +1 -0
  60. package/dist/web/assets/swimlanes-42K2YHIH-BlCv9qMa.js +1 -0
  61. package/dist/web/assets/swimlanesDiagram-VR7AAH4N-DbVrA8C6.js +8 -0
  62. package/dist/web/assets/timeline-definition-24CTP7MA-Ck1DA4y7.js +120 -0
  63. package/dist/web/assets/vennDiagram-4TSXK5OY-CuQjE2nH.js +34 -0
  64. package/dist/web/assets/wardleyDiagram-VM6X3IG4-CjWAr9l-.js +78 -0
  65. package/dist/web/assets/xychartDiagram-S5SC5T6Z-CLcBeX5-.js +7 -0
  66. package/dist/web/index.html +13 -0
  67. package/dist/workspace.js +202 -0
  68. package/package.json +48 -4
package/README.md CHANGED
@@ -1,3 +1,101 @@
1
- # Temporary Holding Version
1
+ # DevBrief (`devbrief-mcp`)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Локальный MCP-управляемый workbench для разработки с ИИ-агентами (Cursor), который решает три главные проблемы современной разработки:
4
+ 1. **Порционное погружение в контекст задачи (Phase 0)** — карта на 1 экран, диаграммы AS-IS/TO-BE (Mermaid), пошаговый разбор как для новичка, интерактивный глоссарий, Blast Radius и инварианты.
5
+ 2. **Смысловое ревью кода (Decision-First Review)** — группировка изменений по риску, контрактам, БД, решениям агента и «переводу» незнакомого стека (например, C# → Python), вместо чтения 50 файлов по алфавиту.
6
+ 3. **Контроль регрессий и эвиденсы (Verification Pack)** — матрица проверок (новая фича + регрессии из Blast Radius), скриншоты «До/После», SQL/API-логи и предложения по обновлению живой документации.
7
+
8
+ **Ноль внешних API-ключей и облаков:** инструмент работает 100% локально. Весь интеллект (чтение монорепы, Azure DevOps, БД, генерация кода, запуск браузера) выполняется вашим агентом в Cursor через MCP.
9
+
10
+ ---
11
+
12
+ ## Быстрый старт
13
+
14
+ ### Установка глобально (после публикации в npm)
15
+ ```bash
16
+ npm install -g devbrief-mcp
17
+ ```
18
+
19
+ Или локально из исходников / `.tgz`:
20
+ ```bash
21
+ npm install
22
+ npm run build
23
+ npm link
24
+ ```
25
+
26
+ ### Подключение к монорепе в Cursor
27
+ В корне вашей монорепы (где лежат доки/спеки и папка `/repos/*`):
28
+ ```bash
29
+ devbrief init
30
+ ```
31
+ Команда создаст:
32
+ - `.cursor/rules/devbrief-workflow.mdc` — протокол работы агента (фазы, правила объяснения, сбор эвиденсов);
33
+ - добавит MCP-сервер `devbrief` (`command: "devbrief", args: ["mcp"]`) в `.cursor/mcp.json`.
34
+
35
+ После этого перезапустите Cursor (или перезагрузите MCP в **Settings → MCP**).
36
+
37
+ ### Посмотреть интерактивное демо (Python + C#)
38
+ ```bash
39
+ devbrief demo
40
+ ```
41
+ Откроет локальный Web UI (`http://127.0.0.1:4310`) с примером PBI на стыке Python и C#.
42
+
43
+ ---
44
+
45
+ ## Ежедневный рабочий цикл в Cursor
46
+
47
+ 1. **Погружение (до кода):**
48
+ > *"Начни PBI #12345 через devbrief — изучи доки в корне, затронутые сервисы в /repos и БД, сначала погрузи меня в контекст."*
49
+ - Открываете ссылку на Web UI, проходите шаги, кликаете незнакомые термины, жмёте **«Объясни проще»**, отвечаете на Open Questions, утверждаете инварианты.
50
+ - Нажимаете **«Промпт для Cursor»** в шапке UI и вставляете в чат — агент заберёт все вопросы/ответы через `devbrief_get_human_feedback`.
51
+
52
+ 2. **Смысловое ревью (после реализации):**
53
+ > *"Собери смысловое ревью по нашим изменениям в devbrief."*
54
+ - Смотрите только критичные контракты, БД, точки решений агента и перевод нового стека (бойлерплейт скрыт по умолчанию). Оставляете вердикты `Ок` / `Почему так?` / `Исправить`.
55
+
56
+ 3. **Регрессии и эвиденсы:**
57
+ > *"Подними сервисы, прогони фичу и регрессии из Blast Radius, приложи скриншоты и SQL-проверки в devbrief."*
58
+ - Проверяете визуальные эвиденсы «До/После» и подтверждаете обновления корневых доков.
59
+
60
+ ---
61
+
62
+ ## CLI команды
63
+
64
+ | Команда | Описание |
65
+ | --- | --- |
66
+ | `devbrief mcp [--port 4310]` | Запуск stdio MCP-сервера для Cursor (автоматически поднимает Web UI, если порт свободен) |
67
+ | `devbrief ui [--port 4310]` | Открыть локальный Web UI вручную |
68
+ | `devbrief init [dir]` | Создать Cursor Rules и прописать MCP в `.cursor/mcp.json` |
69
+ | `devbrief demo` | Создать демо-сессию (Python + C#) и открыть Web UI |
70
+ | `devbrief status` | Показать путь хранилища, статус сервера и список сессий |
71
+
72
+ Переменные окружения:
73
+ - `DEVBRIEF_PORT` — порт Web UI (по умолчанию `4310`).
74
+ - `DEVBRIEF_DATA_DIR` — директория хранения сессий и скриншотов (по умолчанию `~/.devbrief/data`).
75
+
76
+ ---
77
+
78
+ ## MCP-инструменты для внешних агентов
79
+
80
+ - **Сессии и монорепа:** `devbrief_scan_workspace`, `devbrief_git_diff_summary`, `devbrief_create_session`, `devbrief_list_sessions`, `devbrief_get_session`, `devbrief_update_status`
81
+ - **Погружение:** `devbrief_set_overview`, `devbrief_upsert_walkthrough`, `devbrief_upsert_glossary`, `devbrief_set_blast_radius`, `devbrief_upsert_open_questions`
82
+ - **Ревью:** `devbrief_publish_review`, `devbrief_resolve_review_card`
83
+ - **Проверки и эвиденсы:** `devbrief_set_verification_plan`, `devbrief_attach_evidence`, `devbrief_propose_doc_updates`
84
+ - **Синхронизация с человеком:** `devbrief_get_human_feedback`, `devbrief_reply_to_feedback`
85
+ - **MCP Prompts:** `start-pbi-onboarding`, `prepare-behavioral-review`, `run-regression-and-evidence`
86
+
87
+ ---
88
+
89
+ ## Публикация в npm
90
+
91
+ ```bash
92
+ npm login
93
+ # При необходимости смените name в package.json (например, @your-scope/devbrief-mcp)
94
+ npm publish --access public
95
+ ```
96
+ Или для переноса без публикации в публичный реестр:
97
+ ```bash
98
+ npm pack
99
+ # На удалённой машине:
100
+ npm install -g ./devbrief-mcp-0.1.0.tgz
101
+ ```
package/dist/cli.js ADDED
@@ -0,0 +1,195 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process';
3
+ import path from 'node:path';
4
+ import { SessionStore, resolveDataDir } from './store.js';
5
+ import { DEFAULT_PORT, isUiServerRunning, notifyExternalUiServer, startUiServer, } from './http-server.js';
6
+ import { runStdioMcpServer } from './mcp-server.js';
7
+ import { initCursorWorkspace } from './templates.js';
8
+ import { seedDemoSession } from './seed.js';
9
+ function parseArgs(argv) {
10
+ const args = argv.slice(2);
11
+ let command = 'help';
12
+ let port = DEFAULT_PORT;
13
+ let dataDir;
14
+ let noOpen = false;
15
+ let targetDir = process.cwd();
16
+ const positional = [];
17
+ for (let i = 0; i < args.length; i++) {
18
+ const a = args[i];
19
+ if (a === '--port' || a === '-p') {
20
+ port = Number(args[++i] || DEFAULT_PORT);
21
+ }
22
+ else if (a === '--data-dir' || a === '-d') {
23
+ dataDir = args[++i];
24
+ }
25
+ else if (a === '--no-open') {
26
+ noOpen = true;
27
+ }
28
+ else if (a === '--help' || a === '-h') {
29
+ command = 'help';
30
+ }
31
+ else if (!a.startsWith('-')) {
32
+ positional.push(a);
33
+ }
34
+ }
35
+ if (positional[0])
36
+ command = positional[0];
37
+ if (positional[1])
38
+ targetDir = path.resolve(positional[1]);
39
+ return { command, port, dataDir, noOpen, targetDir };
40
+ }
41
+ function openBrowser(url) {
42
+ try {
43
+ if (process.platform === 'win32') {
44
+ spawn('cmd', ['/c', 'start', '', url], { detached: true, stdio: 'ignore' }).unref();
45
+ }
46
+ else if (process.platform === 'darwin') {
47
+ spawn('open', [url], { detached: true, stdio: 'ignore' }).unref();
48
+ }
49
+ else {
50
+ spawn('xdg-open', [url], { detached: true, stdio: 'ignore' }).unref();
51
+ }
52
+ }
53
+ catch {
54
+ // non-fatal
55
+ }
56
+ }
57
+ function printHelp() {
58
+ console.log(`
59
+ devbrief — MCP-controlled local workbench for AI-assisted engineering
60
+
61
+ Usage:
62
+ devbrief mcp [--port 4310] [--data-dir <path>]
63
+ Run as stdio MCP server for Cursor (auto-starts local Web UI if not running).
64
+
65
+ devbrief ui [--port 4310] [--no-open] [--data-dir <path>]
66
+ Start the local Web UI server and open it in your browser.
67
+
68
+ devbrief init [workspace-dir]
69
+ Create .cursor/rules/devbrief-workflow.mdc and register "devbrief" in .cursor/mcp.json.
70
+
71
+ devbrief demo [--port 4310] [--no-open]
72
+ Seed a realistic Python + C# monorepo demo PBI session and launch the Web UI.
73
+
74
+ devbrief status [--port 4310] [--data-dir <path>]
75
+ Show storage path, UI server status, and active sessions.
76
+
77
+ Environment variables:
78
+ DEVBRIEF_PORT Local UI port (default: 4310)
79
+ DEVBRIEF_DATA_DIR Custom session storage directory (default: ~/.devbrief/data)
80
+ `);
81
+ }
82
+ async function main() {
83
+ const opts = parseArgs(process.argv);
84
+ const store = new SessionStore(opts.dataDir);
85
+ const uiUrl = `http://127.0.0.1:${opts.port}`;
86
+ switch (opts.command) {
87
+ case 'mcp': {
88
+ // NEVER log to stdout in MCP stdio mode!
89
+ const alreadyRunning = await isUiServerRunning(opts.port);
90
+ let embeddedServer;
91
+ if (!alreadyRunning) {
92
+ try {
93
+ embeddedServer = await startUiServer(store, opts.port);
94
+ process.stderr.write(`[devbrief] Local Web UI listening at ${embeddedServer.url}\n`);
95
+ }
96
+ catch (err) {
97
+ process.stderr.write(`[devbrief] Could not bind UI port ${opts.port} (${err instanceof Error ? err.message : String(err)}); continuing in MCP-only mode.\n`);
98
+ }
99
+ }
100
+ else {
101
+ process.stderr.write(`[devbrief] Connected to existing Web UI at ${uiUrl}\n`);
102
+ }
103
+ const cleanup = async () => {
104
+ if (embeddedServer)
105
+ await embeddedServer.close();
106
+ process.exit(0);
107
+ };
108
+ process.on('SIGINT', cleanup);
109
+ process.on('SIGTERM', cleanup);
110
+ await runStdioMcpServer({
111
+ store,
112
+ uiBaseUrl: uiUrl,
113
+ onMutate: (sessionId) => {
114
+ if (!embeddedServer) {
115
+ notifyExternalUiServer(opts.port, sessionId);
116
+ }
117
+ },
118
+ });
119
+ return;
120
+ }
121
+ case 'ui': {
122
+ const running = await isUiServerRunning(opts.port);
123
+ if (running) {
124
+ console.log(`DevBrief Web UI is already running at ${uiUrl}`);
125
+ if (!opts.noOpen)
126
+ openBrowser(uiUrl);
127
+ return;
128
+ }
129
+ const server = await startUiServer(store, opts.port);
130
+ console.log(`DevBrief Web UI running at ${server.url}`);
131
+ console.log(`Data directory: ${store.dataDir}`);
132
+ console.log('Press Ctrl+C to stop.');
133
+ if (!opts.noOpen)
134
+ openBrowser(server.url);
135
+ process.on('SIGINT', async () => {
136
+ await server.close();
137
+ process.exit(0);
138
+ });
139
+ return;
140
+ }
141
+ case 'demo': {
142
+ const demo = seedDemoSession(store, opts.targetDir);
143
+ console.log(`Seeded demo session: ${demo.id} — "${demo.title}"`);
144
+ const demoUrl = `${uiUrl}/?session=${encodeURIComponent(demo.id)}`;
145
+ const running = await isUiServerRunning(opts.port);
146
+ if (running) {
147
+ notifyExternalUiServer(opts.port, demo.id);
148
+ console.log(`Opened in running DevBrief UI: ${demoUrl}`);
149
+ if (!opts.noOpen)
150
+ openBrowser(demoUrl);
151
+ return;
152
+ }
153
+ const server = await startUiServer(store, opts.port);
154
+ console.log(`DevBrief Web UI running at ${demoUrl}`);
155
+ console.log('Press Ctrl+C to stop.');
156
+ if (!opts.noOpen)
157
+ openBrowser(demoUrl);
158
+ process.on('SIGINT', async () => {
159
+ await server.close();
160
+ process.exit(0);
161
+ });
162
+ return;
163
+ }
164
+ case 'init': {
165
+ const res = initCursorWorkspace(opts.targetDir);
166
+ console.log(`Initialized DevBrief in: ${opts.targetDir}`);
167
+ console.log(` ✓ Cursor rule written: ${res.ruleFile}`);
168
+ console.log(res.mcpUpdated
169
+ ? ` ✓ Registered "devbrief" MCP server in: ${res.mcpFile}`
170
+ : ` • "devbrief" already present in: ${res.mcpFile}`);
171
+ console.log('\nNext steps:');
172
+ console.log(' 1. Restart Cursor (or reload MCP servers in Cursor Settings -> MCP).');
173
+ console.log(' 2. Ask Cursor: "Начни PBI #12345 через devbrief — сначала погрузи меня в контекст"');
174
+ return;
175
+ }
176
+ case 'status': {
177
+ const running = await isUiServerRunning(opts.port);
178
+ const sessions = store.listSessions();
179
+ console.log(`DevBrief Status`);
180
+ console.log(` Data dir : ${resolveDataDir(opts.dataDir)}`);
181
+ console.log(` Web UI : ${running ? `RUNNING (${uiUrl})` : `STOPPED (port ${opts.port})`}`);
182
+ console.log(` Sessions : ${sessions.length}`);
183
+ for (const s of sessions.slice(0, 10)) {
184
+ console.log(` - ${s.id} [${s.phase}] ${s.title} (feedback: ${s.counts.pendingFeedback}, review pending: ${s.counts.reviewPending})`);
185
+ }
186
+ return;
187
+ }
188
+ default:
189
+ printHelp();
190
+ }
191
+ }
192
+ main().catch((err) => {
193
+ process.stderr.write(`[devbrief] Fatal error: ${err instanceof Error ? err.stack || err.message : String(err)}\n`);
194
+ process.exit(1);
195
+ });
@@ -0,0 +1,369 @@
1
+ import http from 'node:http';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import crypto from 'node:crypto';
5
+ import { fileURLToPath } from 'node:url';
6
+ const __filename = fileURLToPath(import.meta.url);
7
+ const __dirname = path.dirname(__filename);
8
+ export const DEFAULT_PORT = Number(process.env.DEVBRIEF_PORT || 4310);
9
+ const MIME_TYPES = {
10
+ '.html': 'text/html; charset=utf-8',
11
+ '.js': 'application/javascript; charset=utf-8',
12
+ '.css': 'text/css; charset=utf-8',
13
+ '.json': 'application/json; charset=utf-8',
14
+ '.svg': 'image/svg+xml',
15
+ '.png': 'image/png',
16
+ '.jpg': 'image/jpeg',
17
+ '.jpeg': 'image/jpeg',
18
+ '.webp': 'image/webp',
19
+ '.gif': 'image/gif',
20
+ '.txt': 'text/plain; charset=utf-8',
21
+ '.ico': 'image/x-icon',
22
+ };
23
+ function sendJson(res, status, payload) {
24
+ const body = JSON.stringify(payload);
25
+ res.writeHead(status, {
26
+ 'Content-Type': 'application/json; charset=utf-8',
27
+ 'Cache-Control': 'no-store',
28
+ });
29
+ res.end(body);
30
+ }
31
+ async function readJsonBody(req) {
32
+ const chunks = [];
33
+ for await (const chunk of req) {
34
+ chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
35
+ }
36
+ const raw = Buffer.concat(chunks).toString('utf8').trim();
37
+ if (!raw)
38
+ return {};
39
+ return JSON.parse(raw);
40
+ }
41
+ export async function isUiServerRunning(port) {
42
+ return new Promise((resolve) => {
43
+ const req = http.get({ host: '127.0.0.1', port, path: '/api/health', timeout: 800 }, (res) => {
44
+ res.resume();
45
+ resolve(res.statusCode === 200);
46
+ });
47
+ req.on('error', () => resolve(false));
48
+ req.on('timeout', () => {
49
+ req.destroy();
50
+ resolve(false);
51
+ });
52
+ });
53
+ }
54
+ export function notifyExternalUiServer(port, sessionId) {
55
+ const payload = JSON.stringify({ sessionId });
56
+ const req = http.request({
57
+ host: '127.0.0.1',
58
+ port,
59
+ path: '/api/internal/notify',
60
+ method: 'POST',
61
+ headers: {
62
+ 'Content-Type': 'application/json',
63
+ 'Content-Length': Buffer.byteLength(payload),
64
+ },
65
+ timeout: 800,
66
+ }, (res) => res.resume());
67
+ req.on('error', () => {
68
+ // ignore if UI server is not running
69
+ });
70
+ req.end(payload);
71
+ }
72
+ export async function startUiServer(store, port = DEFAULT_PORT) {
73
+ const webDistDir = path.resolve(__dirname, 'web');
74
+ const sseClients = new Set();
75
+ const broadcast = (payload) => {
76
+ const data = `data: ${JSON.stringify(payload)}\n\n`;
77
+ for (const client of sseClients) {
78
+ try {
79
+ client.write(data);
80
+ }
81
+ catch {
82
+ sseClients.delete(client);
83
+ }
84
+ }
85
+ };
86
+ store.startWatching();
87
+ const onStoreChange = (info) => {
88
+ broadcast({ type: 'update', ...info, ts: Date.now() });
89
+ };
90
+ store.on('change', onStoreChange);
91
+ const server = http.createServer(async (req, res) => {
92
+ try {
93
+ const urlObj = new URL(req.url || '/', `http://127.0.0.1:${port}`);
94
+ const pathname = decodeURIComponent(urlObj.pathname);
95
+ const method = req.method || 'GET';
96
+ // CORS for local Vite dev server
97
+ res.setHeader('Access-Control-Allow-Origin', '*');
98
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS');
99
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
100
+ if (method === 'OPTIONS') {
101
+ res.writeHead(204);
102
+ res.end();
103
+ return;
104
+ }
105
+ // Health check
106
+ if (method === 'GET' && pathname === '/api/health') {
107
+ sendJson(res, 200, { ok: true, dataDir: store.dataDir, port });
108
+ return;
109
+ }
110
+ // Cross-process notification endpoint
111
+ if (method === 'POST' && pathname === '/api/internal/notify') {
112
+ const body = await readJsonBody(req);
113
+ broadcast({ type: 'update', sessionId: body.sessionId, ts: Date.now() });
114
+ sendJson(res, 200, { ok: true });
115
+ return;
116
+ }
117
+ // Server-Sent Events stream for real-time updates
118
+ if (method === 'GET' && pathname === '/api/events') {
119
+ res.writeHead(200, {
120
+ 'Content-Type': 'text/event-stream',
121
+ 'Cache-Control': 'no-cache',
122
+ Connection: 'keep-alive',
123
+ });
124
+ res.write(`data: ${JSON.stringify({ type: 'connected', ts: Date.now() })}\n\n`);
125
+ sseClients.add(res);
126
+ const keepAlive = setInterval(() => {
127
+ try {
128
+ res.write(': ping\n\n');
129
+ }
130
+ catch {
131
+ clearInterval(keepAlive);
132
+ }
133
+ }, 25000);
134
+ req.on('close', () => {
135
+ clearInterval(keepAlive);
136
+ sseClients.delete(res);
137
+ });
138
+ return;
139
+ }
140
+ // List sessions
141
+ if (method === 'GET' && pathname === '/api/sessions') {
142
+ sendJson(res, 200, {
143
+ dataDir: store.dataDir,
144
+ sessions: store.listSessions(),
145
+ });
146
+ return;
147
+ }
148
+ // Session-scoped API routes
149
+ const sessionMatch = pathname.match(/^\/api\/sessions\/([^/]+)(\/.*)?$/);
150
+ if (sessionMatch) {
151
+ const sessionId = sessionMatch[1];
152
+ const subPath = sessionMatch[2] || '';
153
+ // GET full session
154
+ if (method === 'GET' && subPath === '') {
155
+ const session = store.getSession(sessionId);
156
+ if (!session) {
157
+ sendJson(res, 404, { error: 'Session not found' });
158
+ return;
159
+ }
160
+ sendJson(res, 200, session);
161
+ return;
162
+ }
163
+ // DELETE session
164
+ if (method === 'DELETE' && subPath === '') {
165
+ const deleted = store.deleteSession(sessionId);
166
+ sendJson(res, deleted ? 200 : 404, { ok: deleted });
167
+ return;
168
+ }
169
+ // GET asset file (screenshots)
170
+ const assetMatch = subPath.match(/^\/assets\/([^/]+)$/);
171
+ if (method === 'GET' && assetMatch) {
172
+ const assetPath = store.resolveAssetPath(sessionId, assetMatch[1]);
173
+ if (!assetPath) {
174
+ res.writeHead(404);
175
+ res.end('Asset not found');
176
+ return;
177
+ }
178
+ const ext = path.extname(assetPath).toLowerCase();
179
+ res.writeHead(200, {
180
+ 'Content-Type': MIME_TYPES[ext] || 'application/octet-stream',
181
+ 'Cache-Control': 'public, max-age=3600',
182
+ });
183
+ fs.createReadStream(assetPath).pipe(res);
184
+ return;
185
+ }
186
+ // Human actions from Web UI
187
+ if (method === 'POST' && subPath === '/walkthrough/toggle') {
188
+ const body = await readJsonBody(req);
189
+ const updated = store.updateSession(sessionId, (s) => {
190
+ const step = s.walkthrough.find((w) => w.id === body.stepId);
191
+ if (!step)
192
+ throw new Error('Step not found');
193
+ step.humanUnderstood = Boolean(body.understood);
194
+ });
195
+ sendJson(res, 200, updated);
196
+ return;
197
+ }
198
+ if (method === 'POST' && subPath === '/blast-radius/update') {
199
+ const body = await readJsonBody(req);
200
+ const updated = store.updateSession(sessionId, (s) => {
201
+ const item = s.blastRadius.find((b) => b.id === body.id);
202
+ if (!item)
203
+ throw new Error('Blast radius item not found');
204
+ if (body.humanApproved !== undefined)
205
+ item.humanApproved = body.humanApproved;
206
+ if (body.humanNote !== undefined)
207
+ item.humanNote = body.humanNote;
208
+ if (body.invariant !== undefined && body.invariant.trim()) {
209
+ item.invariant = body.invariant.trim();
210
+ }
211
+ });
212
+ sendJson(res, 200, updated);
213
+ return;
214
+ }
215
+ if (method === 'POST' && subPath === '/open-questions/answer') {
216
+ const body = await readJsonBody(req);
217
+ const updated = store.updateSession(sessionId, (s) => {
218
+ const q = s.openQuestions.find((item) => item.id === body.id);
219
+ if (!q)
220
+ throw new Error('Open question not found');
221
+ q.humanAnswer = body.answer;
222
+ q.answeredAt = new Date().toISOString();
223
+ });
224
+ sendJson(res, 200, updated);
225
+ return;
226
+ }
227
+ if (method === 'POST' && subPath === '/feedback') {
228
+ const body = await readJsonBody(req);
229
+ if (!body.message?.trim()) {
230
+ sendJson(res, 400, { error: 'Message is required' });
231
+ return;
232
+ }
233
+ const updated = store.updateSession(sessionId, (s) => {
234
+ s.feedback.push({
235
+ id: `fb-${crypto.randomBytes(4).toString('hex')}`,
236
+ targetType: body.targetType || 'general',
237
+ targetId: body.targetId,
238
+ targetLabel: body.targetLabel,
239
+ kind: body.kind || 'question',
240
+ message: body.message.trim(),
241
+ createdAt: new Date().toISOString(),
242
+ status: 'pending',
243
+ });
244
+ });
245
+ sendJson(res, 200, updated);
246
+ return;
247
+ }
248
+ if (method === 'POST' && subPath === '/feedback/resolve') {
249
+ const body = await readJsonBody(req);
250
+ const updated = store.updateSession(sessionId, (s) => {
251
+ const item = s.feedback.find((f) => f.id === body.feedbackId);
252
+ if (!item)
253
+ throw new Error('Feedback not found');
254
+ item.status = 'resolved';
255
+ });
256
+ sendJson(res, 200, updated);
257
+ return;
258
+ }
259
+ if (method === 'POST' && subPath === '/approve-spec') {
260
+ const updated = store.updateSession(sessionId, (s) => {
261
+ s.phase = 'spec_approved';
262
+ s.specApprovedAt = new Date().toISOString();
263
+ });
264
+ sendJson(res, 200, updated);
265
+ return;
266
+ }
267
+ if (method === 'POST' && subPath === '/review/verdict') {
268
+ const body = await readJsonBody(req);
269
+ const updated = store.updateSession(sessionId, (s) => {
270
+ const card = s.reviewCards.find((c) => c.id === body.cardId);
271
+ if (!card)
272
+ throw new Error('Review card not found');
273
+ card.humanVerdict = body.verdict;
274
+ if (body.comment !== undefined)
275
+ card.humanComment = body.comment;
276
+ card.updatedAt = new Date().toISOString();
277
+ });
278
+ sendJson(res, 200, updated);
279
+ return;
280
+ }
281
+ if (method === 'POST' && subPath === '/approve-review') {
282
+ const updated = store.updateSession(sessionId, (s) => {
283
+ s.phase = 'verification';
284
+ s.reviewApprovedAt = new Date().toISOString();
285
+ });
286
+ sendJson(res, 200, updated);
287
+ return;
288
+ }
289
+ if (method === 'POST' && subPath === '/verification/verdict') {
290
+ const body = await readJsonBody(req);
291
+ const updated = store.updateSession(sessionId, (s) => {
292
+ const sc = s.verificationScenarios.find((v) => v.id === body.scenarioId);
293
+ if (!sc)
294
+ throw new Error('Scenario not found');
295
+ sc.humanVerdict = body.verdict;
296
+ if (body.comment !== undefined)
297
+ sc.humanComment = body.comment;
298
+ sc.updatedAt = new Date().toISOString();
299
+ });
300
+ sendJson(res, 200, updated);
301
+ return;
302
+ }
303
+ if (method === 'POST' && subPath === '/doc-updates/status') {
304
+ const body = await readJsonBody(req);
305
+ const updated = store.updateSession(sessionId, (s) => {
306
+ const doc = s.docUpdates.find((d) => d.id === body.id);
307
+ if (!doc)
308
+ throw new Error('Doc proposal not found');
309
+ doc.status = body.status;
310
+ });
311
+ sendJson(res, 200, updated);
312
+ return;
313
+ }
314
+ if (method === 'POST' && subPath === '/complete') {
315
+ const updated = store.updateSession(sessionId, (s) => {
316
+ s.phase = 'done';
317
+ s.agentActivity = undefined;
318
+ });
319
+ sendJson(res, 200, updated);
320
+ return;
321
+ }
322
+ }
323
+ // Static Web UI serving
324
+ if (method === 'GET') {
325
+ const cleanRel = pathname === '/' ? 'index.html' : pathname.replace(/^\/+/, '');
326
+ let filePath = path.join(webDistDir, cleanRel);
327
+ if (!filePath.startsWith(webDistDir)) {
328
+ res.writeHead(403);
329
+ res.end('Forbidden');
330
+ return;
331
+ }
332
+ if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) {
333
+ filePath = path.join(webDistDir, 'index.html');
334
+ }
335
+ if (fs.existsSync(filePath)) {
336
+ const ext = path.extname(filePath).toLowerCase();
337
+ res.writeHead(200, {
338
+ 'Content-Type': MIME_TYPES[ext] || 'application/octet-stream',
339
+ });
340
+ fs.createReadStream(filePath).pipe(res);
341
+ return;
342
+ }
343
+ }
344
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
345
+ res.end('Not Found (have you built the web UI with `npm run build`?)');
346
+ }
347
+ catch (err) {
348
+ const msg = err instanceof Error ? err.message : String(err);
349
+ sendJson(res, 500, { error: msg });
350
+ }
351
+ });
352
+ await new Promise((resolve, reject) => {
353
+ server.once('error', reject);
354
+ server.listen(port, '127.0.0.1', () => resolve());
355
+ });
356
+ return {
357
+ server,
358
+ port,
359
+ url: `http://127.0.0.1:${port}`,
360
+ close: async () => {
361
+ store.off('change', onStoreChange);
362
+ store.stopWatching();
363
+ for (const c of sseClients)
364
+ c.end();
365
+ sseClients.clear();
366
+ await new Promise((resolve) => server.close(() => resolve()));
367
+ },
368
+ };
369
+ }