agentstacks 1.1.0

Core library of agentstacks: packs, tool extensions, plans, and the executor that applies them.
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
//! The official source, and classifying one `init` or `ext add` argument as an official name, a
//! path or a git URL.
//!
//! `init --pack <arg>` and `init --tool <arg>` take either a bare name from the official
//! repository or a directory in the project. `ext add <source>` also takes a git URL. The decision
//! is a rule over the text alone, so it lives here and the flows that call it stay a sequence of
//! steps.
//!
//! # Responsibilities
//!
//! - [`Flag`]: which option or command the argument came from, for the refusal text and the noun it
//!   uses.
//! - [`OFFICIAL_REPOSITORY`], [`TAG_PREFIX`], [`OFFICIAL_PACKS`], [`OFFICIAL_TOOLS`]: the one place
//!   the official source is named.
//! - [`official_major`], [`release_prefix`]: the rule that the official release tags keep the major
//!   of the `api`, and the text of that prefix.
//! - [`Argument`]: the result, either the official repository with the directory inside it, a
//!   project path, or (for `ext add` only) a git URL.
//! - [`ShorthandError`]: the refusal of a bare name the official repository does not hold.
//! - [`classify`]: the rule. For `ext add`, an argument containing `://` or starting with `git@` is
//!   a git URL. Then an argument containing `/` or starting with `.` is a path; anything else is an
//!   official name, even when a directory of that name exists.
//!
//! # Non-responsibilities
//!
//! Choosing among the tags of a repository belongs to `types/resolve`. Reading the directory a path
//! names and turning duplicates into one key belong to the `init` flow.

use std::fmt;

use crate::types::api::API_MAJOR;
use crate::types::project::GitUrl;
use crate::types::project::LocalPath;
use crate::types::project::SourceError;
use crate::types::project::SubPath;
use crate::types::report::Diagnostic;
use crate::types::report::Location;

/// The official repository that holds the packs and the tool extensions.
pub const OFFICIAL_REPOSITORY: &str = "https://github.com/airsstack/agentstacks";

/// The prefix of the release tags that mark a version of the official packs and extensions.
pub const TAG_PREFIX: &str = "packs-v";

/// The release prefix with the major of the `api` this agentstacks speaks, such as `packs-v1`: the
/// tags `init` and `ext add` pick from the official repository start with it.
#[must_use]
pub fn release_prefix() -> String {
    format!("{TAG_PREFIX}{API_MAJOR}")
}

/// The major version a release tag must have, or `None` when any major is accepted.
///
/// It is the major of the `api` when `url` is the official repository and `prefix` is
/// [`TAG_PREFIX`], so a binary never moves to a release of a later `api`. Every other source
/// accepts all its tags.
///
/// The URL is compared byte for byte with [`OFFICIAL_REPOSITORY`], so a `.git` suffix or another
/// case makes it a third-party source.
///
/// # Examples
///
/// ```
/// use agentstacks::types::GitUrl;
/// use agentstacks::types::shorthand::official_major;
///
/// let official = GitUrl::new("https://github.com/airsstack/agentstacks")?;
/// assert_eq!(official_major(&official, "packs-v"), Some(1));
/// assert_eq!(official_major(&official, "rel-"), None);
/// let other = GitUrl::new("https://github.com/acme/packs")?;
/// assert_eq!(official_major(&other, "packs-v"), None);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[must_use]
pub fn official_major(url: &GitUrl, prefix: &str) -> Option<u64> {
    (url.as_str() == OFFICIAL_REPOSITORY && prefix == TAG_PREFIX).then_some(API_MAJOR)
}

/// The pack names the official repository holds under `packs/`.
pub const OFFICIAL_PACKS: [&str; 5] = [
    "core",
    "sdlc",
    "journal",
    "guideline-rust",
    "guideline-python",
];

/// The tool names the official repository holds under `extensions/`.
pub const OFFICIAL_TOOLS: [&str; 3] = ["claude", "musecode", "opencode"];

/// The `init` option or the command an argument came from.
///
/// # Examples
///
/// ```
/// use agentstacks::types::Flag;
///
/// assert_eq!(Flag::Pack.to_string(), "--pack");
/// assert_eq!(Flag::Tool.noun(), "tool");
/// assert_eq!(Flag::Ext.to_string(), "ext add");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Flag {
    /// `--pack`.
    Pack,
    /// `--tool`.
    Tool,
    /// The source of `ext add`: a tool, from a git URL as well as a path or an official name.
    Ext,
}

impl Flag {
    /// The word for what the option names: `pack` or `tool`.
    #[must_use]
    pub const fn noun(self) -> &'static str {
        match self {
            Self::Pack => "pack",
            Self::Tool | Self::Ext => "tool",
        }
    }

    const fn official(self) -> &'static [&'static str] {
        match self {
            Self::Pack => &OFFICIAL_PACKS,
            Self::Tool | Self::Ext => &OFFICIAL_TOOLS,
        }
    }

    const fn directory(self) -> &'static str {
        match self {
            Self::Pack => "packs",
            Self::Tool | Self::Ext => "extensions",
        }
    }

    const fn takes_git_url(self) -> bool {
        matches!(self, Self::Ext)
    }
}

impl fmt::Display for Flag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Pack | Self::Tool => write!(f, "--{}", self.noun()),
            Self::Ext => f.write_str("ext add"),
        }
    }
}

/// Where an `init` or `ext add` argument says a pack or tool comes from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Argument {
    /// A name from the official repository: the repository and the directory inside it.
    Official {
        /// The official repository.
        url: GitUrl,
        /// `packs/<name>` for a pack, `extensions/<name>` for a tool.
        subdir: SubPath,
    },
    /// A directory in the project, as written.
    Path(LocalPath),
    /// A git URL, as written. Only [`Flag::Ext`] produces it.
    Git(GitUrl),
}

/// The refusal of an argument that is a bare name but not an official one.
///
/// # Examples
///
/// ```
/// use agentstacks::types::{Flag, ShorthandError};
///
/// assert_eq!(
///     ShorthandError::NotOfficial(Flag::Tool).to_string(),
///     "not an official tool; pass a path, or add a git source to agentstacks.toml",
/// );
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum ShorthandError {
    /// The name is not one the official repository holds for this option.
    #[error("not an official {}; {}", .0.noun(), hint(*.0))]
    NotOfficial(Flag),
}

/// What to do instead of a name that is not official.
const fn hint(flag: Flag) -> &'static str {
    match flag {
        Flag::Pack | Flag::Tool => "pass a path, or add a git source to agentstacks.toml",
        Flag::Ext => "pass a path or a git URL",
    }
}

/// Classifies `arg`, given with `flag`, as an official name, a project path or a git URL.
///
/// For [`Flag::Ext`], an argument containing `://` or starting with `git@` is a git URL; `init`
/// takes none. Then an argument containing `/` or starting with `.` is a path. Anything else is a
/// name and must be official.
///
/// # Errors
///
/// A [`Diagnostic`] located at the flag and the argument as written (`--pack "x"`, `ext add "x"`):
/// an unknown name, a git URL that leads with `-`, or a path that is absolute or climbs
/// out of the project.
///
/// # Examples
///
/// ```
/// use agentstacks::types::{Argument, Flag, classify_argument};
///
/// let Argument::Official { subdir, .. } = classify_argument(Flag::Pack, "core").map_err(|refused| refused.to_string())? else {
///     return Err("expected an official name".into());
/// };
/// assert_eq!(subdir.as_str(), "packs/core");
///
/// let refused = classify_argument(Flag::Pack, "x").err().ok_or("expected a refusal")?;
/// assert_eq!(
///     refused.to_string(),
///     "--pack \"x\": not an official pack; pass a path, or add a git source to agentstacks.toml",
/// );
///
/// let refused = classify_argument(Flag::Ext, "x").err().ok_or("expected a refusal")?;
/// assert_eq!(
///     refused.to_string(),
///     "ext add \"x\": not an official tool; pass a path or a git URL",
/// );
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn classify(flag: Flag, arg: &str) -> Result<Argument, Diagnostic> {
    let at = || Location::verbatim(format!("{flag} \"{arg}\""));
    if flag.takes_git_url() && (arg.contains("://") || arg.starts_with("git@")) {
        return GitUrl::new(arg)
            .map(Argument::Git)
            .map_err(|error| Diagnostic::new(at(), SourceError::from(error)));
    }
    if arg.contains('/') || arg.starts_with('.') {
        return LocalPath::new(arg)
            .map(Argument::Path)
            .map_err(|error| Diagnostic::new(at(), SourceError::from(error)));
    }
    if !flag.official().contains(&arg) {
        return Err(Diagnostic::new(at(), ShorthandError::NotOfficial(flag)));
    }
    let url = GitUrl::new(OFFICIAL_REPOSITORY)
        .map_err(|e| Diagnostic::new(at(), SourceError::from(e)))?;
    let subdir = SubPath::new(&format!("{}/{arg}", flag.directory()))
        .map_err(|e| Diagnostic::new(at(), SourceError::from(e)))?;
    Ok(Argument::Official { url, subdir })
}

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

    type TestResult = Result<(), Box<dyn std::error::Error>>;

    fn accepted(flag: Flag, arg: &str) -> Result<Argument, String> {
        classify(flag, arg).map_err(|refused| refused.to_string())
    }

    fn refusal(flag: Flag, arg: &str) -> Result<String, Box<dyn std::error::Error>> {
        Ok(classify(flag, arg)
            .err()
            .ok_or("expected a refusal")?
            .to_string())
    }

    #[test]
    fn official_pack_expands_to_the_repository_and_packs_subdir() -> TestResult {
        let Argument::Official { url, subdir } = accepted(Flag::Pack, "core")? else {
            return Err("expected an official name".into());
        };
        assert_eq!(url.as_str(), "https://github.com/airsstack/agentstacks");
        assert_eq!(subdir.as_str(), "packs/core");
        Ok(())
    }

    #[test]
    fn official_tool_expands_to_extensions_subdir() -> TestResult {
        let Argument::Official { url, subdir } = accepted(Flag::Tool, "claude")? else {
            return Err("expected an official name".into());
        };
        assert_eq!(url.as_str(), OFFICIAL_REPOSITORY);
        assert_eq!(subdir.as_str(), "extensions/claude");
        Ok(())
    }

    #[test]
    fn official_tool_opencode_expands_to_extensions_subdir() -> TestResult {
        let Argument::Official { url, subdir } = accepted(Flag::Tool, "opencode")? else {
            return Err("expected an official name".into());
        };
        assert_eq!(url.as_str(), OFFICIAL_REPOSITORY);
        assert_eq!(subdir.as_str(), "extensions/opencode");
        Ok(())
    }

    #[test]
    fn official_tool_musecode_expands_to_extensions_subdir() -> TestResult {
        let Argument::Official { url, subdir } = accepted(Flag::Tool, "musecode")? else {
            return Err("expected an official name".into());
        };
        assert_eq!(url.as_str(), OFFICIAL_REPOSITORY);
        assert_eq!(subdir.as_str(), "extensions/musecode");
        Ok(())
    }

    #[test]
    fn every_official_pack_name_is_accepted() -> TestResult {
        for name in OFFICIAL_PACKS {
            let Argument::Official { subdir, .. } = accepted(Flag::Pack, name)? else {
                return Err(format!("{name} is not official").into());
            };
            assert_eq!(subdir.as_str(), format!("packs/{name}"));
        }
        assert_eq!(
            OFFICIAL_PACKS,
            [
                "core",
                "sdlc",
                "journal",
                "guideline-rust",
                "guideline-python"
            ]
        );
        Ok(())
    }

    #[test]
    fn cmux_is_not_an_official_pack() -> TestResult {
        assert_eq!(
            refusal(Flag::Pack, "cmux")?,
            "--pack \"cmux\": not an official pack; pass a path, or add a git source to agentstacks.toml"
        );
        Ok(())
    }

    #[test]
    fn slash_or_leading_dot_makes_a_path() -> TestResult {
        for text in ["./packs/core", "packs/x", ".hidden"] {
            assert_eq!(
                accepted(Flag::Pack, text)?,
                Argument::Path(LocalPath::new(text)?)
            );
        }
        Ok(())
    }

    #[test]
    fn bare_name_is_never_a_path() -> TestResult {
        assert!(matches!(
            accepted(Flag::Pack, "core")?,
            Argument::Official { .. }
        ));
        Ok(())
    }

    #[test]
    fn unknown_pack_is_refused_with_the_flag_location() -> TestResult {
        assert_eq!(
            refusal(Flag::Pack, "x")?,
            "--pack \"x\": not an official pack; pass a path, or add a git source to agentstacks.toml"
        );
        Ok(())
    }

    #[test]
    fn unknown_name_is_carried_as_the_shorthand_variant() -> TestResult {
        let refused = classify(Flag::Tool, "x")
            .err()
            .ok_or("expected a refusal")?;
        assert!(matches!(
            refused.error(),
            FormatError::Shorthand(ShorthandError::NotOfficial(Flag::Tool))
        ));
        Ok(())
    }

    #[test]
    fn unknown_tool_is_refused_with_the_tool_wording() -> TestResult {
        assert_eq!(
            refusal(Flag::Tool, "x")?,
            "--tool \"x\": not an official tool; pass a path, or add a git source to agentstacks.toml"
        );
        Ok(())
    }

    #[test]
    fn absolute_path_is_refused() -> TestResult {
        assert_eq!(
            refusal(Flag::Pack, "/x")?,
            "--pack \"/x\": absolute paths are not portable"
        );
        Ok(())
    }

    #[test]
    fn climbing_path_is_refused() -> TestResult {
        assert_eq!(
            refusal(Flag::Pack, "../x")?,
            "--pack \"../x\": must stay inside the project"
        );
        Ok(())
    }

    #[test]
    fn ext_classifies_url_path_and_official() -> TestResult {
        for text in ["https://example.com/x.git", "git@host:x.git"] {
            assert_eq!(
                accepted(Flag::Ext, text)?,
                Argument::Git(GitUrl::new(text)?)
            );
        }
        for text in ["./ext/x", "ext/x"] {
            assert_eq!(
                accepted(Flag::Ext, text)?,
                Argument::Path(LocalPath::new(text)?)
            );
        }
        let Argument::Official { url, subdir } = accepted(Flag::Ext, "claude")? else {
            return Err("expected an official name".into());
        };
        assert_eq!(url.as_str(), OFFICIAL_REPOSITORY);
        assert_eq!(subdir.as_str(), "extensions/claude");
        Ok(())
    }

    #[test]
    fn ext_not_official_text() -> TestResult {
        assert_eq!(
            refusal(Flag::Ext, "x")?,
            "ext add \"x\": not an official tool; pass a path or a git URL"
        );
        Ok(())
    }

    #[test]
    fn dash_name_is_not_official() -> TestResult {
        assert_eq!(
            refusal(Flag::Ext, "-x")?,
            "ext add \"-x\": not an official tool; pass a path or a git URL"
        );
        Ok(())
    }

    #[test]
    fn ext_dash_url_refused_verbatim() -> TestResult {
        assert_eq!(
            refusal(Flag::Ext, "--upload-pack=x://y")?,
            "ext add \"--upload-pack=x://y\": URL must not start with \"-\""
        );
        Ok(())
    }

    #[test]
    fn init_still_takes_no_url() -> TestResult {
        for flag in [Flag::Pack, Flag::Tool] {
            let text = "https://example.com/x.git";
            assert_eq!(
                accepted(flag, text)?,
                Argument::Path(LocalPath::new(text)?),
                "{flag}"
            );
            assert_eq!(
                refusal(flag, "git@host:x.git")?,
                format!(
                    "{flag} \"git@host:x.git\": not an official {}; pass a path, or add a git source to agentstacks.toml",
                    flag.noun()
                )
            );
        }
        Ok(())
    }
}