tsk-bin 0.7.0

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
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
use std::io::{Read, Write};
use std::path::Path;
use std::time::{Duration, SystemTime};

use serde::{Deserialize, Serialize};

use crate::ledger::location::state_root_from_env;
use crate::ledger::store::RefreshOutcome;
use crate::self_update::{session_notice, upgrade_for_cloud, CloudUpgrade};

use super::binding::{resolve, UNBOUND_PROMPT};
use super::session::Session;

pub const ENV_FILE_VAR: &str = "CLAUDE_ENV_FILE";
pub const LEDGER_WT_VAR: &str = "TSK_LEDGER_WT";
pub const CLAIM_DIR: &str = "session-start";
pub const CLAIM_WINDOW: Duration = Duration::from_secs(300);
pub const CLAIM_PRUNE_AGE: Duration = Duration::from_secs(24 * 60 * 60);

#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum HookFormat {
    Claude,
    Copilot,
}

#[derive(Deserialize, Default)]
pub struct HookInput {
    #[serde(alias = "sessionId")]
    pub session_id: Option<String>,
    pub source: Option<String>,
}

impl HookInput {
    pub fn parse(bytes: &[u8]) -> HookInput {
        serde_json::from_slice(bytes).unwrap_or_default()
    }

    fn claim_name(&self) -> Option<String> {
        let session_id = self.session_id.as_deref().filter(|v| is_safe_name(v))?;
        let source = self
            .source
            .as_deref()
            .filter(|v| is_safe_name(v))
            .unwrap_or("unknown");
        Some(format!("{}.{}", session_id, source))
    }
}

fn is_safe_name(value: &str) -> bool {
    !value.is_empty()
        && value
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
}

#[derive(Debug, PartialEq)]
pub enum Claim {
    First,
    Duplicate,
}

/// Two hooks can run this command for one `SessionStart` event: the plugin's and a
/// repo's own. The first to create the claim file for the session ID and source does
/// the work. Any other run inside `CLAIM_WINDOW` of that claim is a duplicate. A claim
/// older than the window belongs to an earlier event (a second compact, say) and is
/// replaced. Any I/O error counts as `First`, so a broken state directory never
/// suppresses session start.
pub fn claim(dir: &Path, input: &HookInput, now: SystemTime) -> Claim {
    let Some(name) = input.claim_name() else {
        return Claim::First;
    };
    if std::fs::create_dir_all(dir).is_err() {
        return Claim::First;
    }
    prune_claims(dir, now);
    let path = dir.join(name);
    match create_claim(&path) {
        Ok(()) => return Claim::First,
        Err(e) if e.kind() != std::io::ErrorKind::AlreadyExists => return Claim::First,
        Err(_) => {}
    }
    if !is_older_than(&path, now, CLAIM_WINDOW) {
        return Claim::Duplicate;
    }
    let _ = std::fs::remove_file(&path);
    match create_claim(&path) {
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Claim::Duplicate,
        _ => Claim::First,
    }
}

fn create_claim(path: &Path) -> std::io::Result<()> {
    std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
        .map(|_| ())
}

fn is_older_than(path: &Path, now: SystemTime, age: Duration) -> bool {
    std::fs::metadata(path)
        .and_then(|m| m.modified())
        .ok()
        .and_then(|modified| now.duration_since(modified).ok())
        .is_some_and(|elapsed| elapsed >= age)
}

fn prune_claims(dir: &Path, now: SystemTime) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if is_older_than(&path, now, CLAIM_PRUNE_AGE) {
            let _ = std::fs::remove_file(path);
        }
    }
}

#[derive(Serialize)]
struct SpecificOutput<'a> {
    #[serde(rename = "hookEventName")]
    hook_event_name: &'a str,
    #[serde(rename = "additionalContext")]
    additional_context: &'a str,
}

#[derive(Serialize)]
struct HookOutput<'a> {
    #[serde(rename = "hookSpecificOutput")]
    hook_specific_output: SpecificOutput<'a>,
}

pub fn hook_output(context: &str) -> String {
    serde_json::to_string(&HookOutput {
        hook_specific_output: SpecificOutput {
            hook_event_name: "SessionStart",
            additional_context: context,
        },
    })
    .unwrap_or_default()
}

#[derive(Serialize)]
struct CopilotOutput<'a> {
    #[serde(rename = "additionalContext")]
    additional_context: &'a str,
}

pub fn copilot_output(context: &str) -> String {
    serde_json::to_string(&CopilotOutput {
        additional_context: context,
    })
    .unwrap_or_default()
}

pub fn format_output(format: HookFormat, context: &str) -> String {
    match format {
        HookFormat::Claude => hook_output(context),
        HookFormat::Copilot => copilot_output(context),
    }
}

pub fn fetched_context(
    path: &Path,
    read_hint: &str,
    pending: &PendingNote,
    thread_message: &str,
) -> String {
    let mut context = format!(
        "The ledger was fetched and materialised at {} (also exported as ${}). {}",
        path.display(),
        LEDGER_WT_VAR,
        read_hint
    );
    if !pending.lines.is_empty() {
        context.push(' ');
        context.push_str(&pending_warning(pending));
    }
    context.push(' ');
    context.push_str(thread_message);
    context
}

pub struct PendingNote {
    pub remote_ref: String,
    /// The command that shows what the pending commits change, from the backend.
    pub inspect_hint: String,
    pub lines: Vec<String>,
}

impl PendingNote {
    pub fn from_outcome(outcome: &RefreshOutcome, inspect_hint: String) -> PendingNote {
        PendingNote {
            remote_ref: outcome.remote_label.clone(),
            inspect_hint,
            lines: outcome.pending.clone(),
        }
    }
}

fn pending_warning(pending: &PendingNote) -> String {
    format!(
        "WARNING: the ledger worktree holds a commit that is not on {}, so it was left as it is rather than reset: {}. A worker restart can end a turn between a commit and its push, which leaves exactly this state, so this may be your own work from a turn you hold no record of making. Do not assume another actor made it, and do not discard it on that basis. Read what it changes first, with: {}. Then push it with tsk ledger push, or discard it deliberately once you know what it is.",
        pending.remote_ref,
        pending.lines.join(";"),
        pending.inspect_hint
    )
}

pub fn thread_message(binding: Option<&str>) -> String {
    match binding {
        Some(binding) => {
            let thread_id = binding.split_once(':').map(|(_, id)| id).unwrap_or(binding);
            format!(
                "An existing thread binding was found: {}. Run /tsk:resume-thread {} next.",
                binding, thread_id
            )
        }
        None => UNBOUND_PROMPT.to_string(),
    }
}

pub fn failure_context(error: &str) -> String {
    format!(
        "Warning: the ledger could not be fetched automatically at session start ({}). Run `tsk ledger fetch` manually before reading index.md.",
        error.replace('\n', " ").trim()
    )
}

fn export_to_env_file(path: &Path) -> Result<(), String> {
    let Some(file) = std::env::var_os(ENV_FILE_VAR).filter(|v| !v.is_empty()) else {
        return Ok(());
    };
    let mut handle = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&file)
        .map_err(|e| format!("could not open {}: {}", Path::new(&file).display(), e))?;
    writeln!(handle, "export {}=\"{}\"", LEDGER_WT_VAR, path.display())
        .map_err(|e| format!("could not write {}: {}", Path::new(&file).display(), e))
}

fn context_after_fetch(session: &Session) -> Result<String, String> {
    let outcome = session.store.refresh()?;
    let binding = resolve(session).ok().flatten().map(|b| b.to_string());
    let mut context = fetched_context(
        &outcome.path,
        &session.store.read_index_hint(&outcome.path),
        &PendingNote::from_outcome(
            &outcome,
            session
                .store
                .pending_inspect_hint(&outcome.path, &outcome.remote_head),
        ),
        &thread_message(binding.as_deref()),
    );
    if session
        .store
        .doc_list("missions/")
        .is_ok_and(|missions| missions.is_empty())
    {
        context.push(' ');
        context.push_str(crate::guide::EMPTY_LEDGER_NOTE);
    }
    if let Err(e) = export_to_env_file(&outcome.path) {
        context.push_str(&format!(
            " WARNING: {} was not exported ({}); use the path above.",
            LEDGER_WT_VAR, e
        ));
    }
    Ok(context)
}

pub const REMOTE_VAR: &str = "CLAUDE_CODE_REMOTE";

pub fn is_remote() -> bool {
    std::env::var(REMOTE_VAR).is_ok_and(|v| v == "true")
}

pub fn install_warning(error: &str) -> String {
    format!(
        "Warning: the tsk plugin could not be installed at session start ({}). Run `tsk install-plugin claude-cli` manually.",
        error.replace('\n', " ").trim()
    )
}

pub fn upgrade_warning(error: &str) -> String {
    format!(
        "Warning: tsk could not be upgraded at session start ({}). Run `tsk self-update` manually.",
        error.replace('\n', " ").trim()
    )
}

/// Runs the plugin install for a cloud session. Step lines go to stderr. Returns the
/// warning sentence when a step fails.
fn install_plugin_warning() -> Option<String> {
    let args = crate::install_plugin::InstallPluginArgs::claude_defaults();
    match crate::install_plugin::install(&args, &mut |line| eprintln!("{}", line)) {
        Ok(()) => None,
        Err(e) => {
            eprintln!("{}", e);
            Some(install_warning(&e))
        }
    }
}

pub fn run(format: HookFormat, install_plugin: bool) -> i32 {
    let mut bytes = Vec::new();
    let _ = std::io::stdin().read_to_end(&mut bytes);
    let input = HookInput::parse(&bytes);
    if let Ok(state_root) = state_root_from_env() {
        if claim(&state_root.join(CLAIM_DIR), &input, SystemTime::now()) == Claim::Duplicate {
            return 0;
        }
    }
    let cloud_install = install_plugin && is_remote();
    let mut warnings = Vec::new();
    if cloud_install {
        // A cloud session reuses a cached setup result, so the installed tsk can be
        // old. Upgrade it before the plugin install. This run goes on with the old
        // binary already in memory, and the next command finds the new one.
        if let CloudUpgrade::Failed(e) = upgrade_for_cloud() {
            warnings.push(upgrade_warning(&e));
        }
        warnings.extend(install_plugin_warning());
    }
    let mut context = Session::discover()
        .and_then(|session| context_after_fetch(&session))
        .unwrap_or_else(|e| failure_context(&e));
    if !cloud_install {
        if let Some(notice) = session_notice() {
            context.push(' ');
            context.push_str(&notice);
        }
    }
    for warning in warnings {
        context.push(' ');
        context.push_str(&warning);
    }
    println!("{}", format_output(format, &context));
    0
}

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

    fn no_pending() -> PendingNote {
        PendingNote {
            remote_ref: "origin's refs/heads/tsk/ledger".to_string(),
            inspect_hint: "git -C '/s/ledger' log -p abc123..HEAD".to_string(),
            lines: Vec::new(),
        }
    }

    #[test]
    fn hook_output_is_one_compact_object_in_hook_order() {
        let text = hook_output("a \"b\"");
        assert_eq!(
            text,
            "{\"hookSpecificOutput\":{\"hookEventName\":\"SessionStart\",\"additionalContext\":\"a \\\"b\\\"\"}}"
        );
    }

    #[test]
    fn copilot_output_is_one_compact_object_with_only_the_context() {
        assert_eq!(
            copilot_output("a \"b\""),
            "{\"additionalContext\":\"a \\\"b\\\"\"}"
        );
        assert_eq!(
            format_output(HookFormat::Copilot, "x"),
            "{\"additionalContext\":\"x\"}"
        );
        assert_eq!(format_output(HookFormat::Claude, "x"), hook_output("x"));
    }

    #[test]
    fn hook_input_accepts_the_copilot_camel_case_session_id() {
        let parsed = HookInput::parse(
            b"{\"sessionId\":\"abc-1\",\"timestamp\":1760000000000,\"cwd\":\"/x\",\"source\":\"new\",\"initialPrompt\":null}",
        );
        assert_eq!(parsed.session_id.as_deref(), Some("abc-1"));
        assert_eq!(parsed.source.as_deref(), Some("new"));
        assert_eq!(parsed.claim_name().as_deref(), Some("abc-1.new"));
        let unsafe_id = HookInput::parse(b"{\"sessionId\":\"../x\"}");
        assert!(unsafe_id.claim_name().is_none());
    }

    #[test]
    fn fetched_context_names_the_path_and_the_next_read() {
        let path = PathBuf::from("/s/ledger");
        let context = fetched_context(
            &path,
            "Read /s/ledger/index.md next.",
            &no_pending(),
            "Next.",
        );
        assert_eq!(
            context,
            "The ledger was fetched and materialised at /s/ledger (also exported as $TSK_LEDGER_WT). Read /s/ledger/index.md next. Next."
        );
    }

    #[test]
    fn fetched_context_adds_the_pending_warning() {
        let path = PathBuf::from("/s/ledger");
        let pending = PendingNote {
            lines: vec!["1111111 first".to_string(), "2222222 second".to_string()],
            ..no_pending()
        };
        let context = fetched_context(&path, "Read /s/ledger/index.md next.", &pending, "Next.");
        assert!(context.contains(
            "WARNING: the ledger worktree holds a commit that is not on origin's refs/heads/tsk/ledger"
        ));
        assert!(context.contains("1111111 first;2222222 second"));
        assert!(context.contains("git -C '/s/ledger' log -p abc123..HEAD"));
        assert!(context.contains("push it with tsk ledger push"));
        assert!(context.ends_with(" Next."));
    }

    #[test]
    fn thread_message_names_the_binding_and_the_resume_command() {
        assert_eq!(
            thread_message(Some("worktree:1234abcd")),
            "An existing thread binding was found: worktree:1234abcd. Run /tsk:resume-thread 1234abcd next."
        );
        assert_eq!(thread_message(None), UNBOUND_PROMPT);
    }

    fn input(session_id: Option<&str>, source: Option<&str>) -> HookInput {
        HookInput {
            session_id: session_id.map(str::to_string),
            source: source.map(str::to_string),
        }
    }

    fn age(path: &Path, by: Duration) {
        std::fs::File::options()
            .write(true)
            .open(path)
            .unwrap()
            .set_modified(SystemTime::now() - by)
            .unwrap();
    }

    #[test]
    fn hook_input_parses_the_session_id_and_source_and_ignores_bad_input() {
        let parsed =
            HookInput::parse(b"{\"session_id\":\"abc\",\"source\":\"clear\",\"cwd\":\"/x\"}");
        assert_eq!(parsed.session_id.as_deref(), Some("abc"));
        assert_eq!(parsed.source.as_deref(), Some("clear"));
        assert!(HookInput::parse(b"").session_id.is_none());
        assert!(HookInput::parse(b"not json").session_id.is_none());
    }

    #[test]
    fn claim_marks_a_second_run_for_the_same_event_as_a_duplicate() {
        let dir = tempfile::tempdir().unwrap();
        let event = input(Some("s-1"), Some("startup"));
        assert_eq!(claim(dir.path(), &event, SystemTime::now()), Claim::First);
        assert_eq!(
            claim(dir.path(), &event, SystemTime::now()),
            Claim::Duplicate
        );
        assert_eq!(
            claim(
                dir.path(),
                &input(Some("s-1"), Some("compact")),
                SystemTime::now()
            ),
            Claim::First
        );
        assert_eq!(
            claim(
                dir.path(),
                &input(Some("s-2"), Some("startup")),
                SystemTime::now()
            ),
            Claim::First
        );
    }

    #[test]
    fn claim_replaces_a_claim_older_than_the_window() {
        let dir = tempfile::tempdir().unwrap();
        let event = input(Some("s-1"), Some("compact"));
        assert_eq!(claim(dir.path(), &event, SystemTime::now()), Claim::First);
        age(&dir.path().join("s-1.compact"), CLAIM_WINDOW);
        assert_eq!(claim(dir.path(), &event, SystemTime::now()), Claim::First);
        assert_eq!(
            claim(dir.path(), &event, SystemTime::now()),
            Claim::Duplicate
        );
    }

    #[test]
    fn claim_needs_a_safe_session_id() {
        let dir = tempfile::tempdir().unwrap();
        for event in [input(None, Some("startup")), input(Some("../x"), None)] {
            assert_eq!(claim(dir.path(), &event, SystemTime::now()), Claim::First);
            assert_eq!(claim(dir.path(), &event, SystemTime::now()), Claim::First);
        }
        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
    }

    #[test]
    fn claim_prunes_claims_older_than_a_day() {
        let dir = tempfile::tempdir().unwrap();
        let old = dir.path().join("old.startup");
        std::fs::write(&old, "").unwrap();
        age(&old, CLAIM_PRUNE_AGE);
        claim(
            dir.path(),
            &input(Some("new"), Some("startup")),
            SystemTime::now(),
        );
        assert!(!old.exists());
        assert!(dir.path().join("new.startup").exists());
    }

    #[test]
    fn upgrade_warning_names_the_manual_command() {
        let warning = upgrade_warning("error: curl failed\nexit 22");
        assert!(warning.contains("(error: curl failed exit 22)"));
        assert!(warning.ends_with("Run `tsk self-update` manually."));
    }

    #[test]
    fn failure_context_asks_for_a_manual_fetch() {
        let context = failure_context("error: git fetch failed\nfatal: no remote");
        assert!(context.contains("error: git fetch failed fatal: no remote"));
        assert!(context.contains("Run `tsk ledger fetch` manually"));
    }
}