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
172/// The root configuration. Every module is optional, and unset modules
173/// are omitted from the JSON, so the file only names what is configured.
174#[derive(Serialize, Deserialize, Clone, Debug, Default)]
175pub struct Config {
176 /// SiServer integration.
177 #[serde(skip_serializing_if = "Option::is_none")]
178 pub si: Option<SiConfig>,
179
180 /// GitLab integration (commit discovery).
181 #[serde(skip_serializing_if = "Option::is_none")]
182 pub gitlab: Option<GitLabConfig>,
183
184 /// Jira integration (issue discovery, inbox).
185 #[serde(skip_serializing_if = "Option::is_none")]
186 pub jira: Option<JiraConfig>,
187
188 /// Activity monitor settings.
189 #[serde(skip_serializing_if = "Option::is_none")]
190 pub monitor: Option<MonitorConfig>,
191
192 /// SiServer, the third-party corporate reporting API.
193 #[serde(skip_serializing_if = "Option::is_none")]
194 pub server: Option<ServerConfig>,
195
196 /// kasl-server: the team server this agent reports to.
197 #[serde(default, skip_serializing_if = "Option::is_none")]
198 pub kasl_server: Option<KaslServerConfig>,
199
200 /// Productivity thresholds.
201 #[serde(skip_serializing_if = "Option::is_none")]
202 pub productivity: Option<ProductivityConfig>,
203
204 /// Report export defaults.
205 #[serde(skip_serializing_if = "Option::is_none")]
206 pub report: Option<ReportConfig>,
207
208 /// Task discovery ignore list; built-in defaults apply when absent.
209 #[serde(default, skip_serializing_if = "Option::is_none")]
210 pub task_discovery: Option<TaskDiscoveryConfig>,
211
212 /// Jira inbox polling; requires `jira`, disabled when absent.
213 #[serde(default, skip_serializing_if = "Option::is_none")]
214 pub jira_inbox: Option<JiraInboxConfig>,
215}
216
217/// Settings for polling assigned open Jira issues into the local inbox.
218#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
219pub struct JiraInboxConfig {
220 /// Whether the watcher should poll Jira for open assigned issues.
221 #[serde(default = "default_true")]
222 pub enabled: bool,
223
224 /// Seconds between Jira inbox polls (default 300 = 5 minutes).
225 #[serde(default = "default_jira_inbox_poll_interval")]
226 pub poll_interval_secs: u64,
227
228 /// Whether to show a desktop toast when a new issue appears.
229 #[serde(default = "default_true")]
230 pub notify: bool,
231
232 /// Whether to show a toast when an existing issue visibly changes
233 /// (status, priority, score).
234 #[serde(default = "default_true")]
235 pub notify_changes: bool,
236
237 /// Whether to show a toast when an issue leaves the inbox
238 /// (closed or reassigned). Off by default.
239 #[serde(default)]
240 pub notify_gone: bool,
241
242 /// Extra Jira fields to fetch (custom fields such as Scoring).
243 #[serde(default)]
244 pub custom_fields: Vec<JiraCustomField>,
245
246 /// Field id used for ranking (DESC), typically Scoring (`customfield_…`).
247 #[serde(default, skip_serializing_if = "Option::is_none")]
248 pub sort_by_field: Option<String>,
249
250 /// How long a toast's Snooze button sleeps: 3d, 12h, 2w.
251 ///
252 /// Shares its spelling with `inbox triage --snooze-for`, because a button
253 /// and the picker putting an issue to sleep for different lengths would be
254 /// two behaviours wearing one word.
255 #[serde(default = "default_toast_snooze_for")]
256 pub toast_snooze_for: String,
257}
258
259/// A user-configured Jira custom field for inbox sync / display.
260#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
261pub struct JiraCustomField {
262 /// Jira field id, e.g. `customfield_12345`.
263 pub id: String,
264 /// Human-readable label, e.g. `Scoring`.
265 pub label: String,
266}
267
268fn default_true() -> bool {
269 true
270}
271
272fn default_jira_inbox_poll_interval() -> u64 {
273 300
274}
275
276fn default_toast_snooze_for() -> String {
277 "1d".to_string()
278}
279
280impl Default for JiraInboxConfig {
281 fn default() -> Self {
282 Self {
283 enabled: true,
284 poll_interval_secs: default_jira_inbox_poll_interval(),
285 notify: true,
286 notify_changes: true,
287 notify_gone: false,
288 custom_fields: Vec::new(),
289 sort_by_field: None,
290 toast_snooze_for: default_toast_snooze_for(),
291 }
292 }
293}
294
295impl JiraInboxConfig {
296 /// Field ids to request from Jira search (custom fields only).
297 pub fn extra_field_ids(&self) -> Vec<String> {
298 let mut ids: Vec<String> = self.custom_fields.iter().map(|f| f.id.trim().to_string()).filter(|id| !id.is_empty()).collect();
299 if let Some(sort_id) = &self.sort_by_field {
300 let trimmed = sort_id.trim();
301 if !trimmed.is_empty() && !ids.iter().any(|id| id == trimmed) {
302 ids.push(trimmed.to_string());
303 }
304 }
305 ids
306 }
307}
308
309/// Settings for intelligent task discovery (`kasl task find`).
310#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
311pub struct TaskDiscoveryConfig {
312 /// Names/prefixes of tasks and commits to exclude from discovery.
313 ///
314 /// Matching is case-insensitive after normalization; a pattern matches
315 /// when the candidate name equals it or starts with it.
316 #[serde(default = "default_ignore_names")]
317 pub ignore_names: Vec<String>,
318}
319
320/// Built-in ignore patterns moved from the former hardcoded noise filter.
321pub fn default_ignore_names() -> Vec<String> {
322 vec![
323 "Merge remote-tracking branch".to_string(),
324 "Merge branch ".to_string(),
325 "update webui".to_string(),
326 ]
327}
328
329impl Default for TaskDiscoveryConfig {
330 fn default() -> Self {
331 Self {
332 ignore_names: default_ignore_names(),
333 }
334 }
335}
336
337impl Default for MonitorConfig {
338 fn default() -> Self {
339 MonitorConfig {
340 min_pause_duration: 20,
341 pause_threshold: 60,
342 poll_interval: 500,
343 activity_threshold: 30,
344 min_work_interval: 10,
345 pause_merge_gap: default_pause_merge_gap(),
346 }
347 }
348}
349
350impl Default for ProductivityConfig {
351 fn default() -> Self {
352 ProductivityConfig {
353 min_productivity_threshold: 75.0,
354 workday_hours: 8.0,
355 min_workday_fraction_before_suggest: 0.5,
356 }
357 }
358}
359
360impl Config {
361 /// Loads the config file, or defaults when none exists yet.
362 ///
363 /// ```rust,no_run
364 /// # fn main() -> anyhow::Result<()> {
365 /// use kasl::libs::config::Config;
366 ///
367 /// let config = Config::read()?;
368 ///
369 /// if config.jira.is_some() {
370 /// println!("Jira integration is configured");
371 /// }
372 /// # Ok(())
373 /// # }
374 /// ```
375 pub fn read() -> Result<Config> {
376 let config_file_path = DataStorage::new().get_path(CONFIG_FILE_NAME)?;
377
378 if !config_file_path.exists() {
379 return Ok(Config::default());
380 }
381
382 let config_str = fs::read_to_string(config_file_path)?;
383 let config: Config = serde_json::from_str(&config_str)?;
384 Ok(config)
385 }
386
387 /// Writes the config as pretty-printed JSON, overwriting the file.
388 ///
389 /// ```rust,no_run
390 /// # fn main() -> anyhow::Result<()> {
391 /// use kasl::libs::config::{Config, MonitorConfig};
392 ///
393 /// let mut config = Config::read()?;
394 /// config.monitor = Some(MonitorConfig::default());
395 /// config.save()?;
396 /// # Ok(())
397 /// # }
398 /// ```
399 pub fn save(&self) -> Result<()> {
400 let config_file_path = DataStorage::new().get_path(CONFIG_FILE_NAME)?;
401 let json_content = serde_json::to_string_pretty(&self)?;
402 fs::write(config_file_path, json_content)?;
403 Ok(())
404 }
405
406 /// Returns the ignore list for task discovery.
407 ///
408 /// When `task_discovery` is not configured, returns the built-in defaults.
409 pub fn effective_ignore_names(&self) -> Vec<String> {
410 self.task_discovery
411 .as_ref()
412 .map(|c| c.ignore_names.clone())
413 .unwrap_or_else(default_ignore_names)
414 }
415
416 /// Appends unique names to the discovery ignore list and saves the config.
417 ///
418 /// Uniqueness is determined by [`normalize_task_name`]. Returns how many
419 /// new entries were added.
420 pub fn add_ignore_names(&mut self, names: &[String]) -> Result<usize> {
421 let mut discovery = self.task_discovery.clone().unwrap_or_default();
422 let mut added = 0;
423
424 for name in names {
425 let trimmed = name.trim();
426 if trimmed.is_empty() {
427 continue;
428 }
429 let key = normalize_task_name(trimmed);
430 let exists = discovery.ignore_names.iter().any(|existing| normalize_task_name(existing) == key);
431 if !exists {
432 discovery.ignore_names.push(trimmed.to_string());
433 added += 1;
434 }
435 }
436
437 self.task_discovery = Some(discovery);
438 self.save()?;
439 Ok(added)
440 }
441
442 /// Adds the executable's directory to the global PATH.
443 ///
444 /// Windows-shaped: checks the process PATH first, then edits the
445 /// machine-level registry value via `reg` (which needs admin rights;
446 /// the setup command downgrades a failure here to a warning).
447 ///
448 /// ```rust,no_run
449 /// # fn main() -> anyhow::Result<()> {
450 /// use kasl::libs::config::Config;
451 ///
452 /// Config::set_app_global()?;
453 /// # Ok(())
454 /// # }
455 /// ```
456 pub fn set_app_global() -> Result<()> {
457 let current_exe_path = env::current_exe()?;
458 let exe_dir = current_exe_path.parent().unwrap();
459
460 let mut paths: Vec<PathBuf> = env::split_paths(&env::var_os("PATH").unwrap()).collect();
461 let str_paths: Vec<&str> = paths.iter().filter_map(|p| p.to_str()).collect();
462
463 if str_paths.contains(&exe_dir.to_str().unwrap()) {
464 return Ok(());
465 }
466
467 if paths.iter().any(|p| p.to_str() == Some(exe_dir.to_str().unwrap())) {
468 return Ok(());
469 }
470
471 paths.push(exe_dir.to_path_buf());
472
473 let new_path = env::join_paths(paths).unwrap_or_else(|_| panic!("{}", Message::FailedToJoinPaths.to_string()));
474
475 let path_key = r"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
476
477 let reg_query_output = Command::new("reg")
478 .arg("query")
479 .arg(path_key)
480 .arg("/v")
481 .arg("Path")
482 .output()
483 .unwrap_or_else(|_| panic!("{}", Message::FailedToExecuteRegQuery.to_string()));
484
485 if !reg_query_output.status.success() {
486 let status = reg_query_output.status.to_string();
487 msg_error!(Message::PathRegistryQueryError { status: status.clone() });
488 return Err(anyhow::anyhow!("{}", Message::PathRegistryQueryError { status }));
489 }
490
491 let current_path = str::from_utf8(®_query_output.stdout)
492 .unwrap_or_else(|_| panic!("{}", Message::FailedToParseRegOutput.to_string()))
493 .split_whitespace()
494 .last()
495 .unwrap_or_else(|| panic!("{}", Message::FailedToGetPathFromReg.to_string()));
496
497 let reg_set_output = Command::new("reg")
498 .arg("add")
499 .arg(path_key)
500 .arg("/v")
501 .arg("Path")
502 .arg("/t")
503 .arg("REG_EXPAND_SZ") // Expandable string type for environment variables
504 .arg("/d")
505 .arg(format!("{};{}", current_path, new_path.to_string_lossy()))
506 .arg("/f") // Force overwrite without confirmation
507 .output()
508 .unwrap_or_else(|_| panic!("{}", Message::FailedToExecuteRegSet.to_string()));
509
510 if !reg_set_output.status.success() {
511 let status = reg_set_output.status.to_string();
512 let stderr = String::from_utf8_lossy(®_set_output.stderr).to_string();
513 msg_error!(Message::PathRegistryUpdateError {
514 status: status.clone(),
515 stderr: stderr.clone()
516 });
517 return Err(anyhow::anyhow!("{}", Message::PathRegistryUpdateError { status, stderr }));
518 }
519
520 Ok(())
521 }
522}