@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,206 @@
1
+ import { spawnSync } from "node:child_process";
2
+
3
+ import { loadConfig } from "../config.mjs";
4
+ import { fail, findRepoRoot } from "../git.mjs";
5
+ import { analyzeRegressionImpact, validateRegressionLedger } from "../regression.mjs";
6
+
7
+ const usage = `
8
+ Usage:
9
+ featflow regression <impact|check|validate> [options]
10
+
11
+ Inspects or validates the repository's regression memory ledger (YAML or JSON)
12
+ configured via \`regression.ledgerFile\` in .featflow.json.
13
+
14
+ Subcommands:
15
+ impact Find regression entries whose \`files\` patterns match changed files
16
+ check Shorthand for \`impact --run\` (runs every matched regression command)
17
+ validate Validate ledger schema, duplicate IDs, and referenced guard paths
18
+
19
+ Options:
20
+ --ledger <path> Override ledger path (defaults to regression.ledgerFile)
21
+ --base <ref> Override git diff base ref
22
+ --head <ref> Override git diff head ref (default: HEAD)
23
+ --files <paths...> Evaluate explicit file paths instead of git diff
24
+ --run Execute all unique verification commands for impacted entries
25
+ --strict (validate) Exit non-zero if any concrete guard file path is missing on disk
26
+ --dry-run Preview commands with --run without executing them
27
+ --json Output machine-readable JSON
28
+ -h, --help Show this help
29
+ `.trim();
30
+
31
+ function parseArgs(argv) {
32
+ const options = {
33
+ subcommand: "",
34
+ ledgerFile: "",
35
+ base: "",
36
+ head: "",
37
+ files: [],
38
+ run: false,
39
+ strict: false,
40
+ dryRun: false,
41
+ json: false,
42
+ };
43
+
44
+ for (let i = 0; i < argv.length; i += 1) {
45
+ const arg = argv[i];
46
+ if (arg === "-h" || arg === "--help") {
47
+ console.log(usage);
48
+ process.exit(0);
49
+ }
50
+ if (arg === "--run") {
51
+ options.run = true;
52
+ continue;
53
+ }
54
+ if (arg === "--strict") {
55
+ options.strict = true;
56
+ continue;
57
+ }
58
+ if (arg === "--dry-run") {
59
+ options.dryRun = true;
60
+ continue;
61
+ }
62
+ if (arg === "--json") {
63
+ options.json = true;
64
+ continue;
65
+ }
66
+ if (arg === "--ledger" || arg === "--base" || arg === "--head") {
67
+ const value = argv[++i] ?? "";
68
+ if (!value) fail(`Missing value for ${arg}.`, usage);
69
+ options[arg === "--ledger" ? "ledgerFile" : arg.slice(2)] = value;
70
+ continue;
71
+ }
72
+ if (/^--(?:ledger|base|head)=/.test(arg)) {
73
+ const idx = arg.indexOf("=");
74
+ const key = arg.slice(2, idx);
75
+ options[key === "ledger" ? "ledgerFile" : key] = arg.slice(idx + 1);
76
+ continue;
77
+ }
78
+ if (arg === "--files") {
79
+ while (i + 1 < argv.length && !argv[i + 1].startsWith("-")) {
80
+ options.files.push(argv[++i]);
81
+ }
82
+ continue;
83
+ }
84
+ if (arg.startsWith("-")) {
85
+ fail(`Unknown option for regression: ${arg}`, usage);
86
+ }
87
+ if (!options.subcommand) {
88
+ options.subcommand = arg;
89
+ } else {
90
+ options.files.push(arg);
91
+ }
92
+ }
93
+
94
+ return options;
95
+ }
96
+
97
+ export async function runRegression(argv, forcedSubcommand = "") {
98
+ const options = parseArgs(argv);
99
+ const sub = forcedSubcommand || options.subcommand;
100
+ if (!sub) {
101
+ console.log(usage);
102
+ return;
103
+ }
104
+
105
+ const repoRoot = findRepoRoot(process.cwd());
106
+ if (!repoRoot) {
107
+ fail("Not inside a Git repository.");
108
+ }
109
+ const { config } = loadConfig(repoRoot);
110
+
111
+ try {
112
+ if (sub === "validate") {
113
+ const result = validateRegressionLedger(repoRoot, config, options);
114
+ if (options.json) {
115
+ console.log(JSON.stringify(result, null, 2));
116
+ if (!result.ok) process.exit(1);
117
+ return;
118
+ }
119
+ if (!result.ok) {
120
+ console.error(`Regression ledger validation failed (${result.ledgerFile}):`);
121
+ for (const err of result.errors) console.error(` [error] ${err}`);
122
+ for (const warn of result.warnings) console.error(` [warn] ${warn}`);
123
+ process.exit(1);
124
+ }
125
+ console.log(`Regression ledger valid: ${result.ledgerFile} (${result.entryCount} entries).`);
126
+ if (result.warnings.length > 0) {
127
+ console.warn(`Warnings (${result.warnings.length}):`);
128
+ for (const warn of result.warnings.slice(0, 10)) console.warn(` - ${warn}`);
129
+ if (result.warnings.length > 10) console.warn(` ... and ${result.warnings.length - 10} more`);
130
+ }
131
+ return;
132
+ }
133
+
134
+ if (sub === "impact" || sub === "check") {
135
+ const shouldRun = options.run || sub === "check";
136
+ const report = analyzeRegressionImpact(repoRoot, config, options);
137
+ const executions = [];
138
+
139
+ if (shouldRun && report.uniqueCommands.length > 0) {
140
+ for (const cmd of report.uniqueCommands) {
141
+ if (options.dryRun) {
142
+ executions.push({ command: cmd, ok: true, skipped: true, exitCode: 0 });
143
+ continue;
144
+ }
145
+ const res = spawnSync(cmd, [], {
146
+ cwd: repoRoot,
147
+ shell: true,
148
+ stdio: options.json ? ["ignore", "pipe", "pipe"] : "inherit",
149
+ encoding: "utf8",
150
+ });
151
+ executions.push({
152
+ command: cmd,
153
+ ok: res.status === 0,
154
+ skipped: false,
155
+ exitCode: res.status ?? -1,
156
+ });
157
+ }
158
+ }
159
+
160
+ const allPassed = executions.every((e) => e.ok);
161
+ const payload = { ...report, executions, ok: report.ok && allPassed };
162
+
163
+ if (options.json) {
164
+ console.log(JSON.stringify(payload, null, 2));
165
+ if (!payload.ok) process.exit(1);
166
+ return;
167
+ }
168
+
169
+ if (report.impacted.length === 0) {
170
+ console.log(`No regression ledger entries impacted (${report.changedFiles.length} changed file(s) checked against ${report.entryCount} entries).`);
171
+ return;
172
+ }
173
+
174
+ console.log(`Impacted regression entries (${report.impacted.length} of ${report.entryCount}):`);
175
+ for (const item of report.impacted) {
176
+ console.log(`- [${item.status}] ${item.id}: ${item.title}`);
177
+ console.log(` Matched: ${item.matchedFiles.join(", ")}`);
178
+ console.log(` Invariant: ${item.invariant}`);
179
+ if (item.commands.length > 0) {
180
+ console.log(` Commands: ${item.commands.join(" ; ")}`);
181
+ }
182
+ if (item.missingGuards.length > 0) {
183
+ console.log(` Missing guards: ${item.missingGuards.join(", ")}`);
184
+ }
185
+ }
186
+
187
+ if (shouldRun && executions.length > 0) {
188
+ console.log("");
189
+ console.log("Executed regression guard commands:");
190
+ for (const exec of executions) {
191
+ const tag = exec.skipped ? "DRY-RUN" : exec.ok ? "PASS" : "FAIL";
192
+ console.log(` [${tag}] ${exec.command}`);
193
+ }
194
+ }
195
+
196
+ if (!payload.ok) {
197
+ process.exit(1);
198
+ }
199
+ return;
200
+ }
201
+
202
+ fail(`Unknown regression subcommand "${sub}".`, usage);
203
+ } catch (error) {
204
+ fail(error instanceof Error ? error.message : String(error));
205
+ }
206
+ }
@@ -0,0 +1,343 @@
1
+ import { existsSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import { loadConfig } from "../config.mjs";
5
+ import {
6
+ fail,
7
+ gitConfigGet,
8
+ gitConfigSet,
9
+ localBranchExists,
10
+ remoteBranchExists,
11
+ remoteExists,
12
+ remoteTrackingBranchExists,
13
+ runWrite,
14
+ validateDeveloperBranchName,
15
+ } from "../git.mjs";
16
+ import { createPromptReader, createSmartPrompter, promptSingleSelect } from "../tui-select.mjs";
17
+ import { configureGitHooksSafely } from "./hooks-cmd.mjs";
18
+
19
+ export { createPromptReader };
20
+
21
+ const usage = `
22
+ Usage:
23
+ featflow setup [developer-branch] [options]
24
+
25
+ In developer-branch mode:
26
+ 1. Verifies the integration branch exists (bootstraps & pushes it from releaseBranch if confirmed or --bootstrap-integration).
27
+ 2. Creates or tracks your personal developer branch.
28
+ 3. Pushes and sets upstream tracking (unless --local-only).
29
+ 4. Saves the branch in git config (<developerBranchConfigKey>).
30
+ 5. Enables .githooks safely if present and core.hooksPath is not claimed elsewhere.
31
+
32
+ In trunk mode:
33
+ Verifies baseBranch exists and safely enables .githooks if present.
34
+
35
+ Options:
36
+ --remote <name> Override configured remote (default from .featflow.json).
37
+ --bootstrap-integration Auto-create and push the missing integration branch (e.g. origin/dev) from releaseBranch.
38
+ --local-only Set up locally without touching the remote.
39
+ --skip-hooks Do not configure core.hooksPath.
40
+ -h, --help Show this help.
41
+ `.trim();
42
+
43
+ function parseArgs(argv) {
44
+ const options = {
45
+ branch: "",
46
+ remote: "",
47
+ bootstrapIntegration: false,
48
+ localOnly: false,
49
+ skipHooks: false,
50
+ };
51
+ const positional = [];
52
+
53
+ for (let i = 0; i < argv.length; i += 1) {
54
+ const arg = argv[i];
55
+ if (arg === "-h" || arg === "--help") {
56
+ console.log(usage);
57
+ process.exit(0);
58
+ }
59
+ if (arg === "--bootstrap-integration") {
60
+ options.bootstrapIntegration = true;
61
+ continue;
62
+ }
63
+ if (arg === "--local-only") {
64
+ options.localOnly = true;
65
+ continue;
66
+ }
67
+ if (arg === "--skip-hooks") {
68
+ options.skipHooks = true;
69
+ continue;
70
+ }
71
+ if (arg === "--remote") {
72
+ options.remote = argv[++i] ?? "";
73
+ continue;
74
+ }
75
+ if (arg.startsWith("--remote=")) {
76
+ options.remote = arg.slice("--remote=".length);
77
+ continue;
78
+ }
79
+ if (arg.startsWith("-")) {
80
+ fail(`Unknown option: ${arg}`, usage);
81
+ }
82
+ positional.push(arg);
83
+ }
84
+
85
+ if (positional.length > 1) {
86
+ fail(`Unexpected extra argument: ${positional[1]}`, usage);
87
+ }
88
+ options.branch = positional[0] ?? "";
89
+ return options;
90
+ }
91
+
92
+ function resolveIntegrationStartRef(repoRoot, remote, config) {
93
+ const release = config.releaseBranch || "main";
94
+ if (remote && remoteTrackingBranchExists(remote, release, repoRoot)) {
95
+ return `${remote}/${release}`;
96
+ }
97
+ if (localBranchExists(release, repoRoot)) {
98
+ return release;
99
+ }
100
+ return "HEAD";
101
+ }
102
+
103
+ function ensureLocalDeveloperBranch(repoRoot, branchName, integration, startRef) {
104
+ let createdIntegration = false;
105
+ if (!localBranchExists(integration, repoRoot)) {
106
+ runWrite("git", ["branch", integration, startRef], repoRoot);
107
+ createdIntegration = true;
108
+ }
109
+ if (!localBranchExists(branchName, repoRoot)) {
110
+ runWrite("git", ["branch", branchName, integration], repoRoot);
111
+ return createdIntegration
112
+ ? `created local ${integration} and developer branch from ${startRef}`
113
+ : `created local developer branch from ${integration}`;
114
+ }
115
+ return "using existing local developer branch";
116
+ }
117
+
118
+ async function ensureDeveloperBranch(repoRoot, branchName, remote, config, options = {}) {
119
+ const localOnly = Boolean(options.localOnly);
120
+ const hasRemote = !localOnly && remoteExists(remote, repoRoot);
121
+ const integration = config.integrationBranch;
122
+ const remoteIntegration = `${remote}/${integration}`;
123
+ const startRef = resolveIntegrationStartRef(repoRoot, hasRemote ? remote : "", config);
124
+
125
+ if (hasRemote) {
126
+ let bootstrappedIntegration = false;
127
+
128
+ if (!remoteBranchExists(remote, integration, repoRoot)) {
129
+ let action = options.bootstrapIntegration ? "create-and-push" : "";
130
+ if (!action && options.rl) {
131
+ action = await promptSingleSelect(options.rl, {
132
+ title: `Integration branch "${remoteIntegration}" does not exist yet`,
133
+ defaultId: "create-and-push",
134
+ choices: [
135
+ {
136
+ id: "create-and-push",
137
+ label: "create-and-push",
138
+ detail: `create "${integration}" from "${startRef}", push ${remoteIntegration}, and finish setup`,
139
+ aliases: ["y", "yes", "create", "push"],
140
+ },
141
+ {
142
+ id: "local-only",
143
+ label: "local-only",
144
+ detail: "create local branch only without pushing to remote",
145
+ aliases: ["l", "local"],
146
+ },
147
+ {
148
+ id: "skip",
149
+ label: "skip",
150
+ detail: "abort developer branch setup for now",
151
+ aliases: ["n", "no", "s"],
152
+ },
153
+ ],
154
+ });
155
+ }
156
+
157
+ if (action === "create-and-push") {
158
+ if (!localBranchExists(integration, repoRoot)) {
159
+ runWrite("git", ["branch", integration, startRef], repoRoot);
160
+ }
161
+ runWrite("git", ["push", "-u", remote, integration], repoRoot, {
162
+ env: { FEATFLOW_BOOTSTRAP: "1" },
163
+ });
164
+ bootstrappedIntegration = true;
165
+ } else if (action === "local-only") {
166
+ return ensureLocalDeveloperBranch(repoRoot, branchName, integration, startRef);
167
+ } else {
168
+ throw new Error(
169
+ [
170
+ `Integration branch ${remoteIntegration} does not exist yet.`,
171
+ `Run \`featflow setup ${branchName} --bootstrap-integration\` to create & push ${remoteIntegration} from ${startRef}, or pass --local-only for offline setup.`,
172
+ ].join("\n"),
173
+ );
174
+ }
175
+ }
176
+
177
+ if (!remoteTrackingBranchExists(remote, integration, repoRoot)) {
178
+ runWrite("git", ["fetch", remote, integration], repoRoot);
179
+ }
180
+
181
+ const localExists = localBranchExists(branchName, repoRoot);
182
+ const remoteExistsForBranch = remoteBranchExists(remote, branchName, repoRoot);
183
+
184
+ if (!localExists && remoteExistsForBranch) {
185
+ if (!remoteTrackingBranchExists(remote, branchName, repoRoot)) {
186
+ runWrite("git", ["fetch", remote, branchName], repoRoot);
187
+ }
188
+ runWrite("git", ["branch", "--track", branchName, `${remote}/${branchName}`], repoRoot);
189
+ return bootstrappedIntegration
190
+ ? `bootstrapped ${remoteIntegration} + tracked existing remote branch`
191
+ : "tracked existing remote branch";
192
+ }
193
+
194
+ if (!localExists) {
195
+ runWrite("git", ["branch", branchName, remoteIntegration], repoRoot);
196
+ }
197
+
198
+ runWrite("git", ["push", "-u", remote, branchName], repoRoot, {
199
+ env: { FEATFLOW_BOOTSTRAP: "1" },
200
+ });
201
+ const baseMsg = remoteExistsForBranch
202
+ ? "updated existing remote branch"
203
+ : "created and pushed new developer branch";
204
+ return bootstrappedIntegration ? `bootstrapped ${remoteIntegration} + ${baseMsg}` : baseMsg;
205
+ }
206
+
207
+ if (config.requireRemote && !localOnly) {
208
+ throw new Error(`Remote "${remote}" is not configured. Add a remote or pass --local-only.`);
209
+ }
210
+
211
+ return ensureLocalDeveloperBranch(repoRoot, branchName, integration, startRef);
212
+ }
213
+
214
+ export function suggestDeveloperBranch(repoRoot, config, protectedBranches) {
215
+ const existing = gitConfigGet(config.developerBranchConfigKey, repoRoot);
216
+ if (existing && !protectedBranches.has(existing)) {
217
+ return existing;
218
+ }
219
+ const rawName = gitConfigGet("user.name", repoRoot);
220
+ const slug = rawName
221
+ .trim()
222
+ .toLowerCase()
223
+ .replace(/[^a-z0-9]+/g, "-")
224
+ .replace(/^-+|-+$/g, "");
225
+ if (slug && !protectedBranches.has(slug)) {
226
+ return slug;
227
+ }
228
+ return "";
229
+ }
230
+
231
+ async function resolveDeveloperBranch(options, repoRoot, config, protectedBranches, sharedRl = null) {
232
+ if (options.branch) {
233
+ return options.branch;
234
+ }
235
+ const suggested = suggestDeveloperBranch(repoRoot, config, protectedBranches);
236
+ const isInteractive =
237
+ Boolean(sharedRl) ||
238
+ Boolean(process.stdin.isTTY && process.stdout.isTTY) ||
239
+ process.env.FEATFLOW_FORCE_TTY === "1";
240
+
241
+ if (isInteractive) {
242
+ const rl = sharedRl ?? createSmartPrompter();
243
+ try {
244
+ const promptLabel = suggested
245
+ ? `Personal developer branch name [${suggested}]: `
246
+ : "Personal developer branch name (e.g. alice): ";
247
+ const answer = (await rl.question(promptLabel)).trim();
248
+ const chosen = answer || suggested;
249
+ if (!chosen) {
250
+ throw new Error("Developer branch name is required in developer-branch mode (e.g. `featflow setup alice`).");
251
+ }
252
+ return chosen;
253
+ } finally {
254
+ if (!sharedRl) {
255
+ rl.close();
256
+ }
257
+ }
258
+ }
259
+
260
+ const example = suggested || "alice";
261
+ throw new Error(`Developer branch name is required in developer-branch mode (e.g. \`featflow setup ${example}\`).`);
262
+ }
263
+
264
+ export async function setupDeveloperBranchWorkflow(repoRoot, config, options = {}) {
265
+ const remote = options.remote || config.remote;
266
+ const protectedBranches = new Set(config.protectedBranches);
267
+ const isInteractive =
268
+ Boolean(options.rl) ||
269
+ Boolean(process.stdin.isTTY && process.stdout.isTTY) ||
270
+ process.env.FEATFLOW_FORCE_TTY === "1";
271
+ const ownsPrompter = !options.rl && isInteractive;
272
+ const prompter = options.rl ?? (ownsPrompter ? createSmartPrompter() : null);
273
+
274
+ try {
275
+ const branch = await resolveDeveloperBranch(
276
+ { branch: options.branch ?? "" },
277
+ repoRoot,
278
+ config,
279
+ protectedBranches,
280
+ prompter,
281
+ );
282
+ validateDeveloperBranchName(branch, repoRoot, protectedBranches);
283
+
284
+ const result = await ensureDeveloperBranch(repoRoot, branch, remote, config, {
285
+ localOnly: Boolean(options.localOnly),
286
+ bootstrapIntegration: Boolean(options.bootstrapIntegration),
287
+ rl: prompter,
288
+ });
289
+ gitConfigSet(config.developerBranchConfigKey, branch, repoRoot);
290
+ return { branch, result };
291
+ } finally {
292
+ if (ownsPrompter && prompter) {
293
+ prompter.close();
294
+ }
295
+ }
296
+ }
297
+
298
+ export async function runSetup(argv) {
299
+ const options = parseArgs(argv);
300
+ const { config, repoRoot } = loadConfig(process.cwd());
301
+
302
+ if (config.mode === "developer-branch") {
303
+ try {
304
+ const setupResult = await setupDeveloperBranchWorkflow(repoRoot, config, {
305
+ branch: options.branch,
306
+ remote: options.remote,
307
+ bootstrapIntegration: options.bootstrapIntegration,
308
+ localOnly: options.localOnly,
309
+ });
310
+ options.branch = setupResult.branch;
311
+ console.log(`Developer branch configured: ${setupResult.branch} (${setupResult.result})`);
312
+ } catch (error) {
313
+ fail(error instanceof Error ? error.message : String(error), usage);
314
+ }
315
+ } else {
316
+ if (!localBranchExists(config.baseBranch, repoRoot)) {
317
+ console.log(`Note: configured baseBranch "${config.baseBranch}" does not exist locally yet.`);
318
+ } else {
319
+ console.log(`Trunk workflow ready (base branch: ${config.baseBranch}).`);
320
+ }
321
+ }
322
+
323
+ if (!options.skipHooks && existsSync(path.join(repoRoot, ".githooks"))) {
324
+ const hookResult = configureGitHooksSafely(repoRoot);
325
+ if (hookResult.configured) {
326
+ console.log("Git hooks enabled: core.hooksPath=.githooks");
327
+ } else {
328
+ console.log(`Kept existing core.hooksPath=${hookResult.existingHooksPath} (did not overwrite).`);
329
+ console.log("Wire featflow into your existing hooks with:");
330
+ console.log(" pre-commit: featflow policy pre-commit");
331
+ console.log(" pre-push: featflow policy pre-push");
332
+ console.log(" post-merge: featflow cleanup --post-merge || true");
333
+ }
334
+ }
335
+
336
+ console.log("");
337
+ console.log("Next steps:");
338
+ const sampleBranch =
339
+ config.mode === "developer-branch" ? `fix/${options.branch}-example` : "fix/example-task";
340
+ console.log(` featflow worktree ${sampleBranch}`);
341
+ console.log(" # develop, verify, and commit inside the task worktree");
342
+ console.log(` featflow finish ${sampleBranch}`);
343
+ }
@@ -0,0 +1,137 @@
1
+ import { loadConfig } from "../config.mjs";
2
+ import { fail, findRepoRoot } from "../git.mjs";
3
+ import { evaluateFileSizeBudget, updateFileSizeBaseline } from "../size-check.mjs";
4
+
5
+ const usage = `
6
+ Usage:
7
+ featflow size-check [options]
8
+
9
+ Checks repository files against the configured fileSizeBudget in .featflow.json
10
+ (with legacy baseline ratchet support: legacy files may only shrink, never grow).
11
+
12
+ Options:
13
+ --changed Check only files changed vs developer/base branch + working tree
14
+ --base <ref> Override base ref for --changed
15
+ --head <ref> Override head ref for --changed (default: HEAD)
16
+ --files <paths...> Check explicit file paths
17
+ --update-baseline Generate or tighten the configured baselineFile from current repo state
18
+ --dry-run Preview --update-baseline without writing
19
+ --json Output machine-readable JSON
20
+ -h, --help Show this help
21
+ `.trim();
22
+
23
+ function parseArgs(argv) {
24
+ const options = {
25
+ changed: false,
26
+ base: "",
27
+ head: "",
28
+ files: [],
29
+ updateBaseline: false,
30
+ dryRun: false,
31
+ json: false,
32
+ };
33
+
34
+ for (let i = 0; i < argv.length; i += 1) {
35
+ const arg = argv[i];
36
+ if (arg === "-h" || arg === "--help") {
37
+ console.log(usage);
38
+ process.exit(0);
39
+ }
40
+ if (arg === "--changed") {
41
+ options.changed = true;
42
+ continue;
43
+ }
44
+ if (arg === "--update-baseline") {
45
+ options.updateBaseline = true;
46
+ continue;
47
+ }
48
+ if (arg === "--dry-run") {
49
+ options.dryRun = true;
50
+ continue;
51
+ }
52
+ if (arg === "--json") {
53
+ options.json = true;
54
+ continue;
55
+ }
56
+ if (arg === "--base" || arg === "--head") {
57
+ const value = argv[++i] ?? "";
58
+ if (!value) fail(`Missing value for ${arg}.`, usage);
59
+ options[arg.slice(2)] = value;
60
+ continue;
61
+ }
62
+ if (arg.startsWith("--base=") || arg.startsWith("--head=")) {
63
+ const idx = arg.indexOf("=");
64
+ options[arg.slice(2, idx)] = arg.slice(idx + 1);
65
+ continue;
66
+ }
67
+ if (arg === "--files") {
68
+ while (i + 1 < argv.length && !argv[i + 1].startsWith("-")) {
69
+ options.files.push(argv[++i]);
70
+ }
71
+ options.changed = true;
72
+ continue;
73
+ }
74
+ if (arg.startsWith("-")) {
75
+ fail(`Unknown option for size-check: ${arg}`, usage);
76
+ }
77
+ options.files.push(arg);
78
+ options.changed = true;
79
+ }
80
+
81
+ return options;
82
+ }
83
+
84
+ export async function runSizeCheck(argv) {
85
+ const options = parseArgs(argv);
86
+ const repoRoot = findRepoRoot(process.cwd());
87
+ if (!repoRoot) {
88
+ fail("Not inside a Git repository.");
89
+ }
90
+
91
+ const { config } = loadConfig(repoRoot);
92
+
93
+ if (options.updateBaseline) {
94
+ const updated = updateFileSizeBaseline(repoRoot, config, { dryRun: options.dryRun });
95
+ if (options.json) {
96
+ console.log(JSON.stringify(updated, null, 2));
97
+ return;
98
+ }
99
+ console.log(
100
+ `${options.dryRun ? "[dry-run] Would write" : "Updated"} ${updated.baselineFile} (${updated.entryCount} legacy entries across ${updated.checkedCount} checked files).`,
101
+ );
102
+ return;
103
+ }
104
+
105
+ const result = evaluateFileSizeBudget(repoRoot, config, options);
106
+
107
+ if (options.json) {
108
+ console.log(JSON.stringify(result, null, 2));
109
+ if (!result.ok) process.exit(1);
110
+ return;
111
+ }
112
+
113
+ if (!result.ok) {
114
+ console.error(
115
+ result.changedOnly
116
+ ? "Changed-file size budget failed. Split large changed files before adding more code."
117
+ : "File size budget failed. Split large files before adding more code.",
118
+ );
119
+ for (const failure of result.failures) {
120
+ console.error(`- ${failure.path}: ${failure.lines} lines exceeds ${failure.label}`);
121
+ }
122
+ process.exit(1);
123
+ }
124
+
125
+ if (result.staleBaseline.length > 0) {
126
+ console.warn("File size baseline contains paths that no longer exist:");
127
+ for (const stalePath of result.staleBaseline) {
128
+ console.warn(`- ${stalePath}`);
129
+ }
130
+ }
131
+
132
+ console.log(
133
+ result.changedOnly
134
+ ? `Changed-file size budget passed (${result.checkedCount} changed size-checked files).`
135
+ : `File size budget passed (${result.budgets.production} production, ${result.budgets.style} style, ${result.budgets.test} test lines; legacy baselines may only shrink).`,
136
+ );
137
+ }