Skip to main content

kasl/libs/config/
mod.rs

1//! Application configuration: the data model, disk IO, and PATH setup.
2//! The interactive setup wizard lives in [`wizard`] (reached via
3//! [`Config::init`]).
4//!
5//! ```rust,no_run
6//! # fn main() -> anyhow::Result<()> {
7//! use kasl::libs::config::Config;
8//!
9//! let config = Config::read()?;
10//! let updated_config = Config::init()?;
11//! updated_config.save()?;
12//! # Ok(())
13//! # }
14//! ```
15
16mod wizard;
17
18use super::data_storage::DataStorage;
19use crate::api::gitlab::GitLabConfig;
20use crate::api::jira::JiraConfig;
21use crate::api::si::SiConfig;
22use crate::libs::messages::Message;
23use crate::libs::task::normalize_task_name;
24use crate::msg_error;
25use anyhow::Result;
26use serde::{Deserialize, Serialize};
27use std::env;
28use std::fs;
29use std::path::PathBuf;
30use std::process::Command;
31use std::str;
32
33/// Configuration filename inside the app data directory.
34pub const CONFIG_FILE_NAME: &str = "config.json";
35
36/// A configurable module as listed by the setup wizard.
37#[derive(Debug, Clone)]
38pub struct ConfigModule {
39    /// Internal key used for routing.
40    pub key: String,
41    /// Name shown in the wizard.
42    pub name: String,
43}
44
45/// Activity monitor thresholds and intervals.
46#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
47pub struct MonitorConfig {
48    /// Minimum pause length in minutes to keep as a pause record; shorter
49    /// interruptions are noise, not breaks.
50    pub min_pause_duration: u64,
51
52    /// Seconds without input before a pause is detected.
53    pub pause_threshold: u64,
54
55    /// Milliseconds between activity checks.
56    pub poll_interval: u64,
57
58    /// Seconds of sustained activity required to start a workday - keeps
59    /// a stray mouse nudge from opening the day.
60    pub activity_threshold: u64,
61
62    /// Minimum work interval in minutes; shorter ones are filtered from
63    /// report display.
64    pub min_work_interval: u64,
65
66    /// Maximum gap in seconds between two consecutive pauses to merge them.
67    ///
68    /// When the activity monitor briefly registers a stray input between two
69    /// otherwise continuous inactivity periods, it splits a single break into
70    /// several adjacent pause records. Pauses separated by a gap no longer than
71    /// this value are treated as one continuous pause so that sub-threshold
72    /// segments are not dropped from calculations. The value should stay small
73    /// (a few tens of seconds) so that genuine short work periods between pauses
74    /// are preserved rather than swallowed into the break.
75    #[serde(default = "default_pause_merge_gap")]
76    pub pause_merge_gap: u64,
77}
78
79/// Default gap (in seconds) below which consecutive pauses are merged.
80///
81/// Used both by [`MonitorConfig::default`] and by serde when an existing
82/// configuration file predates the `pause_merge_gap` field.
83fn default_pause_merge_gap() -> u64 {
84    30
85}
86
87/// Productivity thresholds for warnings and report validation.
88#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
89pub struct ProductivityConfig {
90    /// Productivity percentage below which reports warn.
91    pub min_productivity_threshold: f64,
92
93    /// Expected workday length in hours.
94    pub workday_hours: f64,
95
96    /// Fraction of the workday that must pass before warnings appear -
97    /// early-day ratios swing too wildly to act on.
98    pub min_workday_fraction_before_suggest: f64,
99}
100
101/// Report export defaults: output directory and file naming.
102#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
103pub struct ReportConfig {
104    /// Default directory for exports without an explicit `--output`
105    /// (created if missing); unset = timestamped file in the current dir.
106    #[serde(skip_serializing_if = "Option::is_none")]
107    pub output_dir: Option<String>,
108
109    /// File name template (without extension) for generated reports.
110    ///
111    /// Supported placeholders:
112    /// - `{date}` — the report date in `YYYY-MM-DD` format
113    /// - `{seq}`  — a per-day sequence suffix: empty for the first report of the
114    ///   day, then `_2`, `_3`, … for subsequent reports on the same date
115    ///
116    /// The file extension is appended automatically based on the export format.
117    /// Defaults to `daily_report_{date}{seq}` when unset.
118    #[serde(skip_serializing_if = "Option::is_none")]
119    pub filename_template: Option<String>,
120
121    /// Report label language: `en` (default) or `ru`; unknown values fall
122    /// back to `en`.
123    ///
124    /// Russian was the default before 1.0, when the product spoke Russian; the
125    /// shipped default is English and this opts back in.
126    #[serde(skip_serializing_if = "Option::is_none")]
127    pub language: Option<String>,
128
129    /// Design template name (`<data>/report_templates/<name>.json`);
130    /// unset or missing falls back to the built-in `siserver` look.
131    #[serde(skip_serializing_if = "Option::is_none")]
132    pub template: Option<String>,
133}
134
135/// SiServer connection used by `report --send`.
136///
137/// Named `server` for historical reasons - this is the third-party corporate
138/// reporting API, not kasl-server. The team server lives in
139/// [`KaslServerConfig`] under its own key so the two channels can be
140/// configured independently, and eventually used side by side.
141#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
142pub struct ServerConfig {
143    /// Base URL of the reporting API.
144    pub api_url: String,
145
146    /// Token sent with report submissions.
147    pub auth_token: String,
148}
149
150/// Connection to a kasl-server instance: where to reach it, and how to trust
151/// it.
152///
153/// The agent token is deliberately absent - it lives in the OS keyring, like
154/// every other kasl credential, so a readable config file never carries one.
155#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
156pub struct KaslServerConfig {
157    /// Base URL of the server, e.g. `https://kasl.example.com`. Stored
158    /// without a trailing slash so endpoint paths can be appended as-is.
159    pub url: String,
160
161    /// PEM file holding the certificate authority that signed the server's
162    /// certificate.
163    ///
164    /// Self-hosted deployments are routinely behind a company CA or a
165    /// self-signed certificate, which the system trust store does not know.
166    /// Naming the certificate here keeps verification on: the alternative -
167    /// switching it off - would also accept anyone else's certificate.
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    pub ca_certificate: Option<String>,
170
171    /// Whether the watcher tells this server, once a minute, if you are
172    /// working, on a break, or not in a day.
173    ///
174    /// Off until the employee turns it on with `kasl server pulse enable`:
175    /// connecting agrees to send finished days, and a live signal of whether
176    /// someone is at their keyboard is a different thing to agree to. It
177    /// lives here, beside the address, so the consent belongs to this
178    /// connection - disconnecting forgets it, and connecting to another
179    /// server does not inherit it.
180    #[serde(default)]
181    pub pulse: bool,
182}
183
184/// The root configuration. Every module is optional, and unset modules
185/// are omitted from the JSON, so the file only names what is configured.
186#[derive(Serialize, Deserialize, Clone, Debug, Default)]
187pub struct Config {
188    /// SiServer integration.
189    #[serde(skip_serializing_if = "Option::is_none")]
190    pub si: Option<SiConfig>,
191
192    /// GitLab integration (commit discovery).
193    #[serde(skip_serializing_if = "Option::is_none")]
194    pub gitlab: Option<GitLabConfig>,
195
196    /// Jira integration (issue discovery, inbox).
197    #[serde(skip_serializing_if = "Option::is_none")]
198    pub jira: Option<JiraConfig>,
199
200    /// Activity monitor settings.
201    #[serde(skip_serializing_if = "Option::is_none")]
202    pub monitor: Option<MonitorConfig>,
203
204    /// SiServer, the third-party corporate reporting API.
205    #[serde(skip_serializing_if = "Option::is_none")]
206    pub server: Option<ServerConfig>,
207
208    /// kasl-server: the team server this agent reports to.
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub kasl_server: Option<KaslServerConfig>,
211
212    /// Productivity thresholds.
213    #[serde(skip_serializing_if = "Option::is_none")]
214    pub productivity: Option<ProductivityConfig>,
215
216    /// Report export defaults.
217    #[serde(skip_serializing_if = "Option::is_none")]
218    pub report: Option<ReportConfig>,
219
220    /// Task discovery ignore list; built-in defaults apply when absent.
221    #[serde(default, skip_serializing_if = "Option::is_none")]
222    pub task_discovery: Option<TaskDiscoveryConfig>,
223
224    /// Jira inbox polling; requires `jira`, disabled when absent.
225    #[serde(default, skip_serializing_if = "Option::is_none")]
226    pub jira_inbox: Option<JiraInboxConfig>,
227}
228
229/// Settings for polling assigned open Jira issues into the local inbox.
230#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
231pub struct JiraInboxConfig {
232    /// Whether the watcher should poll Jira for open assigned issues.
233    #[serde(default = "default_true")]
234    pub enabled: bool,
235
236    /// Seconds between Jira inbox polls (default 300 = 5 minutes).
237    #[serde(default = "default_jira_inbox_poll_interval")]
238    pub poll_interval_secs: u64,
239
240    /// Whether to show a desktop toast when a new issue appears.
241    #[serde(default = "default_true")]
242    pub notify: bool,
243
244    /// Whether to show a toast when an existing issue changes status or
245    /// priority. Score changes and returns only set the badge.
246    #[serde(default = "default_true")]
247    pub notify_changes: bool,
248
249    /// Whether to show a toast when an issue leaves the inbox
250    /// (closed or reassigned). Off by default.
251    #[serde(default)]
252    pub notify_gone: bool,
253
254    /// Extra Jira fields to fetch (custom fields such as Scoring).
255    #[serde(default)]
256    pub custom_fields: Vec<JiraCustomField>,
257
258    /// Field id used for ranking (DESC), typically Scoring (`customfield_…`).
259    #[serde(default, skip_serializing_if = "Option::is_none")]
260    pub sort_by_field: Option<String>,
261
262    /// How long a toast's Snooze button sleeps: 3d, 12h, 2w.
263    ///
264    /// Shares its spelling with `inbox triage --snooze-for`, because a button
265    /// and the picker putting an issue to sleep for different lengths would be
266    /// two behaviours wearing one word.
267    #[serde(default = "default_toast_snooze_for")]
268    pub toast_snooze_for: String,
269}
270
271/// A user-configured Jira custom field for inbox sync / display.
272#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
273pub struct JiraCustomField {
274    /// Jira field id, e.g. `customfield_12345`.
275    pub id: String,
276    /// Human-readable label, e.g. `Scoring`.
277    pub label: String,
278}
279
280fn default_true() -> bool {
281    true
282}
283
284fn default_jira_inbox_poll_interval() -> u64 {
285    300
286}
287
288fn default_toast_snooze_for() -> String {
289    "1d".to_string()
290}
291
292impl Default for JiraInboxConfig {
293    fn default() -> Self {
294        Self {
295            enabled: true,
296            poll_interval_secs: default_jira_inbox_poll_interval(),
297            notify: true,
298            notify_changes: true,
299            notify_gone: false,
300            custom_fields: Vec::new(),
301            sort_by_field: None,
302            toast_snooze_for: default_toast_snooze_for(),
303        }
304    }
305}
306
307impl JiraInboxConfig {
308    /// Field ids to request from Jira search (custom fields only).
309    pub fn extra_field_ids(&self) -> Vec<String> {
310        let mut ids: Vec<String> = self.custom_fields.iter().map(|f| f.id.trim().to_string()).filter(|id| !id.is_empty()).collect();
311        if let Some(sort_id) = &self.sort_by_field {
312            let trimmed = sort_id.trim();
313            if !trimmed.is_empty() && !ids.iter().any(|id| id == trimmed) {
314                ids.push(trimmed.to_string());
315            }
316        }
317        ids
318    }
319}
320
321/// Settings for intelligent task discovery (`kasl task find`).
322#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
323pub struct TaskDiscoveryConfig {
324    /// Names/prefixes of tasks and commits to exclude from discovery.
325    ///
326    /// Matching is case-insensitive after normalization; a pattern matches
327    /// when the candidate name equals it or starts with it.
328    #[serde(default = "default_ignore_names")]
329    pub ignore_names: Vec<String>,
330}
331
332/// Built-in ignore patterns moved from the former hardcoded noise filter.
333pub fn default_ignore_names() -> Vec<String> {
334    vec![
335        "Merge remote-tracking branch".to_string(),
336        "Merge branch ".to_string(),
337        "update webui".to_string(),
338    ]
339}
340
341impl Default for TaskDiscoveryConfig {
342    fn default() -> Self {
343        Self {
344            ignore_names: default_ignore_names(),
345        }
346    }
347}
348
349impl Default for MonitorConfig {
350    fn default() -> Self {
351        MonitorConfig {
352            min_pause_duration: 20,
353            pause_threshold: 60,
354            poll_interval: 500,
355            activity_threshold: 30,
356            min_work_interval: 10,
357            pause_merge_gap: default_pause_merge_gap(),
358        }
359    }
360}
361
362impl Default for ProductivityConfig {
363    fn default() -> Self {
364        ProductivityConfig {
365            min_productivity_threshold: 75.0,
366            workday_hours: 8.0,
367            min_workday_fraction_before_suggest: 0.5,
368        }
369    }
370}
371
372impl Config {
373    /// Loads the config file, or defaults when none exists yet.
374    ///
375    /// ```rust,no_run
376    /// # fn main() -> anyhow::Result<()> {
377    /// use kasl::libs::config::Config;
378    ///
379    /// let config = Config::read()?;
380    ///
381    /// if config.jira.is_some() {
382    ///     println!("Jira integration is configured");
383    /// }
384    /// # Ok(())
385    /// # }
386    /// ```
387    pub fn read() -> Result<Config> {
388        let config_file_path = DataStorage::new().get_path(CONFIG_FILE_NAME)?;
389
390        if !config_file_path.exists() {
391            return Ok(Config::default());
392        }
393
394        let config_str = fs::read_to_string(config_file_path)?;
395        let config: Config = serde_json::from_str(&config_str)?;
396        Ok(config)
397    }
398
399    /// Writes the config as pretty-printed JSON, overwriting the file.
400    ///
401    /// ```rust,no_run
402    /// # fn main() -> anyhow::Result<()> {
403    /// use kasl::libs::config::{Config, MonitorConfig};
404    ///
405    /// let mut config = Config::read()?;
406    /// config.monitor = Some(MonitorConfig::default());
407    /// config.save()?;
408    /// # Ok(())
409    /// # }
410    /// ```
411    pub fn save(&self) -> Result<()> {
412        let config_file_path = DataStorage::new().get_path(CONFIG_FILE_NAME)?;
413        let json_content = serde_json::to_string_pretty(&self)?;
414        fs::write(config_file_path, json_content)?;
415        Ok(())
416    }
417
418    /// Returns the ignore list for task discovery.
419    ///
420    /// When `task_discovery` is not configured, returns the built-in defaults.
421    pub fn effective_ignore_names(&self) -> Vec<String> {
422        self.task_discovery
423            .as_ref()
424            .map(|c| c.ignore_names.clone())
425            .unwrap_or_else(default_ignore_names)
426    }
427
428    /// Appends unique names to the discovery ignore list and saves the config.
429    ///
430    /// Uniqueness is determined by [`normalize_task_name`]. Returns how many
431    /// new entries were added.
432    pub fn add_ignore_names(&mut self, names: &[String]) -> Result<usize> {
433        let mut discovery = self.task_discovery.clone().unwrap_or_default();
434        let mut added = 0;
435
436        for name in names {
437            let trimmed = name.trim();
438            if trimmed.is_empty() {
439                continue;
440            }
441            let key = normalize_task_name(trimmed);
442            let exists = discovery.ignore_names.iter().any(|existing| normalize_task_name(existing) == key);
443            if !exists {
444                discovery.ignore_names.push(trimmed.to_string());
445                added += 1;
446            }
447        }
448
449        self.task_discovery = Some(discovery);
450        self.save()?;
451        Ok(added)
452    }
453
454    /// Adds the executable's directory to the global PATH.
455    ///
456    /// Windows-shaped: checks the process PATH first, then edits the
457    /// machine-level registry value via `reg` (which needs admin rights;
458    /// the setup command downgrades a failure here to a warning).
459    ///
460    /// ```rust,no_run
461    /// # fn main() -> anyhow::Result<()> {
462    /// use kasl::libs::config::Config;
463    ///
464    /// Config::set_app_global()?;
465    /// # Ok(())
466    /// # }
467    /// ```
468    pub fn set_app_global() -> Result<()> {
469        let current_exe_path = env::current_exe()?;
470        let exe_dir = current_exe_path.parent().unwrap();
471
472        let mut paths: Vec<PathBuf> = env::split_paths(&env::var_os("PATH").unwrap()).collect();
473        let str_paths: Vec<&str> = paths.iter().filter_map(|p| p.to_str()).collect();
474
475        if str_paths.contains(&exe_dir.to_str().unwrap()) {
476            return Ok(());
477        }
478
479        if paths.iter().any(|p| p.to_str() == Some(exe_dir.to_str().unwrap())) {
480            return Ok(());
481        }
482
483        paths.push(exe_dir.to_path_buf());
484
485        let new_path = env::join_paths(paths).unwrap_or_else(|_| panic!("{}", Message::FailedToJoinPaths.to_string()));
486
487        let path_key = r"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
488
489        let reg_query_output = Command::new("reg")
490            .arg("query")
491            .arg(path_key)
492            .arg("/v")
493            .arg("Path")
494            .output()
495            .unwrap_or_else(|_| panic!("{}", Message::FailedToExecuteRegQuery.to_string()));
496
497        if !reg_query_output.status.success() {
498            let status = reg_query_output.status.to_string();
499            msg_error!(Message::PathRegistryQueryError { status: status.clone() });
500            return Err(anyhow::anyhow!("{}", Message::PathRegistryQueryError { status }));
501        }
502
503        let current_path = str::from_utf8(&reg_query_output.stdout)
504            .unwrap_or_else(|_| panic!("{}", Message::FailedToParseRegOutput.to_string()))
505            .split_whitespace()
506            .last()
507            .unwrap_or_else(|| panic!("{}", Message::FailedToGetPathFromReg.to_string()));
508
509        let reg_set_output = Command::new("reg")
510            .arg("add")
511            .arg(path_key)
512            .arg("/v")
513            .arg("Path")
514            .arg("/t")
515            .arg("REG_EXPAND_SZ") // Expandable string type for environment variables
516            .arg("/d")
517            .arg(format!("{};{}", current_path, new_path.to_string_lossy()))
518            .arg("/f") // Force overwrite without confirmation
519            .output()
520            .unwrap_or_else(|_| panic!("{}", Message::FailedToExecuteRegSet.to_string()));
521
522        if !reg_set_output.status.success() {
523            let status = reg_set_output.status.to_string();
524            let stderr = String::from_utf8_lossy(&reg_set_output.stderr).to_string();
525            msg_error!(Message::PathRegistryUpdateError {
526                status: status.clone(),
527                stderr: stderr.clone()
528            });
529            return Err(anyhow::anyhow!("{}", Message::PathRegistryUpdateError { status, stderr }));
530        }
531
532        Ok(())
533    }
534}