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/hook.mjs ADDED
@@ -0,0 +1,168 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import { KIT_ROOT, loadConfig } from "./config.mjs";
5
+ import { runGate } from "./gate.mjs";
6
+ import { git, gitRoot, mergeBase, resolveCommit, scanSecrets } from "./git.mjs";
7
+ import { writeAtomic } from "./lock.mjs";
8
+
9
+ const MARKER = "# orca-flow-managed-hook v1";
10
+ const HOOK_NAME = "pre-push";
11
+
12
+ function resolveHooksDir(cwd) {
13
+ const root = gitRoot(cwd);
14
+ if (!root) throw new Error("Not inside a git repository.");
15
+ const rel = git(root, ["rev-parse", "--git-path", "hooks"]).trim();
16
+ return { root, hooksDir: resolve(root, rel) };
17
+ }
18
+
19
+ function shellQuote(value) {
20
+ return `'${String(value).replace(/'/g, `'\\''`)}'`;
21
+ }
22
+
23
+ /**
24
+ * Inspect whether the orca-flow pre-push hook is installed and whether a prior hook is chained.
25
+ */
26
+ export function hookStatus(cwd = process.cwd()) {
27
+ const { root, hooksDir } = resolveHooksDir(cwd);
28
+ const hookPath = join(hooksDir, HOOK_NAME);
29
+ const prevPath = join(hooksDir, `${HOOK_NAME}.orca-flow-prev`);
30
+ const exists = existsSync(hookPath);
31
+ const managed = exists ? readFileSync(hookPath, "utf8").includes(MARKER) : false;
32
+ return {
33
+ root,
34
+ hooksDir,
35
+ hookPath,
36
+ installed: managed,
37
+ foreignHook: exists && !managed,
38
+ chainedPrev: existsSync(prevPath),
39
+ };
40
+ }
41
+
42
+ /**
43
+ * Install a non-destructive pre-push hook, preserving and chaining any existing user hook.
44
+ */
45
+ export function installHook({ cwd = process.cwd(), kitRoot = KIT_ROOT } = {}) {
46
+ const { root, hooksDir } = resolveHooksDir(cwd);
47
+ const hookPath = join(hooksDir, HOOK_NAME);
48
+ const prevPath = join(hooksDir, `${HOOK_NAME}.orca-flow-prev`);
49
+ mkdirSync(hooksDir, { recursive: true });
50
+
51
+ if (existsSync(hookPath)) {
52
+ const existing = readFileSync(hookPath, "utf8");
53
+ if (!existing.includes(MARKER) && !existsSync(prevPath)) {
54
+ renameSync(hookPath, prevPath);
55
+ }
56
+ }
57
+
58
+ const fallbackBin = resolve(kitRoot, "bin", "oflow.mjs");
59
+ const script = [
60
+ "#!/bin/sh",
61
+ MARKER,
62
+ 'if [ "${OFLOW_SKIP_HOOK:-0}" = "1" ]; then',
63
+ ' echo "[orca-flow] pre-push bypassed via OFLOW_SKIP_HOOK=1"',
64
+ " exit 0",
65
+ "fi",
66
+ 'HOOK_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)',
67
+ 'if [ -x "$HOOK_DIR/pre-push.orca-flow-prev" ]; then',
68
+ ' "$HOOK_DIR/pre-push.orca-flow-prev" "$@"',
69
+ " status=$?",
70
+ ' if [ "$status" -ne 0 ]; then',
71
+ ' exit "$status"',
72
+ " fi",
73
+ "fi",
74
+ `if [ -f ${shellQuote(fallbackBin)} ]; then`,
75
+ ` ${shellQuote(process.execPath)} ${shellQuote(fallbackBin)} hook run pre-push`,
76
+ "elif command -v oflow >/dev/null 2>&1; then",
77
+ " oflow hook run pre-push",
78
+ "else",
79
+ ' echo "[orca-flow] oflow CLI not found; install globally or bypass with OFLOW_SKIP_HOOK=1" >&2',
80
+ " exit 1",
81
+ "fi",
82
+ "",
83
+ ].join("\n");
84
+
85
+ writeAtomic(hookPath, script);
86
+ chmodSync(hookPath, 0o755);
87
+ return { root, hookPath, chainedPrev: existsSync(prevPath), status: "installed" };
88
+ }
89
+
90
+ /**
91
+ * Uninstall the orca-flow pre-push hook and restore any chained user hook.
92
+ */
93
+ export function uninstallHook({ cwd = process.cwd() } = {}) {
94
+ const { root, hooksDir } = resolveHooksDir(cwd);
95
+ const hookPath = join(hooksDir, HOOK_NAME);
96
+ const prevPath = join(hooksDir, `${HOOK_NAME}.orca-flow-prev`);
97
+ if (!existsSync(hookPath)) {
98
+ return { root, hookPath, status: "not-installed" };
99
+ }
100
+ const text = readFileSync(hookPath, "utf8");
101
+ if (!text.includes(MARKER)) {
102
+ return { root, hookPath, status: "kept-foreign" };
103
+ }
104
+ rmSync(hookPath, { force: true });
105
+ if (existsSync(prevPath)) {
106
+ renameSync(prevPath, hookPath);
107
+ return { root, hookPath, status: "restored-previous" };
108
+ }
109
+ return { root, hookPath, status: "removed" };
110
+ }
111
+
112
+ /**
113
+ * Execute pre-push checks: oflow gate plus secret scanning on the outgoing diff.
114
+ */
115
+ export async function runPrePushHook({ cwd = process.cwd() } = {}) {
116
+ if (process.env.OFLOW_SKIP_HOOK === "1") {
117
+ console.log("[orca-flow] pre-push bypassed via OFLOW_SKIP_HOOK=1");
118
+ return 0;
119
+ }
120
+ const gateCode = await runGate([], { cwd });
121
+ if (gateCode !== 0) return gateCode;
122
+
123
+ const { root, config } = loadConfig(cwd);
124
+ try {
125
+ const headSha = resolveCommit(root, "HEAD");
126
+ const mb = mergeBase(root, config.baseBranch, headSha);
127
+ if (mb !== headSha) {
128
+ const diff = git(root, ["-c", "core.pager=cat", "diff", "--no-color", "--no-ext-diff", "--no-textconv", `${mb}...${headSha}`]);
129
+ const secrets = scanSecrets(diff);
130
+ if (secrets.length > 0) {
131
+ console.error(`fail secret-scan: Refusing push (${secrets.join(", ")})`);
132
+ return 4;
133
+ }
134
+ }
135
+ } catch {
136
+ // Unborn or unreachable baseBranch already handled safely during gate.
137
+ }
138
+ return 0;
139
+ }
140
+
141
+ export async function runHook(argv = [], { cwd = process.cwd() } = {}) {
142
+ const [sub = "status", ...rest] = argv;
143
+ if (sub === "install") {
144
+ const res = installHook({ cwd });
145
+ console.log(`hook=${res.status} path=${res.hookPath} chainedPrev=${res.chainedPrev}`);
146
+ return 0;
147
+ }
148
+ if (sub === "uninstall") {
149
+ const res = uninstallHook({ cwd });
150
+ console.log(`hook=${res.status} path=${res.hookPath}`);
151
+ return 0;
152
+ }
153
+ if (sub === "run") {
154
+ const [target = HOOK_NAME] = rest;
155
+ if (target !== HOOK_NAME) {
156
+ throw new Error(`Unsupported hook "${target}". Only "${HOOK_NAME}" is supported.`);
157
+ }
158
+ return runPrePushHook({ cwd });
159
+ }
160
+ if (sub === "status") {
161
+ const { values } = parseArgs({ args: rest, options: { json: { type: "boolean", default: false } } });
162
+ const st = hookStatus(cwd);
163
+ if (values.json) console.log(JSON.stringify(st, null, 2));
164
+ else console.log(`pre-push: ${st.installed ? "installed" : st.foreignHook ? "foreign-hook" : "not-installed"} (chainedPrev=${st.chainedPrev}) -> ${st.hookPath}`);
165
+ return 0;
166
+ }
167
+ throw new Error(`Unknown hook action "${sub}". Use status, install, uninstall, or run.`);
168
+ }
package/src/init.mjs ADDED
@@ -0,0 +1,149 @@
1
+ import { existsSync, mkdirSync, symlinkSync } from "node:fs";
2
+ import { basename, join, resolve } from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import { normalizeAgent, parseAgentList } from "./agents.mjs";
5
+ import { DEFAULT_CONFIG, detectBaseBranch, detectPreset } from "./config.mjs";
6
+ import { writeAtomic } from "./lock.mjs";
7
+
8
+ const PRESET_COMMANDS = {
9
+ "node-ts": { bootstrap: "npm ci", doctor: "node -v", fullCheck: "npm test", verify: "npm run verify" },
10
+ python: { bootstrap: "uv sync || pip install -e .", doctor: "python3 --version", fullCheck: "pytest", verify: "" },
11
+ go: { bootstrap: "go mod download", doctor: "go version", fullCheck: "go test ./...", verify: "" },
12
+ rust: { bootstrap: "cargo fetch", doctor: "cargo --version", fullCheck: "cargo test", verify: "" },
13
+ mobile: { bootstrap: "npm ci", doctor: "orca emulator list", fullCheck: "npm test", verify: "orca emulator list" },
14
+ custom: { bootstrap: "true", doctor: "", fullCheck: "npm test", verify: "" },
15
+ };
16
+
17
+ const PR_TEMPLATE = `## What and why
18
+ <!-- Link the ticket in .scratch/ or issue URL -->
19
+
20
+ ## Evidence
21
+ <!-- Gate output, screenshots, or real-app verification logs -->
22
+
23
+ ## Independent review
24
+ - Author vendor:
25
+ - Reviewer & patch-id:
26
+ - Findings: clean / fixed P0-P1 / remaining P2
27
+
28
+ ## Critical path
29
+ Touches a critical path? yes/no (wait for human review if yes)
30
+ `;
31
+
32
+ function buildAgentsMd(config) {
33
+ return `# ${config.project}
34
+
35
+ Project workflow is managed by \`orca-flow\` (\`.orca-flow.json\`).
36
+
37
+ ## Source of truth
38
+
39
+ - \`docs/PRD.md\` > \`docs/STACK.md\` & \`docs/adr/\` > \`${config.tracker.dir}/<effort>/spec.md\`
40
+ - \`AGENTS.md\` overrides installed skills.
41
+
42
+ ## Checks & Workflow
43
+
44
+ - Local PR gate: \`oflow gate\` (cache + lint + max-lines + related tests)
45
+ - Full check: \`${config.commands.fullCheck || "oflow gate"}\`
46
+ - Real-app verify: \`${config.commands.verify || "see verify-app skill"}\`
47
+ - Active agents: \`${config.agents.allowedWorkers.join(", ")}\` (lead: \`${config.agents.defaultLead}\`)
48
+ - Dispatch 1 ticket per Orca worktree: \`oflow worker <ticket>\` (max ${config.agents.maxConcurrentWorkers} concurrent)
49
+ - Review & PR: \`oflow review run --deep\` -> \`oflow pr\` (never self-merge critical paths)
50
+
51
+ ## Critical paths
52
+
53
+ ${config.criticalPaths.map((p) => `- \`${p}\``).join("\n")}
54
+ `;
55
+ }
56
+
57
+ export function initRepo({ dir = process.cwd(), preset = "auto", tracker = "scratch", agents = "all", lead, dryRun = false, force = false } = {}) {
58
+ const root = resolve(dir);
59
+ const project = basename(root);
60
+ const resolvedPreset = preset === "auto" ? detectPreset(root) : preset;
61
+ if (!PRESET_COMMANDS[resolvedPreset]) {
62
+ throw new Error(`Unknown preset "${preset}". Use auto, node-ts, python, go, rust, mobile, or custom.`);
63
+ }
64
+ if (!["scratch", "github", "linear", "jira"].includes(tracker)) {
65
+ throw new Error(`Unknown tracker "${tracker}". Use scratch, github, linear, or jira.`);
66
+ }
67
+ const allowedWorkers = parseAgentList(agents);
68
+ const defaultLead = lead ? normalizeAgent(lead) : allowedWorkers[0];
69
+ if (!allowedWorkers.includes(defaultLead)) {
70
+ throw new Error(`--lead "${defaultLead}" must be included in allowedWorkers (${allowedWorkers.join(", ")}).`);
71
+ }
72
+
73
+ const config = {
74
+ ...DEFAULT_CONFIG,
75
+ project,
76
+ orcaRepo: `name:${project}`,
77
+ baseBranch: detectBaseBranch(root),
78
+ tracker: tracker === "scratch" ? { type: "scratch", dir: ".scratch" } : { type: tracker },
79
+ agents: { ...DEFAULT_CONFIG.agents, defaultLead, allowedWorkers, reviewMode: "auto" },
80
+ commands: { ...DEFAULT_CONFIG.commands, ...PRESET_COMMANDS[resolvedPreset], gate: "oflow gate" },
81
+ gate: { ...DEFAULT_CONFIG.gate, preset: resolvedPreset },
82
+ };
83
+
84
+ const planned = [
85
+ { path: ".orca-flow.json", content: `${JSON.stringify(config, null, 2)}\n` },
86
+ { path: "AGENTS.md", content: buildAgentsMd(config) },
87
+ { path: ".github/pull_request_template.md", content: PR_TEMPLATE },
88
+ ];
89
+
90
+ if (tracker === "scratch") {
91
+ planned.push(
92
+ { path: ".scratch/NOW.md", content: `# Project board\n\nMax 2 active efforts.\n\n## Active\n\n(none)\n` },
93
+ { path: ".scratch/inbox.md", content: `# Inbox\n\nOne idea per line. Only the user promotes an idea to a spec.\n\n## Ideas\n` },
94
+ { path: "docs/agents/issue-tracker.md", content: `# Issue tracker\n\nIssues live under \`.scratch/<effort>/issues/NN-slug.md\`.\n` },
95
+ );
96
+ }
97
+
98
+ const results = [];
99
+ for (const item of planned) {
100
+ const abs = join(root, item.path);
101
+ const exists = existsSync(abs);
102
+ if (exists && !force) {
103
+ results.push({ path: item.path, status: "kept" });
104
+ continue;
105
+ }
106
+ if (!dryRun) writeAtomic(abs, item.content);
107
+ results.push({ path: item.path, status: exists ? "overwritten" : "created" });
108
+ }
109
+
110
+ const claudeMd = join(root, "CLAUDE.md");
111
+ let claudeStatus = allowedWorkers.includes("claude") ? "kept" : "skipped";
112
+ if (allowedWorkers.includes("claude") && !existsSync(claudeMd)) {
113
+ if (!dryRun) symlinkSync("AGENTS.md", claudeMd);
114
+ claudeStatus = "symlinked";
115
+ }
116
+ results.push({ path: "CLAUDE.md", status: claudeStatus });
117
+
118
+ if (!dryRun && resolvedPreset !== "custom") {
119
+ mkdirSync(join(root, "docs", "adr"), { recursive: true });
120
+ }
121
+ return { root, preset: resolvedPreset, tracker, agents: allowedWorkers, defaultLead, dryRun, files: results };
122
+ }
123
+
124
+ export async function runInit(argv) {
125
+ const { values } = parseArgs({
126
+ args: argv,
127
+ options: {
128
+ dir: { type: "string" },
129
+ preset: { type: "string", default: "auto" },
130
+ tracker: { type: "string", default: "scratch" },
131
+ agents: { type: "string", default: "all" },
132
+ lead: { type: "string" },
133
+ "dry-run": { type: "boolean", default: false },
134
+ force: { type: "boolean", default: false },
135
+ },
136
+ });
137
+ const res = initRepo({
138
+ dir: values.dir ? resolve(values.dir) : process.cwd(),
139
+ preset: values.preset,
140
+ tracker: values.tracker,
141
+ agents: values.agents,
142
+ lead: values.lead,
143
+ dryRun: values["dry-run"],
144
+ force: values.force,
145
+ });
146
+ console.log(`oflow init (${res.preset}, tracker=${res.tracker}, agents=${res.agents.join(",")}${res.dryRun ? ", dry-run" : ""}) -> ${res.root}`);
147
+ for (const f of res.files) console.log(` ${f.status.padEnd(12)} ${f.path}`);
148
+ return 0;
149
+ }
@@ -0,0 +1,192 @@
1
+ import { createHash } from "node:crypto";
2
+ import { execFileSync } from "node:child_process";
3
+ import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, renameSync, rmSync, symlinkSync, unlinkSync } from "node:fs";
4
+ import os from "node:os";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { parseArgs } from "node:util";
7
+ import { parseAgentList } from "./agents.mjs";
8
+ import { KIT_ROOT, parseFrontmatter } from "./config.mjs";
9
+ import { writeAtomic } from "./lock.mjs";
10
+
11
+ function hashDir(dir) {
12
+ const hash = createHash("sha256");
13
+ function walk(cur) {
14
+ for (const entry of readdirSync(cur, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
15
+ const full = join(cur, entry.name);
16
+ hash.update(entry.name);
17
+ if (entry.isDirectory()) walk(full);
18
+ else if (entry.isFile()) hash.update(readFileSync(full));
19
+ }
20
+ }
21
+ walk(dir);
22
+ return hash.digest("hex");
23
+ }
24
+
25
+ export function discoverKitSkills(kitRoot = KIT_ROOT) {
26
+ const skillsDir = join(kitRoot, "skills");
27
+ const skills = [];
28
+ for (const entry of readdirSync(skillsDir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
29
+ if (!entry.isDirectory()) continue;
30
+ const dir = join(skillsDir, entry.name);
31
+ const mdPath = join(dir, "SKILL.md");
32
+ if (!existsSync(mdPath)) continue;
33
+ const fm = parseFrontmatter(readFileSync(mdPath, "utf8"));
34
+ skills.push({
35
+ name: fm.name || entry.name,
36
+ dir,
37
+ hash: hashDir(dir),
38
+ modelInvoked: fm["disable-model-invocation"] !== true,
39
+ });
40
+ }
41
+ return skills;
42
+ }
43
+
44
+ function readManifest(manifestPath) {
45
+ if (!existsSync(manifestPath)) return { version: 1, skills: {} };
46
+ try {
47
+ return JSON.parse(readFileSync(manifestPath, "utf8"));
48
+ } catch {
49
+ return { version: 1, skills: {} };
50
+ }
51
+ }
52
+
53
+ function ensureAgentLink(sourceDir, linkPath, { force, dryRun, backupRoot }) {
54
+ const stat = lstatSync(linkPath, { throwIfNoEntry: false });
55
+ if (stat) {
56
+ if (stat.isSymbolicLink()) {
57
+ const dest = resolve(dirname(linkPath), readlinkSync(linkPath));
58
+ if (dest === resolve(sourceDir)) return "up-to-date";
59
+ if (!force) return "blocked";
60
+ if (!dryRun) unlinkSync(linkPath);
61
+ } else {
62
+ if (!force) return "blocked";
63
+ if (!dryRun) {
64
+ mkdirSync(backupRoot, { recursive: true });
65
+ renameSync(linkPath, join(backupRoot, `${Date.now()}-${linkPath.split("/").slice(-2).join("_")}`));
66
+ }
67
+ }
68
+ }
69
+ if (!dryRun) {
70
+ mkdirSync(dirname(linkPath), { recursive: true });
71
+ symlinkSync(sourceDir, linkPath, "dir");
72
+ }
73
+ return stat ? "replaced" : "linked";
74
+ }
75
+
76
+ export function installKit({ home = os.homedir(), kitRoot = KIT_ROOT, dryRun = false, force = false, skipOrca = false, agents = "all", prune = false } = {}) {
77
+ const selectedAgents = parseAgentList(agents, { home });
78
+ const universalRoot = join(home, ".agents", "skills");
79
+ const backupRoot = join(home, ".agents", ".orca-flow-backup");
80
+ const manifestPath = join(universalRoot, ".orca-flow-manifest.json");
81
+ const agentTargets = [
82
+ { id: "claude", enabled: selectedAgents.includes("claude"), dir: join(home, ".claude", "skills") },
83
+ { id: "gemini", enabled: selectedAgents.includes("antigravity"), dir: join(home, ".gemini", "config", "skills") },
84
+ ];
85
+
86
+ const manifest = readManifest(manifestPath);
87
+ const skills = discoverKitSkills(kitRoot);
88
+ const report = [];
89
+
90
+ for (const skill of skills) {
91
+ const destDir = join(universalRoot, skill.name);
92
+ const stat = lstatSync(destDir, { throwIfNoEntry: false });
93
+ const known = manifest.skills?.[skill.name]?.hash;
94
+ let universalStatus = "install";
95
+
96
+ if (stat) {
97
+ if (stat.isSymbolicLink()) {
98
+ universalStatus = force ? "backup+install" : "blocked";
99
+ } else {
100
+ const curHash = hashDir(destDir);
101
+ if (curHash === skill.hash && known === skill.hash) universalStatus = "up-to-date";
102
+ else if (known && curHash === known) universalStatus = "update";
103
+ else universalStatus = force ? "backup+install" : "blocked";
104
+ }
105
+ }
106
+
107
+ if (!dryRun && (universalStatus === "install" || universalStatus === "update" || universalStatus === "backup+install")) {
108
+ mkdirSync(universalRoot, { recursive: true });
109
+ if (universalStatus === "backup+install" && stat) {
110
+ mkdirSync(backupRoot, { recursive: true });
111
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
112
+ renameSync(destDir, join(backupRoot, `${skill.name}-${stamp}`));
113
+ }
114
+ const tmp = `${destDir}.tmp-${process.pid}`;
115
+ rmSync(tmp, { recursive: true, force: true });
116
+ cpSync(skill.dir, tmp, { recursive: true });
117
+ rmSync(destDir, { recursive: true, force: true });
118
+ renameSync(tmp, destDir);
119
+ manifest.skills[skill.name] = { hash: skill.hash, installedAt: new Date().toISOString() };
120
+ }
121
+
122
+ const links = {};
123
+ for (const target of agentTargets) {
124
+ const linkPath = join(target.dir, skill.name);
125
+ if (!target.enabled) {
126
+ if (prune) {
127
+ const linkStat = lstatSync(linkPath, { throwIfNoEntry: false });
128
+ if (linkStat?.isSymbolicLink() && resolve(dirname(linkPath), readlinkSync(linkPath)) === resolve(destDir)) {
129
+ if (!dryRun) unlinkSync(linkPath);
130
+ links[target.id] = "pruned";
131
+ continue;
132
+ }
133
+ }
134
+ links[target.id] = "disabled";
135
+ continue;
136
+ }
137
+ links[target.id] = universalStatus === "blocked"
138
+ ? "skipped"
139
+ : ensureAgentLink(destDir, linkPath, { force, dryRun, backupRoot });
140
+ }
141
+ report.push({ name: skill.name, universal: universalStatus, links });
142
+ }
143
+
144
+ if (!dryRun) {
145
+ manifest.agents = selectedAgents;
146
+ writeAtomic(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
147
+ }
148
+
149
+ let orcaNote = "skipped";
150
+ if (!skipOrca && !dryRun && home === os.homedir()) {
151
+ try {
152
+ execFileSync("orca", ["skills", "install", "--skill", "orca-cli", "--skill", "orchestration", "--skill", "orca-emulator", "--agent", selectedAgents.join(",")], { stdio: "pipe" });
153
+ orcaNote = "synced";
154
+ } catch {
155
+ orcaNote = "orca CLI unavailable or skipped";
156
+ }
157
+ }
158
+ return { dryRun, home, agents: selectedAgents, skills: report, orcaNote };
159
+ }
160
+
161
+ export async function runInstall(argv) {
162
+ const { values } = parseArgs({
163
+ args: argv,
164
+ options: {
165
+ "dry-run": { type: "boolean", default: false },
166
+ force: { type: "boolean", default: false },
167
+ "skip-orca": { type: "boolean", default: false },
168
+ prune: { type: "boolean", default: false },
169
+ agents: { type: "string", default: "all" },
170
+ home: { type: "string" },
171
+ json: { type: "boolean", default: false },
172
+ },
173
+ });
174
+ const res = installKit({
175
+ home: values.home ? resolve(values.home) : os.homedir(),
176
+ dryRun: values["dry-run"],
177
+ force: values.force,
178
+ skipOrca: values["skip-orca"],
179
+ agents: values.agents,
180
+ prune: values.prune,
181
+ });
182
+ if (values.json) {
183
+ console.log(JSON.stringify(res, null, 2));
184
+ return 0;
185
+ }
186
+ const mode = res.dryRun ? " (dry-run)" : "";
187
+ console.log(`oflow install${mode} (agents=${res.agents.join(",")}) -> ${res.home}`);
188
+ for (const row of res.skills) {
189
+ console.log(` ${row.name.padEnd(18)} universal=${row.universal.padEnd(14)} claude=${row.links.claude.padEnd(10)} gemini=${row.links.gemini}`);
190
+ }
191
+ return 0;
192
+ }
package/src/lock.mjs ADDED
@@ -0,0 +1,80 @@
1
+ import { mkdirSync, openSync, closeSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { setTimeout as delay } from "node:timers/promises";
4
+
5
+ /**
6
+ * Write a file atomically via a PID-unique temp file and rename.
7
+ */
8
+ export function writeAtomic(filePath, content) {
9
+ mkdirSync(dirname(filePath), { recursive: true });
10
+ const tmp = `${filePath}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
11
+ writeFileSync(tmp, content, "utf8");
12
+ try {
13
+ renameSync(tmp, filePath);
14
+ } catch (err) {
15
+ rmSync(tmp, { force: true });
16
+ throw err;
17
+ }
18
+ }
19
+
20
+ function isStaleLock(lockPath, staleMs) {
21
+ try {
22
+ const raw = readFileSync(lockPath, "utf8");
23
+ const parsed = JSON.parse(raw);
24
+ if (!parsed || typeof parsed.pid !== "number" || typeof parsed.createdAt !== "number") {
25
+ return true;
26
+ }
27
+ if (Date.now() - parsed.createdAt > staleMs) return true;
28
+ try {
29
+ process.kill(parsed.pid, 0);
30
+ return false;
31
+ } catch (err) {
32
+ return err.code === "ESRCH";
33
+ }
34
+ } catch {
35
+ return true;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Acquire an exclusive O_EXCL lockfile around targetPath before running fn.
41
+ */
42
+ export async function withLock(targetPath, fn, { timeoutMs = 5000, staleMs = 30000 } = {}) {
43
+ const lockPath = `${targetPath}.lock`;
44
+ mkdirSync(dirname(lockPath), { recursive: true });
45
+ const deadline = Date.now() + timeoutMs;
46
+ const token = `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
47
+
48
+ while (true) {
49
+ try {
50
+ const fd = openSync(lockPath, "wx");
51
+ try {
52
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, createdAt: Date.now(), token }), "utf8");
53
+ } finally {
54
+ closeSync(fd);
55
+ }
56
+ break;
57
+ } catch (err) {
58
+ if (err.code !== "EEXIST") throw err;
59
+ if (isStaleLock(lockPath, staleMs)) {
60
+ rmSync(lockPath, { force: true });
61
+ continue;
62
+ }
63
+ if (Date.now() >= deadline) {
64
+ throw new Error(`Timed out waiting for lock: ${lockPath}`);
65
+ }
66
+ await delay(25);
67
+ }
68
+ }
69
+
70
+ try {
71
+ return await fn();
72
+ } finally {
73
+ try {
74
+ const current = JSON.parse(readFileSync(lockPath, "utf8"));
75
+ if (current?.token === token) rmSync(lockPath, { force: true });
76
+ } catch {
77
+ rmSync(lockPath, { force: true });
78
+ }
79
+ }
80
+ }