cli4ai 0.8.2 → 0.8.3

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.
@@ -10,9 +10,10 @@
10
10
  * - within a scope: .routine.json before .routine.sh
11
11
  */
12
12
 
13
- import { existsSync, readdirSync, statSync } from 'fs';
13
+ import { existsSync, readdirSync, statSync, readFileSync } from 'fs';
14
14
  import { resolve } from 'path';
15
15
  import { ensureCli4aiHome, ensureLocalDir, ROUTINES_DIR, LOCAL_ROUTINES_DIR } from './config.js';
16
+ import { validateScheduleConfig, type RoutineSchedule } from './routine-engine.js';
16
17
 
17
18
  export type RoutineKind = 'json' | 'bash';
18
19
  export type RoutineScope = 'local' | 'global';
@@ -109,3 +110,59 @@ export function resolveRoutine(name: string, projectDir: string, options: Resolv
109
110
  return null;
110
111
  }
111
112
 
113
+ // ═══════════════════════════════════════════════════════════════════════════
114
+ // SCHEDULED ROUTINES
115
+ // ═══════════════════════════════════════════════════════════════════════════
116
+
117
+ export interface ScheduledRoutineInfo extends RoutineInfo {
118
+ schedule: RoutineSchedule;
119
+ }
120
+
121
+ /**
122
+ * Get all routines that have a schedule defined.
123
+ * Only JSON routines can have schedules (bash scripts cannot).
124
+ * Searches both local (if projectDir provided) and global routines.
125
+ */
126
+ export function getScheduledRoutines(projectDir?: string): ScheduledRoutineInfo[] {
127
+ const results: ScheduledRoutineInfo[] = [];
128
+ const seen = new Set<string>();
129
+
130
+ // Collect all JSON routines
131
+ const allRoutines: RoutineInfo[] = [];
132
+
133
+ if (projectDir) {
134
+ allRoutines.push(...getLocalRoutines(projectDir).filter(r => r.kind === 'json'));
135
+ }
136
+ allRoutines.push(...getGlobalRoutines().filter(r => r.kind === 'json'));
137
+
138
+ for (const routine of allRoutines) {
139
+ // Skip if we've already processed a routine with this name (local takes precedence)
140
+ if (seen.has(routine.name)) continue;
141
+ seen.add(routine.name);
142
+
143
+ try {
144
+ const content = readFileSync(routine.path, 'utf-8');
145
+ const data = JSON.parse(content);
146
+
147
+ if (data.schedule && typeof data.schedule === 'object') {
148
+ // Check if schedule is enabled (defaults to true)
149
+ const enabled = (data.schedule as Record<string, unknown>).enabled !== false;
150
+ if (!enabled) continue;
151
+
152
+ try {
153
+ const schedule = validateScheduleConfig(data.schedule, routine.path);
154
+ results.push({
155
+ ...routine,
156
+ schedule
157
+ });
158
+ } catch {
159
+ // Skip routines with invalid schedule configs (don't crash the scheduler)
160
+ }
161
+ }
162
+ } catch {
163
+ // Skip invalid JSON files
164
+ }
165
+ }
166
+
167
+ return results;
168
+ }
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Scheduler daemon entry point.
4
+ *
5
+ * This script runs as a background process and manages scheduled routine execution.
6
+ * It's spawned by `cli4ai scheduler start` with detached mode.
7
+ *
8
+ * Usage: bun scheduler-daemon.ts [--project-dir <dir>]
9
+ */
10
+
11
+ import { Scheduler, writeDaemonPid, removeDaemonPid, appendSchedulerLog, SCHEDULER_LOG_FILE, ensureSchedulerDirs } from './scheduler.js';
12
+ import { createWriteStream } from 'fs';
13
+ import { ensureCli4aiHome } from './config.js';
14
+
15
+ // Parse arguments
16
+ const args = process.argv.slice(2);
17
+ let projectDir: string | undefined;
18
+
19
+ for (let i = 0; i < args.length; i++) {
20
+ if (args[i] === '--project-dir' && args[i + 1]) {
21
+ projectDir = args[i + 1];
22
+ i++;
23
+ }
24
+ }
25
+
26
+ // Ensure directories exist
27
+ ensureCli4aiHome();
28
+ ensureSchedulerDirs();
29
+
30
+ // Redirect stdout/stderr to log file (when running detached)
31
+ if (process.env.CLI4AI_DAEMON === 'true') {
32
+ const logStream = createWriteStream(SCHEDULER_LOG_FILE, { flags: 'a' });
33
+
34
+ // Redirect console output
35
+ const originalLog = console.log;
36
+ const originalError = console.error;
37
+
38
+ console.log = (...args) => {
39
+ const message = args.map(a => typeof a === 'string' ? a : JSON.stringify(a)).join(' ');
40
+ logStream.write(`[${new Date().toISOString()}] [STDOUT] ${message}\n`);
41
+ };
42
+
43
+ console.error = (...args) => {
44
+ const message = args.map(a => typeof a === 'string' ? a : JSON.stringify(a)).join(' ');
45
+ logStream.write(`[${new Date().toISOString()}] [STDERR] ${message}\n`);
46
+ };
47
+
48
+ // Handle uncaught errors
49
+ process.on('uncaughtException', (err) => {
50
+ appendSchedulerLog('error', `Uncaught exception: ${err.message}\n${err.stack}`);
51
+ process.exit(1);
52
+ });
53
+
54
+ process.on('unhandledRejection', (reason) => {
55
+ appendSchedulerLog('error', `Unhandled rejection: ${reason}`);
56
+ });
57
+ }
58
+
59
+ // Write PID file
60
+ writeDaemonPid(process.pid);
61
+ appendSchedulerLog('info', `Daemon started with PID ${process.pid}`);
62
+
63
+ // Create and start scheduler
64
+ const scheduler = new Scheduler({ projectDir });
65
+
66
+ // Handle shutdown signals
67
+ let shuttingDown = false;
68
+
69
+ async function shutdown(signal: string): Promise<void> {
70
+ if (shuttingDown) return;
71
+ shuttingDown = true;
72
+
73
+ appendSchedulerLog('info', `Received ${signal}, shutting down...`);
74
+
75
+ try {
76
+ await scheduler.stop();
77
+ removeDaemonPid();
78
+ appendSchedulerLog('info', 'Daemon stopped gracefully');
79
+ } catch (err) {
80
+ appendSchedulerLog('error', `Error during shutdown: ${err instanceof Error ? err.message : String(err)}`);
81
+ }
82
+
83
+ process.exit(0);
84
+ }
85
+
86
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
87
+ process.on('SIGINT', () => shutdown('SIGINT'));
88
+
89
+ // Start the scheduler
90
+ scheduler.start().catch(err => {
91
+ appendSchedulerLog('error', `Failed to start scheduler: ${err instanceof Error ? err.message : String(err)}`);
92
+ removeDaemonPid();
93
+ process.exit(1);
94
+ });
@@ -0,0 +1,291 @@
1
+ /**
2
+ * Tests for scheduler core functionality.
3
+ */
4
+
5
+ import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
6
+ import { rmSync, existsSync, readdirSync } from 'fs';
7
+ import { join } from 'path';
8
+ import {
9
+ parseInterval,
10
+ getNextRunTime,
11
+ isDaemonRunning,
12
+ getDaemonPid,
13
+ writeDaemonPid,
14
+ removeDaemonPid,
15
+ loadSchedulerState,
16
+ saveSchedulerState,
17
+ saveRunRecord,
18
+ getRunHistory,
19
+ Scheduler,
20
+ SCHEDULER_PID_FILE,
21
+ SCHEDULER_STATE_FILE,
22
+ SCHEDULER_RUNS_DIR,
23
+ type SchedulerState,
24
+ type SchedulerRunRecord
25
+ } from './scheduler.js';
26
+ import { validateScheduleConfig, type RoutineSchedule } from './routine-engine.js';
27
+
28
+ // ═══════════════════════════════════════════════════════════════════════════
29
+ // INTERVAL PARSING TESTS
30
+ // ═══════════════════════════════════════════════════════════════════════════
31
+
32
+ describe('parseInterval', () => {
33
+ test('parses seconds', () => {
34
+ expect(parseInterval('30s')).toBe(30 * 1000);
35
+ expect(parseInterval('1s')).toBe(1000);
36
+ expect(parseInterval('120s')).toBe(120 * 1000);
37
+ });
38
+
39
+ test('parses minutes', () => {
40
+ expect(parseInterval('5m')).toBe(5 * 60 * 1000);
41
+ expect(parseInterval('1m')).toBe(60 * 1000);
42
+ expect(parseInterval('60m')).toBe(60 * 60 * 1000);
43
+ });
44
+
45
+ test('parses hours', () => {
46
+ expect(parseInterval('1h')).toBe(60 * 60 * 1000);
47
+ expect(parseInterval('24h')).toBe(24 * 60 * 60 * 1000);
48
+ });
49
+
50
+ test('parses days', () => {
51
+ expect(parseInterval('1d')).toBe(24 * 60 * 60 * 1000);
52
+ expect(parseInterval('7d')).toBe(7 * 24 * 60 * 60 * 1000);
53
+ });
54
+
55
+ test('throws on invalid format', () => {
56
+ expect(() => parseInterval('10')).toThrow();
57
+ expect(() => parseInterval('10x')).toThrow();
58
+ expect(() => parseInterval('abc')).toThrow();
59
+ expect(() => parseInterval('')).toThrow();
60
+ });
61
+ });
62
+
63
+ // ═══════════════════════════════════════════════════════════════════════════
64
+ // NEXT RUN TIME TESTS
65
+ // ═══════════════════════════════════════════════════════════════════════════
66
+
67
+ describe('getNextRunTime', () => {
68
+ test('calculates next run from interval', () => {
69
+ const now = new Date('2024-01-01T10:00:00Z');
70
+ const schedule: RoutineSchedule = { interval: '1h' };
71
+
72
+ const nextRun = getNextRunTime(schedule, now);
73
+
74
+ expect(nextRun).not.toBeNull();
75
+ expect(nextRun!.getTime()).toBe(now.getTime() + (60 * 60 * 1000));
76
+ });
77
+
78
+ test('calculates next run from cron', () => {
79
+ const now = new Date('2024-01-01T10:30:00Z');
80
+ const schedule: RoutineSchedule = { cron: '0 * * * *' }; // Every hour at :00
81
+
82
+ const nextRun = getNextRunTime(schedule, now);
83
+
84
+ expect(nextRun).not.toBeNull();
85
+ expect(nextRun!.getMinutes()).toBe(0);
86
+ expect(nextRun!.getHours()).toBe(11); // Next hour
87
+ });
88
+
89
+ test('returns earliest when both cron and interval specified', () => {
90
+ const now = new Date('2024-01-01T10:55:00Z');
91
+ const schedule: RoutineSchedule = {
92
+ cron: '0 * * * *', // 5 minutes until :00
93
+ interval: '30m' // 30 minutes
94
+ };
95
+
96
+ const nextRun = getNextRunTime(schedule, now);
97
+
98
+ expect(nextRun).not.toBeNull();
99
+ // Should be the cron time (5 min) not interval (30 min)
100
+ expect(nextRun!.getMinutes()).toBe(0);
101
+ });
102
+
103
+ test('returns null for invalid schedule', () => {
104
+ const schedule: RoutineSchedule = {} as RoutineSchedule;
105
+ const nextRun = getNextRunTime(schedule);
106
+ expect(nextRun).toBeNull();
107
+ });
108
+ });
109
+
110
+ // ═══════════════════════════════════════════════════════════════════════════
111
+ // SCHEDULE VALIDATION TESTS
112
+ // ═══════════════════════════════════════════════════════════════════════════
113
+
114
+ describe('validateScheduleConfig', () => {
115
+ test('validates interval schedule', () => {
116
+ const schedule = validateScheduleConfig({ interval: '1h' });
117
+ expect(schedule.interval).toBe('1h');
118
+ });
119
+
120
+ test('validates cron schedule', () => {
121
+ const schedule = validateScheduleConfig({ cron: '0 9 * * *' });
122
+ expect(schedule.cron).toBe('0 9 * * *');
123
+ });
124
+
125
+ test('validates all optional fields', () => {
126
+ const schedule = validateScheduleConfig({
127
+ interval: '1h',
128
+ timezone: 'Pacific/Auckland',
129
+ enabled: true,
130
+ retries: 3,
131
+ retryDelayMs: 60000,
132
+ concurrency: 'skip'
133
+ });
134
+
135
+ expect(schedule.timezone).toBe('Pacific/Auckland');
136
+ expect(schedule.enabled).toBe(true);
137
+ expect(schedule.retries).toBe(3);
138
+ expect(schedule.retryDelayMs).toBe(60000);
139
+ expect(schedule.concurrency).toBe('skip');
140
+ });
141
+
142
+ test('throws when missing cron and interval', () => {
143
+ expect(() => validateScheduleConfig({})).toThrow('Schedule must have "cron" or "interval"');
144
+ });
145
+
146
+ test('throws on invalid interval format', () => {
147
+ expect(() => validateScheduleConfig({ interval: 'invalid' })).toThrow('must be like "30s"');
148
+ });
149
+
150
+ test('throws on invalid cron format', () => {
151
+ expect(() => validateScheduleConfig({ cron: '* *' })).toThrow('must have 5 or 6 fields');
152
+ });
153
+
154
+ test('throws on invalid retries', () => {
155
+ expect(() => validateScheduleConfig({ interval: '1h', retries: -1 })).toThrow('non-negative integer');
156
+ expect(() => validateScheduleConfig({ interval: '1h', retries: 'abc' })).toThrow('non-negative integer');
157
+ });
158
+
159
+ test('throws on invalid concurrency', () => {
160
+ expect(() => validateScheduleConfig({ interval: '1h', concurrency: 'invalid' })).toThrow('"skip" or "queue"');
161
+ });
162
+ });
163
+
164
+ // ═══════════════════════════════════════════════════════════════════════════
165
+ // STATE MANAGEMENT TESTS
166
+ // ═══════════════════════════════════════════════════════════════════════════
167
+
168
+ describe('state management', () => {
169
+ // Note: These tests use the actual ~/.cli4ai/scheduler directory
170
+ // because paths are resolved at module import time
171
+
172
+ test('saves and loads scheduler state', () => {
173
+ // Clean up first
174
+ if (existsSync(SCHEDULER_STATE_FILE)) {
175
+ rmSync(SCHEDULER_STATE_FILE);
176
+ }
177
+
178
+ const state: SchedulerState = {
179
+ version: 1,
180
+ startedAt: new Date().toISOString(),
181
+ routines: {
182
+ 'test-routine': {
183
+ name: 'test-routine',
184
+ path: '/path/to/routine.json',
185
+ schedule: { interval: '1h' },
186
+ nextRunAt: new Date().toISOString(),
187
+ lastRunAt: null,
188
+ lastStatus: null,
189
+ running: false,
190
+ retryCount: 0
191
+ }
192
+ }
193
+ };
194
+
195
+ saveSchedulerState(state);
196
+ const loaded = loadSchedulerState();
197
+
198
+ expect(loaded).not.toBeNull();
199
+ expect(loaded!.version).toBe(1);
200
+ expect(loaded!.routines['test-routine'].name).toBe('test-routine');
201
+
202
+ // Clean up
203
+ rmSync(SCHEDULER_STATE_FILE);
204
+ });
205
+
206
+ test('returns null when no state file exists', () => {
207
+ // Ensure no state file exists
208
+ if (existsSync(SCHEDULER_STATE_FILE)) {
209
+ rmSync(SCHEDULER_STATE_FILE);
210
+ }
211
+
212
+ const state = loadSchedulerState();
213
+ expect(state).toBeNull();
214
+ });
215
+
216
+ test('saves and retrieves run records', () => {
217
+ // Clean up existing run files for this test
218
+ if (existsSync(SCHEDULER_RUNS_DIR)) {
219
+ const files = readdirSync(SCHEDULER_RUNS_DIR);
220
+ for (const f of files) {
221
+ if (f.startsWith('test-routine-')) {
222
+ rmSync(join(SCHEDULER_RUNS_DIR, f));
223
+ }
224
+ }
225
+ }
226
+
227
+ const record: SchedulerRunRecord = {
228
+ routine: 'test-routine',
229
+ startedAt: new Date().toISOString(),
230
+ finishedAt: new Date().toISOString(),
231
+ status: 'success',
232
+ exitCode: 0,
233
+ durationMs: 1234,
234
+ retryAttempt: 0
235
+ };
236
+
237
+ saveRunRecord(record);
238
+ const history = getRunHistory('test-routine');
239
+
240
+ expect(history.length).toBeGreaterThanOrEqual(1);
241
+ expect(history[0].routine).toBe('test-routine');
242
+ expect(history[0].status).toBe('success');
243
+ });
244
+ });
245
+
246
+ // ═══════════════════════════════════════════════════════════════════════════
247
+ // PID FILE TESTS
248
+ // ═══════════════════════════════════════════════════════════════════════════
249
+
250
+ describe('daemon PID management', () => {
251
+ // Note: These tests use the actual ~/.cli4ai/scheduler directory
252
+ // because paths are resolved at module import time
253
+
254
+ beforeEach(() => {
255
+ // Clean up any existing PID file
256
+ if (existsSync(SCHEDULER_PID_FILE)) {
257
+ rmSync(SCHEDULER_PID_FILE);
258
+ }
259
+ });
260
+
261
+ afterEach(() => {
262
+ // Clean up
263
+ if (existsSync(SCHEDULER_PID_FILE)) {
264
+ rmSync(SCHEDULER_PID_FILE);
265
+ }
266
+ });
267
+
268
+ test('writes and reads PID file', () => {
269
+ writeDaemonPid(12345);
270
+ const pid = getDaemonPid();
271
+ expect(pid).toBe(12345);
272
+ });
273
+
274
+ test('removes PID file', () => {
275
+ writeDaemonPid(12345);
276
+ removeDaemonPid();
277
+ const pid = getDaemonPid();
278
+ expect(pid).toBeNull();
279
+ });
280
+
281
+ test('returns null when no PID file', () => {
282
+ const pid = getDaemonPid();
283
+ expect(pid).toBeNull();
284
+ });
285
+
286
+ test('isDaemonRunning returns false for non-existent process', () => {
287
+ writeDaemonPid(999999); // Unlikely to be running
288
+ const running = isDaemonRunning();
289
+ expect(running).toBe(false);
290
+ });
291
+ });