Skip to main content

ag_session/
orchestration.rs

1//! Orchestration and orchestration-task lifecycle states.
2//!
3//! One orchestration groups the child sessions proposed by a single controller
4//! plan. The orchestration row tracks whether that plan is still awaiting the
5//! user's approval, actively fanning out, or settled; each task row tracks one
6//! child session through creation, execution, and settlement.
7
8use std::collections::HashSet;
9use std::fmt;
10use std::str::FromStr;
11
12use crate::model::SessionStatus;
13
14/// Maximum number of automatic focused-review remediation turns per managed
15/// worker settlement wave.
16pub const MAX_AUTOMATED_REVIEW_ITERATIONS: i64 = 3;
17
18/// Execution behavior for one persisted orchestration task.
19#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
20pub enum OrchestrationTaskKind {
21    /// Produces branch changes that proceed through review and integration.
22    #[default]
23    Implementation,
24    /// Produces a read-only report whose temporary worktree is discarded.
25    Research,
26}
27
28impl fmt::Display for OrchestrationTaskKind {
29    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
30        let value = match self {
31            OrchestrationTaskKind::Implementation => "Implementation",
32            OrchestrationTaskKind::Research => "Research",
33        };
34
35        formatter.write_str(value)
36    }
37}
38
39impl FromStr for OrchestrationTaskKind {
40    type Err = String;
41
42    fn from_str(value: &str) -> Result<Self, Self::Err> {
43        match value {
44            "Implementation" => Ok(OrchestrationTaskKind::Implementation),
45            "Research" => Ok(OrchestrationTaskKind::Research),
46            _ => Err(format!("Unknown orchestration task kind: {value}")),
47        }
48    }
49}
50
51/// Lifecycle state for one controller-owned orchestration.
52#[derive(Clone, Copy, Debug, Eq, PartialEq)]
53pub enum OrchestrationStatus {
54    /// The plan is persisted and parked on the campaign approval board.
55    AwaitingApproval,
56    /// The plan is approved and its tasks are fanning out.
57    Running,
58    /// Cancellation is blocking new fan-out while active children stop.
59    Canceling,
60    /// Every task settled and the controller is verifying the results.
61    Verifying,
62    /// Verification passed and user integration approval is required.
63    AwaitingIntegration,
64    /// Verified tasks are being merged or published in plan order.
65    Integrating,
66    /// Every verified task integrated and the campaign was archived.
67    Done,
68    /// The user canceled the orchestration or its controller session.
69    Canceled,
70}
71
72impl OrchestrationStatus {
73    /// Returns whether the orchestration is still open.
74    ///
75    /// An open plan blocks another plan from being persisted for the same
76    /// controller, including while it waits for approval.
77    pub fn is_active(self) -> bool {
78        matches!(
79            self,
80            OrchestrationStatus::AwaitingApproval
81                | OrchestrationStatus::Running
82                | OrchestrationStatus::Canceling
83                | OrchestrationStatus::Verifying
84                | OrchestrationStatus::AwaitingIntegration
85                | OrchestrationStatus::Integrating
86        )
87    }
88}
89
90impl fmt::Display for OrchestrationStatus {
91    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
92        let value = match self {
93            OrchestrationStatus::AwaitingApproval => "AwaitingApproval",
94            OrchestrationStatus::Running => "Running",
95            OrchestrationStatus::Canceling => "Canceling",
96            OrchestrationStatus::Verifying => "Verifying",
97            OrchestrationStatus::AwaitingIntegration => "AwaitingIntegration",
98            OrchestrationStatus::Integrating => "Integrating",
99            OrchestrationStatus::Done => "Done",
100            OrchestrationStatus::Canceled => "Canceled",
101        };
102
103        formatter.write_str(value)
104    }
105}
106
107impl FromStr for OrchestrationStatus {
108    type Err = String;
109
110    fn from_str(value: &str) -> Result<Self, Self::Err> {
111        match value {
112            "AwaitingApproval" => Ok(OrchestrationStatus::AwaitingApproval),
113            "Running" => Ok(OrchestrationStatus::Running),
114            "Canceling" => Ok(OrchestrationStatus::Canceling),
115            "Verifying" => Ok(OrchestrationStatus::Verifying),
116            "AwaitingIntegration" => Ok(OrchestrationStatus::AwaitingIntegration),
117            "Integrating" => Ok(OrchestrationStatus::Integrating),
118            "Done" => Ok(OrchestrationStatus::Done),
119            "Canceled" => Ok(OrchestrationStatus::Canceled),
120            _ => Err(format!("Unknown orchestration status: {value}")),
121        }
122    }
123}
124
125/// User-selected destination for verified orchestration task branches.
126#[derive(Clone, Copy, Debug, Eq, PartialEq)]
127pub enum IntegrationApproach {
128    /// Merge each verified child branch into the campaign base locally.
129    LocalMerge,
130    /// Publish each verified child branch as a forge review request.
131    ReviewRequest,
132}
133
134impl fmt::Display for IntegrationApproach {
135    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
136        let value = match self {
137            IntegrationApproach::LocalMerge => "LocalMerge",
138            IntegrationApproach::ReviewRequest => "ReviewRequest",
139        };
140
141        formatter.write_str(value)
142    }
143}
144
145impl FromStr for IntegrationApproach {
146    type Err = String;
147
148    fn from_str(value: &str) -> Result<Self, Self::Err> {
149        match value {
150            "LocalMerge" => Ok(IntegrationApproach::LocalMerge),
151            "ReviewRequest" => Ok(IntegrationApproach::ReviewRequest),
152            _ => Err(format!("Unknown integration approach: {value}")),
153        }
154    }
155}
156
157/// Lifecycle state for one orchestration task and its child session.
158#[derive(Clone, Copy, Debug, Eq, PartialEq)]
159pub enum OrchestrationTaskStatus {
160    /// Follow-up scope proposed by the controller and awaiting approval.
161    Proposed,
162    /// Persisted with the proposed plan, not yet approved or fanned out.
163    Planned,
164    /// The child session is being created and started.
165    Creating,
166    /// The child session is running its turn.
167    Running,
168    /// Focused review is running or awaiting a persisted result.
169    Reviewing,
170    /// The coordinator is applying one focused-review suggestion set.
171    ReviewApplying,
172    /// The child session parked on clarification questions.
173    WaitingForInput,
174    /// The child session finished and is ready for review or integration.
175    Ready,
176    /// A research child returned its report and its worktree was discarded.
177    Reported,
178    /// Approved feedback is being delivered to the existing managed child.
179    ContinuationPending,
180    /// Verification passed and this task awaits its integration gate.
181    AwaitingIntegration,
182    /// The coordinator has started branch merge or publication.
183    Merging,
184    /// Branch work was merged locally successfully.
185    Integrated,
186    /// The child branch was published and is waiting for its forge review
187    /// request to merge.
188    ReviewRequested,
189    /// Integration failed and requires attention.
190    IntegrationFailed,
191    /// Ownership permanently transferred from the coordinator to the user.
192    Detached,
193    /// The child session failed, or a straggler was canceled out of band.
194    Failed,
195    /// The task was canceled as part of a cascade cancel.
196    Canceled,
197}
198
199impl OrchestrationTaskStatus {
200    /// Maps one observed child-session status into the task state owned by
201    /// orchestration.
202    pub fn from_child_status(status: SessionStatus) -> Self {
203        match status {
204            SessionStatus::Draft
205            | SessionStatus::InProgress
206            | SessionStatus::Queued
207            | SessionStatus::Rebasing
208            | SessionStatus::Merging => Self::Running,
209            SessionStatus::Question => Self::WaitingForInput,
210            SessionStatus::Review | SessionStatus::AgentReview => Self::Reviewing,
211            SessionStatus::Merged | SessionStatus::Done => Self::Ready,
212            SessionStatus::Canceled => Self::Failed,
213        }
214    }
215
216    /// Returns whether the task reached a state that fan-in treats as settled.
217    ///
218    /// A canceled straggler counts as settled so out-of-band cancellation
219    /// unblocks the roll-up instead of stalling it.
220    pub fn is_settled(self) -> bool {
221        matches!(
222            self,
223            OrchestrationTaskStatus::Ready
224                | OrchestrationTaskStatus::Reported
225                | OrchestrationTaskStatus::Integrated
226                | OrchestrationTaskStatus::ReviewRequested
227                | OrchestrationTaskStatus::IntegrationFailed
228                | OrchestrationTaskStatus::Failed
229                | OrchestrationTaskStatus::Canceled
230                | OrchestrationTaskStatus::Detached
231        )
232    }
233
234    /// Returns the concise user-facing label shown in campaign status output.
235    pub fn campaign_label(self) -> &'static str {
236        self.labels().1
237    }
238
239    /// Returns whether the task currently occupies a parallelism slot.
240    ///
241    /// A task waiting for user input still holds its child session and
242    /// worktree, so it keeps consuming a slot until the user answers.
243    pub fn occupies_parallelism_slot(self) -> bool {
244        matches!(
245            self,
246            OrchestrationTaskStatus::Creating
247                | OrchestrationTaskStatus::Running
248                | OrchestrationTaskStatus::Reviewing
249                | OrchestrationTaskStatus::ReviewApplying
250                | OrchestrationTaskStatus::WaitingForInput
251                | OrchestrationTaskStatus::ContinuationPending
252                | OrchestrationTaskStatus::Merging
253        )
254    }
255
256    /// Returns whether a transition to `next` is valid.
257    ///
258    /// Retry re-enters `Creating` from a settled state with the same task key,
259    /// which is what makes replying "retry the failed tasks" a clean respawn
260    /// rather than a duplicate fan-out.
261    pub fn can_transition_to(self, next: OrchestrationTaskStatus) -> bool {
262        if self == next {
263            return true;
264        }
265
266        matches!(
267            (self, next),
268            (
269                OrchestrationTaskStatus::Proposed,
270                OrchestrationTaskStatus::Planned
271            ) | (
272                OrchestrationTaskStatus::Planned
273                    | OrchestrationTaskStatus::Ready
274                    | OrchestrationTaskStatus::Failed
275                    | OrchestrationTaskStatus::Canceled
276                    | OrchestrationTaskStatus::IntegrationFailed,
277                OrchestrationTaskStatus::Creating
278            ) | (
279                OrchestrationTaskStatus::Creating | OrchestrationTaskStatus::WaitingForInput,
280                OrchestrationTaskStatus::Running
281            ) | (
282                OrchestrationTaskStatus::Running,
283                OrchestrationTaskStatus::Reviewing | OrchestrationTaskStatus::WaitingForInput
284            ) | (
285                OrchestrationTaskStatus::Running
286                    | OrchestrationTaskStatus::Reviewing
287                    | OrchestrationTaskStatus::WaitingForInput,
288                OrchestrationTaskStatus::Ready | OrchestrationTaskStatus::Reported
289            ) | (
290                OrchestrationTaskStatus::Reviewing,
291                OrchestrationTaskStatus::ReviewApplying
292            ) | (
293                OrchestrationTaskStatus::ReviewApplying,
294                OrchestrationTaskStatus::Reviewing
295                    | OrchestrationTaskStatus::WaitingForInput
296                    | OrchestrationTaskStatus::Failed
297            ) | (
298                OrchestrationTaskStatus::Ready,
299                OrchestrationTaskStatus::AwaitingIntegration
300                    | OrchestrationTaskStatus::ContinuationPending
301                    | OrchestrationTaskStatus::Detached
302            ) | (
303                OrchestrationTaskStatus::AwaitingIntegration,
304                OrchestrationTaskStatus::Merging
305                    | OrchestrationTaskStatus::ContinuationPending
306                    | OrchestrationTaskStatus::Detached
307            ) | (
308                OrchestrationTaskStatus::IntegrationFailed,
309                OrchestrationTaskStatus::ContinuationPending | OrchestrationTaskStatus::Detached
310            ) | (
311                OrchestrationTaskStatus::ContinuationPending,
312                OrchestrationTaskStatus::Ready
313                    | OrchestrationTaskStatus::WaitingForInput
314                    | OrchestrationTaskStatus::Failed
315            ) | (
316                OrchestrationTaskStatus::Merging,
317                OrchestrationTaskStatus::Integrated
318                    | OrchestrationTaskStatus::ReviewRequested
319                    | OrchestrationTaskStatus::IntegrationFailed
320            ) | (
321                OrchestrationTaskStatus::ReviewRequested,
322                OrchestrationTaskStatus::Integrated | OrchestrationTaskStatus::IntegrationFailed
323            ) | (
324                OrchestrationTaskStatus::Planned
325                    | OrchestrationTaskStatus::Creating
326                    | OrchestrationTaskStatus::Running
327                    | OrchestrationTaskStatus::Reviewing
328                    | OrchestrationTaskStatus::ReviewApplying
329                    | OrchestrationTaskStatus::WaitingForInput,
330                OrchestrationTaskStatus::Failed | OrchestrationTaskStatus::Canceled
331            )
332        )
333    }
334
335    /// Returns whether this task no longer needs integration work.
336    pub fn is_integration_settled(self) -> bool {
337        matches!(
338            self,
339            OrchestrationTaskStatus::Integrated
340                | OrchestrationTaskStatus::Detached
341                | OrchestrationTaskStatus::Canceled
342                | OrchestrationTaskStatus::Failed
343        )
344    }
345
346    fn labels(self) -> (&'static str, &'static str) {
347        match self {
348            OrchestrationTaskStatus::Proposed => ("Proposed", "awaiting approval"),
349            OrchestrationTaskStatus::Planned => ("Planned", "waiting"),
350            OrchestrationTaskStatus::Creating => ("Creating", "starting"),
351            OrchestrationTaskStatus::Running => ("Running", "running"),
352            OrchestrationTaskStatus::Reviewing => ("Reviewing", "reviewing"),
353            OrchestrationTaskStatus::ReviewApplying => ("ReviewApplying", "applying review"),
354            OrchestrationTaskStatus::WaitingForInput => ("WaitingForInput", "waiting on you"),
355            OrchestrationTaskStatus::Ready => ("Ready", "ready"),
356            OrchestrationTaskStatus::Reported => ("Reported", "reported"),
357            OrchestrationTaskStatus::ContinuationPending => ("ContinuationPending", "continuing"),
358            OrchestrationTaskStatus::AwaitingIntegration => {
359                ("AwaitingIntegration", "awaiting integration")
360            }
361            OrchestrationTaskStatus::Merging => ("Merging", "integrating"),
362            OrchestrationTaskStatus::Integrated => ("Integrated", "integrated"),
363            OrchestrationTaskStatus::ReviewRequested => ("ReviewRequested", "review requested"),
364            OrchestrationTaskStatus::IntegrationFailed => {
365                ("IntegrationFailed", "integration failed")
366            }
367            OrchestrationTaskStatus::Detached => ("Detached", "detached"),
368            OrchestrationTaskStatus::Failed => ("Failed", "failed"),
369            OrchestrationTaskStatus::Canceled => ("Canceled", "canceled"),
370        }
371    }
372}
373
374impl fmt::Display for OrchestrationTaskStatus {
375    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
376        formatter.write_str(self.labels().0)
377    }
378}
379
380impl FromStr for OrchestrationTaskStatus {
381    type Err = String;
382
383    fn from_str(value: &str) -> Result<Self, Self::Err> {
384        match value {
385            "Proposed" => Ok(OrchestrationTaskStatus::Proposed),
386            "Planned" => Ok(OrchestrationTaskStatus::Planned),
387            "Creating" => Ok(OrchestrationTaskStatus::Creating),
388            "Running" => Ok(OrchestrationTaskStatus::Running),
389            "Reviewing" => Ok(OrchestrationTaskStatus::Reviewing),
390            "ReviewApplying" => Ok(OrchestrationTaskStatus::ReviewApplying),
391            "WaitingForInput" => Ok(OrchestrationTaskStatus::WaitingForInput),
392            "Ready" => Ok(OrchestrationTaskStatus::Ready),
393            "Reported" => Ok(OrchestrationTaskStatus::Reported),
394            "ContinuationPending" => Ok(OrchestrationTaskStatus::ContinuationPending),
395            "AwaitingIntegration" => Ok(OrchestrationTaskStatus::AwaitingIntegration),
396            "Merging" => Ok(OrchestrationTaskStatus::Merging),
397            "Integrated" => Ok(OrchestrationTaskStatus::Integrated),
398            "ReviewRequested" => Ok(OrchestrationTaskStatus::ReviewRequested),
399            "IntegrationFailed" => Ok(OrchestrationTaskStatus::IntegrationFailed),
400            "Detached" => Ok(OrchestrationTaskStatus::Detached),
401            "Failed" => Ok(OrchestrationTaskStatus::Failed),
402            "Canceled" => Ok(OrchestrationTaskStatus::Canceled),
403            _ => Err(format!("Unknown orchestration task status: {value}")),
404        }
405    }
406}
407
408/// Pure scheduling decision derived from one orchestration task snapshot.
409#[derive(Clone, Copy, Debug, Eq, PartialEq)]
410pub struct OrchestrationScheduleDecision {
411    /// Whether every non-empty task has settled and roll-up can be claimed.
412    pub should_submit: bool,
413    /// Number of planned tasks that may claim a parallelism slot.
414    pub spawn_count: usize,
415}
416
417/// Pure orchestration policy over typed task observations.
418pub struct OrchestrationPolicy;
419
420impl OrchestrationPolicy {
421    /// Decides fan-out capacity and roll-up readiness without persistence or
422    /// runtime dependencies.
423    pub fn schedule(
424        max_parallelism: usize,
425        task_statuses: &[Option<OrchestrationTaskStatus>],
426    ) -> OrchestrationScheduleDecision {
427        let occupied_slots = task_statuses
428            .iter()
429            .filter(|status| status.is_some_and(OrchestrationTaskStatus::occupies_parallelism_slot))
430            .count();
431        let planned_tasks = task_statuses
432            .iter()
433            .filter(|status| **status == Some(OrchestrationTaskStatus::Planned))
434            .count();
435        let spawn_count = max_parallelism
436            .saturating_sub(occupied_slots)
437            .min(planned_tasks);
438        let should_submit = !task_statuses.is_empty()
439            && task_statuses
440                .iter()
441                .all(|status| status.is_some_and(OrchestrationTaskStatus::is_settled));
442
443        OrchestrationScheduleDecision {
444            should_submit,
445            spawn_count,
446        }
447    }
448}
449
450/// Protocol-independent snapshot of one task proposed by an orchestration
451/// controller.
452#[derive(Clone)]
453pub struct OrchestrationPlanTask {
454    /// Observable conditions checked during settlement verification.
455    pub acceptance_criteria: Vec<String>,
456    /// Whether the task implements changes or returns research findings.
457    pub kind: OrchestrationTaskKind,
458    /// Standalone task prompt delivered to the child session.
459    pub prompt: String,
460    /// Stable kebab-case identity used for retries.
461    pub task_key: String,
462    /// Short user-facing task title.
463    pub title: String,
464    /// Best-effort repository-relative files or directories expected to change.
465    pub touched_areas: Vec<String>,
466}
467
468/// Validates one proposed subtask set before application code persists it.
469///
470/// # Errors
471///
472/// Returns a user-facing reason when the plan is too small, incomplete, or uses
473/// invalid task keys or planning paths.
474pub fn validate_subtasks(subtasks: &[OrchestrationPlanTask], is_retry: bool) -> Result<(), String> {
475    let is_research_wave = !subtasks.is_empty()
476        && subtasks
477            .iter()
478            .all(|subtask| subtask.kind == OrchestrationTaskKind::Research);
479    let has_research = subtasks
480        .iter()
481        .any(|subtask| subtask.kind == OrchestrationTaskKind::Research);
482    if has_research && !is_research_wave {
483        return Err(
484            "research and implementation tasks must be proposed in separate waves.".to_string(),
485        );
486    }
487
488    if subtasks.len() < 2 && !is_retry && !is_research_wave {
489        return Err("a meaningful orchestration requires at least two subtasks.".to_string());
490    }
491
492    let mut task_keys = HashSet::new();
493    for subtask in subtasks {
494        if !is_kebab_case_task_key(&subtask.task_key)
495            || !task_keys.insert(subtask.task_key.as_str())
496        {
497            return Err("every subtask needs a unique kebab-case task key.".to_string());
498        }
499
500        if subtask.prompt.trim().is_empty()
501            || subtask.title.trim().is_empty()
502            || subtask
503                .acceptance_criteria
504                .iter()
505                .all(|criterion| criterion.trim().is_empty())
506        {
507            return Err(format!(
508                "subtask `{}` needs a title, standalone prompt, and acceptance criteria.",
509                subtask.task_key
510            ));
511        }
512        for area in subtask
513            .touched_areas
514            .iter()
515            .filter(|_| subtask.kind == OrchestrationTaskKind::Implementation)
516        {
517            normalized_scope(area).map_err(|reason| {
518                format!(
519                    "subtask `{}` has invalid touched area `{area}`: {reason}.",
520                    subtask.task_key
521                )
522            })?;
523        }
524    }
525
526    Ok(())
527}
528
529fn is_kebab_case_task_key(task_key: &str) -> bool {
530    !task_key.is_empty()
531        && task_key.split('-').all(|segment| {
532            !segment.is_empty()
533                && segment
534                    .bytes()
535                    .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
536        })
537}
538
539fn normalized_scope(area: &str) -> Result<String, &'static str> {
540    let normalized = area.trim().trim_start_matches("./").trim_end_matches('/');
541    if normalized.is_empty()
542        || normalized.starts_with('/')
543        || normalized.split('/').any(|part| part == "..")
544    {
545        return Err("use a non-empty repository-relative path");
546    }
547
548    if normalized.contains(['*', '?', '[', ']', '{', '}']) {
549        return Err("use a literal file or directory path; wildcard patterns are not supported");
550    }
551
552    Ok(normalized.to_string())
553}
554
555#[cfg(test)]
556#[path = "orchestration_test.rs"]
557mod tests;