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/doctor.mjs ADDED
@@ -0,0 +1,190 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { existsSync, lstatSync, readdirSync, readFileSync, readlinkSync } 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 { detectInstalledAgents } from "./agents.mjs";
8
+ import { KIT_ROOT, KIT_VERSION, loadConfig } from "./config.mjs";
9
+ import { gitRoot, resolveCommit } from "./git.mjs";
10
+ import { discoverKitSkills } from "./install.mjs";
11
+
12
+ function hashSkillDir(dir) {
13
+ const hash = createHash("sha256");
14
+ function walk(cur) {
15
+ for (const entry of readdirSync(cur, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
16
+ const full = join(cur, entry.name);
17
+ hash.update(entry.name);
18
+ if (entry.isDirectory()) walk(full);
19
+ else if (entry.isFile()) hash.update(readFileSync(full));
20
+ }
21
+ }
22
+ walk(dir);
23
+ return hash.digest("hex");
24
+ }
25
+
26
+ function checkSkillsSync(home, allowedWorkers) {
27
+ const kitSkills = discoverKitSkills(KIT_ROOT);
28
+ const universalRoot = join(home, ".agents", "skills");
29
+ let synced = 0;
30
+ const linkTargets = [];
31
+ if (allowedWorkers.includes("claude")) linkTargets.push({ id: "claude", dir: join(home, ".claude", "skills") });
32
+ if (allowedWorkers.includes("antigravity")) linkTargets.push({ id: "antigravity", dir: join(home, ".gemini", "config", "skills") });
33
+
34
+ const brokenTargets = new Set();
35
+ for (const skill of kitSkills) {
36
+ const destDir = join(universalRoot, skill.name);
37
+ if (!existsSync(destDir) || hashSkillDir(destDir) !== skill.hash) continue;
38
+ synced++;
39
+ for (const target of linkTargets) {
40
+ const linkPath = join(target.dir, skill.name);
41
+ const st = lstatSync(linkPath, { throwIfNoEntry: false });
42
+ const valid = Boolean(
43
+ st &&
44
+ existsSync(linkPath) &&
45
+ (!st.isSymbolicLink() || resolve(dirname(linkPath), readlinkSync(linkPath)) === resolve(destDir)),
46
+ );
47
+ if (!valid) brokenTargets.add(target.id);
48
+ }
49
+ }
50
+
51
+ if (synced < kitSkills.length) {
52
+ return {
53
+ id: "skills",
54
+ status: "warn",
55
+ detail: `${synced}/${kitSkills.length} skills synced; run "oflow install"`,
56
+ };
57
+ }
58
+ if (brokenTargets.size > 0) {
59
+ return {
60
+ id: "skills",
61
+ status: "warn",
62
+ detail: `missing agent skill links for ${[...brokenTargets].join(", ")}; run "oflow install --agents ${allowedWorkers.join(",")}"`,
63
+ };
64
+ }
65
+ return { id: "skills", status: "ok", detail: `${kitSkills.length}/${kitSkills.length} skills synced` };
66
+ }
67
+
68
+ /**
69
+ * Read-only health check across Node runtime, git repo, skill sync, and active agents.
70
+ */
71
+ export function diagnoseEnvironment({
72
+ cwd = process.cwd(),
73
+ home = os.homedir(),
74
+ pathEnv = process.env.PATH ?? "",
75
+ runCustomDoctor = true,
76
+ } = {}) {
77
+ const checks = [];
78
+ const major = Number.parseInt(process.versions.node.split(".")[0], 10);
79
+ checks.push(
80
+ major >= 22
81
+ ? { id: "node", status: "ok", detail: `Node v${process.versions.node} (>= 22)` }
82
+ : { id: "node", status: "fail", detail: `Node v${process.versions.node} (< 22 required)` },
83
+ );
84
+
85
+ const root = gitRoot(cwd);
86
+ checks.push(
87
+ root
88
+ ? { id: "git", status: "ok", detail: `repo ${root}` }
89
+ : { id: "git", status: "warn", detail: "not inside a git repository" },
90
+ );
91
+
92
+ const { config } = loadConfig(cwd);
93
+ const allowed = config.agents.allowedWorkers;
94
+ checks.push(checkSkillsSync(home, allowed));
95
+
96
+ const installed = detectInstalledAgents({ home, pathEnv });
97
+ const missingAgents = allowed.filter((id) => !installed.includes(id));
98
+ checks.push(
99
+ missingAgents.length === 0
100
+ ? { id: "agents", status: "ok", detail: `active: ${allowed.join(", ")}` }
101
+ : { id: "agents", status: "warn", detail: `missing CLI/config on host for: ${missingAgents.join(", ")}` },
102
+ );
103
+
104
+ if (root) {
105
+ let hasHead = false;
106
+ try {
107
+ resolveCommit(root, "HEAD");
108
+ hasHead = true;
109
+ } catch {
110
+ hasHead = false;
111
+ }
112
+ if (hasHead) {
113
+ try {
114
+ resolveCommit(root, config.baseBranch);
115
+ checks.push({ id: "base-branch", status: "ok", detail: `baseBranch=${config.baseBranch}` });
116
+ } catch {
117
+ checks.push({ id: "base-branch", status: "fail", detail: `baseBranch "${config.baseBranch}" not found` });
118
+ }
119
+ } else {
120
+ checks.push({ id: "base-branch", status: "warn", detail: "repository has no commits yet" });
121
+ }
122
+
123
+ const agentsMd = join(root, "AGENTS.md");
124
+ if (!existsSync(agentsMd)) {
125
+ checks.push({ id: "agents-md", status: "warn", detail: 'AGENTS.md not found; run "oflow init"' });
126
+ } else {
127
+ const lines = readFileSync(agentsMd, "utf8").trimEnd().split(/\r?\n/).length;
128
+ checks.push(
129
+ lines <= 60
130
+ ? { id: "agents-md", status: "ok", detail: `AGENTS.md (${lines} lines <= 60)` }
131
+ : { id: "agents-md", status: "warn", detail: `AGENTS.md has ${lines} lines (> 60 limit)` },
132
+ );
133
+ if (allowed.includes("claude")) {
134
+ checks.push(
135
+ existsSync(join(root, "CLAUDE.md"))
136
+ ? { id: "claude-md", status: "ok", detail: "CLAUDE.md present" }
137
+ : { id: "claude-md", status: "warn", detail: "missing CLAUDE.md symlink" },
138
+ );
139
+ }
140
+ }
141
+
142
+ const custom = config.commands?.doctor?.trim();
143
+ if (runCustomDoctor && custom && custom !== "true" && process.env.OFLOW_IN_DOCTOR !== "1") {
144
+ try {
145
+ execFileSync("sh", ["-c", custom], {
146
+ cwd: root,
147
+ env: { ...process.env, OFLOW_IN_DOCTOR: "1" },
148
+ encoding: "utf8",
149
+ stdio: ["ignore", "pipe", "pipe"],
150
+ });
151
+ checks.push({ id: "custom-doctor", status: "ok", detail: `custom doctor passed (${custom})` });
152
+ } catch (err) {
153
+ const msg = String(err.stderr || err.message).trim().split("\n")[0];
154
+ checks.push({ id: "custom-doctor", status: "fail", detail: `custom doctor failed (${custom}): ${msg}` });
155
+ }
156
+ }
157
+ }
158
+
159
+ const errors = checks.filter((c) => c.status === "fail");
160
+ const warnings = checks.filter((c) => c.status === "warn");
161
+ return { version: KIT_VERSION, ok: errors.length === 0, warnings, errors, checks };
162
+ }
163
+
164
+ export async function runDoctor(argv = [], { cwd = process.cwd(), home = os.homedir() } = {}) {
165
+ const { values } = parseArgs({
166
+ args: argv,
167
+ options: {
168
+ json: { type: "boolean", default: false },
169
+ strict: { type: "boolean", default: false },
170
+ home: { type: "string" },
171
+ "no-custom": { type: "boolean", default: false },
172
+ },
173
+ });
174
+ const res = diagnoseEnvironment({
175
+ cwd,
176
+ home: values.home ? resolve(values.home) : home,
177
+ runCustomDoctor: !values["no-custom"],
178
+ });
179
+ if (values.json) {
180
+ console.log(JSON.stringify(res, null, 2));
181
+ } else {
182
+ console.log(`orca-flow doctor v${res.version}`);
183
+ for (const c of res.checks) {
184
+ const tag = c.status === "ok" ? "[OK]" : c.status === "warn" ? "[WARN]" : "[FAIL]";
185
+ console.log(` ${tag.padEnd(6)} ${c.id.padEnd(14)} ${c.detail}`);
186
+ }
187
+ console.log(`Summary: ${res.errors.length} error(s), ${res.warnings.length} warning(s)`);
188
+ }
189
+ return !res.ok || (values.strict && res.warnings.length > 0) ? 1 : 0;
190
+ }
package/src/gate.mjs ADDED
@@ -0,0 +1,205 @@
1
+ import { execFileSync, spawn } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { existsSync, lstatSync, readFileSync, readlinkSync, rmSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { parseArgs } from "node:util";
6
+ import { loadConfig } from "./config.mjs";
7
+ import { changedFiles, git, gitCommonDir, matchesAnyGlob } from "./git.mjs";
8
+ import { writeAtomic } from "./lock.mjs";
9
+
10
+ const CODE_EXT_RE = /\.(?:[cm]?[jt]sx?|py|go|rs|vue|svelte)$/i;
11
+ const TEST_FILE_RE = /(?:^|\/)(?:test[/_][^/]*|[^/]*\.(?:test|spec)\.[^.]+|[^/]*_test\.go)$/i;
12
+ const UI_FILE_RE = /\.(?:tsx|jsx|vue|svelte)$/i;
13
+
14
+ export function countCodeLines(filePath) {
15
+ const text = readFileSync(filePath, "utf8");
16
+ let count = 0;
17
+ let inBlock = false;
18
+ for (const raw of text.split(/\r?\n/)) {
19
+ const line = raw.trim();
20
+ if (!line) continue;
21
+ if (inBlock) {
22
+ if (line.includes("*/")) inBlock = false;
23
+ continue;
24
+ }
25
+ if (line.startsWith("/*")) {
26
+ if (!line.includes("*/")) inBlock = true;
27
+ continue;
28
+ }
29
+ if (line.startsWith("//") || line.startsWith("#") || line.startsWith("*")) continue;
30
+ count++;
31
+ }
32
+ return count;
33
+ }
34
+
35
+ function findOversizedFiles(root, gateConfig) {
36
+ const raw = git(root, ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], { allowFail: true }) ?? "";
37
+ const files = [...new Set(raw.split("\0").filter((f) => f && CODE_EXT_RE.test(f) && existsSync(join(root, f))))].sort();
38
+ const entries = [];
39
+
40
+ for (const rel of files) {
41
+ const budget = TEST_FILE_RE.test(rel)
42
+ ? gateConfig.lineLimits.test
43
+ : UI_FILE_RE.test(rel)
44
+ ? gateConfig.lineLimits.ui
45
+ : gateConfig.lineLimits.code;
46
+ const count = countCodeLines(join(root, rel));
47
+ if (count > budget) entries.push({ rel, count, budget });
48
+ }
49
+ return entries;
50
+ }
51
+
52
+ export function runRatchet(root, gateConfig) {
53
+ const baselinePath = join(root, gateConfig.baselineFile || ".orca-flow-ratchet.txt");
54
+ const baseline = existsSync(baselinePath)
55
+ ? new Set(readFileSync(baselinePath, "utf8").split(/\r?\n/).map((l) => l.trim()).filter(Boolean))
56
+ : new Set();
57
+
58
+ const entries = findOversizedFiles(root, gateConfig);
59
+ const oversized = new Set(entries.map((e) => e.rel));
60
+ const errors = [];
61
+
62
+ for (const { rel, count, budget } of entries) {
63
+ if (!baseline.has(rel)) {
64
+ errors.push(`${rel}: ${count} code lines (limit: ${budget})`);
65
+ }
66
+ }
67
+
68
+ for (const entry of baseline) {
69
+ if (!oversized.has(entry)) {
70
+ errors.push(`${entry}: no longer over limit or missing; remove from ${gateConfig.baselineFile}`);
71
+ }
72
+ }
73
+
74
+ return { ok: errors.length === 0, errors, oversizedCount: oversized.size };
75
+ }
76
+
77
+ /**
78
+ * Write or remove the ratchet baseline file to match current oversized legacy files.
79
+ */
80
+ export function updateRatchetBaseline(root, gateConfig) {
81
+ const baselinePath = join(root, gateConfig.baselineFile || ".orca-flow-ratchet.txt");
82
+ const files = findOversizedFiles(root, gateConfig).map((e) => e.rel);
83
+ if (files.length > 0) writeAtomic(baselinePath, `${files.join("\n")}\n`);
84
+ else if (existsSync(baselinePath)) rmSync(baselinePath, { force: true });
85
+ return { baselinePath, count: files.length, files };
86
+ }
87
+
88
+ function buildSteps(root, checkedFiles, preset) {
89
+ const steps = [];
90
+ const jsFiles = checkedFiles.filter((f) => /\.(?:[cm]?js)$/i.test(f) && existsSync(join(root, f)));
91
+ const tsFiles = checkedFiles.filter((f) => /\.(?:[cm]?ts|[jt]sx)$/i.test(f) && existsSync(join(root, f)));
92
+ const pyFiles = checkedFiles.filter((f) => /\.py$/i.test(f) && existsSync(join(root, f)));
93
+
94
+ if (preset === "node-ts") {
95
+ const lintTargets = [...tsFiles, ...jsFiles];
96
+ if (existsSync(join(root, "node_modules/.bin/oxlint")) && lintTargets.length) {
97
+ steps.push({ name: "oxlint", cmd: "npx", args: ["oxlint", "--deny-warnings", ...lintTargets] });
98
+ } else if (jsFiles.length) {
99
+ for (const f of jsFiles) steps.push({ name: `syntax ${f}`, cmd: "node", args: ["--check", f] });
100
+ }
101
+ if (existsSync(join(root, "tsconfig.json")) && existsSync(join(root, "node_modules/.bin/tsc"))) {
102
+ steps.push({ name: "typecheck", cmd: "npx", args: ["tsc", "--noEmit"] });
103
+ }
104
+ } else if (preset === "python" && pyFiles.length) {
105
+ steps.push({ name: "py compile", cmd: "python3", args: ["-m", "py_compile", ...pyFiles] });
106
+ } else if (preset === "go" && checkedFiles.some((f) => f.endsWith(".go"))) {
107
+ steps.push({ name: "go vet", cmd: "go", args: ["vet", "./..."] });
108
+ } else if (preset === "rust" && checkedFiles.some((f) => f.endsWith(".rs"))) {
109
+ steps.push({ name: "cargo check", cmd: "cargo", args: ["check"] });
110
+ } else if (jsFiles.length) {
111
+ for (const f of jsFiles) steps.push({ name: `syntax ${f}`, cmd: "node", args: ["--check", f] });
112
+ }
113
+ return steps;
114
+ }
115
+
116
+ function runStep(root, step) {
117
+ return new Promise((resolve) => {
118
+ const start = Date.now();
119
+ const child = spawn(step.cmd, step.args, { cwd: root, stdio: ["ignore", "pipe", "pipe"] });
120
+ const tail = [];
121
+ const pushLine = (chunk) => {
122
+ for (const line of String(chunk).split(/\r?\n/)) {
123
+ if (!line) continue;
124
+ tail.push(line);
125
+ if (tail.length > 40) tail.shift();
126
+ }
127
+ };
128
+ child.stdout.on("data", pushLine);
129
+ child.stderr.on("data", pushLine);
130
+ child.on("error", (err) => pushLine(err.message));
131
+ child.on("close", (code) => {
132
+ const sec = Math.round((Date.now() - start) / 1000);
133
+ if (code === 0) console.log(`pass ${step.name} (${sec}s)`);
134
+ else console.error(`fail ${step.name} (${code}, ${sec}s)\n${tail.join("\n")}`);
135
+ resolve(code === 0);
136
+ });
137
+ });
138
+ }
139
+
140
+ function fingerprint(root, base, head, files, steps) {
141
+ const hash = createHash("sha256").update(JSON.stringify([base, head, steps]));
142
+ for (const rel of files) {
143
+ const full = join(root, rel);
144
+ const st = lstatSync(full, { throwIfNoEntry: false });
145
+ hash.update(JSON.stringify([rel, st?.mode ?? null]));
146
+ if (st?.isFile()) hash.update(readFileSync(full));
147
+ else if (st?.isSymbolicLink()) hash.update(readlinkSync(full));
148
+ }
149
+ return hash.digest("hex");
150
+ }
151
+
152
+ export async function runGate(argv = [], { cwd = process.cwd() } = {}) {
153
+ const { values } = parseArgs({
154
+ args: argv,
155
+ options: { base: { type: "string" }, force: { type: "boolean", default: false }, "update-baseline": { type: "boolean", default: false } },
156
+ });
157
+ const { root, config } = loadConfig(cwd);
158
+ if (values["update-baseline"]) {
159
+ const res = updateRatchetBaseline(root, config.gate);
160
+ console.log(`ratchet baseline updated (${res.count} oversized)`);
161
+ return 0;
162
+ }
163
+ const base = values.base || config.baseBranch;
164
+ const head = git(root, ["rev-parse", "HEAD"], { allowFail: true })?.trim() || "UNBORN";
165
+ const allChanged = head === "UNBORN" || values.force
166
+ ? (git(root, ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], { allowFail: true }) ?? "").split("\0").filter(Boolean)
167
+ : changedFiles(root, base);
168
+
169
+ const checked = allChanged.filter((f) => !matchesAnyGlob(f, config.gate.ignorePaths));
170
+ if (!checked.length) {
171
+ console.log("pass (no code changes)");
172
+ return 0;
173
+ }
174
+
175
+ const steps = buildSteps(root, checked, config.gate.preset);
176
+ const cacheDir = join(gitCommonDir(root), "orca-flow", "gate-cache");
177
+ const key = fingerprint(root, base, head, allChanged, steps);
178
+ const cacheEntry = join(cacheDir, key);
179
+
180
+ if (!values.force && existsSync(cacheEntry)) {
181
+ console.log("pass (cached)");
182
+ return 0;
183
+ }
184
+
185
+ const ratchet = runRatchet(root, config.gate);
186
+ if (!ratchet.ok) {
187
+ console.error(`fail ratchet\n${ratchet.errors.join("\n")}`);
188
+ return 1;
189
+ }
190
+ console.log(`pass ratchet (${ratchet.oversizedCount} baseline)`);
191
+
192
+ const results = await Promise.all(steps.map((s) => runStep(root, s)));
193
+ if (results.includes(false)) return 1;
194
+
195
+ for (const cmd of config.gate.commands ?? []) {
196
+ try {
197
+ execFileSync("sh", ["-c", cmd], { cwd: root, stdio: "inherit" });
198
+ } catch {
199
+ return 1;
200
+ }
201
+ }
202
+
203
+ writeAtomic(cacheEntry, `${new Date().toISOString()}\n`);
204
+ return 0;
205
+ }
package/src/git.mjs ADDED
@@ -0,0 +1,149 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { resolve } from "node:path";
3
+
4
+ const SHA_RE = /^[0-9a-f]{7,40}$/;
5
+ const PATCH_ID_RE = /^[0-9a-f]{40}$/;
6
+
7
+ const SECRET_PATTERNS = [
8
+ { name: "private key", pattern: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
9
+ { name: "GitHub token", pattern: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b/ },
10
+ { name: "GitHub fine-grained token", pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}\b/ },
11
+ { name: "provider API key", pattern: /\bsk-[A-Za-z0-9_-]{20,}\b/ },
12
+ { name: "AWS access key", pattern: /\bAKIA[0-9A-Z]{16}\b/ },
13
+ { name: "Slack token", pattern: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/ },
14
+ { name: "assigned secret", pattern: /^\s*(?:password|passwd|secret|api[_-]?key|access[_-]?token)\s*[:=]\s*\S+/im },
15
+ ];
16
+
17
+ export function git(cwd, args, { input, allowFail = false } = {}) {
18
+ try {
19
+ return execFileSync("git", args, {
20
+ cwd,
21
+ input,
22
+ encoding: "utf8",
23
+ stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
24
+ maxBuffer: 64 * 1024 * 1024,
25
+ });
26
+ } catch (err) {
27
+ if (allowFail) return null;
28
+ const msg = String(err.stderr || err.message).trim().split("\n")[0];
29
+ throw new Error(`git ${args[0]} failed: ${msg}`);
30
+ }
31
+ }
32
+
33
+ export function gitRoot(cwd = process.cwd()) {
34
+ const out = git(cwd, ["rev-parse", "--show-toplevel"], { allowFail: true });
35
+ return out ? out.trim() : null;
36
+ }
37
+
38
+ export function gitCommonDir(cwd = process.cwd()) {
39
+ const out = git(cwd, ["rev-parse", "--git-common-dir"], { allowFail: true });
40
+ if (!out) throw new Error("Not inside a git repository.");
41
+ return resolve(cwd, out.trim());
42
+ }
43
+
44
+ export function currentBranch(cwd = process.cwd()) {
45
+ return git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]).trim();
46
+ }
47
+
48
+ export function resolveCommit(cwd, revision) {
49
+ if (!revision || typeof revision !== "string") {
50
+ throw new Error("A git revision is required.");
51
+ }
52
+ const sha = git(cwd, ["rev-parse", "--verify", "--quiet", `${revision}^{commit}`], { allowFail: true })?.trim();
53
+ if (!sha || !SHA_RE.test(sha)) {
54
+ throw new Error(`Cannot resolve git revision "${revision}".`);
55
+ }
56
+ return sha;
57
+ }
58
+
59
+ export function mergeBase(cwd, baseRef, headRef = "HEAD") {
60
+ const baseSha = resolveCommit(cwd, baseRef);
61
+ const headSha = resolveCommit(cwd, headRef);
62
+ const mb = git(cwd, ["merge-base", baseSha, headSha], { allowFail: true })?.trim();
63
+ if (!mb || !SHA_RE.test(mb)) {
64
+ throw new Error(`Cannot find merge-base between "${baseRef}" and "${headRef}".`);
65
+ }
66
+ return mb;
67
+ }
68
+
69
+ /**
70
+ * Compute patch-id from merge-base(baseRef, headRef)..headRef so clean rebases keep the same patch-id.
71
+ */
72
+ export function computePatchId(cwd, baseRef, headRef = "HEAD") {
73
+ const headSha = resolveCommit(cwd, headRef);
74
+ const mbSha = mergeBase(cwd, baseRef, headSha);
75
+ if (mbSha === headSha) {
76
+ throw new Error(`Diff between ${baseRef} and ${headRef} is empty.`);
77
+ }
78
+ const diff = git(cwd, ["-c", "core.pager=cat", "diff", "--no-color", "--no-ext-diff", "--no-textconv", `${mbSha}...${headSha}`]);
79
+ if (!diff.trim()) {
80
+ throw new Error(`Diff ${mbSha.slice(0, 7)}...${headSha.slice(0, 7)} is empty.`);
81
+ }
82
+ const output = git(cwd, ["patch-id", "--stable"], { input: diff }).trim();
83
+ const id = output.split(/\s+/)[0];
84
+ if (!PATCH_ID_RE.test(id) || /^0+$/.test(id)) {
85
+ throw new Error("git patch-id failed to return a valid 40-char hash.");
86
+ }
87
+ return { base: baseRef, mergeBase: mbSha, head: headSha, patchId: id };
88
+ }
89
+
90
+ export function changedFiles(cwd, baseRef) {
91
+ const mb = mergeBase(cwd, baseRef, "HEAD");
92
+ const diffArgs = ["diff", "--name-only", "--no-renames", "-z"];
93
+ const raw = [
94
+ git(cwd, [...diffArgs, mb, "HEAD", "--"]),
95
+ git(cwd, [...diffArgs, "--cached", "--"]),
96
+ git(cwd, [...diffArgs, "--"]),
97
+ git(cwd, ["ls-files", "--others", "--exclude-standard", "-z"]),
98
+ ].join("");
99
+ return [...new Set(raw.split("\0").filter(Boolean))].sort();
100
+ }
101
+
102
+ export function capturePosition(cwd = process.cwd()) {
103
+ const branch = currentBranch(cwd);
104
+ const head = resolveCommit(cwd, "HEAD");
105
+ const worktree = gitRoot(cwd);
106
+ const status = git(cwd, ["status", "--porcelain=v1", "--untracked-files=normal"]) ?? "";
107
+ const lines = status.split("\n").filter(Boolean);
108
+ const changed = lines.filter((l) => !l.startsWith("?? ")).map((l) => l.slice(3));
109
+ const untracked = lines.filter((l) => l.startsWith("?? ")).map((l) => l.slice(3));
110
+ const upstreamRef = git(cwd, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], { allowFail: true })?.trim() ?? null;
111
+ let upstream = null;
112
+ if (upstreamRef) {
113
+ const remoteHead = git(cwd, ["rev-parse", "--verify", "--quiet", `${upstreamRef}^{commit}`], { allowFail: true })?.trim() ?? null;
114
+ const counts = git(cwd, ["rev-list", "--left-right", "--count", `HEAD...${upstreamRef}`], { allowFail: true })?.trim() ?? "";
115
+ const [ahead, behind] = counts.split(/\s+/).map(Number);
116
+ upstream = { ref: upstreamRef, head: remoteHead, ahead: Number.isFinite(ahead) ? ahead : 0, behind: Number.isFinite(behind) ? behind : 0 };
117
+ }
118
+ return {
119
+ capturedAt: new Date().toISOString(),
120
+ branch,
121
+ head,
122
+ worktree,
123
+ dirty: { changed, untracked },
124
+ upstream,
125
+ pushed: upstream ? upstream.ahead === 0 : false,
126
+ };
127
+ }
128
+
129
+ export function scanSecrets(text) {
130
+ if (!text) return [];
131
+ return SECRET_PATTERNS.filter(({ pattern }) => pattern.test(text)).map(({ name }) => name);
132
+ }
133
+
134
+ export function globToRegExp(glob) {
135
+ const escaped = glob
136
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
137
+ .replace(/\*\*\//g, "__GLOBSTAR_SLASH__")
138
+ .replace(/\*\*/g, "__GLOBSTAR__")
139
+ .replace(/\*/g, "[^/]*")
140
+ .replace(/\?/g, "[^/]")
141
+ .replace(/__GLOBSTAR_SLASH__/g, "(?:.*/)?")
142
+ .replace(/__GLOBSTAR__/g, ".*");
143
+ return new RegExp(`^${escaped}$`);
144
+ }
145
+
146
+ export function matchesAnyGlob(filePath, patterns = []) {
147
+ const norm = filePath.replace(/\\/g, "/");
148
+ return patterns.some((p) => globToRegExp(p).test(norm));
149
+ }