-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-context.ts
More file actions
232 lines (203 loc) · 7.6 KB
/
generate-context.ts
File metadata and controls
232 lines (203 loc) · 7.6 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
#!/usr/bin/env tsx
/**
* core/scripts/generate-context.ts
*
* ==============================================================================
* 🤖 THE "SENSORY SYSTEM" GENERATOR
* ==============================================================================
*
* This script is the "Wake-Up Routine" for AI Agents working on the Astrical platform.
* It scans the current project state and generates two critical artifacts in `core/dev/00_context/`:
*
* 1. current_state.md: A human-readable summary for the AI to "read" and orient itself.
* 2. project_manifest.yaml: A structured dataset for the AI to reference specific paths/modules.
*
* ARCHITECTURAL GOAL:
* Prevent "Context Drift" where an Agent hallucinates files or modules that do not exist.
* By running this script (via `npm run context:refresh`), the Agent gets a real-time
* snapshot of the "World View" before attempting any tasks.
*
* USAGE:
* $ npm run context:refresh
*
* DEPENDENCIES:
* - node:fs/promises
* - node:path
* - glob (Ensure this is in devDependencies: `npm install -D glob`)
* - js-yaml (Ensure this is in devDependencies: `npm install -D js-yaml`)
*/
import fs from 'node:fs/promises';
import path from 'node:path';
import { glob } from 'glob';
import yaml from 'js-yaml';
// --- Configuration ---
const PATHS = {
config: 'content/config.yaml',
modulesDir: 'modules',
pagesDir: 'content/pages',
styleConfig: 'content/style.yaml',
outputDir: 'dev/00_context',
outputMd: 'dev/00_context/current_state.md',
outputYaml: 'dev/00_context/project_manifest.yaml',
};
// --- Types ---
interface ProjectManifest {
timestamp: string;
config: {
exists: boolean;
snippet: string;
};
modules: string[];
theme: {
active: string;
hasUserOverrides: boolean;
};
content: {
pages: Record<string, string[]>; // dir -> [files]
total_pages: number;
structure: string[]; // Flat list of relative paths
};
}
/**
* Main Execution Function
*/
async function main() {
console.log('🤖 [SENSORY SYSTEM] Initiating project scan...');
const startTime = performance.now();
try {
// 1. Prepare Data
const manifest = await buildManifest();
// 2. Write Artifacts
await ensureDirectory(PATHS.outputDir);
await writeMarkdown(manifest);
await writeYaml(manifest);
const duration = (performance.now() - startTime).toFixed(2);
console.log(`✅ [SENSORY SYSTEM] Context refreshed in ${duration}ms.`);
console.log(` 📄 Human Readable: ${PATHS.outputMd}`);
console.log(` 💾 Machine Data: ${PATHS.outputYaml}`);
} catch (error) {
console.error('❌ [SENSORY SYSTEM] Critical Error:', error);
process.exit(1);
}
}
/**
* Scans the filesystem to build the Project Manifest object.
*/
async function buildManifest(): Promise<ProjectManifest> {
const manifest: ProjectManifest = {
timestamp: new Date().toISOString(),
config: { exists: false, snippet: '' },
modules: [],
theme: { active: 'unknown', hasUserOverrides: false },
content: { pages: {}, total_pages: 0, structure: [] },
};
// --- 1. Active Configuration ---
try {
const configRaw = await fs.readFile(PATHS.config, 'utf-8');
manifest.config.exists = true;
// Heuristic: Capture the first 50 lines to give context without token overload
const lines = configRaw.split('\n');
manifest.config.snippet = lines.slice(0, 50).join('\n') + (lines.length > 50 ? '\n... (truncated)' : '');
// Try to parse theme from config if simple YAML
try {
const parsed = yaml.load(configRaw) as any;
manifest.theme.active = parsed?.ui?.theme || 'default';
} catch { /* ignore parse errors for snippet extraction */ }
} catch (e) {
console.warn(`⚠️ Warning: Could not read ${PATHS.config}`);
}
// --- 2. Installed Modules ---
try {
const moduleFiles = await glob(`${PATHS.modulesDir}/*/module.yaml`);
manifest.modules = moduleFiles.map(file => path.dirname(file).split(path.sep).pop() || 'unknown');
} catch (e) {
console.warn(`⚠️ Warning: Could not scan modules directory.`);
}
// --- 3. Content Structure ---
try {
const pageFiles = await glob(`${PATHS.pagesDir}/**/*.yaml`);
manifest.content.total_pages = pageFiles.length;
manifest.content.structure = pageFiles.map(p => path.relative(process.cwd(), p));
// Group by directory for the human-readable report
pageFiles.forEach(p => {
const relPath = path.dirname(p).replace(PATHS.pagesDir, '') || '/root';
const dir = relPath.startsWith('/') ? relPath : `/${relPath}`;
if (!manifest.content.pages[dir]) {
manifest.content.pages[dir] = [];
}
manifest.content.pages[dir].push(path.basename(p, '.yaml'));
});
} catch (e) {
console.warn(`⚠️ Warning: Could not scan content directory.`);
}
// --- 4. Theme State ---
try {
await fs.access(PATHS.styleConfig);
manifest.theme.hasUserOverrides = true;
} catch {
manifest.theme.hasUserOverrides = false;
}
return manifest;
}
/**
* Generates and writes the `current_state.md` file.
* This is optimized for an LLM to "read" quickly.
*/
async function writeMarkdown(manifest: ProjectManifest) {
const lines: string[] = [];
lines.push(`# 🤖 Project State Manifest`);
lines.push(`> **Generated**: ${manifest.timestamp}`);
lines.push(`> **Purpose**: Read this file to orient yourself. Do not edit manually.\n`);
// Section 1: Configuration
lines.push(`## 1. Active Configuration`);
if (manifest.config.exists) {
lines.push(`- **Source**: \`${PATHS.config}\``);
lines.push(`- **Active Theme**: \`${manifest.theme.active}\``);
lines.push('```yaml');
lines.push(manifest.config.snippet);
lines.push('```');
} else {
lines.push(`❌ **CRITICAL**: Configuration file missing at \`${PATHS.config}\``);
}
lines.push('');
// Section 2: Modules
lines.push(`## 2. Installed Modules`);
if (manifest.modules.length === 0) {
lines.push(`- *No external modules detected. Running in Core-only mode.*`);
} else {
manifest.modules.forEach(m => lines.push(`- **${m}**`));
}
lines.push('');
// Section 3: Content Structure
lines.push(`## 3. Content Structure`);
lines.push(`- **Total Pages**: ${manifest.content.total_pages}`);
lines.push(`- **User Overrides**: ${manifest.theme.hasUserOverrides ? '✅ Active (`content/style.yaml`)' : '❌ None'}`);
lines.push('');
lines.push(`### Page Hierarchy`);
const sortedDirs = Object.keys(manifest.content.pages).sort();
sortedDirs.forEach(dir => {
const files = manifest.content.pages[dir].sort().join(', ');
lines.push(`- **\`${dir}\`**: ${files}`);
});
await fs.writeFile(PATHS.outputMd, lines.join('\n'), 'utf-8');
}
/**
* Generates and writes the `project_manifest.yaml` file.
* This is optimized for scripts or agents to look up specific paths.
*/
async function writeYaml(manifest: ProjectManifest) {
const yamlContent = yaml.dump(manifest);
await fs.writeFile(PATHS.outputYaml, yamlContent, 'utf-8');
}
/**
* Helper to ensure the output directory exists.
*/
async function ensureDirectory(dirPath: string) {
try {
await fs.mkdir(dirPath, { recursive: true });
} catch (error) {
if ((error as any).code !== 'EEXIST') throw error;
}
}
// Run the script
main();