claude-rules.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /**
  2. * Claude Rules Extension
  3. *
  4. * Scans the project's .claude/rules/ folder for rule files and lists them
  5. * in the system prompt. The agent can then use the read tool to load
  6. * specific rules when needed.
  7. *
  8. * Best practices for .claude/rules/:
  9. * - Keep rules focused: Each file should cover one topic (e.g., testing.md, api-design.md)
  10. * - Use descriptive filenames: The filename should indicate what the rules cover
  11. * - Use conditional rules sparingly: Only add paths frontmatter when rules truly apply to specific file types
  12. * - Organize with subdirectories: Group related rules (e.g., frontend/, backend/)
  13. *
  14. * Usage:
  15. * 1. Copy this file to ~/.pi/agent/extensions/ or your project's .pi/extensions/
  16. * 2. Create .claude/rules/ folder in your project root
  17. * 3. Add .md files with your rules
  18. */
  19. import * as fs from "node:fs";
  20. import * as path from "node:path";
  21. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  22. /**
  23. * Recursively find all .md files in a directory
  24. */
  25. function findMarkdownFiles(dir: string, basePath: string = ""): string[] {
  26. const results: string[] = [];
  27. if (!fs.existsSync(dir)) {
  28. return results;
  29. }
  30. const entries = fs.readdirSync(dir, { withFileTypes: true });
  31. for (const entry of entries) {
  32. const relativePath = basePath ? `${basePath}/${entry.name}` : entry.name;
  33. if (entry.isDirectory()) {
  34. results.push(...findMarkdownFiles(path.join(dir, entry.name), relativePath));
  35. } else if (entry.isFile() && entry.name.endsWith(".md")) {
  36. results.push(relativePath);
  37. }
  38. }
  39. return results;
  40. }
  41. export default function claudeRulesExtension(pi: ExtensionAPI) {
  42. let ruleFiles: string[] = [];
  43. let rulesDir: string = "";
  44. // Scan for rules on session start
  45. pi.on("session_start", async (_event, ctx) => {
  46. rulesDir = path.join(ctx.cwd, ".claude", "rules");
  47. ruleFiles = findMarkdownFiles(rulesDir);
  48. if (ruleFiles.length > 0) {
  49. ctx.ui.notify(`Found ${ruleFiles.length} rule(s) in .claude/rules/`, "info");
  50. }
  51. });
  52. // Append available rules to system prompt
  53. pi.on("before_agent_start", async (event) => {
  54. if (ruleFiles.length === 0) {
  55. return;
  56. }
  57. const rulesList = ruleFiles.map((f) => `- .claude/rules/${f}`).join("\n");
  58. return {
  59. systemPrompt:
  60. event.systemPrompt +
  61. `
  62. ## Project Rules
  63. The following project rules are available in .claude/rules/:
  64. ${rulesList}
  65. When working on tasks related to these rules, use the read tool to load the relevant rule files for guidance.
  66. `,
  67. };
  68. });
  69. }