akbo-cli 0.0.0-stage → 2.0.0

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