Skip to main content

alien_commands/server/
command_registry.rs

1//! Command registry abstraction for command server
2//!
3//! The CommandRegistry is the **source of truth** for all command metadata.
4//! It tracks command state, timestamps, sizes, and errors.
5//!
6//! Implementations:
7//! - `InMemoryCommandRegistry`: In-memory implementation for tests and local dev (in this crate)
8//! - `PlatformCommandRegistry`: Platform API integration (in alien-manager)
9//!
10//! The command KV store holds only operational data: params/response blobs, pending indices, leases.
11
12use crate::error::{ErrorData, Result};
13use alien_core::{CommandDeliveryMode, CommandState, CommandTarget, CommandTargetType};
14use alien_error::AlienError;
15use async_trait::async_trait;
16use chrono::{DateTime, Utc};
17use serde::{Deserialize, Serialize};
18use std::collections::HashMap;
19use std::sync::Arc;
20use tokio::sync::RwLock;
21use uuid::Uuid;
22
23/// A command target resolved by the registry, plus how commands reach it.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct ResolvedCommandTarget {
26    /// The specific resource the command is addressed to
27    pub target: CommandTarget,
28    /// How commands are delivered to this target (Push or Pull)
29    pub delivery_mode: CommandDeliveryMode,
30}
31
32/// Metadata returned when creating a command
33#[derive(Debug, Clone)]
34pub struct CommandMetadata {
35    /// Unique command ID
36    pub command_id: String,
37    /// The specific resource the command is addressed to
38    pub target: CommandTarget,
39    /// How to dispatch the command (Push or Pull)
40    pub delivery_mode: CommandDeliveryMode,
41    /// Project ID for routing/authorization
42    pub project_id: String,
43}
44
45/// Data needed to build an envelope during lease acquisition
46#[derive(Debug, Clone)]
47pub struct CommandEnvelopeData {
48    pub command_id: String,
49    pub deployment_id: String,
50    pub command: String, // command name
51    pub attempt: u32,
52    pub deadline: Option<DateTime<Utc>>,
53    pub state: CommandState,
54    pub target: CommandTarget,
55    pub delivery_mode: CommandDeliveryMode,
56}
57
58/// Full status for GET /commands/{id}
59#[derive(Debug, Clone)]
60pub struct CommandStatus {
61    pub command_id: String,
62    pub workspace_id: String,
63    pub project_id: String,
64    pub deployment_id: String,
65    pub command: String, // command name
66    pub state: CommandState,
67    pub attempt: u32,
68    pub deadline: Option<DateTime<Utc>>,
69    pub created_at: DateTime<Utc>,
70    pub dispatched_at: Option<DateTime<Utc>>,
71    pub completed_at: Option<DateTime<Utc>>,
72    pub error: Option<serde_json::Value>,
73    pub request_size_bytes: Option<u64>,
74    pub response_size_bytes: Option<u64>,
75    pub target: CommandTarget,
76}
77
78/// Canonical ownership fields needed to authorize command reads.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct CommandAccessContext {
81    pub workspace_id: String,
82    pub project_id: String,
83    pub deployment_id: String,
84    pub target: CommandTarget,
85}
86
87/// Internal command record stored in memory
88#[derive(Debug, Clone, Serialize, Deserialize)]
89#[serde(rename_all = "camelCase")]
90struct CommandRecord {
91    id: String,
92    deployment_id: String,
93    command: String,
94    state: CommandState,
95    attempt: u32,
96    deadline: Option<DateTime<Utc>>,
97    created_at: DateTime<Utc>,
98    dispatched_at: Option<DateTime<Utc>>,
99    completed_at: Option<DateTime<Utc>>,
100    request_size_bytes: Option<u64>,
101    response_size_bytes: Option<u64>,
102    error: Option<serde_json::Value>,
103    target: CommandTarget,
104    delivery_mode: CommandDeliveryMode,
105    project_id: String,
106}
107
108/// Reject a command-target resource id that would break the `:`-delimited key
109/// grammar used by the pending index (`target:{dep}:{rid}:pending:…`) and the
110/// idempotency key (`{dep}:{rid}:{command}:{key}`).
111///
112/// An id containing `:` could forge or collide with another target's key
113/// segments, so it is rejected at the commands layer with a typed error. Only
114/// the delimiter that can forge index segments is enforced at this layer.
115pub fn validate_command_target_id(resource_id: &str) -> Result<()> {
116    if resource_id.contains(':') {
117        return Err(AlienError::new(ErrorData::CommandTargetIdInvalid {
118            resource_id: resource_id.to_string(),
119        }));
120    }
121    Ok(())
122}
123
124/// Reject a command name that would break the same `:`-delimited idempotency
125/// key grammar (`{dep}:{rid}:{command}:{key}`).
126///
127/// The trailing client key routinely contains ':', so a ':' in the command
128/// name would be indistinguishable from the key boundary: (command="a:b",
129/// key="c") and (command="a", key="b:c") would forge the same key. Rejecting
130/// ':' in the command name keeps the command segment unambiguous — the twin of
131/// [`validate_command_target_id`] for the command segment.
132pub fn validate_command_name(command: &str) -> Result<()> {
133    if command.contains(':') {
134        return Err(AlienError::new(ErrorData::InvalidCommand {
135            message: format!("Command name '{command}' must not contain ':'"),
136        }));
137    }
138    Ok(())
139}
140
141/// The reserved command-target id for the operator itself. Commands addressed
142/// to this id are operator-level operations (e.g. an operations-plugin command)
143/// the operator runs via its embedded receiver — not a resource in the
144/// deployment's stack. It is resolved to a pull-mode daemon target without
145/// consulting the stack, since the operator is not a stack resource.
146pub const OPERATOR_COMMAND_TARGET_ID: &str = "operator";
147
148/// The reserved command-target id of a system-provisioned operations worker.
149///
150/// Unlike [`OPERATOR_COMMAND_TARGET_ID`], this is a real Worker in the
151/// deployment's stack, so it resolves like any other stack target and uses the
152/// Worker's push delivery. It runs operations, so the same access rules as the
153/// operator apply: only an operations capability may address it, and
154/// single-target shorthand never selects it.
155pub const OPERATIONS_WORKER_COMMAND_TARGET_ID: &str = "operations-worker";
156
157/// Whether `resource_id` names a reserved target that runs operations.
158pub fn is_operations_command_target(resource_id: &str) -> bool {
159    resource_id == OPERATOR_COMMAND_TARGET_ID || resource_id == OPERATIONS_WORKER_COMMAND_TARGET_ID
160}
161
162/// Whether `target` is a reserved operations target with its expected type:
163/// the operator is always a daemon, the operations worker always a Worker.
164pub fn is_operations_target(target: &CommandTarget) -> bool {
165    (target.resource_id == OPERATOR_COMMAND_TARGET_ID
166        && target.resource_type == CommandTargetType::Daemon)
167        || (target.resource_id == OPERATIONS_WORKER_COMMAND_TARGET_ID
168            && target.resource_type == CommandTargetType::Worker)
169}
170
171/// Target-selection rules shared by both the
172/// in-memory and SQLite registries route through.
173///
174/// - `requested = Some(id)`: the id must be well-formed (no `:`) and name an
175///   existing command-capable target, else `COMMAND_TARGET_NOT_FOUND`. An empty
176///   id never falls back to shorthand. The reserved
177///   [`OPERATOR_COMMAND_TARGET_ID`] always resolves to a pull-mode daemon
178///   target for the operator, independent of the stack.
179/// - `requested = None` (single-target shorthand): exactly one non-reserved
180///   stack target must exist, else `COMMAND_TARGET_AMBIGUOUS` (more than one)
181///   or `NO_COMMAND_TARGETS` (none). Reserved operations targets (see
182///   [`is_operations_command_target`]) are excluded so shorthand can never
183///   address them.
184///
185/// The resolved target's own id is also validated, so a target registered with
186/// a `:`-bearing id can never resolve into the key grammar.
187pub fn select_command_target(
188    deployment_id: &str,
189    targets: &[CommandTarget],
190    requested: Option<&str>,
191) -> Result<CommandTarget> {
192    // The operator is a reserved target, not a stack resource — resolve it
193    // directly so operations commands can be addressed to the operator without
194    // it having to appear in the deployment's command-capable stack targets.
195    if requested == Some(OPERATOR_COMMAND_TARGET_ID) {
196        return Ok(CommandTarget::new(
197            OPERATOR_COMMAND_TARGET_ID.to_string(),
198            CommandTargetType::Daemon,
199        ));
200    }
201
202    let target = match requested {
203        Some(resource_id) => {
204            // Reject ids that would break the key grammar before any lookup.
205            validate_command_target_id(resource_id)?;
206            // An empty resource id is never a valid target — in particular it
207            // must NOT silently fall back to shorthand resolution.
208            let found = if resource_id.is_empty() {
209                None
210            } else {
211                targets.iter().find(|t| t.resource_id == resource_id)
212            };
213            found
214                .ok_or_else(|| {
215                    AlienError::new(ErrorData::CommandTargetNotFound {
216                        resource_id: resource_id.to_string(),
217                        deployment_id: deployment_id.to_string(),
218                    })
219                })?
220                .clone()
221        }
222        None => {
223            let mut candidates = targets
224                .iter()
225                .filter(|target| !is_operations_command_target(&target.resource_id));
226            let Some(single) = candidates.next() else {
227                return Err(AlienError::new(ErrorData::NoCommandTargets {
228                    deployment_id: deployment_id.to_string(),
229                }));
230            };
231            if candidates.next().is_some() {
232                return Err(AlienError::new(ErrorData::CommandTargetAmbiguous {
233                    deployment_id: deployment_id.to_string(),
234                }));
235            }
236            single.clone()
237        }
238    };
239
240    // A registered target whose id breaks the key grammar must never resolve.
241    validate_command_target_id(&target.resource_id)?;
242    Ok(target)
243}
244
245/// Pinned per-type delivery rule — the single implementation both registries
246/// route through. Container and Daemon targets are always Pull; a Worker target
247/// follows `worker_mode`, the caller's derived worker context (production: Push
248/// only when the platform has a push path AND `stack_settings.deployment_model`
249/// is Push).
250pub fn delivery_mode_for(
251    resource_type: CommandTargetType,
252    worker_mode: CommandDeliveryMode,
253) -> CommandDeliveryMode {
254    match resource_type {
255        CommandTargetType::Container | CommandTargetType::Daemon => CommandDeliveryMode::Pull,
256        CommandTargetType::Worker => worker_mode,
257    }
258}
259
260/// Abstraction for command metadata storage and lifecycle tracking.
261///
262/// The CommandRegistry is the source of truth for all command metadata.
263/// Implementations store command state, timestamps, and result information.
264#[async_trait]
265pub trait CommandRegistry: Send + Sync {
266    /// Whether this registry durably stores an operation result contract in
267    /// the same create transaction that makes a command visible.
268    fn persists_operation_result_contract(&self) -> bool {
269        false
270    }
271
272    /// Resolve which command-capable resource a command is addressed to.
273    ///
274    /// `command` is the name being invoked. Registries that know about
275    /// commands served outside the deployment stack (for example operations)
276    /// can use it to reject a name that must be invoked another way, with an
277    /// error that says how. The standalone registries ignore it.
278    ///
279    /// - `requested = Some(id)`: the target must exist and be command-capable,
280    ///   else `COMMAND_TARGET_NOT_FOUND` (an empty id never resolves).
281    /// - `requested = None` (single-target shorthand): exactly one
282    ///   command-capable target must exist, else `COMMAND_TARGET_AMBIGUOUS`
283    ///   (more than one) or `NO_COMMAND_TARGETS` (none).
284    ///
285    /// The returned delivery mode is derived from the target: Container and
286    /// Daemon targets are always Pull. Worker delivery is resolved from the
287    /// deployment model and platform: Kubernetes uses its in-cluster operator
288    /// relay, Local supports embedded Push and remote Pull, and cloud Workers
289    /// use their provider push path only for Push deployments.
290    async fn resolve_target(
291        &self,
292        deployment_id: &str,
293        command: &str,
294        requested: Option<&str>,
295    ) -> Result<ResolvedCommandTarget>;
296
297    /// Create a new command addressed to a previously resolved target and
298    /// return metadata for routing.
299    ///
300    /// The registry generates the command_id and stores all metadata
301    /// (state, target, timestamps, etc.).
302    async fn create_command(
303        &self,
304        deployment_id: &str,
305        command_name: &str,
306        target: &ResolvedCommandTarget,
307        initial_state: CommandState,
308        deadline: Option<DateTime<Utc>>,
309        request_size_bytes: Option<u64>,
310        operation_result_contract: Option<serde_json::Value>,
311    ) -> Result<CommandMetadata>;
312
313    /// Get metadata needed to build an envelope during lease acquisition.
314    ///
315    /// Returns None if command doesn't exist.
316    async fn get_command_metadata(&self, command_id: &str) -> Result<Option<CommandEnvelopeData>>;
317
318    /// Get full command status for status endpoint.
319    ///
320    /// Returns None if command doesn't exist.
321    async fn get_command_status(&self, command_id: &str) -> Result<Option<CommandStatus>>;
322
323    /// Get the canonical ownership fields used to authorize command reads.
324    ///
325    /// The status record is the command registry's source of truth for these
326    /// fields, so this does not require a deployment lookup.
327    async fn get_command_access_context(
328        &self,
329        command_id: &str,
330    ) -> Result<Option<CommandAccessContext>> {
331        Ok(self
332            .get_command_status(command_id)
333            .await?
334            .map(|status| CommandAccessContext {
335                workspace_id: status.workspace_id,
336                project_id: status.project_id,
337                deployment_id: status.deployment_id,
338                target: status.target,
339            }))
340    }
341
342    /// Atomically update a non-terminal command's lifecycle state.
343    ///
344    /// Returns `false` when the command became terminal before the update.
345    /// Terminal transitions use [`Self::complete_command`] instead.
346    async fn update_command_state(
347        &self,
348        command_id: &str,
349        state: CommandState,
350        dispatched_at: Option<DateTime<Utc>>,
351        completed_at: Option<DateTime<Utc>>,
352        response_size_bytes: Option<u64>,
353        error: Option<serde_json::Value>,
354    ) -> Result<bool>;
355
356    /// Atomically transition a command from any NON-terminal state to the
357    /// given terminal `state`.
358    ///
359    /// Returns `false` when the command was already terminal — a concurrent
360    /// submitter won the race — so a terminal record can never be
361    /// overwritten by a late duplicate (redelivered execution racing the
362    /// original whose lease expired).
363    async fn complete_command(
364        &self,
365        command_id: &str,
366        state: CommandState,
367        completed_at: DateTime<Utc>,
368        response_size_bytes: Option<u64>,
369        error: Option<serde_json::Value>,
370    ) -> Result<bool>;
371
372    /// Atomically mark a command Dispatched unless it is already terminal.
373    ///
374    /// Returns `false` when the command reached a terminal state in the
375    /// meantime — e.g. a lease TTL-expired, a new poller won the takeover
376    /// put, and the ORIGINAL holder's submit landed between the poller's
377    /// terminal check and this write. An unconditional write there would
378    /// flip a committed terminal state back to Dispatched.
379    async fn mark_dispatched_if_not_terminal(
380        &self,
381        command_id: &str,
382        dispatched_at: DateTime<Utc>,
383    ) -> Result<bool>;
384
385    /// Increment attempt count (on lease release/expiry).
386    ///
387    /// Returns the new attempt number.
388    async fn increment_attempt(&self, command_id: &str) -> Result<u32>;
389}
390
391/// In-memory implementation for tests and local development.
392///
393/// Tracks command metadata in memory. Targets are registered explicitly via
394/// [`register_target`](Self::register_target); resolution then follows exactly
395/// the production rules documented on [`CommandRegistry::resolve_target`].
396pub struct InMemoryCommandRegistry {
397    commands: Arc<RwLock<HashMap<String, CommandRecord>>>,
398    /// Registered command-capable targets, in registration (declaration) order.
399    ///
400    /// Not scoped per deployment: this registry models a single local
401    /// deployment universe, so every deployment id resolves against the same
402    /// target set (the per-call resolution rules are identical to production).
403    targets: Arc<RwLock<Vec<CommandTarget>>>,
404    /// Delivery mode for Worker targets.
405    ///
406    /// In production this is derived from the deployment's platform and stack
407    /// settings (Push only when the platform has a push path AND
408    /// `stack_settings.deployment_model == Push`). The registrant supplies
409    /// that derived context here once, and the registry applies the pinned
410    /// per-type rule itself — so it is impossible to register a Container or
411    /// Daemon target with a Push mode that production could never produce.
412    worker_delivery_mode: CommandDeliveryMode,
413}
414
415impl InMemoryCommandRegistry {
416    /// Create a new in-memory registry whose Worker targets use Pull delivery
417    /// (the safe default: matches platforms without a push path).
418    pub fn new() -> Self {
419        Self::with_worker_delivery_mode(CommandDeliveryMode::Pull)
420    }
421
422    /// Create a new in-memory registry with the specified Worker delivery mode.
423    ///
424    /// Container/Daemon targets are always Pull regardless of this setting.
425    pub fn with_worker_delivery_mode(worker_delivery_mode: CommandDeliveryMode) -> Self {
426        Self {
427            commands: Arc::new(RwLock::new(HashMap::new())),
428            targets: Arc::new(RwLock::new(Vec::new())),
429            worker_delivery_mode,
430        }
431    }
432
433    /// Register a command-capable target that commands can resolve to.
434    ///
435    /// Mirrors production, where the target set comes from the deployment's
436    /// stack (`Stack::command_targets()`: Worker/Container/Daemon resources
437    /// with `commands_enabled`). The id is validated through the same shared
438    /// guard as resolution, so a `:`-bearing id is rejected here at registration
439    /// rather than surfacing later as a key-grammar collision.
440    pub async fn register_target(
441        &self,
442        resource_id: impl Into<String>,
443        resource_type: CommandTargetType,
444    ) -> Result<()> {
445        let resource_id = resource_id.into();
446        validate_command_target_id(&resource_id)?;
447        self.targets
448            .write()
449            .await
450            .push(CommandTarget::new(resource_id, resource_type));
451        Ok(())
452    }
453
454    /// List all command IDs (useful for debugging/testing)
455    #[allow(dead_code)]
456    pub async fn list_command_ids(&self) -> Vec<String> {
457        let commands = self.commands.read().await;
458        commands.keys().cloned().collect()
459    }
460}
461
462impl Default for InMemoryCommandRegistry {
463    fn default() -> Self {
464        Self::new()
465    }
466}
467
468#[async_trait]
469impl CommandRegistry for InMemoryCommandRegistry {
470    async fn resolve_target(
471        &self,
472        deployment_id: &str,
473        _command: &str,
474        requested: Option<&str>,
475    ) -> Result<ResolvedCommandTarget> {
476        let targets = self.targets.read().await;
477        let target = select_command_target(deployment_id, &targets, requested)?;
478        let delivery_mode = delivery_mode_for(target.resource_type, self.worker_delivery_mode);
479        Ok(ResolvedCommandTarget {
480            target,
481            delivery_mode,
482        })
483    }
484
485    async fn create_command(
486        &self,
487        deployment_id: &str,
488        command_name: &str,
489        target: &ResolvedCommandTarget,
490        initial_state: CommandState,
491        deadline: Option<DateTime<Utc>>,
492        request_size_bytes: Option<u64>,
493        _operation_result_contract: Option<serde_json::Value>,
494    ) -> Result<CommandMetadata> {
495        let command_id = format!("cmd_{}", Uuid::new_v4());
496
497        let record = CommandRecord {
498            id: command_id.clone(),
499            deployment_id: deployment_id.to_string(),
500            command: command_name.to_string(),
501            state: initial_state,
502            attempt: 1,
503            deadline,
504            created_at: Utc::now(),
505            dispatched_at: None,
506            completed_at: None,
507            request_size_bytes,
508            response_size_bytes: None,
509            error: None,
510            target: target.target.clone(),
511            delivery_mode: target.delivery_mode,
512            project_id: "default".to_string(),
513        };
514
515        self.commands
516            .write()
517            .await
518            .insert(command_id.clone(), record);
519
520        Ok(CommandMetadata {
521            command_id,
522            target: target.target.clone(),
523            delivery_mode: target.delivery_mode,
524            project_id: "default".to_string(),
525        })
526    }
527
528    async fn get_command_metadata(&self, command_id: &str) -> Result<Option<CommandEnvelopeData>> {
529        let commands = self.commands.read().await;
530
531        Ok(commands.get(command_id).map(|r| CommandEnvelopeData {
532            command_id: r.id.clone(),
533            deployment_id: r.deployment_id.clone(),
534            command: r.command.clone(),
535            attempt: r.attempt,
536            deadline: r.deadline,
537            state: r.state,
538            target: r.target.clone(),
539            delivery_mode: r.delivery_mode,
540        }))
541    }
542
543    async fn get_command_status(&self, command_id: &str) -> Result<Option<CommandStatus>> {
544        let commands = self.commands.read().await;
545
546        Ok(commands.get(command_id).map(|r| CommandStatus {
547            command_id: r.id.clone(),
548            workspace_id: "default".to_string(),
549            project_id: r.project_id.clone(),
550            deployment_id: r.deployment_id.clone(),
551            command: r.command.clone(),
552            state: r.state,
553            attempt: r.attempt,
554            deadline: r.deadline,
555            created_at: r.created_at,
556            dispatched_at: r.dispatched_at,
557            completed_at: r.completed_at,
558            error: r.error.clone(),
559            request_size_bytes: r.request_size_bytes,
560            response_size_bytes: r.response_size_bytes,
561            target: r.target.clone(),
562        }))
563    }
564
565    async fn update_command_state(
566        &self,
567        command_id: &str,
568        state: CommandState,
569        dispatched_at: Option<DateTime<Utc>>,
570        completed_at: Option<DateTime<Utc>>,
571        response_size_bytes: Option<u64>,
572        error: Option<serde_json::Value>,
573    ) -> Result<bool> {
574        let mut commands = self.commands.write().await;
575
576        if let Some(record) = commands.get_mut(command_id) {
577            if record.state.is_terminal() {
578                return Ok(false);
579            }
580            record.state = state;
581
582            if let Some(ts) = dispatched_at {
583                record.dispatched_at = Some(ts);
584            }
585
586            if let Some(ts) = completed_at {
587                record.completed_at = Some(ts);
588            }
589
590            if let Some(size) = response_size_bytes {
591                record.response_size_bytes = Some(size);
592            }
593
594            if let Some(err) = error {
595                record.error = Some(err);
596            }
597            return Ok(true);
598        }
599
600        Ok(false)
601    }
602
603    async fn complete_command(
604        &self,
605        command_id: &str,
606        state: CommandState,
607        completed_at: DateTime<Utc>,
608        response_size_bytes: Option<u64>,
609        error: Option<serde_json::Value>,
610    ) -> Result<bool> {
611        let mut commands = self.commands.write().await;
612        let Some(record) = commands.get_mut(command_id) else {
613            return Ok(false);
614        };
615        if record.state.is_terminal() {
616            return Ok(false);
617        }
618        record.state = state;
619        record.completed_at = Some(completed_at);
620        if let Some(size) = response_size_bytes {
621            record.response_size_bytes = Some(size);
622        }
623        if let Some(err) = error {
624            record.error = Some(err);
625        }
626        Ok(true)
627    }
628
629    async fn mark_dispatched_if_not_terminal(
630        &self,
631        command_id: &str,
632        dispatched_at: DateTime<Utc>,
633    ) -> Result<bool> {
634        let mut commands = self.commands.write().await;
635        let Some(record) = commands.get_mut(command_id) else {
636            return Ok(false);
637        };
638        if record.state.is_terminal() {
639            return Ok(false);
640        }
641        record.state = CommandState::Dispatched;
642        record.dispatched_at = Some(dispatched_at);
643        Ok(true)
644    }
645
646    async fn increment_attempt(&self, command_id: &str) -> Result<u32> {
647        let mut commands = self.commands.write().await;
648
649        if let Some(record) = commands.get_mut(command_id) {
650            record.attempt += 1;
651            Ok(record.attempt)
652        } else {
653            Ok(1) // Default if not found
654        }
655    }
656}
657
658#[cfg(test)]
659mod tests {
660    use super::*;
661    use alien_core::{CommandDeliveryMode, CommandTarget, CommandTargetType};
662
663    async fn resolved(
664        registry: &InMemoryCommandRegistry,
665        requested: Option<&str>,
666    ) -> Result<ResolvedCommandTarget> {
667        registry
668            .resolve_target("dep-1", "test-command", requested)
669            .await
670    }
671
672    #[tokio::test]
673    async fn test_resolve_explicit_target_found() {
674        let registry = InMemoryCommandRegistry::new();
675        registry
676            .register_target("worker-a", CommandTargetType::Worker)
677            .await
678            .unwrap();
679        registry
680            .register_target("daemon-b", CommandTargetType::Daemon)
681            .await
682            .unwrap();
683
684        let result = resolved(&registry, Some("daemon-b")).await.unwrap();
685        assert_eq!(
686            result.target,
687            CommandTarget::new("daemon-b", CommandTargetType::Daemon)
688        );
689    }
690
691    #[tokio::test]
692    async fn test_resolve_explicit_unknown_target_is_not_found() {
693        let registry = InMemoryCommandRegistry::new();
694        registry
695            .register_target("worker-a", CommandTargetType::Worker)
696            .await
697            .unwrap();
698
699        let err = resolved(&registry, Some("no-such-resource"))
700            .await
701            .unwrap_err();
702        assert_eq!(err.code, "COMMAND_TARGET_NOT_FOUND");
703        assert_eq!(err.http_status_code, Some(404));
704    }
705
706    #[tokio::test]
707    async fn test_resolve_explicit_empty_string_is_not_found() {
708        let registry = InMemoryCommandRegistry::new();
709        registry
710            .register_target("worker-a", CommandTargetType::Worker)
711            .await
712            .unwrap();
713
714        // An explicitly requested empty resource id must never resolve (in
715        // particular it must NOT fall back to shorthand resolution).
716        let err = resolved(&registry, Some("")).await.unwrap_err();
717        assert_eq!(err.code, "COMMAND_TARGET_NOT_FOUND");
718    }
719
720    #[tokio::test]
721    async fn test_resolve_shorthand_single_target_resolves() {
722        let registry = InMemoryCommandRegistry::new();
723        registry
724            .register_target("container-1", CommandTargetType::Container)
725            .await
726            .unwrap();
727
728        let result = resolved(&registry, None).await.unwrap();
729        assert_eq!(
730            result.target,
731            CommandTarget::new("container-1", CommandTargetType::Container)
732        );
733    }
734
735    #[tokio::test]
736    async fn test_resolve_shorthand_two_targets_is_ambiguous() {
737        let registry = InMemoryCommandRegistry::new();
738        registry
739            .register_target("worker-a", CommandTargetType::Worker)
740            .await
741            .unwrap();
742        registry
743            .register_target("worker-b", CommandTargetType::Worker)
744            .await
745            .unwrap();
746
747        let err = resolved(&registry, None).await.unwrap_err();
748        assert_eq!(err.code, "COMMAND_TARGET_AMBIGUOUS");
749        assert_eq!(err.http_status_code, Some(409));
750    }
751
752    #[tokio::test]
753    async fn test_resolve_shorthand_zero_targets_is_no_targets() {
754        let registry = InMemoryCommandRegistry::new();
755
756        let err = resolved(&registry, None).await.unwrap_err();
757        assert_eq!(err.code, "NO_COMMAND_TARGETS");
758        assert_eq!(err.http_status_code, Some(422));
759    }
760
761    #[tokio::test]
762    async fn test_resolve_shorthand_operator_only_is_no_targets() {
763        let registry = InMemoryCommandRegistry::new();
764        registry
765            .register_target(OPERATOR_COMMAND_TARGET_ID, CommandTargetType::Daemon)
766            .await
767            .unwrap();
768
769        let err = resolved(&registry, None).await.unwrap_err();
770        assert_eq!(err.code, "NO_COMMAND_TARGETS");
771        assert_eq!(err.http_status_code, Some(422));
772    }
773
774    #[tokio::test]
775    async fn test_resolve_shorthand_ignores_operator_beside_one_stack_target() {
776        let registry = InMemoryCommandRegistry::new();
777        registry
778            .register_target(OPERATOR_COMMAND_TARGET_ID, CommandTargetType::Daemon)
779            .await
780            .unwrap();
781        registry
782            .register_target("daemon-1", CommandTargetType::Daemon)
783            .await
784            .unwrap();
785
786        let result = resolved(&registry, None).await.unwrap();
787        assert_eq!(
788            result.target,
789            CommandTarget::new("daemon-1", CommandTargetType::Daemon)
790        );
791    }
792
793    #[tokio::test]
794    async fn test_delivery_mode_container_and_daemon_always_pull() {
795        // Even with a Push-capable worker context, Container/Daemon are Pull.
796        let registry =
797            InMemoryCommandRegistry::with_worker_delivery_mode(CommandDeliveryMode::Push);
798        registry
799            .register_target("container-1", CommandTargetType::Container)
800            .await
801            .unwrap();
802        registry
803            .register_target("daemon-1", CommandTargetType::Daemon)
804            .await
805            .unwrap();
806
807        let container = resolved(&registry, Some("container-1")).await.unwrap();
808        assert_eq!(container.delivery_mode, CommandDeliveryMode::Pull);
809
810        let daemon = resolved(&registry, Some("daemon-1")).await.unwrap();
811        assert_eq!(daemon.delivery_mode, CommandDeliveryMode::Pull);
812    }
813
814    #[tokio::test]
815    async fn test_delivery_mode_worker_follows_registered_context() {
816        let push_registry =
817            InMemoryCommandRegistry::with_worker_delivery_mode(CommandDeliveryMode::Push);
818        push_registry
819            .register_target("worker-1", CommandTargetType::Worker)
820            .await
821            .unwrap();
822        let push_worker = push_registry
823            .resolve_target("dep-1", "test-command", Some("worker-1"))
824            .await
825            .unwrap();
826        assert_eq!(push_worker.delivery_mode, CommandDeliveryMode::Push);
827
828        // A manager-side pending path (e.g. Kubernetes operator relay, or a
829        // cloud stack whose deployment model is Pull).
830        let pull_registry =
831            InMemoryCommandRegistry::with_worker_delivery_mode(CommandDeliveryMode::Pull);
832        pull_registry
833            .register_target("worker-1", CommandTargetType::Worker)
834            .await
835            .unwrap();
836        let pull_worker = pull_registry
837            .resolve_target("dep-1", "test-command", Some("worker-1"))
838            .await
839            .unwrap();
840        assert_eq!(pull_worker.delivery_mode, CommandDeliveryMode::Pull);
841    }
842
843    #[tokio::test]
844    async fn test_create_command_stores_target_in_status_and_envelope_data() {
845        let registry = InMemoryCommandRegistry::new();
846        registry
847            .register_target("daemon-1", CommandTargetType::Daemon)
848            .await
849            .unwrap();
850
851        let resolved_target = registry
852            .resolve_target("dep-1", "test-command", None)
853            .await
854            .unwrap();
855        let metadata = registry
856            .create_command(
857                "dep-1",
858                "sync-data",
859                &resolved_target,
860                CommandState::Pending,
861                None,
862                None,
863                None,
864            )
865            .await
866            .unwrap();
867
868        let expected = CommandTarget::new("daemon-1", CommandTargetType::Daemon);
869        assert_eq!(metadata.target, expected);
870        assert_eq!(metadata.delivery_mode, CommandDeliveryMode::Pull);
871
872        let status = registry
873            .get_command_status(&metadata.command_id)
874            .await
875            .unwrap()
876            .unwrap();
877        assert_eq!(status.target, expected);
878
879        let envelope_data = registry
880            .get_command_metadata(&metadata.command_id)
881            .await
882            .unwrap()
883            .unwrap();
884        assert_eq!(envelope_data.target, expected);
885        assert_eq!(envelope_data.delivery_mode, CommandDeliveryMode::Pull);
886    }
887
888    #[tokio::test]
889    async fn non_terminal_update_cannot_resurrect_completed_command() {
890        let registry = InMemoryCommandRegistry::new();
891        registry
892            .register_target("daemon-1", CommandTargetType::Daemon)
893            .await
894            .unwrap();
895        let target = registry
896            .resolve_target("dep-1", "test-command", None)
897            .await
898            .unwrap();
899        let command = registry
900            .create_command(
901                "dep-1",
902                "run",
903                &target,
904                CommandState::Dispatched,
905                None,
906                None,
907                None,
908            )
909            .await
910            .unwrap();
911
912        assert!(registry
913            .complete_command(
914                &command.command_id,
915                CommandState::Succeeded,
916                Utc::now(),
917                None,
918                None,
919            )
920            .await
921            .unwrap());
922        assert!(!registry
923            .update_command_state(
924                &command.command_id,
925                CommandState::Pending,
926                None,
927                None,
928                None,
929                None,
930            )
931            .await
932            .unwrap());
933        assert_eq!(
934            registry
935                .get_command_status(&command.command_id)
936                .await
937                .unwrap()
938                .unwrap()
939                .state,
940            CommandState::Succeeded
941        );
942    }
943
944    #[tokio::test]
945    async fn in_memory_command_access_uses_oss_tenant_context() {
946        let registry = InMemoryCommandRegistry::new();
947        registry
948            .register_target("worker-1", CommandTargetType::Worker)
949            .await
950            .unwrap();
951        let target = registry
952            .resolve_target("dep-1", "test-command", None)
953            .await
954            .unwrap();
955        let command = registry
956            .create_command(
957                "dep-1",
958                "run",
959                &target,
960                CommandState::Pending,
961                None,
962                None,
963                None,
964            )
965            .await
966            .unwrap();
967
968        assert_eq!(command.project_id, "default");
969        assert_eq!(
970            registry
971                .get_command_access_context(&command.command_id)
972                .await
973                .unwrap()
974                .unwrap(),
975            CommandAccessContext {
976                workspace_id: "default".to_string(),
977                project_id: "default".to_string(),
978                deployment_id: "dep-1".to_string(),
979                target: CommandTarget::new("worker-1", CommandTargetType::Worker),
980            }
981        );
982    }
983
984    #[tokio::test]
985    async fn test_register_target_rejects_colon_in_id() {
986        let registry = InMemoryCommandRegistry::new();
987        let err = registry
988            .register_target("evil:pending:x", CommandTargetType::Worker)
989            .await
990            .unwrap_err();
991        assert_eq!(err.code, "COMMAND_TARGET_ID_INVALID");
992        assert_eq!(err.http_status_code, Some(400));
993    }
994
995    #[tokio::test]
996    async fn test_resolve_explicit_colon_id_is_invalid() {
997        let registry = InMemoryCommandRegistry::new();
998        registry
999            .register_target("worker-a", CommandTargetType::Worker)
1000            .await
1001            .unwrap();
1002
1003        // A requested id containing ':' is rejected with a typed error before
1004        // any lookup — it can never be resolved into the key grammar.
1005        let err = resolved(&registry, Some("worker-a:pending:1"))
1006            .await
1007            .unwrap_err();
1008        assert_eq!(err.code, "COMMAND_TARGET_ID_INVALID");
1009    }
1010
1011    #[test]
1012    fn test_select_command_target_rejects_registered_colon_id() {
1013        // Even if a `:`-bearing target slips into the slice (e.g. an unvalidated
1014        // upstream path), selecting it fails loudly rather than resolving.
1015        let targets = vec![CommandTarget::new("a:pending:x", CommandTargetType::Worker)];
1016        let err = select_command_target("dep-1", &targets, None).unwrap_err();
1017        assert_eq!(err.code, "COMMAND_TARGET_ID_INVALID");
1018    }
1019
1020    #[test]
1021    fn operator_target_resolves_without_a_stack_resource() {
1022        // The reserved operator id resolves to a pull-mode daemon target even
1023        // when no stack targets exist — operations commands address the operator
1024        // itself, which is never a stack resource.
1025        let target = select_command_target("dep-1", &[], Some(OPERATOR_COMMAND_TARGET_ID)).unwrap();
1026        assert_eq!(target.resource_id, OPERATOR_COMMAND_TARGET_ID);
1027        assert_eq!(target.resource_type, CommandTargetType::Daemon);
1028        // A daemon target always delivers via pull, regardless of worker mode.
1029        assert_eq!(
1030            delivery_mode_for(target.resource_type, CommandDeliveryMode::Push),
1031            CommandDeliveryMode::Pull
1032        );
1033    }
1034
1035    #[test]
1036    fn operations_worker_resolves_from_the_stack_as_a_push_worker() {
1037        let targets = vec![CommandTarget::new(
1038            OPERATIONS_WORKER_COMMAND_TARGET_ID,
1039            CommandTargetType::Worker,
1040        )];
1041        let target =
1042            select_command_target("dep-1", &targets, Some(OPERATIONS_WORKER_COMMAND_TARGET_ID))
1043                .unwrap();
1044        assert!(is_operations_target(&target));
1045        assert_eq!(
1046            delivery_mode_for(target.resource_type, CommandDeliveryMode::Push),
1047            CommandDeliveryMode::Push
1048        );
1049
1050        // Without the worker in the stack, addressing it fails like any
1051        // missing target instead of resolving to something else.
1052        let err = select_command_target("dep-1", &[], Some(OPERATIONS_WORKER_COMMAND_TARGET_ID))
1053            .unwrap_err();
1054        assert_eq!(err.code, "COMMAND_TARGET_NOT_FOUND");
1055    }
1056
1057    #[test]
1058    fn shorthand_never_selects_the_operations_worker() {
1059        let only_worker = vec![CommandTarget::new(
1060            OPERATIONS_WORKER_COMMAND_TARGET_ID,
1061            CommandTargetType::Worker,
1062        )];
1063        let err = select_command_target("dep-1", &only_worker, None).unwrap_err();
1064        assert_eq!(err.code, "NO_COMMAND_TARGETS");
1065
1066        let with_app = vec![
1067            CommandTarget::new(
1068                OPERATIONS_WORKER_COMMAND_TARGET_ID,
1069                CommandTargetType::Worker,
1070            ),
1071            CommandTarget::new("api", CommandTargetType::Worker),
1072        ];
1073        let target = select_command_target("dep-1", &with_app, None).unwrap();
1074        assert_eq!(target.resource_id, "api");
1075    }
1076
1077    #[test]
1078    fn operator_target_is_not_shadowed_by_a_same_named_stack_resource() {
1079        // Even if a stack somehow registered a "operator" worker, the reserved id
1080        // resolves to the operator daemon (the short-circuit wins).
1081        let targets = vec![CommandTarget::new(
1082            OPERATOR_COMMAND_TARGET_ID,
1083            CommandTargetType::Worker,
1084        )];
1085        let target =
1086            select_command_target("dep-1", &targets, Some(OPERATOR_COMMAND_TARGET_ID)).unwrap();
1087        assert_eq!(target.resource_type, CommandTargetType::Daemon);
1088    }
1089}