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/// Target-selection rules shared by both the
149/// in-memory and SQLite registries route through.
150///
151/// - `requested = Some(id)`: the id must be well-formed (no `:`) and name an
152///   existing command-capable target, else `COMMAND_TARGET_NOT_FOUND`. An empty
153///   id never falls back to shorthand. The reserved
154///   [`OPERATOR_COMMAND_TARGET_ID`] always resolves to a pull-mode daemon
155///   target for the operator, independent of the stack.
156/// - `requested = None` (single-target shorthand): exactly one non-reserved
157///   stack target must exist, else `COMMAND_TARGET_AMBIGUOUS` (more than one)
158///   or `NO_COMMAND_TARGETS` (none). A registered target named
159///   [`OPERATOR_COMMAND_TARGET_ID`] is excluded so shorthand can never address
160///   the operator.
161///
162/// The resolved target's own id is also validated, so a target registered with
163/// a `:`-bearing id can never resolve into the key grammar.
164pub fn select_command_target(
165    deployment_id: &str,
166    targets: &[CommandTarget],
167    requested: Option<&str>,
168) -> Result<CommandTarget> {
169    // The operator is a reserved target, not a stack resource — resolve it
170    // directly so operations commands can be addressed to the operator without
171    // it having to appear in the deployment's command-capable stack targets.
172    if requested == Some(OPERATOR_COMMAND_TARGET_ID) {
173        return Ok(CommandTarget::new(
174            OPERATOR_COMMAND_TARGET_ID.to_string(),
175            CommandTargetType::Daemon,
176        ));
177    }
178
179    let target = match requested {
180        Some(resource_id) => {
181            // Reject ids that would break the key grammar before any lookup.
182            validate_command_target_id(resource_id)?;
183            // An empty resource id is never a valid target — in particular it
184            // must NOT silently fall back to shorthand resolution.
185            let found = if resource_id.is_empty() {
186                None
187            } else {
188                targets.iter().find(|t| t.resource_id == resource_id)
189            };
190            found
191                .ok_or_else(|| {
192                    AlienError::new(ErrorData::CommandTargetNotFound {
193                        resource_id: resource_id.to_string(),
194                        deployment_id: deployment_id.to_string(),
195                    })
196                })?
197                .clone()
198        }
199        None => {
200            let mut candidates = targets
201                .iter()
202                .filter(|target| target.resource_id != OPERATOR_COMMAND_TARGET_ID);
203            let Some(single) = candidates.next() else {
204                return Err(AlienError::new(ErrorData::NoCommandTargets {
205                    deployment_id: deployment_id.to_string(),
206                }));
207            };
208            if candidates.next().is_some() {
209                return Err(AlienError::new(ErrorData::CommandTargetAmbiguous {
210                    deployment_id: deployment_id.to_string(),
211                }));
212            }
213            single.clone()
214        }
215    };
216
217    // A registered target whose id breaks the key grammar must never resolve.
218    validate_command_target_id(&target.resource_id)?;
219    Ok(target)
220}
221
222/// Pinned per-type delivery rule — the single implementation both registries
223/// route through. Container and Daemon targets are always Pull; a Worker target
224/// follows `worker_mode`, the caller's derived worker context (production: Push
225/// only when the platform has a push path AND `stack_settings.deployment_model`
226/// is Push).
227pub fn delivery_mode_for(
228    resource_type: CommandTargetType,
229    worker_mode: CommandDeliveryMode,
230) -> CommandDeliveryMode {
231    match resource_type {
232        CommandTargetType::Container | CommandTargetType::Daemon => CommandDeliveryMode::Pull,
233        CommandTargetType::Worker => worker_mode,
234    }
235}
236
237/// Abstraction for command metadata storage and lifecycle tracking.
238///
239/// The CommandRegistry is the source of truth for all command metadata.
240/// Implementations store command state, timestamps, and result information.
241#[async_trait]
242pub trait CommandRegistry: Send + Sync {
243    /// Resolve which command-capable resource a command is addressed to.
244    ///
245    /// - `requested = Some(id)`: the target must exist and be command-capable,
246    ///   else `COMMAND_TARGET_NOT_FOUND` (an empty id never resolves).
247    /// - `requested = None` (single-target shorthand): exactly one
248    ///   command-capable target must exist, else `COMMAND_TARGET_AMBIGUOUS`
249    ///   (more than one) or `NO_COMMAND_TARGETS` (none).
250    ///
251    /// The returned delivery mode is derived from the target: Container and
252    /// Daemon targets are always Pull. Worker delivery is resolved from the
253    /// deployment model and platform: Kubernetes uses its in-cluster operator
254    /// relay, Local supports embedded Push and remote Pull, and cloud Workers
255    /// use their provider push path only for Push deployments.
256    async fn resolve_target(
257        &self,
258        deployment_id: &str,
259        requested: Option<&str>,
260    ) -> Result<ResolvedCommandTarget>;
261
262    /// Create a new command addressed to a previously resolved target and
263    /// return metadata for routing.
264    ///
265    /// The registry generates the command_id and stores all metadata
266    /// (state, target, timestamps, etc.).
267    async fn create_command(
268        &self,
269        deployment_id: &str,
270        command_name: &str,
271        target: &ResolvedCommandTarget,
272        initial_state: CommandState,
273        deadline: Option<DateTime<Utc>>,
274        request_size_bytes: Option<u64>,
275    ) -> Result<CommandMetadata>;
276
277    /// Get metadata needed to build an envelope during lease acquisition.
278    ///
279    /// Returns None if command doesn't exist.
280    async fn get_command_metadata(&self, command_id: &str) -> Result<Option<CommandEnvelopeData>>;
281
282    /// Get full command status for status endpoint.
283    ///
284    /// Returns None if command doesn't exist.
285    async fn get_command_status(&self, command_id: &str) -> Result<Option<CommandStatus>>;
286
287    /// Get the canonical ownership fields used to authorize command reads.
288    ///
289    /// The status record is the command registry's source of truth for these
290    /// fields, so this does not require a deployment lookup.
291    async fn get_command_access_context(
292        &self,
293        command_id: &str,
294    ) -> Result<Option<CommandAccessContext>> {
295        Ok(self
296            .get_command_status(command_id)
297            .await?
298            .map(|status| CommandAccessContext {
299                workspace_id: status.workspace_id,
300                project_id: status.project_id,
301                deployment_id: status.deployment_id,
302                target: status.target,
303            }))
304    }
305
306    /// Atomically update a non-terminal command's lifecycle state.
307    ///
308    /// Returns `false` when the command became terminal before the update.
309    /// Terminal transitions use [`Self::complete_command`] instead.
310    async fn update_command_state(
311        &self,
312        command_id: &str,
313        state: CommandState,
314        dispatched_at: Option<DateTime<Utc>>,
315        completed_at: Option<DateTime<Utc>>,
316        response_size_bytes: Option<u64>,
317        error: Option<serde_json::Value>,
318    ) -> Result<bool>;
319
320    /// Atomically transition a command from any NON-terminal state to the
321    /// given terminal `state`.
322    ///
323    /// Returns `false` when the command was already terminal — a concurrent
324    /// submitter won the race — so a terminal record can never be
325    /// overwritten by a late duplicate (redelivered execution racing the
326    /// original whose lease expired).
327    async fn complete_command(
328        &self,
329        command_id: &str,
330        state: CommandState,
331        completed_at: DateTime<Utc>,
332        response_size_bytes: Option<u64>,
333        error: Option<serde_json::Value>,
334    ) -> Result<bool>;
335
336    /// Atomically mark a command Dispatched unless it is already terminal.
337    ///
338    /// Returns `false` when the command reached a terminal state in the
339    /// meantime — e.g. a lease TTL-expired, a new poller won the takeover
340    /// put, and the ORIGINAL holder's submit landed between the poller's
341    /// terminal check and this write. An unconditional write there would
342    /// flip a committed terminal state back to Dispatched.
343    async fn mark_dispatched_if_not_terminal(
344        &self,
345        command_id: &str,
346        dispatched_at: DateTime<Utc>,
347    ) -> Result<bool>;
348
349    /// Increment attempt count (on lease release/expiry).
350    ///
351    /// Returns the new attempt number.
352    async fn increment_attempt(&self, command_id: &str) -> Result<u32>;
353}
354
355/// In-memory implementation for tests and local development.
356///
357/// Tracks command metadata in memory. Targets are registered explicitly via
358/// [`register_target`](Self::register_target); resolution then follows exactly
359/// the production rules documented on [`CommandRegistry::resolve_target`].
360pub struct InMemoryCommandRegistry {
361    commands: Arc<RwLock<HashMap<String, CommandRecord>>>,
362    /// Registered command-capable targets, in registration (declaration) order.
363    ///
364    /// Not scoped per deployment: this registry models a single local
365    /// deployment universe, so every deployment id resolves against the same
366    /// target set (the per-call resolution rules are identical to production).
367    targets: Arc<RwLock<Vec<CommandTarget>>>,
368    /// Delivery mode for Worker targets.
369    ///
370    /// In production this is derived from the deployment's platform and stack
371    /// settings (Push only when the platform has a push path AND
372    /// `stack_settings.deployment_model == Push`). The registrant supplies
373    /// that derived context here once, and the registry applies the pinned
374    /// per-type rule itself — so it is impossible to register a Container or
375    /// Daemon target with a Push mode that production could never produce.
376    worker_delivery_mode: CommandDeliveryMode,
377}
378
379impl InMemoryCommandRegistry {
380    /// Create a new in-memory registry whose Worker targets use Pull delivery
381    /// (the safe default: matches platforms without a push path).
382    pub fn new() -> Self {
383        Self::with_worker_delivery_mode(CommandDeliveryMode::Pull)
384    }
385
386    /// Create a new in-memory registry with the specified Worker delivery mode.
387    ///
388    /// Container/Daemon targets are always Pull regardless of this setting.
389    pub fn with_worker_delivery_mode(worker_delivery_mode: CommandDeliveryMode) -> Self {
390        Self {
391            commands: Arc::new(RwLock::new(HashMap::new())),
392            targets: Arc::new(RwLock::new(Vec::new())),
393            worker_delivery_mode,
394        }
395    }
396
397    /// Register a command-capable target that commands can resolve to.
398    ///
399    /// Mirrors production, where the target set comes from the deployment's
400    /// stack (`Stack::command_targets()`: Worker/Container/Daemon resources
401    /// with `commands_enabled`). The id is validated through the same shared
402    /// guard as resolution, so a `:`-bearing id is rejected here at registration
403    /// rather than surfacing later as a key-grammar collision.
404    pub async fn register_target(
405        &self,
406        resource_id: impl Into<String>,
407        resource_type: CommandTargetType,
408    ) -> Result<()> {
409        let resource_id = resource_id.into();
410        validate_command_target_id(&resource_id)?;
411        self.targets
412            .write()
413            .await
414            .push(CommandTarget::new(resource_id, resource_type));
415        Ok(())
416    }
417
418    /// List all command IDs (useful for debugging/testing)
419    #[allow(dead_code)]
420    pub async fn list_command_ids(&self) -> Vec<String> {
421        let commands = self.commands.read().await;
422        commands.keys().cloned().collect()
423    }
424}
425
426impl Default for InMemoryCommandRegistry {
427    fn default() -> Self {
428        Self::new()
429    }
430}
431
432#[async_trait]
433impl CommandRegistry for InMemoryCommandRegistry {
434    async fn resolve_target(
435        &self,
436        deployment_id: &str,
437        requested: Option<&str>,
438    ) -> Result<ResolvedCommandTarget> {
439        let targets = self.targets.read().await;
440        let target = select_command_target(deployment_id, &targets, requested)?;
441        let delivery_mode = delivery_mode_for(target.resource_type, self.worker_delivery_mode);
442        Ok(ResolvedCommandTarget {
443            target,
444            delivery_mode,
445        })
446    }
447
448    async fn create_command(
449        &self,
450        deployment_id: &str,
451        command_name: &str,
452        target: &ResolvedCommandTarget,
453        initial_state: CommandState,
454        deadline: Option<DateTime<Utc>>,
455        request_size_bytes: Option<u64>,
456    ) -> Result<CommandMetadata> {
457        let command_id = format!("cmd_{}", Uuid::new_v4());
458
459        let record = CommandRecord {
460            id: command_id.clone(),
461            deployment_id: deployment_id.to_string(),
462            command: command_name.to_string(),
463            state: initial_state,
464            attempt: 1,
465            deadline,
466            created_at: Utc::now(),
467            dispatched_at: None,
468            completed_at: None,
469            request_size_bytes,
470            response_size_bytes: None,
471            error: None,
472            target: target.target.clone(),
473            delivery_mode: target.delivery_mode,
474            project_id: "default".to_string(),
475        };
476
477        self.commands
478            .write()
479            .await
480            .insert(command_id.clone(), record);
481
482        Ok(CommandMetadata {
483            command_id,
484            target: target.target.clone(),
485            delivery_mode: target.delivery_mode,
486            project_id: "default".to_string(),
487        })
488    }
489
490    async fn get_command_metadata(&self, command_id: &str) -> Result<Option<CommandEnvelopeData>> {
491        let commands = self.commands.read().await;
492
493        Ok(commands.get(command_id).map(|r| CommandEnvelopeData {
494            command_id: r.id.clone(),
495            deployment_id: r.deployment_id.clone(),
496            command: r.command.clone(),
497            attempt: r.attempt,
498            deadline: r.deadline,
499            state: r.state,
500            target: r.target.clone(),
501            delivery_mode: r.delivery_mode,
502        }))
503    }
504
505    async fn get_command_status(&self, command_id: &str) -> Result<Option<CommandStatus>> {
506        let commands = self.commands.read().await;
507
508        Ok(commands.get(command_id).map(|r| CommandStatus {
509            command_id: r.id.clone(),
510            workspace_id: "default".to_string(),
511            project_id: r.project_id.clone(),
512            deployment_id: r.deployment_id.clone(),
513            command: r.command.clone(),
514            state: r.state,
515            attempt: r.attempt,
516            deadline: r.deadline,
517            created_at: r.created_at,
518            dispatched_at: r.dispatched_at,
519            completed_at: r.completed_at,
520            error: r.error.clone(),
521            request_size_bytes: r.request_size_bytes,
522            response_size_bytes: r.response_size_bytes,
523            target: r.target.clone(),
524        }))
525    }
526
527    async fn update_command_state(
528        &self,
529        command_id: &str,
530        state: CommandState,
531        dispatched_at: Option<DateTime<Utc>>,
532        completed_at: Option<DateTime<Utc>>,
533        response_size_bytes: Option<u64>,
534        error: Option<serde_json::Value>,
535    ) -> Result<bool> {
536        let mut commands = self.commands.write().await;
537
538        if let Some(record) = commands.get_mut(command_id) {
539            if record.state.is_terminal() {
540                return Ok(false);
541            }
542            record.state = state;
543
544            if let Some(ts) = dispatched_at {
545                record.dispatched_at = Some(ts);
546            }
547
548            if let Some(ts) = completed_at {
549                record.completed_at = Some(ts);
550            }
551
552            if let Some(size) = response_size_bytes {
553                record.response_size_bytes = Some(size);
554            }
555
556            if let Some(err) = error {
557                record.error = Some(err);
558            }
559            return Ok(true);
560        }
561
562        Ok(false)
563    }
564
565    async fn complete_command(
566        &self,
567        command_id: &str,
568        state: CommandState,
569        completed_at: DateTime<Utc>,
570        response_size_bytes: Option<u64>,
571        error: Option<serde_json::Value>,
572    ) -> Result<bool> {
573        let mut commands = self.commands.write().await;
574        let Some(record) = commands.get_mut(command_id) else {
575            return Ok(false);
576        };
577        if record.state.is_terminal() {
578            return Ok(false);
579        }
580        record.state = state;
581        record.completed_at = Some(completed_at);
582        if let Some(size) = response_size_bytes {
583            record.response_size_bytes = Some(size);
584        }
585        if let Some(err) = error {
586            record.error = Some(err);
587        }
588        Ok(true)
589    }
590
591    async fn mark_dispatched_if_not_terminal(
592        &self,
593        command_id: &str,
594        dispatched_at: DateTime<Utc>,
595    ) -> Result<bool> {
596        let mut commands = self.commands.write().await;
597        let Some(record) = commands.get_mut(command_id) else {
598            return Ok(false);
599        };
600        if record.state.is_terminal() {
601            return Ok(false);
602        }
603        record.state = CommandState::Dispatched;
604        record.dispatched_at = Some(dispatched_at);
605        Ok(true)
606    }
607
608    async fn increment_attempt(&self, command_id: &str) -> Result<u32> {
609        let mut commands = self.commands.write().await;
610
611        if let Some(record) = commands.get_mut(command_id) {
612            record.attempt += 1;
613            Ok(record.attempt)
614        } else {
615            Ok(1) // Default if not found
616        }
617    }
618}
619
620#[cfg(test)]
621mod tests {
622    use super::*;
623    use alien_core::{CommandDeliveryMode, CommandTarget, CommandTargetType};
624
625    async fn resolved(
626        registry: &InMemoryCommandRegistry,
627        requested: Option<&str>,
628    ) -> Result<ResolvedCommandTarget> {
629        registry.resolve_target("dep-1", requested).await
630    }
631
632    #[tokio::test]
633    async fn test_resolve_explicit_target_found() {
634        let registry = InMemoryCommandRegistry::new();
635        registry
636            .register_target("worker-a", CommandTargetType::Worker)
637            .await
638            .unwrap();
639        registry
640            .register_target("daemon-b", CommandTargetType::Daemon)
641            .await
642            .unwrap();
643
644        let result = resolved(&registry, Some("daemon-b")).await.unwrap();
645        assert_eq!(
646            result.target,
647            CommandTarget::new("daemon-b", CommandTargetType::Daemon)
648        );
649    }
650
651    #[tokio::test]
652    async fn test_resolve_explicit_unknown_target_is_not_found() {
653        let registry = InMemoryCommandRegistry::new();
654        registry
655            .register_target("worker-a", CommandTargetType::Worker)
656            .await
657            .unwrap();
658
659        let err = resolved(&registry, Some("no-such-resource"))
660            .await
661            .unwrap_err();
662        assert_eq!(err.code, "COMMAND_TARGET_NOT_FOUND");
663        assert_eq!(err.http_status_code, Some(404));
664    }
665
666    #[tokio::test]
667    async fn test_resolve_explicit_empty_string_is_not_found() {
668        let registry = InMemoryCommandRegistry::new();
669        registry
670            .register_target("worker-a", CommandTargetType::Worker)
671            .await
672            .unwrap();
673
674        // An explicitly requested empty resource id must never resolve (in
675        // particular it must NOT fall back to shorthand resolution).
676        let err = resolved(&registry, Some("")).await.unwrap_err();
677        assert_eq!(err.code, "COMMAND_TARGET_NOT_FOUND");
678    }
679
680    #[tokio::test]
681    async fn test_resolve_shorthand_single_target_resolves() {
682        let registry = InMemoryCommandRegistry::new();
683        registry
684            .register_target("container-1", CommandTargetType::Container)
685            .await
686            .unwrap();
687
688        let result = resolved(&registry, None).await.unwrap();
689        assert_eq!(
690            result.target,
691            CommandTarget::new("container-1", CommandTargetType::Container)
692        );
693    }
694
695    #[tokio::test]
696    async fn test_resolve_shorthand_two_targets_is_ambiguous() {
697        let registry = InMemoryCommandRegistry::new();
698        registry
699            .register_target("worker-a", CommandTargetType::Worker)
700            .await
701            .unwrap();
702        registry
703            .register_target("worker-b", CommandTargetType::Worker)
704            .await
705            .unwrap();
706
707        let err = resolved(&registry, None).await.unwrap_err();
708        assert_eq!(err.code, "COMMAND_TARGET_AMBIGUOUS");
709        assert_eq!(err.http_status_code, Some(409));
710    }
711
712    #[tokio::test]
713    async fn test_resolve_shorthand_zero_targets_is_no_targets() {
714        let registry = InMemoryCommandRegistry::new();
715
716        let err = resolved(&registry, None).await.unwrap_err();
717        assert_eq!(err.code, "NO_COMMAND_TARGETS");
718        assert_eq!(err.http_status_code, Some(422));
719    }
720
721    #[tokio::test]
722    async fn test_resolve_shorthand_operator_only_is_no_targets() {
723        let registry = InMemoryCommandRegistry::new();
724        registry
725            .register_target(OPERATOR_COMMAND_TARGET_ID, CommandTargetType::Daemon)
726            .await
727            .unwrap();
728
729        let err = resolved(&registry, None).await.unwrap_err();
730        assert_eq!(err.code, "NO_COMMAND_TARGETS");
731        assert_eq!(err.http_status_code, Some(422));
732    }
733
734    #[tokio::test]
735    async fn test_resolve_shorthand_ignores_operator_beside_one_stack_target() {
736        let registry = InMemoryCommandRegistry::new();
737        registry
738            .register_target(OPERATOR_COMMAND_TARGET_ID, CommandTargetType::Daemon)
739            .await
740            .unwrap();
741        registry
742            .register_target("daemon-1", CommandTargetType::Daemon)
743            .await
744            .unwrap();
745
746        let result = resolved(&registry, None).await.unwrap();
747        assert_eq!(
748            result.target,
749            CommandTarget::new("daemon-1", CommandTargetType::Daemon)
750        );
751    }
752
753    #[tokio::test]
754    async fn test_delivery_mode_container_and_daemon_always_pull() {
755        // Even with a Push-capable worker context, Container/Daemon are Pull.
756        let registry =
757            InMemoryCommandRegistry::with_worker_delivery_mode(CommandDeliveryMode::Push);
758        registry
759            .register_target("container-1", CommandTargetType::Container)
760            .await
761            .unwrap();
762        registry
763            .register_target("daemon-1", CommandTargetType::Daemon)
764            .await
765            .unwrap();
766
767        let container = resolved(&registry, Some("container-1")).await.unwrap();
768        assert_eq!(container.delivery_mode, CommandDeliveryMode::Pull);
769
770        let daemon = resolved(&registry, Some("daemon-1")).await.unwrap();
771        assert_eq!(daemon.delivery_mode, CommandDeliveryMode::Pull);
772    }
773
774    #[tokio::test]
775    async fn test_delivery_mode_worker_follows_registered_context() {
776        let push_registry =
777            InMemoryCommandRegistry::with_worker_delivery_mode(CommandDeliveryMode::Push);
778        push_registry
779            .register_target("worker-1", CommandTargetType::Worker)
780            .await
781            .unwrap();
782        let push_worker = push_registry
783            .resolve_target("dep-1", Some("worker-1"))
784            .await
785            .unwrap();
786        assert_eq!(push_worker.delivery_mode, CommandDeliveryMode::Push);
787
788        // A manager-side pending path (e.g. Kubernetes operator relay, or a
789        // cloud stack whose deployment model is Pull).
790        let pull_registry =
791            InMemoryCommandRegistry::with_worker_delivery_mode(CommandDeliveryMode::Pull);
792        pull_registry
793            .register_target("worker-1", CommandTargetType::Worker)
794            .await
795            .unwrap();
796        let pull_worker = pull_registry
797            .resolve_target("dep-1", Some("worker-1"))
798            .await
799            .unwrap();
800        assert_eq!(pull_worker.delivery_mode, CommandDeliveryMode::Pull);
801    }
802
803    #[tokio::test]
804    async fn test_create_command_stores_target_in_status_and_envelope_data() {
805        let registry = InMemoryCommandRegistry::new();
806        registry
807            .register_target("daemon-1", CommandTargetType::Daemon)
808            .await
809            .unwrap();
810
811        let resolved_target = registry.resolve_target("dep-1", None).await.unwrap();
812        let metadata = registry
813            .create_command(
814                "dep-1",
815                "sync-data",
816                &resolved_target,
817                CommandState::Pending,
818                None,
819                None,
820            )
821            .await
822            .unwrap();
823
824        let expected = CommandTarget::new("daemon-1", CommandTargetType::Daemon);
825        assert_eq!(metadata.target, expected);
826        assert_eq!(metadata.delivery_mode, CommandDeliveryMode::Pull);
827
828        let status = registry
829            .get_command_status(&metadata.command_id)
830            .await
831            .unwrap()
832            .unwrap();
833        assert_eq!(status.target, expected);
834
835        let envelope_data = registry
836            .get_command_metadata(&metadata.command_id)
837            .await
838            .unwrap()
839            .unwrap();
840        assert_eq!(envelope_data.target, expected);
841        assert_eq!(envelope_data.delivery_mode, CommandDeliveryMode::Pull);
842    }
843
844    #[tokio::test]
845    async fn non_terminal_update_cannot_resurrect_completed_command() {
846        let registry = InMemoryCommandRegistry::new();
847        registry
848            .register_target("daemon-1", CommandTargetType::Daemon)
849            .await
850            .unwrap();
851        let target = registry.resolve_target("dep-1", None).await.unwrap();
852        let command = registry
853            .create_command(
854                "dep-1",
855                "run",
856                &target,
857                CommandState::Dispatched,
858                None,
859                None,
860            )
861            .await
862            .unwrap();
863
864        assert!(registry
865            .complete_command(
866                &command.command_id,
867                CommandState::Succeeded,
868                Utc::now(),
869                None,
870                None,
871            )
872            .await
873            .unwrap());
874        assert!(!registry
875            .update_command_state(
876                &command.command_id,
877                CommandState::Pending,
878                None,
879                None,
880                None,
881                None,
882            )
883            .await
884            .unwrap());
885        assert_eq!(
886            registry
887                .get_command_status(&command.command_id)
888                .await
889                .unwrap()
890                .unwrap()
891                .state,
892            CommandState::Succeeded
893        );
894    }
895
896    #[tokio::test]
897    async fn in_memory_command_access_uses_oss_tenant_context() {
898        let registry = InMemoryCommandRegistry::new();
899        registry
900            .register_target("worker-1", CommandTargetType::Worker)
901            .await
902            .unwrap();
903        let target = registry.resolve_target("dep-1", None).await.unwrap();
904        let command = registry
905            .create_command("dep-1", "run", &target, CommandState::Pending, None, None)
906            .await
907            .unwrap();
908
909        assert_eq!(command.project_id, "default");
910        assert_eq!(
911            registry
912                .get_command_access_context(&command.command_id)
913                .await
914                .unwrap()
915                .unwrap(),
916            CommandAccessContext {
917                workspace_id: "default".to_string(),
918                project_id: "default".to_string(),
919                deployment_id: "dep-1".to_string(),
920                target: CommandTarget::new("worker-1", CommandTargetType::Worker),
921            }
922        );
923    }
924
925    #[tokio::test]
926    async fn test_register_target_rejects_colon_in_id() {
927        let registry = InMemoryCommandRegistry::new();
928        let err = registry
929            .register_target("evil:pending:x", CommandTargetType::Worker)
930            .await
931            .unwrap_err();
932        assert_eq!(err.code, "COMMAND_TARGET_ID_INVALID");
933        assert_eq!(err.http_status_code, Some(400));
934    }
935
936    #[tokio::test]
937    async fn test_resolve_explicit_colon_id_is_invalid() {
938        let registry = InMemoryCommandRegistry::new();
939        registry
940            .register_target("worker-a", CommandTargetType::Worker)
941            .await
942            .unwrap();
943
944        // A requested id containing ':' is rejected with a typed error before
945        // any lookup — it can never be resolved into the key grammar.
946        let err = resolved(&registry, Some("worker-a:pending:1"))
947            .await
948            .unwrap_err();
949        assert_eq!(err.code, "COMMAND_TARGET_ID_INVALID");
950    }
951
952    #[test]
953    fn test_select_command_target_rejects_registered_colon_id() {
954        // Even if a `:`-bearing target slips into the slice (e.g. an unvalidated
955        // upstream path), selecting it fails loudly rather than resolving.
956        let targets = vec![CommandTarget::new("a:pending:x", CommandTargetType::Worker)];
957        let err = select_command_target("dep-1", &targets, None).unwrap_err();
958        assert_eq!(err.code, "COMMAND_TARGET_ID_INVALID");
959    }
960
961    #[test]
962    fn operator_target_resolves_without_a_stack_resource() {
963        // The reserved operator id resolves to a pull-mode daemon target even
964        // when no stack targets exist — operations commands address the operator
965        // itself, which is never a stack resource.
966        let target = select_command_target("dep-1", &[], Some(OPERATOR_COMMAND_TARGET_ID)).unwrap();
967        assert_eq!(target.resource_id, OPERATOR_COMMAND_TARGET_ID);
968        assert_eq!(target.resource_type, CommandTargetType::Daemon);
969        // A daemon target always delivers via pull, regardless of worker mode.
970        assert_eq!(
971            delivery_mode_for(target.resource_type, CommandDeliveryMode::Push),
972            CommandDeliveryMode::Pull
973        );
974    }
975
976    #[test]
977    fn operator_target_is_not_shadowed_by_a_same_named_stack_resource() {
978        // Even if a stack somehow registered a "operator" worker, the reserved id
979        // resolves to the operator daemon (the short-circuit wins).
980        let targets = vec![CommandTarget::new(
981            OPERATOR_COMMAND_TARGET_ID,
982            CommandTargetType::Worker,
983        )];
984        let target =
985            select_command_target("dep-1", &targets, Some(OPERATOR_COMMAND_TARGET_ID)).unwrap();
986        assert_eq!(target.resource_type, CommandTargetType::Daemon);
987    }
988}