Skip to content

Commit 9c4fa55

Browse files
authored
Merge pull request #266 from CambrianTech/feature/rust-module-consolidation
Rust Module Consolidation Phase 2: Optimization & Compute Migration
2 parents 38ca68e + 030b165 commit 9c4fa55

File tree

57 files changed

+2998
-851
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

57 files changed

+2998
-851
lines changed

src/debug/jtag/browser/generated.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/**
22
* Browser Structure Registry - Auto-generated
33
*
4-
* Contains 11 daemons and 187 commands and 2 adapters and 28 widgets.
4+
* Contains 11 daemons and 188 commands and 2 adapters and 28 widgets.
55
* Generated by scripts/generate-structure.ts - DO NOT EDIT MANUALLY
66
*/
77

@@ -152,6 +152,7 @@ import { PersonaLearningPatternQueryBrowserCommand } from './../commands/persona
152152
import { PingBrowserCommand } from './../commands/ping/browser/PingBrowserCommand';
153153
import { PositronCursorBrowserCommand } from './../commands/positron/cursor/browser/PositronCursorBrowserCommand';
154154
import { ProcessRegistryBrowserCommand } from './../commands/process-registry/browser/ProcessRegistryBrowserCommand';
155+
import { RuntimeMetricsBrowserCommand } from './../commands/runtime/metrics/browser/RuntimeMetricsBrowserCommand';
155156
import { SessionCreateBrowserCommand } from './../commands/session/create/browser/SessionCreateBrowserCommand';
156157
import { SessionDestroyBrowserCommand } from './../commands/session/destroy/browser/SessionDestroyBrowserCommand';
157158
import { SessionGetIdBrowserCommand } from './../commands/session/get-id/browser/SessionGetIdBrowserCommand';
@@ -974,6 +975,11 @@ export const BROWSER_COMMANDS: CommandEntry[] = [
974975
className: 'ProcessRegistryBrowserCommand',
975976
commandClass: ProcessRegistryBrowserCommand
976977
},
978+
{
979+
name: 'runtime/metrics',
980+
className: 'RuntimeMetricsBrowserCommand',
981+
commandClass: RuntimeMetricsBrowserCommand
982+
},
977983
{
978984
name: 'session/create',
979985
className: 'SessionCreateBrowserCommand',

src/debug/jtag/commands/ai/rag/query-open/server/RagQueryOpenServerCommand.ts

Lines changed: 41 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { v4 as uuidv4 } from 'uuid';
1717
import type { CodeIndexEntity } from '../../../../../system/data/entities/CodeIndexEntity';
1818
import type { DataListParams, DataListResult } from '../../../../data/list/shared/DataListTypes';
1919
import type { BaseEntity } from '../../../../../system/data/entities/BaseEntity';
20+
import { RustCoreIPCClient } from '../../../../../workers/continuum-core/bindings/RustCoreIPC';
2021

2122
import { EmbeddingGenerate } from '../../../embedding/generate/shared/EmbeddingGenerateTypes';
2223
import { DataList } from '../../../../data/list/shared/DataListTypes';
@@ -125,8 +126,9 @@ export class RagQueryOpenServerCommand extends RagQueryOpenCommand {
125126

126127
console.log(`🔎 Fetched ${listResult.items.length} indexed entries`);
127128

128-
// Step 3: Calculate cosine similarity for each entry
129-
const scoredResults: CodeSearchResult[] = [];
129+
// Step 3: Filter entries and prepare for Rust similarity computation
130+
const filteredEntries: CodeIndexEntity[] = [];
131+
const targetEmbeddings: number[][] = [];
130132

131133
for (const entry of listResult.items as readonly CodeIndexEntity[]) {
132134
// Skip entries without embeddings
@@ -142,21 +144,47 @@ export class RagQueryOpenServerCommand extends RagQueryOpenCommand {
142144
continue;
143145
}
144146

145-
// Calculate cosine similarity
146-
const similarity = this.cosineSimilarity(queryEmbedding, entry.embedding);
147+
filteredEntries.push(entry);
148+
targetEmbeddings.push(entry.embedding);
149+
}
147150

148-
// Only include results above relevance threshold
149-
if (similarity >= minRelevance) {
150-
scoredResults.push({
151-
entry,
152-
relevanceScore: similarity
153-
});
151+
// Step 4: Use Rust for parallel similarity computation (Rayon-accelerated)
152+
let scoredResults: CodeSearchResult[] = [];
153+
154+
if (targetEmbeddings.length > 0) {
155+
try {
156+
const ipc = RustCoreIPCClient.getInstance();
157+
const { results: topKResults, durationMs } = await ipc.embeddingTopK(
158+
queryEmbedding,
159+
targetEmbeddings,
160+
targetEmbeddings.length, // Get all results, filter by threshold
161+
minRelevance
162+
);
163+
164+
console.log(`🦀 Rust computed ${topKResults.length} similarities in ${durationMs}ms`);
165+
166+
// Map indices back to entries
167+
scoredResults = topKResults.map(r => ({
168+
entry: filteredEntries[r.index],
169+
relevanceScore: r.similarity
170+
}));
171+
} catch (error) {
172+
// Fallback to TypeScript if Rust unavailable
173+
console.log(`⚠️ Rust similarity unavailable, using TypeScript fallback: ${error}`);
174+
for (let i = 0; i < filteredEntries.length; i++) {
175+
const similarity = this.cosineSimilarity(queryEmbedding, targetEmbeddings[i]);
176+
if (similarity >= minRelevance) {
177+
scoredResults.push({
178+
entry: filteredEntries[i],
179+
relevanceScore: similarity
180+
});
181+
}
182+
}
183+
// Sort by relevance (highest first) - Rust already returns sorted
184+
scoredResults.sort((a, b) => b.relevanceScore - a.relevanceScore);
154185
}
155186
}
156187

157-
// Step 4: Sort by relevance (highest first)
158-
scoredResults.sort((a, b) => b.relevanceScore - a.relevanceScore);
159-
160188
console.log(`🔎 Found ${scoredResults.length} matches above threshold ${minRelevance}`);
161189

162190
// Step 5: Create query handle
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Development files
2+
.eslintrc*
3+
tsconfig*.json
4+
vitest.config.ts
5+
6+
# Build artifacts
7+
*.js.map
8+
*.d.ts.map
9+
10+
# IDE
11+
.vscode/
12+
.idea/
13+
14+
# Logs
15+
*.log
16+
npm-debug.log*
17+
18+
# OS files
19+
.DS_Store
20+
Thumbs.db
Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
# Runtime Metrics Command
2+
3+
Query Rust module performance metrics including latency percentiles, command counts, and slow command tracking. Enables AI-driven system analysis and optimization.
4+
5+
## Table of Contents
6+
7+
- [Usage](#usage)
8+
- [CLI Usage](#cli-usage)
9+
- [Tool Usage](#tool-usage)
10+
- [Parameters](#parameters)
11+
- [Result](#result)
12+
- [Examples](#examples)
13+
- [Testing](#testing)
14+
- [Unit Tests](#unit-tests)
15+
- [Integration Tests](#integration-tests)
16+
- [Getting Help](#getting-help)
17+
- [Access Level](#access-level)
18+
- [Implementation Notes](#implementation-notes)
19+
20+
## Usage
21+
22+
### CLI Usage
23+
24+
From the command line using the jtag CLI:
25+
26+
```bash
27+
./jtag runtime/metrics [options]
28+
```
29+
30+
### Tool Usage
31+
32+
From Persona tools or programmatic access using `Commands.execute()`:
33+
34+
```typescript
35+
import { Commands } from '@system/core/shared/Commands';
36+
37+
const result = await Commands.execute('runtime/metrics', {
38+
// your parameters here
39+
});
40+
```
41+
42+
## Parameters
43+
44+
- **mode** (optional): `'all' | 'module' | 'slow' | 'list'` - Query mode: 'all' for all modules (default), 'module' for specific module, 'slow' for recent slow commands, 'list' for module configs
45+
- **module** (optional): `string` - Module name when mode='module' (e.g., 'data', 'embedding', 'cognition')
46+
47+
## Result
48+
49+
Returns `RuntimeMetricsResult` with:
50+
51+
Returns CommandResult with:
52+
- **modules**: `ModuleMetrics[]` - Array of module metrics (when mode='all' or 'module')
53+
- **slowCommands**: `SlowCommand[]` - Array of slow commands (when mode='slow')
54+
- **moduleConfigs**: `ModuleConfig[]` - Array of module configurations (when mode='list')
55+
- **count**: `number` - Number of items in the result
56+
- **thresholdMs**: `number` - Slow command threshold in ms (when mode='slow')
57+
58+
## Examples
59+
60+
### Get metrics for all modules
61+
62+
```bash
63+
./jtag runtime/metrics
64+
```
65+
66+
**Expected result:**
67+
{ modules: [...], count: 13 }
68+
69+
### Get metrics for a specific module
70+
71+
```bash
72+
./jtag runtime/metrics --mode=module --module=embedding
73+
```
74+
75+
**Expected result:**
76+
{ modules: [{ moduleName: 'embedding', avgTimeMs: 90, p99Ms: 552, ... }], count: 1 }
77+
78+
### List recent slow commands
79+
80+
```bash
81+
./jtag runtime/metrics --mode=slow
82+
```
83+
84+
**Expected result:**
85+
{ slowCommands: [...], count: 5, thresholdMs: 50 }
86+
87+
### List all module configurations
88+
89+
```bash
90+
./jtag runtime/metrics --mode=list
91+
```
92+
93+
**Expected result:**
94+
{ moduleConfigs: [...], count: 13 }
95+
96+
## Getting Help
97+
98+
### Using the Help Tool
99+
100+
Get detailed usage information for this command:
101+
102+
**CLI:**
103+
```bash
104+
./jtag help runtime/metrics
105+
```
106+
107+
**Tool:**
108+
```typescript
109+
// Use your help tool with command name 'runtime/metrics'
110+
```
111+
112+
### Using the README Tool
113+
114+
Access this README programmatically:
115+
116+
**CLI:**
117+
```bash
118+
./jtag readme runtime/metrics
119+
```
120+
121+
**Tool:**
122+
```typescript
123+
// Use your readme tool with command name 'runtime/metrics'
124+
```
125+
126+
## Testing
127+
128+
### Unit Tests
129+
130+
Test command logic in isolation using mock dependencies:
131+
132+
```bash
133+
# Run unit tests (no server required)
134+
npx tsx commands/Runtime Metrics/test/unit/RuntimeMetricsCommand.test.ts
135+
```
136+
137+
**What's tested:**
138+
- Command structure and parameter validation
139+
- Mock command execution patterns
140+
- Required parameter validation (throws ValidationError)
141+
- Optional parameter handling (sensible defaults)
142+
- Performance requirements
143+
- Assertion utility helpers
144+
145+
**TDD Workflow:**
146+
1. Write/modify unit test first (test-driven development)
147+
2. Run test, see it fail
148+
3. Implement feature
149+
4. Run test, see it pass
150+
5. Refactor if needed
151+
152+
### Integration Tests
153+
154+
Test command with real client connections and system integration:
155+
156+
```bash
157+
# Prerequisites: Server must be running
158+
npm start # Wait 90+ seconds for deployment
159+
160+
# Run integration tests
161+
npx tsx commands/Runtime Metrics/test/integration/RuntimeMetricsIntegration.test.ts
162+
```
163+
164+
**What's tested:**
165+
- Client connection to live system
166+
- Real command execution via WebSocket
167+
- ValidationError handling for missing params
168+
- Optional parameter defaults
169+
- Performance under load
170+
- Various parameter combinations
171+
172+
**Best Practice:**
173+
Run unit tests frequently during development (fast feedback). Run integration tests before committing (verify system integration).
174+
175+
## Access Level
176+
177+
**ai-safe** - Safe for AI personas to call autonomously
178+
179+
## Implementation Notes
180+
181+
- **Shared Logic**: Core business logic in `shared/RuntimeMetricsTypes.ts`
182+
- **Browser**: Browser-specific implementation in `browser/RuntimeMetricsBrowserCommand.ts`
183+
- **Server**: Server-specific implementation in `server/RuntimeMetricsServerCommand.ts`
184+
- **Unit Tests**: Isolated testing in `test/unit/RuntimeMetricsCommand.test.ts`
185+
- **Integration Tests**: System testing in `test/integration/RuntimeMetricsIntegration.test.ts`
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* Runtime Metrics Command - Browser Implementation
3+
*
4+
* Query Rust module performance metrics including latency percentiles, command counts, and slow command tracking. Enables AI-driven system analysis and optimization.
5+
*/
6+
7+
import { CommandBase, type ICommandDaemon } from '@daemons/command-daemon/shared/CommandBase';
8+
import type { JTAGContext } from '@system/core/types/JTAGTypes';
9+
import type { RuntimeMetricsParams, RuntimeMetricsResult } from '../shared/RuntimeMetricsTypes';
10+
11+
export class RuntimeMetricsBrowserCommand extends CommandBase<RuntimeMetricsParams, RuntimeMetricsResult> {
12+
13+
constructor(context: JTAGContext, subpath: string, commander: ICommandDaemon) {
14+
super('runtime/metrics', context, subpath, commander);
15+
}
16+
17+
async execute(params: RuntimeMetricsParams): Promise<RuntimeMetricsResult> {
18+
console.log('🌐 BROWSER: Delegating Runtime Metrics to server');
19+
return await this.remoteExecute(params);
20+
}
21+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
{
2+
"name": "@jtag-commands/runtime/metrics",
3+
"version": "1.0.0",
4+
"description": "Query Rust module performance metrics including latency percentiles, command counts, and slow command tracking. Enables AI-driven system analysis and optimization.",
5+
"main": "server/RuntimeMetricsServerCommand.ts",
6+
"types": "shared/RuntimeMetricsTypes.ts",
7+
"scripts": {
8+
"test": "npm run test:unit && npm run test:integration",
9+
"test:unit": "npx vitest run test/unit/*.test.ts",
10+
"test:integration": "npx tsx test/integration/RuntimeMetricsIntegration.test.ts",
11+
"lint": "npx eslint **/*.ts",
12+
"typecheck": "npx tsc --noEmit"
13+
},
14+
"peerDependencies": {
15+
"@jtag/core": "*"
16+
},
17+
"files": [
18+
"shared/**/*.ts",
19+
"browser/**/*.ts",
20+
"server/**/*.ts",
21+
"test/**/*.ts",
22+
"README.md"
23+
],
24+
"keywords": [
25+
"jtag",
26+
"command",
27+
"runtime/metrics"
28+
],
29+
"license": "MIT",
30+
"author": "",
31+
"repository": {
32+
"type": "git",
33+
"url": ""
34+
}
35+
}

0 commit comments

Comments
 (0)