@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,100 @@
1
+ import { loadConfig, resolveWorktreeParent } from "../config.mjs";
2
+ import {
3
+ currentBranch,
4
+ findWorktreeForBranch,
5
+ gitConfigGet,
6
+ gitWorktrees,
7
+ localBranchExists,
8
+ remoteBranchExists,
9
+ remoteExists,
10
+ remoteTrackingBranchExists,
11
+ } from "../git.mjs";
12
+ import { listFeatureFiles } from "../plan.mjs";
13
+ import { setupInstructions } from "../policy.mjs";
14
+
15
+ const usage = `
16
+ Usage:
17
+ featflow status
18
+
19
+ Shows featflow mode, repository/branch state, worktrees, active feature records, and next step.
20
+ `.trim();
21
+
22
+ function yesNo(value) {
23
+ return value ? "yes" : "no";
24
+ }
25
+
26
+ export async function runStatus(argv) {
27
+ if (argv.includes("-h") || argv.includes("--help")) {
28
+ console.log(usage);
29
+ return;
30
+ }
31
+
32
+ const { config, hasConfigFile, repoRoot } = loadConfig(process.cwd());
33
+ const current = currentBranch(repoRoot);
34
+ const worktrees = gitWorktrees(repoRoot);
35
+ const hooksPath = gitConfigGet("core.hooksPath", repoRoot);
36
+ const hasRemote = remoteExists(config.remote, repoRoot);
37
+
38
+ console.log("featflow status");
39
+ console.log(`Repository: ${repoRoot}`);
40
+ console.log(`Config file: ${hasConfigFile ? ".featflow.json" : "(defaults — run featflow init)"}`);
41
+ console.log(`Mode: ${config.mode}${config.mode === "trunk" ? ` (finishTarget: ${config.finishTarget})` : ""}`);
42
+ console.log(`Current branch: ${current || "(detached)"}`);
43
+ console.log(`Protected branches: ${config.protectedBranches.join(", ") || "(none)"}`);
44
+ console.log(`Worktree parent: ${resolveWorktreeParent(repoRoot, config)}`);
45
+ console.log(`Git hooks path: ${hooksPath || "(not configured)"}`);
46
+
47
+ const activeFeatures = [
48
+ ...listFeatureFiles(repoRoot, config.featuresDir, "active"),
49
+ ...(config.featuresDir === ".featflow/features" ? [] : listFeatureFiles(repoRoot, ".featflow/features", "active")),
50
+ ];
51
+ const pausedFeatures = [
52
+ ...listFeatureFiles(repoRoot, config.featuresDir, "paused"),
53
+ ...(config.featuresDir === ".featflow/features" ? [] : listFeatureFiles(repoRoot, ".featflow/features", "paused")),
54
+ ];
55
+ console.log(`Active feature records: ${activeFeatures.length > 0 ? activeFeatures.join(", ") : "(none)"}`);
56
+ if (pausedFeatures.length > 0) {
57
+ console.log(`Paused feature records: ${pausedFeatures.join(", ")}`);
58
+ }
59
+
60
+ let targetBranch = config.baseBranch;
61
+ if (config.mode === "developer-branch") {
62
+ const devBranch = gitConfigGet(config.developerBranchConfigKey, repoRoot);
63
+ console.log(`Configured developer branch: ${devBranch || "(not configured)"}`);
64
+ if (hasRemote) {
65
+ console.log(
66
+ `Remote ${config.remote}/${config.integrationBranch}: ${yesNo(
67
+ remoteBranchExists(config.remote, config.integrationBranch, repoRoot),
68
+ )}`,
69
+ );
70
+ }
71
+ if (!devBranch) {
72
+ console.log("");
73
+ console.log(setupInstructions(config));
74
+ return;
75
+ }
76
+ targetBranch = devBranch;
77
+ console.log(`Local developer branch: ${yesNo(localBranchExists(devBranch, repoRoot))}`);
78
+ if (hasRemote) {
79
+ console.log(`Tracking ref ${config.remote}/${devBranch}: ${yesNo(remoteTrackingBranchExists(config.remote, devBranch, repoRoot))}`);
80
+ }
81
+ const devWt = findWorktreeForBranch(worktrees, devBranch);
82
+ console.log(`Developer worktree: ${devWt?.path ?? "(not checked out)"}`);
83
+ }
84
+
85
+ console.log(`Worktrees (${worktrees.length}):`);
86
+ for (const wt of worktrees) {
87
+ const label = wt.branch ? wt.branch.replace(/^refs\/heads\//, "") : "(detached)";
88
+ console.log(` - ${wt.path} [${label}]`);
89
+ }
90
+
91
+ console.log("");
92
+ const protectedSet = new Set(config.protectedBranches);
93
+ if (protectedSet.has(current)) {
94
+ console.log(`Next step: create a task worktree from ${targetBranch} before editing tracked files.`);
95
+ } else if (current === targetBranch) {
96
+ console.log("Next step: create a typed task branch/worktree for the next task with `featflow worktree`.");
97
+ } else {
98
+ console.log(`Next step: finish this task with \`featflow finish ${current || "<task-branch>"}\`.`);
99
+ }
100
+ }
@@ -0,0 +1,407 @@
1
+ import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import {
5
+ findManagedAgentDocs,
6
+ inspectAgentDocBlock,
7
+ renderAgentWorkflowBlock,
8
+ resolveAgentDocTargets,
9
+ upsertAgentDocBlock,
10
+ } from "../agent-docs.mjs";
11
+ import { loadConfig, packageRoot } from "../config.mjs";
12
+ import { fail, findRepoRoot } from "../git.mjs";
13
+ import { configureGitHooksSafely } from "./hooks-cmd.mjs";
14
+
15
+ const VALID_GROUPS = new Set(["skill", "issues-skill", "regression-skill", "templates", "githooks", "agent-docs"]);
16
+
17
+ const usage = `
18
+ Usage:
19
+ featflow sync [options]
20
+
21
+ Synchronizes featflow-managed files (Skill, optional featflow-issues / featflow-regression Skills,
22
+ feature templates, .githooks, and managed AGENTS.md / CLAUDE.md workflow blocks) from the installed
23
+ featflow package into the current repository without touching .featflow.json, active/done
24
+ feature records, or custom content outside <!-- FEATFLOW_START --> markers.
25
+
26
+ Options:
27
+ --check Verify managed files match the installed featflow version (exit 1 on drift).
28
+ --dry-run Print files that would be created or updated without writing.
29
+ --only <groups> Comma-separated subset: skill,issues-skill,regression-skill,templates,githooks,agent-docs.
30
+ --with-issues-skill Include .agents/skills/featflow-issues/SKILL.md even if issues is not configured yet.
31
+ --skip-issues-skill Skip .agents/skills/featflow-issues/SKILL.md even if issues is configured.
32
+ --with-regression-skill Include .agents/skills/featflow-regression/SKILL.md.
33
+ --skip-regression-skill Skip .agents/skills/featflow-regression/SKILL.md even if present.
34
+ --with-githooks Include .githooks even if the directory does not exist yet.
35
+ --skip-githooks Skip .githooks even if the directory exists.
36
+ --with-agent-docs Include AGENTS.md / CLAUDE.md even if no managed block exists yet.
37
+ --skip-agent-docs Skip AGENTS.md / CLAUDE.md even if a managed block exists.
38
+ --json Output machine-readable JSON.
39
+ -h, --help Show this help.
40
+ `.trim();
41
+
42
+ function parseArgs(argv) {
43
+ const options = {
44
+ check: false,
45
+ dryRun: false,
46
+ only: null,
47
+ withIssuesSkill: false,
48
+ skipIssuesSkill: false,
49
+ withRegressionSkill: false,
50
+ skipRegressionSkill: false,
51
+ withGithooks: false,
52
+ skipGithooks: false,
53
+ withAgentDocs: false,
54
+ skipAgentDocs: false,
55
+ json: false,
56
+ };
57
+
58
+ for (let i = 0; i < argv.length; i += 1) {
59
+ const arg = argv[i];
60
+ if (arg === "-h" || arg === "--help") {
61
+ console.log(usage);
62
+ process.exit(0);
63
+ }
64
+ if (arg === "--check") {
65
+ options.check = true;
66
+ continue;
67
+ }
68
+ if (arg === "--dry-run") {
69
+ options.dryRun = true;
70
+ continue;
71
+ }
72
+ if (arg === "--with-issues-skill") {
73
+ options.withIssuesSkill = true;
74
+ continue;
75
+ }
76
+ if (arg === "--skip-issues-skill") {
77
+ options.skipIssuesSkill = true;
78
+ continue;
79
+ }
80
+ if (arg === "--with-regression-skill") {
81
+ options.withRegressionSkill = true;
82
+ continue;
83
+ }
84
+ if (arg === "--skip-regression-skill") {
85
+ options.skipRegressionSkill = true;
86
+ continue;
87
+ }
88
+ if (arg === "--with-githooks") {
89
+ options.withGithooks = true;
90
+ continue;
91
+ }
92
+ if (arg === "--skip-githooks") {
93
+ options.skipGithooks = true;
94
+ continue;
95
+ }
96
+ if (arg === "--with-agent-docs") {
97
+ options.withAgentDocs = true;
98
+ continue;
99
+ }
100
+ if (arg === "--skip-agent-docs") {
101
+ options.skipAgentDocs = true;
102
+ continue;
103
+ }
104
+ if (arg === "--json") {
105
+ options.json = true;
106
+ continue;
107
+ }
108
+ if (arg === "--only") {
109
+ options.only = argv[++i] ?? "";
110
+ continue;
111
+ }
112
+ if (arg.startsWith("--only=")) {
113
+ options.only = arg.slice("--only=".length);
114
+ continue;
115
+ }
116
+ fail(`Unknown option: ${arg}`, usage);
117
+ }
118
+
119
+ return options;
120
+ }
121
+
122
+ function normalizeLineEndings(content) {
123
+ return content.replace(/\r\n/g, "\n");
124
+ }
125
+
126
+ function resolveGroups(options, repoRoot, config) {
127
+ if (options.only !== null) {
128
+ const requested = options.only
129
+ .split(",")
130
+ .map((item) => item.trim())
131
+ .filter(Boolean);
132
+ if (requested.length === 0) {
133
+ fail("--only requires at least one group (skill, issues-skill, regression-skill, templates, githooks, agent-docs).", usage);
134
+ }
135
+ for (const group of requested) {
136
+ if (!VALID_GROUPS.has(group)) {
137
+ fail(`Unknown --only group "${group}". Valid groups: skill, issues-skill, regression-skill, templates, githooks, agent-docs.`, usage);
138
+ }
139
+ }
140
+ return new Set(requested);
141
+ }
142
+
143
+ const hasRepoSkill = existsSync(path.join(repoRoot, ".agents", "skills", "featflow", "SKILL.md"));
144
+ const hasIssuesSkill = existsSync(path.join(repoRoot, ".agents", "skills", "featflow-issues", "SKILL.md"));
145
+ const hasRegressionSkill = existsSync(path.join(repoRoot, ".agents", "skills", "featflow-regression", "SKILL.md"));
146
+ const hasRepoTemplates = existsSync(path.join(repoRoot, config.featuresDir, "_template.md"));
147
+ const hasGithooksDir = existsSync(path.join(repoRoot, ".githooks"));
148
+ const managedAgentDocs = findManagedAgentDocs(repoRoot);
149
+ const isMinimalLayout = managedAgentDocs.length > 0 && !hasRepoSkill && !hasRepoTemplates;
150
+
151
+ const groups = new Set();
152
+ if (!isMinimalLayout) {
153
+ groups.add("skill");
154
+ groups.add("templates");
155
+ }
156
+ if (
157
+ !options.skipIssuesSkill &&
158
+ (options.withIssuesSkill || hasIssuesSkill || (!isMinimalLayout && Boolean(config.issues)))
159
+ ) {
160
+ groups.add("issues-skill");
161
+ }
162
+ if (!options.skipRegressionSkill && (options.withRegressionSkill || hasRegressionSkill)) {
163
+ groups.add("regression-skill");
164
+ }
165
+ if (!options.skipGithooks && (options.withGithooks || hasGithooksDir)) {
166
+ groups.add("githooks");
167
+ }
168
+ if (!options.skipAgentDocs && (options.withAgentDocs || managedAgentDocs.length > 0)) {
169
+ groups.add("agent-docs");
170
+ }
171
+ return groups;
172
+ }
173
+
174
+ export function buildManagedFiles(repoRoot, config, groups) {
175
+ const files = [];
176
+
177
+ if (groups.has("skill")) {
178
+ files.push({
179
+ kind: "file",
180
+ group: "skill",
181
+ src: path.join(packageRoot, "skills", "featflow", "SKILL.md"),
182
+ dest: path.join(repoRoot, ".agents", "skills", "featflow", "SKILL.md"),
183
+ executable: false,
184
+ });
185
+ }
186
+
187
+ if (groups.has("issues-skill")) {
188
+ files.push({
189
+ kind: "file",
190
+ group: "issues-skill",
191
+ src: path.join(packageRoot, "skills", "featflow-issues", "SKILL.md"),
192
+ dest: path.join(repoRoot, ".agents", "skills", "featflow-issues", "SKILL.md"),
193
+ executable: false,
194
+ });
195
+ }
196
+
197
+ if (groups.has("regression-skill")) {
198
+ files.push({
199
+ kind: "file",
200
+ group: "regression-skill",
201
+ src: path.join(packageRoot, "skills", "featflow-regression", "SKILL.md"),
202
+ dest: path.join(repoRoot, ".agents", "skills", "featflow-regression", "SKILL.md"),
203
+ executable: false,
204
+ });
205
+ }
206
+
207
+ if (groups.has("templates")) {
208
+ const srcDir = path.join(packageRoot, "templates", "features");
209
+ const destDir = path.join(repoRoot, config.featuresDir);
210
+ for (const name of ["README.md", "_template.md", "_program_template.md"]) {
211
+ files.push({
212
+ kind: "file",
213
+ group: "templates",
214
+ src: path.join(srcDir, name),
215
+ dest: path.join(destDir, name),
216
+ executable: false,
217
+ });
218
+ }
219
+ }
220
+
221
+ if (groups.has("githooks")) {
222
+ const srcDir = path.join(packageRoot, "templates", "githooks");
223
+ const destDir = path.join(repoRoot, ".githooks");
224
+ for (const hook of ["pre-commit", "pre-push", "post-merge"]) {
225
+ files.push({
226
+ kind: "file",
227
+ group: "githooks",
228
+ src: path.join(srcDir, hook),
229
+ dest: path.join(destDir, hook),
230
+ executable: true,
231
+ });
232
+ }
233
+ }
234
+
235
+ if (groups.has("agent-docs")) {
236
+ const managed = findManagedAgentDocs(repoRoot);
237
+ const targets = managed.length > 0 ? managed : resolveAgentDocTargets(repoRoot);
238
+ for (const rel of targets) {
239
+ files.push({
240
+ kind: "agent-doc",
241
+ group: "agent-docs",
242
+ src: path.join(packageRoot, "templates", "snippets", "AGENTS-workflow.md"),
243
+ dest: path.resolve(repoRoot, rel),
244
+ executable: false,
245
+ });
246
+ }
247
+ }
248
+
249
+ return files;
250
+ }
251
+
252
+ export function inspectSyncState(repoRoot, config, groups) {
253
+ const managed = buildManagedFiles(repoRoot, config, groups);
254
+ const renderedBlock = groups.has("agent-docs") ? renderAgentWorkflowBlock() : "";
255
+ const missing = [];
256
+ const drifted = [];
257
+ const upToDate = [];
258
+
259
+ for (const entry of managed) {
260
+ const rel = path.relative(repoRoot, entry.dest).replaceAll("\\", "/");
261
+ if (entry.kind === "agent-doc") {
262
+ const check = inspectAgentDocBlock(entry.dest, renderedBlock);
263
+ if (check.status === "missing-file" || check.status === "missing-block") {
264
+ missing.push({ ...entry, rel });
265
+ } else if (check.status === "drifted") {
266
+ drifted.push({ ...entry, rel });
267
+ } else {
268
+ upToDate.push({ ...entry, rel });
269
+ }
270
+ continue;
271
+ }
272
+
273
+ if (!existsSync(entry.dest)) {
274
+ missing.push({ ...entry, rel });
275
+ continue;
276
+ }
277
+ const expected = normalizeLineEndings(readFileSync(entry.src, "utf8"));
278
+ const actual = normalizeLineEndings(readFileSync(entry.dest, "utf8"));
279
+ if (expected !== actual) {
280
+ drifted.push({ ...entry, rel });
281
+ } else {
282
+ upToDate.push({ ...entry, rel });
283
+ }
284
+ }
285
+
286
+ return {
287
+ ok: missing.length === 0 && drifted.length === 0,
288
+ missing,
289
+ drifted,
290
+ upToDate,
291
+ };
292
+ }
293
+
294
+ export async function runSync(argv) {
295
+ const options = parseArgs(argv);
296
+ const repoRoot = findRepoRoot(process.cwd());
297
+ if (!repoRoot) {
298
+ fail("Not inside a Git repository.");
299
+ }
300
+
301
+ const { config } = loadConfig(repoRoot);
302
+ const groups = resolveGroups(options, repoRoot, config);
303
+ const state = inspectSyncState(repoRoot, config, groups);
304
+
305
+ if (options.check) {
306
+ const summary = {
307
+ ok: state.ok,
308
+ groups: [...groups],
309
+ missing: state.missing.map((item) => item.rel),
310
+ drifted: state.drifted.map((item) => item.rel),
311
+ upToDate: state.upToDate.map((item) => item.rel),
312
+ };
313
+ if (options.json) {
314
+ console.log(JSON.stringify(summary, null, 2));
315
+ } else if (state.ok) {
316
+ console.log(`featflow sync --check passed (${state.upToDate.length} managed files up to date).`);
317
+ } else {
318
+ console.error("featflow sync --check found out-of-date managed files:");
319
+ for (const item of state.missing) {
320
+ console.error(` [missing] ${item.rel}`);
321
+ }
322
+ for (const item of state.drifted) {
323
+ console.error(` [drifted] ${item.rel}`);
324
+ }
325
+ console.error("\nRun `featflow sync` to update them (your .featflow.json will not be modified).");
326
+ }
327
+ if (!state.ok) {
328
+ process.exit(1);
329
+ }
330
+ return;
331
+ }
332
+
333
+ const pending = [...state.missing, ...state.drifted];
334
+ const created = [];
335
+ const updated = [];
336
+ const renderedBlock = groups.has("agent-docs") ? renderAgentWorkflowBlock() : "";
337
+
338
+ for (const item of pending) {
339
+ if (item.kind === "agent-doc") {
340
+ const result = upsertAgentDocBlock(item.dest, renderedBlock, { dryRun: options.dryRun });
341
+ if (result.action === "created") {
342
+ created.push(item.rel);
343
+ } else if (result.action === "updated") {
344
+ updated.push(item.rel);
345
+ }
346
+ continue;
347
+ }
348
+
349
+ const isNew = !existsSync(item.dest);
350
+ if (!options.dryRun) {
351
+ mkdirSync(path.dirname(item.dest), { recursive: true });
352
+ copyFileSync(item.src, item.dest);
353
+ if (item.executable) {
354
+ chmodSync(item.dest, 0o755);
355
+ }
356
+ }
357
+ if (isNew) {
358
+ created.push(item.rel);
359
+ } else {
360
+ updated.push(item.rel);
361
+ }
362
+ }
363
+
364
+ let hookResult = null;
365
+ if (options.withGithooks && !options.dryRun) {
366
+ hookResult = configureGitHooksSafely(repoRoot);
367
+ }
368
+
369
+ if (options.json) {
370
+ console.log(
371
+ JSON.stringify(
372
+ {
373
+ dryRun: options.dryRun,
374
+ groups: [...groups],
375
+ created,
376
+ updated,
377
+ upToDate: state.upToDate.map((item) => item.rel),
378
+ hookResult,
379
+ },
380
+ null,
381
+ 2,
382
+ ),
383
+ );
384
+ return;
385
+ }
386
+
387
+ if (created.length === 0 && updated.length === 0) {
388
+ console.log(`All ${state.upToDate.length} managed featflow files are already up to date.`);
389
+ } else {
390
+ const verb = options.dryRun ? "Would sync" : "Synced";
391
+ console.log(`${verb} featflow managed files (kept .featflow.json untouched):`);
392
+ for (const rel of created) {
393
+ console.log(` + ${rel}`);
394
+ }
395
+ for (const rel of updated) {
396
+ console.log(` ~ ${rel}`);
397
+ }
398
+ }
399
+
400
+ if (hookResult && !hookResult.configured) {
401
+ console.log("");
402
+ console.log(`Kept existing core.hooksPath=${hookResult.existingHooksPath} (did not overwrite).`);
403
+ } else if (hookResult?.configured) {
404
+ console.log("");
405
+ console.log("Git hooks enabled: core.hooksPath=.githooks");
406
+ }
407
+ }
@@ -0,0 +1,206 @@
1
+ import { spawnSync } from "node:child_process";
2
+
3
+ import { changedFileSelection, matchesPattern } from "../changed-files.mjs";
4
+ import { loadConfig } from "../config.mjs";
5
+ import { fail, findRepoRoot } from "../git.mjs";
6
+ import { evaluateFileSizeBudget } from "../size-check.mjs";
7
+ import { analyzeRegressionImpact } from "../regression.mjs";
8
+
9
+ const usage = `
10
+ Usage:
11
+ featflow verify [options]
12
+
13
+ Runs verification commands from \`.featflow.json\` (\`verifyCommands\`) that match
14
+ the current changed files (or all configured commands with \`--all\`).
15
+
16
+ Options:
17
+ --changed Run only commands matching changed files (default)
18
+ --all Run all configured verifyCommands
19
+ --base <ref> Override git diff base ref for --changed
20
+ --head <ref> Override git diff head ref (default: HEAD)
21
+ --files <paths...> Match explicit file paths instead of git diff
22
+ --with-size Also run configured fileSizeBudget check (--changed)
23
+ --with-regression Also include commands from impacted regression ledger entries
24
+ --dry-run Print matched commands without executing them
25
+ --json Output machine-readable JSON
26
+ -h, --help Show this help
27
+ `.trim();
28
+
29
+ function parseArgs(argv) {
30
+ const options = {
31
+ all: false,
32
+ base: "",
33
+ head: "",
34
+ files: [],
35
+ withSize: false,
36
+ withRegression: false,
37
+ dryRun: false,
38
+ json: false,
39
+ };
40
+
41
+ for (let i = 0; i < argv.length; i += 1) {
42
+ const arg = argv[i];
43
+ if (arg === "-h" || arg === "--help") {
44
+ console.log(usage);
45
+ process.exit(0);
46
+ }
47
+ if (arg === "--all") {
48
+ options.all = true;
49
+ continue;
50
+ }
51
+ if (arg === "--changed") {
52
+ options.all = false;
53
+ continue;
54
+ }
55
+ if (arg === "--with-size") {
56
+ options.withSize = true;
57
+ continue;
58
+ }
59
+ if (arg === "--with-regression") {
60
+ options.withRegression = true;
61
+ continue;
62
+ }
63
+ if (arg === "--dry-run") {
64
+ options.dryRun = true;
65
+ continue;
66
+ }
67
+ if (arg === "--json") {
68
+ options.json = true;
69
+ continue;
70
+ }
71
+ if (arg === "--base" || arg === "--head") {
72
+ const value = argv[++i] ?? "";
73
+ if (!value) fail(`Missing value for ${arg}.`, usage);
74
+ options[arg.slice(2)] = value;
75
+ continue;
76
+ }
77
+ if (arg.startsWith("--base=") || arg.startsWith("--head=")) {
78
+ const idx = arg.indexOf("=");
79
+ options[arg.slice(2, idx)] = arg.slice(idx + 1);
80
+ continue;
81
+ }
82
+ if (arg === "--files") {
83
+ while (i + 1 < argv.length && !argv[i + 1].startsWith("-")) {
84
+ options.files.push(argv[++i]);
85
+ }
86
+ continue;
87
+ }
88
+ if (arg.startsWith("-")) {
89
+ fail(`Unknown option for verify: ${arg}`, usage);
90
+ }
91
+ options.files.push(arg);
92
+ }
93
+
94
+ return options;
95
+ }
96
+
97
+ export function planVerifyCommands(repoRoot, config, options = {}) {
98
+ const verifyMap = config.verifyCommands ?? {};
99
+ const selection = options.all
100
+ ? { base: null, head: null, source: "--all", files: [] }
101
+ : changedFileSelection(repoRoot, config, {
102
+ base: options.base,
103
+ head: options.head,
104
+ files: options.files,
105
+ });
106
+
107
+ const planned = [];
108
+ const seenCommands = new Set();
109
+
110
+ for (const [pattern, command] of Object.entries(verifyMap)) {
111
+ if (!command || seenCommands.has(command)) continue;
112
+ const matched =
113
+ options.all ||
114
+ pattern === "*" ||
115
+ selection.files.some((file) => matchesPattern(file, pattern));
116
+ if (matched) {
117
+ seenCommands.add(command);
118
+ planned.push({ source: `verifyCommands[${pattern}]`, command });
119
+ }
120
+ }
121
+
122
+ let regressionReport = null;
123
+ if (options.withRegression && config.regression) {
124
+ regressionReport = analyzeRegressionImpact(repoRoot, config, options);
125
+ for (const cmd of regressionReport.uniqueCommands) {
126
+ if (!seenCommands.has(cmd)) {
127
+ seenCommands.add(cmd);
128
+ planned.push({ source: "regression", command: cmd });
129
+ }
130
+ }
131
+ }
132
+
133
+ return { selection, planned, regressionReport };
134
+ }
135
+
136
+ export async function runVerify(argv) {
137
+ const options = parseArgs(argv);
138
+ const repoRoot = findRepoRoot(process.cwd());
139
+ if (!repoRoot) {
140
+ fail("Not inside a Git repository.");
141
+ }
142
+ const { config } = loadConfig(repoRoot);
143
+
144
+ let sizeResult = null;
145
+ if (options.withSize && config.fileSizeBudget) {
146
+ sizeResult = evaluateFileSizeBudget(repoRoot, config, {
147
+ changed: !options.all,
148
+ base: options.base,
149
+ head: options.head,
150
+ files: options.files,
151
+ });
152
+ }
153
+
154
+ const { selection, planned } = planVerifyCommands(repoRoot, config, options);
155
+ const results = [];
156
+
157
+ for (const entry of planned) {
158
+ if (options.dryRun) {
159
+ results.push({ ...entry, ok: true, skipped: true, exitCode: 0, durationMs: 0 });
160
+ continue;
161
+ }
162
+ const start = Date.now();
163
+ const res = spawnSync(entry.command, [], {
164
+ cwd: repoRoot,
165
+ shell: true,
166
+ stdio: options.json ? ["ignore", "pipe", "pipe"] : "inherit",
167
+ encoding: "utf8",
168
+ });
169
+ results.push({
170
+ ...entry,
171
+ ok: res.status === 0,
172
+ skipped: false,
173
+ exitCode: res.status ?? -1,
174
+ durationMs: Date.now() - start,
175
+ });
176
+ }
177
+
178
+ const ok = results.every((r) => r.ok) && (sizeResult ? sizeResult.ok : true);
179
+
180
+ if (options.json) {
181
+ console.log(JSON.stringify({ ok, selection, sizeCheck: sizeResult, results }, null, 2));
182
+ if (!ok) process.exit(1);
183
+ return;
184
+ }
185
+
186
+ if (sizeResult) {
187
+ console.log(`[${sizeResult.ok ? "PASS" : "FAIL"}] size-check (${sizeResult.checkedCount} files)`);
188
+ for (const f of sizeResult.failures) {
189
+ console.error(` - ${f.path}: ${f.lines} lines exceeds ${f.label}`);
190
+ }
191
+ }
192
+
193
+ if (results.length === 0) {
194
+ console.log("No matching verifyCommands for the current changed files.");
195
+ } else {
196
+ console.log(`Verification summary (${results.length} command(s)):`);
197
+ for (const r of results) {
198
+ const tag = r.skipped ? "DRY-RUN" : r.ok ? "PASS" : "FAIL";
199
+ console.log(` [${tag}] ${r.source}: ${r.command}`);
200
+ }
201
+ }
202
+
203
+ if (!ok) {
204
+ process.exit(1);
205
+ }
206
+ }