rungate 0.2.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 (196) hide show
  1. package/.claude/agents/aditi.md +47 -0
  2. package/.claude/agents/marcus.md +50 -0
  3. package/.claude/agents/quinn.md +58 -0
  4. package/.claude/agents/rook.md +47 -0
  5. package/.claude/agents/serena.md +46 -0
  6. package/.claude/rungate.json +11 -0
  7. package/.fallowrc.json +28 -0
  8. package/.github/copilot-instructions.md +20 -0
  9. package/.rungate/conformity-findings.json +648 -0
  10. package/AGENTS.md +106 -0
  11. package/CODE-MAP.md +50 -0
  12. package/HARNESS.md +88 -0
  13. package/bun.lock +26 -0
  14. package/bunfig.toml +2 -0
  15. package/config/brief-policies.json +28 -0
  16. package/config/ceremony-profiles.json +212 -0
  17. package/config/consumer-cascade-map.json +24 -0
  18. package/config/doc-cascade-map.json +24 -0
  19. package/config/eval.json +84 -0
  20. package/config/profiles/account-plan.yaml +36 -0
  21. package/config/profiles/campaign.yaml +94 -0
  22. package/config/prove-evidence.schema.json +65 -0
  23. package/config/spec-policies.json +36 -0
  24. package/config/workflow-schema.json +281 -0
  25. package/gates/SCHEMA-GUIDE.md +121 -0
  26. package/gates/ac-quality.test.ts +106 -0
  27. package/gates/adversarial.test.ts +274 -0
  28. package/gates/brief-assembler.test.ts +429 -0
  29. package/gates/brief-assembler.ts +334 -0
  30. package/gates/bunfig.toml +2 -0
  31. package/gates/chain.test.ts +91 -0
  32. package/gates/e2e-smoke.test.ts +234 -0
  33. package/gates/error-classifier.test.ts +249 -0
  34. package/gates/error-classifier.ts +89 -0
  35. package/gates/orchestrator.test.ts +950 -0
  36. package/gates/orchestrator.ts +569 -0
  37. package/gates/preload.ts +77 -0
  38. package/gates/prompts/ac-adversary.md +20 -0
  39. package/gates/prompts/evidence-validator.md +22 -0
  40. package/gates/prompts/prove-reproducer.md +53 -0
  41. package/gates/prove.test.ts +164 -0
  42. package/gates/run-gate.ts +936 -0
  43. package/gates/schema-parity.test.ts +197 -0
  44. package/gates/schema.ts +362 -0
  45. package/gates/self-heal.test.ts +511 -0
  46. package/gates/self-heal.ts +121 -0
  47. package/gates/ship-orchestrator.test.ts +379 -0
  48. package/gates/ship-orchestrator.ts +363 -0
  49. package/gates/test-fixtures/broken-no-environments.json +60 -0
  50. package/gates/test-fixtures/valid-standard.json +54 -0
  51. package/gates/test-utils.ts +43 -0
  52. package/gates/witness.ts +220 -0
  53. package/gates/workflow.test.ts +1053 -0
  54. package/hooks/AgentBriefGuard.hook.ts +586 -0
  55. package/hooks/AgentVerdictCapture.hook.ts +134 -0
  56. package/hooks/AutoVerifyGate.hook.ts +76 -0
  57. package/hooks/GateEnforcement.hook.ts +273 -0
  58. package/hooks/IssueCloseGuard.hook.ts +116 -0
  59. package/hooks/MergeGuard.hook.ts +55 -0
  60. package/hooks/StaleTTLCleanup.hook.ts +133 -0
  61. package/hooks/VerifyPhaseLock.hook.ts +81 -0
  62. package/hooks/WorkflowStateGuard.hook.ts +37 -0
  63. package/hooks/lib/agentDetection.ts +70 -0
  64. package/hooks/lib/findWorkflow.ts +101 -0
  65. package/hooks/lib/parseStdin.ts +37 -0
  66. package/hooks/lib/paths.ts +111 -0
  67. package/hooks/lib/utils.ts +81 -0
  68. package/lib/conformity.ts +959 -0
  69. package/lib/paths.ts +23 -0
  70. package/lib/rungate-schema.ts +60 -0
  71. package/lib/signal-phrases.ts +7 -0
  72. package/package.json +20 -0
  73. package/prompts/ac-adversary.md +20 -0
  74. package/prompts/ac-format.md +34 -0
  75. package/prompts/aditi.md +29 -0
  76. package/prompts/blast-radius.md +29 -0
  77. package/prompts/coding-principles.md +34 -0
  78. package/prompts/container-rebuild.md +29 -0
  79. package/prompts/container-verify.md +28 -0
  80. package/prompts/discovery.md +27 -0
  81. package/prompts/environment.md +28 -0
  82. package/prompts/escalation-decision-tree.md +38 -0
  83. package/prompts/evidence-hierarchy.md +31 -0
  84. package/prompts/evidence-validator.md +22 -0
  85. package/prompts/marcus.md +29 -0
  86. package/prompts/prevention.md +26 -0
  87. package/prompts/prove-reproducer.md +43 -0
  88. package/prompts/quinn-decision-tree.md +31 -0
  89. package/prompts/quinn-ui-brief.md +106 -0
  90. package/prompts/quinn.md +29 -0
  91. package/prompts/rca.md +28 -0
  92. package/prompts/read-before-write.md +30 -0
  93. package/prompts/regression.md +26 -0
  94. package/prompts/rook.md +29 -0
  95. package/prompts/serena.md +28 -0
  96. package/prompts/testing-strategy.md +34 -0
  97. package/reference/migration-manifest.json +554 -0
  98. package/reference/prompts/agent-aditi.md +38 -0
  99. package/reference/prompts/agent-marcus.md +38 -0
  100. package/reference/prompts/agent-quinn.md +38 -0
  101. package/reference/prompts/agent-rook.md +37 -0
  102. package/reference/prompts/agent-serena.md +37 -0
  103. package/reference/prompts/council-skill.md +170 -0
  104. package/reference/prompts/goal-skill.md +235 -0
  105. package/reference/prompts/prove-skill.md +283 -0
  106. package/reference/prompts/quinn-standard.md +246 -0
  107. package/reference/prompts/ship-convergence.md +65 -0
  108. package/reference/prompts/ship-escalation.md +43 -0
  109. package/reference/prompts/ship-iteration.md +382 -0
  110. package/reference/prompts/ship-pending-patches.md +246 -0
  111. package/reference/prompts/ship-reference.md +250 -0
  112. package/reference/prompts/ship-skill.md +347 -0
  113. package/reference/prompts/ship-templates.md +215 -0
  114. package/reference/scripts/batch-status.sh +68 -0
  115. package/reference/scripts/chain-compat-check.sh +67 -0
  116. package/reference/scripts/context-audit.sh +314 -0
  117. package/reference/scripts/dead-export-check.sh +61 -0
  118. package/reference/scripts/generate-qc-tables.sh +92 -0
  119. package/reference/scripts/harness-init.sh +111 -0
  120. package/reference/scripts/pai-054-baseline-check.sh +40 -0
  121. package/reference/scripts/prove-smoke-test.sh +112 -0
  122. package/reference/scripts/setup-keychain-salt.sh +12 -0
  123. package/reference/scripts/skill-optimizer-friday.sh +88 -0
  124. package/reference/scripts/skill-qc-test.sh +351 -0
  125. package/reference/scripts/skill-synthesize-tonight.sh +66 -0
  126. package/reference/specs/HARNESS-EXTRACTION-SPEC.md +263 -0
  127. package/reference/specs/harness-v3-bash-deletion-plan.md +65 -0
  128. package/reference/specs/harness-v3-migration-plan.md +188 -0
  129. package/scripts/decision-reconcile.sh +74 -0
  130. package/scripts/decision-reconcile.ts +152 -0
  131. package/scripts/extract-constraints.ts +260 -0
  132. package/scripts/generate-code-map.ts +339 -0
  133. package/scripts/git-hooks/pre-commit +76 -0
  134. package/scripts/git-hooks/pre-push +271 -0
  135. package/scripts/harness-skill-check.sh +52 -0
  136. package/scripts/lib/gap-emit.sh +65 -0
  137. package/scripts/lib/jq-update.sh +30 -0
  138. package/scripts/lib/resolve-slug.sh +30 -0
  139. package/scripts/lib/verify-spec-compliance.sh +102 -0
  140. package/scripts/prove-backfill.sh +87 -0
  141. package/scripts/scaffold-project.ts +1488 -0
  142. package/scripts/scaffold-rungate-config.ts +91 -0
  143. package/scripts/self-containment-check.sh +109 -0
  144. package/scripts/skill-qc-validator.sh +402 -0
  145. package/scripts/slug-resolver.sh +14 -0
  146. package/scripts/sync-spec-tests.ts +236 -0
  147. package/specs/BOOTSTRAP-DATA-FLOW-SPEC.md +2493 -0
  148. package/specs/BOOTSTRAP-TEST-PLAN.md +571 -0
  149. package/specs/HARNESS-GATES.md +256 -0
  150. package/specs/HARNESS-SKILL-CHAIN.md +286 -0
  151. package/specs/HARNESS-SKILL-CONTRACT.md +93 -0
  152. package/specs/HARNESS-STANDARD.md +488 -0
  153. package/specs/SPEC-TEMPLATE.md +53 -0
  154. package/specs/bootstrap-data-flow.png +0 -0
  155. package/specs/harness-automation-matrix.md +314 -0
  156. package/specs/harness-automation-matrix.rules.json +64 -0
  157. package/test/anti.test.ts +80 -0
  158. package/test/contract-negative.test.ts +86 -0
  159. package/test/contract.test.ts +158 -0
  160. package/test/external-deps.test.ts +48 -0
  161. package/test/fixtures/golden-project/.env.example +3 -0
  162. package/test/fixtures/golden-project/Makefile +7 -0
  163. package/test/fixtures/golden-project/docs/adr/ADR-001-framework.md +23 -0
  164. package/test/fixtures/golden-project/docs/setup-guide.md +10 -0
  165. package/test/fixtures/golden-project/package.json +10 -0
  166. package/test/fixtures/golden-project/specs/api-spec.md +20 -0
  167. package/test/fixtures/golden-project/src/auth.ts +8 -0
  168. package/test/fixtures/golden-project/src/db.ts +11 -0
  169. package/test/fixtures/golden-project/src/index.ts +19 -0
  170. package/test/fixtures/golden-project/src/utils/format.ts +3 -0
  171. package/test/fixtures/golden-project/test/auth.test.ts +15 -0
  172. package/test/fixtures/golden-project/tsconfig.json +12 -0
  173. package/test/meta-sc-coverage.test.ts +159 -0
  174. package/test/phase-0.test.ts +846 -0
  175. package/test/phase-1.test.ts +617 -0
  176. package/test/phase-2.test.ts +620 -0
  177. package/test/phase-3.test.ts +99 -0
  178. package/test/scaffold-conformity.test.ts +8 -0
  179. package/test/schema-canary.test.ts +51 -0
  180. package/test/spec-compliance-auto.test.ts +64 -0
  181. package/test/spec-compliance.test.ts +295 -0
  182. package/test/spec-discovery.test.ts +68 -0
  183. package/test/spec-drift.test.ts +5 -0
  184. package/test/structure.test.ts +165 -0
  185. package/test/unit/agent-brief-guard-ship.test.ts +293 -0
  186. package/test/unit/extract-constraints.test.ts +145 -0
  187. package/test/unit/issue-close-guard.test.ts +204 -0
  188. package/test/unit/scaffold-project.test.ts +417 -0
  189. package/test/unit/skill-cooccurrence.test.ts +177 -0
  190. package/test/unit/skill-sequence-logger.test.ts +244 -0
  191. package/test/unit/workflow-state-guard.test.ts +95 -0
  192. package/workflows/batch-ship.js +295 -0
  193. package/workflows/council.js +481 -0
  194. package/workflows/prove.js +560 -0
  195. package/workflows/ship.js +789 -0
  196. package/workflows/verify.js +236 -0
@@ -0,0 +1,481 @@
1
+ export const meta = {
2
+ name: 'council',
3
+ description: 'Multi-round parallel debate with progressive transcript passing',
4
+ whenToUse: 'Architecture decisions, tradeoff analysis, design reviews, any question needing multiple perspectives.',
5
+ phases: [
6
+ { title: 'Research', detail: 'Codebase scan — find relevant files, patterns, prior art' },
7
+ { title: 'Round 1', detail: 'Independent positions — informed by research' },
8
+ { title: 'Round 2', detail: 'Responses — must reference Round 1 points' },
9
+ { title: 'Round 3', detail: 'Synthesis — identify convergence and disagreement' },
10
+ { title: 'Synthesis', detail: 'Chair produces recommendation from all rounds' },
11
+ ],
12
+ }
13
+
14
+ const POSITION_SCHEMA = {
15
+ type: 'object',
16
+ properties: {
17
+ agent: { type: 'string' },
18
+ position: { type: 'string' },
19
+ keyPoints: { type: 'array', items: { type: 'string' } },
20
+ concerns: { type: 'array', items: { type: 'string' } },
21
+ recommendation: { type: 'string' },
22
+ },
23
+ required: ['agent', 'position', 'keyPoints', 'recommendation'],
24
+ }
25
+
26
+ const SYNTHESIS_SCHEMA = {
27
+ type: 'object',
28
+ properties: {
29
+ convergencePoints: { type: 'array', items: { type: 'string' } },
30
+ disagreements: { type: 'array', items: { type: 'string' } },
31
+ recommendation: { type: 'string' },
32
+ rationale: { type: 'string' },
33
+ risks: { type: 'array', items: { type: 'string' } },
34
+ nextSteps: { type: 'array', items: { type: 'string' } },
35
+ enforcementClassification: {
36
+ type: 'array',
37
+ items: {
38
+ type: 'object',
39
+ properties: {
40
+ item: { type: 'string' },
41
+ type: { type: 'string', enum: ['MECHANICAL', 'BEHAVIORAL'] },
42
+ mechanism: { type: 'string' },
43
+ whyNotMechanical: { type: 'string' },
44
+ },
45
+ required: ['item', 'type'],
46
+ },
47
+ },
48
+ specAlignment: {
49
+ type: 'object',
50
+ properties: {
51
+ specRef: { type: 'string' },
52
+ aligned: { type: 'boolean' },
53
+ divergenceReason: { type: 'string' },
54
+ },
55
+ required: ['aligned'],
56
+ },
57
+ },
58
+ required: ['convergencePoints', 'disagreements', 'recommendation', 'rationale', 'enforcementClassification', 'specAlignment'],
59
+ }
60
+
61
+ const RESEARCH_SCHEMA = {
62
+ type: 'object',
63
+ properties: {
64
+ relevantFiles: { type: 'array', items: { type: 'string' } },
65
+ existingPatterns: { type: 'array', items: { type: 'string' } },
66
+ priorArt: { type: 'array', items: { type: 'string' } },
67
+ keyFindings: { type: 'array', items: { type: 'string' } },
68
+ warnings: { type: 'array', items: { type: 'string' } },
69
+ },
70
+ required: ['relevantFiles', 'keyFindings'],
71
+ }
72
+
73
+ // Parse args if passed as string
74
+ let parsedArgs = args || {}
75
+ if (typeof parsedArgs === 'string') {
76
+ try { parsedArgs = JSON.parse(parsedArgs) } catch { parsedArgs = {} }
77
+ }
78
+
79
+ if (!parsedArgs || !parsedArgs.topic) {
80
+ return {
81
+ status: 'ARGS_ERROR',
82
+ message: 'Missing required args. Usage: Workflow({ name: "council", args: { topic: "Should we...", rounds: 3, members: ["architect","engineer","designer","security"] } })',
83
+ received: parsedArgs,
84
+ }
85
+ }
86
+
87
+ const TOPIC = parsedArgs.topic
88
+ const ROUNDS = parsedArgs.rounds || 3
89
+ const MEMBERS = parsedArgs.members || ['architect', 'engineer', 'designer', 'security']
90
+ const CONTEXT = parsedArgs.context || ''
91
+ const NO_RESEARCH = parsedArgs.noResearch || false
92
+ const ISSUE = parsedArgs.issue || null
93
+ const SLUG = parsedArgs.slug || null
94
+ const GOVERNING_SPEC = parsedArgs.governingSpec || null
95
+ const RESEARCH_DIR = SLUG ? `~/.rungate/${SLUG}` : '~/.rungate/council-research'
96
+
97
+ const MEMBER_PROMPTS = {
98
+ architect: 'You are Serena Blackwood, a senior systems architect. Focus on: scalability, modularity, data flow, separation of concerns, long-term maintainability. Challenge over-engineering and under-engineering equally.',
99
+ engineer: 'You are Marcus Webb, a principal engineer. Focus on: implementation feasibility, performance, testability, developer experience, edge cases. Ground abstract ideas in concrete code paths.',
100
+ designer: 'You are Aditi Sharma, a UX/UI design specialist. Focus on: user experience, accessibility, information hierarchy, interaction patterns, cognitive load. Advocate for the end user.',
101
+ security: 'You are Rook Blackburn, a security specialist. Focus on: attack surfaces, data exposure, authentication/authorization, input validation, compliance. Find what others miss.',
102
+ product: 'You are a product manager. Focus on: user value, business impact, prioritization, MVP scope, measurable outcomes. Cut scope that doesn\'t directly serve the user.',
103
+ devops: 'You are an infrastructure specialist. Focus on: deployment, monitoring, reliability, cost, operational burden. Flag anything that creates oncall pain.',
104
+ }
105
+
106
+ // ════════════════════════════════════════════════════════════
107
+ // PHASE 0: Research (codebase scan)
108
+ // ════════════════════════════════════════════════════════════
109
+
110
+ let researchContext = ''
111
+
112
+ if (!NO_RESEARCH) {
113
+ phase('Research')
114
+ log('Phase 0: Parallel research — codebase scan + external sources...')
115
+
116
+ const [codebaseResearch, externalResearch] = await parallel([
117
+ () => agent(`You are a codebase research agent. Search the LOCAL CODEBASE for facts relevant to a council debate.
118
+
119
+ TOPIC: ${TOPIC}
120
+ ${CONTEXT ? `CONTEXT: ${CONTEXT}` : ''}
121
+ ${GOVERNING_SPEC ? `\n**MANDATORY: Read this governing spec FIRST before any other research: ${GOVERNING_SPEC}\nExtract ALL design decisions from it. The council's recommendation MUST align with this spec or explicitly argue for amending it.**\n` : ''}
122
+
123
+ DO THIS:
124
+ 1. grep for keywords from the topic — list every relevant file path with line numbers
125
+ 2. READ the relevant sections of each file — extract the actual code/config, not just the path
126
+ 3. Check PAI/ADR/ and PAI/specs/ for related design docs
127
+ 4. **CRITICAL — Governing spec extraction:** If you find ADRs or specs related to this topic, you MUST:
128
+ a. READ the full document (not just the filename)
129
+ b. EXTRACT the specific design decisions, architectural choices, and constraints
130
+ c. Quote the exact lines that govern this topic's design space
131
+ d. List what the spec says the implementation SHOULD look like
132
+ This is the most important step. A council that debates without knowing its governing spec will produce recommendations that contradict the spec.
133
+ 5. If topic involves builds/deploys/infrastructure: READ the Makefile and extract relevant targets with their full commands
134
+ 6. Check git log for recent related commits
135
+
136
+ YOUR FINAL TEXT OUTPUT IS YOUR RETURN VALUE. Structure it with these headers:
137
+
138
+ ## Relevant Files
139
+ - path/file.ts:42 — description
140
+
141
+ ## Existing Patterns
142
+ - Pattern name: how it works (cite file:line)
143
+
144
+ ## Prior Art
145
+ - ADR-NNN: relevant section — key quote
146
+
147
+ ## Governing Spec Decisions
148
+ - Decision 1: exact quote from spec
149
+ - Decision 2: exact quote from spec
150
+ (If no governing spec found, state "No governing spec found for this topic")
151
+
152
+
153
+ ## Key Findings
154
+ - Most important discovery
155
+
156
+ ## Warnings
157
+ - Gotcha or constraint
158
+
159
+ Be thorough. READ files, don't guess. Include line numbers. Facts only, no opinions.`, { label: 'codebase-researcher', phase: 'Research' }),
160
+
161
+ () => agent(`You are an external research agent. Search the INTERNET and DOCUMENTATION for patterns relevant to a council debate.
162
+
163
+ TOPIC: ${TOPIC}
164
+ ${CONTEXT ? `CONTEXT: ${CONTEXT}` : ''}
165
+
166
+ DO THIS:
167
+ 1. Use WebSearch to find how other projects solve this problem — search 2-3 different queries
168
+ 2. Use Context7 (resolve-library-id then query-docs) for any frameworks/tools mentioned in the topic
169
+ 3. Find established design patterns and their trade-offs
170
+ 4. Find anti-patterns — what has failed for others
171
+
172
+ YOUR FINAL TEXT OUTPUT IS YOUR RETURN VALUE. Structure it with these headers:
173
+
174
+ ## Industry Patterns
175
+ - Pattern name (used by: project/tool): how it works
176
+
177
+ ## Prior Art
178
+ - Framework/tool: relevant approach — key insight
179
+
180
+ ## Key Findings
181
+ - Most important external pattern that applies
182
+
183
+ ## Warnings
184
+ - Anti-pattern or failure mode from external sources
185
+
186
+ Search MULTIPLE sources. Include URLs. Facts only, no opinions.`, { label: 'external-researcher', phase: 'Research' })
187
+ ])
188
+
189
+ const parts = []
190
+
191
+ if (codebaseResearch) {
192
+ parts.push(`## Codebase Research\n\n${codebaseResearch}`)
193
+ const lineCount = codebaseResearch.split('\n').filter(l => l.trim()).length
194
+ log(`Codebase research: ${lineCount} content lines`)
195
+ }
196
+
197
+ if (externalResearch) {
198
+ parts.push(`## External Research\n\n${externalResearch}`)
199
+ const lineCount = externalResearch.split('\n').filter(l => l.trim()).length
200
+ log(`External research: ${lineCount} content lines`)
201
+ }
202
+
203
+ researchContext = parts.length > 0 ? parts.join('\n\n---\n\n') : ''
204
+
205
+ // Write slim research output — synthesis + sources only.
206
+ // findings[] deferred until a real consumer defines what a "finding" means (#300)
207
+ if (researchContext) {
208
+ const sourceRefs = []
209
+ const sections = researchContext.split(/^## /m).filter(s => s.trim())
210
+ let keyFindings = ''
211
+
212
+ for (const section of sections) {
213
+ const lines = section.split('\n')
214
+ const header = lines[0].trim()
215
+ if (header === 'Codebase Research' || header === 'External Research') continue
216
+
217
+ const bullets = lines.slice(1).filter(l => l.trim().startsWith('- ')).map(l => l.trim().replace(/^- /, '').replace(/`/g, ''))
218
+
219
+ for (const bullet of bullets) {
220
+ const fileRefs = bullet.match(/[\w\/.~-]+\.\w+:\d+/g) || []
221
+ for (const ref of fileRefs) {
222
+ if (!sourceRefs.find(s => s.name === ref)) sourceRefs.push({ name: ref, type: 'code' })
223
+ }
224
+ const urlRefs = bullet.match(/https?:\/\/\S+/g) || []
225
+ for (const ref of urlRefs) {
226
+ if (!sourceRefs.find(s => s.name === ref)) sourceRefs.push({ name: ref, type: 'web' })
227
+ }
228
+ }
229
+
230
+ if (header === 'Key Findings') keyFindings = bullets.join(' ')
231
+ }
232
+
233
+ const researchOutput = {
234
+ contractVersion: '1.0',
235
+ query: TOPIC,
236
+ sources: sourceRefs.length > 0 ? sourceRefs : [{ name: 'research-agents', type: 'code' }],
237
+ synthesis: (keyFindings || 'No key findings extracted').slice(0, 1000),
238
+ capturedAt: '(set-by-caller)'
239
+ }
240
+
241
+ await agent(`Write this JSON to ${RESEARCH_DIR}/research-output.json (create directory with mkdir -p if needed):\n${JSON.stringify(researchOutput)}`, { label: 'write-research', phase: 'Research' })
242
+ log(`Research output: ${sourceRefs.length} sources, synthesis ${researchOutput.synthesis.length} chars → ${RESEARCH_DIR}/research-output.json`)
243
+ }
244
+
245
+ if (!researchContext) {
246
+ log('Both research agents returned no results — proceeding without research context')
247
+ }
248
+ } else {
249
+ log('WARN: Research skipped (--noResearch flag) — council debates with training knowledge only. Findings may miss codebase patterns and external prior art.')
250
+ }
251
+
252
+ // ════════════════════════════════════════════════════════════
253
+ // ROUND 1: Independent Positions
254
+ // ════════════════════════════════════════════════════════════
255
+
256
+ phase('Round 1')
257
+ log(`Council convened: ${MEMBERS.length} members, ${ROUNDS} rounds`)
258
+ log(`Topic: ${TOPIC}`)
259
+
260
+ const round1 = await parallel(
261
+ MEMBERS.map(member => () => agent(`
262
+ ${MEMBER_PROMPTS[member] || `You are a ${member} specialist. Bring your domain expertise.`}
263
+
264
+ ## Council Topic
265
+ ${TOPIC}
266
+
267
+ ${CONTEXT ? `## Additional Context\n${CONTEXT}` : ''}
268
+
269
+ ${researchContext ? researchContext : ''}
270
+
271
+ ## Instructions
272
+ This is Round 1 — give your INDEPENDENT position. You have not seen other council members' views.
273
+ - State your position clearly
274
+ - List 3-5 key points supporting your view
275
+ - Flag any concerns or risks you see
276
+ - Give a concrete recommendation
277
+
278
+ Be direct and specific. No hedging. Take a clear stance.
279
+ ${researchContext ? '\n**SPEC ALIGNMENT:** If the research includes a governing spec or ADR, your recommendation MUST either align with its design decisions or explicitly state why the spec should be amended. Silent contradiction is not acceptable.' : ''}
280
+ `, { label: `r1:${member}`, phase: 'Round 1', schema: POSITION_SCHEMA }))
281
+ )
282
+
283
+ const round1Transcript = round1
284
+ .filter(Boolean)
285
+ .map(r => `### ${r.agent}\n**Position:** ${r.position}\n**Key Points:**\n${r.keyPoints.map(p => `- ${p}`).join('\n')}\n**Concerns:** ${(r.concerns || []).join(', ')}\n**Recommendation:** ${r.recommendation}`)
286
+ .join('\n\n---\n\n')
287
+
288
+ log(`Round 1 complete — ${round1.filter(Boolean).length} positions collected`)
289
+
290
+ if (ROUNDS < 2) {
291
+ phase('Synthesis')
292
+ const synthesis = await agent(`
293
+ You are the council chair. Synthesize Round 1 positions into a recommendation.
294
+
295
+ ## Topic
296
+ ${TOPIC}
297
+
298
+ ## Round 1 Positions
299
+ ${round1Transcript}
300
+
301
+ ${researchContext ? researchContext : ''}
302
+
303
+ Identify: convergence points, disagreements, recommended path with rationale, risks, and next steps.
304
+ `, { label: 'chair:synthesis', phase: 'Synthesis', schema: SYNTHESIS_SCHEMA })
305
+
306
+ return { rounds: 1, research: NO_RESEARCH ? null : researchContext, round1: round1.filter(Boolean), synthesis: synthesis }
307
+ }
308
+
309
+ // ════════════════════════════════════════════════════════════
310
+ // ROUND 2: Responses (must reference Round 1)
311
+ // ════════════════════════════════════════════════════════════
312
+
313
+ phase('Round 2')
314
+ log('Round 2 — members respond to each other')
315
+
316
+ const round2 = await parallel(
317
+ MEMBERS.map(member => () => agent(`
318
+ ${MEMBER_PROMPTS[member] || `You are a ${member} specialist.`}
319
+
320
+ ## Council Topic
321
+ ${TOPIC}
322
+
323
+ ${researchContext ? researchContext : ''}
324
+
325
+ ## Round 1 Transcript (all positions)
326
+ ${round1Transcript}
327
+
328
+ ## Instructions — Round 2
329
+ You have now seen all Round 1 positions. In this round you MUST:
330
+ 1. Reference at least 2 other members' points BY NAME (agree, challenge, or build on them)
331
+ 2. Update your position if others raised valid points you hadn't considered
332
+ 3. Identify the strongest counterargument to your position and address it
333
+ 4. Sharpen your recommendation based on the discussion
334
+
335
+ Do NOT repeat your Round 1 position. Engage with the other perspectives.
336
+ ${researchContext ? '\n**SPEC ALIGNMENT:** If the research includes a governing spec or ADR, your recommendation MUST either align with its design decisions or explicitly state why the spec should be amended. Silent contradiction is not acceptable.' : ''}
337
+ `, { label: `r2:${member}`, phase: 'Round 2', schema: POSITION_SCHEMA }))
338
+ )
339
+
340
+ const round2Transcript = round2
341
+ .filter(Boolean)
342
+ .map(r => `### ${r.agent}\n**Position:** ${r.position}\n**Key Points:**\n${r.keyPoints.map(p => `- ${p}`).join('\n')}\n**Concerns:** ${(r.concerns || []).join(', ')}\n**Recommendation:** ${r.recommendation}`)
343
+ .join('\n\n---\n\n')
344
+
345
+ log(`Round 2 complete — ${round2.filter(Boolean).length} responses collected`)
346
+
347
+ if (ROUNDS < 3) {
348
+ phase('Synthesis')
349
+ const synthesis = await agent(`
350
+ You are the council chair. Synthesize 2 rounds of debate into a recommendation.
351
+
352
+ ## Topic
353
+ ${TOPIC}
354
+
355
+ ## Round 1 Positions
356
+ ${round1Transcript}
357
+
358
+ ## Round 2 Responses
359
+ ${round2Transcript}
360
+
361
+ ${researchContext ? researchContext : ''}
362
+
363
+ Identify: convergence points, remaining disagreements, recommended path, rationale, risks, next steps.
364
+ `, { label: 'chair:synthesis', phase: 'Synthesis', schema: SYNTHESIS_SCHEMA })
365
+
366
+ return { rounds: 2, research: NO_RESEARCH ? null : researchContext, round1: round1.filter(Boolean), round2: round2.filter(Boolean), synthesis: synthesis }
367
+ }
368
+
369
+ // ════════════════════════════════════════════════════════════
370
+ // ROUND 3: Synthesis (identify convergence)
371
+ // ════════════════════════════════════════════════════════════
372
+
373
+ phase('Round 3')
374
+ log('Round 3 — members synthesize and identify convergence')
375
+
376
+ const round3 = await parallel(
377
+ MEMBERS.map(member => () => agent(`
378
+ ${MEMBER_PROMPTS[member] || `You are a ${member} specialist.`}
379
+
380
+ ## Council Topic
381
+ ${TOPIC}
382
+
383
+ ${researchContext ? researchContext : ''}
384
+
385
+ ## Full Transcript
386
+
387
+ ### Round 1
388
+ ${round1Transcript}
389
+
390
+ ### Round 2
391
+ ${round2Transcript}
392
+
393
+ ## Instructions — Round 3 (Final)
394
+ This is the final round. You MUST:
395
+ 1. Identify where the council is CONVERGING (shared agreement)
396
+ 2. Identify remaining DISAGREEMENTS that need resolution
397
+ 3. State your FINAL recommendation, informed by all discussion
398
+ 4. If you changed your position from Round 1, explain why
399
+ 5. Propose specific NEXT STEPS the team should take
400
+
401
+ Focus on actionable conclusions, not further debate.
402
+ ${researchContext ? '\n**SPEC ALIGNMENT:** If the research includes a governing spec or ADR, your recommendation MUST either align with its design decisions or explicitly state why the spec should be amended. Silent contradiction is not acceptable.' : ''}
403
+ `, { label: `r3:${member}`, phase: 'Round 3', schema: POSITION_SCHEMA }))
404
+ )
405
+
406
+ const round3Transcript = round3
407
+ .filter(Boolean)
408
+ .map(r => `### ${r.agent}\n**Position:** ${r.position}\n**Key Points:**\n${r.keyPoints.map(p => `- ${p}`).join('\n')}\n**Recommendation:** ${r.recommendation}`)
409
+ .join('\n\n---\n\n')
410
+
411
+ log(`Round 3 complete — ${round3.filter(Boolean).length} final positions collected`)
412
+
413
+ // ════════════════════════════════════════════════════════════
414
+ // SYNTHESIS: Chair produces recommendation
415
+ // ════════════════════════════════════════════════════════════
416
+
417
+ phase('Synthesis')
418
+ log('Chair synthesizing all 3 rounds')
419
+
420
+ const synthesis = await agent(`
421
+ You are the council chair — an impartial synthesizer. Your job is to distill 3 rounds of debate into a clear, actionable recommendation.
422
+
423
+ ## Topic
424
+ ${TOPIC}
425
+
426
+ ## Round 1 — Independent Positions
427
+ ${round1Transcript}
428
+
429
+ ## Round 2 — Responses and Challenges
430
+ ${round2Transcript}
431
+
432
+ ## Round 3 — Final Positions and Convergence
433
+ ${round3Transcript}
434
+
435
+ ${researchContext ? researchContext : ''}
436
+
437
+ ## Your Task
438
+ 1. **Convergence points** — where did the council agree? List each point.
439
+ 2. **Remaining disagreements** — what's still contested? Be specific.
440
+ 3. **Recommendation** — your recommended path forward. Be decisive — pick one direction.
441
+ 4. **Rationale** — why this path, given the discussion? Reference specific member arguments.
442
+ 5. **Risks** — what could go wrong with this recommendation?
443
+ 6. **Next steps** — concrete, actionable items to implement the recommendation.
444
+ 7. **Enforcement classification** — for EACH recommendation and next step, classify:
445
+ - MECHANICAL: can be enforced by code (gate check, hook, smoke test, schema validation). Specify the enforcement mechanism.
446
+ - BEHAVIORAL: can only be enforced by a CLAUDE.md rule or human discipline. Explain why it can't be mechanical.
447
+ The bar is: "mechanical-enforcement-over-rules" — behavioral rules get violated. If a recommendation CAN be a gate check, smoke test, or hook, it MUST be. Only recommend CLAUDE.md rules for things that genuinely can't be automated. If more than half of recommendations are BEHAVIORAL, flag this as a concern.
448
+ 8. **Spec alignment** — Does your recommendation align with or contradict any governing spec/ADR found in the research? If a governing spec exists:
449
+ - Set specRef to the spec path
450
+ - Set aligned to true/false
451
+ - If diverging, explain why and flag as "SPEC AMENDMENT REQUIRED" — the spec must be updated before implementation
452
+ A recommendation that silently contradicts its governing spec is a council failure.
453
+
454
+ Be decisive. The council debated — now someone needs to decide.
455
+ `, { label: 'chair:synthesis', phase: 'Synthesis', schema: SYNTHESIS_SCHEMA })
456
+
457
+ log('Council complete')
458
+
459
+ // Write council-synthesis.json with schema-compliant envelope
460
+ if (SLUG) {
461
+ const synthEnvelope = {
462
+ contractVersion: '1.0',
463
+ topic: TOPIC,
464
+ decisions: [],
465
+ capturedAt: '(set-by-caller)',
466
+ ...synthesis,
467
+ }
468
+ await agent(`Write this JSON to ~/.rungate/${SLUG}/council-synthesis.json (create directory with mkdir -p if needed):\n${JSON.stringify(synthEnvelope)}`, { label: 'write-synthesis', phase: 'Synthesis' })
469
+ log(`Council synthesis written to ~/.rungate/${SLUG}/council-synthesis.json`)
470
+ }
471
+
472
+ return {
473
+ topic: TOPIC,
474
+ rounds: 3,
475
+ members: MEMBERS,
476
+ research: NO_RESEARCH ? null : researchContext,
477
+ round1: round1.filter(Boolean),
478
+ round2: round2.filter(Boolean),
479
+ round3: round3.filter(Boolean),
480
+ synthesis: synthesis,
481
+ }