clt-rs 0.6.19

File-backed task manager with a TUI Kanban board and multi-project Codex agent registry
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
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
use anyhow::{Context, Result};
use clap::{Parser, Subcommand, ValueEnum};
use std::{
    ffi::OsString,
    fs,
    path::{Path, PathBuf},
};

#[cfg(unix)]
use crate::runner::{AutomatedSupervisorSpec, run_automated_session_supervisor};
use crate::{
    agent::{AgentGitMode, ensure_agent_state_dir, open_agent_store, open_agent_store_at},
    application::{
        AgentTaskSelection, ManagedTaskWorkflow, TaskDoneOutcome, clean_agent_state, expand_tasks,
        get_task_root, list_agent_projects, list_tasks, reconcile_agent_project,
        recover_agent_state, register_agent_project, retry_agent_project,
        set_agent_project_enabled, set_agent_project_git_mode, show_agent_logs, show_agent_status,
        unregister_agent_project,
    },
    platform::{AgentServiceAction, manage_agent_service},
    runner::run_automated_exec_gate,
    scheduler::{print_agent_scheduler_pass, run_agent_daemon, run_agent_once},
    session_control::{
        InteractiveCodexResumeMode, run_agent_interactive_session_worker,
        run_agent_session_resume_worker, run_interactive_exec_gate,
    },
    session_recovery::run_orphaned_session_supervisor,
    task::{TaskStatus, add_task, ensure_existing_board, init_tasks, parse_add_task_args},
    tui::{prompt_to_initialize_tasks, tui_view, tui_view_without_active_board},
    worker::run_independent_agent_worker,
};

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum ShellKind {
    Bash,
    Zsh,
}

#[derive(Parser)]
#[command(name = "clt", version)]
#[command(about = "A simple file-system-backed task management system", long_about = None)]
struct Cli {
    /// Force use of current directory instead of git root
    #[arg(long, default_value_t = false)]
    local: bool,

    /// Write the TUI's final project directory for a shell wrapper
    #[arg(long, global = true, hide = true)]
    cwd_file: Option<PathBuf>,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Initializes the tasks directory and status stores
    Init {
        /// Create backlog/todo/doing/done folders instead of markdown files
        #[arg(long, default_value_t = false)]
        folders: bool,
    },
    /// Expands markdown status files into folder-backed task files
    Expand {
        /// Optional status to expand (backlog, todo, doing, done). Expands all if omitted.
        status: Option<String>,
    },
    /// Adds a new task to the todo list
    Add {
        /// The description of the task, optionally followed by tag-like metadata
        #[arg(required = true, num_args = 1.., trailing_var_arg = true)]
        task: Vec<String>,
    },
    /// Queues independent follow-up work in Todo without starting another session
    FollowUp {
        /// Parent status (doing)
        status: String,
        /// Parent task index
        task_index: String,
        /// Work remaining independently of the parent's completed implementation
        description: String,
        /// Failure evidence, baseline comparison, and remaining work
        #[arg(long, required_unless_present = "blocked")]
        evidence: Option<String>,
        /// Use only when an unavailable dependency or input prevents starting the follow-up
        #[arg(long)]
        blocked: Option<String>,
    },
    /// Changes the status of a task
    Status {
        /// The source status (e.g., "todo")
        from: String,
        /// The index of the task to move
        task_index: String,
        /// The destination status (e.g., "doing")
        to: String,
    },
    /// Marks a task as done
    Done {
        /// The status the task is currently in (backlog, todo, doing)
        status: String,
        /// The index of the task to mark as done
        task_index: String,
    },
    /// Deletes a task
    Delete {
        /// The status the task is currently in (backlog, todo, doing, done)
        status: String,
        /// The index of the task to delete
        task_index: String,
    },
    /// Lists tasks. Optional status to filter by (backlog, todo, doing, done)
    List { status: Option<String> },
    /// Prints shell integration that changes directory after leaving the TUI
    ShellInit {
        /// Shell to generate integration for
        #[arg(value_enum)]
        shell: ShellKind,
    },
    /// Manages Codex automation across registered projects
    Agent {
        #[command(subcommand)]
        command: AgentCommands,
    },
}

#[derive(Subcommand)]
enum AgentCommands {
    /// Registers a project for agent runs
    Register {
        /// Project path to register. Defaults to the current directory.
        path: Option<PathBuf>,
    },
    /// Unregisters a project from agent runs
    Unregister {
        /// Project path to unregister. Defaults to the current directory.
        path: Option<PathBuf>,
    },
    /// Pauses agent runs for a registered project
    Pause {
        /// Project path to pause. Defaults to the current directory.
        path: Option<PathBuf>,
    },
    /// Resumes agent runs for a paused registered project
    Resume {
        /// Project path to resume. Defaults to the current directory.
        path: Option<PathBuf>,
    },
    /// Clears a registered project's failure cooldown for an immediate retry
    Retry {
        /// Project path to retry. Defaults to the current directory.
        path: Option<PathBuf>,
    },
    /// Retires unused Git journals with no linked task or commit proof
    Reconcile {
        /// Project path to reconcile. Defaults to the current directory.
        path: Option<PathBuf>,
    },
    /// Configures the git-commit skill for a registered project
    GitCommit {
        #[command(subcommand)]
        command: AgentGitCommitCommands,
    },
    /// Lists registered projects
    Projects,
    /// Runs the scheduler
    Run {
        /// Run one scheduler pass and exit
        #[arg(long, default_value_t = false)]
        once: bool,
    },
    /// Internal independent owner for one scheduled Codex run
    #[command(hide = true)]
    Worker {
        #[arg(long)]
        state_dir: PathBuf,
        #[arg(long)]
        project_id: i64,
        #[arg(long)]
        worker_token: String,
        #[arg(long)]
        task_selection: String,
        #[arg(long)]
        resume_session_id: Option<String>,
    },
    /// Internal exact-session worker used after an interactive handoff
    #[command(hide = true)]
    ResumeSessionWorker {
        #[arg(long)]
        project_id: i64,
        #[arg(long)]
        session_id: String,
    },
    /// Internal replacement supervisor for an already-running orphaned session
    #[command(hide = true)]
    SuperviseSession {
        #[arg(long)]
        state_dir: PathBuf,
        #[arg(long)]
        project_id: i64,
        #[arg(long)]
        session_id: String,
        #[arg(long)]
        child_pid: u32,
        #[arg(long)]
        run_token: String,
    },
    /// Internal terminal guardian used while Codex is interactive
    #[command(hide = true)]
    InteractiveSessionWorker {
        #[arg(long)]
        project_id: i64,
        #[arg(long)]
        session_id: String,
        #[arg(long)]
        from_holder: String,
        #[arg(long, default_value_t = false)]
        resume_exec: bool,
        #[arg(long, alias = "read-only", default_value_t = false)]
        shared_project: bool,
        #[arg(long)]
        control_fd: Option<i32>,
    },
    /// Internal launch gate used to register a known Codex session before exec
    #[command(hide = true)]
    AutomatedExecGate {
        program: PathBuf,
        #[arg(num_args = 0.., trailing_var_arg = true, allow_hyphen_values = true)]
        arguments: Vec<OsString>,
    },
    /// Internal owner that keeps the live Child handle for automated Codex
    #[command(hide = true)]
    AutomatedSessionSupervisor {
        #[arg(long)]
        state_dir: PathBuf,
        #[arg(long)]
        project_id: i64,
        #[arg(long)]
        run_token: String,
        #[arg(long)]
        lease_holder: String,
        #[arg(long)]
        stdout_path: PathBuf,
        #[arg(long)]
        stderr_path: PathBuf,
        program: PathBuf,
        #[arg(num_args = 0.., trailing_var_arg = true, allow_hyphen_values = true)]
        arguments: Vec<OsString>,
    },
    /// Internal launch gate used to register interactive Codex before exec
    #[command(hide = true)]
    InteractiveExecGate {
        #[arg(long)]
        control_fd: Option<i32>,
        program: PathBuf,
        #[arg(num_args = 0.., trailing_var_arg = true, allow_hyphen_values = true)]
        arguments: Vec<OsString>,
    },
    /// Runs the foreground scheduler loop
    Daemon,
    /// Starts the background agent service
    Start,
    /// Stops the background agent service
    Stop,
    /// Recovers the agent registry after stopping services and preserving its database bundle
    Recover,
    /// Shows agent service and project status
    Status,
    /// Shows recent agent logs
    Logs,
    /// Clears stored agent failures, run history, and agent log files
    Clean,
}

#[derive(Subcommand)]
enum AgentGitCommitCommands {
    /// Adds a git-commit skill instruction to this project's agent prompt
    Enable {
        /// Project path to update. Defaults to the current directory.
        path: Option<PathBuf>,
    },
    /// Removes the git-commit skill instruction from this project's agent prompt
    Disable {
        /// Project path to update. Defaults to the current directory.
        path: Option<PathBuf>,
    },
    /// Adds git commit and push instructions to this project's agent prompt
    Push {
        /// Project path to update. Defaults to the current directory.
        path: Option<PathBuf>,
    },
}

pub(super) fn run() -> Result<()> {
    let cli = Cli::parse();
    if let Some(Commands::Agent {
        command:
            AgentCommands::SuperviseSession {
                state_dir,
                project_id,
                session_id,
                child_pid,
                run_token,
            },
    }) = cli.command.as_ref()
    {
        return run_orphaned_session_supervisor(
            state_dir,
            *project_id,
            session_id,
            *child_pid,
            run_token,
        );
    }
    if let Some(Commands::ShellInit { shell }) = cli.command.as_ref() {
        print!("{}", shell_init_script(*shell));
        return Ok(());
    }
    if let Some(Commands::Agent {
        command: AgentCommands::AutomatedExecGate { program, arguments },
    }) = cli.command.as_ref()
    {
        return run_automated_exec_gate(program, arguments);
    }
    if let Some(Commands::Agent {
        command:
            AgentCommands::Worker {
                state_dir,
                project_id,
                worker_token,
                task_selection,
                resume_session_id,
            },
    }) = cli.command.as_ref()
    {
        return run_independent_agent_worker(
            state_dir,
            *project_id,
            worker_token,
            AgentTaskSelection::from_label(task_selection)?,
            resume_session_id.as_deref(),
        );
    }
    #[cfg(unix)]
    if let Some(Commands::Agent {
        command:
            AgentCommands::AutomatedSessionSupervisor {
                state_dir,
                project_id,
                run_token,
                lease_holder,
                stdout_path,
                stderr_path,
                program,
                arguments,
            },
    }) = cli.command.as_ref()
    {
        let exit_code = run_automated_session_supervisor(
            AutomatedSupervisorSpec {
                state_dir,
                project_id: *project_id,
                run_token,
                lease_holder,
                stdout_path,
                stderr_path,
            },
            program,
            arguments,
        )?;
        std::process::exit(exit_code);
    }
    if let Some(Commands::Agent {
        command:
            AgentCommands::InteractiveExecGate {
                control_fd,
                program,
                arguments,
            },
    }) = cli.command.as_ref()
    {
        return run_interactive_exec_gate(*control_fd, program, arguments);
    }

    let root = get_task_root(cli.local)?;
    let cwd = std::env::current_dir()?;

    if root != cwd {
        println!("Using tasks at: {:?}", root);
    }

    match cli.command {
        Some(Commands::Init { folders }) => {
            init_tasks(&root, folders)?;
        }
        Some(Commands::Expand { status }) => {
            expand_tasks(&root, status)?;
        }
        Some(Commands::Add { task }) => {
            let (description, metadata) = parse_add_task_args(task)?;
            let msg = add_task(&root, &description, metadata)?;
            println!("{}", msg);
        }
        Some(Commands::FollowUp {
            status,
            task_index,
            description,
            evidence,
            blocked,
        }) => {
            let status = ManagedTaskWorkflow::new(&root).add_follow_up(
                TaskStatus::parse(&status)?,
                &task_index,
                &description,
                evidence
                    .as_deref()
                    .or(blocked.as_deref())
                    .unwrap_or_default(),
                blocked.as_deref(),
            )?;
            match status {
                TaskStatus::Todo => println!(
                    "Follow-up queued in Todo for a future run. Finish the parent task normally."
                ),
                _ => println!(
                    "Follow-up blocked by the recorded dependency or input; recorded in Doing for later recovery. Finish the parent task normally."
                ),
            }
        }
        Some(Commands::Status {
            from,
            task_index,
            to,
        }) => {
            let from_status = TaskStatus::parse(&from)?;
            let to_status = TaskStatus::parse(&to)?;
            let workflow = ManagedTaskWorkflow::new(&root);
            if to_status == TaskStatus::Done {
                if let TaskDoneOutcome::ExternalCompletion(session_id) =
                    workflow.complete_task(from_status, &task_index)?
                {
                    println!(
                        "Task {task_index} from {from} marked as externally completed; cancelled idle managed Git journal for Codex session {session_id}."
                    );
                }
            } else {
                workflow.move_task(from_status, to_status, &task_index)?;
            }
        }
        Some(Commands::Done { status, task_index }) => {
            let task_status = TaskStatus::parse(&status)?;
            let workflow = ManagedTaskWorkflow::new(&root);
            if task_status == TaskStatus::Done {
                if workflow.reseal_completed_task(&task_index)? {
                    println!(
                        "Task {} in done was resealed; Git finalization is pending.",
                        task_index
                    );
                } else {
                    println!("Task is already done.");
                }
            } else {
                match workflow.complete_task(task_status, &task_index)? {
                    TaskDoneOutcome::Normal => {
                        println!("Task {} from {} marked as done.", task_index, status);
                    }
                    TaskDoneOutcome::Provisional => {
                        println!(
                            "Task {} from {} moved provisionally; Git finalization is pending.",
                            task_index, status
                        );
                    }
                    TaskDoneOutcome::ExternalCompletion(session_id) => {
                        println!(
                            "Task {task_index} from {status} marked as externally completed; cancelled idle managed Git journal for Codex session {session_id}."
                        );
                    }
                }
            }
        }
        Some(Commands::Delete { status, task_index }) => {
            let task_status = TaskStatus::parse(&status)?;
            ManagedTaskWorkflow::new(&root).delete_task(task_status, &task_index)?;
            println!("Task {} from {} deleted successfully.", task_index, status);
        }
        Some(Commands::List { status }) => {
            list_tasks(&root, status)?;
        }
        Some(Commands::ShellInit { .. }) => unreachable!("shell init handled before root lookup"),
        Some(Commands::Agent { command }) => {
            handle_agent_command(command, cli.local, &root)?;
        }
        None => {
            if !ensure_existing_board(&root)? {
                if prompt_to_initialize_tasks()? {
                    init_tasks(&root, false)?;
                } else {
                    let final_root = tui_view_without_active_board(&root)?;
                    write_tui_cwd_file(cli.cwd_file.as_deref(), &final_root)?;
                    return Ok(());
                }
            }
            let final_root = tui_view(&root)?;
            write_tui_cwd_file(cli.cwd_file.as_deref(), &final_root)?;
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests;

fn shell_init_script(shell: ShellKind) -> &'static str {
    match shell {
        ShellKind::Bash | ShellKind::Zsh => {
            r#"clt() {
    local cwd_file cwd exit_status
    cwd_file="$(mktemp "${TMPDIR:-/tmp}/clt-cwd.XXXXXX")" || return
    command clt --cwd-file "$cwd_file" "$@"
    exit_status=$?
    if [ -s "$cwd_file" ]; then
        IFS= read -r cwd < "$cwd_file"
        if [ -n "$cwd" ] && [ "$cwd" != "$PWD" ]; then
            builtin cd -- "$cwd" || exit_status=$?
        fi
    fi
    command rm -f -- "$cwd_file"
    return "$exit_status"
}
"#
        }
    }
}

fn write_tui_cwd_file(cwd_file: Option<&Path>, active_root: &Path) -> Result<()> {
    let Some(cwd_file) = cwd_file else {
        return Ok(());
    };

    fs::write(cwd_file, active_root.as_os_str().as_encoded_bytes())
        .with_context(|| format!("Failed to write TUI exit directory to {cwd_file:?}"))
}

fn handle_agent_command(command: AgentCommands, local: bool, default_root: &Path) -> Result<()> {
    match &command {
        AgentCommands::Start => return manage_agent_service(AgentServiceAction::Start),
        AgentCommands::Stop => return manage_agent_service(AgentServiceAction::Stop),
        AgentCommands::Recover => return recover_agent_state(),
        _ => {}
    }

    match command {
        AgentCommands::Register { path } => {
            let store = open_agent_store()?;
            register_agent_project(&store, path.as_deref(), local, default_root)?;
        }
        AgentCommands::Unregister { path } => {
            let state_dir = ensure_agent_state_dir()?;
            let store = open_agent_store_at(&state_dir)?;
            unregister_agent_project(&store, &state_dir, path.as_deref(), local, default_root)?;
        }
        AgentCommands::Pause { path } => {
            let store = open_agent_store()?;
            set_agent_project_enabled(&store, path.as_deref(), local, default_root, false)?;
        }
        AgentCommands::Resume { path } => {
            let store = open_agent_store()?;
            set_agent_project_enabled(&store, path.as_deref(), local, default_root, true)?;
        }
        AgentCommands::Retry { path } => {
            let store = open_agent_store()?;
            retry_agent_project(&store, path.as_deref(), local, default_root)?;
        }
        AgentCommands::Reconcile { path } => {
            let state_dir = ensure_agent_state_dir()?;
            reconcile_agent_project(&state_dir, path.as_deref(), local, default_root)?;
        }
        AgentCommands::GitCommit { command } => {
            let store = open_agent_store()?;
            match command {
                AgentGitCommitCommands::Enable { path } => {
                    set_agent_project_git_mode(
                        &store,
                        path.as_deref(),
                        local,
                        default_root,
                        AgentGitMode::Commit,
                    )?;
                }
                AgentGitCommitCommands::Disable { path } => {
                    set_agent_project_git_mode(
                        &store,
                        path.as_deref(),
                        local,
                        default_root,
                        AgentGitMode::Off,
                    )?;
                }
                AgentGitCommitCommands::Push { path } => {
                    set_agent_project_git_mode(
                        &store,
                        path.as_deref(),
                        local,
                        default_root,
                        AgentGitMode::CommitAndPush,
                    )?;
                }
            }
        }
        AgentCommands::Projects => {
            let store = open_agent_store()?;
            list_agent_projects(&store)?;
        }
        AgentCommands::Run { once } => {
            if !once {
                anyhow::bail!("clt agent run requires --once for the foreground scheduler pass.");
            }

            let pass = run_agent_once()?;
            print_agent_scheduler_pass(&pass);
        }
        AgentCommands::ResumeSessionWorker {
            project_id,
            session_id,
        } => {
            run_agent_session_resume_worker(project_id, &session_id)?;
        }
        AgentCommands::InteractiveSessionWorker {
            project_id,
            session_id,
            from_holder,
            resume_exec,
            shared_project,
            control_fd,
        } => {
            let mode = if resume_exec {
                InteractiveCodexResumeMode::ResumeExec
            } else if shared_project {
                InteractiveCodexResumeMode::WritableShared
            } else {
                InteractiveCodexResumeMode::WritableIdle
            };
            run_agent_interactive_session_worker(
                project_id,
                &session_id,
                &from_holder,
                mode,
                control_fd,
            )?;
        }
        AgentCommands::AutomatedExecGate { .. }
        | AgentCommands::AutomatedSessionSupervisor { .. }
        | AgentCommands::SuperviseSession { .. }
        | AgentCommands::InteractiveExecGate { .. }
        | AgentCommands::Worker { .. } => {
            unreachable!("Codex exec gate handled before task-root discovery")
        }
        AgentCommands::Daemon => {
            run_agent_daemon()?;
        }
        AgentCommands::Status => {
            let store = open_agent_store()?;
            show_agent_status(&store)?;
        }
        AgentCommands::Logs => {
            let store = open_agent_store()?;
            show_agent_logs(&store)?;
        }
        AgentCommands::Clean => {
            let state_dir = ensure_agent_state_dir()?;
            let store = open_agent_store_at(&state_dir)?;
            clean_agent_state(&store, &state_dir)?;
        }
        AgentCommands::Start | AgentCommands::Stop | AgentCommands::Recover => {
            unreachable!("handled before store open")
        }
    }

    Ok(())
}