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
package/dist/cli.js ADDED
@@ -0,0 +1,1596 @@
1
+ #!/usr/bin/env node
2
+ import 'dotenv/config';
3
+ import { Command } from 'commander';
4
+ import chalk from 'chalk';
5
+ import path from 'node:path';
6
+ import fs from 'node:fs';
7
+ import { Harvester } from './harvester.js';
8
+ import { IndexSynthesizer } from './indexer.js';
9
+ import { UnitSynthesizer } from './unit_synthesizer.js';
10
+ import { HookGenerator } from './hook_generator.js';
11
+ import { KnowledgeValidator } from './validator.js';
12
+ import { cleanArtifacts } from './cleaner.js';
13
+ import { GraphBuilder } from './graph_builder.js';
14
+ import { runMcpServer } from './mcp_server.js';
15
+ import { QueryService } from './query_service.js';
16
+ import { SchemaGenerator, KNOWLEDGE_UNIT_JSON_SCHEMA, MASTER_INDEX_JSON_SCHEMA } from './schema_generator.js';
17
+ import { InitService } from './init_service.js';
18
+ import { CodebaseWatcher } from './watcher.js';
19
+ import { SkillImporter } from './importers/skill_importer.js';
20
+ import { KnowledgePoolResolver } from './pool_resolver.js';
21
+ import { CatalogStore, parseUnitsFromText } from './catalog_store.js';
22
+ import { VERSION } from './version.js';
23
+ import YAML from 'yaml';
24
+ function findRepoRoot(startDir) {
25
+ let current = path.resolve(startDir);
26
+ while (current !== path.dirname(current)) {
27
+ if (fs.existsSync(path.join(current, '.git')) || fs.existsSync(path.join(current, 'knowledge', 'index.yaml'))) {
28
+ return current;
29
+ }
30
+ current = path.dirname(current);
31
+ }
32
+ return path.resolve(startDir);
33
+ }
34
+ const program = new Command();
35
+ program
36
+ .name('akbo')
37
+ .description('AI Knowledge Base Oracle & Operator (AKBO) - Invariant Harvester, Synthesizer & GraphRAG Engine')
38
+ .version(VERSION, '-v, --version')
39
+ .option('-V', 'output the version number', () => {
40
+ console.log(VERSION);
41
+ process.exit(0);
42
+ })
43
+ .option('--pool <path>', 'External knowledge base and cache pool directory (or set AKBO_POOL_DIR)')
44
+ .addHelpText('after', `
45
+ Instant All-In-One Onboarding (1-Shot):
46
+ $ akbo init [dir] [--cli] [-d <domain>]
47
+ Executes the full automated 5-stage setup: harvest -> plan -> generate -> hooks -> schemas -> validate in one shot.
48
+
49
+ Enterprise Staged Pipeline:
50
+ Stage 1: Deterministic Harvester & Polyglot Cross-Boundary Wiring (0 Tokens)
51
+ $ akbo harvest [dir] [-o <path>] [-j, --json]
52
+ Extracts manifests (.sln, .csproj, pom.xml, build.gradle.kts, pyproject.toml, package.json, pnpm-workspace, Cargo.toml),
53
+ schemas (SQLAlchemy, Pydantic, Prisma, JPA, EF Core, Dapper, EDMX, Protobuf, WCF), controllers (FastAPI, Flask, Django, NestJS,
54
+ Next.js, Express, Spring Boot, Quarkus, ASP.NET Core/MVC 5/Web API 2), serverless triggers (Azure Functions), gRPC clients & services,
55
+ cross-boundary HTTP client calls (fetch, axios, HttpClient, requests/httpx, WebClient), and messaging (Celery, Dramatiq, BullMQ,
56
+ Spring Kafka, Spring RabbitMQ, MassTransit, NServiceBus, Wolverine, MediatR, FluentValidation) with canonical cross-language event linking.
57
+
58
+ Stage 2: Master Index Synthesizer (~3k Tokens)
59
+ $ akbo plan [dir] [-d <domain>] [--cli]
60
+ Analyzes harvested topology and synthesizes a proposed knowledge/index.yaml catalog.
61
+
62
+ Stage 3 & 4: Atomic Unit Synthesizer & Hook Generator
63
+ $ akbo generate [dir] [-d <domain>] [--clean] [--cli]
64
+ Synthesizes atomic YAML knowledge units with strict rule/do/dont directives, prioritizing
65
+ recently authored code via Git commit recency and preserving 'authority.level: human_curated' units.
66
+ Emits AI agent pre-execution hooks: AGENTS.md, GEMINI.md, CLAUDE.md, .cursorrules, and MCP configs.
67
+
68
+ Stage 5: Schema & Federation Validator
69
+ $ akbo validate [dir] [-j, --json]
70
+ Verifies that all knowledge units strictly conform to runtime Zod schemas and cross-references.
71
+
72
+ Stage 6: Model Context Protocol (MCP) Server
73
+ $ akbo mcp [dir] [--pool <path>]
74
+ $ akbo-mcp [dir]
75
+ $ npx -y akbo-cli mcp
76
+ Launches native MCP server over STDIO exposing akbo_search, akbo_impact, akbo_context,
77
+ akbo_query, akbo_harvest, akbo_validate, akbo_graph, akbo_list_invariants, akbo_upsert_unit,
78
+ akbo_upsert_units, akbo_get_unit, akbo_delete_unit, and akbo_import_skills tools alongside akbo://knowledge/index resource for
79
+ Google Antigravity, Gemini CLI, Claude Code, Cursor, Windsurf, Copilot, and Codex.
80
+
81
+ External Knowledge Pool (Zero-Touch Monorepo Isolation):
82
+ Separate scanned code (targetDir) from knowledge and cache storage (poolDir):
83
+ $ akbo harvest . --pool C:/AKBO/EnterprisePool
84
+ $ akbo context InvoicesController.cs --pool C:/AKBO/EnterprisePool
85
+ $ akbo mcp . --pool C:/AKBO/EnterprisePool
86
+ (Or set AKBO_POOL_DIR=C:/AKBO/EnterprisePool. All knowledge units, standards, and target-keyed caches live externally)
87
+
88
+ GraphRAG & Live Architecture Pre-Execution Engine:
89
+ 1. Build Codebase Knowledge Graph (CKG) with Cross-Boundary Wiring (0 Tokens):
90
+ $ akbo graph . --format mermaid -o docs/architecture.mmd
91
+ $ akbo graph . --format markdown -o docs/architecture-graph.md
92
+ $ akbo graph . -j, --json
93
+
94
+ 2. Live Architecture & Diagram Continuous Watcher:
95
+ $ akbo watch .
96
+ $ akbo watch . -o docs/architecture.mmd
97
+ $ akbo graph . --format mermaid -o docs/architecture.mmd --watch
98
+ (Continuously watches directory changes with sub-second debounced mtime caching and auto-renders diagrams)
99
+
100
+ 3. Extract 0-Token Topological Neighborhood for AI Agents (Multi-Hop):
101
+ $ akbo context InvoicesController.cs
102
+ $ akbo context "POST /api/invoices" -h 2 -j, --json
103
+ $ akbo context "CreateInvoice" -h 2
104
+ $ akbo context FacturaController
105
+ (Extracts callers, callees, schemas, active invariants with DO/DONT rules, and proactive deprecation warnings)
106
+
107
+ 4. Instant Pre-Execution Invariant Lookup for AI Coding Agents (0 Tokens):
108
+ $ akbo invariants .
109
+ $ akbo invariants . -f src/orders.controller.ts -j, --json
110
+
111
+ 5. Grounded GraphRAG Q&A with Cross-Lingual & Cross-Service Entity Resolution:
112
+ $ akbo query "How are invoices created and what data models are used?" -j
113
+ $ akbo ask "Explain the customer billing architecture across services" --cli
114
+ $ akbo query "Which microservices consume invoice-created events?"
115
+ (Automatically resolves English queries against Spanish, Chinese, German, or local codebases)
116
+
117
+ Developer Tooling & Curated Skill Ingestion:
118
+ $ akbo schema . # Emits schemas/knowledge-unit.json & schemas/index-schema.json and configures .vscode/settings.json
119
+ $ akbo init-hooks . # Bootstraps AGENTS.md, GEMINI.md, CLAUDE.md, .cursorrules, .cursor/mcp.json, .vscode/mcp.json
120
+ $ akbo import-skills . # Ingests .agents/skills/**/SKILL.md as First-Class Skill Pointers (skill_file, reference_files, workflow_gates)
121
+ (Configure .akb/standards.yaml to enforce modern target patterns and prohibit deprecated anti-patterns)
122
+
123
+ Enterprise Bounded Contexts (Central Hub):
124
+ Initialize Platform Core:
125
+ $ akbo harvest . -o .akb/core-skeleton.json
126
+ $ akbo plan . --domain core
127
+ $ akbo generate . --domain core --clean
128
+
129
+ Add Bounded Context Domains (e.g., Billing, Orders):
130
+ $ akbo harvest src/Billing -o .akb/billing-skeleton.json
131
+ $ akbo plan src/Billing --domain billing
132
+ $ akbo generate src/Billing --domain billing --clean
133
+
134
+ Maintenance:
135
+ $ akbo clean . # Removes intermediate .akb/ artifacts
136
+ $ akbo clean . --all # Removes .akb/ and compiled dist/ build files
137
+
138
+ Execution Providers (Multi-LLM via API Key or Local):
139
+ Gemini (Default): Pass '--provider gemini' or set GEMINI_API_KEY (supports gemini-3.5-flash, gemini-2.5-pro)
140
+ OpenAI: Pass '--provider openai' or set OPENAI_API_KEY (supports gpt-4o, gpt-4o-mini, o1, o3-mini)
141
+ Anthropic: Pass '--provider anthropic' or set ANTHROPIC_API_KEY (supports claude-3-7-sonnet, claude-3-5-haiku)
142
+ DeepSeek: Pass '--provider deepseek' or set DEEPSEEK_API_KEY (supports deepseek-chat, deepseek-reasoner)
143
+ Groq: Pass '--provider groq' or set GROQ_API_KEY (supports llama-3.3-70b-versatile, mixtral)
144
+ Ollama / Local: Pass '--provider ollama' [--base-url http://localhost:11434/v1] (100% offline, 0 cost)
145
+ OpenAI-Compatible: Pass '--provider openai-compatible' --base-url <url> --api-key <key>
146
+ System Gemini CLI: Pass '--cli' or '--provider cli' (uses local 'gemini' CLI on PATH, 0 API key required)
147
+ Antigravity CLI: Pass '--agy' or '--provider agy' (uses local 'agy' CLI on PATH, 0 API key required)
148
+
149
+ Detailed Command Help:
150
+ Run 'akbo <command> --help' (e.g. 'akbo init --help', 'akbo watch --help', 'akbo schema --help', 'akbo mcp --help', 'akbo graph --help') for full options and examples.
151
+ `);
152
+ program
153
+ .command('init')
154
+ .argument('[dir]', 'Directory of the codebase to initialize', '.')
155
+ .option('-m, --model <model>', 'LLM model name (e.g. gemini-3.5-flash, gpt-4o, claude-3-7-sonnet, deepseek-chat)')
156
+ .option('-p, --provider <provider>', 'LLM provider ("gemini", "openai", "anthropic", "deepseek", "groq", "ollama", "agy", "cli")', process.env.AKB_PROVIDER)
157
+ .option('--api-key <key>', 'Explicit API key override')
158
+ .option('--base-url <url>', 'Custom endpoint / base URL for OpenAI-compatible or local Ollama endpoints')
159
+ .option('-d, --domain <domain>', 'Scope to a specific Bounded Context domain (e.g. "billing", "core")')
160
+ .option('--cli', 'Use system Gemini CLI instead of direct API call')
161
+ .option('--agy', 'Use system Antigravity CLI (agy) instead of direct API call')
162
+ .option('--no-clean', 'Do not clean intermediate .akb/ artifacts after initialization')
163
+ .option('--no-hooks', 'Skip bootstrapping multi-agent hooks and IDE configuration')
164
+ .option('--force-hooks', 'Force overwrite existing AGENTS.md, CLAUDE.md, and hook files')
165
+ .option('-l, --local', 'Operate strictly within target directory without walking up to parent git repository root')
166
+ .option('--pool <path>', 'External knowledge base and cache pool directory')
167
+ .option('-j, --json', 'Output raw JSON result directly to stdout for machine consumption')
168
+ .description('Onboarding: Full automated 5-stage setup: harvest -> plan -> generate -> hooks -> schemas -> validate in one shot')
169
+ .addHelpText('after', `
170
+ Full Lifecycle Onboarding:
171
+ • Harvests topology and manifests deterministically (Stage 1, 0 tokens).
172
+ • Synthesizes master catalog index and targeted knowledge units (Stage 2 & 3).
173
+ • Emits multi-agent pre-execution hooks (AGENTS.md, GEMINI.md, CLAUDE.md, .cursorrules).
174
+ • Emits JSON Schemas (schemas/knowledge-unit.json) and configures .vscode/settings.json autocomplete.
175
+ • Validates the entire knowledge base hierarchy against runtime schemas (Stage 5).
176
+
177
+ Examples:
178
+ $ akbo init .
179
+ $ akbo init . --cli
180
+ $ akbo init . --agy
181
+ $ akbo init src/Billing --domain billing
182
+ $ akbo init . --json
183
+ `)
184
+ .action(async (dir, options) => {
185
+ const targetDir = path.resolve(dir);
186
+ const forceCli = Boolean(options.cli || options.provider === 'cli');
187
+ const selectedProvider = options.agy || options.provider === 'agy' || options.provider === 'agy-cli' ? 'agy' : options.provider;
188
+ const initService = new InitService(targetDir);
189
+ if (!options.json) {
190
+ console.log(chalk.blue.bold('\nšŸš€ AKB Full Automated Initialization (Stages 1-5)'));
191
+ console.log(chalk.gray(`Target directory: ${targetDir}`));
192
+ if (options.domain)
193
+ console.log(chalk.cyan(`Bounded Context: [${options.domain}]`));
194
+ console.log(chalk.gray(`Model: ${options.model}\n`));
195
+ }
196
+ try {
197
+ const result = await initService.init({
198
+ dir: targetDir,
199
+ poolDir: options.pool || program.opts().pool,
200
+ model: options.model,
201
+ provider: selectedProvider,
202
+ apiKey: options.apiKey,
203
+ baseUrl: options.baseUrl,
204
+ forceCli,
205
+ domain: options.domain,
206
+ clean: options.clean !== false,
207
+ noHooks: options.hooks === false,
208
+ forceHooks: Boolean(options.forceHooks),
209
+ local: Boolean(options.local),
210
+ onProgress: !options.json ? (msg) => console.log(chalk.gray(` ${msg}`)) : undefined
211
+ });
212
+ if (options.json) {
213
+ console.log(JSON.stringify(result, null, 2));
214
+ return;
215
+ }
216
+ console.log(chalk.green.bold(`\nāœ” Initialization complete in ${result.elapsedSeconds}s!`));
217
+ console.log(chalk.white(` • System: ${chalk.bold(result.systemName)}`));
218
+ console.log(chalk.white(` • Knowledge Units Created: ${chalk.bold(result.unitsCount)}`));
219
+ console.log(chalk.white(` • Catalog: ${chalk.cyan(result.catalogPath)}`));
220
+ console.log(chalk.white(` • Agent Hooks Generated: ${chalk.bold(result.generatedHooks.length)}`));
221
+ if (result.validation.valid) {
222
+ console.log(chalk.green(` āœ” Schema Validation Passed: 0 errors`));
223
+ }
224
+ else {
225
+ console.log(chalk.red(` āœ– Validation Warnings/Errors: ${result.validation.errors.join(', ')}`));
226
+ }
227
+ console.log('');
228
+ }
229
+ catch (err) {
230
+ if (options.json) {
231
+ console.log(JSON.stringify({ error: err.message }, null, 2));
232
+ return;
233
+ }
234
+ console.log(chalk.red(`\nāœ– Initialization failed: ${err.message}\n`));
235
+ process.exitCode = 1;
236
+ }
237
+ });
238
+ program
239
+ .command('harvest')
240
+ .argument('[dir]', 'Directory of the codebase to harvest', '.')
241
+ .option('-o, --out <path>', 'Output JSON file path', '.akb/skeleton.json')
242
+ .option('--pool <path>', 'External knowledge base and cache pool directory')
243
+ .option('-j, --json', 'Output raw JSON result directly to stdout for machine consumption')
244
+ .option('--no-cache', 'Disable incremental mtime caching and force fresh harvest')
245
+ .description('Stage 1: Deterministically harvest manifests, schemas, routes, RPCs, and messaging handlers (0 LLM tokens)')
246
+ .addHelpText('after', `
247
+ Harvested Artifacts & Multi-Ecosystem Support:
248
+ • Projects & Workspaces: *.sln, *.csproj, packages.config, web.config, pom.xml, build.gradle.kts, pyproject.toml, requirements.txt, Pipfile, package.json, pnpm-workspace.yaml, turbo.json, Cargo.toml, go.mod
249
+ • Web Endpoints: FastAPI (@app.get, @router.post), Flask (Blueprints, @app.route), Django (urls.py, ViewSets), NestJS (@Controller), Next.js App Router (route.ts) & Pages Router (pages/api), Express/Fastify (router.get, app.post), Spring Boot (@RestController), Quarkus (@Path), ASP.NET Core, ASP.NET MVC 5, Web API 2, Minimal APIs
250
+ • Cross-Boundary HTTP Clients: fetch(), axios (get, post, put, delete, patch), C# HttpClient (GetAsync, PostAsync, etc.), Python requests/httpx/aiohttp, Java WebClient & RestTemplate
251
+ • Cross-Language gRPC: Python stubs, TypeScript/Node clients, C# clients, Java stubs (*Grpc.*ImplBase service implementations) and *.proto definitions
252
+ • Serverless Triggers: Azure Functions ([FunctionName]/[Function] with Http, ServiceBus, Queue, Blob, CosmosDB, Timer)
253
+ • Legacy Service Contracts: WCF Services ([ServiceContract], [OperationContract], [DataContract])
254
+ • Messaging & Background: Celery tasks (@app.task, @shared_task), Dramatiq actors (@dramatiq.actor), BullMQ workers & queues (new Worker, new Queue, @Processor, @Process), Spring Kafka (@KafkaListener), Spring RabbitMQ (@RabbitListener), MassTransit (IConsumer<T>), NServiceBus (IHandleMessages<T>), Wolverine, MediatR, FluentValidation (AbstractValidator<T>)
255
+ • Schemas & RPC: SQLAlchemy (__tablename__, DeclarativeBase), Pydantic (BaseModel), SQLModel, Prisma (schema.prisma), JPA / Hibernate (@Entity, @Table, JpaRepository), Drizzle, TypeORM, Protocol Buffers (*.proto), gRPC Base Services (*GrpcBase), EF Core (DbContext, IEntityTypeConfiguration, ToTable), Dapper SQL queries, EDMX (*.edmx)
256
+ • Multilingual AST: Full Unicode identifier extraction supporting Spanish (Ʊ, Ć”, Ć©), German (Ƥ, ƶ, ü, ß), French (Ƨ, ĆØ), Chinese (Han script), etc.
257
+
258
+ Examples:
259
+ $ akbo harvest .
260
+ $ akbo harvest . --json
261
+ $ akbo harvest src/Billing -o .akb/billing-skeleton.json
262
+ $ akbo harvest path/to/legacy-net48-app
263
+ `)
264
+ .action(async (dir, options) => {
265
+ const targetDir = path.resolve(dir);
266
+ const poolDir = options.pool || program.opts().pool;
267
+ const startTime = Date.now();
268
+ const harvester = new Harvester(targetDir, undefined, poolDir);
269
+ const skeleton = await harvester.harvest({ useCache: !options.noCache });
270
+ const elapsed = ((Date.now() - startTime) / 1000).toFixed(2);
271
+ const outPath = path.isAbsolute(options.out)
272
+ ? options.out
273
+ : (harvester.poolConfig.isExternalPool && options.out === '.akb/skeleton.json'
274
+ ? path.resolve(harvester.poolConfig.poolDir, options.out)
275
+ : path.resolve(targetDir, options.out));
276
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
277
+ fs.writeFileSync(outPath, JSON.stringify(skeleton, null, 2), 'utf-8');
278
+ if (options.json) {
279
+ console.log(JSON.stringify(skeleton, null, 2));
280
+ return;
281
+ }
282
+ console.log(chalk.blue.bold('\nšŸ” AKB Harvester (Deterministic - 0 Tokens)'));
283
+ console.log(chalk.gray(`Scanning target: ${targetDir}\n`));
284
+ console.log(chalk.green(`āœ” Scan complete in ${elapsed}s`));
285
+ console.log(chalk.white(` • Files analyzed (after ignore): ${chalk.bold(skeleton.topology.totalFiles)}`));
286
+ console.log(chalk.white(` • Top-level domains: ${chalk.bold(skeleton.topology.topLevelDirectories.join(', '))}`));
287
+ console.log(chalk.white(` • Detected manifests: ${chalk.bold(skeleton.manifests.length)}`));
288
+ console.log(chalk.white(` • Discovered schemas: ${chalk.bold(skeleton.schemas.length)}`));
289
+ console.log(chalk.white(` • Routes & Commands extracted: ${chalk.bold(skeleton.routesAndCommands.length)}`));
290
+ console.log(chalk.cyan(`\nšŸ’¾ Saved compressed skeleton to: ${outPath}`));
291
+ console.log(chalk.gray(` Size: ${(fs.statSync(outPath).size / 1024).toFixed(1)} KB (Ready for Stage 2 indexing)\n`));
292
+ });
293
+ program
294
+ .command('plan')
295
+ .argument('[dir]', 'Directory of the codebase', '.')
296
+ .option('-m, --model <model>', 'LLM model name (e.g. gemini-3.5-flash, gpt-4o, claude-3-7-sonnet, deepseek-chat)')
297
+ .option('-p, --provider <provider>', 'LLM provider ("gemini", "openai", "anthropic", "deepseek", "groq", "ollama", "agy", "cli")', process.env.AKB_PROVIDER)
298
+ .option('--api-key <key>', 'Explicit API key override')
299
+ .option('--base-url <url>', 'Custom endpoint / base URL for OpenAI-compatible or local Ollama endpoints')
300
+ .option('-s, --skeleton <path>', 'Skeleton JSON path')
301
+ .option('-o, --out <path>', 'Output index.yaml path')
302
+ .option('-d, --domain <domain>', 'Scope to a specific Bounded Context domain (e.g. "billing", "core")')
303
+ .option('--cli', 'Use system Gemini CLI instead of direct API call')
304
+ .option('--agy', 'Use system Antigravity CLI (agy) instead of direct API call')
305
+ .option('-l, --local', 'Operate strictly within target directory without walking up to parent git repository root')
306
+ .option('--pool <path>', 'External knowledge base and cache pool directory')
307
+ .description('Stage 2: Synthesize proposed master index.yaml and target units from skeleton (~3k tokens)')
308
+ .addHelpText('after', `
309
+ Features & Cascading Execution:
310
+ • Self-Healing Cascade: If the skeleton JSON does not exist, akbo automatically runs the Harvester first.
311
+ • Bounded Context Scoping: Use '-d, --domain <name>' to partition large multi-project repositories into domain sub-catalogs.
312
+ • Provider Flexibility: Run with direct Gemini API, OpenAI, Anthropic, Ollama, Gemini CLI ('--cli'), or Antigravity CLI ('--agy').
313
+
314
+ Examples:
315
+ $ akbo plan .
316
+ $ akbo plan src/Billing --domain billing
317
+ $ akbo plan . --cli
318
+ $ akbo plan . --agy
319
+ $ akbo plan . -m gemini-3.5-pro -s .akb/custom-skeleton.json
320
+ `)
321
+ .action(async (dir, options) => {
322
+ const targetDir = path.resolve(dir);
323
+ const poolDir = options.pool || program.opts().pool;
324
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: poolDir });
325
+ const domainPrefix = options.domain ? `${options.domain}-` : '';
326
+ const defaultSkeleton = `.akb/${domainPrefix}skeleton.json`;
327
+ const defaultOut = `.akb/${domainPrefix}proposed-index.yaml`;
328
+ const skeletonInput = options.skeleton || defaultSkeleton;
329
+ const skeletonPath = path.isAbsolute(skeletonInput)
330
+ ? skeletonInput
331
+ : (poolConfig.isExternalPool && !options.skeleton
332
+ ? path.resolve(poolConfig.poolDir, skeletonInput)
333
+ : path.resolve(targetDir, skeletonInput));
334
+ let skeleton;
335
+ if (fs.existsSync(skeletonPath)) {
336
+ skeleton = JSON.parse(fs.readFileSync(skeletonPath, 'utf-8'));
337
+ }
338
+ else {
339
+ console.log(chalk.yellow(`Skeleton not found at ${skeletonPath}. Harvesting first...`));
340
+ const harvester = new Harvester(targetDir, undefined, poolConfig.poolDir);
341
+ skeleton = await harvester.harvest();
342
+ }
343
+ console.log(chalk.blue.bold('\n🧠 AKB Stage 2: Master Index Synthesizer'));
344
+ if (options.domain) {
345
+ console.log(chalk.cyan(` • Scoped Domain: [${options.domain}]`));
346
+ }
347
+ console.log(chalk.gray(`Using model: ${options.model}`));
348
+ const forceCli = Boolean(options.cli || options.provider === 'cli');
349
+ const selectedProvider = options.agy || options.provider === 'agy' || options.provider === 'agy-cli' ? 'agy' : options.provider;
350
+ const startTime = Date.now();
351
+ const synthesizer = new IndexSynthesizer(undefined, options.model, {
352
+ forceCli,
353
+ provider: selectedProvider,
354
+ apiKey: options.apiKey,
355
+ baseUrl: options.baseUrl
356
+ });
357
+ console.log(chalk.cyan(` • Provider: ${synthesizer.providerName}`));
358
+ const plan = await synthesizer.synthesize(skeleton);
359
+ const elapsed = ((Date.now() - startTime) / 1000).toFixed(2);
360
+ const outInput = options.out || defaultOut;
361
+ const outPath = path.isAbsolute(outInput)
362
+ ? outInput
363
+ : (poolConfig.isExternalPool && !options.out
364
+ ? path.resolve(poolConfig.poolDir, outInput)
365
+ : path.resolve(targetDir, outInput));
366
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
367
+ // In a scoped domain, adjust unit paths accordingly
368
+ if (options.domain) {
369
+ for (const [, list] of Object.entries(plan.domains)) {
370
+ for (const u of list) {
371
+ if (options.domain === 'core') {
372
+ u.file = `knowledge/core/${u.id}.yaml`;
373
+ }
374
+ else {
375
+ u.file = `knowledge/domains/${options.domain}/${u.id}.yaml`;
376
+ }
377
+ }
378
+ }
379
+ }
380
+ // Format proposed index.yaml structure
381
+ const indexYaml = {
382
+ system_name: plan.system_name,
383
+ description: plan.description,
384
+ repository_root: targetDir.replace(/\\/g, '/'),
385
+ last_updated: new Date().toISOString().split('T')[0],
386
+ knowledge_units: plan.domains
387
+ };
388
+ fs.writeFileSync(outPath, YAML.stringify(indexYaml), 'utf-8');
389
+ console.log(chalk.green(`āœ” Index synthesized in ${elapsed}s`));
390
+ console.log(chalk.white(` • System: ${chalk.bold(plan.system_name)}`));
391
+ console.log(chalk.white(` • Description: ${plan.description}`));
392
+ let totalUnits = 0;
393
+ for (const [domain, units] of Object.entries(plan.domains)) {
394
+ console.log(chalk.cyan(`\n Domain: [${domain}]`));
395
+ for (const u of units) {
396
+ totalUnits++;
397
+ console.log(chalk.white(` - ${chalk.yellow(u.id)}: ${u.title}`));
398
+ console.log(chalk.gray(` Target files: ${u.targetFilesOrPatterns.join(', ')}`));
399
+ }
400
+ }
401
+ console.log(chalk.green(`\nāœ” Total ${totalUnits} Knowledge Units planned.`));
402
+ console.log(chalk.cyan(`šŸ’¾ Saved proposed index to: ${outPath}\n`));
403
+ });
404
+ program
405
+ .command('generate')
406
+ .argument('[dir]', 'Directory of the codebase', '.')
407
+ .option('-m, --model <model>', 'LLM model name (e.g. gemini-3.5-flash, gpt-4o, claude-3-7-sonnet, deepseek-chat)')
408
+ .option('-p, --provider <provider>', 'LLM provider ("gemini", "openai", "anthropic", "deepseek", "groq", "ollama", "agy", "cli")', process.env.AKB_PROVIDER)
409
+ .option('--api-key <key>', 'Explicit API key override')
410
+ .option('--base-url <url>', 'Custom endpoint / base URL for OpenAI-compatible or local Ollama endpoints')
411
+ .option('--plan <path>', 'Proposed index path')
412
+ .option('-d, --domain <domain>', 'Scope to a specific Bounded Context domain (e.g. "billing", "core")')
413
+ .option('--cli', 'Use system Gemini CLI instead of direct API call')
414
+ .option('--agy', 'Use system Antigravity CLI (agy) instead of direct API call')
415
+ .option('--clean', 'Automatically delete .akb/ intermediate artifacts after successful generation')
416
+ .option('--no-hooks', 'Skip bootstrapping multi-agent hooks and IDE configuration')
417
+ .option('--force-hooks', 'Force overwrite existing AGENTS.md, CLAUDE.md, and hook files')
418
+ .option('-l, --local', 'Operate strictly within target directory without walking up to parent git repository root')
419
+ .option('--pool <path>', 'External knowledge base and cache pool directory')
420
+ .description('Stage 3 & 4: Synthesize atomic knowledge units and bootstrap AI agent hooks (AGENTS.md, GEMINI.md, CLAUDE.md, .cursorrules, and MCP configs)')
421
+ .addHelpText('after', `
422
+ Generation Pipeline & Agent Hook Emission:
423
+ • Targeted Micro-Prompts: Synthesizes individual atomic Knowledge Units with strict rule/do/dont/reason invariants.
424
+ • Domain Federation: Automatically writes knowledge/core/index.yaml or knowledge/domains/<domain>/index.yaml when scoped.
425
+ • AI Agent Pre-Execution Hooks: Generates synchronized AGENTS.md, GEMINI.md, CLAUDE.md, .cursorrules, .cursor/mcp.json, and .vscode/mcp.json instructions.
426
+ • Automated Verification: Executes KnowledgeValidator runtime schema verification on output units before exit.
427
+ • Storage Cleanup: Use '--clean' to automatically purge temporary .akb/ skeleton/plan files.
428
+
429
+ Examples:
430
+ $ akbo generate . --clean
431
+ $ akbo generate src/Billing --domain billing --clean
432
+ $ akbo generate . --cli --clean
433
+ $ akbo generate . --agy --clean
434
+ $ akbo generate . --plan .akb/custom-plan.yaml --clean
435
+ `)
436
+ .action(async (dir, options) => {
437
+ const targetDir = path.resolve(dir);
438
+ const poolDir = options.pool || program.opts().pool;
439
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: poolDir });
440
+ const codeRepoRoot = options.local ? targetDir : findRepoRoot(targetDir);
441
+ const repoRoot = poolConfig.isExternalPool
442
+ ? poolConfig.poolDir
443
+ : (options.local ? targetDir : codeRepoRoot);
444
+ const domainPrefix = options.domain ? `${options.domain}-` : '';
445
+ const defaultPlan = `.akb/${domainPrefix}proposed-index.yaml`;
446
+ const planInput = options.plan || defaultPlan;
447
+ const planPath = path.isAbsolute(planInput)
448
+ ? planInput
449
+ : (poolConfig.isExternalPool ? path.resolve(poolConfig.poolDir, planInput) : path.resolve(targetDir, planInput));
450
+ const forceCli = Boolean(options.cli || options.provider === 'cli');
451
+ const selectedProvider = options.agy || options.provider === 'agy' || options.provider === 'agy-cli' ? 'agy' : options.provider;
452
+ let planData;
453
+ if (fs.existsSync(planPath)) {
454
+ planData = YAML.parse(fs.readFileSync(planPath, 'utf-8'));
455
+ }
456
+ else {
457
+ console.log(chalk.yellow(`Plan not found at ${planPath}. Running harvester and plan first...`));
458
+ const harvester = new Harvester(targetDir, undefined, poolConfig.poolDir);
459
+ const skeleton = await harvester.harvest();
460
+ const synthesizer = new IndexSynthesizer(undefined, options.model, {
461
+ forceCli,
462
+ provider: selectedProvider,
463
+ apiKey: options.apiKey,
464
+ baseUrl: options.baseUrl
465
+ });
466
+ const rawPlan = await synthesizer.synthesize(skeleton);
467
+ planData = {
468
+ system_name: rawPlan.system_name,
469
+ description: rawPlan.description,
470
+ repository_root: targetDir.replace(/\\/g, '/'),
471
+ last_updated: new Date().toISOString().split('T')[0],
472
+ knowledge_units: rawPlan.domains
473
+ };
474
+ }
475
+ console.log(chalk.blue.bold('\nāš™ AKB Stage 3: Targeted Unit Synthesizer'));
476
+ if (options.domain) {
477
+ console.log(chalk.cyan(` • Bounded Context Domain: [${options.domain}]`));
478
+ }
479
+ console.log(chalk.gray(`Target Repository: ${targetDir}`));
480
+ console.log(chalk.gray(`Model: ${options.model}`));
481
+ const unitSynthesizer = new UnitSynthesizer(targetDir, undefined, options.model, 2000, {
482
+ forceCli,
483
+ provider: selectedProvider,
484
+ apiKey: options.apiKey,
485
+ baseUrl: options.baseUrl,
486
+ poolDir: poolConfig.poolDir
487
+ });
488
+ console.log(chalk.cyan(` • Provider: ${unitSynthesizer.providerName}\n`));
489
+ const generatedUnits = [];
490
+ const domains = planData.knowledge_units || {};
491
+ const flatUnits = [];
492
+ for (const [domainName, list] of Object.entries(domains)) {
493
+ for (const u of list) {
494
+ if (options.domain && !u.file.includes('knowledge/')) {
495
+ u.file = options.domain === 'core'
496
+ ? `knowledge/core/${u.id}.yaml`
497
+ : `knowledge/domains/${options.domain}/${u.id}.yaml`;
498
+ }
499
+ flatUnits.push(u);
500
+ }
501
+ }
502
+ console.log(chalk.white(`Synthesizing ${flatUnits.length} units with targeted micro-prompts...`));
503
+ for (const unit of flatUnits) {
504
+ // Write unit file (resolve against repoRoot if it starts with knowledge/)
505
+ const outFilePath = unit.file.startsWith('knowledge/')
506
+ ? path.resolve(repoRoot, unit.file)
507
+ : path.resolve(targetDir, unit.file);
508
+ // Protect human_curated or locked knowledge units from overwrite
509
+ if (fs.existsSync(outFilePath) && !options.force) {
510
+ try {
511
+ const existing = YAML.parse(fs.readFileSync(outFilePath, 'utf-8'));
512
+ if (existing?.authority?.level === 'human_curated' || existing?.status === 'locked') {
513
+ console.log(chalk.yellow(` • Skipping ${unit.id}: protected (${existing?.authority?.level || existing?.status})`));
514
+ generatedUnits.push(existing);
515
+ continue;
516
+ }
517
+ }
518
+ catch { }
519
+ }
520
+ process.stdout.write(chalk.gray(` • Synthesizing ${unit.id} (${unit.title})... `));
521
+ const startTime = Date.now();
522
+ try {
523
+ const unitContent = await unitSynthesizer.synthesizeUnit(unit);
524
+ const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
525
+ generatedUnits.push(unitContent);
526
+ fs.mkdirSync(path.dirname(outFilePath), { recursive: true });
527
+ fs.writeFileSync(outFilePath, YAML.stringify(unitContent), 'utf-8');
528
+ console.log(chalk.green(`āœ” (${elapsed}s)`));
529
+ }
530
+ catch (err) {
531
+ console.log(chalk.red(`āœ– Failed: ${err.message}`));
532
+ }
533
+ }
534
+ // Determine catalog location
535
+ if (options.domain) {
536
+ // Namespaced Central Hub mode
537
+ const isCore = options.domain === 'core';
538
+ const catalogRelPath = isCore
539
+ ? 'knowledge/core/index.yaml'
540
+ : `knowledge/domains/${options.domain}/index.yaml`;
541
+ const catalogFullPath = path.resolve(repoRoot, catalogRelPath);
542
+ fs.mkdirSync(path.dirname(catalogFullPath), { recursive: true });
543
+ const domainCatalogYaml = {
544
+ system_name: `${planData.system_name || options.domain}`,
545
+ description: planData.description || `Domain catalog for ${options.domain}`,
546
+ knowledge_units_count: generatedUnits.length,
547
+ last_updated: new Date().toISOString().split('T')[0],
548
+ knowledge_units: {}
549
+ };
550
+ for (const u of generatedUnits) {
551
+ if (!domainCatalogYaml.knowledge_units[u.domain]) {
552
+ domainCatalogYaml.knowledge_units[u.domain] = [];
553
+ }
554
+ domainCatalogYaml.knowledge_units[u.domain].push({
555
+ id: u.id,
556
+ file: options.domain === 'core'
557
+ ? `knowledge/core/${u.id}.yaml`
558
+ : `knowledge/domains/${options.domain}/${u.id}.yaml`,
559
+ title: u.title
560
+ });
561
+ }
562
+ fs.writeFileSync(catalogFullPath, YAML.stringify(domainCatalogYaml), 'utf-8');
563
+ console.log(chalk.cyan(`\nāœ” Wrote Domain Catalog: ${catalogFullPath}`));
564
+ // Register domain in root knowledge/index.yaml router
565
+ const rootIndexPath = path.resolve(repoRoot, 'knowledge', 'index.yaml');
566
+ let rootIndexData = { system_name: 'EnterprisePlatform', domains: [] };
567
+ if (fs.existsSync(rootIndexPath)) {
568
+ try {
569
+ rootIndexData = YAML.parse(fs.readFileSync(rootIndexPath, 'utf-8')) || rootIndexData;
570
+ }
571
+ catch { }
572
+ }
573
+ if (!Array.isArray(rootIndexData.domains)) {
574
+ rootIndexData.domains = [];
575
+ }
576
+ const relScope = path.relative(codeRepoRoot, targetDir).replace(/\\/g, '/');
577
+ const appliesTo = !relScope || relScope === '.' || isCore ? ['**/*'] : [`${relScope}/**`];
578
+ const domainEntry = {
579
+ id: options.domain,
580
+ name: planData.system_name || options.domain,
581
+ catalog: catalogRelPath,
582
+ applies_to: appliesTo
583
+ };
584
+ const existingIdx = rootIndexData.domains.findIndex((d) => d.id === options.domain);
585
+ if (existingIdx >= 0) {
586
+ rootIndexData.domains[existingIdx] = domainEntry;
587
+ }
588
+ else {
589
+ rootIndexData.domains.push(domainEntry);
590
+ }
591
+ if (!rootIndexData.repository_root) {
592
+ rootIndexData.repository_root = codeRepoRoot.replace(/\\/g, '/');
593
+ }
594
+ rootIndexData.last_updated = new Date().toISOString().split('T')[0];
595
+ fs.writeFileSync(rootIndexPath, YAML.stringify(rootIndexData), 'utf-8');
596
+ console.log(chalk.cyan(`āœ” Registered domain in Master Router: ${rootIndexPath}`));
597
+ }
598
+ else {
599
+ // Standard flat index mode
600
+ const finalIndexPath = path.resolve(poolConfig.knowledgeDir, 'index.yaml');
601
+ fs.mkdirSync(path.dirname(finalIndexPath), { recursive: true });
602
+ const finalIndexYaml = {
603
+ system_name: planData.system_name,
604
+ repository_root: codeRepoRoot.replace(/\\/g, '/'),
605
+ knowledge_units_count: generatedUnits.length,
606
+ last_updated: new Date().toISOString().split('T')[0],
607
+ knowledge_units: {}
608
+ };
609
+ for (const u of generatedUnits) {
610
+ if (!finalIndexYaml.knowledge_units[u.domain]) {
611
+ finalIndexYaml.knowledge_units[u.domain] = [];
612
+ }
613
+ finalIndexYaml.knowledge_units[u.domain].push({
614
+ id: u.id,
615
+ file: `knowledge/${u.domain}/${u.id}.yaml`,
616
+ title: u.title
617
+ });
618
+ }
619
+ fs.writeFileSync(finalIndexPath, YAML.stringify(finalIndexYaml), 'utf-8');
620
+ console.log(chalk.cyan(`\nāœ” Wrote Master Index: ${finalIndexPath}`));
621
+ }
622
+ // Stage 4: Generate Bootstrap Hooks
623
+ const shouldWriteHooks = options.hooks !== false && !(poolConfig.isExternalPool && !options.forceHooks);
624
+ if (shouldWriteHooks) {
625
+ console.log(chalk.blue.bold('\nšŸš€ AKB Stage 4: Bootstrap Hooks & Agent Instructions'));
626
+ const hookGen = new HookGenerator(repoRoot);
627
+ const proposedIndexForHooks = {
628
+ system_name: planData.system_name,
629
+ description: planData.description,
630
+ domains: domains
631
+ };
632
+ const writtenHooks = hookGen.writeAllHooks(proposedIndexForHooks, generatedUnits, { forceHooks: Boolean(options.forceHooks) });
633
+ for (const hookPath of writtenHooks) {
634
+ console.log(chalk.white(` āœ” Created/Updated ${hookPath}`));
635
+ }
636
+ }
637
+ else {
638
+ console.log(chalk.gray(`\nā© Skipping Stage 4 hook generation (${poolConfig.isExternalPool ? 'external pool active' : '--no-hooks enabled'})`));
639
+ }
640
+ // Run validator
641
+ console.log(chalk.blue.bold('\n🧪 Validating Generated Knowledge Base...'));
642
+ const validator = new KnowledgeValidator(targetDir, poolConfig.poolDir);
643
+ const valResult = await validator.validate();
644
+ if (valResult.valid) {
645
+ console.log(chalk.green(`āœ” Validation passed: ${valResult.unitCount} units verified with 0 errors!`));
646
+ }
647
+ else {
648
+ console.log(chalk.red(`āœ– Validation found ${valResult.errors.length} errors:`));
649
+ for (const err of valResult.errors)
650
+ console.log(chalk.red(` - ${err}`));
651
+ }
652
+ // Auto-cleanup intermediate artifacts if requested
653
+ if (options.clean) {
654
+ const cleanRes = cleanArtifacts(targetDir);
655
+ if (cleanRes.removed.length > 0) {
656
+ console.log(chalk.cyan(`\n🧹 Auto-cleaned intermediate artifacts: ${cleanRes.removed.join(', ')}`));
657
+ }
658
+ }
659
+ });
660
+ program
661
+ .command('clean')
662
+ .argument('[dir]', 'Directory of the codebase', '.')
663
+ .option('-a, --all', 'Also remove compiled build artifacts (dist/)')
664
+ .option('--pool <path>', 'External knowledge base and cache pool directory')
665
+ .description('Maintenance: Remove intermediate AKBO artifacts (.akb/) and free disk space')
666
+ .addHelpText('after', `
667
+ Cleanup Behavior:
668
+ • Default: Deletes intermediate .akb/ temporary skeletons, plans, and caches while preserving .akb/standards.yaml, .akb/custom-extractors.yaml, and .akb/ignore.
669
+ • Full Clean (-a, --all): Additionally deletes compiled TypeScript build files (dist/).
670
+
671
+ Examples:
672
+ $ akbo clean .
673
+ $ akbo clean . --pool C:/AKBO/Pool
674
+ $ akbo clean . --all
675
+ `)
676
+ .action(async (dir, options) => {
677
+ const targetDir = path.resolve(dir);
678
+ const poolDir = options.pool || program.opts().pool;
679
+ console.log(chalk.blue.bold('\n🧹 AKB Cleaner: ') + chalk.gray(targetDir));
680
+ const result = cleanArtifacts(targetDir, { includeDist: options.all });
681
+ if (poolDir && path.resolve(poolDir) !== targetDir) {
682
+ const poolResult = cleanArtifacts(path.resolve(poolDir), { includeDist: false });
683
+ result.removed.push(...poolResult.removed.map(r => `[pool] ${r}`));
684
+ result.totalBytesFreed += poolResult.totalBytesFreed;
685
+ }
686
+ if (result.removed.length === 0) {
687
+ console.log(chalk.gray(' Nothing to clean (no intermediate artifacts found).\n'));
688
+ }
689
+ else {
690
+ const kb = (result.totalBytesFreed / 1024).toFixed(1);
691
+ console.log(chalk.green(` āœ” Removed: ${result.removed.join(', ')}`));
692
+ console.log(chalk.white(` āœ” Freed: ${chalk.bold(kb)} KB\n`));
693
+ }
694
+ });
695
+ program
696
+ .command('validate')
697
+ .argument('[dir]', 'Directory of the codebase', '.')
698
+ .option('--pool <path>', 'External knowledge base and cache pool directory')
699
+ .option('-j, --json', 'Output raw JSON validation result directly to stdout for machine consumption')
700
+ .description('Stage 5: Validate knowledge/ directory against the AKB runtime schema and federation standards')
701
+ .addHelpText('after', `
702
+ Validation Gates:
703
+ • Master Index & Sub-Catalogs: Verifies knowledge/index.yaml and domain sub-catalogs.
704
+ • Schema Adherence: Enforces strict runtime Zod validation on all Knowledge Units (id, type, domain, status, version, authority, owner, applies_to, rule, do, dont, reason).
705
+ • Cross-Reference Integrity: Validates all 'related_items' links across Knowledge Units.
706
+ • Path Normalization: Checks for POSIX-compliant paths and ensures referenced files exist.
707
+
708
+ Examples:
709
+ $ akbo validate .
710
+ $ akbo validate . --pool C:/AKBO/EnterprisePool
711
+ $ akbo validate . --json
712
+ $ akbo validate path/to/enterprise/repo
713
+ `)
714
+ .action(async (dir, options) => {
715
+ const targetDir = path.resolve(dir);
716
+ const poolDir = options.pool || program.opts().pool;
717
+ const validator = new KnowledgeValidator(targetDir, poolDir);
718
+ const result = await validator.validate();
719
+ if (options.json) {
720
+ console.log(JSON.stringify(result, null, 2));
721
+ return;
722
+ }
723
+ console.log(chalk.blue.bold('\n🧪 Validating Knowledge Base: ') + chalk.gray(targetDir));
724
+ if (result.valid) {
725
+ console.log(chalk.green(`\nāœ” SUCCESS: Knowledge base is valid (${result.unitCount} units checked)`));
726
+ if (result.warnings.length > 0) {
727
+ console.log(chalk.yellow(`\nWarnings (${result.warnings.length}):`));
728
+ for (const w of result.warnings)
729
+ console.log(chalk.yellow(` • ${w}`));
730
+ }
731
+ }
732
+ else {
733
+ console.log(chalk.red(`\nāœ– FAILED: Found ${result.errors.length} errors:`));
734
+ for (const e of result.errors)
735
+ console.log(chalk.red(` • ${e}`));
736
+ }
737
+ });
738
+ program
739
+ .command('graph')
740
+ .argument('[dir]', 'Directory of the codebase', '.')
741
+ .option('-o, --out <path>', 'Output path', '.akb/graph.json')
742
+ .option('--format <format>', 'Export format: json, mermaid, markdown', 'json')
743
+ .option('--no-cluster', 'Disable domain subgraph clustering in Mermaid format')
744
+ .option('--max-nodes <n>', 'Maximum number of nodes to include in Mermaid diagram (default: 40, 0 for unlimited)', '40')
745
+ .option('--node-types <types>', 'Comma-separated node types to include in Mermaid export (e.g. project,endpoint,handler,schema)')
746
+ .option('--no-cache', 'Disable incremental mtime caching and force fresh harvest')
747
+ .option('-w, --watch', 'Continuously watch codebase for changes and automatically re-render graph')
748
+ .option('--pool <path>', 'External knowledge base and cache pool directory')
749
+ .option('-j, --json', 'Output raw JSON graph directly to stdout for machine consumption')
750
+ .description('GraphRAG: Deterministically build the Codebase Knowledge Graph (CKG) (0 LLM tokens)')
751
+ .addHelpText('after', `
752
+ Two-Pass Graph Engine Details:
753
+ • Pass 1: Deterministic registration of projects, endpoints, handlers, messages, schemas, validators, and invariants.
754
+ • Pass 2: Directed relationship wiring:
755
+ - EXPOSES: Project -> Endpoint
756
+ - HANDLES: Handler -> Message
757
+ - DISPATCHES: Endpoint -> Message (including event publishers)
758
+ - PERSISTED_BY: Schema -> Context / Relational Table
759
+ - DEPENDS_ON: Project -> Project
760
+ - CONSTRAINS: Invariant -> Project / Source Code
761
+ - RELATES_TO: Invariant -> Invariant & Canonical Event Matching across Languages
762
+ - VALIDATES: Validator -> Command / Message
763
+ - CONSUMES_EVENT: Function / Endpoint / Worker -> Message / Queue
764
+ - CALLS_HTTP: Client HTTP Call / Caller Project -> Target Server Endpoint (Cross-Boundary)
765
+ - CALLS_GRPC: gRPC Client Stub / Caller Project -> Target RPC Service (Cross-Boundary)
766
+ • Supported Formats:
767
+ - json: Raw Codebase Knowledge Graph AST with node/edge metadata.
768
+ - mermaid: Flowchart TD syntax ready for GitHub PR descriptions, wikis, and live previews.
769
+ - markdown: Complete architectural document featuring Mermaid diagram + tabular entity inventory.
770
+ • Two-Tier Caching: Persists built graph in .akb/cache.json alongside skeleton with in-memory caching for sub-millisecond repeated lookups.
771
+
772
+ Examples:
773
+ $ akbo graph .
774
+ $ akbo graph . --pool C:/AKBO/EnterprisePool
775
+ $ akbo graph . --json
776
+ $ akbo graph . --format mermaid
777
+ $ akbo graph . --format mermaid -o docs/architecture.mmd
778
+ $ akbo graph . --format mermaid -o docs/architecture.mmd --watch
779
+ $ akbo graph . --format markdown -o docs/architecture-graph.md
780
+ $ akbo graph src/Billing -o .akb/billing-graph.json
781
+ `)
782
+ .action(async (dir, options) => {
783
+ const targetDir = path.resolve(dir);
784
+ const poolDir = options.pool || program.opts().pool;
785
+ const startTime = Date.now();
786
+ const harvester = new Harvester(targetDir, undefined, poolDir);
787
+ const skeleton = await harvester.harvest({ useCache: !options.noCache });
788
+ const graphBuilder = new GraphBuilder(targetDir, poolDir);
789
+ const graph = await graphBuilder.buildGraph(skeleton, undefined, { useCache: !options.noCache });
790
+ const elapsed = ((Date.now() - startTime) / 1000).toFixed(2);
791
+ if (options.json) {
792
+ console.log(JSON.stringify(graph, null, 2));
793
+ return;
794
+ }
795
+ console.log(chalk.blue.bold('\nšŸ•ø AKB Graph Builder (Deterministic - 0 Tokens)'));
796
+ console.log(chalk.gray(`Scanning target: ${targetDir}\n`));
797
+ const outPath = path.isAbsolute(options.out)
798
+ ? options.out
799
+ : (harvester.poolConfig.isExternalPool && options.out === '.akb/graph.json'
800
+ ? path.resolve(harvester.poolConfig.poolDir, options.out)
801
+ : path.resolve(targetDir, options.out));
802
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
803
+ const maxNodes = parseInt(options.maxNodes, 10);
804
+ const nodeTypes = options.nodeTypes ? options.nodeTypes.split(',').map((s) => s.trim()) : undefined;
805
+ if (options.watch) {
806
+ console.log(chalk.blue.bold('\nšŸ‘€ AKB Live Architecture Watcher'));
807
+ console.log(chalk.gray(`Watching directory: ${targetDir}`));
808
+ console.log(chalk.gray(`Output file: ${outPath} (${options.format})`));
809
+ console.log(chalk.gray(`Press Ctrl+C to stop watching...\n`));
810
+ const watcher = new CodebaseWatcher(targetDir, poolDir);
811
+ await watcher.start({
812
+ dir: targetDir,
813
+ out: outPath,
814
+ format: options.format,
815
+ clustered: options.cluster !== false,
816
+ maxNodes: isNaN(maxNodes) ? 40 : maxNodes,
817
+ nodeTypes,
818
+ onUpdate: (event) => {
819
+ console.log(chalk.green(`[${new Date().toLocaleTimeString()}] āœ” Updated CKG: ${event.nodesCount} nodes, ${event.edgesCount} edges in ${event.durationMs}ms`));
820
+ if (event.outPath) {
821
+ console.log(chalk.cyan(` šŸ’¾ Re-rendered: ${event.outPath}`));
822
+ }
823
+ }
824
+ });
825
+ return;
826
+ }
827
+ if (options.format === 'mermaid') {
828
+ const mermaid = graphBuilder.exportMermaid(graph, {
829
+ clustered: options.cluster !== false,
830
+ maxNodes: isNaN(maxNodes) ? 40 : maxNodes,
831
+ nodeTypes
832
+ });
833
+ fs.writeFileSync(outPath, mermaid, 'utf-8');
834
+ console.log(chalk.green(`āœ” Generated Mermaid diagram with ${graph.nodes.length} nodes and ${graph.edges.length} edges in ${elapsed}s`));
835
+ console.log(chalk.cyan(`šŸ’¾ Saved Mermaid graph to: ${outPath}\n`));
836
+ }
837
+ else if (options.format === 'markdown') {
838
+ let md = `# Codebase Knowledge Graph\n\n`;
839
+ md += `Total Entities: ${graph.nodes.length} | Relationships: ${graph.edges.length}\n\n`;
840
+ md += `\`\`\`mermaid\n${graphBuilder.exportMermaid(graph, {
841
+ clustered: options.cluster !== false,
842
+ maxNodes: isNaN(maxNodes) ? 40 : maxNodes,
843
+ nodeTypes
844
+ })}\n\`\`\`\n\n`;
845
+ md += `## Entities\n| ID | Type | Label | File |\n| :--- | :--- | :--- | :--- |\n`;
846
+ for (const n of graph.nodes) {
847
+ md += `| \`${n.id}\` | ${n.type} | ${n.label} | ${n.file || '-'} |\n`;
848
+ }
849
+ fs.writeFileSync(outPath, md, 'utf-8');
850
+ console.log(chalk.green(`āœ” Generated Markdown architecture graph in ${elapsed}s`));
851
+ console.log(chalk.cyan(`šŸ’¾ Saved Markdown graph to: ${outPath}\n`));
852
+ }
853
+ else {
854
+ fs.writeFileSync(outPath, JSON.stringify(graph, null, 2), 'utf-8');
855
+ console.log(chalk.green(`āœ” Built CKG with ${graph.nodes.length} nodes and ${graph.edges.length} edges in ${elapsed}s`));
856
+ console.log(chalk.cyan(`šŸ’¾ Saved Codebase Knowledge Graph to: ${outPath}\n`));
857
+ }
858
+ });
859
+ program
860
+ .command('watch')
861
+ .argument('[dir]', 'Directory of the codebase to watch', '.')
862
+ .option('-o, --out <path>', 'Output path (e.g. docs/architecture.mmd)', 'docs/architecture.mmd')
863
+ .option('--format <format>', 'Export format: json, mermaid, markdown', 'mermaid')
864
+ .option('--no-cluster', 'Disable domain subgraph clustering in Mermaid format')
865
+ .option('--max-nodes <n>', 'Maximum number of nodes to include in Mermaid diagram', '40')
866
+ .option('--node-types <types>', 'Comma-separated node types to include in Mermaid export')
867
+ .option('--pool <path>', 'External knowledge base and cache pool directory')
868
+ .description('Live Architecture: Continuously watch codebase changes and automatically re-render the Codebase Knowledge Graph')
869
+ .addHelpText('after', `
870
+ Live Architecture Rendering:
871
+ • Incremental File Watching: Watches directory for file modifications, additions, and deletions.
872
+ • Sub-second CKG Refresh: Automatically updates the Codebase Knowledge Graph via mtime caching.
873
+ • Live Diagram Export: Auto-saves refreshed Mermaid or Markdown graphs to documentation files.
874
+
875
+ Examples:
876
+ $ akbo watch .
877
+ $ akbo watch . -o docs/architecture.mmd
878
+ $ akbo watch . --format markdown -o docs/architecture.md
879
+ `)
880
+ .action(async (dir, options) => {
881
+ const targetDir = path.resolve(dir);
882
+ const poolDir = options.pool || program.opts().pool;
883
+ const outPath = path.isAbsolute(options.out)
884
+ ? options.out
885
+ : path.resolve(targetDir, options.out);
886
+ console.log(chalk.blue.bold('\nšŸ‘€ AKB Live Architecture Watcher'));
887
+ console.log(chalk.gray(`Watching directory: ${targetDir}`));
888
+ console.log(chalk.gray(`Output file: ${outPath} (${options.format})`));
889
+ console.log(chalk.gray(`Press Ctrl+C to stop watching...\n`));
890
+ const maxNodes = parseInt(options.maxNodes, 10);
891
+ const nodeTypes = options.nodeTypes ? options.nodeTypes.split(',').map((s) => s.trim()) : undefined;
892
+ const watcher = new CodebaseWatcher(targetDir, poolDir);
893
+ await watcher.start({
894
+ dir: targetDir,
895
+ out: outPath,
896
+ format: options.format,
897
+ clustered: options.cluster !== false,
898
+ maxNodes: isNaN(maxNodes) ? 40 : maxNodes,
899
+ nodeTypes,
900
+ onUpdate: (event) => {
901
+ console.log(chalk.green(`[${new Date().toLocaleTimeString()}] āœ” Updated CKG: ${event.nodesCount} nodes, ${event.edgesCount} edges in ${event.durationMs}ms`));
902
+ if (event.outPath) {
903
+ console.log(chalk.cyan(` šŸ’¾ Re-rendered: ${event.outPath}`));
904
+ }
905
+ }
906
+ });
907
+ });
908
+ program
909
+ .command('context')
910
+ .argument('<target>', 'Target file, endpoint, or entity name to extract architectural context for')
911
+ .argument('[dir]', 'Directory of the codebase', '.')
912
+ .option('-h, --hops <hops>', 'Maximum traversal hops (1 or 2)', '2')
913
+ .option('--no-cache', 'Disable incremental mtime caching and force fresh harvest')
914
+ .option('--pool <path>', 'External knowledge base and cache pool directory')
915
+ .option('-j, --json', 'Output raw JSON neighborhood directly to stdout for machine consumption')
916
+ .description('GraphRAG: Extract 0-token topological neighborhood (1-2 hops) & active invariants for AI agent pre-execution')
917
+ .addHelpText('after', `
918
+ Agent Pre-Execution Protocol:
919
+ • Zero-Token Subgraph Extraction: Extracts the 1-hop or 2-hop topological neighborhood around any code entity in sub-milliseconds.
920
+ • Polyglot Cross-Boundary Traversal: Traverses multi-service boundaries seamlessly across languages (Next.js fetch -> .NET InvoicesController -> Java Spring Kafka -> Python Celery).
921
+ • Invariant & Validation Injection: Gathers active architectural standards, rules, FluentValidation constraints, and do/dont rules from knowledge/ units.
922
+ • Hallucination Prevention: Feeds precise, grounded context into AI coding assistants (Antigravity, Cursor, Claude Code, Copilot) before any code is modified.
923
+ • Target Matching & File Fallback: Supports class names, endpoint signatures, message types, validators, or arbitrary file paths (automatically resolving non-endpoint files to owning project dependencies and applicable invariants).
924
+
925
+ Examples:
926
+ $ akbo context InvoicesController.cs
927
+ $ akbo context InvoicesController.cs --pool C:/AKBO/EnterprisePool
928
+ $ akbo context "POST /api/invoices" -j
929
+ $ akbo context BillingDbContext -h 1
930
+ $ akbo context CreateInvoiceValidator
931
+ $ akbo context ProcessOrder
932
+ $ akbo context FacturaController
933
+ $ akbo context "ObtenerFactura"
934
+ `)
935
+ .action(async (target, dir, options) => {
936
+ const targetDir = path.resolve(dir);
937
+ const poolDir = options.pool || program.opts().pool;
938
+ const harvester = new Harvester(targetDir, undefined, poolDir);
939
+ const skeleton = await harvester.harvest({ useCache: !options.noCache });
940
+ const graphBuilder = new GraphBuilder(targetDir, poolDir);
941
+ const graph = await graphBuilder.buildGraph(skeleton, undefined, { useCache: !options.noCache });
942
+ const hops = parseInt(options.hops, 10) || 2;
943
+ const neighborhood = graphBuilder.extractNeighborhood(graph, target, hops);
944
+ if (options.json) {
945
+ if (!neighborhood) {
946
+ console.log(JSON.stringify({ error: `No graph entity matching "${target}" was found in the codebase graph.` }, null, 2));
947
+ }
948
+ else {
949
+ console.log(JSON.stringify(neighborhood, null, 2));
950
+ }
951
+ return;
952
+ }
953
+ if (!neighborhood) {
954
+ console.log(chalk.yellow(`\n⚠ No graph node matching "${target}" was found in the codebase graph.\n`));
955
+ return;
956
+ }
957
+ console.log(chalk.blue.bold(`\nšŸ“ GraphRAG Context: [${neighborhood.centerNode.type.toUpperCase()}] ${neighborhood.centerNode.label}`));
958
+ console.log(chalk.gray(`Found ${neighborhood.nodes.length} connected entities across ${neighborhood.edges.length} edges (${hops} hops):\n`));
959
+ console.log(neighborhood.formattedContext);
960
+ console.log('');
961
+ });
962
+ program
963
+ .command('query')
964
+ .alias('ask')
965
+ .argument('<prompt>', 'Question or architectural query about the codebase')
966
+ .argument('[dir]', 'Directory of the codebase', '.')
967
+ .option('-m, --model <model>', 'LLM model name (e.g. gemini-3.5-flash, gpt-4o, claude-3-7-sonnet, deepseek-chat)', process.env.GEMINI_MODEL || 'gemini-3.5-flash')
968
+ .option('-p, --provider <provider>', 'LLM provider ("gemini", "openai", "anthropic", "deepseek", "groq", "ollama", "agy", "cli")', process.env.AKB_PROVIDER)
969
+ .option('--api-key <key>', 'Explicit API key override')
970
+ .option('--base-url <url>', 'Custom endpoint / base URL for OpenAI-compatible or local Ollama endpoints')
971
+ .option('--cli', 'Use system Gemini CLI instead of direct API call')
972
+ .option('--agy', 'Use system Antigravity CLI (agy) instead of direct API call')
973
+ .option('--no-cache', 'Disable incremental mtime caching and force fresh harvest')
974
+ .option('--pool <path>', 'External knowledge base and cache pool directory')
975
+ .option('-j, --json', 'Output raw JSON answer directly to stdout for machine consumption')
976
+ .description('GraphRAG: Answer architectural questions grounded strictly in the Codebase Knowledge Graph with zero hallucinations')
977
+ .addHelpText('after', `
978
+ Cross-Lingual GraphRAG Architecture:
979
+ • Semantic Seed Grounding: Automatically resolves English questions against localized codebases where classes, endpoints, and database models are named in Spanish (Factura, Cliente, Pedido), Chinese (å‘ē„Ø, ē”Øęˆ·), German (Rechnung, Kunde), French, etc.
980
+ • Multi-Seed Neighborhood Merging: Strips punctuation, filters question stopwords, and fuses topological contexts from multiple entities into a single unified prompt slice.
981
+ • Topological Neighborhood Grounding: Deterministically traverses connected entities and active invariants before generating the answer.
982
+ • Zero Hallucination: Answers cite exact code symbols, file locations, and architectural constraints discovered in the graph.
983
+ • Multi-LLM Provider Execution: Seamlessly run via Gemini, OpenAI, Anthropic Claude, DeepSeek, Groq, Ollama / Local, Gemini CLI ('--cli'), or Antigravity CLI ('--agy').
984
+
985
+ Examples:
986
+ $ akbo query "How are invoices created and what data models are used?"
987
+ $ akbo query "How are invoices created and what data models are used?" --pool C:/AKBO/EnterprisePool
988
+ $ akbo query "How are invoices created and what data models are used?" -j
989
+ $ akbo ask "Explain the customer billing architecture" --cli
990
+ $ akbo ask "Explain the customer billing architecture" --agy
991
+ $ akbo ask "Explain the customer billing architecture" -p openai -m gpt-4o
992
+ $ akbo query "Explain the customer billing architecture" -p anthropic -m claude-3-7-sonnet
993
+ $ akbo query "What validation rules are enforced for CreateInvoiceCommand?" -p ollama
994
+ $ akbo query "Which Azure Functions consume ServiceBus messages?"
995
+ $ akbo query "Which message consumers handle payment events?"
996
+ $ akbo ask "What architectural invariants constrain data persistence?"
997
+ $ akbo query "Vilka endpoints hanterar fakturering?"
998
+ `)
999
+ .action(async (prompt, dir, options) => {
1000
+ const targetDir = path.resolve(dir);
1001
+ const poolDir = options.pool || program.opts().pool;
1002
+ if (!options.json) {
1003
+ console.log(chalk.blue.bold('\n🧠 AKB GraphRAG Query: ') + chalk.white(`"${prompt}"`));
1004
+ }
1005
+ const forceCli = Boolean(options.cli || options.provider === 'cli');
1006
+ const selectedProvider = options.agy || options.provider === 'agy' || options.provider === 'agy-cli' ? 'agy' : options.provider;
1007
+ const queryService = new QueryService(targetDir, poolDir);
1008
+ try {
1009
+ const result = await queryService.query(prompt, {
1010
+ dir: targetDir,
1011
+ poolDir,
1012
+ model: options.model,
1013
+ forceCli,
1014
+ providerName: selectedProvider,
1015
+ apiKey: options.apiKey,
1016
+ baseUrl: options.baseUrl,
1017
+ useCache: !options.noCache,
1018
+ onProgress: !options.json
1019
+ ? (msg) => {
1020
+ process.stdout.write(chalk.gray(msg.endsWith('\n') ? msg : `${msg}\n`));
1021
+ }
1022
+ : undefined
1023
+ });
1024
+ if (options.json) {
1025
+ console.log(JSON.stringify({
1026
+ answer: result.answer,
1027
+ keyEntities: result.keyEntities,
1028
+ activeRules: result.activeRules
1029
+ }, null, 2));
1030
+ return;
1031
+ }
1032
+ console.log(chalk.green.bold('āœ” Answer:'));
1033
+ console.log(chalk.white(result.answer));
1034
+ if (result.keyEntities && result.keyEntities.length > 0) {
1035
+ console.log(chalk.cyan('\nKey Entities Involved:'));
1036
+ for (const ent of result.keyEntities)
1037
+ console.log(chalk.gray(` • ${ent}`));
1038
+ }
1039
+ if (result.activeRules && result.activeRules.length > 0) {
1040
+ console.log(chalk.yellow('\nEnforced Architectural Invariants:'));
1041
+ for (const rule of result.activeRules)
1042
+ console.log(chalk.gray(` • ${rule}`));
1043
+ }
1044
+ console.log('');
1045
+ }
1046
+ catch (err) {
1047
+ if (options.json) {
1048
+ console.log(JSON.stringify({ error: err.message }, null, 2));
1049
+ return;
1050
+ }
1051
+ console.log(chalk.red(`āœ– Failed to synthesize answer: ${err.message}`));
1052
+ }
1053
+ });
1054
+ program
1055
+ .command('invariants')
1056
+ .argument('[dir]', 'Directory of the codebase', '.')
1057
+ .option('-f, --file <file>', 'Target file to find matching applicable invariants for (matches applies_to)')
1058
+ .option('-d, --domain <domain>', 'Domain or category filter (e.g. "architecture", "development")')
1059
+ .option('-q, --query <query>', 'Substring or keyword search across rule, title, id, reason, do, dont')
1060
+ .option('--pool <path>', 'External knowledge base and cache pool directory')
1061
+ .option('-j, --json', 'Output raw JSON result directly to stdout for machine consumption')
1062
+ .description('Knowledge Base: List architectural invariants and rules applicable to the codebase or a specific file (0 LLM tokens)')
1063
+ .addHelpText('after', `
1064
+ Pre-Execution Invariant Lookup:
1065
+ • Zero LLM Overhead: Instantly inspects active rules, directives, workflow gates, companion references, and do/dont constraints before modifying files.
1066
+ • File Scoping: Pass '-f, --file <path>' to match against unit 'applies_to' patterns.
1067
+ • Domain Scoping: Pass '-d, --domain <name>' to filter by domain catalog.
1068
+ • Keyword Search: Pass '-q, --query <term>' to filter rules and directives instantly.
1069
+ • Interactive Links: Cites clickable skill specifications (file:///) and references in GraphRAG context.
1070
+
1071
+ Examples:
1072
+ $ akbo invariants .
1073
+ $ akbo invariants . -f src/cli.ts
1074
+ $ akbo invariants . -q Invoice -j
1075
+ $ akbo invariants . -f src/cli.ts --pool C:/AKBO/EnterprisePool
1076
+ $ akbo invariants . -d architecture -j
1077
+ `)
1078
+ .action(async (dir, options) => {
1079
+ const targetDir = path.resolve(dir);
1080
+ const poolDir = options.pool || program.opts().pool;
1081
+ const graphBuilder = new GraphBuilder(targetDir, poolDir);
1082
+ const units = graphBuilder.loadKnowledgeUnits();
1083
+ let filtered = units;
1084
+ if (options.domain) {
1085
+ const dLower = options.domain.toLowerCase();
1086
+ filtered = filtered.filter(u => (u.domain && u.domain.toLowerCase() === dLower) ||
1087
+ (u.id && u.id.toLowerCase().startsWith(dLower)));
1088
+ }
1089
+ if (options.file) {
1090
+ filtered = filtered.filter(u => graphBuilder.matchesAppliesTo(u, options.file));
1091
+ }
1092
+ if (options.query) {
1093
+ const qLower = options.query.toLowerCase().trim();
1094
+ filtered = filtered.filter(u => {
1095
+ const matchId = u.id && u.id.toLowerCase().includes(qLower);
1096
+ const matchTitle = u.title && u.title.toLowerCase().includes(qLower);
1097
+ const matchRule = u.rule && u.rule.toLowerCase().includes(qLower);
1098
+ const matchReason = u.reason && u.reason.toLowerCase().includes(qLower);
1099
+ const matchDo = Array.isArray(u.do) && u.do.some(d => d.toLowerCase().includes(qLower));
1100
+ const matchDont = Array.isArray(u.dont) && u.dont.some(d => d.toLowerCase().includes(qLower));
1101
+ const matchApplies = Array.isArray(u.applies_to) && u.applies_to.some(a => a.toLowerCase().includes(qLower));
1102
+ return matchId || matchTitle || matchRule || matchReason || matchDo || matchDont || matchApplies;
1103
+ });
1104
+ }
1105
+ if (options.json) {
1106
+ console.log(JSON.stringify(filtered.map(u => ({
1107
+ id: u.id,
1108
+ type: u.type,
1109
+ status: u.status,
1110
+ title: u.title,
1111
+ domain: u.domain || 'general',
1112
+ rule: u.rule,
1113
+ reason: u.reason,
1114
+ applies_to: u.applies_to || [],
1115
+ skill_file: u.skill_file,
1116
+ reference_files: u.reference_files,
1117
+ workflow_gates: u.workflow_gates,
1118
+ do: u.do || [],
1119
+ dont: u.dont || [],
1120
+ related_items: u.related_items || [],
1121
+ authority: u.authority
1122
+ })), null, 2));
1123
+ return;
1124
+ }
1125
+ console.log(chalk.blue.bold('\nšŸ“œ AKB Invariants Inventory: ') + chalk.gray(targetDir));
1126
+ if (options.file)
1127
+ console.log(chalk.cyan(` • Scoped to file: ${options.file}`));
1128
+ if (options.domain)
1129
+ console.log(chalk.cyan(` • Scoped to domain: ${options.domain}`));
1130
+ console.log(chalk.white(` Found ${chalk.bold(filtered.length)} matching architectural invariant(s):\n`));
1131
+ for (const u of filtered) {
1132
+ console.log(chalk.yellow.bold(`[${u.id}] ${u.title}`));
1133
+ console.log(chalk.white(` Rule: ${u.rule}`));
1134
+ if (u.skill_file) {
1135
+ console.log(chalk.cyan(` Skill Source: ${u.skill_file}`));
1136
+ }
1137
+ if (u.reference_files && u.reference_files.length > 0) {
1138
+ console.log(chalk.cyan(` References: ${u.reference_files.join(', ')}`));
1139
+ }
1140
+ if (u.workflow_gates && u.workflow_gates.length > 0) {
1141
+ console.log(chalk.green(` Workflow Gates:`));
1142
+ for (let i = 0; i < u.workflow_gates.length; i++) {
1143
+ console.log(chalk.green(` ${i + 1}. ${u.workflow_gates[i]}`));
1144
+ }
1145
+ }
1146
+ if (u.applies_to && u.applies_to.length > 0) {
1147
+ console.log(chalk.gray(` Applies to: ${u.applies_to.join(', ')}`));
1148
+ }
1149
+ console.log('');
1150
+ }
1151
+ });
1152
+ program
1153
+ .command('import-skills')
1154
+ .argument('[dir]', 'Directory of the codebase', '.')
1155
+ .option('-s, --source <globs...>', 'Source glob pattern(s) for skill files', ['.agents/skills/**/SKILL.md', 'skills/**/SKILL.md'])
1156
+ .option('-d, --domain <domain>', 'Target knowledge domain (default: "development")', 'development')
1157
+ .option('-f, --force', 'Force overwrite existing Knowledge Units if they already exist')
1158
+ .option('--pool <path>', 'External knowledge base and cache pool directory')
1159
+ .option('-j, --json', 'Output machine-readable JSON result')
1160
+ .description('Ingest and convert curated agent skills (SKILL.md) into validated, protected Knowledge Units')
1161
+ .addHelpText('after', `
1162
+ Features:
1163
+ • Non-Lossy Skill Pointer Architecture: Preserves skill source paths ('skill_file'), discovers companion reference guides ('reference_files: references/*.md'), extracts procedural verification gates ('workflow_gates'), and applies smart language/wildcard file scoping.
1164
+ • Human Curated Protection: Tags imported units with 'authority.level: human_curated' and 'status: locked' so Stage 3 generators never overwrite human-curated knowledge.
1165
+ • Automatic Catalog Indexing: Formally registers imported units in knowledge/index.yaml and updates the master inventory.
1166
+
1167
+ Examples:
1168
+ $ akbo import-skills .
1169
+ $ akbo import-skills . --pool C:/AKBO/EnterprisePool
1170
+ $ akbo import-skills . -s ".agents/skills/**/SKILL.md" -d architecture
1171
+ $ akbo import-skills . --force
1172
+ `)
1173
+ .action(async (dir, options) => {
1174
+ const targetDir = path.resolve(dir);
1175
+ const poolDir = options.pool || program.opts().pool;
1176
+ const importer = new SkillImporter(targetDir, poolDir);
1177
+ const result = await importer.importSkills({
1178
+ repoRoot: targetDir,
1179
+ poolDir,
1180
+ sourceGlobs: options.source,
1181
+ domain: options.domain,
1182
+ force: options.force
1183
+ });
1184
+ if (options.json) {
1185
+ console.log(JSON.stringify(result, null, 2));
1186
+ return;
1187
+ }
1188
+ console.log(chalk.blue.bold('\nšŸ“„ AKB Skill Importer: ') + chalk.gray(targetDir));
1189
+ if (result.imported.length > 0) {
1190
+ console.log(chalk.green(`āœ” Successfully imported ${result.imported.length} skill(s) into knowledge base:`));
1191
+ for (const item of result.imported) {
1192
+ console.log(chalk.white(` • ${chalk.yellow.bold(item.unitId)}: ${item.title} -> ${chalk.cyan(item.unitPath)}`));
1193
+ }
1194
+ }
1195
+ else {
1196
+ console.log(chalk.yellow('No new skills were imported.'));
1197
+ }
1198
+ if (result.skipped.length > 0) {
1199
+ console.log(chalk.gray(`\nSkipped ${result.skipped.length} existing or unparseable item(s):`));
1200
+ for (const item of result.skipped) {
1201
+ console.log(chalk.gray(` - ${item}`));
1202
+ }
1203
+ }
1204
+ if (result.errors.length > 0) {
1205
+ console.log(chalk.red(`\nErrors encountered (${result.errors.length}):`));
1206
+ for (const err of result.errors) {
1207
+ console.log(chalk.red(` āœ– ${err}`));
1208
+ }
1209
+ }
1210
+ console.log('');
1211
+ });
1212
+ program
1213
+ .command('mcp')
1214
+ .argument('[dir]', 'Directory of the codebase', '.')
1215
+ .option('--pool <path>', 'External knowledge base and cache pool directory')
1216
+ .option('--disable-tools <csv>', 'Comma-separated list of tools to disable (or set AKBO_DISABLE_TOOLS)')
1217
+ .option('--zero-token-only', 'Disable all LLM-backed tools (e.g. akbo_query) (or set AKBO_ZERO_TOKEN_ONLY=1)')
1218
+ .option('--disallow-root-scan', 'Reject scans targeting the root repository directory (or set AKBO_DISALLOW_ROOT_SCAN=1)')
1219
+ .option('--disallow-dirs <csv>', 'Comma-separated list of directories disallowed from scanning (or set AKBO_DISALLOW_DIRS)')
1220
+ .description('Stage 6: Launch native Model Context Protocol (MCP) server over STDIO for AI agent integration')
1221
+ .addHelpText('after', `
1222
+ Model Context Protocol (MCP) Server:
1223
+ • Stdio Transport: Compatible with Google Antigravity, Gemini CLI, Claude Code, Cursor, Windsurf, Copilot, and Codex.
1224
+ • Tools Exposed:
1225
+ - akbo_search: Fast, zero-token in-memory entity search across symbols, endpoints, schemas (<5ms).
1226
+ - akbo_impact: Directional blast-radius and inbound dependent calculation.
1227
+ - akbo_context: 0-token topological neighborhood (1-2 hops) & active invariants for an entity or endpoint.
1228
+ - akbo_query: GraphRAG Q&A grounded strictly in the Codebase Knowledge Graph (supports agy).
1229
+ - akbo_harvest: Deterministically scan codebase topology, manifests, schemas, and endpoints (0 tokens).
1230
+ - akbo_validate: Validate knowledge/ directory against the AKB runtime schema and federation standards.
1231
+ - akbo_graph: Deterministically build the Codebase Knowledge Graph (CKG) (json, mermaid, markdown).
1232
+ - akbo_list_invariants: Retrieve architectural invariants filtered by file, domain, or query (0 tokens).
1233
+ - akbo_upsert_unit: Add or update a knowledge standard or decision in the external pool (single or batch).
1234
+ - akbo_upsert_units: Batch upsert multiple knowledge units atomically.
1235
+ - akbo_get_unit: Retrieve knowledge unit by unique ID.
1236
+ - akbo_delete_unit: Delete knowledge unit and update index atomically.
1237
+ - akbo_import_skills: Import agent skills (.agents/skills/**/SKILL.md) into the central knowledge pool.
1238
+ • Resources Exposed:
1239
+ - akbo://knowledge/index: Real-time read access to the project's knowledge/index.yaml catalog.
1240
+
1241
+ Examples:
1242
+ $ akbo mcp .
1243
+ $ akbo mcp . --pool C:/AKBO/EnterprisePool
1244
+ $ akbo mcp . --disable-tools akbo_query,akbo_import_skills
1245
+ $ akbo mcp . --zero-token-only --disallow-root-scan
1246
+ $ akbo-mcp
1247
+ $ npx -y akbo-cli mcp
1248
+ `)
1249
+ .action(async (dir, options) => {
1250
+ const targetDir = path.resolve(dir);
1251
+ const poolDir = options?.pool || program.opts().pool;
1252
+ if (poolDir) {
1253
+ process.env.AKBO_POOL_DIR = poolDir;
1254
+ }
1255
+ const disableTools = options?.disableTools ? options.disableTools.split(',').map((s) => s.trim()) : undefined;
1256
+ const disallowedDirs = options?.disallowDirs ? options.disallowDirs.split(',').map((s) => s.trim()) : undefined;
1257
+ await runMcpServer(targetDir, poolDir, {
1258
+ poolDir,
1259
+ disableTools,
1260
+ zeroTokenOnly: Boolean(options?.zeroTokenOnly),
1261
+ disallowRootScan: Boolean(options?.disallowRootScan),
1262
+ disallowedDirs
1263
+ });
1264
+ });
1265
+ program
1266
+ .command('upsert')
1267
+ .argument('[dir]', 'Directory of the codebase', '.')
1268
+ .option('--pool <path>', 'External knowledge base and cache pool directory')
1269
+ .option('--from-file <file>', 'Path to JSON or YAML file containing a knowledge unit or array of units')
1270
+ .option('--stdin', 'Read knowledge unit or array JSON/YAML from standard input')
1271
+ .option('--validate', 'Run runtime schema validation after upserting (default: true)', true)
1272
+ .option('--no-validate', 'Skip runtime schema validation')
1273
+ .option('-j, --json', 'Output machine-readable JSON result directly to stdout')
1274
+ .description('Knowledge Base: Atomically upsert one or more knowledge units or decisions into the external pool')
1275
+ .addHelpText('after', `
1276
+ Features:
1277
+ • Atomic Batch Writes: Strips UTF-8 BOM, validates schemas, writes unit YAMLs via atomic .tmp renames, and updates index.yaml once.
1278
+ • Dual Standard & Decision Support: Validates standards against StandardKnowledgeUnitSchema and decisions against DecisionKnowledgeUnitSchema.
1279
+ • Glob Normalization: Automatically converts backslashes to forward slashes and strips leading ./ or repo-name prefixes.
1280
+ • EOL Preservation: Detects and preserves existing CRLF (\r\n) line endings on Windows.
1281
+
1282
+ Examples:
1283
+ $ akbo upsert . --pool C:/AKBO/EnterprisePool --from-file unit.json
1284
+ $ akbo upsert . --pool C:/AKBO/EnterprisePool --from-file batch-units.json -j
1285
+ $ cat new-standard.yaml | akbo upsert . --pool C:/AKBO/EnterprisePool --stdin
1286
+ `)
1287
+ .action(async (dir, options) => {
1288
+ const targetDir = path.resolve(dir);
1289
+ const poolDir = options.pool || program.opts().pool;
1290
+ if (!options.fromFile && !options.stdin) {
1291
+ if (options.json) {
1292
+ console.log(JSON.stringify({ error: 'Either --from-file <path> or --stdin must be provided.' }));
1293
+ }
1294
+ else {
1295
+ console.error(chalk.red('Error: Either --from-file <path> or --stdin must be provided.'));
1296
+ }
1297
+ process.exit(1);
1298
+ }
1299
+ let rawText = '';
1300
+ if (options.fromFile) {
1301
+ const filePath = path.resolve(options.fromFile);
1302
+ if (!fs.existsSync(filePath)) {
1303
+ if (options.json) {
1304
+ console.log(JSON.stringify({ error: `File not found: ${filePath}` }));
1305
+ }
1306
+ else {
1307
+ console.error(chalk.red(`Error: File not found: ${filePath}`));
1308
+ }
1309
+ process.exit(1);
1310
+ }
1311
+ rawText = fs.readFileSync(filePath, 'utf-8');
1312
+ }
1313
+ else if (options.stdin) {
1314
+ rawText = await new Promise((resolve, reject) => {
1315
+ let data = '';
1316
+ process.stdin.setEncoding('utf-8');
1317
+ process.stdin.on('data', chunk => { data += chunk; });
1318
+ process.stdin.on('end', () => { resolve(data); });
1319
+ process.stdin.on('error', err => { reject(err); });
1320
+ });
1321
+ }
1322
+ const units = parseUnitsFromText(rawText);
1323
+ if (units.length === 0) {
1324
+ if (options.json) {
1325
+ console.log(JSON.stringify({ error: 'No valid knowledge unit objects parsed from input.' }));
1326
+ }
1327
+ else {
1328
+ console.error(chalk.red('Error: No valid knowledge unit objects parsed from input.'));
1329
+ }
1330
+ process.exit(1);
1331
+ }
1332
+ const result = await CatalogStore.upsertUnits(units, {
1333
+ targetDir,
1334
+ poolDir,
1335
+ validate: options.validate !== false
1336
+ });
1337
+ if (options.json) {
1338
+ console.log(JSON.stringify(result, null, 2));
1339
+ if (!result.success)
1340
+ process.exit(1);
1341
+ return;
1342
+ }
1343
+ if (!result.success) {
1344
+ console.error(chalk.red(`āŒ Upsert failed: ${result.error}`));
1345
+ process.exit(1);
1346
+ }
1347
+ console.log(chalk.blue.bold('\nšŸ’¾ AKB Knowledge Unit Upsert: ') + chalk.gray(targetDir));
1348
+ console.log(chalk.green(`āœ” Successfully upserted ${result.count} unit(s): ${result.units.join(', ')}`));
1349
+ if (result.validation) {
1350
+ if (result.validation.valid) {
1351
+ console.log(chalk.green(`āœ” Catalog validation passed (${result.validation.unitCount} units).`));
1352
+ }
1353
+ else {
1354
+ console.log(chalk.yellow(`⚠ Catalog validation reported issues:`));
1355
+ for (const err of result.validation.errors)
1356
+ console.log(chalk.red(` • ${err}`));
1357
+ }
1358
+ }
1359
+ });
1360
+ program
1361
+ .command('get-unit')
1362
+ .argument('<id>', 'Unique knowledge unit ID to retrieve')
1363
+ .argument('[dir]', 'Directory of the codebase', '.')
1364
+ .option('--pool <path>', 'External knowledge base and cache pool directory')
1365
+ .option('-j, --json', 'Output machine-readable JSON result directly to stdout')
1366
+ .description('Knowledge Base: Fetch the complete YAML definition and metadata for a knowledge unit by ID')
1367
+ .action(async (id, dir, options) => {
1368
+ const targetDir = path.resolve(dir || '.');
1369
+ const poolDir = options.pool || program.opts().pool;
1370
+ const result = CatalogStore.getUnit(id, { targetDir, poolDir });
1371
+ if (!result) {
1372
+ if (options.json) {
1373
+ console.log(JSON.stringify({ error: `Knowledge unit "${id}" not found.` }));
1374
+ }
1375
+ else {
1376
+ console.error(chalk.red(`Error: Knowledge unit "${id}" not found in knowledge pool.`));
1377
+ }
1378
+ process.exit(1);
1379
+ }
1380
+ if (options.json) {
1381
+ console.log(JSON.stringify(result.unit, null, 2));
1382
+ }
1383
+ else {
1384
+ console.log(result.rawYaml);
1385
+ }
1386
+ });
1387
+ program
1388
+ .command('delete-unit')
1389
+ .argument('<id>', 'Unique knowledge unit ID to delete')
1390
+ .argument('[dir]', 'Directory of the codebase', '.')
1391
+ .option('--pool <path>', 'External knowledge base and cache pool directory')
1392
+ .option('--validate', 'Run runtime schema validation after deletion (default: true)', true)
1393
+ .option('--no-validate', 'Skip runtime schema validation')
1394
+ .option('-j, --json', 'Output machine-readable JSON result directly to stdout')
1395
+ .description('Knowledge Base: Delete a knowledge unit, remove index entry, decrement counts, and clear cache')
1396
+ .action(async (id, dir, options) => {
1397
+ const targetDir = path.resolve(dir || '.');
1398
+ const poolDir = options.pool || program.opts().pool;
1399
+ const result = await CatalogStore.deleteUnit(id, {
1400
+ targetDir,
1401
+ poolDir,
1402
+ validate: options.validate !== false
1403
+ });
1404
+ if (options.json) {
1405
+ console.log(JSON.stringify(result, null, 2));
1406
+ if (!result.success)
1407
+ process.exit(1);
1408
+ return;
1409
+ }
1410
+ if (!result.success) {
1411
+ console.error(chalk.red(`Error: ${result.error}`));
1412
+ process.exit(1);
1413
+ }
1414
+ console.log(chalk.green(`āœ” Successfully deleted unit "${id}" from ${result.filePath} and updated index.yaml.`));
1415
+ if (result.validation) {
1416
+ if (result.validation.valid) {
1417
+ console.log(chalk.green(`āœ” Catalog validation passed.`));
1418
+ }
1419
+ else {
1420
+ console.log(chalk.yellow(`⚠ Catalog validation reported issues:`));
1421
+ for (const err of result.validation.errors)
1422
+ console.log(chalk.red(` • ${err}`));
1423
+ }
1424
+ }
1425
+ });
1426
+ program
1427
+ .command('init-hooks')
1428
+ .argument('[dir]', 'Directory of the codebase', '.')
1429
+ .option('-l, --local', 'Operate strictly within target directory without walking up to parent git repository root')
1430
+ .option('--force-hooks', 'Force overwrite existing AGENTS.md, CLAUDE.md, and hook files')
1431
+ .description('Stage 4: Bootstrap multi-agent instruction hooks (AGENTS.md, GEMINI.md, CLAUDE.md, .cursorrules, and MCP configs)')
1432
+ .addHelpText('after', `
1433
+ Agent Integration Hooks:
1434
+ • AGENTS.md & GEMINI.md: Strict mandatory pre-execution protocol instructing agents to read knowledge/index.yaml first.
1435
+ • CLAUDE.md: Architecture rules, build commands, and context protocol for Claude Code.
1436
+ • .cursorrules: Workspace rules for Cursor AI.
1437
+ • .cursor/mcp.json & .vscode/mcp.json: MCP server configuration enabling Cursor and VS Code AI to use akbo tools natively.
1438
+
1439
+ Examples:
1440
+ $ akbo init-hooks .
1441
+ `)
1442
+ .action(async (dir, options) => {
1443
+ const targetDir = path.resolve(dir);
1444
+ const repoRoot = options.local ? targetDir : findRepoRoot(targetDir);
1445
+ const hookGen = new HookGenerator(repoRoot);
1446
+ const indexPath = path.join(repoRoot, 'knowledge', 'index.yaml');
1447
+ let index = {
1448
+ system_name: path.basename(repoRoot),
1449
+ description: 'AI-Native Knowledge Base',
1450
+ domains: {}
1451
+ };
1452
+ const units = [];
1453
+ if (fs.existsSync(indexPath)) {
1454
+ try {
1455
+ const rawIndex = YAML.parse(fs.readFileSync(indexPath, 'utf-8'));
1456
+ index.system_name = rawIndex.system_name || index.system_name;
1457
+ index.description = rawIndex.description || index.description;
1458
+ if (rawIndex.knowledge_units) {
1459
+ for (const [domain, unitList] of Object.entries(rawIndex.knowledge_units)) {
1460
+ index.domains[domain] = unitList;
1461
+ if (Array.isArray(unitList)) {
1462
+ for (const u of unitList) {
1463
+ const uFile = path.resolve(repoRoot, u.file);
1464
+ if (fs.existsSync(uFile)) {
1465
+ try {
1466
+ const uContent = YAML.parse(fs.readFileSync(uFile, 'utf-8'));
1467
+ units.push(uContent);
1468
+ }
1469
+ catch { }
1470
+ }
1471
+ }
1472
+ }
1473
+ }
1474
+ }
1475
+ }
1476
+ catch (err) {
1477
+ console.error(chalk.yellow(`Could not parse knowledge/index.yaml: ${err.message}`));
1478
+ }
1479
+ }
1480
+ console.log(chalk.blue.bold('\nšŸš€ AKB Hook Generator: Bootstrapping Multi-Agent Integration Hooks'));
1481
+ const written = hookGen.writeAllHooks(index, units, { forceHooks: Boolean(options.forceHooks) });
1482
+ for (const file of written) {
1483
+ console.log(chalk.white(` āœ” Created/Updated ${file}`));
1484
+ }
1485
+ console.log(chalk.green(`\nāœ” Multi-agent instruction hooks & MCP server configuration initialized successfully!\n`));
1486
+ });
1487
+ program
1488
+ .command('schema')
1489
+ .argument('[dir]', 'Directory of the codebase', '.')
1490
+ .option('--pool <path>', 'External knowledge base and cache pool directory')
1491
+ .option('-j, --json', 'Output raw JSON schemas directly to stdout for machine consumption')
1492
+ .description('Developer Tooling: Generate JSON Schemas for knowledge units and configure .vscode/settings.json autocomplete')
1493
+ .addHelpText('after', `
1494
+ Schema Generation & IDE Integration:
1495
+ • Emits schemas/knowledge-unit.json and schemas/index-schema.json.
1496
+ • Injects yaml.schemas mappings into .vscode/settings.json.
1497
+ • Enables hover documentation, property autocomplete, and validation in VS Code, Cursor, and IDEs.
1498
+
1499
+ Examples:
1500
+ $ akbo schema .
1501
+ $ akbo schema . --pool C:/AKBO/Pool
1502
+ $ akbo schema . --json
1503
+ `)
1504
+ .action(async (dir, options) => {
1505
+ const targetDir = path.resolve(dir);
1506
+ const poolDir = options.pool || program.opts().pool;
1507
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: poolDir });
1508
+ const schemaDir = poolConfig.isExternalPool ? poolConfig.poolDir : targetDir;
1509
+ if (options.json) {
1510
+ console.log(JSON.stringify({
1511
+ knowledgeUnitSchema: KNOWLEDGE_UNIT_JSON_SCHEMA,
1512
+ masterIndexSchema: MASTER_INDEX_JSON_SCHEMA
1513
+ }, null, 2));
1514
+ return;
1515
+ }
1516
+ console.log(chalk.blue.bold('\nšŸ“ AKB JSON Schema Generator'));
1517
+ console.log(chalk.gray(`Target directory: ${schemaDir}\n`));
1518
+ const schemaGen = new SchemaGenerator(schemaDir);
1519
+ const result = schemaGen.writeAll();
1520
+ for (const s of result.writtenSchemas) {
1521
+ console.log(chalk.green(` āœ” Emitted JSON Schema: ${s}`));
1522
+ }
1523
+ console.log(chalk.green(` āœ” Configured IDE settings: ${result.settingsPath}`));
1524
+ console.log(chalk.cyan('\nVS Code and Cursor will now provide real-time hover documentation and autocomplete for knowledge/**/*.yaml!\n'));
1525
+ });
1526
+ program
1527
+ .command('version')
1528
+ .description('Display detailed version and environment information')
1529
+ .option('-j, --json', 'Output version information in machine-readable JSON format')
1530
+ .action((options) => {
1531
+ if (options.json) {
1532
+ console.log(JSON.stringify({
1533
+ name: 'akbo-cli',
1534
+ version: VERSION,
1535
+ node: process.version,
1536
+ platform: process.platform,
1537
+ arch: process.arch
1538
+ }, null, 2));
1539
+ return;
1540
+ }
1541
+ console.log(`akbo-cli v${VERSION}`);
1542
+ });
1543
+ if (process.argv[1] && path.basename(process.argv[1]).includes('akbo-mcp')) {
1544
+ let targetDir = '.';
1545
+ let poolDir;
1546
+ let disableTools;
1547
+ let zeroTokenOnly = false;
1548
+ let disallowRootScan = false;
1549
+ let disallowedDirs;
1550
+ for (let i = 2; i < process.argv.length; i++) {
1551
+ const arg = process.argv[i];
1552
+ if (arg === '--pool' && i + 1 < process.argv.length) {
1553
+ poolDir = process.argv[++i];
1554
+ }
1555
+ else if (arg.startsWith('--pool=')) {
1556
+ poolDir = arg.slice(7);
1557
+ }
1558
+ else if (arg === '--disable-tools' && i + 1 < process.argv.length) {
1559
+ disableTools = process.argv[++i].split(',').map(s => s.trim());
1560
+ }
1561
+ else if (arg.startsWith('--disable-tools=')) {
1562
+ disableTools = arg.slice(16).split(',').map(s => s.trim());
1563
+ }
1564
+ else if (arg === '--zero-token-only') {
1565
+ zeroTokenOnly = true;
1566
+ }
1567
+ else if (arg === '--disallow-root-scan') {
1568
+ disallowRootScan = true;
1569
+ }
1570
+ else if (arg === '--disallow-dirs' && i + 1 < process.argv.length) {
1571
+ disallowedDirs = process.argv[++i].split(',').map(s => s.trim());
1572
+ }
1573
+ else if (arg.startsWith('--disallow-dirs=')) {
1574
+ disallowedDirs = arg.slice(16).split(',').map(s => s.trim());
1575
+ }
1576
+ else if (!arg.startsWith('-') && targetDir === '.') {
1577
+ targetDir = arg;
1578
+ }
1579
+ }
1580
+ if (poolDir) {
1581
+ process.env.AKBO_POOL_DIR = poolDir;
1582
+ }
1583
+ runMcpServer(path.resolve(targetDir), poolDir, {
1584
+ poolDir,
1585
+ disableTools,
1586
+ zeroTokenOnly,
1587
+ disallowRootScan,
1588
+ disallowedDirs
1589
+ }).catch((err) => {
1590
+ console.error('Fatal MCP Server error:', err);
1591
+ process.exit(1);
1592
+ });
1593
+ }
1594
+ else {
1595
+ program.parse(process.argv);
1596
+ }