devsandbox 0.9.0

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
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
//! The `devsbd thread put` body: the schema the host checks, and nothing the
//! helper knows about (docs/decisions/0022-helper-has-no-dependencies.md: the helper only
//! checks JSON syntax, so everything here runs on the host).
//!
//! The body comes from inside a container and ends up driving dashboard
//! actions, so every field is bounded and every reference is checked: paths
//! stay inside the instance workspace, URLs are http(s) only, and the `child`
//! an action targets must be a key a dispatcher could actually have ensured.
//! A reject is one line, because that line becomes an `error` record in the
//! sender's own Inbox — it is the only feedback the author gets.

use std::collections::BTreeSet;

use serde::{Deserialize, Serialize};

use super::is_url;
use crate::devsbd::control::{valid_key, MAX_KEY};

/// Numbered `1`-`9` in the thread pane, so nine is the ceiling.
pub const MAX_ACTIONS: usize = 9;

/// Caps on the free-text fields. Generous for their purpose and far under
/// `notify::MAX_RECORD`, so a runaway dispatcher can't fill the store.
const MAX_TITLE: usize = 200;
const MAX_STATUS: usize = 60;
const MAX_LINK: usize = 2000;
const MAX_LABEL: usize = 60;
const MAX_PATH: usize = 400;
const MAX_PLACEHOLDER: usize = 100;
const MAX_HINT: usize = 100;

/// A fixed set: it drives the Inbox views and the unread badge.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum State {
    NeedsYou,
    #[default]
    Active,
    Done,
}

impl State {
    pub fn as_str(self) -> &'static str {
        match self {
            State::NeedsYou => "needs-you",
            State::Active => "active",
            State::Done => "done",
        }
    }
}

/// One `devsbd thread put` body: the thread's header. Also serialized (as
/// JSON) by `devsbd thread ls`, which hands a dispatcher back exactly what it
/// put.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ThreadPut {
    pub key: String,
    pub title: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub link: Option<String>,
    pub state: State,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    /// Key of one of the sender's dispatcher children: the instance the
    /// thread is about, and what its host actions target.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub child: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub actions: Vec<Action>,
    /// Present when the thread takes replies.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compose: Option<Compose>,
}

/// A button on the thread. Field order is load-bearing for TOML: `host` is a
/// table and must be serialized after every scalar.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Action {
    pub id: String,
    pub label: String,
    /// Also enqueue an event for the owner, even with a `host` verb.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub notify: bool,
    /// Built-in: set the thread (and its child) done, and enqueue an event.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub done: bool,
    /// Runs in the dashboard with no dispatcher round trip; absent means the
    /// action is only an event for the owner.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub host: Option<HostVerb>,
}

impl Action {
    /// Whether pressing it enqueues an event for the owner: a dispatcher
    /// action (no `host`), `notify: true`, or the `done: true` built-in.
    pub fn enqueues_event(&self) -> bool {
        self.host.is_none() || self.notify || self.done
    }
}

/// The fixed host-action table (docs/architecture/inbox/threads-and-feed.md, *`thread put`*). Externally
/// tagged, so the body is exactly one verb object — two keys don't deserialize.
/// There is no arbitrary host command, ever.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HostVerb {
    Vscode(Vscode),
    Terminal(NoArgs),
    Logs(NoArgs),
    Forward(Forward),
    Open(Open),
    Rm(NoArgs),
}

/// A verb that takes no arguments; still written `{}` so every verb has the
/// same shape.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NoArgs {}

#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Vscode {
    /// Relative to the instance's workspace folder.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub line: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub col: Option<u32>,
}

#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Forward {
    /// Checked as 1-65535 rather than typed `u16`, so 0 and 70000 get the
    /// same one-line reason as every other field.
    pub port: u32,
}

#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Open {
    pub url: String,
}

/// The reply box: its placeholder, and `hint`, one dim line under it saying
/// what sending does now ("Starts a comments run with your message").
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Compose {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub placeholder: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hint: Option<String>,
}

/// Fields a put used to take, with what to do instead: `deny_unknown_fields`
/// rejects them anyway, but serde's "unknown field" doesn't say where they
/// went.
const REMOVED: &[(&str, &str)] = &[
    ("message", "`message` was removed: send explanations with `devsbd thread send` (docs/automations-guide.md, Messages (`devsbd thread send`))"),
    ("reply", "`reply` was renamed `compose`"),
];

/// Parse and check one put body. `Err` is a single line naming the field to
/// fix: it is shown to the sender as an `error` record.
pub fn parse(body: &str) -> Result<ThreadPut, String> {
    let put: ThreadPut = serde_json::from_str(body).map_err(|e| removed_field(body).unwrap_or_else(|| e.to_string()))?;
    validate(&put)?;
    Ok(put)
}

/// The reason for the first [`REMOVED`] field in `body`, if it has one. Only
/// called on a body that already failed, so the second parse costs nothing
/// on the happy path.
fn removed_field(body: &str) -> Option<String> {
    let serde_json::Value::Object(map) = serde_json::from_str(body).ok()? else { return None };
    REMOVED.iter().find(|(field, _)| map.contains_key(*field)).map(|(_, why)| why.to_string())
}

fn validate(put: &ThreadPut) -> Result<(), String> {
    check_key("key", &put.key)?;
    check_text("title", &put.title, MAX_TITLE)?;
    if put.title.trim().is_empty() {
        return Err("`title` is empty".into());
    }
    if let Some(link) = &put.link {
        check_text("link", link, MAX_LINK)?;
        check_url("link", link)?;
    }
    if let Some(status) = &put.status {
        check_text("status", status, MAX_STATUS)?;
    }
    if let Some(child) = &put.child {
        check_key("child", child)?;
    }
    if put.actions.len() > MAX_ACTIONS {
        return Err(format!("{} actions, at most {MAX_ACTIONS} allowed", put.actions.len()));
    }
    let mut seen = BTreeSet::new();
    for action in &put.actions {
        check_action(action)?;
        if !seen.insert(action.id.as_str()) {
            return Err(format!("duplicate action id `{}`", action.id));
        }
    }
    if let Some(compose) = &put.compose {
        if let Some(placeholder) = &compose.placeholder {
            check_text("compose.placeholder", placeholder, MAX_PLACEHOLDER)?;
        }
        if let Some(hint) = &compose.hint {
            check_text("compose.hint", hint, MAX_HINT)?;
        }
    }
    Ok(())
}

fn check_action(action: &Action) -> Result<(), String> {
    if !valid_action_id(&action.id) {
        return Err(format!(
            "bad action id `{}`: lowercase letters, digits and `-`, 1-{MAX_KEY} chars",
            action.id
        ));
    }
    check_text(&format!("action `{}` label", action.id), &action.label, MAX_LABEL)?;
    if action.label.trim().is_empty() {
        return Err(format!("action `{}` has an empty label", action.id));
    }
    match &action.host {
        Some(HostVerb::Vscode(v)) => {
            if let Some(path) = &v.path {
                check_workspace_path(path)?;
            }
        }
        Some(HostVerb::Forward(f)) => {
            if !(1..=65535).contains(&f.port) {
                return Err(format!("bad forward port {}: 1-65535", f.port));
            }
        }
        Some(HostVerb::Open(o)) => {
            check_text("open.url", &o.url, MAX_LINK)?;
            check_url("open.url", &o.url)?;
        }
        _ => {}
    }
    Ok(())
}

/// `[a-z0-9-]{1,40}`: the action id is a stable handle the dispatcher gets
/// back in its event, never a path or a name, so a leading `-` is harmless.
fn valid_action_id(id: &str) -> bool {
    !id.is_empty()
        && id.len() <= MAX_KEY
        && id.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
}

pub(super) fn check_key(field: &str, key: &str) -> Result<(), String> {
    if valid_key(key) {
        return Ok(());
    }
    Err(format!(
        "bad `{field}` `{key}`: lowercase letters, digits and `-`, starting with a letter or \
         digit, at most {MAX_KEY} chars"
    ))
}

pub(super) fn check_text(field: &str, value: &str, max: usize) -> Result<(), String> {
    if value.len() > max {
        return Err(format!("`{field}` is longer than {max} bytes"));
    }
    // Control characters would corrupt a terminal row. Tabs and CRs are
    // allowed: `sanitize` expands/normalizes them right after, and LLM code
    // blocks are often tab-indented or CRLF.
    if value.chars().any(|c| c.is_control() && !matches!(c, '\n' | '\t' | '\r')) {
        return Err(format!("`{field}` contains a control character"));
    }
    Ok(())
}

fn check_url(field: &str, url: &str) -> Result<(), String> {
    if is_url(url) {
        return Ok(());
    }
    Err(format!("`{field}` is not an http(s) URL: {url}"))
}

/// A path the `vscode` action may open: relative to the instance workspace,
/// with no component that could climb out of it. Normalization isn't enough —
/// an absolute path or a `..` is refused outright, so nothing downstream has
/// to re-derive where the workspace ends.
fn check_workspace_path(path: &str) -> Result<(), String> {
    check_text("vscode.path", path, MAX_PATH)?;
    if path.is_empty() {
        return Err("`vscode.path` is empty".into());
    }
    if path.starts_with('/') || path.starts_with('~') {
        return Err(format!("`vscode.path` must be relative to the workspace: {path}"));
    }
    for component in path.split('/') {
        if component.is_empty() {
            return Err(format!("`vscode.path` has an empty component: {path}"));
        }
        if component == ".." {
            return Err(format!("`vscode.path` must stay inside the workspace: {path}"));
        }
    }
    Ok(())
}

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

    /// The plan's example body (docs/architecture/inbox/threads-and-feed.md, *`thread put`*).
    const EXAMPLE: &str = r##"{
      "key": "pr-6900",
      "title": "#6900 feat/agent-run-cost-event",
      "link": "https://github.com/stackblitz/bolt/pull/6900",
      "state": "needs-you",
      "status": "review draft replies",
      "child": "pr-6900",
      "actions": [
        { "id": "open-draft", "label": "Open draft", "host": { "vscode": { "path": ".dispatcher/pr-6900-replies.md", "line": 1 } } },
        { "id": "post", "label": "Post replies" },
        { "id": "done", "label": "Done", "done": true }
      ],
      "compose": { "placeholder": "Instructions for the next run" }
    }"##;

    #[test]
    fn parses_the_documented_body() {
        let put = parse(EXAMPLE).unwrap();
        assert_eq!(put.key, "pr-6900");
        assert_eq!(put.state, State::NeedsYou);
        assert_eq!(put.child.as_deref(), Some("pr-6900"));
        assert_eq!(put.actions.len(), 3);
        assert_eq!(
            put.actions[0].host,
            Some(HostVerb::Vscode(Vscode {
                path: Some(".dispatcher/pr-6900-replies.md".into()),
                line: Some(1),
                col: None
            }))
        );
        assert_eq!(put.actions[1].host, None, "no `host` = a dispatcher action");
        assert!(put.actions[2].done);
        let compose = put.compose.unwrap();
        assert_eq!(compose.placeholder.as_deref(), Some("Instructions for the next run"));
        assert_eq!(compose.hint, None);
    }

    #[test]
    fn compose_takes_a_placeholder_and_a_hint() {
        let body = r#"{"key":"k","title":"t","state":"active","compose":{"placeholder":"p","hint":"Starts a run"}}"#;
        let put = parse(body).unwrap();
        assert_eq!(put.compose, Some(Compose { placeholder: Some("p".into()), hint: Some("Starts a run".into()) }));
        let none = parse(r#"{"key":"k","title":"t","state":"active"}"#).unwrap();
        assert_eq!(none.compose, None);
        assert!(parse(r#"{"key":"k","title":"t","state":"active","compose":{"nope":1}}"#).is_err());
    }

    #[test]
    fn minimal_body_and_every_host_verb() {
        let put = parse(r#"{"key":"k","title":"t","state":"active"}"#).unwrap();
        assert_eq!(put, ThreadPut { key: "k".into(), title: "t".into(), state: State::Active, ..Default::default() });
        for verb in [
            r#"{"vscode":{}}"#,
            r#"{"vscode":{"path":"a/b.rs","line":3,"col":7}}"#,
            r#"{"terminal":{}}"#,
            r#"{"logs":{}}"#,
            r#"{"forward":{"port":65535}}"#,
            r#"{"open":{"url":"https://x/y"}}"#,
            r#"{"rm":{}}"#,
        ] {
            let body = format!(
                r#"{{"key":"k","title":"t","state":"done","actions":[{{"id":"a","label":"A","host":{verb}}}]}}"#
            );
            assert!(parse(&body).is_ok(), "{verb}: {:?}", parse(&body));
        }
    }

    #[test]
    fn rejects_unknown_fields_and_bad_shapes() {
        let bad = [
            r#"{"key":"k","title":"t","state":"active","nope":1}"#,
            r#"{"key":"k","title":"t"}"#,                              // no state
            r#"{"key":"k","state":"active"}"#,                         // no title
            r#"{"title":"t","state":"active"}"#,                       // no key
            r#"{"key":"k","title":"t","state":"later"}"#,              // unknown state
            // Exactly one verb per action, with its own fields only.
            r#"{"key":"k","title":"t","state":"active","actions":[{"id":"a","label":"A","host":{"terminal":{},"logs":{}}}]}"#,
            r#"{"key":"k","title":"t","state":"active","actions":[{"id":"a","label":"A","host":{"shell":{}}}]}"#,
            r#"{"key":"k","title":"t","state":"active","actions":[{"id":"a","label":"A","host":{"vscode":{"file":"x"}}}]}"#,
            r#"{"key":"k","title":"t","state":"active","actions":[{"id":"a"}]}"#,
        ];
        for body in bad {
            assert!(parse(body).is_err(), "{body} parsed");
        }
    }

    /// Each rule gets its own body, so a reason can't be reached by accident.
    #[test]
    fn rejects_every_invalid_field() {
        let put = |extra: &str| format!(r#"{{"key":"k","title":"t","state":"active"{extra}}}"#);
        let cases: &[(String, &str)] = &[
            (r#"{"key":"Bad","title":"t","state":"active"}"#.into(), "bad `key`"),
            (put(r#","child":"Bad""#), "bad `child`"),
            (r#"{"key":"k","title":"  ","state":"active"}"#.into(), "`title` is empty"),
            (format!(r#"{{"key":"k","title":"{}","state":"active"}}"#, "x".repeat(MAX_TITLE + 1)), "`title` is longer"),
            (put(&format!(r#","status":"{}""#, "x".repeat(MAX_STATUS + 1))), "`status` is longer"),
            (put(r#","status":"a\u0007b""#), "control character"),
            (put(r#","link":"ftp://x""#), "`link` is not an http(s) URL"),
            (put(r#","link":"/etc/passwd""#), "`link` is not an http(s) URL"),
            (put(&format!(r#","compose":{{"placeholder":"{}"}}"#, "p".repeat(MAX_PLACEHOLDER + 1))), "`compose.placeholder` is longer"),
            (put(&format!(r#","compose":{{"hint":"{}"}}"#, "h".repeat(MAX_HINT + 1))), "`compose.hint` is longer"),
            (put(r#","compose":{"hint":"a\u0007b"}"#), "control character"),
            (put(r#","actions":[{"id":"a","label":"A"},{"id":"a","label":"B"}]"#), "duplicate action id"),
            (put(r#","actions":[{"id":"Bad","label":"A"}]"#), "bad action id"),
            (put(r#","actions":[{"id":"","label":"A"}]"#), "bad action id"),
            (put(r#","actions":[{"id":"a","label":" "}]"#), "empty label"),
            (put(r#","actions":[{"id":"a","label":"A","host":{"forward":{"port":0}}}]"#), "bad forward port"),
            (put(r#","actions":[{"id":"a","label":"A","host":{"forward":{"port":65536}}}]"#), "bad forward port"),
            (put(r#","actions":[{"id":"a","label":"A","host":{"open":{"url":"file:///etc"}}}]"#), "`open.url` is not an http(s) URL"),
            (put(r#","actions":[{"id":"a","label":"A","host":{"vscode":{"path":"/etc/passwd"}}}]"#), "must be relative"),
            (put(r#","actions":[{"id":"a","label":"A","host":{"vscode":{"path":"~/x"}}}]"#), "must be relative"),
            (put(r#","actions":[{"id":"a","label":"A","host":{"vscode":{"path":"a/../../etc"}}}]"#), "stay inside the workspace"),
            (put(r#","actions":[{"id":"a","label":"A","host":{"vscode":{"path":"a//b"}}}]"#), "empty component"),
            (put(r#","actions":[{"id":"a","label":"A","host":{"vscode":{"path":""}}}]"#), "`vscode.path` is empty"),
        ];
        for (body, reason) in cases {
            let err = parse(body).unwrap_err();
            assert!(err.contains(reason), "{body}\nwanted {reason:?}, got {err:?}");
        }
        // Ten actions is one too many.
        let actions: Vec<String> =
            (0..10).map(|i| format!(r#"{{"id":"a{i}","label":"A"}}"#)).collect();
        let err = parse(&put(&format!(r#","actions":[{}]"#, actions.join(",")))).unwrap_err();
        assert!(err.contains("at most 9 allowed"), "{err}");
        assert!(parse(&put(&format!(r#","actions":[{}]"#, actions[..9].join(",")))).is_ok());
        // Tab-indented, CRLF text (common in LLM code blocks) passes;
        // `sanitize` normalizes it after.
        assert!(parse(&put(r#","status":"\tfn x()\r\n""#)).is_ok());
    }

    /// The fields puts used to take fail with where they went, not serde's
    /// generic "unknown field".
    #[test]
    fn rejects_removed_fields_with_what_to_do_instead() {
        let message = parse(r#"{"key":"k","title":"t","state":"active","message":"hi"}"#).unwrap_err();
        assert_eq!(
            message,
            "`message` was removed: send explanations with `devsbd thread send` (docs/automations-guide.md, Messages (`devsbd thread send`))"
        );
        let reply = parse(r#"{"key":"k","title":"t","state":"active","reply":{"placeholder":"p"}}"#).unwrap_err();
        assert_eq!(reply, "`reply` was renamed `compose`");
        // Any other unknown field keeps serde's reason.
        let other = parse(r#"{"key":"k","title":"t","state":"active","nope":1}"#).unwrap_err();
        assert!(other.contains("unknown field `nope`"), "{other}");
    }

    #[test]
    fn rejects_malformed_json_with_one_line() {
        let err = parse("{").unwrap_err();
        assert!(!err.contains('\n'), "{err}");
    }
}