akbo-cli 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +786 -2
  2. package/dist/catalog_store.d.ts +131 -0
  3. package/dist/catalog_store.js +506 -0
  4. package/dist/cleaner.d.ts +11 -0
  5. package/dist/cleaner.js +92 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.js +1961 -0
  8. package/dist/dream_engine.d.ts +61 -0
  9. package/dist/dream_engine.js +330 -0
  10. package/dist/extractors/base.d.ts +35 -0
  11. package/dist/extractors/base.js +17 -0
  12. package/dist/extractors/custom_extractor.d.ts +55 -0
  13. package/dist/extractors/custom_extractor.js +198 -0
  14. package/dist/extractors/dotnet_extractor.d.ts +11 -0
  15. package/dist/extractors/dotnet_extractor.js +579 -0
  16. package/dist/extractors/golang_extractor.d.ts +11 -0
  17. package/dist/extractors/golang_extractor.js +73 -0
  18. package/dist/extractors/index.d.ts +14 -0
  19. package/dist/extractors/index.js +30 -0
  20. package/dist/extractors/jvm_extractor.d.ts +11 -0
  21. package/dist/extractors/jvm_extractor.js +319 -0
  22. package/dist/extractors/node_extractor.d.ts +11 -0
  23. package/dist/extractors/node_extractor.js +306 -0
  24. package/dist/extractors/proto_graphql_extractor.d.ts +11 -0
  25. package/dist/extractors/proto_graphql_extractor.js +125 -0
  26. package/dist/extractors/python_extractor.d.ts +11 -0
  27. package/dist/extractors/python_extractor.js +298 -0
  28. package/dist/extractors/rust_extractor.d.ts +11 -0
  29. package/dist/extractors/rust_extractor.js +66 -0
  30. package/dist/graph_builder.d.ts +87 -0
  31. package/dist/graph_builder.js +1516 -0
  32. package/dist/guard_service.d.ts +33 -0
  33. package/dist/guard_service.js +167 -0
  34. package/dist/harvester.d.ts +38 -0
  35. package/dist/harvester.js +461 -0
  36. package/dist/hook_generator.d.ts +34 -0
  37. package/dist/hook_generator.js +269 -0
  38. package/dist/importers/skill_importer.d.ts +43 -0
  39. package/dist/importers/skill_importer.js +470 -0
  40. package/dist/index.d.ts +20 -0
  41. package/dist/index.js +20 -0
  42. package/dist/indexer.d.ts +19 -0
  43. package/dist/indexer.js +108 -0
  44. package/dist/init_service.d.ts +37 -0
  45. package/dist/init_service.js +246 -0
  46. package/dist/mcp_server.d.ts +10 -0
  47. package/dist/mcp_server.js +846 -0
  48. package/dist/pool_resolver.d.ts +40 -0
  49. package/dist/pool_resolver.js +84 -0
  50. package/dist/provider.d.ts +135 -0
  51. package/dist/provider.js +880 -0
  52. package/dist/query_service.d.ts +33 -0
  53. package/dist/query_service.js +161 -0
  54. package/dist/schema_generator.d.ts +236 -0
  55. package/dist/schema_generator.js +264 -0
  56. package/dist/standards_loader.d.ts +7 -0
  57. package/dist/standards_loader.js +33 -0
  58. package/dist/types.d.ts +323 -0
  59. package/dist/types.js +123 -0
  60. package/dist/unit_synthesizer.d.ts +22 -0
  61. package/dist/unit_synthesizer.js +196 -0
  62. package/dist/validator.d.ts +13 -0
  63. package/dist/validator.js +152 -0
  64. package/dist/version.d.ts +6 -0
  65. package/dist/version.js +16 -0
  66. package/dist/watcher.d.ts +38 -0
  67. package/dist/watcher.js +132 -0
  68. package/package.json +56 -6
  69. package/schemas/index-schema.json +98 -0
  70. package/schemas/knowledge-unit.json +154 -0
@@ -0,0 +1,461 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { globby } from 'globby';
4
+ import ignore from 'ignore';
5
+ import { createDefaultExtractors, CustomRegexExtractor } from './extractors/index.js';
6
+ import { VERSION as CLI_VERSION } from './version.js';
7
+ import { KnowledgePoolResolver } from './pool_resolver.js';
8
+ // Common files/directories that should always be excluded from scanning
9
+ const DEFAULT_IGNORES = [
10
+ '.git',
11
+ '.svn',
12
+ 'node_modules',
13
+ 'dist',
14
+ 'build',
15
+ 'target',
16
+ '.gradle',
17
+ '.idea',
18
+ 'bin',
19
+ 'obj',
20
+ '[bB]in',
21
+ '[oO]bj',
22
+ '.vs',
23
+ 'TestResults',
24
+ '[tT]estResults',
25
+ 'PublishedWebs',
26
+ 'Debug',
27
+ 'Release',
28
+ '.svelte-kit',
29
+ '.next',
30
+ '.nuxt',
31
+ 'coverage',
32
+ '.cache',
33
+ '*.pyc',
34
+ '__pycache__',
35
+ '.venv',
36
+ 'venv',
37
+ '.akb',
38
+ '.akb*',
39
+ 'temp-*',
40
+ 'temp_*',
41
+ 'temp',
42
+ 'tmp'
43
+ ];
44
+ /**
45
+ * Checks whether a "packages" directory is a legacy .NET NuGet packages repository
46
+ * (contains repositories.config or versioned nupkg folders, and lacks package.json workspaces).
47
+ */
48
+ export function isNuGetPackagesDir(repoRoot) {
49
+ const pkgsDir = path.join(repoRoot, 'packages');
50
+ if (!fs.existsSync(pkgsDir))
51
+ return false;
52
+ try {
53
+ if (fs.existsSync(path.join(pkgsDir, 'repositories.config'))) {
54
+ return true;
55
+ }
56
+ const entries = fs.readdirSync(pkgsDir, { withFileTypes: true });
57
+ for (const entry of entries) {
58
+ if (entry.isDirectory() && fs.existsSync(path.join(pkgsDir, entry.name, 'package.json'))) {
59
+ return false; // JS/TS monorepo workspace
60
+ }
61
+ }
62
+ return entries.some(e => e.name.endsWith('.nupkg') || e.name.includes('.'));
63
+ }
64
+ catch {
65
+ return false;
66
+ }
67
+ }
68
+ /**
69
+ * Maps simple ignore patterns into glob-safe patterns (matching nested directories)
70
+ * for fast-glob / globby traversal performance on large monorepos.
71
+ */
72
+ export function getGlobSafeIgnores(ignores) {
73
+ const result = [];
74
+ for (const pat of ignores) {
75
+ result.push(pat);
76
+ if (!pat.startsWith('**/')) {
77
+ if (pat.endsWith('/**')) {
78
+ result.push(`**/${pat}`);
79
+ }
80
+ else {
81
+ result.push(`**/${pat}/**`);
82
+ result.push(`**/${pat}`);
83
+ }
84
+ }
85
+ }
86
+ return [...new Set(result)];
87
+ }
88
+ export class Harvester {
89
+ static MAX_FILE_SIZE_BYTES = 512 * 1024; // 512 KB
90
+ static PREVIEW_CHUNK_SIZE_BYTES = 64 * 1024; // 64 KB preview for oversized files
91
+ repoRoot;
92
+ poolConfig;
93
+ ig = ignore();
94
+ extractors;
95
+ constructor(repoRoot, extractors, poolDir) {
96
+ this.repoRoot = path.resolve(repoRoot);
97
+ this.poolConfig = KnowledgePoolResolver.resolve(this.repoRoot, { explicitPoolDir: poolDir });
98
+ this.extractors = extractors || createDefaultExtractors();
99
+ // Auto-discover repository-level custom extractors (.akb/custom-extractors.yaml or .json or pool)
100
+ const customYml = path.join(this.repoRoot, '.akb', 'custom-extractors.yaml');
101
+ const customYmlAlt = path.join(this.repoRoot, '.akb', 'custom-extractors.yml');
102
+ const customJson = path.join(this.repoRoot, '.akb', 'custom-extractors.json');
103
+ const poolCustomYml = this.poolConfig.customExtractorsFile;
104
+ const customPath = [customYml, customYmlAlt, customJson, poolCustomYml].find(p => p && fs.existsSync(p));
105
+ if (customPath) {
106
+ const customExtractor = CustomRegexExtractor.fromFile(customPath);
107
+ if (customExtractor) {
108
+ this.extractors.push(customExtractor);
109
+ }
110
+ }
111
+ this.initIgnore();
112
+ }
113
+ /**
114
+ * Safely reads a file with size guards to prevent V8 out-of-memory errors
115
+ * and catastrophic regex backtracking on massive or generated files.
116
+ */
117
+ readFileSafe(fullPath) {
118
+ try {
119
+ const stats = fs.statSync(fullPath);
120
+ let buffer;
121
+ if (stats.size > Harvester.MAX_FILE_SIZE_BYTES) {
122
+ // Read initial preview chunk for oversized files
123
+ const fd = fs.openSync(fullPath, 'r');
124
+ const buf = Buffer.alloc(Harvester.PREVIEW_CHUNK_SIZE_BYTES);
125
+ const bytesRead = fs.readSync(fd, buf, 0, buf.length, 0);
126
+ fs.closeSync(fd);
127
+ buffer = buf.subarray(0, bytesRead);
128
+ }
129
+ else {
130
+ buffer = fs.readFileSync(fullPath);
131
+ }
132
+ // First attempt UTF-8 with fatal: true so invalid byte sequences throw TypeError
133
+ try {
134
+ const utf8Decoder = new TextDecoder('utf-8', { fatal: true });
135
+ return utf8Decoder.decode(buffer);
136
+ }
137
+ catch (err) {
138
+ if (err instanceof TypeError) {
139
+ // Fall back to Windows-1252 (CP1252) for legacy Windows C#/source files
140
+ try {
141
+ const cp1252Decoder = new TextDecoder('windows-1252');
142
+ return cp1252Decoder.decode(buffer);
143
+ }
144
+ catch {
145
+ return buffer.toString('binary');
146
+ }
147
+ }
148
+ return buffer.toString('utf-8');
149
+ }
150
+ }
151
+ catch {
152
+ return null;
153
+ }
154
+ }
155
+ loadGitignoreFile(filePath, baseDir) {
156
+ if (!fs.existsSync(filePath))
157
+ return;
158
+ try {
159
+ const content = this.readFileSafe(filePath);
160
+ if (!content)
161
+ return;
162
+ if (baseDir === this.repoRoot) {
163
+ this.ig.add(content);
164
+ return;
165
+ }
166
+ // Ancestor directory: rebase anchored patterns relative to this.repoRoot
167
+ const relToAncestor = path.relative(baseDir, this.repoRoot).replace(/\\/g, '/');
168
+ const lines = content.split(/\r?\n/);
169
+ const rebasedLines = [];
170
+ for (const line of lines) {
171
+ const trimmed = line.trim();
172
+ if (!trimmed || trimmed.startsWith('#'))
173
+ continue;
174
+ const isNegated = trimmed.startsWith('!');
175
+ const rawRule = isNegated ? trimmed.slice(1) : trimmed;
176
+ if (rawRule.startsWith('/')) {
177
+ const stripped = rawRule.slice(1);
178
+ if (stripped === relToAncestor || stripped.startsWith(relToAncestor + '/')) {
179
+ const rebased = '/' + stripped.slice(relToAncestor.length).replace(/^\//, '');
180
+ rebasedLines.push(isNegated ? `!${rebased}` : rebased);
181
+ }
182
+ }
183
+ else {
184
+ rebasedLines.push(trimmed);
185
+ }
186
+ }
187
+ if (rebasedLines.length > 0) {
188
+ this.ig.add(rebasedLines);
189
+ }
190
+ }
191
+ catch {
192
+ // Continue on read error
193
+ }
194
+ }
195
+ initIgnore() {
196
+ this.ig.add(DEFAULT_IGNORES);
197
+ // 1. Walk upward to git root and load ancestor .gitignore files
198
+ const ancestors = [];
199
+ let curr = path.dirname(this.repoRoot);
200
+ while (curr && curr !== path.dirname(curr)) {
201
+ if (fs.existsSync(path.join(curr, '.gitignore'))) {
202
+ ancestors.push(curr);
203
+ }
204
+ if (fs.existsSync(path.join(curr, '.git'))) {
205
+ break;
206
+ }
207
+ curr = path.dirname(curr);
208
+ }
209
+ for (const anc of ancestors.reverse()) {
210
+ this.loadGitignoreFile(path.join(anc, '.gitignore'), anc);
211
+ }
212
+ // 2. Load targetDir .gitignore
213
+ this.loadGitignoreFile(path.join(this.repoRoot, '.gitignore'), this.repoRoot);
214
+ // 3. Load optional .akb/ignore from repoRoot or poolDir
215
+ const ignoreFiles = [
216
+ path.join(this.repoRoot, '.akb', 'ignore'),
217
+ path.join(this.poolConfig.poolDir, '.akb', 'ignore')
218
+ ];
219
+ for (const ignPath of ignoreFiles) {
220
+ if (fs.existsSync(ignPath)) {
221
+ try {
222
+ const content = this.readFileSafe(ignPath);
223
+ if (content) {
224
+ this.ig.add(content);
225
+ }
226
+ }
227
+ catch { }
228
+ }
229
+ }
230
+ }
231
+ async harvest(options) {
232
+ const globIgnores = getGlobSafeIgnores(DEFAULT_IGNORES);
233
+ if (isNuGetPackagesDir(this.repoRoot)) {
234
+ globIgnores.push('**/packages/**', 'packages/**');
235
+ }
236
+ const allFiles = await globby(['**/*'], {
237
+ cwd: this.repoRoot,
238
+ dot: true,
239
+ onlyFiles: true,
240
+ ignore: globIgnores,
241
+ suppressErrors: true
242
+ });
243
+ const useCache = options?.useCache ?? false;
244
+ const cacheFile = path.resolve(options?.cachePath || this.poolConfig.cacheFile);
245
+ const filteredFiles = allFiles.filter(file => {
246
+ const norm = file.replace(/\\/g, '/');
247
+ if (this.ig.ignores(norm))
248
+ return false;
249
+ if (path.resolve(this.repoRoot, file) === cacheFile)
250
+ return false;
251
+ return true;
252
+ });
253
+ let maxMtime = 0;
254
+ if (useCache) {
255
+ for (const f of filteredFiles) {
256
+ try {
257
+ const mtime = fs.statSync(path.join(this.repoRoot, f)).mtimeMs;
258
+ if (mtime > maxMtime)
259
+ maxMtime = mtime;
260
+ }
261
+ catch { }
262
+ }
263
+ }
264
+ if (useCache && fs.existsSync(cacheFile)) {
265
+ try {
266
+ const cachedRaw = JSON.parse(fs.readFileSync(cacheFile, 'utf-8'));
267
+ if (cachedRaw && cachedRaw.cacheKey && cachedRaw.skeleton) {
268
+ // Version-stamp cacheKey to guarantee invalidation on akbo-cli upgrades
269
+ if (cachedRaw.cacheKey.cliVersion === CLI_VERSION &&
270
+ cachedRaw.cacheKey.totalFiles === filteredFiles.length &&
271
+ cachedRaw.cacheKey.maxMtime === maxMtime &&
272
+ cachedRaw.cacheKey.repoPath === this.repoRoot) {
273
+ return cachedRaw.skeleton;
274
+ }
275
+ }
276
+ }
277
+ catch {
278
+ // Fall back to fresh harvest if cache reading fails
279
+ }
280
+ }
281
+ const topology = this.analyzeTopology(filteredFiles);
282
+ const manifests = this.extractManifests(filteredFiles);
283
+ const schemas = this.extractSchemas(filteredFiles);
284
+ const routesAndCommands = this.extractRoutesAndCommands(filteredFiles);
285
+ const scriptsAndWorkflows = this.extractScriptsAndWorkflows(manifests, filteredFiles);
286
+ const skeleton = {
287
+ timestamp: new Date().toISOString(),
288
+ repoPath: this.repoRoot,
289
+ topology,
290
+ manifests,
291
+ schemas,
292
+ routesAndCommands,
293
+ scriptsAndWorkflows
294
+ };
295
+ if (useCache) {
296
+ try {
297
+ // maxMtime already computed once during cache verification; reuse it directly
298
+ fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
299
+ fs.writeFileSync(cacheFile, JSON.stringify({
300
+ cacheKey: {
301
+ cliVersion: CLI_VERSION,
302
+ totalFiles: filteredFiles.length,
303
+ maxMtime,
304
+ repoPath: this.repoRoot
305
+ },
306
+ skeleton
307
+ }), 'utf-8');
308
+ }
309
+ catch {
310
+ // Skip cache write errors
311
+ }
312
+ }
313
+ return skeleton;
314
+ }
315
+ analyzeTopology(files) {
316
+ const topDirs = new Set();
317
+ const keyDirs = {};
318
+ const entryPoints = [];
319
+ const commonEntryRegex = /^(src\/)?(index|main|app|server|lib|cli|program|startup)\.(ts|js|rs|py|go|cs)$/i;
320
+ for (const file of files) {
321
+ const normalized = file.replace(/\\/g, '/');
322
+ const parts = normalized.split('/');
323
+ if (parts.length > 1) {
324
+ const top = parts[0];
325
+ topDirs.add(top);
326
+ if (!keyDirs[top])
327
+ keyDirs[top] = [];
328
+ if (keyDirs[top].length < 15) {
329
+ keyDirs[top].push(parts.slice(1).join('/'));
330
+ }
331
+ }
332
+ if (commonEntryRegex.test(normalized) ||
333
+ normalized.endsWith('/Program.cs') ||
334
+ normalized === 'Program.cs' ||
335
+ normalized.endsWith('/Global.asax.cs') ||
336
+ normalized === 'Global.asax.cs' ||
337
+ normalized.endsWith('/Global.asax') ||
338
+ normalized === 'Global.asax' ||
339
+ normalized.endsWith('Application.java') ||
340
+ normalized.endsWith('Application.kt') ||
341
+ normalized.endsWith('/Main.java') ||
342
+ normalized === 'Main.java' ||
343
+ normalized.includes('src-tauri/src/main.rs') ||
344
+ normalized.includes('src-tauri/src/lib.rs')) {
345
+ entryPoints.push(normalized);
346
+ }
347
+ }
348
+ return {
349
+ totalFiles: files.length,
350
+ topLevelDirectories: Array.from(topDirs).sort(),
351
+ keyDirectories: keyDirs,
352
+ entryPoints: [...new Set(entryPoints)]
353
+ };
354
+ }
355
+ extractManifests(files) {
356
+ const manifests = [];
357
+ for (const f of files) {
358
+ const fullPath = path.join(this.repoRoot, f);
359
+ const normalized = f.replace(/\\/g, '/');
360
+ const matchedExtractor = this.extractors.find(e => e.canExtractManifest?.(normalized));
361
+ if (matchedExtractor && matchedExtractor.extractManifest) {
362
+ const content = this.readFileSafe(fullPath);
363
+ if (content) {
364
+ try {
365
+ const extracted = matchedExtractor.extractManifest(normalized, content);
366
+ if (extracted) {
367
+ if (Array.isArray(extracted)) {
368
+ manifests.push(...extracted);
369
+ }
370
+ else {
371
+ manifests.push(extracted);
372
+ }
373
+ }
374
+ }
375
+ catch {
376
+ // Ignore extraction errors
377
+ }
378
+ }
379
+ }
380
+ }
381
+ return manifests;
382
+ }
383
+ extractSchemas(files) {
384
+ const schemas = [];
385
+ for (const f of files) {
386
+ const fullPath = path.join(this.repoRoot, f);
387
+ const normalized = f.replace(/\\/g, '/');
388
+ const matchedExtractors = this.extractors.filter(e => e.canExtractSchema?.(normalized));
389
+ if (matchedExtractors.length > 0) {
390
+ const content = this.readFileSafe(fullPath);
391
+ if (content) {
392
+ for (const extractor of matchedExtractors) {
393
+ if (extractor.extractSchemas) {
394
+ try {
395
+ const extracted = extractor.extractSchemas(normalized, content);
396
+ if (extracted && extracted.length > 0) {
397
+ schemas.push(...extracted);
398
+ }
399
+ }
400
+ catch {
401
+ // Ignore extraction errors
402
+ }
403
+ }
404
+ }
405
+ }
406
+ }
407
+ }
408
+ return schemas;
409
+ }
410
+ extractRoutesAndCommands(files) {
411
+ const items = [];
412
+ for (const f of files) {
413
+ const fullPath = path.join(this.repoRoot, f);
414
+ const normalized = f.replace(/\\/g, '/');
415
+ const matchedExtractors = this.extractors.filter(e => e.canExtractRoutes?.(normalized));
416
+ if (matchedExtractors.length > 0) {
417
+ const content = this.readFileSafe(fullPath);
418
+ if (content) {
419
+ for (const extractor of matchedExtractors) {
420
+ if (extractor.extractRoutesAndCommands) {
421
+ try {
422
+ const extracted = extractor.extractRoutesAndCommands(normalized, content);
423
+ if (extracted && extracted.length > 0) {
424
+ items.push(...extracted);
425
+ }
426
+ }
427
+ catch {
428
+ // Ignore extraction errors
429
+ }
430
+ }
431
+ }
432
+ }
433
+ }
434
+ }
435
+ // Deduplicate
436
+ const uniqueItems = [];
437
+ const seen = new Set();
438
+ for (const item of items) {
439
+ const key = `${item.file}::${item.signature}`;
440
+ if (!seen.has(key)) {
441
+ seen.add(key);
442
+ uniqueItems.push(item);
443
+ }
444
+ }
445
+ return uniqueItems;
446
+ }
447
+ extractScriptsAndWorkflows(manifests, files) {
448
+ let packageScripts;
449
+ const npmManifest = manifests.find(m => m.type === 'npm');
450
+ if (npmManifest && npmManifest.contentSummary.scripts) {
451
+ packageScripts = npmManifest.contentSummary.scripts;
452
+ }
453
+ const githubWorkflows = files
454
+ .filter(f => f.replace(/\\/g, '/').startsWith('.github/workflows/'))
455
+ .map(f => f.replace(/\\/g, '/'));
456
+ return {
457
+ packageScripts,
458
+ githubWorkflows
459
+ };
460
+ }
461
+ }
@@ -0,0 +1,34 @@
1
+ import type { ProposedIndex, KnowledgeUnitContent } from './types.js';
2
+ export interface WriteHooksOptions {
3
+ forceHooks?: boolean;
4
+ }
5
+ export declare class HookGenerator {
6
+ private repoRoot;
7
+ constructor(repoRoot: string);
8
+ /**
9
+ * Detects the line ending (\r\n or \n) of an existing file, defaulting to OS standard.
10
+ */
11
+ detectEol(filePath: string): string;
12
+ /**
13
+ * Normalizes content with the specified line ending.
14
+ */
15
+ formatWithEol(content: string, eol: string): string;
16
+ /**
17
+ * Safely updates or creates a markdown hook file (AGENTS.md, CLAUDE.md, GEMINI.md)
18
+ * using non-destructive fenced blocks (<!-- akbo:start -->...<!-- akbo:end -->).
19
+ */
20
+ writeMarkdownHook(filePath: string, content: string, options?: WriteHooksOptions): void;
21
+ generateAgentsMd(index: ProposedIndex, units: KnowledgeUnitContent[]): string;
22
+ generateClaudeMd(index: ProposedIndex, units: KnowledgeUnitContent[]): string;
23
+ /**
24
+ * Generates standard llms.txt file (compact index for LLMs and AI coding agents).
25
+ */
26
+ generateLlmsTxt(index: ProposedIndex, units: KnowledgeUnitContent[]): string;
27
+ /**
28
+ * Generates standard llms-full.txt file (comprehensive context including full invariant rules).
29
+ */
30
+ generateLlmsFullTxt(index: ProposedIndex, units: KnowledgeUnitContent[]): string;
31
+ generateCursorRules(): string;
32
+ generateMcpConfig(): string;
33
+ writeAllHooks(index: ProposedIndex, units: KnowledgeUnitContent[], options?: WriteHooksOptions): string[];
34
+ }