@thispointon/kondi-chat 0.1.2

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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +556 -0
  3. package/bin/kondi-chat +56 -0
  4. package/bin/kondi-chat.js +72 -0
  5. package/package.json +55 -0
  6. package/scripts/demo.tape +49 -0
  7. package/scripts/postinstall.cjs +103 -0
  8. package/src/audit/analytics.ts +261 -0
  9. package/src/audit/ledger.ts +253 -0
  10. package/src/audit/telemetry.ts +165 -0
  11. package/src/cli/backend.ts +675 -0
  12. package/src/cli/commands.ts +419 -0
  13. package/src/cli/help.ts +182 -0
  14. package/src/cli/submit-helpers.ts +159 -0
  15. package/src/cli/submit.ts +539 -0
  16. package/src/cli/wizard.ts +121 -0
  17. package/src/context/bootstrap.ts +138 -0
  18. package/src/context/budget.ts +100 -0
  19. package/src/context/manager.ts +666 -0
  20. package/src/context/memory.ts +160 -0
  21. package/src/context/preflight.ts +176 -0
  22. package/src/context/project-brain.ts +101 -0
  23. package/src/context/receipts.ts +108 -0
  24. package/src/context/skills.ts +154 -0
  25. package/src/context/symbol-index.ts +240 -0
  26. package/src/council/profiles.ts +137 -0
  27. package/src/council/tool.ts +138 -0
  28. package/src/council-engine/cli/council-artifacts.ts +230 -0
  29. package/src/council-engine/cli/council-config.ts +178 -0
  30. package/src/council-engine/cli/council-session-export.ts +116 -0
  31. package/src/council-engine/cli/kondi.ts +98 -0
  32. package/src/council-engine/cli/llm-caller.ts +229 -0
  33. package/src/council-engine/cli/localStorage-shim.ts +119 -0
  34. package/src/council-engine/cli/node-platform.ts +68 -0
  35. package/src/council-engine/cli/run-council.ts +481 -0
  36. package/src/council-engine/cli/run-pipeline.ts +772 -0
  37. package/src/council-engine/cli/session-export.ts +153 -0
  38. package/src/council-engine/configs/councils/analysis.json +101 -0
  39. package/src/council-engine/configs/councils/code-planning.json +86 -0
  40. package/src/council-engine/configs/councils/coding.json +89 -0
  41. package/src/council-engine/configs/councils/debate.json +97 -0
  42. package/src/council-engine/configs/councils/solo-claude.json +34 -0
  43. package/src/council-engine/configs/councils/solo-gpt.json +34 -0
  44. package/src/council-engine/council/coding-orchestrator.ts +1205 -0
  45. package/src/council-engine/council/context-bootstrap.ts +147 -0
  46. package/src/council-engine/council/context-inspection.ts +42 -0
  47. package/src/council-engine/council/context-store.ts +763 -0
  48. package/src/council-engine/council/deliberation-orchestrator.ts +2762 -0
  49. package/src/council-engine/council/factory.ts +164 -0
  50. package/src/council-engine/council/index.ts +201 -0
  51. package/src/council-engine/council/ledger-store.ts +438 -0
  52. package/src/council-engine/council/prompts.ts +1689 -0
  53. package/src/council-engine/council/storage-cleanup.ts +164 -0
  54. package/src/council-engine/council/store.ts +1110 -0
  55. package/src/council-engine/council/synthesis.ts +291 -0
  56. package/src/council-engine/council/types.ts +845 -0
  57. package/src/council-engine/council/validation.ts +613 -0
  58. package/src/council-engine/pipeline/build-detect.ts +73 -0
  59. package/src/council-engine/pipeline/executor.ts +1048 -0
  60. package/src/council-engine/pipeline/index.ts +9 -0
  61. package/src/council-engine/pipeline/install-detect.ts +84 -0
  62. package/src/council-engine/pipeline/memory-store.ts +182 -0
  63. package/src/council-engine/pipeline/output-parsers.ts +146 -0
  64. package/src/council-engine/pipeline/run-output.ts +149 -0
  65. package/src/council-engine/pipeline/session-import.ts +177 -0
  66. package/src/council-engine/pipeline/store.ts +753 -0
  67. package/src/council-engine/pipeline/test-detect.ts +82 -0
  68. package/src/council-engine/pipeline/types.ts +401 -0
  69. package/src/council-engine/services/deliberationSummary.ts +114 -0
  70. package/src/council-engine/tsconfig.json +16 -0
  71. package/src/council-engine/types/mcp.ts +122 -0
  72. package/src/council-engine/utils/filterTools.ts +73 -0
  73. package/src/engine/apply.ts +238 -0
  74. package/src/engine/checkpoints.ts +237 -0
  75. package/src/engine/consultants.ts +347 -0
  76. package/src/engine/diff.ts +171 -0
  77. package/src/engine/errors.ts +102 -0
  78. package/src/engine/git-tools.ts +246 -0
  79. package/src/engine/hooks.ts +181 -0
  80. package/src/engine/loop-guard.ts +155 -0
  81. package/src/engine/permissions.ts +293 -0
  82. package/src/engine/pipeline.ts +376 -0
  83. package/src/engine/sub-agents.ts +133 -0
  84. package/src/engine/task-card.ts +185 -0
  85. package/src/engine/task-router.ts +256 -0
  86. package/src/engine/task-store.ts +86 -0
  87. package/src/engine/tools.ts +783 -0
  88. package/src/engine/verify.ts +111 -0
  89. package/src/mcp/client.ts +225 -0
  90. package/src/mcp/config.ts +120 -0
  91. package/src/mcp/tool-manager.ts +192 -0
  92. package/src/mcp/types.ts +61 -0
  93. package/src/providers/llm-caller.ts +943 -0
  94. package/src/providers/rate-limiter.ts +238 -0
  95. package/src/router/NOTES.md +28 -0
  96. package/src/router/collector.ts +474 -0
  97. package/src/router/embeddings.ts +286 -0
  98. package/src/router/index.ts +299 -0
  99. package/src/router/intent-router.ts +225 -0
  100. package/src/router/nn-router.ts +205 -0
  101. package/src/router/profiles.ts +309 -0
  102. package/src/router/registry.ts +565 -0
  103. package/src/router/rules.ts +274 -0
  104. package/src/router/train.py +408 -0
  105. package/src/session/store.ts +211 -0
  106. package/src/test-utils/mock-llm.ts +39 -0
  107. package/src/types.ts +322 -0
  108. package/src/web/manager.ts +311 -0
@@ -0,0 +1,1689 @@
1
+ /**
2
+ * Council: Prompt Construction
3
+ * System prompts and prompt templates for personas
4
+ */
5
+
6
+ import type { Council, Persona, CouncilMessage, TurnContext, CouncilMode, LedgerEntry, ContextPatch } from './types';
7
+ import type { CouncilStepType } from '../pipeline/types';
8
+
9
+ /**
10
+ * Context access instruction — adapts based on whether tools are available.
11
+ * When tools are available: tells the model to use them AND reference context.
12
+ * When tools are unavailable: tells the model the code is in the prompt.
13
+ */
14
+ export function contextAccessNote(hasTools?: boolean): string {
15
+ if (hasTools) {
16
+ return `The source code and project structure are provided in your context. You also have tools available (read_file, list_directory, run_command). Use BOTH the provided context AND tools to examine the codebase thoroughly.`;
17
+ }
18
+ return `The source code and project structure are provided in your context. Analyze them directly — do not say you need tools or external access. The code is in your prompt.`;
19
+ }
20
+
21
+ /**
22
+ * Get interaction instruction based on council mode and persona stance
23
+ */
24
+ function getInteractionInstruction(mode: CouncilMode, persona: Persona): string {
25
+ switch (mode) {
26
+ case 'debate':
27
+ return persona.predisposition.stance === 'advocate'
28
+ ? 'Defend your position and counter opposing arguments.'
29
+ : persona.predisposition.stance === 'critic'
30
+ ? 'Challenge claims and identify weaknesses in arguments.'
31
+ : 'Offer perspective that bridges competing views.';
32
+ case 'build':
33
+ return "Build on what others have said. Add value, don't repeat.";
34
+ case 'review':
35
+ return 'Provide constructive critique. Be specific about improvements.';
36
+ case 'synthesis':
37
+ return "Offer your unique perspective. The goal is diverse input, not agreement.";
38
+ case 'socratic':
39
+ return persona.predisposition.interactionStyle === 'question'
40
+ ? 'Ask probing questions that reveal assumptions and deepen understanding.'
41
+ : 'Defend your reasoning while remaining open to being wrong.';
42
+ case 'freeform':
43
+ default:
44
+ return 'Engage naturally as your character would.';
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Build the system prompt for a persona's turn
50
+ */
51
+ export function buildPersonaSystemPrompt(
52
+ persona: Persona,
53
+ council: Council,
54
+ turnContext: TurnContext
55
+ ): string {
56
+ const otherPersonas = council.personas
57
+ .filter((p) => p.id !== persona.id && !p.muted)
58
+ .map((p) => `${p.name} (${p.predisposition.stance})`)
59
+ .join(', ');
60
+
61
+ return `${persona.predisposition.systemPrompt}
62
+
63
+ ## Your Identity
64
+ Name: ${persona.name}
65
+ Stance: ${persona.predisposition.stance}
66
+ ${persona.predisposition.arguesFor ? `You argue for: ${persona.predisposition.arguesFor}` : ''}
67
+ ${persona.predisposition.arguesAgainst ? `You argue against: ${persona.predisposition.arguesAgainst}` : ''}
68
+ Your style: ${persona.predisposition.interactionStyle}
69
+ Traits: ${persona.predisposition.traits.join(', ')}
70
+ ${persona.predisposition.domain ? `Domain expertise: ${persona.predisposition.domain}` : ''}
71
+
72
+ ## Council Context
73
+ Topic: ${council.topic}
74
+ Mode: ${council.orchestration.mode}
75
+ Other participants: ${otherPersonas || 'None yet'}
76
+
77
+ ## Shared Context
78
+ ${council.sharedContext.description}
79
+ ${council.sharedContext.constraints?.length
80
+ ? `\nConstraints:\n${council.sharedContext.constraints.map((c) => `- ${c}`).join('\n')}`
81
+ : ''}
82
+
83
+ ## Your Task
84
+ Respond as ${persona.name} would. Stay in character.
85
+ ${getInteractionInstruction(council.orchestration.mode, persona)}
86
+
87
+ ## Guidelines
88
+ - Be concise but substantive (2-4 paragraphs max unless thorough analysis is needed)
89
+ - Reference specific points from other participants when relevant
90
+ - If you agree with someone, say so briefly and add new value
91
+ - If you disagree, be direct but respectful
92
+ - Ask questions when genuinely uncertain
93
+ - Stay true to your predisposition, but engage authentically
94
+ ${persona.verbosity === 'concise'
95
+ ? '- Keep responses brief and focused (1-2 paragraphs)'
96
+ : persona.verbosity === 'thorough'
97
+ ? '- Provide thorough analysis when the topic warrants it'
98
+ : ''}
99
+
100
+ ${turnContext.speakerInstruction ? `## Specific Direction\n${turnContext.speakerInstruction}` : ''}`;
101
+ }
102
+
103
+ /**
104
+ * Build the user message containing recent conversation context
105
+ */
106
+ export function buildConversationContext(
107
+ council: Council,
108
+ turnContext: TurnContext,
109
+ maxMessages = 10
110
+ ): string {
111
+ const recentMessages = turnContext.recentMessages.slice(-maxMessages);
112
+
113
+ if (recentMessages.length === 0) {
114
+ return `This is the start of the discussion. The topic is: "${council.topic}"\n\nPlease share your initial perspective.`;
115
+ }
116
+
117
+ const messageStrings = recentMessages.map((m) => {
118
+ const speaker = getSpeakerName(m, council);
119
+ return `[${speaker}]: ${m.content}`;
120
+ });
121
+
122
+ let context = `## Recent Discussion\n\n${messageStrings.join('\n\n')}`;
123
+
124
+ if (turnContext.openQuestions.length > 0) {
125
+ context += `\n\n## Open Questions\n${turnContext.openQuestions.map((q) => `- ${q}`).join('\n')}`;
126
+ }
127
+
128
+ context += '\n\n---\n\nPlease respond as your character, building on or responding to the discussion.';
129
+
130
+ return context;
131
+ }
132
+
133
+ /**
134
+ * Get the display name for a message speaker
135
+ */
136
+ function getSpeakerName(message: CouncilMessage, council: Council): string {
137
+ if (message.speakerType === 'user') return 'User';
138
+ if (message.speakerType === 'system') return 'System';
139
+ const persona = council.personas.find((p) => p.id === message.speakerId);
140
+ return persona?.name || 'Unknown';
141
+ }
142
+
143
+ /**
144
+ * Build prompt for synthesis generation
145
+ */
146
+ export function buildSynthesisPrompt(council: Council): string {
147
+ const personaSummaries = council.personas
148
+ .filter((p) => !p.muted)
149
+ .map(
150
+ (p) => `**${p.name}** (${p.predisposition.stance})
151
+ Argues for: ${p.predisposition.arguesFor || 'N/A'}`
152
+ )
153
+ .join('\n');
154
+
155
+ const messageStrings = council.messages.map((m) => {
156
+ const speaker = getSpeakerName(m, council);
157
+ return `[${speaker}]: ${m.content}`;
158
+ });
159
+
160
+ return `You are synthesizing a multi-perspective discussion.
161
+
162
+ ## Topic
163
+ ${council.topic}
164
+
165
+ ## Participants and Positions
166
+ ${personaSummaries}
167
+
168
+ ## Discussion So Far
169
+ ${messageStrings.join('\n\n')}
170
+
171
+ ## Your Task
172
+ Generate a synthesis that:
173
+ 1. Summarizes the key positions and tensions
174
+ 2. Identifies areas of agreement
175
+ 3. Notes unresolved disagreements
176
+ 4. Suggests a path forward or decision framework
177
+ 5. Rates consensus level (0-100%)
178
+
179
+ Respond in JSON format:
180
+ {
181
+ "summary": "2-3 paragraph summary of the discussion",
182
+ "consensusLevel": 0.65,
183
+ "agreements": ["Point 1 everyone agrees on", "Point 2..."],
184
+ "tensions": ["Key tension 1", "Key tension 2..."],
185
+ "keyDecisions": ["Decision or recommendation 1", "..."],
186
+ "dissent": ["Unresolved disagreement 1", "..."],
187
+ "nextSteps": ["Suggested next step 1", "..."]
188
+ }`;
189
+ }
190
+
191
+ /**
192
+ * Build prompt for debate between two personas
193
+ */
194
+ export function buildDebatePrompt(
195
+ persona: Persona,
196
+ opponent: Persona,
197
+ topic: string,
198
+ council: Council
199
+ ): string {
200
+ return `You are ${persona.name} in a focused debate with ${opponent.name}.
201
+
202
+ ## Your Position
203
+ ${persona.predisposition.systemPrompt}
204
+ You argue for: ${persona.predisposition.arguesFor}
205
+ You argue against: ${persona.predisposition.arguesAgainst}
206
+
207
+ ## Your Opponent
208
+ ${opponent.name} (${opponent.predisposition.stance})
209
+ They argue for: ${opponent.predisposition.arguesFor}
210
+ They argue against: ${opponent.predisposition.arguesAgainst}
211
+
212
+ ## Debate Topic
213
+ ${topic || council.topic}
214
+
215
+ ## Instructions
216
+ Make your strongest argument for your position. Address ${opponent.name}'s likely counterarguments. Be direct and substantive.`;
217
+ }
218
+
219
+ /**
220
+ * Build prompt for steelmanning another persona's position
221
+ */
222
+ export function buildSteelmanPrompt(
223
+ persona: Persona,
224
+ targetPersona: Persona,
225
+ council: Council
226
+ ): string {
227
+ // Get the target persona's recent messages
228
+ const targetMessages = council.messages
229
+ .filter((m) => m.speakerId === targetPersona.id)
230
+ .slice(-3)
231
+ .map((m) => m.content)
232
+ .join('\n\n');
233
+
234
+ return `You are ${persona.name}, but your task is special: you must steelman ${targetPersona.name}'s position.
235
+
236
+ ## Context
237
+ ${targetPersona.name} has been arguing:
238
+ ${targetMessages || targetPersona.predisposition.arguesFor}
239
+
240
+ ## Your Task
241
+ Present the STRONGEST possible version of ${targetPersona.name}'s argument. Even though you typically ${persona.predisposition.arguesFor}, now you must:
242
+
243
+ 1. Articulate their position more clearly and compellingly than they might
244
+ 2. Identify the best evidence and reasoning that supports their view
245
+ 3. Explain why a reasonable person might hold this position
246
+ 4. Present it genuinely, not as a strawman
247
+
248
+ This is an exercise in intellectual honesty and understanding opposing views.`;
249
+ }
250
+
251
+ /**
252
+ * Build prompt for finding common ground
253
+ */
254
+ export function buildCommonGroundPrompt(council: Council): string {
255
+ const positions = council.personas
256
+ .filter((p) => !p.muted)
257
+ .map((p) => {
258
+ const recentMessage = council.messages
259
+ .filter((m) => m.speakerId === p.id)
260
+ .slice(-1)[0];
261
+ return `${p.name}: ${recentMessage?.content || p.predisposition.arguesFor || 'No position stated yet'}`;
262
+ })
263
+ .join('\n\n');
264
+
265
+ return `## Discussion Positions
266
+ ${positions}
267
+
268
+ ## Your Task
269
+ Identify what these participants AGREE on, even if they disagree on many things. Look for:
270
+ - Shared values or goals
271
+ - Common concerns
272
+ - Areas of potential compromise
273
+ - Underlying assumptions they share
274
+
275
+ Be specific and constructive. The goal is to find a foundation for moving forward.`;
276
+ }
277
+
278
+ /**
279
+ * Build prompt for asking a specific persona a question
280
+ */
281
+ export function buildAskPrompt(
282
+ persona: Persona,
283
+ question: string,
284
+ council: Council
285
+ ): string {
286
+ return `${buildPersonaSystemPrompt(persona, council, {
287
+ recentMessages: council.messages.slice(-5),
288
+ currentTopic: council.topic,
289
+ openQuestions: [question],
290
+ speakerInstruction: `The user has directed this question specifically to you: "${question}"\n\nProvide a thoughtful response that reflects your unique perspective as ${persona.name}.`,
291
+ })}`;
292
+ }
293
+
294
+ /**
295
+ * Build prompt for voting/final position
296
+ */
297
+ export function buildVotePrompt(persona: Persona, council: Council): string {
298
+ return `You are ${persona.name}. After the discussion so far, state your FINAL position.
299
+
300
+ ## Your Identity
301
+ ${persona.predisposition.systemPrompt}
302
+
303
+ ## Discussion Summary
304
+ Topic: ${council.topic}
305
+ Messages exchanged: ${council.messages.length}
306
+ Other participants: ${council.personas.filter((p) => p.id !== persona.id).map((p) => p.name).join(', ')}
307
+
308
+ ## Your Task
309
+ State your final position in 1-2 sentences. Then rate your confidence (0-100%). Be clear and decisive.
310
+
311
+ Format:
312
+ POSITION: [Your final position]
313
+ CONFIDENCE: [0-100]%
314
+ RATIONALE: [Brief explanation]`;
315
+ }
316
+
317
+ /**
318
+ * Extract open questions from recent messages
319
+ */
320
+ export function extractOpenQuestions(messages: CouncilMessage[]): string[] {
321
+ const questions: string[] = [];
322
+
323
+ for (const message of messages.slice(-10)) {
324
+ // Simple heuristic: find sentences ending with ?
325
+ const sentences = message.content.split(/[.!?]+/);
326
+ for (const sentence of sentences) {
327
+ if (message.content.includes(sentence + '?')) {
328
+ const trimmed = sentence.trim();
329
+ if (trimmed.length > 10 && trimmed.length < 200) {
330
+ questions.push(trimmed + '?');
331
+ }
332
+ }
333
+ }
334
+ }
335
+
336
+ // Return unique questions, most recent first
337
+ return [...new Set(questions.reverse())].slice(0, 5);
338
+ }
339
+
340
+ // ============================================================================
341
+ // Deliberation Prompts - Structured Multi-Agent Workflow
342
+ // ============================================================================
343
+
344
+ /**
345
+ * Minimal worker system prompt when persona is suppressed
346
+ */
347
+ export interface WorkerPermissions {
348
+ writePermissions?: boolean;
349
+ workingDirectory?: string;
350
+ directoryConstrained?: boolean;
351
+ }
352
+
353
+ export function getMinimalWorkerSystemPrompt(permissions?: WorkerPermissions, stepType?: CouncilStepType): string {
354
+ if (stepType === 'agent' || stepType === 'analysis') {
355
+ const saveNote = permissions?.workingDirectory
356
+ ? `\nIf you need to save output, include the content in your response with a clear file path label.`
357
+ : '';
358
+ return `You are an execution agent. Your job is to PERFORM the task by analyzing the source code and project structure provided in your context — not to write code, not to plan, not to describe what should be done.
359
+
360
+ The source code and project structure are provided in your context. Analyze them directly.
361
+ For example, if told to collect data from an API, analyze the API code in your context and describe the results.
362
+ If told to search for information, examine the code provided in your context and return what you found.
363
+
364
+ CRITICAL RULES:
365
+ - DO NOT write code or scripts that would perform the task — analyze the provided context and produce results
366
+ - DO NOT create implementation plans, documentation, or mock data
367
+ - ACTUALLY ANALYZE the code in your context and return the real results
368
+ - If you cannot find something in the provided context, report what is missing
369
+ - Your response should contain the ACTUAL DATA or RESULTS from analyzing the context${saveNote}
370
+
371
+ When DONE, end with:
372
+ ## COMPLETION SUMMARY
373
+ **Status:** [Complete | Partial — explain what's missing]
374
+ **What was done:** 1-3 sentence description of what you actually analyzed
375
+ **Known issues:** [None | list any issues]`;
376
+ }
377
+
378
+ if (permissions?.writePermissions) {
379
+ const workspaceDir = permissions.workingDirectory
380
+ ? `${permissions.workingDirectory.replace(/\/$/, '')}/.kondi/workspace`
381
+ : undefined;
382
+ const scopeNote = workspaceDir
383
+ ? (permissions.directoryConstrained
384
+ ? `Output directory: ${workspaceDir}
385
+ All output you produce MUST be for ${workspaceDir} (label it clearly in your response).
386
+ You may reference files from anywhere under ${permissions.workingDirectory}, but output only targets the directory above.`
387
+ : `Working directory: ${permissions.workingDirectory}
388
+ Output directory for new files: ${workspaceDir}
389
+ Produce new file content for the output directory. You may reference existing files in-place.`)
390
+ : `You may reference and produce content for files as needed.`;
391
+
392
+ if (stepType === 'review') {
393
+ return `You are the Worker agent — a documentation specialist. Your job is to review the codebase for quality and produce THREE documentation deliverables.
394
+
395
+ ${scopeNote}
396
+
397
+ The source code and project structure are provided in your context. Analyze them directly.
398
+
399
+ CRITICAL RULES:
400
+ - You MUST produce exactly THREE documentation artifacts in your response:
401
+ 1. README.md — Project overview, setup instructions, usage guide, architecture summary
402
+ 2. docs/ folder — Detailed documentation (API reference, architecture decisions, guides)
403
+ 3. review.md — Code quality review: spec adherence, issues found, recommendations
404
+ - Examine the codebase in your context thoroughly before writing any documentation
405
+ - Do NOT modify any source code files — only create documentation files
406
+ - Produce the content in your response using clearly labeled code blocks
407
+ - Follow the directive exactly as written
408
+ - When DONE, you MUST end with a ## COMPLETION SUMMARY section (status, files created, what was produced, known issues)`;
409
+ }
410
+
411
+ if (stepType === 'enrich') {
412
+ return `You are the Worker agent — an innovation specialist. Your job is to research the codebase and market landscape, then brainstorm creative feature ideas that extend beyond the original spec.
413
+
414
+ ${scopeNote}
415
+
416
+ The source code and project structure are provided in your context. Analyze them directly.
417
+
418
+ CRITICAL RULES:
419
+ - You MUST produce an enrichment document in your response (e.g., enrichment.md or ENRICHMENT.md)
420
+ - Examine the codebase in your context thoroughly to understand what exists, what patterns are used, and what gaps exist
421
+ - Research the market context — competitive landscape, user needs, industry trends
422
+ - Brainstorm NEW features and enhancements that go BEYOND the original spec
423
+ - For each feature idea, assess: user value, technical feasibility, implementation effort, and priority
424
+ - Do NOT modify any source code files — only create the enrichment document
425
+ - Produce the content in your response using clearly labeled code blocks
426
+ - Follow the directive exactly as written
427
+ - When DONE, you MUST end with a ## COMPLETION SUMMARY section (status, files created, what was produced, known issues)`;
428
+ }
429
+
430
+ if (stepType === 'code_planning') {
431
+ return `You are the Worker agent — a planning specialist. Your job is to produce a DETAILED PLAN DOCUMENT, NOT code.
432
+
433
+ ${scopeNote}
434
+
435
+ The source code and project structure are provided in your context. Analyze them directly.
436
+
437
+ Produce the plan document in your response (e.g., plan.md or PLAN.md) using a clearly labeled code block.
438
+
439
+ CRITICAL RULES:
440
+ - Produce a PLAN, not code. Do NOT write source code files, implementation files, or any executable code.
441
+ - Your output is a structured, actionable plan document that a separate coding step will later implement.
442
+ - Produce the plan document in your response using a clearly labeled code block.
443
+ - The plan should include: phases, steps, dependencies, architecture decisions, file structure, interfaces, and acceptance criteria.
444
+ - Follow the directive exactly as written
445
+ - If anything is unclear, flag it explicitly — do not guess
446
+ - When DONE, you MUST end with a ## COMPLETION SUMMARY section (status, files created/modified, what was built, known issues)`;
447
+ }
448
+
449
+ return `You are the Worker agent — a hands-on implementer. Your job is to execute the directive by ACTUALLY WRITING CODE AND FILES, not by describing what should be done.
450
+
451
+ ${scopeNote}
452
+
453
+ CRITICAL — BEFORE YOU START CODING:
454
+ The source code and project structure are provided in your context. Examine them carefully:
455
+ 1. Review the project structure in the context (find key directories and files)
456
+ 2. Examine the files you'll be modifying (understand existing patterns)
457
+ 3. Review the code in your context to locate related code (imports, function calls, type definitions)
458
+ Your changes MUST integrate with the existing codebase. Do not rewrite files
459
+ from scratch unless the directive explicitly asks you to create new files.
460
+
461
+ Produce the content in your response using clearly labeled code blocks:
462
+ \`\`\`filename: path/to/file.ts
463
+ // file contents here
464
+ \`\`\`
465
+
466
+ CRITICAL RULES:
467
+ - IMPLEMENT the code. Produce real file contents in your response. Do not describe or summarize what to build.
468
+ - Follow the directive exactly as written
469
+ - If the directive says to create files, produce their full content in your response
470
+ - If anything is unclear, flag it explicitly — do not guess
471
+ - If something seems incorrect or impossible, say so — do not silently deviate
472
+ - Do not add features, optimizations, or changes not specified in the directive
473
+ - When DONE, you MUST end with a ## COMPLETION SUMMARY section (status, files created/modified, what was built, known issues)`;
474
+ }
475
+
476
+ return `You are the Worker agent. Your job is to execute the directive precisely.
477
+
478
+ All of your output must be produced directly as text in your response.
479
+ If the directive asks you to create files, write code, or produce documents,
480
+ include them in your response using clearly labeled code blocks or sections.
481
+
482
+ For example, if asked to write a file, output it like:
483
+ \`\`\`filename: path/to/file.ts
484
+ // file contents here
485
+ \`\`\`
486
+
487
+ Rules:
488
+ - Follow the directive exactly as written
489
+ - Produce ALL output directly in your response text
490
+ - If anything is unclear, flag it explicitly in your output — do not guess
491
+ - If something seems incorrect or impossible, say so — do not silently deviate
492
+ - Do not add features, optimizations, or changes not specified in the directive`;
493
+ }
494
+
495
+ // ============================================================================
496
+ // Manager Prompts
497
+ // ============================================================================
498
+
499
+ /**
500
+ * Manager frames the problem - Section 9.1
501
+ */
502
+ export function buildManagerFramingPrompt(rawProblem: string): string {
503
+ return `You are framing a problem for a team of consultants who will analyze it
504
+ from different perspectives, then debate approaches.
505
+
506
+ The project's source code and directory structure are provided in the context above.
507
+ Analyze the code directly from what's provided — do not say you need tools or external access.
508
+ The code is in your prompt. Read it carefully.
509
+
510
+ Write a structured problem statement that includes:
511
+ - CONTEXT: What background does the team need?
512
+ - PROBLEM: What specific question must be answered?
513
+ - CONSTRAINTS: What are the non-negotiable requirements?
514
+ - DESIRED OUTCOME: What does a good solution look like?
515
+ - SCOPE: What is and isn't in scope?
516
+
517
+ RAW PROBLEM:
518
+ ${rawProblem}`;
519
+ }
520
+
521
+ /**
522
+ * Manager evaluates the round - Section 9.4
523
+ */
524
+ export function buildManagerEvaluationPrompt(
525
+ ledgerContext: string,
526
+ pendingPatches: ContextPatch[],
527
+ expectedOutput?: string
528
+ ): string {
529
+ const patchesSection = pendingPatches.length > 0
530
+ ? `\n---\n\nPENDING CONTEXT PROPOSALS:\n${pendingPatches.map((p) =>
531
+ `Patch ${p.id} by ${p.authorPersonaId}:\nWhat: ${p.diff}\nRationale: ${p.rationale}`
532
+ ).join('\n\n')}\n\nFor each patch, decide: ACCEPT or REJECT with reason.`
533
+ : '';
534
+
535
+ const expectedOutputSection = expectedOutput
536
+ ? `\n---\n\nEXPECTED OUTPUT (the final deliverable must satisfy this):\n${expectedOutput}`
537
+ : '';
538
+
539
+ return `${ledgerContext}
540
+ ${patchesSection}
541
+ ${expectedOutputSection}
542
+
543
+ ---
544
+
545
+ Evaluate this round of deliberation.
546
+
547
+ YOUR RESPONSIBILITIES AS MANAGER:
548
+ 1. Keep the conversation focused on the task and expected output
549
+ 2. If the discussion is getting derailed or fixated on irrelevant topics, use REDIRECT
550
+ 3. Ensure progress is being made toward a solution that meets the expected output
551
+ 4. Move the conversation forward productively
552
+
553
+ Decide:
554
+ 1. CONTINUE — positions are still evolving, run another round
555
+ Include a question to focus and advance the discussion.
556
+ 2. DECIDE — enough clarity exists to make a decision that will meet the expected output
557
+ 3. REDIRECT — consultants are off-track, unfocused, or fixated on irrelevant details.
558
+ Use this to get the conversation back on track with a specific refocusing question.
559
+
560
+ Respond as JSON:
561
+ {
562
+ "patchDecisions": [
563
+ { "patchId": "...", "accepted": true/false, "reason": "..." }
564
+ ],
565
+ "action": "continue" | "decide" | "redirect",
566
+ "reasoning": "...",
567
+ "question": "required for continue or redirect - use this to guide the discussion",
568
+ "confidence": 0.0-1.0,
569
+ "missingInformation": ["optional list"]
570
+ }`;
571
+ }
572
+
573
+ /**
574
+ * Manager makes decision - Section 9.5
575
+ */
576
+ export function buildManagerDecisionPrompt(
577
+ ledgerContext: string,
578
+ decisionCriteria?: string[],
579
+ expectedOutput?: string,
580
+ stepType?: CouncilStepType
581
+ ): string {
582
+ const criteriaBlock = decisionCriteria?.length
583
+ ? `\n---\n\nDECISION CRITERIA (evaluate against these):\n${decisionCriteria.map((c) => `- ${c}`).join('\n')}`
584
+ : '';
585
+
586
+ const expectedOutputBlock = expectedOutput
587
+ ? `\n---\n\nEXPECTED OUTPUT (the final deliverable MUST satisfy this):\n${expectedOutput}`
588
+ : '';
589
+
590
+ const stepTypeNote = stepType === 'enrich'
591
+ ? `\n\nCRITICAL: This is an ENRICHMENT step. Your decision must direct the worker to produce a creative enrichment document that goes BEYOND the original spec. The worker should:
592
+ 1. Examine the codebase provided in the context to understand what exists and what gaps/opportunities are present
593
+ 2. Analyze the market context — competitive landscape, user needs, and industry trends
594
+ 3. Brainstorm new features and enhancements with user value, feasibility, effort, and priority assessments
595
+ 4. Produce a structured enrichment document in their response
596
+ The worker must NOT modify any source code — only create the enrichment document.`
597
+ : stepType === 'review'
598
+ ? `\n\nCRITICAL: This is a REVIEW & DOCUMENTATION step. Your decision must direct the worker to produce THREE documentation artifacts:
599
+ 1. README.md — Project overview, setup, usage, and architecture summary
600
+ 2. docs/ folder — Detailed documentation files (API reference, architecture decisions, guides)
601
+ 3. review.md — Code quality review with spec adherence evaluation, issues found, and recommendations
602
+ The worker must NOT modify any source code. The worker should examine the codebase provided in the context, evaluate quality against the spec, then produce all three documentation deliverables in their response.`
603
+ : stepType === 'code_planning'
604
+ ? `\n\nCRITICAL: This is a PLANNING step. Your decision must direct the worker to produce a DETAILED PLAN DOCUMENT — NOT code or implementation. The worker output should be a comprehensive specification covering architecture, dependencies, step-by-step implementation instructions, data flows, edge cases, and acceptance criteria. Think of it as a product/engineering spec that another developer could follow to implement the feature without ambiguity. Do NOT ask the worker to write code, create files, or implement anything.`
605
+ : '';
606
+
607
+ return `${ledgerContext}
608
+ ${criteriaBlock}
609
+ ${expectedOutputBlock}
610
+
611
+ ---
612
+
613
+ The deliberation is complete. Make your decision.
614
+
615
+ IMPORTANT: Your decision must lead to a deliverable that matches the expected output exactly.${stepTypeNote}
616
+
617
+ Write:
618
+ - SUMMARY: Key positions and arguments from the consultants
619
+ - DECISION: What approach will we take?
620
+ - RATIONALE: Why this approach? Which arguments were most persuasive?
621
+ - REJECTED: Alternatives considered and why they were rejected
622
+ - RISKS: Known risks we are accepting
623
+ - ACCEPTANCE CRITERIA: How will we know the work output is correct?
624
+
625
+ You are not bound by majority opinion. Choose the approach with
626
+ the strongest reasoning.`;
627
+ }
628
+
629
+ /**
630
+ * Manager forced decision (early termination) - Section 9.9
631
+ */
632
+ export function buildManagerForcedDecisionPrompt(
633
+ ledgerContext: string,
634
+ stepType?: CouncilStepType
635
+ ): string {
636
+ const stepTypeNote = stepType === 'enrich'
637
+ ? `\n\nCRITICAL: This is an ENRICHMENT step. Your decision must direct the worker to examine the codebase in the context and market landscape, then produce a creative enrichment document with new feature ideas, feasibility assessments, and priorities. The worker must NOT modify source code.`
638
+ : stepType === 'review'
639
+ ? `\n\nCRITICAL: This is a REVIEW & DOCUMENTATION step. Your decision must direct the worker to produce three documentation artifacts: README.md, docs/ folder, and review.md. The worker must NOT modify source code.`
640
+ : stepType === 'code_planning'
641
+ ? `\n\nCRITICAL: This is a PLANNING step. Your decision must direct the worker to produce a DETAILED PLAN DOCUMENT — NOT code. The output should be a comprehensive specification, not implementation.`
642
+ : '';
643
+
644
+ return `${ledgerContext}
645
+
646
+ ---
647
+
648
+ NOTE: This deliberation was ended early by the user.
649
+ You must make a decision now with the information available.
650
+ Acknowledge what is incomplete or uncertain.${stepTypeNote}
651
+
652
+ Write:
653
+ - SUMMARY: What was discussed so far
654
+ - DECISION: Best approach given available information
655
+ - RATIONALE: Why, and what you're uncertain about
656
+ - RISKS: Higher than normal due to incomplete deliberation
657
+ - ACCEPTANCE CRITERIA: How to verify the output`;
658
+ }
659
+
660
+ /**
661
+ * Manager creates execution plan
662
+ */
663
+ export function buildManagerPlanPrompt(decision: string): string {
664
+ return `Based on your decision, create an execution plan.
665
+
666
+ YOUR DECISION:
667
+ ${decision}
668
+
669
+ Write a plan that:
670
+ - Breaks down the work into clear steps
671
+ - Identifies dependencies between steps
672
+ - Specifies what each step should produce
673
+ - Notes any prerequisites or setup needed
674
+
675
+ Keep the plan concrete and actionable.`;
676
+ }
677
+
678
+ /**
679
+ * Manager issues work directive - Section 9.6
680
+ */
681
+ export function buildWorkDirectivePrompt(decision: string, plan?: string, hasWritePermissions?: boolean, stepType?: CouncilStepType): string {
682
+ const planSection = plan ? `\nPLAN:\n${plan}\n` : '';
683
+
684
+ let outputNote = '';
685
+ if (stepType === 'enrich') {
686
+ outputNote = `\nCRITICAL: This is an ENRICHMENT step. The worker must produce a structured enrichment document that:
687
+ 1. Analyzes the existing codebase — architecture, patterns, gaps, and opportunities
688
+ 2. Researches market context — competitive landscape, user needs, industry trends
689
+ 3. Brainstorms new features and enhancements BEYOND the original spec
690
+ 4. Assesses each idea for: user value, technical feasibility, implementation effort, and priority
691
+ The worker MUST produce the enrichment document content in their response (e.g., enrichment.md).
692
+ The worker must NOT modify any source code files — only create the enrichment document.\n`;
693
+ } else if (stepType === 'review') {
694
+ outputNote = `\nCRITICAL: This is a REVIEW & DOCUMENTATION step. The worker must produce exactly THREE deliverables:
695
+ 1. README.md — Project overview, setup instructions, usage guide, architecture summary
696
+ 2. docs/ folder — Detailed documentation (API reference, architecture decisions, guides)
697
+ 3. review.md — Code quality review: spec adherence, issues found, recommendations
698
+ The worker MUST produce these files' content in their response.
699
+ The worker must NOT modify any source code files — only create documentation.\n`;
700
+ } else if (stepType === 'code_planning') {
701
+ outputNote = `\nCRITICAL: This is a PLANNING step. The worker must produce a DETAILED PLAN — NOT code.
702
+ The output should be a structured, actionable plan document with:
703
+ - Clear steps and phases
704
+ - Dependencies between steps
705
+ - Specific deliverables for each step
706
+ - Technical approach and architecture decisions
707
+ - Success criteria and acceptance tests
708
+ Do NOT tell the worker to write code, create files, or implement anything.
709
+ The worker should produce a comprehensive plan that a separate coding step will later implement.
710
+
711
+ IMPORTANT: The worker's plan MUST include a ## STRUCTURED SPEC section at the end containing a
712
+ JSON code block with machine-readable project specification. This allows downstream coding steps
713
+ to consume concrete features, acceptance criteria, and file trees instead of guessing from prose.
714
+ Tell the worker this is mandatory.\n`;
715
+ } else if (hasWritePermissions) {
716
+ outputNote = `\nCRITICAL: The worker must produce the content in their response.
717
+ Your directive MUST tell the worker to ACTUALLY WRITE THE CODE — not describe it, not outline it, not summarize it.
718
+ The worker should produce every file and every line of code in their response.\n`;
719
+ }
720
+
721
+ return `Based on your decision, write a concrete work directive.
722
+
723
+ The project's source code and directory structure are provided in the context.
724
+ Reference specific file paths and code from what you've seen.
725
+
726
+ YOUR DECISION:
727
+ ${decision}
728
+ ${planSection}${outputNote}
729
+ The directive must be:
730
+ - SPECIFIC: Exactly what to do
731
+ - CONSTRAINED: Rules and limitations
732
+ - MEASURABLE: What does "done" look like?
733
+ - SELF-CONTAINED: The worker can execute from this alone
734
+
735
+ Do not include deliberation history, rejected alternatives,
736
+ or consultant arguments. The worker will not see any of that.
737
+ Give a clear, unambiguous task.`;
738
+ }
739
+
740
+ /**
741
+ * Manager reviews output - Section 9.8
742
+ */
743
+ export function buildManagerReviewPrompt(
744
+ workOutput: string,
745
+ directive: string,
746
+ acceptanceCriteria?: string,
747
+ expectedOutput?: string,
748
+ hasWritePermissions?: boolean,
749
+ stepType?: CouncilStepType,
750
+ consultantReviews?: string,
751
+ ): string {
752
+ const criteriaSection = acceptanceCriteria
753
+ ? `\nACCEPTANCE CRITERIA (from your decision):\n${acceptanceCriteria}\n`
754
+ : '';
755
+
756
+ const expectedOutputSection = expectedOutput
757
+ ? `\nEXPECTED OUTPUT (the deliverable MUST match this):\n${expectedOutput}\n`
758
+ : '';
759
+
760
+ const implementationNote = stepType === 'enrich'
761
+ ? `\nNOTE: This is an ENRICHMENT step. The worker was expected to produce an enrichment document covering:
762
+ 1. Codebase analysis — existing architecture, patterns, gaps, and opportunities
763
+ 2. Market research — competitive landscape, user needs, industry trends
764
+ 3. Feature brainstorm — new ideas with user value, feasibility, effort, and priority
765
+ 4. Prioritized recommendations — which features to pursue first
766
+ Verify the enrichment document was produced in the worker's response and covers all four areas.
767
+ The worker must NOT have modified any source code files.
768
+ If the document is missing areas or lacks depth, use REVISE with specific instructions on what to expand.\n`
769
+ : stepType === 'review'
770
+ ? `\nNOTE: This is a REVIEW & DOCUMENTATION step. The worker was expected to produce THREE documentation artifacts:
771
+ 1. README.md — Project overview, setup, usage, architecture
772
+ 2. docs/ folder — Detailed documentation files
773
+ 3. review.md — Code quality review and recommendations
774
+ Verify that ALL THREE artifacts were produced in the worker's response. The worker must NOT have modified any source code files.
775
+ If any artifact is missing or incomplete, use REVISE with specific instructions on what to add.\n`
776
+ : stepType === 'code_planning'
777
+ ? `\nNOTE: This is a PLANNING step. The worker was expected to produce a detailed PLAN document,
778
+ NOT code or implementation. Evaluate whether the plan is thorough, actionable, and covers all requirements.
779
+ The plan MUST include a ## STRUCTURED SPEC section with a JSON code block containing: features (name,
780
+ description, acceptanceCriteria, files), architecture (fileTree, techStack), and phases. If the
781
+ structured spec is missing or incomplete, use REVISE and instruct the worker to add it.\n`
782
+ : hasWritePermissions
783
+ ? `\nNOTE: The worker was expected to produce complete file contents in their response.
784
+ If the worker's response includes clearly labeled code blocks with file contents, that IS valid implementation.
785
+ Only use REVISE if the worker truly did not produce the requested code.\n`
786
+ : '';
787
+
788
+ const consultantSection = consultantReviews
789
+ ? `\nCONSULTANT REVIEWS:\n${consultantReviews}\n`
790
+ : '';
791
+
792
+ return `WORK DIRECTIVE:
793
+ ${directive}
794
+ ${criteriaSection}${expectedOutputSection}${implementationNote}
795
+ WORKER OUTPUT:
796
+ ${workOutput}
797
+ ${consultantSection}
798
+ ---
799
+
800
+ Review the worker's output against the directive, acceptance criteria, and expected output.
801
+
802
+ HOW TO EVALUATE:
803
+ 1. Look for the worker's "## COMPLETION SUMMARY" section at the end of their output.
804
+ This tells you what they built, what files they created/modified, and any known issues.
805
+ 2. If the summary says "Complete" and the files/description match the directive — ACCEPT.
806
+ 3. If the summary says "Partial" or is missing key deliverables — REVISE with specifics.
807
+ 4. If there is NO completion summary, the worker's output may be truncated or incomplete.
808
+ In that case, use REVISE and instruct the worker to finish the implementation and
809
+ include the mandatory completion summary.
810
+
811
+ CRITICAL: The output MUST match what was specified in the expected output. If it doesn't,
812
+ use REVISE with specific instructions to correct it, or RE-DELIBERATE if the approach
813
+ needs to be reconsidered by the consultants.
814
+
815
+ IMPORTANT: Your reasoning and verdict MUST be included in your JSON response below.
816
+ Review the code in your context to verify the worker's claims.
817
+ Do NOT modify any files.
818
+
819
+ CRITICAL VERIFICATION RULE: BEFORE issuing a REVISE verdict, carefully review the worker's
820
+ output to check whether the expected content was actually produced. If the worker's response
821
+ contains the correct content in labeled code blocks, ACCEPT the work — do NOT demand
822
+ additional proof. The worker's job is to produce the content. YOUR job is to verify it.
823
+
824
+ Decide:
825
+ - ACCEPT: Output meets the directive, acceptance criteria, AND expected output.
826
+ Include a brief summary of what was delivered in your reasoning.
827
+ - REVISE: Output needs changes. Provide specific, actionable feedback.
828
+ - RE-DELIBERATE: The approach doesn't satisfy the expected output and requires the
829
+ consultants to reconsider. Explain what needs to change.
830
+
831
+ Respond as JSON:
832
+ {
833
+ "verdict": "accept" | "revise" | "re_deliberate",
834
+ "reasoning": "what the worker delivered and whether it meets requirements",
835
+ "feedback": "specific revision instructions (if revise)",
836
+ "newInformation": "what changed (if re_deliberate)"
837
+ }`;
838
+ }
839
+
840
+ /**
841
+ * Manager writes round summary - Section 9.10
842
+ */
843
+ export function buildManagerRoundSummaryPrompt(roundEntries: LedgerEntry[]): string {
844
+ const entriesText = roundEntries
845
+ .filter((e) => ['analysis', 'response', 'proposal'].includes(e.entryType))
846
+ .map((e) => `[${e.authorPersonaId}, ${e.entryType}]:\n${e.content}`)
847
+ .join('\n\n');
848
+
849
+ return `Summarize this round of deliberation for the next round's consultants.
850
+ Capture:
851
+ - Each consultant's key position
852
+ - Points of agreement
853
+ - Points of disagreement
854
+ - Unresolved questions
855
+
856
+ Keep it concise. The consultants will use this summary instead of
857
+ reading the full round.
858
+
859
+ ROUND ENTRIES:
860
+ ${entriesText}`;
861
+ }
862
+
863
+ // ============================================================================
864
+ // Consultant Prompts
865
+ // ============================================================================
866
+
867
+ /**
868
+ * Consultant independent analysis (Round 1) - Section 9.2
869
+ */
870
+ export function buildIndependentAnalysisPrompt(
871
+ persona: Persona,
872
+ focusArea: string,
873
+ contextContent: string
874
+ ): string {
875
+ return `${contextContent}
876
+
877
+ ---
878
+
879
+ Analyze this problem from your area of expertise (${focusArea}).
880
+
881
+ Provide:
882
+ - Your assessment of the key challenges
883
+ - Your recommended approach
884
+ - Risks and concerns from your perspective
885
+ - Tradeoffs to consider
886
+
887
+ If you believe the shared context is missing something important,
888
+ you may propose a CONTEXT CHANGE by clearly marking it:
889
+
890
+ PROPOSED CONTEXT CHANGE:
891
+ What: {description of what to add/modify}
892
+ Why: {rationale}
893
+
894
+ Other consultants are analyzing this independently. You will see
895
+ their perspectives and can respond in the next round.
896
+
897
+ The source code and project structure are provided in your context. Analyze them directly to strengthen your analysis.`;
898
+ }
899
+
900
+ /**
901
+ * Consultant deliberation response (Round 2+) - Section 9.3
902
+ */
903
+ export function buildDeliberationResponsePrompt(
904
+ persona: Persona,
905
+ focusArea: string,
906
+ fullContext: string
907
+ ): string {
908
+ return `${fullContext}
909
+
910
+ ---
911
+
912
+ You have seen the other consultants' analyses. Provide your updated perspective:
913
+
914
+ - Where do you AGREE with other consultants and why?
915
+ - Where do you DISAGREE and what is your counter-argument?
916
+ - What important considerations have been MISSED?
917
+ - Has your position CHANGED? If so, how and why?
918
+ - What is your REFINED recommendation?
919
+
920
+ Do not restate your previous position unchanged.
921
+ Engage substantively with the other perspectives.
922
+
923
+ You may propose a CONTEXT CHANGE if you believe the shared context
924
+ should be updated:
925
+
926
+ PROPOSED CONTEXT CHANGE:
927
+ What: {description}
928
+ Why: {rationale}
929
+
930
+ The source code and project structure are provided in your context. Examine them to research and verify claims when it would strengthen your argument.`;
931
+ }
932
+
933
+ /**
934
+ * Consultant final position before manager decision
935
+ */
936
+ export function buildConsultantFinalPositionPrompt(
937
+ persona: Persona, focusArea: string, fullContext: string
938
+ ): string {
939
+ return `The deliberation is ending. Based on everything discussed, provide your FINAL POSITION.
940
+
941
+ DELIBERATION CONTEXT:
942
+ ${fullContext}
943
+
944
+ ---
945
+
946
+ As ${persona.name} (focus: ${focusArea}), state:
947
+ 1. Your recommended approach (1-2 sentences)
948
+ 2. The single biggest risk if your recommendation is ignored
949
+ 3. Any non-negotiable constraint from your domain
950
+
951
+ Be brief and decisive — this is your last input before the manager decides.`;
952
+ }
953
+
954
+ /**
955
+ * Consultant review of worker output
956
+ */
957
+ export function buildConsultantReviewPrompt(
958
+ persona: Persona, focusArea: string,
959
+ workOutput: string, directive: string, expectedOutput?: string
960
+ ): string {
961
+ return `Review the worker's output from your domain perspective (${focusArea}).
962
+
963
+ DIRECTIVE (what was requested):
964
+ ${directive}
965
+ ${expectedOutput ? `\nEXPECTED OUTCOME: ${expectedOutput}` : ''}
966
+
967
+ WORKER OUTPUT:
968
+ ${workOutput}
969
+
970
+ ---
971
+
972
+ As ${persona.name}, evaluate from your ${focusArea} perspective:
973
+ 1. Does the output meet the directive requirements?
974
+ 2. Any issues in your domain? (e.g., security flaws, performance problems, missing edge cases)
975
+ 3. Specific improvements needed (if any)
976
+
977
+ Review the code in your context to verify claims.
978
+ Be concise — 3-5 sentences max. Focus on actionable feedback, not style preferences.`;
979
+ }
980
+
981
+ // ============================================================================
982
+ // Worker Prompts
983
+ // ============================================================================
984
+
985
+ /**
986
+ * Worker execution - Section 9.7
987
+ */
988
+ export function buildWorkerExecutionPrompt(directive: string, permissions?: WorkerPermissions, stepType?: CouncilStepType): string {
989
+ if (stepType === 'agent' || stepType === 'analysis') {
990
+ const saveNote = permissions?.writePermissions && permissions?.workingDirectory
991
+ ? `\nIf you need to save output to a file, include the content in your response with a clear file path label for: ${permissions.workingDirectory}`
992
+ : '';
993
+ return `TASK:
994
+ ${directive}
995
+
996
+ ---
997
+ EXECUTE THIS TASK NOW by analyzing the source code and project structure provided in your context. Do NOT write code, scripts, or plans.
998
+ Examine the code provided in the context directly to perform the work and return the actual results.${saveNote}
999
+
1000
+ When DONE, end with:
1001
+ ## COMPLETION SUMMARY
1002
+ **Status:** [Complete | Partial — explain what's missing]
1003
+ **What was done:** 1-3 sentence description of what you actually analyzed
1004
+ **Known issues:** [None | list any issues]`;
1005
+ }
1006
+
1007
+ if (permissions?.writePermissions) {
1008
+ if (stepType === 'enrich') {
1009
+ return `DIRECTIVE:
1010
+ ${directive}
1011
+
1012
+ ---
1013
+ STEP 1 — RESEARCH THE PROJECT:
1014
+ Examine the project structure, source files, and existing documentation provided in your context.
1015
+ Understand the architecture, patterns, conventions, and capabilities. Note what exists and what's missing.
1016
+
1017
+ STEP 2 — RESEARCH THE MARKET:
1018
+ Analyze the competitive landscape, user needs, and industry trends relevant to this project.
1019
+ Draw on your knowledge of the domain.
1020
+ Consider: What do competing products offer? What do users expect? What are emerging trends?
1021
+
1022
+ STEP 3 — BRAINSTORM FEATURES:
1023
+ Generate creative feature ideas and enhancements that go BEYOND the original spec. For each idea include:
1024
+ - **Feature name** and brief description
1025
+ - **User value** — why users would want this
1026
+ - **Technical feasibility** — how hard to implement given the existing architecture
1027
+ - **Implementation effort** — rough estimate (small / medium / large)
1028
+ - **Priority** — recommended priority (P0 critical / P1 high / P2 medium / P3 nice-to-have)
1029
+
1030
+ STEP 4 — WRITE ENRICHMENT DOCUMENT:
1031
+ Produce the enrichment document content in your response (e.g., enrichment.md) structured as:
1032
+ - Executive Summary
1033
+ - Codebase Analysis (architecture, patterns, gaps, opportunities)
1034
+ - Market Research (competitive landscape, user needs, trends)
1035
+ - Feature Ideas (the full brainstorm from Step 3)
1036
+ - Prioritized Recommendations (top features to pursue, with rationale)
1037
+
1038
+ Do NOT modify any source code files — only create the enrichment document.
1039
+ Produce the content in your response using a clearly labeled code block.
1040
+
1041
+ MANDATORY — When you are DONE, you MUST end your response with a completion summary
1042
+ in EXACTLY this format:
1043
+
1044
+ ## COMPLETION SUMMARY
1045
+ **Status:** [Complete | Partial — explain what's missing]
1046
+ **Files created:**
1047
+ - path/to/enrichment.md — brief description
1048
+ **What was produced:** 1-3 sentence description of the enrichment document
1049
+ **Known issues:** [None | list any issues]`;
1050
+ }
1051
+
1052
+ if (stepType === 'review') {
1053
+ return `DIRECTIVE:
1054
+ ${directive}
1055
+
1056
+ ---
1057
+ STEP 1 — UNDERSTAND THE CODEBASE:
1058
+ Examine the project structure, source files, and existing documentation provided in your context.
1059
+ Understand the architecture, patterns, and conventions used.
1060
+
1061
+ STEP 2 — REVIEW CODE QUALITY:
1062
+ Evaluate the codebase against the spec/requirements provided in the directive.
1063
+ Note: code quality issues, spec adherence gaps, architectural concerns, and areas for improvement.
1064
+
1065
+ STEP 3 — WRITE DOCUMENTATION:
1066
+ You MUST produce exactly THREE documentation artifacts in your response:
1067
+
1068
+ 1. README.md — Project overview, setup instructions, usage guide, architecture summary
1069
+ 2. docs/ folder — Create multiple files covering: API reference, architecture decisions, developer guides
1070
+ (e.g., docs/architecture.md, docs/api-reference.md, docs/getting-started.md)
1071
+ 3. review.md — Code quality review including: spec adherence evaluation, issues found, recommendations, quality score
1072
+
1073
+ Do NOT modify any source code files — only create documentation files.
1074
+ Produce the content in your response using clearly labeled code blocks for EACH file.
1075
+
1076
+ MANDATORY — When you are DONE, you MUST end your response with a completion summary
1077
+ in EXACTLY this format:
1078
+
1079
+ ## COMPLETION SUMMARY
1080
+ **Status:** [Complete | Partial — explain what's missing]
1081
+ **Files created:**
1082
+ - README.md — brief description
1083
+ - docs/architecture.md — brief description
1084
+ - docs/api-reference.md — brief description
1085
+ - review.md — brief description
1086
+ **What was produced:** 1-3 sentence description of the documentation
1087
+ **Known issues:** [None | list any issues]
1088
+
1089
+ This summary is CRITICAL — the manager uses it to evaluate your work. Do NOT skip it.`;
1090
+ }
1091
+
1092
+ if (stepType === 'code_planning') {
1093
+ return `DIRECTIVE:
1094
+ ${directive}
1095
+
1096
+ ---
1097
+ IMPORTANT: You are a planning agent.
1098
+ Your job is to produce a DETAILED PLAN DOCUMENT — NOT code.
1099
+
1100
+ Produce the plan document in your response (e.g., plan.md or PLAN.md) using a clearly labeled code block.
1101
+ Do NOT write source code, implementation files, or any executable code.
1102
+
1103
+ The plan should be thorough and actionable, covering:
1104
+ - Clear phases and steps
1105
+ - Dependencies between steps
1106
+ - Architecture and design decisions
1107
+ - File/module structure
1108
+ - Interface definitions
1109
+ - Success criteria and acceptance tests
1110
+
1111
+ MANDATORY STRUCTURED SPEC — Your plan document MUST end with a ## STRUCTURED SPEC section
1112
+ containing a JSON code block. This machine-readable spec allows downstream coding steps to
1113
+ consume concrete features, acceptance criteria, and file trees. Format:
1114
+
1115
+ \`\`\`json
1116
+ {
1117
+ "features": [
1118
+ {
1119
+ "name": "Feature name",
1120
+ "description": "What it does",
1121
+ "acceptanceCriteria": ["Criterion 1", "Criterion 2"],
1122
+ "files": ["src/path/to/file.ts"]
1123
+ }
1124
+ ],
1125
+ "architecture": {
1126
+ "fileTree": ["src/", "src/components/", "src/utils/"],
1127
+ "techStack": ["React", "TypeScript"]
1128
+ },
1129
+ "phases": [
1130
+ {
1131
+ "name": "Phase 1",
1132
+ "features": ["Feature name"],
1133
+ "dependencies": []
1134
+ }
1135
+ ]
1136
+ }
1137
+ \`\`\`
1138
+
1139
+ This structured spec is CRITICAL — downstream coding steps parse it to decompose work.
1140
+
1141
+ MANDATORY — When you are DONE, you MUST end your response with a completion summary
1142
+ in EXACTLY this format:
1143
+
1144
+ ## COMPLETION SUMMARY
1145
+ **Status:** [Complete | Partial — explain what's missing]
1146
+ **Files created:**
1147
+ - path/to/plan.md — brief description
1148
+ **What was produced:** 1-3 sentence description of the plan
1149
+ **Known issues:** [None | list any issues]
1150
+
1151
+ This summary is CRITICAL — the manager uses it to evaluate your work. Do NOT skip it.`;
1152
+ }
1153
+
1154
+ return `DIRECTIVE:
1155
+ ${directive}
1156
+
1157
+ ---
1158
+ STEP 1 — UNDERSTAND THE CODEBASE:
1159
+ Before writing any code, examine the existing files provided in your context.
1160
+ Understand the project structure, existing patterns, and conventions.
1161
+ Your implementation must integrate with what already exists.
1162
+
1163
+ STEP 2 — IMPLEMENT:
1164
+ You are an implementation agent.
1165
+ DO NOT just describe what needs to be done or output vague summaries.
1166
+ Produce the content in your response using clearly labeled code blocks:
1167
+ \`\`\`filename: path/to/file.ts
1168
+ // file contents here
1169
+ \`\`\`
1170
+
1171
+ You MUST produce every file's content in your response — do not just show snippets.
1172
+
1173
+ MANDATORY — When you are DONE implementing, you MUST end your response with a completion summary
1174
+ in EXACTLY this format:
1175
+
1176
+ ## COMPLETION SUMMARY
1177
+ **Status:** [Complete | Partial — explain what's missing]
1178
+ **Files created:**
1179
+ - path/to/file1.ts — brief description
1180
+ - path/to/file2.ts — brief description
1181
+ **Files modified:**
1182
+ - path/to/existing.ts — what changed
1183
+ **What was built:** 1-3 sentence description of the working result
1184
+ **Known issues:** [None | list any issues]
1185
+
1186
+ This summary is CRITICAL — the manager uses it to evaluate your work. Do NOT skip it.`;
1187
+ }
1188
+
1189
+ return `DIRECTIVE:
1190
+ ${directive}
1191
+
1192
+ ---
1193
+ Remember: Produce all output directly in your response. Use labeled code blocks for any files or code.
1194
+
1195
+ MANDATORY — When you are DONE, you MUST end your response with a completion summary
1196
+ in EXACTLY this format:
1197
+
1198
+ ## COMPLETION SUMMARY
1199
+ **Status:** [Complete | Partial — explain what's missing]
1200
+ **Files/sections produced:**
1201
+ - filename or section — brief description
1202
+ **What was built:** 1-3 sentence description of the result
1203
+ **Known issues:** [None | list any issues]
1204
+
1205
+ This summary is CRITICAL — the manager uses it to evaluate your work. Do NOT skip it.`;
1206
+ }
1207
+
1208
+ /**
1209
+ * Worker revision - Section 9.7.1
1210
+ */
1211
+ export function buildWorkerRevisionPrompt(
1212
+ directive: string,
1213
+ previousOutput: string,
1214
+ feedback: string,
1215
+ permissions?: WorkerPermissions,
1216
+ stepType?: CouncilStepType,
1217
+ ): string {
1218
+ if (permissions?.writePermissions) {
1219
+ if (stepType === 'enrich') {
1220
+ return `DIRECTIVE:
1221
+ ${directive}
1222
+
1223
+ YOUR PREVIOUS OUTPUT:
1224
+ ${previousOutput}
1225
+
1226
+ REVISION FEEDBACK:
1227
+ ${feedback}
1228
+
1229
+ Revise your enrichment document to address the feedback. Follow the original directive.
1230
+ Only change what the feedback asks you to change.
1231
+
1232
+ IMPORTANT: Produce the updated enrichment document content in your response using a clearly labeled code block.
1233
+ Review your previous output carefully, then produce the revised version.
1234
+ Do NOT modify any source code files — only the enrichment document.
1235
+
1236
+ MANDATORY — When you are DONE with revisions, you MUST end your response with a completion summary
1237
+ in EXACTLY this format:
1238
+
1239
+ ## COMPLETION SUMMARY
1240
+ **Status:** [Complete | Partial — explain what's missing]
1241
+ **Files created:**
1242
+ - path/to/file — brief description
1243
+ **Files modified:**
1244
+ - path/to/file — what changed
1245
+ **What was produced:** 1-3 sentence description of the enrichment document
1246
+ **What was revised:** 1-2 sentences on what the feedback asked for and what you changed
1247
+ **Known issues:** [None | list any issues]`;
1248
+ }
1249
+
1250
+ if (stepType === 'review') {
1251
+ return `DIRECTIVE:
1252
+ ${directive}
1253
+
1254
+ YOUR PREVIOUS OUTPUT:
1255
+ ${previousOutput}
1256
+
1257
+ REVISION FEEDBACK:
1258
+ ${feedback}
1259
+
1260
+ Revise your documentation to address the feedback. Follow the original directive.
1261
+ Only change what the feedback asks you to change.
1262
+
1263
+ IMPORTANT: Produce the updated documentation content in your response using clearly labeled code blocks.
1264
+ Review your previous output carefully, then produce the revised versions.
1265
+ You must maintain all three deliverables: README.md, docs/ folder, and review.md.
1266
+ Do NOT modify any source code files — only documentation files.
1267
+
1268
+ MANDATORY — When you are DONE with revisions, you MUST end your response with a completion summary
1269
+ in EXACTLY this format:
1270
+
1271
+ ## COMPLETION SUMMARY
1272
+ **Status:** [Complete | Partial — explain what's missing]
1273
+ **Files created:**
1274
+ - path/to/file — brief description
1275
+ **Files modified:**
1276
+ - path/to/file — what changed
1277
+ **What was produced:** 1-3 sentence description of the documentation
1278
+ **What was revised:** 1-2 sentences on what the feedback asked for and what you changed
1279
+ **Known issues:** [None | list any issues]
1280
+
1281
+ This summary is CRITICAL — the manager uses it to evaluate your work. Do NOT skip it.`;
1282
+ }
1283
+
1284
+ if (stepType === 'code_planning') {
1285
+ return `DIRECTIVE:
1286
+ ${directive}
1287
+
1288
+ YOUR PREVIOUS PLAN:
1289
+ ${previousOutput}
1290
+
1291
+ REVISION FEEDBACK:
1292
+ ${feedback}
1293
+
1294
+ Revise your plan document to address the feedback. Follow the original directive.
1295
+ Only change what the feedback asks you to change.
1296
+
1297
+ IMPORTANT: Produce the updated plan document in your response using a clearly labeled code block.
1298
+ Actually revise the plan content. Do NOT write source code or implementation files.
1299
+
1300
+ IMPORTANT: Preserve the ## STRUCTURED SPEC section with the JSON code block at the end of the plan.
1301
+ Update the structured spec to reflect any changes from the revision. The structured spec must contain:
1302
+ features (name, description, acceptanceCriteria, files), architecture (fileTree, techStack), and phases.
1303
+
1304
+ MANDATORY — When you are DONE with revisions, you MUST end your response with a completion summary
1305
+ in EXACTLY this format:
1306
+
1307
+ ## COMPLETION SUMMARY
1308
+ **Status:** [Complete | Partial — explain what's missing]
1309
+ **Files created:**
1310
+ - path/to/plan.md — brief description
1311
+ **Files modified:**
1312
+ - path/to/plan.md — what changed
1313
+ **What was produced:** 1-3 sentence description of the plan
1314
+ **What was revised:** 1-2 sentences on what the feedback asked for and what you changed
1315
+ **Known issues:** [None | list any issues]
1316
+
1317
+ This summary is CRITICAL — the manager uses it to evaluate your work. Do NOT skip it.`;
1318
+ }
1319
+
1320
+ return `DIRECTIVE:
1321
+ ${directive}
1322
+
1323
+ YOUR PREVIOUS OUTPUT:
1324
+ ${previousOutput}
1325
+
1326
+ REVISION FEEDBACK:
1327
+ ${feedback}
1328
+
1329
+ Revise your implementation to address the feedback. Follow the original directive.
1330
+ Only change what the feedback asks you to change.
1331
+
1332
+ IMPORTANT: Produce the updated file contents in your response using clearly labeled code blocks.
1333
+ Review your previous output carefully, then produce the revised versions.
1334
+
1335
+ MANDATORY — When you are DONE with revisions, you MUST end your response with a completion summary
1336
+ in EXACTLY this format:
1337
+
1338
+ ## COMPLETION SUMMARY
1339
+ **Status:** [Complete | Partial — explain what's missing]
1340
+ **Files created:**
1341
+ - path/to/file1.ts — brief description
1342
+ **Files modified:**
1343
+ - path/to/existing.ts — what changed
1344
+ **What was built:** 1-3 sentence description of the working result
1345
+ **What was revised:** 1-2 sentences on what the feedback asked for and what you changed
1346
+ **Known issues:** [None | list any issues]
1347
+
1348
+ This summary is CRITICAL — the manager uses it to evaluate your work. Do NOT skip it.`;
1349
+ }
1350
+
1351
+ return `DIRECTIVE:
1352
+ ${directive}
1353
+
1354
+ YOUR PREVIOUS OUTPUT:
1355
+ ${previousOutput}
1356
+
1357
+ REVISION FEEDBACK:
1358
+ ${feedback}
1359
+
1360
+ Revise your output to address the feedback. Follow the original
1361
+ directive. Only change what the feedback asks you to change.
1362
+
1363
+ Remember: Produce all output directly in your response. Use labeled code blocks for any files or code.
1364
+
1365
+ MANDATORY — When you are DONE with revisions, you MUST end your response with a completion summary
1366
+ in EXACTLY this format:
1367
+
1368
+ ## COMPLETION SUMMARY
1369
+ **Status:** [Complete | Partial — explain what's missing]
1370
+ **Files/sections produced:**
1371
+ - filename or section — brief description
1372
+ **What was built:** 1-3 sentence description of the result
1373
+ **What was revised:** 1-2 sentences on what the feedback asked for and what you changed
1374
+ **Known issues:** [None | list any issues]
1375
+
1376
+ This summary is CRITICAL — the manager uses it to evaluate your work. Do NOT skip it.`;
1377
+ }
1378
+
1379
+ // ============================================================================
1380
+ // Coding Orchestrator Prompts
1381
+ // ============================================================================
1382
+
1383
+ /**
1384
+ * Manager decomposes a spec into parallel modules for workers
1385
+ */
1386
+ export function buildDecompositionPrompt(spec: string, workerCount: number): string {
1387
+ const contextPreamble = `BEFORE DECOMPOSING — EXAMINE THE CONTEXT:
1388
+ The source code and project structure are provided in your context. Analyze them directly:
1389
+ 1. Review the existing project structure in the context (key directories and files)
1390
+ 2. Understand what code already exists (examine key files in the context)
1391
+ 3. Identify files that need to be modified vs. created from scratch
1392
+ 4. Note existing patterns, frameworks, and conventions
1393
+
1394
+ Your decomposition MUST account for existing code. Do not plan to recreate
1395
+ things that already exist — plan to modify or extend them.
1396
+
1397
+ `;
1398
+
1399
+ if (workerCount <= 1) {
1400
+ return `You are decomposing a specification into an implementation plan for a single worker.
1401
+
1402
+ ${contextPreamble}SPECIFICATION:
1403
+ ${spec}
1404
+
1405
+ ---
1406
+
1407
+ Since there is only 1 worker, produce a single module with the full implementation directive.
1408
+
1409
+ Respond as JSON:
1410
+ {
1411
+ "modules": [
1412
+ {
1413
+ "name": "main",
1414
+ "files": ["list of files to create or modify"],
1415
+ "interfaces": "public interfaces this module exposes (types, exports, APIs)",
1416
+ "dependencies": [],
1417
+ "directive": "complete implementation directive for the worker"
1418
+ }
1419
+ ],
1420
+ "integrationNotes": "any notes about how the code fits together",
1421
+ "testStrategy": "how to verify the implementation works",
1422
+ "installCommand": "command to install dependencies (e.g. npm install, pip install -r requirements.txt). Empty string if not needed or if build handles it (cargo build).",
1423
+ "buildCommand": "command to compile/build the project (e.g. npm run build, tsc --noEmit, cargo build). Empty string if no build step needed."
1424
+ }`;
1425
+ }
1426
+
1427
+ return `You are decomposing a specification into ${workerCount} parallel modules for worker agents.
1428
+
1429
+ ${contextPreamble}SPECIFICATION:
1430
+ ${spec}
1431
+
1432
+ ---
1433
+
1434
+ Break this spec into ${workerCount} modules that can be implemented in parallel.
1435
+
1436
+ Requirements:
1437
+ - Each module should be as independent as possible
1438
+ - Define clear interfaces between modules so workers can code to a contract
1439
+ - Each module gets its own list of files, a directive, and declared dependencies
1440
+ - If modules depend on each other, list the dependency by module name
1441
+ - Directives must be concrete and self-contained — workers only see their own module
1442
+
1443
+ Respond as JSON:
1444
+ {
1445
+ "modules": [
1446
+ {
1447
+ "name": "descriptive-module-name",
1448
+ "files": ["list of files this module creates or modifies"],
1449
+ "interfaces": "public interfaces this module exposes (types, exports, APIs) that other modules may depend on",
1450
+ "dependencies": ["names of other modules this depends on"],
1451
+ "directive": "complete implementation directive for the worker assigned to this module"
1452
+ }
1453
+ ],
1454
+ "integrationNotes": "how the modules connect — shared types, import paths, integration points",
1455
+ "testStrategy": "how to verify the full implementation works end-to-end",
1456
+ "installCommand": "command to install dependencies (e.g. npm install, pip install -r requirements.txt). Empty string if not needed or if build handles it (cargo build).",
1457
+ "buildCommand": "command to compile/build the project (e.g. npm run build, tsc --noEmit, cargo build). Empty string if no build step needed."
1458
+ }`;
1459
+ }
1460
+
1461
+ /**
1462
+ * Per-worker directive with module scope and interfaces of other modules
1463
+ */
1464
+ export function buildModuleDirectivePrompt(
1465
+ module: { name: string; files: string[]; interfaces: string; dependencies: string[]; directive: string },
1466
+ otherModuleInterfaces: Array<{ name: string; interfaces: string }>,
1467
+ integrationNotes: string,
1468
+ permissions?: WorkerPermissions,
1469
+ ): string {
1470
+ const interfacesSection = otherModuleInterfaces.length > 0
1471
+ ? `\n## OTHER MODULE INTERFACES (code to these contracts — do NOT implement them)\n${otherModuleInterfaces.map(
1472
+ (m) => `### ${m.name}\n${m.interfaces}`
1473
+ ).join('\n\n')}\n`
1474
+ : '';
1475
+
1476
+ const depsSection = module.dependencies.length > 0
1477
+ ? `\nDependencies: This module depends on: ${module.dependencies.join(', ')}\nImport from the interfaces above — do not reimplement them.\n`
1478
+ : '';
1479
+
1480
+ const scopeNote = permissions?.writePermissions
1481
+ ? `\nIMPORTANT: Produce every file's content in your response using clearly labeled code blocks:
1482
+ \`\`\`filename: path/to/file.ts
1483
+ // contents
1484
+ \`\`\`
1485
+ ${permissions.workingDirectory
1486
+ ? (permissions.directoryConstrained
1487
+ ? `All file operations MUST be within: ${permissions.workingDirectory}`
1488
+ : `Working directory: ${permissions.workingDirectory}`)
1489
+ : 'You may produce content for files as needed.'}\n`
1490
+ : `\nOutput all code in labeled code blocks:\n\`\`\`filename: path/to/file.ts\n// contents\n\`\`\`\n`;
1491
+
1492
+ return `## MODULE: ${module.name}
1493
+ Files: ${module.files.join(', ')}
1494
+
1495
+ NOTE: The source code and project structure are provided in your context. Examine them before coding.
1496
+ Your implementation must integrate with the existing codebase.
1497
+
1498
+ ## DIRECTIVE
1499
+ ${module.directive}
1500
+ ${interfacesSection}${depsSection}
1501
+ ## INTEGRATION NOTES
1502
+ ${integrationNotes}
1503
+ ${scopeNote}
1504
+ MANDATORY — When DONE, end with:
1505
+
1506
+ ## COMPLETION SUMMARY
1507
+ **Status:** [Complete | Partial — explain what's missing]
1508
+ **Files created/modified:** list each with brief description
1509
+ **What was built:** 1-3 sentence description
1510
+ **Known issues:** [None | list any issues]`;
1511
+ }
1512
+
1513
+ /**
1514
+ * Code reviewer evaluates all worker outputs against the original spec
1515
+ */
1516
+ export function buildCodeReviewPrompt(
1517
+ spec: string,
1518
+ workerOutputs: Array<{ moduleName: string; output: string }>,
1519
+ expectedOutput?: string,
1520
+ ): string {
1521
+ const outputsSection = workerOutputs
1522
+ .map((w) => `### Module: ${w.moduleName}\n${w.output}`)
1523
+ .join('\n\n---\n\n');
1524
+
1525
+ const expectedSection = expectedOutput
1526
+ ? `\n## EXPECTED OUTPUT\n${expectedOutput}\n`
1527
+ : '';
1528
+
1529
+ return `You are a code reviewer. Review all worker implementations against the original specification.
1530
+
1531
+ ## ORIGINAL SPECIFICATION
1532
+ ${spec}
1533
+ ${expectedSection}
1534
+ ## WORKER IMPLEMENTATIONS
1535
+ ${outputsSection}
1536
+
1537
+ The source code and project structure are provided in your context. Review the code in the context
1538
+ to verify the implementation. Cross-reference the worker output against what exists in the codebase.
1539
+
1540
+ ---
1541
+
1542
+ STEP 1 — INVESTIGATE:
1543
+ Examine the code provided in the context. Verify that the worker's output is consistent with
1544
+ the existing codebase and matches the specification. Note any discrepancies.
1545
+
1546
+ STEP 2 — ASSESS:
1547
+ Review for:
1548
+ 1. **Correctness**: Does the implementation match the spec? Are all requirements met?
1549
+ 2. **Integration**: Will the modules work together? Are interfaces compatible?
1550
+ 3. **Quality**: Are there bugs, edge cases, or obvious issues?
1551
+ 4. **Completeness**: Is anything missing from the spec?
1552
+
1553
+ STEP 3 — RESPOND:
1554
+ After your investigation, respond with ONLY a JSON block (no other text after it):
1555
+
1556
+ \`\`\`json
1557
+ {
1558
+ "verdict": "pass" | "needs_revision",
1559
+ "issues": [
1560
+ {
1561
+ "module": "module-name",
1562
+ "severity": "critical" | "major" | "minor",
1563
+ "description": "Specific description of what is wrong — reference the exact file, function, or line",
1564
+ "suggestion": "Exact fix: what code to change, what to add, or what to remove"
1565
+ }
1566
+ ],
1567
+ "summary": "overall assessment of the implementation"
1568
+ }
1569
+ \`\`\`
1570
+
1571
+ CRITICAL RULES:
1572
+ - If verdict is "needs_revision", the issues array MUST NOT be empty.
1573
+ - Each issue MUST have a specific description (file path + what's wrong) and a concrete suggestion (what to change).
1574
+ - Do NOT say "needs_revision" without explaining exactly what to fix — vague feedback wastes a revision cycle.
1575
+ - If there are no critical or major issues, verdict MUST be "pass".
1576
+ - Only use "needs_revision" for issues that would prevent the code from working correctly.`;
1577
+ }
1578
+
1579
+ /**
1580
+ * Minimal system prompt for reviewer role (read-only)
1581
+ */
1582
+ export function buildReviewerSystemPrompt(): string {
1583
+ return `You are a Code Reviewer agent. Your job is to evaluate code quality and correctness.
1584
+ The source code and project structure are provided in your context. Examine them directly
1585
+ when verifying worker implementations. Do not rely solely on worker output text.
1586
+
1587
+ You do NOT write code or modify files. You only review and provide feedback.
1588
+ Your output must be structured JSON with a verdict and list of issues.
1589
+
1590
+ Be thorough but practical — flag real problems, not style preferences.
1591
+ Focus on correctness, spec compliance, and integration issues.`;
1592
+ }
1593
+
1594
+ /**
1595
+ * Debugger worker fixes test failures
1596
+ */
1597
+ export function buildDebugFixPrompt(
1598
+ testOutput: string,
1599
+ allCode: string,
1600
+ spec: string,
1601
+ permissions?: WorkerPermissions,
1602
+ moduleName?: string,
1603
+ moduleFiles?: string[],
1604
+ ): string {
1605
+ const scopeNote = permissions?.writePermissions
1606
+ ? `\nIMPORTANT: Produce the fixed file contents in your response using clearly labeled code blocks.
1607
+ Do NOT just describe fixes — produce the corrected code.
1608
+ ${permissions.workingDirectory
1609
+ ? (permissions.directoryConstrained
1610
+ ? `All file operations MUST be within: ${permissions.workingDirectory}`
1611
+ : `Working directory: ${permissions.workingDirectory}`)
1612
+ : 'You may produce content for files as needed.'}\n`
1613
+ : `\nOutput all fixes in labeled code blocks.\n`;
1614
+
1615
+ const moduleContext = moduleName
1616
+ ? `\n## YOUR MODULE: ${moduleName}
1617
+ ${moduleFiles?.length ? `Files: ${moduleFiles.join(', ')}` : ''}
1618
+ Focus your fixes on this module's code. Other modules are handled by other workers.\n`
1619
+ : '';
1620
+
1621
+ return `You are a debugger. Tests/build are failing. Fix the code to make them pass.
1622
+
1623
+ ## TEST OUTPUT (failures)
1624
+ ${testOutput}
1625
+ ${moduleContext}
1626
+ ## CURRENT CODE
1627
+ ${allCode}
1628
+
1629
+ ## ORIGINAL SPECIFICATION
1630
+ ${spec}
1631
+ ${scopeNote}
1632
+ Instructions:
1633
+ - Analyze the test failures and identify root causes
1634
+ - If failures indicate missing packages or modules (e.g. "Cannot find module", "ModuleNotFoundError",
1635
+ "command not found"), ensure dependencies are declared in the project manifest and installed
1636
+ - Make MINIMAL, targeted fixes — do not rewrite or refactor unrelated code
1637
+ - Fix only what's broken, preserve everything else
1638
+ - If a test failure reveals a spec misunderstanding, fix the code to match the spec
1639
+
1640
+ MANDATORY — When DONE, end with:
1641
+
1642
+ ## COMPLETION SUMMARY
1643
+ **Status:** [Complete | Partial]
1644
+ **Files modified:** list each with what was fixed
1645
+ **Fixes applied:** brief description of each fix
1646
+ **Known issues:** [None | list any remaining issues]`;
1647
+ }
1648
+
1649
+ /**
1650
+ * Worker revision based on reviewer feedback
1651
+ */
1652
+ export function buildRevisionFromReviewPrompt(
1653
+ reviewFeedback: string,
1654
+ previousOutput: string,
1655
+ moduleDirective: string,
1656
+ permissions?: WorkerPermissions,
1657
+ ): string {
1658
+ const scopeNote = permissions?.writePermissions
1659
+ ? `\nIMPORTANT: Produce the updated file contents in your response using clearly labeled code blocks.
1660
+ Do NOT just describe changes — produce the corrected code.
1661
+ ${permissions.workingDirectory
1662
+ ? (permissions.directoryConstrained
1663
+ ? `All file operations MUST be within: ${permissions.workingDirectory}`
1664
+ : `Working directory: ${permissions.workingDirectory}`)
1665
+ : 'You may produce content for files as needed.'}\n`
1666
+ : `\nOutput all revised code in labeled code blocks.\n`;
1667
+
1668
+ return `## ORIGINAL DIRECTIVE
1669
+ ${moduleDirective}
1670
+
1671
+ ## YOUR PREVIOUS OUTPUT
1672
+ ${previousOutput}
1673
+
1674
+ ## REVIEWER FEEDBACK
1675
+ ${reviewFeedback}
1676
+
1677
+ ---
1678
+
1679
+ Revise your implementation to address the reviewer's feedback.
1680
+ Only change what the feedback asks you to change — do not rewrite unrelated code.
1681
+ ${scopeNote}
1682
+ MANDATORY — When DONE, end with:
1683
+
1684
+ ## COMPLETION SUMMARY
1685
+ **Status:** [Complete | Partial]
1686
+ **Files created/modified:** list each with brief description
1687
+ **What was revised:** 1-2 sentences on what the feedback asked for and what you changed
1688
+ **Known issues:** [None | list any issues]`;
1689
+ }