-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrulesManager.js
More file actions
193 lines (172 loc) · 6.22 KB
/
rulesManager.js
File metadata and controls
193 lines (172 loc) · 6.22 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
/**
* rulesManager.js — Project-level rules/skills for the AI agent.
*
* Reads rules from:
* 1. <projectRoot>/.guide/rules/*.md (individual rule files)
* 2. <projectRoot>/AGENTS.md (project-wide agent instructions)
*
* Rules are injected into the system prompt at chat start.
* The agent can create/update rules via the save_rule tool.
*/
'use strict';
const fs = require('fs');
const path = require('path');
const log = require('./logger');
class RulesManager {
constructor() {
this._projectPath = null;
this._rulesDir = null;
this._guideInstructionsPath = null; // from settings
this._cache = null;
this._cacheTime = 0;
}
initialize(projectPath) {
this._projectPath = projectPath;
this._rulesDir = projectPath ? path.join(projectPath, '.guide', 'rules') : null;
this._cache = null;
this._cacheTime = 0;
}
/** Set the guide instructions path from settings. Invalidates cache. */
setGuideInstructionsPath(p) {
this._guideInstructionsPath = p || null;
this._cache = null;
}
/**
* Load all rules and return as a single prompt string.
* Cached for 10 seconds to avoid repeated disk reads.
*/
getRulesPrompt() {
if (!this._projectPath) return '';
if (this._cache && Date.now() - this._cacheTime < 10000) return this._cache;
const sections = [];
// 1. Read AGENTS.md from project root
const agentsMd = path.join(this._projectPath, 'AGENTS.md');
try {
if (fs.existsSync(agentsMd)) {
const content = fs.readFileSync(agentsMd, 'utf-8').trim();
if (content) sections.push(`## Project Instructions (AGENTS.md)\n${content}`);
}
} catch (e) {
log.warn('Rules', `Failed to read AGENTS.md: ${e.message}`);
}
// 2. Read .guide/rules/*.md
if (this._rulesDir) {
try {
if (fs.existsSync(this._rulesDir)) {
const files = fs.readdirSync(this._rulesDir)
.filter(f => f.endsWith('.md'))
.sort();
for (const file of files) {
try {
const content = fs.readFileSync(path.join(this._rulesDir, file), 'utf-8').trim();
if (content) {
const name = file.replace(/\.md$/, '');
sections.push(`## Rule: ${name}\n${content}`);
}
} catch (e) {
log.warn('Rules', `Failed to read rule ${file}: ${e.message}`);
}
}
}
} catch (e) {
log.warn('Rules', `Failed to scan rules directory: ${e.message}`);
}
}
// 3. Read guide instructions file (from settings)
if (this._guideInstructionsPath) {
try {
const instrPath = path.isAbsolute(this._guideInstructionsPath)
? this._guideInstructionsPath
: path.join(this._projectPath || process.cwd(), this._guideInstructionsPath);
if (fs.existsSync(instrPath)) {
const content = fs.readFileSync(instrPath, 'utf-8').trim();
if (content) {
sections.push(`## Guide Instructions (${this._guideInstructionsPath})\n${content}`);
}
}
} catch (e) {
log.warn('Rules', `Failed to read guide instructions: ${e.message}`);
}
}
if (sections.length === 0) {
this._cache = '';
this._cacheTime = Date.now();
return '';
}
this._cache = `\n\n# Project Rules & Skills\nThe following rules and instructions have been set for this project. Follow them.\n\n${sections.join('\n\n')}\n`;
this._cacheTime = Date.now();
return this._cache;
}
/**
* Save or update a rule file.
* @param {string} name - Rule name (used as filename, .md appended)
* @param {string} content - Rule content (markdown)
* @returns {{ success: boolean, path?: string, error?: string }}
*/
saveRule(name, content) {
if (!this._projectPath) return { success: false, error: 'No project open' };
if (!name || !content) return { success: false, error: 'Name and content are required' };
const safeName = name.replace(/[^a-zA-Z0-9_-]/g, '-').toLowerCase();
const rulesDir = path.join(this._projectPath, '.guide', 'rules');
const filePath = path.join(rulesDir, `${safeName}.md`);
try {
fs.mkdirSync(rulesDir, { recursive: true });
fs.writeFileSync(filePath, content.trim() + '\n', 'utf-8');
this._cache = null;
log.info('Rules', `Saved rule: ${safeName}`);
return { success: true, path: filePath };
} catch (e) {
return { success: false, error: `Failed to save rule: ${e.message}` };
}
}
/**
* Delete a rule file.
*/
deleteRule(name) {
if (!this._projectPath) return { success: false, error: 'No project open' };
const safeName = name.replace(/[^a-zA-Z0-9_-]/g, '-').toLowerCase();
const filePath = path.join(this._projectPath, '.guide', 'rules', `${safeName}.md`);
try {
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
this._cache = null;
return { success: true };
}
return { success: false, error: 'Rule not found' };
} catch (e) {
return { success: false, error: e.message };
}
}
/**
* List all rule names.
*/
listRules() {
const rules = [];
if (!this._projectPath) return rules;
const agentsMd = path.join(this._projectPath, 'AGENTS.md');
if (fs.existsSync(agentsMd)) {
rules.push({ name: 'AGENTS.md', type: 'project', path: agentsMd });
}
if (this._rulesDir && fs.existsSync(this._rulesDir)) {
try {
const files = fs.readdirSync(this._rulesDir).filter(f => f.endsWith('.md')).sort();
for (const f of files) {
rules.push({ name: f.replace(/\.md$/, ''), type: 'rule', path: path.join(this._rulesDir, f) });
}
} catch { /* ignore */ }
}
// Include guide instructions file if configured
if (this._guideInstructionsPath) {
try {
const instrPath = path.isAbsolute(this._guideInstructionsPath)
? this._guideInstructionsPath
: path.join(this._projectPath, this._guideInstructionsPath);
if (fs.existsSync(instrPath)) {
rules.push({ name: this._guideInstructionsPath, type: 'guide-instructions', path: instrPath });
}
} catch { /* ignore */ }
}
return rules;
}
}
module.exports = { RulesManager };