@danielstyle/featflow 0.0.0-stage → 0.6.3

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 (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +206 -2
  3. package/README.zh-CN.md +163 -0
  4. package/bin/featflow.mjs +113 -0
  5. package/package.json +62 -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 +110 -0
  13. package/src/commands/doctor.mjs +265 -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 +238 -0
  17. package/src/commands/init.mjs +382 -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 +51 -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/status.mjs +100 -0
  27. package/src/commands/sync.mjs +407 -0
  28. package/src/commands/verify.mjs +206 -0
  29. package/src/commands/worktree.mjs +205 -0
  30. package/src/config.mjs +295 -0
  31. package/src/detect.mjs +314 -0
  32. package/src/git.mjs +331 -0
  33. package/src/hook-adapters.mjs +218 -0
  34. package/src/hooks-core.mjs +420 -0
  35. package/src/index.mjs +13 -0
  36. package/src/init-args.mjs +282 -0
  37. package/src/init-hooks.mjs +312 -0
  38. package/src/init-prompts.mjs +191 -0
  39. package/src/issues-helpers.mjs +463 -0
  40. package/src/issues.mjs +521 -0
  41. package/src/plan.mjs +202 -0
  42. package/src/policy.mjs +143 -0
  43. package/src/regression.mjs +338 -0
  44. package/src/size-check.mjs +203 -0
  45. package/src/tui-select.mjs +378 -0
  46. package/templates/adapters/antigravity/hooks.json +42 -0
  47. package/templates/adapters/claude-code/settings.json +46 -0
  48. package/templates/adapters/codex/config.toml +19 -0
  49. package/templates/adapters/cursor/hooks.json +27 -0
  50. package/templates/agents/codex/codebase-locator.toml +28 -0
  51. package/templates/agents/codex/implementation-scout.toml +28 -0
  52. package/templates/agents/codex/regression-guard-planner.toml +20 -0
  53. package/templates/features/README.md +56 -0
  54. package/templates/features/_program_template.md +79 -0
  55. package/templates/features/_template.md +120 -0
  56. package/templates/features/current-feature.md +18 -0
  57. package/templates/githooks/post-merge +7 -0
  58. package/templates/githooks/pre-commit +11 -0
  59. package/templates/githooks/pre-push +10 -0
  60. package/templates/regression/regression-ledger.yml +23 -0
  61. package/templates/snippets/AGENTS-workflow.md +21 -0
@@ -0,0 +1,382 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import { findManagedAgentDocs, renderAgentWorkflowBlock, resolveAgentDocTargets, upsertAgentDocBlock } from "../agent-docs.mjs";
5
+ import {
6
+ CONFIG_FILENAME,
7
+ DEFAULT_FILE_SIZE_BUDGET,
8
+ DEFAULT_ISSUES_CONFIG,
9
+ DEFAULT_REGRESSION_CONFIG,
10
+ packageRoot,
11
+ presetConfig,
12
+ } from "../config.mjs";
13
+ import { applyDetectedConfig, detectRepoEnvironment } from "../detect.mjs";
14
+ import { fail, findRepoRoot, gitConfigGet } from "../git.mjs";
15
+ import { INIT_USAGE, parseInitArgs } from "../init-args.mjs";
16
+ import {
17
+ copyTemplateFile,
18
+ ensureGitignoreEntries,
19
+ installAntigravityHooks,
20
+ installClaudeHooks,
21
+ installCodexAgents,
22
+ installCodexHooks,
23
+ installCursorHooks,
24
+ installInitialRegressionLedger,
25
+ writeTextFile,
26
+ } from "../init-hooks.mjs";
27
+ import { promptInteractiveOptions } from "../init-prompts.mjs";
28
+ import { evaluateFileSizeBudget, updateFileSizeBaseline } from "../size-check.mjs";
29
+ import { createSmartPrompter, promptSingleSelect } from "../tui-select.mjs";
30
+ import { configureGitHooksSafely, installLocalHooks } from "./hooks-cmd.mjs";
31
+ import { setupDeveloperBranchWorkflow } from "./setup.mjs";
32
+
33
+ export {
34
+ configureGitHooksSafely,
35
+ installAntigravityHooks,
36
+ installClaudeHooks,
37
+ installCodexAgents,
38
+ installCodexHooks,
39
+ installCursorHooks,
40
+ };
41
+
42
+ function readExistingRawConfig(configPath) {
43
+ if (!existsSync(configPath)) {
44
+ return null;
45
+ }
46
+ try {
47
+ const parsed = JSON.parse(readFileSync(configPath, "utf8"));
48
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
49
+ } catch (error) {
50
+ fail(`Existing ${CONFIG_FILENAME} is invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
51
+ }
52
+ }
53
+
54
+ export async function runInit(argv) {
55
+ const options = parseInitArgs(argv);
56
+ const repoRoot = findRepoRoot(process.cwd());
57
+ if (!repoRoot) {
58
+ fail("Not inside a Git repository. Run `git init` first.");
59
+ }
60
+
61
+ const configPath = path.join(repoRoot, CONFIG_FILENAME);
62
+ const existingConfig = options.merge ? readExistingRawConfig(configPath) : null;
63
+
64
+ const detected = options.detect
65
+ ? detectRepoEnvironment(repoRoot, { featuresDir: options.featuresDir || existingConfig?.featuresDir || "features" })
66
+ : null;
67
+
68
+ const isInteractive =
69
+ !options.yes &&
70
+ (Boolean(process.stdin.isTTY && process.stdout.isTTY) || process.env.FEATFLOW_FORCE_TTY === "1");
71
+
72
+ const prompter = isInteractive ? createSmartPrompter() : null;
73
+
74
+ try {
75
+ if (prompter && detected) {
76
+ await promptInteractiveOptions(prompter, options, detected, repoRoot, existingConfig);
77
+ }
78
+
79
+ let config;
80
+ let configChangedInMerge = false;
81
+ if (options.merge && existingConfig) {
82
+ config = structuredClone(existingConfig);
83
+ if (options.withIssues && !config.issues) {
84
+ config.issues = { ...DEFAULT_ISSUES_CONFIG, assetsRepo: options.issueAssetsRepo || null };
85
+ configChangedInMerge = true;
86
+ } else if (options.issueAssetsRepo && config.issues && !config.issues.assetsRepo) {
87
+ config.issues.assetsRepo = options.issueAssetsRepo;
88
+ configChangedInMerge = true;
89
+ }
90
+ if (options.withSizeBudget && !config.fileSizeBudget) {
91
+ config.fileSizeBudget = { ...DEFAULT_FILE_SIZE_BUDGET };
92
+ configChangedInMerge = true;
93
+ }
94
+ if (options.withRegression && !config.regression) {
95
+ config.regression = { ...DEFAULT_REGRESSION_CONFIG };
96
+ configChangedInMerge = true;
97
+ }
98
+ } else {
99
+ try {
100
+ config = presetConfig(options.mode);
101
+ } catch (error) {
102
+ fail(error instanceof Error ? error.message : String(error), INIT_USAGE);
103
+ }
104
+ if (detected) {
105
+ config = applyDetectedConfig(config, detected, {
106
+ explicitFeaturesDir: Boolean(options.featuresDir),
107
+ minimal: options.minimal,
108
+ localFeatures: options.localFeatures,
109
+ });
110
+ }
111
+ if (options.featuresDir) config.featuresDir = options.featuresDir;
112
+ if (options.finishTarget) {
113
+ if (config.mode !== "trunk" || !["merge", "pr"].includes(options.finishTarget)) {
114
+ fail(`--finish-target "${options.finishTarget}" is only valid in trunk mode ("merge" or "pr").`, INIT_USAGE);
115
+ }
116
+ config.finishTarget = options.finishTarget;
117
+ }
118
+ if (options.localFeatures) config.trackFeaturesInGit = false;
119
+ if (options.trackPointer) config.trackCurrentFeaturePointer = true;
120
+ if (options.withIssues) {
121
+ config.issues = { ...DEFAULT_ISSUES_CONFIG, assetsRepo: options.issueAssetsRepo || null };
122
+ }
123
+ if (options.withSizeBudget) config.fileSizeBudget = { ...DEFAULT_FILE_SIZE_BUDGET };
124
+ if (options.withRegression) config.regression = { ...DEFAULT_REGRESSION_CONFIG };
125
+ }
126
+
127
+ const shouldInstallLocalHooks =
128
+ !options.noHooks && !options.withGithooks && (options.localHooks || (options.minimal && !options.merge));
129
+ const shouldInstallRepoHooks = !options.noHooks && options.withGithooks;
130
+
131
+ const created = [];
132
+ const updated = [];
133
+ const skipped = [];
134
+ const notices = [];
135
+
136
+ if (!options.merge && detected?.featuresDirConflict && !options.featuresDir) {
137
+ notices.push(
138
+ `Detected existing non-featflow "features/" directory; set featuresDir="${config.featuresDir}" to avoid collision (override with --features-dir).`,
139
+ );
140
+ }
141
+
142
+ if (options.merge && existingConfig) {
143
+ if (configChangedInMerge) {
144
+ writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
145
+ updated.push(configPath);
146
+ } else {
147
+ skipped.push(configPath);
148
+ }
149
+ } else {
150
+ writeTextFile(configPath, `${JSON.stringify(config, null, 2)}\n`, options.force, created, skipped);
151
+ }
152
+
153
+ const featuresDir = config.featuresDir || "features";
154
+ if (!options.minimal && !(options.merge && existingConfig)) {
155
+ const featuresRoot = path.join(repoRoot, featuresDir);
156
+ for (const subdir of ["active", "done", "paused", "programs"]) {
157
+ mkdirSync(path.join(featuresRoot, subdir), { recursive: true });
158
+ const gitkeep = path.join(featuresRoot, subdir, ".gitkeep");
159
+ if (config.trackFeaturesInGit !== false && !existsSync(gitkeep)) {
160
+ writeFileSync(gitkeep, "", "utf8");
161
+ created.push(gitkeep);
162
+ }
163
+ }
164
+
165
+ const templateFeaturesDir = path.join(packageRoot, "templates", "features");
166
+ for (const file of ["README.md", "_template.md", "_program_template.md"]) {
167
+ copyTemplateFile(path.join(templateFeaturesDir, file), path.join(featuresRoot, file), options.force, created, skipped);
168
+ }
169
+ if (config.trackCurrentFeaturePointer) {
170
+ copyTemplateFile(
171
+ path.join(templateFeaturesDir, "current-feature.md"),
172
+ path.join(featuresRoot, "current-feature.md"),
173
+ options.force,
174
+ created,
175
+ skipped,
176
+ );
177
+ }
178
+
179
+ copyTemplateFile(
180
+ path.join(packageRoot, "skills", "featflow", "SKILL.md"),
181
+ path.join(repoRoot, ".agents", "skills", "featflow", "SKILL.md"),
182
+ options.force,
183
+ created,
184
+ skipped,
185
+ );
186
+ }
187
+
188
+ if (!options.minimal) {
189
+ if (options.withIssues) {
190
+ copyTemplateFile(
191
+ path.join(packageRoot, "skills", "featflow-issues", "SKILL.md"),
192
+ path.join(repoRoot, ".agents", "skills", "featflow-issues", "SKILL.md"),
193
+ options.force,
194
+ created,
195
+ skipped,
196
+ );
197
+ }
198
+ if (options.withRegression) {
199
+ copyTemplateFile(
200
+ path.join(packageRoot, "skills", "featflow-regression", "SKILL.md"),
201
+ path.join(repoRoot, ".agents", "skills", "featflow-regression", "SKILL.md"),
202
+ options.force,
203
+ created,
204
+ skipped,
205
+ );
206
+ installInitialRegressionLedger(
207
+ repoRoot,
208
+ config.regression?.ledgerFile || DEFAULT_REGRESSION_CONFIG.ledgerFile,
209
+ options.force,
210
+ created,
211
+ skipped,
212
+ );
213
+ }
214
+ }
215
+
216
+ if (options.updateAgentDocs) {
217
+ const targets =
218
+ options.merge && existingConfig && !options.agentDocs
219
+ ? findManagedAgentDocs(repoRoot)
220
+ : resolveAgentDocTargets(repoRoot, options.agentDocs);
221
+ const renderedBlock = renderAgentWorkflowBlock();
222
+ for (const relTarget of targets) {
223
+ const absTarget = path.resolve(repoRoot, relTarget);
224
+ const result = upsertAgentDocBlock(absTarget, renderedBlock);
225
+ if (result.action === "created") created.push(absTarget);
226
+ else if (result.action === "updated") updated.push(absTarget);
227
+ else skipped.push(absTarget);
228
+ }
229
+ }
230
+
231
+ let hookNotice = "";
232
+ if (shouldInstallRepoHooks) {
233
+ const srcHooks = path.join(packageRoot, "templates", "githooks");
234
+ const destHooks = path.join(repoRoot, ".githooks");
235
+ for (const hook of ["pre-commit", "pre-push", "post-merge"]) {
236
+ const dest = path.join(destHooks, hook);
237
+ const copied = copyTemplateFile(path.join(srcHooks, hook), dest, options.force, created, skipped);
238
+ if (copied || existsSync(dest)) chmodSync(dest, 0o755);
239
+ }
240
+ const hookResult = configureGitHooksSafely(repoRoot);
241
+ hookNotice = hookResult.configured
242
+ ? "Git hooks enabled: core.hooksPath=.githooks"
243
+ : [
244
+ `Kept existing core.hooksPath=${hookResult.existingHooksPath} (did not overwrite).`,
245
+ "Add these lines to your existing hook manager instead:",
246
+ " pre-commit: featflow policy pre-commit",
247
+ " pre-push: featflow policy pre-push",
248
+ " post-merge: featflow cleanup --post-merge || true",
249
+ ].join("\n");
250
+ } else if (shouldInstallLocalHooks) {
251
+ const localResult = installLocalHooks(repoRoot, { quiet: true });
252
+ hookNotice = localResult.installed
253
+ ? `Local Git hooks enabled in ${localResult.hooksDir}: ${localResult.hooks.join(", ")}`
254
+ : [
255
+ `Kept existing core.hooksPath=${localResult.existingHooksPath} (did not overwrite).`,
256
+ "Add these lines to your existing hook manager instead:",
257
+ " pre-commit: featflow policy pre-commit",
258
+ " pre-push: featflow policy pre-push",
259
+ " post-merge: featflow cleanup --post-merge || true",
260
+ ].join("\n");
261
+ }
262
+
263
+ if (options.withAntigravityHooks) {
264
+ installAntigravityHooks(repoRoot, options.force, created, updated, skipped, notices);
265
+ }
266
+ if (options.withCodexHooks) {
267
+ installCodexHooks(repoRoot, options.force, created, updated, skipped, notices);
268
+ }
269
+ if (options.withClaudeHooks) {
270
+ installClaudeHooks(repoRoot, options.force, created, updated, skipped, notices);
271
+ }
272
+ if (options.withCursorHooks) {
273
+ installCursorHooks(repoRoot, options.force, created, updated, skipped, notices);
274
+ }
275
+ if (options.withCodexAgents) {
276
+ installCodexAgents(repoRoot, options.force, created, skipped);
277
+ }
278
+
279
+ if (options.withSizeBudget && config.fileSizeBudget?.baselineFile) {
280
+ const baselineAbs = path.resolve(repoRoot, config.fileSizeBudget.baselineFile);
281
+ if (!existsSync(baselineAbs)) {
282
+ const evalRes = evaluateFileSizeBudget(repoRoot, config);
283
+ if (!evalRes.ok) {
284
+ const baseRes = updateFileSizeBaseline(repoRoot, config);
285
+ created.push(baseRes.absPath);
286
+ notices.push(
287
+ `Generated legacy size baseline ${baseRes.baselineFile} (${baseRes.entryCount} oversized file(s) ratcheted so existing code passes immediately).`,
288
+ );
289
+ }
290
+ }
291
+ }
292
+
293
+ let ignoredAdded = [];
294
+ if (options.updateGitignore) {
295
+ const entries = [".featflow/"];
296
+ if (!options.minimal && !(options.merge && existingConfig)) {
297
+ if (config.trackFeaturesInGit === false) entries.push(`${featuresDir}/`);
298
+ else if (!config.trackCurrentFeaturePointer) entries.push(`${featuresDir}/current-feature.md`);
299
+ }
300
+ ignoredAdded = ensureGitignoreEntries(repoRoot, entries);
301
+ }
302
+
303
+ let devSetupSummary = "";
304
+ const devBranchConfigKey = config.developerBranchConfigKey || "featflow.developerBranch";
305
+ const hasConfiguredDevBranch = Boolean(gitConfigGet(devBranchConfigKey, repoRoot));
306
+ if (config.mode === "developer-branch" && (!options.merge || !hasConfiguredDevBranch)) {
307
+ let shouldRunSetup = Boolean(options.developerBranch);
308
+ if (!shouldRunSetup && prompter) {
309
+ const answer = await promptSingleSelect(prompter, {
310
+ title: "Set up your personal developer branch now?",
311
+ defaultId: "yes",
312
+ choices: [
313
+ { id: "yes", label: "Yes", detail: "create/track your personal developer branch now", aliases: ["y", "true"] },
314
+ { id: "no", label: "No", detail: "skip for now (run `featflow setup <name>` later)", aliases: ["n", "false"] },
315
+ ],
316
+ });
317
+ shouldRunSetup = answer === "yes";
318
+ }
319
+ if (shouldRunSetup) {
320
+ try {
321
+ const setupRes = await setupDeveloperBranchWorkflow(repoRoot, config, {
322
+ branch: options.developerBranch,
323
+ localOnly: options.localOnly,
324
+ rl: prompter,
325
+ });
326
+ devSetupSummary = `Developer branch configured: ${setupRes.branch} (${setupRes.result})`;
327
+ } catch (error) {
328
+ notices.push(
329
+ `[WARN] Developer branch setup was NOT completed:\n${error instanceof Error ? error.message : String(error)}`,
330
+ );
331
+ }
332
+ }
333
+ }
334
+
335
+ const actionVerb = options.merge && existingConfig ? "Upgraded" : "Initialized";
336
+ const profileLabel = options.minimal ? "minimal" : options.preset || "full";
337
+ console.log(`${actionVerb} featflow in ${repoRoot} (mode: ${config.mode}, profile: ${profileLabel})`);
338
+ if (detected && !(options.merge && existingConfig)) {
339
+ const verifySummary =
340
+ Object.keys(config.verifyCommands ?? {}).length > 0 ? Object.values(config.verifyCommands)[0] : "(none)";
341
+ console.log(
342
+ `Detected: baseBranch=${config.baseBranch}, protected=[${(config.protectedBranches ?? []).join(", ")}], productPaths=[${(config.productPaths ?? []).join(", ")}], verify=${verifySummary}`,
343
+ );
344
+ }
345
+ if (created.length > 0) {
346
+ console.log("Created:");
347
+ for (const file of created) console.log(` - ${path.relative(repoRoot, file)}`);
348
+ }
349
+ if (updated.length > 0) {
350
+ console.log("Updated (non-destructive):");
351
+ for (const file of updated) console.log(` - ${path.relative(repoRoot, file)}`);
352
+ }
353
+ if (skipped.length > 0) {
354
+ console.log("Kept existing (pass --force to overwrite):");
355
+ for (const file of skipped) console.log(` - ${path.relative(repoRoot, file)}`);
356
+ }
357
+ if (ignoredAdded.length > 0) console.log(`Updated .gitignore with: ${ignoredAdded.join(", ")}`);
358
+ if (hookNotice) console.log(`\n${hookNotice}`);
359
+ if (devSetupSummary) console.log(`\n${devSetupSummary}`);
360
+ for (const notice of notices) console.log(`\n${notice}`);
361
+
362
+ if (!options.merge && detected?.suggestions?.length > 0) {
363
+ console.log("\nOptional .featflow.json suggestions:");
364
+ for (const suggestion of detected.suggestions) console.log(` - ${suggestion}`);
365
+ }
366
+
367
+ console.log("\nNext steps:");
368
+ const steps = [];
369
+ if (!options.merge && config.mode === "developer-branch" && !devSetupSummary) {
370
+ steps.push("Run: featflow setup <your-branch-name>");
371
+ }
372
+ steps.push("Start a task worktree: featflow worktree feat/my-first-task");
373
+ steps.push(
374
+ options.minimal
375
+ ? "Draft a feature record inside the worktree: featflow new my-first-task --local"
376
+ : "Check workflow health anytime with: featflow doctor",
377
+ );
378
+ steps.forEach((step, idx) => console.log(` ${idx + 1}. ${step}`));
379
+ } finally {
380
+ if (prompter) prompter.close();
381
+ }
382
+ }