akbo-cli 0.0.0-stage → 1.9.4

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 (66) hide show
  1. package/README.md +706 -2
  2. package/dist/catalog_store.d.ts +78 -0
  3. package/dist/catalog_store.js +375 -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 +1596 -0
  8. package/dist/extractors/base.d.ts +35 -0
  9. package/dist/extractors/base.js +17 -0
  10. package/dist/extractors/custom_extractor.d.ts +55 -0
  11. package/dist/extractors/custom_extractor.js +198 -0
  12. package/dist/extractors/dotnet_extractor.d.ts +11 -0
  13. package/dist/extractors/dotnet_extractor.js +579 -0
  14. package/dist/extractors/golang_extractor.d.ts +11 -0
  15. package/dist/extractors/golang_extractor.js +73 -0
  16. package/dist/extractors/index.d.ts +14 -0
  17. package/dist/extractors/index.js +30 -0
  18. package/dist/extractors/jvm_extractor.d.ts +11 -0
  19. package/dist/extractors/jvm_extractor.js +319 -0
  20. package/dist/extractors/node_extractor.d.ts +11 -0
  21. package/dist/extractors/node_extractor.js +306 -0
  22. package/dist/extractors/proto_graphql_extractor.d.ts +11 -0
  23. package/dist/extractors/proto_graphql_extractor.js +125 -0
  24. package/dist/extractors/python_extractor.d.ts +11 -0
  25. package/dist/extractors/python_extractor.js +298 -0
  26. package/dist/extractors/rust_extractor.d.ts +11 -0
  27. package/dist/extractors/rust_extractor.js +66 -0
  28. package/dist/graph_builder.d.ts +87 -0
  29. package/dist/graph_builder.js +1498 -0
  30. package/dist/harvester.d.ts +38 -0
  31. package/dist/harvester.js +461 -0
  32. package/dist/hook_generator.d.ts +26 -0
  33. package/dist/hook_generator.js +203 -0
  34. package/dist/importers/skill_importer.d.ts +43 -0
  35. package/dist/importers/skill_importer.js +470 -0
  36. package/dist/index.d.ts +17 -0
  37. package/dist/index.js +17 -0
  38. package/dist/indexer.d.ts +19 -0
  39. package/dist/indexer.js +108 -0
  40. package/dist/init_service.d.ts +37 -0
  41. package/dist/init_service.js +246 -0
  42. package/dist/mcp_server.d.ts +10 -0
  43. package/dist/mcp_server.js +632 -0
  44. package/dist/pool_resolver.d.ts +40 -0
  45. package/dist/pool_resolver.js +84 -0
  46. package/dist/provider.d.ts +135 -0
  47. package/dist/provider.js +880 -0
  48. package/dist/query_service.d.ts +33 -0
  49. package/dist/query_service.js +161 -0
  50. package/dist/schema_generator.d.ts +236 -0
  51. package/dist/schema_generator.js +264 -0
  52. package/dist/standards_loader.d.ts +7 -0
  53. package/dist/standards_loader.js +33 -0
  54. package/dist/types.d.ts +265 -0
  55. package/dist/types.js +105 -0
  56. package/dist/unit_synthesizer.d.ts +22 -0
  57. package/dist/unit_synthesizer.js +196 -0
  58. package/dist/validator.d.ts +13 -0
  59. package/dist/validator.js +152 -0
  60. package/dist/version.d.ts +6 -0
  61. package/dist/version.js +16 -0
  62. package/dist/watcher.d.ts +38 -0
  63. package/dist/watcher.js +132 -0
  64. package/package.json +56 -6
  65. package/schemas/index-schema.json +98 -0
  66. package/schemas/knowledge-unit.json +154 -0
@@ -0,0 +1,470 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { globby } from 'globby';
4
+ import YAML from 'yaml';
5
+ import { KnowledgePoolResolver } from '../pool_resolver.js';
6
+ export class SkillImporter {
7
+ repoRoot;
8
+ poolConfig;
9
+ constructor(repoRoot = process.cwd(), poolDir) {
10
+ this.repoRoot = path.resolve(repoRoot);
11
+ const hasExplicitPool = Boolean(poolDir || process.env.AKBO_POOL_DIR);
12
+ this.poolConfig = hasExplicitPool
13
+ ? KnowledgePoolResolver.resolve(this.repoRoot, { explicitPoolDir: poolDir })
14
+ : {
15
+ targetDir: this.repoRoot,
16
+ poolDir: this.repoRoot,
17
+ isExternalPool: false,
18
+ knowledgeDir: path.join(this.repoRoot, 'knowledge'),
19
+ standardsFile: path.join(this.repoRoot, '.akb', 'standards.yaml'),
20
+ customExtractorsFile: path.join(this.repoRoot, '.akb', 'custom-extractors.yaml'),
21
+ cacheDir: path.join(this.repoRoot, '.akb', 'caches'),
22
+ cacheFile: path.join(this.repoRoot, '.akb', 'caches', `${path.basename(this.repoRoot)}-cache.json`)
23
+ };
24
+ }
25
+ /**
26
+ * Scans for SKILL.md files and converts them into validated, human_curated Knowledge Units.
27
+ */
28
+ async importSkills(options) {
29
+ if (options.poolDir) {
30
+ this.poolConfig = KnowledgePoolResolver.resolve(this.repoRoot, { explicitPoolDir: options.poolDir });
31
+ }
32
+ const globs = options.sourceGlobs && options.sourceGlobs.length > 0
33
+ ? options.sourceGlobs
34
+ : [
35
+ '.agents/skills/**/SKILL.md',
36
+ 'skills/**/SKILL.md',
37
+ '.github/skills/**/SKILL.md'
38
+ ];
39
+ const matchedFiles = await globby(globs, {
40
+ cwd: this.repoRoot,
41
+ dot: true,
42
+ onlyFiles: true
43
+ });
44
+ const result = {
45
+ imported: [],
46
+ skipped: [],
47
+ errors: []
48
+ };
49
+ if (matchedFiles.length === 0) {
50
+ return result;
51
+ }
52
+ const domain = options.domain || 'development';
53
+ const targetKnowledgeDir = path.join(this.poolConfig.knowledgeDir, domain);
54
+ fs.mkdirSync(targetKnowledgeDir, { recursive: true });
55
+ for (const relSkillPath of matchedFiles) {
56
+ const fullSkillPath = path.join(this.repoRoot, relSkillPath);
57
+ try {
58
+ const rawContent = fs.readFileSync(fullSkillPath, 'utf-8');
59
+ const skillDir = path.dirname(fullSkillPath);
60
+ const refFiles = this.discoverReferenceFiles(skillDir);
61
+ const parsedUnit = this.parseSkillMarkdown(relSkillPath, rawContent, domain, refFiles);
62
+ if (!parsedUnit) {
63
+ result.skipped.push(relSkillPath);
64
+ continue;
65
+ }
66
+ const unitFileName = `${parsedUnit.id}.yaml`;
67
+ const unitRelativePath = `knowledge/${domain}/${unitFileName}`.replace(/\\/g, '/');
68
+ const unitFullPath = path.join(this.poolConfig.poolDir, unitRelativePath);
69
+ if (fs.existsSync(unitFullPath) && !options.force) {
70
+ result.skipped.push(`${relSkillPath} (already exists as ${unitRelativePath})`);
71
+ continue;
72
+ }
73
+ fs.writeFileSync(unitFullPath, YAML.stringify(parsedUnit), 'utf-8');
74
+ // Register in knowledge/index.yaml if present
75
+ this.registerInIndexYaml(parsedUnit, unitRelativePath, domain);
76
+ result.imported.push({
77
+ skillPath: relSkillPath,
78
+ unitId: parsedUnit.id,
79
+ unitPath: unitRelativePath,
80
+ title: parsedUnit.title
81
+ });
82
+ }
83
+ catch (err) {
84
+ result.errors.push(`${relSkillPath}: ${err.message}`);
85
+ }
86
+ }
87
+ return result;
88
+ }
89
+ /**
90
+ * Parses SKILL.md YAML frontmatter and markdown body into KnowledgeUnitContent.
91
+ */
92
+ parseSkillMarkdown(relPath, content, defaultDomain = 'development', referenceFiles = []) {
93
+ let frontmatter = {};
94
+ let markdownBody = content;
95
+ // 1. Extract YAML Frontmatter
96
+ const frontmatterMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);
97
+ if (frontmatterMatch) {
98
+ try {
99
+ frontmatter = YAML.parse(frontmatterMatch[1]) || {};
100
+ }
101
+ catch { }
102
+ markdownBody = frontmatterMatch[2];
103
+ }
104
+ const rawName = frontmatter.name || path.basename(path.dirname(relPath));
105
+ const title = frontmatter.title || this.extractFirstHeading(markdownBody) || rawName;
106
+ const description = frontmatter.description || '';
107
+ // Generate deterministic clean ID
108
+ const cleanSlug = rawName
109
+ .replace(/[^a-zA-Z0-9_-]/g, '')
110
+ .replace(/[-_]+/g, '_')
111
+ .toUpperCase();
112
+ const prefix = defaultDomain === 'architecture' ? 'ARCH' : (defaultDomain === 'product' ? 'PROD' : 'DEV');
113
+ const id = `${prefix}-SKILL-${cleanSlug.slice(0, 24)}`;
114
+ // 2. Extract Sections, Bullets & Workflow Gates
115
+ const doItems = [];
116
+ const dontItems = [];
117
+ const explicitGates = [];
118
+ const fallbackNumbered = [];
119
+ const lines = markdownBody.split('\n');
120
+ let currentSection = 'overview';
121
+ let currentSectionLevel = 0;
122
+ const overviewLines = [];
123
+ const reasonLines = [];
124
+ for (const rawLine of lines) {
125
+ const line = rawLine.trim();
126
+ const headingMatch = line.match(/^(#{1,6})\s+(.*)$/);
127
+ if (headingMatch) {
128
+ const level = headingMatch[1].length;
129
+ const headingText = headingMatch[2].trim();
130
+ if (/^(?:do|target\s+patterns?|guidelines?|best\s+practices?|recommendations?|rules?)/i.test(headingText)) {
131
+ currentSection = 'do';
132
+ currentSectionLevel = level;
133
+ continue;
134
+ }
135
+ else if (/^(?:dont|don't|anti-patterns?|avoid|prohibited|never)/i.test(headingText)) {
136
+ currentSection = 'dont';
137
+ currentSectionLevel = level;
138
+ continue;
139
+ }
140
+ else if (/^(?:reason|rationale|why)/i.test(headingText)) {
141
+ currentSection = 'reason';
142
+ currentSectionLevel = level;
143
+ continue;
144
+ }
145
+ else if (/^(?:workflow\s+gates?|implementation\s+gates?|completion\s+gates?|verification\s+steps?|gates?|procedure|flow|steps|checklist)/i.test(headingText)) {
146
+ currentSection = 'gates';
147
+ currentSectionLevel = level;
148
+ continue;
149
+ }
150
+ else if (level <= currentSectionLevel || currentSectionLevel === 0) {
151
+ currentSection = 'none';
152
+ currentSectionLevel = level;
153
+ continue;
154
+ }
155
+ else {
156
+ // Sub-heading nested inside the active section (e.g. ### Sub-step inside ## Completion Gates)
157
+ continue;
158
+ }
159
+ }
160
+ // Check numbered list items (procedural steps / gates)
161
+ const numMatch = line.match(/^\d+\.\s+(.*)$/);
162
+ if (numMatch) {
163
+ const text = numMatch[1].trim();
164
+ if (currentSection === 'gates') {
165
+ explicitGates.push(text);
166
+ }
167
+ else {
168
+ fallbackNumbered.push(text);
169
+ }
170
+ if (currentSection === 'do') {
171
+ doItems.push(text);
172
+ }
173
+ continue;
174
+ }
175
+ // Check checklist items: - [ ] or - [x]
176
+ const checkMatch = line.match(/^[-*]\s+\[[ xX]\]\s+(.*)$/);
177
+ if (checkMatch) {
178
+ const text = checkMatch[1].trim();
179
+ if (currentSection === 'gates') {
180
+ explicitGates.push(text);
181
+ }
182
+ else {
183
+ fallbackNumbered.push(text);
184
+ }
185
+ if (currentSection === 'do') {
186
+ doItems.push(text);
187
+ }
188
+ continue;
189
+ }
190
+ // Check bullet items
191
+ const bulletMatch = line.match(/^[-*]\s+(.*)$/);
192
+ if (bulletMatch) {
193
+ const text = bulletMatch[1].trim();
194
+ if (/^(?:dont|don't|do\s+not|never|avoid|prohibit)\b/i.test(text)) {
195
+ dontItems.push(text);
196
+ }
197
+ else if (/^(?:do|must|always|enforce|target)\b/i.test(text)) {
198
+ doItems.push(text);
199
+ }
200
+ else if (currentSection === 'dont') {
201
+ dontItems.push(text);
202
+ }
203
+ else if (currentSection === 'do') {
204
+ doItems.push(text);
205
+ }
206
+ else if (currentSection === 'gates') {
207
+ explicitGates.push(text);
208
+ }
209
+ }
210
+ else if (line.length > 0) {
211
+ if (currentSection === 'reason') {
212
+ reasonLines.push(line);
213
+ }
214
+ else if (currentSection === 'overview' && overviewLines.length < 5) {
215
+ overviewLines.push(line);
216
+ }
217
+ }
218
+ }
219
+ // Workflow gates resolution: prioritize explicit gate section items over fallback numbered items
220
+ const resolvedGates = explicitGates.length > 0 ? explicitGates : fallbackNumbered;
221
+ // Fallbacks
222
+ const ruleText = description || overviewLines.join(' ') || `Adhere strictly to the ${title} specification.`;
223
+ const reasonText = reasonLines.join(' ') || `Enforces human-curated domain invariants and consistency for ${title}.`;
224
+ if (resolvedGates.length > 0) {
225
+ for (const gate of resolvedGates.slice(0, 5)) {
226
+ if (!doItems.includes(gate)) {
227
+ doItems.push(gate);
228
+ }
229
+ }
230
+ }
231
+ if (doItems.length === 0) {
232
+ doItems.push(`Follow the ${title} architectural guidelines and target patterns.`);
233
+ }
234
+ if (dontItems.length === 0) {
235
+ dontItems.push(`Do not deviate from the curated ${title} specification.`);
236
+ }
237
+ // Smart applies_to resolution
238
+ const rawAppliesTo = frontmatter.applies_to || frontmatter.paths || frontmatter.file_patterns || frontmatter.globs;
239
+ let appliesTo;
240
+ if (rawAppliesTo) {
241
+ appliesTo = Array.isArray(rawAppliesTo) ? rawAppliesTo : [rawAppliesTo];
242
+ }
243
+ else {
244
+ const isGlobalStandard = /coding[-_ ]standard|general[-_ ]guideline|global[-_ ]standard|repository[-_ ]rule/i.test(rawName) ||
245
+ /coding\s+standards?/i.test(title);
246
+ const targetedGlobs = !isGlobalStandard ? this.inferTargetedPathGlobs(description, content) : [];
247
+ if (targetedGlobs.length > 0) {
248
+ appliesTo = targetedGlobs;
249
+ }
250
+ else if (/(?:^|\W)(?:C#|\.NET|CSharp)(?:\W|$)|(?:\.cs\b)/i.test(content)) {
251
+ appliesTo = ['**/*.cs'];
252
+ }
253
+ else if (/(?:^|\W)(?:TypeScript|React)(?:\W|$)|(?:\.tsx?\b)/i.test(content)) {
254
+ appliesTo = ['**/*.ts', '**/*.tsx'];
255
+ }
256
+ else if (/(?:^|\W)(?:Java|Spring)(?:\W|$)|(?:\.java\b)/i.test(content)) {
257
+ appliesTo = ['**/*.java'];
258
+ }
259
+ else if (/(?:^|\W)(?:Python|Django|FastAPI)(?:\W|$)|(?:\.py\b)/i.test(content)) {
260
+ appliesTo = ['**/*.py'];
261
+ }
262
+ else if (/(?:^|\W)(?:Go|Golang)(?:\W|$)|(?:\.go\b)/i.test(content)) {
263
+ appliesTo = ['**/*.go'];
264
+ }
265
+ else {
266
+ appliesTo = ['**'];
267
+ }
268
+ }
269
+ return {
270
+ id,
271
+ type: defaultDomain === 'architecture' ? 'architecture_standard' : 'development_standard',
272
+ title,
273
+ domain: defaultDomain,
274
+ status: frontmatter.status || 'approved',
275
+ version: frontmatter.version || '1.0.0',
276
+ authority: {
277
+ level: 'human_curated',
278
+ confidence: 'verified'
279
+ },
280
+ owner: {
281
+ team: frontmatter.owner?.team || 'domain_experts'
282
+ },
283
+ applies_to: appliesTo,
284
+ rule: ruleText,
285
+ do: doItems.slice(0, 10),
286
+ dont: dontItems.slice(0, 10),
287
+ reason: reasonText,
288
+ related_items: [],
289
+ skill_file: relPath.replace(/\\/g, '/'),
290
+ reference_files: referenceFiles.length > 0 ? referenceFiles : undefined,
291
+ workflow_gates: resolvedGates.length > 0 ? resolvedGates.slice(0, 10) : undefined
292
+ };
293
+ }
294
+ /**
295
+ * Infers targeted file/directory globs (e.g. WebClient/**, Shared/ExportService/**)
296
+ * from skill description and content before falling back to repo-wide wildcards.
297
+ */
298
+ inferTargetedPathGlobs(description, content) {
299
+ const searchCorpus = `${description}\n${content}`;
300
+ const globs = new Set();
301
+ const proseSlashRegex = /^(?:true\/false|false\/true|yes\/no|no\/yes|and\/or|read\/write|write\/read|client\/server|server\/client|in\/out|input\/output|master\/slave|min\/max|up\/down|on\/off|get\/set|req\/res|v\d+\/v\d+)$/i;
302
+ // 1. Explicit glob patterns like Platform/** or path/to/*
303
+ const globPatternRegex = /(?:^|\s|`)([\w\-. ]+\/(?:\*\*|\*))(?:`|\s|$)/g;
304
+ let globMatch;
305
+ while ((globMatch = globPatternRegex.exec(searchCorpus)) !== null) {
306
+ const g = globMatch[1].trim().replace(/\\/g, '/');
307
+ if (g && !g.includes('://')) {
308
+ globs.add(g.endsWith('/**') ? g : (g.endsWith('/*') ? `${g}*` : `${g}/**`));
309
+ }
310
+ }
311
+ // 2. Backticked directory paths (e.g. `Core/DbTools`, `Shared/ExportService`, `WebClient`)
312
+ const backtickRegex = /`([^`\r\n]+)`/g;
313
+ let btMatch;
314
+ const commonIgnoredTokens = new Set([
315
+ 'string', 'int', 'bool', 'boolean', 'void', 'task', 'async', 'null',
316
+ 'true', 'false', 'undefined', 'object', 'any', 'c#', '.net', 'csharp',
317
+ 'typescript', 'javascript', 'python', 'java', 'go', 'golang', 'sql'
318
+ ]);
319
+ while ((btMatch = backtickRegex.exec(searchCorpus)) !== null) {
320
+ const rawToken = btMatch[1].trim();
321
+ if (!rawToken || rawToken.length < 2)
322
+ continue;
323
+ if (/[();=<>{}@$"]/.test(rawToken) || rawToken.includes('://'))
324
+ continue;
325
+ if (commonIgnoredTokens.has(rawToken.toLowerCase()))
326
+ continue;
327
+ const norm = rawToken.replace(/\\/g, '/');
328
+ // If token contains a path slash, it is an explicit directory prefix (e.g. Core/DbTools)
329
+ if (norm.includes('/') && !norm.startsWith('http')) {
330
+ if (proseSlashRegex.test(norm))
331
+ continue;
332
+ const clean = norm.replace(/\/+(\*\*|\*)?$/, '').trim();
333
+ if (clean.length > 1) {
334
+ globs.add(`${clean}/**`);
335
+ }
336
+ continue;
337
+ }
338
+ // If token is a single folder name (e.g. WebClient)
339
+ // Check if it exists as a directory on disk or is contextualized as a directory/subsystem/project
340
+ const potentialDir = path.join(this.repoRoot, norm);
341
+ let isDir = false;
342
+ try {
343
+ if (fs.existsSync(potentialDir) && fs.statSync(potentialDir).isDirectory()) {
344
+ isDir = true;
345
+ }
346
+ }
347
+ catch { }
348
+ const escaped = norm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
349
+ const hasDirContext = new RegExp(`(?:in|under|for|within|subsystem|directory|project|folder)\\s+[\`"]${escaped}[\`"]`, 'i').test(searchCorpus) ||
350
+ new RegExp(`[\`"]${escaped}[\`"]\\s+(?:directory|folder|project|subsystem|service|client|module)`, 'i').test(searchCorpus);
351
+ if (isDir || hasDirContext) {
352
+ globs.add(`${norm}/**`);
353
+ }
354
+ }
355
+ // 3. Un-backticked directory paths in description or text (e.g. under Subsystem Name/DbTools and Shared/CommonService)
356
+ const unquotedPathRegex = /\b([a-zA-Z0-9_.\-]+(?:\s+[a-zA-Z0-9_.\-]+)?\/[a-zA-Z0-9_.\-]+(?:\s+[a-zA-Z0-9_.\-]+)?(?:\/[a-zA-Z0-9_.\-]+)*)\b/g;
357
+ let uqMatch;
358
+ while ((uqMatch = unquotedPathRegex.exec(searchCorpus)) !== null) {
359
+ let rawPath = uqMatch[1].trim();
360
+ rawPath = rawPath.replace(/[.,;:!?)\]}>]+$/, '').trim();
361
+ rawPath = rawPath.replace(/^(?:and|or|the|with|for|in|to|from|under)\s+/gi, '').trim();
362
+ rawPath = rawPath.replace(/\s+(?:and|or|the|with|for|in|to|from|under)\b/gi, '').trim();
363
+ const norm = rawPath.replace(/\\/g, '/');
364
+ if (proseSlashRegex.test(norm) || norm.includes('://'))
365
+ continue;
366
+ const escaped = norm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
367
+ const inDescription = description.includes(rawPath);
368
+ const hasDirContext = new RegExp(`(?:in|under|for|within|subsystem|directory|project|folder|path)\\s+${escaped}`, 'i').test(searchCorpus) ||
369
+ new RegExp(`${escaped}\\s+(?:directory|folder|project|subsystem|service|client|module)`, 'i').test(searchCorpus);
370
+ const potentialDir = path.join(this.repoRoot, norm);
371
+ let existsOnDisk = false;
372
+ try {
373
+ if (fs.existsSync(potentialDir) && fs.statSync(potentialDir).isDirectory()) {
374
+ existsOnDisk = true;
375
+ }
376
+ }
377
+ catch { }
378
+ if (inDescription || hasDirContext || existsOnDisk) {
379
+ const clean = norm.replace(/\/+(\*\*|\*)?$/, '').trim();
380
+ if (clean.length > 2) {
381
+ globs.add(`${clean}/**`);
382
+ }
383
+ }
384
+ }
385
+ return Array.from(globs);
386
+ }
387
+ /**
388
+ * Discovers supporting reference markdown files in sibling directories (e.g. references/*.md).
389
+ */
390
+ discoverReferenceFiles(skillDir) {
391
+ const referencesDir = path.join(skillDir, 'references');
392
+ if (!fs.existsSync(referencesDir))
393
+ return [];
394
+ try {
395
+ const files = [];
396
+ const walk = (d) => {
397
+ for (const entry of fs.readdirSync(d, { withFileTypes: true })) {
398
+ const full = path.join(d, entry.name);
399
+ if (entry.isDirectory()) {
400
+ walk(full);
401
+ }
402
+ else if (entry.isFile() && entry.name.endsWith('.md')) {
403
+ files.push(path.relative(this.repoRoot, full).replace(/\\/g, '/'));
404
+ }
405
+ }
406
+ };
407
+ walk(referencesDir);
408
+ return files.sort();
409
+ }
410
+ catch {
411
+ return [];
412
+ }
413
+ }
414
+ extractFirstHeading(markdown) {
415
+ const match = markdown.match(/^#+\s+(.+)$/m);
416
+ return match ? match[1].trim() : null;
417
+ }
418
+ registerInIndexYaml(unit, relPath, domain) {
419
+ const indexPath = path.join(this.poolConfig.knowledgeDir, 'index.yaml');
420
+ let indexObj;
421
+ if (fs.existsSync(indexPath)) {
422
+ try {
423
+ const raw = fs.readFileSync(indexPath, 'utf-8');
424
+ indexObj = YAML.parse(raw);
425
+ }
426
+ catch { }
427
+ }
428
+ if (!indexObj || typeof indexObj !== 'object') {
429
+ indexObj = {
430
+ system_name: path.basename(this.repoRoot),
431
+ repository_root: this.repoRoot.replace(/\\/g, '/'),
432
+ knowledge_units_count: 0,
433
+ last_updated: new Date().toISOString().split('T')[0],
434
+ knowledge_units: {}
435
+ };
436
+ }
437
+ try {
438
+ if (!indexObj.repository_root) {
439
+ indexObj.repository_root = this.repoRoot.replace(/\\/g, '/');
440
+ }
441
+ indexObj.knowledge_units = indexObj.knowledge_units || {};
442
+ indexObj.knowledge_units[domain] = indexObj.knowledge_units[domain] || [];
443
+ // Check if already registered
444
+ const list = indexObj.knowledge_units[domain];
445
+ const existingIdx = list.findIndex((u) => u.id === unit.id);
446
+ const entry = {
447
+ id: unit.id,
448
+ file: relPath.replace(/\\/g, '/'),
449
+ title: unit.title
450
+ };
451
+ if (existingIdx >= 0) {
452
+ list[existingIdx] = entry;
453
+ }
454
+ else {
455
+ list.push(entry);
456
+ }
457
+ // Recalculate count
458
+ let total = 0;
459
+ for (const d of Object.keys(indexObj.knowledge_units)) {
460
+ if (Array.isArray(indexObj.knowledge_units[d])) {
461
+ total += indexObj.knowledge_units[d].length;
462
+ }
463
+ }
464
+ indexObj.knowledge_units_count = total;
465
+ indexObj.last_updated = new Date().toISOString().split('T')[0];
466
+ fs.writeFileSync(indexPath, YAML.stringify(indexObj), 'utf-8');
467
+ }
468
+ catch { }
469
+ }
470
+ }
@@ -0,0 +1,17 @@
1
+ export * from './types.js';
2
+ export * from './provider.js';
3
+ export * from './cleaner.js';
4
+ export { Harvester } from './harvester.js';
5
+ export { IndexSynthesizer } from './indexer.js';
6
+ export { UnitSynthesizer } from './unit_synthesizer.js';
7
+ export { HookGenerator } from './hook_generator.js';
8
+ export { KnowledgeValidator } from './validator.js';
9
+ export { GraphBuilder } from './graph_builder.js';
10
+ export { createMcpServer, runMcpServer } from './mcp_server.js';
11
+ export { QueryService, type QueryServiceOptions, type QueryResult } from './query_service.js';
12
+ export { SchemaGenerator } from './schema_generator.js';
13
+ export { InitService, type InitOptions, type InitResult } from './init_service.js';
14
+ export { CodebaseWatcher, type WatchOptions } from './watcher.js';
15
+ export { KnowledgePoolResolver, type PoolConfig, type ResolveOptions } from './pool_resolver.js';
16
+ export { VERSION, getVersion } from './version.js';
17
+ export * from './extractors/index.js';
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ export * from './types.js';
2
+ export * from './provider.js';
3
+ export * from './cleaner.js';
4
+ export { Harvester } from './harvester.js';
5
+ export { IndexSynthesizer } from './indexer.js';
6
+ export { UnitSynthesizer } from './unit_synthesizer.js';
7
+ export { HookGenerator } from './hook_generator.js';
8
+ export { KnowledgeValidator } from './validator.js';
9
+ export { GraphBuilder } from './graph_builder.js';
10
+ export { createMcpServer, runMcpServer } from './mcp_server.js';
11
+ export { QueryService } from './query_service.js';
12
+ export { SchemaGenerator } from './schema_generator.js';
13
+ export { InitService } from './init_service.js';
14
+ export { CodebaseWatcher } from './watcher.js';
15
+ export { KnowledgePoolResolver } from './pool_resolver.js';
16
+ export { VERSION, getVersion } from './version.js';
17
+ export * from './extractors/index.js';
@@ -0,0 +1,19 @@
1
+ import type { RepositorySkeleton, ProposedIndex } from './types.js';
2
+ import { type LLMProvider } from './provider.js';
3
+ export declare class IndexSynthesizer {
4
+ private provider;
5
+ client?: any;
6
+ private modelName;
7
+ constructor(apiKeyOrProvider?: string | LLMProvider, modelName?: string, options?: {
8
+ forceCli?: boolean;
9
+ provider?: string;
10
+ baseUrl?: string;
11
+ apiKey?: string;
12
+ });
13
+ get providerName(): string;
14
+ synthesize(skeleton: RepositorySkeleton, options?: {
15
+ systemName?: string;
16
+ strictness?: string;
17
+ }): Promise<ProposedIndex>;
18
+ private buildPrompt;
19
+ }
@@ -0,0 +1,108 @@
1
+ import { createLLMProvider, GeminiApiProvider } from './provider.js';
2
+ export class IndexSynthesizer {
3
+ provider;
4
+ client;
5
+ modelName;
6
+ constructor(apiKeyOrProvider, modelName = process.env.GEMINI_MODEL || 'gemini-3.5-flash', options) {
7
+ this.modelName = modelName;
8
+ if (apiKeyOrProvider && typeof apiKeyOrProvider === 'object' && 'generateJson' in apiKeyOrProvider) {
9
+ this.provider = apiKeyOrProvider;
10
+ if ('client' in apiKeyOrProvider) {
11
+ this.client = apiKeyOrProvider.client;
12
+ }
13
+ }
14
+ else {
15
+ const explicitKey = typeof apiKeyOrProvider === 'string' ? apiKeyOrProvider : options?.apiKey;
16
+ const provider = createLLMProvider({
17
+ apiKey: explicitKey,
18
+ model: modelName,
19
+ forceCli: options?.forceCli,
20
+ provider: options?.provider,
21
+ baseUrl: options?.baseUrl
22
+ });
23
+ this.provider = provider;
24
+ if (provider instanceof GeminiApiProvider) {
25
+ this.client = provider.client;
26
+ }
27
+ }
28
+ }
29
+ get providerName() {
30
+ return this.provider.name;
31
+ }
32
+ async synthesize(skeleton, options) {
33
+ const prompt = this.buildPrompt(skeleton, options);
34
+ try {
35
+ const parsed = await this.provider.generateJson(prompt);
36
+ return parsed;
37
+ }
38
+ catch (err) {
39
+ throw new Error(`Failed to parse LLM response into ProposedIndex JSON: ${err.message}`);
40
+ }
41
+ }
42
+ buildPrompt(skeleton, options) {
43
+ return `
44
+ You are the Lead System Architect for the "AI-Native Knowledge Base" Standard.
45
+ Your goal is to inspect a compressed architectural skeleton of a repository and propose a structured "knowledge/index.yaml" design.
46
+
47
+ The AI-Native Knowledge Base groups architectural and development standards into atomic units stored as:
48
+ knowledge/<domain>/<ID>.yaml
49
+
50
+ Standard domains:
51
+ - architecture (e.g. ARCH-SYS-001, ARCH-DATA-001, ARCH-PROC-001, ARCH-API-001)
52
+ - development (e.g. DEV-RUST-001, DEV-REACT-001, DEV-SVELTE-001, DEV-TEST-001)
53
+ - product (e.g. PROD-MODEL-001, PROD-TOOL-001, PROD-RULE-001)
54
+ - decisions (e.g. ADR-001, ADR-002)
55
+ - production / security (if applicable)
56
+
57
+ Here is the compressed repository skeleton:
58
+ - Repo Path: ${skeleton.repoPath}
59
+ - Top-Level Folders: ${skeleton.topology.topLevelDirectories.join(', ')}
60
+ - Total Files: ${skeleton.topology.totalFiles}
61
+ - Entry Points: ${skeleton.topology.entryPoints.join(', ')}
62
+ - Manifests detected: ${JSON.stringify(skeleton.manifests, null, 2)}
63
+ - Schemas detected: ${JSON.stringify(skeleton.schemas, null, 2)}
64
+ - Sample Routes/Commands (Total ${skeleton.routesAndCommands.length}): ${JSON.stringify(skeleton.routesAndCommands.slice(0, 15), null, 2)}
65
+ - Scripts & Workflows: ${JSON.stringify(skeleton.scriptsAndWorkflows, null, 2)}
66
+
67
+ User preferences:
68
+ - System Name override: ${options?.systemName || 'Auto-detect'}
69
+ - Strictness level: ${options?.strictness || 'Strict Enterprise Invariants'}
70
+
71
+ TASK:
72
+ Propose between 4 to 8 high-impact Knowledge Units covering:
73
+ 1. Core System & Framework Architecture (ARCH-SYS-001)
74
+ 2. Database / Persistence / State Standard (ARCH-DATA-001)
75
+ 3. Frontend or Backend Core Development standard (e.g., DEV-SVELTE-001 or DEV-FASTAPI-001)
76
+ 4. Automated Verification & Testing Gates (DEV-TEST-001)
77
+ 5. Core Business / Product Domain Rules (e.g., PROD-CORE-001 or PROD-TOOL-001)
78
+
79
+ For each Knowledge Unit, specify:
80
+ - id: e.g. "ARCH-SYS-001"
81
+ - domain: "architecture" | "development" | "product" | "decisions" | "production" | "security"
82
+ - file: path like "knowledge/architecture/ARCH-SYS-001.yaml"
83
+ - title: clear architectural title
84
+ - purpose: 1-sentence purpose
85
+ - targetFilesOrPatterns: array of 1 to 4 key files or path patterns the synthesizer should inspect in Stage 3 to write this unit.
86
+
87
+ Output STRICT JSON matching this schema:
88
+ {
89
+ "system_name": string,
90
+ "description": string,
91
+ "domains": {
92
+ "architecture": [
93
+ {
94
+ "id": string,
95
+ "domain": string,
96
+ "file": string,
97
+ "title": string,
98
+ "purpose": string,
99
+ "targetFilesOrPatterns": [string]
100
+ }
101
+ ],
102
+ "development": [...],
103
+ "product": [...]
104
+ }
105
+ }
106
+ `;
107
+ }
108
+ }
@@ -0,0 +1,37 @@
1
+ export interface InitOptions {
2
+ dir?: string;
3
+ poolDir?: string;
4
+ model?: string;
5
+ provider?: string;
6
+ apiKey?: string;
7
+ baseUrl?: string;
8
+ forceCli?: boolean;
9
+ domain?: string;
10
+ clean?: boolean;
11
+ noHooks?: boolean;
12
+ forceHooks?: boolean;
13
+ local?: boolean;
14
+ onProgress?: (message: string) => void;
15
+ }
16
+ export interface InitResult {
17
+ success: boolean;
18
+ systemName: string;
19
+ unitsCount: number;
20
+ catalogPath: string;
21
+ generatedHooks: string[];
22
+ validation: {
23
+ valid: boolean;
24
+ errors: string[];
25
+ warnings: string[];
26
+ };
27
+ elapsedSeconds: number;
28
+ }
29
+ /**
30
+ * All-in-one orchestrator coordinating the complete 5-stage initialization pipeline:
31
+ * Stage 1 (Harvest) -> Stage 2 (Plan) -> Stage 3 (Generate) -> Stage 4 (Hooks & Schemas) -> Stage 5 (Validate).
32
+ */
33
+ export declare class InitService {
34
+ private repoRoot;
35
+ constructor(repoRoot?: string);
36
+ init(options?: InitOptions): Promise<InitResult>;
37
+ }