This repository was archived by the owner on Jun 28, 2026. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathproject-rules.service.ts
More file actions
603 lines (508 loc) · 16.5 KB
/
Copy pathproject-rules.service.ts
File metadata and controls
603 lines (508 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
import * as fs from "fs";
import * as path from "path";
import * as vscode from "vscode";
import { Logger, LogLevel } from "../infrastructure/logger/logger";
import { FileService } from "./file-service";
import { WorkspaceIdentityService } from "./workspace-identity.service";
/**
* Supported rule file locations in priority order
*/
const RULE_FILE_LOCATIONS = [
".codebuddy/rules.md",
".codebuddy/rules/index.md",
".codebuddyrules",
"CODEBUDDY.md",
];
/**
* Configuration keys for project rules
*/
const CONFIG_KEYS = {
enabled: "codebuddy.rules.enabled",
maxTokens: "codebuddy.rules.maxTokens",
showIndicator: "codebuddy.rules.showIndicator",
} as const;
/**
* Default configuration values
*/
const DEFAULTS = {
enabled: true,
maxTokens: 2000,
showIndicator: true,
charsPerToken: 4,
} as const;
export interface IProjectRules {
content: string;
filePath: string;
tokenCount: number;
lastModified: Date;
truncated: boolean;
}
export interface IProjectRulesStatus {
hasRules: boolean;
tokenCount: number;
filePath?: string;
truncated?: boolean;
}
/**
* ProjectRulesService manages project-specific rules that are injected into AI prompts.
* Rules are loaded from .codebuddy/rules.md or similar files in the workspace.
*
* Features:
* - Auto-loads rules on workspace open
* - Watches for file changes and reloads
* - Respects token budget limits
* - Merges multiple rule files
* - Notifies webview of status changes
*/
export class ProjectRulesService implements vscode.Disposable {
private static instance: ProjectRulesService | undefined;
private readonly logger: Logger;
private readonly fileService: FileService;
private readonly disposables: vscode.Disposable[] = [];
private cachedRules: IProjectRules | undefined;
private statusCallback: ((status: IProjectRulesStatus) => void) | undefined;
private constructor() {
this.logger = Logger.initialize("ProjectRulesService", {
minLevel: LogLevel.DEBUG,
enableConsole: true,
enableFile: true,
enableTelemetry: false,
});
this.fileService = new FileService();
}
/**
* Get singleton instance of ProjectRulesService
*/
public static getInstance(): ProjectRulesService {
if (!ProjectRulesService.instance) {
ProjectRulesService.instance = new ProjectRulesService();
}
return ProjectRulesService.instance;
}
/**
* Initialize the service - load rules and set up file watchers
*/
public async initialize(): Promise<void> {
this.logger.info("Initializing ProjectRulesService");
// Load rules on startup
await this.loadRules();
// Set up file watchers for rule files
this.setupFileWatchers();
// Watch for configuration changes
this.disposables.push(
vscode.workspace.onDidChangeConfiguration((e) => {
if (
e.affectsConfiguration("codebuddy.rules") ||
e.affectsConfiguration("rules.customRules") ||
e.affectsConfiguration("rules.customSystemPrompt")
) {
this.loadRules();
}
}),
);
this.logger.info("ProjectRulesService initialized");
}
/**
* Load rules from file system and settings
*/
public async loadRules(): Promise<void> {
if (!this.isEnabled()) {
this.cachedRules = undefined;
this.notifyStatusChange();
return;
}
const workspaceRoot = this.getWorkspaceRoot();
if (!workspaceRoot) {
this.logger.warn("No workspace root found");
this.cachedRules = undefined;
this.notifyStatusChange();
return;
}
try {
// Try to find and load rule file
const ruleFile = await this.findRuleFile(workspaceRoot);
if (ruleFile) {
const content = await this.readRuleFile(ruleFile);
const { processedContent, truncated } = this.processContent(content);
this.cachedRules = {
content: processedContent,
filePath: ruleFile,
tokenCount: this.estimateTokens(processedContent),
lastModified: new Date(),
truncated,
};
this.logger.info(
`Loaded project rules from ${ruleFile} (${this.cachedRules.tokenCount} tokens)`,
);
if (truncated) {
vscode.window.showWarningMessage(
`Project rules exceeded token limit and were truncated. Consider reducing rules content.`,
);
}
} else {
this.cachedRules = undefined;
this.logger.info("No project rules file found");
}
// Merge with settings-based rules
await this.mergeSettingsRules();
this.notifyStatusChange();
} catch (error: any) {
this.logger.error("Error loading project rules:", error);
this.cachedRules = undefined;
this.notifyStatusChange();
}
}
/**
* Get the current rules content for prompt injection
*/
public getRules(): string | undefined {
if (!this.isEnabled() || !this.cachedRules) {
return undefined;
}
return this.cachedRules.content;
}
/**
* Check if project rules are loaded
*/
public hasRules(): boolean {
return this.isEnabled() && !!this.cachedRules?.content;
}
/**
* Get current status for UI display
*/
public getStatus(): IProjectRulesStatus {
return {
hasRules: this.hasRules(),
tokenCount: this.cachedRules?.tokenCount ?? 0,
filePath: this.cachedRules?.filePath,
truncated: this.cachedRules?.truncated,
};
}
/**
* Get the rules file path (creates if doesn't exist using scaffold command)
*/
public getRulesFilePath(): string | undefined {
return this.cachedRules?.filePath;
}
/**
* Set callback for status changes (for webview notification)
*/
public onStatusChange(
callback: (status: IProjectRulesStatus) => void,
): vscode.Disposable {
this.statusCallback = callback;
// Immediately notify current status
callback(this.getStatus());
return {
dispose: () => {
this.statusCallback = undefined;
},
};
}
/**
* Create a new rules file with template content
*/
public async createRulesFile(): Promise<string | undefined> {
const workspaceRoot = this.getWorkspaceRoot();
if (!workspaceRoot) {
vscode.window.showErrorMessage("No workspace folder open");
return undefined;
}
const codeBuddyDir = path.join(workspaceRoot, ".codebuddy");
const rulesPath = path.join(codeBuddyDir, "rules.md");
// Check if file already exists
if (fs.existsSync(rulesPath)) {
const openExisting = await vscode.window.showQuickPick(
["Open existing", "Overwrite"],
{
placeHolder: "Rules file already exists. What would you like to do?",
},
);
if (openExisting === "Open existing") {
await this.openRulesFile(rulesPath);
return rulesPath;
} else if (!openExisting) {
return undefined;
}
}
// Ensure .codebuddy directory exists
if (!fs.existsSync(codeBuddyDir)) {
fs.mkdirSync(codeBuddyDir, { recursive: true });
}
// Write template content
const templateContent = this.getTemplateContent();
fs.writeFileSync(rulesPath, templateContent, "utf-8");
this.logger.info(`Created project rules file at ${rulesPath}`);
// Open the file
await this.openRulesFile(rulesPath);
// Reload rules
await this.loadRules();
vscode.window.showInformationMessage(
"Project rules file created! Edit it to customize AI behavior.",
);
return rulesPath;
}
/**
* Open the rules file in editor
*/
public async openRulesFile(filePath?: string): Promise<void> {
const pathToOpen = filePath ?? this.cachedRules?.filePath;
if (!pathToOpen) {
// No rules file exists, offer to create one
const create = await vscode.window.showInformationMessage(
"No project rules file found. Would you like to create one?",
"Create",
"Cancel",
);
if (create === "Create") {
await this.createRulesFile();
}
return;
}
try {
const doc = await vscode.workspace.openTextDocument(pathToOpen);
await vscode.window.showTextDocument(doc);
} catch (error: any) {
this.logger.error(`Failed to open rules file: ${error.message}`);
vscode.window.showErrorMessage(
`Failed to open rules file: ${error.message}`,
);
}
}
/**
* Force reload rules
*/
public async reloadRules(): Promise<void> {
await this.loadRules();
vscode.window.showInformationMessage(
this.hasRules()
? `Project rules reloaded (${this.cachedRules?.tokenCount} tokens)`
: "No project rules found",
);
}
/**
* Dispose of resources
*/
public dispose(): void {
this.disposables.forEach((d) => d.dispose());
this.disposables.length = 0;
ProjectRulesService.instance = undefined;
}
// ================== Private Methods ==================
private isEnabled(): boolean {
return vscode.workspace
.getConfiguration()
.get<boolean>(CONFIG_KEYS.enabled, DEFAULTS.enabled);
}
private getMaxTokens(): number {
return vscode.workspace
.getConfiguration()
.get<number>(CONFIG_KEYS.maxTokens, DEFAULTS.maxTokens);
}
private getWorkspaceRoot(): string | undefined {
return vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
}
private async findRuleFile(
workspaceRoot: string,
): Promise<string | undefined> {
for (const location of RULE_FILE_LOCATIONS) {
const fullPath = path.join(workspaceRoot, location);
if (fs.existsSync(fullPath)) {
return fullPath;
}
}
// Also check for multiple rule files in .codebuddy/rules/
const rulesDir = path.join(workspaceRoot, ".codebuddy", "rules");
if (fs.existsSync(rulesDir) && fs.statSync(rulesDir).isDirectory()) {
const files = fs.readdirSync(rulesDir).filter((f) => f.endsWith(".md"));
if (files.length > 0) {
return rulesDir; // Return directory path to indicate multiple files
}
}
return undefined;
}
private async readRuleFile(filePath: string): Promise<string> {
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
// Read all .md files in directory and concatenate
const files = fs
.readdirSync(filePath)
.filter((f) => f.endsWith(".md"))
.sort();
const contents: string[] = [];
for (const file of files) {
const content = fs.readFileSync(path.join(filePath, file), "utf-8");
contents.push(`<!-- From: ${file} -->\n${content}`);
}
return contents.join("\n\n---\n\n");
} else {
return fs.readFileSync(filePath, "utf-8");
}
}
private processContent(content: string): {
processedContent: string;
truncated: boolean;
} {
const maxTokens = this.getMaxTokens();
const maxChars = maxTokens * DEFAULTS.charsPerToken;
if (content.length <= maxChars) {
return { processedContent: content, truncated: false };
}
// Truncate at a sensible boundary (end of line)
let truncatedContent = content.substring(0, maxChars);
const lastNewline = truncatedContent.lastIndexOf("\n");
if (lastNewline > maxChars * 0.8) {
truncatedContent = truncatedContent.substring(0, lastNewline);
}
truncatedContent += "\n\n<!-- Rules truncated due to token limit -->";
return { processedContent: truncatedContent, truncated: true };
}
private estimateTokens(content: string): number {
return Math.ceil(content.length / DEFAULTS.charsPerToken);
}
private async mergeSettingsRules(): Promise<void> {
// Get global rules from ~/.codebuddy/rules.md (lowest priority)
const globalRulesContent = await this.loadGlobalRules();
// Get custom system prompt from settings
const customSystemPrompt = vscode.workspace
.getConfiguration()
.get<string>("rules.customSystemPrompt", "");
// Get custom rules array from settings
const customRules = vscode.workspace
.getConfiguration()
.get<
Array<{ content: string; enabled: boolean }>
>("rules.customRules", []);
const enabledRules = customRules
.filter((r) => r.enabled)
.map((r) => r.content);
// Priority (highest → lowest): workspace file > settings snippets > global file.
// Later entries in the array take precedence when topics conflict.
const allRules: string[] = [];
// 1. Global rules (lowest priority — can be overridden by everything below)
if (globalRulesContent) {
allRules.push("## Global Rules\n" + globalRulesContent);
}
// 2. Settings-level snippets
if (enabledRules.length > 0) {
allRules.push("## Settings-Based Rules\n" + enabledRules.join("\n\n"));
}
if (customSystemPrompt) {
allRules.push("## Additional Instructions\n" + customSystemPrompt);
}
// 3. Workspace-level rules file (highest priority — overrides all)
if (this.cachedRules?.content) {
allRules.push(this.cachedRules.content);
}
if (allRules.length > 0) {
const mergedContent = allRules.join("\n\n---\n\n");
const { processedContent, truncated } =
this.processContent(mergedContent);
if (!this.cachedRules) {
this.cachedRules = {
content: processedContent,
filePath: "settings",
tokenCount: this.estimateTokens(processedContent),
lastModified: new Date(),
truncated,
};
} else {
this.cachedRules.content = processedContent;
this.cachedRules.tokenCount = this.estimateTokens(processedContent);
this.cachedRules.truncated = truncated;
}
}
}
/**
* Load global rules from ~/.codebuddy/rules.md (shared across all workspaces).
*/
private async loadGlobalRules(): Promise<string | undefined> {
try {
const globalPath = WorkspaceIdentityService.getGlobalRulesPath();
await fs.promises.access(globalPath);
const content = (await fs.promises.readFile(globalPath, "utf-8")).trim();
if (content) {
this.logger.info(
`Loaded global rules from ${globalPath} (${this.estimateTokens(content)} tokens)`,
);
return content;
}
} catch (error: any) {
// ENOENT is expected when no global rules file exists
if (error.code !== "ENOENT") {
this.logger.warn(`Failed to load global rules: ${error.message}`);
}
}
return undefined;
}
private setupFileWatchers(): void {
const watchers = this.fileService.createWatcher(
{
patterns: [
".codebuddy/rules.md",
".codebuddy/rules/*.md",
".codebuddyrules",
"CODEBUDDY.md",
],
},
// onCreated
(uri) => {
this.logger.info(`Rules file created: ${uri.fsPath}`);
this.loadRules();
},
// onChanged
(uri) => {
this.logger.info(`Rules file changed: ${uri.fsPath}`);
this.loadRules();
},
// onDeleted
(uri) => {
this.logger.info(`Rules file deleted: ${uri.fsPath}`);
this.loadRules();
},
);
this.disposables.push(...watchers);
}
private notifyStatusChange(): void {
if (this.statusCallback) {
this.statusCallback(this.getStatus());
}
}
private getTemplateContent(): string {
return `# Project Rules for CodeBuddy
These rules are automatically included in every AI prompt. Use them to ensure consistent code generation that matches your project's conventions.
## Code Style
- Use [functional/class] components
- Prefer \`const\` over \`let\`, never use \`var\`
- Use [named/default] exports
- Maximum line length: [80/100/120] characters
## Architecture
- All API calls go through \`src/services/\`
- State management uses [Redux/Zustand/Context]
- Follow the [repository/service] pattern for data access
## Naming Conventions
- Components: PascalCase (\`UserProfile.tsx\`)
- Utilities: camelCase (\`formatDate.ts\`)
- Constants: SCREAMING_SNAKE_CASE
- Interfaces: prefix with \`I\` (\`IUserProfile\`)
## Error Handling
- Always use try/catch for async operations
- Log errors with context information
- Show user-friendly error messages, not stack traces
## Testing
- Write unit tests for all new functions
- Use \`describe\`/\`it\` pattern
- Mock external dependencies
## Security
- Never log sensitive data (passwords, tokens, PII)
- Sanitize all user inputs
- Use parameterized queries for database operations
## Documentation
- Add JSDoc comments to public functions
- Include usage examples for complex APIs
- Keep README up to date
---
*Tip: Remove sections that don't apply to your project. Keep rules concise for better token efficiency.*
`;
}
}