lean-ctx 3.12.11

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported proxy integrations.
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
// SPDX-License-Identifier: Apache-2.0
//! `lean-ctx cloud computer runner add|list|remove`: GitHub Actions and
//! GitLab CI runners on LeanCTX computers, as LeanCTX Cloud runs them
//! (`/v1/runners`, [`lean_ctx_cloud::runners`]; Local Read kinds
//! `cloud.runners` and `cloud.runner.ack`, local-read-v1 §45).
//!
//! A runner binds an existing computer of the person's account or team:
//! LeanCTX Cloud registers it on that scope's live computer, which keeps its
//! own role and price. `remove` unbinds the runner; the computer stays.
//! `add` and `remove` run only with `--yes`. The forge's registration token
//! is read only after `--yes`, from standard input (`--token-stdin`) or a
//! hidden prompt, and goes only to the connected LeanCTX Cloud in the one
//! `add` request: never a flag, never printed, never logged, never stored.

use std::io::{BufRead, Read};

use serde::Serialize;
use serde_json::{Map, Value};
use zeroize::Zeroizing;

use lean_ctx_cloud::CloudStore;
use lean_ctx_cloud::computers::{self, Answer, Refusal};
use lean_ctx_cloud::config::CloudConfig;
use lean_ctx_cloud::runners::{
    self, AddRequest, MAX_LABELS, RegistrationToken, RunnerList, Target,
};
use lean_ctx_cloud::state::InstanceRecord;

use super::Args;
use super::cloud;
use super::ssh;
use crate::cli::local_read::{self, Code, Failure};

/// Local Read kind of the list.
pub(super) const KIND_LIST: &str = "cloud.runners";
/// Local Read kind of a write's answer.
pub(super) const KIND_ACK: &str = "cloud.runner.ack";
/// The longest line read from standard input for the token; the token is at
/// most 255 characters, so a longer line is refused as too long.
const MAX_TOKEN_LINE: u64 = 1024;

pub(super) const HELP: &str = "\
lean-ctx cloud computer runner — CI runners for GitHub and GitLab on LeanCTX computers

USAGE:
  lean-ctx cloud computer runner add (--gitlab https://<host> | --github <owner/repo>)
        [--name <name>] [--label <label>]… [--team <team id> | --personal]
        [--token-stdin] [--request-id <id>] [--yes] [--json]
  lean-ctx cloud computer runner list [--json]
  lean-ctx cloud computer runner remove <name|id> [--request-id <id>] [--yes] [--json]

add     Bind a runner to an existing LeanCTX computer of your team (--team, or
        the team this machine is connected to) or of your account (--personal).
        It registers with your GitLab server (the runner token decides the
        project or group) or your GitHub repository. --label sets runner labels
        (GitHub) or tags (GitLab). The default name is gl-<host> or gh-<repo>.
        The computer keeps its role and its price; the runner adds no cost of
        its own. add runs only with --yes; without it the command says what it
        would do and exits 1 (confirmation_required).
        The registration token is read after --yes: from standard input with
        --token-stdin, else at a hidden prompt. It goes only to the cloud over
        TLS, is never printed, logged or stored, and is never a command-line flag.
        Pass it from a file or a secret store (--token-stdin < file), not with
        `echo <token> |`, which can leave it in your shell history.
list    Your runners; --json prints cloud.runners.
remove  Unbind the runner and deregister it from the forge; the computer stays
        (needs --yes). --json prints cloud.runner.ack.

The cloud decides who may do this and on which computer.
";

/// `cloud computer runner …`; `args.positionals` is `["runner", verb, …]`.
pub(super) fn run(args: &Args) {
    let json = args.json();
    let verb = args.positionals.get(1).map_or("help", String::as_str);
    if verb == "help" {
        print!("{HELP}");
        return;
    }
    let result = match verb {
        "add" | "list" | "remove" => cloud::connected().and_then(|(store, config, instance)| {
            let ctx = Ctx {
                store: &store,
                config: &config,
                instance: &instance,
                args,
            };
            match verb {
                "add" => add(&ctx),
                "list" => list(&ctx),
                _ => remove(&ctx),
            }
        }),
        other => Err(Failure::invalid(format!(
            "unknown runner subcommand '{other}' (add, list, remove)"
        ))),
    };
    if let Err(failure) = result {
        if json {
            local_read::fail(&failure);
        }
        eprintln!("cloud computer runner: {}", failure.message);
        std::process::exit(failure.code.exit_status());
    }
}

/// One runner command on the connected instance.
struct Ctx<'a> {
    store: &'a CloudStore,
    config: &'a CloudConfig,
    instance: &'a InstanceRecord,
    args: &'a Args,
}

/// `cloud.runners`: the cloud's rows, passed on. No balance (a runner costs
/// nothing beyond its computer) and no local clock (#498).
#[derive(Debug, Serialize, PartialEq)]
struct ListDoc {
    /// `false`: this cloud does not offer runners (its `503 not_configured`).
    available: bool,
    runners: Vec<Map<String, Value>>,
}

fn list_doc(answer: Answer<RunnerList>) -> Result<ListDoc, Failure> {
    match answer {
        Answer::Done(list) => Ok(ListDoc {
            available: true,
            runners: list.runners,
        }),
        Answer::NotOffered => Ok(ListDoc {
            available: false,
            runners: Vec::new(),
        }),
        Answer::Refused(refusal) => Err(refused(&refusal)),
    }
}

fn fetch_list(ctx: &Ctx<'_>) -> Result<RunnerList, Failure> {
    let send = computers::connected(ctx.store, ctx.config);
    match runners::list(&send).map_err(Failure::from)? {
        Answer::Done(list) => Ok(list),
        Answer::NotOffered => Err(not_offered()),
        Answer::Refused(refusal) => Err(refused(&refusal)),
    }
}

fn list(ctx: &Ctx<'_>) -> Result<(), Failure> {
    let send = computers::connected(ctx.store, ctx.config);
    let doc = list_doc(runners::list(&send).map_err(Failure::from)?)?;
    if ctx.args.json() {
        local_read::emit(KIND_LIST, || Ok(doc));
        return Ok(());
    }
    if !doc.available {
        println!("The Cloud does not offer CI runners yet.");
        return Ok(());
    }
    if doc.runners.is_empty() {
        println!(
            "no CI runner yet (lean-ctx cloud computer runner add --github <owner/repo> | --gitlab https://<host>)"
        );
    }
    for row in &doc.runners {
        let text = |k: &str| row.get(k).and_then(Value::as_str).unwrap_or("-");
        let runner = |k: &str| {
            row.get("runner")
                .and_then(|r| r.get(k))
                .and_then(Value::as_str)
                .unwrap_or("-")
        };
        println!(
            "{:<20} {:<7} {:<32} {:<12} {:<14} {}",
            text("name"),
            runner("forge"),
            runner("target"),
            runner("status"),
            text("state"),
            text("id")
        );
    }
    Ok(())
}

/// `cloud.runner.ack`: what the cloud did with a write. `state` and `role`
/// are the computer's; `status` is the runner's (`pending`, `registered`,
/// `removed`, …).
#[derive(Debug, Serialize, PartialEq)]
struct AckDoc {
    action: &'static str,
    id: Value,
    name: Value,
    state: Value,
    role: Value,
    forge: Value,
    target: Value,
    status: Value,
    registered: Value,
    request_id: String,
}

fn ack(
    action: &'static str,
    row: &Map<String, Value>,
    request_id: String,
    target: Option<&Target>,
) -> AckDoc {
    let pick = |k: &str| row.get(k).cloned().unwrap_or(Value::Null);
    let runner = |k: &str| {
        row.get("runner")
            .and_then(|r| r.get(k))
            .cloned()
            .unwrap_or(Value::Null)
    };
    let or_sent = |value: Value, sent: Option<&str>| match (value, sent) {
        (Value::Null, Some(sent)) => Value::String(sent.to_owned()),
        (value, _) => value,
    };
    AckDoc {
        action,
        id: pick("id"),
        name: pick("name"),
        state: pick("state"),
        role: pick("role"),
        forge: or_sent(runner("forge"), target.map(Target::forge)),
        target: or_sent(runner("target"), target.map(Target::target)),
        status: runner("status"),
        registered: runner("registered"),
        request_id,
    }
}

/// The target of `add`: exactly one of `--gitlab` and `--github`.
fn target_of(args: &Args) -> Result<Target, Failure> {
    match (args.value("--gitlab"), args.value("--github")) {
        (Some(_), Some(_)) => Err(Failure::invalid("give --gitlab or --github, not both")),
        (Some(url), None) => Target::gitlab(url).map_err(Failure::invalid),
        (None, Some(repo)) => Target::github(repo).map_err(Failure::invalid),
        (None, None) => Err(Failure::invalid(
            "name the forge: --gitlab https://<host> or --github <owner/repo>",
        )),
    }
}

fn labels_of(args: &Args) -> Result<Vec<String>, Failure> {
    let mut labels: Vec<String> = Vec::new();
    for label in args.all("--label") {
        if !runners::valid_label(label) {
            return Err(Failure::invalid(format!(
                "--label '{}': use 1-64 of A-Z, a-z, 0-9, _, . and -",
                label
                    .chars()
                    .filter(|c| !c.is_control())
                    .take(80)
                    .collect::<String>()
            )));
        }
        if !labels.iter().any(|l| l == label) {
            labels.push(label.to_owned());
        }
    }
    if labels.len() > MAX_LABELS {
        return Err(Failure::invalid(format!(
            "at most {MAX_LABELS} labels per runner"
        )));
    }
    Ok(labels)
}

/// The scope a runner binds: `--personal` (the person's account, also on a
/// machine connected to a team), `--team <team id>` (a slug is passed on as
/// given; LeanCTX Cloud resolves it), else the scope this machine is
/// connected to. `None` is the personal account.
fn scope_of(args: &Args, instance: &InstanceRecord) -> Result<Option<String>, Failure> {
    match (args.has("--personal"), args.value("--team")) {
        (true, Some(_)) => Err(Failure::invalid("give --team or --personal, not both")),
        (true, None) => Ok(None),
        (false, Some(team)) => {
            let ok = (1..=64).contains(&team.len())
                && team
                    .bytes()
                    .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'));
            if ok {
                Ok(Some(team.to_owned()))
            } else {
                Err(Failure::invalid(
                    "--team: give the team's id (or its slug), 1-64 of A-Z, a-z, 0-9, _ and -",
                ))
            }
        }
        (false, None) if instance.org_kind.as_deref() == Some("personal") => Ok(None),
        (false, None) => Ok(Some(instance.org_id.clone())),
    }
}

/// The request id: `--request-id` when given (checked), else a new one.
fn request_id(args: &Args) -> Result<String, Failure> {
    match args.value("--request-id") {
        Some(id) if computers::valid_request_id(id) => Ok(id.to_owned()),
        Some(_) => Err(Failure::invalid(
            "--request-id: use 8-64 of A-Z, a-z, 0-9, _ and -",
        )),
        None => Ok(computers::new_request_id()),
    }
}

fn confirmation(what: String) -> Failure {
    Failure::new(Code::ConfirmationRequired, what)
}

fn scope_text(team: Option<&str>, instance: &InstanceRecord) -> String {
    match team {
        None => "your account".to_owned(),
        Some(team) if team == instance.org_id => format!("team {}", instance.org_name),
        Some(team) => format!("team {team}"),
    }
}

fn add(ctx: &Ctx<'_>) -> Result<(), Failure> {
    let target = target_of(ctx.args)?;
    let labels = labels_of(ctx.args)?;
    let name = match ctx.args.value("--name") {
        Some(name) => name.to_owned(),
        None => target.default_name(),
    };
    ssh::check_name(&name).map_err(Failure::invalid)?;
    let team = scope_of(ctx.args, ctx.instance)?;
    let request_id = request_id(ctx.args)?;
    if !ctx.args.yes() {
        // Nothing is sent and no token is read.
        return Err(confirmation(format!(
            "add runner '{name}' for {} {}: binds it to the existing LeanCTX computer of {}; the computer keeps its role and price. Nothing was done; repeat with --yes to add it.",
            target.forge(),
            target.target(),
            scope_text(team.as_deref(), ctx.instance)
        )));
    }
    let token = read_token(ctx.args.has("--token-stdin"), &target)?;
    let request = AddRequest {
        request_id: request_id.clone(),
        name,
        team,
        target,
        labels,
    };
    let send = runners::connected_raw(ctx.store, ctx.config);
    let answer = runners::add(&send, &request, &token).map_err(Failure::from)?;
    drop(token);
    match answer {
        Answer::Done(row) => finish(ctx, &ack("add", &row, request_id, Some(&request.target))),
        Answer::NotOffered => Err(not_offered()),
        Answer::Refused(refusal) => Err(refused(&refusal)),
    }
}

fn remove(ctx: &Ctx<'_>) -> Result<(), Failure> {
    let wanted = ctx
        .args
        .positionals
        .get(2)
        .map(String::as_str)
        .ok_or_else(|| Failure::invalid("name the runner (or give its id)"))?;
    let by_id = runners::valid_id(wanted);
    if !by_id {
        ssh::check_name(wanted).map_err(Failure::invalid)?;
    }
    let request_id = request_id(ctx.args)?;
    if !ctx.args.yes() {
        return Err(confirmation(format!(
            "remove runner '{wanted}': deregisters it from the forge and unbinds it; the computer stays. Nothing was done; repeat with --yes to remove it."
        )));
    }
    let id = if by_id {
        wanted.to_owned()
    } else {
        let list = fetch_list(ctx)?;
        let row = cloud::pick(&list.runners, wanted, ctx.instance)?;
        row.get("id")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_owned()
    };
    let send = computers::connected(ctx.store, ctx.config);
    match runners::remove(&send, &id, &request_id).map_err(Failure::from)? {
        Answer::Done(answer) => finish(ctx, &ack("remove", &answer, request_id, None)),
        Answer::NotOffered => Err(not_offered()),
        Answer::Refused(refusal) => Err(refused(&refusal)),
    }
}

/// The registration token: the first line of standard input with
/// `--token-stdin` (at most [`MAX_TOKEN_LINE`] bytes), else a hidden prompt
/// on the terminal. Never echoed.
fn read_token(from_stdin: bool, target: &Target) -> Result<RegistrationToken, Failure> {
    let raw = if from_stdin {
        let mut line = Zeroizing::new(String::new());
        std::io::stdin()
            .lock()
            .take(MAX_TOKEN_LINE)
            .read_line(&mut line)
            .map_err(|e| Failure::invalid(format!("cannot read the token from stdin: {e}")))?;
        line
    } else if lean_ctx::core::host_env::stdin_is_terminal() {
        Zeroizing::new(
            rpassword::prompt_password("Runner registration token (input hidden): ").map_err(
                |e| Failure::invalid(format!("cannot read the token at the prompt: {e}")),
            )?,
        )
    } else {
        return Err(Failure::invalid(
            "give the registration token on standard input with --token-stdin (no terminal for a hidden prompt)",
        ));
    };
    token_of(&raw, target)
}

fn token_of(raw: &str, target: &Target) -> Result<RegistrationToken, Failure> {
    RegistrationToken::new(raw, target).map_err(Failure::invalid)
}

fn finish(ctx: &Ctx<'_>, doc: &AckDoc) -> Result<(), Failure> {
    if ctx.args.json() {
        local_read::emit(KIND_ACK, || Ok(doc));
        return Ok(());
    }
    let text = |v: &Value| v.as_str().unwrap_or("-").to_owned();
    println!(
        "{}: runner '{}' ({}) for {} {} is {}",
        doc.action,
        text(&doc.name),
        text(&doc.id),
        text(&doc.forge),
        text(&doc.target),
        text(&doc.status)
    );
    Ok(())
}

/// The cloud's refusal of a runner request: the runner codes LeanCTX Cloud
/// sends (local-read-v1 §45), else as for computers.
fn refused(refusal: &Refusal) -> Failure {
    let code = match refusal.code.as_str() {
        "step_up_required" => Some(Code::StepUpRequired),
        "runner_exists" => Some(Code::ComputerExists),
        "runner_token_rejected" => Some(Code::InvalidField),
        _ => None,
    };
    let mut failure = cloud::refused(refusal);
    if let Some(code) = code {
        failure.code = code;
    }
    failure
}

fn not_offered() -> Failure {
    Failure::new(Code::NotOffered, "The Cloud does not offer CI runners yet.")
}

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

    fn args(raw: &[&str]) -> Args {
        Args::parse(&raw.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>()).expect("args")
    }

    fn object(value: Value) -> Map<String, Value> {
        let Value::Object(map) = value else {
            panic!("not an object: {value}");
        };
        map
    }

    fn instance(kind: &str) -> InstanceRecord {
        serde_json::from_value(json!({
            "instance_id": "inst_1", "org_id": "8f0c1a52-1111-4222-8333-944455556666",
            "org_name": "Acme", "label": "mac", "url": "https://cloud.example",
            "org_salt_id": "salt", "enrolled_at": "2026-11-01T00:00:00Z",
            "org_kind": kind
        }))
        .expect("instance")
    }

    fn refusal(status: u16, code: &str, reason: Option<&str>) -> Refusal {
        Refusal {
            status,
            code: code.to_owned(),
            message: Some("no".to_owned()),
            next_step: None,
            retry_after_s: None,
            details: None,
            reason: reason.map(str::to_owned),
        }
    }

    #[test]
    fn the_target_is_exactly_one_forge() {
        let gl = target_of(&args(&[
            "runner",
            "add",
            "--gitlab",
            "https://gitlab.example.com",
        ]))
        .expect("gitlab");
        assert_eq!(gl.forge(), "gitlab");
        let gh = target_of(&args(&["runner", "add", "--github", "leanctx/lean-ctx"])).expect("gh");
        assert_eq!(gh.target(), "leanctx/lean-ctx");
        let both = target_of(&args(&[
            "runner",
            "add",
            "--gitlab",
            "https://g.example",
            "--github",
            "o/r",
        ]))
        .expect_err("both");
        assert_eq!(both.code, Code::InvalidArgument);
        assert!(target_of(&args(&["runner", "add"])).is_err());
        assert!(target_of(&args(&["runner", "add", "--gitlab", "http://g.example"])).is_err());
    }

    #[test]
    fn a_token_is_never_a_flag() {
        for raw in [
            vec!["runner", "add", "--token", "glrt-SECRET-123456"],
            vec!["runner", "add", "--token=glrt-SECRET-123456"],
        ] {
            let raw: Vec<String> = raw.iter().map(|s| (*s).to_owned()).collect();
            let err = Args::parse(&raw).expect_err("refused");
            assert!(!err.contains("SECRET"), "{err}");
        }
    }

    #[test]
    fn a_bad_token_message_never_repeats_it() {
        let gitlab = Target::gitlab("https://gitlab.example.com").expect("gl");
        let failure = token_of("glrt SECRET with spaces", &gitlab).expect_err("bad");
        assert_eq!(failure.code, Code::InvalidArgument);
        assert!(!failure.message.contains("SECRET"));
        assert!(token_of("glrt-SECRET-1234567890\n", &gitlab).is_ok());
        let github = Target::github("o/r").expect("gh");
        assert!(token_of("glrt-SECRET-1234567890", &github).is_err());
    }

    #[test]
    fn labels_are_checked_and_deduplicated() {
        let labels = labels_of(&args(&[
            "runner", "add", "--label", "linux", "--label", "x64", "--label", "linux",
        ]))
        .expect("labels");
        assert_eq!(labels, ["linux", "x64"]);
        assert!(labels_of(&args(&["runner", "add", "--label", "a b"])).is_err());
        let many: Vec<String> = (0..=MAX_LABELS)
            .flat_map(|i| ["--label".to_owned(), format!("l{i}")])
            .collect();
        let mut raw = vec!["runner".to_owned(), "add".to_owned()];
        raw.extend(many);
        assert!(labels_of(&Args::parse(&raw).expect("args")).is_err());
    }

    #[test]
    fn the_scope_is_personal_a_team_or_the_connected_one() {
        let team = instance("team");
        let personal = instance("personal");
        assert_eq!(
            scope_of(&args(&["runner", "add", "--personal"]), &team).expect("personal"),
            None
        );
        assert_eq!(
            scope_of(&args(&["runner", "add", "--team", "acme-dev"]), &personal).expect("slug"),
            Some("acme-dev".to_owned())
        );
        assert_eq!(
            scope_of(&args(&["runner", "add"]), &team).expect("connected"),
            Some(team.org_id.clone())
        );
        assert_eq!(
            scope_of(&args(&["runner", "add"]), &personal).expect("mine"),
            None
        );
        assert!(
            scope_of(
                &args(&["runner", "add", "--personal", "--team", "x"]),
                &team
            )
            .is_err()
        );
        assert!(scope_of(&args(&["runner", "add", "--team", "a/b"]), &team).is_err());
        assert_eq!(scope_text(Some(&team.org_id), &team), "team Acme");
        assert_eq!(scope_text(None, &team), "your account");
    }

    #[test]
    fn the_ack_names_the_runner_status_and_carries_no_billing() {
        let row = object(json!({
            "id": "cmp_9", "name": "gh-lean-ctx", "state": "running", "role": "general",
            "runner": { "status": "pending", "registered": false }
        }));
        let target = Target::github("leanctx/lean-ctx").expect("gh");
        let doc = ack("add", &row, "req_12345678".into(), Some(&target));
        let value = serde_json::to_value(&doc).expect("json");
        assert_eq!(value["forge"], "github");
        assert_eq!(value["target"], "leanctx/lean-ctx");
        assert_eq!(value["status"], "pending");
        assert_eq!(value["registered"], false);
        assert!(value.get("billing").is_none());
        let gone = object(
            json!({ "id": "cmp_9", "name": "gh-lean-ctx", "state": "running",
            "runner": { "status": "removed" } }),
        );
        let value =
            serde_json::to_value(ack("remove", &gone, "req_12345678".into(), None)).expect("json");
        assert_eq!(value["status"], "removed");
        assert_eq!(value["state"], "running", "the computer stays");
        assert_eq!(value["forge"], Value::Null);
    }

    #[test]
    fn runner_refusals_have_their_codes() {
        assert_eq!(
            refused(&refusal(403, "step_up_required", None)).code,
            Code::StepUpRequired
        );
        assert_eq!(
            refused(&refusal(409, "runner_exists", None)).code,
            Code::ComputerExists
        );
        assert_eq!(
            refused(&refusal(422, "runner_token_rejected", None)).code,
            Code::InvalidField
        );
        assert_eq!(
            refused(&refusal(409, "invalid_state", Some("runner_limit"))).code,
            Code::InvalidState
        );
        assert_eq!(
            refused(&refusal(404, "no_computer", None)).code,
            Code::NoComputer
        );
        let failure = refused(&refusal(403, "step_up_required", None));
        assert!(
            failure.message.contains("step_up_required"),
            "{}",
            failure.message
        );
        assert_eq!(Code::StepUpRequired.as_str(), "step_up_required");
        assert_eq!(not_offered().code, Code::NotOffered);
    }

    #[test]
    fn a_cloud_without_runners_lists_none_and_no_balance() {
        let doc = list_doc(Answer::NotOffered).expect("doc");
        assert!(!doc.available);
        assert!(doc.runners.is_empty());
        let done = list_doc(Answer::Done(RunnerList {
            runners: vec![object(
                json!({ "id": "cmp_1", "name": "gl-x", "state": "running" }),
            )],
        }))
        .expect("doc");
        assert!(done.available);
        assert_eq!(done.runners.len(), 1);
        let value = serde_json::to_value(&done).expect("json");
        assert!(value.get("balance").is_none());
        assert!(value.get("as_of").is_none());
    }
}