-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
819 lines (726 loc) · 28.6 KB
/
Copy pathindex.ts
File metadata and controls
819 lines (726 loc) · 28.6 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
#!/usr/bin/env bun
import { Command } from 'commander';
import chalk from 'chalk';
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
import { createRequire } from 'module';
import { execSync } from 'child_process';
import { closeStaleOpenSessions, completeLatestSession, getLatestSession, setSessionJiraWorklogId } from './lib/db.js';
import { isClockifyEnabled } from './lib/credentials.js';
import { ensureNativeAddons } from './lib/ensure-native-addons.js';
import { DASHBOARD_PORT, DASHBOARD_URL, IS_DEV } from './lib/constants.js';
import type { Clockify as ClockifyType } from './clockify.js';
import { shouldFireEod } from './lib/eod.js';
import {
readEodState,
markEodFired,
setEodSnoozeUntil,
clearEodSnoozeUntil,
getUpdateSettings,
} from './lib/settings.js';
import { getUpdateCache, setUpdateCache, markNotifiedVersion } from './lib/update-cache.js';
import { notify } from './lib/notifier.js';
interface Project {
id: string;
name: string;
}
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const program = new Command();
// Clockify + Jira pull in axios (via follow-redirects), which in Bun triggers
// a tty WriteStream crash when loaded from a git hook context. Defer.
let _clockify: ClockifyType | null = null;
async function clockify(): Promise<ClockifyType> {
if (!_clockify) {
const { Clockify } = await import('./clockify.js');
_clockify = new Clockify();
}
return _clockify;
}
async function stopJiraTimer(...args: Parameters<typeof import('./lib/jira.js').stopJiraTimer>) {
const { stopJiraTimer: fn } = await import('./lib/jira.js');
return fn(...args);
}
async function getLocalProjects(): Promise<Project[]> {
const dataDir = path.join(__dirname, '../data');
const localProjectsPath = path.join(dataDir, 'local-projects.json');
try {
// Ensure the data directory exists
await fs.promises.mkdir(dataDir, { recursive: true });
// If the file does not exist, create it with an empty array
try {
await fs.promises.access(localProjectsPath, fs.constants.F_OK);
} catch {
await fs.promises.writeFile(localProjectsPath, '[]', 'utf8');
}
const data = await fs.promises.readFile(localProjectsPath, 'utf8');
return JSON.parse(data);
} catch (_error: unknown) {
return [];
}
}
async function getWorkspaceAndUser() {
const user = await (await clockify()).getUser();
if (!user) {
console.log(chalk.red('[index] Could not connect to Clockify. Please check your API key.'));
process.exit(1);
}
const workspaceId = user.defaultWorkspace;
const userId = user.id;
return {
workspaceId,
userId,
};
}
const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf-8'));
program.name('clocktopus').description('CLI time-tracking automation for Clockify').version(pkg.version);
program
.command('start')
.description('Start a new time entry. Select a project interactively.')
.argument('[message]', 'Description for the time entry')
.option('-j, --jira <ticket>', 'Jira ticket number')
.option('--no-billable', 'Mark the time entry as non-billable')
.action(async (message, options) => {
const { startTimer } = await import('./lib/start-timer.js');
if (!isClockifyEnabled()) {
if (!options.jira) {
console.error(chalk.red('Jira-only mode requires --jira <ticket>.'));
process.exit(1);
}
const description = (message && String(message).trim()) || options.jira;
await startTimer({ description, ticket: options.jira, projectId: null, billable: options.billable });
console.log(chalk.green(`Timer started for ${chalk.bold(options.jira)} (Jira-only mode).`));
return;
}
const { workspaceId } = await getWorkspaceAndUser();
let projects: Project[] = await (await clockify()).getProjects(workspaceId);
let localProjects = await getLocalProjects();
if (localProjects.length === 0) {
const allProjects = projects.map((p) => ({ id: p.id, name: p.name }));
const localProjectsPath = path.join(__dirname, '../data/local-projects.json');
fs.writeFileSync(localProjectsPath, JSON.stringify(allProjects, null, 2), 'utf8');
console.log(
chalk.green(
'All projects have been saved to data/local-projects.json. Please edit this file to select your preferred projects.',
),
);
localProjects = allProjects;
}
if (localProjects.length > 0) {
const localProjectIds = localProjects.map((p) => p.id);
projects = projects.filter((p) => localProjectIds.includes(p.id));
}
if (!projects || projects.length === 0) {
console.log(chalk.yellow('No projects found in your workspace.'));
return;
}
const inquirer = (await import('inquirer')).default;
const { selectedProjectId } = await inquirer.prompt([
{
type: 'list',
name: 'selectedProjectId',
message: 'Which project do you want to work on?',
choices: projects.map((p: { name: string; id: string }) => ({ name: p.name, value: p.id })),
},
]);
await startTimer({
description: message || options.jira || '',
ticket: options.jira ?? null,
projectId: selectedProjectId,
billable: options.billable,
});
const projectName = projects.find((p) => p.id === selectedProjectId)?.name;
console.log(chalk.green(`Timer started for project: ${chalk.bold(projectName)}`));
});
program
.command('stop')
.description('Stop the currently running time entry.')
.action(async () => {
const latestSession = getLatestSession();
if (isClockifyEnabled()) {
const { workspaceId, userId } = await getWorkspaceAndUser();
const stoppedEntry = await (await clockify()).stopTimer(workspaceId, userId);
if (!stoppedEntry) {
console.log(chalk.yellow('No timer was running.'));
return;
}
} else {
if (!latestSession || latestSession.completedAt) {
console.log(chalk.yellow('No timer was running.'));
return;
}
}
const completedAt = new Date().toISOString();
completeLatestSession(completedAt);
if (latestSession?.jiraTicket) {
const timeSpentSeconds = Math.round(
(new Date(completedAt).getTime() - new Date(latestSession.startedAt).getTime()) / 1000,
);
if (timeSpentSeconds >= 60) {
try {
const worklog = await stopJiraTimer(latestSession.jiraTicket, timeSpentSeconds);
if (worklog?.id) setSessionJiraWorklogId(latestSession.id, worklog.id);
} catch (error) {
console.error('Error stopping Jira timer:', error);
}
}
}
console.log(chalk.red('Timer stopped.'));
});
program
.command('status')
.description('Check the status of the current timer.')
.action(async () => {
if (isClockifyEnabled()) {
const { workspaceId, userId } = await getWorkspaceAndUser();
const activeEntry = await (await clockify()).getActiveTimer(workspaceId, userId);
if (activeEntry) {
const startTime = new Date(activeEntry.timeInterval.start);
const duration = (new Date().getTime() - startTime.getTime()) / 1000;
const hours = Math.floor(duration / 3600);
const minutes = Math.floor((duration % 3600) / 60);
console.log(chalk.green('🕒 A timer is currently running.'));
console.log(` - ${chalk.bold('Project:')} ${activeEntry.project.name}`);
console.log(` - ${chalk.bold('Running for:')} ${hours}h ${minutes}m`);
return;
}
console.log(chalk.yellow('No timer is currently running.'));
return;
}
// Jira-only mode: read from DB
const { getOpenSession } = await import('./lib/db.js');
const open = getOpenSession();
if (!open) {
console.log(chalk.yellow('No timer is currently running.'));
return;
}
const startTime = new Date(open.startedAt);
const duration = (new Date().getTime() - startTime.getTime()) / 1000;
const hours = Math.floor(duration / 3600);
const minutes = Math.floor((duration % 3600) / 60);
console.log(chalk.green('🕒 A timer is currently running (Jira-only mode).'));
if (open.jiraTicket) console.log(` - ${chalk.bold('Jira:')} ${open.jiraTicket}`);
console.log(` - ${chalk.bold('Description:')} ${open.description}`);
console.log(` - ${chalk.bold('Running for:')} ${hours}h ${minutes}m`);
});
function sleep(ms: number) {
return new Promise((res) => setTimeout(res, ms));
}
program
.command('monitor:run', { hidden: true })
.description('Run monitor in foreground (used by PM2).')
.action(async () => {
const creds = isClockifyEnabled() ? await getWorkspaceAndUser() : { workspaceId: '', userId: '' };
const { workspaceId, userId } = creds;
// Auto-close any session left open longer than this on monitor startup,
// so a PM2 restart after a long sleep doesn't accidentally bill the
// entire gap to Jira when the next idle/lock event fires.
const MAX_OPEN_SESSION_MS = 12 * 60 * 60 * 1000; // 12h
try {
const stale = closeStaleOpenSessions(MAX_OPEN_SESSION_MS);
if (stale.length > 0) {
console.log(
chalk.yellow(
`Auto-closed ${stale.length} stale open session(s) older than ${MAX_OPEN_SESSION_MS / 3600_000}h. ` +
`No Jira worklog was posted for these; review and log manually if needed.`,
),
);
for (const s of stale) {
console.log(
chalk.gray(` - id=${s.id} jira=${s.jiraTicket ?? '-'} startedAt=${s.startedAt} closedAt=${s.completedAt}`),
);
}
}
} catch (err) {
console.error(chalk.red('Failed to scan for stale open sessions:'), err);
}
async function runUpdateCheck() {
const settings = getUpdateSettings();
if (!settings.autoCheck) return;
const { getCurrentVersion, fetchLatestVersion, isUpdateAvailable } = await import('./lib/updater.js');
const latest = await fetchLatestVersion({ force: true });
if (!latest) return;
setUpdateCache({
latestVersion: latest.version,
publishedAt: latest.publishedAt,
checkedAt: new Date().toISOString(),
});
const current = getCurrentVersion();
if (!isUpdateAvailable(current, latest.version)) return;
if (!settings.notify) return;
const cache = getUpdateCache();
if (cache?.notifiedVersion === latest.version) return;
notify({
subtitle: 'Update available',
message: `Clocktopus ${latest.version} available — open dashboard to update`,
sound: false,
wait: false,
timeout: 8,
});
markNotifiedVersion(latest.version);
}
runUpdateCheck().catch((err) => console.error(chalk.red('Update check failed:'), err));
const updateCheckInterval = setInterval(
() => {
runUpdateCheck().catch((err) => console.error(chalk.red('Update check failed:'), err));
},
6 * 60 * 60 * 1000,
);
process.on('SIGTERM', () => clearInterval(updateCheckInterval));
process.on('SIGINT', () => clearInterval(updateCheckInterval));
async function stopTimerAndLog(reason: string) {
const clockifyOn = isClockifyEnabled();
const latestSession = getLatestSession();
if (clockifyOn) {
const activeEntry = await (await clockify()).getActiveTimer(workspaceId, userId);
if (!activeEntry) return false;
} else {
if (!latestSession || latestSession.completedAt) return false;
}
console.log(chalk.yellow(reason));
// Use idleTime to rewind end-of-work to the moment user actually went idle,
// so a weekend gap or long sleep doesn't get billed to Jira.
let idleSec = 0;
try {
const idleModule = await import('desktop-idle');
idleSec = Math.max(0, Math.floor(idleModule.default.getIdleTime() || 0));
} catch {}
let completedMs = Date.now() - idleSec * 1000;
if (latestSession) {
const startedMs = new Date(latestSession.startedAt).getTime();
// Don't let the adjusted end fall before start; floor at start+1s.
if (completedMs < startedMs) completedMs = startedMs + 1000;
}
const completedAt = new Date(completedMs).toISOString();
if (clockifyOn) {
const stoppedEntry = await (await clockify()).stopTimer(workspaceId, userId);
if (!stoppedEntry) return false;
}
completeLatestSession(completedAt, true);
if (latestSession?.jiraTicket) {
const timeSpentSeconds = Math.round(
(new Date(completedAt).getTime() - new Date(latestSession.startedAt).getTime()) / 1000,
);
if (timeSpentSeconds >= 60) {
try {
const worklog = await stopJiraTimer(latestSession.jiraTicket, timeSpentSeconds);
if (worklog?.id) setSessionJiraWorklogId(latestSession.id, worklog.id);
} catch (err) {
console.error('Error stopping Jira timer:', err);
}
}
}
console.log(chalk.red('Timer stopped.'));
return true;
}
// Safer restart w/ cooldown; only resume a recent auto-completed session
let lastResumeAt = 0;
let resuming = false;
const RESUME_COOLDOWN_MS = 10_000;
// Shared between lock-state and idle-time watchers so a resume triggered
// by one path disarms the other (otherwise both fire and we get two starts).
let isLocked = false;
let lastIdle = false;
async function safeRestartTimerIfNeeded() {
const now = Date.now();
if (resuming || now - lastResumeAt < RESUME_COOLDOWN_MS) return;
resuming = true;
// Gate concurrent callers immediately; refine on success/failure below.
lastResumeAt = now;
try {
// Small delay lets services settle after wake/activity
await sleep(800);
const latestSession = getLatestSession();
if (!latestSession) return;
const twoHoursAgo = Date.now() - 2 * 60 * 60 * 1000;
const completedMs = latestSession.completedAt ? new Date(latestSession.completedAt).getTime() : 0;
if (!latestSession.isAutoCompleted || completedMs <= twoHoursAgo) return;
if (isClockifyEnabled()) {
if (!latestSession.projectId) return;
const activeEntry = await (await clockify()).getActiveTimer(workspaceId, userId);
if (activeEntry) {
isLocked = false;
lastIdle = false;
return;
}
await (
await clockify()
).startTimer(
workspaceId,
latestSession.projectId,
latestSession.description,
latestSession.jiraTicket ?? undefined,
);
console.log(chalk.green('Timer restarted for the last used project.'));
lastResumeAt = Date.now();
isLocked = false;
lastIdle = false;
return;
}
// Jira-only resume: new DB session with a fresh uuid, same ticket.
// Re-read latest to guard against a concurrent insert from another path.
if (!latestSession.jiraTicket) return;
const fresh = getLatestSession();
if (fresh && !fresh.completedAt) {
isLocked = false;
lastIdle = false;
return;
}
const { v4: uuidv4 } = await import('uuid');
const { logSessionStart } = await import('./lib/db.js');
const sessionId = uuidv4();
const startedAt = new Date().toISOString();
logSessionStart(
sessionId,
latestSession.projectId ?? null,
latestSession.description,
startedAt,
latestSession.jiraTicket,
);
console.log(chalk.green(`Resumed Jira timer for ${latestSession.jiraTicket}.`));
lastResumeAt = Date.now();
isLocked = false;
lastIdle = false;
} finally {
resuming = false;
}
}
console.log(chalk.blue('Monitoring display events (Unified Log) and idle time...'));
let pollInterval: NodeJS.Timeout | null = null;
console.log(chalk.blue('Monitoring display/lock state (macos-notification-state) and idle time...'));
try {
if (process.platform === 'darwin') {
const nsModule = await import('macos-notification-state');
const getSessionState = nsModule.default?.getSessionState || nsModule.getSessionState;
if (!getSessionState) {
throw new Error('getSessionState not found in module');
}
// Verify the native addon actually works before setting up polling
const initialState = getSessionState();
console.log(chalk.gray(`Initial session state: ${initialState}`));
pollInterval = setInterval(async () => {
try {
const state = getSessionState();
const locked = state === 'SESSION_SCREEN_IS_LOCKED';
if (locked && !isLocked) {
isLocked = true;
await stopTimerAndLog('Screen is locked/off. Stopping timer...');
} else if (!locked && isLocked) {
console.log(chalk.green('Screen is unlocked/on. Attempting to restart timer...'));
await safeRestartTimerIfNeeded();
isLocked = false;
}
} catch (error) {
console.error('Error polling session state:', error);
if (pollInterval) {
clearInterval(pollInterval);
pollInterval = null;
console.error(chalk.red('Display monitoring disabled due to repeated errors.'));
}
}
}, 3000);
} else {
console.log(chalk.yellow('Display monitoring (lock state) is only supported on macOS. Skipping.'));
}
} catch (err) {
console.error(chalk.red('Failed to load macos-notification-state. Display monitoring will be disabled.'));
console.error(err);
}
const IDLE_THRESHOLD_SECONDS = 300; // 5 minutes
const idleInterval = setInterval(async () => {
try {
const idleModule = await import('desktop-idle');
const idleTime = idleModule.default.getIdleTime();
if (idleTime >= IDLE_THRESHOLD_SECONDS) {
const stopped = await stopTimerAndLog(`System idle for ${Math.floor(idleTime)} seconds. Stopping timer...`);
if (stopped) lastIdle = true;
} else {
// User active again → resume even if display log events were missed
if (lastIdle) {
await safeRestartTimerIfNeeded();
}
lastIdle = false;
}
} catch (e) {
// swallow; desktop-idle can occasionally throw on wake races
}
}, 5000);
const EOD_TICK_MS = 60_000;
function localDateString(d: Date): string {
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${y}-${m}-${day}`;
}
const eodInterval = setInterval(async () => {
try {
const { getOpenSession } = await import('./lib/db.js');
const open = getOpenSession();
const state = readEodState(!!open);
const decision = shouldFireEod({ now: new Date(), state });
if (decision === 'skip') return;
const today = localDateString(new Date());
const isPrimary = decision === 'fire-primary';
if (isPrimary) markEodFired(today);
notify(
{
subtitle: 'End of day',
message: 'Timer still running. Stop now?',
actions: ['Stop'],
closeLabel: isPrimary ? 'Snooze 15m' : 'Dismiss',
open: DASHBOARD_URL,
timeout: 1800,
},
async (err, _resp, meta) => {
if (err) {
console.error('EOD notification error:', err);
return;
}
const choice = meta?.activationValue;
const type = meta?.activationType;
if (choice === 'Stop') {
try {
await stopTimerAndLog('End-of-day reminder.');
} catch (e) {
console.error('EOD stop failed:', e);
}
clearEodSnoozeUntil();
} else if (isPrimary && type === 'closed') {
const snoozeUntil = new Date(Date.now() + 15 * 60_000).toISOString();
setEodSnoozeUntil(snoozeUntil);
}
},
);
if (!isPrimary) {
clearEodSnoozeUntil();
}
} catch (e) {
console.error('EOD tick error:', e);
}
}, EOD_TICK_MS);
function cleanupAndExit(code = 0) {
try {
clearInterval(idleInterval);
} catch {}
try {
clearInterval(eodInterval);
} catch {}
try {
if (pollInterval) clearInterval(pollInterval);
} catch {}
process.exit(code);
}
process.on('SIGINT', () => {
console.log(chalk.gray('\nStopping monitor...'));
cleanupAndExit(0);
});
process.on('SIGTERM', () => cleanupAndExit(0));
});
program
.command('dash')
.description(`Start the Clocktopus web dashboard on localhost:${DASHBOARD_PORT}.`)
.action(async () => {
const { startDashboard } = await import('./dashboard/server.js');
startDashboard();
});
const MONITOR_PM2_NAME = IS_DEV ? 'clocktopus-monitor-dev' : 'clocktopus-monitor';
const DASH_PM2_NAME = IS_DEV ? 'clocktopus-dash-dev' : 'clocktopus-dash';
const pm2Bin = path.join(path.dirname(createRequire(import.meta.url).resolve('pm2')), 'bin', 'pm2');
const bunBin = (() => {
try {
return execSync('which bun', { encoding: 'utf-8' }).trim();
} catch {
return 'bun';
}
})();
const pm2Cmd = `${bunBin} ${pm2Bin}`;
program
.command('update')
.description('Check for and install a newer clocktopus npm release.')
.option('--yes', 'Install without prompting.', false)
.option('--check', 'Only print current + latest, do not install.', false)
.action(async (opts: { yes: boolean; check: boolean }) => {
const { getCurrentVersion, fetchLatestVersion, isUpdateAvailable, runUpdate, stopMonitorIfRunning } = await import(
'./lib/updater.js'
);
const current = getCurrentVersion();
process.stdout.write(`Current: ${current}\n`);
const latest = await fetchLatestVersion({ force: true });
if (!latest) {
console.error(chalk.red('Could not reach the npm registry.'));
process.exit(1);
}
process.stdout.write(`Latest: ${latest.version}\n`);
if (!isUpdateAvailable(current, latest.version)) {
console.log(chalk.green('Already up to date.'));
return;
}
if (opts.check) return;
if (!opts.yes) {
const { simplePrompt } = await import('./lib/simple-prompt.js');
const answers = await simplePrompt([
{
type: 'confirm',
name: 'install',
message: `Install clocktopus ${latest.version}?`,
default: false,
},
]);
if (!answers.install) {
console.log('Cancelled.');
return;
}
}
console.log(chalk.blue('Stopping monitor (if running)…'));
await stopMonitorIfRunning();
console.log(chalk.blue('Installing…'));
try {
await runUpdate({ onLog: (line) => process.stdout.write(line + '\n') });
} catch (err) {
console.error(chalk.red(`Update failed: ${err instanceof Error ? err.message : String(err)}`));
process.exit(1);
}
console.log(chalk.green(`Updated to ${latest.version}. Restart monitor with: mrestart`));
});
program
.command('monitor')
.description('Start idle monitor as a background daemon.')
.action(async () => {
ensureNativeAddons();
const { execSync } = await import('child_process');
const bunPath = execSync('which bun', { encoding: 'utf-8' }).trim();
const scriptPath = path.join(__dirname, 'index.js');
try {
try {
execSync(`${pm2Cmd} delete ${MONITOR_PM2_NAME}`, { stdio: 'ignore' });
} catch {}
execSync(`${pm2Cmd} start ${scriptPath} --name ${MONITOR_PM2_NAME} --interpreter ${bunPath} -- monitor:run`, {
stdio: 'inherit',
});
console.log(chalk.green('Idle monitor started in background.'));
console.log(chalk.gray(' Stop: clocktopus monitor:stop'));
console.log(chalk.gray(' Logs: clocktopus monitor:logs'));
} catch {
console.error(chalk.red('Failed to start monitor.'));
}
});
program
.command('monitor:stop')
.description('Stop the idle monitor daemon.')
.action(async () => {
const { execSync } = await import('child_process');
try {
execSync(`${pm2Cmd} stop ${MONITOR_PM2_NAME}`, { stdio: 'inherit' });
} catch {
console.log(chalk.yellow('Monitor is not running.'));
}
});
program
.command('monitor:logs')
.description('Show idle monitor logs.')
.action(async () => {
const { execSync } = await import('child_process');
try {
execSync(`${pm2Cmd} logs ${MONITOR_PM2_NAME} --lines 50`, { stdio: 'inherit' });
} catch {
console.log(chalk.yellow('Monitor is not running.'));
}
});
program
.command('serve')
.description('Start dashboard as a background daemon (PM2).')
.action(async () => {
const { execSync } = await import('child_process');
const bunPath = execSync('which bun', { encoding: 'utf-8' }).trim();
const scriptPath = path.join(__dirname, 'index.js');
try {
try {
execSync(`${pm2Cmd} delete ${DASH_PM2_NAME}`, { stdio: 'ignore' });
} catch {}
execSync(`${pm2Cmd} start ${scriptPath} --name ${DASH_PM2_NAME} --interpreter ${bunPath} -- dash`, {
stdio: 'inherit',
});
console.log(chalk.green(`Dashboard running at ${DASHBOARD_URL}`));
console.log(chalk.gray(' Stop: clocktopus serve:stop'));
console.log(chalk.gray(' Logs: clocktopus serve:logs'));
} catch {
console.error(chalk.red('Failed to start dashboard daemon.'));
}
});
program
.command('serve:stop')
.description('Stop the dashboard daemon.')
.action(async () => {
const { execSync } = await import('child_process');
try {
execSync(`${pm2Cmd} stop ${DASH_PM2_NAME}`, { stdio: 'inherit' });
} catch {
console.log(chalk.yellow('Dashboard is not running.'));
}
});
program
.command('serve:logs')
.description('Show dashboard daemon logs.')
.action(async () => {
const { execSync } = await import('child_process');
try {
execSync(`${pm2Cmd} logs ${DASH_PM2_NAME} --lines 50`, { stdio: 'inherit' });
} catch {
console.log(chalk.yellow('Dashboard is not running.'));
}
});
program
.command('hook:install')
.description('Install global git post-checkout hook (prompts to start timer on branch switch).')
.action(async () => {
const { installHook } = await import('./lib/hook-install.js');
await installHook();
console.log(chalk.green('Clocktopus post-checkout hook installed globally.'));
console.log(chalk.gray(' Disable per-repo: touch .clocktopus-ignore'));
console.log(chalk.gray(' Disable per-session: export CLOCKTOPUS_HOOK_DISABLE=1'));
console.log(chalk.gray(' Uninstall: clocktopus hook:uninstall'));
console.log();
console.log(chalk.yellow('Husky users: local core.hooksPath overrides global.'));
console.log(chalk.gray(' Inside each husky repo, run: clocktopus hook:install-husky'));
});
program
.command('hook:uninstall')
.description('Remove the global git post-checkout hook.')
.action(async () => {
const { uninstallHook } = await import('./lib/hook-install.js');
await uninstallHook();
console.log(chalk.green('Clocktopus post-checkout hook removed.'));
});
program
.command('hook:install-husky')
.description('Write a .husky/post-checkout in the current repo that chains to the global hook.')
.action(async () => {
const { installHuskyHook } = await import('./lib/husky-install.js');
const result = installHuskyHook(process.cwd());
if (result.installed) {
const verb = result.overwritten ? 'Overwrote' : 'Installed';
console.log(chalk.green(`${verb} husky post-checkout at ${result.path}.`));
console.log(chalk.gray(' Commit it so teammates using husky get it too.'));
return;
}
if (result.reason === 'no-husky-dir') {
console.error(chalk.red('No .husky/ directory found. Run from the root of a husky-enabled repo.'));
process.exit(1);
}
});
program
.command('hook:prompt <branch>')
.description('(internal) Prompt to start a timer after git checkout.')
.action(async (branch: string) => {
const { runHookPrompt } = await import('./lib/hook-prompt.js');
try {
await runHookPrompt(branch, { cwd: process.cwd() });
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : String(e);
console.error(chalk.red(`Hook prompt failed: ${msg}`));
}
// Force exit — /dev/tty fs streams and the sqlite handle keep the event loop alive.
process.exit(0);
});
program.parse(process.argv);