eclipse-cli 0.13.4

Command-line interface for eclipse
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
//! `eclipse cron`: the commands behind the timer.
//!
//! `list` and `logs` read; `add`, `remove`, `install-timer` and `remove-timer` write; `run` is
//! what the systemd timer invokes, and it is the only one that spends a model call. Everything
//! it decides — which jobs are due — comes from [`eclipse_core::cron`], so the schedule logic is
//! tested without a clock or an agent.
//!
//! A run of a job is unattended by definition, so tools are approved up front: a prompt that
//! stops to ask a question at 07:30 has done nothing. What it costs is one session per run,
//! written the same way an interactive one is, and a log file under `cron/runs/<job>/`.

use crate::ui::Style;
use anyhow::{bail, Result};
use eclipse_core::config::{self, process_env, Config, EnvFn};
use eclipse_core::cron::{self, Job, State};
use eclipse_core::runtime::{Agent, AgentEvent};
use eclipse_core::session::now_ms;
use eclipse_core::tools::AllowAll;
use std::path::Path;

/// How many runs `logs` prints when nobody says: the CLI's flag default and `/cron logs`'s, named
/// once so the two cannot disagree (#230).
pub const DEFAULT_LOGS: usize = 5;

/// The table: what is scheduled, what ran, and when it fires next.
///
/// Returned as text rather than printed, because two surfaces draw it — `eclipse cron list` and
/// `/cron` (#230). The done-when there is that they are the *same* table, and the test compares
/// this function's output against the command's rather than against a second copy of the strings.
pub fn table(root: &Path, style: &Style) -> Result<String> {
    let (jobs, problems) = cron::load_reporting(root)?;
    for problem in &problems {
        // On stderr, every tick: a skipped job is a job that is not running, and the journal of the
        // timer is the only place a scheduled run can say anything (`#405`).
        eprintln!("cron: {problem}");
    }
    let state = cron::load_state(root)?;
    let now = now_ms() as i64;
    if jobs.is_empty() {
        return Ok(format!(
            "{}\n  add one with `eclipse cron add --name brief --schedule \"daily 07:30\" \\\n\
             --prompt \"...\"`, or edit {}",
            style.yellow("no jobs are scheduled."),
            cron::jobs_path(root).display()
        ));
    }
    let name_w = jobs.iter().map(|j| j.name.len()).max().unwrap_or(4).max(4);
    let mut out = format!(
        "{:<name_w$}  {:<18}  {:<20}  last",
        "job",
        "schedule",
        "next",
        name_w = name_w
    );
    for job in &jobs {
        let s = state.get(&job.name);
        let next = match cron::next_due_for(job, &state, now) {
            None => "— (disabled)".to_string(),
            Some(ms) => describe_when(ms, now),
        };
        let last = match (&s.last_outcome, s.last_started_ms) {
            (Some(outcome), Some(at)) => {
                format!("{} {}", describe_when_past(at, now), outcome)
            }
            (None, _) => "never".to_string(),
            (Some(outcome), None) => outcome.clone(),
        };
        out.push_str(&format!(
            "\n{:<name_w$}  {:<18}  {:<20}  {}",
            job.name,
            job.schedule.describe(),
            next,
            last,
            name_w = name_w
        ));
    }
    Ok(out)
}

/// `eclipse cron list`: the shared table, plus the one note only this command can be given.
pub fn list(cfg: &Config, root: &Path, json: bool, style: &Style) -> Result<()> {
    // A skipped block is a job that is not running, and this is where somebody looks for why
    // (`#405`). On stderr, so a `--json` pipe stays parseable.
    if let Ok((_, problems)) = cron::load_reporting(root) {
        for problem in &problems {
            eprintln!("cron: {problem}");
        }
    }
    if json {
        let now = now_ms() as i64;
        let views = cron::views(root, now)?;
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "now_ms": now,
                "jobs_file": cron::jobs_path(root).display().to_string(),
                "jobs": views,
            }))?
        );
        return Ok(());
    }
    println!("{}", table(root, style)?);
    if cfg.route_pin.is_some() {
        println!(
            "\n{}",
            style.dim(
                "note: --route was given, so this listing is unaffected but `cron run` \
                       would pin every job to that route"
            )
        );
    }
    Ok(())
}

/// `eclipse cron run [NAME] [--force]`: one tick.
///
/// Without a name it runs the jobs that are due; with one it runs that job whether or not it is
/// due (an explicit ask beats a schedule, and `--force` is not needed for it). Exit code 1 if
/// any job failed, so a shell can tell.
pub async fn run(
    cfg: &Config,
    root: &Path,
    only: Option<&str>,
    force: bool,
    json: bool,
    style: &Style,
) -> Result<i32> {
    let jobs = cron::load(root)?;
    if jobs.is_empty() {
        if only.is_none() {
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&serde_json::json!({
                        "ran": 0,
                        "jobs": [],
                        "note": "no jobs are scheduled",
                    }))?
                );
            } else {
                println!("{}", style.dim("no jobs are scheduled; nothing to do"));
            }
            return Ok(0);
        }
        bail!("no jobs are scheduled");
    }
    let now = now_ms() as i64;
    // A look, not a decision. Most minutes have nothing to do, and an idle tick should not touch
    // the lock at all — so a read here decides only whether it is worth asking for it. Whatever it
    // finds may be out of date by the time the lock is ours, which is why nothing below is decided
    // from it (`#598`).
    if only.is_none() && !force {
        let mut look: State = cron::load_state(root)?;
        // Seeding is work, and it has to be written: a tick whose whole job is anchoring a newly
        // added `daily` one must not mistake itself for an idle tick and drop the anchor (`#561`).
        let seeded = cron::seed_first_seen(&jobs, &mut look, now);
        if seeded.is_empty() && cron::due(&jobs, &mut look, now).is_empty() {
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&serde_json::json!({
                        "ran": 0,
                        "jobs": [],
                        "note": "nothing to run",
                    }))?
                );
            }
            // Silence is the normal case: the timer ticks every minute and most ticks have nothing
            // to do. Only a person asking for output gets a line.
            return Ok(0);
        }
    }

    let Some(mut tick) = cron::lock(root, now)? else {
        // A previous tick is still working. Not an error, and not worth a model call.
        if json {
            println!(
                "{}",
                serde_json::to_string_pretty(&serde_json::json!({
                    "ran": 0,
                    "jobs": [],
                    "note": "a previous run still holds the lock",
                }))?
            );
        } else {
            println!(
                "{}",
                style.dim("a previous run still holds the lock; this tick does nothing")
            );
        }
        return Ok(0);
    };

    // Now, and only now, the tick reads what it is going to act on (`#598`). Read before the lock,
    // a tick decided from a snapshot a previous tick had already superseded: the job it had just
    // run still looked due, so both ran it, and the second saved its older copy of the counters
    // over the first one's. The lock is the decision point, so everything that decides is here.
    let mut state: State = cron::load_state(root)?;
    // A job that has appeared since the last tick gets its anchor here, or a `daily`/`weekly` job
    // would wait for history nothing writes and never fire (`#561`).
    let seeded = cron::seed_first_seen(&jobs, &mut state, now);

    let selected: Vec<Job> = match only {
        Some(name) => {
            let job = jobs
                .iter()
                .find(|j| j.name == name)
                .ok_or_else(|| {
                    anyhow::anyhow!("no job named `{name}`; `eclipse cron list` shows the names")
                })?
                .clone();
            vec![job]
        }
        None => {
            let mut due: Vec<Job> = cron::due(&jobs, &mut state, now)
                .into_iter()
                .cloned()
                .collect();
            if force {
                due = jobs.iter().filter(|j| j.enabled).cloned().collect();
            }
            due
        }
    };
    if selected.is_empty() && seeded.is_empty() {
        // Another tick ran what this one came for between the look above and the lock. Nothing to
        // say: the jobs did run, once.
        if json {
            println!(
                "{}",
                serde_json::to_string_pretty(&serde_json::json!({
                    "ran": 0,
                    "jobs": [],
                    "note": "nothing to run",
                }))?
            );
        } else if force || only.is_some() {
            println!("{}", style.dim("nothing to run"));
        }
        return Ok(0);
    }

    // The seed is state, not a note: unsaved, the next tick would anchor the same job later and a
    // daily one would slide forward for ever. Written under the lock, before anything runs.
    if !seeded.is_empty() {
        cron::save_state(root, &state)?;
    }
    if selected.is_empty() {
        if json {
            println!(
                "{}",
                serde_json::to_string_pretty(&serde_json::json!({
                    "ran": 0,
                    "jobs": [],
                    "note": "nothing to run; anchored the jobs added since the last tick",
                }))?
            );
        } else if force || only.is_some() {
            println!("{}", style.dim("nothing to run"));
        }
        return Ok(0);
    }

    let mut failures = 0usize;
    let mut records: Vec<serde_json::Value> = Vec::new();
    for job in &selected {
        // Proof of life between jobs: a tick that legitimately runs longer than the stale mark is
        // not abandoned, and saying so is what stops the next minute's tick running the jobs this
        // one has not reached yet (`#407`).
        if !tick.touch(now_ms() as i64) {
            eprintln!(
                "cron: another tick took the lock while this one was working; stopping before `{}`",
                job.name
            );
            break;
        }
        let started = now_ms() as i64;
        state
            .jobs
            .entry(job.name.clone())
            .or_default()
            .last_started_ms = Some(started);
        state.jobs.entry(job.name.clone()).or_default().runs += 1;
        cron::save_state(root, &state)?;

        let outcome = run_one(cfg, job).await;
        let (body, failed) = match outcome {
            Ok((text, hops)) => {
                let mut body = format!(
                    "# {} — {}\n\nschedule {}\n\n",
                    job.name,
                    iso_local(started),
                    job.schedule.describe()
                );
                if let Some(line) = hops {
                    body.push_str(&format!("{line}\n\n"));
                }
                body.push_str("---\n\n");
                body.push_str(text.trim_end_matches('\n'));
                body.push('\n');
                (body, false)
            }
            Err(e) => {
                failures += 1;
                let body = format!(
                    "# {} — failed\n\nstarted {}\n\n---\n\n{}\n",
                    job.name,
                    iso_local(started),
                    e
                );
                (body, true)
            }
        };
        // The reply has already run and been paid for. A file this tick cannot write is a problem to
        // report, not a reason to abandon the rest of the tick: the `?` here used to skip every other
        // due job, and to lose this one's outcome, so `cron list` kept showing the run before it.
        let mut problems: Vec<String> = Vec::new();
        let path = match cron::write_run(root, &job.name, started, &body) {
            Ok(path) => Some(path),
            Err(e) => {
                failures += 1;
                problems.push(format!("the run log could not be written: {e}"));
                None
            }
        };
        if let Some(deliver) = &job.deliver {
            let target = expand_path(deliver);
            let written = match target.parent() {
                Some(dir) => std::fs::create_dir_all(dir)
                    .map_err(|e| format!("creating {}: {e}", dir.display())),
                None => Ok(()),
            }
            .and_then(|()| {
                let text = if failed {
                    format!(
                        "# {} failed at {}\n\n{}\n",
                        job.name,
                        iso_local(started),
                        body
                    )
                } else {
                    body.clone()
                };
                std::fs::write(&target, text)
                    .map_err(|e| format!("writing {}: {e}", target.display()))
            });
            if let Err(e) = written {
                failures += 1;
                problems.push(format!("the delivery to {deliver} failed: {e}"));
            }
        }
        if !problems.is_empty() {
            // Into the run log, where the next reader looks, and onto the terminal: the log is the
            // record, the line is so an unattended tick's damage is visible in a journal.
            if let Some(path) = &path {
                let mut text = String::from("\n");
                for problem in &problems {
                    text.push_str(&format!("- {problem}\n"));
                }
                if let Ok(mut file) = std::fs::OpenOptions::new().append(true).open(path) {
                    let _ = std::io::Write::write_all(&mut file, text.as_bytes());
                }
            }
            if !json {
                for problem in &problems {
                    println!("{} {}", style.red("problem:"), problem);
                }
            }
        }
        let finished = now_ms() as i64;
        {
            let entry = state.jobs.entry(job.name.clone()).or_default();
            entry.last_finished_ms = Some(finished);
            entry.last_outcome = Some(if failed {
                "failed".to_string()
            } else {
                "ok".to_string()
            });
        }
        cron::save_state(root, &state)?;

        if json {
            records.push(serde_json::json!({
                "name": job.name,
                "ok": !failed,
                "outcome": if failed { "failed" } else { "ok" },
                "started_ms": started,
                "finished_ms": finished,
                "log": path.as_ref().map(|p| p.display().to_string()),
                "problems": problems,
            }));
            continue;
        }
        let mark = if failed {
            style.red("failed")
        } else {
            style.green("ok")
        };
        println!(
            "{} {} {}",
            mark,
            job.name,
            style
                .dim(&path.map_or_else(|| "<no run log>".to_string(), |p| p.display().to_string()))
        );
    }
    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "ran": records.len(),
                "failed": failures,
                "jobs": records,
            }))?
        );
    }
    Ok(if failures > 0 { 1 } else { 0 })
}

/// The config a job runs with: its own route pinned, and its own directory as the workspace.
///
/// `workdir` is "the directory the job starts in, when it needs to touch files", and in this agent
/// the workspace root is what that means: the file tools are confined to it, `shell` runs in it, and
/// the `AGENT.md` walk begins there. Applied through the same field the rest of the program uses, so
/// there is one rule for "where a tool may write" and not two.
fn job_config(cfg: &Config, job: &Job) -> Result<Config> {
    let mut job_cfg = cfg.clone();
    if let Some(route) = &job.route {
        job_cfg.pin_route(Some(route), &process_env)?;
    }
    if let Some(workdir) = &job.workdir {
        job_cfg.tools.workspace_root = Some(expand_path(workdir));
    }
    Ok(job_cfg)
}

/// Run one job and return its reply. The hop line is what the run said about fallback, if any.
async fn run_one(cfg: &Config, job: &Job) -> Result<(String, Option<String>)> {
    let job_cfg = job_config(cfg, job)?;
    let agent = Agent::from_config(&job_cfg)?;

    // A job may demand a shape, exactly as `run --schema` does: its own field wins, then the
    // machine-wide `[agent] output_schema`. The schema rides in the request as `response_format`,
    // and the same check M15 uses judges the reply — "is this a JSON document", not field-by-field
    // validation. Unattended is where that matters: a job whose answer came back as prose fails
    // and says so in its own log, rather than a consumer downstream finding out.
    let shape =
        crate::resolve_schema(job.schema.as_deref(), &job_cfg)?.map(crate::Shape::parse_json);

    let mut prompt = String::new();
    if !job.skills.is_empty() {
        let names: Vec<String> = job.skills.iter().map(|s| format!("`{s}`")).collect();
        prompt.push_str(&format!(
            "Load these skills with the skill_view tool before you start: {}.\n\n",
            names.join(", ")
        ));
    }
    prompt.push_str(&job.prompt);

    // Every assistant turn, in order. A job that used a tool has several, and the last one is
    // the answer; earlier ones are the model saying what it was about to do, which is worth
    // keeping in the log rather than dropping.
    let turns = std::sync::Mutex::new(Vec::<String>::new());
    let hop_line = std::sync::Mutex::new(None::<String>);
    let sink = |event: AgentEvent| {
        if let AgentEvent::Message(text) = event {
            if let Ok(mut v) = turns.lock() {
                v.push(text);
            }
        }
    };
    let run = agent
        .run_checked(
            None,
            &prompt,
            &AllowAll,
            &sink,
            &eclipse_core::cancel::Cancel::new(),
            &eclipse_core::runtime::RunOptions {
                output_schema: shape.as_ref().map(|s| s.schema.clone()),
                // A scheduled job runs in a process that is gone before a naming call could
                // return, and its session carries the name its opening message gave it.
                title: false,
                ..Default::default()
            },
            shape.as_ref().map(|s| &*s.check),
        )
        .await?;
    drop(hop_line);
    let hops = eclipse_core::router::describe_hops(&run.hops);
    let text = turns
        .into_inner()
        .unwrap_or_default()
        .into_iter()
        .filter(|t| !t.trim().is_empty())
        .collect::<Vec<_>>()
        .join("\n\n");
    Ok((text, hops))
}

/// `eclipse cron add …` — one `[[job]]` block, appended.
#[allow(clippy::too_many_arguments)]
pub fn add(
    root: &Path,
    name: &str,
    schedule: &str,
    prompt: &str,
    deliver: Option<&str>,
    route: Option<&str>,
    workdir: Option<&str>,
    skills: Vec<String>,
    schema: Option<&str>,
    style: &Style,
) -> Result<()> {
    // Two checks the page does not make, because they are about this surface: `!command` is a
    // composer gesture, and `--schema` here is a path or an inline document that has to resolve
    // now rather than at 07:30 into a log nobody reads. Everything else is `Draft`'s rule, shared
    // with the dashboard so the two cannot disagree.
    if let crate::bang::Line::Bang(_) = crate::bang::parse(prompt) {
        bail!(
            "{}",
            crate::bang::refusal(crate::bang::Surface::Cron).expect("a job has no keyboard")
        );
    }
    // A schedule that spawns background jobs is a fork bomb with a schedule: a job has no
    // composer to return to, so the line is refused rather than stored to fail every tick.
    if eclipse_core::tasks::bg_prompt(prompt).is_some() {
        bail!("{}", eclipse_core::tasks::bg_refusal("a cron job"));
    }
    // `/yolo` is a mode this session is in, and a job is nobody's session: refused here rather
    // than stored to run with every approval pre-answered and nothing on screen saying so.
    if prompt.trim_start().starts_with("/yolo") {
        bail!("{}", crate::yolo::refusal("a cron job"));
    }
    if let Some(source) = schema {
        crate::read_schema(source)?;
    }
    let job = cron::Draft {
        name: name.to_string(),
        schedule: schedule.to_string(),
        prompt: prompt.to_string(),
        deliver: deliver.map(|s| s.to_string()),
        route: route.map(|s| s.to_string()),
        workdir: workdir.map(|s| s.to_string()),
        skills,
        schema: schema.map(|s| s.to_string()),
        enabled: true,
    }
    // One rule for both front ends: the page submits the same `Draft` and gets the same sentences.
    .to_job()?;
    // Validate by round-tripping through the loader, so `add` cannot write a file `list` would
    // refuse to read.
    cron::append_job(root, &job)?;
    cron::load(root)?;
    println!(
        "{} {} ({}) → {}",
        style.green("added"),
        job.name,
        job.schedule.describe(),
        cron::jobs_path(root).display()
    );
    println!(
        "{}",
        style.dim("`eclipse cron install-timer` makes it run without you")
    );
    Ok(())
}

/// `eclipse cron enable|disable NAME`: the same switch the dashboard's row carries.
///
/// A disabled job keeps its prompt, its schedule and its history; only `due` ignores it. Deleting
/// to silence something is the worse option, because the prompt is the part that was written.
pub fn toggle(root: &Path, name: &str, enabled: bool, style: &Style) -> Result<()> {
    match cron::set_enabled(root, name, enabled)? {
        Some(job) => {
            let word = if enabled { "enabled" } else { "disabled" };
            println!(
                "{} {} ({})",
                style.green(word),
                job.name,
                job.schedule.describe()
            );
            Ok(())
        }
        None => bail!("no job named `{name}`; `eclipse cron list` shows the names"),
    }
}

pub fn remove(root: &Path, name: &str, style: &Style) -> Result<()> {
    if cron::remove_job(root, name)? {
        println!("{} {}", style.green("removed"), name);
        Ok(())
    } else {
        bail!("no job named `{name}`")
    }
}

/// `eclipse cron logs NAME`: the run files, newest first, with their first line of answer.
///
/// `--json` hands the page the same `cron::RunView` — the answer, the beginning of the text and how
/// long the rest is — so neither surface has to parse a run file to know what happened.
pub fn logs(root: &Path, name: &str, limit: usize, json: bool, style: &Style) -> Result<()> {
    if json {
        if !cron::load(root)?.iter().any(|j| j.name == name) {
            bail!("no job named `{name}`");
        }
        let runs = cron::runs(root, name, limit);
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "job": name,
                "runs_dir": cron::runs_dir(root, name).display().to_string(),
                "runs": runs,
            }))?
        );
        return Ok(());
    }
    println!("{}", log_text(root, name, limit, style)?);
    Ok(())
}

/// The same lines `eclipse cron logs` prints, for `/cron logs` (#230).
pub fn log_text(root: &Path, name: &str, limit: usize, style: &Style) -> Result<String> {
    if !cron::load(root)?.iter().any(|j| j.name == name) {
        bail!("no job named `{name}`; {}", names(root)?);
    }
    let runs = cron::runs(root, name, limit);
    if runs.is_empty() {
        return Ok(style.dim("no runs yet"));
    }
    Ok(runs
        .iter()
        .map(|run| {
            format!(
                "{}  {}\n    {}",
                style.dim(&run.at),
                run.answer,
                style.dim(&run.path)
            )
        })
        .collect::<Vec<_>>()
        .join("\n"))
}

/// The names that exist, for a refusal that says what to type instead of only what was wrong.
pub fn names(root: &Path) -> Result<String> {
    let jobs = cron::load(root)?;
    if jobs.is_empty() {
        return Ok("no jobs are scheduled".to_string());
    }
    let list: Vec<String> = jobs.iter().map(|j| format!("`{}`", j.name)).collect();
    Ok(format!("jobs: {}", list.join(", ")))
}

/// The systemd user units, written where `systemctl --user` looks for them.
const SERVICE_NAME: &str = "eclipse-cron.service";
const TIMER_NAME: &str = "eclipse-cron.timer";

/// The systemd user unit directory, from an injected environment so a test needs no `$HOME`.
fn units_dir_in(env: EnvFn) -> Option<std::path::PathBuf> {
    env("HOME").map(|home| {
        std::path::PathBuf::from(home)
            .join(".config")
            .join("systemd")
            .join("user")
    })
}

fn units_dir() -> Result<std::path::PathBuf> {
    units_dir_in(&process_env).ok_or_else(|| anyhow::anyhow!("HOME is not set"))
}

/// `eclipse cron install-timer`: write the units and enable the timer, as the current user.
///
/// No root: these are user units, which is the only kind an agent that lives in `~/.eclipse`
/// has any business installing.
pub fn install_timer(style: &Style) -> Result<()> {
    let exe = std::env::current_exe()
        .map_err(|e| anyhow::anyhow!("cannot find this program to point the unit at: {e}"))?;
    let dir = units_dir()?;
    std::fs::create_dir_all(&dir)?;
    let service = format!(
        "[Unit]\n\
         Description=Eclipse scheduled prompts (one tick)\n\
         Documentation=file:{}\n\
         \n\
         [Service]\n\
         Type=oneshot\n\
         ExecStart={} cron run\n\
         # A tick with nothing due exits in milliseconds; the timer wakes every minute.\n\
         Nice=5\n",
        cron::jobs_path(&config::home_root(&process_env).unwrap_or_default()).display(),
        crate::gateway_cli::systemd_word(&exe)
    );
    let timer = "[Unit]\n\
                 Description=Tick Eclipse's scheduled prompts every minute\n\
                 \n\
                 [Timer]\n\
                 OnBootSec=1min\n\
                 OnUnitActiveSec=1min\n\
                 AccuracySec=10s\n\
                 # Catch up once after the machine was off, rather than a burst per missed minute.\n\
                 Persistent=true\n\
                 \n\
                 [Install]\n\
                 WantedBy=timers.target\n";
    let service_path = dir.join(SERVICE_NAME);
    let timer_path = dir.join(TIMER_NAME);
    std::fs::write(&service_path, service)?;
    std::fs::write(&timer_path, timer)?;
    println!("{} {}", style.green("wrote"), service_path.display());
    println!("{} {}", style.green("wrote"), timer_path.display());

    let ran = std::process::Command::new("systemctl")
        .args(["--user", "daemon-reload"])
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
        && std::process::Command::new("systemctl")
            .args(["--user", "enable", "--now", TIMER_NAME])
            .status()
            .map(|s| s.success())
            .unwrap_or(false);
    if ran {
        println!("{} {}", style.green("enabled"), TIMER_NAME);
        println!(
            "{}",
            style.dim(
                "  `systemctl --user list-timers eclipse-cron.timer` shows the next tick; \
                 `journalctl --user -u eclipse-cron.service` shows what ran"
            )
        );
        println!(
            "{}",
            style.dim(
                "  to run while you are logged out: loginctl enable-linger $USER (needs root)"
            )
        );
    } else {
        println!(
            "{}",
            style.yellow("systemctl did not take it; enable it by hand with:")
        );
        println!("  systemctl --user daemon-reload");
        println!("  systemctl --user enable --now {TIMER_NAME}");
        // Both files are on disk and nothing ticks: a half-install that used to exit 0.
        bail!(
            "the units are written to {} but systemctl did not enable the timer — run the two commands above",
            dir.display()
        );
    }
    Ok(())
}

pub fn remove_timer(style: &Style) -> Result<()> {
    let dir = units_dir()?;
    let _ = std::process::Command::new("systemctl")
        .args(["--user", "disable", "--now", TIMER_NAME])
        .status();
    let mut removed = false;
    for name in [TIMER_NAME, SERVICE_NAME] {
        let path = dir.join(name);
        if path.exists() {
            std::fs::remove_file(&path)?;
            removed = true;
            println!("{} {}", style.green("removed"), path.display());
        }
    }
    let _ = std::process::Command::new("systemctl")
        .args(["--user", "daemon-reload"])
        .status();
    if !removed {
        println!("{}", style.dim("no timer was installed"));
    }
    Ok(())
}

// ---------------------------------------------------------------------------------------------
// Time, for people
// ---------------------------------------------------------------------------------------------

/// `2026-11-29 07:30`, in local time. The formatter itself lives in the store beside the run
/// reader, so `cron logs --json` and this line cannot disagree about what a moment looks like.
pub fn iso_local(ms: i64) -> String {
    cron::iso_local(ms)
}

/// The next time, plus how far away it is: `2026-11-29 07:30 (in 8h 12m)`.
fn describe_when(ms: i64, now: i64) -> String {
    let delta = ms - now;
    format!("{} ({})", short_when(ms, now), humanize(delta))
}

fn describe_when_past(ms: i64, now: i64) -> String {
    let delta = now - ms;
    if delta < 5_000 {
        return "just now".to_string();
    }
    format!("{} ago", span(delta))
}

/// Near times as a clock, far ones as a date: a listing that says `2026-11-29 07:30` for
/// something due in five minutes is harder to read than `08:42`.
fn short_when(ms: i64, now: i64) -> String {
    let delta = ms - now;
    if (0..86_400_000).contains(&delta) {
        let (_, _, _, h, m) = cron::local_parts(ms);
        format!("{h:02}:{m:02}")
    } else {
        iso_local(ms)[..10].to_string()
    }
}

fn humanize(delta_ms: i64) -> String {
    if delta_ms < 0 {
        return format!("{} ago", span(delta_ms));
    }
    if delta_ms < 5_000 {
        return "now".to_string();
    }
    format!("in {}", span(delta_ms))
}

fn span(delta_ms: i64) -> String {
    let secs = delta_ms.unsigned_abs() / 1000;
    if secs < 60 {
        format!("{secs}s")
    } else if secs < 3600 {
        format!("{}m", secs / 60)
    } else if secs < 86_400 {
        format!("{}h {}m", secs / 3600, (secs % 3600) / 60)
    } else {
        format!("{}d", secs / 86_400)
    }
}

/// `~/x` and `$HOME/x` into a path, without the config module's private helper.
fn expand_path(text: &str) -> std::path::PathBuf {
    if let Some(rest) = text.strip_prefix("~/") {
        if let Some(home) = process_env("HOME") {
            return std::path::PathBuf::from(home).join(rest);
        }
    }
    std::path::PathBuf::from(text)
}

/// Whether anything is firing jobs, read off the filesystem.
///
/// `#230` asks the composer's table to say "the scheduler is not running" when it is not. The honest
/// source for that is **not** the gateway: `eclipse-gateway` deliberately does not tick cron
/// (`schedule.rs`: "cron keeps its own timer so a wedged tick cannot take the dashboard with it"), so
/// a gateway that is down has no bearing on whether a job fires. What fires jobs is the systemd user
/// timer `cron install-timer` writes, and a unit file plus its enablement symlink answer that
/// question without starting a process.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Scheduler {
    /// The timer unit file, when `cron install-timer` has been run.
    pub timer: Option<std::path::PathBuf>,
    /// Whether that timer is wanted by `default.target` — installed is not the same as enabled, and
    /// a timer that vanishes at reboot is exactly how a job silently stops.
    pub enabled: bool,
    /// The newest `last_started_ms` across the jobs: evidence of a tick, not an intent to tick.
    pub last_tick_ms: Option<i64>,
}

/// Whether systemd will start the timer at boot, from the enable symlink.
///
/// `enable` creates that symlink in the `.wants` directory named by the unit's own `WantedBy=`,
/// which is `timers.target` for the unit written above — and `default.target` for a timer installed
/// by an older build. Both are symlinks systemd follows, so both mean it fires. Reading only
/// `default.target` called every healthy install dead and told its owner to run the command they had
/// already run (`#600`).
fn enabled_in(units: &Path) -> bool {
    ["timers.target.wants", "default.target.wants"]
        .iter()
        .any(|want| units.join(want).join(TIMER_NAME).exists())
}

/// What is scheduling these jobs, from the units on disk and the state file.
pub fn scheduler(root: &Path) -> Scheduler {
    scheduler_with(root, &process_env)
}

fn scheduler_with(root: &Path, env: EnvFn) -> Scheduler {
    let units = units_dir_in(env);
    let timer = units
        .as_ref()
        .map(|dir| dir.join(TIMER_NAME))
        .filter(|path| path.is_file());
    let enabled = units.as_deref().is_some_and(enabled_in);
    let last_tick_ms = cron::load_state(root)
        .map(|state| {
            state
                .jobs
                .values()
                .filter_map(|entry| entry.last_started_ms)
                .max()
        })
        .ok()
        .flatten();
    Scheduler {
        timer,
        enabled,
        last_tick_ms,
    }
}

/// The line under the table when nothing is going to fire it, or `None` when something is.
///
/// Silent in the healthy case on purpose: a table that shouts "running" every time teaches people to
/// stop reading the line that matters.
pub fn scheduler_note(sched: &Scheduler, style: &Style) -> Option<String> {
    let now = now_ms() as i64;
    match (&sched.timer, sched.enabled) {
        (Some(_), true) => sched.last_tick_ms.map(|at| {
            style.dim(&format!(
                "scheduler: {} is enabled; the last tick was {}",
                TIMER_NAME,
                describe_when_past(at, now)
            ))
        }),
        (Some(_), false) => Some(format!(
            "scheduler: {} is installed but not enabled, so nothing fires after a reboot — \
             `systemctl --user enable --now {TIMER_NAME}`",
            TIMER_NAME
        )),
        (None, _) => Some(
            "scheduler: nothing is installed to run these, so a job fires only when you ask — \
             `eclipse cron install-timer` installs it"
                .to_string(),
        ),
    }
}

/// Where the `eclipse` binary is, for the one thing this process should not do in-process.
///
/// `/cron run` spawns `eclipse cron run <name>` rather than driving an agent inside the composer, so
/// the job runs with its own route, workspace and approval mode — the same binary the timer invokes,
/// which is the only way a hand-run and a scheduled run cannot drift. `ECLIPSE_BIN` first so a test
/// can point at a stand-in.
fn eclipse_bin() -> std::path::PathBuf {
    if let Some(path) = std::env::var_os("ECLIPSE_BIN") {
        return std::path::PathBuf::from(path);
    }
    if let Ok(exe) = std::env::current_exe() {
        if let Some(dir) = exe.parent() {
            let beside = dir.join("eclipse");
            if beside.is_file() {
                return beside;
            }
        }
    }
    std::path::PathBuf::from("eclipse")
}

/// `/cron run <name>`: fire one job now, in a child process, and report what it did.
///
/// Waits: the issue asks for the exit code, and an exit code that arrives later in another pane is
/// not a report. The job's own lines come from the child, its summary from the run file the child
/// wrote — so nothing here re-renders a job's answer.
pub fn run_now(
    place: Option<&eclipse_core::config::Where>,
    root: &Path,
    name: &str,
    style: &Style,
) -> Result<String> {
    if !cron::load(root)?.iter().any(|j| j.name == name) {
        bail!("no job named `{name}`; {}", names(root)?);
    }
    let mut command = std::process::Command::new(eclipse_bin());
    // `#442`: the child resolved the *default* config while this process read one named by
    // `--config`, so a composer started with `eclipse --config somewhere.toml` fired its job
    // against a different file — found and listed here, run there. Both flags are global on
    // `eclipse`, so both go before the subcommand, in the order `--config` then `--profile` (a
    // profile is an overlay on the base file, and passing them the other way round reads backwards
    // in the process list even though it resolves the same).
    if let Some(config) = place.and_then(|p| p.config.as_ref()) {
        command.arg("--config").arg(config);
    }
    if let Some(profile) = place.and_then(|p| p.profile.as_deref()) {
        command.arg("--profile").arg(profile);
    }
    let output = command
        .args(["cron", "run", name])
        .output()
        .map_err(|e| anyhow::anyhow!("could not start {}: {e}", eclipse_bin().display()))?;
    let mut out = String::from_utf8_lossy(&output.stdout)
        .trim_end()
        .to_string();
    let err = String::from_utf8_lossy(&output.stderr)
        .trim_end()
        .to_string();
    if !err.is_empty() {
        if !out.is_empty() {
            out.push('\n');
        }
        out.push_str(err.trim_end());
    }
    let code = output.status.code().unwrap_or(-1);
    // The run file is the summary: the answer's first line and how much more of it there is.
    if let Some(run) = cron::runs(root, name, 1).first() {
        if !out.is_empty() {
            out.push('\n');
        }
        out.push_str(&format!(
            "{} {}{}",
            style.dim("said:"),
            run.answer,
            if run.truncated || run.chars > run.answer.chars().count() {
                format!(" (+{} more chars in {})", run.chars, run.path)
            } else {
                String::new()
            }
        ));
    }
    if !out.is_empty() {
        out.push('\n');
    }
    out.push_str(&format!(
        "{} {}",
        style.dim("exit code:"),
        if code == 0 {
            style.green("0")
        } else {
            style.red(&code.to_string())
        }
    ));
    Ok(out)
}

/// Everything `/cron` can be asked, as text (#230).
///
/// Read verbs only. Adding a job stays in the CLI: `cron add` validates the schedule and the tool
/// name against the schema while it is typed, and a whitespace grammar for that is how somebody ends
/// up with a job that was almost right.
pub fn composer(
    place: Option<&eclipse_core::config::Where>,
    root: &Path,
    arg: &str,
    style: &Style,
) -> Result<String> {
    let words: Vec<&str> = arg.split_whitespace().collect();
    match words.as_slice() {
        [] => {
            let mut out = table(root, style)?;
            if let Some(note) = scheduler_note(&scheduler(root), style) {
                out.push('\n');
                out.push('\n');
                out.push_str(&note);
            }
            Ok(out)
        }
        ["run", name, ..] => run_now(place, root, name, style),
        ["logs", name] => log_text(root, name, DEFAULT_LOGS, style),
        ["logs", name, count, ..] => {
            let limit = count.parse::<usize>().map_err(|_| {
                anyhow::anyhow!("`{count}` is not a number of lines; `eclipse cron logs {name} -n {count}`")
            })?;
            log_text(root, name, limit, style)
        }
        ["add", ..] => bail!(
            "a job is a file with a schedule and a tool policy: `eclipse cron add --name ... --schedule ... --prompt ...`"
        ),
        ["remove", ..] | ["rm", ..] => {
            bail!("`eclipse cron remove <name>` — removing is a file change, and the CLI is where a file changes")
        }
        [other, ..] => bail!(
            "`/cron` shows the table, `/cron run <name>` and `/cron logs <name> [n]`; `{other}` is not one of those"
        ),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use eclipse_core::cron::Schedule;

    fn job(workdir: Option<&str>) -> Job {
        Job {
            name: "brief".into(),
            schedule: Schedule::parse("every 1h").unwrap(),
            prompt: "summarise".into(),
            enabled: true,
            route: None,
            workdir: workdir.map(|s| s.to_string()),
            skills: Vec::new(),
            deliver: None,
            schema: None,
        }
    }

    /// The flag was stored and never read, so a job scoped to a directory wrote into the default
    /// workspace while the flag read as working.
    #[test]
    fn a_job_runs_in_the_workspace_it_was_given() {
        let cfg = Config::default();
        let scoped = job_config(&cfg, &job(Some("/srv/notes"))).unwrap();
        assert_eq!(
            scoped.tools.workspace_root,
            Some(std::path::PathBuf::from("/srv/notes"))
        );
    }

    /// No directory named, no change: the job keeps whatever the config already said.
    #[test]
    fn a_job_without_a_directory_keeps_the_configured_workspace() {
        let mut cfg = Config::default();
        cfg.tools.workspace_root = Some(std::path::PathBuf::from("/work"));
        let plain = job_config(&cfg, &job(None)).unwrap();
        assert_eq!(
            plain.tools.workspace_root,
            Some(std::path::PathBuf::from("/work"))
        );
    }

    /// `#230`: the composer's table is the command's table, not a second rendering of the same
    /// facts. The two surfaces are compared as bytes here; the end-to-end test in `tests/cli.rs`
    /// does the same through the built binary.
    #[test]
    fn the_composer_shows_the_table_the_command_prints() {
        let home = tempfile::tempdir().unwrap();
        let root = home.path();
        cron::append_job(root, &job(None)).unwrap();
        let style = Style::plain();

        let tabled = table(root, &style).unwrap();
        let composed = composer(None, root, "", &style).unwrap();
        assert!(
            composed.starts_with(&tabled),
            "the same table, then whatever the scheduler has to say:\n{tabled}\n---\n{composed}"
        );
        // Whatever follows is the scheduler line, or nothing at all — never a second table.
        let rest = composed.strip_prefix(&tabled).unwrap().trim();
        assert!(
            rest.is_empty() || rest.starts_with("scheduler:"),
            "only the scheduler line may follow: {rest:?}"
        );
    }

    /// The three states of "is anything firing this", said by a pure function so the answer does not
    /// depend on what this machine happens to have installed.
    #[test]
    fn the_scheduler_line_names_the_thing_that_is_missing() {
        let style = Style::plain();
        let timer = std::path::PathBuf::from("/home/x/.config/systemd/user/eclipse-cron.timer");

        let none = scheduler_note(
            &Scheduler {
                timer: None,
                enabled: false,
                last_tick_ms: None,
            },
            &style,
        )
        .unwrap();
        assert!(none.contains("nothing is installed"), "{none}");
        assert!(
            none.contains("eclipse cron install-timer"),
            "it says how to fix it: {none}"
        );

        let off = scheduler_note(
            &Scheduler {
                timer: Some(timer.clone()),
                enabled: false,
                last_tick_ms: None,
            },
            &style,
        )
        .unwrap();
        assert!(off.contains("installed but not enabled"), "{off}");

        let on = scheduler_note(
            &Scheduler {
                timer: Some(timer),
                enabled: true,
                last_tick_ms: Some(now_ms() as i64 - 90_000),
            },
            &style,
        )
        .unwrap();
        assert!(on.contains("is enabled"), "{on}");
        assert!(on.contains("last tick"), "{on}");

        // Enabled, and no tick recorded yet: nothing to claim, so nothing is said.
        assert_eq!(
            scheduler_note(
                &Scheduler {
                    timer: Some(std::path::PathBuf::from("/u/eclipse-cron.timer")),
                    enabled: true,
                    last_tick_ms: None,
                },
                &style,
            ),
            None
        );
    }

    /// A name that does not exist refuses with the names that do, because "no job named `breg`" is a
    /// dead end when the answer is one typo away.
    #[test]
    fn an_unknown_job_name_lists_the_ones_that_exist() {
        let home = tempfile::tempdir().unwrap();
        let root = home.path();
        cron::append_job(root, &job(None)).unwrap();
        let style = Style::plain();
        for asked in ["logs breg", "run breg"] {
            let refused = composer(None, root, asked, &style).unwrap_err().to_string();
            assert!(refused.contains("breg"), "{refused}");
            assert!(
                refused.contains("`brief`"),
                "the names that exist: {refused}"
            );
        }
    }

    /// Writing a job stays in the CLI, and the refusal says which command — a composer that silently
    /// accepted a half-valid schedule would be the worst of both shapes.
    #[test]
    fn adding_and_removing_refuse_and_name_the_cli() {
        let home = tempfile::tempdir().unwrap();
        let root = home.path();
        let style = Style::plain();
        let added = composer(None, root, "add --name x", &style)
            .unwrap_err()
            .to_string();
        assert!(added.contains("eclipse cron add"), "{added}");
        let removed = composer(None, root, "remove brief", &style)
            .unwrap_err()
            .to_string();
        assert!(removed.contains("eclipse cron remove"), "{removed}");
        // And a word that is not a verb at all says what the verb does take.
        let other = composer(None, root, "watch", &style)
            .unwrap_err()
            .to_string();
        assert!(other.contains("/cron run <name>"), "{other}");
    }

    /// `[n]` is honoured and the bare form uses the same default the CLI flag does — the constant is
    /// the flag's `default_value_t`, so the two cannot drift.
    #[test]
    fn logs_defaults_to_the_flag_default_and_honours_a_count() {
        let home = tempfile::tempdir().unwrap();
        let root = home.path();
        cron::append_job(root, &job(None)).unwrap();
        let style = Style::plain();
        for minute in 0..7 {
            cron::write_run(
                root,
                "brief",
                1_700_000_000_000 + minute * 60_000,
                &format!("# brief — run {minute}\n\n---\n\nanswer {minute}\n"),
            )
            .unwrap();
        }
        let bare = log_text(root, "brief", DEFAULT_LOGS, &style).unwrap();
        assert_eq!(bare.matches("answer ").count(), DEFAULT_LOGS, "{bare}");
        let two = log_text(root, "brief", 2, &style).unwrap();
        assert_eq!(two.matches("answer ").count(), 2, "{two}");
        // The composer's own parsing reaches the same function.
        let through = composer(None, root, "logs brief 2", &style).unwrap();
        assert_eq!(through, two);
        let unparsable = composer(None, root, "logs brief nine", &style)
            .unwrap_err()
            .to_string();
        assert!(unparsable.contains("-n nine"), "{unparsable}");
    }

    /// `#600`: `install_timer` writes `WantedBy=timers.target`, so systemd puts the enable symlink in
    /// `timers.target.wants/` — and `scheduler()` read `default.target.wants/`, so every healthy
    /// install was reported dead and told to run the command it had already run. Reproduced through
    /// the REPL: a fake `$HOME` with a correct `timers.target.wants` symlink printed "installed but
    /// not enabled, so nothing fires after a reboot".
    #[test]
    fn a_timer_enabled_under_timers_target_reads_as_enabled() {
        let home = tempfile::tempdir().unwrap();
        let units = home.path().join(".config").join("systemd").join("user");
        std::fs::create_dir_all(units.join("timers.target.wants")).unwrap();
        std::fs::write(units.join(TIMER_NAME), "[Timer]\n").unwrap();
        std::fs::write(
            units.join("timers.target.wants").join(TIMER_NAME),
            "[Install]\n",
        )
        .unwrap();

        let env = |key: &str| (key == "HOME").then(|| home.path().to_string_lossy().into_owned());
        let sched = scheduler_with(home.path(), &env);
        assert!(
            sched.enabled,
            "a timer systemd will start read as disabled, so the table warns forever"
        );
    }

    /// A timer installed by an older build declares `WantedBy=default.target`, and that symlink is
    /// one systemd follows too — so it counts, and this fix does not trade one false warning for
    /// another.
    #[test]
    fn a_timer_enabled_under_default_target_also_reads_as_enabled() {
        let home = tempfile::tempdir().unwrap();
        let units = home.path().join(".config").join("systemd").join("user");
        std::fs::create_dir_all(units.join("default.target.wants")).unwrap();
        std::fs::write(units.join(TIMER_NAME), "[Timer]\n").unwrap();
        std::fs::write(
            units.join("default.target.wants").join(TIMER_NAME),
            "[Install]\n",
        )
        .unwrap();

        let env = |key: &str| (key == "HOME").then(|| home.path().to_string_lossy().into_owned());
        assert!(scheduler_with(home.path(), &env).enabled);
    }

    /// And the warning has to keep firing when it is true: a unit with no enable symlink anywhere.
    #[test]
    fn a_timer_with_no_enable_symlink_reads_as_disabled() {
        let home = tempfile::tempdir().unwrap();
        let units = home.path().join(".config").join("systemd").join("user");
        std::fs::create_dir_all(&units).unwrap();
        std::fs::write(units.join(TIMER_NAME), "[Timer]\n").unwrap();

        let env = |key: &str| (key == "HOME").then(|| home.path().to_string_lossy().into_owned());
        assert!(!scheduler_with(home.path(), &env).enabled);
    }

    /// `~/notes` is what a person types, and `add` accepts it — so `run` has to expand it too, or
    /// the flag means one thing when it is checked and another when the job runs.
    #[test]
    fn a_tilde_is_expanded_the_same_way_at_add_and_at_run() {
        let mut cfg = Config::default();
        cfg.tools.workspace_root = None;
        let scoped = job_config(&cfg, &job(Some("~/notes"))).unwrap();
        assert_eq!(
            scoped.tools.workspace_root,
            Some(expand_path("~/notes")),
            "one expansion, both ends"
        );
    }
}