Skip to main content

deepstrike_core/proc/
mod.rs

1use compact_str::CompactString;
2use serde::{Deserialize, Serialize};
3
4use crate::types::agent::{AgentIsolation, AgentRole, ContextInheritance};
5use crate::types::result::{SubAgentResult, TerminationReason};
6
7/// Kernel-owned lifecycle state for a spawned agent process.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(rename_all = "snake_case")]
10pub enum ProcessState {
11    Running,
12    Joined,
13    Failed,
14}
15
16impl ProcessState {
17    pub fn label(self) -> &'static str {
18        match self {
19            Self::Running => "running",
20            Self::Joined => "joined",
21            Self::Failed => "failed",
22        }
23    }
24}
25
26/// Project a task's schedulability onto the coarser process lifecycle exposed in the
27/// `AgentProcess` view. Inverse of `impl From<ProcessState> for TaskLifecycle`: a child task is
28/// `Joined` once it completed successfully, `Failed` on any other terminal reason, else `Running`.
29fn process_state_of(state: crate::scheduler::tcb::TaskLifecycle) -> ProcessState {
30    use crate::scheduler::tcb::TaskLifecycle;
31    match state {
32        TaskLifecycle::Done(TerminationReason::Completed) => ProcessState::Joined,
33        TaskLifecycle::Done(_) => ProcessState::Failed,
34        _ => ProcessState::Running,
35    }
36}
37
38/// A sub-agent process registered by the kernel.
39///
40/// The kernel owns only declarative lifecycle state. Host execution,
41/// worktree/remote isolation, I/O, and concurrency remain SDK concerns.
42#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct AgentProcess {
44    pub agent_id: CompactString,
45    pub parent_session_id: CompactString,
46    pub role: AgentRole,
47    pub isolation: AgentIsolation,
48    pub context_inheritance: ContextInheritance,
49    pub state: ProcessState,
50    #[serde(default, skip_serializing_if = "Vec::is_empty")]
51    pub permitted_capability_ids: Vec<CompactString>,
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub result: Option<SubAgentResult>,
54}
55
56impl AgentProcess {
57    /// Reconstruct an `AgentProcess` from a child [`crate::scheduler::tcb::Tcb`] (M1 收口).
58    ///
59    /// Returns `None` for the root task (no `proc`). This is the bridge that makes the
60    /// `AgentProcess` records a *derived view* over the kernel's `TaskTable`: the sub-agent's
61    /// declarative identity lives on the TCB, and the `AgentProcess` shape — the SDK ABI /
62    /// session-log contract — is rebuilt on demand without a second source of truth.
63    pub fn from_tcb(tcb: &crate::scheduler::tcb::Tcb) -> Option<Self> {
64        let info = tcb.proc.as_ref()?;
65        Some(Self {
66            agent_id: tcb.id.clone(),
67            parent_session_id: info.parent_session_id.clone(),
68            role: info.role,
69            isolation: info.isolation,
70            context_inheritance: info.context_inheritance,
71            state: process_state_of(tcb.state),
72            permitted_capability_ids: tcb.caps.clone(),
73            result: info.result.clone(),
74        })
75    }
76
77    pub fn result_termination_label(&self) -> Option<&'static str> {
78        Some(self.result.as_ref()?.result.termination.label())
79    }
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85    use crate::scheduler::policy::SchedulerBudget;
86    use crate::scheduler::tcb::{Tcb, TaskLifecycle};
87    use crate::types::agent::{AgentIdentity, AgentRole, AgentRunSpec, IsolationManifest};
88    use crate::types::capability::CapabilityManifest;
89
90    fn child_tcb(id: &str) -> Tcb {
91        let spec = AgentRunSpec::new(
92            AgentIdentity::sub_agent(id, &format!("{id}-session")),
93            AgentRole::Implement,
94            "do work",
95        );
96        let manifest = IsolationManifest::from_spec(&spec, "parent-sess", &CapabilityManifest::new());
97        Tcb::spawned(&manifest, SchedulerBudget::default())
98    }
99
100    #[test]
101    fn from_tcb_is_none_for_root_task() {
102        let root = Tcb::root("root", SchedulerBudget::default());
103        assert!(AgentProcess::from_tcb(&root).is_none());
104    }
105
106    #[test]
107    fn from_tcb_reconstructs_running_process() {
108        let tcb = child_tcb("worker");
109        let p = AgentProcess::from_tcb(&tcb).expect("child reconstructs a process");
110        assert_eq!(p.agent_id.as_str(), "worker");
111        assert_eq!(p.parent_session_id.as_str(), "parent-sess");
112        assert_eq!(p.role, AgentRole::Implement);
113        assert_eq!(p.state, ProcessState::Running);
114        assert!(p.result.is_none());
115    }
116
117    #[test]
118    fn process_state_of_maps_terminal_task_states() {
119        assert_eq!(process_state_of(TaskLifecycle::Running), ProcessState::Running);
120        assert_eq!(
121            process_state_of(TaskLifecycle::Done(TerminationReason::Completed)),
122            ProcessState::Joined
123        );
124        assert_eq!(
125            process_state_of(TaskLifecycle::Done(TerminationReason::Error)),
126            ProcessState::Failed
127        );
128        assert_eq!(
129            process_state_of(TaskLifecycle::Done(TerminationReason::Timeout)),
130            ProcessState::Failed
131        );
132    }
133}