orca-flow 0.0.0-stage → 1.3.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/LICENSE +21 -0
  3. package/README.md +86 -2
  4. package/ROADMAP.md +83 -0
  5. package/bin/oflow.mjs +80 -0
  6. package/package.json +52 -4
  7. package/references/checklists/migrations.md +8 -0
  8. package/references/checklists/performance.md +8 -0
  9. package/references/checklists/security.md +9 -0
  10. package/references/checklists/ui-a11y.md +8 -0
  11. package/site/app.js +271 -0
  12. package/site/cinema.js +125 -0
  13. package/site/data.js +243 -0
  14. package/site/favicon.svg +14 -0
  15. package/site/i18n.js +86 -0
  16. package/site/index.html +306 -0
  17. package/site/motion.js +200 -0
  18. package/site/playbook.js +221 -0
  19. package/site/styles.css +244 -0
  20. package/skills/architecture/SKILL.md +17 -0
  21. package/skills/build-ticket/SKILL.md +29 -0
  22. package/skills/debug/SKILL.md +17 -0
  23. package/skills/grill-spec/SKILL.md +26 -0
  24. package/skills/lead-effort/SKILL.md +26 -0
  25. package/skills/proto-spike/SKILL.md +17 -0
  26. package/skills/resume/SKILL.md +26 -0
  27. package/skills/retro-guardrail/SKILL.md +19 -0
  28. package/skills/setup-project/SKILL.md +26 -0
  29. package/skills/slice-tickets/SKILL.md +31 -0
  30. package/skills/verify-app/SKILL.md +22 -0
  31. package/src/agents.mjs +278 -0
  32. package/src/checkpoint.mjs +160 -0
  33. package/src/config.mjs +140 -0
  34. package/src/doctor.mjs +190 -0
  35. package/src/gate.mjs +205 -0
  36. package/src/git.mjs +149 -0
  37. package/src/hook.mjs +168 -0
  38. package/src/init.mjs +149 -0
  39. package/src/install.mjs +192 -0
  40. package/src/lock.mjs +80 -0
  41. package/src/pr.mjs +120 -0
  42. package/src/review.mjs +254 -0
  43. package/src/seal.mjs +200 -0
  44. package/src/site-server.mjs +57 -0
  45. package/src/stats.mjs +257 -0
  46. package/src/status.mjs +234 -0
  47. package/src/tracker-github.mjs +196 -0
  48. package/src/wave.mjs +193 -0
  49. package/src/worker.mjs +297 -0
package/src/stats.mjs ADDED
@@ -0,0 +1,257 @@
1
+ import { createReadStream, existsSync, readdirSync, statSync } from "node:fs";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
+ import { createInterface } from "node:readline";
4
+ import { parseArgs } from "node:util";
5
+ import { loadConfig } from "./config.mjs";
6
+
7
+ const BUILTIN_COMMANDS = new Set([
8
+ "clear", "compact", "config", "context", "cost", "doctor", "exit", "help",
9
+ "login", "logout", "mcp", "memory", "model", "permissions", "resume", "rewind", "status", "usage",
10
+ ]);
11
+
12
+ function classifyCommand(cmd, target) {
13
+ if (!cmd) return;
14
+ if (/\boflow\s+gate\b|\bnpm\s+run\s+check:changed\b/.test(cmd)) target.gate++;
15
+ if (/\bnpm\s+run\s+check\b|\bpytest\b|\bgo\s+test\b|\bcargo\s+test\b/.test(cmd)) target.check++;
16
+ if (/\boflow\s+review\b|\bnpm\s+run\s+review(?::claude(?::deep)?)?\b/.test(cmd)) target.review++;
17
+ }
18
+
19
+ function blankStats() {
20
+ return { peak: 0, totalInput: 0, cachedInput: 0, gate: 0, check: 0, review: 0, subagents: 0, skills: new Set() };
21
+ }
22
+
23
+ function calcCacheHitRate(stat) {
24
+ if (!stat.totalInput) return 0;
25
+ return Math.min(1, Math.round((stat.cachedInput / stat.totalInput) * 1000) / 1000);
26
+ }
27
+
28
+ function collectSlashSkills(content, skills) {
29
+ const blocks = typeof content === "string"
30
+ ? [content]
31
+ : (Array.isArray(content) ? content : []).filter((b) => b.type === "text").map((b) => b.text ?? "");
32
+ for (const text of blocks) {
33
+ for (const [, name] of text.matchAll(/<command-name>\/([\w:-]+)<\/command-name>/g)) {
34
+ if (!BUILTIN_COMMANDS.has(name)) skills.add(name);
35
+ }
36
+ }
37
+ }
38
+
39
+ export async function analyzeTranscript(transcriptPath, { cwd } = {}) {
40
+ const abs = resolve(transcriptPath);
41
+ if (!existsSync(abs)) throw new Error(`Transcript not found: ${abs}`);
42
+
43
+ const subDir = join(dirname(abs), basename(abs, ".jsonl"), "subagents");
44
+ const subFiles = existsSync(subDir)
45
+ ? readdirSync(subDir).filter((f) => /^agent-.*\.jsonl$/.test(f)).map((f) => join(subDir, f))
46
+ : [];
47
+
48
+ const main = blankStats();
49
+ const subagents = blankStats();
50
+ const seenIds = new Set();
51
+ let vendor = "unknown";
52
+
53
+ for (const file of [abs, ...subFiles]) {
54
+ const rl = createInterface({ input: createReadStream(file), crlfDelay: Infinity });
55
+ for await (const line of rl) {
56
+ if (!line.trim()) continue;
57
+ const rec = JSON.parse(line);
58
+ const isSub = file !== abs || rec.isSidechain === true;
59
+ const target = isSub ? subagents : main;
60
+
61
+ if (rec.type === "PLANNER_RESPONSE") {
62
+ vendor = "antigravity";
63
+ const inp = rec.input_tokens ?? 0;
64
+ const cached = rec.cache_read_tokens ?? 0;
65
+ target.peak = Math.max(target.peak, inp);
66
+ target.totalInput += inp;
67
+ target.cachedInput += cached;
68
+ for (const call of Array.isArray(rec.tool_calls) ? rec.tool_calls : []) {
69
+ if (call.name === "invoke_subagent") target.subagents++;
70
+ if (call.name === "run_command") classifyCommand(call.args?.CommandLine, target);
71
+ if (call.name === "read_file" && typeof call.args?.Path === "string") {
72
+ const m = call.args.Path.match(/skills\/([^/]+)\/SKILL\.md$/);
73
+ if (m) target.skills.add(m[1]);
74
+ }
75
+ }
76
+ continue;
77
+ }
78
+
79
+ if (rec.type === "event_msg" || rec.type === "response_item" || rec.type === "turn_context") {
80
+ vendor = vendor === "unknown" ? "codex" : vendor;
81
+ if (rec.type === "event_msg" && rec.payload?.type === "token_count") {
82
+ const info = rec.payload?.info;
83
+ const last = info?.last_token_usage;
84
+ const ctx = last
85
+ ? (last.input_tokens ?? 0) + (last.cached_input_tokens ?? 0)
86
+ : (info?.total_token_usage?.input_tokens ?? 0);
87
+ target.peak = Math.max(target.peak, ctx);
88
+ if (last) {
89
+ target.totalInput += ctx;
90
+ target.cachedInput += last.cached_input_tokens ?? 0;
91
+ }
92
+ } else if (rec.type === "response_item" && rec.payload?.type === "function_call") {
93
+ let args = {};
94
+ if (typeof rec.payload.arguments === "string") {
95
+ try { args = JSON.parse(rec.payload.arguments); } catch { args = {}; }
96
+ } else if (rec.payload.arguments && typeof rec.payload.arguments === "object") {
97
+ args = rec.payload.arguments;
98
+ }
99
+ const name = rec.payload.name;
100
+ if (name === "exec_command" || name === "shell" || name === "shell_command") {
101
+ const cmd = args.cmd || (Array.isArray(args.command) ? args.command.join(" ") : args.command) || "";
102
+ classifyCommand(cmd, target);
103
+ } else if (name === "spawn_agent") {
104
+ target.subagents++;
105
+ }
106
+ }
107
+ continue;
108
+ }
109
+
110
+ if (rec.type === "user" || rec.type === "assistant") {
111
+ vendor = vendor === "unknown" ? "claude" : vendor;
112
+ const { content, usage } = rec.message ?? {};
113
+ if (rec.type === "user") {
114
+ collectSlashSkills(content, target.skills);
115
+ continue;
116
+ }
117
+ const cached = usage?.cache_read_input_tokens ?? 0;
118
+ const ctx = (usage?.input_tokens ?? 0) + (usage?.cache_creation_input_tokens ?? 0) + cached;
119
+ target.peak = Math.max(target.peak, ctx);
120
+ target.totalInput += ctx;
121
+ target.cachedInput += cached;
122
+ for (const call of Array.isArray(content) ? content : []) {
123
+ if (call.type !== "tool_use" || (call.id && seenIds.has(call.id))) continue;
124
+ if (call.id) seenIds.add(call.id);
125
+ if (call.name === "Agent" || call.name === "Task") target.subagents++;
126
+ if (call.name === "Skill" && call.input?.skill) target.skills.add(call.input.skill);
127
+ if (call.name === "Bash") classifyCommand(call.input?.command, target);
128
+ }
129
+ }
130
+ }
131
+ }
132
+
133
+ let tokenBudget = 150000;
134
+ let maxGateRuns = 2;
135
+ try {
136
+ const { config } = loadConfig(cwd ?? dirname(abs));
137
+ tokenBudget = config.agents?.tokenBudget ?? 150000;
138
+ maxGateRuns = config.agents?.maxGateRuns ?? 2;
139
+ } catch {
140
+ // Fall back to default thresholds outside a repo.
141
+ }
142
+
143
+ const breaches = [];
144
+ if (main.peak > tokenBudget) breaches.push(`peak=${main.peak}>${tokenBudget}`);
145
+ if (main.gate > maxGateRuns) breaches.push(`gate=${main.gate}>${maxGateRuns}`);
146
+ if (main.subagents > 4) breaches.push(`subagents=${main.subagents}>4`);
147
+
148
+ return {
149
+ vendor,
150
+ main: { ...main, cacheHitRate: calcCacheHitRate(main), skills: [...main.skills].sort() },
151
+ subagents: { ...subagents, cacheHitRate: calcCacheHitRate(subagents), skills: [...subagents.skills].sort() },
152
+ breaches,
153
+ };
154
+ }
155
+
156
+ function collectTranscriptFiles(dir) {
157
+ const found = [];
158
+ for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
159
+ const full = join(dir, entry.name);
160
+ if (entry.isDirectory()) {
161
+ if (entry.name === "subagents") continue;
162
+ found.push(...collectTranscriptFiles(full));
163
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
164
+ found.push(full);
165
+ }
166
+ }
167
+ return found;
168
+ }
169
+
170
+ /**
171
+ * Aggregate session metrics across a transcript directory and compare ROI by vendor.
172
+ */
173
+ export async function analyzeDirectory(dirPath, { cwd } = {}) {
174
+ const absDir = resolve(dirPath);
175
+ if (!existsSync(absDir) || !statSync(absDir).isDirectory()) {
176
+ throw new Error(`Directory not found: ${absDir}`);
177
+ }
178
+ const files = collectTranscriptFiles(absDir);
179
+ if (!files.length) {
180
+ return { dir: absDir, totalSessions: 0, totalBreaches: 0, vendors: {}, sessions: [] };
181
+ }
182
+
183
+ const sessions = [];
184
+ const grouped = new Map();
185
+ let totalBreaches = 0;
186
+
187
+ for (const file of files) {
188
+ const res = await analyzeTranscript(file, { cwd });
189
+ sessions.push({ file, ...res });
190
+ if (res.breaches.length > 0) totalBreaches++;
191
+ if (!grouped.has(res.vendor)) grouped.set(res.vendor, []);
192
+ grouped.get(res.vendor).push(res);
193
+ }
194
+
195
+ const vendors = {};
196
+ for (const [vendor, list] of [...grouped.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
197
+ const n = list.length;
198
+ const peaks = list.map((s) => s.main.peak);
199
+ const cacheSum = list.reduce((acc, s) => acc + s.main.cacheHitRate, 0);
200
+ const gateSum = list.reduce((acc, s) => acc + s.main.gate, 0);
201
+ const firstPass = list.filter((s) => s.main.gate <= 1).length;
202
+ const budgetOk = list.filter((s) => s.breaches.length === 0).length;
203
+ vendors[vendor] = {
204
+ sessions: n,
205
+ avgPeak: Math.round(peaks.reduce((a, b) => a + b, 0) / n),
206
+ maxPeak: Math.max(...peaks),
207
+ avgCacheHitPct: Math.round((cacheSum / n) * 100),
208
+ firstPassGatePct: Math.round((firstPass / n) * 100),
209
+ avgGates: Math.round((gateSum / n) * 10) / 10,
210
+ budgetPassPct: Math.round((budgetOk / n) * 100),
211
+ };
212
+ }
213
+
214
+ return { dir: absDir, totalSessions: sessions.length, totalBreaches, vendors, sessions };
215
+ }
216
+
217
+ export async function runStats(argv, { cwd = process.cwd() } = {}) {
218
+ const { values, positionals } = parseArgs({
219
+ args: argv,
220
+ allowPositionals: true,
221
+ options: {
222
+ dir: { type: "string" },
223
+ compare: { type: "boolean", default: false },
224
+ strict: { type: "boolean", default: false },
225
+ json: { type: "boolean", default: false },
226
+ },
227
+ });
228
+ const target = positionals[0];
229
+ const dirArg = values.dir || (target && existsSync(resolve(cwd, target)) && statSync(resolve(cwd, target)).isDirectory() ? target : null);
230
+ if (dirArg) {
231
+ const report = await analyzeDirectory(resolve(cwd, dirArg), { cwd });
232
+ if (values.json) {
233
+ console.log(JSON.stringify(report, null, 2));
234
+ } else if (!report.totalSessions) {
235
+ console.log(`No .jsonl transcripts found in ${report.dir}`);
236
+ } else {
237
+ console.log(`Vendor ROI (${report.totalSessions} session(s), ${report.totalBreaches} breach(es))`);
238
+ console.log("Vendor | Sessions | Avg Peak | Cache Hit | 1st-Pass Gate | Budget OK");
239
+ for (const [vendor, v] of Object.entries(report.vendors)) {
240
+ console.log(`${vendor.padEnd(13)} | ${String(v.sessions).padEnd(8)} | ${String(v.avgPeak).padEnd(8)} | ${`${v.avgCacheHitPct}%`.padEnd(9)} | ${`${v.firstPassGatePct}%`.padEnd(13)} | ${v.budgetPassPct}%`);
241
+ }
242
+ }
243
+ return values.strict && report.totalBreaches > 0 ? 2 : 0;
244
+ }
245
+
246
+ if (!target) throw new Error("Usage: oflow stats (<transcript.jsonl> | --dir <dir> [--compare]) [--strict] [--json]");
247
+ const res = await analyzeTranscript(resolve(cwd, target), { cwd });
248
+ if (values.json) {
249
+ console.log(JSON.stringify(res, null, 2));
250
+ } else {
251
+ console.log(`Vendor: ${res.vendor}`);
252
+ console.log(`Main thread | peak=${res.main.peak} | cache=${Math.round(res.main.cacheHitRate * 100)}% | gate=${res.main.gate} | check=${res.main.check} | review=${res.main.review} | subagents=${res.main.subagents} | skills=${res.main.skills.join(",") || "none"}`);
253
+ console.log(`Subagents | peak=${res.subagents.peak} | gate=${res.subagents.gate} | skills=${res.subagents.skills.join(",") || "none"}`);
254
+ console.log(res.breaches.length ? `BUDGET: breach (${res.breaches.join(", ")})` : "BUDGET: ok");
255
+ }
256
+ return values.strict && res.breaches.length ? 2 : 0;
257
+ }
package/src/status.mjs ADDED
@@ -0,0 +1,234 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import { KIT_VERSION, loadConfig } from "./config.mjs";
5
+ import { capturePosition, git, gitCommonDir } from "./git.mjs";
6
+ import { checkVerdict } from "./review.mjs";
7
+ import { findScopeOverlap, parseTouches } from "./wave.mjs";
8
+
9
+ function extractField(text, name) {
10
+ const m = text.match(new RegExp(`^(?:\\*\\*)?${name}:(?:\\*\\*)?(.*)$`, "m"));
11
+ return m ? m[1].trim() : null;
12
+ }
13
+
14
+ function parseBlockers(raw) {
15
+ if (!raw || /^(none|-|n\/a)$/i.test(raw)) return [];
16
+ const out = [];
17
+ for (const token of raw.split(/[\s,]+/)) {
18
+ const clean = token.replace(/^#/, "").trim();
19
+ if (clean) out.push(clean);
20
+ }
21
+ return out;
22
+ }
23
+
24
+ function resolveBlockerTicket(token, tickets) {
25
+ const padded = /^\d+$/.test(token) ? token.padStart(2, "0") : token;
26
+ return tickets.find(
27
+ (t) =>
28
+ t.fileName === token ||
29
+ t.fileName.startsWith(`${padded}-`) ||
30
+ t.fileName.startsWith(`${token}-`) ||
31
+ t.id === padded ||
32
+ t.id === token,
33
+ );
34
+ }
35
+
36
+ /**
37
+ * Scan .scratch/<effort>/issues/*.md tickets, validate DAG dependencies, and classify states.
38
+ */
39
+ export function scanEfforts(root, trackerConfig = { type: "scratch", dir: ".scratch" }) {
40
+ if (trackerConfig.type !== "scratch") return [];
41
+ const dirRel = trackerConfig.dir || ".scratch";
42
+ const trackerDir = join(root, dirRel);
43
+ if (!existsSync(trackerDir)) return [];
44
+
45
+ const efforts = [];
46
+ const entries = readdirSync(trackerDir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
47
+
48
+ for (const entry of entries) {
49
+ if (!entry.isDirectory() || entry.name.startsWith("_") || entry.name.startsWith(".")) continue;
50
+ const issuesDir = join(trackerDir, entry.name, "issues");
51
+ if (!existsSync(issuesDir)) continue;
52
+
53
+ const files = readdirSync(issuesDir).filter((f) => f.endsWith(".md")).sort();
54
+ const tickets = files.map((fileName) => {
55
+ const text = readFileSync(join(issuesDir, fileName), "utf8");
56
+ const m = fileName.match(/^(\d+)-/);
57
+ const status = extractField(text, "Status") || "open";
58
+ return {
59
+ id: m ? m[1] : basename(fileName, ".md"),
60
+ fileName,
61
+ file: `${dirRel}/${entry.name}/issues/${fileName}`.replace(/\\/g, "/"),
62
+ status,
63
+ done: /^(done|merged|resolved)\b/i.test(status),
64
+ active: /^(in[-_ ]?progress|running|active|review|in[-_ ]?review)\b/i.test(status),
65
+ agent: extractField(text, "Agent") || "auto",
66
+ touches: parseTouches(extractField(text, "Touches")),
67
+ rawBlockers: parseBlockers(extractField(text, "Blocked by")),
68
+ resolvedBlockers: [],
69
+ missingBlockers: [],
70
+ inCycle: false,
71
+ state: "ready",
72
+ };
73
+ });
74
+
75
+ const byFile = new Map(tickets.map((t) => [t.fileName, t]));
76
+ for (const t of tickets) {
77
+ for (const tok of t.rawBlockers) {
78
+ const hit = resolveBlockerTicket(tok, tickets);
79
+ if (hit) t.resolvedBlockers.push(hit.fileName);
80
+ else t.missingBlockers.push(tok);
81
+ }
82
+ }
83
+
84
+ const color = new Map();
85
+ const stack = [];
86
+ const cycles = [];
87
+ const seenCycles = new Set();
88
+
89
+ function dfs(fileName) {
90
+ color.set(fileName, 1);
91
+ stack.push(fileName);
92
+ const node = byFile.get(fileName);
93
+ for (const dep of node?.resolvedBlockers ?? []) {
94
+ const c = color.get(dep) ?? 0;
95
+ if (c === 1) {
96
+ const idx = stack.indexOf(dep);
97
+ const loop = [...stack.slice(idx), dep];
98
+ const label = loop.map((f) => byFile.get(f)?.id ?? f).join(" -> ");
99
+ if (!seenCycles.has(label)) {
100
+ seenCycles.add(label);
101
+ cycles.push(label);
102
+ }
103
+ for (const f of loop) {
104
+ const item = byFile.get(f);
105
+ if (item) item.inCycle = true;
106
+ }
107
+ } else if (c === 0) {
108
+ dfs(dep);
109
+ }
110
+ }
111
+ stack.pop();
112
+ color.set(fileName, 2);
113
+ }
114
+
115
+ for (const t of tickets) {
116
+ if ((color.get(t.fileName) ?? 0) === 0) dfs(t.fileName);
117
+ }
118
+
119
+ const counts = { total: tickets.length, done: 0, active: 0, ready: 0, blocked: 0, invalid: 0 };
120
+ for (const t of tickets) {
121
+ if (t.done) t.state = "done";
122
+ else if (t.inCycle || t.missingBlockers.length > 0) t.state = "invalid";
123
+ else if (t.resolvedBlockers.some((dep) => !byFile.get(dep)?.done)) t.state = "blocked";
124
+ else if (t.active) t.state = "active";
125
+ else t.state = "ready";
126
+ counts[t.state]++;
127
+ }
128
+
129
+ const live = tickets.filter((t) => t.state === "active" || t.state === "ready");
130
+ const touchConflicts = [];
131
+ for (let i = 0; i < live.length; i++) {
132
+ for (let j = i + 1; j < live.length; j++) {
133
+ const hit = findScopeOverlap(live[i].touches, live[j].touches);
134
+ if (hit) {
135
+ touchConflicts.push({
136
+ a: live[i].id,
137
+ b: live[j].id,
138
+ fileA: live[i].file,
139
+ fileB: live[j].file,
140
+ overlap: `${hit.patternA} <-> ${hit.patternB}`,
141
+ });
142
+ }
143
+ }
144
+ }
145
+
146
+ efforts.push({ effort: entry.name, tickets, counts, cycles, touchConflicts });
147
+ }
148
+ return efforts;
149
+ }
150
+
151
+ function readCheckpointsSafe(root) {
152
+ try {
153
+ const dir = join(gitCommonDir(root), "orca-flow", "checkpoints");
154
+ if (!existsSync(dir)) return [];
155
+ return readdirSync(dir)
156
+ .filter((f) => f.endsWith(".json"))
157
+ .sort()
158
+ .map((f) => {
159
+ const rec = JSON.parse(readFileSync(join(dir, f), "utf8"));
160
+ return { slug: basename(f, ".json"), phase: rec.phase, agent: rec.agent, branch: rec.branch, head: rec.head };
161
+ });
162
+ } catch {
163
+ return [];
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Collect read-only repository status, verdict, checkpoints, and effort ticket DAGs.
169
+ */
170
+ export function collectStatus(cwd = process.cwd()) {
171
+ const { root, exists, config } = loadConfig(cwd);
172
+ let position;
173
+ try {
174
+ position = capturePosition(root);
175
+ } catch {
176
+ const branch = git(root, ["rev-parse", "--abbrev-ref", "HEAD"], { allowFail: true })?.trim() || "UNBORN";
177
+ position = { branch, head: null, worktree: root, dirty: { changed: [], untracked: [] }, upstream: null, pushed: false };
178
+ }
179
+
180
+ let verdict;
181
+ try {
182
+ verdict = checkVerdict({ cwd: root });
183
+ } catch (err) {
184
+ verdict = { state: "unverified", branch: position.branch, detail: err.message };
185
+ }
186
+
187
+ const checkpoints = readCheckpointsSafe(root);
188
+ const efforts = scanEfforts(root, config.tracker);
189
+
190
+ return {
191
+ version: KIT_VERSION,
192
+ project: config.project,
193
+ configExists: exists,
194
+ topology: config.agents.topology,
195
+ allowedWorkers: config.agents.allowedWorkers,
196
+ defaultLead: config.agents.defaultLead,
197
+ position,
198
+ verdict,
199
+ checkpoints,
200
+ efforts,
201
+ };
202
+ }
203
+
204
+ export async function runStatus(argv = [], { cwd = process.cwd() } = {}) {
205
+ const { values } = parseArgs({ args: argv, options: { json: { type: "boolean", default: false } } });
206
+ const res = collectStatus(cwd);
207
+ if (values.json) {
208
+ console.log(JSON.stringify(res, null, 2));
209
+ } else {
210
+ const dirty = res.position.dirty.changed.length + res.position.dirty.untracked.length;
211
+ console.log(`${res.project} (orca-flow v${res.version})`);
212
+ console.log(`Branch: ${res.position.branch} (${dirty === 0 ? "clean" : `${dirty} dirty`}) | Verdict: ${res.verdict.state}${res.verdict.stored?.by ? ` (${res.verdict.stored.by})` : ""}`);
213
+ console.log(`Agents: ${res.topology} [${res.allowedWorkers.join(", ")}] (lead: ${res.defaultLead}) | Checkpoints: ${res.checkpoints.length}`);
214
+ if (!res.efforts.length) {
215
+ console.log("Efforts: none");
216
+ } else {
217
+ for (const e of res.efforts) {
218
+ const activeStr = e.counts.active ? `, ${e.counts.active} active` : "";
219
+ const extra = e.counts.invalid ? `, ${e.counts.invalid} invalid` : "";
220
+ console.log(`Effort ${e.effort}: ${e.counts.done} done${activeStr}, ${e.counts.ready} ready, ${e.counts.blocked} blocked${extra}`);
221
+ for (const t of e.tickets.filter((item) => item.state === "ready")) {
222
+ const scope = t.touches.length ? ` [touches: ${t.touches.join(", ")}]` : "";
223
+ console.log(` ready -> oflow worker ${t.file}${scope}`);
224
+ }
225
+ for (const c of e.cycles) console.log(` CYCLE -> ${c}`);
226
+ for (const ov of e.touchConflicts) console.log(` OVERLAP -> ${ov.a} & ${ov.b} (${ov.overlap})`);
227
+ for (const t of e.tickets.filter((item) => item.missingBlockers.length > 0)) {
228
+ console.log(` ERROR -> ${t.file} missing blocker(s): ${t.missingBlockers.join(", ")}`);
229
+ }
230
+ }
231
+ }
232
+ }
233
+ return res.efforts.some((e) => e.cycles.length > 0) ? 2 : 0;
234
+ }
@@ -0,0 +1,196 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { parseArgs } from "node:util";
5
+ import { loadConfig } from "./config.mjs";
6
+ import { gitCommonDir } from "./git.mjs";
7
+ import { writeAtomic } from "./lock.mjs";
8
+ import { scanEfforts } from "./status.mjs";
9
+
10
+ function extractField(text, name) {
11
+ const m = text.match(new RegExp(`^(?:\\*\\*)?${name}:(?:\\*\\*)?(.*)$`, "m"));
12
+ return m ? m[1].trim() : null;
13
+ }
14
+
15
+ /**
16
+ * Parse a GitHub issue token (#42, gh:42, issue:42) into a positive integer or null.
17
+ */
18
+ export function parseGithubIssueRef(raw) {
19
+ const m = String(raw || "").trim().match(/^(?:#|gh:|issue:)(\d+)$/i);
20
+ if (!m) return null;
21
+ const num = Number.parseInt(m[1], 10);
22
+ return num > 0 ? num : null;
23
+ }
24
+
25
+ export function defaultGhRunner(args, { cwd = process.cwd() } = {}) {
26
+ return execFileSync("gh", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
27
+ }
28
+
29
+ export function fetchGithubIssue(issueNumber, { cwd = process.cwd(), ghRunner = defaultGhRunner } = {}) {
30
+ const raw = ghRunner(
31
+ ["issue", "view", String(issueNumber), "--json", "number,title,body,state,labels,url"],
32
+ { cwd },
33
+ );
34
+ return JSON.parse(raw);
35
+ }
36
+
37
+ function parseIssueBlockers(raw) {
38
+ if (!raw || /^(none|-|n\/a)$/i.test(raw)) return [];
39
+ const nums = [];
40
+ for (const tok of raw.split(/[\s,]+/)) {
41
+ const m = tok.trim().match(/^(?:#|gh:|issue:)?(\d+)$/i);
42
+ if (m) nums.push(Number.parseInt(m[1], 10));
43
+ }
44
+ return [...new Set(nums)];
45
+ }
46
+
47
+ /**
48
+ * Fetch a GitHub issue, enforce blockers/open state, and materialize a ticket under .git/orca-flow/.
49
+ */
50
+ export function materializeGithubIssue(issueNumber, { cwd = process.cwd(), force = false, ghRunner = defaultGhRunner } = {}) {
51
+ const { root } = loadConfig(cwd);
52
+ const issue = fetchGithubIssue(issueNumber, { cwd: root, ghRunner });
53
+ const state = String(issue.state || "OPEN").toUpperCase();
54
+ if (!force && state === "CLOSED") {
55
+ throw new Error(`GitHub issue #${issue.number} is already CLOSED (pass --force to dispatch anyway).`);
56
+ }
57
+
58
+ const body = String(issue.body ?? "");
59
+ const labelAgent = (issue.labels ?? [])
60
+ .map((l) => (typeof l === "string" ? l : l?.name ?? ""))
61
+ .find((n) => /^agent:/i.test(n))
62
+ ?.slice(6)
63
+ ?.trim();
64
+ const agent = extractField(body, "Agent") || labelAgent || "auto";
65
+ const model = extractField(body, "Model");
66
+ const touches = extractField(body, "Touches");
67
+
68
+ const blockerNums = parseIssueBlockers(extractField(body, "Blocked by"));
69
+ if (!force && blockerNums.length > 0) {
70
+ const openBlockers = [];
71
+ for (const depNum of blockerNums) {
72
+ const dep = fetchGithubIssue(depNum, { cwd: root, ghRunner });
73
+ const depState = String(dep.state || "OPEN").toUpperCase();
74
+ if (depState !== "CLOSED") openBlockers.push(`#${depNum} (${depState})`);
75
+ }
76
+ if (openBlockers.length > 0) {
77
+ throw new Error(`GitHub issue #${issue.number} is blocked by open issue(s): ${openBlockers.join(", ")}.`);
78
+ }
79
+ }
80
+
81
+ const lines = [
82
+ `# #${issue.number}: ${issue.title || `Issue ${issue.number}`}`,
83
+ "",
84
+ `Agent: ${agent}`,
85
+ ...(model ? [`Model: ${model}`] : []),
86
+ ...(touches ? [`Touches: ${touches}`] : []),
87
+ "Blocked by: none",
88
+ "Status: open",
89
+ ...(issue.url ? [`URL: ${issue.url}`] : []),
90
+ "",
91
+ body.trim(),
92
+ "",
93
+ ];
94
+ const ticketPath = join(gitCommonDir(root), "orca-flow", "github-issues", `issue-${issue.number}.md`);
95
+ writeAtomic(ticketPath, lines.join("\n"));
96
+
97
+ return {
98
+ issue,
99
+ ticketPath,
100
+ name: `issue-${issue.number}`,
101
+ portOffset: (issue.number % 100) || 1,
102
+ };
103
+ }
104
+
105
+ function rewriteBodyForGithub(text, resolvedBlockers, idToGhNum) {
106
+ if (!resolvedBlockers.length) return text;
107
+ const mapped = resolvedBlockers.map((file) => idToGhNum.get(file)).filter(Boolean);
108
+ if (!mapped.length) return text;
109
+ const line = `Blocked by: ${mapped.map((n) => `#${n}`).join(", ")}`;
110
+ if (/^(?:\*\*)?Blocked by:(?:\*\*)?.*$/m.test(text)) {
111
+ return text.replace(/^(?:\*\*)?Blocked by:(?:\*\*)?.*$/m, line);
112
+ }
113
+ return `${text.trimEnd()}\n\n${line}\n`;
114
+ }
115
+
116
+ function stampGithubField(text, issueNum) {
117
+ const tag = `GitHub: #${issueNum}`;
118
+ if (/^GitHub:\s*#?\d+/m.test(text)) return text.replace(/^GitHub:\s*#?\d+.*$/m, tag);
119
+ if (/^#\s+.*$/m.test(text)) return text.replace(/^(#\s+.*)$/m, `$1\n\n${tag}`);
120
+ return `${tag}\n${text}`;
121
+ }
122
+
123
+ /**
124
+ * Idempotently sync .scratch/<effort>/issues/*.md vertical slices to GitHub Issues.
125
+ */
126
+ export function syncSlicesToGithub({ cwd = process.cwd(), effort, dryRun = false, ghRunner = defaultGhRunner } = {}) {
127
+ const { root, config } = loadConfig(cwd);
128
+ let efforts = scanEfforts(root, config.tracker);
129
+ if (effort) {
130
+ efforts = efforts.filter((e) => e.effort === effort);
131
+ }
132
+ if (!efforts.length) {
133
+ throw new Error(`No matching efforts found under ${config.tracker.dir || ".scratch"}.`);
134
+ }
135
+
136
+ const items = [];
137
+ for (const e of efforts) {
138
+ const idToGhNum = new Map();
139
+ for (const t of e.tickets) {
140
+ const absPath = join(root, t.file);
141
+ const text = readFileSync(absPath, "utf8");
142
+ const existing = extractField(text, "GitHub")?.match(/#?(\d+)/);
143
+ if (existing) {
144
+ const issueNumber = Number.parseInt(existing[1], 10);
145
+ idToGhNum.set(t.fileName, issueNumber);
146
+ items.push({ file: t.file, status: "already-synced", issueNumber });
147
+ continue;
148
+ }
149
+
150
+ const heading = text.match(/^#\s+(.+)$/m)?.[1]?.trim() || `${e.effort}/${t.id}`;
151
+ const syncedBody = rewriteBodyForGithub(text, t.resolvedBlockers, idToGhNum);
152
+ const ghArgs = ["issue", "create", "--title", `[${e.effort}/${t.id}] ${heading}`, "--body", syncedBody];
153
+ if (dryRun) {
154
+ items.push({ file: t.file, status: "planned", ghArgs });
155
+ continue;
156
+ }
157
+
158
+ const out = ghRunner(ghArgs, { cwd: root }).trim();
159
+ const createdMatch = out.match(/(?:\/issues\/|#)(\d+)\b/);
160
+ if (!createdMatch) {
161
+ throw new Error(`Unable to parse created GitHub issue number from output: "${out}"`);
162
+ }
163
+ const issueNumber = Number.parseInt(createdMatch[1], 10);
164
+ idToGhNum.set(t.fileName, issueNumber);
165
+ writeAtomic(absPath, stampGithubField(text, issueNumber));
166
+ items.push({ file: t.file, status: "created", issueNumber, url: out });
167
+ }
168
+ }
169
+
170
+ return { root, dryRun, items };
171
+ }
172
+
173
+ export async function runSlice(argv = [], { cwd = process.cwd(), ghRunner = defaultGhRunner } = {}) {
174
+ const { values } = parseArgs({
175
+ args: argv,
176
+ options: {
177
+ "sync-github": { type: "boolean", default: false },
178
+ effort: { type: "string" },
179
+ "dry-run": { type: "boolean", default: false },
180
+ json: { type: "boolean", default: false },
181
+ },
182
+ });
183
+ if (!values["sync-github"]) {
184
+ throw new Error("Usage: oflow slice --sync-github [--effort <name>] [--dry-run] [--json]");
185
+ }
186
+ const res = syncSlicesToGithub({ cwd, effort: values.effort, dryRun: values["dry-run"], ghRunner });
187
+ if (values.json) {
188
+ console.log(JSON.stringify(res, null, 2));
189
+ } else {
190
+ for (const item of res.items) {
191
+ const ref = item.issueNumber ? ` -> #${item.issueNumber}` : "";
192
+ console.log(` ${item.status.padEnd(15)} ${item.file}${ref}`);
193
+ }
194
+ }
195
+ return 0;
196
+ }