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    /// The logical task that owns this process — the kernel's own lineage fact (§10.4). Never a
46    /// host session id: mapping a child task onto a child session stays host-side (§5.2, §22.6).
47    pub parent_task_id: CompactString,
48    pub role: AgentRole,
49    pub isolation: AgentIsolation,
50    pub context_inheritance: ContextInheritance,
51    pub state: ProcessState,
52    #[serde(default, skip_serializing_if = "Vec::is_empty")]
53    pub permitted_capability_ids: Vec<CompactString>,
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub result: Option<SubAgentResult>,
56}
57
58impl AgentProcess {
59    /// Reconstruct an `AgentProcess` from a child [`crate::scheduler::tcb::Tcb`] (M1 收口).
60    ///
61    /// Returns `None` for the root task (no `proc`). This is the bridge that makes the
62    /// `AgentProcess` records a *derived view* over the kernel's `TaskTable`: the sub-agent's
63    /// declarative identity lives on the TCB, and the `AgentProcess` shape — the SDK ABI /
64    /// session-log contract — is rebuilt on demand without a second source of truth.
65    pub fn from_tcb(tcb: &crate::scheduler::tcb::Tcb) -> Option<Self> {
66        let info = tcb.proc.as_ref()?;
67        Some(Self {
68            agent_id: tcb.id.clone(),
69            parent_task_id: tcb.parent.clone().unwrap_or_default(),
70            role: info.role,
71            isolation: info.isolation,
72            context_inheritance: info.context_inheritance,
73            state: process_state_of(tcb.state),
74            permitted_capability_ids: tcb.caps.clone(),
75            result: info.result.clone(),
76        })
77    }
78
79    pub fn result_termination_label(&self) -> Option<&'static str> {
80        Some(self.result.as_ref()?.result.termination.label())
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87    use crate::scheduler::policy::SchedulerBudget;
88    use crate::scheduler::tcb::{TaskLifecycle, Tcb};
89    use crate::types::agent::{AgentIdentity, AgentRole, AgentRunSpec, IsolationManifest};
90    use crate::types::capability::CapabilityManifest;
91
92    fn child_tcb(id: &str) -> Tcb {
93        let spec = AgentRunSpec::new(
94            AgentIdentity::sub_agent(id, format!("{id}-session")),
95            AgentRole::Implement,
96            "do work",
97        );
98        let manifest = IsolationManifest::from_spec(&spec, &CapabilityManifest::new());
99        Tcb::spawned(&manifest, SchedulerBudget::default())
100    }
101
102    #[test]
103    fn from_tcb_is_none_for_root_task() {
104        let root = Tcb::root("root", SchedulerBudget::default());
105        assert!(AgentProcess::from_tcb(&root).is_none());
106    }
107
108    #[test]
109    fn from_tcb_reconstructs_running_process() {
110        let tcb = child_tcb("worker");
111        let p = AgentProcess::from_tcb(&tcb).expect("child reconstructs a process");
112        assert_eq!(p.agent_id.as_str(), "worker");
113        assert_eq!(
114            p.parent_task_id.as_str(),
115            "root",
116            "lineage is the logical parent task, not a host session"
117        );
118        assert_eq!(p.role, AgentRole::Implement);
119        assert_eq!(p.state, ProcessState::Running);
120        assert!(p.result.is_none());
121    }
122
123    #[test]
124    fn process_state_of_maps_terminal_task_states() {
125        assert_eq!(
126            process_state_of(TaskLifecycle::Running),
127            ProcessState::Running
128        );
129        assert_eq!(
130            process_state_of(TaskLifecycle::Done(TerminationReason::Completed)),
131            ProcessState::Joined
132        );
133        assert_eq!(
134            process_state_of(TaskLifecycle::Done(TerminationReason::Error)),
135            ProcessState::Failed
136        );
137        assert_eq!(
138            process_state_of(TaskLifecycle::Done(TerminationReason::Timeout)),
139            ProcessState::Failed
140        );
141    }
142}