rigger 0.22.0

One seat for all your projects and tasks: a local record of what is done, what is next and when it ships - read by you and your coding assistant
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
//! A thin project skill, written from a template and the record.
//!
//! A skill file is what an assistant reads before it reads anything else
//! about a project. The ones this line kept by hand grew to sixteen
//! kilobytes each: a product summary, four rituals, a table of where things
//! are, the commands to run. Seventeen of them, nearly identical, and every
//! change to the ritual was seventeen edits - or, more often, one edit and
//! sixteen skills quietly out of date.
//!
//! Most of what they held is now held better elsewhere. The state of the
//! work is the context packet. The rituals are the same for every project
//! and belong in one place. What is left for the skill to say is how to
//! ask the record - and that is a template with the project's name in it.
//!
//! So the skill is generated: one template, the fields of the record, and
//! whatever a project's hub says only about itself. rigger ships a template
//! in English; a line that writes its own puts it in the data directory and
//! every skill follows it from then on.

use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};

use crate::paths;

/// The marker that says a skill file is generated.
///
/// Placed after the front matter, because that is where the assistant stops
/// parsing metadata and starts reading. It carries no timestamp: a stamp
/// would make an unchanged skill a diff on every run.
pub const MARK: &str = "<!-- generated by rigger skill; edit the template, not this file -->";

/// The template a line writes for itself, in the data directory.
pub const TEMPLATE_FILE: &str = "skill.md";

/// Overrides where `--install` writes.
pub const SKILLS_DIR_ENV: &str = "RIGGER_SKILLS_DIR";

/// The template rigger ships.
pub const DEFAULT_TEMPLATE: &str = include_str!("skill.template.md");

/// The template for the one skill that covers the whole line.
pub const DEFAULT_LINE_TEMPLATE: &str = include_str!("skill.line.template.md");

/// The template a line writes for its own one skill.
pub const LINE_TEMPLATE_FILE: &str = "skill.line.md";

/// The longest a skill's description may be.
///
/// Every assistant that reads these files loads all of their descriptions
/// at once, to decide which skill a request belongs to, and refuses a
/// catalogue it cannot parse. Anthropic's limit is 1024 characters, and a
/// description over it is not truncated - the skill is rejected whole, so
/// the failure is "this skill does not exist" rather than "this line is
/// long". One skill for seventeen projects makes that an easy limit to
/// cross by listing them, which is why the list lives in the body.
pub const DESCRIPTION_LIMIT: usize = 1024;

/// What a description may not contain.
///
/// The catalogue is assembled into markup, and a description carrying
/// angle brackets breaks the parse of every skill around it, not only its
/// own. A path like `C:\Projects\<project>` is the natural way to write
/// the trigger this skill needs, so this is a real hazard here and not a
/// theoretical one.
pub const FORBIDDEN_IN_DESCRIPTION: [char; 2] = ['<', '>'];

/// The profile's name as a sentence names it.
///
/// A profile called `line` would otherwise read as "the line line", and
/// one called `work` as "the work line" - which is right. So the word is
/// added only when the name does not already end in it.
fn named(line: &str) -> String {
    if line.eq_ignore_ascii_case("line") || line.to_lowercase().ends_with(" line") {
        format!("the {line}")
    } else {
        format!("the {line} line")
    }
}

/// The description of the line's one skill.
///
/// One sentence about what it covers and two about how a project is named,
/// because those are the only two things a router has to get right: that
/// this skill is the one for any project of the line, and that the request
/// says which.
pub fn line_description(line: &str, projects: &[Listed]) -> String {
    let line = named(line);
    let mut out = format!(
        "Work on any project of {line}: the record says where a project stands, what the current stage is, and how the work is done there. Name the project in the request, or work in its directory - the path is recorded. Triggers on \"work on NAME\", \"continue NAME\", \"what is next for NAME\", \"wishes for NAME\", and any change under a recorded project's directory."
    );
    // The names themselves, while they fit. A router matching "continue
    // midda" has to see the word `midda` somewhere, and the body is not
    // loaded until the skill is already chosen. What does not fit is in
    // the body, which is why running out of room here is not an error.
    let names: Vec<&str> = projects.iter().map(|p| p.name.as_str()).collect();
    if !names.is_empty() {
        let tail = format!(" The projects: {}.", names.join(", "));
        if out.chars().count() + tail.chars().count() <= DESCRIPTION_LIMIT {
            out.push_str(&tail);
        }
    }
    out
}

/// Whether a description is one an assistant will accept.
///
/// Checked rather than trusted, because the failure it prevents is silent:
/// a skill whose description is refused does not announce itself, it
/// simply never matches anything, and the next session reads no skill at
/// all and nobody finds out for a month.
pub fn check_description(description: &str) -> Result<()> {
    let length = description.chars().count();
    if length > DESCRIPTION_LIMIT {
        bail!(
            "the description is {length} characters, over the {DESCRIPTION_LIMIT} an assistant accepts; a skill whose description is refused never matches anything, so the list of projects belongs in the body"
        );
    }
    if let Some(c) = description.chars().find(|c| FORBIDDEN_IN_DESCRIPTION.contains(c)) {
        bail!("the description contains `{c}`, which breaks the catalogue an assistant parses; write the path without angle brackets");
    }
    Ok(())
}

/// A project as the line's skill lists it.
pub struct Listed {
    pub name: String,
    pub path: String,
    pub about: Option<String>,
}

/// The table of projects in the body: what each one is, and where.
pub fn projects_table(projects: &[Listed]) -> String {
    if projects.is_empty() {
        return "No projects are recorded yet; `rigger project add <path>` records one.".to_string();
    }
    let mut out = String::from("| Project | What it is | Where |\n| --- | --- | --- |\n");
    for p in projects {
        let about = p.about.as_deref().unwrap_or("a project recorded in rigger");
        out.push_str(&format!("| `{}` | {} | `{}` |\n", p.name, escape_cell(about), p.path));
    }
    out.pop();
    out
}

/// A pipe in a description would end the cell it is in.
fn escape_cell(text: &str) -> String {
    text.replace('|', "\\|").replace('\n', " ")
}

/// What fills the placeholders.
pub struct Fields<'a> {
    pub name: &'a str,
    pub path: &'a str,
    pub remote: Option<&'a str>,
    /// Where the hub is, when the record knows. `{{file:...}}` reads from it.
    pub hub: Option<&'a Path>,
    /// One line about the project, from its manifest.
    pub about: Option<&'a str>,
}

/// A rendered skill, and what the template asked for that was not there.
#[derive(Debug)]
pub struct Rendered {
    pub text: String,
    /// Said rather than failed: a hub file the template includes may not
    /// exist for every project, and a skill with the section empty is
    /// still a skill.
    pub notes: Vec<String>,
}

/// Where the template is read from.
pub enum Source {
    File(PathBuf),
    BuiltIn,
}

impl std::fmt::Display for Source {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Source::File(path) => write!(f, "{}", path.display()),
            Source::BuiltIn => write!(f, "the built-in template"),
        }
    }
}

/// Where a template is looked for: the profile's directory first - a line
/// and a ticket desk do not share rituals - then the data directory.
pub fn template_paths() -> Result<Vec<PathBuf>> {
    Ok(vec![crate::profile::current_dir()?.join(TEMPLATE_FILE), paths::data_dir()?.join(TEMPLATE_FILE)])
}

/// The template named, else the profile's, else the data directory's, else
/// the built-in one.
pub fn load_template(explicit: Option<&Path>) -> Result<(String, Source)> {
    if let Some(path) = explicit {
        let text = std::fs::read_to_string(path).with_context(|| format!("cannot read {}", path.display()))?;
        return Ok((text, Source::File(path.to_path_buf())));
    }
    for path in template_paths()? {
        match std::fs::read_to_string(&path) {
            Ok(text) => return Ok((text, Source::File(path))),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
            Err(e) => return Err(e).with_context(|| format!("cannot read {}", path.display())),
        }
    }
    Ok((DEFAULT_TEMPLATE.to_string(), Source::BuiltIn))
}

/// Whether this run may write outside its own data directory.
///
/// `RIGGER_DATA_DIR` names a record somewhere other than the owner's, which
/// is what a test harness and a throwaway profile both do. A command that
/// then wrote into `~/.claude/skills` would reach out of the box it was put
/// in - and it did: a test that recorded a project rewrote the owner's real
/// skill to describe the test's fixture, because `project add` keeps an
/// installed skill current and nothing said where "installed" was.
///
/// A skill asked for by name still goes where it is asked to go; this only
/// governs what a command does of its own accord.
pub fn may_refresh_installed() -> bool {
    std::env::var_os(SKILLS_DIR_ENV).is_some() || std::env::var_os(paths::DATA_DIR_ENV).is_none()
}

/// Where skills are installed: `RIGGER_SKILLS_DIR`, else the directory the
/// default assistant reads, `~/.claude/skills`.
pub fn skills_dir() -> Result<PathBuf> {
    if let Some(dir) = std::env::var_os(SKILLS_DIR_ENV) {
        return Ok(PathBuf::from(dir));
    }
    let home = directories::BaseDirs::new().context("cannot determine the home directory")?;
    Ok(home.home_dir().join(".claude").join("skills"))
}

/// Whether a skill file was generated by rigger.
pub fn is_generated(text: &str) -> bool {
    text.lines().take(40).any(|l| l.trim() == MARK)
}

/// Fills the template.
///
/// Placeholders are `{{name}}`, `{{path}}`, `{{remote}}`, `{{hub}}`,
/// `{{about}}`, and `{{file:NAME}}` for the contents of a file in the hub.
/// A placeholder the template spells that rigger does not know is an
/// error, not an empty string: a skill with a hole in it would be read by
/// every session before anyone noticed.
pub fn render(template: &str, fields: &Fields) -> Result<Rendered> {
    let mut out = String::with_capacity(template.len());
    let mut notes = Vec::new();
    let mut rest = template;
    while let Some(start) = rest.find("{{") {
        out.push_str(&rest[..start]);
        let after = &rest[start + 2..];
        let Some(end) = after.find("}}") else {
            bail!("the template opens a placeholder with `{{{{` and never closes it");
        };
        let key = after[..end].trim();
        out.push_str(&value(key, fields, &mut notes)?);
        rest = &after[end + 2..];
    }
    out.push_str(rest);
    Ok(Rendered { text: with_mark(&out), notes })
}

/// Fills the line template.
///
/// Its placeholders are its own - `{{line}}`, `{{description}}`,
/// `{{projects}}` - and none of a project template's, because there is no
/// one project for them to mean. A template that spelt `{{name}}` here
/// would have to pick a project arbitrarily, so it is an error instead.
pub fn render_line(template: &str, line: &str, description: &str, projects: &[Listed]) -> Result<Rendered> {
    check_description(description)?;
    let table = projects_table(projects);
    let mut out = String::with_capacity(template.len());
    let mut rest = template;
    while let Some(start) = rest.find("{{") {
        out.push_str(&rest[..start]);
        let after = &rest[start + 2..];
        let Some(end) = after.find("}}") else {
            bail!("the template opens a placeholder with `{{{{` and never closes it");
        };
        let key = after[..end].trim();
        out.push_str(match key {
            "line" => line,
            "description" => description,
            "projects" => &table,
            _ => bail!("the line template names {{{{{key}}}}}, which rigger does not know; a skill for the whole line knows line, description and projects"),
        });
        rest = &after[end + 2..];
    }
    out.push_str(rest);
    Ok(Rendered {
        text: with_mark(&out),
        notes: Vec::new(),
    })
}

/// Where the line template is looked for, the same way a project's is.
pub fn line_template_paths() -> Result<Vec<PathBuf>> {
    Ok(vec![
        crate::profile::current_dir()?.join(LINE_TEMPLATE_FILE),
        paths::data_dir()?.join(LINE_TEMPLATE_FILE),
    ])
}

/// The line template named, else the profile's, else the data
/// directory's, else the built-in one.
pub fn load_line_template(explicit: Option<&Path>) -> Result<(String, Source)> {
    if let Some(path) = explicit {
        let text = std::fs::read_to_string(path).with_context(|| format!("cannot read {}", path.display()))?;
        return Ok((text, Source::File(path.to_path_buf())));
    }
    for path in line_template_paths()? {
        match std::fs::read_to_string(&path) {
            Ok(text) => return Ok((text, Source::File(path))),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
            Err(e) => return Err(e).with_context(|| format!("cannot read {}", path.display())),
        }
    }
    Ok((DEFAULT_LINE_TEMPLATE.to_string(), Source::BuiltIn))
}

fn value(key: &str, fields: &Fields, notes: &mut Vec<String>) -> Result<String> {
    Ok(match key {
        "name" => fields.name.to_string(),
        "path" => fields.path.to_string(),
        "remote" => fields.remote.map(|r| format!(" - {r}")).unwrap_or_default(),
        "hub" => fields.hub.map(|h| h.display().to_string()).unwrap_or_else(|| "not recorded yet".to_string()),
        "about" => fields.about.unwrap_or("a project recorded in rigger").to_string(),
        _ => match key.strip_prefix("file:") {
            Some(file) => included(file.trim(), fields.hub, notes),
            None => bail!("the template names {{{{{key}}}}}, which rigger does not know; it knows name, path, remote, hub, about and file:<name>"),
        },
    })
}

/// A file of the hub, for the part of a skill only that project can say.
fn included(file: &str, hub: Option<&Path>, notes: &mut Vec<String>) -> String {
    let Some(hub) = hub else {
        notes.push(format!(
            "{{{{file:{file}}}}} left empty: the record does not know where the hub is; import or export one"
        ));
        return String::new();
    };
    let path = hub.join(file);
    match std::fs::read_to_string(&path) {
        Ok(text) => text.trim().to_string(),
        Err(_) => {
            notes.push(format!("{{{{file:{file}}}}} left empty: {} does not exist", path.display()));
            String::new()
        }
    }
}

/// Puts the mark where the front matter ends, or at the top when there is
/// none. A file that already carries it is left as it is.
fn with_mark(text: &str) -> String {
    if is_generated(text) {
        return text.to_string();
    }
    if let Some(rest) = text.strip_prefix("---\n").or_else(|| text.strip_prefix("---\r\n"))
        && let Some(end) = rest.find("\n---")
    {
        // Past the closing rule and its line break, then the mark, then the
        // body as the template wrote it.
        let after_rule = &rest[end + 1..];
        let rule_len = after_rule.find('\n').map(|i| i + 1).unwrap_or(after_rule.len());
        let head_len = text.len() - rest.len() + end + 1 + rule_len;
        let (head, body) = text.split_at(head_len);
        return format!("{head}\n{MARK}\n{body}");
    }
    format!("{MARK}\n\n{text}")
}

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

    fn fields(hub: Option<&Path>) -> Fields<'_> {
        Fields {
            name: "sample",
            path: "C:\\dev\\sample",
            remote: Some("https://example.com/sample.git"),
            hub,
            about: Some("a sample"),
        }
    }

    #[test]
    fn every_field_is_filled() {
        let r = render("{{name}} at {{path}}{{remote}}: {{about}}; hub {{hub}}", &fields(None)).unwrap();
        assert!(
            r.text
                .ends_with("sample at C:\\dev\\sample - https://example.com/sample.git: a sample; hub not recorded yet"),
            "{}",
            r.text
        );
    }

    #[test]
    fn the_mark_lands_after_the_front_matter() {
        let r = render("---\nname: {{name}}\n---\n\n# {{name}}\n", &fields(None)).unwrap();
        assert_eq!(r.text, format!("---\nname: sample\n---\n\n{MARK}\n\n# sample\n"));
        assert!(is_generated(&r.text));
    }

    #[test]
    fn without_front_matter_the_mark_comes_first() {
        let r = render("# {{name}}\n", &fields(None)).unwrap();
        assert!(r.text.starts_with(MARK), "{}", r.text);
    }

    #[test]
    fn an_unknown_placeholder_is_an_error_not_a_hole() {
        let err = render("{{nope}}", &fields(None)).unwrap_err().to_string();
        assert!(err.contains("{{nope}}"), "{err}");
    }

    #[test]
    fn a_hub_file_is_included_and_a_missing_one_is_noted() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("Rituals.md"), "  deploy after the tag\n").unwrap();
        let r = render("{{file:Rituals.md}}|{{file:Other.md}}", &fields(Some(dir.path()))).unwrap();
        assert!(r.text.ends_with("deploy after the tag|"), "{}", r.text);
        assert_eq!(r.notes.len(), 1, "{:?}", r.notes);
        assert!(r.notes[0].contains("Other.md"), "{:?}", r.notes);
    }

    fn listed(names: &[&str]) -> Vec<Listed> {
        names
            .iter()
            .map(|n| Listed {
                name: (*n).to_string(),
                path: format!("/dev/{n}"),
                about: None,
            })
            .collect()
    }

    #[test]
    fn a_description_over_the_limit_is_refused_rather_than_written() {
        // The failure this prevents is silent: an assistant rejects a skill
        // whose description is too long, and the skill then matches nothing
        // and says nothing. So the refusal is checked by making it happen.
        let long = "x".repeat(DESCRIPTION_LIMIT + 1);
        let err = check_description(&long).unwrap_err().to_string();
        assert!(err.contains(&(DESCRIPTION_LIMIT + 1).to_string()), "the error says how long it was: {err}");
        assert!(err.contains("body"), "and where the list belongs instead: {err}");

        // Exactly at the limit is within it.
        check_description(&"x".repeat(DESCRIPTION_LIMIT)).unwrap();

        // And `render_line` refuses rather than writing such a file.
        let template = "---
name: {{line}}
description: {{description}}
---
";
        assert!(render_line(template, "line", &long, &[]).is_err());
    }

    #[test]
    fn angle_brackets_are_refused_because_they_break_the_whole_catalogue() {
        // A path like `C:\Projects\<project>` is the natural way to write
        // this skill's trigger, so this is a real hazard and not a
        // theoretical one - and it breaks the parse of the skills around
        // it, not only its own.
        let err = check_description("work in C:/Projects/<project>").unwrap_err().to_string();
        assert!(err.contains("catalogue"), "{err}");
        check_description("work in C:/Projects/, named in the request").unwrap();
    }

    #[test]
    fn a_line_too_long_to_name_keeps_the_description_within_the_limit() {
        // The names go into the description while they fit. A line of
        // sixty products with long names is how that stops fitting, and
        // the description must shorten rather than be refused - the list
        // is in the body for exactly this reason.
        let many: Vec<String> = (0..60).map(|i| format!("a-rather-long-product-name-{i}")).collect();
        let refs: Vec<&str> = many.iter().map(String::as_str).collect();
        let description = line_description("line", &listed(&refs));
        check_description(&description).expect("a long line still yields a usable description");
        assert!(!description.contains("a-rather-long-product-name-59"), "the tail is left to the body");

        // A line small enough to name is named.
        let few = line_description("line", &listed(&["sample", "other"]));
        assert!(few.contains("sample, other"), "{few}");
        check_description(&few).unwrap();
    }

    #[test]
    fn the_line_template_knows_its_own_placeholders_and_no_others() {
        let r = render_line("{{line}} | {{description}} | {{projects}}", "line", "about it", &listed(&["sample"])).unwrap();
        assert!(r.text.contains("line | about it |"), "{}", r.text);
        assert!(r.text.contains("| `sample` |"), "{}", r.text);

        // `{{name}}` would have to pick a project arbitrarily.
        let err = render_line("{{name}}", "line", "about it", &[]).unwrap_err().to_string();
        assert!(err.contains("{{name}}"), "{err}");
    }

    #[test]
    fn a_line_with_no_projects_says_so_rather_than_printing_an_empty_table() {
        let table = projects_table(&[]);
        assert!(table.contains("project add"), "{table}");
    }

    #[test]
    fn a_pipe_in_a_description_does_not_end_the_cell_it_sits_in() {
        let listed = vec![Listed {
            name: "sample".into(),
            path: "/dev/sample".into(),
            about: Some("reads a | writes b".into()),
        }];
        let table = projects_table(&listed);
        assert!(table.contains("reads a \\| writes b"), "{table}");
        // One row, not two: an unescaped pipe would split the cell.
        assert_eq!(table.lines().filter(|l| l.contains("sample")).count(), 1, "{table}");
    }

    #[test]
    fn the_built_in_line_template_renders_and_fits() {
        let listed = listed(&["sample", "other"]);
        let description = line_description("line", &listed);
        let r = render_line(DEFAULT_LINE_TEMPLATE, "line", &description, &listed).unwrap();
        assert!(
            r.text.starts_with(
                "---
name: line
"
            ),
            "{}",
            r.text
        );
        assert!(r.text.contains("rigger context <project>"), "{}", r.text);
        assert!(r.text.contains("| `sample` |"), "{}", r.text);
        assert!(is_generated(&r.text));
    }

    #[test]
    fn the_built_in_template_renders() {
        let r = render(DEFAULT_TEMPLATE, &fields(None)).unwrap();
        assert!(r.text.contains("rigger context sample"), "{}", r.text);
        assert!(r.text.starts_with("---\nname: sample\n"), "{}", r.text);
        assert!(r.notes.is_empty(), "{:?}", r.notes);
    }
}