refactor: major codebase cleanup - BDD comments, file splitting, bug fixes (#1350)

* style(tests): normalize BDD comments from '// #given' to '// given'

- Replace 4,668 Python-style BDD comments across 107 test files
- Patterns changed: // #given -> // given, // #when -> // when, // #then -> // then
- Also handles no-space variants: //#given -> // given

* fix(rules-injector): prefer output.metadata.filePath over output.title

- Extract file path resolution to dedicated output-path.ts module
- Prefer metadata.filePath which contains actual file path
- Fall back to output.title only when metadata unavailable
- Fixes issue where rules weren't injected when tool output title was a label

* feat(slashcommand): add optional user_message parameter

- Add user_message optional parameter for command arguments
- Model can now call: command='publish' user_message='patch'
- Improves error messages with clearer format guidance
- Helps LLMs understand correct parameter usage

* feat(hooks): restore compaction-context-injector hook

- Restore hook deleted in cbbc7bd0 for session compaction context
- Injects 7 mandatory sections: User Requests, Final Goal, Work Completed,
  Remaining Tasks, Active Working Context, MUST NOT Do, Agent Verification State
- Re-register in hooks/index.ts and main plugin entry

* refactor(background-agent): split manager.ts into focused modules

- Extract constants.ts for TTL values and internal types (52 lines)
- Extract state.ts for TaskStateManager class (204 lines)
- Extract spawner.ts for task creation logic (244 lines)
- Extract result-handler.ts for completion handling (265 lines)
- Reduce manager.ts from 1377 to 755 lines (45% reduction)
- Maintain backward compatible exports

* refactor(agents): split prometheus-prompt.ts into subdirectory

- Move 1196-line prometheus-prompt.ts to prometheus/ subdirectory
- Organize prompt sections into separate files for maintainability
- Update agents/index.ts exports

* refactor(delegate-task): split tools.ts into focused modules

- Extract categories.ts for category definitions and routing
- Extract executor.ts for task execution logic
- Extract helpers.ts for utility functions
- Extract prompt-builder.ts for prompt construction
- Reduce tools.ts complexity with cleaner separation of concerns

* refactor(builtin-skills): split skills.ts into individual skill files

- Move each skill to dedicated file in skills/ subdirectory
- Create barrel export for backward compatibility
- Improve maintainability with focused skill modules

* chore: update import paths and lockfile

- Update prometheus import path after refactor
- Update bun.lock

* fix(tests): complete BDD comment normalization

- Fix remaining #when/#then patterns missed by initial sed
- Affected: state.test.ts, events.test.ts

---------

Co-authored-by: justsisyphus <justsisyphus@users.noreply.github.com>
This commit is contained in:
YeonGyu-Kim
2026-02-01 16:47:50 +09:00
committed by GitHub
parent c83150d9ea
commit f146aeff0f
145 changed files with 10307 additions and 9562 deletions
+48 -48
View File
@@ -22,7 +22,7 @@ describe("findRuleFiles", () => {
describe(".github/instructions/ discovery", () => {
it("should discover .github/instructions/*.instructions.md files", () => {
// #given .github/instructions/ with valid files
// given .github/instructions/ with valid files
const instructionsDir = join(TEST_DIR, ".github", "instructions");
mkdirSync(instructionsDir, { recursive: true });
writeFileSync(
@@ -39,10 +39,10 @@ describe("findRuleFiles", () => {
const currentFile = join(srcDir, "index.ts");
writeFileSync(currentFile, "code");
// #when finding rules for a file
// when finding rules for a file
const candidates = findRuleFiles(TEST_DIR, homeDir, currentFile);
// #then should find both instruction files
// then should find both instruction files
const paths = candidates.map((c) => c.path);
expect(
paths.some((p) => p.includes("typescript.instructions.md"))
@@ -53,7 +53,7 @@ describe("findRuleFiles", () => {
});
it("should ignore non-.instructions.md files in .github/instructions/", () => {
// #given .github/instructions/ with invalid files
// given .github/instructions/ with invalid files
const instructionsDir = join(TEST_DIR, ".github", "instructions");
mkdirSync(instructionsDir, { recursive: true });
writeFileSync(
@@ -66,10 +66,10 @@ describe("findRuleFiles", () => {
const currentFile = join(TEST_DIR, "index.ts");
writeFileSync(currentFile, "code");
// #when finding rules
// when finding rules
const candidates = findRuleFiles(TEST_DIR, homeDir, currentFile);
// #then should only find .instructions.md file
// then should only find .instructions.md file
const paths = candidates.map((c) => c.path);
expect(paths.some((p) => p.includes("valid.instructions.md"))).toBe(
true
@@ -79,7 +79,7 @@ describe("findRuleFiles", () => {
});
it("should discover nested .instructions.md files in subdirectories", () => {
// #given nested .github/instructions/ structure
// given nested .github/instructions/ structure
const instructionsDir = join(TEST_DIR, ".github", "instructions");
const frontendDir = join(instructionsDir, "frontend");
mkdirSync(frontendDir, { recursive: true });
@@ -91,10 +91,10 @@ describe("findRuleFiles", () => {
const currentFile = join(TEST_DIR, "app.tsx");
writeFileSync(currentFile, "code");
// #when finding rules
// when finding rules
const candidates = findRuleFiles(TEST_DIR, homeDir, currentFile);
// #then should find nested instruction file
// then should find nested instruction file
const paths = candidates.map((c) => c.path);
expect(paths.some((p) => p.includes("react.instructions.md"))).toBe(
true
@@ -104,7 +104,7 @@ describe("findRuleFiles", () => {
describe(".github/copilot-instructions.md (single file)", () => {
it("should discover copilot-instructions.md at project root", () => {
// #given .github/copilot-instructions.md at root
// given .github/copilot-instructions.md at root
const githubDir = join(TEST_DIR, ".github");
mkdirSync(githubDir, { recursive: true });
writeFileSync(
@@ -115,10 +115,10 @@ describe("findRuleFiles", () => {
const currentFile = join(TEST_DIR, "index.ts");
writeFileSync(currentFile, "code");
// #when finding rules
// when finding rules
const candidates = findRuleFiles(TEST_DIR, homeDir, currentFile);
// #then should find the single file rule
// then should find the single file rule
const singleFile = candidates.find((c) =>
c.path.includes("copilot-instructions.md")
);
@@ -127,7 +127,7 @@ describe("findRuleFiles", () => {
});
it("should mark single file rules with isSingleFile: true", () => {
// #given copilot-instructions.md
// given copilot-instructions.md
const githubDir = join(TEST_DIR, ".github");
mkdirSync(githubDir, { recursive: true });
writeFileSync(
@@ -138,17 +138,17 @@ describe("findRuleFiles", () => {
const currentFile = join(TEST_DIR, "file.ts");
writeFileSync(currentFile, "code");
// #when finding rules
// when finding rules
const candidates = findRuleFiles(TEST_DIR, homeDir, currentFile);
// #then isSingleFile should be true
// then isSingleFile should be true
const copilotFile = candidates.find((c) => c.isSingleFile);
expect(copilotFile).toBeDefined();
expect(copilotFile?.path).toContain("copilot-instructions.md");
});
it("should set distance to 0 for single file rules", () => {
// #given copilot-instructions.md at project root
// given copilot-instructions.md at project root
const githubDir = join(TEST_DIR, ".github");
mkdirSync(githubDir, { recursive: true });
writeFileSync(
@@ -161,10 +161,10 @@ describe("findRuleFiles", () => {
const currentFile = join(srcDir, "file.ts");
writeFileSync(currentFile, "code");
// #when finding rules from deeply nested file
// when finding rules from deeply nested file
const candidates = findRuleFiles(TEST_DIR, homeDir, currentFile);
// #then single file should have distance 0
// then single file should have distance 0
const copilotFile = candidates.find((c) => c.isSingleFile);
expect(copilotFile?.distance).toBe(0);
});
@@ -172,7 +172,7 @@ describe("findRuleFiles", () => {
describe("backward compatibility", () => {
it("should still discover .claude/rules/ files", () => {
// #given .claude/rules/ directory
// given .claude/rules/ directory
const rulesDir = join(TEST_DIR, ".claude", "rules");
mkdirSync(rulesDir, { recursive: true });
writeFileSync(join(rulesDir, "typescript.md"), "TS rules");
@@ -180,16 +180,16 @@ describe("findRuleFiles", () => {
const currentFile = join(TEST_DIR, "index.ts");
writeFileSync(currentFile, "code");
// #when finding rules
// when finding rules
const candidates = findRuleFiles(TEST_DIR, homeDir, currentFile);
// #then should find claude rules
// then should find claude rules
const paths = candidates.map((c) => c.path);
expect(paths.some((p) => p.includes(".claude/rules/"))).toBe(true);
});
it("should still discover .cursor/rules/ files", () => {
// #given .cursor/rules/ directory
// given .cursor/rules/ directory
const rulesDir = join(TEST_DIR, ".cursor", "rules");
mkdirSync(rulesDir, { recursive: true });
writeFileSync(join(rulesDir, "python.md"), "PY rules");
@@ -197,16 +197,16 @@ describe("findRuleFiles", () => {
const currentFile = join(TEST_DIR, "main.py");
writeFileSync(currentFile, "code");
// #when finding rules
// when finding rules
const candidates = findRuleFiles(TEST_DIR, homeDir, currentFile);
// #then should find cursor rules
// then should find cursor rules
const paths = candidates.map((c) => c.path);
expect(paths.some((p) => p.includes(".cursor/rules/"))).toBe(true);
});
it("should discover .mdc files in rule directories", () => {
// #given .mdc file in .claude/rules/
// given .mdc file in .claude/rules/
const rulesDir = join(TEST_DIR, ".claude", "rules");
mkdirSync(rulesDir, { recursive: true });
writeFileSync(join(rulesDir, "advanced.mdc"), "MDC rules");
@@ -214,10 +214,10 @@ describe("findRuleFiles", () => {
const currentFile = join(TEST_DIR, "app.ts");
writeFileSync(currentFile, "code");
// #when finding rules
// when finding rules
const candidates = findRuleFiles(TEST_DIR, homeDir, currentFile);
// #then should find .mdc file
// then should find .mdc file
const paths = candidates.map((c) => c.path);
expect(paths.some((p) => p.endsWith("advanced.mdc"))).toBe(true);
});
@@ -225,7 +225,7 @@ describe("findRuleFiles", () => {
describe("mixed sources", () => {
it("should discover rules from all sources", () => {
// #given rules in multiple directories
// given rules in multiple directories
const claudeRules = join(TEST_DIR, ".claude", "rules");
const cursorRules = join(TEST_DIR, ".cursor", "rules");
const githubInstructions = join(TEST_DIR, ".github", "instructions");
@@ -246,10 +246,10 @@ describe("findRuleFiles", () => {
const currentFile = join(TEST_DIR, "index.ts");
writeFileSync(currentFile, "code");
// #when finding rules
// when finding rules
const candidates = findRuleFiles(TEST_DIR, homeDir, currentFile);
// #then should find all rules
// then should find all rules
expect(candidates.length).toBeGreaterThanOrEqual(4);
const paths = candidates.map((c) => c.path);
expect(paths.some((p) => p.includes(".claude/rules/"))).toBe(true);
@@ -263,7 +263,7 @@ describe("findRuleFiles", () => {
});
it("should not duplicate single file rules", () => {
// #given copilot-instructions.md
// given copilot-instructions.md
const githubDir = join(TEST_DIR, ".github");
mkdirSync(githubDir, { recursive: true });
writeFileSync(
@@ -274,10 +274,10 @@ describe("findRuleFiles", () => {
const currentFile = join(TEST_DIR, "file.ts");
writeFileSync(currentFile, "code");
// #when finding rules
// when finding rules
const candidates = findRuleFiles(TEST_DIR, homeDir, currentFile);
// #then should only have one copilot-instructions.md entry
// then should only have one copilot-instructions.md entry
const copilotFiles = candidates.filter((c) =>
c.path.includes("copilot-instructions.md")
);
@@ -287,7 +287,7 @@ describe("findRuleFiles", () => {
describe("user-level rules", () => {
it("should discover user-level .claude/rules/ files", () => {
// #given user-level rules
// given user-level rules
const userRulesDir = join(homeDir, ".claude", "rules");
mkdirSync(userRulesDir, { recursive: true });
writeFileSync(join(userRulesDir, "global.md"), "Global user rules");
@@ -295,17 +295,17 @@ describe("findRuleFiles", () => {
const currentFile = join(TEST_DIR, "app.ts");
writeFileSync(currentFile, "code");
// #when finding rules
// when finding rules
const candidates = findRuleFiles(TEST_DIR, homeDir, currentFile);
// #then should find user-level rules
// then should find user-level rules
const userRule = candidates.find((c) => c.isGlobal);
expect(userRule).toBeDefined();
expect(userRule?.path).toContain("global.md");
});
it("should mark user-level rules as isGlobal: true", () => {
// #given user-level rules
// given user-level rules
const userRulesDir = join(homeDir, ".claude", "rules");
mkdirSync(userRulesDir, { recursive: true });
writeFileSync(join(userRulesDir, "user.md"), "User rules");
@@ -313,10 +313,10 @@ describe("findRuleFiles", () => {
const currentFile = join(TEST_DIR, "app.ts");
writeFileSync(currentFile, "code");
// #when finding rules
// when finding rules
const candidates = findRuleFiles(TEST_DIR, homeDir, currentFile);
// #then isGlobal should be true
// then isGlobal should be true
const userRule = candidates.find((c) => c.path.includes("user.md"));
expect(userRule?.isGlobal).toBe(true);
expect(userRule?.distance).toBe(9999);
@@ -338,44 +338,44 @@ describe("findProjectRoot", () => {
});
it("should find project root with .git directory", () => {
// #given directory with .git
// given directory with .git
mkdirSync(join(TEST_DIR, ".git"), { recursive: true });
const nestedFile = join(TEST_DIR, "src", "components", "Button.tsx");
mkdirSync(join(TEST_DIR, "src", "components"), { recursive: true });
writeFileSync(nestedFile, "code");
// #when finding project root from nested file
// when finding project root from nested file
const root = findProjectRoot(nestedFile);
// #then should return the directory with .git
// then should return the directory with .git
expect(root).toBe(TEST_DIR);
});
it("should find project root with package.json", () => {
// #given directory with package.json
// given directory with package.json
writeFileSync(join(TEST_DIR, "package.json"), "{}");
const nestedFile = join(TEST_DIR, "lib", "index.js");
mkdirSync(join(TEST_DIR, "lib"), { recursive: true });
writeFileSync(nestedFile, "code");
// #when finding project root
// when finding project root
const root = findProjectRoot(nestedFile);
// #then should find the package.json directory
// then should find the package.json directory
expect(root).toBe(TEST_DIR);
});
it("should return null when no project markers found", () => {
// #given directory without any project markers
// given directory without any project markers
const isolatedDir = join(TEST_DIR, "isolated");
mkdirSync(isolatedDir, { recursive: true });
const file = join(isolatedDir, "file.txt");
writeFileSync(file, "content");
// #when finding project root
// when finding project root
const root = findProjectRoot(file);
// #then should return null
// then should return null
expect(root).toBeNull();
});
});
+5 -1
View File
@@ -16,6 +16,7 @@ import {
saveInjectedRules,
} from "./storage";
import { createDynamicTruncator } from "../../shared/dynamic-truncator";
import { getRuleInjectionFilePath } from "./output-path";
interface ToolExecuteInput {
tool: string;
@@ -72,6 +73,7 @@ export function createRulesInjectorHook(ctx: PluginInput) {
return resolve(ctx.directory, path);
}
async function processFilePathForInjection(
filePath: string,
sessionID: string,
@@ -144,7 +146,9 @@ export function createRulesInjectorHook(ctx: PluginInput) {
const toolName = input.tool.toLowerCase();
if (TRACKED_TOOLS.includes(toolName)) {
await processFilePathForInjection(output.title, input.sessionID, output);
const filePath = getRuleInjectionFilePath(output);
if (!filePath) return;
await processFilePathForInjection(filePath, input.sessionID, output);
return;
}
};
@@ -0,0 +1,46 @@
import { describe, expect, it } from "bun:test";
import { getRuleInjectionFilePath } from "./output-path";
describe("getRuleInjectionFilePath", () => {
it("prefers metadata filePath when available", () => {
// given
const output = {
title: "read file",
metadata: { filePath: "/project/src/app.ts" },
};
// when
const result = getRuleInjectionFilePath(output);
// then
expect(result).toBe("/project/src/app.ts");
});
it("falls back to title when metadata filePath is missing", () => {
// given
const output = {
title: "src/app.ts",
metadata: {},
};
// when
const result = getRuleInjectionFilePath(output);
// then
expect(result).toBe("src/app.ts");
});
it("returns null when both title and metadata are empty", () => {
// given
const output = {
title: "",
metadata: null,
};
// when
const result = getRuleInjectionFilePath(output);
// then
expect(result).toBeNull();
});
});
+22
View File
@@ -0,0 +1,22 @@
export interface ToolExecuteOutputShape {
title: string;
metadata: unknown;
}
export function getRuleInjectionFilePath(
output: ToolExecuteOutputShape
): string | null {
const metadata = output.metadata as Record<string, unknown> | null;
const metadataFilePath =
metadata && typeof metadata === "object" ? metadata.filePath : undefined;
if (typeof metadataFilePath === "string" && metadataFilePath.length > 0) {
return metadataFilePath;
}
if (typeof output.title === "string" && output.title.length > 0) {
return output.title;
}
return null;
}
+45 -45
View File
@@ -4,36 +4,36 @@ import { parseRuleFrontmatter } from "./parser";
describe("parseRuleFrontmatter", () => {
describe("applyTo field (GitHub Copilot format)", () => {
it("should parse applyTo as single string", () => {
// #given frontmatter with applyTo as single string
// given frontmatter with applyTo as single string
const content = `---
applyTo: "*.ts"
---
Rule content here`;
// #when parsing
// when parsing
const result = parseRuleFrontmatter(content);
// #then globs should contain the pattern
// then globs should contain the pattern
expect(result.metadata.globs).toBe("*.ts");
expect(result.body).toBe("Rule content here");
});
it("should parse applyTo as inline array", () => {
// #given frontmatter with applyTo as inline array
// given frontmatter with applyTo as inline array
const content = `---
applyTo: ["*.ts", "*.tsx"]
---
Rule content`;
// #when parsing
// when parsing
const result = parseRuleFrontmatter(content);
// #then globs should be array
// then globs should be array
expect(result.metadata.globs).toEqual(["*.ts", "*.tsx"]);
});
it("should parse applyTo as multi-line array", () => {
// #given frontmatter with applyTo as multi-line array
// given frontmatter with applyTo as multi-line array
const content = `---
applyTo:
- "*.ts"
@@ -41,68 +41,68 @@ applyTo:
---
Content`;
// #when parsing
// when parsing
const result = parseRuleFrontmatter(content);
// #then globs should be array
// then globs should be array
expect(result.metadata.globs).toEqual(["*.ts", "src/**/*.js"]);
});
it("should parse applyTo as comma-separated string", () => {
// #given frontmatter with comma-separated applyTo
// given frontmatter with comma-separated applyTo
const content = `---
applyTo: "*.ts, *.js"
---
Content`;
// #when parsing
// when parsing
const result = parseRuleFrontmatter(content);
// #then globs should be array
// then globs should be array
expect(result.metadata.globs).toEqual(["*.ts", "*.js"]);
});
it("should merge applyTo and globs when both present", () => {
// #given frontmatter with both applyTo and globs
// given frontmatter with both applyTo and globs
const content = `---
globs: "*.md"
applyTo: "*.ts"
---
Content`;
// #when parsing
// when parsing
const result = parseRuleFrontmatter(content);
// #then should merge both into globs array
// then should merge both into globs array
expect(result.metadata.globs).toEqual(["*.md", "*.ts"]);
});
it("should parse applyTo without quotes", () => {
// #given frontmatter with unquoted applyTo
// given frontmatter with unquoted applyTo
const content = `---
applyTo: **/*.py
---
Python rules`;
// #when parsing
// when parsing
const result = parseRuleFrontmatter(content);
// #then should parse correctly
// then should parse correctly
expect(result.metadata.globs).toBe("**/*.py");
});
it("should parse applyTo with description", () => {
// #given frontmatter with applyTo and description (GitHub Copilot style)
// given frontmatter with applyTo and description (GitHub Copilot style)
const content = `---
applyTo: "**/*.ts,**/*.tsx"
description: "TypeScript coding standards"
---
# TypeScript Guidelines`;
// #when parsing
// when parsing
const result = parseRuleFrontmatter(content);
// #then should parse both fields
// then should parse both fields
expect(result.metadata.globs).toEqual(["**/*.ts", "**/*.tsx"]);
expect(result.metadata.description).toBe("TypeScript coding standards");
});
@@ -110,70 +110,70 @@ description: "TypeScript coding standards"
describe("existing globs/paths parsing (backward compatibility)", () => {
it("should still parse globs field correctly", () => {
// #given existing globs format
// given existing globs format
const content = `---
globs: ["*.py", "**/*.ts"]
---
Python/TypeScript rules`;
// #when parsing
// when parsing
const result = parseRuleFrontmatter(content);
// #then should work as before
// then should work as before
expect(result.metadata.globs).toEqual(["*.py", "**/*.ts"]);
});
it("should still parse paths field as alias", () => {
// #given paths field (Claude Code style)
// given paths field (Claude Code style)
const content = `---
paths: ["src/**"]
---
Source rules`;
// #when parsing
// when parsing
const result = parseRuleFrontmatter(content);
// #then should map to globs
// then should map to globs
expect(result.metadata.globs).toEqual(["src/**"]);
});
it("should parse alwaysApply correctly", () => {
// #given frontmatter with alwaysApply
// given frontmatter with alwaysApply
const content = `---
alwaysApply: true
---
Always apply this rule`;
// #when parsing
// when parsing
const result = parseRuleFrontmatter(content);
// #then should recognize alwaysApply
// then should recognize alwaysApply
expect(result.metadata.alwaysApply).toBe(true);
});
});
describe("no frontmatter", () => {
it("should return empty metadata and full body for plain markdown", () => {
// #given markdown without frontmatter
// given markdown without frontmatter
const content = `# Instructions
This is a plain rule file without frontmatter.`;
// #when parsing
// when parsing
const result = parseRuleFrontmatter(content);
// #then should have empty metadata
// then should have empty metadata
expect(result.metadata).toEqual({});
expect(result.body).toBe(content);
});
it("should handle empty content", () => {
// #given empty content
// given empty content
const content = "";
// #when parsing
// when parsing
const result = parseRuleFrontmatter(content);
// #then should return empty metadata and body
// then should return empty metadata and body
expect(result.metadata).toEqual({});
expect(result.body).toBe("");
});
@@ -181,22 +181,22 @@ This is a plain rule file without frontmatter.`;
describe("edge cases", () => {
it("should handle frontmatter with only applyTo", () => {
// #given minimal GitHub Copilot format
// given minimal GitHub Copilot format
const content = `---
applyTo: "**"
---
Apply to all files`;
// #when parsing
// when parsing
const result = parseRuleFrontmatter(content);
// #then should parse correctly
// then should parse correctly
expect(result.metadata.globs).toBe("**");
expect(result.body).toBe("Apply to all files");
});
it("should handle mixed array formats", () => {
// #given globs as multi-line and applyTo as inline
// given globs as multi-line and applyTo as inline
const content = `---
globs:
- "*.md"
@@ -204,21 +204,21 @@ applyTo: ["*.ts", "*.js"]
---
Mixed format`;
// #when parsing
// when parsing
const result = parseRuleFrontmatter(content);
// #then should merge both
// then should merge both
expect(result.metadata.globs).toEqual(["*.md", "*.ts", "*.js"]);
});
it("should handle Windows-style line endings", () => {
// #given content with CRLF
// given content with CRLF
const content = "---\r\napplyTo: \"*.ts\"\r\n---\r\nWindows content";
// #when parsing
// when parsing
const result = parseRuleFrontmatter(content);
// #then should parse correctly
// then should parse correctly
expect(result.metadata.globs).toBe("*.ts");
expect(result.body).toBe("Windows content");
});