@danielstyle/featflow 0.0.0-stage → 0.6.4

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 (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +249 -2
  3. package/README.zh-CN.md +250 -0
  4. package/bin/featflow.mjs +116 -0
  5. package/package.json +63 -4
  6. package/skills/featflow/SKILL.md +127 -0
  7. package/skills/featflow-issues/SKILL.md +104 -0
  8. package/skills/featflow-regression/SKILL.md +63 -0
  9. package/src/agent-docs.mjs +143 -0
  10. package/src/changed-files.mjs +204 -0
  11. package/src/commands/cleanup.mjs +221 -0
  12. package/src/commands/codegraph.mjs +108 -0
  13. package/src/commands/doctor.mjs +303 -0
  14. package/src/commands/finish.mjs +249 -0
  15. package/src/commands/hook-cmd.mjs +78 -0
  16. package/src/commands/hooks-cmd.mjs +247 -0
  17. package/src/commands/init.mjs +477 -0
  18. package/src/commands/issue.mjs +434 -0
  19. package/src/commands/new.mjs +311 -0
  20. package/src/commands/plan-check.mjs +75 -0
  21. package/src/commands/policy-cmd.mjs +55 -0
  22. package/src/commands/pr-cleanup.mjs +194 -0
  23. package/src/commands/regression.mjs +206 -0
  24. package/src/commands/setup.mjs +343 -0
  25. package/src/commands/size-check.mjs +137 -0
  26. package/src/commands/skills.mjs +181 -0
  27. package/src/commands/status.mjs +100 -0
  28. package/src/commands/sync.mjs +421 -0
  29. package/src/commands/verify.mjs +206 -0
  30. package/src/commands/worktree.mjs +205 -0
  31. package/src/config.mjs +295 -0
  32. package/src/detect.mjs +314 -0
  33. package/src/git.mjs +331 -0
  34. package/src/hook-adapters.mjs +218 -0
  35. package/src/hooks-core.mjs +420 -0
  36. package/src/index.mjs +14 -0
  37. package/src/init-args.mjs +294 -0
  38. package/src/init-hooks.mjs +312 -0
  39. package/src/init-prompts.mjs +191 -0
  40. package/src/issues-helpers.mjs +463 -0
  41. package/src/issues.mjs +521 -0
  42. package/src/plan.mjs +202 -0
  43. package/src/policy.mjs +143 -0
  44. package/src/regression.mjs +338 -0
  45. package/src/size-check.mjs +203 -0
  46. package/src/skills-manager.mjs +348 -0
  47. package/src/tui-select.mjs +378 -0
  48. package/templates/adapters/antigravity/hooks.json +42 -0
  49. package/templates/adapters/claude-code/settings.json +46 -0
  50. package/templates/adapters/codex/config.toml +19 -0
  51. package/templates/adapters/cursor/hooks.json +27 -0
  52. package/templates/agents/codex/codebase-locator.toml +28 -0
  53. package/templates/agents/codex/implementation-scout.toml +28 -0
  54. package/templates/agents/codex/regression-guard-planner.toml +20 -0
  55. package/templates/features/README.md +56 -0
  56. package/templates/features/_program_template.md +79 -0
  57. package/templates/features/_template.md +120 -0
  58. package/templates/features/current-feature.md +18 -0
  59. package/templates/githooks/post-merge +10 -0
  60. package/templates/githooks/pre-commit +14 -0
  61. package/templates/githooks/pre-push +13 -0
  62. package/templates/regression/regression-ledger.yml +23 -0
  63. package/templates/snippets/AGENTS-workflow.md +21 -0
@@ -0,0 +1,303 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import {
5
+ DEFAULT_AGENT_DOC_CANDIDATES,
6
+ findManagedAgentDocs,
7
+ inspectAgentDocBlock,
8
+ renderAgentWorkflowBlock,
9
+ } from "../agent-docs.mjs";
10
+ import { loadConfig } from "../config.mjs";
11
+ import { commandExists, findGitCommonDir, findRepoRoot, gitConfigGet, localBranchExists } from "../git.mjs";
12
+ import { validateActiveFeaturePlan } from "../plan.mjs";
13
+ import {
14
+ inspectCliAvailability,
15
+ inspectSkillsStatus,
16
+ requiredSkillsForConfig,
17
+ } from "../skills-manager.mjs";
18
+ import { inspectCodegraphState } from "./codegraph.mjs";
19
+ import { inspectSyncState } from "./sync.mjs";
20
+
21
+ const usage = `
22
+ Usage:
23
+ featflow doctor
24
+
25
+ Checks Git, featflow CLI availability, .featflow.json, feature templates,
26
+ global/repo Agent Skills (including drift & shadowing), managed AGENTS.md /
27
+ CLAUDE.md blocks, Git & AI agent hooks, and active feature plan health.
28
+ `.trim();
29
+
30
+ export async function runDoctor(argv) {
31
+ if (argv.includes("-h") || argv.includes("--help")) {
32
+ console.log(usage);
33
+ return;
34
+ }
35
+
36
+ const checks = [];
37
+ const add = (status, label, detail) => checks.push({ status, label, detail });
38
+
39
+ add(commandExists("git") ? "PASS" : "FAIL", "Git CLI", commandExists("git") ? "available" : "git not found");
40
+ add(
41
+ commandExists("gh") ? "PASS" : "INFO",
42
+ "GitHub CLI (gh)",
43
+ commandExists("gh") ? "available (for issue & pr-cleanup)" : "optional — needed only for issue & pr-cleanup",
44
+ );
45
+
46
+ const repoRoot = findRepoRoot(process.cwd());
47
+ if (!repoRoot) {
48
+ add("FAIL", "Git repository", "Not inside a Git repository.");
49
+ printChecks(checks);
50
+ process.exit(1);
51
+ }
52
+
53
+ const configuredAgentHooks = [];
54
+ if (existsSync(path.join(repoRoot, ".agents", "hooks.json"))) configuredAgentHooks.push("antigravity");
55
+ if (existsSync(path.join(repoRoot, ".claude", "settings.json"))) configuredAgentHooks.push("claude-code");
56
+ if (existsSync(path.join(repoRoot, ".codex", "config.toml"))) configuredAgentHooks.push("codex");
57
+ if (existsSync(path.join(repoRoot, ".cursor", "hooks.json"))) configuredAgentHooks.push("cursor");
58
+
59
+ const cliState = inspectCliAvailability(repoRoot);
60
+ if (cliState.onPath) {
61
+ add("PASS", "featflow CLI", "available on PATH");
62
+ } else if (configuredAgentHooks.length > 0) {
63
+ add(
64
+ "WARN",
65
+ "featflow CLI",
66
+ "not on PATH (configured AI agent hooks invoke `featflow hook ...` directly; run `npm install -g @danielstyle/featflow`)",
67
+ );
68
+ } else if (cliState.localBin || cliState.mainLocalBin) {
69
+ add("PASS", "featflow CLI", "available via local node_modules/.bin/featflow");
70
+ } else {
71
+ add("INFO", "featflow CLI", "not on PATH (install globally via `npm install -g @danielstyle/featflow` for direct shell/hook usage)");
72
+ }
73
+
74
+ let loaded;
75
+ try {
76
+ loaded = loadConfig(repoRoot);
77
+ add(
78
+ loaded.hasConfigFile ? "PASS" : "INFO",
79
+ "Config (.featflow.json)",
80
+ loaded.hasConfigFile
81
+ ? `mode=${loaded.config.mode}`
82
+ : "not found (using global defaults; run `featflow init --minimal` to customize)",
83
+ );
84
+ } catch (error) {
85
+ add("FAIL", "Config (.featflow.json)", error instanceof Error ? error.message : String(error));
86
+ printChecks(checks);
87
+ process.exit(1);
88
+ }
89
+
90
+ const { config } = loaded;
91
+
92
+ const templatePath = path.join(repoRoot, config.featuresDir, "_template.md");
93
+ const hasRepoTemplates =
94
+ existsSync(templatePath) ||
95
+ existsSync(path.join(repoRoot, config.featuresDir, "README.md")) ||
96
+ existsSync(path.join(repoRoot, config.featuresDir, "_program_template.md"));
97
+
98
+ if (existsSync(templatePath)) {
99
+ add("PASS", "Feature template", path.relative(repoRoot, templatePath));
100
+ } else {
101
+ add("PASS", "Feature template", "using built-in template (global/minimal mode)");
102
+ }
103
+
104
+ const requiredSkills = requiredSkillsForConfig(config);
105
+ const ensureAgents = [
106
+ "agents",
107
+ ...(configuredAgentHooks.includes("claude-code") ? ["claude-code"] : []),
108
+ ...(configuredAgentHooks.includes("codex") ? ["codex"] : []),
109
+ ...(configuredAgentHooks.includes("cursor") ? ["cursor"] : []),
110
+ ];
111
+ const skillReport = inspectSkillsStatus({
112
+ repoRoot,
113
+ skillNames: requiredSkills,
114
+ ensureAgents,
115
+ });
116
+
117
+ const allInRepo = skillReport.skills.every((s) => s.hasRepoCopy);
118
+ if (allInRepo) {
119
+ add("PASS", "Agent Skill", `repo (.agents/skills/: ${requiredSkills.join(", ")})`);
120
+ const staleShadows = skillReport.skills.filter((s) => s.repoStaleShadow).map((s) => s.name);
121
+ if (staleShadows.length > 0) {
122
+ add(
123
+ "WARN",
124
+ "Skill precedence",
125
+ `repo .agents/skills/ (${staleShadows.join(", ")}) is outdated and shadows global skills (run \`featflow sync\` or remove repo copies to follow global updates)`,
126
+ );
127
+ } else if (skillReport.shadowedSkills.length > 0) {
128
+ add(
129
+ "INFO",
130
+ "Skill precedence",
131
+ `repo .agents/skills/ (${skillReport.shadowedSkills.join(", ")}) takes precedence over global skills in this repo`,
132
+ );
133
+ }
134
+ } else if (skillReport.allGlobalReady) {
135
+ add(
136
+ "PASS",
137
+ "Agent Skill",
138
+ `global (${requiredSkills.join(", ")} in ${skillReport.targets.map((t) => t.displayDir).join(", ")})`,
139
+ );
140
+ } else {
141
+ const parts = [];
142
+ if (skillReport.missingSkills.length > 0) {
143
+ parts.push(`missing: ${skillReport.missingSkills.join(", ")}`);
144
+ }
145
+ if (skillReport.driftedSkills.length > 0) {
146
+ parts.push(`outdated: ${skillReport.driftedSkills.join(", ")}`);
147
+ }
148
+ const pending = [...new Set([...skillReport.missingSkills, ...skillReport.driftedSkills])];
149
+ add(
150
+ "WARN",
151
+ "Agent Skill",
152
+ `${parts.join("; ")} (run \`featflow skills install\` or \`npx skills add https://github.com/daniel-style/featflow --skill ${pending.join(" ")} -g\`)`,
153
+ );
154
+ }
155
+
156
+ const managedAgentDocs = findManagedAgentDocs(repoRoot);
157
+ if (managedAgentDocs.length > 0) {
158
+ const renderedBlock = renderAgentWorkflowBlock();
159
+ const driftedDocs = managedAgentDocs.filter(
160
+ (rel) => inspectAgentDocBlock(path.resolve(repoRoot, rel), renderedBlock).status !== "up-to-date",
161
+ );
162
+ if (driftedDocs.length === 0) {
163
+ add("PASS", "Agent docs", `${managedAgentDocs.join(", ")} (managed block up to date)`);
164
+ } else {
165
+ add("WARN", "Agent docs", `drifted: ${driftedDocs.join(", ")} (run \`featflow sync\`)`);
166
+ }
167
+ } else {
168
+ const existingRawDocs = DEFAULT_AGENT_DOC_CANDIDATES.filter((rel) => existsSync(path.join(repoRoot, rel)));
169
+ if (existingRawDocs.length > 0) {
170
+ add(
171
+ "INFO",
172
+ "Agent docs",
173
+ `${existingRawDocs.join(", ")} has no featflow managed block (run \`featflow sync --only agent-docs\`)`,
174
+ );
175
+ } else {
176
+ add("INFO", "Agent docs", "no AGENTS.md/CLAUDE.md managed block (run `featflow sync --only agent-docs` or `featflow init`)");
177
+ }
178
+ }
179
+
180
+ const hasRepoSkill = existsSync(path.join(repoRoot, ".agents", "skills", "featflow", "SKILL.md"));
181
+ const hasIssuesSkill = existsSync(path.join(repoRoot, ".agents", "skills", "featflow-issues", "SKILL.md"));
182
+ const hasRegressionSkill = existsSync(path.join(repoRoot, ".agents", "skills", "featflow-regression", "SKILL.md"));
183
+ if (config.issues) {
184
+ const assetsDetail = config.issues.assetsRepo ? `, assetsRepo=${config.issues.assetsRepo}` : "";
185
+ add("PASS", "Issues workflow", `enabled (${config.issues.provider}${assetsDetail})`);
186
+ }
187
+ if (config.fileSizeBudget) {
188
+ const preCommitTag = config.fileSizeBudget.enforceInPreCommit ? ", pre-commit=on" : "";
189
+ add(
190
+ "PASS",
191
+ "File size budget",
192
+ `enabled (prod=${config.fileSizeBudget.production}, style=${config.fileSizeBudget.style}, test=${config.fileSizeBudget.test}${preCommitTag})`,
193
+ );
194
+ }
195
+ if (config.regression) {
196
+ const ledgerExists = existsSync(path.resolve(repoRoot, config.regression.ledgerFile));
197
+ add(
198
+ ledgerExists ? "PASS" : "WARN",
199
+ "Regression ledger",
200
+ ledgerExists ? config.regression.ledgerFile : `configured "${config.regression.ledgerFile}" not found`,
201
+ );
202
+ }
203
+
204
+ if (configuredAgentHooks.length > 0) {
205
+ add("PASS", "AI Agent hooks", configuredAgentHooks.join(", "));
206
+ } else {
207
+ add("INFO", "AI Agent hooks", "none installed (run `featflow init --merge --with-all-hooks` or interactive `featflow init --merge`)");
208
+ }
209
+
210
+ const cg = inspectCodegraphState(repoRoot);
211
+ if (cg.installed) {
212
+ add("PASS", "CodeGraph", cg.indexed ? "CLI available, local index present" : "CLI available (run `featflow codegraph` to index)");
213
+ } else {
214
+ add("INFO", "CodeGraph", "optional — CLI not installed");
215
+ }
216
+
217
+ const syncGroups = new Set();
218
+ if (hasRepoSkill) {
219
+ syncGroups.add("skill");
220
+ }
221
+ if (hasIssuesSkill || (Boolean(config.issues) && hasRepoSkill)) {
222
+ syncGroups.add("issues-skill");
223
+ }
224
+ if (hasRegressionSkill || (Boolean(config.regression) && hasRepoSkill)) {
225
+ syncGroups.add("regression-skill");
226
+ }
227
+ if (hasRepoTemplates) {
228
+ syncGroups.add("templates");
229
+ }
230
+ if (existsSync(path.join(repoRoot, ".githooks"))) {
231
+ syncGroups.add("githooks");
232
+ }
233
+ if (managedAgentDocs.length > 0) {
234
+ syncGroups.add("agent-docs");
235
+ }
236
+
237
+ if (syncGroups.size === 0) {
238
+ add("PASS", "Managed files sync", "zero-footprint mode (no repo-managed files)");
239
+ } else {
240
+ const syncState = inspectSyncState(repoRoot, config, syncGroups);
241
+ if (syncState.ok) {
242
+ add("PASS", "Managed files sync", `${syncState.upToDate.length} files match installed featflow`);
243
+ } else {
244
+ const issues = [
245
+ ...syncState.missing.map((item) => `missing ${item.rel}`),
246
+ ...syncState.drifted.map((item) => `drifted ${item.rel}`),
247
+ ];
248
+ add("WARN", "Managed files sync", `${issues.join(", ")} (run \`featflow sync\`)`);
249
+ }
250
+ }
251
+
252
+ const hooksPath = gitConfigGet("core.hooksPath", repoRoot);
253
+ const commonDir = findGitCommonDir(repoRoot);
254
+ const localPreCommit = commonDir ? path.join(commonDir, "hooks", "pre-commit") : "";
255
+ const hasLocalHook = Boolean(localPreCommit && existsSync(localPreCommit) && readFileSync(localPreCommit, "utf8").includes("featflow managed hook"));
256
+ if (hooksPath === ".githooks") {
257
+ add("PASS", "Git hooks", "core.hooksPath=.githooks");
258
+ } else if (hooksPath) {
259
+ add("INFO", "Git hooks", `external hooks manager detected (core.hooksPath=${hooksPath})`);
260
+ } else if (hasLocalHook) {
261
+ add("PASS", "Git hooks", "local .git/hooks managed blocks installed");
262
+ } else {
263
+ add("INFO", "Git hooks", "not configured (run `featflow hooks install --local` or `featflow init --with-githooks`)");
264
+ }
265
+
266
+ if (config.mode === "developer-branch") {
267
+ const devBranch = gitConfigGet(config.developerBranchConfigKey, repoRoot);
268
+ if (!devBranch) {
269
+ add("FAIL", "Developer branch", `not configured (run \`featflow setup <your-branch>\`)`);
270
+ } else if (!localBranchExists(devBranch, repoRoot)) {
271
+ add("FAIL", "Developer branch", `configured "${devBranch}" does not exist locally`);
272
+ } else {
273
+ add("PASS", "Developer branch", devBranch);
274
+ }
275
+ } else {
276
+ add(
277
+ localBranchExists(config.baseBranch, repoRoot) ? "PASS" : "WARN",
278
+ "Base branch",
279
+ localBranchExists(config.baseBranch, repoRoot) ? config.baseBranch : `local branch "${config.baseBranch}" not found yet`,
280
+ );
281
+ }
282
+
283
+ const plan = validateActiveFeaturePlan(repoRoot, { featuresDir: config.featuresDir });
284
+ if (plan.skipped) {
285
+ add("PASS", "Active feature plan", "no active feature record");
286
+ } else if (plan.ok) {
287
+ add("PASS", "Active feature plan", `${plan.activeFeature} is complete and approved`);
288
+ } else {
289
+ add("WARN", "Active feature plan", `${plan.activeFeature}: ${plan.errors.join("; ")}`);
290
+ }
291
+
292
+ printChecks(checks);
293
+
294
+ if (checks.some((item) => item.status === "FAIL")) {
295
+ process.exit(1);
296
+ }
297
+ }
298
+
299
+ function printChecks(checks) {
300
+ for (const item of checks) {
301
+ console.log(`[${item.status}] ${item.label}: ${item.detail}`);
302
+ }
303
+ }
@@ -0,0 +1,249 @@
1
+ import path from "node:path";
2
+
3
+ import { loadConfig, resolveWorktreeParent } from "../config.mjs";
4
+ import {
5
+ ensureCleanWorktree,
6
+ fail,
7
+ findWorktreeForBranch,
8
+ gitConfigGet,
9
+ gitWorktrees,
10
+ isInsidePath,
11
+ localBranchExists,
12
+ remoteExists,
13
+ remoteTrackingBranchExists,
14
+ runWrite,
15
+ sanitizeBranchForDir,
16
+ validateTaskBranchName,
17
+ } from "../git.mjs";
18
+ import { setupInstructions } from "../policy.mjs";
19
+ import { cleanupMergedTaskBranches } from "./cleanup.mjs";
20
+
21
+ const usage = `
22
+ Usage:
23
+ featflow finish <task-branch> [options]
24
+
25
+ Completes a verified task branch:
26
+ - In developer-branch mode: merges into your personal developer branch,
27
+ pushes it (unless --no-push or offline), and removes the clean task worktree & branch.
28
+ - In trunk mode (finishTarget=merge): merges into baseBranch, pushes if remote exists
29
+ (unless --no-push), and removes the clean task worktree & branch.
30
+ - In trunk mode (finishTarget=pr or --pr): pushes the task branch so you can open a PR,
31
+ keeping the worktree until "featflow pr-cleanup <pr>" runs after merge.
32
+
33
+ Options:
34
+ --developer <branch> Override configured developer branch.
35
+ --remote <name> Remote to fetch/push. Defaults to config.remote.
36
+ --worktree <path> Override the task worktree path.
37
+ --pr Push task branch for a pull request instead of merging locally.
38
+ --no-push Skip fetching from and pushing to the remote.
39
+ --dry-run Print mutating commands without running them.
40
+ --keep-worktree Do not remove the task worktree.
41
+ --keep-branch Do not delete the local task branch.
42
+ -h, --help Show this help.
43
+ `.trim();
44
+
45
+ function parseArgs(argv) {
46
+ const options = {
47
+ developer: "",
48
+ dryRun: false,
49
+ keepBranch: false,
50
+ keepWorktree: false,
51
+ noPush: false,
52
+ pr: false,
53
+ remote: "",
54
+ taskBranch: "",
55
+ worktree: "",
56
+ };
57
+ const positional = [];
58
+
59
+ for (let i = 0; i < argv.length; i += 1) {
60
+ const arg = argv[i];
61
+ if (arg === "-h" || arg === "--help") {
62
+ console.log(usage);
63
+ process.exit(0);
64
+ }
65
+ if (arg === "--dry-run") {
66
+ options.dryRun = true;
67
+ continue;
68
+ }
69
+ if (arg === "--no-push") {
70
+ options.noPush = true;
71
+ continue;
72
+ }
73
+ if (arg === "--pr") {
74
+ options.pr = true;
75
+ continue;
76
+ }
77
+ if (arg === "--keep-worktree") {
78
+ options.keepWorktree = true;
79
+ continue;
80
+ }
81
+ if (arg === "--keep-branch") {
82
+ options.keepBranch = true;
83
+ continue;
84
+ }
85
+ if (arg === "--developer" || arg === "--remote" || arg === "--worktree") {
86
+ options[arg.slice(2)] = argv[++i] ?? "";
87
+ continue;
88
+ }
89
+ if (arg.startsWith("--developer=") || arg.startsWith("--remote=") || arg.startsWith("--worktree=")) {
90
+ const idx = arg.indexOf("=");
91
+ options[arg.slice(2, idx)] = arg.slice(idx + 1);
92
+ continue;
93
+ }
94
+ if (arg.startsWith("-")) {
95
+ fail(`Unknown option: ${arg}`, usage);
96
+ }
97
+ positional.push(arg);
98
+ }
99
+
100
+ if (positional.length !== 1) {
101
+ fail("Expected exactly one task branch name.", usage);
102
+ }
103
+ options.taskBranch = positional[0];
104
+ return options;
105
+ }
106
+
107
+ function ensureTargetWorktree(repoRoot, config, targetBranch, options) {
108
+ let worktrees = gitWorktrees(repoRoot);
109
+ let targetWorktree = findWorktreeForBranch(worktrees, targetBranch);
110
+ if (targetWorktree) {
111
+ return targetWorktree;
112
+ }
113
+
114
+ const parent = resolveWorktreeParent(repoRoot, config);
115
+ const worktreePath = path.join(parent, sanitizeBranchForDir(targetBranch));
116
+ runWrite("git", ["worktree", "add", worktreePath, targetBranch], repoRoot, options);
117
+ if (options.dryRun) {
118
+ return { path: worktreePath, dryRunMissing: true };
119
+ }
120
+ worktrees = gitWorktrees(repoRoot);
121
+ targetWorktree = findWorktreeForBranch(worktrees, targetBranch);
122
+ if (!targetWorktree) {
123
+ throw new Error(`Could not find worktree for ${targetBranch} after creating ${worktreePath}.`);
124
+ }
125
+ return targetWorktree;
126
+ }
127
+
128
+ export async function runFinish(argv) {
129
+ const options = parseArgs(argv);
130
+ const { config, repoRoot } = loadConfig(process.cwd());
131
+ const remote = options.remote || config.remote;
132
+
133
+ try {
134
+ validateTaskBranchName(options.taskBranch, repoRoot, new Set(config.protectedBranches));
135
+ } catch (error) {
136
+ fail(error instanceof Error ? error.message : String(error));
137
+ }
138
+
139
+ if (!localBranchExists(options.taskBranch, repoRoot)) {
140
+ fail(`Local task branch "${options.taskBranch}" does not exist.`);
141
+ }
142
+
143
+ const taskWorktree = options.worktree
144
+ ? { path: path.resolve(options.worktree) }
145
+ : findWorktreeForBranch(gitWorktrees(repoRoot), options.taskBranch);
146
+
147
+ if (taskWorktree) {
148
+ ensureCleanWorktree(taskWorktree.path, "task");
149
+ }
150
+
151
+ const hasRemote = !options.noPush && remoteExists(remote, repoRoot);
152
+
153
+ // PR-based finish (trunk + pr strategy or explicit --pr)
154
+ if (options.pr || (config.mode === "trunk" && config.finishTarget === "pr")) {
155
+ const pushCwd = taskWorktree?.path ?? repoRoot;
156
+ if (hasRemote) {
157
+ runWrite("git", ["push", "-u", remote, options.taskBranch], pushCwd, { dryRun: options.dryRun });
158
+ }
159
+ const base = config.mode === "developer-branch" ? config.integrationBranch : config.baseBranch;
160
+ console.log(`Task branch ready for pull request: ${options.taskBranch}`);
161
+ console.log(`Open PR: gh pr create --base ${base} --head ${options.taskBranch}`);
162
+ console.log("After merge, clean up locally with: featflow pr-cleanup <pr-number>");
163
+ return;
164
+ }
165
+
166
+ let targetBranch = config.baseBranch;
167
+ let developerBranch = "";
168
+
169
+ if (config.mode === "developer-branch") {
170
+ developerBranch = options.developer || gitConfigGet(config.developerBranchConfigKey, repoRoot);
171
+ if (!developerBranch) {
172
+ fail(setupInstructions(config));
173
+ }
174
+ targetBranch = developerBranch;
175
+ }
176
+
177
+ if (options.taskBranch === targetBranch) {
178
+ fail(`Task branch and target branch (${targetBranch}) must be different.`);
179
+ }
180
+ if (!localBranchExists(targetBranch, repoRoot)) {
181
+ fail(`Local target branch "${targetBranch}" does not exist.`);
182
+ }
183
+
184
+ const targetWorktree = ensureTargetWorktree(repoRoot, config, targetBranch, { dryRun: options.dryRun });
185
+ if (!targetWorktree.dryRunMissing) {
186
+ ensureCleanWorktree(targetWorktree.path, "target");
187
+ }
188
+
189
+ const internalEnv = config.mode === "trunk" ? { FEATFLOW_INTERNAL_FINISH: "1" } : undefined;
190
+
191
+ if (hasRemote) {
192
+ runWrite("git", ["fetch", remote, targetBranch], targetWorktree.path, { dryRun: options.dryRun });
193
+ if (remoteTrackingBranchExists(remote, targetBranch, targetWorktree.path)) {
194
+ runWrite("git", ["merge", "--ff-only", `${remote}/${targetBranch}`], targetWorktree.path, {
195
+ dryRun: options.dryRun,
196
+ env: internalEnv,
197
+ });
198
+ }
199
+ }
200
+
201
+ // Move out of task worktree BEFORE merging so post-merge hooks & worktree removal succeed
202
+ if (taskWorktree && !options.keepWorktree && isInsidePath(process.cwd(), taskWorktree.path)) {
203
+ process.chdir(targetWorktree.path);
204
+ }
205
+
206
+ runWrite("git", ["merge", "--no-edit", options.taskBranch], targetWorktree.path, {
207
+ dryRun: options.dryRun,
208
+ env: internalEnv,
209
+ });
210
+
211
+ if (hasRemote) {
212
+ runWrite("git", ["push", remote, targetBranch], targetWorktree.path, {
213
+ dryRun: options.dryRun,
214
+ env: internalEnv,
215
+ });
216
+ }
217
+
218
+ const remainingTaskWorktree = findWorktreeForBranch(gitWorktrees(targetWorktree.path), options.taskBranch);
219
+ if (remainingTaskWorktree && !options.keepWorktree) {
220
+ if (isInsidePath(process.cwd(), remainingTaskWorktree.path)) {
221
+ process.chdir(targetWorktree.path);
222
+ }
223
+ runWrite("git", ["worktree", "remove", remainingTaskWorktree.path], targetWorktree.path, {
224
+ dryRun: options.dryRun,
225
+ });
226
+ }
227
+
228
+ if (!options.keepBranch && localBranchExists(options.taskBranch, targetWorktree.path)) {
229
+ runWrite("git", ["branch", "-d", options.taskBranch], targetWorktree.path, { dryRun: options.dryRun });
230
+ }
231
+
232
+ cleanupMergedTaskBranches({
233
+ cwd: targetWorktree.path,
234
+ config,
235
+ targetBranch,
236
+ developerBranch,
237
+ dryRun: options.dryRun,
238
+ excludeBranches: options.keepBranch || options.keepWorktree ? [options.taskBranch] : [],
239
+ });
240
+
241
+ const prefix = options.dryRun ? "Dry run complete:" : "Target branch updated:";
242
+ const suffix = hasRemote ? "" : " (local only)";
243
+ console.log(`${prefix} ${targetBranch}${suffix}`);
244
+ if (config.mode === "developer-branch") {
245
+ console.log(
246
+ `No PR was opened. Create a PR to ${config.integrationBranch} only when ${targetBranch} is ready for team integration.`,
247
+ );
248
+ }
249
+ }
@@ -0,0 +1,78 @@
1
+ import { loadConfig } from "../config.mjs";
2
+ import { fail } from "../git.mjs";
3
+ import {
4
+ dispatchHookAdapter,
5
+ resolveHookCwd,
6
+ SUPPORTED_HOOK_ADAPTERS,
7
+ SUPPORTED_HOOK_EVENTS,
8
+ } from "../hook-adapters.mjs";
9
+
10
+ const usage = `
11
+ Usage:
12
+ featflow hook <codex|claude-code|antigravity|cursor> <event>
13
+
14
+ Supported events:
15
+ codex / claude-code: pre-tool-use | post-tool-use | user-prompt | stop
16
+ antigravity: pre-invocation | pre-tool-use | post-tool-use | stop
17
+ cursor: before-submit-prompt | pre-tool-use | post-tool-use | stop
18
+
19
+ Reads hook JSON from stdin and emits the adapter-appropriate response and exit code.
20
+ `.trim();
21
+
22
+ async function readStdinJson() {
23
+ const chunks = [];
24
+ for await (const chunk of process.stdin) {
25
+ chunks.push(chunk);
26
+ }
27
+ const raw = Buffer.concat(chunks).toString("utf8").trim();
28
+ if (!raw) {
29
+ return {};
30
+ }
31
+ try {
32
+ return JSON.parse(raw);
33
+ } catch {
34
+ return { _raw: raw };
35
+ }
36
+ }
37
+
38
+ export async function runHook(argv) {
39
+ const [adapter, event] = argv;
40
+ if (!adapter || adapter === "-h" || adapter === "--help") {
41
+ console.log(usage);
42
+ return;
43
+ }
44
+
45
+ if (!SUPPORTED_HOOK_ADAPTERS.includes(adapter)) {
46
+ fail(
47
+ `Unsupported hook adapter "${adapter}". Expected one of: ${SUPPORTED_HOOK_ADAPTERS.join(", ")}.`,
48
+ usage,
49
+ );
50
+ }
51
+ const validEvents = SUPPORTED_HOOK_EVENTS[adapter] ?? [];
52
+ if (!validEvents.includes(event ?? "")) {
53
+ fail(
54
+ `Unsupported hook event "${event ?? ""}" for adapter "${adapter}". Expected one of: ${validEvents.join(", ")}.`,
55
+ usage,
56
+ );
57
+ }
58
+
59
+ const rawInput = await readStdinJson();
60
+ const startCwd = resolveHookCwd(rawInput, process.cwd());
61
+ const { config, repoRoot } = loadConfig(startCwd);
62
+
63
+ const outcome = dispatchHookAdapter(adapter, event, rawInput, {
64
+ repoRoot,
65
+ config,
66
+ env: process.env,
67
+ });
68
+
69
+ if (outcome.stdout) {
70
+ process.stdout.write(outcome.stdout);
71
+ }
72
+ if (outcome.stderr) {
73
+ process.stderr.write(outcome.stderr);
74
+ }
75
+ if (outcome.exitCode && outcome.exitCode !== 0) {
76
+ process.exit(outcome.exitCode);
77
+ }
78
+ }