@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.
@@ -0,0 +1,339 @@
1
+ /**
2
+ * Role registry for `oalo swarm`: built-in specialist presets, curated `--team`
3
+ * bundles, repo-local `.oalo/roles/<name>.json` overrides, and user-global
4
+ * `~/.oalo/roles/<name>.json` custom roles.
5
+ *
6
+ * Also parses per-role harness overrides (`role@claude:opus`,
7
+ * `ml-systems@opencode:openrouter/deepseek/deepseek-v4.1-flash`,
8
+ * `tester@cmd:node mock.mjs`).
9
+ */
10
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { parseHarnessSpec } from "./harness.js";
14
+
15
+ export const BUILTIN_ROLES = {
16
+ architect: {
17
+ category: "engineering",
18
+ focus: "System boundaries, module interfaces, data flow, and clean task decomposition with disjoint file write-sets.",
19
+ checklist: [
20
+ "Identify clear component boundaries and exact function/API signatures",
21
+ "Flag coupling hotspots and shared files that would cause parallel merge conflicts",
22
+ "Propose the simplest architecture that satisfies current requirements",
23
+ ],
24
+ },
25
+ backend: {
26
+ category: "engineering",
27
+ focus: "Server logic, persistence, API contracts, concurrency, error handling, and migration safety.",
28
+ checklist: [
29
+ "Check input validation, idempotency, and error status codes",
30
+ "Verify database schema, query patterns, and backward-compatible migrations",
31
+ "Call out race conditions, retries, and background job failure modes",
32
+ ],
33
+ },
34
+ frontend: {
35
+ category: "engineering",
36
+ focus: "UI state management, component ergonomics, accessibility, responsive layout, and client-server sync.",
37
+ checklist: [
38
+ "Check loading, empty, and error states for every view",
39
+ "Verify state flow, optimistic updates, and cache invalidation",
40
+ "Keep components modular with minimal prop drilling",
41
+ ],
42
+ },
43
+ db: {
44
+ category: "engineering",
45
+ focus: "Schema design, indexing, query plans, transactions, locking, and safe zero-downtime migrations.",
46
+ checklist: [
47
+ "Verify primary keys, foreign keys, uniqueness constraints, and indexes",
48
+ "Check migration safety (additive first, no destructive locks on hot tables)",
49
+ "Flag N+1 queries, unbounded scans, and transaction scope issues",
50
+ ],
51
+ },
52
+ security: {
53
+ category: "engineering",
54
+ focus: "AuthN/AuthZ, tenant isolation, secret handling, injection vectors, SSRF, and least-privilege boundaries.",
55
+ checklist: [
56
+ "Verify auth and tenant scoping on every entry point and background action",
57
+ "Check for secret leakage in logs, env files, errors, or client bundles",
58
+ "Flag untrusted input reaching SQL, shell commands, HTML, or outbound HTTP",
59
+ ],
60
+ },
61
+ reliability: {
62
+ category: "engineering",
63
+ focus: "Failure modes, timeouts, rate limits, observability, graceful degradation, and recovery playbooks.",
64
+ checklist: [
65
+ "Check every external call for timeouts, retries, and circuit-breaking",
66
+ "Verify crash recovery, idempotency, and partial-failure cleanup",
67
+ "Ensure actionable logs, metrics, and health checks exist",
68
+ ],
69
+ },
70
+ performance: {
71
+ category: "engineering",
72
+ focus: "Latency bottlenecks, memory footprint, caching, batching, and algorithmic complexity.",
73
+ checklist: [
74
+ "Identify hot paths, unnecessary serialization, and blocking I/O",
75
+ "Check payload sizes, pagination, and bounded buffers/queues",
76
+ "Suggest concrete benchmark commands to verify speedups",
77
+ ],
78
+ },
79
+ testing: {
80
+ category: "engineering",
81
+ focus: "Deterministic verification strategy, edge-case coverage, test isolation, and fast feedback loops.",
82
+ checklist: [
83
+ "Define machine-verifiable acceptance criteria for every planned task",
84
+ "Cover happy path, boundary conditions, failure recovery, and concurrency",
85
+ "Keep tests fast, deterministic, and isolated from external state",
86
+ ],
87
+ },
88
+ devops: {
89
+ category: "engineering",
90
+ focus: "Build pipelines, container images, env configuration, rollouts, rollbacks, and CI gates.",
91
+ checklist: [
92
+ "Verify reproducible builds, minimal runtime deps, and clear env var contracts",
93
+ "Check canary rollout, health probes, and fast rollback path",
94
+ "Ensure CI catches regressions before deployment",
95
+ ],
96
+ },
97
+ ux: {
98
+ category: "product",
99
+ focus: "User mental model, CLI/UI ergonomics, copy clarity, defaults, and eliminating unnecessary friction.",
100
+ checklist: [
101
+ "Check first-run experience and sensible zero-config defaults",
102
+ "Ensure error messages tell the user exactly what failed and what to run next",
103
+ "Cut ceremony and redundant flags/steps wherever possible",
104
+ ],
105
+ },
106
+ simplifier: {
107
+ category: "product",
108
+ focus: "Ruthless YAGNI and scope reduction: cut premature abstractions, extra layers, and over-engineering.",
109
+ checklist: [
110
+ "Challenge every new file, abstraction, or dependency that is not strictly needed now",
111
+ "Look for existing utilities in the repo that can be reused directly",
112
+ "Propose the smallest high-leverage slice that proves value end-to-end",
113
+ ],
114
+ },
115
+ skeptic: {
116
+ category: "review",
117
+ focus: "Adversarial red-teamer: hunt for hidden assumptions, edge cases, silent failures, and ways the plan could blow up.",
118
+ checklist: [
119
+ "Ask what breaks under bad input, partial crashes, or concurrent runs",
120
+ "Challenge optimistic estimates or unverified assumptions from other roles",
121
+ "Name the top 2-3 failure scenarios that must be tested explicitly",
122
+ ],
123
+ },
124
+ "ml-systems": {
125
+ category: "research",
126
+ focus: "Reproducible local ML/AI experimentation: bounded runtimes, seed control, resource isolation, and experiment ledgers.",
127
+ checklist: [
128
+ "Enforce deterministic seeds, wall-clock budgets, and clean subprocess cleanup",
129
+ "Keep experiment state and metrics in an append-only disk ledger (SQLite/TSV/JSON)",
130
+ "Separate mutable experiment code from immutable evaluation harnesses",
131
+ ],
132
+ },
133
+ "eval-engineer": {
134
+ category: "research",
135
+ focus: "Leak-free benchmarks, objective scoring functions, regression gates, and statistical significance.",
136
+ checklist: [
137
+ "Verify train/val/test separation and guard against reward hacking or eval leakage",
138
+ "Define a single unambiguous primary metric plus guardrail metrics (latency, cost)",
139
+ "Ensure the verifier command exits cleanly and prints parseable scores",
140
+ ],
141
+ },
142
+ "data-pipeline": {
143
+ category: "research",
144
+ focus: "Dataset ingestion, chunking, provenance, caching, deduplication, and schema validation.",
145
+ checklist: [
146
+ "Check data cleanliness, deduplication, and deterministic preprocessing",
147
+ "Verify incremental caching so repeated runs do not redo expensive prep",
148
+ "Validate record schemas and handle malformed rows gracefully",
149
+ ],
150
+ },
151
+ "prompt-engineer": {
152
+ category: "research",
153
+ focus: "System prompts, tool schemas, structured outputs, few-shot examples, and failure-case guardrails.",
154
+ checklist: [
155
+ "Keep prompts concise, unambiguous, and backed by strict JSON/tool schemas",
156
+ "Test edge cases, refusals, and multi-turn tool-use drift via `oalo qa`",
157
+ "Optimize token efficiency and model routing (fast models for simple steps)",
158
+ ],
159
+ },
160
+ };
161
+
162
+ export const ROLE_ALIASES = {
163
+ architecture: "architect",
164
+ tests: "testing",
165
+ qa: "testing",
166
+ perf: "performance",
167
+ sec: "security",
168
+ ml: "ml-systems",
169
+ eval: "eval-engineer",
170
+ prompts: "prompt-engineer",
171
+ };
172
+
173
+ export const BUILTIN_TEAMS = {
174
+ engineering: {
175
+ description: "Balanced build team: architecture, backend, testing, and a red-team skeptic",
176
+ roles: ["architect", "backend", "testing", "skeptic"],
177
+ },
178
+ audit: {
179
+ description: "Deep codebase audit across architecture, security, reliability, and performance",
180
+ roles: ["architect", "security", "reliability", "performance"],
181
+ },
182
+ research: {
183
+ description: "Local AI / AutoResearch pipeline design: architect, ml-systems, eval-engineer, skeptic",
184
+ roles: ["architect", "ml-systems", "eval-engineer", "skeptic"],
185
+ },
186
+ feature: {
187
+ description: "Pragmatic feature scoping: architect, backend, testing, and YAGNI simplifier",
188
+ roles: ["architect", "backend", "testing", "simplifier"],
189
+ },
190
+ "oalo-bot": {
191
+ description: "Oalo bot/flow design: prompt-engineer, eval-engineer, ux, and skeptic",
192
+ roles: ["prompt-engineer", "eval-engineer", "ux", "skeptic"],
193
+ },
194
+ };
195
+
196
+ const VALID_ROLE_NAME = /^[a-z0-9][a-z0-9_-]{0,39}$/;
197
+
198
+ export function normalizeRoleName(name) {
199
+ const n = String(name || "").trim().toLowerCase();
200
+ return ROLE_ALIASES[n] || n;
201
+ }
202
+
203
+ export function projectRolesDir(root) {
204
+ return join(root, ".oalo", "roles");
205
+ }
206
+
207
+ export function globalRolesDir() {
208
+ return join(process.env.OALO_HOME || homedir(), ".oalo", "roles");
209
+ }
210
+
211
+ function readRoleDir(dir, source) {
212
+ const out = {};
213
+ if (!dir || !existsSync(dir)) return out;
214
+ for (const f of readdirSync(dir)) {
215
+ if (!f.endsWith(".json")) continue;
216
+ try {
217
+ const data = JSON.parse(readFileSync(join(dir, f), "utf8"));
218
+ const name = String(data.name || f.replace(/\.json$/, "")).toLowerCase();
219
+ out[name] = {
220
+ name,
221
+ source,
222
+ category: data.category || "custom",
223
+ focus: String(data.focus || "").trim(),
224
+ checklist: Array.isArray(data.checklist) ? data.checklist.map((x) => String(x).trim()).filter(Boolean) : [],
225
+ harness: data.harness ? String(data.harness).trim() : null,
226
+ };
227
+ } catch {}
228
+ }
229
+ return out;
230
+ }
231
+
232
+ /** Return merged map of all available roles (project > global > builtin). */
233
+ export function loadRoleRegistry(root = null) {
234
+ const merged = {};
235
+ for (const [name, def] of Object.entries(BUILTIN_ROLES)) {
236
+ merged[name] = { name, source: "builtin", harness: null, ...def };
237
+ }
238
+ const globalRoles = readRoleDir(globalRolesDir(), "global");
239
+ for (const [name, def] of Object.entries(globalRoles)) merged[name] = def;
240
+ if (root) {
241
+ const projRoles = readRoleDir(projectRolesDir(root), "project");
242
+ for (const [name, def] of Object.entries(projRoles)) merged[name] = def;
243
+ }
244
+ return merged;
245
+ }
246
+
247
+ export function getRole(root, rawName) {
248
+ const registry = loadRoleRegistry(root);
249
+ const direct = String(rawName || "").trim().toLowerCase();
250
+ if (registry[direct]) return registry[direct];
251
+ const canonical = normalizeRoleName(direct);
252
+ if (registry[canonical]) return registry[canonical];
253
+ return null;
254
+ }
255
+
256
+ export function saveRole({ root, name, focus, checklist = [], harness = null, category = "custom", global = false }) {
257
+ const clean = String(name || "").trim().toLowerCase();
258
+ if (!VALID_ROLE_NAME.test(clean)) {
259
+ throw new Error(`invalid role name \`${name}\` (use lowercase letters, digits, hyphens, underscores)`);
260
+ }
261
+ if (!String(focus || "").trim()) {
262
+ throw new Error("role requires --focus <description>");
263
+ }
264
+ const dir = global ? globalRolesDir() : projectRolesDir(root);
265
+ mkdirSync(dir, { recursive: true });
266
+ const file = join(dir, `${clean}.json`);
267
+ const record = {
268
+ name: clean,
269
+ category,
270
+ focus: String(focus).trim(),
271
+ checklist: Array.isArray(checklist)
272
+ ? checklist.map((x) => String(x).trim()).filter(Boolean)
273
+ : String(checklist || "")
274
+ .split(",")
275
+ .map((x) => x.trim())
276
+ .filter(Boolean),
277
+ ...(harness ? { harness: String(harness).trim() } : {}),
278
+ };
279
+ writeFileSync(file, JSON.stringify(record, null, 2) + "\n");
280
+ return { ...record, source: global ? "global" : "project", file };
281
+ }
282
+
283
+ export function deleteRole({ root, name, global = false }) {
284
+ const clean = String(name || "").trim().toLowerCase();
285
+ const dir = global ? globalRolesDir() : projectRolesDir(root);
286
+ const file = join(dir, `${clean}.json`);
287
+ if (!existsSync(file)) {
288
+ throw new Error(`custom role \`${clean}\` not found in ${dir}`);
289
+ }
290
+ rmSync(file, { force: true });
291
+ return { deleted: clean, scope: global ? "global" : "project", file };
292
+ }
293
+
294
+ /**
295
+ * Parse a role spec list (e.g. "architect@claude:opus,ml-systems,skeptic")
296
+ * or a `--team` preset into fully resolved role objects with their effective
297
+ * harness spec.
298
+ */
299
+ export function resolveRoleSpecs({ root = null, roles = null, team = null, defaultHarness }) {
300
+ let rawEntries = [];
301
+ if (roles && (Array.isArray(roles) ? roles.length : String(roles).trim())) {
302
+ if (Array.isArray(roles)) {
303
+ rawEntries = roles.map((r) => String(r).trim()).filter(Boolean);
304
+ } else {
305
+ const s = String(roles).trim();
306
+ rawEntries = (s.includes("||") ? s.split("||") : s.split(",")).map((r) => r.trim()).filter(Boolean);
307
+ }
308
+ } else if (team) {
309
+ const key = String(team).trim().toLowerCase();
310
+ const t = BUILTIN_TEAMS[key];
311
+ if (!t) {
312
+ throw new Error(`unknown team preset \`${team}\` (available: ${Object.keys(BUILTIN_TEAMS).join(", ")})`);
313
+ }
314
+ rawEntries = [...t.roles];
315
+ } else {
316
+ rawEntries = ["architect", "backend", "security"];
317
+ }
318
+
319
+ const registry = loadRoleRegistry(root);
320
+ return rawEntries.map((entry) => {
321
+ const at = entry.indexOf("@");
322
+ const rawName = (at === -1 ? entry : entry.slice(0, at)).trim();
323
+ const inlineHarness = at === -1 ? null : entry.slice(at + 1).trim() || null;
324
+ const direct = rawName.toLowerCase();
325
+ const canonical = normalizeRoleName(direct);
326
+ const def = registry[direct] || registry[canonical] || null;
327
+ const effectiveHarness = parseHarnessSpec(inlineHarness || def?.harness || defaultHarness);
328
+
329
+ return {
330
+ name: rawName,
331
+ canonical: def?.name || direct,
332
+ source: def?.source || "adhoc",
333
+ category: def?.category || "adhoc",
334
+ focus: def?.focus || "",
335
+ checklist: def?.checklist || [],
336
+ harness: effectiveHarness,
337
+ };
338
+ });
339
+ }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Git worktree and shell helpers shared by Node-based coordination commands
3
+ * (`ralph`, `race`, `review`, `swarm`, `auto`). Worktrees always live outside
4
+ * the repo under ~/.oalo/worktrees/<project>-<hash>/ so main-checkout tools
5
+ * never see in-progress parallel branches.
6
+ */
7
+ import { spawn, spawnSync } from "node:child_process";
8
+ import { createHash } from "node:crypto";
9
+ import { existsSync, mkdirSync, realpathSync, rmSync } from "node:fs";
10
+ import { homedir } from "node:os";
11
+ import { basename, join } from "node:path";
12
+
13
+ export function gitTry(cwd, args, env = {}) {
14
+ const r = spawnSync("git", args, {
15
+ cwd,
16
+ encoding: "utf8",
17
+ env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: "0" },
18
+ maxBuffer: 64 * 1024 * 1024,
19
+ });
20
+ return {
21
+ ok: r.status === 0,
22
+ code: r.status,
23
+ stdout: (r.stdout || "").trim(),
24
+ stderr: (r.stderr || "").trim(),
25
+ };
26
+ }
27
+
28
+ export function git(cwd, args, env = {}) {
29
+ const r = gitTry(cwd, args, env);
30
+ if (!r.ok) throw new Error(`git ${args.join(" ")} failed: ${r.stderr || r.stdout}`);
31
+ return r.stdout;
32
+ }
33
+
34
+ export function projectRoot(cwd = process.cwd()) {
35
+ const r = gitTry(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
36
+ if (!r.ok) return null;
37
+ const dir = r.stdout.replace(/\/$/, "");
38
+ return dir.endsWith("/.git") ? dir.slice(0, -"/.git".length) : dir;
39
+ }
40
+
41
+ export function requireProjectRoot(cwd = process.cwd()) {
42
+ const root = projectRoot(cwd);
43
+ if (!root) throw new Error("not inside a git repository");
44
+ return root;
45
+ }
46
+
47
+ export function head(cwd) {
48
+ return git(cwd, ["rev-parse", "HEAD"]);
49
+ }
50
+
51
+ export function currentBranch(cwd) {
52
+ const r = gitTry(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
53
+ return r.ok ? r.stdout : null;
54
+ }
55
+
56
+ export function isClean(cwd) {
57
+ return git(cwd, ["status", "--porcelain"]) === "";
58
+ }
59
+
60
+ export function worktreeBase(root) {
61
+ let real = root;
62
+ try {
63
+ real = realpathSync(root);
64
+ } catch {}
65
+ const name = basename(real).toLowerCase().replace(/[^a-z0-9._-]+/g, "-") || "project";
66
+ const hash = createHash("sha1").update(real).digest("hex").slice(0, 8);
67
+ return join(process.env.OALO_HOME || homedir(), ".oalo", "worktrees", `${name}-${hash}`);
68
+ }
69
+
70
+ export function createWorktree({ root, namespace, name, baseRef = "HEAD" }) {
71
+ const baseSha = git(root, ["rev-parse", "--verify", `${baseRef}^{commit}`]);
72
+ const dir = join(worktreeBase(root), namespace, name);
73
+ const branch = `oalo/${namespace}/${name}`;
74
+ mkdirSync(join(worktreeBase(root), namespace), { recursive: true });
75
+ if (existsSync(dir)) {
76
+ gitTry(root, ["worktree", "remove", "--force", dir]);
77
+ rmSync(dir, { recursive: true, force: true });
78
+ }
79
+ gitTry(root, ["worktree", "prune"]);
80
+ gitTry(root, ["branch", "-D", branch]);
81
+ git(root, ["worktree", "add", "-b", branch, dir, baseSha]);
82
+ return { path: dir, branch, baseSha };
83
+ }
84
+
85
+ export function removeWorktree({ root, path, branch = null, deleteBranch = true }) {
86
+ if (path && existsSync(path)) {
87
+ gitTry(root, ["worktree", "remove", "--force", path]);
88
+ if (existsSync(path)) rmSync(path, { recursive: true, force: true });
89
+ }
90
+ gitTry(root, ["worktree", "prune"]);
91
+ if (deleteBranch && branch) gitTry(root, ["branch", "-D", branch]);
92
+ }
93
+
94
+ export function diffSummary(cwd, baseSha, ref = "HEAD") {
95
+ const stat = gitTry(cwd, ["diff", "--shortstat", `${baseSha}...${ref}`]).stdout;
96
+ const files = gitTry(cwd, ["diff", "--name-only", `${baseSha}...${ref}`])
97
+ .stdout.split("\n")
98
+ .filter(Boolean);
99
+ const commits = gitTry(cwd, ["log", "--format=%h %s", `${baseSha}..${ref}`])
100
+ .stdout.split("\n")
101
+ .filter(Boolean);
102
+ return { stat, files, commits };
103
+ }
104
+
105
+ export function commitAll(cwd, message) {
106
+ git(cwd, ["add", "-A"]);
107
+ if (isClean(cwd)) return null;
108
+ git(cwd, ["commit", "-m", message], {
109
+ GIT_AUTHOR_NAME: process.env.GIT_AUTHOR_NAME || "oalo agent",
110
+ GIT_AUTHOR_EMAIL: process.env.GIT_AUTHOR_EMAIL || "agent@oalo.local",
111
+ GIT_COMMITTER_NAME: process.env.GIT_COMMITTER_NAME || "oalo agent",
112
+ GIT_COMMITTER_EMAIL: process.env.GIT_COMMITTER_EMAIL || "agent@oalo.local",
113
+ });
114
+ return head(cwd);
115
+ }
116
+
117
+ /** Run a shell verification command asynchronously with bounded output capture. */
118
+ export function runShell(cmd, { cwd = process.cwd(), env = {}, timeoutMs = 10 * 60 * 1000 } = {}) {
119
+ const start = Date.now();
120
+ return new Promise((resolve) => {
121
+ const child = spawn("sh", ["-c", cmd], {
122
+ cwd,
123
+ env: { ...process.env, ...env },
124
+ stdio: ["ignore", "pipe", "pipe"],
125
+ });
126
+ let output = "";
127
+ const keep = (b) => {
128
+ output += b.toString("utf8");
129
+ if (output.length > 512 * 1024) output = output.slice(-256 * 1024);
130
+ };
131
+ child.stdout.on("data", keep);
132
+ child.stderr.on("data", keep);
133
+ let timedOut = false;
134
+ const timer = timeoutMs > 0
135
+ ? setTimeout(() => {
136
+ timedOut = true;
137
+ try {
138
+ child.kill("SIGKILL");
139
+ } catch {}
140
+ }, timeoutMs)
141
+ : null;
142
+ child.on("error", (err) => {
143
+ if (timer) clearTimeout(timer);
144
+ resolve({ ok: false, status: 127, signal: null, timedOut, output: `${output}\n${err.message}`.trim(), durationMs: Date.now() - start });
145
+ });
146
+ child.on("close", (status, signal) => {
147
+ if (timer) clearTimeout(timer);
148
+ resolve({ ok: status === 0 && !timedOut, status, signal, timedOut, output: output.trim(), durationMs: Date.now() - start });
149
+ });
150
+ });
151
+ }
152
+
153
+ export function tailLines(text, n = 60) {
154
+ return String(text || "").trim().split("\n").slice(-n).join("\n");
155
+ }