hws 0.3.0

Heyo Web Services SDK: create and manage workloads on app-lb, read their telemetry, and the `heyctl` CLI
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
//! The wire contract between app-lb and this crate.
//!
//! `src/types.rs` promises these tests exist; until now they did not, and the
//! `extra` maps were carried without anything asserting on them. The fixtures in
//! `../testdata/wire/*.json` are written by app-lb's *own* response types
//! (`app-lb/src/wire_golden.rs`), so parsing one here and finding `extra` empty
//! is the only check that this crate still understands every field the server
//! sends.
//!
//! Leniency is what makes the check necessary rather than redundant: to a
//! defaulting deserializer an unknown field and an absent one are identical, so
//! a field that disappears from this crate's structs breaks nothing and blanks a
//! column. `extra` turns that into a failing test.
//!
//! Regenerate the fixtures with:
//!   `UPDATE_GOLDEN=1 cargo test -p app-lb wire_golden`

use hws::types::{
    ArtifactStoreInfo, AuthProviderView, CreatedPostgresDatabase, DeletedPostgresDatabase, DeploymentSpec, DeploymentStatus, DiskInventory, DiskState, JobRecord, MetricsResponse, NamespacePlugin, PluginInstalls, PluginView, PostgresDatabases,
    UpstreamTrafficStatus, WorkflowList, WorkflowView,
};
use std::path::PathBuf;

fn fixture(name: &str) -> String {
    let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .expect("heyctl lives inside the app-lb workspace")
        .join("testdata")
        .join("wire")
        .join(format!("{name}.json"));
    std::fs::read_to_string(&path).unwrap_or_else(|e| {
        panic!(
            "{}: {e}\nrun `UPDATE_GOLDEN=1 cargo test -p app-lb wire_golden`",
            path.display()
        )
    })
}

/// The check that matters: every field app-lb sends has a name here.
#[test]
fn workflow_view_understands_every_field() {
    let w: WorkflowView = serde_json::from_str(&fixture("workflow")).expect("fixture parses");

    assert!(
        w.extra.is_empty(),
        "heyctl does not understand these fields app-lb sends: {:?}\n\
         Add them to WorkflowView in src/types.rs.",
        w.extra.keys().collect::<Vec<_>>()
    );

    // And the values actually landed, rather than defaulting past a rename.
    assert_eq!(w.id, "build");
    assert_eq!(w.git_ref, "main", "`ref` on the wire, `git_ref` in Rust");
    assert_eq!(w.path, ".ci/workflows/*.yml");
    assert_eq!(w.network, "prod-runners");
    assert!(w.auth.is_some(), "a SecretRef must survive as an opaque value");
    assert_eq!(w.secrets_prefix.as_deref(), Some("ci/app"));
    assert!(w.enabled);
}

/// The listing the `ci` orchestrator polls. Enveloped, so the envelope needs its
/// own check — a bare-array assumption here would fail at runtime, not compile
/// time.
#[test]
fn workflow_list_understands_every_field() {
    let list: WorkflowList = serde_json::from_str(&fixture("workflow-list")).expect("parses");
    assert!(
        list.extra.is_empty(),
        "unknown fields on the list envelope: {:?}",
        list.extra.keys().collect::<Vec<_>>()
    );
    assert_eq!(list.workflows.len(), 1);
    assert!(list.workflows[0].extra.is_empty());
    assert_eq!(list.workflows[0].id, "build");
}

/// A minimal object gets its defaults filled server-side, so the client must see
/// them rather than empty strings.
#[test]
fn a_minimal_workflow_arrives_with_its_defaults_filled() {
    let w: WorkflowView = serde_json::from_str(&fixture("workflow-minimal")).expect("parses");
    assert!(w.extra.is_empty(), "{:?}", w.extra.keys().collect::<Vec<_>>());
    assert_eq!(w.git_ref, "main");
    assert_eq!(w.path, ".ci/workflows/*.yml");
    assert!(w.enabled);
    assert!(w.auth.is_none());
}

/// Leniency itself: a *newer* server sending a field this build has no name for
/// must still parse, and the unknown field must be reachable rather than
/// discarded. That is the property the `extra` map buys.
#[test]
fn an_unknown_field_parses_and_is_reachable() {
    let mut value: serde_json::Value =
        serde_json::from_str(&fixture("workflow")).expect("fixture parses");
    value["concurrency_group"] = serde_json::json!("prod");

    let w: WorkflowView = serde_json::from_value(value).expect("a newer server still parses");
    assert_eq!(w.id, "build", "the known fields still land");
    assert_eq!(
        w.extra.get("concurrency_group").and_then(|v| v.as_str()),
        Some("prod"),
        "an unknown field must be reachable, not dropped"
    );
}

#[test]
fn upstream_traffic_status_understands_every_field() {
    let status: UpstreamTrafficStatus =
        serde_json::from_str(&fixture("upstream-traffic-status")).expect("fixture parses");
    assert!(
        status.extra.is_empty(),
        "unknown upstream traffic fields: {:?}",
        status.extra.keys().collect::<Vec<_>>()
    );
    assert_eq!(status.deployment_id, "stage");
    assert_eq!(status.upstream, "us1.example.com:443");
    assert_eq!(status.state, "draining");
    assert!(status.healthy);
    assert_eq!(status.in_flight, 3);
    assert_eq!(status.reason.as_deref(), Some("regional maintenance"));
    assert_eq!(status.started_at, Some(1_722_400_000));
}

/// The disk inventory `heyctl get disks` renders.
///
/// Checked field-by-field rather than only through `extra`, because this
/// response is the one an operator reads while deciding whether gigabytes are
/// safe to delete. A blanked column here is not a cosmetic regression: `held_by`
/// going missing turns "never reclaim this" into an empty cell, and the two size
/// fields disagreeing by design means silently rendering the wrong one
/// misreports how full the host actually is.
#[test]
fn disk_inventory_understands_every_field() {
    let inv: DiskInventory = serde_json::from_str(&fixture("disks")).expect("fixture parses");
    assert!(
        inv.extra.is_empty(),
        "unknown inventory fields: {:?}",
        inv.extra.keys().collect::<Vec<_>>()
    );
    assert!(inv.complete);
    assert_eq!(inv.data_dir, "/var/lib/heyo");
    assert_eq!(inv.ttl_secs, 604_800);
    assert_eq!(inv.totals.disks, 3);
    // The free-space block, which is what turns "here are the disks" into "and
    // that is why a create just failed". A fixture below the floor, so the
    // pressure path has a shape a client can render.
    assert_eq!(inv.free_bytes, Some(12_884_901_888));
    assert_eq!(inv.filesystem_bytes, Some(536_870_912_000));
    // The orphan clock is the policy that matters here, and it must survive the
    // wire: an orphan is the disk of a VM that never created, and retaining a
    // copy of that on the seven-day TTL is the leak this separates out.
    assert!(inv.orphan_ttl_secs > 0, "the orphan TTL must survive the wire");
    assert!(
        inv.orphan_ttl_secs < inv.ttl_secs,
        "an orphan must expire sooner than a recoverable disk, not later",
    );
    assert_eq!(inv.totals.reclaimable_bytes, 2_147_483_648);
    assert!(
        inv.totals.extra.is_empty(),
        "unknown totals fields: {:?}",
        inv.totals.extra.keys().collect::<Vec<_>>()
    );

    assert_eq!(inv.disks.len(), 3);
    for d in &inv.disks {
        assert!(
            d.extra.is_empty(),
            "unknown disk fields on {}: {:?}",
            d.sandbox_id,
            d.extra.keys().collect::<Vec<_>>()
        );
        for p in &d.parts {
            assert!(
                p.extra.is_empty(),
                "unknown disk-part fields: {:?}",
                p.extra.keys().collect::<Vec<_>>()
            );
        }
    }

    // The running disk: claimed, held, and sparse — the case where the two size
    // columns differ by 8x and reporting either alone would mislead.
    let running = &inv.disks[0];
    assert_eq!(running.sandbox_id, "sb-1a2b3c4d");
    assert_eq!(running.deployment.as_deref(), Some("web"));
    assert_eq!(running.state, DiskState::Running);
    assert!(running.claimed);
    assert_eq!(running.bytes, 1_073_741_824);
    assert_eq!(running.apparent_bytes, 8_589_934_592);
    assert_eq!(running.held_by.as_deref(), Some("in use by a running sandbox"));
    assert_eq!(running.parts.len(), 2);
    assert_eq!(running.roots, vec!["run/sb-1a2b3c4d".to_string()]);

    // The orphan: no daemon record, nothing holding it, and an expiry the sweep
    // will act on. `held_by: None` is what makes it reclaimable.
    let orphan = &inv.disks[1];
    assert_eq!(orphan.state, DiskState::Orphan);
    assert_eq!(orphan.deployment, None);
    assert_eq!(orphan.held_by, None);
    assert_eq!(orphan.expires_at, Some(1_759_604_800));

    // The pinned one: an operator said never, which outranks any age.
    let pinned = &inv.disks[2];
    assert_eq!(pinned.state, DiskState::Stopped);
    assert!(pinned.retain);
    assert_eq!(pinned.note.as_deref(), Some("keeping for the incident postmortem"));
    assert_eq!(pinned.expires_at, None);
}

/// A state this build has never heard of must degrade, not blank the listing.
#[test]
fn an_unknown_disk_state_degrades_to_unknown() {
    let mut value: serde_json::Value =
        serde_json::from_str(&fixture("disks")).expect("fixture parses");
    value["disks"][0]["state"] = serde_json::json!("quiescing");

    let inv: DiskInventory = serde_json::from_value(value).expect("a newer server still parses");
    assert_eq!(inv.disks[0].state, DiskState::Unknown);
    assert_eq!(inv.disks[1].state, DiskState::Orphan, "the other rows are unaffected");
}

/// `GET /metrics`, which had no contract test at all until now.
///
/// That gap was not theoretical. `AutoscaleCounts` was missing `boot_timeouts`
/// while app-lb had been sending it, so `heyctl describe` could not distinguish
/// the two ways a pool gets stuck at `ready: 0` — a guest that never becomes
/// healthy, and a VM that is never created. Both render as silence, and the
/// second one sends you to debug an image that never ran.
///
/// Asserting `extra` is empty at every level is what keeps that from recurring:
/// a lenient deserializer cannot tell an absent field from an unknown one, so
/// without this a field app-lb adds is simply never shown.
#[test]
fn metrics_response_understands_every_field() {
    let m: MetricsResponse =
        serde_json::from_str(&fixture("metrics-response")).expect("fixture parses");
    assert!(
        m.extra.is_empty(),
        "unknown metrics fields: {:?}",
        m.extra.keys().collect::<Vec<_>>()
    );
    assert!(
        m.global.extra.is_empty(),
        "unknown global-metrics fields: {:?}",
        m.global.extra.keys().collect::<Vec<_>>()
    );

    // The daemon block: the one field that says whether everything else here is
    // live or frozen. The fixture is the unreachable case on purpose.
    assert!(
        m.daemon.extra.is_empty(),
        "unknown daemon fields: {:?}",
        m.daemon.extra.keys().collect::<Vec<_>>()
    );
    assert!(!m.daemon.reachable, "the fixture records an unreachable daemon");
    assert!(
        m.daemon.last_error.as_deref().is_some_and(|e| e.contains("deployed-sandboxes")),
        "the reason must survive the wire, not just the boolean",
    );

    let a = &m.global.autoscale;
    assert!(
        a.extra.is_empty(),
        "unknown autoscale fields: {:?}",
        a.extra.keys().collect::<Vec<_>>()
    );
    assert_eq!(a.vms_created, 2);
    assert_eq!(a.boot_timeouts, 1, "the field that had gone missing");
    assert_eq!(a.create_failures, 1);
    assert_eq!(
        a.last_create_error.as_deref(),
        Some("api error (500): No space left on device"),
        "the reason a pool is stuck must survive the wire",
    );

    for d in &m.deployments {
        assert!(
            d.metrics.autoscale.extra.is_empty(),
            "unknown per-deployment autoscale fields: {:?}",
            d.metrics.autoscale.extra.keys().collect::<Vec<_>>()
        );
    }
}

/// Guest mounts, which are the one part of the VM template whose *absence* has a
/// consequence a client must be able to explain: a mount with no `digest` is a
/// deployment whose pool cannot start.
///
/// `VmSpec` carries no `extra` map — it is a spec mirror rather than a response
/// envelope — so this asserts the values landed instead. A rename or a dropped
/// field shows up as a default here, which is exactly the silent-blank-column
/// failure this file exists to catch.
#[test]
fn guest_mounts_survive_the_wire() {
    let d: DeploymentStatus =
        serde_json::from_str(&fixture("deployment-status-vm")).expect("fixture parses");
    let vm = d.spec.vm.expect("the vm fixture has a template");

    assert_eq!(vm.mounts.len(), 1, "the mount must not be dropped");
    let m = &vm.mounts[0];
    assert_eq!(m.path, "/data/corpus");
    assert_eq!(m.store, "http://127.0.0.1:8080");
    assert_eq!(m.artifact_ref, "corpus-2026-08", "`ref` on the wire");
    assert_eq!(m.strip_components, Some(1));
    assert!(m.read_only, "the fixture's mount is read-only");
    assert!(m.auth.is_some(), "a SecretRef must survive as an opaque value");
    assert!(
        m.digest.as_deref().is_some_and(|d| d.len() == 64),
        "the resolved digest is what says which bytes the guests hold",
    );
    assert!(m.summary().contains("/data/corpus"));
}

/// The third kind of pull, whose result lives in `mounts` rather than in
/// `image` — so a client that only understood the other two would render a mount
/// pull as a job that did nothing.
#[test]
fn a_mount_pull_reports_every_mount() {
    let j: JobRecord = serde_json::from_str(&fixture("job-mount-pull")).expect("fixture parses");

    assert!(j.is_mount_pull(), "kind is `mount-pull`, not `artifact-pull`");
    assert_eq!(j.mounts.len(), 2);

    let fetched = &j.mounts[0];
    assert_eq!(fetched.path, "/data/corpus");
    assert_eq!(fetched.artifact_ref, "corpus-2026-08", "`ref` on the wire");
    assert_eq!(fetched.files, Some(1_204));
    assert_eq!(fetched.bytes, Some(734_003_200));
    assert_eq!(fetched.unpacked, Some(2_147_483_648));
    assert!(fetched.changed, "this one moved the pool");
    assert!(fetched.tree.is_some());

    // The common case, and the one whose rendering must not read as an error:
    // the tree was already on this host, so nothing was fetched or unpacked.
    let reused = &j.mounts[1];
    assert!(reused.reused);
    assert!(!reused.changed);
    assert_eq!(reused.bytes, Some(0));
    assert_eq!(reused.files, None, "nothing was unpacked, which is not zero files");

    assert_eq!(j.result_summary(), "1/2 updated");
    assert_eq!(j.target_summary(), "/data/corpus,/opt/models");
}

/// A JWT gate's verification policy, which is the one part of a spec whose
/// *misreading* is a security question: a client that dropped `require` would
/// render a restricted deployment as open to anyone the issuer signs for.
#[test]
fn a_jwt_gate_survives_the_wire() {
    let d: DeploymentStatus =
        serde_json::from_str(&fixture("deployment-status-jwt")).expect("fixture parses");
    let gate = d.spec.auth.expect("the fixture is gated");

    assert!(gate.accepts_jwt(), "the provider list carries `jwt`");
    assert!(
        gate.providers().iter().any(|p| p == "google"),
        "the fixture is the mixed gate: a person signs in, a program presents a token",
    );

    let jwt = gate.jwt.expect("the verification policy must not be dropped");
    assert_eq!(jwt.issuer, "auth-service");
    assert_eq!(jwt.audience.as_deref(), Some("heyo-app"));
    assert_eq!(jwt.algorithms, vec!["HS256"]);
    assert_eq!(jwt.subject_claim, "userId", "the Heyo auth API's subject is not `sub`");
    assert_eq!(jwt.cookie.as_deref(), Some("heyo_access_token"));
    assert_eq!(jwt.leeway_secs, Some(30));
    assert!(jwt.secret.is_some(), "a SecretRef must survive as an opaque value");

    // The claim map is the gate's allow-list, and it renders as one.
    assert_eq!(jwt.require.len(), 2);
    let summary = jwt.require_summary();
    assert!(summary.contains("role=user|admin"), "{summary}");
    assert!(summary.contains("accountId=acct_7f3c"), "{summary}");
    assert!(jwt.key_summary().contains("heyo-auth"), "{}", jwt.key_summary());
}

/// The auth provider object, in both shapes app-lb serialises it in.
#[test]
fn auth_provider_view_understands_every_field() {
    let heyo: AuthProviderView =
        serde_json::from_str(&fixture("auth-provider-heyo")).expect("fixture parses");
    assert!(
        heyo.extra.is_empty(),
        "heyctl does not understand these fields app-lb sends: {:?}\n\
         Add them to AuthProviderView in src/types.rs.",
        heyo.extra.keys().collect::<Vec<_>>()
    );
    assert_eq!(heyo.name, "heyo");
    assert_eq!(heyo.namespace, "team-a");
    assert_eq!(heyo.providers(), vec!["jwt".to_string()]);
    let jwt = heyo.jwt.as_ref().expect("a jwt provider carries its policy");
    assert_eq!(jwt.issuer, "auth-service");
    assert_eq!(jwt.subject_claim, "userId", "the Heyo auth API's subject is not `sub`");
    assert_eq!(heyo.admits(), "role=user|admin");
    assert_eq!(heyo.trust_summary(), "auth-service");

    let google: AuthProviderView =
        serde_json::from_str(&fixture("auth-provider-google")).expect("fixture parses");
    assert!(
        google.extra.is_empty(),
        "unknown fields on the google provider: {:?}",
        google.extra.keys().collect::<Vec<_>>()
    );
    assert_eq!(google.providers(), vec!["google".to_string()]);
    assert!(google.client_secret.is_some(), "a SecretRef must survive as a reference");
    assert_eq!(google.admits(), "@example.com");
    assert_eq!(google.cookie_domain.as_deref(), Some(".example.com"));
}

/// A gate that inherits its identity carries `provider_ref` and nothing else —
/// which only reads correctly if this crate knows the field exists.
#[test]
fn an_inherited_gate_names_the_provider_it_came_from() {
    // This fixture is a bare spec, not the status envelope a listing returns.
    let spec: DeploymentSpec =
        serde_json::from_str(&fixture("deployment-inherited-gate")).expect("fixture parses");
    let gate = spec.auth.as_ref().expect("the fixture has a gate");
    assert_eq!(gate.provider_ref.as_deref(), Some("corp-google"));
    assert_eq!(spec.namespace(), "team-a", "the provider is looked up in this namespace");
    assert!(gate.client_id.is_none(), "an inheriting gate carries no identity of its own");
}

/// The plugin list `heyctl plugins` renders.
#[test]
fn plugin_view_understands_every_field() {
    let plugins: Vec<PluginView> = serde_json::from_str(&fixture("plugins")).expect("fixture parses");
    for p in &plugins {
        assert!(
            p.extra.is_empty(),
            "heyctl does not understand these fields app-lb sends: {:?}\n\
             Add them to PluginView in src/types.rs.",
            p.extra.keys().collect::<Vec<_>>()
        );
    }
    let on = &plugins[0];
    assert_eq!(on.id, "example");
    assert!(on.enabled);
    assert_eq!(on.last_error.as_deref(), Some("connection refused"), "enabled and failing is a state");
    assert_eq!(on.config["url"], "http://127.0.0.1:34199");
    assert!(on.per_namespace);
    assert_eq!(on.installed_in, ["team-a"]);
    assert_eq!(on.dashboard.as_deref(), Some("ui"));
    assert!(plugins[1].dashboard.is_none());
    assert!(!plugins[1].enabled);
    assert!(!plugins[1].per_namespace);
}

/// What `heyctl plugins list -n` renders: both halves of "does this plugin
/// serve my namespace" — the operator's switch and the namespace's install.
#[test]
fn namespace_plugin_understands_every_field() {
    let plugins: Vec<NamespacePlugin> =
        serde_json::from_str(&fixture("namespace-plugins")).expect("fixture parses");
    for p in &plugins {
        assert!(
            p.extra.is_empty(),
            "unknown namespace plugin fields: {:?}",
            p.extra.keys().collect::<Vec<_>>()
        );
    }
    let obs = &plugins[0];
    assert_eq!(obs.id, "obs");
    assert!(obs.enabled && obs.installed);
    assert_eq!(obs.installed_at, Some(1_760_000_000));
    assert_eq!(obs.installed_by.as_deref(), Some("token:0123456789ab"));
    assert_eq!(obs.dashboard.as_deref(), Some("ui"));
    let other = &plugins[1];
    assert!(!other.enabled && !other.installed);
    assert!(other.installed_at.is_none() && other.config.is_none());
}

/// The install set app-obs polls to decide what to collect.
#[test]
fn plugin_installs_understands_every_field() {
    let i: PluginInstalls =
        serde_json::from_str(&fixture("plugin-installs")).expect("fixture parses");
    assert!(i.extra.is_empty(), "{:?}", i.extra.keys().collect::<Vec<_>>());
    assert_eq!(i.plugin, "obs");
    assert!(i.enabled);
    assert_eq!(i.namespaces, ["team-a", "team-b"]);
    for (ns, install) in &i.installs {
        assert!(install.extra.is_empty(), "{ns}: {:?}", install.extra.keys().collect::<Vec<_>>());
    }
    assert_eq!(i.installs["team-a"].installed_by.as_deref(), Some("user:u_123"));
    assert!(i.installs["team-b"].installed_by.is_none(), "the operator installs unattributed");
}

/// The request half of the contract for the workload routes: what this crate
/// *sends*, checked against a scripted transport. Needs `test-util`.
#[cfg(feature = "test-util")]
/// `GET /images` and `POST /images/sweep`, as app-lb writes them.
#[test]
fn the_image_inventory_reads_every_field() {
    use hws::{ImageInventory, ImageSweep};
    let inv: ImageInventory = serde_json::from_str(&fixture("images")).expect("fixture parses");
    assert!(inv.extra.is_empty(), "unmodelled: {:?}", inv.extra.keys().collect::<Vec<_>>());
    assert!(inv.complete);
    assert_eq!(inv.delete_supported, Some(true));
    assert_eq!((inv.cache_bytes, inv.cache_budget_bytes), (Some(0), Some(21_474_836_480)));
    assert_eq!((inv.cache_hits, inv.cache_misses), (4, 1));
    for i in &inv.images {
        assert!(i.extra.is_empty(), "{}: unmodelled {:?}", i.name, i.extra.keys().collect::<Vec<_>>());
    }
    let pulled = inv.images.iter().find(|i| i.name == "img-c74abee2ce8409f1").unwrap();
    assert_eq!(pulled.source, "pull");
    assert_eq!(pulled.artifact_ref.as_deref(), Some("heyo/alpine:3.24"));
    assert_eq!(
        pulled.references.iter().map(ToString::to_string).collect::<Vec<_>>(),
        vec!["deployment/web", "rollout of web", "job job-1 of api"]
    );
    let gone = inv.images.iter().find(|i| i.tier == "offloaded").unwrap();
    assert!(!gone.present);
    assert!(gone.offloaded_to.as_deref().unwrap().contains("app-lb-offload:"));

    let sweep: ImageSweep = serde_json::from_str(&fixture("images-sweep")).expect("fixture parses");
    assert_eq!(sweep.offloaded, vec!["img-0000000000000000"]);
    assert_eq!(sweep.failed[0].0, "img-1111111111111111");
}

mod requests {
    use hws::Client;

    /// The image routes send what app-lb's routes take.
    #[tokio::test]
    async fn image_requests_have_the_routes_shapes() {
        let (c, stub) = client(
            Stub::new()
                .json(200, json!({"images": []}))
                .json(200, json!({"offloaded": [], "failed": []}))
                .json(200, json!({"name": "img-a"}))
                .json(200, json!({"name": "img-a", "pinned": true}))
                .reply(204, ""),
        );
        c.images().await.unwrap();
        c.sweep_images().await.unwrap();
        c.offload_image("img-a").await.unwrap();
        assert!(c.pin_image("img-a", true).await.unwrap().pinned);
        c.delete_image("img-a").await.unwrap();
        let calls = stub.calls();
        let seen: Vec<_> = calls.iter().map(|c| (c.method, c.path.as_str())).collect();
        assert_eq!(
            seen,
            vec![
                (Method::Get, "/images"),
                (Method::Post, "/images/sweep"),
                (Method::Post, "/images/img-a/offload"),
                (Method::Patch, "/images/img-a"),
                (Method::Delete, "/images/img-a"),
            ]
        );
        assert_eq!(calls[3].body, Some(json!({"pinned": true})));
    }
    use hws::transport::Method;
    use hws::transport::stub::Stub;
    use serde_json::json;
    use std::sync::Arc;

    fn client(stub: Stub) -> (Client, Arc<Stub>) {
        let stub = Arc::new(stub);
        (Client::with_transport(stub.clone()), stub)
    }

    /// A namespace token cannot read `GET /jobs/:id` on older app-lbs, so a
    /// waiter told the deployment polls that deployment's job list instead.
    #[tokio::test]
    async fn a_job_is_waited_on_through_its_deployment() {
        let rec = |status: &str| {
            json!([
                {"id": "job-other", "deployment": "web", "kind": "artifact-pull", "status": "succeeded",
                 "started_at": 1, "finished_at": 2, "log": []},
                {"id": "job-1", "deployment": "web", "kind": "artifact-pull", "status": status,
                 "started_at": 1, "finished_at": null, "log": ["pulling"]}
            ])
        };
        let (c, stub) = client(Stub::new().json(200, rec("running")).json(200, rec("succeeded")));
        let done = c
            .wait_for_job("job-1")
            .in_deployment("web")
            .poll_every(std::time::Duration::from_millis(1))
            .await
            .unwrap();
        assert_eq!(done.status, "succeeded");
        let paths: Vec<_> = stub.calls().into_iter().map(|c| (c.method, c.path)).collect();
        assert_eq!(paths, vec![(Method::Get, "/deployments/web/jobs".to_string()); 2]);

        let (c, _) = client(Stub::new().json(200, json!([])));
        let gone = c.wait_for_job("job-9").in_deployment("web").await.unwrap_err();
        assert!(matches!(gone, hws::Error::NotFound { .. }), "{gone:?}");
    }

    /// The shape app-lb's `/whoami` answers a namespace token with, and the
    /// namespace a command may therefore assume.
    #[tokio::test]
    async fn whoami_names_the_namespace_a_token_is_confined_to() {
        let (c, stub) = client(
            Stub::new()
                .json(200, json!({
                    "caller": "app-token", "admin_scope": "admin", "fleet": false, "confined": true,
                    "may": {"read_view_routes": true, "use_admin_routes": true},
                    "token": {"id": "0123456789ab", "name": "ci"}, "namespace": "team-a",
                    "deployments": [], "expires_at": null, "expires_in_secs": null, "note": "…"
                }))
                .json(200, json!({
                    "caller": "federated", "admin_scope": "view", "fleet": false, "confined": true,
                    "may": {"read_view_routes": true, "use_admin_routes": false},
                    "subject": {"user_id": "u"}, "namespaces": {"a": "view", "b": "admin"}
                }))
                .json(200, json!({"caller": "operator", "admin_scope": "admin", "fleet": true, "confined": false})),
        );
        let me = c.whoami().await.unwrap();
        assert!(me.extra.is_empty(), "{:?}", me.extra.keys().collect::<Vec<_>>());
        assert_eq!(me.sole_namespace(), Some("team-a"));
        assert_eq!(me.token.unwrap().name, "ci");
        assert_eq!(c.whoami().await.unwrap().sole_namespace(), None, "two namespaces, none assumed");
        assert_eq!(c.whoami().await.unwrap().sole_namespace(), None, "the operator is everywhere");
        assert_eq!(stub.calls()[0].path, "/whoami");
    }

    #[tokio::test]
    async fn a_rollout_carries_its_idempotency_key_and_revision() {
        let op = json!({"operation_id": "op-1", "deployment": "web", "source_revision": "r1",
            "target_spec_sha256": "abc", "status": "running", "phase": "preparing",
            "readiness_verified": false, "previous_stopped": false, "error": null,
            "preparation_stage": null});
        let mut done = op.clone();
        done["status"] = json!("succeeded");
        let (c, stub) = client(Stub::new().json(202, op).json(200, done));
        let spec = json!({"id": "web", "vm": {"image": "x"}});
        let started = c.start_rollout("web", "op-1", "r1", &spec).await.unwrap();
        assert!(started.extra.is_empty(), "{:?}", started.extra.keys().collect::<Vec<_>>());
        assert!(!started.is_finished());
        assert!(c.rollout("web", "op-1").await.unwrap().is_finished());

        let calls = stub.calls();
        assert_eq!(calls[0].method, Method::Post);
        assert_eq!(calls[0].path, "/deployments/web/rollouts");
        assert_eq!(
            calls[0].body,
            Some(json!({"operation_id": "op-1", "expected_revision": "r1", "spec": spec}))
        );
        assert_eq!(calls[1].path, "/deployments/web/rollouts/op-1");
    }

    #[tokio::test]
    async fn discovery_status_is_camel_case_on_the_wire() {
        let (c, stub) = client(Stub::new().json(200, json!({
            "serviceId": "web", "version": 3,
            "upstreams": [{"peer": "10.0.0.2:8080", "draining": false, "inFlight": 2}]
        })));
        let s = c.discovery_status("web", true).await.unwrap();
        assert!(s.extra.is_empty(), "{:?}", s.extra.keys().collect::<Vec<_>>());
        assert_eq!(s.service_id, "web");
        assert_eq!(s.upstreams[0].in_flight, 2);
        assert_eq!(stub.calls()[0].path, "/deployments/web/discovery-status?staged=true");
    }
}

/// A fleet token as a member server lists it. `fleet` and `mirrored_from` are
/// what tell an operator where a token works and where it can be revoked.
#[test]
fn mirrored_token_summary_understands_every_field() {
    let t: hws::types::TokenSummary =
        serde_json::from_str(&fixture("token-summary-mirrored")).expect("fixture parses");
    assert!(
        t.extra.is_empty(),
        "heyctl does not understand these fields app-lb sends: {:?}\n\
         Add them to TokenSummary in src/types.rs.",
        t.extra.keys().collect::<Vec<_>>()
    );
    assert!(t.fleet);
    assert_eq!(t.mirrored_from.as_deref(), Some("us2"));
}

/// The postgres plugin's three answers, recorded from the plugin itself
/// (`src/plugins/postgres.rs`) rather than from a response type.
#[test]
fn postgres_plugin_answers_are_understood() {
    let list: PostgresDatabases =
        serde_json::from_str(&fixture("postgres-databases")).expect("fixture parses");
    assert!(
        list.extra.is_empty(),
        "unknown list fields: {:?}",
        list.extra.keys().collect::<Vec<_>>()
    );
    let db = &list.databases[0];
    assert!(
        db.extra.is_empty(),
        "unknown database fields: {:?}",
        db.extra.keys().collect::<Vec<_>>()
    );
    assert_eq!(
        (db.name.as_str(), db.database.as_str()),
        ("app", "ns_team_a_app")
    );
    assert_eq!(
        (db.live, db.secret.as_deref()),
        (Some(true), Some("pg-app"))
    );
    assert_eq!((list.port, list.limit), (6432, 2));

    let created: CreatedPostgresDatabase =
        serde_json::from_str(&fixture("postgres-database-created")).expect("fixture parses");
    assert!(
        created.extra.is_empty(),
        "unknown create fields: {:?}",
        created.extra.keys().collect::<Vec<_>>()
    );
    assert_eq!(created.password, "p@ss/w:rd");
    assert!(
        created
            .url
            .as_deref()
            .is_some_and(|u| u.starts_with("postgres://"))
    );
    assert_eq!(created.status, "provisioning");

    let deleted: DeletedPostgresDatabase =
        serde_json::from_str(&fixture("postgres-database-deleted")).expect("fixture parses");
    assert!(
        deleted.extra.is_empty(),
        "unknown delete fields: {:?}",
        deleted.extra.keys().collect::<Vec<_>>()
    );
    assert_eq!(deleted.deleted, "app");
    assert_eq!(deleted.secret_kept.as_deref(), Some("pg-app"));
}

/// The artifacts plugin's description of the store, recorded from the plugin
/// (`src/plugins/artifacts.rs`).
#[test]
fn artifact_store_info_is_understood() {
    let info: ArtifactStoreInfo =
        serde_json::from_str(&fixture("artifact-store-info")).expect("fixture parses");
    assert!(info.extra.is_empty(), "unknown fields: {:?}", info.extra.keys().collect::<Vec<_>>());
    assert!(info.available && info.writable);
    assert_eq!((info.namespace.as_str(), info.prefix.as_str()), ("team-a", "team-a/"));
}