musubix 2.1.0 → 2.2.0

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