@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,218 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ import { changedFiles } from "./changed-files.mjs";
6
+ import {
7
+ evaluatePostToolUse,
8
+ evaluatePreToolUse,
9
+ evaluateStopGate,
10
+ evaluateUserPrompt,
11
+ normalizeHookPayload,
12
+ stateFilePath,
13
+ } from "./hooks-core.mjs";
14
+ import { evaluateFileSizeBudget } from "./size-check.mjs";
15
+
16
+ export const SUPPORTED_HOOK_ADAPTERS = ["codex", "claude-code", "antigravity", "cursor"];
17
+
18
+ export const SUPPORTED_HOOK_EVENTS = {
19
+ codex: ["pre-tool-use", "post-tool-use", "user-prompt", "stop"],
20
+ "claude-code": ["pre-tool-use", "post-tool-use", "user-prompt", "stop"],
21
+ antigravity: ["pre-invocation", "user-prompt", "pre-tool-use", "post-tool-use", "stop"],
22
+ cursor: ["before-submit-prompt", "user-prompt", "pre-tool-use", "post-tool-use", "stop"],
23
+ };
24
+
25
+ export function resolveHookCwd(rawInput, fallbackCwd = process.cwd()) {
26
+ const input = rawInput && typeof rawInput === "object" ? rawInput : {};
27
+ const candidates = [
28
+ input.cwd,
29
+ Array.isArray(input.workspacePaths) ? input.workspacePaths[0] : null,
30
+ Array.isArray(input.workspace_roots) ? input.workspace_roots[0] : null,
31
+ ];
32
+ for (const candidate of candidates) {
33
+ if (typeof candidate === "string" && candidate.trim() && existsSync(candidate.trim())) {
34
+ return candidate.trim();
35
+ }
36
+ }
37
+ return fallbackCwd;
38
+ }
39
+
40
+ function formatSizeFailureReason(result) {
41
+ return [
42
+ "featflow changed-file size budget failed:",
43
+ ...result.failures.map((f) => `- ${f.path}: ${f.lines} lines exceeds ${f.label}`),
44
+ "Split oversized files into smaller focused modules before finishing.",
45
+ ].join("\n");
46
+ }
47
+
48
+ function runAntigravityHook(event, rawInput, payload, { repoRoot, config, env }) {
49
+ if (event === "pre-invocation" || event === "user-prompt") {
50
+ const prompt = payload.prompt.trim();
51
+ if (!prompt) {
52
+ return { stdout: "{}\n", exitCode: 0 };
53
+ }
54
+ const sig = createHash("sha256")
55
+ .update(JSON.stringify({ conversationId: rawInput?.conversationId ?? "", prompt }))
56
+ .digest("hex");
57
+ const sigPath = stateFilePath(repoRoot, "antigravity-pre-invocation.sig", env);
58
+ if (existsSync(sigPath) && readFileSync(sigPath, "utf8").trim() === sig) {
59
+ return { stdout: "{}\n", exitCode: 0 };
60
+ }
61
+ writeFileSync(sigPath, `${sig}\n`);
62
+
63
+ const result = evaluateUserPrompt(config, payload);
64
+ if (result.additionalContext) {
65
+ return {
66
+ stdout: `${JSON.stringify({
67
+ injectSteps: [{ systemMessage: { systemMessage: result.additionalContext } }],
68
+ })}\n`,
69
+ exitCode: 0,
70
+ };
71
+ }
72
+ return { stdout: "{}\n", exitCode: 0 };
73
+ }
74
+
75
+ if (event === "pre-tool-use") {
76
+ const result = evaluatePreToolUse(repoRoot, config, payload, env);
77
+ if (result.decision === "block") {
78
+ return {
79
+ stdout: `${JSON.stringify({ decision: "deny", reason: result.message })}\n`,
80
+ exitCode: 0,
81
+ };
82
+ }
83
+ return { stdout: `${JSON.stringify({ decision: "allow" })}\n`, exitCode: 0 };
84
+ }
85
+
86
+ if (event === "post-tool-use") {
87
+ // Antigravity PostToolUse hooks are observational and cannot block;
88
+ // changed-file size enforcement runs in Stop and Git pre-commit.
89
+ return { stdout: "{}\n", exitCode: 0 };
90
+ }
91
+
92
+ if (event === "stop") {
93
+ if (rawInput?.continuationActive === true) {
94
+ return { stdout: "{}\n", exitCode: 0 };
95
+ }
96
+ const budget = config.fileSizeBudget;
97
+ if (
98
+ budget &&
99
+ budget.enforceInPostToolUse &&
100
+ env.FEATFLOW_SKIP_POST_TOOL_QUALITY !== "1" &&
101
+ env.FEATFLOW_DISABLE_STOP_GATE !== "1"
102
+ ) {
103
+ const extSet = new Set(budget.extensions.map((ext) => ext.toLowerCase()));
104
+ const touched = changedFiles(repoRoot, config).filter((file) => extSet.has(path.extname(file).toLowerCase()));
105
+ if (touched.length > 0) {
106
+ const sizeRes = evaluateFileSizeBudget(repoRoot, config, { changed: true, files: touched });
107
+ if (!sizeRes.ok) {
108
+ return {
109
+ stdout: `${JSON.stringify({ decision: "continue", reason: formatSizeFailureReason(sizeRes) })}\n`,
110
+ exitCode: 0,
111
+ };
112
+ }
113
+ }
114
+ }
115
+
116
+ const stopRes = evaluateStopGate(repoRoot, config, env);
117
+ if (stopRes.decision === "block") {
118
+ return {
119
+ stdout: `${JSON.stringify({ decision: "continue", reason: stopRes.message })}\n`,
120
+ exitCode: 0,
121
+ };
122
+ }
123
+ return { stdout: "{}\n", exitCode: 0 };
124
+ }
125
+
126
+ return { stdout: "{}\n", exitCode: 0 };
127
+ }
128
+
129
+ function runCursorHook(event, payload, { repoRoot, config, env }) {
130
+ if (event === "before-submit-prompt" || event === "user-prompt") {
131
+ return { stdout: `${JSON.stringify({ continue: true })}\n`, exitCode: 0 };
132
+ }
133
+
134
+ if (event === "pre-tool-use") {
135
+ const result = evaluatePreToolUse(repoRoot, config, payload, env);
136
+ if (result.decision === "block") {
137
+ return {
138
+ stdout: `${JSON.stringify({
139
+ permission: "deny",
140
+ user_message: result.message,
141
+ agent_message: result.message,
142
+ })}\n`,
143
+ exitCode: 0,
144
+ };
145
+ }
146
+ return { stdout: `${JSON.stringify({ permission: "allow" })}\n`, exitCode: 0 };
147
+ }
148
+
149
+ if (event === "post-tool-use") {
150
+ const result = evaluatePostToolUse(repoRoot, config, payload, env);
151
+ if (result.decision === "block") {
152
+ return {
153
+ stdout: `${JSON.stringify({ additional_context: result.message })}\n`,
154
+ exitCode: 0,
155
+ };
156
+ }
157
+ return { stdout: "{}\n", exitCode: 0 };
158
+ }
159
+
160
+ if (event === "stop") {
161
+ const result = evaluateStopGate(repoRoot, config, env);
162
+ if (result.decision === "block") {
163
+ return {
164
+ stdout: `${JSON.stringify({ followup_message: result.message })}\n`,
165
+ exitCode: 0,
166
+ };
167
+ }
168
+ return { stdout: "{}\n", exitCode: 0 };
169
+ }
170
+
171
+ return { stdout: "{}\n", exitCode: 0 };
172
+ }
173
+
174
+ function runCodexOrClaudeHook(event, payload, { repoRoot, config, env }) {
175
+ if (event === "pre-tool-use") {
176
+ const result = evaluatePreToolUse(repoRoot, config, payload, env);
177
+ return result.decision === "block" ? { stderr: `${result.message}\n`, exitCode: 2 } : { exitCode: 0 };
178
+ }
179
+
180
+ if (event === "post-tool-use") {
181
+ const result = evaluatePostToolUse(repoRoot, config, payload, env);
182
+ return result.decision === "block" ? { stderr: `${result.message}\n`, exitCode: 2 } : { exitCode: 0 };
183
+ }
184
+
185
+ if (event === "user-prompt") {
186
+ const result = evaluateUserPrompt(config, payload);
187
+ if (result.additionalContext) {
188
+ return {
189
+ stdout: `${JSON.stringify({
190
+ hookSpecificOutput: {
191
+ hookEventName: "UserPromptSubmit",
192
+ additionalContext: result.additionalContext,
193
+ },
194
+ })}\n`,
195
+ exitCode: 0,
196
+ };
197
+ }
198
+ return { exitCode: 0 };
199
+ }
200
+
201
+ if (event === "stop") {
202
+ const result = evaluateStopGate(repoRoot, config, env);
203
+ return result.decision === "block" ? { stderr: `${result.message}\n`, exitCode: 2 } : { exitCode: 0 };
204
+ }
205
+
206
+ return { exitCode: 0 };
207
+ }
208
+
209
+ export function dispatchHookAdapter(adapter, event, rawInput, context) {
210
+ const payload = normalizeHookPayload(adapter, rawInput);
211
+ if (adapter === "antigravity") {
212
+ return runAntigravityHook(event, rawInput, payload, context);
213
+ }
214
+ if (adapter === "cursor") {
215
+ return runCursorHook(event, payload, context);
216
+ }
217
+ return runCodexOrClaudeHook(event, payload, context);
218
+ }
@@ -0,0 +1,420 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ import { changedFiles, matchesPattern } from "./changed-files.mjs";
6
+ import { currentBranch } from "./git.mjs";
7
+ import { validateActiveFeaturePlan } from "./plan.mjs";
8
+ import { checkWorkflowReady } from "./policy.mjs";
9
+ import { evaluateFileSizeBudget } from "./size-check.mjs";
10
+
11
+ const MUTATING_SHELL_PATTERNS = [
12
+ /\b(?:sed|perl)\s+-i\b/,
13
+ /(?:^|[;&|]\s*)(?:cp|mv|rm|touch|mkdir|chmod|truncate|install)\b/,
14
+ /(?:^|[;&|]\s*)tee\b/,
15
+ /(?:^|[^0-9])>>?\s*[^\s&]/,
16
+ /\bgit\s+(?:apply|checkout\s+--|restore)\b/,
17
+ ];
18
+
19
+ const WORKFLOW_MUTATING_PATTERNS = [
20
+ /\bgit\s+(?:add|commit|merge|rebase|rm|mv|push)\b/,
21
+ /\bgit\s+(?:switch|checkout)\s+-[^\n;]*[cb]\b/,
22
+ /\bgit\s+branch\s+(?!--show-current\b|--list\b|-l\b|-a\b|-r\b|-v\b|-vv\b)/,
23
+ /\bgit\s+worktree\s+(?:add|remove|prune)\b/,
24
+ /\bfeatflow\s+(?:worktree|finish)\b/,
25
+ ];
26
+
27
+ export function extractCodexPatchPaths(patchText) {
28
+ const paths = [];
29
+ for (const line of String(patchText ?? "").split(/\r?\n/)) {
30
+ const match = line.match(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/);
31
+ if (match) {
32
+ paths.push(match[1].trim());
33
+ }
34
+ }
35
+ return paths;
36
+ }
37
+
38
+ export function normalizeHookPayload(adapter, rawInput) {
39
+ const input = rawInput && typeof rawInput === "object" ? rawInput : {};
40
+ const antigravityCall = input.toolCall && typeof input.toolCall === "object" ? input.toolCall : null;
41
+ const toolName = String(antigravityCall?.name ?? input.tool_name ?? input.toolName ?? "");
42
+ const toolInput = antigravityCall?.args ?? input.tool_input ?? input.toolInput ?? {};
43
+ const prompt = String(
44
+ input.lastUserInput ?? input.prompt ?? input.user_prompt ?? input.userPrompt ?? "",
45
+ );
46
+
47
+ let command = typeof input.command === "string" ? input.command : "";
48
+ let rawPatch = "";
49
+ let filePaths = [];
50
+ if (typeof input.file_path === "string" && input.file_path.trim()) {
51
+ filePaths.push(input.file_path.trim());
52
+ }
53
+
54
+ if (typeof toolInput === "string") {
55
+ if (toolInput.includes("*** Begin Patch")) {
56
+ rawPatch = toolInput;
57
+ filePaths = extractCodexPatchPaths(toolInput);
58
+ } else if (!command) {
59
+ command = toolInput;
60
+ }
61
+ } else if (toolInput && typeof toolInput === "object") {
62
+ if (!command) {
63
+ command = String(
64
+ toolInput.CommandLine ?? toolInput.cmd ?? toolInput.command ?? toolInput.shell_command ?? "",
65
+ );
66
+ }
67
+ const patch = String(toolInput.patch ?? toolInput.diff ?? toolInput.input ?? "");
68
+ if (patch) {
69
+ rawPatch = patch;
70
+ if (patch.includes("*** Begin Patch")) {
71
+ filePaths.push(...extractCodexPatchPaths(patch));
72
+ }
73
+ }
74
+ for (const key of ["file_path", "TargetFile", "target_file", "notebook_path"]) {
75
+ if (typeof toolInput[key] === "string" && toolInput[key].trim()) {
76
+ filePaths.push(toolInput[key].trim());
77
+ }
78
+ }
79
+ for (const key of ["Path", "path"]) {
80
+ if (typeof toolInput[key] === "string" && toolInput[key].trim() && isEditToolName(toolName)) {
81
+ filePaths.push(toolInput[key].trim());
82
+ }
83
+ }
84
+ }
85
+
86
+ return {
87
+ adapter,
88
+ toolName,
89
+ command,
90
+ rawPatch,
91
+ filePaths: [...new Set(filePaths)],
92
+ prompt,
93
+ };
94
+ }
95
+
96
+ function isEditToolName(toolName) {
97
+ return /^(?:edit|multiedit|write|write_file|edit_file|replace_file_content|multi_replace_file_content|write_to_file|strreplace|notebookedit|apply_patch)$/i.test(
98
+ toolName,
99
+ );
100
+ }
101
+
102
+ function isSetupCommand(command) {
103
+ return /\bfeatflow\s+(?:init|setup)\b|\bpnpm\s+developer:setup\b/.test(command);
104
+ }
105
+
106
+ function isMutatingShellCommand(command) {
107
+ return MUTATING_SHELL_PATTERNS.some((pattern) => pattern.test(command));
108
+ }
109
+
110
+ function isMutatingWorkflowCommand(command) {
111
+ return WORKFLOW_MUTATING_PATTERNS.some((pattern) => pattern.test(command)) || isMutatingShellCommand(command);
112
+ }
113
+
114
+ function normalizeRelativePath(repoRoot, rawPath) {
115
+ const resolved = path.isAbsolute(rawPath) ? path.relative(repoRoot, rawPath) : rawPath;
116
+ return resolved.replaceAll("\\", "/").replace(/^\.\//, "");
117
+ }
118
+
119
+ function isProductPath(relPath, productPaths) {
120
+ return productPaths.some((prefix) => {
121
+ const normalized = prefix.replaceAll("\\", "/").replace(/^\.\//, "");
122
+ return normalized.endsWith("/") ? relPath.startsWith(normalized) : relPath === normalized || relPath.startsWith(`${normalized}/`);
123
+ });
124
+ }
125
+
126
+ function commandTargetsProductPath(command, productPaths) {
127
+ if (!command || !isMutatingShellCommand(command)) {
128
+ return false;
129
+ }
130
+ return productPaths.some((prefix) => {
131
+ const normalized = prefix.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/$/, "");
132
+ const escaped = normalized.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
133
+ return new RegExp(`(?:^|[\\s"'=/>])${escaped}(?:/|\\b)`).test(command);
134
+ });
135
+ }
136
+
137
+ function commandPushesProtectedBranch(command, protectedBranches) {
138
+ const match = command.match(/\bgit\s+push\b([^\n;]*)/);
139
+ if (!match || protectedBranches.length === 0) {
140
+ return null;
141
+ }
142
+ const args = match[1];
143
+ for (const branch of protectedBranches) {
144
+ const escaped = branch.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
145
+ const regex = new RegExp(`(?:^|\\s)(?:[\\w.-]+\\s+)?${escaped}(?=\\s|$)|refs/heads/${escaped}\\b`);
146
+ if (regex.test(args)) {
147
+ return branch;
148
+ }
149
+ }
150
+ return null;
151
+ }
152
+
153
+ function checkDangerousCommands(command, config) {
154
+ if (!command) {
155
+ return null;
156
+ }
157
+ const rules = config.dangerousCommands ?? {};
158
+
159
+ if (
160
+ rules.blockDestructiveGit &&
161
+ /\bgit\s+reset\s+--hard\b|\bgit\s+checkout\s+--\b|\bgit\s+clean\s+-[^\n;]*[fd]/.test(command)
162
+ ) {
163
+ return "Destructive Git cleanup can discard user work. Ask the user explicitly before running it.";
164
+ }
165
+
166
+ if (
167
+ rules.blockForcePush &&
168
+ /\bgit\s+push\b[^\n;]*(?:--force(?:-with-lease)?|-f)\b|\bgit\s+branch\s+-D\b/.test(command)
169
+ ) {
170
+ return "Force pushes and force-deleting branches are blocked unless the user explicitly asks for them.";
171
+ }
172
+
173
+ if (
174
+ rules.blockEnvWrite &&
175
+ /(?:^|[;&|]\s*)(?:echo|printf|cat|tee|cp|mv|touch)\b[^\n;]*(?:>\s*|\.\/)?\.env(?:\.[\w.-]+)?\b/.test(command) &&
176
+ !/\.env\.example\b/.test(command)
177
+ ) {
178
+ return "Do not overwrite real `.env` files from automated commands; edit `.env.example` or ask the user.";
179
+ }
180
+
181
+ for (const pm of rules.blockedPackageManagers ?? []) {
182
+ const escaped = pm.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
183
+ if (new RegExp(`(^|[;&|()\\s])${escaped}(?:\\s|$)`).test(command)) {
184
+ return `Package manager "${pm}" is disallowed by .featflow.json.`;
185
+ }
186
+ }
187
+
188
+ for (const custom of rules.blockedCommands ?? []) {
189
+ if (!custom || typeof custom.pattern !== "string" || !custom.pattern) continue;
190
+ try {
191
+ if (new RegExp(custom.pattern).test(command)) {
192
+ return custom.reason || `Command matched blockedCommands rule "${custom.pattern}" in .featflow.json.`;
193
+ }
194
+ } catch {
195
+ // Ignore malformed custom regex in config rather than crashing hooks
196
+ }
197
+ }
198
+
199
+ return null;
200
+ }
201
+
202
+ export function evaluatePreToolUse(repoRoot, config, payload, env = process.env) {
203
+ const { toolName, command, rawPatch, filePaths } = payload;
204
+
205
+ if (toolName && toolName.toLowerCase().includes("apply") && rawPatch && filePaths.length === 0) {
206
+ return {
207
+ decision: "block",
208
+ message: "featflow blocked apply_patch because no target file paths could be parsed from the patch payload. Re-run with a standard apply_patch hunk.",
209
+ };
210
+ }
211
+
212
+ const danger = checkDangerousCommands(command, config);
213
+ if (danger) {
214
+ return {
215
+ decision: "block",
216
+ message: `featflow blocked this command: ${danger}\nCommand: ${command}`,
217
+ };
218
+ }
219
+
220
+ const protectedPush = commandPushesProtectedBranch(command, config.protectedBranches);
221
+ if (protectedPush && env.FEATFLOW_BOOTSTRAP !== "1") {
222
+ return {
223
+ decision: "block",
224
+ message: `featflow blocked direct push to protected branch "${protectedPush}". Use a pull request or featflow finish.`,
225
+ };
226
+ }
227
+
228
+ const needsWriteCheck =
229
+ env.FEATFLOW_BOOTSTRAP !== "1" &&
230
+ !isSetupCommand(command) &&
231
+ (filePaths.length > 0 || isMutatingWorkflowCommand(command));
232
+
233
+ if (needsWriteCheck) {
234
+ const ready = checkWorkflowReady(repoRoot, config, env);
235
+ if (!ready.ok) {
236
+ return {
237
+ decision: "block",
238
+ message: `featflow blocked write-oriented work:\n${ready.message}`,
239
+ };
240
+ }
241
+
242
+ const branch = currentBranch(repoRoot);
243
+ if (new Set(config.protectedBranches).has(branch)) {
244
+ return {
245
+ decision: "block",
246
+ message: `featflow blocked direct edits on protected branch "${branch}". Create a task worktree first: featflow worktree <prefix>/<task>`,
247
+ };
248
+ }
249
+ }
250
+
251
+ const relFilePaths = filePaths.map((entry) => normalizeRelativePath(repoRoot, entry));
252
+ const editsProductCode =
253
+ relFilePaths.some((rel) => isProductPath(rel, config.productPaths)) ||
254
+ commandTargetsProductPath(command, config.productPaths);
255
+
256
+ if (editsProductCode) {
257
+ const planResult = validateActiveFeaturePlan(repoRoot, {
258
+ featuresDir: config.featuresDir,
259
+ requireApproved: true,
260
+ });
261
+ if (!planResult.ok) {
262
+ return {
263
+ decision: "block",
264
+ message: [
265
+ `featflow blocked product-code edits because the active feature plan (${planResult.activeFeature}) is incomplete:`,
266
+ ...planResult.errors.map((err) => `- ${err}`),
267
+ ].join("\n"),
268
+ };
269
+ }
270
+ }
271
+
272
+ return { decision: "allow" };
273
+ }
274
+
275
+ export function evaluateUserPrompt(config, payload) {
276
+ const lower = (payload.prompt ?? "").toLowerCase();
277
+ const reminders = [];
278
+
279
+ if (/feature|plan|workflow|worktree|milestone|roadmap|refactor|implement|迁移|重构|计划|工作流|功能|实现/.test(lower)) {
280
+ reminders.push(
281
+ `For substantial or write-oriented work, follow the \`featflow\` skill: complete read-only discovery, present a concrete plan, wait for approval, and work in a dedicated worktree (\`featflow worktree\`).`,
282
+ );
283
+ }
284
+
285
+ if (/bug|fix|regression|broken|failing|error|报错|修复|故障|失败/.test(lower)) {
286
+ reminders.push(
287
+ "For bug fixes or regressions, inspect existing behavior/tests first, present the root cause and fix plan before editing, and include a regression test in the Test Plan.",
288
+ );
289
+ if (config.regression) {
290
+ reminders.push(
291
+ `Check impacted regression guards in \`${config.regression.ledgerFile}\` via \`featflow regression impact --json\` before editing and record new durable guards.`,
292
+ );
293
+ }
294
+ }
295
+
296
+ if (
297
+ config.issues &&
298
+ /\b(?:issues?|claim|triage)\b|#\d+|提单|提个单|提个\s*bug|提个需求|提个\s*feat|记个单|记一下.*bug|拉单|看单|认领|工单/.test(
299
+ lower,
300
+ )
301
+ ) {
302
+ reminders.push(
303
+ "For GitHub Issues (filing with prefixes/screenshots or claiming & reviewing), follow the `featflow-issues` skill and use `featflow issue create|list|view|claim|review|release` (do not create an Issue for plain direct fix requests).",
304
+ );
305
+ }
306
+
307
+ if (reminders.length === 0) {
308
+ return { additionalContext: "" };
309
+ }
310
+
311
+ const modeNote =
312
+ config.mode === "developer-branch"
313
+ ? `Branch mode: developer-branch (base from \`git config ${config.developerBranchConfigKey}\`, finish with \`featflow finish <branch>\`).`
314
+ : `Branch mode: trunk (base from \`${config.baseBranch}\`, finish with \`featflow finish <branch>\`).`;
315
+
316
+ return {
317
+ additionalContext: `featflow reminders:\n- ${modeNote}\n- ${reminders.join("\n- ")}`,
318
+ };
319
+ }
320
+
321
+ export function stateFilePath(repoRoot, name, env = process.env) {
322
+ const dir = env.FEATFLOW_HOOK_STATE_DIR ?? path.resolve(repoRoot, ".featflow", "hook-state");
323
+ mkdirSync(dir, { recursive: true });
324
+ return path.resolve(dir, name);
325
+ }
326
+
327
+ export function evaluatePostToolUse(repoRoot, config, payload, env = process.env) {
328
+ if (env.FEATFLOW_SKIP_POST_TOOL_QUALITY === "1") {
329
+ return { decision: "allow" };
330
+ }
331
+ const budget = config.fileSizeBudget;
332
+ if (!budget || !budget.enforceInPostToolUse) {
333
+ return { decision: "allow" };
334
+ }
335
+
336
+ const extSet = new Set(budget.extensions.map((ext) => ext.toLowerCase()));
337
+ const touched = changedFiles(repoRoot, config).filter((file) => extSet.has(path.extname(file).toLowerCase()));
338
+ if (touched.length === 0) {
339
+ return { decision: "allow" };
340
+ }
341
+
342
+ const sig = createHash("sha256")
343
+ .update(JSON.stringify({ touched, toolName: payload?.toolName ?? "" }))
344
+ .digest("hex");
345
+ const sigPath = stateFilePath(repoRoot, "post-tool-size.sig", env);
346
+ if (existsSync(sigPath) && readFileSync(sigPath, "utf8").trim() === sig) {
347
+ return { decision: "allow" };
348
+ }
349
+ writeFileSync(sigPath, `${sig}\n`);
350
+
351
+ const result = evaluateFileSizeBudget(repoRoot, config, { changed: true, files: touched });
352
+ if (result.ok) {
353
+ return { decision: "allow" };
354
+ }
355
+
356
+ return {
357
+ decision: "block",
358
+ message: [
359
+ "featflow changed-file size budget failed after tool edit:",
360
+ ...result.failures.map((f) => `- ${f.path}: ${f.lines} lines exceeds ${f.label}`),
361
+ "Split oversized files into smaller focused modules before adding more code.",
362
+ ].join("\n"),
363
+ };
364
+ }
365
+
366
+ export function evaluateStopGate(repoRoot, config, env = process.env) {
367
+ if (env.FEATFLOW_DISABLE_STOP_GATE === "1") {
368
+ return { decision: "allow" };
369
+ }
370
+
371
+ const files = changedFiles(repoRoot, config);
372
+ if (files.length === 0) {
373
+ return { decision: "allow" };
374
+ }
375
+
376
+ const recommendations = [];
377
+ for (const [prefix, command] of Object.entries(config.verifyCommands ?? {})) {
378
+ const matched = prefix === "*" || files.some((file) => matchesPattern(file, prefix));
379
+ if (matched) {
380
+ recommendations.push(`${prefix}: run \`${command}\`.`);
381
+ }
382
+ }
383
+
384
+ if (config.fileSizeBudget && config.fileSizeBudget.enforceInStopGate) {
385
+ const extSet = new Set(config.fileSizeBudget.extensions.map((ext) => ext.toLowerCase()));
386
+ if (files.some((file) => extSet.has(path.extname(file).toLowerCase()))) {
387
+ recommendations.push("File size budget: run `featflow size-check --changed`.");
388
+ }
389
+ }
390
+
391
+ if (config.regression && config.regression.enforceInStopGate) {
392
+ recommendations.push("Regression ledger: run `featflow regression impact`.");
393
+ }
394
+
395
+ if (files.some((file) => file.startsWith(`${config.featuresDir}/`))) {
396
+ recommendations.push("Feature records changed: ensure `Verification` and `Handoff` sections reflect actual results.");
397
+ }
398
+
399
+ if (recommendations.length === 0) {
400
+ return { decision: "allow" };
401
+ }
402
+
403
+ const sig = createHash("sha256")
404
+ .update(JSON.stringify({ changedFiles: files, recommendations }))
405
+ .digest("hex");
406
+ const sigPath = stateFilePath(repoRoot, "stop-gate.sig", env);
407
+ if (existsSync(sigPath) && readFileSync(sigPath, "utf8").trim() === sig) {
408
+ return { decision: "allow" };
409
+ }
410
+ writeFileSync(sigPath, `${sig}\n`);
411
+
412
+ return {
413
+ decision: "block",
414
+ message: [
415
+ "Before final handoff, account for these featflow verification checks:",
416
+ ...recommendations.map((item) => `- ${item}`),
417
+ "Run the relevant commands or explicitly record skipped checks and residual risks in your handoff.",
418
+ ].join("\n"),
419
+ };
420
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,14 @@
1
+ export * from "./config.mjs";
2
+ export * from "./git.mjs";
3
+ export * from "./changed-files.mjs";
4
+ export * from "./plan.mjs";
5
+ export * from "./policy.mjs";
6
+ export * from "./hooks-core.mjs";
7
+ export * from "./hook-adapters.mjs";
8
+ export * from "./tui-select.mjs";
9
+ export * from "./detect.mjs";
10
+ export * from "./agent-docs.mjs";
11
+ export * from "./issues.mjs";
12
+ export * from "./size-check.mjs";
13
+ export * from "./regression.mjs";
14
+ export * from "./skills-manager.mjs";