@oalo-ai/cli 0.5.1 → 0.7.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.
- package/README.md +45 -10
- package/man/oalo.1 +359 -16
- package/package.json +2 -2
- package/plugin/.claude-plugin/plugin.json +2 -2
- package/plugin/skills/oalo/SKILL.md +124 -30
- package/src/agents/harness.js +357 -0
- package/src/agents/roles.js +339 -0
- package/src/agents/worktree.js +155 -0
- package/src/commands/auto.js +239 -0
- package/src/commands/bots.js +2 -2
- package/src/commands/crm.js +114 -0
- package/src/commands/db.js +2 -1
- package/src/commands/heal.js +141 -0
- package/src/commands/inbox.js +127 -0
- package/src/commands/link.js +1 -1
- package/src/commands/race.js +390 -0
- package/src/commands/ralph.js +302 -0
- package/src/commands/review.js +233 -0
- package/src/commands/serve.js +1 -1
- package/src/commands/skill.js +15 -5
- package/src/commands/swarm.js +457 -0
- package/src/commands/switches.js +32 -1
- package/src/commands/usage.js +66 -0
- package/src/coord-release.json +9 -9
- package/src/help.js +225 -15
- package/src/index.js +36 -0
- package/src/mcp/describe.js +3 -2
- package/src/mcp/tools.js +84 -2
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Strategy 3: `oalo race` — Best-of-N competitive racing across isolated git
|
|
3
|
+
* worktrees. Zero decomposition tax: run 2-N models/harnesses on the exact same
|
|
4
|
+
* task in parallel, verify every attempt with the same command, compare
|
|
5
|
+
* pass/fail + diff size + cost, and merge the winner cleanly.
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { runAgent, parseHarnessList, parseHarnessSpec, detectDefaultHarness, extractJsonObject } from "../agents/harness.js";
|
|
10
|
+
import {
|
|
11
|
+
requireProjectRoot,
|
|
12
|
+
createWorktree,
|
|
13
|
+
removeWorktree,
|
|
14
|
+
commitAll,
|
|
15
|
+
diffSummary,
|
|
16
|
+
runShell,
|
|
17
|
+
tailLines,
|
|
18
|
+
git,
|
|
19
|
+
gitTry,
|
|
20
|
+
isClean,
|
|
21
|
+
currentBranch,
|
|
22
|
+
} from "../agents/worktree.js";
|
|
23
|
+
|
|
24
|
+
const USAGE = `usage:
|
|
25
|
+
oalo race "<goal>" --models <spec1,spec2,...> [--verify "<cmd>"] [--judge <spec>] [--budget <usd>] [--timeout <s>] [--base <ref>] [--json]
|
|
26
|
+
oalo race status [<run-id>] [--json]
|
|
27
|
+
oalo race pick <run-id> <slot> [--keep] [--json]
|
|
28
|
+
oalo race clean [<run-id>] [--json]
|
|
29
|
+
|
|
30
|
+
examples:
|
|
31
|
+
oalo race "Fix WebSocket reconnect" --models claude:sonnet,opencode:openrouter/deepseek/deepseek-v4.1-flash --verify "mix test" --judge claude:sonnet
|
|
32
|
+
oalo race pick race-abc123 1`;
|
|
33
|
+
|
|
34
|
+
function racesDir(root) {
|
|
35
|
+
return join(root, ".oalo", "races");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function loadRace(root, runId) {
|
|
39
|
+
const dir = racesDir(root);
|
|
40
|
+
if (!existsSync(dir)) throw new Error("no races found in this repo");
|
|
41
|
+
let id = runId;
|
|
42
|
+
if (!id) {
|
|
43
|
+
const files = readdirSync(dir)
|
|
44
|
+
.filter((f) => f.endsWith(".json"))
|
|
45
|
+
.sort()
|
|
46
|
+
.reverse();
|
|
47
|
+
if (!files.length) throw new Error("no races found in this repo");
|
|
48
|
+
id = files[0].replace(/\.json$/, "");
|
|
49
|
+
}
|
|
50
|
+
const p = join(dir, `${id}.json`);
|
|
51
|
+
if (!existsSync(p)) throw new Error(`race not found: ${id}`);
|
|
52
|
+
return { path: p, data: JSON.parse(readFileSync(p, "utf8")) };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function buildRacerPrompt({ goal, verifyCmd, slot, total, label }) {
|
|
56
|
+
return [
|
|
57
|
+
`# Competitive Race — Slot ${slot}/${total} (${label})`,
|
|
58
|
+
"",
|
|
59
|
+
"You are working in an isolated git worktree competing to deliver the cleanest, most correct solution.",
|
|
60
|
+
"",
|
|
61
|
+
"## Goal",
|
|
62
|
+
goal,
|
|
63
|
+
verifyCmd ? `\n## Verifier\nYour solution will be graded automatically by running:\n\`${verifyCmd}\`\nMake sure it passes before you finish.` : "",
|
|
64
|
+
"",
|
|
65
|
+
"## Rules",
|
|
66
|
+
"- Keep changes focused, minimal, and well-tested.",
|
|
67
|
+
"- Commit your changes (or leave them ready in this worktree).",
|
|
68
|
+
]
|
|
69
|
+
.filter(Boolean)
|
|
70
|
+
.join("\n");
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const MAX_CANDIDATE_DIFF = 30_000;
|
|
74
|
+
|
|
75
|
+
function buildJudgePrompt({ goal, verifyCmd, candidates }) {
|
|
76
|
+
const lines = [
|
|
77
|
+
"# Blind Race Judge",
|
|
78
|
+
"",
|
|
79
|
+
"Multiple independent candidates ALL passed the verifier for the same engineering goal.",
|
|
80
|
+
"Candidate identities and model names are hidden to prevent bias. Compare ONLY the diffs below.",
|
|
81
|
+
"Do NOT modify any files.",
|
|
82
|
+
"",
|
|
83
|
+
"## Goal",
|
|
84
|
+
goal,
|
|
85
|
+
verifyCmd ? `\n## Verifier (all candidates passed)\n\`${verifyCmd}\`` : "",
|
|
86
|
+
"",
|
|
87
|
+
"## Candidates",
|
|
88
|
+
];
|
|
89
|
+
for (const c of candidates) {
|
|
90
|
+
const clipped = c.diff.length > MAX_CANDIDATE_DIFF ? `${c.diff.slice(0, MAX_CANDIDATE_DIFF)}\n... [diff truncated]` : c.diff;
|
|
91
|
+
lines.push(
|
|
92
|
+
`\n### Candidate ${c.alias} (${c.diffstat})`,
|
|
93
|
+
"```diff",
|
|
94
|
+
clipped || "(empty diff)",
|
|
95
|
+
"```",
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
lines.push(
|
|
99
|
+
"",
|
|
100
|
+
"## Output Format (STRICT JSON ONLY)",
|
|
101
|
+
"Choose the single best candidate based on correctness, edge-case safety, clarity, and minimal surface area.",
|
|
102
|
+
"Return ONLY this JSON object:",
|
|
103
|
+
"```json",
|
|
104
|
+
JSON.stringify(
|
|
105
|
+
{
|
|
106
|
+
winner: "A",
|
|
107
|
+
ranking: ["A", "B"],
|
|
108
|
+
rationale: "1-3 sentences explaining why the winner is cleanest/safest.",
|
|
109
|
+
},
|
|
110
|
+
null,
|
|
111
|
+
2,
|
|
112
|
+
),
|
|
113
|
+
"```",
|
|
114
|
+
);
|
|
115
|
+
return lines.join("\n");
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function runBlindJudge({ root, judgeSpec, goal, verifyCmd, passing, timeoutMs, log }) {
|
|
119
|
+
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
120
|
+
const aliasToSlot = new Map();
|
|
121
|
+
const candidates = passing.map((r, i) => {
|
|
122
|
+
const alias = letters[i] || String(i + 1);
|
|
123
|
+
aliasToSlot.set(alias, r.slot);
|
|
124
|
+
const diff = gitTry(r.worktree, ["diff", `${r.base_sha}...HEAD`]).stdout;
|
|
125
|
+
return { alias, slot: r.slot, diffstat: r.diffstat, diff };
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
const spec = parseHarnessSpec(judgeSpec);
|
|
129
|
+
log(`running blind judge (${spec.label}) across ${candidates.length} passing candidates`);
|
|
130
|
+
const res = await runAgent({
|
|
131
|
+
harness: spec,
|
|
132
|
+
prompt: buildJudgePrompt({ goal, verifyCmd, candidates }),
|
|
133
|
+
cwd: root,
|
|
134
|
+
readonly: true,
|
|
135
|
+
timeoutMs,
|
|
136
|
+
env: {
|
|
137
|
+
OALO_RACE_JUDGE: "1",
|
|
138
|
+
OALO_RACE_CANDIDATES: String(candidates.length),
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
const obj = extractJsonObject(res.text);
|
|
143
|
+
const rawWinner = String(obj?.winner || "").trim().toUpperCase().replace(/^CANDIDATE\s+/i, "");
|
|
144
|
+
const winnerSlot = aliasToSlot.get(rawWinner) ?? null;
|
|
145
|
+
const ranking = Array.isArray(obj?.ranking)
|
|
146
|
+
? obj.ranking
|
|
147
|
+
.map((a) => aliasToSlot.get(String(a).trim().toUpperCase().replace(/^CANDIDATE\s+/i, "")))
|
|
148
|
+
.filter((s) => s != null)
|
|
149
|
+
: [];
|
|
150
|
+
|
|
151
|
+
return {
|
|
152
|
+
harness: spec.label,
|
|
153
|
+
ok: res.ok && winnerSlot != null,
|
|
154
|
+
winner_slot: winnerSlot,
|
|
155
|
+
ranking,
|
|
156
|
+
rationale: String(obj?.rationale || res.text || res.stderr || "").trim().slice(0, 600),
|
|
157
|
+
cost_usd: Number((res.costUsd || 0).toFixed(6)),
|
|
158
|
+
duration_ms: res.durationMs,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export async function runRace(opts) {
|
|
163
|
+
const goal = String(opts.goal || "").trim();
|
|
164
|
+
if (!goal) throw new Error("race requires a goal description");
|
|
165
|
+
|
|
166
|
+
const specs = parseHarnessList(opts.models);
|
|
167
|
+
if (!specs.length) {
|
|
168
|
+
const def = detectDefaultHarness();
|
|
169
|
+
specs.push(...parseHarnessList(`${def},${def}`));
|
|
170
|
+
}
|
|
171
|
+
const verifyCmd = opts.verify ? String(opts.verify).trim() : null;
|
|
172
|
+
const timeoutMs = Math.max(5, Number(opts.timeoutS || 600)) * 1000;
|
|
173
|
+
const perRacerBudget = opts.budgetUsd != null ? Number(opts.budgetUsd) / specs.length : null;
|
|
174
|
+
const baseRef = opts.base || "HEAD";
|
|
175
|
+
const quiet = !!opts.quiet;
|
|
176
|
+
|
|
177
|
+
const cwd = opts.cwd || process.cwd();
|
|
178
|
+
const root = opts.root || requireProjectRoot(cwd);
|
|
179
|
+
const runId = `race-${Date.now().toString(36)}`;
|
|
180
|
+
mkdirSync(racesDir(root), { recursive: true });
|
|
181
|
+
|
|
182
|
+
const log = (msg) => {
|
|
183
|
+
if (!quiet) console.error(`[race] ${msg}`);
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
log(`starting ${runId} with ${specs.length} racer(s) from ${baseRef}`);
|
|
187
|
+
const startedAt = Date.now();
|
|
188
|
+
|
|
189
|
+
const racers = await Promise.all(
|
|
190
|
+
specs.map(async (spec, idx) => {
|
|
191
|
+
const slot = idx + 1;
|
|
192
|
+
const wt = createWorktree({ root, namespace: runId, name: `slot-${slot}`, baseRef });
|
|
193
|
+
log(`slot ${slot} (${spec.label}) -> ${wt.path}`);
|
|
194
|
+
const res = await runAgent({
|
|
195
|
+
harness: spec,
|
|
196
|
+
prompt: buildRacerPrompt({ goal, verifyCmd, slot, total: specs.length, label: spec.label }),
|
|
197
|
+
cwd: wt.path,
|
|
198
|
+
readonly: false,
|
|
199
|
+
maxBudgetUsd: perRacerBudget,
|
|
200
|
+
timeoutMs,
|
|
201
|
+
env: {
|
|
202
|
+
OALO_RACE_RUN_ID: runId,
|
|
203
|
+
OALO_RACE_SLOT: String(slot),
|
|
204
|
+
OALO_RACE_GOAL: goal,
|
|
205
|
+
OALO_RACE_VERIFY: verifyCmd || "",
|
|
206
|
+
},
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
// Snapshot any uncommitted edits so every slot is cleanly inspectable and mergeable.
|
|
210
|
+
commitAll(wt.path, `race ${runId} slot ${slot} (${spec.label})`);
|
|
211
|
+
|
|
212
|
+
let verify = null;
|
|
213
|
+
if (verifyCmd) {
|
|
214
|
+
verify = await runShell(verifyCmd, { cwd: wt.path, timeoutMs });
|
|
215
|
+
}
|
|
216
|
+
const diff = diffSummary(wt.path, wt.baseSha, "HEAD");
|
|
217
|
+
|
|
218
|
+
const score = {
|
|
219
|
+
slot,
|
|
220
|
+
label: spec.label,
|
|
221
|
+
harness: spec.harness,
|
|
222
|
+
model: spec.model,
|
|
223
|
+
branch: wt.branch,
|
|
224
|
+
worktree: wt.path,
|
|
225
|
+
base_sha: wt.baseSha,
|
|
226
|
+
agent_ok: res.ok,
|
|
227
|
+
verify_ok: verify ? verify.ok : null,
|
|
228
|
+
verify_status: verify ? verify.status : null,
|
|
229
|
+
verify_tail: verify && !verify.ok ? tailLines(verify.output, 25) : null,
|
|
230
|
+
commits: diff.commits.length,
|
|
231
|
+
files_changed: diff.files.length,
|
|
232
|
+
files: diff.files,
|
|
233
|
+
diffstat: diff.stat || "no changes",
|
|
234
|
+
cost_usd: Number((res.costUsd || 0).toFixed(6)),
|
|
235
|
+
duration_ms: res.durationMs + (verify?.durationMs || 0),
|
|
236
|
+
summary: (res.text || "").trim().slice(0, 400),
|
|
237
|
+
};
|
|
238
|
+
log(`slot ${slot} (${spec.label}) done: verify=${score.verify_ok === null ? "n/a" : score.verify_ok ? "PASS" : "FAIL"} (${score.diffstat}, $${score.cost_usd.toFixed(4)})`);
|
|
239
|
+
return score;
|
|
240
|
+
}),
|
|
241
|
+
);
|
|
242
|
+
|
|
243
|
+
// Recommend best passing racer (lowest cost, then fewest changed files).
|
|
244
|
+
// If --judge is set and 2+ racers pass, run a blind LLM judge over anonymized diffs.
|
|
245
|
+
const passing = racers.filter((r) => (verifyCmd ? r.verify_ok === true : r.agent_ok) && r.commits > 0);
|
|
246
|
+
passing.sort((a, b) => a.cost_usd - b.cost_usd || a.files_changed - b.files_changed || a.duration_ms - b.duration_ms);
|
|
247
|
+
let recommended = passing[0]?.slot ?? null;
|
|
248
|
+
let judge = null;
|
|
249
|
+
|
|
250
|
+
if (opts.judge && passing.length >= 2) {
|
|
251
|
+
judge = await runBlindJudge({ root, judgeSpec: opts.judge, goal, verifyCmd, passing, timeoutMs, log });
|
|
252
|
+
if (judge.winner_slot != null) {
|
|
253
|
+
recommended = judge.winner_slot;
|
|
254
|
+
log(`blind judge (${judge.harness}) picked slot ${recommended}: ${judge.rationale}`);
|
|
255
|
+
} else {
|
|
256
|
+
log(`blind judge (${judge.harness}) returned no valid winner; falling back to deterministic tie-break (slot ${recommended})`);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const record = {
|
|
261
|
+
run_id: runId,
|
|
262
|
+
goal,
|
|
263
|
+
verify: verifyCmd,
|
|
264
|
+
base_ref: baseRef,
|
|
265
|
+
created_at: new Date().toISOString(),
|
|
266
|
+
duration_ms: Date.now() - startedAt,
|
|
267
|
+
picked_slot: null,
|
|
268
|
+
recommended_slot: recommended,
|
|
269
|
+
judge,
|
|
270
|
+
racers,
|
|
271
|
+
};
|
|
272
|
+
writeFileSync(join(racesDir(root), `${runId}.json`), JSON.stringify(record, null, 2) + "\n");
|
|
273
|
+
return record;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
export function pickRace({ root, runId, slot, keep = false }) {
|
|
277
|
+
const { path: recordPath, data } = loadRace(root, runId);
|
|
278
|
+
const slotNum = Number(slot);
|
|
279
|
+
const winner = (data.racers || []).find((r) => r.slot === slotNum);
|
|
280
|
+
if (!winner) throw new Error(`slot ${slot} not found in ${data.run_id}`);
|
|
281
|
+
if (!isClean(root)) {
|
|
282
|
+
throw new Error("working tree has uncommitted changes; commit or stash them before `oalo race pick`");
|
|
283
|
+
}
|
|
284
|
+
const targetBranch = currentBranch(root) || "HEAD";
|
|
285
|
+
const m = gitTry(root, ["merge", "--no-ff", "--no-edit", "-m", `oalo race: merge ${data.run_id} slot ${slotNum} (${winner.label})`, winner.branch], {
|
|
286
|
+
GIT_AUTHOR_NAME: process.env.GIT_AUTHOR_NAME || "oalo race",
|
|
287
|
+
GIT_AUTHOR_EMAIL: process.env.GIT_AUTHOR_EMAIL || "race@oalo.local",
|
|
288
|
+
GIT_COMMITTER_NAME: process.env.GIT_COMMITTER_NAME || "oalo race",
|
|
289
|
+
GIT_COMMITTER_EMAIL: process.env.GIT_COMMITTER_EMAIL || "race@oalo.local",
|
|
290
|
+
});
|
|
291
|
+
if (!m.ok) {
|
|
292
|
+
gitTry(root, ["merge", "--abort"]);
|
|
293
|
+
throw new Error(`merge conflict merging ${winner.branch} into ${targetBranch}:\n${m.stderr || m.stdout}`);
|
|
294
|
+
}
|
|
295
|
+
const mergeCommit = git(root, ["rev-parse", "HEAD"]);
|
|
296
|
+
|
|
297
|
+
if (!keep) {
|
|
298
|
+
for (const r of data.racers) {
|
|
299
|
+
removeWorktree({ root, path: r.worktree, branch: r.branch, deleteBranch: true });
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
data.picked_slot = slotNum;
|
|
303
|
+
data.merge_commit = mergeCommit;
|
|
304
|
+
data.cleaned = !keep;
|
|
305
|
+
writeFileSync(recordPath, JSON.stringify(data, null, 2) + "\n");
|
|
306
|
+
return { run_id: data.run_id, picked_slot: slotNum, label: winner.label, target_branch: targetBranch, merge_commit: mergeCommit, cleaned: !keep };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export function cleanRace({ root, runId = null }) {
|
|
310
|
+
const { path: recordPath, data } = loadRace(root, runId);
|
|
311
|
+
for (const r of data.racers || []) {
|
|
312
|
+
removeWorktree({ root, path: r.worktree, branch: r.branch, deleteBranch: true });
|
|
313
|
+
}
|
|
314
|
+
rmSync(recordPath, { force: true });
|
|
315
|
+
return { cleaned: data.run_id, slots_removed: (data.racers || []).length };
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function printScoreboard(rec) {
|
|
319
|
+
console.log(`\nRace ${rec.run_id}: ${rec.goal}`);
|
|
320
|
+
if (rec.verify) console.log(`Verifier: ${rec.verify}`);
|
|
321
|
+
console.log("");
|
|
322
|
+
console.log("SLOT HARNESS VERIFY FILES COST TIME DIFFSTAT");
|
|
323
|
+
for (const r of rec.racers) {
|
|
324
|
+
const v = r.verify_ok === null ? "n/a " : r.verify_ok ? "PASS " : "FAIL ";
|
|
325
|
+
const star = rec.recommended_slot === r.slot ? "*" : " ";
|
|
326
|
+
console.log(
|
|
327
|
+
`${star}${String(r.slot).padEnd(4)} ${String(r.label).slice(0, 30).padEnd(31)} ${v} ${String(r.files_changed).padEnd(6)} $${r.cost_usd.toFixed(3).padEnd(7)} ${(r.duration_ms / 1000).toFixed(1).padEnd(6)}s ${r.diffstat}`,
|
|
328
|
+
);
|
|
329
|
+
}
|
|
330
|
+
if (rec.judge) {
|
|
331
|
+
console.log(`\nBlind Judge (${rec.judge.harness}, $${rec.judge.cost_usd.toFixed(4)}): ${rec.judge.rationale}`);
|
|
332
|
+
}
|
|
333
|
+
if (rec.recommended_slot) {
|
|
334
|
+
console.log(`\nRecommended: slot ${rec.recommended_slot} -> oalo race pick ${rec.run_id} ${rec.recommended_slot}`);
|
|
335
|
+
} else {
|
|
336
|
+
console.log(`\nNo passing slot with commits. Inspect worktrees or clean up with: oalo race clean ${rec.run_id}`);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
export async function race(flags, rest) {
|
|
341
|
+
const sub = rest[1];
|
|
342
|
+
if (flags.help || !sub || sub === "help") {
|
|
343
|
+
console.log(USAGE);
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
const root = requireProjectRoot(process.cwd());
|
|
347
|
+
|
|
348
|
+
if (sub === "status") {
|
|
349
|
+
const { data } = loadRace(root, rest[2] || null);
|
|
350
|
+
if (flags.json) console.log(JSON.stringify(data, null, 2));
|
|
351
|
+
else printScoreboard(data);
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
if (sub === "pick") {
|
|
355
|
+
const runId = rest[2];
|
|
356
|
+
const slot = rest[3];
|
|
357
|
+
if (!runId || !slot) {
|
|
358
|
+
console.error("usage: oalo race pick <run-id> <slot> [--keep]");
|
|
359
|
+
process.exit(2);
|
|
360
|
+
}
|
|
361
|
+
const res = pickRace({ root, runId, slot, keep: !!flags.keep });
|
|
362
|
+
if (flags.json) console.log(JSON.stringify(res, null, 2));
|
|
363
|
+
else console.log(`merged ${res.run_id} slot ${res.picked_slot} (${res.label}) into ${res.target_branch} at ${res.merge_commit.slice(0, 10)}`);
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
if (sub === "clean") {
|
|
367
|
+
const res = cleanRace({ root, runId: rest[2] || null });
|
|
368
|
+
if (flags.json) console.log(JSON.stringify(res, null, 2));
|
|
369
|
+
else console.log(`cleaned ${res.cleaned} (${res.slots_removed} worktree(s) removed)`);
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const goal = typeof flags.goal === "string" ? flags.goal : rest.slice(1).join(" ").trim();
|
|
374
|
+
const rec = await runRace({
|
|
375
|
+
root,
|
|
376
|
+
goal,
|
|
377
|
+
models: typeof flags.models === "string" ? flags.models : typeof flags.harness === "string" ? flags.harness : null,
|
|
378
|
+
verify: typeof flags.verify === "string" ? flags.verify : null,
|
|
379
|
+
judge: typeof flags.judge === "string" ? flags.judge : null,
|
|
380
|
+
budgetUsd: flags.budget ? Number(flags.budget) : null,
|
|
381
|
+
timeoutS: flags.timeout ? Number(flags.timeout) : 600,
|
|
382
|
+
base: typeof flags.base === "string" ? flags.base : "HEAD",
|
|
383
|
+
quiet: !!flags.json,
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
if (flags.json) console.log(JSON.stringify(rec, null, 2));
|
|
387
|
+
else printScoreboard(rec);
|
|
388
|
+
|
|
389
|
+
if (rec.verify && !rec.recommended_slot) process.exit(1);
|
|
390
|
+
}
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Strategy 2: `oalo ralph` — Fresh-context iterative grind against a disk
|
|
3
|
+
* ledger and a deterministic machine verifier (`npm test`, `mix test`,
|
|
4
|
+
* `oalo qa bot_xxx --script ...`).
|
|
5
|
+
*
|
|
6
|
+
* Each iteration starts a brand-new agent process (zero context bloat), reads
|
|
7
|
+
* the current disk state + failing verifier output, makes one focused change,
|
|
8
|
+
* re-verifies, and exits cleanly once green or when iteration/cost limits hit.
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { join, resolve } from "node:path";
|
|
12
|
+
import { runAgent, parseHarnessSpec, detectDefaultHarness } from "../agents/harness.js";
|
|
13
|
+
import {
|
|
14
|
+
requireProjectRoot,
|
|
15
|
+
createWorktree,
|
|
16
|
+
removeWorktree,
|
|
17
|
+
commitAll,
|
|
18
|
+
runShell,
|
|
19
|
+
tailLines,
|
|
20
|
+
gitTry,
|
|
21
|
+
} from "../agents/worktree.js";
|
|
22
|
+
|
|
23
|
+
const USAGE = `usage:
|
|
24
|
+
oalo ralph --goal "<text>" --verify "<cmd>" [options]
|
|
25
|
+
|
|
26
|
+
options:
|
|
27
|
+
--goal <text> What the loop should achieve (or pass as first positional arg)
|
|
28
|
+
--verify <cmd> Machine verifier command (e.g. "npm test", "oalo qa bot_x --script qa.json")
|
|
29
|
+
--plan <file> Optional markdown checklist (loop continues until no \`- [ ]\` items remain)
|
|
30
|
+
--harness <spec> Agent harness: claude[:model], opencode[:model], codex[:model], cmd:<shell>
|
|
31
|
+
--max-iters <n> Maximum fresh-context iterations (default: 10)
|
|
32
|
+
--max-cost <usd> Maximum total USD spend across iterations (default: 5.00)
|
|
33
|
+
--timeout <s> Per-iteration timeout in seconds (default: 600)
|
|
34
|
+
--commit Auto-commit changes after each passing or progressing iteration
|
|
35
|
+
--worktree Run inside an isolated git worktree instead of the current checkout
|
|
36
|
+
--json Print structured JSON summary`;
|
|
37
|
+
|
|
38
|
+
function uncheckedItems(planPath) {
|
|
39
|
+
if (!planPath || !existsSync(planPath)) return [];
|
|
40
|
+
return readFileSync(planPath, "utf8")
|
|
41
|
+
.split("\n")
|
|
42
|
+
.filter((l) => /^\s*-\s*\[\s\]\s+/.test(l))
|
|
43
|
+
.map((l) => l.replace(/^\s*-\s*\[\s\]\s+/, "").trim());
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function buildIterationPrompt({ goal, verifyCmd, iteration, maxIters, planFile, remainingItems, progressMd, verifyOutput, recentCommits }) {
|
|
47
|
+
const sections = [
|
|
48
|
+
`# Ralph Loop — Iteration ${iteration} of ${maxIters}`,
|
|
49
|
+
"",
|
|
50
|
+
"You are a fresh-context agent executing ONE focused iteration of an iterative engineering loop.",
|
|
51
|
+
"State lives on disk (git + files + progress log), not in chat history.",
|
|
52
|
+
"",
|
|
53
|
+
`## Goal`,
|
|
54
|
+
goal,
|
|
55
|
+
"",
|
|
56
|
+
`## Machine Verifier`,
|
|
57
|
+
`Command: \`${verifyCmd}\``,
|
|
58
|
+
"",
|
|
59
|
+
"### Latest Verifier Output",
|
|
60
|
+
"```",
|
|
61
|
+
verifyOutput || "(not yet run)",
|
|
62
|
+
"```",
|
|
63
|
+
];
|
|
64
|
+
if (planFile && remainingItems.length) {
|
|
65
|
+
sections.push(
|
|
66
|
+
"",
|
|
67
|
+
`## Plan Checklist (${planFile})`,
|
|
68
|
+
`Remaining unchecked items (${remainingItems.length}):`,
|
|
69
|
+
...remainingItems.slice(0, 10).map((it) => `- [ ] ${it}`),
|
|
70
|
+
"Check off (`- [x]`) only items that are completely done and verified.",
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
if (recentCommits) {
|
|
74
|
+
sections.push("", "## Recent Git Commits", "```", recentCommits, "```");
|
|
75
|
+
}
|
|
76
|
+
if (progressMd) {
|
|
77
|
+
sections.push("", "## Prior Iterations (progress.md)", progressMd.slice(-4000));
|
|
78
|
+
}
|
|
79
|
+
sections.push(
|
|
80
|
+
"",
|
|
81
|
+
"## Instructions",
|
|
82
|
+
"1. Fix the highest-impact failing check or complete the next unchecked plan item.",
|
|
83
|
+
"2. Run the verifier yourself if helpful, and keep changes minimal and clean.",
|
|
84
|
+
"3. Exit with a concise summary of what you changed and what remains.",
|
|
85
|
+
);
|
|
86
|
+
return sections.join("\n");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function runRalph(opts) {
|
|
90
|
+
const goal = String(opts.goal || "").trim();
|
|
91
|
+
const verifyCmd = String(opts.verify || "").trim();
|
|
92
|
+
if (!goal) throw new Error("ralph requires --goal <text>");
|
|
93
|
+
if (!verifyCmd) throw new Error("ralph requires --verify <cmd>");
|
|
94
|
+
|
|
95
|
+
const maxIters = Math.max(1, Number(opts.maxIters || 10));
|
|
96
|
+
const maxCost = opts.maxCost != null && Number.isFinite(Number(opts.maxCost)) ? Number(opts.maxCost) : 5.0;
|
|
97
|
+
const timeoutMs = Math.max(5, Number(opts.timeoutS || 600)) * 1000;
|
|
98
|
+
const harness = parseHarnessSpec(opts.harness || detectDefaultHarness());
|
|
99
|
+
const doCommit = !!opts.commit;
|
|
100
|
+
const useWorktree = !!opts.worktree;
|
|
101
|
+
const quiet = !!opts.quiet;
|
|
102
|
+
|
|
103
|
+
const cwd = opts.cwd || process.cwd();
|
|
104
|
+
const root = opts.root || requireProjectRoot(cwd);
|
|
105
|
+
const runId = `ralph-${Date.now().toString(36)}`;
|
|
106
|
+
const stateDir = join(root, ".oalo", "ralph", runId);
|
|
107
|
+
mkdirSync(stateDir, { recursive: true });
|
|
108
|
+
const progressPath = join(stateDir, "progress.md");
|
|
109
|
+
const statePath = join(stateDir, "state.json");
|
|
110
|
+
|
|
111
|
+
let workDir = cwd;
|
|
112
|
+
let wt = null;
|
|
113
|
+
if (useWorktree) {
|
|
114
|
+
wt = createWorktree({ root, namespace: "ralph", name: runId });
|
|
115
|
+
workDir = wt.path;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const planPath = opts.plan ? resolve(workDir, opts.plan) : null;
|
|
119
|
+
const log = (msg) => {
|
|
120
|
+
if (!quiet) console.error(`[ralph] ${msg}`);
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const startedAt = Date.now();
|
|
124
|
+
const iterations = [];
|
|
125
|
+
let totalCostUsd = 0;
|
|
126
|
+
|
|
127
|
+
const saveState = (status) => {
|
|
128
|
+
writeFileSync(
|
|
129
|
+
statePath,
|
|
130
|
+
JSON.stringify(
|
|
131
|
+
{
|
|
132
|
+
run_id: runId,
|
|
133
|
+
status,
|
|
134
|
+
goal,
|
|
135
|
+
verify: verifyCmd,
|
|
136
|
+
harness: harness.label,
|
|
137
|
+
work_dir: workDir,
|
|
138
|
+
branch: wt?.branch || null,
|
|
139
|
+
total_cost_usd: Number(totalCostUsd.toFixed(6)),
|
|
140
|
+
duration_ms: Date.now() - startedAt,
|
|
141
|
+
iterations,
|
|
142
|
+
},
|
|
143
|
+
null,
|
|
144
|
+
2,
|
|
145
|
+
) + "\n",
|
|
146
|
+
);
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
// Pre-flight verify: if already green and no remaining plan items, stop immediately at $0.
|
|
150
|
+
let lastVerify = await runShell(verifyCmd, { cwd: workDir, timeoutMs });
|
|
151
|
+
let remaining = uncheckedItems(planPath);
|
|
152
|
+
if (lastVerify.ok && remaining.length === 0) {
|
|
153
|
+
log("verifier already passing with 0 remaining plan items — nothing to do");
|
|
154
|
+
saveState("passed");
|
|
155
|
+
return {
|
|
156
|
+
run_id: runId,
|
|
157
|
+
status: "passed",
|
|
158
|
+
already_passing: true,
|
|
159
|
+
iterations: [],
|
|
160
|
+
total_cost_usd: 0,
|
|
161
|
+
duration_ms: Date.now() - startedAt,
|
|
162
|
+
work_dir: workDir,
|
|
163
|
+
branch: wt?.branch || null,
|
|
164
|
+
state_dir: stateDir,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
writeFileSync(progressPath, `# Ralph Progress (${runId})\n\nGoal: ${goal}\nVerifier: \`${verifyCmd}\`\n\n`);
|
|
169
|
+
|
|
170
|
+
let finalStatus = "max_iters_reached";
|
|
171
|
+
|
|
172
|
+
for (let i = 1; i <= maxIters; i++) {
|
|
173
|
+
if (totalCostUsd >= maxCost) {
|
|
174
|
+
finalStatus = "budget_exceeded";
|
|
175
|
+
log(`budget cap $${maxCost.toFixed(2)} reached (spent $${totalCostUsd.toFixed(4)})`);
|
|
176
|
+
break;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
log(`iteration ${i}/${maxIters} -> ${harness.label}`);
|
|
180
|
+
const recentCommits = gitTry(workDir, ["log", "--format=%h %s", "-n8"]).stdout;
|
|
181
|
+
const progressMd = existsSync(progressPath) ? readFileSync(progressPath, "utf8") : "";
|
|
182
|
+
const prompt = buildIterationPrompt({
|
|
183
|
+
goal,
|
|
184
|
+
verifyCmd,
|
|
185
|
+
iteration: i,
|
|
186
|
+
maxIters,
|
|
187
|
+
planFile: opts.plan || null,
|
|
188
|
+
remainingItems: remaining,
|
|
189
|
+
progressMd,
|
|
190
|
+
verifyOutput: tailLines(lastVerify.output, 80),
|
|
191
|
+
recentCommits,
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
const agent = await runAgent({
|
|
195
|
+
harness,
|
|
196
|
+
prompt,
|
|
197
|
+
cwd: workDir,
|
|
198
|
+
readonly: false,
|
|
199
|
+
maxBudgetUsd: Math.max(0.01, maxCost - totalCostUsd),
|
|
200
|
+
timeoutMs,
|
|
201
|
+
env: {
|
|
202
|
+
OALO_RALPH_RUN_ID: runId,
|
|
203
|
+
OALO_RALPH_ITERATION: String(i),
|
|
204
|
+
OALO_RALPH_GOAL: goal,
|
|
205
|
+
OALO_RALPH_VERIFY: verifyCmd,
|
|
206
|
+
OALO_RALPH_PROGRESS_FILE: progressPath,
|
|
207
|
+
},
|
|
208
|
+
});
|
|
209
|
+
totalCostUsd += agent.costUsd || 0;
|
|
210
|
+
|
|
211
|
+
lastVerify = await runShell(verifyCmd, { cwd: workDir, timeoutMs });
|
|
212
|
+
remaining = uncheckedItems(planPath);
|
|
213
|
+
|
|
214
|
+
let commitSha = null;
|
|
215
|
+
if (doCommit && lastVerify.ok) {
|
|
216
|
+
commitSha = commitAll(workDir, `ralph: iteration ${i} (${goal.slice(0, 50)})`);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const entry = {
|
|
220
|
+
iteration: i,
|
|
221
|
+
agent_ok: agent.ok,
|
|
222
|
+
verify_ok: lastVerify.ok,
|
|
223
|
+
verify_status: lastVerify.status,
|
|
224
|
+
remaining_plan_items: remaining.length,
|
|
225
|
+
cost_usd: Number((agent.costUsd || 0).toFixed(6)),
|
|
226
|
+
duration_ms: agent.durationMs + lastVerify.durationMs,
|
|
227
|
+
commit: commitSha,
|
|
228
|
+
summary: (agent.text || "").trim().slice(0, 500),
|
|
229
|
+
};
|
|
230
|
+
iterations.push(entry);
|
|
231
|
+
|
|
232
|
+
const logBlock = [
|
|
233
|
+
`## Iteration ${i} — verify=${lastVerify.ok ? "PASS" : `FAIL(${lastVerify.status})`} cost=$${entry.cost_usd.toFixed(4)}`,
|
|
234
|
+
commitSha ? `Commit: ${commitSha.slice(0, 10)}` : null,
|
|
235
|
+
entry.summary ? `Summary: ${entry.summary}` : null,
|
|
236
|
+
!lastVerify.ok ? `Verifier tail:\n\`\`\`\n${tailLines(lastVerify.output, 25)}\n\`\`\`` : null,
|
|
237
|
+
"",
|
|
238
|
+
]
|
|
239
|
+
.filter(Boolean)
|
|
240
|
+
.join("\n");
|
|
241
|
+
writeFileSync(progressPath, readFileSync(progressPath, "utf8") + logBlock + "\n");
|
|
242
|
+
saveState(lastVerify.ok && remaining.length === 0 ? "passed" : "running");
|
|
243
|
+
|
|
244
|
+
log(`iteration ${i}: verify=${lastVerify.ok ? "PASS" : "FAIL"} remaining_plan=${remaining.length} cost=$${entry.cost_usd.toFixed(4)}`);
|
|
245
|
+
|
|
246
|
+
if (lastVerify.ok && remaining.length === 0) {
|
|
247
|
+
finalStatus = "passed";
|
|
248
|
+
break;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
saveState(finalStatus);
|
|
253
|
+
return {
|
|
254
|
+
run_id: runId,
|
|
255
|
+
status: finalStatus,
|
|
256
|
+
iterations,
|
|
257
|
+
total_cost_usd: Number(totalCostUsd.toFixed(6)),
|
|
258
|
+
duration_ms: Date.now() - startedAt,
|
|
259
|
+
work_dir: workDir,
|
|
260
|
+
branch: wt?.branch || null,
|
|
261
|
+
state_dir: stateDir,
|
|
262
|
+
cleanupWorktree: wt ? () => removeWorktree({ root, path: wt.path, branch: wt.branch }) : null,
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export async function ralph(flags, rest) {
|
|
267
|
+
if (flags.help || rest[1] === "help") {
|
|
268
|
+
console.log(USAGE);
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
const goal = typeof flags.goal === "string" ? flags.goal : rest.slice(1).join(" ").trim();
|
|
272
|
+
const verify = typeof flags.verify === "string" ? flags.verify : "";
|
|
273
|
+
if (!goal || !verify) {
|
|
274
|
+
console.error("oalo ralph requires --goal <text> and --verify <cmd>\n\n" + USAGE);
|
|
275
|
+
process.exit(2);
|
|
276
|
+
}
|
|
277
|
+
const result = await runRalph({
|
|
278
|
+
goal,
|
|
279
|
+
verify,
|
|
280
|
+
plan: typeof flags.plan === "string" ? flags.plan : null,
|
|
281
|
+
harness: typeof flags.harness === "string" ? flags.harness : null,
|
|
282
|
+
maxIters: flags["max-iters"] ? Number(flags["max-iters"]) : 10,
|
|
283
|
+
maxCost: flags["max-cost"] ? Number(flags["max-cost"]) : 5.0,
|
|
284
|
+
timeoutS: flags.timeout ? Number(flags.timeout) : 600,
|
|
285
|
+
commit: !!flags.commit,
|
|
286
|
+
worktree: !!flags.worktree,
|
|
287
|
+
quiet: !!flags.json,
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
const out = { ...result };
|
|
291
|
+
delete out.cleanupWorktree;
|
|
292
|
+
|
|
293
|
+
if (flags.json) {
|
|
294
|
+
console.log(JSON.stringify(out, null, 2));
|
|
295
|
+
} else {
|
|
296
|
+
console.log(`\nRalph ${out.run_id}: ${out.status}`);
|
|
297
|
+
console.log(` iterations: ${out.iterations.length} cost: $${out.total_cost_usd.toFixed(4)} time: ${(out.duration_ms / 1000).toFixed(1)}s`);
|
|
298
|
+
if (out.branch) console.log(` worktree branch: ${out.branch} (${out.work_dir})`);
|
|
299
|
+
console.log(` ledger: ${out.state_dir}`);
|
|
300
|
+
}
|
|
301
|
+
if (out.status !== "passed") process.exit(1);
|
|
302
|
+
}
|