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
@@ -0,0 +1,19 @@
1
+ ---
2
+ name: retro-guardrail
3
+ version: 1.3.0
4
+ description: Audit completed effort sessions with oflow stats and encode repeated mistakes into gates, ratchets, lint rules, or tests instead of prose.
5
+ disable-model-invocation: true
6
+ ---
7
+
8
+ # Retro to Guardrail
9
+
10
+ Turn recurring session waste or review findings into automated checks.
11
+
12
+ ## Steps
13
+
14
+ 1. Collect metrics for each completed ticket session (or compare vendors across the whole effort) using `oflow stats <transcript.jsonl>` or `oflow stats --dir <logs-dir> --compare`.
15
+ 2. List breaches (`peak > 150,000`, `gate > 2`, `subagents > 4`) and recurring P0/P1/P2 review findings across the effort.
16
+ 3. Drop one-offs. For every repeated mistake (2+ occurrences):
17
+ - Encode it as an automated check in `oflow gate` (`ratchet`, lint rule, layering check, contract test, or checklist trigger).
18
+ - Add prose to `AGENTS.md` only if no mechanical check can catch it.
19
+ 4. Update `.scratch/NOW.md` and close the effort cleanly.
@@ -0,0 +1,26 @@
1
+ ---
2
+ name: setup-project
3
+ version: 1.3.0
4
+ description: Scaffold .orca-flow.json, minimal AGENTS.md, tracker layout, and a first real-app verification harness for any repository.
5
+ disable-model-invocation: true
6
+ ---
7
+
8
+ # Setup Project
9
+
10
+ Initialize `orca-flow` in the current repository without adding bloat.
11
+
12
+ ## Steps
13
+
14
+ 1. Inspect the repo root for stack markers (`package.json`, `pyproject.toml`, `go.mod`, `Cargo.toml`, `ios/`/`android/`), existing `AGENTS.md` / `CLAUDE.md`, and `git remote -v`.
15
+ 2. Ask the user only for what exploration cannot settle:
16
+ - Active agents (`claude`, `codex`, `agy` — 1, 2, or all 3, or `auto`).
17
+ - Tracker type (`scratch` local markdown vs `github` / `linear` / `jira`).
18
+ - Critical paths that must wait for human approval before merge.
19
+ 3. Run `oflow init --preset <auto|node-ts|python|go|rust|mobile|custom> --tracker <type> --agents <spec>`.
20
+ 4. Verify host setup with `oflow doctor` and ensure Orca settings (`orca repo show`) match `commands.bootstrap` and `commands.doctor`.
21
+ 5. If no real-surface verification exists yet, use the `verify-app` skill pattern to add a single smoke check command and wire it into `.orca-flow.json` under `commands.verify`.
22
+
23
+ ## Done when
24
+
25
+ - `.orca-flow.json` and `AGENTS.md` (<= 60 lines) exist.
26
+ - `oflow gate` passes on the repo.
@@ -0,0 +1,31 @@
1
+ ---
2
+ name: slice-tickets
3
+ version: 1.3.0
4
+ description: Break an approved spec into dependency-ordered vertical slices sized under 150k tokens and assigned across enabled agents.
5
+ disable-model-invocation: true
6
+ ---
7
+
8
+ # Slice Tickets
9
+
10
+ Split `.scratch/<effort>/spec.md` into independent, verifiable vertical tickets (one ticket = one Orca worktree = one PR).
11
+
12
+ ## Sizing & Risk beats size
13
+
14
+ - Each ticket must fit comfortably inside one session (`< 150,000` tokens, `<= 4` subagents, `<= 2` `oflow gate` runs).
15
+ - Small diffs (< 50 lines) with zero `riskTriggers` may stay inline for the Lead. Any change touching a public contract, cross-module boundary, auth/permissions, persistence/migration, concurrency/retries, or external webhooks must be a full ticket with cross-vendor review.
16
+
17
+ ## Vendor assignment
18
+
19
+ Read `agents.allowedWorkers` and `agents.defaultLead` from `.orca-flow.json` (`oflow agents status`) first. Assign `Agent:` only from enabled vendors (or use `Agent: auto` for `defaultLead`); in 1-agent setups, assign all parallel worktrees to that active agent:
20
+
21
+ - `Agent: codex` — well-specified backend logic, reproducing bug tests, docs sync, data pipelines.
22
+ - `Agent: claude` — UI/UX fidelity, ambiguous flows, urgent fixes, or critical paths (`Model: opus` for design/critical, `sonnet` by default).
23
+ - `Agent: antigravity` (alias `agy`) — cross-module refactors, browser QA, or quota balancing when Claude/Codex hit rate limits.
24
+
25
+ ## Ticket format (`.scratch/<effort>/issues/NN-slug.md`)
26
+
27
+ Include: `## Goal`, `## Constraints`, `## Definition of done` (naming exact checks and `verify-app` flow), `Touches:` (comma-separated globs/paths the ticket may edit to avoid parallel merge conflicts), `Blocked by:`, `Agent:`, `Model:`, and `Status: ready-for-agent`.
28
+
29
+ ## Done when
30
+
31
+ - Tickets are written, committed to the tracker/main per repo policy, and the Lead compacts context (`< 150k` baseline) before dispatching workers.
@@ -0,0 +1,22 @@
1
+ ---
2
+ name: verify-app
3
+ version: 1.3.0
4
+ description: Prove changes on the real application surface (Web browser, HTTP server, CLI, or mobile emulator) with isolated ports/databases and captured artifacts.
5
+ ---
6
+
7
+ # Verify App
8
+
9
+ "Tests pass" alone is not behavior proof for user-facing flows or integrations.
10
+
11
+ ## Surface guide
12
+
13
+ - **Web / SaaS**: Launch the built app against a seeded local DB using isolated `VERIFY_PORT` and `VERIFY_DATABASE_URL`. Drive real user flows via Playwright or Orca browser (`orca ports`, `orca tab create`, `orca snapshot`, `orca screenshot`), check console/server logs, and verify DB state afterward.
14
+ - **Backend / API**: Start the real server process on an ephemeral port, execute real HTTP/webhook requests against it, and assert persisted state plus clean teardown.
15
+ - **Mobile**: Use Orca's `orca emulator` skill (`attach`, `tap`, `type`, `screenshot`, accessibility tree, and logcat).
16
+ - **CLI**: Execute the compiled binary in a clean temp directory with real git state.
17
+
18
+ ## Proof standards
19
+
20
+ - Drive the user-visible path; never call test-only bypass endpoints.
21
+ - Keep missing coverage explicit; never weaken assertions to force green.
22
+ - Attach concrete evidence (logs, screenshots, exit codes) to the PR body.
package/src/agents.mjs ADDED
@@ -0,0 +1,278 @@
1
+ import { accessSync, constants, existsSync, lstatSync, readFileSync, readlinkSync, symlinkSync, unlinkSync } from "node:fs";
2
+ import os from "node:os";
3
+ import { delimiter, join } from "node:path";
4
+ import { parseArgs } from "node:util";
5
+ import { loadConfig } from "./config.mjs";
6
+ import { writeAtomic } from "./lock.mjs";
7
+
8
+ export const ALL_AGENTS = ["claude", "codex", "antigravity"];
9
+
10
+ export const VENDORS = {
11
+ claude: {
12
+ id: "claude",
13
+ label: "Claude",
14
+ bin: "claude",
15
+ configDir: ".claude",
16
+ reviewPref: ["codex", "antigravity"],
17
+ },
18
+ codex: {
19
+ id: "codex",
20
+ label: "Codex",
21
+ bin: "codex",
22
+ configDir: ".codex",
23
+ reviewPref: ["claude", "antigravity"],
24
+ },
25
+ antigravity: {
26
+ id: "antigravity",
27
+ label: "Antigravity (agy)",
28
+ bin: "agy",
29
+ configDir: ".gemini",
30
+ reviewPref: ["codex", "claude"],
31
+ },
32
+ };
33
+
34
+ const ALIASES = {
35
+ claude: "claude",
36
+ "claude-code": "claude",
37
+ codex: "codex",
38
+ openai: "codex",
39
+ antigravity: "antigravity",
40
+ agy: "antigravity",
41
+ gemini: "antigravity",
42
+ };
43
+
44
+ const REVIEW_MODES = new Set(["auto", "cross-vendor", "independent"]);
45
+
46
+ /**
47
+ * Normalize a vendor name or alias into a canonical agent ID.
48
+ */
49
+ export function normalizeAgent(raw) {
50
+ const key = typeof raw === "string" ? raw.trim().toLowerCase() : "";
51
+ const canonical = ALIASES[key];
52
+ if (!canonical) {
53
+ throw new Error(`Unknown agent "${raw}". Use claude, codex, or antigravity (alias: agy).`);
54
+ }
55
+ return canonical;
56
+ }
57
+
58
+ function hasExecutable(bin, pathEnv) {
59
+ const dirs = String(pathEnv || "").split(delimiter).filter(Boolean);
60
+ const exts = process.platform === "win32" ? ["", ".exe", ".cmd", ".bat"] : [""];
61
+ for (const dir of dirs) {
62
+ for (const ext of exts) {
63
+ const candidate = join(dir, `${bin}${ext}`);
64
+ try {
65
+ accessSync(candidate, process.platform === "win32" ? constants.F_OK : constants.X_OK);
66
+ return true;
67
+ } catch {
68
+ // Check next candidate in PATH.
69
+ }
70
+ }
71
+ }
72
+ return false;
73
+ }
74
+
75
+ /**
76
+ * Detect which supported agent CLIs or config directories exist on this host.
77
+ */
78
+ export function detectInstalledAgents({ home = os.homedir(), pathEnv = process.env.PATH ?? "" } = {}) {
79
+ const found = [];
80
+ for (const id of ALL_AGENTS) {
81
+ const vendor = VENDORS[id];
82
+ if (hasExecutable(vendor.bin, pathEnv) || existsSync(join(home, vendor.configDir))) {
83
+ found.push(id);
84
+ }
85
+ }
86
+ return found;
87
+ }
88
+
89
+ /**
90
+ * Parse a comma/space list, "all", or "auto" into deduplicated canonical agent IDs.
91
+ */
92
+ export function parseAgentList(spec, { home = os.homedir(), pathEnv = process.env.PATH ?? "" } = {}) {
93
+ if (!spec) return [...ALL_AGENTS];
94
+ if (typeof spec === "string") {
95
+ const trimmed = spec.trim().toLowerCase();
96
+ if (!trimmed || trimmed === "all") return [...ALL_AGENTS];
97
+ if (trimmed === "auto") {
98
+ const detected = detectInstalledAgents({ home, pathEnv });
99
+ return detected.length ? detected : [...ALL_AGENTS];
100
+ }
101
+ }
102
+ const tokens = Array.isArray(spec) ? spec : String(spec).split(/[,+\s]+/).filter(Boolean);
103
+ const out = [];
104
+ for (const token of tokens) {
105
+ const id = normalizeAgent(token);
106
+ if (!out.includes(id)) out.push(id);
107
+ }
108
+ if (!out.length) {
109
+ throw new Error("At least one agent must be specified (claude, codex, or antigravity).");
110
+ }
111
+ return out;
112
+ }
113
+
114
+ export function describeTopology(allowedWorkers) {
115
+ if (allowedWorkers.length <= 1) return "solo";
116
+ if (allowedWorkers.length === 2) return "duo";
117
+ return "tri";
118
+ }
119
+
120
+ /**
121
+ * Normalize raw agent settings and compute topology + consistent defaultLead.
122
+ */
123
+ export function resolveAgentsConfig(rawAgents = {}) {
124
+ const allowedWorkers = parseAgentList(rawAgents.allowedWorkers ?? ALL_AGENTS);
125
+ let defaultLead = allowedWorkers[0];
126
+ if (rawAgents.defaultLead) {
127
+ const candidate = normalizeAgent(rawAgents.defaultLead);
128
+ if (allowedWorkers.includes(candidate)) defaultLead = candidate;
129
+ }
130
+ const reviewMode = rawAgents.reviewMode ?? "auto";
131
+ if (!REVIEW_MODES.has(reviewMode)) {
132
+ throw new Error(`Invalid agents.reviewMode "${reviewMode}". Use auto, cross-vendor, or independent.`);
133
+ }
134
+ return {
135
+ ...rawAgents,
136
+ allowedWorkers,
137
+ defaultLead,
138
+ reviewMode,
139
+ topology: describeTopology(allowedWorkers),
140
+ };
141
+ }
142
+
143
+ /**
144
+ * Pick an independent reviewer across 1-, 2-, or 3-agent topologies.
145
+ */
146
+ export function selectReviewer(authorRaw, agentsConfig, explicitBy = null) {
147
+ const author = normalizeAgent(authorRaw || agentsConfig.defaultLead);
148
+ const allowed = agentsConfig.allowedWorkers;
149
+ const reviewMode = agentsConfig.reviewMode || "auto";
150
+
151
+ if (explicitBy) {
152
+ const vendor = normalizeAgent(explicitBy);
153
+ if (vendor === author) {
154
+ if (reviewMode === "cross-vendor") {
155
+ throw new Error(`Cross-vendor review is enforced, so reviewer cannot match author "${author}".`);
156
+ }
157
+ return { author, vendor, mode: "independent", reviewerTag: `agent:${vendor}-independent` };
158
+ }
159
+ return { author, vendor, mode: "cross-vendor", reviewerTag: `agent:${vendor}` };
160
+ }
161
+
162
+ if (reviewMode !== "independent") {
163
+ const candidates = [...VENDORS[author].reviewPref, ...allowed];
164
+ const peer = candidates.find((v) => v !== author && allowed.includes(v));
165
+ if (peer) {
166
+ return { author, vendor: peer, mode: "cross-vendor", reviewerTag: `agent:${peer}` };
167
+ }
168
+ }
169
+
170
+ if (reviewMode === "cross-vendor") {
171
+ throw new Error(
172
+ `Repository requires cross-vendor review, but allowedWorkers only has [${allowed.join(", ")}]. ` +
173
+ `Record a human verdict (oflow review record --by human:<name>) or set agents.reviewMode to "auto".`,
174
+ );
175
+ }
176
+
177
+ const solo = allowed.includes(author) ? author : allowed[0];
178
+ return { author, vendor: solo, mode: "independent", reviewerTag: `agent:${solo}-independent` };
179
+ }
180
+
181
+ function syncClaudeSymlink(root, allowedWorkers) {
182
+ const agentsMd = join(root, "AGENTS.md");
183
+ const claudeMd = join(root, "CLAUDE.md");
184
+ const stat = lstatSync(claudeMd, { throwIfNoEntry: false });
185
+ if (allowedWorkers.includes("claude")) {
186
+ if (existsSync(agentsMd) && !stat) symlinkSync("AGENTS.md", claudeMd);
187
+ } else if (stat?.isSymbolicLink() && readlinkSync(claudeMd) === "AGENTS.md") {
188
+ unlinkSync(claudeMd);
189
+ }
190
+ }
191
+
192
+ export async function runAgents(argv = [], { cwd = process.cwd(), home = os.homedir() } = {}) {
193
+ const [sub = "status", ...rest] = argv;
194
+ if (sub === "set") {
195
+ const { values, positionals } = parseArgs({
196
+ args: rest,
197
+ allowPositionals: true,
198
+ options: {
199
+ lead: { type: "string" },
200
+ "review-mode": { type: "string" },
201
+ "max-workers": { type: "string" },
202
+ },
203
+ });
204
+ const [spec, ...extra] = positionals;
205
+ if (!spec || extra.length) {
206
+ throw new Error("Usage: oflow agents set <agents|auto|all> [--lead <agent>] [--review-mode auto|cross-vendor|independent] [--max-workers <n>]");
207
+ }
208
+
209
+ const allowedWorkers = parseAgentList(spec, { home });
210
+ const { root, configPath, exists, config } = loadConfig(cwd);
211
+ const defaultLead = values.lead
212
+ ? normalizeAgent(values.lead)
213
+ : (allowedWorkers.includes(config.agents.defaultLead) ? config.agents.defaultLead : allowedWorkers[0]);
214
+ if (!allowedWorkers.includes(defaultLead)) {
215
+ throw new Error(`--lead "${defaultLead}" must be included in allowedWorkers (${allowedWorkers.join(", ")}).`);
216
+ }
217
+
218
+ const reviewMode = values["review-mode"] ?? "auto";
219
+ if (!REVIEW_MODES.has(reviewMode)) {
220
+ throw new Error(`Invalid --review-mode "${reviewMode}". Use auto, cross-vendor, or independent.`);
221
+ }
222
+
223
+ let maxConcurrentWorkers = config.agents.maxConcurrentWorkers;
224
+ if (values["max-workers"] !== undefined) {
225
+ const parsed = Number.parseInt(values["max-workers"], 10);
226
+ if (!Number.isInteger(parsed) || parsed < 1) {
227
+ throw new Error(`--max-workers must be a positive integer; got "${values["max-workers"]}".`);
228
+ }
229
+ maxConcurrentWorkers = parsed;
230
+ }
231
+
232
+ const stored = exists ? JSON.parse(readFileSync(configPath, "utf8")) : { ...config };
233
+ const prevAgents = { ...(stored.agents ?? config.agents) };
234
+ delete prevAgents.topology;
235
+ stored.agents = { ...prevAgents, defaultLead, allowedWorkers, reviewMode, maxConcurrentWorkers };
236
+ writeAtomic(configPath, `${JSON.stringify(stored, null, 2)}\n`);
237
+ syncClaudeSymlink(root, allowedWorkers);
238
+
239
+ const resolved = resolveAgentsConfig(stored.agents);
240
+ console.log(`Updated ${configPath}`);
241
+ console.log(` topology=${resolved.topology} allowedWorkers=${resolved.allowedWorkers.join(",")} defaultLead=${resolved.defaultLead} reviewMode=${resolved.reviewMode}`);
242
+ return 0;
243
+ }
244
+
245
+ const opts = sub === "status" ? rest : argv;
246
+ const { values } = parseArgs({ args: opts, options: { json: { type: "boolean", default: false } } });
247
+ const { config, exists } = loadConfig(cwd);
248
+ const installed = detectInstalledAgents({ home });
249
+ const routing = config.agents.allowedWorkers.map((author) => {
250
+ try {
251
+ return selectReviewer(author, config.agents);
252
+ } catch (err) {
253
+ return { author, vendor: null, mode: "blocked", error: err.message };
254
+ }
255
+ });
256
+ const payload = {
257
+ configExists: exists,
258
+ topology: config.agents.topology,
259
+ installed,
260
+ allowedWorkers: config.agents.allowedWorkers,
261
+ defaultLead: config.agents.defaultLead,
262
+ reviewMode: config.agents.reviewMode,
263
+ routing,
264
+ };
265
+
266
+ if (values.json) {
267
+ console.log(JSON.stringify(payload, null, 2));
268
+ return 0;
269
+ }
270
+ console.log(`Topology: ${payload.topology} (${payload.allowedWorkers.length} active agent${payload.allowedWorkers.length > 1 ? "s" : ""})`);
271
+ console.log(`Installed on host: ${payload.installed.join(", ") || "none detected"}`);
272
+ console.log(`Allowed workers: ${payload.allowedWorkers.join(", ")} (lead: ${payload.defaultLead}, reviewMode: ${payload.reviewMode})`);
273
+ for (const r of payload.routing) {
274
+ const target = r.vendor ? `${r.vendor} (${r.mode}, tag=${r.reviewerTag})` : `blocked (${r.error})`;
275
+ console.log(` review ${r.author} -> ${target}`);
276
+ }
277
+ return 0;
278
+ }
@@ -0,0 +1,160 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync } from "node:fs";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import { normalizeAgent } from "./agents.mjs";
5
+ import { loadConfig } from "./config.mjs";
6
+ import { capturePosition, gitCommonDir, gitRoot, scanSecrets } from "./git.mjs";
7
+ import { withLock, writeAtomic } from "./lock.mjs";
8
+
9
+ const SLUG_RE = /^[a-zA-Z0-9._-]+$/;
10
+
11
+ function checkpointDir(cwd) {
12
+ return join(gitCommonDir(cwd), "orca-flow", "checkpoints");
13
+ }
14
+
15
+ function checkpointFile(cwd, slug) {
16
+ if (!slug || !SLUG_RE.test(slug) || slug === "." || slug === "..") {
17
+ throw new Error(`Invalid checkpoint slug "${slug}".`);
18
+ }
19
+ return join(checkpointDir(cwd), `${slug}.json`);
20
+ }
21
+
22
+ function resolveCheckpointAgent(cwd, rawAgent) {
23
+ if (rawAgent) {
24
+ try {
25
+ return normalizeAgent(rawAgent);
26
+ } catch {
27
+ return rawAgent;
28
+ }
29
+ }
30
+ try {
31
+ return loadConfig(cwd).config.agents.defaultLead;
32
+ } catch {
33
+ return "claude";
34
+ }
35
+ }
36
+
37
+ export async function saveCheckpoint(slug, { phase = "build", agent, next = "", patchId = null, cwd = process.cwd() } = {}) {
38
+ const file = checkpointFile(cwd, slug);
39
+ const pos = capturePosition(cwd);
40
+ const resolvedAgent = resolveCheckpointAgent(cwd, agent);
41
+ const record = {
42
+ slug,
43
+ phase,
44
+ agent: resolvedAgent,
45
+ next,
46
+ patchId,
47
+ branch: pos.branch,
48
+ head: pos.head,
49
+ worktree: pos.worktree,
50
+ dirty: pos.dirty,
51
+ pushed: pos.pushed,
52
+ updatedAt: pos.capturedAt,
53
+ };
54
+ await withLock(file, () => writeAtomic(file, `${JSON.stringify(record, null, 2)}\n`));
55
+ return record;
56
+ }
57
+
58
+ export function checkCheckpoint(slug, { cwd = process.cwd() } = {}) {
59
+ const file = checkpointFile(cwd, slug);
60
+ if (!existsSync(file)) return { ok: false, exitCode: 1, state: "missing", detail: `no checkpoint for "${slug}"` };
61
+ const record = JSON.parse(readFileSync(file, "utf8"));
62
+ const live = capturePosition(cwd);
63
+ if (record.branch !== live.branch) {
64
+ return { ok: false, exitCode: 3, state: "branch-moved", record, live, detail: `recorded branch ${record.branch}, live ${live.branch}` };
65
+ }
66
+ if (record.head !== live.head) {
67
+ return { ok: false, exitCode: 3, state: "head-moved", record, live, detail: `recorded head ${record.head.slice(0, 12)}, live ${live.head.slice(0, 12)}` };
68
+ }
69
+ return { ok: true, exitCode: 0, state: "current", record, live };
70
+ }
71
+
72
+ function canonicalPath(target) {
73
+ let cur = resolve(target);
74
+ const tail = [];
75
+ while (!existsSync(cur)) {
76
+ const parent = dirname(cur);
77
+ if (parent === cur) break;
78
+ tail.unshift(basename(cur));
79
+ cur = parent;
80
+ }
81
+ const realBase = existsSync(cur) ? realpathSync(cur) : cur;
82
+ return join(realBase, ...tail);
83
+ }
84
+
85
+ export function exportHandoff(slug, { out, cwd = process.cwd() } = {}) {
86
+ const file = checkpointFile(cwd, slug);
87
+ if (!existsSync(file)) throw new Error(`No checkpoint "${slug}" to export.`);
88
+ const record = JSON.parse(readFileSync(file, "utf8"));
89
+ const live = capturePosition(cwd);
90
+ const md = [
91
+ `# Handoff: ${slug}`,
92
+ "",
93
+ `- Phase: ${record.phase}`,
94
+ `- Previous agent: ${record.agent}`,
95
+ `- Branch: ${live.branch}`,
96
+ `- Live HEAD: ${live.head}`,
97
+ `- Pushed: ${live.pushed}`,
98
+ `- Dirty: ${live.dirty.changed.length} changed, ${live.dirty.untracked.length} untracked`,
99
+ `- Next: ${record.next || "(specify next action)"}`,
100
+ "",
101
+ "```json",
102
+ JSON.stringify(record, null, 2),
103
+ "```",
104
+ "",
105
+ ].join("\n");
106
+
107
+ const secrets = scanSecrets(md);
108
+ if (secrets.length) {
109
+ const err = new Error(`Refusing handoff export: contains potential ${secrets.join(", ")}`);
110
+ err.exitCode = 4;
111
+ throw err;
112
+ }
113
+
114
+ if (out) {
115
+ const absOut = canonicalPath(resolve(cwd, out));
116
+ const root = gitRoot(cwd);
117
+ const realRoot = root ? canonicalPath(root) : null;
118
+ if (realRoot && (absOut === realRoot || absOut.startsWith(`${realRoot}/`))) {
119
+ const err = new Error("Refusing to write handoff inside the git repository.");
120
+ err.exitCode = 4;
121
+ throw err;
122
+ }
123
+ writeAtomic(absOut, md);
124
+ }
125
+ return md;
126
+ }
127
+
128
+ export async function runCheckpoint(argv, { cwd = process.cwd() } = {}) {
129
+ const [action, slug, ...rest] = argv;
130
+ if (action === "list" || !action) {
131
+ const dir = checkpointDir(cwd);
132
+ mkdirSync(dir, { recursive: true });
133
+ const files = readdirSync(dir).filter((f) => f.endsWith(".json")).sort();
134
+ for (const f of files) {
135
+ const rec = JSON.parse(readFileSync(join(dir, f), "utf8"));
136
+ console.log(`${basename(f, ".json")} phase=${rec.phase} agent=${rec.agent} branch=${rec.branch} head=${rec.head.slice(0, 12)}`);
137
+ }
138
+ if (!files.length) console.log("no checkpoints");
139
+ return 0;
140
+ }
141
+ if (action === "save") {
142
+ const { values } = parseArgs({ args: rest, options: { phase: { type: "string", default: "build" }, agent: { type: "string" }, next: { type: "string", default: "" }, "patch-id": { type: "string" } } });
143
+ const rec = await saveCheckpoint(slug, { phase: values.phase, agent: values.agent, next: values.next, patchId: values["patch-id"] ?? null, cwd });
144
+ console.log(`${rec.slug} saved phase=${rec.phase} agent=${rec.agent} head=${rec.head.slice(0, 12)}`);
145
+ return 0;
146
+ }
147
+ if (action === "check") {
148
+ const res = checkCheckpoint(slug, { cwd });
149
+ console.log(`${slug} state=${res.state} ${res.detail ?? ""}`.trim());
150
+ return res.exitCode;
151
+ }
152
+ if (action === "handoff") {
153
+ const { values } = parseArgs({ args: rest, options: { out: { type: "string" } } });
154
+ const md = exportHandoff(slug, { out: values.out, cwd });
155
+ if (!values.out) process.stdout.write(md);
156
+ else console.log(`handoff written to ${resolve(cwd, values.out)}`);
157
+ return 0;
158
+ }
159
+ throw new Error(`Unknown checkpoint action "${action}". Use save, check, list, or handoff.`);
160
+ }
package/src/config.mjs ADDED
@@ -0,0 +1,140 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { resolveAgentsConfig } from "./agents.mjs";
5
+ import { git, gitRoot } from "./git.mjs";
6
+
7
+ export const KIT_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
8
+ export const KIT_VERSION = JSON.parse(readFileSync(join(KIT_ROOT, "package.json"), "utf8")).version;
9
+
10
+ export const DEFAULT_CONFIG = {
11
+ version: 1,
12
+ project: "project",
13
+ orcaRepo: "",
14
+ baseBranch: "origin/main",
15
+ tracker: { type: "scratch", dir: ".scratch" },
16
+ agents: {
17
+ defaultLead: "claude",
18
+ allowedWorkers: ["claude", "codex", "antigravity"],
19
+ reviewMode: "auto",
20
+ maxConcurrentWorkers: 3,
21
+ tokenBudget: 150000,
22
+ maxGateRuns: 2,
23
+ maxRepairRounds: 3,
24
+ worktreeMode: "new-top-level",
25
+ },
26
+ commands: {
27
+ bootstrap: "true",
28
+ doctor: "",
29
+ gate: "oflow gate",
30
+ fullCheck: "npm test",
31
+ verify: "",
32
+ },
33
+ gate: {
34
+ preset: "auto",
35
+ ignorePaths: ["docs/**", ".scratch/**", "*.md", "*.mdx", "LICENSE"],
36
+ lineLimits: { code: 300, ui: 400, test: 800 },
37
+ baselineFile: ".orca-flow-ratchet.txt",
38
+ },
39
+ verifyIsolation: {
40
+ portEnv: "VERIFY_PORT",
41
+ dbEnv: "VERIFY_DATABASE_URL",
42
+ },
43
+ criticalPaths: [
44
+ "**/auth/**",
45
+ "**/billing/**",
46
+ "**/migrations/**",
47
+ "**/webhooks/**",
48
+ "**/env.*",
49
+ "Dockerfile",
50
+ ],
51
+ riskTriggers: [
52
+ "public-contract",
53
+ "cross-module-boundary",
54
+ "auth-or-permissions",
55
+ "persistence-or-migration",
56
+ "concurrency-or-retries",
57
+ "external-webhook",
58
+ ],
59
+ };
60
+
61
+ export function detectPreset(cwd) {
62
+ if (existsSync(join(cwd, "ios")) || existsSync(join(cwd, "android")) || existsSync(join(cwd, "Podfile"))) {
63
+ return "mobile";
64
+ }
65
+ if (existsSync(join(cwd, "pyproject.toml")) || existsSync(join(cwd, "requirements.txt"))) {
66
+ return "python";
67
+ }
68
+ if (existsSync(join(cwd, "go.mod"))) return "go";
69
+ if (existsSync(join(cwd, "Cargo.toml"))) return "rust";
70
+ if (existsSync(join(cwd, "package.json"))) return "node-ts";
71
+ return "custom";
72
+ }
73
+
74
+ export function detectBaseBranch(cwd) {
75
+ const remoteOriginMain = git(cwd, ["rev-parse", "--verify", "--quiet", "origin/main^{commit}"], { allowFail: true });
76
+ if (remoteOriginMain) return "origin/main";
77
+ const localMain = git(cwd, ["rev-parse", "--verify", "--quiet", "main^{commit}"], { allowFail: true });
78
+ if (localMain) return "main";
79
+ return "HEAD";
80
+ }
81
+
82
+ export function loadConfig(cwd = process.cwd()) {
83
+ const root = gitRoot(cwd) ?? resolve(cwd);
84
+ const configPath = join(root, ".orca-flow.json");
85
+ let user = {};
86
+ if (existsSync(configPath)) {
87
+ user = JSON.parse(readFileSync(configPath, "utf8"));
88
+ }
89
+ const merged = {
90
+ ...DEFAULT_CONFIG,
91
+ ...user,
92
+ project: user.project || basename(root),
93
+ orcaRepo: user.orcaRepo || `name:${basename(root)}`,
94
+ baseBranch: user.baseBranch || detectBaseBranch(root),
95
+ tracker: { ...DEFAULT_CONFIG.tracker, ...(user.tracker ?? {}) },
96
+ agents: resolveAgentsConfig({
97
+ ...DEFAULT_CONFIG.agents,
98
+ ...(user.agents ?? {}),
99
+ defaultLead: user.agents?.defaultLead,
100
+ }),
101
+ commands: { ...DEFAULT_CONFIG.commands, ...(user.commands ?? {}) },
102
+ gate: {
103
+ ...DEFAULT_CONFIG.gate,
104
+ ...(user.gate ?? {}),
105
+ lineLimits: { ...DEFAULT_CONFIG.gate.lineLimits, ...(user.gate?.lineLimits ?? {}) },
106
+ },
107
+ verifyIsolation: { ...DEFAULT_CONFIG.verifyIsolation, ...(user.verifyIsolation ?? {}) },
108
+ };
109
+ if (merged.gate.preset === "auto") {
110
+ merged.gate.preset = detectPreset(root);
111
+ }
112
+ return { root, configPath, exists: existsSync(configPath), config: merged };
113
+ }
114
+
115
+ export function branchSlug(branch) {
116
+ return String(branch || "detached")
117
+ .replace(/[^a-zA-Z0-9._-]+/g, "-")
118
+ .replace(/^-+|-+$/g, "") || "branch";
119
+ }
120
+
121
+ /**
122
+ * Parse simple YAML frontmatter key/value pairs from a SKILL.md string.
123
+ */
124
+ export function parseFrontmatter(text) {
125
+ const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
126
+ if (!match) return {};
127
+ const out = {};
128
+ for (const line of match[1].split(/\r?\n/)) {
129
+ const kv = line.match(/^([a-zA-Z0-9_-]+):\s*(.*)$/);
130
+ if (!kv) continue;
131
+ let val = kv[2].trim();
132
+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
133
+ val = val.slice(1, -1);
134
+ }
135
+ if (val === "true") val = true;
136
+ else if (val === "false") val = false;
137
+ out[kv[1]] = val;
138
+ }
139
+ return out;
140
+ }