forked from Yeachan-Heo/oh-my-claudecode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-background-tasks.ts
More file actions
288 lines (240 loc) · 10 KB
/
test-background-tasks.ts
File metadata and controls
288 lines (240 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/**
* Comprehensive test for background task management
* Run with: npx tsx test-background-tasks.ts
*/
import {
createSisyphusSession,
shouldRunInBackground,
DEFAULT_MAX_BACKGROUND_TASKS,
LONG_RUNNING_PATTERNS,
BLOCKING_PATTERNS,
} from './dist/index.js';
// Test colors for output
const green = (s: string) => `\x1b[32m${s}\x1b[0m`;
const red = (s: string) => `\x1b[31m${s}\x1b[0m`;
const yellow = (s: string) => `\x1b[33m${s}\x1b[0m`;
const blue = (s: string) => `\x1b[34m${s}\x1b[0m`;
let testsPassed = 0;
let testsFailed = 0;
function test(name: string, fn: () => boolean | void) {
try {
const result = fn();
if (result === false) {
console.log(red(`✗ ${name}`));
testsFailed++;
} else {
console.log(green(`✓ ${name}`));
testsPassed++;
}
} catch (e) {
console.log(red(`✗ ${name}`));
console.log(red(` Error: ${e}`));
testsFailed++;
}
}
function assertEqual<T>(actual: T, expected: T, msg?: string): boolean {
if (actual !== expected) {
console.log(red(` Expected: ${expected}, Got: ${actual}${msg ? ` (${msg})` : ''}`));
return false;
}
return true;
}
console.log(blue('\n═══════════════════════════════════════════════════════════'));
console.log(blue(' Background Task Management Tests'));
console.log(blue('═══════════════════════════════════════════════════════════\n'));
// ============================================
// Test 1: Pattern Detection - Long Running Commands
// ============================================
console.log(yellow('\n▸ Testing Long-Running Pattern Detection\n'));
const longRunningCommands = [
'npm install',
'npm ci',
'yarn install',
'pnpm install',
'pip install requests',
'cargo build',
'cargo test',
'go build ./...',
'npm run build',
'npm run test',
'make all',
'docker build -t myapp .',
'docker pull nginx',
'git clone https://github.com/example/repo.git',
'pytest tests/',
'jest --coverage',
'vitest',
'prisma migrate deploy',
'webpack --mode production',
];
for (const cmd of longRunningCommands) {
test(`Long-running: "${cmd}" should run in background`, () => {
const decision = shouldRunInBackground(cmd);
return assertEqual(decision.runInBackground, true, cmd);
});
}
// ============================================
// Test 2: Pattern Detection - Quick/Blocking Commands
// ============================================
console.log(yellow('\n▸ Testing Blocking Pattern Detection\n'));
const blockingCommands = [
'ls -la',
'pwd',
'cat file.txt',
'echo "hello"',
'git status',
'git diff',
'git log --oneline -5',
'head -10 file.txt',
'tail -20 log.txt',
'which node',
'env',
'cp src dest',
'mv old new',
'mkdir newdir',
];
for (const cmd of blockingCommands) {
test(`Blocking: "${cmd}" should NOT run in background`, () => {
const decision = shouldRunInBackground(cmd);
return assertEqual(decision.runInBackground, false, cmd);
});
}
// ============================================
// Test 3: Concurrency Limit Enforcement
// ============================================
console.log(yellow('\n▸ Testing Concurrency Limits\n'));
test('At capacity: should NOT allow background even for long command', () => {
const decision = shouldRunInBackground('npm install', 5, 5); // at limit
return assertEqual(decision.runInBackground, false) &&
decision.reason.includes('limit');
});
test('Under capacity: should allow background for long command', () => {
const decision = shouldRunInBackground('npm install', 2, 5); // under limit
return assertEqual(decision.runInBackground, true);
});
test('Default max tasks is 5', () => {
return assertEqual(DEFAULT_MAX_BACKGROUND_TASKS, 5);
});
// ============================================
// Test 4: TaskExecutionDecision Metadata
// ============================================
console.log(yellow('\n▸ Testing Decision Metadata\n'));
test('Long-running command has high confidence', () => {
const decision = shouldRunInBackground('npm install');
return assertEqual(decision.confidence, 'high') &&
assertEqual(decision.estimatedDuration, 'long');
});
test('Quick command has high confidence', () => {
const decision = shouldRunInBackground('ls -la');
return assertEqual(decision.confidence, 'high') &&
assertEqual(decision.estimatedDuration, 'quick');
});
test('Unknown command has low confidence', () => {
const decision = shouldRunInBackground('some-unknown-command --flag');
return assertEqual(decision.confidence, 'low') &&
assertEqual(decision.estimatedDuration, 'unknown');
});
// ============================================
// Test 5: BackgroundTaskManager
// ============================================
console.log(yellow('\n▸ Testing BackgroundTaskManager\n'));
test('Session includes BackgroundTaskManager', () => {
const session = createSisyphusSession({ skipConfigLoad: true });
return session.backgroundTasks !== undefined &&
typeof session.backgroundTasks.registerTask === 'function' &&
typeof session.backgroundTasks.getTasks === 'function' &&
typeof session.backgroundTasks.canStartNewTask === 'function';
});
test('Session includes shouldRunInBackground method', () => {
const session = createSisyphusSession({ skipConfigLoad: true });
return typeof session.shouldRunInBackground === 'function';
});
test('Manager tracks registered tasks', () => {
const session = createSisyphusSession({ skipConfigLoad: true });
const task = session.backgroundTasks.registerTask('test-agent', 'test prompt');
return task.id !== undefined &&
task.status === 'pending' &&
session.backgroundTasks.getTasks().length === 1;
});
test('Manager enforces capacity limits', () => {
const session = createSisyphusSession({
skipConfigLoad: true,
config: { permissions: { maxBackgroundTasks: 2 } }
});
// Register 2 tasks
session.backgroundTasks.registerTask('agent1', 'prompt1');
session.backgroundTasks.registerTask('agent2', 'prompt2');
// Should be at capacity
return assertEqual(session.backgroundTasks.canStartNewTask(), false);
});
test('Manager updates task status', () => {
const session = createSisyphusSession({ skipConfigLoad: true });
const task = session.backgroundTasks.registerTask('test-agent', 'test prompt');
session.backgroundTasks.completeTask(task.id, 'success result');
const tasks = session.backgroundTasks.getTasks();
return tasks[0].status === 'completed' && tasks[0].result === 'success result';
});
test('Manager prunes completed tasks', () => {
const session = createSisyphusSession({ skipConfigLoad: true });
const task1 = session.backgroundTasks.registerTask('agent1', 'prompt1');
session.backgroundTasks.registerTask('agent2', 'prompt2');
session.backgroundTasks.completeTask(task1.id, 'done');
const pruned = session.backgroundTasks.pruneCompletedTasks();
return pruned === 1 && session.backgroundTasks.getTasks().length === 1;
});
// ============================================
// Test 6: System Prompt Integration
// ============================================
console.log(yellow('\n▸ Testing System Prompt Integration\n'));
test('System prompt includes background task guidance', () => {
const session = createSisyphusSession({ skipConfigLoad: true });
const systemPrompt = session.queryOptions.options.systemPrompt;
return systemPrompt.includes('Background Task Execution') &&
systemPrompt.includes('run_in_background') &&
systemPrompt.includes('TaskOutput');
});
test('System prompt includes concurrency limit info', () => {
const session = createSisyphusSession({ skipConfigLoad: true });
const systemPrompt = session.queryOptions.options.systemPrompt;
return systemPrompt.includes('Maximum') &&
systemPrompt.includes('concurrent background tasks');
});
// ============================================
// Test 7: Pattern Coverage
// ============================================
console.log(yellow('\n▸ Testing Pattern Coverage\n'));
test('LONG_RUNNING_PATTERNS array is populated', () => {
return LONG_RUNNING_PATTERNS.length > 10;
});
test('BLOCKING_PATTERNS array is populated', () => {
return BLOCKING_PATTERNS.length > 5;
});
// Complex command chain detection
test('Complex piped commands without blocking start suggest background', () => {
// Note: commands starting with blocking patterns (cat, ls, etc.) will be detected as blocking
// Only chains that don't start with blocking patterns will be detected as potentially long
const decision = shouldRunInBackground('find . -name "*.ts" | xargs grep "import" | sort | uniq -c');
// Has >2 pipes, might be long
return decision.estimatedDuration === 'medium' || decision.runInBackground === true;
});
test('Commands starting with blocking patterns stay blocking even if piped', () => {
// cat is a blocking pattern, so this should be blocking
const decision = shouldRunInBackground('cat log.txt | grep error');
return decision.runInBackground === false;
});
// ============================================
// Summary
// ============================================
console.log(blue('\n═══════════════════════════════════════════════════════════'));
console.log(blue(' Test Summary'));
console.log(blue('═══════════════════════════════════════════════════════════\n'));
console.log(`${green(`Passed: ${testsPassed}`)}`);
console.log(`${testsFailed > 0 ? red(`Failed: ${testsFailed}`) : green(`Failed: ${testsFailed}`)}`);
console.log(`Total: ${testsPassed + testsFailed}`);
if (testsFailed > 0) {
console.log(red('\n✗ Some tests failed!\n'));
process.exit(1);
} else {
console.log(green('\n✓ All tests passed!\n'));
process.exit(0);
}