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
@@ -0,0 +1,735 @@
1
+ import crypto from 'node:crypto';
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { z } from 'zod';
5
+ import { sanitizeId } from './store.js';
6
+ import { scanMonorepoWorkspace, getWorkspaceGitDiffSummary } from './workspace.js';
7
+ const codeRefSchema = z.object({
8
+ path: z.string().describe('Absolute path or path relative to monorepo root (e.g. repos/orders-api/src/Handler.cs)'),
9
+ startLine: z.number().int().positive().optional(),
10
+ endLine: z.number().int().positive().optional(),
11
+ symbol: z.string().optional().describe('Function, class, or endpoint name'),
12
+ note: z.string().optional(),
13
+ });
14
+ const riskSchema = z.enum(['critical', 'high', 'medium', 'low']);
15
+ const phaseSchema = z.enum([
16
+ 'onboarding',
17
+ 'spec_approved',
18
+ 'implementing',
19
+ 'review',
20
+ 'verification',
21
+ 'done',
22
+ ]);
23
+ function okJson(data) {
24
+ return {
25
+ content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],
26
+ };
27
+ }
28
+ function sessionUrl(baseUrl, sessionId, tab) {
29
+ const params = new URLSearchParams({ session: sessionId });
30
+ if (tab)
31
+ params.set('tab', tab);
32
+ return `${baseUrl}/?${params.toString()}`;
33
+ }
34
+ export function createDevBriefMcpServer(options) {
35
+ const { store, uiBaseUrl, onMutate } = options;
36
+ const notify = (sessionId) => {
37
+ try {
38
+ onMutate?.(sessionId);
39
+ }
40
+ catch {
41
+ // non-fatal
42
+ }
43
+ };
44
+ const server = new McpServer({
45
+ name: 'devbrief',
46
+ version: '0.1.0',
47
+ });
48
+ // =========================================================================
49
+ // 1. WORKSPACE & SESSION MANAGEMENT
50
+ // =========================================================================
51
+ server.tool('devbrief_scan_workspace', 'Scan a monorepo root directory (docs/specs in root and service repos inside /repos/*) to inspect stacks, git branches, and dirty files.', {
52
+ workspacePath: z.string().describe('Absolute path to the monorepo root directory'),
53
+ }, async ({ workspacePath }) => {
54
+ const scan = scanMonorepoWorkspace(workspacePath);
55
+ return okJson(scan);
56
+ });
57
+ server.tool('devbrief_git_diff_summary', 'Get concise git diff --stat and untracked files across the monorepo or a specific repo inside /repos/*.', {
58
+ workspacePath: z.string().describe('Absolute path to the monorepo root directory'),
59
+ repoName: z.string().optional().describe('Optional repo folder name inside /repos/'),
60
+ }, async ({ workspacePath, repoName }) => {
61
+ const diffs = getWorkspaceGitDiffSummary(workspacePath, repoName);
62
+ return okJson({ workspacePath, repos: diffs });
63
+ });
64
+ server.tool('devbrief_create_session', 'Create (or update metadata of) a DevBrief session for a PBI / task. Returns the sessionId and live Web UI URL.', {
65
+ sessionId: z.string().optional().describe('Optional stable ID such as PBI-12345'),
66
+ title: z.string().describe('Short clear title of the PBI or feature'),
67
+ pbiId: z.string().optional().describe('Azure DevOps PBI / Ticket ID (e.g. PBI-12345)'),
68
+ pbiUrl: z.string().optional().describe('Direct URL to Azure DevOps work item'),
69
+ workspacePath: z.string().optional().describe('Absolute path to monorepo root (used for Cursor deep links)'),
70
+ phase: phaseSchema.optional().default('onboarding'),
71
+ agentActivity: z.string().optional().describe('Current live status shown in the UI banner'),
72
+ }, async (args) => {
73
+ const id = sanitizeId(args.sessionId || args.pbiId || args.title);
74
+ const existing = store.getSession(id);
75
+ const now = new Date().toISOString();
76
+ const session = existing
77
+ ? {
78
+ ...existing,
79
+ title: args.title,
80
+ pbiId: args.pbiId ?? existing.pbiId,
81
+ pbiUrl: args.pbiUrl ?? existing.pbiUrl,
82
+ workspacePath: args.workspacePath ?? existing.workspacePath,
83
+ phase: args.phase ?? existing.phase,
84
+ agentActivity: args.agentActivity ?? existing.agentActivity,
85
+ }
86
+ : {
87
+ id,
88
+ title: args.title,
89
+ pbiId: args.pbiId,
90
+ pbiUrl: args.pbiUrl,
91
+ workspacePath: args.workspacePath,
92
+ phase: args.phase ?? 'onboarding',
93
+ agentActivity: args.agentActivity,
94
+ createdAt: now,
95
+ updatedAt: now,
96
+ walkthrough: [],
97
+ glossary: [],
98
+ blastRadius: [],
99
+ openQuestions: [],
100
+ reviewCards: [],
101
+ verificationScenarios: [],
102
+ docUpdates: [],
103
+ feedback: [],
104
+ };
105
+ store.saveSession(session);
106
+ notify(session.id);
107
+ return okJson({
108
+ sessionId: session.id,
109
+ uiUrl: sessionUrl(uiBaseUrl, session.id, 'onboarding'),
110
+ phase: session.phase,
111
+ existed: Boolean(existing),
112
+ });
113
+ });
114
+ server.tool('devbrief_list_sessions', 'List all DevBrief sessions with their current phase, pending human questions, and review/verification counts.', {}, async () => {
115
+ const sessions = store.listSessions();
116
+ return okJson({
117
+ uiBaseUrl,
118
+ sessions: sessions.map((s) => ({
119
+ ...s,
120
+ uiUrl: sessionUrl(uiBaseUrl, s.id),
121
+ })),
122
+ });
123
+ });
124
+ server.tool('devbrief_get_session', 'Fetch the full state (or a single section) of a DevBrief session.', {
125
+ sessionId: z.string(),
126
+ section: z
127
+ .enum(['all', 'overview', 'walkthrough', 'glossary', 'blastRadius', 'openQuestions', 'reviewCards', 'verificationScenarios', 'docUpdates', 'feedback'])
128
+ .optional()
129
+ .default('all'),
130
+ }, async ({ sessionId, section }) => {
131
+ const session = store.getSession(sessionId);
132
+ if (!session) {
133
+ return okJson({ error: `Session "${sessionId}" not found` });
134
+ }
135
+ if (section === 'all') {
136
+ return okJson({ uiUrl: sessionUrl(uiBaseUrl, session.id), session });
137
+ }
138
+ return okJson({
139
+ sessionId: session.id,
140
+ phase: session.phase,
141
+ [section]: session[section],
142
+ });
143
+ });
144
+ server.tool('devbrief_update_status', 'Update the session phase and/or live agent activity message displayed at the top of the Web UI.', {
145
+ sessionId: z.string(),
146
+ phase: phaseSchema.optional(),
147
+ agentActivity: z.string().nullable().optional().describe('Pass null or empty string to clear the live banner'),
148
+ }, async ({ sessionId, phase, agentActivity }) => {
149
+ const updated = store.updateSession(sessionId, (s) => {
150
+ if (phase)
151
+ s.phase = phase;
152
+ if (agentActivity !== undefined) {
153
+ s.agentActivity = agentActivity || undefined;
154
+ }
155
+ });
156
+ notify(updated.id);
157
+ return okJson({
158
+ sessionId: updated.id,
159
+ phase: updated.phase,
160
+ agentActivity: updated.agentActivity ?? null,
161
+ uiUrl: sessionUrl(uiBaseUrl, updated.id),
162
+ });
163
+ });
164
+ // =========================================================================
165
+ // 2. STAGE 1: INCREMENTAL CONTEXT ONBOARDING
166
+ // =========================================================================
167
+ server.tool('devbrief_set_overview', 'Set the 1-screen executive overview, affected services, relevant root docs, and AS-IS / TO-BE Mermaid architecture diagrams.', {
168
+ sessionId: z.string(),
169
+ tldr: z.string().describe('2-4 sentence plain-language summary of the task'),
170
+ businessGoal: z.string().describe('Why the business/user needs this change'),
171
+ whyNow: z.string().optional().describe('Context or trigger for this PBI'),
172
+ affectedServices: z.array(z.string()).default([]),
173
+ relevantDocs: z.array(codeRefSchema).default([]),
174
+ asIsMermaid: z.string().optional().describe('Valid Mermaid diagram (flowchart LR/TD or sequenceDiagram) showing current system behavior'),
175
+ toBeMermaid: z.string().optional().describe('Valid Mermaid diagram showing target behavior after this PBI'),
176
+ }, async (args) => {
177
+ const updated = store.updateSession(args.sessionId, (s) => {
178
+ s.overview = {
179
+ tldr: args.tldr,
180
+ businessGoal: args.businessGoal,
181
+ whyNow: args.whyNow,
182
+ affectedServices: args.affectedServices,
183
+ relevantDocs: args.relevantDocs,
184
+ asIsMermaid: args.asIsMermaid,
185
+ toBeMermaid: args.toBeMermaid,
186
+ updatedAt: new Date().toISOString(),
187
+ };
188
+ });
189
+ notify(updated.id);
190
+ return okJson({
191
+ ok: true,
192
+ sessionId: updated.id,
193
+ uiUrl: sessionUrl(uiBaseUrl, updated.id, 'onboarding'),
194
+ });
195
+ });
196
+ server.tool('devbrief_upsert_walkthrough', 'Publish or update incremental, bite-sized walkthrough steps that onboard the human developer like a beginner (cause & effect first, code refs collapsible).', {
197
+ sessionId: z.string(),
198
+ replaceAll: z.boolean().optional().default(false),
199
+ steps: z.array(z.object({
200
+ id: z.string(),
201
+ order: z.number().int().min(1),
202
+ title: z.string(),
203
+ service: z.string().optional(),
204
+ simpleExplanation: z.string().describe('Clear beginner-friendly explanation with cause -> effect, no assumed memory'),
205
+ whyItMatters: z.string().optional().describe('Why this part exists and how it affects the feature or existing behavior'),
206
+ technicalDetails: z.string().optional().describe('Deeper implementation notes (hidden behind an expandable section by default)'),
207
+ codeRefs: z.array(codeRefSchema).default([]),
208
+ relatedTerms: z.array(z.string()).default([]).describe('Glossary term names mentioned in this step'),
209
+ })),
210
+ }, async ({ sessionId, replaceAll, steps }) => {
211
+ const updated = store.updateSession(sessionId, (s) => {
212
+ const existingMap = new Map(s.walkthrough.map((w) => [w.id, w]));
213
+ if (replaceAll) {
214
+ s.walkthrough = steps
215
+ .map((st) => ({
216
+ ...st,
217
+ humanUnderstood: existingMap.get(st.id)?.humanUnderstood ?? false,
218
+ }))
219
+ .sort((a, b) => a.order - b.order);
220
+ }
221
+ else {
222
+ for (const st of steps) {
223
+ const prev = existingMap.get(st.id);
224
+ existingMap.set(st.id, {
225
+ ...st,
226
+ humanUnderstood: prev?.humanUnderstood ?? false,
227
+ });
228
+ }
229
+ s.walkthrough = Array.from(existingMap.values()).sort((a, b) => a.order - b.order);
230
+ }
231
+ });
232
+ notify(updated.id);
233
+ return okJson({
234
+ ok: true,
235
+ sessionId: updated.id,
236
+ stepCount: updated.walkthrough.length,
237
+ uiUrl: sessionUrl(uiBaseUrl, updated.id, 'onboarding'),
238
+ });
239
+ });
240
+ server.tool('devbrief_upsert_glossary', 'Add or update domain/architecture glossary terms. Terms are automatically highlighted inline inside walkthrough explanations so the human can click any unfamiliar term.', {
241
+ sessionId: z.string(),
242
+ terms: z.array(z.object({
243
+ term: z.string(),
244
+ shortDef: z.string().describe('One-line definition for quick tooltip/preview'),
245
+ beginnerExplanation: z.string().describe('Plain-language explanation with concrete context from this project'),
246
+ analogy: z.string().optional().describe('Simple real-world or Python-developer analogy'),
247
+ whereUsed: z.string().optional(),
248
+ codeRef: codeRefSchema.optional(),
249
+ })),
250
+ }, async ({ sessionId, terms }) => {
251
+ const updated = store.updateSession(sessionId, (s) => {
252
+ const map = new Map(s.glossary.map((g) => [g.term.toLowerCase(), g]));
253
+ for (const t of terms) {
254
+ map.set(t.term.toLowerCase(), t);
255
+ }
256
+ s.glossary = Array.from(map.values()).sort((a, b) => a.term.localeCompare(b.term));
257
+ });
258
+ notify(updated.id);
259
+ return okJson({ ok: true, sessionId: updated.id, termCount: updated.glossary.length });
260
+ });
261
+ server.tool('devbrief_set_blast_radius', 'Publish impacted areas, neighboring services/tables/APIs, what could regress, and invariants that must NOT break (include real DB/API findings when checked).', {
262
+ sessionId: z.string(),
263
+ replaceAll: z.boolean().optional().default(false),
264
+ items: z.array(z.object({
265
+ id: z.string(),
266
+ service: z.string(),
267
+ area: z.string().describe('Endpoint, table, queue, job, or feature area'),
268
+ riskLevel: riskSchema,
269
+ howItCurrentlyWorks: z.string(),
270
+ whatCouldBreak: z.string(),
271
+ invariant: z.string().describe('Explicit rule that must stay true after our change'),
272
+ dbOrApiEvidence: z.string().optional().describe('Observed fact from DB query, spec doc, or API contract'),
273
+ codeRefs: z.array(codeRefSchema).default([]),
274
+ })),
275
+ }, async ({ sessionId, replaceAll, items }) => {
276
+ const updated = store.updateSession(sessionId, (s) => {
277
+ const prevMap = new Map(s.blastRadius.map((b) => [b.id, b]));
278
+ if (replaceAll) {
279
+ s.blastRadius = items.map((item) => ({
280
+ ...item,
281
+ humanApproved: prevMap.get(item.id)?.humanApproved ?? false,
282
+ humanNote: prevMap.get(item.id)?.humanNote,
283
+ }));
284
+ }
285
+ else {
286
+ for (const item of items) {
287
+ const prev = prevMap.get(item.id);
288
+ prevMap.set(item.id, {
289
+ ...item,
290
+ humanApproved: prev?.humanApproved ?? false,
291
+ humanNote: prev?.humanNote,
292
+ });
293
+ }
294
+ s.blastRadius = Array.from(prevMap.values());
295
+ }
296
+ });
297
+ notify(updated.id);
298
+ return okJson({ ok: true, sessionId: updated.id, blastRadiusCount: updated.blastRadius.length });
299
+ });
300
+ server.tool('devbrief_upsert_open_questions', 'Publish ambiguities, edge cases, or assumptions from the PBI that need human confirmation before or during implementation.', {
301
+ sessionId: z.string(),
302
+ questions: z.array(z.object({
303
+ id: z.string(),
304
+ question: z.string(),
305
+ context: z.string().optional(),
306
+ agentDefaultAssumption: z.string().describe('What the agent will assume if the human approves default'),
307
+ options: z.array(z.string()).optional(),
308
+ impact: z.string().optional(),
309
+ })),
310
+ }, async ({ sessionId, questions }) => {
311
+ const updated = store.updateSession(sessionId, (s) => {
312
+ const map = new Map(s.openQuestions.map((q) => [q.id, q]));
313
+ for (const q of questions) {
314
+ const prev = map.get(q.id);
315
+ map.set(q.id, {
316
+ ...q,
317
+ humanAnswer: prev?.humanAnswer,
318
+ answeredAt: prev?.answeredAt,
319
+ });
320
+ }
321
+ s.openQuestions = Array.from(map.values());
322
+ });
323
+ notify(updated.id);
324
+ return okJson({ ok: true, sessionId: updated.id, openQuestionCount: updated.openQuestions.length });
325
+ });
326
+ // =========================================================================
327
+ // 3. STAGE 2: DECISION-FIRST CODE REVIEW
328
+ // =========================================================================
329
+ server.tool('devbrief_publish_review', 'Publish grouped behavioral code review cards (organized by risk, contracts, DB changes, agent decisions, and new-stack bridges instead of raw alphabetical file lists).', {
330
+ sessionId: z.string(),
331
+ replaceAll: z.boolean().optional().default(false),
332
+ setPhaseToReview: z.boolean().optional().default(true),
333
+ cards: z.array(z.object({
334
+ id: z.string(),
335
+ title: z.string(),
336
+ category: z.enum([
337
+ 'contract',
338
+ 'database',
339
+ 'business_logic',
340
+ 'agent_decision',
341
+ 'new_stack_bridge',
342
+ 'security',
343
+ 'boilerplate',
344
+ ]),
345
+ risk: riskSchema,
346
+ service: z.string().optional(),
347
+ stack: z.string().optional().describe('e.g. C# / .NET, Python, SQL, React'),
348
+ summary: z.string(),
349
+ beforeBehavior: z.string().optional(),
350
+ afterBehavior: z.string(),
351
+ whyAgentChoseThis: z.string().optional().describe('Trade-offs or assumptions the agent made here'),
352
+ stackBridgeNote: z
353
+ .string()
354
+ .optional()
355
+ .describe('Helpful mental-model translation for an unfamiliar stack (e.g. explaining C# DI/EF Core/Records in Python terms)'),
356
+ diffs: z
357
+ .array(z.object({
358
+ filePath: z.string(),
359
+ startLine: z.number().int().positive().optional(),
360
+ language: z.string().optional(),
361
+ snippet: z.string().describe('Focused unified diff or key changed lines'),
362
+ }))
363
+ .default([]),
364
+ codeRefs: z.array(codeRefSchema).default([]),
365
+ })),
366
+ }, async ({ sessionId, replaceAll, setPhaseToReview, cards }) => {
367
+ const now = new Date().toISOString();
368
+ const updated = store.updateSession(sessionId, (s) => {
369
+ if (setPhaseToReview)
370
+ s.phase = 'review';
371
+ const prevMap = new Map(s.reviewCards.map((c) => [c.id, c]));
372
+ if (replaceAll) {
373
+ s.reviewCards = cards.map((c) => {
374
+ const prev = prevMap.get(c.id);
375
+ return {
376
+ ...c,
377
+ humanVerdict: prev?.humanVerdict ?? 'pending',
378
+ humanComment: prev?.humanComment,
379
+ agentResolution: prev?.agentResolution,
380
+ updatedAt: now,
381
+ };
382
+ });
383
+ }
384
+ else {
385
+ for (const c of cards) {
386
+ const prev = prevMap.get(c.id);
387
+ prevMap.set(c.id, {
388
+ ...c,
389
+ humanVerdict: prev?.humanVerdict ?? 'pending',
390
+ humanComment: prev?.humanComment,
391
+ agentResolution: prev?.agentResolution,
392
+ updatedAt: now,
393
+ });
394
+ }
395
+ s.reviewCards = Array.from(prevMap.values());
396
+ }
397
+ });
398
+ notify(updated.id);
399
+ return okJson({
400
+ ok: true,
401
+ sessionId: updated.id,
402
+ reviewCardCount: updated.reviewCards.length,
403
+ uiUrl: sessionUrl(uiBaseUrl, updated.id, 'review'),
404
+ });
405
+ });
406
+ server.tool('devbrief_resolve_review_card', 'Record how the agent addressed a human review comment or change request on a review card, optionally updating its diff snippet.', {
407
+ sessionId: z.string(),
408
+ cardId: z.string(),
409
+ resolution: z.string().describe('Clear explanation of what was fixed or why the implementation works this way'),
410
+ resetVerdictToPending: z.boolean().optional().default(true),
411
+ updatedDiffs: z
412
+ .array(z.object({
413
+ filePath: z.string(),
414
+ startLine: z.number().int().positive().optional(),
415
+ language: z.string().optional(),
416
+ snippet: z.string(),
417
+ }))
418
+ .optional(),
419
+ }, async ({ sessionId, cardId, resolution, resetVerdictToPending, updatedDiffs }) => {
420
+ const updated = store.updateSession(sessionId, (s) => {
421
+ const card = s.reviewCards.find((c) => c.id === cardId);
422
+ if (!card)
423
+ throw new Error(`Review card "${cardId}" not found`);
424
+ card.agentResolution = resolution;
425
+ if (updatedDiffs)
426
+ card.diffs = updatedDiffs;
427
+ if (resetVerdictToPending)
428
+ card.humanVerdict = 'pending';
429
+ card.updatedAt = new Date().toISOString();
430
+ });
431
+ notify(updated.id);
432
+ return okJson({ ok: true, sessionId: updated.id, cardId });
433
+ });
434
+ // =========================================================================
435
+ // 4. STAGE 3: REGRESSION CONTROL & EVIDENCE PACK
436
+ // =========================================================================
437
+ server.tool('devbrief_set_verification_plan', 'Publish or update verification and regression test scenarios (new feature checks + blast-radius regression checks + DB checks).', {
438
+ sessionId: z.string(),
439
+ replaceAll: z.boolean().optional().default(false),
440
+ setPhaseToVerification: z.boolean().optional().default(false),
441
+ scenarios: z.array(z.object({
442
+ id: z.string(),
443
+ title: z.string(),
444
+ kind: z.enum(['feature', 'regression', 'edge_case', 'db_check']),
445
+ service: z.string().optional(),
446
+ steps: z.array(z.string()).default([]),
447
+ expectedOutcome: z.string(),
448
+ actualOutcome: z.string().optional(),
449
+ status: z.enum(['pending', 'passed', 'failed', 'blocked']).default('pending'),
450
+ linkedBlastRadiusId: z.string().optional(),
451
+ })),
452
+ }, async ({ sessionId, replaceAll, setPhaseToVerification, scenarios }) => {
453
+ const now = new Date().toISOString();
454
+ const updated = store.updateSession(sessionId, (s) => {
455
+ if (setPhaseToVerification)
456
+ s.phase = 'verification';
457
+ const prevMap = new Map(s.verificationScenarios.map((v) => [v.id, v]));
458
+ if (replaceAll) {
459
+ s.verificationScenarios = scenarios.map((sc) => {
460
+ const prev = prevMap.get(sc.id);
461
+ return {
462
+ ...sc,
463
+ evidence: prev?.evidence ?? [],
464
+ humanVerdict: prev?.humanVerdict ?? 'pending',
465
+ humanComment: prev?.humanComment,
466
+ updatedAt: now,
467
+ };
468
+ });
469
+ }
470
+ else {
471
+ for (const sc of scenarios) {
472
+ const prev = prevMap.get(sc.id);
473
+ prevMap.set(sc.id, {
474
+ ...sc,
475
+ evidence: prev?.evidence ?? [],
476
+ humanVerdict: prev?.humanVerdict ?? 'pending',
477
+ humanComment: prev?.humanComment,
478
+ updatedAt: now,
479
+ });
480
+ }
481
+ s.verificationScenarios = Array.from(prevMap.values());
482
+ }
483
+ });
484
+ notify(updated.id);
485
+ return okJson({
486
+ ok: true,
487
+ sessionId: updated.id,
488
+ scenarioCount: updated.verificationScenarios.length,
489
+ uiUrl: sessionUrl(uiBaseUrl, updated.id, 'verification'),
490
+ });
491
+ });
492
+ server.tool('devbrief_attach_evidence', 'Attach concrete verification evidence (local browser screenshot path, before/after screenshots, API response JSON, SQL query result, or log excerpt) to a verification scenario.', {
493
+ sessionId: z.string(),
494
+ scenarioId: z.string(),
495
+ kind: z.enum(['screenshot', 'api_response', 'db_query', 'log', 'before_after', 'note']),
496
+ title: z.string(),
497
+ description: z.string().optional(),
498
+ content: z.string().optional().describe('Text/JSON/SQL/log payload'),
499
+ filePath: z.string().optional().describe('Local path to screenshot image file to copy into session assets'),
500
+ beforeFilePath: z.string().optional().describe('Optional local path to BEFORE screenshot for before_after comparisons'),
501
+ updateScenarioStatus: z.enum(['pending', 'passed', 'failed', 'blocked']).optional(),
502
+ actualOutcome: z.string().optional(),
503
+ }, async (args) => {
504
+ let assetFile;
505
+ let beforeAssetFile;
506
+ if (args.filePath) {
507
+ assetFile = store.copyAssetFile(args.sessionId, args.filePath, args.title);
508
+ }
509
+ if (args.beforeFilePath) {
510
+ beforeAssetFile = store.copyAssetFile(args.sessionId, args.beforeFilePath, `before-${args.title}`);
511
+ }
512
+ const item = {
513
+ id: `ev-${crypto.randomBytes(4).toString('hex')}`,
514
+ kind: args.kind,
515
+ title: args.title,
516
+ description: args.description,
517
+ content: args.content,
518
+ assetFile,
519
+ beforeAssetFile,
520
+ createdAt: new Date().toISOString(),
521
+ };
522
+ const updated = store.updateSession(args.sessionId, (s) => {
523
+ const scenario = s.verificationScenarios.find((v) => v.id === args.scenarioId);
524
+ if (!scenario) {
525
+ throw new Error(`Verification scenario "${args.scenarioId}" not found`);
526
+ }
527
+ scenario.evidence.push(item);
528
+ if (args.updateScenarioStatus)
529
+ scenario.status = args.updateScenarioStatus;
530
+ if (args.actualOutcome)
531
+ scenario.actualOutcome = args.actualOutcome;
532
+ scenario.updatedAt = new Date().toISOString();
533
+ });
534
+ notify(updated.id);
535
+ return okJson({
536
+ ok: true,
537
+ sessionId: updated.id,
538
+ scenarioId: args.scenarioId,
539
+ evidenceId: item.id,
540
+ assetFile: assetFile ?? null,
541
+ uiUrl: sessionUrl(uiBaseUrl, updated.id, 'verification'),
542
+ });
543
+ });
544
+ server.tool('devbrief_propose_doc_updates', 'Propose living-documentation updates to root docs/specs or service cards so team knowledge stays accurate after this PBI.', {
545
+ sessionId: z.string(),
546
+ proposals: z.array(z.object({
547
+ id: z.string(),
548
+ docPath: z.string(),
549
+ section: z.string().optional(),
550
+ reason: z.string(),
551
+ proposedChange: z.string(),
552
+ status: z.enum(['proposed', 'approved', 'skipped', 'applied']).optional(),
553
+ })),
554
+ }, async ({ sessionId, proposals }) => {
555
+ const updated = store.updateSession(sessionId, (s) => {
556
+ const map = new Map(s.docUpdates.map((d) => [d.id, d]));
557
+ for (const p of proposals) {
558
+ const prev = map.get(p.id);
559
+ map.set(p.id, {
560
+ ...p,
561
+ status: p.status ?? prev?.status ?? 'proposed',
562
+ });
563
+ }
564
+ s.docUpdates = Array.from(map.values());
565
+ });
566
+ notify(updated.id);
567
+ return okJson({ ok: true, sessionId: updated.id, docUpdateCount: updated.docUpdates.length });
568
+ });
569
+ // =========================================================================
570
+ // 5. HUMAN <-> AGENT FEEDBACK SYNC
571
+ // =========================================================================
572
+ server.tool('devbrief_get_human_feedback', 'Read all pending questions ("explain simpler", "show DB example"), answered Open Questions, approved/edited invariants, review verdicts/comments, and verification re-check requests submitted by the human in the Web UI.', {
573
+ sessionId: z.string(),
574
+ onlyPending: z.boolean().optional().default(true),
575
+ }, async ({ sessionId, onlyPending }) => {
576
+ const s = store.getSession(sessionId);
577
+ if (!s)
578
+ return okJson({ error: `Session "${sessionId}" not found` });
579
+ const feedbackItems = onlyPending
580
+ ? s.feedback.filter((f) => f.status === 'pending')
581
+ : s.feedback;
582
+ const answeredQuestions = s.openQuestions.filter((q) => Boolean(q.humanAnswer?.trim()));
583
+ const unansweredQuestions = s.openQuestions.filter((q) => !q.humanAnswer?.trim());
584
+ const reviewActionItems = s.reviewCards
585
+ .filter((c) => c.humanVerdict === 'request_change' || c.humanVerdict === 'ask_why')
586
+ .map((c) => ({
587
+ cardId: c.id,
588
+ title: c.title,
589
+ verdict: c.humanVerdict,
590
+ humanComment: c.humanComment,
591
+ service: c.service,
592
+ }));
593
+ const verificationRechecks = s.verificationScenarios
594
+ .filter((v) => v.humanVerdict === 'recheck')
595
+ .map((v) => ({
596
+ scenarioId: v.id,
597
+ title: v.title,
598
+ humanComment: v.humanComment,
599
+ }));
600
+ const approvedInvariants = s.blastRadius
601
+ .filter((b) => b.humanApproved || b.humanNote)
602
+ .map((b) => ({
603
+ id: b.id,
604
+ service: b.service,
605
+ area: b.area,
606
+ invariant: b.invariant,
607
+ humanApproved: b.humanApproved,
608
+ humanNote: b.humanNote,
609
+ }));
610
+ const approvedDocUpdates = s.docUpdates.filter((d) => d.status === 'approved');
611
+ return okJson({
612
+ sessionId: s.id,
613
+ phase: s.phase,
614
+ specApprovedAt: s.specApprovedAt ?? null,
615
+ reviewApprovedAt: s.reviewApprovedAt ?? null,
616
+ walkthroughProgress: {
617
+ understood: s.walkthrough.filter((w) => w.humanUnderstood).length,
618
+ total: s.walkthrough.length,
619
+ },
620
+ pendingQuestionsFromHuman: feedbackItems,
621
+ answeredOpenQuestions: answeredQuestions.map((q) => ({
622
+ id: q.id,
623
+ question: q.question,
624
+ humanAnswer: q.humanAnswer,
625
+ })),
626
+ unansweredOpenQuestionsCount: unansweredQuestions.length,
627
+ approvedInvariants,
628
+ reviewActionItems,
629
+ verificationRechecks,
630
+ approvedDocUpdates,
631
+ });
632
+ });
633
+ server.tool('devbrief_reply_to_feedback', 'Answer a specific human question or "explain simpler" request submitted from the Web UI. The answer appears immediately inline in the browser.', {
634
+ sessionId: z.string(),
635
+ feedbackId: z.string(),
636
+ reply: z.string().describe('Clear, tailored answer (or simpler explanation with concrete examples/analogies)'),
637
+ markStatus: z.enum(['answered', 'resolved']).optional().default('answered'),
638
+ }, async ({ sessionId, feedbackId, reply, markStatus }) => {
639
+ const updated = store.updateSession(sessionId, (s) => {
640
+ const item = s.feedback.find((f) => f.id === feedbackId);
641
+ if (!item)
642
+ throw new Error(`Feedback item "${feedbackId}" not found`);
643
+ item.agentReply = reply;
644
+ item.status = markStatus;
645
+ item.repliedAt = new Date().toISOString();
646
+ });
647
+ notify(updated.id);
648
+ return okJson({ ok: true, sessionId: updated.id, feedbackId, status: markStatus });
649
+ });
650
+ // =========================================================================
651
+ // 6. MCP PROMPTS (One-click workflows in Cursor)
652
+ // =========================================================================
653
+ server.prompt('start-pbi-onboarding', 'Investigate a PBI across the monorepo, root docs, Azure DevOps, and DBs, then publish an incremental beginner-friendly briefing in DevBrief.', {
654
+ pbiRef: z.string().describe('PBI number, URL, or task description'),
655
+ workspacePath: z.string().optional().describe('Absolute path to monorepo root'),
656
+ }, async ({ pbiRef, workspacePath }) => ({
657
+ messages: [
658
+ {
659
+ role: 'user',
660
+ content: {
661
+ type: 'text',
662
+ text: [
663
+ `Start a DevBrief Phase-0 Context Onboarding for: ${pbiRef}`,
664
+ workspacePath ? `Monorepo root: ${workspacePath}` : '',
665
+ '',
666
+ 'Follow this exact protocol:',
667
+ '1. Read the PBI details (from Azure DevOps MCP if available) and call devbrief_scan_workspace to map root docs/specs and /repos/* services.',
668
+ '2. Call devbrief_create_session with a clear sessionId (e.g. PBI-12345), workspacePath, and agentActivity="Investigating context...".',
669
+ '3. Read relevant root specs/docs and inspect the impacted services (and DB schema/data via DB MCP if helpful).',
670
+ '4. Call devbrief_set_overview with a 1-screen TL;DR, business goal, affected services, relevant root docs, and valid Mermaid AS-IS and TO-BE diagrams.',
671
+ '5. Call devbrief_upsert_walkthrough with 4-7 bite-sized ordered steps. Write simpleExplanation like teaching a smart beginner (cause -> effect, zero assumed memory). Put deep code details in technicalDetails and attach codeRefs.',
672
+ '6. Call devbrief_upsert_glossary for every non-obvious domain or stack term (include Python analogies for C#/.NET concepts).',
673
+ '7. Call devbrief_set_blast_radius listing neighboring services/tables/APIs that could regress and explicit invariants that MUST NOT break.',
674
+ '8. Call devbrief_upsert_open_questions for any ambiguities or assumptions.',
675
+ '9. Clear agentActivity with devbrief_update_status, give me the DevBrief UI link, and WAIT for my review/approval before editing code.',
676
+ ]
677
+ .filter(Boolean)
678
+ .join('\n'),
679
+ },
680
+ },
681
+ ],
682
+ }));
683
+ server.prompt('prepare-behavioral-review', 'Inspect git diffs across impacted repos and publish Decision-First review cards in DevBrief.', {
684
+ sessionId: z.string(),
685
+ }, async ({ sessionId }) => ({
686
+ messages: [
687
+ {
688
+ role: 'user',
689
+ content: {
690
+ type: 'text',
691
+ text: [
692
+ `Prepare a Decision-First Code Review in DevBrief for session "${sessionId}".`,
693
+ '1. Inspect git diffs across the modified repos (you can use devbrief_git_diff_summary + git diff).',
694
+ '2. Group changes by behavioral meaning & risk — NOT alphabetically by file:',
695
+ ' - contract / database / security (critical/high)',
696
+ ' - business_logic & agent_decision (explicitly explain every assumption or trade-off you chose)',
697
+ ' - new_stack_bridge (for C# or unfamiliar stacks, include stackBridgeNote translating idioms to Python mental models)',
698
+ ' - boilerplate (low risk, concise summary so the human can skip reading it)',
699
+ '3. Call devbrief_publish_review with focused diff snippets and Before -> After behavior summaries.',
700
+ '4. Return the DevBrief Review UI URL and highlight the top 3 items I should inspect first.',
701
+ ].join('\n'),
702
+ },
703
+ },
704
+ ],
705
+ }));
706
+ server.prompt('run-regression-and-evidence', 'Verify the feature and Blast Radius regressions locally, then attach screenshots/API/DB evidence to DevBrief.', {
707
+ sessionId: z.string(),
708
+ }, async ({ sessionId }) => ({
709
+ messages: [
710
+ {
711
+ role: 'user',
712
+ content: {
713
+ type: 'text',
714
+ text: [
715
+ `Build the Verification & Regression Evidence Pack in DevBrief for session "${sessionId}".`,
716
+ '1. Read the session via devbrief_get_session to review approved invariants and blastRadius.',
717
+ '2. Call devbrief_set_verification_plan (with setPhaseToVerification=true) covering:',
718
+ ' - Happy path + edge cases of the new PBI (kind: feature / edge_case)',
719
+ ' - At least 2-3 regression checks linked to blastRadius items (kind: regression)',
720
+ ' - Real DB state verification (kind: db_check)',
721
+ '3. Run the services locally, execute browser/API/DB checks, and attach concrete proofs via devbrief_attach_evidence (screenshots, API JSON, SQL output, logs).',
722
+ '4. Call devbrief_propose_doc_updates for any root specs/docs that should be updated to reflect the new system behavior.',
723
+ '5. Return the DevBrief Verification UI URL.',
724
+ ].join('\n'),
725
+ },
726
+ },
727
+ ],
728
+ }));
729
+ return server;
730
+ }
731
+ export async function runStdioMcpServer(options) {
732
+ const server = createDevBriefMcpServer(options);
733
+ const transport = new StdioServerTransport();
734
+ await server.connect(transport);
735
+ }