kasl-cli 1.3.0

Work activity tracker CLI: automatic workday and break detection, task management with Jira/GitLab integration, productivity reports and exports
Documentation
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
//! Database operations for tracking pause periods.
//!
//! Manages the storage and retrieval of pause records during work sessions:
//! absences detected automatically by the activity monitor, and ones the user
//! recorded by hand because the monitor could not see them.
//!
//! ## Usage
//!
//! ```rust,no_run
//! # fn main() -> anyhow::Result<()> {
//! use kasl::db::pauses::Pauses;
//!
//! let pauses = Pauses::new()?;
//! pauses.insert_start()?;
//! pauses.insert_end()?; // completes the most recent open pause
//! # Ok(())
//! # }
//! ```

use crate::db::db::Db;
use crate::db::workdays::Workday;
use crate::libs::config::Config;
use crate::libs::pause::Pause;
use anyhow::Result;
use chrono::{Local, NaiveDate, NaiveDateTime, TimeDelta};
use parking_lot::Mutex;
use rusqlite::{Connection, params};
use std::sync::Arc;

// An open pause has end IS NULL; duration is stored in seconds on close.
const SCHEMA_PAUSES: &str = "CREATE TABLE IF NOT EXISTS pauses (
    id INTEGER NOT NULL PRIMARY KEY,
    start TIMESTAMP NOT NULL,
    end TIMESTAMP,
    duration INTEGER,
    protected INTEGER NOT NULL DEFAULT 0,
    reason TEXT
)";

const INSERT_PAUSE: &str = "INSERT INTO pauses (start) VALUES (datetime(CURRENT_TIMESTAMP, 'localtime'))";

const INSERT_PAUSE_WITH_TIME: &str = "INSERT INTO pauses (start) VALUES (?1)";

const UPDATE_PAUSE: &str = "UPDATE pauses SET end = (datetime(CURRENT_TIMESTAMP, 'localtime')), duration = ?1 WHERE id = ?2";

const SELECT_LAST_PAUSE: &str = "SELECT id, start FROM pauses WHERE end IS NULL ORDER BY id DESC LIMIT 1";

/// Select all completed pauses for a specific date.
///
/// Retrieves every completed pause (end IS NOT NULL) for the given date
/// ordered chronologically. Duration filtering is performed in Rust after
/// merging consecutive pauses, so no threshold is applied here.
const SELECT_DAILY_PAUSES: &str =
    "SELECT id, start, end, duration, protected FROM pauses WHERE date(start) = date(?1) AND end IS NOT NULL ORDER BY start ASC, id ASC";

/// Insert a complete manual pause with explicit start, end and duration.
///
/// Used by `kasl pauses add`, where the user states when they were away
/// instead of the monitor detecting it. `protected` decides whether the
/// record is exempt from threshold filtering and merging.
const INSERT_MANUAL_PAUSE: &str = "INSERT INTO pauses (start, end, duration, protected, reason) VALUES (?1, ?2, ?3, ?4, ?5)";

const DELETE_PAUSE: &str = "DELETE FROM pauses WHERE id = ?";

/// Pause table access. The connection sits behind a mutex because the
/// monitor thread and user commands write concurrently.
pub struct Pauses {
    pub conn: Arc<Mutex<Connection>>,
    pub min_duration: Option<String>,
    pub max_duration: Option<String>,
}

impl Pauses {
    /// Opens the database and ensures the pauses table exists.
    ///
    /// ```rust,no_run
    /// # fn main() -> anyhow::Result<()> {
    /// use kasl::db::pauses::Pauses;
    ///
    /// let pauses = Pauses::new()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new() -> Result<Pauses> {
        let db_conn = Db::new()?.conn;
        db_conn.execute(SCHEMA_PAUSES, [])?;

        Ok(Pauses {
            conn: Arc::new(Mutex::new(db_conn)),
            min_duration: None,
            max_duration: None,
        })
    }

    pub fn set_min_duration(&self, min_duration: u64) -> Self {
        let min_duration_secs = (min_duration * 60) as i64; // Convert minutes to seconds
        Self {
            conn: self.conn.clone(),
            min_duration: Some(min_duration_secs.to_string()),
            max_duration: None,
        }
    }

    pub fn set_max_duration(&self, max_duration: u64) -> Self {
        let max_duration_secs = (max_duration * 60) as i64; // Convert minutes to second
        Self {
            conn: self.conn.clone(),
            min_duration: None,
            max_duration: Some(max_duration_secs.to_string()),
        }
    }

    /// Merges consecutive pauses separated only by an insignificant work gap.
    ///
    /// The activity monitor can split a single, effectively continuous break into
    /// several adjacent pause records separated by brief bursts of activity (a
    /// stray mouse move, a few seconds of typing). Because a duration threshold is
    /// applied per-record, some of these segments may individually fall below the
    /// threshold and be discarded, even though together they form one long pause.
    /// Merging such chains before filtering ensures they are treated as a single
    /// pause.
    ///
    /// Two pauses are merged when the gap between the end of one and the start of
    /// the next does not exceed `max_gap_secs` (a work interval shorter than this
    /// is not considered meaningful work). The merged pause keeps the earliest
    /// start, the latest end, and its duration is recomputed as `end - start`.
    ///
    /// The input is expected to be sorted chronologically by start time.
    /// Protected pauses never participate in merging: they were stated by the
    /// user with explicit bounds, so absorbing them into a neighbour (or
    /// absorbing a neighbour into them) would falsify what the user recorded.
    fn merge_consecutive_pauses(pauses: Vec<Pause>, max_gap_secs: i64) -> Vec<Pause> {
        let mut merged: Vec<Pause> = Vec::with_capacity(pauses.len());

        for pause in pauses {
            if pause.protected {
                merged.push(pause);
                continue;
            }

            if let Some(last) = merged.last_mut()
                && !last.protected
                && let Some(last_end) = last.end
            {
                // Merge when the work gap between the pauses is small enough
                // (contiguous, overlapping, or a negligible burst of activity).
                let gap = (pause.start - last_end).num_seconds();
                if gap <= max_gap_secs {
                    let new_end = match pause.end {
                        Some(end) => Some(end.max(last_end)),
                        None => Some(last_end),
                    };
                    last.end = new_end;
                    if let Some(end) = last.end {
                        last.duration = Some(TimeDelta::seconds((end - last.start).num_seconds()));
                    }
                    continue;
                }
            }
            merged.push(pause);
        }

        merged
    }

    /// Returns the active duration threshold in seconds, if any is configured.
    ///
    /// Positive value with `min` semantics is expressed through `min_duration`,
    /// `max` semantics through `max_duration`. Only one of them is ever set.
    fn duration_threshold_seconds(&self) -> Option<i64> {
        self.min_duration.as_ref().or(self.max_duration.as_ref()).and_then(|d| d.parse::<i64>().ok())
    }

    /// Opens a pause at the current time; `insert_end` closes it later.
    ///
    /// ```rust,no_run
    /// # use kasl::db::pauses::Pauses;
    /// # fn main() -> anyhow::Result<()> {
    /// let pauses = Pauses::new()?;
    /// pauses.insert_start()?; // Pause started at current time
    /// # Ok(())
    /// # }
    /// ```
    pub fn insert_start(&self) -> rusqlite::Result<()> {
        let conn_guard = self.conn.lock();
        conn_guard.execute(INSERT_PAUSE, [])?;
        Ok(())
    }

    /// Opens a pause at a stated local time (imports, corrections).
    ///
    /// ```rust,no_run
    /// # use kasl::db::pauses::Pauses;
    /// use chrono::NaiveDateTime;
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// let pauses = Pauses::new()?;
    /// let start_time = NaiveDateTime::parse_from_str(
    ///     "2025-01-15 14:30:00",
    ///     "%Y-%m-%d %H:%M:%S"
    /// )?;
    /// pauses.insert_start_with_time(start_time)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn insert_start_with_time(&self, start_time: NaiveDateTime) -> Result<()> {
        let conn_guard = self.conn.lock();
        let start_str = start_time.format("%Y-%m-%d %H:%M:%S").to_string();
        conn_guard.execute(INSERT_PAUSE_WITH_TIME, [&start_str])?;
        Ok(())
    }

    /// Closes the most recent open pause, computing its duration; a no-op
    /// when no pause is open.
    ///
    /// ```rust,no_run
    /// # use kasl::db::pauses::Pauses;
    /// # fn main() -> anyhow::Result<()> {
    /// let pauses = Pauses::new()?;
    /// pauses.insert_start()?;
    /// // ... user is inactive for 5 minutes ...
    /// pauses.insert_end()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn insert_end(&self) -> Result<()> {
        let end = Local::now().naive_local();
        let conn_guard = self.conn.lock();

        let mut stmt = conn_guard.prepare(SELECT_LAST_PAUSE)?;
        let pause_row = stmt.query_row([], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?)));
        if let Ok((id, start_str)) = pause_row {
            let start = NaiveDateTime::parse_from_str(&start_str, "%Y-%m-%d %H:%M:%S")?;
            let duration = (end - start).num_seconds();
            conn_guard.execute(UPDATE_PAUSE, [&duration.to_string(), &id.to_string()])?;
        }

        Ok(())
    }

    /// Records a complete pause stated by the user, with explicit bounds.
    ///
    /// Unlike monitor-detected pauses, which are opened by `insert_start` and
    /// closed later by `insert_end`, a manual pause is written in one shot: the
    /// user knows when they left and how long they were gone. No placement is
    /// inferred and no time is invented.
    pub fn insert_manual(&self, start: NaiveDateTime, duration: TimeDelta, protected: bool, reason: Option<&str>) -> Result<i64> {
        let end = start + duration;
        let conn_guard = self.conn.lock();
        conn_guard.execute(
            INSERT_MANUAL_PAUSE,
            params![
                start.format("%Y-%m-%d %H:%M:%S").to_string(),
                end.format("%Y-%m-%d %H:%M:%S").to_string(),
                duration.num_seconds(),
                protected as i64,
                reason,
            ],
        )?;
        Ok(conn_guard.last_insert_rowid())
    }

    /// Returns the pause overlapping the given time range, if any exists.
    ///
    /// Used to reject a manual pause that would collide with an already
    /// recorded one, so the day never contains contradictory absences.
    pub fn find_overlapping(&self, start: NaiveDateTime, end: NaiveDateTime) -> Result<Option<Pause>> {
        let pauses = self.get_daily_pauses(start.date())?;
        Ok(pauses.into_iter().find(|p| p.end.map(|p_end| p.start < end && start < p_end).unwrap_or(false)))
    }

    /// Returns the date's completed pauses: fetched chronologically, merged
    /// across insignificant gaps, then filtered by the configured threshold
    /// (see the comments in the body for the exact rules).
    ///
    /// ```rust,no_run
    /// # use kasl::db::pauses::Pauses;
    /// use chrono::Local;
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// // Get pauses of 10 minutes or longer
    /// let pauses = Pauses::new()?.set_min_duration(10);
    /// let today = Local::now().date_naive();
    ///
    /// let significant_pauses = pauses.get_daily_pauses(today)?;
    /// for pause in significant_pauses {
    ///     println!("Pause: {:?} - {:?}", pause.start, pause.end);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_daily_pauses(&self, date: NaiveDate) -> Result<Vec<Pause>> {
        let date_str = date.format("%Y-%m-%d").to_string();
        let conn_guard = self.conn.lock();
        // Fetch all completed pauses for the date, ordered chronologically.
        let mut stmt = conn_guard.prepare(SELECT_DAILY_PAUSES)?;
        let pause_iter = stmt.query_map([&date_str], |row| {
            // Parse timestamps from database strings
            let start_str: String = row.get(1)?;
            let end_str: Option<String> = row.get(2)?;
            let duration: i64 = row.get(3).unwrap_or(0);

            // Create Pause object with parsed data
            Ok(Pause {
                id: row.get(0)?,
                start: NaiveDateTime::parse_from_str(&start_str, "%Y-%m-%d %H:%M:%S").unwrap(),
                end: end_str.map(|s| NaiveDateTime::parse_from_str(&s, "%Y-%m-%d %H:%M:%S").unwrap()),
                duration: Some(TimeDelta::seconds(duration)),
                protected: row.get::<_, i64>(4).unwrap_or(0) != 0,
            })
        })?;

        // Collect results, handling any parsing errors
        let mut pauses = Vec::new();
        for pause_result in pause_iter {
            pauses.push(pause_result?);
        }

        // Merge consecutive pauses separated only by an insignificant gap so that
        // a chain of adjacent pauses (split by a stray input) is treated as a
        // single continuous pause before filtering. The tolerance is the small,
        // dedicated `pause_merge_gap` setting (in seconds): genuine work periods
        // between pauses are longer than this and remain separate.
        let max_gap_secs = Config::read().ok().and_then(|c| c.monitor).map(|m| m.pause_merge_gap as i64).unwrap_or(0);
        let pauses = Self::merge_consecutive_pauses(pauses, max_gap_secs);

        // Apply the configured duration threshold to the merged pauses.
        //
        // Protected pauses bypass the `min_duration` threshold entirely: the user
        // stated them deliberately, so a short manual entry must not be filtered
        // away. The `max_duration` filter is used to isolate *short* pauses for
        // productivity accounting, so protected records are excluded from it —
        // they are accounted for as real, long-form absences.
        let pauses = match (&self.min_duration, &self.max_duration) {
            (Some(_), _) => {
                let min = self.duration_threshold_seconds().unwrap_or(0);
                pauses
                    .into_iter()
                    .filter(|p| p.protected || p.duration.map(|d| d.num_seconds()).unwrap_or(0) >= min)
                    .collect()
            }
            (_, Some(_)) => {
                let max = self.duration_threshold_seconds().unwrap_or(0);
                pauses
                    .into_iter()
                    .filter(|p| !p.protected && p.duration.map(|d| d.num_seconds()).unwrap_or(0) < max)
                    .collect()
            }
            _ => pauses,
        };

        Ok(pauses)
    }

    /// Fetches daily pauses and keeps only the portions inside the workday bounds.
    ///
    /// Drops pauses entirely before `workday.start` or after `workday.end`, and
    /// clips straddling pauses to `[workday.start, workday.end]`.
    pub fn get_workday_pauses(&self, workday: &Workday) -> Result<Vec<Pause>> {
        let pauses = self.get_daily_pauses(workday.date)?;
        Ok(filter_pauses_to_workday(pauses, workday))
    }

    /// Deletes one pause by id.
    ///
    /// ```rust,no_run
    /// # use kasl::db::pauses::Pauses;
    /// # fn main() -> anyhow::Result<()> {
    /// let pauses = Pauses::new()?;
    /// pauses.delete(123)?; // Delete pause with ID 123
    /// # Ok(())
    /// # }
    /// ```
    pub fn delete(&self, id: i32) -> Result<()> {
        let conn_guard = self.conn.lock();
        conn_guard.execute(DELETE_PAUSE, params![id])?;
        Ok(())
    }

    /// Deletes several pauses under one lock; unknown ids are not counted,
    /// an empty slice is a no-op.
    ///
    /// ```rust,no_run
    /// # use kasl::db::pauses::Pauses;
    /// # fn main() -> anyhow::Result<()> {
    /// let pauses = Pauses::new()?;
    /// let ids_to_delete = vec![101, 102, 103];
    /// let deleted_count = pauses.delete_many(&ids_to_delete)?;
    /// println!("Deleted {} pause records", deleted_count);
    /// # Ok(())
    /// # }
    /// ```
    pub fn delete_many(&self, ids: &[i32]) -> Result<usize> {
        // Handle empty input early to avoid unnecessary database operations
        if ids.is_empty() {
            return Ok(0);
        }

        let conn_guard = self.conn.lock();
        let mut deleted = 0;

        // Delete each record individually within the locked connection
        // This could be optimized with a single IN clause query for large batches
        for id in ids {
            deleted += conn_guard.execute(DELETE_PAUSE, params![id])?;
        }

        Ok(deleted)
    }
}

/// Keeps only pause portions that fall inside the workday time bounds.
///
/// - Drops pauses that end at or before `workday.start`
/// - Drops open-ended pauses that start before `workday.start`
/// - Drops pauses that start at or after `workday.end` (when end is set)
/// - Clips straddling pauses to `[workday.start, workday.end]` and recomputes duration
pub fn filter_pauses_to_workday(pauses: Vec<Pause>, workday: &Workday) -> Vec<Pause> {
    let work_start = workday.start;
    let work_end = workday.end;

    pauses
        .into_iter()
        .filter_map(|mut pause| {
            if let Some(end) = pause.end {
                if end <= work_start {
                    return None;
                }
            } else if pause.start < work_start {
                return None;
            }

            if let Some(work_end) = work_end
                && pause.start >= work_end
            {
                return None;
            }

            if pause.start < work_start {
                pause.start = work_start;
            }
            if let (Some(end), Some(work_end)) = (pause.end, work_end)
                && end > work_end
            {
                pause.end = Some(work_end);
            }
            if let Some(end) = pause.end {
                if end <= pause.start {
                    return None;
                }
                pause.duration = Some(end - pause.start);
            }

            Some(pause)
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::NaiveDate;

    fn workday(start: &str, end: Option<&str>) -> Workday {
        Workday {
            id: 1,
            date: NaiveDate::from_ymd_opt(2026, 7, 29).unwrap(),
            start: NaiveDateTime::parse_from_str(start, "%Y-%m-%d %H:%M:%S").unwrap(),
            end: end.map(|e| NaiveDateTime::parse_from_str(e, "%Y-%m-%d %H:%M:%S").unwrap()),
        }
    }

    fn pause(id: i32, start: &str, end: &str) -> Pause {
        let start = NaiveDateTime::parse_from_str(start, "%Y-%m-%d %H:%M:%S").unwrap();
        let end = NaiveDateTime::parse_from_str(end, "%Y-%m-%d %H:%M:%S").unwrap();
        Pause {
            id,
            start,
            end: Some(end),
            duration: Some(end - start),
            protected: false,
        }
    }

    #[test]
    fn drops_pauses_entirely_before_workday_start() {
        let wd = workday("2026-07-29 10:04:30", None);
        let pauses = vec![pause(1, "2026-07-29 10:02:23", "2026-07-29 10:04:26")];
        let filtered = filter_pauses_to_workday(pauses, &wd);
        assert!(filtered.is_empty());
    }

    #[test]
    fn drops_pauses_entirely_after_workday_end() {
        let wd = workday("2026-07-29 10:00:00", Some("2026-07-29 18:00:00"));
        let pauses = vec![pause(1, "2026-07-29 18:30:00", "2026-07-29 18:45:00")];
        let filtered = filter_pauses_to_workday(pauses, &wd);
        assert!(filtered.is_empty());
    }

    #[test]
    fn clips_pause_that_straddles_workday_start() {
        let wd = workday("2026-07-29 10:00:00", Some("2026-07-29 18:00:00"));
        let pauses = vec![pause(1, "2026-07-29 09:50:00", "2026-07-29 10:10:00")];
        let filtered = filter_pauses_to_workday(pauses, &wd);
        assert_eq!(filtered.len(), 1);
        assert_eq!(
            filtered[0].start,
            NaiveDateTime::parse_from_str("2026-07-29 10:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
        );
        assert_eq!(
            filtered[0].end.unwrap(),
            NaiveDateTime::parse_from_str("2026-07-29 10:10:00", "%Y-%m-%d %H:%M:%S").unwrap()
        );
        assert_eq!(filtered[0].duration.unwrap().num_minutes(), 10);
    }

    #[test]
    fn keeps_pause_fully_inside_workday() {
        let wd = workday("2026-07-29 10:00:00", Some("2026-07-29 18:00:00"));
        let pauses = vec![pause(1, "2026-07-29 12:00:00", "2026-07-29 12:20:00")];
        let filtered = filter_pauses_to_workday(pauses, &wd);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].duration.unwrap().num_minutes(), 20);
    }
}