alien-core 3.3.65

Deploy software into your customers' cloud accounts and keep it fully managed
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
//! Command-target discovery and the command env-var injection helpers for
//! [`Stack`]. Workers receive authenticated platform pushes; Containers and
//! Daemons run the pull receiver. Both are derived from the same ordered
//! [`Stack::command_targets`] list.

use crate::error::{ErrorData, Result};
use crate::{EnvironmentVariable, EnvironmentVariableType, Stack};
use alien_error::AlienError;

/// Builds a single [`EnvironmentVariable`] scoped to exactly one resource.
///
/// Every command env var is scoped via `target_resources` so it reaches only
/// its own resource; this collapses the otherwise-verbatim struct literals in
/// the polling/receiver builders below into one place.
fn scoped(
    name: &str,
    value: impl Into<String>,
    var_type: EnvironmentVariableType,
    target_id: &str,
) -> EnvironmentVariable {
    EnvironmentVariable {
        name: name.to_string(),
        value: value.into(),
        var_type,
        target_resources: Some(vec![target_id.to_string()]),
    }
}

impl Stack {
    /// Returns the ordered list of command-capable targets in this stack:
    /// Worker, Container, and Daemon resources with `commands_enabled` set,
    /// in stack declaration order.
    ///
    /// Declaration order is the order resources were added to the stack
    /// (via `StackBuilder::add`/`add_with_dependencies`/`add_with_remote_access`).
    /// `resources` is an `IndexMap`, which preserves insertion order, so
    /// iterating it directly yields declaration order without any extra
    /// bookkeeping.
    pub fn command_targets(&self) -> Vec<crate::commands_types::CommandTarget> {
        use crate::commands_types::{CommandTarget, CommandTargetType};

        self.resources
            .iter()
            .filter_map(|(id, entry)| {
                if let Some(worker) = entry.config.downcast_ref::<crate::Worker>() {
                    worker
                        .commands_enabled
                        .then(|| CommandTarget::new(id.clone(), CommandTargetType::Worker))
                } else if let Some(container) = entry.config.downcast_ref::<crate::Container>() {
                    container
                        .commands_enabled
                        .then(|| CommandTarget::new(id.clone(), CommandTargetType::Container))
                } else if let Some(daemon) = entry.config.downcast_ref::<crate::Daemon>() {
                    daemon
                        .commands_enabled
                        .then(|| CommandTarget::new(id.clone(), CommandTargetType::Daemon))
                } else {
                    None
                }
            })
            .collect()
    }

    /// Whether `alien build` recorded that the command receiver of this
    /// Container or Daemon reads `ALIEN_COMMANDS_CAPABILITY_FILE`
    /// (`commands_capability_file`). Everything else is treated as a receiver
    /// from an older build: it needs `ALIEN_COMMANDS_TOKEN` to start. This is
    /// the one place that rule lives; deployers and token revocation use it.
    pub fn command_receiver_reads_capability_file(&self, resource_id: &str) -> bool {
        let Some(entry) = self.resources.get(resource_id) else {
            return false;
        };
        if let Some(container) = entry.config.downcast_ref::<crate::Container>() {
            container.commands_capability_file
        } else if let Some(daemon) = entry.config.downcast_ref::<crate::Daemon>() {
            daemon.commands_capability_file
        } else {
            false
        }
    }

    /// Ids of the command-enabled Containers and Daemons whose receiver is not
    /// recorded as reading the capability file. While any exists, the
    /// deployment token must stay valid: those receivers cannot start without it.
    pub fn command_receivers_without_capability_file(&self) -> Vec<String> {
        use crate::commands_types::CommandTargetType;

        self.command_targets()
            .into_iter()
            .filter(|target| {
                matches!(
                    target.resource_type,
                    CommandTargetType::Container | CommandTargetType::Daemon
                )
            })
            .map(|target| target.resource_id)
            .filter(|id| !self.command_receiver_reads_capability_file(id))
            .collect()
    }

    /// Returns the authentication token used by the manager/operator to push
    /// commands to each command-enabled Local/Kubernetes Worker runtime.
    /// Cloud-native Worker transports authenticate through their platform and
    /// do not use this helper.
    pub fn worker_command_push_env_vars(
        &self,
        commands_token: Option<&str>,
    ) -> Result<Vec<EnvironmentVariable>> {
        use crate::commands_types::CommandTargetType;

        let mut vars = Vec::new();
        for target in self
            .command_targets()
            .into_iter()
            .filter(|target| target.resource_type == CommandTargetType::Worker)
        {
            let id = target.resource_id;
            let token = require_command_token(commands_token, &id)?;
            vars.push(scoped(
                crate::ENV_ALIEN_COMMANDS_TOKEN,
                token,
                EnvironmentVariableType::Secret,
                &id,
            ));
        }
        Ok(vars)
    }

    /// Returns the command *receiver* environment variables for each
    /// command-enabled Container and Daemon in this stack, scoped via
    /// `target_resources` so every var reaches only its own resource.
    ///
    /// Workers receive platform pushes; Containers and Daemons run the pull
    /// receiver, which reads this environment:
    ///   - `ALIEN_COMMANDS_URL` (Plain) — base receiver URL
    ///   - the credential, chosen per target by `credential`
    ///   - `ALIEN_COMMANDS_TARGET_RESOURCE_ID` (Plain) — this resource's id
    ///   - `ALIEN_COMMANDS_TARGET_RESOURCE_TYPE` (Plain) — `container`/`daemon`
    ///
    /// `ALIEN_DEPLOYMENT_ID` is intentionally NOT emitted here: the manager and
    /// operator already inject it deployment-wide (`target_resources: None`).
    ///
    /// Workers are excluded here, and a commands-disabled Container/Daemon is
    /// never a `command_targets()` entry, so it receives nothing.
    pub fn receiver_command_env_vars(
        &self,
        commands_url: &str,
        credential: impl Fn(&str) -> ReceiverCommandCredential,
    ) -> Result<Vec<EnvironmentVariable>> {
        use crate::commands_types::CommandTargetType;

        let mut vars = Vec::new();
        for target in self.command_targets().into_iter().filter(|target| {
            matches!(
                target.resource_type,
                CommandTargetType::Container | CommandTargetType::Daemon
            )
        }) {
            let resource_type = target.resource_type.as_str();
            let id = target.resource_id;
            vars.push(scoped(
                crate::ENV_ALIEN_COMMANDS_URL,
                commands_url,
                EnvironmentVariableType::Plain,
                &id,
            ));
            match credential(&id) {
                // Without a credential the receiver cannot start; fail the
                // deploy here, where the cause is nameable.
                ReceiverCommandCredential::Token(token) => vars.push(scoped(
                    crate::ENV_ALIEN_COMMANDS_TOKEN,
                    require_command_token(token.as_deref(), &id)?,
                    EnvironmentVariableType::Secret,
                    &id,
                )),
                ReceiverCommandCredential::HostFiles => vars.extend([
                    scoped(
                        crate::ENV_ALIEN_COMMANDS_CAPABILITY_FILE,
                        crate::HOST_COMMANDS_CAPABILITY_FILE,
                        EnvironmentVariableType::Plain,
                        &id,
                    ),
                    scoped(
                        crate::ENV_ALIEN_COMMANDS_TOKEN_FILE,
                        crate::HOST_COMMANDS_TOKEN_FILE,
                        EnvironmentVariableType::Plain,
                        &id,
                    ),
                ]),
            }
            vars.extend([
                scoped(
                    crate::ENV_ALIEN_COMMANDS_TARGET_RESOURCE_TYPE,
                    resource_type,
                    EnvironmentVariableType::Plain,
                    &id,
                ),
                scoped(
                    crate::ENV_ALIEN_COMMANDS_TARGET_RESOURCE_ID,
                    id.clone(),
                    EnvironmentVariableType::Plain,
                    &id,
                ),
            ]);
        }
        Ok(vars)
    }
}

/// How a Container or Daemon command receiver gets its credential.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReceiverCommandCredential {
    /// A bearer token in `ALIEN_COMMANDS_TOKEN`. `None` fails the deploy.
    Token(Option<String>),
    /// The machine that runs the workload writes a short-lived credential to
    /// `HOST_COMMANDS_CAPABILITY_FILE` and `HOST_COMMANDS_TOKEN_FILE` and
    /// refreshes it. No token is put into the workload's environment.
    HostFiles,
}

/// The deployment token, or a deploy-time error naming the command-enabled
/// resource that needs it — a runtime crash-loop on a missing env var is the
/// only alternative.
fn require_command_token<'a>(token: Option<&'a str>, resource_id: &str) -> Result<&'a str> {
    token
        .filter(|value| !value.trim().is_empty())
        .ok_or_else(|| {
            AlienError::new(ErrorData::CommandTokenMissing {
                resource_id: resource_id.to_string(),
                reason: "the deployment record carries no non-empty deployment token".to_string(),
            })
        })
}

#[cfg(test)]
mod tests {
    use super::ReceiverCommandCredential;
    use crate::resource::ResourceLifecycle;
    use crate::{
        Container, ContainerCode, Daemon, DaemonCode, ResourceSpec, Stack, Storage, Worker,
        WorkerCode,
    };

    #[test]
    fn command_targets_returns_only_commands_enabled_resources_in_declaration_order() {
        let worker_enabled = Worker::new("worker-a".to_string())
            .code(WorkerCode::Image {
                image: "worker:latest".to_string(),
            })
            .permissions("execution".to_string())
            .commands_enabled(true)
            .build();

        let container_disabled = Container::new("container-b".to_string())
            .code(ContainerCode::Image {
                image: "container:latest".to_string(),
            })
            .cpu(ResourceSpec {
                min: "0.5".to_string(),
                desired: "1".to_string(),
            })
            .memory(ResourceSpec {
                min: "512Mi".to_string(),
                desired: "1Gi".to_string(),
            })
            .port(8080)
            .permissions("container-execution".to_string())
            .build();

        let daemon_enabled = Daemon::new("daemon-c".to_string())
            .code(DaemonCode::Image {
                image: "daemon:latest".to_string(),
            })
            .permissions("daemon-execution".to_string())
            .commands_enabled(true)
            .build();

        let container_enabled = Container::new("container-d".to_string())
            .code(ContainerCode::Image {
                image: "container:latest".to_string(),
            })
            .cpu(ResourceSpec {
                min: "0.5".to_string(),
                desired: "1".to_string(),
            })
            .memory(ResourceSpec {
                min: "512Mi".to_string(),
                desired: "1Gi".to_string(),
            })
            .port(8080)
            .permissions("container-execution".to_string())
            .commands_enabled(true)
            .build();

        let worker_disabled = Worker::new("worker-e".to_string())
            .code(WorkerCode::Image {
                image: "worker:latest".to_string(),
            })
            .permissions("execution".to_string())
            .build();

        let storage = Storage::new("bucket-f".to_string()).build();

        // Declaration order: worker-a (enabled), container-b (disabled),
        // daemon-c (enabled), container-d (enabled), worker-e (disabled),
        // bucket-f (not a command-capable resource type at all).
        let stack = Stack::new("command-targets-stack".to_string())
            .add(worker_enabled, ResourceLifecycle::Live)
            .add(container_disabled, ResourceLifecycle::Live)
            .add(daemon_enabled, ResourceLifecycle::Live)
            .add(container_enabled, ResourceLifecycle::Live)
            .add(worker_disabled, ResourceLifecycle::Live)
            .add(storage, ResourceLifecycle::Frozen)
            .build();

        let targets = stack.command_targets();

        assert_eq!(
            targets,
            vec![
                crate::commands_types::CommandTarget::new(
                    "worker-a",
                    crate::commands_types::CommandTargetType::Worker
                ),
                crate::commands_types::CommandTarget::new(
                    "daemon-c",
                    crate::commands_types::CommandTargetType::Daemon
                ),
                crate::commands_types::CommandTarget::new(
                    "container-d",
                    crate::commands_types::CommandTargetType::Container
                ),
            ]
        );
    }

    #[test]
    fn command_targets_empty_when_no_commands_enabled_resources() {
        let worker = Worker::new("worker-only".to_string())
            .code(WorkerCode::Image {
                image: "worker:latest".to_string(),
            })
            .permissions("execution".to_string())
            .build();

        let stack = Stack::new("no-targets-stack".to_string())
            .add(worker, ResourceLifecycle::Live)
            .build();

        assert!(stack.command_targets().is_empty());
    }

    #[test]
    fn worker_command_push_env_vars_scopes_secret_per_worker() {
        let worker_a = Worker::new("worker-a".to_string())
            .code(WorkerCode::Image {
                image: "worker:latest".to_string(),
            })
            .permissions("execution".to_string())
            .commands_enabled(true)
            .build();

        let worker_b = Worker::new("worker-b".to_string())
            .code(WorkerCode::Image {
                image: "worker:latest".to_string(),
            })
            .permissions("execution".to_string())
            .commands_enabled(true)
            .build();

        // Commands-disabled Workers must not expose a command push endpoint.
        let worker_disabled = Worker::new("worker-off".to_string())
            .code(WorkerCode::Image {
                image: "worker:latest".to_string(),
            })
            .permissions("execution".to_string())
            .build();

        let daemon_enabled = Daemon::new("daemon-c".to_string())
            .code(DaemonCode::Image {
                image: "daemon:latest".to_string(),
            })
            .permissions("daemon-execution".to_string())
            .commands_enabled(true)
            .build();

        let stack = Stack::new("worker-push-env-stack".to_string())
            .add(worker_a, ResourceLifecycle::Live)
            .add(worker_b, ResourceLifecycle::Live)
            .add(worker_disabled, ResourceLifecycle::Live)
            .add(daemon_enabled, ResourceLifecycle::Live)
            .build();

        let vars = stack
            .worker_command_push_env_vars(Some("tok"))
            .expect("token present");

        // Every var is scoped to exactly one command-enabled Worker — nothing
        // is deployment-wide, and neither the disabled Worker nor the Daemon
        // is ever a scope target.
        assert!(vars.iter().all(|v| {
            v.target_resources == Some(vec!["worker-a".to_string()])
                || v.target_resources == Some(vec!["worker-b".to_string()])
        }));

        // Each command-enabled Worker gets only its scoped push token.
        for worker_id in ["worker-a", "worker-b"] {
            let scoped: Vec<_> = vars
                .iter()
                .filter(|v| v.target_resources == Some(vec![worker_id.to_string()]))
                .collect();
            assert_eq!(scoped.len(), 1, "expected one push token for {worker_id}");
            assert!(scoped.iter().any(|v| {
                v.name == crate::ENV_ALIEN_COMMANDS_TOKEN
                    && v.value == "tok"
                    && v.var_type == crate::EnvironmentVariableType::Secret
            }));
        }
    }

    #[test]
    fn worker_command_push_env_vars_fails_without_token() {
        let worker = Worker::new("worker-a".to_string())
            .code(WorkerCode::Image {
                image: "worker:latest".to_string(),
            })
            .permissions("execution".to_string())
            .commands_enabled(true)
            .build();

        let stack = Stack::new("worker-no-token-stack".to_string())
            .add(worker, ResourceLifecycle::Live)
            .build();

        // A command-enabled worker without a token would expose no usable push
        // endpoint, so deployment must fail loudly.
        for token in [None, Some(""), Some("   \t")] {
            let error = stack
                .worker_command_push_env_vars(token)
                .expect_err("missing or blank token must fail the env build");
            assert_eq!(error.code, "COMMAND_TOKEN_MISSING");
            assert!(error.to_string().contains("worker-a"));
        }

        let original = "  nonempty-token  ";
        let vars = stack
            .worker_command_push_env_vars(Some(original))
            .expect("non-empty token");
        assert_eq!(vars[0].value, original, "token bytes must be preserved");
    }

    #[test]
    fn receiver_command_env_vars_scopes_contract_per_container_and_daemon() {
        let container_a = Container::new("container-a".to_string())
            .code(ContainerCode::Image {
                image: "container:latest".to_string(),
            })
            .cpu(ResourceSpec {
                min: "0.5".to_string(),
                desired: "1".to_string(),
            })
            .memory(ResourceSpec {
                min: "512Mi".to_string(),
                desired: "1Gi".to_string(),
            })
            .port(8080)
            .permissions("container-execution".to_string())
            .commands_enabled(true)
            .build();

        let daemon_b = Daemon::new("daemon-b".to_string())
            .code(DaemonCode::Image {
                image: "daemon:latest".to_string(),
            })
            .permissions("daemon-execution".to_string())
            .commands_enabled(true)
            .build();

        // Commands-DISABLED container: must receive NONE of the receiver vars.
        let container_off = Container::new("container-off".to_string())
            .code(ContainerCode::Image {
                image: "container:latest".to_string(),
            })
            .cpu(ResourceSpec {
                min: "0.5".to_string(),
                desired: "1".to_string(),
            })
            .memory(ResourceSpec {
                min: "512Mi".to_string(),
                desired: "1Gi".to_string(),
            })
            .port(8080)
            .permissions("container-execution".to_string())
            .build();

        // Commands-enabled Worker gets push auth, not the receiver contract.
        let worker_enabled = Worker::new("worker-c".to_string())
            .code(WorkerCode::Image {
                image: "worker:latest".to_string(),
            })
            .permissions("execution".to_string())
            .commands_enabled(true)
            .build();

        let stack = Stack::new("receiver-env-stack".to_string())
            .add(container_a, ResourceLifecycle::Live)
            .add(daemon_b, ResourceLifecycle::Live)
            .add(container_off, ResourceLifecycle::Live)
            .add(worker_enabled, ResourceLifecycle::Live)
            .build();

        let vars = stack
            .receiver_command_env_vars("https://cmd.example.test/v1", |_| {
                ReceiverCommandCredential::Token(Some("tok".into()))
            })
            .expect("token present");

        // Every var is scoped to exactly one command-enabled Container/Daemon —
        // nothing is deployment-wide, and neither the disabled container nor the
        // Worker is ever a scope target.
        assert!(vars.iter().all(|v| {
            v.target_resources == Some(vec!["container-a".to_string()])
                || v.target_resources == Some(vec!["daemon-b".to_string()])
        }));

        // ALIEN_DEPLOYMENT_ID remains deployment-wide and is not duplicated.
        assert!(!vars
            .iter()
            .any(|v| v.name == crate::ENV_ALIEN_DEPLOYMENT_ID));

        for (resource_id, expected_type) in [("container-a", "container"), ("daemon-b", "daemon")] {
            let scoped: Vec<_> = vars
                .iter()
                .filter(|v| v.target_resources == Some(vec![resource_id.to_string()]))
                .collect();
            assert_eq!(
                scoped.len(),
                4,
                "expected 4 receiver vars for {resource_id}"
            );
            assert!(scoped.iter().any(|v| {
                v.name == crate::ENV_ALIEN_COMMANDS_URL
                    && v.value == "https://cmd.example.test/v1"
                    && v.var_type == crate::EnvironmentVariableType::Plain
            }));
            assert!(scoped.iter().any(|v| {
                v.name == crate::ENV_ALIEN_COMMANDS_TOKEN
                    && v.value == "tok"
                    && v.var_type == crate::EnvironmentVariableType::Secret
            }));
            assert!(scoped.iter().any(|v| {
                v.name == crate::ENV_ALIEN_COMMANDS_TARGET_RESOURCE_ID && v.value == resource_id
            }));
            assert!(scoped.iter().any(|v| {
                v.name == crate::ENV_ALIEN_COMMANDS_TARGET_RESOURCE_TYPE
                    && v.value == expected_type
                    && v.var_type == crate::EnvironmentVariableType::Plain
            }));
        }
    }

    #[test]
    fn receiver_command_env_vars_fails_without_token() {
        let container = Container::new("container-a".to_string())
            .code(ContainerCode::Image {
                image: "container:latest".to_string(),
            })
            .cpu(ResourceSpec {
                min: "0.5".to_string(),
                desired: "1".to_string(),
            })
            .memory(ResourceSpec {
                min: "512Mi".to_string(),
                desired: "1Gi".to_string(),
            })
            .port(8080)
            .permissions("container-execution".to_string())
            .commands_enabled(true)
            .build();

        let daemon = Daemon::new("daemon-b".to_string())
            .code(DaemonCode::Image {
                image: "daemon:latest".to_string(),
            })
            .permissions("daemon-execution".to_string())
            .commands_enabled(true)
            .build();

        let stack = Stack::new("receiver-no-token-stack".to_string())
            .add(container, ResourceLifecycle::Live)
            .add(daemon, ResourceLifecycle::Live)
            .build();

        // Four of the five receiver vars without the token would make
        // Receiver::from_env crash-loop at startup; the deploy must fail.
        for token in [None, Some(""), Some("   \n")] {
            let error = stack
                .receiver_command_env_vars("https://cmd.example.test/v1", |_| {
                    ReceiverCommandCredential::Token(token.map(str::to_string))
                })
                .expect_err("missing or blank token must fail the env build");
            assert_eq!(error.code, "COMMAND_TOKEN_MISSING");
            assert!(error.to_string().contains("container-a"));
        }

        let original = "  nonempty-token  ";
        let vars = stack
            .receiver_command_env_vars("https://cmd.example.test/v1", |_| {
                ReceiverCommandCredential::Token(Some(original.into()))
            })
            .expect("non-empty token");
        assert!(vars
            .iter()
            .filter(|var| var.name == crate::ENV_ALIEN_COMMANDS_TOKEN)
            .all(|var| var.value == original));
    }

    #[test]
    fn receiver_command_env_vars_empty_without_command_targets() {
        let worker = Worker::new("worker-only".to_string())
            .code(WorkerCode::Image {
                image: "worker:latest".to_string(),
            })
            .permissions("execution".to_string())
            .commands_enabled(true)
            .build();

        let stack = Stack::new("receiver-worker-only-stack".to_string())
            .add(worker, ResourceLifecycle::Live)
            .build();

        // Only a Worker target exists → receiver helper yields nothing.
        assert!(stack
            .receiver_command_env_vars("https://cmd.example.test/v1", |_| {
                ReceiverCommandCredential::Token(Some("tok".into()))
            })
            .expect("no command targets")
            .is_empty());
    }

    #[test]
    fn a_receiver_counts_as_reading_the_capability_file_only_when_marked() {
        let container = |id: &str, marked: bool, enabled: bool| {
            Container::new(id.to_string())
                .code(ContainerCode::Image {
                    image: "container:latest".to_string(),
                })
                .cpu(ResourceSpec {
                    min: "0.5".to_string(),
                    desired: "1".to_string(),
                })
                .memory(ResourceSpec {
                    min: "512Mi".to_string(),
                    desired: "1Gi".to_string(),
                })
                .port(8080)
                .permissions("container-execution".to_string())
                .commands_enabled(enabled)
                .commands_capability_file(marked)
                .build()
        };
        let daemon = |id: &str, marked: bool| {
            Daemon::new(id.to_string())
                .code(DaemonCode::Image {
                    image: "daemon:latest".to_string(),
                })
                .permissions("daemon-execution".to_string())
                .commands_enabled(true)
                .commands_capability_file(marked)
                .build()
        };
        let stack = Stack::new("marker-stack".to_string())
            .add(
                container("old-container", false, true),
                ResourceLifecycle::Live,
            )
            .add(
                container("new-container", true, true),
                ResourceLifecycle::Live,
            )
            .add(
                container("quiet-container", false, false),
                ResourceLifecycle::Live,
            )
            .add(daemon("old-daemon", false), ResourceLifecycle::Live)
            .add(daemon("new-daemon", true), ResourceLifecycle::Live)
            .build();

        assert!(stack.command_receiver_reads_capability_file("new-container"));
        assert!(stack.command_receiver_reads_capability_file("new-daemon"));
        assert!(!stack.command_receiver_reads_capability_file("old-container"));
        assert!(!stack.command_receiver_reads_capability_file("missing"));
        // A resource that receives no commands has no receiver to wait for.
        assert_eq!(
            stack.command_receivers_without_capability_file(),
            vec!["old-container".to_string(), "old-daemon".to_string()]
        );

        // The marker survives a release round trip; an old release has none.
        let json = serde_json::to_value(&stack).unwrap();
        let round_trip: Stack = serde_json::from_value(json.clone()).unwrap();
        assert!(round_trip.command_receiver_reads_capability_file("new-daemon"));
        let resource = &json["resources"]["old-daemon"]["config"];
        assert!(
            resource.get("commandsCapabilityFile").is_none(),
            "{resource}"
        );
        assert_eq!(
            json["resources"]["new-daemon"]["config"]["commandsCapabilityFile"],
            true
        );

        // A stack stored by a build that predates the field reads as an old
        // receiver, even for a resource that is marked today.
        let mut stored_by_old_build = json.clone();
        for id in ["new-container", "new-daemon"] {
            stored_by_old_build["resources"][id]["config"]
                .as_object_mut()
                .unwrap()
                .remove("commandsCapabilityFile");
        }
        let old_stack: Stack = serde_json::from_value(stored_by_old_build).unwrap();
        // Resource order follows the JSON object's key order, which depends on
        // whether the workspace turns on serde_json's `preserve_order`, so the
        // set is compared, not its order.
        let mut without_file = old_stack.command_receivers_without_capability_file();
        without_file.sort();
        assert_eq!(
            without_file,
            vec![
                "new-container".to_string(),
                "new-daemon".to_string(),
                "old-container".to_string(),
                "old-daemon".to_string()
            ]
        );
    }
}