ruvnet-kb-first 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +674 -0
  3. package/SKILL.md +740 -0
  4. package/bin/kb-first.js +123 -0
  5. package/install/init-project.sh +435 -0
  6. package/install/install-global.sh +257 -0
  7. package/install/kb-first-autodetect.sh +108 -0
  8. package/install/kb-first-command.md +80 -0
  9. package/install/kb-first-skill.md +262 -0
  10. package/package.json +87 -0
  11. package/phases/00-assessment.md +529 -0
  12. package/phases/01-storage.md +194 -0
  13. package/phases/01.5-hooks-setup.md +521 -0
  14. package/phases/02-kb-creation.md +413 -0
  15. package/phases/03-persistence.md +125 -0
  16. package/phases/04-visualization.md +170 -0
  17. package/phases/05-integration.md +114 -0
  18. package/phases/06-scaffold.md +130 -0
  19. package/phases/07-build.md +493 -0
  20. package/phases/08-verification.md +597 -0
  21. package/phases/09-security.md +512 -0
  22. package/phases/10-documentation.md +613 -0
  23. package/phases/11-deployment.md +670 -0
  24. package/phases/testing.md +713 -0
  25. package/scripts/1.5-hooks-verify.sh +252 -0
  26. package/scripts/8.1-code-scan.sh +58 -0
  27. package/scripts/8.2-import-check.sh +42 -0
  28. package/scripts/8.3-source-returns.sh +52 -0
  29. package/scripts/8.4-startup-verify.sh +65 -0
  30. package/scripts/8.5-fallback-check.sh +63 -0
  31. package/scripts/8.6-attribution.sh +56 -0
  32. package/scripts/8.7-confidence.sh +56 -0
  33. package/scripts/8.8-gap-logging.sh +70 -0
  34. package/scripts/9-security-audit.sh +202 -0
  35. package/scripts/init-project.sh +395 -0
  36. package/scripts/verify-enforcement.sh +167 -0
  37. package/src/commands/hooks.js +361 -0
  38. package/src/commands/init.js +315 -0
  39. package/src/commands/phase.js +372 -0
  40. package/src/commands/score.js +380 -0
  41. package/src/commands/status.js +193 -0
  42. package/src/commands/verify.js +286 -0
  43. package/src/index.js +56 -0
  44. package/src/mcp-server.js +412 -0
  45. package/templates/attention-router.ts +534 -0
  46. package/templates/code-analysis.ts +683 -0
  47. package/templates/federated-kb-learner.ts +649 -0
  48. package/templates/gnn-engine.ts +1091 -0
  49. package/templates/intentions.md +277 -0
  50. package/templates/kb-client.ts +905 -0
  51. package/templates/schema.sql +303 -0
  52. package/templates/sona-config.ts +312 -0
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * RuvNet KB-First Application Builder CLI
5
+ *
6
+ * Build intelligent applications on expert knowledge bases.
7
+ *
8
+ * Commands:
9
+ * init - Initialize KB-First structure in current project
10
+ * score - Calculate KB-First compliance score
11
+ * verify - Run verification checks
12
+ * hooks - Manage KB-First hooks
13
+ * status - Show KB-First project status
14
+ * phase - Run a specific build phase
15
+ *
16
+ * Usage:
17
+ * npx ruvnet-kb-first init
18
+ * npx kb-first score
19
+ * kb-first verify --phase=8
20
+ */
21
+
22
+ import { program } from 'commander';
23
+ import chalk from 'chalk';
24
+ import { fileURLToPath } from 'url';
25
+ import { dirname, join } from 'path';
26
+ import { readFileSync } from 'fs';
27
+
28
+ const __filename = fileURLToPath(import.meta.url);
29
+ const __dirname = dirname(__filename);
30
+ const packageJson = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8'));
31
+
32
+ // Import commands
33
+ import { initCommand } from '../src/commands/init.js';
34
+ import { scoreCommand } from '../src/commands/score.js';
35
+ import { verifyCommand } from '../src/commands/verify.js';
36
+ import { hooksCommand } from '../src/commands/hooks.js';
37
+ import { statusCommand } from '../src/commands/status.js';
38
+ import { phaseCommand } from '../src/commands/phase.js';
39
+
40
+ // ASCII Banner
41
+ const banner = `
42
+ ${chalk.cyan('╔═══════════════════════════════════════════════════════════════╗')}
43
+ ${chalk.cyan('║')} ${chalk.bold.white('RuvNet KB-First Application Builder')} ${chalk.cyan('║')}
44
+ ${chalk.cyan('║')} ${chalk.gray('Build intelligent applications on expert knowledge')} ${chalk.cyan('║')}
45
+ ${chalk.cyan('╚═══════════════════════════════════════════════════════════════╝')}
46
+ `;
47
+
48
+ program
49
+ .name('kb-first')
50
+ .description('KB-First Application Builder - Build on expert knowledge')
51
+ .version(packageJson.version)
52
+ .addHelpText('beforeAll', banner);
53
+
54
+ // Init command
55
+ program
56
+ .command('init')
57
+ .description('Initialize KB-First structure in current project')
58
+ .option('-f, --force', 'Overwrite existing configuration')
59
+ .option('-t, --template <type>', 'Template type (basic, api, fullstack)', 'basic')
60
+ .option('--no-hooks', 'Skip hook installation')
61
+ .action(initCommand);
62
+
63
+ // Score command
64
+ program
65
+ .command('score')
66
+ .description('Calculate KB-First compliance score')
67
+ .option('-d, --detailed', 'Show detailed breakdown')
68
+ .option('-j, --json', 'Output as JSON')
69
+ .option('--phase <number>', 'Score specific phase only')
70
+ .action(scoreCommand);
71
+
72
+ // Verify command
73
+ program
74
+ .command('verify')
75
+ .description('Run KB-First verification checks')
76
+ .option('-p, --phase <number>', 'Verify specific phase')
77
+ .option('-a, --all', 'Run all verification scripts')
78
+ .option('-v, --verbose', 'Verbose output')
79
+ .action(verifyCommand);
80
+
81
+ // Hooks command
82
+ program
83
+ .command('hooks')
84
+ .description('Manage KB-First hooks')
85
+ .option('--install', 'Install hooks to project')
86
+ .option('--verify', 'Verify hook installation')
87
+ .option('--train', 'Pre-train hooks with KB patterns')
88
+ .option('--status', 'Show hook status')
89
+ .action(hooksCommand);
90
+
91
+ // Status command
92
+ program
93
+ .command('status')
94
+ .description('Show KB-First project status')
95
+ .option('-d, --detailed', 'Show detailed status')
96
+ .action(statusCommand);
97
+
98
+ // Phase command
99
+ program
100
+ .command('phase <number>')
101
+ .description('Run a specific build phase (0-11)')
102
+ .option('-s, --sub <number>', 'Run specific sub-phase')
103
+ .option('--skip-gate', 'Skip quality gate (not recommended)')
104
+ .action(phaseCommand);
105
+
106
+ // MCP server command (hidden - used internally)
107
+ program
108
+ .command('mcp')
109
+ .description('Start MCP server for Claude Code integration')
110
+ .option('-p, --port <number>', 'Server port', '3847')
111
+ .action(async (options) => {
112
+ const { startMCPServer } = await import('../src/mcp-server.js');
113
+ await startMCPServer(options);
114
+ });
115
+
116
+ // Parse arguments
117
+ program.parse();
118
+
119
+ // Show help if no command provided
120
+ if (!process.argv.slice(2).length) {
121
+ console.log(banner);
122
+ program.outputHelp();
123
+ }
@@ -0,0 +1,435 @@
1
+ #!/bin/bash
2
+ # KB-First Project Initializer
3
+ # Version 4.2.0 | Created 2026-01-01
4
+ #
5
+ # Initialize KB-First in a new or existing project
6
+
7
+ set -e
8
+
9
+ echo "╔═══════════════════════════════════════════════════════════════╗"
10
+ echo "║ KB-First Project Initialization v4.2.0 ║"
11
+ echo "╚═══════════════════════════════════════════════════════════════╝"
12
+ echo ""
13
+
14
+ # Check if we're in a git repo
15
+ if [ ! -d ".git" ]; then
16
+ echo "⚠️ Warning: Not in a git repository"
17
+ read -p "Continue anyway? [y/N] " -n 1 -r
18
+ echo
19
+ if [[ ! $REPLY =~ ^[Yy]$ ]]; then
20
+ exit 1
21
+ fi
22
+ fi
23
+
24
+ # Determine project type
25
+ echo "Detecting project type..."
26
+ if [ -f "package.json" ]; then
27
+ PROJECT_TYPE="node"
28
+ echo " Detected: Node.js project"
29
+ elif [ -f "requirements.txt" ] || [ -f "pyproject.toml" ]; then
30
+ PROJECT_TYPE="python"
31
+ echo " Detected: Python project"
32
+ elif [ -f "Cargo.toml" ]; then
33
+ PROJECT_TYPE="rust"
34
+ echo " Detected: Rust project"
35
+ elif [ -f "go.mod" ]; then
36
+ PROJECT_TYPE="go"
37
+ echo " Detected: Go project"
38
+ else
39
+ PROJECT_TYPE="generic"
40
+ echo " Detected: Generic project"
41
+ fi
42
+
43
+ # Create CLAUDE.md with KB-First rules
44
+ echo ""
45
+ echo "Creating CLAUDE.md with KB-First rules..."
46
+
47
+ cat > CLAUDE.md << 'EOF'
48
+ # KB-First Project Configuration
49
+
50
+ This project uses the KB-First architecture. All development must follow these rules.
51
+
52
+ ## Critical Rules (NEVER VIOLATE)
53
+
54
+ ```
55
+ RULE 1: No hardcoded domain logic
56
+ ❌ const rate = 0.04;
57
+ ✅ const rate = await kb.search("withdrawal rate");
58
+
59
+ RULE 2: Every domain function queries KB
60
+ Every file in src/domain/ imports from ../kb
61
+
62
+ RULE 3: All responses include kbSources
63
+ Traceability is mandatory
64
+
65
+ RULE 4: Startup verification required
66
+ App exits if KB unavailable
67
+
68
+ RULE 5: No fallback logic
69
+ ❌ rules = kb.get() || DEFAULT_RULES
70
+ ✅ rules = kb.get(); if (!rules) throw Error("KB missing");
71
+ ```
72
+
73
+ ## KB Quality Score Target: ≥98/100
74
+
75
+ | Component | Points | Criteria |
76
+ |-----------|--------|----------|
77
+ | Expert Coverage | 0-40 | Number of cited experts |
78
+ | Depth | 0-30 | Recursive depth of KB tree |
79
+ | Completeness | 0-30 | Nodes with actual content |
80
+ | Attribution | +5 | All nodes have source_expert |
81
+ | Confidence | +5 | All nodes have confidence score |
82
+
83
+ ## App Compliance Score Target: 100/100
84
+
85
+ | Component | Points | Criteria |
86
+ |-----------|--------|----------|
87
+ | KB Imports | 0-25 | All domain files import kb |
88
+ | Source Returns | 0-25 | All responses have kbSources |
89
+ | No Hardcode | 0-20 | No magic numbers in domain |
90
+ | Startup Verify | 0-15 | KB check in entry point |
91
+ | No Fallbacks | 0-15 | No `|| DEFAULT` patterns |
92
+
93
+ ## Commands
94
+
95
+ ```
96
+ /kb-first # Run KB-First builder
97
+ /kb-first score # Score current state
98
+ /kb-first verify # Run verification checks
99
+ ```
100
+
101
+ ## Phase Documentation
102
+
103
+ See: https://github.com/ruvnet/kb-first-builder
104
+
105
+ ---
106
+
107
+ *KB-First v4.2.0*
108
+ EOF
109
+
110
+ echo " ✅ Created CLAUDE.md"
111
+
112
+ # Create project structure
113
+ echo ""
114
+ echo "Creating project structure..."
115
+
116
+ # Create directories
117
+ mkdir -p src/kb
118
+ mkdir -p src/domain
119
+ mkdir -p src/api
120
+ mkdir -p visualization
121
+
122
+ # Create KB enforcement document
123
+ cat > KB_ENFORCEMENT.md << 'EOF'
124
+ # KB Enforcement Rules
125
+
126
+ ## BEFORE Writing Any Domain Logic
127
+
128
+ 1. Query KB for relevant data
129
+ 2. Never hardcode numeric values
130
+ 3. Never use fallback defaults
131
+ 4. Always return kbSources
132
+
133
+ ## Domain File Template
134
+
135
+ ```typescript
136
+ import { kb } from '../kb';
137
+
138
+ export async function calculate(input: Input): Promise<Result> {
139
+ // Query KB for domain rules
140
+ const rules = await kb.search('calculation rules', { namespace: 'domain' });
141
+
142
+ if (!rules || rules.length === 0) {
143
+ throw new Error('KB missing required rules');
144
+ }
145
+
146
+ // Use KB values
147
+ const rate = rules.find(r => r.key === 'rate')?.value;
148
+
149
+ // Perform calculation
150
+ const result = performCalculation(input, rate);
151
+
152
+ // Return with sources
153
+ return {
154
+ ...result,
155
+ kbSources: rules.map(r => ({
156
+ title: r.title,
157
+ expert: r.source_expert,
158
+ confidence: r.confidence
159
+ }))
160
+ };
161
+ }
162
+ ```
163
+
164
+ ## Verification Before Commit
165
+
166
+ Run: `/kb-first verify`
167
+
168
+ All 8 checks must PASS:
169
+ - 8.1: No hardcoded values
170
+ - 8.2: KB imports in all domain files
171
+ - 8.3: kbSources in all returns
172
+ - 8.4: Startup verification
173
+ - 8.5: No fallback patterns
174
+ - 8.6: Expert attribution
175
+ - 8.7: Confidence scores
176
+ - 8.8: Gap logging
177
+ EOF
178
+
179
+ echo " ✅ Created KB_ENFORCEMENT.md"
180
+
181
+ # Create minimal KB client stub
182
+ cat > src/kb/index.ts << 'EOF'
183
+ /**
184
+ * KB Client - Knowledge Base Interface
185
+ *
186
+ * This is a stub. Replace with your actual KB implementation.
187
+ * See: https://github.com/ruvnet/kb-first-builder
188
+ */
189
+
190
+ export interface KBNode {
191
+ id: string;
192
+ title: string;
193
+ content: string;
194
+ source_expert: string;
195
+ confidence: number;
196
+ namespace: string;
197
+ }
198
+
199
+ export interface KBSearchOptions {
200
+ namespace?: string;
201
+ limit?: number;
202
+ minConfidence?: number;
203
+ }
204
+
205
+ export interface KBSource {
206
+ title: string;
207
+ expert: string;
208
+ confidence: number;
209
+ }
210
+
211
+ class KBClient {
212
+ private connected = false;
213
+
214
+ async verifyConnection(): Promise<boolean> {
215
+ // TODO: Implement actual connection check
216
+ // Should return false if KB is unavailable
217
+ console.log('[KB] Verifying connection...');
218
+ this.connected = true;
219
+ return this.connected;
220
+ }
221
+
222
+ async search(query: string, options?: KBSearchOptions): Promise<KBNode[]> {
223
+ if (!this.connected) {
224
+ throw new Error('KB not connected. Call verifyConnection() first.');
225
+ }
226
+
227
+ // TODO: Implement actual KB search
228
+ // This should query your PostgreSQL database
229
+ console.log(`[KB] Searching: "${query}"`);
230
+
231
+ return [];
232
+ }
233
+
234
+ async logGap(query: string): Promise<void> {
235
+ // TODO: Log unanswered queries for KB improvement
236
+ console.log(`[KB] Gap logged: "${query}"`);
237
+ }
238
+ }
239
+
240
+ export const kb = new KBClient();
241
+ export default kb;
242
+ EOF
243
+
244
+ echo " ✅ Created src/kb/index.ts (stub)"
245
+
246
+ # Create entry point stub
247
+ cat > src/index.ts << 'EOF'
248
+ /**
249
+ * Application Entry Point
250
+ *
251
+ * KB-First: Verify KB connection before anything else
252
+ */
253
+
254
+ import { kb } from './kb';
255
+
256
+ async function main() {
257
+ // KB-First: Verify connection FIRST
258
+ console.log('Verifying KB connection...');
259
+ const kbOk = await kb.verifyConnection();
260
+
261
+ if (!kbOk) {
262
+ console.error('ERROR: KB unavailable. Cannot start application.');
263
+ process.exit(1);
264
+ }
265
+
266
+ console.log('KB connected successfully.');
267
+
268
+ // TODO: Initialize your application
269
+ console.log('Application starting...');
270
+ }
271
+
272
+ main().catch((err) => {
273
+ console.error('Fatal error:', err);
274
+ process.exit(1);
275
+ });
276
+ EOF
277
+
278
+ echo " ✅ Created src/index.ts with KB verification"
279
+
280
+ # Create scripts directory and copy verification scripts
281
+ echo ""
282
+ echo "Setting up verification scripts..."
283
+
284
+ mkdir -p scripts
285
+
286
+ # Create a simplified verification script
287
+ cat > scripts/verify-all.sh << 'EOF'
288
+ #!/bin/bash
289
+ # KB-First Verification Suite
290
+ # Run all Phase 8 verification checks
291
+
292
+ set -e
293
+
294
+ echo "=== KB-First Verification Suite ==="
295
+ echo ""
296
+
297
+ PASS=0
298
+ FAIL=0
299
+
300
+ # Check 1: No hardcoded values in domain
301
+ echo "8.1 Checking for hardcoded values..."
302
+ if grep -rE "= [0-9]+\.[0-9]+" src/domain 2>/dev/null | grep -v "node_modules"; then
303
+ echo " ❌ FAIL: Hardcoded values found"
304
+ FAIL=$((FAIL + 1))
305
+ else
306
+ echo " ✅ PASS: No hardcoded values"
307
+ PASS=$((PASS + 1))
308
+ fi
309
+
310
+ # Check 2: KB imports
311
+ echo "8.2 Checking KB imports..."
312
+ if [ -d "src/domain" ]; then
313
+ MISSING=$(find src/domain -name "*.ts" -o -name "*.js" 2>/dev/null | while read f; do
314
+ if ! grep -q "from.*kb" "$f" 2>/dev/null; then
315
+ echo "$f"
316
+ fi
317
+ done)
318
+ if [ -n "$MISSING" ]; then
319
+ echo " ❌ FAIL: Files missing KB import"
320
+ FAIL=$((FAIL + 1))
321
+ else
322
+ echo " ✅ PASS: All domain files import KB"
323
+ PASS=$((PASS + 1))
324
+ fi
325
+ else
326
+ echo " ⏭️ SKIP: No src/domain directory"
327
+ fi
328
+
329
+ # Check 3: Startup verification
330
+ echo "8.4 Checking startup verification..."
331
+ if grep -q "verifyConnection" src/index.ts 2>/dev/null; then
332
+ echo " ✅ PASS: Startup verification found"
333
+ PASS=$((PASS + 1))
334
+ else
335
+ echo " ❌ FAIL: No startup verification"
336
+ FAIL=$((FAIL + 1))
337
+ fi
338
+
339
+ # Check 4: No fallback patterns
340
+ echo "8.5 Checking for fallback patterns..."
341
+ if grep -rE "\|\| \[\]|\|\| \{\}|\|\| null|\|\| 0|\?\? \[\]|\?\? \{\}" src/domain 2>/dev/null | grep -v "node_modules"; then
342
+ echo " ❌ FAIL: Fallback patterns found"
343
+ FAIL=$((FAIL + 1))
344
+ else
345
+ echo " ✅ PASS: No fallback patterns"
346
+ PASS=$((PASS + 1))
347
+ fi
348
+
349
+ echo ""
350
+ echo "================================================"
351
+ echo "Results: $PASS passed, $FAIL failed"
352
+
353
+ if [ $FAIL -eq 0 ]; then
354
+ echo "✅ All checks passed!"
355
+ exit 0
356
+ else
357
+ echo "❌ Some checks failed. Review and fix before proceeding."
358
+ exit 1
359
+ fi
360
+ EOF
361
+
362
+ chmod +x scripts/verify-all.sh
363
+ echo " ✅ Created scripts/verify-all.sh"
364
+
365
+ # Create PROJECT_INTENTIONS.md template
366
+ echo ""
367
+ echo "Creating PROJECT_INTENTIONS.md template..."
368
+
369
+ cat > PROJECT_INTENTIONS.md << 'EOF'
370
+ # Project Intentions
371
+
372
+ ## What I Want to Build
373
+
374
+ [Describe your application in 2-3 sentences]
375
+
376
+ ## Who Will Use This
377
+
378
+ [Describe your target users]
379
+
380
+ ## Core Features
381
+
382
+ 1. [Feature 1]
383
+ 2. [Feature 2]
384
+ 3. [Feature 3]
385
+
386
+ ## Knowledge Domain
387
+
388
+ [What domain knowledge does this application need?]
389
+
390
+ ## Example Queries
391
+
392
+ What questions should the KB be able to answer?
393
+
394
+ 1. [Example question 1]
395
+ 2. [Example question 2]
396
+ 3. [Example question 3]
397
+
398
+ ## Success Criteria
399
+
400
+ How will you know when the application is complete?
401
+
402
+ 1. [Criterion 1]
403
+ 2. [Criterion 2]
404
+ 3. [Criterion 3]
405
+
406
+ ---
407
+
408
+ *Fill out this file, then run `/kb-first` to start building.*
409
+ EOF
410
+
411
+ echo " ✅ Created PROJECT_INTENTIONS.md"
412
+
413
+ # Summary
414
+ echo ""
415
+ echo "═══════════════════════════════════════════════════════════════"
416
+ echo "✅ KB-First project initialized!"
417
+ echo ""
418
+ echo "Project structure:"
419
+ echo " ├── CLAUDE.md # KB-First rules for Claude"
420
+ echo " ├── KB_ENFORCEMENT.md # Enforcement documentation"
421
+ echo " ├── PROJECT_INTENTIONS.md # Fill this out first!"
422
+ echo " ├── src/"
423
+ echo " │ ├── kb/ # KB client"
424
+ echo " │ ├── domain/ # Domain logic (uses KB)"
425
+ echo " │ ├── api/ # API routes"
426
+ echo " │ └── index.ts # Entry point (verifies KB)"
427
+ echo " ├── scripts/"
428
+ echo " │ └── verify-all.sh # Verification suite"
429
+ echo " └── visualization/ # KB visualization"
430
+ echo ""
431
+ echo "Next steps:"
432
+ echo " 1. Fill out PROJECT_INTENTIONS.md"
433
+ echo " 2. Run: /kb-first"
434
+ echo ""
435
+ echo "═══════════════════════════════════════════════════════════════"