-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgoal.rs
More file actions
3964 lines (3770 loc) · 142 KB
/
Copy pathgoal.rs
File metadata and controls
3964 lines (3770 loc) · 142 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Goal mode: first-class plan-then-deploy orchestration.
//!
//! `/goal` (TUI/web) sends `start_goal`. The core owns a phase machine:
//! planning → plan_ready (optional) → deploying → running → synthesizing →
//! done|failed.
//!
//! Control Center / CEO mode (`ceo_mode=true`) extends the loop:
//! planning → reviewing (bounded revise) → deploying → running → verifying →
//! (certified→done) | (replan→planning, iteration-capped→failed).
//! The planning turn must call `goal_write_plan` with a structured plan;
//! deploy runs subagents under the user's concurrency and model/provider caps.
//! After workers finish, a parent synthesizing (single-pass) or verifying
//! (CEO) turn closes the loop without prompting the user.
use crate::protocol::{emit, Event};
use crate::subagent::ModelCandidate;
use crate::tools::Outcome;
use crate::State;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GoalPhase {
#[default]
Idle,
Planning,
/// Parent CEO turn self-reviews the plan before deploy (CEO mode only).
Reviewing,
PlanReady,
Deploying,
Running,
/// Workers finished; parent turn is summarizing results for the user.
Synthesizing,
/// Parent CEO turn verifies deploy artifacts against the goal (CEO mode).
Verifying,
/// Transitional: verify failed and a replan turn is starting (CEO mode).
Replanning,
Blocked,
Done,
Failed,
Cancelled,
}
impl GoalPhase {
pub fn as_str(&self) -> &'static str {
match self {
GoalPhase::Idle => "idle",
GoalPhase::Planning => "planning",
GoalPhase::Reviewing => "reviewing",
GoalPhase::PlanReady => "plan_ready",
GoalPhase::Deploying => "deploying",
GoalPhase::Running => "running",
GoalPhase::Synthesizing => "synthesizing",
GoalPhase::Verifying => "verifying",
GoalPhase::Replanning => "replanning",
GoalPhase::Blocked => "blocked",
GoalPhase::Done => "done",
GoalPhase::Failed => "failed",
GoalPhase::Cancelled => "cancelled",
}
}
/// Phases where employee subagents may run without a live leader turn
/// answering `contact_supervisor` — auto-resolve `need_decision`.
pub fn auto_resolves_supervisor(&self) -> bool {
matches!(
self,
GoalPhase::Planning
| GoalPhase::Reviewing
| GoalPhase::Deploying
| GoalPhase::Running
| GoalPhase::Verifying
| GoalPhase::Replanning
)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct GoalTransitionError {
pub code: String,
pub from: GoalPhase,
pub to: GoalPhase,
pub message: String,
}
/// Validate the persisted goal state machine before mutating it. Explicit user
/// revision may reopen a terminal goal into Planning; autonomous execution may
/// otherwise only move forward or enter a terminal failure/cancellation state.
pub fn validate_transition(from: &GoalPhase, to: &GoalPhase) -> Result<(), GoalTransitionError> {
let allowed = from == to
|| matches!(
(from, to),
(GoalPhase::Idle, GoalPhase::Planning)
| (GoalPhase::Planning, GoalPhase::PlanReady)
| (GoalPhase::PlanReady, GoalPhase::Reviewing)
| (GoalPhase::PlanReady, GoalPhase::Deploying)
| (GoalPhase::PlanReady, GoalPhase::Planning)
| (GoalPhase::Reviewing, GoalPhase::PlanReady)
| (GoalPhase::Reviewing, GoalPhase::Planning)
| (GoalPhase::Deploying, GoalPhase::Running)
| (GoalPhase::Running, GoalPhase::Verifying)
| (GoalPhase::Running, GoalPhase::Synthesizing)
| (GoalPhase::Verifying, GoalPhase::Done)
| (GoalPhase::Verifying, GoalPhase::Replanning)
| (GoalPhase::Replanning, GoalPhase::Planning)
| (GoalPhase::Synthesizing, GoalPhase::Done)
| (GoalPhase::Blocked, GoalPhase::Planning)
| (GoalPhase::Done, GoalPhase::Planning)
| (GoalPhase::Failed, GoalPhase::Planning)
| (GoalPhase::Cancelled, GoalPhase::Planning)
)
|| (matches!(
to,
GoalPhase::Failed | GoalPhase::Cancelled | GoalPhase::Blocked
) && !matches!(
from,
GoalPhase::Idle | GoalPhase::Done | GoalPhase::Failed | GoalPhase::Cancelled
));
if allowed {
return Ok(());
}
Err(GoalTransitionError {
code: "invalid_goal_transition".into(),
from: from.clone(),
to: to.clone(),
message: format!(
"invalid goal transition: {} -> {}",
from.as_str(),
to.as_str()
),
})
}
fn emit_transition_error(error: &GoalTransitionError) {
emit(
&Event::new("error")
.with("code", json!(error.code))
.with("from", json!(error.from.as_str()))
.with("to", json!(error.to.as_str()))
.with("message", json!(error.message)),
);
}
/// Structured review / verify verdict surfaced to the UI.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct GoalVerdict {
pub ok: bool,
pub summary: String,
#[serde(default)]
pub evidence_paths: Vec<String>,
/// Unix epoch milliseconds when the verdict was recorded.
#[serde(default)]
pub at_ms: u64,
}
impl GoalVerdict {
pub fn to_json(&self) -> Value {
json!({
"ok": self.ok,
"summary": self.summary,
"evidence_paths": self.evidence_paths,
"at": self.at_ms,
})
}
}
/// Default verify→replan cycles for Control Center CEO mode.
pub const DEFAULT_CEO_MAX_ITERATIONS: u32 = 3;
/// Default pre-deploy self-review revise budget for CEO mode.
pub const DEFAULT_CEO_MAX_PLAN_REVISIONS: u32 = 2;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DeployStatus {
Pending,
Running,
Done,
Failed,
Skipped,
}
impl DeployStatus {
pub fn as_str(&self) -> &'static str {
match self {
DeployStatus::Pending => "pending",
DeployStatus::Running => "running",
DeployStatus::Done => "done",
DeployStatus::Failed => "failed",
DeployStatus::Skipped => "skipped",
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GoalStep {
pub id: String,
pub agent: String,
pub title: String,
pub task: String,
#[serde(default)]
pub model: Option<String>,
#[serde(default)]
pub depends_on: Vec<String>,
#[serde(default)]
pub parallel_group: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GoalPlan {
pub summary: String,
pub steps: Vec<GoalStep>,
#[serde(default)]
pub risks: Vec<String>,
#[serde(default)]
pub validation: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeployPrompt {
pub step_id: String,
pub agent: String,
pub task: String,
#[serde(default)]
pub model: Option<String>,
pub status: DeployStatus,
#[serde(default)]
pub run_id: Option<String>,
#[serde(default)]
pub summary: Option<String>,
#[serde(default)]
pub title: String,
}
/// Optional per-role model overrides from the Advanced section of `/goal`.
/// Empty string / None means "use step model or allowlist / parent default".
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct RoleModels {
#[serde(default)]
pub planner: Option<String>,
#[serde(default)]
pub worker: Option<String>,
#[serde(default)]
pub reviewer: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GoalMode {
pub id: String,
pub goal: String,
pub phase: GoalPhase,
pub concurrency: u32,
pub max_tasks: u32,
pub allowed_models: Vec<String>,
pub allowed_providers: Vec<String>,
/// When true, deploy immediately after a valid plan. When false, stop at
/// `plan_ready` until `approve_goal_plan`.
pub auto_deploy: bool,
/// When true, run the autonomous CEO loop (self-review → verify → replan).
/// When false, classic single-pass `/goal`: plan → deploy → synthesize → Done.
#[serde(default)]
pub ceo_mode: bool,
/// Verify→replan iteration counter (0 before first verify).
#[serde(default)]
pub iteration: u32,
/// Cap on verify→replan cycles. 0 disables replan (single-pass verify skip
/// when combined with `ceo_mode=false`).
#[serde(default)]
pub max_iterations: u32,
/// Pre-deploy self-review revise counter.
#[serde(default)]
pub plan_revision: u32,
/// Cap on plan self-review revisions before first deploy.
#[serde(default)]
pub max_plan_revisions: u32,
/// Latest plan self-review verdict (CEO mode).
#[serde(default)]
pub review_verdict: Option<GoalVerdict>,
/// Latest post-deploy verify verdict (CEO mode).
#[serde(default)]
pub verify_verdict: Option<GoalVerdict>,
/// Gaps from the latest failed verify, fed into the next replan.
#[serde(default)]
pub remaining_gaps: Vec<String>,
/// Self-review feedback (also mirrored into `revise_feedback` on revise).
#[serde(default)]
pub self_review_feedback: Option<String>,
/// True once verify certifies the goal complete.
#[serde(default)]
pub certified: bool,
/// Advanced: preferred model per agent role (planner / worker / reviewer).
#[serde(default)]
pub role_models: RoleModels,
/// Advanced: max concurrent subagents per model id. Missing keys fall back
/// to the global `concurrency` cap.
#[serde(default)]
pub model_concurrency: HashMap<String, u32>,
pub plan: Option<GoalPlan>,
pub prompts: Vec<DeployPrompt>,
pub active_run_ids: Vec<String>,
pub version: u64,
pub error: Option<String>,
/// Orchestrator model used for the planning turn / parent model for deploy.
pub parent_model: String,
#[serde(default)]
pub reasoning_effort: String,
/// True when a plan was accepted and deploy should run after the planning turn.
#[serde(default)]
pub deploy_after_turn: bool,
/// Optional revise feedback appended on the next planning turn.
#[serde(default)]
pub revise_feedback: Option<String>,
/// Speculative scout findings gathered while the planner runs.
#[serde(default)]
pub scout_findings: Option<String>,
}
impl Default for GoalMode {
fn default() -> Self {
Self {
id: String::new(),
goal: String::new(),
phase: GoalPhase::Idle,
concurrency: 4,
max_tasks: 8,
allowed_models: Vec::new(),
allowed_providers: Vec::new(),
auto_deploy: true,
ceo_mode: false,
iteration: 0,
max_iterations: 0,
plan_revision: 0,
max_plan_revisions: 0,
review_verdict: None,
verify_verdict: None,
remaining_gaps: Vec::new(),
self_review_feedback: None,
certified: false,
role_models: RoleModels::default(),
model_concurrency: HashMap::new(),
plan: None,
prompts: Vec::new(),
active_run_ids: Vec::new(),
version: 0,
error: None,
parent_model: String::new(),
reasoning_effort: "medium".into(),
deploy_after_turn: false,
revise_feedback: None,
scout_findings: None,
}
}
}
impl GoalMode {
pub fn is_active(&self) -> bool {
!matches!(
self.phase,
GoalPhase::Idle | GoalPhase::Done | GoalPhase::Failed | GoalPhase::Cancelled
)
}
pub fn touch(&mut self) {
self.version = self.version.wrapping_add(1);
}
pub fn to_event_value(&self) -> Value {
json!({
"id": self.id,
"goal": self.goal,
"phase": self.phase.as_str(),
"concurrency": self.concurrency,
"max_tasks": self.max_tasks,
"allowed_models": self.allowed_models,
"allowed_providers": self.allowed_providers,
"auto_deploy": self.auto_deploy,
"ceo_mode": self.ceo_mode,
"mode": if self.ceo_mode { "ceo" } else { "single_pass" },
"iteration": self.iteration,
"max_iterations": self.max_iterations,
"plan_revision": self.plan_revision,
"max_plan_revisions": self.max_plan_revisions,
"review_verdict": self.review_verdict.as_ref().map(|v| v.to_json()),
"verify_verdict": self.verify_verdict.as_ref().map(|v| v.to_json()),
"remaining_gaps": self.remaining_gaps,
"self_review_feedback": self.self_review_feedback,
"certified": self.certified,
"role_models": {
"planner": self.role_models.planner,
"worker": self.role_models.worker,
"reviewer": self.role_models.reviewer,
},
"model_concurrency": self.model_concurrency,
"prompts": self.prompts.iter().map(|p| json!({
"step_id": p.step_id,
"agent": p.agent,
"title": p.title,
"task": p.task,
"model": p.model,
"status": p.status.as_str(),
"run_id": p.run_id,
"summary": p.summary,
})).collect::<Vec<_>>(),
"active_run_ids": self.active_run_ids,
"version": self.version,
"error": self.error,
"parent_model": self.parent_model,
})
}
/// Cap for a specific model: per-model override if set, else global concurrency.
pub fn concurrency_for_model(&self, model: &str) -> u32 {
self.model_concurrency
.get(model)
.copied()
.unwrap_or(self.concurrency)
.clamp(1, self.concurrency.max(1))
}
}
/// Human-facing scheduling profile derived from the user's concurrency cap.
/// A high cap is treated as an instruction to shape the plan for breadth, not
/// merely as a larger semaphore for a plan that may still be entirely serial.
pub fn execution_profile(concurrency: u32) -> &'static str {
match concurrency {
0 | 1 => "serial",
2..=7 => "parallel",
_ => "ultra_parallel",
}
}
fn planning_parallelism_guidance(mode: &GoalMode) -> String {
let available = mode.concurrency.min(mode.max_tasks).max(1);
match execution_profile(mode.concurrency) {
"ultra_parallel" => {
// Leave room for an integration/review task when the task budget
// permits, while still asking the planner to fill almost all of a
// large concurrency window immediately.
let roots = if mode.max_tasks > available {
available
} else {
available.saturating_sub(1).max(1)
};
format!(
r#"Execution profile: ULTRA PARALLEL.
- Treat the {available} available slots as a throughput budget that should be actively used.
- Aim for about {roots} useful root steps (empty depends_on) in the first launch window when the goal has enough separable work.
- Split reconnaissance by independent area and run it concurrently; do not put one global scout in front of unrelated workers.
- Partition implementation steps by non-overlapping files/components. Add dependencies only when a step truly consumes another step's artifact.
- Reserve a final integration/review step when useful, depending only on the specific work it validates.
- A sequential chain is still correct for genuinely indivisible work, but briefly say why in the plan summary."#
)
}
"parallel" => format!(
r#"Execution profile: PARALLEL.
- Expose up to {available} independent root steps where the work naturally separates.
- Do not make unrelated work wait behind a single reconnaissance step.
- Add depends_on only for a real data, artifact, or ordering dependency."#
),
_ => "Execution profile: SERIAL. Produce the shortest dependency chain that safely completes the goal.".into(),
}
}
/// Resolve which model a step should run with, given role overrides + allowlist.
pub fn resolve_step_model(
mode: &GoalMode,
agent: &str,
step_model: Option<String>,
) -> Option<String> {
let role = match agent {
"planner" => mode.role_models.planner.clone(),
"worker" => mode.role_models.worker.clone(),
"reviewer" => mode.role_models.reviewer.clone(),
_ => None,
};
// Role override wins when set (Advanced section is explicit). Do NOT
// auto-pin `allowed_models[0]` here — that forced every step through the
// model-override path (and previously the worktree parallel wrapper) even
// when the planner omitted step.model. Parent model + allowlist filter in
// `resolve_model_candidates` already enforces the allowlist.
let candidate = role.or(step_model);
match candidate {
Some(m)
if !mode.allowed_models.is_empty() && !mode.allowed_models.iter().any(|a| a == &m) =>
{
// Role/step model outside allowlist → fall back to first allowed.
mode.allowed_models.first().cloned()
}
other => other,
}
}
/// Whether a goal deploy step should run in a git worktree when concurrency > 1.
///
/// Read-focused agents write disjoint artifacts (e.g. `review/<id>.md`) and do
/// not need full-tree isolation. Forcing `worktree:true` on every step wrapped
/// each one as a one-item parallel batch and raced concurrent `git worktree add`,
/// which aborted entire review waves (session 2026-07-15_13-46-39).
pub fn goal_step_needs_worktree(agent: &str) -> bool {
match agent {
"scout" | "researcher" | "planner" | "reviewer" | "context-builder" | "oracle" => false,
// worker (and unknown/custom agents that may edit shared files)
_ => true,
}
}
/// Appended to every deploy step's task so workers know the deferred `browser`
/// tools (and git/web/bulk) exist and can be loaded on demand. The subagent
/// system prompt already lists the deferred groups; this reminder ties them to
/// the step so web/UI verification is not silently skipped.
const TOOL_AVAILABILITY_SECTION: &str = "
# Tool availability
Builtin/project worker, reviewer, scout, researcher, planner, oracle, context-builder, and delegate agents include diagnostics, git read, knowledge, workspace_activity, and load_tools (plus role-specific tools). Call `load_tools` before first use of extra deferred groups: `git` (mutators push/pull), `web`, `bulk`, `ide`, `process`, `mcp`, and `browser` (create/navigate/snapshot/click/fill/screenshot — only when this build has a browser backend). Prefer native tools over bash. If this step needs to drive or verify a web page / UI / e2e flow, load `browser` (or use browser_* already on worker/researcher allowlists) instead of skipping that work. If a needed core tool is missing from your schema, call load_tools with its name/group or escalate with contact_supervisor.";
/// Appended (conditionally — see [`goal_step_should_validate`]) to
/// implementation/review steps so every deploy step self-validates: build,
/// run tests, confirm zero errors, and report results. This is the "ensure
/// validation after every step" guarantee — it does not depend on the planner
/// remembering to write a test clause into `step.task`.
const VALIDATION_GATE_SECTION: &str = "
# Validation gate (required for this step)
Where applicable to this step's work, finish only after:
- Building/compiling the affected code and confirming zero errors (prefer the core `diagnostics` tool; else `cargo check` / `cargo build`, `go build ./...`, `npm run build`, `tsc --noEmit`).
- Running the relevant test suite and confirming zero failures (e.g. `cargo test`, `go test ./...`, `npm test`, `pytest`). If you added or changed behavior, add or update tests for it.
- Fixing any errors or failing tests before reporting done — never leave a red build.
- Summarizing the build/test results (commands run + pass/fail counts) in your final output.";
/// Whether a goal deploy step should receive the per-step validation gate
/// (build/compile + run tests, confirm zero errors). Pure-recon agents
/// (scout / researcher / context-builder) only read and produce notes, so the
/// gate is skipped for them. Implementation, review, and custom agents must
/// validate their own work.
pub fn goal_step_should_validate(agent: &str) -> bool {
!matches!(agent, "scout" | "researcher" | "context-builder")
}
fn should_validate_goal_after_wave(wave_idx: usize, wave_count: usize) -> bool {
wave_count > 0 && wave_idx + 1 == wave_count
}
// ---------------------------------------------------------------------------
// Construction / validation
// ---------------------------------------------------------------------------
pub struct StartGoalArgs {
pub goal: String,
pub concurrency: Option<u32>,
pub max_tasks: Option<u32>,
pub allowed_models: Vec<String>,
pub allowed_providers: Vec<String>,
pub auto_deploy: Option<bool>,
/// Enable autonomous CEO loop (Control Center). Default false = classic /goal.
pub ceo_mode: Option<bool>,
pub max_iterations: Option<u32>,
pub max_plan_revisions: Option<u32>,
pub role_models: RoleModels,
pub model_concurrency: HashMap<String, u32>,
pub model: String,
pub reasoning_effort: Option<String>,
pub default_concurrency: u32,
pub default_max_tasks: u32,
}
fn normalize_role_model(m: Option<String>, allowed: &[String]) -> Option<String> {
let m = m.map(|s| s.trim().to_string()).filter(|s| !s.is_empty())?;
if !allowed.is_empty() && !allowed.iter().any(|a| a == &m) {
return None; // drop invalid role model vs allowlist
}
Some(m)
}
/// Planning/parent model must stay inside the selected allowlist.
pub fn resolve_goal_parent_model(
planner: Option<String>,
session: String,
allowed: &[String],
) -> String {
if let Some(p) = planner {
return p;
}
if allowed.is_empty() || allowed.iter().any(|a| a == &session) {
return session;
}
allowed[0].clone()
}
pub fn new_goal(args: StartGoalArgs) -> Result<GoalMode, String> {
let goal = args.goal.trim().to_string();
if goal.is_empty() {
return Err("goal text must not be empty".into());
}
if goal.chars().count() < 4 {
return Err("goal text is too short".into());
}
let concurrency = args
.concurrency
.unwrap_or(args.default_concurrency)
.clamp(1, 32);
let max_tasks = args
.max_tasks
.unwrap_or(args.default_max_tasks)
.clamp(1, 64);
if concurrency > max_tasks {
return Err(format!(
"concurrency ({concurrency}) cannot exceed max_tasks ({max_tasks})"
));
}
let allowed_models = args.allowed_models;
let role_models = RoleModels {
planner: normalize_role_model(args.role_models.planner, &allowed_models),
worker: normalize_role_model(args.role_models.worker, &allowed_models),
reviewer: normalize_role_model(args.role_models.reviewer, &allowed_models),
};
// Clamp per-model concurrency to 1..=global concurrency.
let mut model_concurrency: HashMap<String, u32> = HashMap::new();
for (k, v) in args.model_concurrency {
let key = k.trim().to_string();
if key.is_empty() {
continue;
}
if !allowed_models.is_empty() && !allowed_models.iter().any(|a| a == &key) {
continue;
}
model_concurrency.insert(key, v.clamp(1, concurrency));
}
// Planning turn prefers planner role model when set. Selected models are
// exclusive: the session model is used only if it is on the allowlist.
let parent_model =
resolve_goal_parent_model(role_models.planner.clone(), args.model, &allowed_models);
let ceo_mode = args.ceo_mode.unwrap_or(false);
let (max_iterations, max_plan_revisions) = if ceo_mode {
(
args.max_iterations
.unwrap_or(DEFAULT_CEO_MAX_ITERATIONS)
.clamp(1, 32),
args.max_plan_revisions
.unwrap_or(DEFAULT_CEO_MAX_PLAN_REVISIONS)
.clamp(0, 16),
)
} else {
// Classic single-pass: no self-review / verify-replan budgets.
(
args.max_iterations.unwrap_or(0),
args.max_plan_revisions.unwrap_or(0),
)
};
let id = format!("goal-{}", now_ms());
Ok(GoalMode {
id,
goal,
phase: GoalPhase::Planning,
concurrency,
max_tasks,
allowed_models,
allowed_providers: args.allowed_providers,
auto_deploy: args.auto_deploy.unwrap_or(true),
ceo_mode,
iteration: 0,
max_iterations,
plan_revision: 0,
max_plan_revisions,
review_verdict: None,
verify_verdict: None,
remaining_gaps: Vec::new(),
self_review_feedback: None,
certified: false,
role_models,
model_concurrency,
plan: None,
prompts: Vec::new(),
active_run_ids: Vec::new(),
version: 1,
error: None,
parent_model,
reasoning_effort: args.reasoning_effort.unwrap_or_else(|| "medium".into()),
deploy_after_turn: false,
revise_feedback: None,
scout_findings: None,
})
}
/// Parse + validate a `goal_write_plan` payload into a GoalPlan and deploy prompts.
pub fn apply_plan(
mode: &mut GoalMode,
args: &Value,
known_agents: &HashSet<String>,
) -> Result<(), String> {
if mode.phase != GoalPhase::Planning {
return Err(format!(
"goal_write_plan only valid during planning (phase={})",
mode.phase.as_str()
));
}
let summary = args
.get("summary")
.and_then(|v| v.as_str())
.unwrap_or("")
.trim()
.to_string();
if summary.is_empty() {
return Err("goal_write_plan requires a non-empty 'summary'".into());
}
let steps_raw = args
.get("steps")
.and_then(|v| v.as_array())
.ok_or_else(|| "goal_write_plan requires a 'steps' array".to_string())?;
if steps_raw.is_empty() {
return Err("goal_write_plan requires at least one step".into());
}
if steps_raw.len() as u32 > mode.max_tasks {
return Err(format!(
"plan has {} steps (max_tasks={})",
steps_raw.len(),
mode.max_tasks
));
}
let mut steps: Vec<GoalStep> = Vec::new();
let mut ids: HashSet<String> = HashSet::new();
for (i, s) in steps_raw.iter().enumerate() {
let id = s
.get("id")
.and_then(|v| v.as_str())
.map(|x| x.trim().to_string())
.filter(|x| !x.is_empty())
.unwrap_or_else(|| format!("{}", i + 1));
if !ids.insert(id.clone()) {
return Err(format!("duplicate step id '{id}'"));
}
let agent = s
.get("agent")
.and_then(|v| v.as_str())
.unwrap_or("")
.trim()
.to_string();
if agent.is_empty() {
return Err(format!("step '{id}' missing agent"));
}
if !known_agents.is_empty() && !known_agents.contains(&agent) {
// Soft warning: still allow unknown custom agents the registry may
// not have listed yet; only hard-fail empty.
}
let title = s
.get("title")
.and_then(|v| v.as_str())
.unwrap_or("")
.trim()
.to_string();
let task = s
.get("task")
.and_then(|v| v.as_str())
.unwrap_or("")
.trim()
.to_string();
if task.is_empty() {
return Err(format!("step '{id}' missing task prompt"));
}
let step_model = s
.get("model")
.and_then(|v| v.as_str())
.map(|m| m.trim().to_string())
.filter(|m| !m.is_empty());
// Strip models outside the allowlist (empty allowlist = unrestricted).
let step_model = match step_model {
Some(m)
if !mode.allowed_models.is_empty()
&& !mode.allowed_models.iter().any(|a| a == &m) =>
{
None
}
other => other,
};
// Role models (Advanced) applied later when materializing DeployPrompt.
let depends_on: Vec<String> = s
.get("depends_on")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|x| x.as_str().map(|s| s.to_string()))
.collect()
})
.unwrap_or_default();
let parallel_group = s
.get("parallel_group")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.filter(|s| !s.is_empty());
steps.push(GoalStep {
id,
agent,
title: if title.is_empty() {
format!("step {}", i + 1)
} else {
title
},
task,
model: step_model,
depends_on,
parallel_group,
});
}
// Validate depends_on references.
for step in &steps {
for dep in &step.depends_on {
if !ids.contains(dep) {
return Err(format!(
"step '{}' depends on unknown id '{}'",
step.id, dep
));
}
if dep == &step.id {
return Err(format!("step '{}' cannot depend on itself", step.id));
}
}
}
// Cycle check via topo waves.
if topo_waves(&steps).is_err() {
return Err("step depends_on graph contains a cycle".into());
}
let risks: Vec<String> = args
.get("risks")
.and_then(|v| v.as_array())
.map(|a| {
a.iter()
.filter_map(|x| x.as_str().map(|s| s.to_string()))
.collect()
})
.unwrap_or_default();
let validation: Vec<String> = args
.get("validation")
.and_then(|v| v.as_array())
.map(|a| {
a.iter()
.filter_map(|x| x.as_str().map(|s| s.to_string()))
.collect()
})
.unwrap_or_default();
let plan = GoalPlan {
summary,
steps: steps.clone(),
risks,
validation,
};
let mut prompts = Vec::new();
let scout_block = mode
.scout_findings
.as_ref()
.map(|s| format!("\n\n# Speculative scout findings\n{s}"))
.unwrap_or_default();
for step in &plan.steps {
let validation_block = if plan.validation.is_empty() {
"(none specified)".to_string()
} else {
plan.validation
.iter()
.map(|v| format!("- {v}"))
.collect::<Vec<_>>()
.join("\n")
};
// Per-step validation gate is appended only to implementation/review
// agents (pure-recon steps only read — see goal_step_should_validate).
let validation_gate = if goal_step_should_validate(&step.agent) {
VALIDATION_GATE_SECTION
} else {
""
};
let full_task = format!(
"# Goal\n{}\n\n# Step: {}\n{}\n\n# Validation criteria for the overall goal\n{}{}{}{}",
mode.goal,
step.title,
step.task,
validation_block,
scout_block,
TOOL_AVAILABILITY_SECTION,
validation_gate,
);
prompts.push(DeployPrompt {
step_id: step.id.clone(),
agent: step.agent.clone(),
task: full_task,
model: resolve_step_model(mode, &step.agent, step.model.clone()),
status: DeployStatus::Pending,
run_id: None,
summary: None,
title: step.title.clone(),
});
}
mode.plan = Some(plan);
mode.prompts = prompts;
mode.error = None;
mode.touch();
mode.deploy_after_turn = mode.auto_deploy;
if !transition(mode, GoalPhase::PlanReady, Some("plan ready")) {
return Err("invalid goal phase while applying plan".into());
}
Ok(())
}
/// Partition steps into waves respecting depends_on. Err on cycles.
pub fn topo_waves(steps: &[GoalStep]) -> Result<Vec<Vec<String>>, String> {
let mut remaining: HashMap<String, HashSet<String>> = HashMap::new();
for s in steps {
remaining.insert(s.id.clone(), s.depends_on.iter().cloned().collect());
}
let mut done: HashSet<String> = HashSet::new();
let mut waves: Vec<Vec<String>> = Vec::new();
while done.len() < steps.len() {
let mut wave: Vec<String> = remaining
.iter()
.filter(|(id, deps)| !done.contains(*id) && deps.iter().all(|d| done.contains(d)))
.map(|(id, _)| id.clone())
.collect();
if wave.is_empty() {
return Err("cycle".into());
}
wave.sort();
for id in &wave {
done.insert(id.clone());
}
waves.push(wave);
}
Ok(waves)
}
/// Filter a model candidate list by goal allowlists (models + providers via registry
/// and/or explicit `provider/model` pins). Model allowlisting is already applied
/// by `build_model_candidates`; the provider check here prefers an explicit pin
/// over the registry mapping so a duplicated model id keeps its picked owner.
pub fn filter_model_candidates(
candidates: &[ModelCandidate],
mode: &GoalMode,
model_providers: &HashMap<String, String>,
) -> Vec<ModelCandidate> {
candidates
.iter()
.filter(|c| {
if !mode.allowed_providers.is_empty() {
let prov = c
.provider
.as_deref()
.or_else(|| model_providers.get(&c.model).map(|s| s.as_str()))
.unwrap_or("");
if prov.is_empty() {
// Unknown provider mapping: keep candidate (may still work on active).
return true;
}
if !mode
.allowed_providers
.iter()
.any(|p| p.eq_ignore_ascii_case(prov))
{
return false;
}
}
true
})
.cloned()
.collect()
}
/// Cap parallel concurrency for subagent calls when goal mode is active.
pub fn cap_concurrency(requested: u32, mode: &GoalMode) -> u32 {
requested.min(mode.concurrency).max(1)
}
// ---------------------------------------------------------------------------
// Events
// ---------------------------------------------------------------------------
pub fn emit_goal_state(mode: &GoalMode) {
let mut ev = Event::new("goal_state");
if let Value::Object(map) = mode.to_event_value() {
for (k, v) in map {
ev = ev.with(&k, v);
}
}
emit(&ev);
}
pub fn emit_goal_plan(mode: &GoalMode) {
let Some(plan) = &mode.plan else {
return;
};