0xray 2.1.4 → 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 (159) hide show
  1. package/dist/CHANGELOG.md +31 -0
  2. package/dist/cli/commands/govern.d.ts +29 -0
  3. package/dist/cli/commands/govern.js +152 -0
  4. package/dist/cli/index.js +29 -216
  5. package/dist/core/framework-logger.js +30 -1
  6. package/dist/delegation/index.d.ts +1 -2
  7. package/dist/delegation/index.js +1 -2
  8. package/dist/enforcement/enforcer-tools.js +1 -1
  9. package/dist/execution/proposal-applier.d.ts +1 -9
  10. package/dist/execution/proposal-applier.js +18 -173
  11. package/dist/governance/codex-policy.service.d.ts +7 -25
  12. package/dist/governance/codex-policy.service.js +8 -26
  13. package/dist/governance/governance-core.d.ts +22 -28
  14. package/dist/governance/governance-core.js +31 -101
  15. package/dist/governance/governance-service.d.ts +1 -0
  16. package/dist/governance/governance-service.js +67 -4
  17. package/dist/governance/governance-types.d.ts +5 -2
  18. package/dist/inference/index.d.ts +3 -4
  19. package/dist/inference/inference-accumulator.js +1 -1
  20. package/dist/inference/inference-cycle.d.ts +12 -18
  21. package/dist/inference/inference-cycle.js +120 -335
  22. package/dist/integrations/base/index.d.ts +0 -1
  23. package/dist/integrations/base/index.js +0 -2
  24. package/dist/integrations/grok/hooks/pre-tool-use.js +4 -18
  25. package/dist/integrations/hermes-agent/bridge.mjs +9 -0
  26. package/dist/mcps/config/server-config-registry.js +1 -1
  27. package/dist/mcps/governance.server.js +3 -4
  28. package/dist/mcps/knowledge-skills/api-design.server.js +10 -0
  29. package/dist/mcps/knowledge-skills/architecture-patterns.server.js +10 -0
  30. package/dist/mcps/knowledge-skills/bug-triage-specialist.server.js +10 -0
  31. package/dist/mcps/knowledge-skills/code-analyzer.server.js +10 -0
  32. package/dist/mcps/knowledge-skills/code-review.server.js +10 -0
  33. package/dist/mcps/knowledge-skills/content-creator.server.js +10 -0
  34. package/dist/mcps/knowledge-skills/database-design.server.js +10 -0
  35. package/dist/mcps/knowledge-skills/devops-deployment.server.js +10 -0
  36. package/dist/mcps/knowledge-skills/git-workflow.server.js +10 -0
  37. package/dist/mcps/knowledge-skills/growth-strategist.server.js +10 -0
  38. package/dist/mcps/knowledge-skills/log-monitor.server.js +10 -0
  39. package/dist/mcps/knowledge-skills/mobile-development.server.js +10 -0
  40. package/dist/mcps/knowledge-skills/multimodal-looker.server.js +10 -0
  41. package/dist/mcps/knowledge-skills/performance-optimization.server.js +10 -0
  42. package/dist/mcps/knowledge-skills/project-analysis.server.js +10 -0
  43. package/dist/mcps/knowledge-skills/refactoring-strategies.server.js +10 -0
  44. package/dist/mcps/knowledge-skills/security-audit.server.js +10 -0
  45. package/dist/mcps/knowledge-skills/seo-consultant.server.js +10 -0
  46. package/dist/mcps/knowledge-skills/skill-invocation.server.d.ts +4 -0
  47. package/dist/mcps/knowledge-skills/skill-invocation.server.js +33 -14
  48. package/dist/mcps/knowledge-skills/strategist.server.js +10 -0
  49. package/dist/mcps/knowledge-skills/tech-writer.server.js +10 -0
  50. package/dist/mcps/knowledge-skills/testing-strategy.server.js +10 -0
  51. package/dist/mcps/knowledge-skills/ui-ux-design.server.js +10 -0
  52. package/dist/metrics/agent-metrics.d.ts +2 -1
  53. package/dist/nucleus/govern-http.d.ts +59 -0
  54. package/dist/nucleus/govern-http.js +172 -0
  55. package/dist/nucleus/index.d.ts +14 -0
  56. package/dist/nucleus/index.js +9 -0
  57. package/dist/nucleus/kernel.d.ts +51 -0
  58. package/dist/nucleus/kernel.js +62 -0
  59. package/dist/nucleus/plugin-registry.d.ts +104 -0
  60. package/dist/nucleus/plugin-registry.js +147 -0
  61. package/dist/orchestrator/orchestrator.d.ts +0 -1
  62. package/dist/orchestrator/orchestrator.js +0 -21
  63. package/dist/postprocessor/PostProcessor.d.ts +13 -1
  64. package/dist/postprocessor/PostProcessor.js +41 -1
  65. package/dist/postprocessor/autofix/AutoFixEngine.d.ts +0 -8
  66. package/dist/postprocessor/autofix/AutoFixEngine.js +0 -54
  67. package/dist/postprocessor/metamorphosis/MetamorphosisEngine.d.ts +25 -0
  68. package/dist/postprocessor/metamorphosis/MetamorphosisEngine.js +10 -0
  69. package/dist/postprocessor/metamorphosis/SelfProposalEngine.d.ts +68 -0
  70. package/dist/postprocessor/metamorphosis/SelfProposalEngine.js +371 -0
  71. package/dist/skills/orchestrator/SKILL.md +1 -1
  72. package/dist/state/index.d.ts +0 -2
  73. package/package.json +4 -3
  74. package/scripts/node/universal-version-manager.js +2 -2
  75. package/src/mcps/config/__tests__/server-config-registry.test.ts +6 -15
  76. package/src/mcps/config/server-config-registry.ts +1 -1
  77. package/src/mcps/governance.server.ts +3 -5
  78. package/src/mcps/knowledge-skills/api-design.server.ts +9 -0
  79. package/src/mcps/knowledge-skills/architecture-patterns.server.ts +9 -0
  80. package/src/mcps/knowledge-skills/bug-triage-specialist.server.ts +9 -0
  81. package/src/mcps/knowledge-skills/code-analyzer.server.ts +9 -0
  82. package/src/mcps/knowledge-skills/code-review.server.ts +9 -0
  83. package/src/mcps/knowledge-skills/content-creator.server.ts +9 -0
  84. package/src/mcps/knowledge-skills/database-design.server.ts +9 -0
  85. package/src/mcps/knowledge-skills/devops-deployment.server.ts +9 -0
  86. package/src/mcps/knowledge-skills/git-workflow.server.ts +9 -0
  87. package/src/mcps/knowledge-skills/growth-strategist.server.ts +9 -0
  88. package/src/mcps/knowledge-skills/log-monitor.server.ts +9 -0
  89. package/src/mcps/knowledge-skills/mobile-development.server.ts +9 -0
  90. package/src/mcps/knowledge-skills/multimodal-looker.server.ts +9 -0
  91. package/src/mcps/knowledge-skills/performance-optimization.server.ts +9 -0
  92. package/src/mcps/knowledge-skills/project-analysis.server.ts +9 -0
  93. package/src/mcps/knowledge-skills/refactoring-strategies.server.ts +9 -0
  94. package/src/mcps/knowledge-skills/security-audit.server.ts +9 -0
  95. package/src/mcps/knowledge-skills/seo-consultant.server.ts +9 -0
  96. package/src/mcps/knowledge-skills/session-management.server.ts +1 -0
  97. package/src/mcps/knowledge-skills/skill-invocation.server.ts +44 -29
  98. package/src/mcps/knowledge-skills/strategist.server.ts +9 -0
  99. package/src/mcps/knowledge-skills/tech-writer.server.ts +9 -0
  100. package/src/mcps/knowledge-skills/testing-strategy.server.ts +9 -0
  101. package/src/mcps/knowledge-skills/ui-ux-design.server.ts +9 -0
  102. package/src/skills/orchestrator/SKILL.md +1 -1
  103. package/.opencode/agents/testing-best-practices.yml +0 -12
  104. package/dist/analytics/consent-manager.d.ts +0 -93
  105. package/dist/analytics/consent-manager.js +0 -258
  106. package/dist/analytics/simple-pattern-analyzer.d.ts +0 -80
  107. package/dist/analytics/simple-pattern-analyzer.js +0 -297
  108. package/dist/cli/commands/analytics-disable.d.ts +0 -9
  109. package/dist/cli/commands/analytics-disable.js +0 -72
  110. package/dist/cli/commands/analytics-enable-action.d.ts +0 -8
  111. package/dist/cli/commands/analytics-enable-action.js +0 -82
  112. package/dist/cli/commands/analytics-preview.d.ts +0 -9
  113. package/dist/cli/commands/analytics-preview.js +0 -106
  114. package/dist/cli/commands/analytics-status.d.ts +0 -9
  115. package/dist/cli/commands/analytics-status.js +0 -68
  116. package/dist/cli/server.d.ts +0 -1
  117. package/dist/cli/server.js +0 -147
  118. package/dist/core/errors.d.ts +0 -3
  119. package/dist/core/errors.js +0 -10
  120. package/dist/core/logging-config.d.ts +0 -11
  121. package/dist/core/logging-config.js +0 -43
  122. package/dist/core/trace-context.d.ts +0 -12
  123. package/dist/core/trace-context.js +0 -33
  124. package/dist/delegation/voting-coordinator.d.ts +0 -49
  125. package/dist/delegation/voting-coordinator.js +0 -375
  126. package/dist/enforcement/test-auto-healing.d.ts +0 -83
  127. package/dist/enforcement/test-auto-healing.js +0 -325
  128. package/dist/integrations/base/ExampleIntegration.d.ts +0 -47
  129. package/dist/integrations/base/ExampleIntegration.js +0 -181
  130. package/dist/mcps/knowledge-skills/testing-best-practices.server.d.ts +0 -34
  131. package/dist/mcps/knowledge-skills/testing-best-practices.server.js +0 -831
  132. package/dist/mcps/orchestrator.server.d.ts +0 -10
  133. package/dist/mcps/orchestrator.server.js +0 -19
  134. package/dist/orchestrator/self-direction-activation.d.ts +0 -109
  135. package/dist/orchestrator/self-direction-activation.js +0 -245
  136. package/dist/orchestrator/universal-librarian-consultation.d.ts +0 -98
  137. package/dist/orchestrator/universal-librarian-consultation.js +0 -216
  138. package/dist/orchestrator/universal-registry-bridge.d.ts +0 -85
  139. package/dist/orchestrator/universal-registry-bridge.js +0 -247
  140. package/dist/performance/performance-budget-enforcer.d.ts +0 -158
  141. package/dist/performance/performance-budget-enforcer.js +0 -434
  142. package/dist/performance/performance-regression-tester.d.ts +0 -108
  143. package/dist/performance/performance-regression-tester.js +0 -342
  144. package/dist/skills/testing-best-practices/SKILL.md +0 -37
  145. package/dist/state/context-providers.d.ts +0 -4
  146. package/dist/state/context-providers.js +0 -1
  147. package/dist/state/state-types.d.ts +0 -5
  148. package/dist/state/state-types.js +0 -1
  149. package/dist/utils/batch-operations.d.ts +0 -25
  150. package/dist/utils/batch-operations.js +0 -292
  151. package/dist/utils/test-template-generator.d.ts +0 -25
  152. package/dist/utils/test-template-generator.js +0 -178
  153. package/dist/utils/token-manager.d.ts +0 -48
  154. package/dist/utils/token-manager.js +0 -163
  155. package/src/mcps/knowledge-skills/testing-best-practices.server.test.ts +0 -136
  156. package/src/mcps/knowledge-skills/testing-best-practices.server.ts +0 -1183
  157. package/src/mcps/orchestrator.server.ts +0 -34
  158. package/src/opencode/agents/testing-best-practices.yml +0 -12
  159. package/src/skills/testing-best-practices/SKILL.md +0 -37
@@ -1,292 +0,0 @@
1
- import { spawn } from "child_process";
2
- import * as fs from "fs";
3
- import * as path from "path";
4
- import { getBatchOperations } from "../core/features-config.js";
5
- /**
6
- * Validate operation is safe for command execution
7
- * Prevents command injection by validating patterns and replacements
8
- */
9
- function validateSafeString(str, operationType) {
10
- // Allow only alphanumeric, basic regex characters, and whitespace
11
- // SECURITY: Blocks shell metacharacters that could enable command injection
12
- const safePattern = /^[a-zA-Z0-9\s\-_.@\\{}()*+?^$.|<>]+$/;
13
- const isSafe = safePattern.test(str) && str.length <= 200;
14
- if (!isSafe) {
15
- const errorMsg = operationType
16
- ? `Invalid ${operationType} operation: ${str}`
17
- : `Invalid operation: ${str}`;
18
- throw new Error(errorMsg);
19
- }
20
- return isSafe;
21
- }
22
- /**
23
- * Validate operation type and pattern/replacement strings
24
- */
25
- function validateOperation(op) {
26
- // For FileOperation, validate the operation type
27
- if ("operation" in op) {
28
- const allowedOperations = ["replace", "append", "prepend", "delete"];
29
- if (!allowedOperations.includes(op.operation)) {
30
- throw new Error(`Invalid operation type: ${op.operation}`);
31
- }
32
- }
33
- // For ReplacementOperation, validate pattern/replacement strings
34
- if ("pattern" in op) {
35
- // Validate pattern string for command injection prevention
36
- if (op.pattern) {
37
- validateSafeString(op.pattern, 'pattern');
38
- }
39
- // Validate replacement string if it exists (ReplacementOperation only)
40
- if ("replacement" in op && op.replacement) {
41
- validateSafeString(op.replacement, 'replacement');
42
- }
43
- }
44
- // Validate content if it exists (FileOperation only)
45
- if ("content" in op && op.content) {
46
- validateSafeString(op.content, 'content');
47
- }
48
- }
49
- function escapeForSed(str) {
50
- return str.replace(/[\/&]/g, "\\$&");
51
- }
52
- function escapeForGrep(str) {
53
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
54
- }
55
- export async function batchReplace(files, operations) {
56
- const startTime = Date.now();
57
- const config = getBatchOperations();
58
- if (!config.enabled) {
59
- return executeSequential(files, operations, startTime);
60
- }
61
- const firstOperation = operations[0];
62
- if (config.prefer_sed_for_replacements &&
63
- operations.length === 1 &&
64
- firstOperation) {
65
- return executeSedBatch(files, firstOperation, startTime);
66
- }
67
- if (config.parallel_file_updates &&
68
- files.length > config.auto_batch_threshold) {
69
- return executeParallelBatch(files, operations, config.max_concurrent_edits, startTime);
70
- }
71
- return executeSequential(files, operations, startTime);
72
- }
73
- /**
74
- * Execute sed command using spawn to prevent command injection
75
- * SECURITY: Uses array arguments to prevent shell injection attacks
76
- */
77
- async function executeSedBatch(files, operation, startTime) {
78
- const errors = [];
79
- let filesModified = 0;
80
- const pattern = operation.isRegex
81
- ? operation.pattern
82
- : escapeForGrep(operation.pattern);
83
- const replacement = escapeForSed(operation.replacement);
84
- const sedFlags = operation.caseSensitive ? "g" : "gi";
85
- for (const file of files) {
86
- try {
87
- if (!fs.existsSync(file)) {
88
- errors.push({ file, error: "File not found" });
89
- continue;
90
- }
91
- // SECURITY FIX: Use spawn with array arguments to prevent command injection
92
- // This avoids shell interpretation and injection attacks
93
- const args = ["-i", "", `s/${pattern}/${replacement}/${sedFlags}`, file];
94
- await new Promise((resolve, reject) => {
95
- const sedProcess = spawn("sed", args);
96
- let stderr = "";
97
- sedProcess.stderr?.on("data", (data) => {
98
- stderr += data.toString();
99
- });
100
- sedProcess.on("close", (code) => {
101
- if (code === 0) {
102
- resolve();
103
- }
104
- else {
105
- reject(new Error(`sed failed with code ${code}: ${stderr}`));
106
- }
107
- });
108
- sedProcess.on("error", (err) => {
109
- reject(new Error(`Failed to spawn sed: ${err.message}`));
110
- });
111
- });
112
- filesModified++;
113
- }
114
- catch (err) {
115
- const errorMessage = err instanceof Error ? err.message : String(err);
116
- errors.push({ file, error: errorMessage });
117
- }
118
- }
119
- return {
120
- success: errors.length === 0,
121
- filesModified,
122
- errors,
123
- duration: Date.now() - startTime,
124
- };
125
- }
126
- async function executeParallelBatch(files, operations, maxConcurrent, startTime) {
127
- const errors = [];
128
- let filesModified = 0;
129
- const chunks = [];
130
- for (let i = 0; i < files.length; i += maxConcurrent) {
131
- chunks.push(files.slice(i, i + maxConcurrent));
132
- }
133
- for (const chunk of chunks) {
134
- const promises = chunk.map(async (file) => {
135
- try {
136
- await processFileOperations(file, operations);
137
- return { file, success: true };
138
- }
139
- catch (err) {
140
- const errorMessage = err instanceof Error ? err.message : String(err);
141
- return { file, success: false, error: errorMessage };
142
- }
143
- });
144
- const results = await Promise.all(promises);
145
- for (const result of results) {
146
- if (result.success) {
147
- filesModified++;
148
- }
149
- else if (result.error) {
150
- errors.push({ file: result.file, error: result.error });
151
- }
152
- }
153
- }
154
- return {
155
- success: errors.length === 0,
156
- filesModified,
157
- errors,
158
- duration: Date.now() - startTime,
159
- };
160
- }
161
- async function executeSequential(files, operations, startTime) {
162
- const errors = [];
163
- let filesModified = 0;
164
- for (const file of files) {
165
- try {
166
- await processFileOperations(file, operations);
167
- filesModified++;
168
- }
169
- catch (err) {
170
- const errorMessage = err instanceof Error ? err.message : String(err);
171
- errors.push({ file, error: errorMessage });
172
- }
173
- }
174
- return {
175
- success: errors.length === 0,
176
- filesModified,
177
- errors,
178
- duration: Date.now() - startTime,
179
- };
180
- }
181
- async function processFileOperations(filePath, operations) {
182
- if (!fs.existsSync(filePath)) {
183
- throw new Error(`File not found: ${filePath}`);
184
- }
185
- let content = fs.readFileSync(filePath, "utf-8");
186
- let modified = false;
187
- for (const op of operations) {
188
- const flags = op.caseSensitive ? "g" : "gi";
189
- const regex = op.isRegex
190
- ? new RegExp(op.pattern, flags)
191
- : new RegExp(escapeForGrep(op.pattern), flags);
192
- if (regex.test(content)) {
193
- content = content.replace(regex, op.replacement);
194
- modified = true;
195
- }
196
- }
197
- if (modified) {
198
- fs.writeFileSync(filePath, content, "utf-8");
199
- }
200
- }
201
- export async function batchFileOperations(operations) {
202
- const startTime = Date.now();
203
- const errors = [];
204
- let filesModified = 0;
205
- for (const op of operations) {
206
- try {
207
- switch (op.operation) {
208
- case "replace":
209
- if (op.pattern && op.content) {
210
- await processFileOperations(op.filePath, [
211
- { pattern: op.pattern, replacement: op.content },
212
- ]);
213
- }
214
- break;
215
- case "append":
216
- if (op.content) {
217
- const existing = fs.existsSync(op.filePath)
218
- ? fs.readFileSync(op.filePath, "utf-8")
219
- : "";
220
- fs.writeFileSync(op.filePath, existing + op.content, "utf-8");
221
- }
222
- break;
223
- case "prepend":
224
- if (op.content) {
225
- const existing = fs.existsSync(op.filePath)
226
- ? fs.readFileSync(op.filePath, "utf-8")
227
- : "";
228
- fs.writeFileSync(op.filePath, op.content + existing, "utf-8");
229
- }
230
- break;
231
- case "delete":
232
- if (fs.existsSync(op.filePath)) {
233
- fs.unlinkSync(op.filePath);
234
- }
235
- break;
236
- }
237
- filesModified++;
238
- }
239
- catch (err) {
240
- const errorMessage = err instanceof Error ? err.message : String(err);
241
- errors.push({ file: op.filePath, error: errorMessage });
242
- }
243
- }
244
- return {
245
- success: errors.length === 0,
246
- filesModified,
247
- errors,
248
- duration: Date.now() - startTime,
249
- };
250
- }
251
- export function findFilesWithPattern(directory, pattern, extensions = [".ts", ".tsx", ".js", ".jsx", ".json"]) {
252
- const results = [];
253
- function searchDir(dir) {
254
- const entries = fs.readdirSync(dir, { withFileTypes: true });
255
- for (const entry of entries) {
256
- const fullPath = path.join(dir, entry.name);
257
- if (entry.name.startsWith(".") || entry.name === "node_modules") {
258
- continue;
259
- }
260
- if (entry.isDirectory()) {
261
- searchDir(fullPath);
262
- }
263
- else if (entry.isFile()) {
264
- const ext = path.extname(entry.name);
265
- if (extensions.includes(ext)) {
266
- try {
267
- const content = fs.readFileSync(fullPath, "utf-8");
268
- if (content.includes(pattern)) {
269
- results.push(fullPath);
270
- }
271
- }
272
- catch {
273
- continue;
274
- }
275
- }
276
- }
277
- }
278
- }
279
- searchDir(directory);
280
- return results;
281
- }
282
- export async function bulkRename(directory, oldName, newName, extensions = [".ts", ".tsx", ".js", ".jsx"]) {
283
- const files = findFilesWithPattern(directory, oldName, extensions);
284
- return batchReplace(files, [
285
- {
286
- pattern: oldName,
287
- replacement: newName,
288
- isRegex: false,
289
- caseSensitive: true,
290
- },
291
- ]);
292
- }
@@ -1,25 +0,0 @@
1
- /**
2
- * Test Template Generator for 0xRay Framework
3
- *
4
- * Automatically generates test templates for different file types
5
- * to ensure consistent test coverage and structure.
6
- */
7
- export interface TestTemplateOptions {
8
- filePath: string;
9
- componentName?: string;
10
- exports?: string[];
11
- isReact?: boolean;
12
- isTypeScript?: boolean;
13
- }
14
- /**
15
- * Generate a test template based on file type and structure
16
- */
17
- export declare function generateTestTemplate(options: TestTemplateOptions): string;
18
- /**
19
- * Analyze a source file to extract exports for test generation
20
- */
21
- export declare function analyzeSourceFile(filePath: string): {
22
- exports: string[];
23
- isReact: boolean;
24
- isTypeScript: boolean;
25
- };
@@ -1,178 +0,0 @@
1
- /**
2
- * Test Template Generator for 0xRay Framework
3
- *
4
- * Automatically generates test templates for different file types
5
- * to ensure consistent test coverage and structure.
6
- */
7
- import { frameworkLogger } from "../core/framework-logger.js";
8
- import fs from "fs";
9
- /**
10
- * Generate a test template based on file type and structure
11
- */
12
- export function generateTestTemplate(options) {
13
- const { filePath, componentName, exports = [], isReact = false, isTypeScript = false, } = options;
14
- const fileName = filePath
15
- .split("/")
16
- .pop()
17
- ?.replace(/\.(ts|tsx|js|jsx)$/, "") || "Unknown";
18
- const testFileName = `${fileName}.test.${isTypeScript ? "ts" : "js"}${isReact ? "x" : ""}`;
19
- if (isReact) {
20
- return generateReactTestTemplate(fileName, componentName || fileName, isTypeScript);
21
- }
22
- return generateUnitTestTemplate(fileName, exports, isTypeScript);
23
- }
24
- /**
25
- * Generate React component test template
26
- */
27
- function generateReactTestTemplate(fileName, componentName, isTypeScript) {
28
- const typeAnnotation = isTypeScript ? ": RenderResult" : "";
29
- const typeImport = isTypeScript ? ", RenderResult" : "";
30
- return `import { render, screen } from '@testing-library/react';
31
- import { expect, describe, it${typeImport} } from '${isTypeScript ? "vitest" : "jest"}';
32
- import { ${componentName} } from './${fileName}';
33
-
34
- describe('${componentName}', () => {
35
- it('should render successfully', () => {
36
- const { container }${typeAnnotation} = render(<${componentName} />);
37
- expect(container).toBeInTheDocument();
38
- });
39
-
40
- it('should render with default props', () => {
41
- render(<${componentName} />);
42
- // Add specific assertions based on component behavior
43
- expect(screen.getByRole('generic')).toBeInTheDocument();
44
- });
45
-
46
- // Add more test cases based on component props and behavior
47
- // it('should handle prop changes', () => {
48
- // const { rerender } = render(<${componentName} prop="value" />);
49
- // expect(screen.getByText('value')).toBeInTheDocument();
50
- //
51
- // rerender(<${componentName} prop="newValue" />);
52
- // expect(screen.getByText('newValue')).toBeInTheDocument();
53
- // });
54
-
55
- // Add accessibility tests
56
- it('should be accessible', () => {
57
- const { container } = render(<${componentName} />);
58
- expect(container).toBeAccessible();
59
- });
60
- });
61
- `;
62
- }
63
- /**
64
- * Generate unit test template for utility functions/classes
65
- */
66
- function generateUnitTestTemplate(fileName, exports, isTypeScript) {
67
- const describeBlocks = exports
68
- .map((exportName) => {
69
- if (exportName.match(/^[A-Z]/)) {
70
- // Class export
71
- return generateClassTestTemplate(exportName);
72
- }
73
- else {
74
- // Function export
75
- return generateFunctionTestTemplate(exportName);
76
- }
77
- })
78
- .join("\n\n");
79
- return `import { expect, describe, it } from '${isTypeScript ? "vitest" : "jest"}';
80
- ${exports.length > 0 ? `import { ${exports.join(", ")} } from './${fileName}';` : `// import functions from './${fileName}'`}
81
-
82
- ${describeBlocks}
83
-
84
- describe('${fileName}', () => {
85
- // Add general module tests here
86
- it('should export expected functions', () => {
87
- ${exports.length > 0 ? exports.map((exp) => `expect(typeof ${exp}).toBe('function');`).join("\n ") : "// Add export tests"}
88
- });
89
- });
90
- `;
91
- }
92
- /**
93
- * Generate test template for a class
94
- */
95
- function generateClassTestTemplate(className) {
96
- return `describe('${className}', () => {
97
- let instance: ${className};
98
-
99
- beforeEach(() => {
100
- // instance = new ${className}();
101
- });
102
-
103
- it('should create instance successfully', () => {
104
- // expect(instance).toBeInstanceOf(${className});
105
- expect(true).toBe(true); // Placeholder test
106
- });
107
-
108
- // Add method tests
109
- // it('should have expected methods', () => {
110
- // expect(typeof instance.methodName).toBe('function');
111
- // });
112
-
113
- // Add property tests
114
- // it('should have expected properties', () => {
115
- // expect(instance.propertyName).toBeDefined();
116
- // });
117
- });`;
118
- }
119
- /**
120
- * Generate test template for a function
121
- */
122
- function generateFunctionTestTemplate(functionName) {
123
- return `describe('${functionName}', () => {
124
- it('should be a function', () => {
125
- expect(typeof ${functionName}).toBe('function');
126
- });
127
-
128
- it('should handle basic input', () => {
129
- // const result = ${functionName}(/* test input */);
130
- // expect(result).toBe(/* expected output */);
131
- expect(true).toBe(true); // Placeholder test
132
- });
133
-
134
- it('should handle edge cases', () => {
135
- // Test null, undefined, empty inputs
136
- // expect(() => ${functionName}(null)).toThrow();
137
- expect(true).toBe(true); // Placeholder test
138
- });
139
-
140
- // Add more specific test cases based on function behavior
141
- });`;
142
- }
143
- /**
144
- * Analyze a source file to extract exports for test generation
145
- */
146
- export function analyzeSourceFile(filePath) {
147
- try {
148
- const content = fs.readFileSync(filePath, "utf-8");
149
- const exports = [];
150
- const isReact = /\b(React|jsx?|tsx?)\b/.test(content) ||
151
- filePath.endsWith(".tsx") ||
152
- filePath.endsWith(".jsx");
153
- const isTypeScript = filePath.endsWith(".ts") || filePath.endsWith(".tsx");
154
- // Extract named exports
155
- const exportMatches = content.match(/export\s+(?:const|function|class|let|var)\s+(\w+)/g);
156
- if (exportMatches) {
157
- exportMatches.forEach((match) => {
158
- const nameMatch = match.match(/(?:const|function|class|let|var)\s+(\w+)/);
159
- if (nameMatch && nameMatch[1] && !exports.includes(nameMatch[1])) {
160
- exports.push(nameMatch[1]);
161
- }
162
- });
163
- }
164
- // Extract default export if no named exports found
165
- if (exports.length === 0 && /export\s+default/.test(content)) {
166
- const fileName = filePath
167
- .split("/")
168
- .pop()
169
- ?.replace(/\.(ts|tsx|js|jsx)$/, "") || "Component";
170
- exports.push(fileName.charAt(0).toUpperCase() + fileName.slice(1));
171
- }
172
- return { exports, isReact, isTypeScript };
173
- }
174
- catch (error) {
175
- frameworkLogger.log("test-template-generator", "analyze-file", "error", { error, message: `Error analyzing ${filePath}:` });
176
- return { exports: [], isReact: false, isTypeScript: false };
177
- }
178
- }
@@ -1,48 +0,0 @@
1
- export interface TokenLimits {
2
- maxPromptTokens: number;
3
- warningThreshold: number;
4
- modelLimits: Record<string, number>;
5
- }
6
- export interface ContextPruningConfig {
7
- enabled: boolean;
8
- aggressivePruning: boolean;
9
- preserveCriticalContext: boolean;
10
- }
11
- export declare class TokenManager {
12
- private config;
13
- constructor(configPath?: string);
14
- private loadConfig;
15
- /**
16
- * Estimate token count for text (rough approximation)
17
- * Uses 4 characters per token as a conservative estimate
18
- */
19
- estimateTokens(text: string): number;
20
- /**
21
- * Check if prompt exceeds limits
22
- */
23
- checkLimits(prompt: string, modelName?: string): {
24
- withinLimit: boolean;
25
- currentTokens: number;
26
- maxTokens: number;
27
- needsPruning: boolean;
28
- warning: boolean;
29
- };
30
- /**
31
- * Prune context to fit within token limits
32
- */
33
- pruneContext(context: string, targetTokens?: number): string;
34
- private extractCriticalSections;
35
- private extractSection;
36
- private extractNonCriticalContent;
37
- private pruneNonCriticalContent;
38
- /**
39
- * Generate warning message for token limits
40
- */
41
- generateWarning(limitCheck: ReturnType<TokenManager["checkLimits"]>): string;
42
- /**
43
- * Get current configuration
44
- */
45
- getConfig(): TokenLimits & {
46
- contextPruning: ContextPruningConfig;
47
- };
48
- }