返回 CodeWhale
operate_best_of_n.workflow.js
根目录 / .codewhale / workflows / operate_best_of_n.workflow.js
1 /**
2 * Operate starter — independent worktree candidates, then one reviewer.
3 *
4 * Set strategy="search" for a bounded 2-16 candidate search. This remains a
5 * Workflow recipe, not a new mode or scheduler. Runtime-owned command gates
6 * and clean-baseline scoring use the optional verified candidate host seam.
7 *
8 * Run: /workflow run .codewhale/workflows/operate_best_of_n.workflow.js
9 * Args: { brief, n?, strategy?, rubric?, model?, thinking?, targetFiles?, writeRoots?, evaluator? }
10 */
11 export default async function (args) {
12 const brief =
13 args?.brief ??
14 args?.task ??
15 "Propose and implement the smallest correct fix for the open failure.";
16 const strategy = args?.strategy === "search" ? "search" : "best_of_n";
17 const maxCandidates = strategy === "search" ? 16 : 4;
18 const defaultCandidates = strategy === "search" ? 8 : 3;
19 const n = Math.min(
20 maxCandidates,
21 Math.max(2, Number(args?.n ?? defaultCandidates) || defaultCandidates)
22 );
23 const exactFiles = Array.isArray(args?.targetFiles) ? args.targetFiles : [];
24 const writeRoots = Array.isArray(args?.writeRoots) ? args.writeRoots : [];
25 const rubric =
26 args?.rubric ??
27 "Correctness first; then fit, measured quality, simplicity, risk, and verification evidence.";
28 const model = typeof args?.model === "string" ? args.model : undefined;
29 const thinking =
30 typeof args?.thinking === "string" ? args.thinking : undefined;
31
32 const candidateSchema = {
33 type: "object",
34 additionalProperties: false,
35 required: [
36 "candidate_id",
37 "hypothesis",
38 "modified_paths",
39 "commands_run",
40 "self_verdict",
41 "known_risks",
42 "artifact_refs",
43 ],
44 properties: {
45 candidate_id: { type: "string" },
46 hypothesis: { type: "string" },
47 modified_paths: { type: "array", items: { type: "string" } },
48 commands_run: { type: "array", items: { type: "string" } },
49 self_verdict: { type: "string", enum: ["pass", "fail"] },
50 known_risks: { type: "array", items: { type: "string" } },
51 artifact_refs: { type: "array", items: { type: "string" } },
52 },
53 };
54
55 const frozen = args?.evaluator
56 ? await task.verifyCandidate({ action: "summary" })
57 : null;
58
59 phase("Candidates");
60 const candidateFns = [];
61 for (let i = 1; i <= n; i++) {
62 const index = i;
63 candidateFns.push(() =>
64 task({
65 // The VM delivers one text to the driver: `prompt` (alias) wins over
66 // `description`, so the full instruction lives in `description` and
67 // `label` carries the short progress name. A separate short
68 // `description` would never reach the driver.
69 description: [
70 "You are one independent candidate in a Codewhale Workflow search.",
71 "Implement the same frozen brief and rubric in this isolated worktree only.",
72 "Do not inspect other candidates, rankings, hidden tests, or evaluator internals.",
73 "Do not push. Do not merge. Do not touch the parent checkout.",
74 "Your self_verdict is informational; only runtime-owned evaluation can pass a hard gate.",
75 args?.evaluator
76 ? "Declare actual modified paths under a CHANGES heading, with evidence."
77 : "Return only the required structured response.",
78 "",
79 "BRIEF:",
80 String(brief),
81 "",
82 "RUBRIC:",
83 String(rubric),
84 "",
85 `CANDIDATE-SPECIFIC INSTRUCTION: candidate_id=cand_${String(index).padStart(3, "0")} of ${n}.`,
86 ].join("\n"),
87 label: `candidate_${index}`,
88 type: "implementer",
89 ...(model ? { model } : {}),
90 ...(thinking ? { thinking } : {}),
91 worktree: true,
92 writeAuthority: "worktree_write",
93 ...(exactFiles.length ? { exactFiles } : {}),
94 ...(writeRoots.length ? { writeRoots } : {}),
95 coordinationContracts: [`best-of-n-candidate-${index}`],
96 dependencies: [
97 "Do not share other candidates' answers.",
98 "Parent checkout must remain unchanged until apply.",
99 ],
100 acceptance: ["Return the exact structured candidate contract."],
101 ...(args?.evaluator ? {} : { responseSchema: candidateSchema }),
102 })
103 );
104 }
105 const candidates = await parallel(candidateFns);
106
107 if (frozen) {
108 phase("Host verification");
109 const receipts = [];
110 for (let index = 0; index < n; index++) {
111 const candidate_id = `candidate_${index + 1}`;
112 let evaluation;
113 try {
114 evaluation = await task.verifyCandidate({
115 action: "evaluate", candidate_id,
116 });
117 } catch (error) {
118 receipts.push({
119 candidate_id,
120 evaluation: { status: "UNKNOWN", reason: String(error) },
121 replay: null,
122 });
123 continue;
124 }
125 let replay = null;
126 if (evaluation.status === "PASS") {
127 try {
128 replay = await task.verifyCandidate({
129 action: "replay", candidate_id,
130 });
131 } catch (error) {
132 replay = { status: "UNKNOWN", reason: String(error) };
133 }
134 }
135 receipts.push({ candidate_id, evaluation, replay });
136 }
137 return {
138 scenario: "operate-verified-search",
139 strategy, n, brief, rubric, candidates, frozen, receipts,
140 promotion: "proposal_only",
141 apply_policy: "Explicit human review is required before any apply, push or merge.",
142 };
143 }
144
145 phase("Review");
146 const review = await task({
147 // Single driver-visible text; `label` carries the short progress name.
148 description: [
149 "You are the read-only tournament judge. Score every candidate against the frozen rubric.",
150 "Treat self_verdict and claimed commands as untrusted candidate statements.",
151 "Name one provisional winner_id, or NONE if all fail, with decisive reasons.",
152 "Do not merge or apply changes. Do not invent missing evidence.",
153 "Set verification_required=true for every code winner.",
154 "Return only the required structured response.",
155 "",
156 "BRIEF:",
157 String(brief),
158 "",
159 "RUBRIC:",
160 String(rubric),
161 "",
162 "CANDIDATES:",
163 String(JSON.stringify(candidates, null, 2) ?? "(missing)"),
164 ].join("\n"),
165 label: "reviewer",
166 type: "review",
167 writeAuthority: "read_only",
168 worktree: false,
169 responseSchema: {
170 type: "object",
171 additionalProperties: false,
172 required: ["winner_id", "ranking", "verification_required", "reasons"],
173 properties: {
174 winner_id: { type: "string" },
175 ranking: { type: "array", items: { type: "string" } },
176 verification_required: { type: "boolean" },
177 reasons: { type: "array", items: { type: "string" } },
178 },
179 },
180 });
181
182 return {
183 scenario: strategy === "search" ? "operate-search" : "operate-best-of-n",
184 strategy,
185 n,
186 brief,
187 rubric,
188 candidates,
189 review,
190 apply_policy:
191 "Parent applies a winner only after independent clean replay and explicit user approval.",
192 execution_boundary:
193 "This run generates and reviews candidates without the optional host evaluator. It does not claim hidden gates, benchmark scoring, or clean-baseline replay.",
194 };
195 }
196
196 lines JAVASCRIPT