musubix 3.3.10 → 3.4.1

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 (95) hide show
  1. package/.github/AGENTS.md +949 -0
  2. package/.github/prompts/sdd-change-apply.prompt.md +283 -0
  3. package/.github/prompts/sdd-change-archive.prompt.md +241 -0
  4. package/.github/prompts/sdd-change-init.prompt.md +269 -0
  5. package/.github/prompts/sdd-design.prompt.md +250 -0
  6. package/.github/prompts/sdd-implement.prompt.md +387 -0
  7. package/.github/prompts/sdd-requirements.prompt.md +193 -0
  8. package/.github/prompts/sdd-review.prompt.md +155 -0
  9. package/.github/prompts/sdd-security.prompt.md +228 -0
  10. package/.github/prompts/sdd-steering.prompt.md +269 -0
  11. package/.github/prompts/sdd-tasks.prompt.md +255 -0
  12. package/.github/prompts/sdd-test.prompt.md +230 -0
  13. package/.github/prompts/sdd-validate.prompt.md +304 -0
  14. package/.github/skills/musubix-adr-generation/SKILL.md +209 -0
  15. package/.github/skills/musubix-best-practices/SKILL.md +315 -0
  16. package/.github/skills/musubix-c4-design/SKILL.md +162 -0
  17. package/.github/skills/musubix-code-generation/SKILL.md +237 -0
  18. package/.github/skills/musubix-domain-inference/SKILL.md +196 -0
  19. package/.github/skills/musubix-ears-validation/SKILL.md +161 -0
  20. package/.github/skills/musubix-sdd-workflow/SKILL.md +217 -0
  21. package/.github/skills/musubix-technical-writing/SKILL.md +444 -0
  22. package/.github/skills/musubix-test-generation/SKILL.md +212 -0
  23. package/.github/skills/musubix-traceability/SKILL.md +141 -0
  24. package/AGENTS.md +1134 -0
  25. package/LICENSE +21 -0
  26. package/README.ja.md +313 -0
  27. package/README.md +315 -50
  28. package/bin/musubix-mcp.js +15 -0
  29. package/bin/musubix.js +9 -1
  30. package/docs/API-REFERENCE.md +1425 -0
  31. package/docs/GITHUB-ACTIONS-NPM-SETUP.md +132 -0
  32. package/docs/INSTALL-GUIDE.ja.md +459 -0
  33. package/docs/INSTALL-GUIDE.md +459 -0
  34. package/docs/MIGRATION-v3.0.md +324 -0
  35. package/docs/MUSUBI-enhancement_roadmap_20260105.md +651 -0
  36. package/docs/MUSUBIX-v3.0-User-Guide.md +1357 -0
  37. package/docs/MUSUBIXv2.2.0-Manual-outline.md +136 -0
  38. package/docs/MUSUBIXv2.2.0-Manual.md +3123 -0
  39. package/docs/MUSUBIXv2.3.5-Refactering.md +1310 -0
  40. package/docs/MUSUBIv1.6.1-enhancement_roadmap_20260105.md +291 -0
  41. package/docs/MUSUBIv2.2.0-USERGUIDE.md +2079 -0
  42. package/docs/ROADMAP-v1.5.md +116 -0
  43. package/docs/SwarmCoding.md +1284 -0
  44. package/docs/Test-prompt.md +105 -0
  45. package/docs/USER-GUIDE-v1.8.0.md +2371 -0
  46. package/docs/USER-GUIDE.ja.md +2147 -0
  47. package/docs/USER-GUIDE.md +3022 -0
  48. package/docs/YATA-GLOBAL-GUIDE.ja.md +750 -0
  49. package/docs/YATA-GLOBAL-GUIDE.md +595 -0
  50. package/docs/YATA-LOCAL-GUIDE.ja.md +989 -0
  51. package/docs/YATA-LOCAL-GUIDE.md +730 -0
  52. package/docs/adr/0001-real-time-pattern-learning-architecture-for-v1-5-0.md +75 -0
  53. package/docs/adr/0002-pattern-sharing-protocol-for-cross-team-collaborat.md +79 -0
  54. package/docs/adr/0003-owl-2-rl-implementation-strategy-for-advanced-infe.md +90 -0
  55. package/docs/adr/ADR-v3.4.0-001-deep-research-architecture.md +217 -0
  56. package/docs/adr/ADR-v3.4.0-002-search-provider-selection.md +308 -0
  57. package/docs/adr/ADR-v3.4.0-003-lm-api-integration.md +475 -0
  58. package/docs/enterprise-knowledge-management.md +1737 -0
  59. package/docs/evolution-from-musubi-to-musubix.md +2170 -0
  60. package/docs/getting-started-with-sdd.md +1602 -0
  61. package/docs/moodle-refactering-codegraph-musubix.md +391 -0
  62. package/docs/moodle-refactering-codegraph.md +278 -0
  63. package/docs/overview/MUSUBIX-CodeGraph.md +322 -0
  64. package/docs/overview/MUSUBIX-Core.md +671 -0
  65. package/docs/overview/MUSUBIX-Decisions.md +494 -0
  66. package/docs/overview/MUSUBIX-FormalVerify.md +566 -0
  67. package/docs/overview/MUSUBIX-Knowledge.md +1231 -0
  68. package/docs/overview/MUSUBIX-Learning.md +837 -0
  69. package/docs/overview/MUSUBIX-MCP-Server.md +535 -0
  70. package/docs/overview/MUSUBIX-Overview.md +264 -0
  71. package/docs/overview/MUSUBIX-Phase1-Complete.md +271 -0
  72. package/docs/overview/MUSUBIX-Phase2-Complete.md +310 -0
  73. package/docs/overview/MUSUBIX-Policy.md +477 -0
  74. package/docs/overview/MUSUBIX-Roadmap-v2.md +399 -0
  75. package/docs/overview/MUSUBIX-Security-Plan.md +939 -0
  76. package/docs/overview/MUSUBIX-Security-v2.1.md +668 -0
  77. package/docs/overview/MUSUBIX-Security.md +891 -0
  78. package/docs/overview/MUSUBIX-YATA.md +666 -0
  79. package/docs/overview/MUSUBIX-v2.2.0-Advanced-Learning.md +513 -0
  80. package/docs/overview/Neuro-SymbolicAI.md +159 -0
  81. package/docs/packages/knowledge.md +594 -0
  82. package/docs/qiita-linux-kernel-knowledge-graph.md +596 -0
  83. package/package.json +55 -49
  84. package/scripts/generate-quality-gate-report.ts +106 -0
  85. package/scripts/postinstall.js +94 -0
  86. package/steering/.musubi-version +1 -0
  87. package/steering/product.ja.md +572 -0
  88. package/steering/project.yml +66 -0
  89. package/steering/rules/constitution.md +491 -0
  90. package/steering/structure.ja.md +503 -0
  91. package/steering/tech.ja.md +208 -0
  92. package/dist/index.d.ts +0 -25
  93. package/dist/index.d.ts.map +0 -1
  94. package/dist/index.js +0 -74
  95. package/dist/index.js.map +0 -1
@@ -0,0 +1,3022 @@
1
+ # MUSUBIX User Guide
2
+
3
+ > Neuro-Symbolic AI Coding with Ultimate Specification Driven Development
4
+
5
+ ---
6
+
7
+ ## Table of Contents
8
+
9
+ 1. [Introduction](#introduction)
10
+ 2. [Installation](#installation)
11
+ 3. [CLI Usage](#cli-usage)
12
+ 4. [Quick Start](#quick-start)
13
+ 5. [SDD Workflow](#sdd-workflow)
14
+ 6. [Self-Learning System](#self-learning-system)
15
+ 7. [C4 Code Generation](#c4-code-generation)
16
+ 8. [Symbolic Reasoning](#symbolic-reasoning) *(v1.2.0)*
17
+ 9. [Consistency Validation](#consistency-validation) *(v1.4.1)*
18
+ 10. [Advanced Inference](#advanced-inference) *(v1.4.5)*
19
+ 11. [Interactive REPL Mode](#interactive-repl-mode) *(v1.5.0)*
20
+ 12. [YATA Local](#yata-local) *(v1.6.3)*
21
+ 13. [YATA Global](#yata-global) *(v1.6.3)*
22
+ 14. [KGPR - Knowledge Graph Pull Request](#kgpr---knowledge-graph-pull-request) *(v1.6.4)*
23
+ 15. [YATA Platform Enhancements](#yata-platform-enhancements) *(v1.7.0)*
24
+ 16. [Formal Verification](#formal-verification) *(v1.7.5)*
25
+ 17. [Security Analysis](#security-analysis) *(v1.8.0)*
26
+ 18. [DFG/CFG Extraction](#dfgcfg-extraction) *(v2.0.0)*
27
+ 19. [Lean 4 Integration](#lean-4-integration) *(v2.0.0)*
28
+ 20. [YATA Scale](#yata-scale) *(v2.0.0)*
29
+ 21. [Library Learning](#library-learning) *(v2.0.0)*
30
+ 22. [Neural Search](#neural-search) *(v2.0.0)*
31
+ 23. [Program Synthesis](#program-synthesis) *(v2.0.0)*
32
+ 24. [Advanced Learning Enhancement](#advanced-learning-enhancement) *(v2.2.0)*
33
+ 25. [Performance Optimization](#performance-optimization) *(v3.1.0 NEW!)*
34
+ 26. [MCP Server Integration](#mcp-server-integration)
35
+ 27. [YATA Integration](#yata-integration)
36
+ 28. [Best Practices](#best-practices)
37
+ 29. [Troubleshooting](#troubleshooting)
38
+
39
+ ---
40
+
41
+ ## Introduction
42
+
43
+ ### What is MUSUBIX?
44
+
45
+ **MUSUBIX** is an Ultimate Specification Driven Development (SDD) platform based on Neuro-Symbolic AI. By integrating MUSUBI (SDD Engine) with YATA (Knowledge Graph), it provides an AI-assisted development environment that maintains requirements, design, and implementation consistency.
46
+
47
+ ### 9 Constitutional Articles
48
+
49
+ MUSUBIX development follows 9 Articles:
50
+
51
+ | Article | Description |
52
+ |---------|-------------|
53
+ | Article 1 | EARS-format requirements |
54
+ | Article 2 | C4 architecture design |
55
+ | Article 3 | ADR-based technical decisions |
56
+ | Article 4 | Test-first development (TDD) |
57
+ | Article 5 | Full requirement traceability |
58
+ | Article 6 | CI/CD automation |
59
+ | Article 7 | Knowledge graph management |
60
+ | Article 8 | AI-assisted code review |
61
+ | Article 9 | Continuous quality improvement |
62
+
63
+ ---
64
+
65
+ ## Installation
66
+
67
+ ### System Requirements
68
+
69
+ - Node.js: >= 20.0.0
70
+ - npm: >= 10.0.0
71
+ - TypeScript: >= 5.3
72
+
73
+ ### Method 1: Global Installation (Recommended)
74
+
75
+ ```bash
76
+ # Global installation
77
+ npm install -g musubix
78
+
79
+ # Verify installation
80
+ musubix --version
81
+ ```
82
+
83
+ ### Method 2: Using npx
84
+
85
+ ```bash
86
+ # Initialize project without installation
87
+ npx musubix init my-project
88
+
89
+ # Project templates
90
+ npx musubix init my-app --template typescript
91
+ npx musubix init my-api --template node
92
+ npx musubix init my-web --template react
93
+ ```
94
+
95
+ ### Method 3: Project Dependency
96
+
97
+ ```bash
98
+ # Add to existing project
99
+ npm install musubix
100
+
101
+ # Use with npx
102
+ npx musubix --help
103
+ ```
104
+
105
+ ### Method 4: From Source
106
+
107
+ ```bash
108
+ # Clone repository
109
+ git clone https://github.com/nahisaho/MUSUBIX.git
110
+ cd MUSUBIX
111
+
112
+ # Install dependencies
113
+ npm install
114
+
115
+ # Build
116
+ npm run build
117
+
118
+ # Global link
119
+ npm link
120
+ ```
121
+
122
+ ### YATA Installation (Optional)
123
+
124
+ If you want to use knowledge graph features, install YATA separately:
125
+
126
+ ```bash
127
+ # Install uv (if not installed)
128
+ curl -LsSf https://astral.sh/uv/install.sh | sh
129
+
130
+ # Clone YATA
131
+ git clone https://github.com/nahisaho/YATA.git
132
+ cd YATA
133
+
134
+ # Create Python environment
135
+ uv venv
136
+ source .venv/bin/activate # Linux/macOS
137
+ # or .venv\Scripts\activate # Windows
138
+
139
+ # Install dependencies
140
+ uv pip install -e ".[dev]"
141
+ ```
142
+
143
+ ---
144
+
145
+ ## CLI Usage
146
+
147
+ ### musubix Command
148
+
149
+ Main command for project management:
150
+
151
+ ```bash
152
+ # Initialize project
153
+ musubix init <project-name>
154
+
155
+ # Available templates
156
+ musubix init my-project --template typescript
157
+ musubix init my-project --template node
158
+ musubix init my-project --template react
159
+
160
+ # Help
161
+ musubix --help
162
+
163
+ # Version
164
+ musubix --version
165
+ ```
166
+
167
+ ### Design Commands *(v3.1.0 NEW!)*
168
+
169
+ ```bash
170
+ # Generate C4 design from requirements
171
+ musubix design generate <file>
172
+
173
+ # Validate design patterns
174
+ musubix design validate <file>
175
+
176
+ # REQ↔DES traceability validation
177
+ musubix design traceability
178
+ musubix design traceability --min-coverage 80 # Set coverage threshold
179
+ musubix design traceability --require-full # Require 100% coverage
180
+ ```
181
+
182
+ ### Code Generation Commands *(v3.1.0 NEW!)*
183
+
184
+ ```bash
185
+ # Generate code from C4 design
186
+ musubix codegen generate <file> --output src/
187
+
188
+ # Generate status transition code from spec
189
+ musubix codegen status <spec> # Union type (default)
190
+ musubix codegen status <spec> --enum # Enum type
191
+ musubix codegen status <spec> --no-validator # Skip validation functions
192
+ musubix codegen status <spec> --no-helpers # Skip helper functions
193
+ ```
194
+
195
+ ### Scaffold Commands *(v3.1.0 Enhanced!)*
196
+
197
+ ```bash
198
+ # DDD project scaffolding
199
+ musubix scaffold domain-model <name>
200
+
201
+ # With entities
202
+ musubix scaffold domain-model <name> -e "User,Order"
203
+
204
+ # With Value Objects
205
+ musubix scaffold domain-model <name> -v "Price,Email"
206
+
207
+ # With status machines
208
+ musubix scaffold domain-model <name> -s "Order,Task"
209
+
210
+ # Combined options
211
+ musubix scaffold domain-model myproject -e "User,Order" -v "Price,Email" -s "Order"
212
+ ```
213
+
214
+ ### musubix-mcp Command
215
+
216
+ Start MCP server for AI platform integration:
217
+
218
+ ```bash
219
+ # Start with stdio transport (default)
220
+ musubix-mcp
221
+
222
+ # Start with SSE transport
223
+ musubix-mcp --transport sse --port 3000
224
+
225
+ # Help
226
+ musubix-mcp --help
227
+
228
+ # Version
229
+ musubix-mcp --version
230
+ ```
231
+
232
+ ---
233
+
234
+ ## Quick Start
235
+
236
+ ### Basic TypeScript Usage
237
+
238
+ ```typescript
239
+ import {
240
+ createRequirementsService,
241
+ createDesignService,
242
+ createValidationService
243
+ } from 'musubix';
244
+
245
+ // Create services
246
+ const requirements = createRequirementsService();
247
+ const design = createDesignService();
248
+ const validation = createValidationService();
249
+
250
+ // Add requirement (EARS format)
251
+ const req = requirements.addRequirement({
252
+ id: 'REQ-001',
253
+ text: 'When a user logs in, the system shall authenticate the user',
254
+ priority: 'high',
255
+ acceptanceCriteria: [
256
+ 'JWT token shall be returned on successful login',
257
+ 'Error message shall be displayed on failure'
258
+ ]
259
+ });
260
+
261
+ // Create design
262
+ const des = design.createComponent({
263
+ id: 'DES-001',
264
+ name: 'AuthModule',
265
+ type: 'component',
266
+ requirements: ['REQ-001'],
267
+ decisions: ['Use JWT authentication']
268
+ });
269
+
270
+ // Validate
271
+ const result = validation.validate({
272
+ requirements: [req],
273
+ designs: [des]
274
+ });
275
+
276
+ console.log(result.compliant); // true or false
277
+ ```
278
+
279
+ ### SDD Workflow Overview
280
+
281
+ ```
282
+ ┌─────────────────┐
283
+ │ Requirements │ EARS format requirements
284
+ └────────┬────────┘
285
+
286
+ ┌─────────────────┐
287
+ │ Design │ C4 Architecture + ADR
288
+ └────────┬────────┘
289
+
290
+ ┌─────────────────┐
291
+ │ Tasks │ Traceable implementation tasks
292
+ └────────┬────────┘
293
+
294
+ ┌─────────────────┐
295
+ │ Validation │ 9 Articles compliance check
296
+ └─────────────────┘
297
+ ```
298
+
299
+ ---
300
+
301
+ ## SDD Workflow
302
+
303
+ ### Phase 1: Requirements (EARS Format)
304
+
305
+ Use EARS (Easy Approach to Requirements Syntax) format for requirements:
306
+
307
+ ```typescript
308
+ const requirements = createRequirementsService();
309
+
310
+ // Pattern: "When <trigger>, the system shall <response>"
311
+ const loginReq = requirements.addRequirement({
312
+ id: 'REQ-001',
313
+ text: 'When a user enters valid credentials, the system shall issue an authentication token',
314
+ priority: 'high',
315
+ acceptanceCriteria: [
316
+ 'Token shall be valid for 24 hours',
317
+ 'Token shall include user information'
318
+ ]
319
+ });
320
+
321
+ // Pattern: "While <state>, the system shall <behavior>"
322
+ const sessionReq = requirements.addRequirement({
323
+ id: 'REQ-002',
324
+ text: 'While a session is active, the system shall maintain user state',
325
+ priority: 'medium'
326
+ });
327
+
328
+ // Get all requirements
329
+ const allReqs = requirements.getAllRequirements();
330
+ console.log(`Total requirements: ${allReqs.length}`);
331
+ ```
332
+
333
+ ### Phase 2: Design (C4 + ADR)
334
+
335
+ #### C4 Model
336
+
337
+ Design at 4 levels:
338
+
339
+ ```typescript
340
+ const design = createDesignService();
341
+
342
+ // Level 1: Context
343
+ const system = design.createContainer({
344
+ id: 'SYS-001',
345
+ name: 'MUSUBIX System',
346
+ type: 'system',
347
+ description: 'Neuro-Symbolic AI-based SDD platform'
348
+ });
349
+
350
+ // Level 2: Container
351
+ const apiServer = design.createContainer({
352
+ id: 'CON-001',
353
+ name: 'API Server',
354
+ type: 'container',
355
+ parent: 'SYS-001',
356
+ technology: 'Node.js + Express'
357
+ });
358
+
359
+ // Level 3: Component
360
+ const authModule = design.createComponent({
361
+ id: 'COMP-001',
362
+ name: 'Authentication Module',
363
+ type: 'component',
364
+ parent: 'CON-001',
365
+ requirements: ['REQ-001']
366
+ });
367
+ ```
368
+
369
+ #### ADR (Architecture Decision Record)
370
+
371
+ Document technical decisions:
372
+
373
+ ```typescript
374
+ const adr = design.createADR({
375
+ id: 'ADR-001',
376
+ title: 'JWT for Authentication',
377
+ context: 'Need to select stateless authentication method',
378
+ decision: 'Use JWT',
379
+ status: 'accepted',
380
+ consequences: [
381
+ 'Positive: Stateless, scalable',
382
+ 'Negative: Token revocation requires additional implementation'
383
+ ],
384
+ relatedRequirements: ['REQ-001']
385
+ });
386
+ ```
387
+
388
+ ### Phase 3: Tasks
389
+
390
+ Break down requirements and designs into implementation tasks:
391
+
392
+ ```typescript
393
+ const tasks = createTaskService();
394
+
395
+ // Create task linked to requirements
396
+ const task = tasks.createTask({
397
+ id: 'TASK-001',
398
+ title: 'Implement JWT authentication',
399
+ description: 'Implement JWT-based authentication module',
400
+ requirements: ['REQ-001'],
401
+ designs: ['COMP-001'],
402
+ estimatedHours: 4,
403
+ acceptanceCriteria: [
404
+ 'Login API endpoint completed',
405
+ 'JWT generation/validation tests passing'
406
+ ]
407
+ });
408
+
409
+ // Track progress
410
+ tasks.updateProgress('TASK-001', {
411
+ status: 'in-progress',
412
+ completedItems: ['Login API endpoint completed']
413
+ });
414
+ ```
415
+
416
+ ### Phase 4: Validation
417
+
418
+ Check compliance with 9 Constitutional Articles:
419
+
420
+ ```typescript
421
+ const validation = createValidationService();
422
+
423
+ // Full validation
424
+ const result = validation.validateAll({
425
+ requirements: requirements.getAllRequirements(),
426
+ designs: design.getAllDesigns(),
427
+ tasks: tasks.getAllTasks()
428
+ });
429
+
430
+ // Check results
431
+ console.log('Compliant:', result.compliant);
432
+ console.log('Score:', result.score);
433
+
434
+ // Check details by Article
435
+ result.articleResults.forEach(article => {
436
+ console.log(`Article ${article.number}: ${article.passed ? '✓' : '✗'}`);
437
+ if (!article.passed) {
438
+ console.log(' Issues:', article.issues);
439
+ }
440
+ });
441
+ ```
442
+
443
+ ---
444
+
445
+ ## Self-Learning System
446
+
447
+ MUSUBIX includes a self-learning system that improves through feedback collection and pattern extraction.
448
+
449
+ ### Learning CLI Commands
450
+
451
+ ```bash
452
+ # View learning status dashboard
453
+ musubix learn status
454
+
455
+ # Record feedback on an artifact
456
+ musubix learn feedback <artifact-id> --type accept|reject|modify --artifact-type requirement|design|code|test --reason "explanation"
457
+
458
+ # List learned patterns
459
+ musubix learn patterns
460
+
461
+ # Manually register a pattern
462
+ musubix learn add-pattern <name> --category code|design|requirement|test --action prefer|avoid --description "pattern description"
463
+
464
+ # Remove a pattern
465
+ musubix learn remove-pattern <pattern-id>
466
+
467
+ # Get context-based recommendations
468
+ musubix learn recommend --artifact-type code
469
+
470
+ # Apply decay to unused patterns
471
+ musubix learn decay
472
+
473
+ # Export learning data (v1.4.0 enhanced)
474
+ musubix learn export --output learning-data.json
475
+ # Options:
476
+ # --privacy-filter Remove sensitive data (API keys, passwords)
477
+ # --patterns-only Export patterns only (exclude feedback)
478
+ # --feedback-only Export feedback only (exclude patterns)
479
+ # --min-confidence <n> Minimum confidence threshold (0-1)
480
+
481
+ # Import learning data with merge strategy (v1.4.0 enhanced)
482
+ musubix learn import learning-data.json
483
+ # Options:
484
+ # --merge-strategy <skip|overwrite|merge> How to handle duplicates
485
+ # --dry-run Preview without applying
486
+ # --patterns-only Import patterns only
487
+ # --feedback-only Import feedback only
488
+ ```
489
+
490
+ ### Programmatic Usage
491
+
492
+ ```typescript
493
+ import { createLearningEngine } from '@nahisaho/musubix-core';
494
+
495
+ const learningEngine = createLearningEngine();
496
+
497
+ // Record feedback
498
+ await learningEngine.recordFeedback({
499
+ type: 'accept',
500
+ artifactType: 'code',
501
+ artifactId: 'AUTH-001',
502
+ reason: 'Good implementation of JWT authentication'
503
+ });
504
+
505
+ // Get recommendations
506
+ const recommendations = await learningEngine.getRecommendations({
507
+ artifactType: 'code',
508
+ context: 'authentication'
509
+ });
510
+
511
+ // Export learning data
512
+ const data = await learningEngine.exportData();
513
+ ```
514
+
515
+ ### Pattern Extraction
516
+
517
+ Patterns are automatically extracted when similar feedback is recorded multiple times (default threshold: 3).
518
+
519
+ ```typescript
520
+ // Patterns gain confidence with each occurrence
521
+ // High-confidence patterns (≥70%) appear in recommendations
522
+ const stats = await learningEngine.getStats();
523
+ console.log(`Total patterns: ${stats.totalPatterns}`);
524
+ console.log(`High confidence patterns: ${stats.highConfidencePatterns}`);
525
+ ```
526
+
527
+ ---
528
+
529
+ ## C4 Code Generation
530
+
531
+ Generate TypeScript skeleton code from C4 design documents.
532
+
533
+ ### CLI Usage
534
+
535
+ ```bash
536
+ # Generate code from C4 design
537
+ musubix codegen generate design-c4.md --output src/
538
+
539
+ # With specific language
540
+ musubix codegen generate design-c4.md --output src/ --language typescript
541
+ ```
542
+
543
+ ### Generated Code Structure
544
+
545
+ From a C4 design with components like:
546
+
547
+ | ID | Name | Type | Description |
548
+ |----|------|------|-------------|
549
+ | auth | AuthService | component | Authentication |
550
+
551
+ MUSUBIX generates:
552
+
553
+ ```typescript
554
+ // auth-service.ts
555
+ export interface IAuthService {
556
+ authenticate(credentials: { username: string; password: string }): Promise<{ token: string }>;
557
+ validate(token: string): Promise<boolean>;
558
+ }
559
+
560
+ export class AuthService implements IAuthService {
561
+ async authenticate(credentials: { username: string; password: string }): Promise<{ token: string }> {
562
+ // TODO: Implement authenticate
563
+ throw new Error('Not implemented');
564
+ }
565
+
566
+ async validate(token: string): Promise<boolean> {
567
+ // TODO: Implement validate
568
+ throw new Error('Not implemented');
569
+ }
570
+ }
571
+
572
+ export function createAuthService(): IAuthService {
573
+ return new AuthService();
574
+ }
575
+ ```
576
+
577
+ ---
578
+
579
+ ## Interactive REPL Mode
580
+
581
+ *(New in v1.5.0, Enhanced in v1.6.0)*
582
+
583
+ MUSUBIX provides an interactive REPL (Read-Eval-Print-Loop) shell for real-time command execution and exploration.
584
+
585
+ ### Starting REPL
586
+
587
+ ```bash
588
+ # Start interactive REPL
589
+ musubix repl
590
+
591
+ # With custom history file
592
+ musubix repl --history ~/.musubix-repl-history
593
+
594
+ # Without colors
595
+ musubix repl --no-color
596
+ ```
597
+
598
+ ### REPL Features
599
+
600
+ | Feature | Description |
601
+ |---------|-------------|
602
+ | Command completion | TAB completion for commands, options |
603
+ | History navigation | UP/DOWN arrows, history search |
604
+ | Session variables | `$name=value` to set, `$name` to reference |
605
+ | Output formatting | JSON, YAML, Table auto-formatting |
606
+ | CLI integration | Execute any CLI command directly |
607
+
608
+ ### Basic Usage
609
+
610
+ ```bash
611
+ musubix> help # Show all commands
612
+ musubix> help requirements # Show command details
613
+ musubix> requirements analyze input.md # Execute CLI command
614
+ musubix> $project=my-app # Set session variable
615
+ musubix> design generate $project # Use variable in command
616
+ musubix> history # Show command history
617
+ musubix> exit # Exit REPL
618
+ ```
619
+
620
+ ### Session Variables
621
+
622
+ ```bash
623
+ # Set variables
624
+ musubix> $req=REQ-001
625
+ musubix> $file=./docs/requirements.md
626
+
627
+ # Use in commands
628
+ musubix> requirements validate $file
629
+ musubix> trace impact $req
630
+
631
+ # Special variable: $_ holds last result
632
+ musubix> requirements analyze input.md
633
+ musubix> $_ # Access last result
634
+ ```
635
+
636
+ ### Output Formats
637
+
638
+ ```bash
639
+ # Auto-detect best format (default)
640
+ musubix> learn status
641
+
642
+ # Force JSON output
643
+ musubix> set format json
644
+ musubix> learn patterns
645
+
646
+ # Force YAML output
647
+ musubix> set format yaml
648
+
649
+ # Force table output
650
+ musubix> set format table
651
+ ```
652
+
653
+ ### History Management
654
+
655
+ ```bash
656
+ # Show recent commands
657
+ musubix> history
658
+
659
+ # Search history (Ctrl+R style)
660
+ musubix> history search requirements
661
+
662
+ # Clear history
663
+ musubix> history clear
664
+ ```
665
+
666
+ ### REPL Components
667
+
668
+ | Component | Purpose |
669
+ |-----------|---------|
670
+ | `ReplEngine` | Main REPL controller |
671
+ | `CommandCompleter` | TAB completion provider |
672
+ | `HistoryManager` | Command history persistence |
673
+ | `SessionState` | Variable storage |
674
+ | `OutputFormatter` | JSON/YAML/Table output |
675
+ | `PromptRenderer` | Dynamic prompt display |
676
+
677
+ ---
678
+
679
+ ## YATA Local
680
+
681
+ *(New in v1.6.3)*
682
+
683
+ YATA Local provides a high-performance, SQLite-based local knowledge graph with built-in inference capabilities. Designed for single-user, offline scenarios where data sovereignty and speed are critical.
684
+
685
+ ### Features
686
+
687
+ | Feature | Description |
688
+ |---------|-------------|
689
+ | **SQLite Storage** | WAL mode for concurrent reads, single-writer |
690
+ | **Full-Text Search** | FTS5-based triple search |
691
+ | **Graph Traversal** | BFS/DFS with depth control |
692
+ | **Inference Engine** | 4 OWL-lite rules (transitivity, symmetry, inverse, domain/range) |
693
+ | **Constraints** | 4 validation rules (cardinality, disjoint, unique, required) |
694
+ | **ACID Transactions** | Full transaction support |
695
+
696
+ ### Installation
697
+
698
+ ```bash
699
+ npm install @nahisaho/yata-local
700
+ ```
701
+
702
+ ### Quick Start
703
+
704
+ ```typescript
705
+ import { YataLocal } from '@nahisaho/yata-local';
706
+
707
+ // Initialize with default config
708
+ const yata = new YataLocal('./knowledge.db');
709
+ await yata.initialize();
710
+
711
+ // Add triples
712
+ await yata.addTriple({
713
+ subject: 'Person:john',
714
+ predicate: 'hasParent',
715
+ object: 'Person:mary'
716
+ });
717
+
718
+ // Query triples
719
+ const results = await yata.query({
720
+ subject: 'Person:john',
721
+ predicate: 'hasParent'
722
+ });
723
+
724
+ // Full-text search
725
+ const searchResults = await yata.search('john parent');
726
+
727
+ // Graph traversal (BFS)
728
+ const ancestors = await yata.traverse('Person:john', 'hasParent', {
729
+ direction: 'outgoing',
730
+ maxDepth: 5,
731
+ algorithm: 'bfs'
732
+ });
733
+
734
+ // Clean up
735
+ await yata.close();
736
+ ```
737
+
738
+ ### Inference Engine
739
+
740
+ YATA Local supports four OWL-lite inference rules:
741
+
742
+ | Rule | Description | Example |
743
+ |------|-------------|---------|
744
+ | **Transitivity** | If A→B and B→C then A→C | hasAncestor is transitive |
745
+ | **Symmetry** | If A→B then B→A | friendOf is symmetric |
746
+ | **Inverse** | If A→B via P then B→A via P⁻¹ | hasChild ↔ hasParent |
747
+ | **Domain/Range** | Type inference from predicate | hasAge implies Person |
748
+
749
+ ```typescript
750
+ // Run inference
751
+ const inferred = await yata.infer();
752
+ console.log(`Inferred ${inferred.length} new triples`);
753
+ ```
754
+
755
+ ### Constraints
756
+
757
+ ```typescript
758
+ // Define constraints
759
+ await yata.addConstraint({
760
+ type: 'cardinality',
761
+ predicate: 'hasSpouse',
762
+ max: 1
763
+ });
764
+
765
+ // Validate
766
+ const violations = await yata.validate();
767
+ if (violations.length > 0) {
768
+ console.error('Constraint violations:', violations);
769
+ }
770
+ ```
771
+
772
+ ### Configuration Options
773
+
774
+ ```typescript
775
+ const yata = new YataLocal('./knowledge.db', {
776
+ // WAL mode for better concurrency (default: true)
777
+ walMode: true,
778
+
779
+ // Enable FTS5 search (default: true)
780
+ enableSearch: true,
781
+
782
+ // Auto-run inference on writes (default: false)
783
+ autoInfer: false,
784
+
785
+ // Journal mode (default: 'wal')
786
+ journalMode: 'wal'
787
+ });
788
+ ```
789
+
790
+ ---
791
+
792
+ ## YATA Global
793
+
794
+ *(New in v1.6.3)*
795
+
796
+ YATA Global is a distributed knowledge graph platform for team collaboration. It provides REST API access to shared knowledge graphs with offline support and intelligent synchronization.
797
+
798
+ ### Features
799
+
800
+ | Feature | Description |
801
+ |---------|-------------|
802
+ | **REST API** | Full CRUD operations via HTTP |
803
+ | **Offline Cache** | SQLite-based local cache |
804
+ | **Sync Engine** | Push/Pull with conflict resolution |
805
+ | **Conflict Resolution** | Last-write-wins or custom strategies |
806
+ | **Authentication** | API key-based auth |
807
+ | **Batch Operations** | Bulk triple operations |
808
+
809
+ ### Installation
810
+
811
+ ```bash
812
+ npm install @nahisaho/yata-global
813
+ ```
814
+
815
+ ### Quick Start
816
+
817
+ ```typescript
818
+ import { YataGlobal } from '@nahisaho/yata-global';
819
+
820
+ // Initialize client
821
+ const yata = new YataGlobal({
822
+ endpoint: 'https://yata.example.com/api',
823
+ apiKey: 'your-api-key',
824
+ graphId: 'project-knowledge'
825
+ });
826
+
827
+ await yata.initialize();
828
+
829
+ // Add triples (batched)
830
+ await yata.addTriples([
831
+ { subject: 'Task:001', predicate: 'assignedTo', object: 'User:alice' },
832
+ { subject: 'Task:001', predicate: 'status', object: 'in-progress' }
833
+ ]);
834
+
835
+ // Query with filters
836
+ const tasks = await yata.query({
837
+ predicate: 'assignedTo',
838
+ object: 'User:alice'
839
+ });
840
+
841
+ // Clean up
842
+ await yata.close();
843
+ ```
844
+
845
+ ### Offline Support
846
+
847
+ YATA Global supports offline-first operation with automatic synchronization:
848
+
849
+ ```typescript
850
+ const yata = new YataGlobal({
851
+ endpoint: 'https://yata.example.com/api',
852
+ apiKey: 'your-api-key',
853
+ graphId: 'project-knowledge',
854
+
855
+ // Offline configuration
856
+ offlineMode: true,
857
+ cachePath: './yata-cache.db',
858
+ syncInterval: 60000 // Auto-sync every 60 seconds
859
+ });
860
+
861
+ // Works offline - cached locally
862
+ await yata.addTriple({
863
+ subject: 'Note:001',
864
+ predicate: 'content',
865
+ object: 'Important meeting notes'
866
+ });
867
+
868
+ // Manual sync when online
869
+ await yata.sync();
870
+ ```
871
+
872
+ ### Conflict Resolution
873
+
874
+ ```typescript
875
+ const yata = new YataGlobal({
876
+ // ... other options
877
+
878
+ conflictStrategy: 'last-write-wins', // Default
879
+ // or: 'server-wins', 'client-wins', 'manual'
880
+
881
+ onConflict: async (local, remote) => {
882
+ // Custom resolution logic
883
+ console.log('Conflict detected:', local, remote);
884
+ return remote; // Prefer remote version
885
+ }
886
+ });
887
+ ```
888
+
889
+ ### Sync Status
890
+
891
+ ```typescript
892
+ // Check sync status
893
+ const status = await yata.getSyncStatus();
894
+ console.log(`Pending changes: ${status.pendingPush}`);
895
+ console.log(`Last sync: ${status.lastSyncAt}`);
896
+
897
+ // Force full sync
898
+ await yata.sync({ force: true });
899
+ ```
900
+
901
+ ### When to Use YATA Local vs YATA Global
902
+
903
+ | Use Case | Recommended |
904
+ |----------|-------------|
905
+ | Personal knowledge base | YATA Local |
906
+ | Single-user application | YATA Local |
907
+ | Privacy-sensitive data | YATA Local |
908
+ | Team collaboration | YATA Global |
909
+ | Cross-device access | YATA Global |
910
+ | Shared project knowledge | YATA Global |
911
+ | Offline-first with sync | YATA Global |
912
+
913
+ ---
914
+
915
+ ## KGPR - Knowledge Graph Pull Request
916
+
917
+ *(v1.6.4)*
918
+
919
+ KGPR (Knowledge Graph Pull Request) enables safe sharing of knowledge graphs from YATA Local to YATA Global using a GitHub PR-like workflow.
920
+
921
+ ### Workflow
922
+
923
+ ```
924
+ ┌─────────────┐ ┌──────────────┐ ┌───────────────┐
925
+ │ YATA Local │ ──► │ KGPR (Draft) │ ──► │ YATA Global │
926
+ │ (Local KG) │ │ (Extract) │ │ (Review/Merge)│
927
+ └─────────────┘ └──────────────┘ └───────────────┘
928
+
929
+ Status Flow:
930
+ draft → open → reviewing → approved/changes_requested → merged/closed
931
+ ```
932
+
933
+ ### Privacy Levels
934
+
935
+ | Level | Filtered Content |
936
+ |-------|------------------|
937
+ | `strict` | File paths, URLs, credentials, all metadata |
938
+ | `moderate` | File paths, URLs, credentials |
939
+ | `none` | No filtering |
940
+
941
+ ### CLI Commands
942
+
943
+ ```bash
944
+ # Create a KGPR
945
+ musubix kgpr create -t "Add authentication patterns"
946
+
947
+ # Preview diff before creating
948
+ musubix kgpr diff --namespace myproject --privacy moderate
949
+
950
+ # List KGPRs
951
+ musubix kgpr list
952
+
953
+ # Submit KGPR for review
954
+ musubix kgpr submit <id>
955
+
956
+ # Show KGPR details
957
+ musubix kgpr show <id>
958
+
959
+ # Close without merging
960
+ musubix kgpr close <id>
961
+ ```
962
+
963
+ ### MCP Tools
964
+
965
+ | Tool | Description |
966
+ |------|-------------|
967
+ | `kgpr_create` | Create KGPR from local knowledge graph |
968
+ | `kgpr_diff` | Preview diff before creating KGPR |
969
+ | `kgpr_list` | List all KGPRs |
970
+ | `kgpr_submit` | Submit KGPR for review |
971
+ | `kgpr_review` | Review KGPR (approve/changes_requested/commented) |
972
+
973
+ ### Example Usage
974
+
975
+ ```bash
976
+ # 1. Preview what will be shared
977
+ musubix kgpr diff --privacy strict
978
+
979
+ # 2. Create KGPR with description
980
+ musubix kgpr create -t "Share React patterns" -d "Learned patterns from project-x"
981
+
982
+ # 3. Review the KGPR
983
+ musubix kgpr show KGPR-001
984
+
985
+ # 4. Submit for review
986
+ musubix kgpr submit KGPR-001
987
+ ```
988
+
989
+ ---
990
+
991
+ ## YATA Platform Enhancements
992
+
993
+ *(v1.7.0)*
994
+
995
+ Version 1.7.0 introduces significant enhancements to the YATA platform with 5 major features.
996
+
997
+ ### Phase 1: Index Optimization
998
+
999
+ Optimized query performance for YATA Local with composite indexes.
1000
+
1001
+ ```typescript
1002
+ import { IndexOptimizer } from '@nahisaho/yata-local';
1003
+
1004
+ const optimizer = new IndexOptimizer(database);
1005
+
1006
+ // Analyze and create optimal indexes
1007
+ const analysis = await optimizer.analyzeQueryPatterns();
1008
+ const created = await optimizer.createOptimalIndexes();
1009
+
1010
+ // Check index health
1011
+ const health = await optimizer.checkIndexHealth();
1012
+ ```
1013
+
1014
+ **Key Features:**
1015
+ - Composite index creation for common query patterns
1016
+ - Index health monitoring with fragmentation detection
1017
+ - Automatic optimization recommendations
1018
+
1019
+ ### Phase 2: Enhanced Export Pipeline
1020
+
1021
+ Powerful export capabilities with incremental export and multiple formats.
1022
+
1023
+ ```typescript
1024
+ import { ExportPipeline } from '@nahisaho/yata-local';
1025
+
1026
+ const pipeline = new ExportPipeline(database);
1027
+
1028
+ // Full export
1029
+ const fullData = await pipeline.exportFull({ namespace: 'myproject' });
1030
+
1031
+ // Incremental export (changes since last export)
1032
+ const changes = await pipeline.exportIncremental({
1033
+ since: lastExportTimestamp,
1034
+ format: 'json'
1035
+ });
1036
+
1037
+ // Export with transformation
1038
+ const transformed = await pipeline.exportWithTransform({
1039
+ format: 'rdf',
1040
+ includeMetadata: true
1041
+ });
1042
+ ```
1043
+
1044
+ **Supported Formats:**
1045
+ - JSON (default)
1046
+ - RDF/Turtle
1047
+ - N-Triples
1048
+ - Custom transformers
1049
+
1050
+ ### Phase 3: Global Sync Integration
1051
+
1052
+ Seamless synchronization between YATA Local and YATA Global.
1053
+
1054
+ ```typescript
1055
+ import { GlobalSyncClient, SyncEngine } from '@nahisaho/yata-global';
1056
+
1057
+ const client = new GlobalSyncClient({
1058
+ endpoint: 'https://yata-global.example.com',
1059
+ offlineMode: true
1060
+ });
1061
+
1062
+ // Initialize sync
1063
+ await client.initialize();
1064
+
1065
+ // Push local changes
1066
+ const syncResult = await client.sync({
1067
+ namespace: 'myproject',
1068
+ direction: 'push'
1069
+ });
1070
+
1071
+ // Pull updates from global
1072
+ await client.sync({
1073
+ namespace: 'shared-patterns',
1074
+ direction: 'pull'
1075
+ });
1076
+ ```
1077
+
1078
+ **Features:**
1079
+ - Offline-first with automatic sync
1080
+ - Conflict resolution strategies
1081
+ - Selective namespace sync
1082
+ - Framework pattern repository
1083
+
1084
+ ### Phase 4: Code Generator Enhancement
1085
+
1086
+ Advanced code generation from design documents.
1087
+
1088
+ ```typescript
1089
+ import { CodeGenerator } from '@nahisaho/yata-local';
1090
+
1091
+ const generator = new CodeGenerator({
1092
+ language: 'typescript',
1093
+ outputDir: './src/generated'
1094
+ });
1095
+
1096
+ // Generate from C4 design
1097
+ const result = await generator.generateFromC4(designDocument);
1098
+
1099
+ // Generate with custom templates
1100
+ await generator.generate({
1101
+ template: 'repository-pattern',
1102
+ context: { entityName: 'User' }
1103
+ });
1104
+ ```
1105
+
1106
+ **Supported Patterns:**
1107
+ - Repository Pattern
1108
+ - Service Layer
1109
+ - Factory Pattern
1110
+ - Domain Events
1111
+ - Value Objects
1112
+
1113
+ ### Phase 5: YATA UI (Web Visualization)
1114
+
1115
+ Web-based visualization and management interface for knowledge graphs.
1116
+
1117
+ ```typescript
1118
+ import { YataUIServer, createYataUIServer } from '@nahisaho/yata-ui';
1119
+
1120
+ // Create and start server
1121
+ const server = createYataUIServer({
1122
+ port: 3000,
1123
+ enableRealtime: true
1124
+ });
1125
+
1126
+ // Set data provider
1127
+ server.setDataProvider(async () => ({
1128
+ nodes: await getEntities(),
1129
+ edges: await getRelationships()
1130
+ }));
1131
+
1132
+ await server.start();
1133
+ console.log(`UI available at ${server.getUrl()}`);
1134
+ ```
1135
+
1136
+ **UI Features:**
1137
+ - Interactive graph visualization
1138
+ - Real-time updates via WebSocket
1139
+ - Namespace filtering
1140
+ - Entity/Relationship editing
1141
+ - Export/Import functionality
1142
+
1143
+ ### v1.7.0 Package Summary
1144
+
1145
+ | Package | Description |
1146
+ |---------|-------------|
1147
+ | `@nahisaho/yata-local` | IndexOptimizer, ExportPipeline, CodeGenerator |
1148
+ | `@nahisaho/yata-global` | GlobalSyncClient, SyncEngine, CacheManager |
1149
+ | `@nahisaho/yata-ui` | YataUIServer, Graph visualization |
1150
+
1151
+ ---
1152
+
1153
+ ## Formal Verification
1154
+
1155
+ *(v1.7.5)*
1156
+
1157
+ The `@nahisaho/musubix-formal-verify` package provides formal verification capabilities using the Z3 SMT solver.
1158
+
1159
+ ### Installation
1160
+
1161
+ ```bash
1162
+ npm install @nahisaho/musubix-formal-verify
1163
+ # Optional: Install z3-solver for WebAssembly support
1164
+ npm install z3-solver
1165
+ ```
1166
+
1167
+ ### Z3 SMT Solver Integration
1168
+
1169
+ ```typescript
1170
+ import { Z3Adapter, PreconditionVerifier, PostconditionVerifier } from '@nahisaho/musubix-formal-verify';
1171
+
1172
+ // Create Z3 adapter (auto-selects backend)
1173
+ const z3 = await Z3Adapter.create();
1174
+
1175
+ // Precondition verification
1176
+ const preVerifier = new PreconditionVerifier(z3);
1177
+ const result = await preVerifier.verify({
1178
+ condition: { expression: 'amount > 0 && balance >= amount', format: 'javascript' },
1179
+ variables: [
1180
+ { name: 'amount', type: 'Int' },
1181
+ { name: 'balance', type: 'Int' },
1182
+ ],
1183
+ });
1184
+
1185
+ console.log(result.status); // 'valid' | 'invalid' | 'unknown' | 'error'
1186
+ ```
1187
+
1188
+ ### Hoare Triple Verification
1189
+
1190
+ ```typescript
1191
+ // Verify {P} C {Q}
1192
+ const postVerifier = new PostconditionVerifier(z3);
1193
+ const hoareResult = await postVerifier.verify({
1194
+ precondition: { expression: 'balance >= amount', format: 'javascript' },
1195
+ postcondition: { expression: 'balance_new == balance - amount', format: 'javascript' },
1196
+ preVariables: [{ name: 'balance', type: 'Int' }, { name: 'amount', type: 'Int' }],
1197
+ postVariables: [{ name: 'balance_new', type: 'Int' }],
1198
+ transition: 'balance_new == balance - amount',
1199
+ });
1200
+ ```
1201
+
1202
+ ### EARS to SMT Conversion
1203
+
1204
+ ```typescript
1205
+ import { EarsToSmtConverter } from '@nahisaho/musubix-formal-verify';
1206
+
1207
+ const converter = new EarsToSmtConverter();
1208
+
1209
+ // Convert EARS requirements to SMT-LIB2
1210
+ const results = converter.convertMultiple([
1211
+ 'THE system SHALL validate inputs', // ubiquitous
1212
+ 'WHEN error, THE system SHALL notify user', // event-driven
1213
+ 'WHILE busy, THE system SHALL queue requests', // state-driven
1214
+ 'THE system SHALL NOT expose secrets', // unwanted
1215
+ 'IF admin, THEN THE system SHALL allow edit', // optional
1216
+ ]);
1217
+
1218
+ results.forEach(r => {
1219
+ console.log(`Pattern: ${r.formula?.metadata.earsPattern.type}`);
1220
+ console.log(`SMT: ${r.formula?.smtLib2}`);
1221
+ });
1222
+ ```
1223
+
1224
+ ### Traceability Database
1225
+
1226
+ ```typescript
1227
+ import { TraceabilityDB, ImpactAnalyzer } from '@nahisaho/musubix-formal-verify';
1228
+
1229
+ // Create SQLite-based traceability database
1230
+ const db = new TraceabilityDB('./trace.db');
1231
+
1232
+ // Add nodes
1233
+ await db.addNode({ id: 'REQ-001', type: 'requirement', title: 'User Auth' });
1234
+ await db.addNode({ id: 'DES-001', type: 'design', title: 'AuthService' });
1235
+ await db.addNode({ id: 'CODE-001', type: 'code', title: 'auth.ts' });
1236
+
1237
+ // Add traceability links
1238
+ await db.addLink({ source: 'DES-001', target: 'REQ-001', type: 'satisfies' });
1239
+ await db.addLink({ source: 'CODE-001', target: 'DES-001', type: 'implements' });
1240
+
1241
+ // Impact analysis
1242
+ const analyzer = new ImpactAnalyzer(db);
1243
+ const impact = await analyzer.analyze('REQ-001');
1244
+ console.log(`Impacted nodes: ${impact.totalImpacted}`);
1245
+ ```
1246
+
1247
+ ### v1.7.5 Package Summary
1248
+
1249
+ | Package | Description |
1250
+ |---------|-------------|
1251
+ | `@nahisaho/musubix-formal-verify` | Z3 integration, Hoare verification, EARS→SMT, TraceabilityDB |
1252
+
1253
+ ### Supported Variable Types
1254
+
1255
+ | Type | Description |
1256
+ |------|-------------|
1257
+ | `Int` | Integer values |
1258
+ | `Real` | Real numbers |
1259
+ | `Bool` | Boolean values |
1260
+ | `String` | String values |
1261
+ | `Array` | Array types |
1262
+ | `BitVec` | Bit vectors |
1263
+
1264
+ ---
1265
+
1266
+ ## Security Analysis
1267
+
1268
+ *(v1.8.0)*
1269
+
1270
+ The `@nahisaho/musubix-security` package provides comprehensive security analysis capabilities for TypeScript/JavaScript projects.
1271
+
1272
+ ### Installation
1273
+
1274
+ ```bash
1275
+ npm install @nahisaho/musubix-security
1276
+ ```
1277
+
1278
+ ### Vulnerability Scanning
1279
+
1280
+ Detects OWASP Top 10 and CWE Top 25 vulnerabilities using AST analysis:
1281
+
1282
+ ```typescript
1283
+ import { VulnerabilityScanner, createSecurityService } from '@nahisaho/musubix-security';
1284
+
1285
+ // Scan a single file
1286
+ const scanner = new VulnerabilityScanner();
1287
+ const vulnerabilities = scanner.scanFile('src/api.ts');
1288
+
1289
+ // Scan a directory
1290
+ const result = await scanner.scanDirectory('./src');
1291
+ console.log(`Found ${result.vulnerabilities.length} vulnerabilities`);
1292
+ console.log(`Scanned ${result.scannedFiles} files`);
1293
+ ```
1294
+
1295
+ ### Detected Vulnerabilities
1296
+
1297
+ | Category | CWE | Severity |
1298
+ |----------|-----|----------|
1299
+ | SQL Injection | CWE-89 | Critical |
1300
+ | Command Injection | CWE-78 | Critical |
1301
+ | XSS | CWE-79 | High |
1302
+ | Path Traversal | CWE-22 | High |
1303
+ | Code Injection | CWE-94 | Critical |
1304
+ | NoSQL Injection | CWE-943 | High |
1305
+
1306
+ ### Secret Detection
1307
+
1308
+ Detects hardcoded credentials and sensitive information:
1309
+
1310
+ ```typescript
1311
+ import { SecretDetector } from '@nahisaho/musubix-security';
1312
+
1313
+ const detector = new SecretDetector();
1314
+ const secrets = detector.scanContent(content, 'config.ts');
1315
+ const result = await detector.scan('./src');
1316
+
1317
+ console.log(`Found ${result.summary.total} secrets`);
1318
+ ```
1319
+
1320
+ ### Detected Secret Types
1321
+
1322
+ | Type | Pattern |
1323
+ |------|--------|
1324
+ | AWS Access Key | `AKIA...` |
1325
+ | AWS Secret Key | 40-char base64 |
1326
+ | GitHub Token | `ghp_*`, `gho_*`, `ghu_*` |
1327
+ | Private Key | PEM format |
1328
+ | Database URL | `postgres://`, `mongodb://` |
1329
+ | JWT Secret | JWT signing secrets |
1330
+ | Stripe Key | `sk_live_*`, `sk_test_*` |
1331
+
1332
+ ### Taint Analysis
1333
+
1334
+ Tracks data flow from user input (sources) to dangerous functions (sinks):
1335
+
1336
+ ```typescript
1337
+ import { TaintAnalyzer } from '@nahisaho/musubix-security';
1338
+
1339
+ const analyzer = new TaintAnalyzer();
1340
+ const result = analyzer.analyze('./src');
1341
+
1342
+ console.log(`Sources: ${result.sources.length}`);
1343
+ console.log(`Sinks: ${result.sinks.length}`);
1344
+ console.log(`Taint paths: ${result.paths.length}`);
1345
+ ```
1346
+
1347
+ ### Dependency Auditing
1348
+
1349
+ Integrates with npm audit to detect vulnerable dependencies:
1350
+
1351
+ ```typescript
1352
+ import { DependencyAuditor } from '@nahisaho/musubix-security';
1353
+
1354
+ const auditor = new DependencyAuditor();
1355
+ const result = await auditor.audit('./project');
1356
+
1357
+ console.log(`Critical: ${result.summary.critical}`);
1358
+ console.log(`High: ${result.summary.high}`);
1359
+ ```
1360
+
1361
+ ### Integrated Security Service
1362
+
1363
+ Combines all security analysis features:
1364
+
1365
+ ```typescript
1366
+ import { createSecurityService } from '@nahisaho/musubix-security';
1367
+
1368
+ const service = createSecurityService();
1369
+
1370
+ // Full security scan
1371
+ const result = await service.scan({
1372
+ target: './src',
1373
+ vulnerabilities: true,
1374
+ taint: true,
1375
+ secrets: true,
1376
+ dependencies: true,
1377
+ generateFixes: true,
1378
+ });
1379
+
1380
+ console.log(`Total vulnerabilities: ${result.summary.totalVulnerabilities}`);
1381
+ console.log(`Total secrets: ${result.summary.totalSecrets}`);
1382
+ console.log(`Fixes generated: ${result.summary.fixesGenerated}`);
1383
+ ```
1384
+
1385
+ ### Report Generation
1386
+
1387
+ Generate reports in multiple formats:
1388
+
1389
+ ```typescript
1390
+ // SARIF format (GitHub Code Scanning compatible)
1391
+ const sarifReport = await service.generateReport(result, 'sarif');
1392
+
1393
+ // Markdown format
1394
+ const mdReport = await service.generateReport(result, 'markdown');
1395
+
1396
+ // HTML format
1397
+ const htmlReport = await service.generateReport(result, 'html');
1398
+ ```
1399
+
1400
+ ### CLI Usage
1401
+
1402
+ ```bash
1403
+ # Full security scan
1404
+ npx musubix-security scan ./src
1405
+
1406
+ # Vulnerability scan only
1407
+ npx musubix-security scan ./src --vulnerabilities-only
1408
+
1409
+ # Secret detection
1410
+ npx musubix-security secrets ./src
1411
+
1412
+ # Taint analysis
1413
+ npx musubix-security taint ./src
1414
+
1415
+ # Dependency audit
1416
+ npx musubix-security audit ./project
1417
+
1418
+ # Generate SARIF report
1419
+ npx musubix-security scan ./src --format sarif --output report.sarif
1420
+ ```
1421
+
1422
+ ### v1.8.0 Package Summary
1423
+
1424
+ | Package | Description |
1425
+ |---------|-------------|
1426
+ | `@nahisaho/musubix-security` | Vulnerability scanning, secret detection, taint analysis, dependency auditing |
1427
+
1428
+ ---
1429
+
1430
+ ## DFG/CFG Extraction
1431
+
1432
+ *(v2.0.0)*
1433
+
1434
+ The `@nahisaho/musubix-dfg` package provides Data Flow Graph (DFG) and Control Flow Graph (CFG) extraction for TypeScript and JavaScript code analysis.
1435
+
1436
+ ### Installation
1437
+
1438
+ ```bash
1439
+ npm install @nahisaho/musubix-dfg
1440
+ ```
1441
+
1442
+ ### DFG Extraction
1443
+
1444
+ Extract data flow graphs from source code:
1445
+
1446
+ ```typescript
1447
+ import { extractDFG, DFGExtractor } from '@nahisaho/musubix-dfg';
1448
+
1449
+ // Simple extraction
1450
+ const dfg = extractDFG(sourceCode, 'typescript');
1451
+
1452
+ // With configuration
1453
+ const extractor = new DFGExtractor({
1454
+ includeImplicitFlows: true,
1455
+ trackConstants: true,
1456
+ });
1457
+ const result = extractor.extract(sourceCode);
1458
+
1459
+ console.log(`Nodes: ${result.nodes.length}`);
1460
+ console.log(`Edges: ${result.edges.length}`);
1461
+ ```
1462
+
1463
+ ### CFG Extraction
1464
+
1465
+ Extract control flow graphs:
1466
+
1467
+ ```typescript
1468
+ import { extractCFG, CFGExtractor } from '@nahisaho/musubix-dfg';
1469
+
1470
+ const cfg = extractCFG(sourceCode);
1471
+
1472
+ // Traverse CFG
1473
+ for (const block of cfg.blocks) {
1474
+ console.log(`Block ${block.id}: ${block.statements.length} statements`);
1475
+ console.log(`Successors: ${block.successors.join(', ')}`);
1476
+ }
1477
+ ```
1478
+
1479
+ ### Def-Use Chain Analysis
1480
+
1481
+ Build definition-use chains for variable tracking:
1482
+
1483
+ ```typescript
1484
+ import { analyzeDefUse } from '@nahisaho/musubix-dfg';
1485
+
1486
+ const chains = analyzeDefUse(dfg);
1487
+
1488
+ for (const chain of chains) {
1489
+ console.log(`Variable: ${chain.variable}`);
1490
+ console.log(`Defined at: line ${chain.definition.line}`);
1491
+ console.log(`Used at: ${chain.uses.map(u => u.line).join(', ')}`);
1492
+ }
1493
+ ```
1494
+
1495
+ ### Data Dependency Analysis
1496
+
1497
+ Analyze data dependencies between statements:
1498
+
1499
+ ```typescript
1500
+ import { analyzeDataDependencies } from '@nahisaho/musubix-dfg';
1501
+
1502
+ const deps = analyzeDataDependencies(dfg);
1503
+
1504
+ for (const dep of deps) {
1505
+ console.log(`${dep.from} -> ${dep.to}: ${dep.type}`);
1506
+ }
1507
+ ```
1508
+
1509
+ ---
1510
+
1511
+ ## Lean 4 Integration
1512
+
1513
+ *(v2.0.0)*
1514
+
1515
+ The `@nahisaho/musubix-lean` package provides integration with the Lean 4 theorem prover for formal verification of requirements.
1516
+
1517
+ ### Installation
1518
+
1519
+ ```bash
1520
+ npm install @nahisaho/musubix-lean
1521
+ ```
1522
+
1523
+ ### EARS to Lean Conversion
1524
+
1525
+ Convert EARS requirements to Lean 4 theorems:
1526
+
1527
+ ```typescript
1528
+ import { EarsToLeanConverter } from '@nahisaho/musubix-lean';
1529
+
1530
+ const converter = new EarsToLeanConverter();
1531
+
1532
+ // Convert EARS requirement
1533
+ const earsRequirement = {
1534
+ id: 'REQ-001',
1535
+ type: 'event-driven',
1536
+ trigger: 'user clicks submit',
1537
+ response: 'system saves form data',
1538
+ };
1539
+
1540
+ const theorem = converter.convert(earsRequirement);
1541
+ console.log(theorem.leanCode);
1542
+ // theorem REQ_001 : ∀ (s : State),
1543
+ // user_clicks_submit s → saves_form_data (next s)
1544
+ ```
1545
+
1546
+ ### Lean AST Parsing
1547
+
1548
+ Parse and manipulate Lean 4 code:
1549
+
1550
+ ```typescript
1551
+ import { LeanParser, LeanAST } from '@nahisaho/musubix-lean';
1552
+
1553
+ const parser = new LeanParser();
1554
+ const ast = parser.parse(leanCode);
1555
+
1556
+ // Traverse AST
1557
+ for (const decl of ast.declarations) {
1558
+ if (decl.type === 'theorem') {
1559
+ console.log(`Theorem: ${decl.name}`);
1560
+ console.log(`Statement: ${decl.statement}`);
1561
+ }
1562
+ }
1563
+ ```
1564
+
1565
+ ### Proof Engine
1566
+
1567
+ Execute proofs using Lean 4:
1568
+
1569
+ ```typescript
1570
+ import { LeanProofEngine } from '@nahisaho/musubix-lean';
1571
+
1572
+ const engine = new LeanProofEngine({
1573
+ leanPath: '/usr/bin/lean',
1574
+ timeout: 30000,
1575
+ });
1576
+
1577
+ const result = await engine.prove(theorem);
1578
+
1579
+ if (result.success) {
1580
+ console.log('Proof verified!');
1581
+ console.log(`Proof: ${result.proof}`);
1582
+ } else {
1583
+ console.log(`Failed: ${result.error}`);
1584
+ }
1585
+ ```
1586
+
1587
+ ### ReProver Integration
1588
+
1589
+ Use ReProver for automated proof search:
1590
+
1591
+ ```typescript
1592
+ import { ReProverClient } from '@nahisaho/musubix-lean';
1593
+
1594
+ const reprover = new ReProverClient({
1595
+ endpoint: 'http://localhost:8080',
1596
+ maxDepth: 10,
1597
+ });
1598
+
1599
+ const proof = await reprover.searchProof(theorem);
1600
+
1601
+ if (proof.found) {
1602
+ console.log('Proof found!');
1603
+ console.log(proof.tactics);
1604
+ }
1605
+ ```
1606
+
1607
+ ---
1608
+
1609
+ ## YATA Scale
1610
+
1611
+ *(v2.0.0)*
1612
+
1613
+ The `@nahisaho/yata-scale` package provides distributed knowledge graph capabilities with sharding, caching, and synchronization.
1614
+
1615
+ ### Installation
1616
+
1617
+ ```bash
1618
+ npm install @nahisaho/yata-scale
1619
+ ```
1620
+
1621
+ ### High-Level API
1622
+
1623
+ Use `YataScaleManager` for simplified access:
1624
+
1625
+ ```typescript
1626
+ import { YataScaleManager } from '@nahisaho/yata-scale';
1627
+
1628
+ const yata = new YataScaleManager({
1629
+ shards: 16,
1630
+ cacheConfig: {
1631
+ l1MaxSize: 1000,
1632
+ l2MaxSize: 10000,
1633
+ l3Path: './cache',
1634
+ },
1635
+ });
1636
+
1637
+ // Store entity
1638
+ await yata.putEntity({
1639
+ id: 'entity-1',
1640
+ type: 'Document',
1641
+ properties: { title: 'Example' },
1642
+ });
1643
+
1644
+ // Query
1645
+ const results = await yata.query('SELECT ?s WHERE { ?s rdf:type Document }');
1646
+ ```
1647
+
1648
+ ### Sharding
1649
+
1650
+ Distribute data across shards using consistent hashing:
1651
+
1652
+ ```typescript
1653
+ import { ShardManager, HashPartitionStrategy } from '@nahisaho/yata-scale';
1654
+
1655
+ const shardManager = new ShardManager({
1656
+ shardCount: 16,
1657
+ virtualNodes: 150,
1658
+ strategy: new HashPartitionStrategy(),
1659
+ });
1660
+
1661
+ // Get shard for entity
1662
+ const shard = shardManager.getShardForEntity('entity-id');
1663
+ console.log(`Entity assigned to shard ${shard.id}`);
1664
+
1665
+ // Rebalance on node changes
1666
+ await shardManager.addNode('node-5');
1667
+ ```
1668
+
1669
+ ### Multi-Tier Caching
1670
+
1671
+ Three-tier caching for optimal performance:
1672
+
1673
+ ```typescript
1674
+ import { CacheManager, L1Cache, L2Cache, L3Cache } from '@nahisaho/yata-scale';
1675
+
1676
+ const cache = new CacheManager({
1677
+ l1: new L1Cache({ maxSize: 1000 }), // LRU cache
1678
+ l2: new L2Cache({ maxSize: 10000 }), // LFU cache
1679
+ l3: new L3Cache({ path: './cache' }), // Disk cache
1680
+ });
1681
+
1682
+ // Cache operations
1683
+ await cache.set('key', value, { ttl: 3600 });
1684
+ const result = await cache.get('key');
1685
+
1686
+ // Invalidation
1687
+ await cache.invalidate('key');
1688
+ await cache.invalidatePattern('user:*');
1689
+ ```
1690
+
1691
+ ### Index Management
1692
+
1693
+ Multiple index types for efficient queries:
1694
+
1695
+ ```typescript
1696
+ import { IndexManager, BPlusTreeIndex, FullTextIndex, GraphIndex } from '@nahisaho/yata-scale';
1697
+
1698
+ const indexManager = new IndexManager();
1699
+
1700
+ // B+ Tree for range queries
1701
+ indexManager.addIndex('timestamp', new BPlusTreeIndex());
1702
+
1703
+ // Full-text for search
1704
+ indexManager.addIndex('content', new FullTextIndex());
1705
+
1706
+ // Graph for traversal
1707
+ indexManager.addIndex('relationships', new GraphIndex());
1708
+ ```
1709
+
1710
+ ### Vector Clock Synchronization
1711
+
1712
+ Distributed synchronization with conflict resolution:
1713
+
1714
+ ```typescript
1715
+ import { SyncController, VectorClock, ConflictResolver } from '@nahisaho/yata-scale';
1716
+
1717
+ const sync = new SyncController({
1718
+ nodeId: 'node-1',
1719
+ conflictStrategy: 'last-write-wins',
1720
+ });
1721
+
1722
+ // Synchronize with peers
1723
+ await sync.synchronize();
1724
+
1725
+ // Manual conflict resolution
1726
+ sync.onConflict((conflict) => {
1727
+ console.log(`Conflict on ${conflict.key}`);
1728
+ return conflict.local; // or conflict.remote
1729
+ });
1730
+ ```
1731
+
1732
+ ### v2.0.0 Package Summary
1733
+
1734
+ | Package | Tests | Description |
1735
+ |---------|-------|-------------|
1736
+ | `@nahisaho/musubix-dfg` | 30 | DFG/CFG extraction, Def-Use analysis |
1737
+ | `@nahisaho/musubix-lean` | 151 | Lean 4 theorem proving, EARS conversion |
1738
+ | `@nahisaho/yata-scale` | 57 | Distributed sharding, caching, sync |
1739
+ | **Total** | **238** | **Phase 1: Deep Symbolic Integration** |
1740
+
1741
+ ---
1742
+
1743
+ ## Library Learning
1744
+
1745
+ *(v2.0.0 NEW!)*
1746
+
1747
+ The `@nahisaho/musubix-library-learner` package provides intelligent API pattern extraction and documentation from TypeScript libraries, enabling the system to learn and suggest library usage patterns.
1748
+
1749
+ ### Installation
1750
+
1751
+ ```bash
1752
+ npm install @nahisaho/musubix-library-learner
1753
+ ```
1754
+
1755
+ ### Library Analysis
1756
+
1757
+ Analyze and learn patterns from TypeScript libraries:
1758
+
1759
+ ```typescript
1760
+ import { LibraryLearner, LibraryAnalyzer } from '@nahisaho/musubix-library-learner';
1761
+
1762
+ const learner = new LibraryLearner();
1763
+
1764
+ // Analyze a library
1765
+ const patterns = await learner.analyze({
1766
+ libraryName: 'lodash',
1767
+ sourceDir: './node_modules/lodash',
1768
+ includeExamples: true,
1769
+ });
1770
+
1771
+ console.log(`Found ${patterns.length} API patterns`);
1772
+ for (const pattern of patterns) {
1773
+ console.log(`- ${pattern.name}: ${pattern.description}`);
1774
+ }
1775
+ ```
1776
+
1777
+ ### Pattern Extraction
1778
+
1779
+ Extract usage patterns from code examples:
1780
+
1781
+ ```typescript
1782
+ import { PatternExtractor } from '@nahisaho/musubix-library-learner';
1783
+
1784
+ const extractor = new PatternExtractor();
1785
+
1786
+ const patterns = await extractor.extract({
1787
+ code: sourceCode,
1788
+ libraryContext: 'express',
1789
+ });
1790
+
1791
+ // Get common patterns
1792
+ for (const pattern of patterns) {
1793
+ console.log(`Pattern: ${pattern.type}`);
1794
+ console.log(`Example: ${pattern.example}`);
1795
+ console.log(`Frequency: ${pattern.frequency}`);
1796
+ }
1797
+ ```
1798
+
1799
+ ### API Documentation Generation
1800
+
1801
+ Generate documentation from learned patterns:
1802
+
1803
+ ```typescript
1804
+ import { DocGenerator } from '@nahisaho/musubix-library-learner';
1805
+
1806
+ const generator = new DocGenerator();
1807
+
1808
+ const docs = await generator.generate({
1809
+ patterns: learnedPatterns,
1810
+ format: 'markdown',
1811
+ includeExamples: true,
1812
+ });
1813
+
1814
+ await fs.writeFile('API-PATTERNS.md', docs);
1815
+ ```
1816
+
1817
+ ### TypeScript Analysis
1818
+
1819
+ Deep analysis of TypeScript declarations:
1820
+
1821
+ ```typescript
1822
+ import { TypeScriptAnalyzer } from '@nahisaho/musubix-library-learner';
1823
+
1824
+ const analyzer = new TypeScriptAnalyzer();
1825
+
1826
+ const analysis = await analyzer.analyze('./src/index.ts');
1827
+
1828
+ // Get exported types
1829
+ for (const type of analysis.exports) {
1830
+ console.log(`${type.name}: ${type.kind}`);
1831
+ if (type.kind === 'function') {
1832
+ console.log(` Params: ${type.parameters.join(', ')}`);
1833
+ console.log(` Returns: ${type.returnType}`);
1834
+ }
1835
+ }
1836
+ ```
1837
+
1838
+ ---
1839
+
1840
+ ## Neural Search
1841
+
1842
+ *(v2.0.0 NEW!)*
1843
+
1844
+ The `@nahisaho/musubix-neural-search` package provides semantic code search using embeddings and neural ranking, enabling context-aware code discovery across your codebase.
1845
+
1846
+ ### Installation
1847
+
1848
+ ```bash
1849
+ npm install @nahisaho/musubix-neural-search
1850
+ ```
1851
+
1852
+ ### Semantic Search
1853
+
1854
+ Search code by meaning, not just keywords:
1855
+
1856
+ ```typescript
1857
+ import { NeuralSearchEngine } from '@nahisaho/musubix-neural-search';
1858
+
1859
+ const search = new NeuralSearchEngine({
1860
+ embeddingModel: 'code-bert',
1861
+ indexPath: './search-index',
1862
+ });
1863
+
1864
+ // Index your codebase
1865
+ await search.index('./src');
1866
+
1867
+ // Semantic search
1868
+ const results = await search.search({
1869
+ query: 'function that validates email addresses',
1870
+ limit: 10,
1871
+ });
1872
+
1873
+ for (const result of results) {
1874
+ console.log(`${result.file}:${result.line} (score: ${result.score})`);
1875
+ console.log(` ${result.snippet}`);
1876
+ }
1877
+ ```
1878
+
1879
+ ### Code Embeddings
1880
+
1881
+ Generate embeddings for code snippets:
1882
+
1883
+ ```typescript
1884
+ import { CodeEmbedder } from '@nahisaho/musubix-neural-search';
1885
+
1886
+ const embedder = new CodeEmbedder();
1887
+
1888
+ const embedding = await embedder.embed({
1889
+ code: 'function add(a: number, b: number) { return a + b; }',
1890
+ language: 'typescript',
1891
+ });
1892
+
1893
+ // Compare similarity
1894
+ const similarity = embedder.cosineSimilarity(embedding1, embedding2);
1895
+ console.log(`Similarity: ${similarity}`);
1896
+ ```
1897
+
1898
+ ### Hybrid Search
1899
+
1900
+ Combine lexical and semantic search:
1901
+
1902
+ ```typescript
1903
+ import { HybridSearchEngine } from '@nahisaho/musubix-neural-search';
1904
+
1905
+ const hybrid = new HybridSearchEngine({
1906
+ lexicalWeight: 0.3,
1907
+ semanticWeight: 0.7,
1908
+ });
1909
+
1910
+ const results = await hybrid.search({
1911
+ query: 'authentication middleware express',
1912
+ filters: {
1913
+ language: 'typescript',
1914
+ path: 'src/middleware/**',
1915
+ },
1916
+ });
1917
+ ```
1918
+
1919
+ ### Code Ranking
1920
+
1921
+ Neural ranking for search results:
1922
+
1923
+ ```typescript
1924
+ import { CodeRanker } from '@nahisaho/musubix-neural-search';
1925
+
1926
+ const ranker = new CodeRanker();
1927
+
1928
+ const ranked = await ranker.rank({
1929
+ query: 'parse JSON safely',
1930
+ candidates: searchResults,
1931
+ context: {
1932
+ currentFile: './src/utils.ts',
1933
+ recentFiles: ['./src/api.ts', './src/config.ts'],
1934
+ },
1935
+ });
1936
+ ```
1937
+
1938
+ ---
1939
+
1940
+ ## Program Synthesis
1941
+
1942
+ *(v2.0.0 NEW!)*
1943
+
1944
+ The `@nahisaho/musubix-synthesis` package provides neural-guided program synthesis, generating code from specifications using symbolic constraints and neural networks.
1945
+
1946
+ ### Installation
1947
+
1948
+ ```bash
1949
+ npm install @nahisaho/musubix-synthesis
1950
+ ```
1951
+
1952
+ ### Specification-Based Synthesis
1953
+
1954
+ Generate code from formal specifications:
1955
+
1956
+ ```typescript
1957
+ import { ProgramSynthesizer } from '@nahisaho/musubix-synthesis';
1958
+
1959
+ const synthesizer = new ProgramSynthesizer();
1960
+
1961
+ const result = await synthesizer.synthesize({
1962
+ specification: {
1963
+ input: 'array of numbers',
1964
+ output: 'array of numbers (sorted ascending)',
1965
+ constraints: ['stable sort', 'O(n log n) complexity'],
1966
+ },
1967
+ language: 'typescript',
1968
+ });
1969
+
1970
+ console.log(result.code);
1971
+ // function sort(arr: number[]): number[] {
1972
+ // return [...arr].sort((a, b) => a - b);
1973
+ // }
1974
+ ```
1975
+
1976
+ ### Example-Based Synthesis
1977
+
1978
+ Generate code from input/output examples:
1979
+
1980
+ ```typescript
1981
+ import { ExampleBasedSynthesizer } from '@nahisaho/musubix-synthesis';
1982
+
1983
+ const synthesizer = new ExampleBasedSynthesizer();
1984
+
1985
+ const result = await synthesizer.synthesize({
1986
+ examples: [
1987
+ { input: ['hello', 'world'], output: 'hello world' },
1988
+ { input: ['foo', 'bar', 'baz'], output: 'foo bar baz' },
1989
+ ],
1990
+ language: 'typescript',
1991
+ });
1992
+
1993
+ console.log(result.code);
1994
+ // function join(arr: string[]): string {
1995
+ // return arr.join(' ');
1996
+ // }
1997
+ ```
1998
+
1999
+ ### Sketch-Based Synthesis
2000
+
2001
+ Fill in holes in partial programs:
2002
+
2003
+ ```typescript
2004
+ import { SketchSynthesizer } from '@nahisaho/musubix-synthesis';
2005
+
2006
+ const synthesizer = new SketchSynthesizer();
2007
+
2008
+ const result = await synthesizer.complete({
2009
+ sketch: `
2010
+ function validate(email: string): boolean {
2011
+ const pattern = ??; // hole to fill
2012
+ return pattern.test(email);
2013
+ }
2014
+ `,
2015
+ constraints: ['must validate common email formats'],
2016
+ });
2017
+
2018
+ console.log(result.code);
2019
+ // const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
2020
+ ```
2021
+
2022
+ ### Neural-Guided Search
2023
+
2024
+ Use neural networks to guide synthesis search:
2025
+
2026
+ ```typescript
2027
+ import { NeuralGuidedSynthesizer } from '@nahisaho/musubix-synthesis';
2028
+
2029
+ const synthesizer = new NeuralGuidedSynthesizer({
2030
+ model: 'codegen-2B',
2031
+ beamWidth: 5,
2032
+ maxDepth: 10,
2033
+ });
2034
+
2035
+ const result = await synthesizer.synthesize({
2036
+ description: 'Parse a CSV string into array of objects with headers as keys',
2037
+ tests: [
2038
+ {
2039
+ input: 'name,age\\nAlice,30\\nBob,25',
2040
+ output: [{ name: 'Alice', age: '30' }, { name: 'Bob', age: '25' }],
2041
+ },
2042
+ ],
2043
+ });
2044
+
2045
+ if (result.verified) {
2046
+ console.log('All tests pass!');
2047
+ console.log(result.code);
2048
+ }
2049
+ ```
2050
+
2051
+ ### Synthesis Verification
2052
+
2053
+ Verify synthesized code against specifications:
2054
+
2055
+ ```typescript
2056
+ import { SynthesisVerifier } from '@nahisaho/musubix-synthesis';
2057
+
2058
+ const verifier = new SynthesisVerifier();
2059
+
2060
+ const verification = await verifier.verify({
2061
+ code: synthesizedCode,
2062
+ specification: originalSpec,
2063
+ tests: testCases,
2064
+ });
2065
+
2066
+ console.log(`Verified: ${verification.passed}`);
2067
+ console.log(`Coverage: ${verification.testCoverage}%`);
2068
+ for (const issue of verification.issues) {
2069
+ console.log(`Issue: ${issue.message}`);
2070
+ }
2071
+ ```
2072
+
2073
+ ### v2.0.0 Package Summary
2074
+
2075
+ | Package | Tests | Description |
2076
+ |---------|-------|-------------|
2077
+ | **Phase 1: Deep Symbolic Integration** | | |
2078
+ | `@nahisaho/musubix-dfg` | 30 | DFG/CFG extraction, Def-Use analysis |
2079
+ | `@nahisaho/musubix-lean` | 151 | Lean 4 theorem proving, EARS conversion |
2080
+ | `@nahisaho/yata-scale` | 57 | Distributed sharding, caching, sync |
2081
+ | **Phase 2: Advanced Learning** | | |
2082
+ | `@nahisaho/musubix-library-learner` | 132 | API pattern extraction, documentation |
2083
+ | `@nahisaho/musubix-neural-search` | 144 | Semantic code search, embeddings |
2084
+ | `@nahisaho/musubix-synthesis` | 146 | Neural-guided program synthesis |
2085
+ | **Total v2.0.0 New** | **660** | **6 new packages** |
2086
+
2087
+ ---
2088
+
2089
+ ## Advanced Learning Enhancement
2090
+
2091
+ *(v2.2.0 NEW!)*
2092
+
2093
+ MUSUBIX v2.2.0では、Neural Search、Library Learner、Synthesisの3パッケージに対して高度な学習機能を追加しました。
2094
+
2095
+ ### Neural Search Enhancement
2096
+
2097
+ #### ContextAwareEmbedder
2098
+
2099
+ AST構造を認識したコンテキスト埋め込み:
2100
+
2101
+ ```typescript
2102
+ import { ContextAwareEmbedder } from '@nahisaho/musubix-neural-search';
2103
+
2104
+ const embedder = new ContextAwareEmbedder({
2105
+ windowSize: 5,
2106
+ includeAST: true,
2107
+ });
2108
+
2109
+ const embedding = embedder.embed(code, {
2110
+ surrounding: surroundingCode,
2111
+ imports: importStatements,
2112
+ });
2113
+ ```
2114
+
2115
+ #### HybridRanker
2116
+
2117
+ BM25とベクトル類似度のハイブリッドランキング:
2118
+
2119
+ ```typescript
2120
+ import { HybridRanker } from '@nahisaho/musubix-neural-search';
2121
+
2122
+ const ranker = new HybridRanker({ alpha: 0.6 });
2123
+ const results = ranker.rank(query, documents);
2124
+ ```
2125
+
2126
+ #### EmbeddingCache
2127
+
2128
+ LRU + TTL管理キャッシュ:
2129
+
2130
+ ```typescript
2131
+ import { EmbeddingCache } from '@nahisaho/musubix-neural-search';
2132
+
2133
+ const cache = new EmbeddingCache({
2134
+ maxSize: 10000,
2135
+ ttlMs: 3600000,
2136
+ });
2137
+
2138
+ cache.set('key', embedding);
2139
+ const stats = cache.getStats(); // { hits, misses, hitRate }
2140
+ ```
2141
+
2142
+ #### TrajectoryLogger
2143
+
2144
+ 検索軌跡のロギング:
2145
+
2146
+ ```typescript
2147
+ import { createTrajectoryLogger } from '@nahisaho/musubix-neural-search';
2148
+
2149
+ const logger = createTrajectoryLogger();
2150
+ logger.logBranch({ depth: 1, score: 0.85, action: 'expand' });
2151
+
2152
+ const trajectory = logger.getTrajectory();
2153
+ const parquet = logger.export('parquet');
2154
+ ```
2155
+
2156
+ ### Library Learner Enhancement
2157
+
2158
+ #### SemanticChunker
2159
+
2160
+ AST境界認識チャンキング:
2161
+
2162
+ ```typescript
2163
+ import { SemanticChunker } from '@nahisaho/musubix-library-learner';
2164
+
2165
+ const chunker = new SemanticChunker({
2166
+ minSize: 50,
2167
+ maxSize: 500,
2168
+ respectBoundaries: true,
2169
+ });
2170
+
2171
+ const chunks = chunker.chunk(code);
2172
+ ```
2173
+
2174
+ #### PatternVersionManager
2175
+
2176
+ Git風バージョン管理:
2177
+
2178
+ ```typescript
2179
+ import { PatternVersionManager } from '@nahisaho/musubix-library-learner';
2180
+
2181
+ const manager = new PatternVersionManager();
2182
+ manager.commit(pattern, 'Add validation pattern');
2183
+ const history = manager.getHistory(patternId);
2184
+ manager.rollback(patternId, commitId);
2185
+ ```
2186
+
2187
+ #### MetricsExporter
2188
+
2189
+ 学習メトリクスのエクスポート:
2190
+
2191
+ ```typescript
2192
+ import { createMetricsExporter } from '@nahisaho/musubix-library-learner';
2193
+
2194
+ const exporter = createMetricsExporter(library);
2195
+ const json = exporter.export('json');
2196
+ const markdown = exporter.export('markdown');
2197
+ const summary = exporter.getSummary();
2198
+ // { totalPatterns, averageConfidence, healthStatus }
2199
+ ```
2200
+
2201
+ ### Synthesis Enhancement
2202
+
2203
+ #### MetaLearningEngine
2204
+
2205
+ タスク類似度ベースの戦略選択:
2206
+
2207
+ ```typescript
2208
+ import { createMetaLearningEngine } from '@nahisaho/musubix-synthesis';
2209
+
2210
+ const meta = createMetaLearningEngine({
2211
+ historySize: 100,
2212
+ similarityThreshold: 0.7,
2213
+ });
2214
+
2215
+ meta.recordTask(task, result);
2216
+ const strategy = meta.selectStrategy(newTask);
2217
+ ```
2218
+
2219
+ #### DSLExtender
2220
+
2221
+ パターンからのDSL演算子自動生成:
2222
+
2223
+ ```typescript
2224
+ import { createDSLExtender } from '@nahisaho/musubix-synthesis';
2225
+
2226
+ const extender = createDSLExtender(baseDSL);
2227
+ const gaps = extender.detectGaps(patterns);
2228
+ const suggestions = extender.suggestOperators(gaps);
2229
+ ```
2230
+
2231
+ #### ExampleAnalyzer
2232
+
2233
+ 例題品質分析:
2234
+
2235
+ ```typescript
2236
+ import { createExampleAnalyzer } from '@nahisaho/musubix-synthesis';
2237
+
2238
+ const analyzer = createExampleAnalyzer();
2239
+ const quality = analyzer.analyzeQuality(examples);
2240
+ const coverage = analyzer.analyzeCoverage(examples, dsl);
2241
+ ```
2242
+
2243
+ #### ExplanationGenerator
2244
+
2245
+ 合成プログラムの自然言語説明:
2246
+
2247
+ ```typescript
2248
+ import { createExplanationGenerator } from '@nahisaho/musubix-synthesis';
2249
+
2250
+ const explainer = createExplanationGenerator();
2251
+ const explanation = explainer.generate(program);
2252
+ const summary = explainer.summarize(program);
2253
+ // "Converts to uppercase"
2254
+ ```
2255
+
2256
+ ### v2.2.0 CLI Commands
2257
+
2258
+ ```bash
2259
+ # プログラム合成
2260
+ npx musubix synthesize <examples.json>
2261
+ npx musubix syn <examples.json> # エイリアス
2262
+
2263
+ # パターンライブラリ管理
2264
+ npx musubix library learn <file>
2265
+ npx musubix library query <query>
2266
+ npx musubix library stats
2267
+ npx musubix lib stats # エイリアス
2268
+ ```
2269
+
2270
+ ### v2.2.0 Test Statistics
2271
+
2272
+ | EPIC | Tasks | Tests |
2273
+ |------|-------|-------|
2274
+ | Neural Search | 7 | 138 |
2275
+ | Library Learner | 7 | 145 |
2276
+ | Synthesis | 6 | 108 |
2277
+ | Integration | 4 | 73 |
2278
+ | **Total** | **28** | **464** |
2279
+
2280
+ ---
2281
+
2282
+ ## Performance Optimization
2283
+
2284
+ *(v3.1.0)*
2285
+
2286
+ Performance utilities for CLI commands and pattern processing.
2287
+
2288
+ ### Performance Measurement
2289
+
2290
+ ```typescript
2291
+ import {
2292
+ PerformanceTimer,
2293
+ measureAsync,
2294
+ measureSync,
2295
+ PerformanceCollector,
2296
+ createPerformanceCollector,
2297
+ formatPerformanceReport,
2298
+ } from '@nahisaho/musubix-core/cli';
2299
+
2300
+ // Measure async operation
2301
+ const { result, performance } = await measureAsync('api-call', async () => {
2302
+ return await fetchData();
2303
+ });
2304
+ console.log(`Duration: ${performance.durationMs}ms`);
2305
+
2306
+ // Create collector with default baselines
2307
+ const collector = createPerformanceCollector();
2308
+ collector.addResult(performance);
2309
+
2310
+ // Generate and format report
2311
+ const report = collector.generateReport();
2312
+ console.log(formatPerformanceReport(report));
2313
+ // === Performance Report ===
2314
+ // Average: 150.25ms
2315
+ // Min: 100ms
2316
+ // Max: 200ms
2317
+ // ✅ cli:init: 300ms (target: 500ms, 60%)
2318
+ ```
2319
+
2320
+ ### Lazy Loading
2321
+
2322
+ ```typescript
2323
+ import {
2324
+ createLazyLoader,
2325
+ LazyModuleRegistry,
2326
+ globalLazyRegistry,
2327
+ BatchLoader,
2328
+ } from '@nahisaho/musubix-core/cli';
2329
+
2330
+ // Lazy module loading
2331
+ const heavyModule = createLazyLoader(() => import('./heavy-module'));
2332
+ const module = await heavyModule(); // Loads only on first access
2333
+
2334
+ // Module registry for multiple lazy modules
2335
+ const registry = new LazyModuleRegistry();
2336
+ registry.register('parser', () => import('./parser'));
2337
+ registry.register('formatter', () => import('./formatter'));
2338
+
2339
+ const parser = await registry.get('parser');
2340
+ await registry.preload(['parser', 'formatter']);
2341
+
2342
+ // Batch loading with deduplication
2343
+ const loader = new BatchLoader(async (keys) => {
2344
+ const results = await fetchMany(keys);
2345
+ return new Map(keys.map((k, i) => [k, results[i]]));
2346
+ }, 10); // 10ms batch delay
2347
+
2348
+ const [a, b, c] = await Promise.all([
2349
+ loader.load('a'),
2350
+ loader.load('b'),
2351
+ loader.load('c'),
2352
+ ]); // Single batch request
2353
+ ```
2354
+
2355
+ ### Pattern Cache
2356
+
2357
+ ```typescript
2358
+ import {
2359
+ LRUCache,
2360
+ PatternCache,
2361
+ globalPatternCache,
2362
+ memoize,
2363
+ memoizeAsync,
2364
+ } from '@nahisaho/musubix-core/learning';
2365
+
2366
+ // LRU cache with TTL
2367
+ const cache = new LRUCache<string, Pattern>({
2368
+ maxSize: 100,
2369
+ ttlMs: 60000, // 1 minute TTL
2370
+ });
2371
+ cache.set('pattern-1', patternData);
2372
+ const pattern = cache.get('pattern-1');
2373
+
2374
+ // Get cache statistics
2375
+ const stats = cache.getStats();
2376
+ // { size: 1, maxSize: 100, hits: 5, misses: 2, hitRatio: 0.71, evictions: 0 }
2377
+
2378
+ // Category-based pattern cache
2379
+ const patternCache = new PatternCache({ maxSize: 50, ttlMs: 300000 });
2380
+ patternCache.set('design', 'singleton', { name: 'Singleton' });
2381
+ patternCache.set('code', 'factory', { name: 'Factory' });
2382
+
2383
+ // Memoize expensive functions
2384
+ const expensiveFn = memoize((x: number) => {
2385
+ // Heavy computation
2386
+ return x * 2;
2387
+ });
2388
+
2389
+ // Memoize async functions with concurrent call deduplication
2390
+ const fetchUser = memoizeAsync(async (id: string) => {
2391
+ return await api.getUser(id);
2392
+ });
2393
+ ```
2394
+
2395
+ ### Default Performance Baselines
2396
+
2397
+ | Operation | Target (ms) | Max (ms) |
2398
+ |-----------|-------------|----------|
2399
+ | `cli:init` | 500 | 1000 |
2400
+ | `cli:validate` | 200 | 500 |
2401
+ | `cli:analyze` | 1000 | 2000 |
2402
+ | `cli:generate` | 500 | 1000 |
2403
+ | `pattern:query` | 100 | 300 |
2404
+ | `pattern:extract` | 500 | 1000 |
2405
+ | `learning:recommend` | 200 | 500 |
2406
+
2407
+ ---
2408
+
2409
+ ## MCP Server Integration
2410
+
2411
+ ### CLI Startup
2412
+
2413
+ ```bash
2414
+ # Default (stdio transport)
2415
+ musubix-mcp
2416
+
2417
+ # SSE transport
2418
+ musubix-mcp --transport sse --port 3000
2419
+
2420
+ # WebSocket transport
2421
+ musubix-mcp --transport websocket --port 3001
2422
+ ```
2423
+
2424
+ ### Programmatic Startup
2425
+
2426
+ ```typescript
2427
+ import { startServer, createMCPServer } from '@nahisaho/musubix-mcp-server';
2428
+
2429
+ // Simple startup
2430
+ await startServer();
2431
+
2432
+ // Startup with options
2433
+ const server = createMCPServer({
2434
+ transport: 'sse',
2435
+ port: 3000
2436
+ });
2437
+ await server.start();
2438
+ ```
2439
+
2440
+ ### AI Platform Integration
2441
+
2442
+ #### GitHub Copilot (VS Code)
2443
+
2444
+ Add to `.vscode/settings.json`:
2445
+
2446
+ ```json
2447
+ {
2448
+ "github.copilot.chat.mcpServers": {
2449
+ "musubix": {
2450
+ "command": "musubix-mcp",
2451
+ "args": ["--transport", "stdio"]
2452
+ }
2453
+ }
2454
+ }
2455
+ ```
2456
+
2457
+ #### Claude Desktop
2458
+
2459
+ Add to Claude configuration file (`~/.config/claude/config.json` or similar):
2460
+
2461
+ ```json
2462
+ {
2463
+ "mcpServers": {
2464
+ "musubix": {
2465
+ "command": "musubix-mcp",
2466
+ "args": []
2467
+ }
2468
+ }
2469
+ }
2470
+ ```
2471
+
2472
+ #### Cursor
2473
+
2474
+ Add to `.cursor/mcp.json`:
2475
+
2476
+ ```json
2477
+ {
2478
+ "mcpServers": {
2479
+ "musubix": {
2480
+ "command": "musubix-mcp",
2481
+ "args": ["--transport", "stdio"]
2482
+ }
2483
+ }
2484
+ }
2485
+ ```
2486
+
2487
+ ### Available MCP Tools
2488
+
2489
+ | Tool Name | Description |
2490
+ |-----------|-------------|
2491
+ | `create_requirement` | Create EARS-format requirement |
2492
+ | `validate_requirements` | Validate requirements |
2493
+ | `create_design` | Create C4 design element |
2494
+ | `create_adr` | Create ADR |
2495
+ | `create_task` | Create implementation task |
2496
+ | `validate_all` | Full 9 Articles compliance check |
2497
+ | `get_traceability` | Get traceability matrix |
2498
+
2499
+ ---
2500
+
2501
+ ## Symbolic Reasoning
2502
+
2503
+ *(v1.2.0 New Feature)*
2504
+
2505
+ ### Overview
2506
+
2507
+ Symbolic reasoning enhances LLM outputs by applying formal verification and knowledge-graph backed reasoning. This hybrid approach (Neuro-Symbolic) combines the creativity of neural networks with the precision of symbolic logic.
2508
+
2509
+ ### Key Components
2510
+
2511
+ | Component | Description |
2512
+ |-----------|-------------|
2513
+ | `SemanticCodeFilterPipeline` | Filter LLM outputs for code quality |
2514
+ | `HallucinationDetector` | Detect and prevent hallucinated outputs |
2515
+ | `EarsToFormalSpecConverter` | Convert EARS requirements to formal Z3 specifications |
2516
+ | `Z3Adapter` | Interface with Z3 solver for formal verification |
2517
+ | `QualityGateValidator` | Validate against 17 quality gate checks |
2518
+
2519
+ ### Usage
2520
+
2521
+ #### Semantic Code Filtering
2522
+
2523
+ ```typescript
2524
+ import { SemanticCodeFilterPipeline } from '@nahisaho/musubix-core';
2525
+
2526
+ const pipeline = new SemanticCodeFilterPipeline({
2527
+ enableHallucinationDetection: true,
2528
+ maxRetries: 3
2529
+ });
2530
+
2531
+ const result = await pipeline.filter({
2532
+ code: generatedCode,
2533
+ context: { language: 'typescript', domain: 'authentication' }
2534
+ });
2535
+
2536
+ if (result.isValid) {
2537
+ console.log('Code passed validation:', result.filteredCode);
2538
+ } else {
2539
+ console.log('Issues found:', result.issues);
2540
+ }
2541
+ ```
2542
+
2543
+ #### Hallucination Detection
2544
+
2545
+ ```typescript
2546
+ import { HallucinationDetector } from '@nahisaho/musubix-core';
2547
+
2548
+ const detector = new HallucinationDetector();
2549
+
2550
+ const analysis = await detector.analyze({
2551
+ response: llmResponse,
2552
+ groundTruth: knownFacts,
2553
+ context: projectContext
2554
+ });
2555
+
2556
+ console.log('Confidence score:', analysis.confidence);
2557
+ console.log('Hallucination risks:', analysis.risks);
2558
+ ```
2559
+
2560
+ #### EARS to Formal Specification
2561
+
2562
+ ```typescript
2563
+ import { EarsToFormalSpecConverter } from '@nahisaho/musubix-core';
2564
+
2565
+ const converter = new EarsToFormalSpecConverter();
2566
+
2567
+ const formalSpec = await converter.convert({
2568
+ earsRequirement: 'WHEN user clicks login, THE system SHALL authenticate within 2 seconds',
2569
+ requirementId: 'REQ-AUTH-001'
2570
+ });
2571
+
2572
+ // Returns Z3-compatible specification
2573
+ console.log(formalSpec.z3Expression);
2574
+ ```
2575
+
2576
+ #### Quality Gate Validation
2577
+
2578
+ ```typescript
2579
+ import { QualityGateValidator } from '@nahisaho/musubix-core';
2580
+
2581
+ const validator = new QualityGateValidator();
2582
+
2583
+ const gateResult = await validator.validate({
2584
+ requirements: requirementsList,
2585
+ designs: designDocuments,
2586
+ tasks: taskList
2587
+ });
2588
+
2589
+ console.log('All gates passed:', gateResult.allPassed);
2590
+ console.log('Gate details:', gateResult.gates);
2591
+ // 17 quality checks including EARS compliance, traceability, etc.
2592
+ ```
2593
+
2594
+ ### Quality Gate Checks
2595
+
2596
+ | Gate | Description |
2597
+ |------|-------------|
2598
+ | EARS Compliance | Requirements follow EARS patterns |
2599
+ | Unique IDs | All artifacts have unique identifiers |
2600
+ | Traceability | Full traceability chain exists |
2601
+ | Design Coverage | All requirements have designs |
2602
+ | Task Coverage | All designs have tasks |
2603
+ | No Orphans | No orphaned requirements or tasks |
2604
+ | Completeness | All required fields are present |
2605
+ | ... | And 10 more quality checks |
2606
+
2607
+ ---
2608
+
2609
+ ## Consistency Validation
2610
+
2611
+ *(v1.4.1 New Feature)*
2612
+
2613
+ ### Overview
2614
+
2615
+ Consistency validation ensures data integrity when adding triples to the knowledge graph. Based on OWL constraints, it detects violations before they corrupt the knowledge base.
2616
+
2617
+ ### Validation Types
2618
+
2619
+ | Type | Description | Severity |
2620
+ |------|-------------|----------|
2621
+ | `disjoint-class-membership` | Instance belongs to disjoint classes | error |
2622
+ | `functional-property-violation` | Multiple values for functional property | error |
2623
+ | `inverse-functional-violation` | Same value maps to multiple subjects | error |
2624
+ | `asymmetric-violation` | Inverse relation exists for asymmetric property | error |
2625
+ | `irreflexive-violation` | Self-reference for irreflexive property | error |
2626
+ | `duplicate-triple` | Exact duplicate triple | warning |
2627
+ | `circular-dependency` | Circular subClassOf chain | error |
2628
+
2629
+ ### Usage
2630
+
2631
+ #### Validated Triple Addition
2632
+
2633
+ ```typescript
2634
+ import { N3Store } from '@nahisaho/musubix-ontology-mcp';
2635
+
2636
+ // Enable validation on add
2637
+ const store = new N3Store({}, true);
2638
+
2639
+ // Add with validation
2640
+ const result = store.addTripleValidated({
2641
+ subject: 'http://example.org/Person1',
2642
+ predicate: 'http://example.org/hasMother',
2643
+ object: 'http://example.org/Mother1'
2644
+ });
2645
+
2646
+ if (!result.success) {
2647
+ console.error('Validation errors:', result.validation.errors);
2648
+ }
2649
+ ```
2650
+
2651
+ #### Store-wide Consistency Check
2652
+
2653
+ ```typescript
2654
+ // Check entire store
2655
+ const consistency = store.checkConsistency();
2656
+
2657
+ if (!consistency.consistent) {
2658
+ for (const violation of consistency.violations) {
2659
+ console.log(`${violation.type}: ${violation.message}`);
2660
+ console.log('Affected triples:', violation.triples);
2661
+ }
2662
+
2663
+ // Get fix suggestions
2664
+ for (const suggestion of consistency.suggestions) {
2665
+ console.log(`Suggestion: ${suggestion.suggestion}`);
2666
+ console.log(`Auto-fixable: ${suggestion.autoFixable}`);
2667
+ }
2668
+ }
2669
+ ```
2670
+
2671
+ #### Direct Validator Usage
2672
+
2673
+ ```typescript
2674
+ import { ConsistencyValidator } from '@nahisaho/musubix-ontology-mcp';
2675
+
2676
+ const validator = new ConsistencyValidator({
2677
+ checkDisjointClasses: true,
2678
+ checkFunctionalProperties: true,
2679
+ checkDuplicates: true,
2680
+ checkCircularDependencies: true
2681
+ });
2682
+
2683
+ // Validate before adding
2684
+ const validation = validator.validateTriple(newTriple, existingTriples);
2685
+ if (!validation.valid) {
2686
+ console.error(validation.errors);
2687
+ }
2688
+
2689
+ // Find duplicates
2690
+ const duplicates = validator.findDuplicates(allTriples);
2691
+ const semanticDuplicates = validator.findSemanticDuplicates(allTriples);
2692
+ ```
2693
+
2694
+ ---
2695
+
2696
+ ## Advanced Inference
2697
+
2698
+ *(v1.4.5 New Feature)*
2699
+
2700
+ ### Overview
2701
+
2702
+ Advanced Inference provides OWL 2 RL reasoning and Datalog evaluation capabilities for the knowledge graph. It supports materialization of implicit facts, rule-based inference, and human-readable explanations.
2703
+
2704
+ ### Key Components
2705
+
2706
+ | Component | Description |
2707
+ |-----------|-------------|
2708
+ | `OWL2RLReasoner` | OWL 2 RL profile reasoning with 20+ built-in rules |
2709
+ | `DatalogEngine` | Stratified Datalog evaluation engine |
2710
+ | `InferenceExplainer` | Natural language explanation generator |
2711
+ | `ProgressReporter` | Real-time inference progress tracking |
2712
+
2713
+ ### OWL 2 RL Reasoning
2714
+
2715
+ ```typescript
2716
+ import { OWL2RLReasoner } from '@nahisaho/musubix-ontology-mcp';
2717
+
2718
+ const reasoner = new OWL2RLReasoner({
2719
+ maxIterations: 100,
2720
+ enablePropertyChains: true,
2721
+ enableInverseProperties: true
2722
+ });
2723
+
2724
+ // Run reasoning on store
2725
+ const result = await reasoner.reason(store, {
2726
+ onProgress: (progress) => {
2727
+ console.log(`Iteration ${progress.iteration}: ${progress.newTriples} new triples`);
2728
+ }
2729
+ });
2730
+
2731
+ console.log(`Inferred ${result.inferredCount} new facts`);
2732
+ console.log(`Rules applied: ${result.rulesApplied.join(', ')}`);
2733
+ ```
2734
+
2735
+ ### OWL 2 RL Rules
2736
+
2737
+ | Rule ID | Name | Description |
2738
+ |---------|------|-------------|
2739
+ | `prp-dom` | Property Domain | Infer type from property domain |
2740
+ | `prp-rng` | Property Range | Infer type from property range |
2741
+ | `prp-inv1/2` | Inverse Properties | Infer inverse relationships |
2742
+ | `prp-trp` | Transitive Properties | Chain transitive properties |
2743
+ | `prp-symp` | Symmetric Properties | Infer symmetric relationships |
2744
+ | `cax-sco` | SubClassOf | Propagate class membership |
2745
+ | `scm-spo` | SubPropertyOf | Property subsumption |
2746
+ | `eq-rep-s/p/o` | SameAs Replacement | Substitute equal individuals |
2747
+
2748
+ ### Datalog Evaluation
2749
+
2750
+ ```typescript
2751
+ import { DatalogEngine } from '@nahisaho/musubix-ontology-mcp';
2752
+
2753
+ const engine = new DatalogEngine();
2754
+
2755
+ // Define rules
2756
+ const rules = [
2757
+ {
2758
+ head: { predicate: 'ancestor', args: ['?x', '?y'] },
2759
+ body: [
2760
+ { predicate: 'parent', args: ['?x', '?y'] }
2761
+ ]
2762
+ },
2763
+ {
2764
+ head: { predicate: 'ancestor', args: ['?x', '?z'] },
2765
+ body: [
2766
+ { predicate: 'parent', args: ['?x', '?y'] },
2767
+ { predicate: 'ancestor', args: ['?y', '?z'] }
2768
+ ]
2769
+ }
2770
+ ];
2771
+
2772
+ // Evaluate rules
2773
+ const result = await engine.evaluate(rules, facts, {
2774
+ onProgress: (progress) => {
2775
+ console.log(`Stratum ${progress.stratum}: evaluating ${progress.rule}`);
2776
+ }
2777
+ });
2778
+
2779
+ console.log(`Derived ${result.derivedFacts.length} new facts`);
2780
+ ```
2781
+
2782
+ ### Inference Explanation
2783
+
2784
+ ```typescript
2785
+ import { InferenceExplainer, ExplanationFormat } from '@nahisaho/musubix-ontology-mcp';
2786
+
2787
+ const explainer = new InferenceExplainer(reasoner.getProvenanceLog());
2788
+
2789
+ // Get explanation for a specific triple
2790
+ const explanation = explainer.explain(
2791
+ 'http://example.org/Animal',
2792
+ 'rdf:type',
2793
+ 'owl:Class',
2794
+ ExplanationFormat.TEXT
2795
+ );
2796
+
2797
+ console.log(explanation);
2798
+ // Output: "Animal is a Class because it is declared as owl:Class via rule cax-sco"
2799
+
2800
+ // Generate HTML explanation
2801
+ const htmlExplanation = explainer.explain(
2802
+ subject, predicate, object,
2803
+ ExplanationFormat.HTML
2804
+ );
2805
+ ```
2806
+
2807
+ ### Progress Reporting
2808
+
2809
+ ```typescript
2810
+ import { createProgressReporter } from '@nahisaho/musubix-ontology-mcp';
2811
+
2812
+ const reporter = createProgressReporter({
2813
+ onProgress: (info) => {
2814
+ console.log(`Phase: ${info.phase}`);
2815
+ console.log(`Iteration: ${info.iteration}/${info.maxIterations}`);
2816
+ console.log(`Triples: ${info.totalTriples}`);
2817
+ console.log(`New inferences: ${info.newInferences}`);
2818
+ },
2819
+ throttleMs: 500 // Report every 500ms
2820
+ });
2821
+
2822
+ await reasoner.reason(store, { progressReporter: reporter });
2823
+ ```
2824
+
2825
+ ---
2826
+
2827
+ ## YATA Integration
2828
+
2829
+ ### What is YATA?
2830
+
2831
+ **YATA** (Yet Another Thinking Agent) is a knowledge graph management MCP server that stores and retrieves expertise and know-how as structured data. **Note: YATA is a separate Python-based installation.**
2832
+
2833
+ ### Architecture
2834
+
2835
+ ```
2836
+ ┌─────────────────────────────────────────┐
2837
+ │ AI Platform │
2838
+ │ (GitHub Copilot, Claude, etc.) │
2839
+ └─────────────┬───────────────────────────┘
2840
+ │ MCP Protocol
2841
+ ┌───────┴───────┐
2842
+ ↓ ↓
2843
+ ┌──────────┐ ┌──────────┐
2844
+ │ MUSUBIX │ │ YATA │
2845
+ │ MCP │ │ MCP │
2846
+ │ Server │ │ Server │
2847
+ └────┬─────┘ └────┬─────┘
2848
+ │ │
2849
+ ↓ ↓
2850
+ ┌──────────┐ ┌──────────┐
2851
+ │ SDD │ │ Knowledge│
2852
+ │ Engine │ │ Graph │
2853
+ └──────────┘ └──────────┘
2854
+ ```
2855
+
2856
+ ### YATA Client (from MUSUBIX)
2857
+
2858
+ ```typescript
2859
+ import { createYATAClient } from '@nahisaho/musubix-yata-client';
2860
+
2861
+ // Create client
2862
+ const yata = createYATAClient({
2863
+ endpoint: 'http://localhost:8000',
2864
+ apiKey: process.env.YATA_API_KEY
2865
+ });
2866
+
2867
+ // Save knowledge
2868
+ await yata.addKnowledge({
2869
+ topic: 'jwt-authentication',
2870
+ content: 'Best practices for JWT implementation',
2871
+ tags: ['security', 'authentication'],
2872
+ relatedRequirements: ['REQ-001']
2873
+ });
2874
+
2875
+ // Search knowledge
2876
+ const results = await yata.search({
2877
+ query: 'authentication best practices',
2878
+ limit: 10
2879
+ });
2880
+ ```
2881
+
2882
+ ### YATA Features
2883
+
2884
+ | Feature | Description |
2885
+ |---------|-------------|
2886
+ | 34 MCP Tools | Read/write/query knowledge graphs |
2887
+ | 47 Frameworks | TypeScript, Python, React, etc. |
2888
+ | Vector Search | Semantic knowledge search |
2889
+ | Relationship Mapping | Connect knowledge nodes |
2890
+
2891
+ ---
2892
+
2893
+ ## Best Practices
2894
+
2895
+ ### 1. Requirements Best Practices
2896
+
2897
+ ✅ **Recommended**:
2898
+ - Use EARS format
2899
+ - Include verifiable acceptance criteria
2900
+ - One function per requirement
2901
+
2902
+ ❌ **Avoid**:
2903
+ - Vague expressions ("appropriately", "quickly", etc.)
2904
+ - Multiple functions in one requirement
2905
+ - Implementation details in requirements
2906
+
2907
+ ### 2. Design Best Practices
2908
+
2909
+ ✅ **Recommended**:
2910
+ - Utilize all 4 C4 levels
2911
+ - Document important decisions with ADR
2912
+ - Maintain traceability to requirements
2913
+
2914
+ ❌ **Avoid**:
2915
+ - Over-detailed initial design
2916
+ - Omitting decision rationale
2917
+ - Isolated design documents
2918
+
2919
+ ### 3. Task Management Best Practices
2920
+
2921
+ ✅ **Recommended**:
2922
+ - Granularity within 4 hours
2923
+ - Clear links to requirements
2924
+ - Explicit completion criteria
2925
+
2926
+ ❌ **Avoid**:
2927
+ - Tasks too large (8+ hours)
2928
+ - Tasks without requirement links
2929
+ - Vague completion criteria
2930
+
2931
+ ---
2932
+
2933
+ ## Troubleshooting
2934
+
2935
+ ### Common Problems and Solutions
2936
+
2937
+ #### Requirements Validation Error
2938
+
2939
+ ```
2940
+ Error: EARS format not detected
2941
+ ```
2942
+
2943
+ **Solution**: Include an EARS pattern in your requirement text.
2944
+
2945
+ ```typescript
2946
+ // Before
2947
+ const text = 'Implement authentication feature';
2948
+
2949
+ // After
2950
+ const text = 'When a user logs in, the system shall perform authentication';
2951
+ ```
2952
+
2953
+ #### Traceability Warning
2954
+
2955
+ ```
2956
+ Warning: Requirement REQ-001 has no design reference
2957
+ ```
2958
+
2959
+ **Solution**: Create a design document and link it.
2960
+
2961
+ ```typescript
2962
+ requirementsService.linkDesign('REQ-001', 'DES-001');
2963
+ ```
2964
+
2965
+ #### MCP Server Connection Error
2966
+
2967
+ ```
2968
+ Error: Cannot connect to MCP server
2969
+ ```
2970
+
2971
+ **Solution**:
2972
+ 1. Verify server is running
2973
+ 2. Check port number
2974
+ 3. Check firewall settings
2975
+
2976
+ ```bash
2977
+ # Check server status
2978
+ ps aux | grep musubix
2979
+ ```
2980
+
2981
+ #### YATA Connection Error
2982
+
2983
+ ```
2984
+ Error: Cannot connect to YATA endpoint
2985
+ ```
2986
+
2987
+ **Solution**:
2988
+ 1. Verify endpoint URL
2989
+ 2. Check API key
2990
+ 3. Check network settings
2991
+
2992
+ ```typescript
2993
+ const client = createYATAClient({
2994
+ endpoint: 'http://localhost:8000', // Correct URL
2995
+ apiKey: process.env.YATA_API_KEY // Verify environment variable
2996
+ });
2997
+ ```
2998
+
2999
+ ---
3000
+
3001
+ ## Next Steps
3002
+
3003
+ - 📚 See [API Reference](./API-REFERENCE.md)
3004
+ - 💡 Check [Sample Projects](./examples/)
3005
+ - 🤝 Read [Contribution Guide](./CONTRIBUTING.md)
3006
+
3007
+ ---
3008
+
3009
+ ## Related Documents
3010
+
3011
+ | Document | Description |
3012
+ |----------|-------------|
3013
+ | [INSTALL-GUIDE.md](INSTALL-GUIDE.md) | Detailed installation guide |
3014
+ | [API-REFERENCE.md](API-REFERENCE.md) | API reference |
3015
+ | [evolution-from-musubi-to-musubix.md](evolution-from-musubi-to-musubix.md) | Evolution from MUSUBI |
3016
+ | [overview/MUSUBIX-v2.2.0-Advanced-Learning.md](overview/MUSUBIX-v2.2.0-Advanced-Learning.md) | v2.2.0 Advanced Learning details |
3017
+
3018
+ ---
3019
+
3020
+ **Version**: 2.2.0
3021
+ **Last Updated**: 2026-01-08
3022
+ **MUSUBIX Project**