kasl-cli 1.10.1

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
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
//! The kasl-server client, against a local HTTP server.
//!
//! What is under test is how the client reads what comes back, which is where
//! a connection command can mislead: a URL pointing at something that is not a
//! kasl-server, a token the server refuses, an instance whose database is
//! down. Each of those has to arrive as its own message, because each has a
//! different fix.

use chrono::{DateTime, NaiveDate};
use kasl::api::kasl_server::{DayResult, DayUpload, KaslServer};
use kasl::libs::config::KaslServerConfig;
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

/// A client pointed at the mock server.
fn client_for(server: &MockServer) -> KaslServer {
    KaslServer::new(&KaslServerConfig {
        url: server.uri(),
        ca_certificate: None,
    })
    .expect("the client should build for a plain http url")
}

#[tokio::test]
async fn health_reports_the_server_version() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/health"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "ok",
            "version": "0.14.1",
            "database": "ok"
        })))
        .mount(&server)
        .await;

    let health = client_for(&server).health().await.unwrap();

    assert_eq!(health.status, "ok");
    assert_eq!(health.version, "0.14.1");
    assert_eq!(health.database, "ok");
}

#[tokio::test]
async fn a_server_that_answers_but_is_not_kasl_server_is_named_as_such() {
    let server = MockServer::start().await;
    // A parked domain, a proxy, a different app on that port: all answer 200
    // with something that is not a health report. Reading that as "connected"
    // is the failure this guards.
    Mock::given(method("GET"))
        .and(path("/health"))
        .respond_with(ResponseTemplate::new(200).set_body_string("<html><body>It works!</body></html>"))
        .mount(&server)
        .await;

    let error = client_for(&server).health().await.unwrap_err().to_string();

    assert!(error.contains("not like a kasl-server"), "unexpected error: {}", error);
}

#[tokio::test]
async fn an_unhealthy_database_is_reported_rather_than_hidden() {
    let server = MockServer::start().await;
    // The server answers 503 when it cannot reach its database. The client
    // must surface the status rather than treat a reachable process as a
    // working server.
    Mock::given(method("GET"))
        .and(path("/health"))
        .respond_with(ResponseTemplate::new(503).set_body_json(serde_json::json!({
            "status": "degraded",
            "version": "0.14.1",
            "database": "unreachable"
        })))
        .mount(&server)
        .await;

    let error = client_for(&server).health().await.unwrap_err().to_string();

    assert!(error.contains("503"), "the error should carry the status: {}", error);
}

#[tokio::test]
async fn whoami_names_the_employee_behind_the_token() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/agent/whoami"))
        .and(header("authorization", "Bearer token-kirill"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "user_name": "kirill",
            "agent_name": "laptop",
            "api_version": "v1",
            "server_version": "0.14.1"
        })))
        .mount(&server)
        .await;

    let identity = client_for(&server).identify("token-kirill").await.unwrap();

    assert_eq!(identity.user_name, "kirill");
    assert_eq!(identity.agent_name, "laptop");
    assert_eq!(identity.api_version, "v1");
    assert_eq!(identity.server_version, "0.14.1");
}

#[tokio::test]
async fn the_token_travels_as_a_bearer_header() {
    let server = MockServer::start().await;
    // Mounted with the header matcher only: a request without it matches
    // nothing and the mock server answers 404, so this fails if the token is
    // sent some other way - or not at all.
    Mock::given(method("GET"))
        .and(path("/api/v1/agent/whoami"))
        .and(header("authorization", "Bearer token-kirill"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "user_name": "kirill",
            "agent_name": "laptop",
            "api_version": "v1",
            "server_version": "0.14.1"
        })))
        .mount(&server)
        .await;

    assert!(client_for(&server).identify("token-kirill").await.is_ok());
    // The same call with a different token must not match the mock.
    assert!(client_for(&server).identify("someone-elses-token").await.is_err());
}

#[tokio::test]
async fn a_refused_token_is_reported_as_a_token_problem() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/v1/agent/whoami"))
        .respond_with(ResponseTemplate::new(401).set_body_json(serde_json::json!({
            "error": "the token is not recognized, has been revoked, or its user is deactivated"
        })))
        .mount(&server)
        .await;

    let error = client_for(&server).identify("stale-token").await.unwrap_err().to_string();

    // The distinction that matters to whoever is connecting: fix the token,
    // not the URL or the network.
    assert!(error.contains("rejected this token"), "unexpected error: {}", error);
    assert!(error.contains("revoked"), "the message should suggest what went wrong: {}", error);
}

#[tokio::test]
async fn an_unexpected_status_is_not_read_as_success() {
    let server = MockServer::start().await;
    // A reverse proxy in front of a stopped server, for instance. Neither a
    // valid identity nor an authentication problem.
    Mock::given(method("GET"))
        .and(path("/api/v1/agent/whoami"))
        .respond_with(ResponseTemplate::new(502))
        .mount(&server)
        .await;

    let error = client_for(&server).identify("token-kirill").await.unwrap_err().to_string();

    assert!(error.contains("502"), "the error should carry the status: {}", error);
}

#[tokio::test]
async fn a_server_that_is_not_listening_is_reported_by_url() {
    // A URL that resolves but has nothing behind it - the common typo, and a
    // different fix from a bad token.
    let config = KaslServerConfig {
        // Port 1 is reserved and never has a listener.
        url: "http://127.0.0.1:1".to_string(),
        ca_certificate: None,
    };

    let error = KaslServer::new(&config).unwrap().health().await.unwrap_err().to_string();

    assert!(error.contains("cannot reach"), "unexpected error: {}", error);
    assert!(error.contains("127.0.0.1:1"), "the error should name the url: {}", error);
}

#[tokio::test]
async fn a_url_with_a_trailing_slash_still_addresses_the_endpoints() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/health"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "ok",
            "version": "0.14.1",
            "database": "ok"
        })))
        .mount(&server)
        .await;

    // Without normalisation this would request `//health`, which a strict
    // router does not match.
    let client = KaslServer::new(&KaslServerConfig {
        url: format!("{}/", server.uri()),
        ca_certificate: None,
    })
    .unwrap();

    assert!(client.health().await.is_ok());
}

/// A minimal day, enough for the server to have something to answer about.
fn a_day() -> DayUpload {
    DayUpload {
        date: NaiveDate::from_ymd_opt(2026, 8, 31).unwrap(),
        started_at: DateTime::parse_from_rfc3339("2026-08-31T09:00:00-03:00").unwrap(),
        ended_at: Some(DateTime::parse_from_rfc3339("2026-08-31T18:00:00-03:00").unwrap()),
        pauses: vec![],
        tasks: vec![],
        tasks_are_complete: true,
    }
}

/// What the server sends back for an accepted day.
fn accepted_body(deleted_tasks: u64) -> serde_json::Value {
    serde_json::json!({
        "workday_id": "0f7b6f0e-4f2f-4a3e-9a2c-6a2b1c3d4e5f",
        "date": "2026-08-31",
        "pauses": 2,
        "tasks": 3,
        "deleted_tasks": deleted_tasks,
        "privacy_level": "full"
    })
}

#[tokio::test]
async fn an_accepted_day_is_reported_with_what_the_server_stored() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/v1/days"))
        .and(header("authorization", "Bearer token-kirill"))
        .respond_with(ResponseTemplate::new(200).set_body_json(accepted_body(1)))
        .mount(&server)
        .await;

    let accepted = client_for(&server).upload_day("token-kirill", &a_day()).await.unwrap();

    assert_eq!(accepted.pauses, 2);
    assert_eq!(accepted.tasks, 3);
    // The visible consequence of `tasks_are_complete`: a task deleted here
    // was deleted there. Silence about it would hide a deletion.
    assert_eq!(accepted.deleted_tasks, 1);
}

#[tokio::test]
async fn the_payload_carries_offsets_and_the_authoritative_flag() {
    // What the wire actually gets. The server refuses an instant without an
    // offset and reads a missing flag as "do not delete anything" (ADR 0003,
    // ADR 0005), so both have to survive serialisation - a detail no
    // round-trip through our own types would catch.
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/v1/days"))
        .respond_with(ResponseTemplate::new(200).set_body_json(accepted_body(0)))
        .mount(&server)
        .await;

    client_for(&server).upload_day("token-kirill", &a_day()).await.unwrap();

    let requests = server.received_requests().await.unwrap();
    let body: serde_json::Value = serde_json::from_slice(&requests[0].body).unwrap();

    assert_eq!(body["date"], "2026-08-31", "the agent's own date, not one derived from the instant");
    assert_eq!(body["started_at"], "2026-08-31T09:00:00-03:00");
    assert_eq!(body["ended_at"], "2026-08-31T18:00:00-03:00");
    assert_eq!(body["tasks_are_complete"], true);
}

#[tokio::test]
async fn an_open_day_omits_the_end_rather_than_sending_null() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/v1/days"))
        .respond_with(ResponseTemplate::new(200).set_body_json(accepted_body(0)))
        .mount(&server)
        .await;

    let mut day = a_day();
    day.ended_at = None;
    client_for(&server).upload_day("token-kirill", &day).await.unwrap();

    let requests = server.received_requests().await.unwrap();
    let body: serde_json::Value = serde_json::from_slice(&requests[0].body).unwrap();

    assert!(body.get("ended_at").is_none(), "an unfinished day carries no end: {}", body);
}

#[tokio::test]
async fn a_refused_payload_is_not_worth_retrying() {
    let server = MockServer::start().await;
    // The server's own rule: 4xx will never be accepted as sent (ADR 0005).
    // A queue that retried this would ask forever.
    Mock::given(method("POST"))
        .and(path("/api/v1/days"))
        .respond_with(ResponseTemplate::new(400).set_body_json(serde_json::json!({"error": "tasks[0]: name is empty"})))
        .mount(&server)
        .await;

    let error = client_for(&server).upload_day("token-kirill", &a_day()).await.unwrap_err();

    assert!(!error.is_retryable(), "a 400 must not be queued for a retry");
    // The server's sentence, not the JSON wrapper around it: it names what to
    // fix, and the wrapper buries it.
    assert!(error.to_string().contains("tasks[0]: name is empty"), "unexpected error: {}", error);
}

#[tokio::test]
async fn a_failure_states_the_status_once() {
    let server = MockServer::start().await;
    // The server's own error text opens with the status, and the message the
    // user reads adds it too. Adding it a third time in between produced
    // "the server refused the day (401 Unauthorized): 401 Unauthorized: the
    // token is not recognized" - three problems where there is one. Found by
    // running the real thing: every test here asserted the status was
    // present, and none that it appeared once.
    Mock::given(method("POST"))
        .and(path("/api/v1/days"))
        .respond_with(ResponseTemplate::new(401).set_body_json(serde_json::json!({"error": "401 Unauthorized: the token is not recognized"})))
        .mount(&server)
        .await;

    let error = client_for(&server).upload_day("stale-token", &a_day()).await.unwrap_err().to_string();

    assert_eq!(
        error.matches("401").count(),
        2,
        "the status belongs to the wrapper and the server's own sentence, nowhere else: {}",
        error
    );
}

#[tokio::test]
async fn a_failure_without_a_body_still_says_what_happened() {
    let server = MockServer::start().await;
    // A bare status and no explanation. The message has to carry the status
    // itself here, or there is nothing at all to go on.
    Mock::given(method("POST"))
        .and(path("/api/v1/days"))
        .respond_with(ResponseTemplate::new(418))
        .mount(&server)
        .await;

    let error = client_for(&server).upload_day("token-kirill", &a_day()).await.unwrap_err().to_string();

    assert!(error.contains("418"), "the status is all there is to report: {}", error);
}

#[tokio::test]
async fn a_rejected_token_is_not_worth_retrying() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/v1/days"))
        .respond_with(ResponseTemplate::new(401))
        .mount(&server)
        .await;

    let error = client_for(&server).upload_day("stale-token", &a_day()).await.unwrap_err();

    assert!(!error.is_retryable(), "a revoked token is fixed by reconnecting, not by waiting");
    assert!(error.to_string().contains("401"), "the error should carry the status: {}", error);
}

#[tokio::test]
async fn a_server_that_could_not_answer_keeps_the_day() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/v1/days"))
        .respond_with(ResponseTemplate::new(503))
        .mount(&server)
        .await;

    let error = client_for(&server).upload_day("token-kirill", &a_day()).await.unwrap_err();

    assert!(error.is_retryable(), "a 5xx means the server could not answer this time");
}

#[tokio::test]
async fn being_rate_limited_is_worth_retrying_despite_being_a_4xx() {
    let server = MockServer::start().await;
    // 429 sits inside the 4xx range and is the one exception to it: the
    // payload is fine, the server is only asking for a pause. Treating it
    // like the other 4xx would throw away a day that would have been accepted.
    Mock::given(method("POST"))
        .and(path("/api/v1/days"))
        .respond_with(ResponseTemplate::new(429))
        .mount(&server)
        .await;

    let error = client_for(&server).upload_day("token-kirill", &a_day()).await.unwrap_err();

    assert!(error.is_retryable(), "429 asks for a later attempt, not for the day to be dropped");
}

#[tokio::test]
async fn an_unreachable_server_keeps_the_day() {
    let client = KaslServer::new(&KaslServerConfig {
        // Port 1 is reserved and never has a listener.
        url: "http://127.0.0.1:1".to_string(),
        ca_certificate: None,
    })
    .unwrap();

    let error = client.upload_day("token-kirill", &a_day()).await.unwrap_err();

    assert!(error.is_retryable(), "nothing was answered, so nothing was written there");
    assert!(error.to_string().contains("127.0.0.1:1"), "the error should name the url: {}", error);
}

#[tokio::test]
async fn a_success_that_is_not_a_day_report_is_not_read_as_stored() {
    let server = MockServer::start().await;
    // A proxy or a different app answering 200 on that path. Reading it as an
    // accepted day would drop the day from a queue that never delivered it.
    Mock::given(method("POST"))
        .and(path("/api/v1/days"))
        .respond_with(ResponseTemplate::new(200).set_body_string("<html>OK</html>"))
        .mount(&server)
        .await;

    let error = client_for(&server).upload_day("token-kirill", &a_day()).await.unwrap_err();

    assert!(!error.is_retryable(), "an address answering for something else will not come good on a retry");
    assert!(error.to_string().contains("unreadably"), "unexpected error: {}", error);
}

/// A day for `date`, so a batch can carry several distinguishable ones.
fn a_day_on(date: &str) -> DayUpload {
    DayUpload {
        date: NaiveDate::parse_from_str(date, "%Y-%m-%d").unwrap(),
        started_at: DateTime::parse_from_rfc3339(&format!("{}T09:00:00-03:00", date)).unwrap(),
        ended_at: Some(DateTime::parse_from_rfc3339(&format!("{}T18:00:00-03:00", date)).unwrap()),
        pauses: vec![],
        tasks: vec![],
        tasks_are_complete: true,
    }
}

#[tokio::test]
async fn a_batch_reports_each_day_separately() {
    let server = MockServer::start().await;
    // The shape the server actually answers with: a per-day list, not one
    // verdict for the request (ADR 0005 in kasl-server).
    Mock::given(method("POST"))
        .and(path("/api/v1/days/batch"))
        .and(header("authorization", "Bearer token-kirill"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "accepted": 1,
            "rejected": 1,
            "results": [
                {
                    "status": "accepted",
                    "workday_id": "0f7b6f0e-4f2f-4a3e-9a2c-6a2b1c3d4e5f",
                    "date": "2026-08-30",
                    "pauses": 2,
                    "tasks": 3,
                    "deleted_tasks": 0,
                    "privacy_level": "full"
                },
                {
                    "status": "rejected",
                    "date": "2026-08-31",
                    "error": "tasks[0]: name is empty"
                }
            ]
        })))
        .mount(&server)
        .await;

    let result = client_for(&server)
        .upload_batch("token-kirill", &[a_day_on("2026-08-30"), a_day_on("2026-08-31")])
        .await
        .unwrap();

    assert_eq!(result.accepted, 1);
    assert_eq!(result.rejected, 1);
    assert_eq!(result.results.len(), 2);

    match &result.results[0] {
        DayResult::Accepted { day } => {
            assert_eq!(day.date, NaiveDate::from_ymd_opt(2026, 8, 30).unwrap());
            assert_eq!(day.tasks, 3);
        }
        other => panic!("the first day was accepted, not {:?}", other),
    }

    match &result.results[1] {
        DayResult::Rejected { date, error } => {
            assert_eq!(*date, NaiveDate::from_ymd_opt(2026, 8, 31).unwrap());
            assert!(error.contains("name is empty"), "the reason should survive: {}", error);
        }
        other => panic!("the second day was rejected, not {:?}", other),
    }
}

#[tokio::test]
async fn a_batch_that_answers_200_with_rejections_is_not_read_as_success() {
    let server = MockServer::start().await;
    // The trap ADR 0005 names outright: the status describes the request,
    // which was processed. A client reading only the status believes two days
    // arrived and drops both from its queue.
    Mock::given(method("POST"))
        .and(path("/api/v1/days/batch"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "accepted": 0,
            "rejected": 2,
            "results": [
                {"status": "rejected", "date": "2026-08-30", "error": "started_at has no offset"},
                {"status": "rejected", "date": "2026-08-31", "error": "started_at has no offset"}
            ]
        })))
        .mount(&server)
        .await;

    let result = client_for(&server)
        .upload_batch("token-kirill", &[a_day_on("2026-08-30"), a_day_on("2026-08-31")])
        .await
        .expect("the request itself succeeded");

    assert_eq!(result.accepted, 0, "the request was fine; the days were not");
    assert!(
        result.results.iter().all(|day| matches!(day, DayResult::Rejected { .. })),
        "both days should read as rejected"
    );
}

#[tokio::test]
async fn a_batch_too_large_is_refused_without_a_retry() {
    let server = MockServer::start().await;
    // 413 past KASL_MAX_BATCH_DAYS. Retrying the identical request would get
    // the same answer forever; the caller has to send fewer days.
    Mock::given(method("POST"))
        .and(path("/api/v1/days/batch"))
        .respond_with(ResponseTemplate::new(413).set_body_json(serde_json::json!({
            "error": "a batch carries at most 30 days; split the backlog"
        })))
        .mount(&server)
        .await;

    let error = client_for(&server).upload_batch("token-kirill", &[a_day()]).await.unwrap_err();

    assert!(!error.is_retryable(), "the same oversized request will never be accepted");
    assert!(error.to_string().contains("split the backlog"), "the fix should survive: {}", error);
}

#[tokio::test]
async fn a_batch_meeting_a_server_error_keeps_every_day() {
    let server = MockServer::start().await;
    // The server aborts a batch it failed on rather than calling the days
    // rejected, so this must read as "try later" - not as data to discard.
    Mock::given(method("POST"))
        .and(path("/api/v1/days/batch"))
        .respond_with(ResponseTemplate::new(500).set_body_json(serde_json::json!({"error": "database is unavailable"})))
        .mount(&server)
        .await;

    let error = client_for(&server)
        .upload_batch("token-kirill", &[a_day_on("2026-08-30"), a_day_on("2026-08-31")])
        .await
        .unwrap_err();

    assert!(error.is_retryable(), "a server that failed on the batch is worth asking again");
}

#[tokio::test]
async fn a_rate_limited_batch_is_worth_repeating() {
    let server = MockServer::start().await;
    // 429 sits inside the 4xx range and is the one exception to "4xx is
    // final". Reading it by range alone would throw a backlog away for
    // sending too fast.
    Mock::given(method("POST"))
        .and(path("/api/v1/days/batch"))
        .respond_with(ResponseTemplate::new(429).set_body_json(serde_json::json!({"error": "too many requests"})))
        .mount(&server)
        .await;

    let error = client_for(&server).upload_batch("token-kirill", &[a_day()]).await.unwrap_err();

    assert!(error.is_retryable(), "a rate limit is a wait, not a refusal of the data");
}