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
251/// A user-configured Jira custom field for inbox sync / display.
252#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
253pub struct JiraCustomField {
254 /// Jira field id, e.g. `customfield_12345`.
255 pub id: String,
256 /// Human-readable label, e.g. `Scoring`.
257 pub label: String,
258}
259
260fn default_true() -> bool {
261 true
262}
263
264fn default_jira_inbox_poll_interval() -> u64 {
265 300
266}
267
268impl Default for JiraInboxConfig {
269 fn default() -> Self {
270 Self {
271 enabled: true,
272 poll_interval_secs: default_jira_inbox_poll_interval(),
273 notify: true,
274 notify_changes: true,
275 notify_gone: false,
276 custom_fields: Vec::new(),
277 sort_by_field: None,
278 }
279 }
280}
281
282impl JiraInboxConfig {
283 /// Field ids to request from Jira search (custom fields only).
284 pub fn extra_field_ids(&self) -> Vec<String> {
285 let mut ids: Vec<String> = self.custom_fields.iter().map(|f| f.id.trim().to_string()).filter(|id| !id.is_empty()).collect();
286 if let Some(sort_id) = &self.sort_by_field {
287 let trimmed = sort_id.trim();
288 if !trimmed.is_empty() && !ids.iter().any(|id| id == trimmed) {
289 ids.push(trimmed.to_string());
290 }
291 }
292 ids
293 }
294}
295
296/// Settings for intelligent task discovery (`kasl task find`).
297#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
298pub struct TaskDiscoveryConfig {
299 /// Names/prefixes of tasks and commits to exclude from discovery.
300 ///
301 /// Matching is case-insensitive after normalization; a pattern matches
302 /// when the candidate name equals it or starts with it.
303 #[serde(default = "default_ignore_names")]
304 pub ignore_names: Vec<String>,
305}
306
307/// Built-in ignore patterns moved from the former hardcoded noise filter.
308pub fn default_ignore_names() -> Vec<String> {
309 vec![
310 "Merge remote-tracking branch".to_string(),
311 "Merge branch ".to_string(),
312 "update webui".to_string(),
313 ]
314}
315
316impl Default for TaskDiscoveryConfig {
317 fn default() -> Self {
318 Self {
319 ignore_names: default_ignore_names(),
320 }
321 }
322}
323
324impl Default for MonitorConfig {
325 fn default() -> Self {
326 MonitorConfig {
327 min_pause_duration: 20,
328 pause_threshold: 60,
329 poll_interval: 500,
330 activity_threshold: 30,
331 min_work_interval: 10,
332 pause_merge_gap: default_pause_merge_gap(),
333 }
334 }
335}
336
337impl Default for ProductivityConfig {
338 fn default() -> Self {
339 ProductivityConfig {
340 min_productivity_threshold: 75.0,
341 workday_hours: 8.0,
342 min_workday_fraction_before_suggest: 0.5,
343 }
344 }
345}
346
347impl Config {
348 /// Loads the config file, or defaults when none exists yet.
349 ///
350 /// ```rust,no_run
351 /// # fn main() -> anyhow::Result<()> {
352 /// use kasl::libs::config::Config;
353 ///
354 /// let config = Config::read()?;
355 ///
356 /// if config.jira.is_some() {
357 /// println!("Jira integration is configured");
358 /// }
359 /// # Ok(())
360 /// # }
361 /// ```
362 pub fn read() -> Result<Config> {
363 let config_file_path = DataStorage::new().get_path(CONFIG_FILE_NAME)?;
364
365 if !config_file_path.exists() {
366 return Ok(Config::default());
367 }
368
369 let config_str = fs::read_to_string(config_file_path)?;
370 let config: Config = serde_json::from_str(&config_str)?;
371 Ok(config)
372 }
373
374 /// Writes the config as pretty-printed JSON, overwriting the file.
375 ///
376 /// ```rust,no_run
377 /// # fn main() -> anyhow::Result<()> {
378 /// use kasl::libs::config::{Config, MonitorConfig};
379 ///
380 /// let mut config = Config::read()?;
381 /// config.monitor = Some(MonitorConfig::default());
382 /// config.save()?;
383 /// # Ok(())
384 /// # }
385 /// ```
386 pub fn save(&self) -> Result<()> {
387 let config_file_path = DataStorage::new().get_path(CONFIG_FILE_NAME)?;
388 let json_content = serde_json::to_string_pretty(&self)?;
389 fs::write(config_file_path, json_content)?;
390 Ok(())
391 }
392
393 /// Returns the ignore list for task discovery.
394 ///
395 /// When `task_discovery` is not configured, returns the built-in defaults.
396 pub fn effective_ignore_names(&self) -> Vec<String> {
397 self.task_discovery
398 .as_ref()
399 .map(|c| c.ignore_names.clone())
400 .unwrap_or_else(default_ignore_names)
401 }
402
403 /// Appends unique names to the discovery ignore list and saves the config.
404 ///
405 /// Uniqueness is determined by [`normalize_task_name`]. Returns how many
406 /// new entries were added.
407 pub fn add_ignore_names(&mut self, names: &[String]) -> Result<usize> {
408 let mut discovery = self.task_discovery.clone().unwrap_or_default();
409 let mut added = 0;
410
411 for name in names {
412 let trimmed = name.trim();
413 if trimmed.is_empty() {
414 continue;
415 }
416 let key = normalize_task_name(trimmed);
417 let exists = discovery.ignore_names.iter().any(|existing| normalize_task_name(existing) == key);
418 if !exists {
419 discovery.ignore_names.push(trimmed.to_string());
420 added += 1;
421 }
422 }
423
424 self.task_discovery = Some(discovery);
425 self.save()?;
426 Ok(added)
427 }
428
429 /// Adds the executable's directory to the global PATH.
430 ///
431 /// Windows-shaped: checks the process PATH first, then edits the
432 /// machine-level registry value via `reg` (which needs admin rights;
433 /// the setup command downgrades a failure here to a warning).
434 ///
435 /// ```rust,no_run
436 /// # fn main() -> anyhow::Result<()> {
437 /// use kasl::libs::config::Config;
438 ///
439 /// Config::set_app_global()?;
440 /// # Ok(())
441 /// # }
442 /// ```
443 pub fn set_app_global() -> Result<()> {
444 let current_exe_path = env::current_exe()?;
445 let exe_dir = current_exe_path.parent().unwrap();
446
447 let mut paths: Vec<PathBuf> = env::split_paths(&env::var_os("PATH").unwrap()).collect();
448 let str_paths: Vec<&str> = paths.iter().filter_map(|p| p.to_str()).collect();
449
450 if str_paths.contains(&exe_dir.to_str().unwrap()) {
451 return Ok(());
452 }
453
454 if paths.iter().any(|p| p.to_str() == Some(exe_dir.to_str().unwrap())) {
455 return Ok(());
456 }
457
458 paths.push(exe_dir.to_path_buf());
459
460 let new_path = env::join_paths(paths).unwrap_or_else(|_| panic!("{}", Message::FailedToJoinPaths.to_string()));
461
462 let path_key = r"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
463
464 let reg_query_output = Command::new("reg")
465 .arg("query")
466 .arg(path_key)
467 .arg("/v")
468 .arg("Path")
469 .output()
470 .unwrap_or_else(|_| panic!("{}", Message::FailedToExecuteRegQuery.to_string()));
471
472 if !reg_query_output.status.success() {
473 let status = reg_query_output.status.to_string();
474 msg_error!(Message::PathRegistryQueryError { status: status.clone() });
475 return Err(anyhow::anyhow!("{}", Message::PathRegistryQueryError { status }));
476 }
477
478 let current_path = str::from_utf8(®_query_output.stdout)
479 .unwrap_or_else(|_| panic!("{}", Message::FailedToParseRegOutput.to_string()))
480 .split_whitespace()
481 .last()
482 .unwrap_or_else(|| panic!("{}", Message::FailedToGetPathFromReg.to_string()));
483
484 let reg_set_output = Command::new("reg")
485 .arg("add")
486 .arg(path_key)
487 .arg("/v")
488 .arg("Path")
489 .arg("/t")
490 .arg("REG_EXPAND_SZ") // Expandable string type for environment variables
491 .arg("/d")
492 .arg(format!("{};{}", current_path, new_path.to_string_lossy()))
493 .arg("/f") // Force overwrite without confirmation
494 .output()
495 .unwrap_or_else(|_| panic!("{}", Message::FailedToExecuteRegSet.to_string()));
496
497 if !reg_set_output.status.success() {
498 let status = reg_set_output.status.to_string();
499 let stderr = String::from_utf8_lossy(®_set_output.stderr).to_string();
500 msg_error!(Message::PathRegistryUpdateError {
501 status: status.clone(),
502 stderr: stderr.clone()
503 });
504 return Err(anyhow::anyhow!("{}", Message::PathRegistryUpdateError { status, stderr }));
505 }
506
507 Ok(())
508 }
509}