@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,239 @@
1
+ /**
2
+ * Strategy 6: `oalo auto` — Composable coordination presets ("Packs", Gas City
3
+ * style). Bundles Strategies 1-5 into one ergonomic command for the four most
4
+ * common engineering shapes (`qa-grind`, `bugfix`, `audit`, `feature`), plus
5
+ * project-defined JSON workflows under `.oalo/workflows/<name>.json`.
6
+ */
7
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { runRalph } from "./ralph.js";
10
+ import { runRace, pickRace } from "./race.js";
11
+ import { runCriticReview } from "./review.js";
12
+ import { runSwarm, promoteSwarm, runCoordCli } from "./swarm.js";
13
+ import { requireProjectRoot, runShell } from "../agents/worktree.js";
14
+
15
+ const USAGE = `usage:
16
+ oalo auto list [--json]
17
+ oalo auto <preset> "<goal>" [options]
18
+
19
+ built-in presets:
20
+ qa-grind Ralph fresh-context loop against --verify (e.g. "oalo qa ..." or "npm test")
21
+ bugfix Best-of-N race across --models against --verify (add --auto-pick to merge winner)
22
+ audit Read-only multi-role blackboard swarm (architecture, security, reliability)
23
+ feature Swarm design -> promote to oalo coord -> (optional approve) -> coord up + reviewer
24
+
25
+ custom packs:
26
+ Place JSON files in .oalo/workflows/<name>.json with { "description": "...", "stages": [...] }`;
27
+
28
+ const BUILTINS = {
29
+ "qa-grind": {
30
+ description: "Fresh-context Ralph loop until --verify passes (great with `oalo qa` or `npm test`)",
31
+ stages: [{ type: "ralph" }],
32
+ },
33
+ bugfix: {
34
+ description: "Best-of-N competitive race across --models against --verify, optionally auto-picking winner",
35
+ stages: [{ type: "race" }],
36
+ },
37
+ audit: {
38
+ description: "Read-only 2-round multi-role swarm (architecture, security, reliability) -> report.md",
39
+ stages: [{ type: "swarm", roles: ["architecture", "security", "reliability"], rounds: 2, readonly: true }],
40
+ },
41
+ feature: {
42
+ description: "Swarm design -> promote to oalo coord -> approve plan (if --auto-approve) -> oalo coord up",
43
+ stages: [
44
+ { type: "swarm", roles: ["architect", "backend", "tests"], rounds: 2, readonly: true },
45
+ { type: "promote" },
46
+ { type: "coord_up" },
47
+ ],
48
+ },
49
+ };
50
+
51
+ function loadCustomPacks(root) {
52
+ const dir = join(root, ".oalo", "workflows");
53
+ if (!existsSync(dir)) return {};
54
+ const packs = {};
55
+ for (const f of readdirSync(dir)) {
56
+ if (!f.endsWith(".json")) continue;
57
+ try {
58
+ packs[f.replace(/\.json$/, "")] = JSON.parse(readFileSync(join(dir, f), "utf8"));
59
+ } catch {}
60
+ }
61
+ return packs;
62
+ }
63
+
64
+ function interpolate(val, ctx) {
65
+ if (typeof val !== "string") return val;
66
+ return val
67
+ .replaceAll("{{goal}}", ctx.goal || "")
68
+ .replaceAll("{{verify}}", ctx.verify || "");
69
+ }
70
+
71
+ export async function runAuto({ root, preset, goal, flags = {} }) {
72
+ const custom = loadCustomPacks(root);
73
+ const pack = custom[preset] || BUILTINS[preset];
74
+ if (!pack) {
75
+ const names = [...Object.keys(BUILTINS), ...Object.keys(custom)];
76
+ throw new Error(`unknown preset \`${preset}\` (available: ${names.join(", ")})`);
77
+ }
78
+
79
+ const quiet = !!flags.json;
80
+ const log = (msg) => {
81
+ if (!quiet) console.error(`[auto:${preset}] ${msg}`);
82
+ };
83
+ const ctx = {
84
+ goal: goal || "",
85
+ verify: typeof flags.verify === "string" ? flags.verify : "",
86
+ lastSwarmId: null,
87
+ lastRaceId: null,
88
+ };
89
+
90
+ const results = [];
91
+ for (let i = 0; i < (pack.stages || []).length; i++) {
92
+ const stage = pack.stages[i];
93
+ log(`stage ${i + 1}/${pack.stages.length}: ${stage.type}`);
94
+
95
+ if (stage.type === "ralph") {
96
+ const verify = interpolate(stage.verify, ctx) || ctx.verify;
97
+ const r = await runRalph({
98
+ root,
99
+ cwd: root,
100
+ goal: interpolate(stage.goal, ctx) || ctx.goal,
101
+ verify,
102
+ plan: stage.plan || (typeof flags.plan === "string" ? flags.plan : null),
103
+ harness: stage.harness || (typeof flags.harness === "string" ? flags.harness : null),
104
+ maxIters: flags["max-iters"] ? Number(flags["max-iters"]) : stage.max_iters || 10,
105
+ maxCost: flags["max-cost"] ? Number(flags["max-cost"]) : stage.max_cost || 5.0,
106
+ commit: flags.commit != null ? !!flags.commit : !!stage.commit,
107
+ worktree: flags.worktree != null ? !!flags.worktree : !!stage.worktree,
108
+ quiet,
109
+ });
110
+ const clean = { ...r };
111
+ delete clean.cleanupWorktree;
112
+ results.push({ stage: stage.type, result: clean });
113
+ if (r.status !== "passed") return { preset, ok: false, failed_stage: stage.type, results };
114
+ } else if (stage.type === "race") {
115
+ const verify = interpolate(stage.verify, ctx) || ctx.verify || null;
116
+ const rec = await runRace({
117
+ root,
118
+ goal: interpolate(stage.goal, ctx) || ctx.goal,
119
+ models: typeof flags.models === "string" ? flags.models : stage.models || (typeof flags.harness === "string" ? flags.harness : null),
120
+ verify,
121
+ judge: typeof flags.judge === "string" ? flags.judge : stage.judge || null,
122
+ budgetUsd: flags.budget ? Number(flags.budget) : stage.budget || null,
123
+ quiet,
124
+ });
125
+ ctx.lastRaceId = rec.run_id;
126
+ let picked = null;
127
+ const autoPick = flags["auto-pick"] != null ? !!flags["auto-pick"] : !!stage.auto_pick;
128
+ if (autoPick && rec.recommended_slot) {
129
+ picked = pickRace({ root, runId: rec.run_id, slot: rec.recommended_slot });
130
+ log(`auto-picked winner slot ${picked.picked_slot} (${picked.label})`);
131
+ }
132
+ results.push({ stage: stage.type, result: { ...rec, picked } });
133
+ if (verify && !rec.recommended_slot) return { preset, ok: false, failed_stage: stage.type, results };
134
+ } else if (stage.type === "swarm") {
135
+ const s = await runSwarm({
136
+ root,
137
+ goal: interpolate(stage.goal, ctx) || ctx.goal,
138
+ team: typeof flags.team === "string" ? flags.team : stage.team || null,
139
+ roles: typeof flags.roles === "string" ? flags.roles : stage.roles || null,
140
+ rounds: flags.rounds ? Number(flags.rounds) : stage.rounds || 2,
141
+ harness: typeof flags.harness === "string" ? flags.harness : stage.harness || null,
142
+ readonly: stage.readonly !== false,
143
+ budgetUsd: flags.budget ? Number(flags.budget) : stage.budget || null,
144
+ quiet,
145
+ });
146
+ ctx.lastSwarmId = s.run_id;
147
+ results.push({ stage: stage.type, result: s });
148
+ } else if (stage.type === "promote") {
149
+ const p = promoteSwarm({ root, runId: ctx.lastSwarmId });
150
+ results.push({ stage: stage.type, result: p });
151
+ // Note: human plan approval gate stays enforced; user approves in terminal or passes --auto-approve when running interactively.
152
+ if (flags["auto-approve"] || stage.auto_approve) {
153
+ const app = runCoordCli(root, ["coord", "approve", "plan", "--yes"]);
154
+ if (app.status !== 0) {
155
+ return {
156
+ preset,
157
+ ok: false,
158
+ failed_stage: "approve_plan",
159
+ note: (app.stderr || app.stdout || "").trim(),
160
+ results,
161
+ };
162
+ }
163
+ }
164
+ } else if (stage.type === "coord_up") {
165
+ const args = ["coord", "up", "--json"];
166
+ if (flags.workers || stage.workers) args.push("--workers", String(flags.workers || stage.workers));
167
+ if (flags.harness || stage.harness) args.push("--harness", String(flags.harness || stage.harness));
168
+ if (flags.budget || stage.budget) args.push("--budget", String(flags.budget || stage.budget));
169
+ if (flags["no-auto-merge"]) args.push("--no-auto-merge");
170
+ const up = runCoordCli(root, args);
171
+ let parsed = null;
172
+ try {
173
+ parsed = JSON.parse(up.stdout);
174
+ } catch {
175
+ parsed = { raw: up.stdout, stderr: up.stderr };
176
+ }
177
+ results.push({ stage: stage.type, result: parsed });
178
+ if (up.status !== 0 && parsed?.status !== "needs_human") {
179
+ return { preset, ok: false, failed_stage: stage.type, results };
180
+ }
181
+ } else if (stage.type === "review") {
182
+ const rev = await runCriticReview({
183
+ cwd: root,
184
+ against: stage.against || (typeof flags.against === "string" ? flags.against : null),
185
+ models: typeof flags.reviewer === "string" ? flags.reviewer : stage.models || (typeof flags.models === "string" ? flags.models : null),
186
+ strict: !!(flags.strict || stage.strict),
187
+ quiet,
188
+ });
189
+ results.push({ stage: stage.type, result: rev });
190
+ if (!rev.approved) return { preset, ok: false, failed_stage: stage.type, results };
191
+ } else if (stage.type === "shell") {
192
+ const cmd = interpolate(stage.cmd, ctx);
193
+ const r = await runShell(cmd, { cwd: root });
194
+ results.push({ stage: stage.type, cmd, result: r });
195
+ if (!r.ok) return { preset, ok: false, failed_stage: stage.type, results };
196
+ } else {
197
+ throw new Error(`unknown workflow stage type: ${stage.type}`);
198
+ }
199
+ }
200
+
201
+ return { preset, ok: true, results };
202
+ }
203
+
204
+ export async function auto(flags, rest) {
205
+ const sub = rest[1];
206
+ if (flags.help || !sub || sub === "help") {
207
+ console.log(USAGE);
208
+ return;
209
+ }
210
+ const root = requireProjectRoot(process.cwd());
211
+
212
+ if (sub === "list") {
213
+ const custom = loadCustomPacks(root);
214
+ const list = [
215
+ ...Object.entries(BUILTINS).map(([name, p]) => ({ name, source: "builtin", description: p.description, stages: p.stages.map((s) => s.type) })),
216
+ ...Object.entries(custom).map(([name, p]) => ({ name, source: ".oalo/workflows", description: p.description || "", stages: (p.stages || []).map((s) => s.type) })),
217
+ ];
218
+ if (flags.json) console.log(JSON.stringify(list, null, 2));
219
+ else {
220
+ for (const item of list) {
221
+ console.log(` ${item.name.padEnd(14)} [${item.source}] ${item.description} (${item.stages.join(" -> ")})`);
222
+ }
223
+ }
224
+ return;
225
+ }
226
+
227
+ const preset = sub;
228
+ const goal = typeof flags.goal === "string" ? flags.goal : rest.slice(2).join(" ").trim();
229
+ const res = await runAuto({ root, preset, goal, flags });
230
+ if (flags.json) {
231
+ console.log(JSON.stringify(res, null, 2));
232
+ } else {
233
+ console.log(`\nAuto preset \`${preset}\`: ${res.ok ? "OK" : `STOPPED (${res.failed_stage})`}`);
234
+ for (const s of res.results) {
235
+ console.log(` - ${s.stage}: ${s.result?.status || s.result?.verdict || (s.result?.ok === false ? "failed" : "done")}`);
236
+ }
237
+ }
238
+ if (!res.ok) process.exit(1);
239
+ }
@@ -15,7 +15,7 @@ import { dim } from "../events.js";
15
15
  * oalo bots settings <bot> every setting and its value
16
16
  * oalo bots settings <bot> set key=value ... [--yes] [--dry-run]
17
17
  * oalo bots settings --explain [key] what each setting does
18
- * oalo bots graph <bot> [--build] [--reset --yes] its knowledge graph
18
+ * oalo bots graph <bot> [--build] [--search <q>] [--export <file>] [--import <file>] [--resync] [--reset --yes] its knowledge graph
19
19
  *
20
20
  * A source is a table made searchable with `oalo data vectorize`: its handle
21
21
  * (`model:products`, `table:prod.faq`) or just its name when that's unique.
@@ -63,7 +63,7 @@ const USAGE = [
63
63
  " oalo bots settings <bot> [--json]",
64
64
  " oalo bots settings <bot> set key=value [key=value ...] [--yes] [--dry-run]",
65
65
  " oalo bots settings --explain [key]",
66
- " oalo bots graph <bot> [--build] [--reset --yes] [--json]",
66
+ " oalo bots graph <bot> [--build] [--search <query>] [--export <file>] [--import <file>] [--resync] [--reset --yes] [--json]",
67
67
  ].join("\n");
68
68
 
69
69
  async function list(ch, flags, url) {
@@ -0,0 +1,114 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { OaloChannel } from "../channel.js";
3
+ import { resolve as resolveConfig, controlPlane, HOW_TO_CONNECT } from "../config.js";
4
+ import { dim } from "../events.js";
5
+
6
+ /**
7
+ * `oalo crm`: CRM contact import (`crm:import_contacts`).
8
+ *
9
+ * oalo crm import <file.csv> [--tags tag1,tag2] [--dry-run] [--json]
10
+ */
11
+ export async function crm(flags, rest, opts = {}) {
12
+ const sub = rest[1];
13
+ const filePath = rest[2];
14
+ if (sub !== "import" || !filePath) {
15
+ return fail("usage: oalo crm import <file.csv> [--tags a,b] [--dry-run] [--json]", 2, flags);
16
+ }
17
+
18
+ let csvText;
19
+ try {
20
+ csvText = readFileSync(filePath, "utf8");
21
+ } catch (e) {
22
+ return fail(`could not read ${filePath}: ${e.message}`, 2, flags);
23
+ }
24
+
25
+ const rows = parseContactsCsv(csvText);
26
+ if (!rows.length) {
27
+ return fail("no contact rows found in CSV (expected a header row with email, phone, or name)", 2, flags);
28
+ }
29
+
30
+ const tags =
31
+ typeof flags.tags === "string"
32
+ ? flags.tags.split(",").map((t) => t.trim()).filter(Boolean)
33
+ : [];
34
+
35
+ if (flags["dry-run"]) {
36
+ if (flags.json) return void console.log(JSON.stringify({ dry_run: true, count: rows.length, tags, preview: rows.slice(0, 5) }, null, 2));
37
+ console.log(`dry run: ${rows.length} contact row(s) ready to import${tags.length ? ` with tags [${tags.join(", ")}]` : ""}`);
38
+ for (const r of rows.slice(0, 5)) console.log(` ${dim(JSON.stringify(r))}`);
39
+ return;
40
+ }
41
+
42
+ const cfg = resolveConfig(flags);
43
+ const { url, token } = controlPlane(cfg);
44
+ if (!url || !token) return fail(`oalo crm needs a CLI token.\n\n${HOW_TO_CONNECT}`, 2, flags);
45
+
46
+ const ch = (opts.channel || ((o) => new OaloChannel(o)))({ url, token });
47
+ try {
48
+ await ch.connect();
49
+ const r = await ch.call("crm:import_contacts", { rows, tags }, 60_000);
50
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
51
+ console.log(`imported ${rows.length} row(s): created=${r.created ?? 0}, updated=${r.updated ?? 0}, skipped=${r.skipped ?? 0}`);
52
+ } catch (e) {
53
+ return fail(e.message, 1, flags);
54
+ } finally {
55
+ ch.close();
56
+ }
57
+ }
58
+
59
+ /** RFC-4180 CSV parser returning array of plain objects keyed by header name. */
60
+ export function parseContactsCsv(text) {
61
+ const table = [];
62
+ let row = [];
63
+ let field = "";
64
+ let inQuotes = false;
65
+
66
+ for (let i = 0; i < text.length; i++) {
67
+ const ch = text[i];
68
+ if (inQuotes) {
69
+ if (ch === '"') {
70
+ if (text[i + 1] === '"') {
71
+ field += '"';
72
+ i++;
73
+ } else {
74
+ inQuotes = false;
75
+ }
76
+ } else {
77
+ field += ch;
78
+ }
79
+ } else if (ch === '"') {
80
+ inQuotes = true;
81
+ } else if (ch === ",") {
82
+ row.push(field);
83
+ field = "";
84
+ } else if (ch === "\r" || ch === "\n") {
85
+ if (ch === "\r" && text[i + 1] === "\n") i++;
86
+ row.push(field);
87
+ if (row.some((cell) => cell.trim() !== "")) table.push(row);
88
+ row = [];
89
+ field = "";
90
+ } else {
91
+ field += ch;
92
+ }
93
+ }
94
+ row.push(field);
95
+ if (row.some((cell) => cell.trim() !== "")) table.push(row);
96
+
97
+ if (table.length < 2) return [];
98
+ const headers = table[0].map((h) => h.replace(/^\uFEFF/, "").trim().toLowerCase().replace(/\s+/g, "_"));
99
+ return table.slice(1).map((cells) => {
100
+ const obj = {};
101
+ headers.forEach((h, idx) => {
102
+ if (!h) return;
103
+ const val = (cells[idx] ?? "").trim();
104
+ if (val !== "") obj[h] = val;
105
+ });
106
+ return obj;
107
+ }).filter((o) => Object.keys(o).length > 0);
108
+ }
109
+
110
+ function fail(msg, code, flags) {
111
+ if (flags?.json) console.log(JSON.stringify({ error: msg }));
112
+ else console.error(msg);
113
+ process.exitCode = code;
114
+ }
@@ -34,7 +34,8 @@ const TABLES_SQL =
34
34
  * `oalo db query "<sql>"`: one read-only statement against an env (default
35
35
  * the project's, dev). It runs on the Base as the env's app login, in a
36
36
  * read-only transaction that is rolled back, so nothing is ever written.
37
- * Workspace admins only, as the dump. `oalo db tables` lists the env's tables.
37
+ * Admins and members with Developer access (`oalo db dump` and `restore` are
38
+ * workspace admins only). `oalo db tables` lists the env's tables.
38
39
  */
39
40
  async function query(flags, sql, opts, { tables = false } = {}) {
40
41
  if (typeof sql !== "string" || !sql.trim()) return fail('usage: oalo db query "select ..." [--env dev|prod] [--limit <n>] [--json]', 2);
@@ -0,0 +1,141 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { spawnSync } from "node:child_process";
3
+ import { join } from "node:path";
4
+ import { OaloChannel } from "../channel.js";
5
+ import { resolve as resolveConfig, controlPlane, HOW_TO_CONNECT } from "../config.js";
6
+ import { dim } from "../events.js";
7
+
8
+ /**
9
+ * `oalo heal`: inspect runtime errors, run/suggest integration tests, and run
10
+ * self-healing either on the Base or locally (`--local`), plus approve/reject
11
+ * generated fix PRs.
12
+ */
13
+ export async function heal(flags, rest, opts = {}) {
14
+ const cfg = resolveConfig(flags);
15
+ const { url, token } = controlPlane(cfg);
16
+ if (!url || !token) return fail(`oalo heal needs a CLI token.\n\n${HOW_TO_CONNECT}`, 2);
17
+
18
+ const sub = rest[1] || "list";
19
+ const arg = rest[2];
20
+ const app = typeof flags.app === "string" ? flags.app : cfg.appId;
21
+
22
+ const ch = (opts.channel || ((o) => new OaloChannel(o)))({ url, token });
23
+ try {
24
+ await ch.connect();
25
+
26
+ if (sub === "list") {
27
+ if (!app) return fail("Pass --app <slug> or link an app with `oalo link --app <slug>`.", 2);
28
+ const r = await ch.call("apps:heal:list", { app });
29
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
30
+ const errors = r.errors || [];
31
+ const runs = r.runs || [];
32
+ console.log(`${r.app} policy: mode=${r.policy?.mode} runner=${r.policy?.runner}`);
33
+ if (!errors.length) {
34
+ console.log(" No runtime errors recorded.");
35
+ } else {
36
+ for (const e of errors) {
37
+ console.log(` #${e.id} [${e.status}] (${e.occurrences}x) ${e.platform}/${e.source}: ${e.title}`);
38
+ }
39
+ }
40
+ if (runs.length) {
41
+ console.log("\nRecent heal runs:");
42
+ for (const h of runs) {
43
+ console.log(` heal #${h.id} (error #${h.error_id}) [${h.status}] branch=${h.branch || "-"}${h.pr_url ? ` ${dim(h.pr_url)}` : ""}`);
44
+ }
45
+ }
46
+ return;
47
+ }
48
+
49
+ if (sub === "inspect") {
50
+ if (!arg) return fail("Usage: oalo heal inspect <error_id>", 2);
51
+ const b = await ch.call("apps:heal:bundle", { error_id: arg });
52
+ if (flags.json) return void console.log(JSON.stringify(b, null, 2));
53
+ const e = b.error;
54
+ console.log(`Error #${e.id} [${e.status}] on ${e.slug} (${e.env}, ${e.platform}/${e.source})`);
55
+ console.log(`Title: ${e.title}`);
56
+ console.log(`Route: ${e.method || ""} ${e.route || "/"} (HTTP ${e.status_code ?? "-"}) · ${e.occurrences}x`);
57
+ if (e.diagnosis) console.log(`\nDiagnosis:\n${e.diagnosis}`);
58
+ if (e.stack_trace) console.log(`\nStack:\n${e.stack_trace}`);
59
+ if (e.sample_logs) console.log(`\nLogs:\n${e.sample_logs}`);
60
+ return;
61
+ }
62
+
63
+ if (sub === "run") {
64
+ if (!arg) return fail("Usage: oalo heal run <error_id> [--local] [--mode branch_and_pr|diagnose_only|auto_deploy]", 2);
65
+ if (flags.local) {
66
+ const b = await ch.call("apps:heal:bundle", { error_id: arg });
67
+ const dir = join(process.cwd(), ".oalo", "heal");
68
+ mkdirSync(dir, { recursive: true });
69
+ const outPath = join(dir, `error-${b.error.id}.json`);
70
+ writeFileSync(outPath, JSON.stringify(b, null, 2) + "\n", "utf8");
71
+ const branch = b.branch || `oalo/fix-${b.error.id}`;
72
+ const git = spawnSync("git", ["checkout", "-B", branch], { encoding: "utf8" });
73
+ if (flags.json) {
74
+ return void console.log(JSON.stringify({ ok: true, bundle_path: outPath, branch, git_switched: git.status === 0 }, null, 2));
75
+ }
76
+ console.log(`Saved error bundle to ${outPath}`);
77
+ if (git.status === 0) console.log(`Switched local git branch to ${branch}`);
78
+ console.log(`Fix error #${b.error.id} (${b.error.title}), run tests, and push branch ${branch} to Forgejo.`);
79
+ return;
80
+ }
81
+
82
+ const r = await ch.call("apps:heal:start", {
83
+ error_id: arg,
84
+ ...(typeof flags.mode === "string" ? { mode: flags.mode } : {}),
85
+ runner: "base",
86
+ });
87
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
88
+ console.log(`Heal #${r.run?.id} ${r.run?.status} on branch ${r.run?.branch}`);
89
+ return;
90
+ }
91
+
92
+ if (sub === "approve") {
93
+ if (!arg) return fail("Usage: oalo heal approve <heal_id>", 2);
94
+ const r = await ch.call("apps:heal:approve", { id: arg });
95
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
96
+ console.log(`Heal #${r.run?.id} approved and merged (${r.run?.status}).`);
97
+ return;
98
+ }
99
+
100
+ if (sub === "reject") {
101
+ if (!arg) return fail("Usage: oalo heal reject <heal_id>", 2);
102
+ const r = await ch.call("apps:heal:reject", { id: arg });
103
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
104
+ console.log(`Heal #${r.run?.id} rejected and closed.`);
105
+ return;
106
+ }
107
+
108
+ if (sub === "tests") {
109
+ if (!app) return fail("Pass --app <slug>.", 2);
110
+ const r = await ch.call("apps:tests:run", { app, env: typeof flags.env === "string" ? flags.env : "dev" });
111
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
112
+ const run = r.run || {};
113
+ console.log(`${app} tests (${run.status}): ${run.passed_count} passed, ${run.failed_count} failed (${run.duration_ms}ms)`);
114
+ for (const tc of run.results || []) {
115
+ console.log(` ${tc.passed ? "ok " : "FAIL"} ${tc.name} (${tc.status ?? "err"}, ${tc.duration_ms}ms)`);
116
+ for (const f of tc.failures || []) console.log(` - ${f}`);
117
+ }
118
+ if (run.failed_count > 0) process.exitCode = 1;
119
+ return;
120
+ }
121
+
122
+ if (sub === "suggest-tests") {
123
+ if (!app) return fail("Pass --app <slug>.", 2);
124
+ const r = await ch.call("apps:tests:suggest", { app, auto: Boolean(flags.auto) });
125
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
126
+ console.log(`Suggestion #${r.suggestion?.id} [${r.suggestion?.status}]: ${r.suggestion?.title}`);
127
+ return;
128
+ }
129
+
130
+ return fail(`Unknown heal subcommand: ${sub}. Use list, inspect, run, approve, reject, tests, or suggest-tests.`, 2);
131
+ } catch (e) {
132
+ return fail(e.message, 1);
133
+ } finally {
134
+ ch.close();
135
+ }
136
+ }
137
+
138
+ function fail(msg, code) {
139
+ console.error(msg);
140
+ process.exitCode = code;
141
+ }
@@ -0,0 +1,127 @@
1
+ import { OaloChannel } from "../channel.js";
2
+ import { resolve as resolveConfig, controlPlane, HOW_TO_CONNECT } from "../config.js";
3
+ import { dim } from "../events.js";
4
+
5
+ /**
6
+ * `oalo inbox`: live team inbox actions (Q2: Live Copilot drafts, internal
7
+ * whisper notes, and org-wide `/` saved replies).
8
+ *
9
+ * oalo inbox list [--limit N] [--json]
10
+ * oalo inbox note <conversation-id> "<text>" [--json]
11
+ * oalo inbox draft <conversation-id> [--hint "<guidance>"] [--json]
12
+ * oalo inbox replies [list | set <shortcut> "<body...>" [--title "..."] | delete <id>] [--json]
13
+ */
14
+ export async function inbox(flags, rest, opts = {}) {
15
+ const sub = rest[1] || "list";
16
+ if (!["list", "note", "draft", "replies"].includes(sub)) {
17
+ return fail(USAGE, 2, flags);
18
+ }
19
+
20
+ const cfg = resolveConfig(flags);
21
+ const { url, token } = controlPlane(cfg);
22
+ if (!url || !token) return fail(`oalo inbox needs a CLI token.\n\n${HOW_TO_CONNECT}`, 2, flags);
23
+
24
+ const ch = (opts.channel || ((o) => new OaloChannel(o)))({ url, token });
25
+ try {
26
+ await ch.connect();
27
+ if (sub === "list") return await listConversations(ch, flags);
28
+ if (sub === "note") return await addNote(ch, rest.slice(2), flags);
29
+ if (sub === "draft") return await draftReply(ch, rest.slice(2), flags);
30
+ if (sub === "replies") return await savedReplies(ch, rest.slice(2), flags);
31
+ } catch (e) {
32
+ return fail(e.message, 1, flags);
33
+ } finally {
34
+ ch.close();
35
+ }
36
+ }
37
+
38
+ const USAGE = [
39
+ "usage: oalo inbox list [--limit N] [--json]",
40
+ ' oalo inbox note <conversation-id> "<internal whisper note>" [--json]',
41
+ ' oalo inbox draft <conversation-id> [--hint "<guidance>"] [--json]',
42
+ ' oalo inbox replies [list | set <shortcut> "<body...>" [--title "..."] | delete <id>] [--json]',
43
+ ].join("\n");
44
+
45
+ async function listConversations(ch, flags) {
46
+ const limit = Number(flags.limit) > 0 ? Number(flags.limit) : 20;
47
+ const r = await ch.call("conversations:inbox", { limit });
48
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
49
+ const convs = r?.conversations || r?.items || [];
50
+ if (!convs.length) return void console.log("no conversations in inbox");
51
+ for (const c of convs) {
52
+ const who = c.contact_name || c.external_ref || "anonymous";
53
+ const chName = c.channel || "web";
54
+ const preview = String(c.last_message || "").replace(/\s+/g, " ").slice(0, 60);
55
+ console.log(`${String(c.id).padEnd(8)} ${chName.padEnd(10)} ${String(who).slice(0, 24).padEnd(24)} ${dim(preview)}`);
56
+ }
57
+ }
58
+
59
+ async function addNote(ch, args, flags) {
60
+ const id = Number(args[0]);
61
+ const text = args.slice(1).join(" ").trim();
62
+ if (!Number.isInteger(id) || id <= 0 || !text) {
63
+ return fail('usage: oalo inbox note <conversation-id> "<internal whisper note>"', 2, flags);
64
+ }
65
+ const r = await ch.call("chat:bots:conversations:note", { id, text });
66
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
67
+ console.log(`added internal note to conversation #${id}`);
68
+ }
69
+
70
+ async function draftReply(ch, args, flags) {
71
+ const id = Number(args[0]);
72
+ if (!Number.isInteger(id) || id <= 0) {
73
+ return fail('usage: oalo inbox draft <conversation-id> [--hint "<guidance>"] [--json]', 2, flags);
74
+ }
75
+ const params = { id, ...(typeof flags.hint === "string" && flags.hint.trim() ? { hint: flags.hint.trim() } : {}) };
76
+ const r = await ch.call("chat:bots:conversations:draft_reply", params, 60_000);
77
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
78
+ console.log(r?.draft || "");
79
+ console.error(dim("draft only; nothing was sent to the customer"));
80
+ }
81
+
82
+ async function savedReplies(ch, args, flags) {
83
+ const action = args[0] || "list";
84
+ if (action === "list") {
85
+ const r = await ch.call("inbox:saved_replies:list", {});
86
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
87
+ const list = r?.replies || [];
88
+ if (!list.length) return void console.log("no saved replies yet");
89
+ for (const item of list) {
90
+ const snippet = String(item.body || "").replace(/\s+/g, " ").slice(0, 65);
91
+ console.log(`/${String(item.shortcut || "").padEnd(18)} ${item.id} ${dim(snippet)}`);
92
+ }
93
+ return;
94
+ }
95
+ if (action === "set") {
96
+ const shortcut = String(args[1] || "").replace(/^\/+/, "").trim();
97
+ const body = args.slice(2).join(" ").trim();
98
+ if (!shortcut || !body) {
99
+ return fail('usage: oalo inbox replies set <shortcut> "<body...>" [--title "..."]', 2, flags);
100
+ }
101
+ const params = {
102
+ shortcut,
103
+ body,
104
+ ...(typeof flags.title === "string" && flags.title.trim() ? { title: flags.title.trim() } : {}),
105
+ ...(typeof flags.id === "string" && flags.id.trim() ? { id: flags.id.trim() } : {}),
106
+ };
107
+ const r = await ch.call("inbox:saved_replies:upsert", params);
108
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
109
+ console.log(`saved /${shortcut} (${r?.reply?.id || "ok"})`);
110
+ return;
111
+ }
112
+ if (action === "delete") {
113
+ const id = args[1];
114
+ if (!id) return fail("usage: oalo inbox replies delete <id>", 2, flags);
115
+ const r = await ch.call("inbox:saved_replies:delete", { id });
116
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
117
+ console.log(`deleted saved reply ${id}`);
118
+ return;
119
+ }
120
+ return fail(USAGE, 2, flags);
121
+ }
122
+
123
+ function fail(msg, code, flags) {
124
+ if (flags?.json) console.log(JSON.stringify({ error: msg }));
125
+ else console.error(msg);
126
+ process.exitCode = code;
127
+ }
@@ -126,7 +126,7 @@ async function status(flags, opts = {}) {
126
126
  const makeChannel = opts.channel || ((o) => new OaloChannel(o));
127
127
 
128
128
  if (!cfg.serverUrl) {
129
- console.log("not linked. run: oalo link --server <url> --token <token>");
129
+ console.log("not linked. run: oalo login <workspace> (or: oalo link --server <url> [--token <sync-token>] [--cli-token <cli-token>])");
130
130
  process.exitCode = 1;
131
131
  return;
132
132
  }