sloop-daemon 0.5.0

Agentic coding scheduler — a daemon that runs background coding agents autonomously in isolated git worktrees
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
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
use std::fmt;

use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

pub const PROTOCOL_VERSION: u32 = 1;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RequestId(String);

impl RequestId {
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RequestEnvelope {
    pub v: u32,
    pub id: RequestId,
    #[serde(flatten)]
    pub request: Request,
    pub token: Option<String>,
}

impl RequestEnvelope {
    pub fn new(id: RequestId, request: Request, token: Option<String>) -> Self {
        Self {
            v: PROTOCOL_VERSION,
            id,
            request,
            token,
        }
    }

    pub fn decode(line: &str) -> Result<Self, ProtocolError> {
        let value: Value = serde_json::from_str(line)
            .map_err(|error| ProtocolError::invalid_request(format!("malformed JSON: {error}")))?;
        let object = value
            .as_object()
            .ok_or_else(|| ProtocolError::invalid_request("request must be a JSON object"))?;

        let version = object.get("v").and_then(Value::as_u64).ok_or_else(|| {
            ProtocolError::invalid_request("request field `v` must be an integer")
        })?;
        if version != u64::from(PROTOCOL_VERSION) {
            return Err(ProtocolError::new(
                ErrorCode::UnsupportedVersion,
                format!("unsupported protocol version {version}"),
                json!({"supported": [PROTOCOL_VERSION], "received": version}),
            ));
        }

        let verb = object.get("verb").and_then(Value::as_str).ok_or_else(|| {
            ProtocolError::invalid_request("request field `verb` must be a string")
        })?;
        if !Request::is_known_verb(verb) {
            return Err(ProtocolError::new(
                ErrorCode::UnknownVerb,
                format!("unknown verb `{verb}`"),
                json!({"verb": verb}),
            ));
        }

        serde_json::from_value(value).map_err(|error| {
            ProtocolError::invalid_request(format!("invalid request envelope: {error}"))
        })
    }

    pub fn encode(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "verb", content = "args", rename_all = "snake_case")]
pub enum Request {
    Init(EmptyArgs),
    Daemon(EmptyArgs),
    Restart(EmptyArgs),
    Post(PostArgs),
    Run(RunArgs),
    Retry(TicketReferenceArgs),
    Hold(TicketReferenceArgs),
    Ready(TicketReferenceArgs),
    List(ListArgs),
    Status(EmptyArgs),
    Pause(EmptyArgs),
    Resume(EmptyArgs),
    Stop(StopArgs),
    Cancel(RunReferenceArgs),
    Logs(LogsArgs),
    Wait(RunReferenceArgs),
    Events(EventsArgs),
    Reindex(EmptyArgs),
    Brief(EmptyArgs),
    Show(ShowArgs),
    Note(NoteArgs),
    Verdict(VerdictArgs),
}

impl Request {
    pub fn verb(&self) -> &'static str {
        match self {
            Self::Init(_) => "init",
            Self::Daemon(_) => "daemon",
            Self::Restart(_) => "restart",
            Self::Post(_) => "post",
            Self::Run(_) => "run",
            Self::Retry(_) => "retry",
            Self::Hold(_) => "hold",
            Self::Ready(_) => "ready",
            Self::List(_) => "list",
            Self::Status(_) => "status",
            Self::Pause(_) => "pause",
            Self::Resume(_) => "resume",
            Self::Stop(_) => "stop",
            Self::Cancel(_) => "cancel",
            Self::Logs(_) => "logs",
            Self::Wait(_) => "wait",
            Self::Events(_) => "events",
            Self::Reindex(_) => "reindex",
            Self::Brief(_) => "brief",
            Self::Show(_) => "show",
            Self::Note(_) => "note",
            Self::Verdict(_) => "verdict",
        }
    }

    pub fn capability(&self) -> Capability {
        match self {
            Self::Brief(_) | Self::Note(_) | Self::Verdict(_) => Capability::Worker,
            Self::Show(_) => Capability::Both,
            _ => Capability::Operator,
        }
    }

    fn is_known_verb(verb: &str) -> bool {
        matches!(
            verb,
            "init"
                | "daemon"
                | "restart"
                | "post"
                | "run"
                | "retry"
                | "hold"
                | "ready"
                | "list"
                | "status"
                | "pause"
                | "resume"
                | "stop"
                | "cancel"
                | "logs"
                | "wait"
                | "events"
                | "reindex"
                | "brief"
                | "show"
                | "note"
                | "verdict"
        )
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Capability {
    Operator,
    Worker,
    Both,
}

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

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PostArgs {
    pub file: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flow: Option<String>,
    pub trigger: PostTrigger,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PostTrigger {
    Auto,
    At { time: String },
    Manual,
    Hold,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RunArgs {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ticket: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    pub trigger: RunTrigger,
    pub only: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum RunTrigger {
    Now,
    At { local_time: String },
    Every { interval_ms: u64 },
    Overnight,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StopArgs {
    #[serde(default)]
    pub force: bool,
}

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

/// A cursor-paginated read of one run's captured output. `stage` narrows the
/// page to a single flow stage, `tail` keeps the last N matching entries
/// instead of the first N, and `after` resumes from a previously returned
/// cursor so a follower streams without replaying what it has seen.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LogsArgs {
    pub run: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stage: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tail: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub after: Option<u64>,
}

/// A cursor-paginated read of the activity feed. `after` resumes from a
/// previously returned cursor; `tail` starts that many events before the
/// newest one and wins when both are given. One page per request — clients
/// stream by polling with the returned cursor.
///
/// `scope` narrows the feed to one reference, resolved by the daemon exactly
/// as `show` resolves it, so thin clients never reimplement that ladder. The
/// returned `next_cursor` still advances across filtered-out rows, so a scoped
/// watcher does not rescan the feed when its scope matches nothing.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EventsArgs {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub after: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tail: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scope: Option<String>,
}

/// `limit` keeps only that many of the newest tickets. Absent means all of
/// them, which is what a client that predates the field sends.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ListArgs {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

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

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ShowArgs {
    #[serde(default, rename = "ref", skip_serializing_if = "Option::is_none")]
    pub reference: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

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

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VerdictArgs {
    pub verdict: VerdictValue,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// How sure the reporter says it is. Absent from a client that predates
    /// the field, and read as `medium`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confidence: Option<ConfidenceValue>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VerdictValue {
    Pass,
    Fail,
}

/// Three named levels and nothing else. A float would decode here and then
/// have to mean something in aggregation, which v1 deliberately does not
/// define, so the wire type refuses one outright.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConfidenceValue {
    Low,
    Medium,
    High,
}

impl From<ConfidenceValue> for crate::flow::Confidence {
    fn from(value: ConfidenceValue) -> Self {
        match value {
            ConfidenceValue::Low => Self::Low,
            ConfidenceValue::Medium => Self::Medium,
            ConfidenceValue::High => Self::High,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCode {
    InvalidArguments,
    InvalidRequest,
    UnsupportedVersion,
    UnknownVerb,
    DaemonUnavailable,
    Unauthorized,
    NotFound,
    Conflict,
    CooldownActive,
    Internal,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ErrorBody {
    pub code: ErrorCode,
    pub message: String,
    pub details: Value,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ProtocolError {
    pub body: ErrorBody,
}

impl ProtocolError {
    pub fn new(code: ErrorCode, message: impl Into<String>, details: Value) -> Self {
        Self {
            body: ErrorBody {
                code,
                message: message.into(),
                details,
            },
        }
    }

    fn invalid_request(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::InvalidRequest, message, json!({}))
    }
}

impl fmt::Display for ProtocolError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.body.message)
    }
}

impl std::error::Error for ProtocolError {}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ResponseEnvelope {
    pub id: Option<RequestId>,
    pub ok: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<ErrorBody>,
}

impl ResponseEnvelope {
    pub fn success(id: Option<RequestId>, data: Value) -> Self {
        Self {
            id,
            ok: true,
            data: Some(data),
            error: None,
        }
    }

    pub fn failure(id: Option<RequestId>, error: ErrorBody) -> Self {
        Self {
            id,
            ok: false,
            data: None,
            error: Some(error),
        }
    }
}

#[cfg(test)]
mod tests {
    use serde_json::{Value, json};

    use super::{
        EmptyArgs, ErrorBody, ErrorCode, Request, RequestEnvelope, RequestId, ResponseEnvelope,
        RunArgs, RunTrigger,
    };

    #[test]
    fn request_envelope_serializes_to_the_public_wire_shape() {
        let envelope = RequestEnvelope::new(
            RequestId::new("req-123"),
            Request::Run(RunArgs {
                ticket: Some("T1".into()),
                project: None,
                trigger: RunTrigger::Now,
                only: Vec::new(),
            }),
            None,
        );

        let value: Value = serde_json::from_str(&envelope.encode().unwrap()).unwrap();
        assert_eq!(
            value,
            json!({
                "v": 1,
                "id": "req-123",
                "verb": "run",
                "args": {
                    "ticket": "T1",
                    "trigger": {"kind": "now"},
                    "only": []
                },
                "token": null
            })
        );
    }

    #[test]
    fn request_envelope_round_trips() {
        let expected = RequestEnvelope::new(
            RequestId::new("req-1"),
            Request::Brief(EmptyArgs::default()),
            Some("worker-token".into()),
        );

        let decoded = RequestEnvelope::decode(&expected.encode().unwrap()).unwrap();
        assert_eq!(decoded, expected);
    }

    #[test]
    fn restart_is_a_public_operator_verb() {
        let request = RequestEnvelope::decode(
            r#"{"v":1,"id":"req-1","verb":"restart","args":{},"token":null}"#,
        )
        .unwrap()
        .request;

        assert!(matches!(request, Request::Restart(_)));
        assert_eq!(request.capability(), super::Capability::Operator);
    }

    #[test]
    fn malformed_json_is_an_invalid_request() {
        let error = RequestEnvelope::decode("{").unwrap_err();
        assert_eq!(error.body.code, ErrorCode::InvalidRequest);
    }

    #[test]
    fn unsupported_versions_have_a_stable_error_code() {
        let error = RequestEnvelope::decode(
            r#"{"v":2,"id":"req-1","verb":"status","args":{},"token":null}"#,
        )
        .unwrap_err();

        assert_eq!(error.body.code, ErrorCode::UnsupportedVersion);
        assert_eq!(error.body.details["received"], 2);
    }

    #[test]
    fn unknown_verbs_have_a_stable_error_code() {
        let error = RequestEnvelope::decode(
            r#"{"v":1,"id":"req-1","verb":"merge","args":{},"token":null}"#,
        )
        .unwrap_err();

        assert_eq!(error.body.code, ErrorCode::UnknownVerb);
        assert_eq!(error.body.details["verb"], "merge");
    }

    #[test]
    fn known_verbs_reject_invalid_arguments() {
        let error = RequestEnvelope::decode(
            r#"{"v":1,"id":"req-1","verb":"show","args":{"unknown":true},"token":"token"}"#,
        )
        .unwrap_err();

        assert_eq!(error.body.code, ErrorCode::InvalidRequest);
    }

    #[test]
    fn show_accepts_additive_dashboard_pattern_and_limit_arguments() {
        for args in [r#"{}"#, r#"{"ref":"log","limit":5}"#] {
            let request = RequestEnvelope::decode(&format!(
                r#"{{"v":1,"id":"req-1","verb":"show","args":{args},"token":null}}"#
            ))
            .expect("decode show request");
            assert!(matches!(request.request, Request::Show(_)));
        }
    }

    #[test]
    fn response_envelopes_have_exclusive_success_and_error_payloads() {
        let success = serde_json::to_value(ResponseEnvelope::success(
            Some(RequestId::new("req-1")),
            json!({"paused": false}),
        ))
        .unwrap();
        assert_eq!(
            success,
            json!({"id": "req-1", "ok": true, "data": {"paused": false}})
        );

        let failure = serde_json::to_value(ResponseEnvelope::failure(
            Some(RequestId::new("req-2")),
            ErrorBody {
                code: ErrorCode::Conflict,
                message: "ticket is already claimed".into(),
                details: json!({"ticket": "T1"}),
            },
        ))
        .unwrap();
        assert_eq!(
            failure,
            json!({
                "id": "req-2",
                "ok": false,
                "error": {
                    "code": "conflict",
                    "message": "ticket is already claimed",
                    "details": {"ticket": "T1"}
                }
            })
        );
    }
}