tsk-bin 0.31.1

tsk — work with a clear context
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
pub mod binding;
pub mod clock;
pub mod entry;
pub mod ops;
pub mod session;
pub mod session_start;

use std::io::Read;

use clap::Subcommand;
use serde::Serialize;

use binding::{
    is_skipped, open_mission_lines, resolve, resolve_local, unbound_prompt, write_skip,
    UNBOUND_PROMPT,
};
use ops::StartOutcome;
use session::Session;

#[derive(Subcommand)]
pub enum ThreadCommands {
    #[command(
        about = "Mint a thread, bind this session or worktree to it, and push; prints started:<thread-id>, or resume-required:<thread-id> with exit status 2 when a binding exists. With a mission ID the thread works that mission, which must have a record, or a briefing document at missions/<category>/<ID>-<slug>.md; an unknown ID is refused. With no mission ID the thread has no mission and no tasks; tsk thread set mission attaches one later. Clears tsk thread skip"
    )]
    Start {
        #[arg(
            help = "Mission ID, for example M-TSK-SCHEMA; omit it to start a thread with no mission"
        )]
        mission_id: Option<String>,
        #[arg(
            hide = true,
            help = "No longer needed. Accepted and ignored, so older plugin skills keep working"
        )]
        briefing_path: Option<String>,
    },
    #[command(
        about = "Append a continuation state entry to a thread and push; prints paused:<thread-id>, then three lines that verify the hand-off: code: clean or code: dirty (N files), code pushed: yes or no, and ledger: pushed or ledger: N changes not pushed. With --bound the thread is the one this session or worktree is bound to: tsk thread pause --bound <task-id> <whats-next>. The mission comes from the thread. When the mission has a record, a task ID must name one of its tasks. A thread with no mission has no tasks: its task ID must be empty"
    )]
    Pause {
        #[arg(
            long,
            help = "Pause the thread this session or worktree is bound to, read from the ledger store with no network call. Then pass two arguments only: <task-id> <whats-next>"
        )]
        bound: bool,
        #[arg(help = "Thread ID (with --bound: the task ID)")]
        thread_id: String,
        #[arg(
            help = "Task in progress, for example T-05 or T-5; can be empty (with --bound: what's next)",
            allow_hyphen_values = true
        )]
        task_id: String,
        #[arg(
            help = "A short account of where things stand",
            allow_hyphen_values = true,
            required_unless_present = "bound"
        )]
        whats_next: Option<String>,
        #[arg(
            hide = true,
            allow_hyphen_values = true,
            help = "The old form is pause <thread-id> <mission-link> <task-id> <whats-next>. The mission link is ignored"
        )]
        legacy_whats_next: Option<String>,
    },
    #[command(
        about = "Bind this session or worktree to a thread, replacing its earlier binding, and print its latest continuation state entry as JSON with a warning when another actor wrote to it. The binding is a local write: it prints a note on stderr and goes out with the next push (thread start, pause or stop, or tsk ledger push)"
    )]
    Resume {
        #[arg(help = "Thread ID")]
        thread_id: String,
    },
    #[command(about = "Change a field of a thread; the one field today is the mission")]
    Set {
        #[command(subcommand)]
        field: SetCommands,
    },
    #[command(
        about = "Remove this session's or worktree's binding without deleting the thread; prints detached:<thread-id>. Every binding is a row in the ledger. The change is a local write: it prints a note on stderr and goes out with the next push (thread start, pause or stop, or tsk ledger push)"
    )]
    Detach,
    #[command(
        about = "Record that this session or worktree works without a thread, so the Stop hook check stops asking for one; prints skipped. The record is local to this clone and is never pushed. tsk thread start and tsk thread resume clear it"
    )]
    Skip,
    #[command(
        about = "Delete a thread, its continuation state and every binding to it, cloud or worktree, and push; prints stopped:<thread-id>"
    )]
    Stop {
        #[arg(help = "Thread ID; defaults to the thread this session or worktree is bound to")]
        thread_id: Option<String>,
    },
    #[command(
        about = "List every thread on the ledger as one JSON object per line, most recently paused first. Each row has actors: the sessions and worktrees bound to the thread, as {\"actor\", \"kind\"} objects, empty when none is"
    )]
    List,
    #[command(
        name = "prune-bindings",
        about = "Remove the bindings of cloud sessions that have ended: cloud rows registered more than --older-than days ago (30 by default), except this session's own. A worktree binding is never removed. Prints removed <actor> <thread-id> per row, then a count. The change is local: tsk ledger push publishes it. With --dry-run it prints would remove ... and changes nothing"
    )]
    PruneBindings {
        #[arg(
            long,
            value_name = "DAYS",
            default_value_t = ops::DEFAULT_PRUNE_DAYS,
            help = "Remove cloud bindings registered more than this many days ago"
        )]
        older_than: u64,
        #[arg(long, help = "Print what would be removed and change nothing")]
        dry_run: bool,
    },
    #[command(
        about = "Print this session's or worktree's binding as cloud:<thread-id> or worktree:<thread-id>, then actor: <name> (<kind>) on a second line when this session or worktree is registered as an actor (tsk actor register); exit status 1 and no output with no binding. A worktree that still has a tsk-thread-id marker file gets a binding row from it, and the file is removed (not with --no-fetch)"
    )]
    Binding {
        #[arg(long, help = "Read the existing ledger worktree without fetching")]
        no_fetch: bool,
    },
    #[command(
        about = "Print the session title for this session or worktree: <mission ID>: <actor name> when it is registered as an actor and bound to a thread with a mission, the actor name alone when the thread has no mission or there is no binding, and the mission ID alone when no actor is registered. Exit status 1 and no output with neither. Reads the ledger store as it is and never fetches, so it shows a local write such as tsk thread set mission at once. The skills pass the title to set_session_title in a cloud session"
    )]
    Title,
    #[command(
        about = "Stop hook check: when this session or worktree is unbound, has not skipped a thread and the ledger holds missions, print a block decision as JSON that asks for a thread. Otherwise, when the ledger store holds changes that are not pushed (no network), start a background publish (tsk ledger push --background; TSK_BACKGROUND_PUBLISH=off switches it off) and print nothing. Exit 0 whatever happens. Reads stdin; never fetches"
    )]
    Guard,
    #[command(
        about = "SessionStart hook: reads the session ID and source from stdin, exits with no output when another run already claimed that event, fetches the ledger, exports TSK_LEDGER_WT to CLAUDE_ENV_FILE when set, and prints the hook JSON with the session context in the --format shape (claude by default, or copilot); accepts session_id or sessionId on stdin; exits 0 even when the fetch fails"
    )]
    SessionStart {
        #[arg(
            long,
            value_enum,
            default_value = "claude",
            help = "Hook output format: claude (hookSpecificOutput JSON) or copilot (additionalContext JSON)"
        )]
        format: session_start::HookFormat,
        #[arg(
            long,
            value_enum,
            value_name = "TARGET",
            help = "In a Claude Code cloud session (CLAUDE_CODE_REMOTE=true), install the tsk plugin first, as tsk install-plugin does; only claude-cli is accepted. Step lines go to stderr. A failure adds a warning to the context"
        )]
        install_plugin: Option<crate::install_plugin::Target>,
        #[arg(
            long,
            value_name = "SEMVER",
            help = "The version of the tsk plugin loaded in this session. When it is lower than the plugin version this tsk expects, the context asks for a plugin update; an absent or unparseable value adds nothing"
        )]
        plugin_version: Option<String>,
    },
}

#[derive(Subcommand)]
pub enum SetCommands {
    #[command(
        about = "Attach a mission to a thread, or change or remove its mission; prints mission-set:<thread-id>:<mission-id>, or mission-cleared:<thread-id> with --none. The mission must have a record, or a briefing document at missions/<category>/<ID>-<slug>.md; an unknown ID is refused. Earlier continuation entries keep the mission they were written with. The change is a local write: it prints a note on stderr and goes out with the next push (thread start, pause or stop, or tsk ledger push)"
    )]
    Mission {
        #[arg(
            help = "Mission ID, for example M-TSK-SCHEMA; with --none, the thread ID instead",
            required_unless_present = "none"
        )]
        mission_id: Option<String>,
        #[arg(help = "Thread ID; defaults to the thread this session or worktree is bound to")]
        thread_id: Option<String>,
        #[arg(
            long,
            help = "Remove the thread's mission instead of setting one; takes the thread ID alone"
        )]
        none: bool,
    },
}

#[derive(Serialize)]
struct BlockDecision<'a> {
    decision: &'a str,
    reason: &'a str,
}

pub fn block_decision(reason: &str) -> String {
    serde_json::to_string(&BlockDecision {
        decision: "block",
        reason,
    })
    .unwrap_or_default()
}

/// The Stop hook check. Prints a block decision when this session or worktree is unbound,
/// has not skipped a thread and the ledger holds missions. Otherwise, when the ledger
/// store holds changes that are not pushed, it starts a background publish and prints
/// nothing (ADR 0020). It reads the local store and never fetches. It never fails.
fn guard() -> Option<String> {
    let Ok(session) = Session::discover() else {
        return Some(UNBOUND_PROMPT.to_string());
    };
    if let Some(reason) = unbound_reason(&session) {
        return Some(reason);
    }
    if crate::ledger::background::enabled() {
        // A failure to start is not the hook's failure: SessionEnd and the next turn
        // publish too.
        let _ = crate::ledger::background::start(
            session.store.as_ref(),
            crate::ledger::background::DEFAULT_MESSAGE,
        );
    }
    None
}

/// The reason to block because nothing binds this session or worktree to a thread.
fn unbound_reason(session: &Session) -> Option<String> {
    if is_skipped(session) {
        return None;
    }
    let local = session.store.exists_locally().unwrap_or(false);
    if !local {
        return Some(UNBOUND_PROMPT.to_string());
    }
    if resolve_local(session).ok().flatten().is_some() {
        return None;
    }
    match (
        session.store.missions_load(),
        session.store.doc_list("missions/"),
    ) {
        (Ok(missions), Ok(documents)) if missions.is_empty() && documents.is_empty() => None,
        (Ok(missions), _) => Some(unbound_prompt(&open_mission_lines(&missions))),
        _ => Some(UNBOUND_PROMPT.to_string()),
    }
}

pub fn run(action: ThreadCommands) -> Result<i32, String> {
    if let ThreadCommands::Guard = action {
        let mut input = String::new();
        let _ = std::io::stdin().read_to_string(&mut input);
        if let Some(reason) = guard() {
            println!("{}", block_decision(&reason));
        }
        return Ok(0);
    }

    if let ThreadCommands::SessionStart {
        format,
        install_plugin,
        plugin_version,
    } = action
    {
        if install_plugin == Some(crate::install_plugin::Target::CopilotCli) {
            return Err(
                "error: --install-plugin accepts only claude-cli: GitHub Copilot CLI reads plugin hooks itself"
                    .to_string(),
            );
        }
        return Ok(session_start::run(
            format,
            install_plugin.is_some(),
            plugin_version.as_deref(),
        ));
    }

    let session = Session::discover()?;
    match action {
        ThreadCommands::Start {
            mission_id,
            briefing_path,
        } => {
            if briefing_path.is_some() {
                eprintln!(
                    "note: the briefing path argument of tsk thread start is no longer needed and is ignored"
                );
            }
            match ops::start(&session, mission_id.as_deref())? {
                StartOutcome::Started(id) => {
                    println!("started:{}", id);
                    Ok(0)
                }
                StartOutcome::ResumeRequired(id) => {
                    println!("resume-required:{}", id);
                    Ok(2)
                }
            }
        }
        ThreadCommands::Pause {
            bound,
            thread_id,
            task_id,
            whats_next,
            legacy_whats_next,
        } => {
            let (thread_id, task_id, whats_next) = if bound {
                // With --bound the first two positionals are the task and what's next.
                if whats_next.is_some() || legacy_whats_next.is_some() {
                    return Err(
                        "error: --bound takes two arguments: tsk thread pause --bound <task-id> <whats-next>"
                            .to_string(),
                    );
                }
                let binding = resolve_local(&session)?.ok_or_else(|| {
                    "error: this session or worktree is bound to no thread, so --bound has none to pause. Pass the thread ID: tsk thread pause <thread-id> <task-id> <whats-next>"
                        .to_string()
                })?;
                (binding.thread_id().to_string(), thread_id, task_id)
            } else {
                let whats_next = whats_next.unwrap_or_default();
                // The old form puts a mission link before the task. It is ignored.
                match legacy_whats_next {
                    Some(last) => {
                        eprintln!(
                            "note: the mission link argument of tsk thread pause is no longer needed and is ignored"
                        );
                        (thread_id, whats_next, last)
                    }
                    None => (thread_id, task_id, whats_next),
                }
            };
            ops::pause(&session, &thread_id, &task_id, &whats_next)?;
            println!("paused:{}", thread_id);
            for line in ops::pause_report(&session) {
                println!("{}", line);
            }
            Ok(0)
        }
        ThreadCommands::Set {
            field:
                SetCommands::Mission {
                    mission_id,
                    thread_id,
                    none,
                },
        } => {
            // With --none the only positional is the thread ID.
            let (mission_id, thread_id) = if none {
                if thread_id.is_some() {
                    return Err(
                        "error: --none takes no mission ID: tsk thread set mission --none [<thread-id>]"
                            .to_string(),
                    );
                }
                (None, mission_id)
            } else {
                (mission_id, thread_id)
            };
            let done = ops::set_mission(&session, mission_id.as_deref(), thread_id.as_deref())?;
            match done.mission_id {
                Some(mission_id) => println!("mission-set:{}:{}", done.thread_id, mission_id),
                None => println!("mission-cleared:{}", done.thread_id),
            }
            Ok(0)
        }
        ThreadCommands::Skip => {
            write_skip(&session)?;
            println!("skipped");
            Ok(0)
        }
        ThreadCommands::Resume { thread_id } => {
            let outcome = ops::resume(&session, &thread_id)?;
            println!("{}", ops::render_resume(&outcome));
            Ok(0)
        }
        ThreadCommands::Detach => {
            let id = ops::detach(&session)?;
            println!("detached:{}", id);
            Ok(0)
        }
        ThreadCommands::Stop { thread_id } => {
            let id = ops::stop(&session, thread_id.as_deref())?;
            println!("stopped:{}", id);
            Ok(0)
        }
        ThreadCommands::List => {
            for row in ops::list(&session)? {
                println!(
                    "{}",
                    serde_json::to_string(&row)
                        .map_err(|e| format!("error: could not render a thread: {}", e))?
                );
            }
            Ok(0)
        }
        ThreadCommands::PruneBindings {
            older_than,
            dry_run,
        } => {
            let rows = ops::prune_bindings(&session, older_than, dry_run)?;
            for line in ops::render_prune(&rows, dry_run) {
                println!("{}", line);
            }
            Ok(0)
        }
        ThreadCommands::Binding { no_fetch } => {
            let binding = if no_fetch {
                resolve_local(&session)?
            } else {
                session.refresh()?;
                resolve(&session)?
            };
            match binding {
                Some(binding) => {
                    println!("{}", binding);
                    // The actor, on a line of its own, so the first line stays the
                    // binding alone.
                    if let Some(actor) = crate::actor::current(&session)? {
                        println!("actor: {}", actor.label());
                    }
                    Ok(0)
                }
                None => Ok(1),
            }
        }
        ThreadCommands::Title => {
            let actor = crate::actor::current(&session)?.map(|actor| actor.name);
            let mission = match resolve_local(&session)? {
                Some(binding) => session
                    .store
                    .thread_info(binding.thread_id())
                    .ok()
                    .and_then(|info| ops::thread_mission(&info)),
                None => None,
            };
            match ops::session_title(actor.as_deref(), mission.as_deref()) {
                Some(title) => {
                    println!("{}", title);
                    Ok(0)
                }
                None => Ok(1),
            }
        }
        ThreadCommands::Guard | ThreadCommands::SessionStart { .. } => Ok(0),
    }
}

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

    #[test]
    fn block_decision_is_compact_json_with_the_unbound_prompt() {
        let text = block_decision(UNBOUND_PROMPT);
        assert!(
            text.starts_with("{\"decision\":\"block\",\"reason\":\"No thread binding was found")
        );
        let value: serde_json::Value = serde_json::from_str(&text).unwrap();
        assert_eq!(value["reason"], UNBOUND_PROMPT);
    }
}