opencode-orchestra 0.0.0-stage → 1.0.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.
@@ -0,0 +1,545 @@
1
+ import { saveTeamworkState } from "./board.js";
2
+ import { extractConversationContext, mergeAdditionalContext, } from "./context.js";
3
+ import { heuristicClassifyTeamwork, parseTeamworkClassifierDecision, parseVerificationDecision, } from "./parser.js";
4
+ import { runIsolatedWorker, throwIfAborted, } from "./pipeline.js";
5
+ export function buildTeamworkClassifyPrompt(task) {
6
+ return [
7
+ "Classify the following software engineering task into exactly one Teamwork mode:",
8
+ "- `swe`: implementing features, fixing bugs, refactoring, or modifying code with QA/review gates.",
9
+ "- `review`: pure code/document/architecture review or critique WITHOUT modifying source files.",
10
+ "- `audit`: deep forensic & victory audit of a document, spec, or codebase claims WITHOUT modifying files.",
11
+ "- `discover`: open-ended exploration, hypothesis testing, and knowledge curation (duo discovery).",
12
+ "- `colosseum`: comparing competing designs, approaches, or architectures with a Judge.",
13
+ "",
14
+ "Reply with ONLY one word: `swe`, `review`, `audit`, `discover`, or `colosseum`.",
15
+ "",
16
+ `<task>\n${task}\n</task>`,
17
+ ].join("\n");
18
+ }
19
+ function renderContextBlocks(contextBlocks) {
20
+ const trimmed = contextBlocks?.trim();
21
+ if (!trimmed)
22
+ return "";
23
+ return `\n\n${trimmed}`;
24
+ }
25
+ export function buildTeamworkImplementerPrompt(task, contextBlocks) {
26
+ return `You are a Teamwork agent with role: **implementer**.
27
+ - **implementer**: Code modification — implement changes cleanly and verify correctness.
28
+
29
+ <original_task>
30
+ ${task}
31
+ </original_task>${renderContextBlocks(contextBlocks)}
32
+
33
+ ## Rules
34
+ 1. Read <original_task> verbatim and explore the relevant files before editing.
35
+ 2. Implement the change following the repository's existing conventions.
36
+ 3. Run the actual build and test suite — never claim verification you did not execute.
37
+ 4. Do NOT weaken, skip, or delete existing tests to make your change pass.
38
+ 5. Report ONCE at the very end with an explicit Verification Record separating tested from untested claims.
39
+
40
+ ## Required Handoff Format
41
+ - **Changes Made**: files touched and substance of each change
42
+ - **Verification Record**: exact commands run + observed pass/fail output, plus unverified aspects
43
+ - **Known Risks / Open Questions**: anything the Reviewer and Critic should inspect closely`;
44
+ }
45
+ export function buildTeamworkReviewerPrompt(task, implementerReport, contextBlocks) {
46
+ return `You are a Teamwork agent with role: **reviewer** (Gate Reviewer).
47
+ - **reviewer**: Objective review — assess work quality, verify claims against the actual workspace, and issue a verdict.
48
+
49
+ <original_task>
50
+ ${task}
51
+ </original_task>${renderContextBlocks(contextBlocks)}
52
+
53
+ <implementer_handoff>
54
+ ${implementerReport}
55
+ </implementer_handoff>
56
+
57
+ ## Rules
58
+ 1. Do NOT modify source files.
59
+ 2. Independently verify the workspace (inspect modified files, diffs, and test results).
60
+ 3. Check every requirement in <original_task>. Do NOT approve work that cheats, skips tests, or leaves fatal defects.
61
+ 4. Start your response with:
62
+ - \`VERDICT: PASS\` if all requirements are met and verified, OR
63
+ - \`VERDICT: FAIL\` if defects or unverified critical gaps remain.
64
+ 5. Follow the verdict with concrete, evidence-backed findings (file paths, symbols, commands).`;
65
+ }
66
+ export function buildTeamworkCriticPrompt(task, subjectReport, contextBlocks) {
67
+ return `You are a Teamwork agent with role: **critic**.
68
+ - **critic**: Adversarial challenge — stress-test assumptions, find failure modes, edge cases, and propose counter-examples.
69
+
70
+ <original_task>
71
+ ${task}
72
+ </original_task>${renderContextBlocks(contextBlocks)}
73
+
74
+ <subject_report>
75
+ ${subjectReport}
76
+ </subject_report>
77
+
78
+ ## Rules
79
+ 1. Do NOT modify source files.
80
+ 2. Treat <subject_report> as an unverified hypothesis. Probe boundary values, null/empty inputs, error paths, concurrency, and subtle regressions.
81
+ 3. Only report concrete, reproducible, or code-evidenced failure modes — cite exact files/lines or counter-examples.
82
+ 4. Start your response with:
83
+ - \`VERDICT: PASS\` if no material defects or counter-examples were found, OR
84
+ - \`VERDICT: FAIL\` if you found concrete defects that must be fixed.`;
85
+ }
86
+ export function buildTeamworkQaPrompt(task, implementerReport, reviewerReport, criticReport, round, contextBlocks, openIssuesLedger) {
87
+ const ledgerBlock = openIssuesLedger && openIssuesLedger.length > 0
88
+ ? `\n\n<cumulative_open_issues_ledger>\n${openIssuesLedger.join("\n")}\n</cumulative_open_issues_ledger>`
89
+ : "";
90
+ return `You are a Teamwork agent with role: **qa** (QA Fix Round #${round}).
91
+ - **qa**: Quality assurance — fix defects only, no unrelated feature work.
92
+
93
+ <original_task>
94
+ ${task}
95
+ </original_task>${renderContextBlocks(contextBlocks)}${ledgerBlock}
96
+
97
+ <implementer_handoff>
98
+ ${implementerReport}
99
+ </implementer_handoff>
100
+
101
+ <reviewer_findings>
102
+ ${reviewerReport}
103
+ </reviewer_findings>
104
+
105
+ <critic_findings>
106
+ ${criticReport}
107
+ </critic_findings>
108
+
109
+ ## Rules
110
+ 1. Fix every valid defect identified by the Reviewer, Critic, and cumulative open-issues ledger with minimal, clean diffs.
111
+ 2. Add or strengthen tests covering each defect you fixed.
112
+ 3. Run the full relevant test suite and report exact commands and results.
113
+ 4. Provide a concise QA Handoff summarizing defects fixed and Verification Record.`;
114
+ }
115
+ export function buildTeamworkReviewTrackPrompt(task, role, contextBlocks) {
116
+ const roleDesc = role === "reviewer"
117
+ ? "Objective review: assess completeness, correctness, clarity, and verify all claims against the codebase/document."
118
+ : "Adversarial challenge: stress-test assumptions, identify failure modes, security/robustness risks, and propose counter-examples.";
119
+ return `You are a Teamwork agent with role: **${role}** (Document / Codebase Review Track).
120
+ - **${role}**: ${roleDesc}
121
+
122
+ <original_task>
123
+ ${task}
124
+ </original_task>${renderContextBlocks(contextBlocks)}
125
+
126
+ ## Rules
127
+ 1. Do NOT modify repository source files.
128
+ 2. Cite exact file paths, line numbers, symbols, and concrete evidence for every finding.
129
+ 3. Organize findings by severity (Critical, Major, Minor) and clearly separate facts from inferences.`;
130
+ }
131
+ export function buildTeamworkSynthesizerPrompt(task, reviewerReport, criticReport, contextBlocks) {
132
+ return `You are the Teamwork **Track Synthesizer** (Document / Codebase Review Variant).
133
+ Aggregate the independent Reviewer and Critic reports into an authoritative Executive Summary + consolidated technical review.
134
+
135
+ <original_task>
136
+ ${task}
137
+ </original_task>${renderContextBlocks(contextBlocks)}
138
+
139
+ <reviewer_report>
140
+ ${reviewerReport}
141
+ </reviewer_report>
142
+
143
+ <critic_report>
144
+ ${criticReport}
145
+ </critic_report>
146
+
147
+ ## Instructions
148
+ 1. Deduplicate overlapping findings and resolve any disagreements using evidence.
149
+ 2. Lead with a concise **Executive Summary** and overall assessment.
150
+ 3. Present prioritized, actionable findings (Critical -> Major -> Minor) with exact file/line citations.`;
151
+ }
152
+ export function buildTeamworkColosseumWorkerPrompt(task, contenderIndex, totalContenders, contextBlocks) {
153
+ const angleHints = [
154
+ "Favor simplicity, minimal diff, and idiomatic maintainability.",
155
+ "Favor robustness, extensibility, edge-case resilience, and performance.",
156
+ "Favor an unconventional or alternative architecture that avoids hidden coupling.",
157
+ "Favor strict type safety, testability, and zero-regression guarantees.",
158
+ "Favor operational clarity, observability, and clean failure recovery.",
159
+ ];
160
+ const angle = angleHints[(contenderIndex - 1) % angleHints.length];
161
+ return `You are **Contender #${contenderIndex} of ${totalContenders}** in a Teamwork Colosseum evaluation.
162
+ Design and justify the strongest possible solution to the task below.
163
+
164
+ <original_task>
165
+ ${task}
166
+ </original_task>${renderContextBlocks(contextBlocks)}
167
+
168
+ ## Design Lens
169
+ ${angle}
170
+
171
+ ## Rules
172
+ 1. Do NOT modify repository source files; inspect the workspace to ground your proposal in real code.
173
+ 2. Provide a concrete, implementable proposal with exact files/APIs, trade-offs, risks, and a verification plan.`;
174
+ }
175
+ export function buildTeamworkColosseumVerifierPrompt(task, proposals, contextBlocks) {
176
+ const formatted = proposals
177
+ .map((p) => `<proposal name="${p.label}">\n${p.report}\n</proposal>`)
178
+ .join("\n\n");
179
+ return `You are the **Teamwork Colosseum Verifier** (independent empirical fact-checker).
180
+ Verify the factual claims, referenced files/APIs, constraints, and feasibility of each contender's proposal before the Judge scores them.
181
+
182
+ <original_task>
183
+ ${task}
184
+ </original_task>${renderContextBlocks(contextBlocks)}
185
+
186
+ ${formatted}
187
+
188
+ ## Rules
189
+ 1. Do NOT modify repository source files.
190
+ 2. For each contender, check whether cited files, symbols, and assumptions actually exist and hold true in the workspace.
191
+ 3. Flag any hallucinated APIs, hidden coupling, or unverified claims so the Judge can weight them accurately.`;
192
+ }
193
+ export function buildTeamworkJudgePrompt(task, proposals, contextBlocks, verifierReport) {
194
+ const formatted = proposals
195
+ .map((p) => `<proposal name="${p.label}">\n${p.report}\n</proposal>`)
196
+ .join("\n\n");
197
+ const verifierBlock = verifierReport?.trim()
198
+ ? `\n\n<independent_verifier_report>\n${verifierReport.trim()}\n</independent_verifier_report>`
199
+ : "";
200
+ return `You are the **Teamwork Colosseum Judge**.
201
+ Evaluate the competing proposals below against <original_task> and select the winning approach (or synthesize a superior hybrid).
202
+
203
+ <original_task>
204
+ ${task}
205
+ </original_task>${renderContextBlocks(contextBlocks)}
206
+
207
+ ${formatted}${verifierBlock}
208
+
209
+ ## Instructions
210
+ 1. Score each contender on: Correctness, Simplicity, Edge-Case Safety, and Fit with the existing codebase (incorporating the independent Verifier's findings).
211
+ 2. Declare a clear winner (or hybrid) and explain why the rejected trade-offs lost.
212
+ 3. Provide a concrete, actionable implementation blueprint for the winning approach.`;
213
+ }
214
+ export function buildTeamworkDiscoveryWorkerPrompt(task, role, contextBlocks) {
215
+ const roleDesc = role === "explorer"
216
+ ? "Deep exploration — map the problem space, code paths, and concrete hypotheses."
217
+ : "Empirical challenge — test hypotheses against real code/runtime evidence and surface counter-examples.";
218
+ return `You are a Teamwork agent with role: **${role}** (Duo Discovery Track).
219
+ - **${role}**: ${roleDesc}
220
+
221
+ <original_task>
222
+ ${task}
223
+ </original_task>${renderContextBlocks(contextBlocks)}
224
+
225
+ ## Rules
226
+ 1. Do NOT modify repository source files.
227
+ 2. Ground every hypothesis and counter-example in exact files, line numbers, symbols, or command outputs.
228
+ 3. End with **Confirmed Findings**, **Refuted Assumptions**, and **Open Questions**.`;
229
+ }
230
+ export function buildTeamworkKnowledgeCuratorPrompt(task, explorerReport, challengerReport, contextBlocks) {
231
+ return `You are the Teamwork **Knowledge Curator** (Duo Discovery Track).
232
+ Consolidate the Explorer and Empirical Challenger findings into a clear, evidence-backed knowledge brief.
233
+
234
+ <original_task>
235
+ ${task}
236
+ </original_task>${renderContextBlocks(contextBlocks)}
237
+
238
+ <explorer_report>
239
+ ${explorerReport}
240
+ </explorer_report>
241
+
242
+ <empirical_challenger_report>
243
+ ${challengerReport}
244
+ </empirical_challenger_report>
245
+
246
+ ## Instructions
247
+ 1. Reconcile hypotheses against empirical challenges; keep only evidence-backed conclusions.
248
+ 2. Present a structured brief: **Verified Facts**, **Refuted Hypotheses**, **Key Trade-offs**, and **Recommended Next Steps**.`;
249
+ }
250
+ export function buildTeamworkAuditWorkerPrompt(task, role, contextBlocks) {
251
+ const roleDesc = role === "forensic_auditor"
252
+ ? "Forensic audit — verify every factual claim, dependency, and code/document citation line by line."
253
+ : "Victory audit — verify whether success criteria, edge cases, and acceptance gates are genuinely met without shortcuts.";
254
+ return `You are a Teamwork agent with role: **${role}** (Forensic & Victory Audit Track).
255
+ - **${role}**: ${roleDesc}
256
+
257
+ <original_task>
258
+ ${task}
259
+ </original_task>${renderContextBlocks(contextBlocks)}
260
+
261
+ ## Rules
262
+ 1. Do NOT modify repository source files.
263
+ 2. Start your response with \`VERDICT: PASS\` or \`VERDICT: FAIL\`.
264
+ 3. Follow with concrete, line-cited findings organized by severity (Critical, Major, Minor).`;
265
+ }
266
+ async function resolveTeamworkMode(sessionClient, sessionID, task, requestedMode) {
267
+ if (requestedMode === "swe" ||
268
+ requestedMode === "review" ||
269
+ requestedMode === "colosseum" ||
270
+ requestedMode === "discover" ||
271
+ requestedMode === "audit") {
272
+ return requestedMode;
273
+ }
274
+ try {
275
+ const res = await sessionClient.generate({
276
+ sessionID,
277
+ prompt: buildTeamworkClassifyPrompt(task),
278
+ });
279
+ return parseTeamworkClassifierDecision(res.text, task);
280
+ }
281
+ catch {
282
+ return heuristicClassifyTeamwork(task);
283
+ }
284
+ }
285
+ async function settleWorkerPair(first, second, childSessionIDs) {
286
+ const [r1, r2] = await Promise.allSettled([first, second]);
287
+ if (r1.status === "fulfilled")
288
+ childSessionIDs.push(r1.value.sessionID);
289
+ if (r2.status === "fulfilled")
290
+ childSessionIDs.push(r2.value.sessionID);
291
+ if (r1.status === "rejected")
292
+ throw r1.reason;
293
+ if (r2.status === "rejected")
294
+ throw r2.reason;
295
+ return [r1.value, r2.value];
296
+ }
297
+ export async function runTeamworkPipeline(sessionClient, options) {
298
+ const { sessionID, task: rawTask, additionalContext, mode: requestedMode = "auto", maxQaRounds = 1, workers = 2, scopingContext, storage, modelOverride, onProgress, signal, } = options;
299
+ const parentContext = additionalContext?.trim()
300
+ ? undefined
301
+ : await extractConversationContext(sessionClient, sessionID);
302
+ const effectiveContext = mergeAdditionalContext(additionalContext, parentContext);
303
+ const contextParts = [];
304
+ if (effectiveContext) {
305
+ contextParts.push(`<additional_context>\n${effectiveContext}\n</additional_context>`);
306
+ }
307
+ if (scopingContext?.trim()) {
308
+ contextParts.push(`<scoping_context>\n${scopingContext.trim()}\n</scoping_context>`);
309
+ }
310
+ const contextBlocks = contextParts.length > 0 ? contextParts.join("\n\n") : undefined;
311
+ const task = rawTask;
312
+ const runId = `tw-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`;
313
+ const persist = async (mode, status, milestones) => {
314
+ if (!storage)
315
+ return;
316
+ try {
317
+ await saveTeamworkState(storage, runId, {
318
+ runId,
319
+ mode,
320
+ task: rawTask,
321
+ status,
322
+ milestones,
323
+ updatedAt: Date.now(),
324
+ });
325
+ }
326
+ catch {
327
+ // Non-fatal persistence error
328
+ }
329
+ };
330
+ const clampedMaxQaRounds = Math.max(0, Math.min(3, Math.floor(maxQaRounds)));
331
+ const childSessionIDs = [];
332
+ throwIfAborted(signal, "Teamwork pipeline");
333
+ await onProgress?.("Teamwork Phase 1: Selecting workflow track...");
334
+ const mode = await resolveTeamworkMode(sessionClient, sessionID, rawTask, requestedMode);
335
+ throwIfAborted(signal, "Teamwork pipeline");
336
+ await persist(mode, "running", [{ name: "track_selected", status: "done" }]);
337
+ try {
338
+ if (mode === "discover") {
339
+ await onProgress?.("Teamwork Duo Discovery: Dispatching Explorer & Empirical Challenger in parallel...");
340
+ const [explorerRes, challengerRes] = await settleWorkerPair(runIsolatedWorker(sessionClient, sessionID, "Teamwork Explorer", buildTeamworkDiscoveryWorkerPrompt(task, "explorer", contextBlocks), modelOverride, signal, undefined, undefined, { readOnly: true }), runIsolatedWorker(sessionClient, sessionID, "Teamwork Empirical Challenger", buildTeamworkDiscoveryWorkerPrompt(task, "empirical_challenger", contextBlocks), modelOverride, signal, undefined, undefined, { readOnly: true }), childSessionIDs);
341
+ await onProgress?.("Teamwork Duo Discovery: Knowledge Curator synthesizing findings...");
342
+ const curatorRes = await runIsolatedWorker(sessionClient, sessionID, "Teamwork Knowledge Curator", buildTeamworkKnowledgeCuratorPrompt(task, explorerRes.text, challengerRes.text, contextBlocks), modelOverride, signal, undefined, undefined, { readOnly: true });
343
+ childSessionIDs.push(curatorRes.sessionID);
344
+ await persist(mode, "completed", [
345
+ { name: "duo_discovery", status: "done" },
346
+ { name: "knowledge_curation", status: "done" },
347
+ ]);
348
+ return {
349
+ runId,
350
+ mode,
351
+ qaRoundsExecuted: 0,
352
+ childSessionIDs,
353
+ report: curatorRes.text,
354
+ gateVerdict: "N/A",
355
+ gateSummary: "Duo Discovery completed with parallel Explorer + Empirical Challenger + Knowledge Curator.",
356
+ };
357
+ }
358
+ if (mode === "audit") {
359
+ await onProgress?.("Teamwork Audit Track: Dispatching Forensic Auditor & Victory Auditor in parallel...");
360
+ const [forensicRes, victoryRes] = await settleWorkerPair(runIsolatedWorker(sessionClient, sessionID, "Teamwork Forensic Auditor", buildTeamworkAuditWorkerPrompt(task, "forensic_auditor", contextBlocks), modelOverride, signal, undefined, undefined, { readOnly: true }), runIsolatedWorker(sessionClient, sessionID, "Teamwork Victory Auditor", buildTeamworkAuditWorkerPrompt(task, "victory_auditor", contextBlocks), modelOverride, signal, undefined, undefined, { readOnly: true }), childSessionIDs);
361
+ const forensicDecision = parseVerificationDecision(forensicRes.text);
362
+ const victoryDecision = parseVerificationDecision(victoryRes.text);
363
+ const auditVerdict = forensicDecision.passed && victoryDecision.passed ? "PASS" : "FAIL";
364
+ await onProgress?.("Teamwork Audit Track: Synthesizing audit report...");
365
+ const synthRes = await runIsolatedWorker(sessionClient, sessionID, "Teamwork Audit Synthesizer", buildTeamworkSynthesizerPrompt(task, forensicRes.text, victoryRes.text, contextBlocks), modelOverride, signal, undefined, undefined, { readOnly: true });
366
+ childSessionIDs.push(synthRes.sessionID);
367
+ await persist(mode, auditVerdict === "PASS" ? "completed" : "failed", [
368
+ { name: "forensic_and_victory_audit", status: "done" },
369
+ { name: "synthesis", status: "done" },
370
+ ]);
371
+ return {
372
+ runId,
373
+ mode,
374
+ qaRoundsExecuted: 0,
375
+ childSessionIDs,
376
+ report: synthRes.text,
377
+ gateVerdict: auditVerdict,
378
+ gateSummary: [
379
+ `### Forensic Auditor (${forensicDecision.passed ? "PASS" : "FAIL"})`,
380
+ forensicDecision.reason,
381
+ "",
382
+ `### Victory Auditor (${victoryDecision.passed ? "PASS" : "FAIL"})`,
383
+ victoryDecision.reason,
384
+ ].join("\n"),
385
+ };
386
+ }
387
+ if (mode === "review") {
388
+ await onProgress?.("Teamwork Review Track: Dispatching parallel Reviewer & Critic...");
389
+ const [reviewerSettled, criticSettled] = await Promise.allSettled([
390
+ runIsolatedWorker(sessionClient, sessionID, "Teamwork Reviewer", buildTeamworkReviewTrackPrompt(task, "reviewer", contextBlocks), modelOverride, signal, undefined, undefined, { readOnly: true }),
391
+ runIsolatedWorker(sessionClient, sessionID, "Teamwork Critic", buildTeamworkReviewTrackPrompt(task, "critic", contextBlocks), modelOverride, signal, undefined, undefined, { readOnly: true }),
392
+ ]);
393
+ throwIfAborted(signal, "Teamwork pipeline");
394
+ if (reviewerSettled.status === "rejected" &&
395
+ criticSettled.status === "rejected") {
396
+ const revErr = reviewerSettled.reason instanceof Error
397
+ ? reviewerSettled.reason.message
398
+ : String(reviewerSettled.reason);
399
+ const critErr = criticSettled.reason instanceof Error
400
+ ? criticSettled.reason.message
401
+ : String(criticSettled.reason);
402
+ throw new Error(`Both Teamwork Review Track workers failed: Reviewer: ${revErr}; Critic: ${critErr}`);
403
+ }
404
+ if (reviewerSettled.status === "fulfilled") {
405
+ childSessionIDs.push(reviewerSettled.value.sessionID);
406
+ }
407
+ if (criticSettled.status === "fulfilled") {
408
+ childSessionIDs.push(criticSettled.value.sessionID);
409
+ }
410
+ const reviewerText = reviewerSettled.status === "fulfilled"
411
+ ? reviewerSettled.value.text
412
+ : `[Reviewer failed: ${reviewerSettled.reason instanceof Error ? reviewerSettled.reason.message : String(reviewerSettled.reason)}]`;
413
+ const criticText = criticSettled.status === "fulfilled"
414
+ ? criticSettled.value.text
415
+ : `[Critic failed: ${criticSettled.reason instanceof Error ? criticSettled.reason.message : String(criticSettled.reason)}]`;
416
+ await onProgress?.("Teamwork Review Track: Synthesizing executive summary...");
417
+ const synthRes = await runIsolatedWorker(sessionClient, sessionID, "Teamwork Track Synthesizer", buildTeamworkSynthesizerPrompt(task, reviewerText, criticText, contextBlocks), modelOverride, signal, undefined, undefined, { readOnly: true });
418
+ childSessionIDs.push(synthRes.sessionID);
419
+ await persist(mode, "completed", [
420
+ { name: "parallel_review", status: "done" },
421
+ { name: "synthesis", status: "done" },
422
+ ]);
423
+ const partialNote = reviewerSettled.status === "rejected"
424
+ ? " (Reviewer failed; synthesized from Critic only)"
425
+ : criticSettled.status === "rejected"
426
+ ? " (Critic failed; synthesized from Reviewer only)"
427
+ : "";
428
+ return {
429
+ runId,
430
+ mode,
431
+ qaRoundsExecuted: 0,
432
+ childSessionIDs,
433
+ report: synthRes.text,
434
+ gateVerdict: "N/A",
435
+ gateSummary: `Review track completed with parallel Reviewer + Critic + Track Synthesizer.${partialNote}`,
436
+ };
437
+ }
438
+ if (mode === "colosseum") {
439
+ const contenderCount = Math.max(2, Math.min(5, Math.floor(workers)));
440
+ await onProgress?.(`Teamwork Colosseum: Dispatching ${contenderCount} competing contenders in parallel...`);
441
+ const contenderSettled = await Promise.allSettled(Array.from({ length: contenderCount }, (_, idx) => runIsolatedWorker(sessionClient, sessionID, `Teamwork Colosseum Contender #${idx + 1}`, buildTeamworkColosseumWorkerPrompt(task, idx + 1, contenderCount, contextBlocks), modelOverride, signal, undefined, undefined, { readOnly: true })));
442
+ throwIfAborted(signal, "Teamwork pipeline");
443
+ const proposals = [];
444
+ const failedContenders = [];
445
+ contenderSettled.forEach((res, idx) => {
446
+ if (res.status === "fulfilled") {
447
+ childSessionIDs.push(res.value.sessionID);
448
+ proposals.push({
449
+ label: `Contender #${idx + 1}`,
450
+ report: res.value.text,
451
+ });
452
+ }
453
+ else {
454
+ const msg = res.reason instanceof Error ? res.reason.message : String(res.reason);
455
+ failedContenders.push(`Contender #${idx + 1}: ${msg}`);
456
+ }
457
+ });
458
+ if (proposals.length === 0) {
459
+ throw new Error(`All ${contenderCount} Teamwork Colosseum contenders failed: ${failedContenders.join("; ")}`);
460
+ }
461
+ await onProgress?.("Teamwork Colosseum: Independent Verifier checking contender claims...");
462
+ const verifierRes = await runIsolatedWorker(sessionClient, sessionID, "Teamwork Colosseum Verifier", buildTeamworkColosseumVerifierPrompt(task, proposals, contextBlocks), modelOverride, signal, undefined, undefined, { readOnly: true });
463
+ childSessionIDs.push(verifierRes.sessionID);
464
+ await onProgress?.("Teamwork Colosseum: Judge evaluating proposals...");
465
+ const judgeRes = await runIsolatedWorker(sessionClient, sessionID, "Teamwork Colosseum Judge", buildTeamworkJudgePrompt(task, proposals, contextBlocks, verifierRes.text), modelOverride, signal, undefined, undefined, { readOnly: true });
466
+ childSessionIDs.push(judgeRes.sessionID);
467
+ await persist(mode, "completed", [
468
+ { name: "contenders", status: "done" },
469
+ { name: "verifier", status: "done" },
470
+ { name: "judge", status: "done" },
471
+ ]);
472
+ return {
473
+ runId,
474
+ mode,
475
+ qaRoundsExecuted: 0,
476
+ childSessionIDs,
477
+ report: judgeRes.text,
478
+ gateVerdict: "N/A",
479
+ gateSummary: `Colosseum evaluated ${proposals.length}/${contenderCount} independent proposals via independent Verifier + Teamwork Judge.${failedContenders.length > 0 ? ` (${failedContenders.length} failed)` : ""}`,
480
+ };
481
+ }
482
+ // Default: SWE Light Track (Implementer -> Parallel Reviewer + Critic Gate -> QA Fix Loop)
483
+ await onProgress?.("Teamwork SWE: Dispatching Implementer...");
484
+ const implRes = await runIsolatedWorker(sessionClient, sessionID, "Teamwork Implementer", buildTeamworkImplementerPrompt(task, contextBlocks), modelOverride, signal);
485
+ childSessionIDs.push(implRes.sessionID);
486
+ let currentReport = implRes.text;
487
+ let qaRoundsExecuted = 0;
488
+ let gateVerdict = "FAIL";
489
+ let gateSummary = "";
490
+ const openIssuesLedger = [];
491
+ for (let attempt = 0; attempt <= clampedMaxQaRounds; attempt++) {
492
+ await onProgress?.(`Teamwork SWE: Running parallel Gate Reviewer & Critic (check #${attempt + 1})...`);
493
+ const [reviewerRes, criticRes] = await settleWorkerPair(runIsolatedWorker(sessionClient, sessionID, `Teamwork Gate Reviewer #${attempt + 1}`, buildTeamworkReviewerPrompt(task, currentReport, contextBlocks), modelOverride, signal, undefined, undefined, { readOnly: true }), runIsolatedWorker(sessionClient, sessionID, `Teamwork Critic #${attempt + 1}`, buildTeamworkCriticPrompt(task, currentReport, contextBlocks), modelOverride, signal, undefined, undefined, { readOnly: true }), childSessionIDs);
494
+ const revDecision = parseVerificationDecision(reviewerRes.text);
495
+ const critDecision = parseVerificationDecision(criticRes.text);
496
+ gateSummary = [
497
+ `### Gate Reviewer (${revDecision.passed ? "PASS" : "FAIL"})`,
498
+ revDecision.reason,
499
+ "",
500
+ `### Critic (${critDecision.passed ? "PASS" : "FAIL"})`,
501
+ critDecision.reason,
502
+ ].join("\n");
503
+ if (revDecision.passed && critDecision.passed) {
504
+ gateVerdict = "PASS";
505
+ break;
506
+ }
507
+ openIssuesLedger.push(`- Gate Check #${attempt + 1}: Reviewer=${revDecision.passed ? "PASS" : "FAIL"} (${revDecision.reason}); Critic=${critDecision.passed ? "PASS" : "FAIL"} (${critDecision.reason})`);
508
+ gateVerdict = "FAIL";
509
+ if (attempt < clampedMaxQaRounds) {
510
+ qaRoundsExecuted++;
511
+ await onProgress?.(`Teamwork SWE: Gate found defects; running QA Fix Round #${qaRoundsExecuted}...`);
512
+ const qaRes = await runIsolatedWorker(sessionClient, sessionID, `Teamwork QA #${qaRoundsExecuted}`, buildTeamworkQaPrompt(task, currentReport, reviewerRes.text, criticRes.text, qaRoundsExecuted, contextBlocks, openIssuesLedger), modelOverride, signal);
513
+ childSessionIDs.push(qaRes.sessionID);
514
+ currentReport = qaRes.text;
515
+ }
516
+ }
517
+ await persist(mode, gateVerdict === "PASS" ? "completed" : "failed", [
518
+ { name: "implementer", status: "done" },
519
+ {
520
+ name: "qa_gate",
521
+ status: gateVerdict === "PASS" ? "done" : "failed",
522
+ summary: `${qaRoundsExecuted} QA round(s)`,
523
+ },
524
+ ]);
525
+ return {
526
+ runId,
527
+ mode,
528
+ qaRoundsExecuted,
529
+ childSessionIDs,
530
+ report: currentReport,
531
+ gateVerdict,
532
+ gateSummary,
533
+ };
534
+ }
535
+ catch (err) {
536
+ await persist(mode, "failed", [
537
+ {
538
+ name: "execution",
539
+ status: "failed",
540
+ summary: err instanceof Error ? err.message : String(err),
541
+ },
542
+ ]);
543
+ throw err;
544
+ }
545
+ }
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "opencode-orchestra",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Model-agnostic multi-agent orchestration (/boost, /teamwork, /swarm) plugin for OpenCode V2.",
5
+ "type": "module",
6
+ "files": [
7
+ "dist"
8
+ ],
9
+ "main": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js"
15
+ }
16
+ },
17
+ "scripts": {
18
+ "build": "tsc",
19
+ "typecheck": "tsc --noEmit",
20
+ "test": "bun test",
21
+ "prepublishOnly": "bun run typecheck && bun run build && bun test"
22
+ },
23
+ "dependencies": {
24
+ "@opencode/plugin": "^2.4.3"
25
+ },
26
+ "devDependencies": {
27
+ "@types/bun": "latest",
28
+ "typescript": "^5.8.0"
29
+ }
30
+ }