This repository was archived by the owner on Jan 22, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddon.js
More file actions
460 lines (404 loc) · 14.9 KB
/
addon.js
File metadata and controls
460 lines (404 loc) · 14.9 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
/**
* Addon System for Sigrid Workspaces
*
* Addons provide modular functionality that can be added to workspaces.
* They are simple JavaScript objects - no coupling to directory structure.
*
* See test-fixtures/addons/ for example addons (like sqlite.js).
*
* Addons are JavaScript objects with the following structure:
*
* {
* name: string, // Addon name
* version: string, // Addon version
* description: string, // Human-readable description
* dependencies: object, // npm dependencies to add to package.json
* aiRulesAddition: string,// Text to append to AI_RULES.md
* files: { // Files to write to workspace
* 'path/to/file.js': 'file content...',
* ...
* },
* internal: [string] // Paths to exclude from snapshots (implementation files)
* }
*
* Addons can be defined inline, loaded from files, or generated programmatically.
*/
import fs from 'node:fs/promises';
import path from 'node:path';
/**
* Get the path to the addons.json file for a workspace
* @param {string} workspacePath - Workspace directory path
* @returns {string} Path to addons.json
*/
function getAddonsFile(workspacePath) {
return path.join(workspacePath, '.sigrid', 'addons.json');
}
/**
* Generate unique identifier for an addon
* @param {Object} addon - Addon object
* @returns {string} Unique identifier (name@version)
*/
function getAddonId(addon) {
const version = addon.version || '1.0.0';
return `${addon.name}@${version}`;
}
/**
* Read addons registry from workspace filesystem
* @param {string} workspacePath - Workspace directory path
* @returns {Promise<Object>} Addons registry
*/
async function readAddonsRegistry(workspacePath) {
const filePath = getAddonsFile(workspacePath);
try {
const content = await fs.readFile(filePath, 'utf-8');
return JSON.parse(content);
} catch (error) {
if (error.code === 'ENOENT') {
return { applied: {} }; // File doesn't exist yet
}
throw error;
}
}
/**
* Write addons registry to workspace filesystem
* @param {string} workspacePath - Workspace directory path
* @param {Object} registry - Addons registry
*/
async function writeAddonsRegistry(workspacePath, registry) {
const filePath = getAddonsFile(workspacePath);
await fs.mkdir(path.dirname(filePath), { recursive: true });
await fs.writeFile(filePath, JSON.stringify(registry, null, 2), 'utf-8');
}
/**
* Generate AI rules addition text from addon's API definition
* Auto-generates LLM documentation from structured API metadata
*
* @param {Object} addon - Addon object with api field
* @param {string} addon.name - Addon name
* @param {string} [addon.description] - Brief description
* @param {Object} [addon.api] - Structured API definition
* @param {string} [addon.docs] - Path to documentation file
* @param {string} [addon.technology] - Technology used
* @param {string} [addon.useCases] - Use cases description
* @returns {string} Formatted AI rules addition text
*
* @example
* // Addon with structured API definition
* const addon = {
* name: 'sqlite',
* description: 'Browser SQLite database',
* technology: 'sql.js (SQLite WASM) with IndexedDB',
* useCases: 'Perfect for todo apps, notes, offline-first apps',
* docs: 'docs/database-api.md',
* api: {
* '@/lib/database': {
* exports: {
* 'createDatabase': 'Creates a new SQLite database instance'
* },
* methods: {
* 'query(sql, params)': 'Execute SELECT queries',
* 'execute(sql, params)': 'Execute INSERT/UPDATE/DELETE',
* 'transaction(statements)': 'Run multiple statements atomically'
* }
* }
* }
* };
* const aiRules = generateAIRulesFromAPI(addon);
*/
export function generateAIRulesFromAPI(addon) {
if (!addon.api) {
return ''; // No API definition provided
}
const title = addon.name.charAt(0).toUpperCase() + addon.name.slice(1);
let content = `\n## ${title}\n\n${addon.description || `Provides ${addon.name} functionality`}`;
const bullets = [];
// Extract imports and exports from api definition
const apiPaths = Object.keys(addon.api);
for (const importPath of apiPaths) {
const apiDef = addon.api[importPath];
// Add imports
if (apiDef.exports) {
const exportNames = Object.keys(apiDef.exports);
if (exportNames.length > 0) {
bullets.push(`**Import**: \`import { ${exportNames.join(', ')} } from '${importPath}'\``);
}
}
}
// Add documentation reference
if (addon.docs) {
bullets.push(`**Documentation**: See \`${addon.docs}\` for complete API reference and examples`);
}
// Add technology
if (addon.technology) {
bullets.push(`**Technology**: ${addon.technology}`);
}
// Add use cases
if (addon.useCases) {
bullets.push(`**Use Case**: ${addon.useCases}`);
}
if (bullets.length > 0) {
content += ':\n\n' + bullets.map(b => `- ${b}`).join('\n');
}
// Add API methods summary
const allMethods = [];
for (const importPath of apiPaths) {
const apiDef = addon.api[importPath];
if (apiDef.methods) {
allMethods.push(...Object.keys(apiDef.methods));
}
}
if (allMethods.length > 0) {
content += `\n\nMain API: ${allMethods.map(m => `\`${m}\``).join(', ')}.`;
if (addon.docs) {
content += ' See the docs for usage patterns.';
}
}
// Add conventions from API definition
const allConventions = [];
for (const importPath of apiPaths) {
const apiDef = addon.api[importPath];
if (apiDef.conventions && Array.isArray(apiDef.conventions)) {
allConventions.push(...apiDef.conventions);
}
}
if (allConventions.length > 0) {
content += '\n\n**Conventions**:\n\n';
content += allConventions.map(c => `- ${c}`).join('\n');
}
content += '\n';
return content;
}
/**
* Validate that addon's API definition matches its file contents
* Throws error if validation fails
* @param {Object} addon - Addon object
* @throws {Error} If API definition doesn't match files
*/
function validateAddonAPI(addon) {
if (!addon.api || !addon.files) {
return;
}
const errors = [];
// Check each API module
for (const [importPath, apiDef] of Object.entries(addon.api)) {
// Convert import path to file path
// @/lib/database -> src/lib/database.js (or .ts)
const possiblePaths = [
importPath.replace('@/', 'src/') + '.js',
importPath.replace('@/', 'src/') + '.ts',
importPath.replace('@/', 'src/') + '.jsx',
importPath.replace('@/', 'src/') + '.tsx'
];
// Find matching file
const filePath = possiblePaths.find(p => addon.files[p]);
if (!filePath) {
errors.push(`API defines "${importPath}" but no matching file found in files object`);
continue;
}
const fileContent = addon.files[filePath];
// Validate exports
if (apiDef.exports) {
for (const exportName of Object.keys(apiDef.exports)) {
// Simple check: does export appear in file?
const exportPatterns = [
`export function ${exportName}`,
`export const ${exportName}`,
`export async function ${exportName}`,
`export { ${exportName}`,
`function ${exportName}`
];
const found = exportPatterns.some(pattern => fileContent.includes(pattern));
if (!found) {
errors.push(`API defines export "${exportName}" in ${importPath} but it does not exist in ${filePath}`);
}
}
}
}
if (errors.length > 0) {
throw new Error(`Addon API validation failed:\n - ${errors.join('\n - ')}`);
}
}
/**
* Get list of paths that should be excluded from snapshots for a workspace
* @param {string} workspacePath - Workspace directory path
* @returns {Promise<Array<string>>} Array of paths to exclude
*/
export async function getAddonInternalPaths(workspacePath) {
const registry = await readAddonsRegistry(workspacePath);
const allInternalPaths = [];
// Collect internal paths from all applied addons
for (const addonData of Object.values(registry.applied)) {
if (addonData.internalPaths) {
allInternalPaths.push(...addonData.internalPaths);
}
}
return allInternalPaths;
}
/**
* Apply an addon to a workspace
*
* @param {import('./workspace.js').Workspace} workspace - Workspace instance
* @param {Object} addon - Addon object
* @param {string} addon.name - Addon name
* @param {string} addon.version - Addon version
* @param {string} [addon.description] - Description
* @param {Object} [addon.dependencies] - npm dependencies to add
* @param {string} [addon.aiRulesAddition] - Text to append to AI_RULES.md
* @param {Object} [addon.api] - Structured API definition for auto-generating AI rules
* @param {Object} addon.files - Files to write { 'path': 'content' }
* @param {Array<string>} [addon.internal] - Paths to exclude from snapshots
* @param {Object} [options] - Additional options
* @param {boolean} [options.validate] - Validate API definitions against actual file contents
* @returns {Promise<Object>} Application result
*
* @example
* // Simple addon
* await applyAddon(workspace, {
* name: 'config',
* files: {
* 'src/config.js': 'export const API_URL = "https://api.example.com";'
* }
* });
*
* @example
* // Complex addon with dependencies
* import sqliteAddon from './addons/sqlite.js';
* await applyAddon(workspace, sqliteAddon);
*/
export async function applyAddon(workspace, addon, options = {}) {
if (!addon || typeof addon !== 'object') {
throw new Error('Addon must be an object');
}
if (!addon.name) {
throw new Error('Addon must have a name');
}
if (!addon.files || typeof addon.files !== 'object') {
throw new Error('Addon must have a files object');
}
// Generate unique ID for this addon
const addonId = getAddonId(addon);
// Check if addon is already applied (idempotent)
const registry = await readAddonsRegistry(workspace.path);
if (registry.applied[addonId]) {
return {
addon: addon.name,
version: addon.version || '1.0.0',
alreadyApplied: true,
appliedAt: registry.applied[addonId].appliedAt
};
}
const result = {
addon: addon.name,
version: addon.version || '1.0.0',
filesAdded: []
};
// Validate API definitions (always-on, minimal overhead)
// Throws if validation fails
if (addon.api) {
validateAddonAPI(addon);
}
// 1. Write all files to workspace
for (const [filePath, content] of Object.entries(addon.files)) {
const fullPath = path.join(workspace.path, filePath);
// Create directory if needed
await fs.mkdir(path.dirname(fullPath), { recursive: true });
// Write file
await fs.writeFile(fullPath, content, 'utf-8');
result.filesAdded.push(filePath);
}
// 2. Register addon in workspace registry
registry.applied[addonId] = {
name: addon.name,
version: addon.version || '1.0.0',
appliedAt: new Date().toISOString(),
internalPaths: addon.internal || []
};
await writeAddonsRegistry(workspace.path, registry);
// 3. Update package.json with dependencies
if (addon.dependencies && Object.keys(addon.dependencies).length > 0) {
const packageJsonPath = path.join(workspace.path, 'package.json');
let packageJson;
try {
packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf-8'));
} catch (error) {
if (error.code === 'ENOENT') {
// package.json doesn't exist, create minimal one
packageJson = {
name: 'workspace',
version: '1.0.0',
dependencies: {}
};
} else {
throw error;
}
}
packageJson.dependencies = {
...packageJson.dependencies,
...addon.dependencies
};
await fs.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2) + '\n');
result.dependenciesAdded = addon.dependencies;
}
// 4. Update AI_RULES.md with addon instructions
// Auto-generate from api field if aiRulesAddition not provided
let aiRulesContent = addon.aiRulesAddition;
if (!aiRulesContent && addon.api) {
aiRulesContent = generateAIRulesFromAPI(addon);
}
if (aiRulesContent) {
const aiRulesPath = path.join(workspace.path, 'AI_RULES.md');
let currentRules = '';
try {
currentRules = await fs.readFile(aiRulesPath, 'utf-8');
} catch (error) {
if (error.code !== 'ENOENT') throw error;
// File doesn't exist, create it with a header
currentRules = '# AI Rules\n\nProject-specific instructions for AI assistants.\n';
}
await fs.writeFile(aiRulesPath, currentRules + aiRulesContent);
result.aiRulesUpdated = true;
}
return result;
}
/**
* Check if an addon is applied to a workspace
* @param {import('./workspace.js').Workspace} workspace - Workspace instance
* @param {Object} addon - Addon object to check
* @returns {Promise<boolean>} True if addon is applied
*/
export async function isAddonApplied(workspace, addon) {
// Check if addon dependencies are in package.json
const packageJsonPath = path.join(workspace.path, 'package.json');
const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf-8'));
if (addon.dependencies) {
for (const dep of Object.keys(addon.dependencies)) {
if (!packageJson.dependencies?.[dep]) {
return false;
}
}
}
// Check if AI rules contain the addon's content
let contentToCheck = addon.aiRulesAddition;
if (!contentToCheck && addon.api) {
// Generate the content that would have been added
contentToCheck = generateAIRulesFromAPI(addon);
}
if (contentToCheck) {
const aiRulesPath = path.join(workspace.path, 'AI_RULES.md');
try {
const aiRules = await fs.readFile(aiRulesPath, 'utf-8');
// Check if the specific content is present
// Use a substring as a marker
const marker = contentToCheck.trim().substring(0, 50);
if (!aiRules.includes(marker)) {
return false;
}
} catch (error) {
if (error.code === 'ENOENT') {
return false; // AI_RULES.md doesn't exist, addon not applied
}
throw error;
}
}
return true;
}