Skip to main content

alien_core/
stack_commands.rs

1//! Command-target discovery and the command env-var injection helpers for
2//! [`Stack`]. Workers receive authenticated platform pushes; Containers and
3//! Daemons run the pull receiver. Both are derived from the same ordered
4//! [`Stack::command_targets`] list.
5
6use crate::error::{ErrorData, Result};
7use crate::{EnvironmentVariable, EnvironmentVariableType, Stack};
8use alien_error::AlienError;
9
10/// Builds a single [`EnvironmentVariable`] scoped to exactly one resource.
11///
12/// Every command env var is scoped via `target_resources` so it reaches only
13/// its own resource; this collapses the otherwise-verbatim struct literals in
14/// the polling/receiver builders below into one place.
15fn scoped(
16    name: &str,
17    value: impl Into<String>,
18    var_type: EnvironmentVariableType,
19    target_id: &str,
20) -> EnvironmentVariable {
21    EnvironmentVariable {
22        name: name.to_string(),
23        value: value.into(),
24        var_type,
25        target_resources: Some(vec![target_id.to_string()]),
26    }
27}
28
29impl Stack {
30    /// Returns the ordered list of command-capable targets in this stack:
31    /// Worker, Container, and Daemon resources with `commands_enabled` set,
32    /// in stack declaration order.
33    ///
34    /// Declaration order is the order resources were added to the stack
35    /// (via `StackBuilder::add`/`add_with_dependencies`/`add_with_remote_access`).
36    /// `resources` is an `IndexMap`, which preserves insertion order, so
37    /// iterating it directly yields declaration order without any extra
38    /// bookkeeping.
39    pub fn command_targets(&self) -> Vec<crate::commands_types::CommandTarget> {
40        use crate::commands_types::{CommandTarget, CommandTargetType};
41
42        self.resources
43            .iter()
44            .filter_map(|(id, entry)| {
45                if let Some(worker) = entry.config.downcast_ref::<crate::Worker>() {
46                    worker
47                        .commands_enabled
48                        .then(|| CommandTarget::new(id.clone(), CommandTargetType::Worker))
49                } else if let Some(container) = entry.config.downcast_ref::<crate::Container>() {
50                    container
51                        .commands_enabled
52                        .then(|| CommandTarget::new(id.clone(), CommandTargetType::Container))
53                } else if let Some(daemon) = entry.config.downcast_ref::<crate::Daemon>() {
54                    daemon
55                        .commands_enabled
56                        .then(|| CommandTarget::new(id.clone(), CommandTargetType::Daemon))
57                } else {
58                    None
59                }
60            })
61            .collect()
62    }
63
64    /// Whether `alien build` recorded that the command receiver of this
65    /// Container or Daemon reads `ALIEN_COMMANDS_CAPABILITY_FILE`
66    /// (`commands_capability_file`). Everything else is treated as a receiver
67    /// from an older build: it needs `ALIEN_COMMANDS_TOKEN` to start. This is
68    /// the one place that rule lives; deployers and token revocation use it.
69    pub fn command_receiver_reads_capability_file(&self, resource_id: &str) -> bool {
70        let Some(entry) = self.resources.get(resource_id) else {
71            return false;
72        };
73        if let Some(container) = entry.config.downcast_ref::<crate::Container>() {
74            container.commands_capability_file
75        } else if let Some(daemon) = entry.config.downcast_ref::<crate::Daemon>() {
76            daemon.commands_capability_file
77        } else {
78            false
79        }
80    }
81
82    /// Ids of the command-enabled Containers and Daemons whose receiver is not
83    /// recorded as reading the capability file. While any exists, the
84    /// deployment token must stay valid: those receivers cannot start without it.
85    pub fn command_receivers_without_capability_file(&self) -> Vec<String> {
86        use crate::commands_types::CommandTargetType;
87
88        self.command_targets()
89            .into_iter()
90            .filter(|target| {
91                matches!(
92                    target.resource_type,
93                    CommandTargetType::Container | CommandTargetType::Daemon
94                )
95            })
96            .map(|target| target.resource_id)
97            .filter(|id| !self.command_receiver_reads_capability_file(id))
98            .collect()
99    }
100
101    /// Returns the authentication token used by the manager/operator to push
102    /// commands to each command-enabled Local/Kubernetes Worker runtime.
103    /// Cloud-native Worker transports authenticate through their platform and
104    /// do not use this helper.
105    pub fn worker_command_push_env_vars(
106        &self,
107        commands_token: Option<&str>,
108    ) -> Result<Vec<EnvironmentVariable>> {
109        use crate::commands_types::CommandTargetType;
110
111        let mut vars = Vec::new();
112        for target in self
113            .command_targets()
114            .into_iter()
115            .filter(|target| target.resource_type == CommandTargetType::Worker)
116        {
117            let id = target.resource_id;
118            let token = require_command_token(commands_token, &id)?;
119            vars.push(scoped(
120                crate::ENV_ALIEN_COMMANDS_TOKEN,
121                token,
122                EnvironmentVariableType::Secret,
123                &id,
124            ));
125        }
126        Ok(vars)
127    }
128
129    /// Returns the command *receiver* environment variables for each
130    /// command-enabled Container and Daemon in this stack, scoped via
131    /// `target_resources` so every var reaches only its own resource.
132    ///
133    /// Workers receive platform pushes; Containers and Daemons run the pull
134    /// receiver, which reads this environment:
135    ///   - `ALIEN_COMMANDS_URL` (Plain) — base receiver URL
136    ///   - the credential, chosen per target by `credential`
137    ///   - `ALIEN_COMMANDS_TARGET_RESOURCE_ID` (Plain) — this resource's id
138    ///   - `ALIEN_COMMANDS_TARGET_RESOURCE_TYPE` (Plain) — `container`/`daemon`
139    ///
140    /// `ALIEN_DEPLOYMENT_ID` is intentionally NOT emitted here: the manager and
141    /// operator already inject it deployment-wide (`target_resources: None`).
142    ///
143    /// Workers are excluded here, and a commands-disabled Container/Daemon is
144    /// never a `command_targets()` entry, so it receives nothing.
145    pub fn receiver_command_env_vars(
146        &self,
147        commands_url: &str,
148        credential: impl Fn(&str) -> ReceiverCommandCredential,
149    ) -> Result<Vec<EnvironmentVariable>> {
150        use crate::commands_types::CommandTargetType;
151
152        let mut vars = Vec::new();
153        for target in self.command_targets().into_iter().filter(|target| {
154            matches!(
155                target.resource_type,
156                CommandTargetType::Container | CommandTargetType::Daemon
157            )
158        }) {
159            let resource_type = target.resource_type.as_str();
160            let id = target.resource_id;
161            vars.push(scoped(
162                crate::ENV_ALIEN_COMMANDS_URL,
163                commands_url,
164                EnvironmentVariableType::Plain,
165                &id,
166            ));
167            match credential(&id) {
168                // Without a credential the receiver cannot start; fail the
169                // deploy here, where the cause is nameable.
170                ReceiverCommandCredential::Token(token) => vars.push(scoped(
171                    crate::ENV_ALIEN_COMMANDS_TOKEN,
172                    require_command_token(token.as_deref(), &id)?,
173                    EnvironmentVariableType::Secret,
174                    &id,
175                )),
176                ReceiverCommandCredential::HostFiles => vars.extend([
177                    scoped(
178                        crate::ENV_ALIEN_COMMANDS_CAPABILITY_FILE,
179                        crate::HOST_COMMANDS_CAPABILITY_FILE,
180                        EnvironmentVariableType::Plain,
181                        &id,
182                    ),
183                    scoped(
184                        crate::ENV_ALIEN_COMMANDS_TOKEN_FILE,
185                        crate::HOST_COMMANDS_TOKEN_FILE,
186                        EnvironmentVariableType::Plain,
187                        &id,
188                    ),
189                ]),
190            }
191            vars.extend([
192                scoped(
193                    crate::ENV_ALIEN_COMMANDS_TARGET_RESOURCE_TYPE,
194                    resource_type,
195                    EnvironmentVariableType::Plain,
196                    &id,
197                ),
198                scoped(
199                    crate::ENV_ALIEN_COMMANDS_TARGET_RESOURCE_ID,
200                    id.clone(),
201                    EnvironmentVariableType::Plain,
202                    &id,
203                ),
204            ]);
205        }
206        Ok(vars)
207    }
208}
209
210/// How a Container or Daemon command receiver gets its credential.
211#[derive(Debug, Clone, PartialEq, Eq)]
212pub enum ReceiverCommandCredential {
213    /// A bearer token in `ALIEN_COMMANDS_TOKEN`. `None` fails the deploy.
214    Token(Option<String>),
215    /// The machine that runs the workload writes a short-lived credential to
216    /// `HOST_COMMANDS_CAPABILITY_FILE` and `HOST_COMMANDS_TOKEN_FILE` and
217    /// refreshes it. No token is put into the workload's environment.
218    HostFiles,
219}
220
221/// The deployment token, or a deploy-time error naming the command-enabled
222/// resource that needs it — a runtime crash-loop on a missing env var is the
223/// only alternative.
224fn require_command_token<'a>(token: Option<&'a str>, resource_id: &str) -> Result<&'a str> {
225    token
226        .filter(|value| !value.trim().is_empty())
227        .ok_or_else(|| {
228            AlienError::new(ErrorData::CommandTokenMissing {
229                resource_id: resource_id.to_string(),
230                reason: "the deployment record carries no non-empty deployment token".to_string(),
231            })
232        })
233}
234
235#[cfg(test)]
236mod tests {
237    use super::ReceiverCommandCredential;
238    use crate::resource::ResourceLifecycle;
239    use crate::{
240        Container, ContainerCode, Daemon, DaemonCode, ResourceSpec, Stack, Storage, Worker,
241        WorkerCode,
242    };
243
244    #[test]
245    fn command_targets_returns_only_commands_enabled_resources_in_declaration_order() {
246        let worker_enabled = Worker::new("worker-a".to_string())
247            .code(WorkerCode::Image {
248                image: "worker:latest".to_string(),
249            })
250            .permissions("execution".to_string())
251            .commands_enabled(true)
252            .build();
253
254        let container_disabled = Container::new("container-b".to_string())
255            .code(ContainerCode::Image {
256                image: "container:latest".to_string(),
257            })
258            .cpu(ResourceSpec {
259                min: "0.5".to_string(),
260                desired: "1".to_string(),
261            })
262            .memory(ResourceSpec {
263                min: "512Mi".to_string(),
264                desired: "1Gi".to_string(),
265            })
266            .port(8080)
267            .permissions("container-execution".to_string())
268            .build();
269
270        let daemon_enabled = Daemon::new("daemon-c".to_string())
271            .code(DaemonCode::Image {
272                image: "daemon:latest".to_string(),
273            })
274            .permissions("daemon-execution".to_string())
275            .commands_enabled(true)
276            .build();
277
278        let container_enabled = Container::new("container-d".to_string())
279            .code(ContainerCode::Image {
280                image: "container:latest".to_string(),
281            })
282            .cpu(ResourceSpec {
283                min: "0.5".to_string(),
284                desired: "1".to_string(),
285            })
286            .memory(ResourceSpec {
287                min: "512Mi".to_string(),
288                desired: "1Gi".to_string(),
289            })
290            .port(8080)
291            .permissions("container-execution".to_string())
292            .commands_enabled(true)
293            .build();
294
295        let worker_disabled = Worker::new("worker-e".to_string())
296            .code(WorkerCode::Image {
297                image: "worker:latest".to_string(),
298            })
299            .permissions("execution".to_string())
300            .build();
301
302        let storage = Storage::new("bucket-f".to_string()).build();
303
304        // Declaration order: worker-a (enabled), container-b (disabled),
305        // daemon-c (enabled), container-d (enabled), worker-e (disabled),
306        // bucket-f (not a command-capable resource type at all).
307        let stack = Stack::new("command-targets-stack".to_string())
308            .add(worker_enabled, ResourceLifecycle::Live)
309            .add(container_disabled, ResourceLifecycle::Live)
310            .add(daemon_enabled, ResourceLifecycle::Live)
311            .add(container_enabled, ResourceLifecycle::Live)
312            .add(worker_disabled, ResourceLifecycle::Live)
313            .add(storage, ResourceLifecycle::Frozen)
314            .build();
315
316        let targets = stack.command_targets();
317
318        assert_eq!(
319            targets,
320            vec![
321                crate::commands_types::CommandTarget::new(
322                    "worker-a",
323                    crate::commands_types::CommandTargetType::Worker
324                ),
325                crate::commands_types::CommandTarget::new(
326                    "daemon-c",
327                    crate::commands_types::CommandTargetType::Daemon
328                ),
329                crate::commands_types::CommandTarget::new(
330                    "container-d",
331                    crate::commands_types::CommandTargetType::Container
332                ),
333            ]
334        );
335    }
336
337    #[test]
338    fn command_targets_empty_when_no_commands_enabled_resources() {
339        let worker = Worker::new("worker-only".to_string())
340            .code(WorkerCode::Image {
341                image: "worker:latest".to_string(),
342            })
343            .permissions("execution".to_string())
344            .build();
345
346        let stack = Stack::new("no-targets-stack".to_string())
347            .add(worker, ResourceLifecycle::Live)
348            .build();
349
350        assert!(stack.command_targets().is_empty());
351    }
352
353    #[test]
354    fn worker_command_push_env_vars_scopes_secret_per_worker() {
355        let worker_a = Worker::new("worker-a".to_string())
356            .code(WorkerCode::Image {
357                image: "worker:latest".to_string(),
358            })
359            .permissions("execution".to_string())
360            .commands_enabled(true)
361            .build();
362
363        let worker_b = Worker::new("worker-b".to_string())
364            .code(WorkerCode::Image {
365                image: "worker:latest".to_string(),
366            })
367            .permissions("execution".to_string())
368            .commands_enabled(true)
369            .build();
370
371        // Commands-disabled Workers must not expose a command push endpoint.
372        let worker_disabled = Worker::new("worker-off".to_string())
373            .code(WorkerCode::Image {
374                image: "worker:latest".to_string(),
375            })
376            .permissions("execution".to_string())
377            .build();
378
379        let daemon_enabled = Daemon::new("daemon-c".to_string())
380            .code(DaemonCode::Image {
381                image: "daemon:latest".to_string(),
382            })
383            .permissions("daemon-execution".to_string())
384            .commands_enabled(true)
385            .build();
386
387        let stack = Stack::new("worker-push-env-stack".to_string())
388            .add(worker_a, ResourceLifecycle::Live)
389            .add(worker_b, ResourceLifecycle::Live)
390            .add(worker_disabled, ResourceLifecycle::Live)
391            .add(daemon_enabled, ResourceLifecycle::Live)
392            .build();
393
394        let vars = stack
395            .worker_command_push_env_vars(Some("tok"))
396            .expect("token present");
397
398        // Every var is scoped to exactly one command-enabled Worker — nothing
399        // is deployment-wide, and neither the disabled Worker nor the Daemon
400        // is ever a scope target.
401        assert!(vars.iter().all(|v| {
402            v.target_resources == Some(vec!["worker-a".to_string()])
403                || v.target_resources == Some(vec!["worker-b".to_string()])
404        }));
405
406        // Each command-enabled Worker gets only its scoped push token.
407        for worker_id in ["worker-a", "worker-b"] {
408            let scoped: Vec<_> = vars
409                .iter()
410                .filter(|v| v.target_resources == Some(vec![worker_id.to_string()]))
411                .collect();
412            assert_eq!(scoped.len(), 1, "expected one push token for {worker_id}");
413            assert!(scoped.iter().any(|v| {
414                v.name == crate::ENV_ALIEN_COMMANDS_TOKEN
415                    && v.value == "tok"
416                    && v.var_type == crate::EnvironmentVariableType::Secret
417            }));
418        }
419    }
420
421    #[test]
422    fn worker_command_push_env_vars_fails_without_token() {
423        let worker = Worker::new("worker-a".to_string())
424            .code(WorkerCode::Image {
425                image: "worker:latest".to_string(),
426            })
427            .permissions("execution".to_string())
428            .commands_enabled(true)
429            .build();
430
431        let stack = Stack::new("worker-no-token-stack".to_string())
432            .add(worker, ResourceLifecycle::Live)
433            .build();
434
435        // A command-enabled worker without a token would expose no usable push
436        // endpoint, so deployment must fail loudly.
437        for token in [None, Some(""), Some("   \t")] {
438            let error = stack
439                .worker_command_push_env_vars(token)
440                .expect_err("missing or blank token must fail the env build");
441            assert_eq!(error.code, "COMMAND_TOKEN_MISSING");
442            assert!(error.to_string().contains("worker-a"));
443        }
444
445        let original = "  nonempty-token  ";
446        let vars = stack
447            .worker_command_push_env_vars(Some(original))
448            .expect("non-empty token");
449        assert_eq!(vars[0].value, original, "token bytes must be preserved");
450    }
451
452    #[test]
453    fn receiver_command_env_vars_scopes_contract_per_container_and_daemon() {
454        let container_a = Container::new("container-a".to_string())
455            .code(ContainerCode::Image {
456                image: "container:latest".to_string(),
457            })
458            .cpu(ResourceSpec {
459                min: "0.5".to_string(),
460                desired: "1".to_string(),
461            })
462            .memory(ResourceSpec {
463                min: "512Mi".to_string(),
464                desired: "1Gi".to_string(),
465            })
466            .port(8080)
467            .permissions("container-execution".to_string())
468            .commands_enabled(true)
469            .build();
470
471        let daemon_b = Daemon::new("daemon-b".to_string())
472            .code(DaemonCode::Image {
473                image: "daemon:latest".to_string(),
474            })
475            .permissions("daemon-execution".to_string())
476            .commands_enabled(true)
477            .build();
478
479        // Commands-DISABLED container: must receive NONE of the receiver vars.
480        let container_off = Container::new("container-off".to_string())
481            .code(ContainerCode::Image {
482                image: "container:latest".to_string(),
483            })
484            .cpu(ResourceSpec {
485                min: "0.5".to_string(),
486                desired: "1".to_string(),
487            })
488            .memory(ResourceSpec {
489                min: "512Mi".to_string(),
490                desired: "1Gi".to_string(),
491            })
492            .port(8080)
493            .permissions("container-execution".to_string())
494            .build();
495
496        // Commands-enabled Worker gets push auth, not the receiver contract.
497        let worker_enabled = Worker::new("worker-c".to_string())
498            .code(WorkerCode::Image {
499                image: "worker:latest".to_string(),
500            })
501            .permissions("execution".to_string())
502            .commands_enabled(true)
503            .build();
504
505        let stack = Stack::new("receiver-env-stack".to_string())
506            .add(container_a, ResourceLifecycle::Live)
507            .add(daemon_b, ResourceLifecycle::Live)
508            .add(container_off, ResourceLifecycle::Live)
509            .add(worker_enabled, ResourceLifecycle::Live)
510            .build();
511
512        let vars = stack
513            .receiver_command_env_vars("https://cmd.example.test/v1", |_| {
514                ReceiverCommandCredential::Token(Some("tok".into()))
515            })
516            .expect("token present");
517
518        // Every var is scoped to exactly one command-enabled Container/Daemon —
519        // nothing is deployment-wide, and neither the disabled container nor the
520        // Worker is ever a scope target.
521        assert!(vars.iter().all(|v| {
522            v.target_resources == Some(vec!["container-a".to_string()])
523                || v.target_resources == Some(vec!["daemon-b".to_string()])
524        }));
525
526        // ALIEN_DEPLOYMENT_ID remains deployment-wide and is not duplicated.
527        assert!(!vars
528            .iter()
529            .any(|v| v.name == crate::ENV_ALIEN_DEPLOYMENT_ID));
530
531        for (resource_id, expected_type) in [("container-a", "container"), ("daemon-b", "daemon")] {
532            let scoped: Vec<_> = vars
533                .iter()
534                .filter(|v| v.target_resources == Some(vec![resource_id.to_string()]))
535                .collect();
536            assert_eq!(
537                scoped.len(),
538                4,
539                "expected 4 receiver vars for {resource_id}"
540            );
541            assert!(scoped.iter().any(|v| {
542                v.name == crate::ENV_ALIEN_COMMANDS_URL
543                    && v.value == "https://cmd.example.test/v1"
544                    && v.var_type == crate::EnvironmentVariableType::Plain
545            }));
546            assert!(scoped.iter().any(|v| {
547                v.name == crate::ENV_ALIEN_COMMANDS_TOKEN
548                    && v.value == "tok"
549                    && v.var_type == crate::EnvironmentVariableType::Secret
550            }));
551            assert!(scoped.iter().any(|v| {
552                v.name == crate::ENV_ALIEN_COMMANDS_TARGET_RESOURCE_ID && v.value == resource_id
553            }));
554            assert!(scoped.iter().any(|v| {
555                v.name == crate::ENV_ALIEN_COMMANDS_TARGET_RESOURCE_TYPE
556                    && v.value == expected_type
557                    && v.var_type == crate::EnvironmentVariableType::Plain
558            }));
559        }
560    }
561
562    #[test]
563    fn receiver_command_env_vars_fails_without_token() {
564        let container = Container::new("container-a".to_string())
565            .code(ContainerCode::Image {
566                image: "container:latest".to_string(),
567            })
568            .cpu(ResourceSpec {
569                min: "0.5".to_string(),
570                desired: "1".to_string(),
571            })
572            .memory(ResourceSpec {
573                min: "512Mi".to_string(),
574                desired: "1Gi".to_string(),
575            })
576            .port(8080)
577            .permissions("container-execution".to_string())
578            .commands_enabled(true)
579            .build();
580
581        let daemon = Daemon::new("daemon-b".to_string())
582            .code(DaemonCode::Image {
583                image: "daemon:latest".to_string(),
584            })
585            .permissions("daemon-execution".to_string())
586            .commands_enabled(true)
587            .build();
588
589        let stack = Stack::new("receiver-no-token-stack".to_string())
590            .add(container, ResourceLifecycle::Live)
591            .add(daemon, ResourceLifecycle::Live)
592            .build();
593
594        // Four of the five receiver vars without the token would make
595        // Receiver::from_env crash-loop at startup; the deploy must fail.
596        for token in [None, Some(""), Some("   \n")] {
597            let error = stack
598                .receiver_command_env_vars("https://cmd.example.test/v1", |_| {
599                    ReceiverCommandCredential::Token(token.map(str::to_string))
600                })
601                .expect_err("missing or blank token must fail the env build");
602            assert_eq!(error.code, "COMMAND_TOKEN_MISSING");
603            assert!(error.to_string().contains("container-a"));
604        }
605
606        let original = "  nonempty-token  ";
607        let vars = stack
608            .receiver_command_env_vars("https://cmd.example.test/v1", |_| {
609                ReceiverCommandCredential::Token(Some(original.into()))
610            })
611            .expect("non-empty token");
612        assert!(vars
613            .iter()
614            .filter(|var| var.name == crate::ENV_ALIEN_COMMANDS_TOKEN)
615            .all(|var| var.value == original));
616    }
617
618    #[test]
619    fn receiver_command_env_vars_empty_without_command_targets() {
620        let worker = Worker::new("worker-only".to_string())
621            .code(WorkerCode::Image {
622                image: "worker:latest".to_string(),
623            })
624            .permissions("execution".to_string())
625            .commands_enabled(true)
626            .build();
627
628        let stack = Stack::new("receiver-worker-only-stack".to_string())
629            .add(worker, ResourceLifecycle::Live)
630            .build();
631
632        // Only a Worker target exists → receiver helper yields nothing.
633        assert!(stack
634            .receiver_command_env_vars("https://cmd.example.test/v1", |_| {
635                ReceiverCommandCredential::Token(Some("tok".into()))
636            })
637            .expect("no command targets")
638            .is_empty());
639    }
640
641    #[test]
642    fn a_receiver_counts_as_reading_the_capability_file_only_when_marked() {
643        let container = |id: &str, marked: bool, enabled: bool| {
644            Container::new(id.to_string())
645                .code(ContainerCode::Image {
646                    image: "container:latest".to_string(),
647                })
648                .cpu(ResourceSpec {
649                    min: "0.5".to_string(),
650                    desired: "1".to_string(),
651                })
652                .memory(ResourceSpec {
653                    min: "512Mi".to_string(),
654                    desired: "1Gi".to_string(),
655                })
656                .port(8080)
657                .permissions("container-execution".to_string())
658                .commands_enabled(enabled)
659                .commands_capability_file(marked)
660                .build()
661        };
662        let daemon = |id: &str, marked: bool| {
663            Daemon::new(id.to_string())
664                .code(DaemonCode::Image {
665                    image: "daemon:latest".to_string(),
666                })
667                .permissions("daemon-execution".to_string())
668                .commands_enabled(true)
669                .commands_capability_file(marked)
670                .build()
671        };
672        let stack = Stack::new("marker-stack".to_string())
673            .add(
674                container("old-container", false, true),
675                ResourceLifecycle::Live,
676            )
677            .add(
678                container("new-container", true, true),
679                ResourceLifecycle::Live,
680            )
681            .add(
682                container("quiet-container", false, false),
683                ResourceLifecycle::Live,
684            )
685            .add(daemon("old-daemon", false), ResourceLifecycle::Live)
686            .add(daemon("new-daemon", true), ResourceLifecycle::Live)
687            .build();
688
689        assert!(stack.command_receiver_reads_capability_file("new-container"));
690        assert!(stack.command_receiver_reads_capability_file("new-daemon"));
691        assert!(!stack.command_receiver_reads_capability_file("old-container"));
692        assert!(!stack.command_receiver_reads_capability_file("missing"));
693        // A resource that receives no commands has no receiver to wait for.
694        assert_eq!(
695            stack.command_receivers_without_capability_file(),
696            vec!["old-container".to_string(), "old-daemon".to_string()]
697        );
698
699        // The marker survives a release round trip; an old release has none.
700        let json = serde_json::to_value(&stack).unwrap();
701        let round_trip: Stack = serde_json::from_value(json.clone()).unwrap();
702        assert!(round_trip.command_receiver_reads_capability_file("new-daemon"));
703        let resource = &json["resources"]["old-daemon"]["config"];
704        assert!(
705            resource.get("commandsCapabilityFile").is_none(),
706            "{resource}"
707        );
708        assert_eq!(
709            json["resources"]["new-daemon"]["config"]["commandsCapabilityFile"],
710            true
711        );
712
713        // A stack stored by a build that predates the field reads as an old
714        // receiver, even for a resource that is marked today.
715        let mut stored_by_old_build = json.clone();
716        for id in ["new-container", "new-daemon"] {
717            stored_by_old_build["resources"][id]["config"]
718                .as_object_mut()
719                .unwrap()
720                .remove("commandsCapabilityFile");
721        }
722        let old_stack: Stack = serde_json::from_value(stored_by_old_build).unwrap();
723        // Resource order follows the JSON object's key order, which depends on
724        // whether the workspace turns on serde_json's `preserve_order`, so the
725        // set is compared, not its order.
726        let mut without_file = old_stack.command_receivers_without_capability_file();
727        without_file.sort();
728        assert_eq!(
729            without_file,
730            vec![
731                "new-container".to_string(),
732                "new-daemon".to_string(),
733                "old-container".to_string(),
734                "old-daemon".to_string()
735            ]
736        );
737    }
738}