-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathlib.rs
More file actions
2145 lines (1978 loc) · 82.9 KB
/
Copy pathlib.rs
File metadata and controls
2145 lines (1978 loc) · 82.9 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
//! Multi-agent orchestration with scheduling, budgeting, and compound review.
//!
//! This crate provides the core orchestration engine for managing fleets of AI agents
//! with features for resource scheduling, cost tracking, and coordinated review workflows.
//!
//! # Core Components
//!
//! - **AgentOrchestrator**: Main orchestrator running the "dark factory" pattern
//! - **DualModeOrchestrator**: Real-time and batch processing modes with fairness scheduling
//! - **CompoundReviewWorkflow**: Multi-agent review swarm with persona-based specialization
//! - **Scheduler**: Time-based and event-driven task scheduling
//! - **HandoffBuffer**: Inter-agent state transfer with TTL management
//! - **CostTracker**: Budget enforcement and spending monitoring
//! - **NightwatchMonitor**: Drift detection and rate limiting
//!
//! # Example
//!
//! ```rust,ignore
//! use terraphim_orchestrator::{AgentOrchestrator, OrchestratorConfig};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let config = OrchestratorConfig::default();
//! let mut orchestrator = AgentOrchestrator::new(config).await?;
//!
//! // Run the orchestration loop
//! orchestrator.run().await?;
//! # Ok(())
//! # }
//! ```
pub mod adf_commands;
pub mod agent_registry;
pub mod agent_run_command;
pub mod agent_run_record;
pub mod agent_runner;
mod auto_merge_impl;
pub mod compound;
pub mod concurrency;
pub mod config;
pub mod control_plane;
pub mod cost_tracker;
#[cfg(unix)]
pub mod direct_dispatch;
mod dispatch_impl;
pub mod dispatcher;
pub mod dual_mode;
pub mod error;
pub mod error_signatures;
mod escalation_impl;
pub mod evolution;
pub mod flow;
pub mod gitea_skill_loader;
pub mod handoff;
pub mod kg_router;
pub mod learning;
pub mod local_skills;
pub mod mention;
pub mod mention_chain;
mod mentions_impl;
pub mod metrics_persistence;
pub mod mode;
pub mod nightwatch;
pub mod output_poster;
pub mod persona;
pub mod post_merge_gate;
pub mod pr_dispatch;
pub mod pr_gate;
pub mod pr_gate_context;
pub mod pr_gate_prompt;
pub mod pr_gate_result;
mod pr_handlers_impl;
pub mod pr_poller;
pub mod pr_review;
mod pre_check_impl;
pub mod project_adf;
pub mod project_control;
pub mod provider_budget;
pub mod provider_probe;
#[cfg(feature = "quickwit")]
pub mod quickwit;
#[cfg(feature = "quickwit")]
pub mod quickwit_bulk;
pub mod rate_limiter;
mod reconcile_impl;
pub mod scheduler;
mod scheduling_impl;
pub mod scope;
mod spawn_impl;
mod telemetry_impl;
pub mod webhook;
pub mod worktree_guard;
pub use agent_registry::{AgentKey, AgentRegistry, AgentScope, AgentSource, RegisteredAgent};
pub use agent_run_command::{
applicable_modes, is_cron_schedule_valid, parse_agent_args, run_synthetic, run_validate,
run_validate_all, schedule_for_agent, validate_agent_all_modes, AgentSubcommand,
AgentValidateAllReport, OutputFormat,
};
pub use agent_run_record::{
AgentRunRecord, ExitClass, ExitClassification, ExitClassifier, RunTrigger,
};
pub use agent_runner::{
probe_cli_tool, probe_model_available, run_agent_synthetic, validate_agent_runtime,
AgentRunRequest, AgentRuntimeValidationReport, GiteaTargetReport, ModeResult, SyntheticEvent,
TriggerMode,
};
pub use compound::{CompoundReviewResult, CompoundReviewWorkflow, ReviewGroupDef, SwarmConfig};
pub use concurrency::{ConcurrencyController, FairnessPolicy, ModeQuotas};
#[cfg(feature = "quickwit")]
pub use config::QuickwitConfig;
pub use config::{
AgentDefinition, AgentLayer, CompoundReviewConfig, ConcurrencyConfig, EvolutionConfig,
GiteaOutputConfig, LearningConfig, MentionConfig, NightwatchConfig, OrchestratorConfig,
PreCheckStrategy, TrackerConfig, TrackerStates, WebhookConfig, WorkflowConfig,
};
pub use cost_tracker::{AgentMetrics, BudgetVerdict, CostSnapshot, CostTracker, ExecutionMetrics};
pub use dispatcher::{DispatchTask, Dispatcher, DispatcherStats};
pub use dual_mode::DualModeOrchestrator;
pub use error::OrchestratorError;
pub use handoff::{HandoffBuffer, HandoffContext, HandoffLedger};
pub use mention::{
migrate_legacy_mention_cursor, parse_mention_tokens, parse_mentions, resolve_mention,
resolve_persona_mention, DetectedMention, MentionCursor, MentionTokens, MentionTracker,
};
pub use mention_chain::{
MentionChainError, MentionChainTracker, MentionContextArgs, DEFAULT_MAX_MENTION_DEPTH,
};
pub use metrics_persistence::{
InMemoryMetricsPersistence, MetricsPersistence, MetricsPersistenceConfig,
MetricsPersistenceError, PersistedAgentMetrics,
};
pub use mode::{IssueMode, TimeMode};
pub use nightwatch::{
dual_panel_evaluate, validate_certificate, Claim, CorrectionAction, CorrectionLevel,
DriftAlert, DriftMetrics, DriftScore, DualPanelResult, NightwatchMonitor, RateLimitTracker,
RateLimitWindow, ReasoningCertificate,
};
pub use output_poster::OutputPoster;
pub use persona::{MetapromptRenderError, MetapromptRenderer, PersonaRegistry};
pub use project_adf::ProjectAdfConfig;
#[cfg(feature = "quickwit")]
pub use quickwit_bulk::QuickwitEsBulkSink;
pub use rate_limiter::{is_rate_limit_backoff_enabled, RateLimiter};
pub use scheduler::{ScheduleEvent, TimeScheduler};
pub use worktree_guard::{with_worktree_guard, with_worktree_guard_async, WorktreeGuard};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use std::sync::{Arc, Mutex};
use terraphim_router::RoutingEngine;
use terraphim_spawner::health::{CircuitBreaker, HealthStatus};
use terraphim_spawner::output::OutputEvent;
use terraphim_spawner::{AgentHandle, AgentSpawner, SpawnContext};
use tokio::sync::broadcast;
use tracing::{debug, error, info, warn};
/// Result of evaluating a pre-check strategy before spawning an agent.
#[derive(Debug, Clone)]
pub enum PreCheckResult {
/// Pre-check found actionable findings. Agent should spawn with findings prepended.
Findings(String),
/// Nothing to do. Skip spawn.
NoFindings,
/// Pre-check execution itself failed. Fail-open: spawn anyway.
Failed(String),
}
/// Status of a single agent in the fleet.
#[derive(Debug, Clone)]
pub struct AgentStatus {
pub name: String,
pub layer: AgentLayer,
pub running: bool,
pub health: HealthStatus,
pub drift_score: Option<f64>,
pub uptime: Duration,
pub restart_count: u32,
/// API calls remaining per provider (None if no limit known).
pub api_calls_remaining: HashMap<String, Option<u32>>,
}
/// Runtime state for a managed agent.
struct ManagedAgent {
definition: AgentDefinition,
handle: AgentHandle,
started_at: Instant,
restart_count: u32,
output_rx: broadcast::Receiver<OutputEvent>,
spawned_by_mention: bool,
worktree_path: Option<PathBuf>,
routed_model: Option<String>,
session_id: String,
mention_chain_id: Option<String>,
mention_depth: Option<u32>,
mention_parent_agent: Option<String>,
/// Concurrency permit held while the agent is running. Released on drop.
#[allow(dead_code)]
concurrency_permit: Option<concurrency::AgentPermit>,
/// When set, post a terminal commit status on agent exit.
/// Tuple of (head_sha, context).
commit_status_post: Option<(String, String)>,
/// When set, derive the terminal commit status from a parsed
/// `adf:gate-result` block in the agent's drain log instead of the
/// process exit code. Populated for PR gate agents only.
gate_meta: Option<crate::pr_gate_result::PrGateMeta>,
/// Temp file path for streaming agent output. Renamed to final path on exit.
output_tmp_path: Option<PathBuf>,
/// Worktree guard for automatic cleanup on agent crash.
#[allow(dead_code)]
worktree_guard: Option<crate::worktree_guard::WorktreeGuard>,
}
#[cfg(not(test))]
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
struct PersistedRestartState {
/// project -> agent -> restart count
#[serde(default)]
counts_by_project: HashMap<String, HashMap<String, u32>>,
/// project -> agent -> last failure timestamp (unix seconds)
#[serde(default)]
last_failure_unix_secs_by_project: HashMap<String, HashMap<String, i64>>,
/// Legacy flat map retained for backward-compatible deserialisation.
#[serde(default, skip_serializing)]
counts: HashMap<String, u32>,
/// Legacy flat map retained for backward-compatible deserialisation.
#[serde(default, skip_serializing)]
last_failure_unix_secs: HashMap<String, i64>,
}
/// The main orchestrator that runs the dark factory.
pub struct AgentOrchestrator {
config: OrchestratorConfig,
agent_registry: AgentRegistry,
spawner: AgentSpawner,
router: RoutingEngine,
nightwatch: NightwatchMonitor,
scheduler: TimeScheduler,
compound_workflow: CompoundReviewWorkflow,
active_agents: HashMap<String, ManagedAgent>,
rate_limiter: RateLimitTracker,
shutdown_requested: bool,
/// Total restart count per (project, agent) pair (persists across agent lifecycle).
restart_counts: HashMap<(String, String), u32>,
/// Last non-zero exit timestamp per (project, agent), used for budget windowing.
restart_last_failure_unix_secs: HashMap<(String, String), i64>,
/// Last exit time per (project, agent) (for cooldown enforcement).
restart_cooldowns: HashMap<(String, String), Instant>,
/// Timestamp of the last reconciliation tick (for cron comparison).
last_tick_time: chrono::DateTime<chrono::Utc>,
/// In-memory buffer for handoff contexts with TTL.
handoff_buffer: HandoffBuffer,
/// Append-only JSONL ledger for handoff history.
handoff_ledger: HandoffLedger,
/// Per-agent cost tracking with budget enforcement.
cost_tracker: CostTracker,
/// Registry of persona definitions for metaprompt generation.
persona_registry: PersonaRegistry,
/// Renderer for persona metaprompts.
metaprompt_renderer: MetapromptRenderer,
/// Output poster for posting agent output to Gitea issues.
output_poster: Option<OutputPoster>,
/// Circuit breakers for each provider to prevent cascading failures.
#[allow(dead_code)]
circuit_breakers: Arc<Mutex<HashMap<String, CircuitBreaker>>>,
/// Per-agent last-run commit hash for GitDiff strategy.
/// Key: agent name. Value: commit SHA.
last_run_commits: HashMap<String, String>,
/// Per-agent last cron fire timestamp to prevent re-triggering within same schedule window.
/// Key: agent name. Value: timestamp of last fire.
last_cron_fire: HashMap<String, chrono::DateTime<chrono::Utc>>,
/// Last compound-review fire time, used to gate the compound schedule
/// independently of `last_tick_time`. Mirrors the `last_cron_fire`
/// pattern for per-agent crons. Without this cursor, if the
/// `reconcile_tick` future is cancelled mid-await by its 90 s
/// `tokio::time::timeout` safety wrapper, `last_tick_time` is never
/// advanced and the same compound-review occurrence re-fires on the
/// very next tick, producing a worktree storm (#1562).
last_compound_review_fired_at: Option<chrono::DateTime<chrono::Utc>>,
/// Lazy-initialised Gitea tracker for gitea-issue pre-check.
pre_check_tracker: Option<terraphim_tracker::GiteaTracker>,
/// Active flow executions keyed by flow name.
#[allow(dead_code)]
active_flows: HashMap<String, tokio::task::JoinHandle<flow::state::FlowRunState>>,
/// Active compound review execution (spawned in background to avoid
/// blocking reconcile_tick). None when no compound review is running.
active_compound_review:
Option<tokio::task::JoinHandle<Result<CompoundReviewResult, OrchestratorError>>>,
/// Per-project mention cursors, keyed by project id.
///
/// Each project gets its own cursor so repo-wide polls can advance
/// independently. Legacy single-project mode uses the synthetic
/// [`dispatcher::LEGACY_PROJECT_ID`] key.
mention_cursors: HashMap<String, MentionCursor>,
/// Receiver for webhook dispatch requests.
webhook_dispatch_rx: Option<tokio::sync::mpsc::Receiver<webhook::WebhookDispatch>>,
/// Monotonically increasing tick counter for poll_modulo gating.
tick_count: u64,
#[cfg(feature = "quickwit")]
quickwit_sink: Option<quickwit::QuickwitFleetSink>,
/// Classifier for structured agent exit classification using KG-boosted matching.
exit_classifier: ExitClassifier,
/// KG-driven model router loaded from taxonomy markdown files.
kg_router: Option<kg_router::KgRouter>,
/// Per-provider health tracking with circuit breakers.
provider_health: provider_probe::ProviderHealthMap,
/// Live telemetry store for model performance tracking from CLI output.
telemetry_store: control_plane::TelemetryStore,
/// Per-provider hour/day spend tracker consulted by the routing
/// engine. `None` when the config declares no [[providers]] entries.
provider_budget_tracker: Option<Arc<provider_budget::ProviderBudgetTracker>>,
/// Compiled per-provider stderr classifiers built from
/// `[[providers]].error_signatures`. Providers without signatures
/// are absent from the map and classify as
/// [`error_signatures::ErrorKind::Unknown`] (fail-safe).
provider_error_signatures: error_signatures::ProviderSignatureMap,
provider_rate_limits: ProviderRateLimitWindow,
retry_counts: HashMap<String, (u32, Instant)>,
/// Dedupe set of [`error_signatures::unknown_dedupe_key`] values so we
/// don't open a new `[ADF]` Gitea issue for every retry of the same
/// stderr shape. Process-lifetime in-memory; intentional since the
/// window between duplicates is short and restarting the orchestrator
/// is an acceptable dedupe reset.
unknown_error_dedupe: Arc<Mutex<std::collections::HashSet<String>>>,
/// Counter of consecutive `project-meta` failures per project. Tripped
/// entries cause the orchestrator to create a pause flag and open an
/// `[ADF]` Gitea escalation issue.
project_failure_counter: project_control::ProjectFailureCounter,
/// Resolved pause-flag directory. Derived from
/// [`OrchestratorConfig::pause_dir`] or [`project_control::DEFAULT_PAUSE_DIR`].
pause_dir: PathBuf,
/// Unified priority queue for all dispatch sources (time, issue, mention,
/// review-pr, auto-merge, post-merge-gate).
dispatcher: dispatcher::Dispatcher,
/// Per-(project, PR) rate limiter for verdict polling. Keeps the
/// orchestrator from re-hitting Gitea for the same PR every tick.
pr_poll_rate_limiter: pr_poller::PrPollRateLimiter,
/// Per-project dedupe set of `(pr_number, head_sha)` already enqueued
/// for auto-merge so the same revision is never dispatched twice.
auto_merge_enqueued: pr_poller::AutoMergeDedupeSet,
/// TTL-based dedupe cache for auto-merge failure issues. Prevents
/// duplicate `[ADF] Auto-merge failed` issues for the same PR within
/// a 24-hour window.
auto_merge_failure_dedupe: pr_poller::AutoMergeFailureDedupe,
/// Shared learning store. `None` when `learning.enabled = false` or
/// when initialisation failed (graceful degradation).
learning_store: Option<learning::SharedLearningStore>,
/// Learning config snapshot (min_trust, max_tokens, etc.).
learning_config: config::LearningConfig,
/// Agent name -> learning IDs injected at spawn time, used to record
/// outcome feedback at exit.
injected_learning_ids: HashMap<String, Vec<String>>,
/// Global concurrency controller enforcing agent limits and fairness.
concurrency_controller: concurrency::ConcurrencyController,
/// Directory for per-agent output log files. Each completed agent run
/// writes its stdout+stderr to `<agent_log_dir>/<name>-<timestamp>.log`.
agent_log_dir: PathBuf,
/// Cache directory populated from Gitea at startup (issue #1434).
/// `None` when `gitea_skill_repo` is not configured. When `Some`, this
/// directory is prepended to the skill search path so remote skills
/// shadow local ones while local directories remain as fallback.
gitea_skill_cache_dir: Option<PathBuf>,
/// Agent evolution manager. No-op when evolution feature is disabled
/// or `evolution.enabled = false` in config.
evolution_manager: evolution::EvolutionManager,
config_error_counters: HashMap<String, u32>,
quarantined_agents: std::collections::HashSet<String>,
}
/// Build the composite restart-state key for an agent definition.
///
/// Legacy (project-less) agents use [`crate::dispatcher::LEGACY_PROJECT_ID`]
/// so restart counts never collide across projects once projects are added.
pub(crate) fn agent_key(def: &AgentDefinition) -> (String, String) {
(
def.project
.clone()
.unwrap_or_else(|| crate::dispatcher::LEGACY_PROJECT_ID.to_string()),
def.name.clone(),
)
}
struct ProviderRateLimitWindow {
blocked_until: HashMap<String, Instant>,
}
impl ProviderRateLimitWindow {
fn new() -> Self {
Self {
blocked_until: HashMap::new(),
}
}
fn block_until(&mut self, provider: &str, until: Instant) {
self.blocked_until.insert(provider.to_string(), until);
}
#[allow(dead_code)]
fn is_blocked(&self, provider: &str) -> bool {
self.blocked_until
.get(provider)
.is_some_and(|until| Instant::now() < *until)
}
fn blocked_providers(&self) -> Vec<String> {
let now = Instant::now();
self.blocked_until
.iter()
.filter(|(_, until)| **until > now)
.map(|(k, _)| k.clone())
.collect()
}
fn clean_expired(&mut self) {
let now = Instant::now();
self.blocked_until.retain(|_, until| *until > now);
}
}
/// Conservative fallback block applied at the quota-detect site when no
/// "resets" line is present in stderr at all (i.e. `parse_reset_time` cannot
/// even be invoked with useful input). Long enough to skip the next cron
/// firing (~30 min active-window cadence); short enough that a misclassified
/// non-quota error does not disable the provider for the day.
pub(crate) const DEFAULT_RATE_LIMIT_BLOCK: Duration = Duration::from_secs(900);
pub(crate) fn parse_reset_time(quota_line: &str) -> Option<Instant> {
let line = quota_line.to_lowercase();
if let Some(idx) = line.find("resets in ") {
let rest = &line[idx + "resets in ".len()..];
let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
if let Ok(n) = digits.parse::<u64>() {
if rest.contains("hour") {
return Some(Instant::now() + Duration::from_secs(n * 3600));
}
if rest.contains("minute") {
return Some(Instant::now() + Duration::from_secs(n * 60));
}
// Short abbreviations used by Claude Code: "resets in 4h", "resets in 30m".
// The character immediately after the digits disambiguates the unit.
let unit = rest.chars().nth(digits.len());
match unit {
Some('h') => return Some(Instant::now() + Duration::from_secs(n * 3600)),
Some('m') => {
// Guard against "min..." which is already handled above; the
// "minute" branch returned first, so any remaining 'm' here
// is the short form.
return Some(Instant::now() + Duration::from_secs(n * 60));
}
_ => {}
}
}
}
// "resets 11pm" / "resets 7am" -- wall-clock hour with am/pm suffix, no "in"/"at".
// Treat the hour as UTC (bigbox locale); compute next future occurrence.
if let Some(idx) = line.find("resets ") {
let rest = line[idx + "resets ".len()..].trim_start();
let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
if !digits.is_empty() {
let after_digits = &rest[digits.len()..];
let is_pm = after_digits.starts_with("pm");
let is_am = after_digits.starts_with("am");
if is_pm || is_am {
if let Ok(h) = digits.parse::<u32>() {
if h <= 12 {
let hour_24 = match (h, is_pm) {
(12, true) => 12,
(12, false) => 0,
(h, true) => h + 12,
(h, false) => h,
};
if let Some(time) = chrono::NaiveTime::from_hms_opt(hour_24, 0, 0) {
let now = chrono::Utc::now();
let mut target_date = now.date_naive();
let mut target_utc =
chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
target_date.and_time(time),
chrono::Utc,
);
if target_utc <= now {
target_date += chrono::Duration::days(1);
target_utc =
chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
target_date.and_time(time),
chrono::Utc,
);
}
if let Ok(delta) = (target_utc - now).to_std() {
return Some(Instant::now() + delta);
}
}
}
}
}
}
}
if let Some(idx) = line.find("resets at ") {
let rest = &line[idx + "resets at ".len()..];
if let Some(time_str) = rest
.strip_suffix(" utc")
.or_else(|| rest.strip_suffix(" utc."))
{
if let Ok(hour_min) = chrono::NaiveTime::parse_from_str(time_str.trim(), "%H:%M") {
let now = chrono::Utc::now();
let mut target_date = now.date_naive();
let target = target_date.and_time(hour_min);
let mut target_utc =
chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(target, chrono::Utc);
if target_utc <= now {
target_date += chrono::Duration::days(1);
let target = target_date.and_time(hour_min);
target_utc = chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
target,
chrono::Utc,
);
}
let delta = (target_utc - now).to_std().ok()?;
return Some(Instant::now() + delta);
}
}
}
if line.contains("resets ") {
return Some(Instant::now() + Duration::from_secs(3600));
}
None
}
/// Build the optional provider-level hour/day budget tracker from the
/// [[providers]] config block. Returns `Ok(None)` when no providers are
/// declared (no cap = no tracker, routing works unchanged).
fn build_provider_budget_tracker(
config: &OrchestratorConfig,
) -> Result<Option<Arc<provider_budget::ProviderBudgetTracker>>, OrchestratorError> {
if config.providers.is_empty() {
if config.provider_budget_state_file.is_some() {
warn!("provider_budget_state_file set but no [[providers]] entries; tracker disabled");
}
return Ok(None);
}
let tracker = match config.provider_budget_state_file.as_ref() {
Some(path) => provider_budget::ProviderBudgetTracker::with_persistence(
config.providers.clone(),
path.clone(),
)
.map_err(|e| {
OrchestratorError::Config(format!(
"failed to load provider budget state from {}: {}",
path.display(),
e
))
})?,
None => provider_budget::ProviderBudgetTracker::new(config.providers.clone()),
};
info!(
providers = tracker.providers().collect::<Vec<_>>().join(","),
persistence = ?config.provider_budget_state_file,
"provider budget tracker initialised"
);
Ok(Some(Arc::new(tracker)))
}
/// Build the global concurrency controller from orchestrator config.
///
/// Uses `workflow.concurrency` when workflow mode is configured; otherwise
/// falls back to sensible defaults (global_max = 10, time_max = 10,
/// issue_max = 5, round-robin fairness).
fn build_concurrency_controller(config: &OrchestratorConfig) -> concurrency::ConcurrencyController {
let (global_max, time_max, issue_max, fairness) = config
.workflow
.as_ref()
.map(|w| {
(
w.concurrency.global_max,
w.concurrency.global_max, // time-driven shares global pool
w.concurrency.issue_max,
w.concurrency
.fairness
.parse::<concurrency::FairnessPolicy>()
.unwrap_or(concurrency::FairnessPolicy::RoundRobin),
)
})
.unwrap_or((10, 10, 5, concurrency::FairnessPolicy::RoundRobin));
let quotas = concurrency::ModeQuotas {
time_max,
issue_max,
};
let project_caps: HashMap<String, concurrency::ProjectCaps> = config
.projects
.iter()
.filter_map(|p| {
p.max_concurrent_agents.map(|max| {
(
p.id.clone(),
concurrency::ProjectCaps {
max_concurrent_agents: max,
max_concurrent_mention_agents: p.max_concurrent_mention_agents,
},
)
})
})
.collect();
concurrency::ConcurrencyController::with_project_caps(
global_max,
quotas,
fairness,
project_caps,
)
}
/// Build the per-project runtime map consumed by
/// [`flow::executor::FlowExecutor::with_projects`].
pub(crate) fn build_flow_project_runtimes(
config: &OrchestratorConfig,
) -> HashMap<String, flow::executor::ProjectRuntime> {
config
.projects
.iter()
.map(|p| {
(
p.id.clone(),
flow::executor::ProjectRuntime {
working_dir: p.working_dir.clone(),
gitea_owner: p.gitea.as_ref().map(|g| g.owner.clone()),
gitea_repo: p.gitea.as_ref().map(|g| g.repo.clone()),
},
)
})
.collect()
}
/// Build a [`SpawnContext`] for an agent, resolving per-project working_dir,
/// Gitea owner/repo, and the project id itself into the child process's
/// environment (`ADF_PROJECT_ID`, `ADF_WORKING_DIR`, `GITEA_OWNER`,
/// `GITEA_REPO`). Legacy (project-less) agents use [`SpawnContext::global()`].
///
/// When an [`OutputPoster`] is available and has a per-agent Gitea token
/// for `(project, agent_name)` (loaded from `agent_tokens.json`), the
/// token is injected as `GITEA_TOKEN` so the agent's own `gtr` / API
/// calls inside its task shell post under its own Gitea identity. Without
/// this, `source ~/.profile` would overlay the shared root token.
pub(crate) fn build_spawn_context_for_agent(
config: &OrchestratorConfig,
def: &AgentDefinition,
output_poster: Option<&OutputPoster>,
) -> SpawnContext {
let Some(pid) = def.project.as_deref() else {
return SpawnContext::global();
};
let Some(project) = config.project_by_id(pid) else {
return SpawnContext::global();
};
let working_dir_str = project.working_dir.to_string_lossy().into_owned();
let mut ctx = SpawnContext::with_working_dir(project.working_dir.clone())
.with_env("ADF_PROJECT_ID", pid)
.with_env("ADF_WORKING_DIR", working_dir_str);
if let Some(gitea) = project.gitea.as_ref() {
ctx = ctx
.with_env("GITEA_URL", gitea.base_url.clone())
.with_env("GITEA_OWNER", gitea.owner.clone())
.with_env("GITEA_REPO", gitea.repo.clone());
}
if let Some(poster) = output_poster {
if let Some(token) = poster.agent_token(pid, &def.name) {
ctx = ctx.with_env("GITEA_TOKEN", token.to_string());
}
}
ctx
}
/// Flatten persisted nested maps (project -> agent -> count) and any legacy
/// flat entries into the in-memory composite key map. Legacy flat entries are
/// mapped to [`crate::dispatcher::LEGACY_PROJECT_ID`].
#[cfg(not(test))]
fn flatten_restart_counts(state: &PersistedRestartState) -> HashMap<(String, String), u32> {
let mut out: HashMap<(String, String), u32> = HashMap::new();
for (project, per_agent) in &state.counts_by_project {
for (agent, count) in per_agent {
out.insert((project.clone(), agent.clone()), *count);
}
}
for (agent, count) in &state.counts {
out.entry((
crate::dispatcher::LEGACY_PROJECT_ID.to_string(),
agent.clone(),
))
.or_insert(*count);
}
out
}
/// Flatten persisted nested maps for last-failure timestamps into the
/// composite key format.
#[cfg(not(test))]
fn flatten_restart_failures(state: &PersistedRestartState) -> HashMap<(String, String), i64> {
let mut out: HashMap<(String, String), i64> = HashMap::new();
for (project, per_agent) in &state.last_failure_unix_secs_by_project {
for (agent, ts) in per_agent {
out.insert((project.clone(), agent.clone()), *ts);
}
}
for (agent, ts) in &state.last_failure_unix_secs {
out.entry((
crate::dispatcher::LEGACY_PROJECT_ID.to_string(),
agent.clone(),
))
.or_insert(*ts);
}
out
}
/// Re-nest composite keyed maps into the persisted `project -> agent -> value`
/// shape for serialisation.
#[cfg(not(test))]
fn nest_by_project<V: Clone>(
flat: &HashMap<(String, String), V>,
) -> HashMap<String, HashMap<String, V>> {
let mut out: HashMap<String, HashMap<String, V>> = HashMap::new();
for ((project, agent), value) in flat {
out.entry(project.clone())
.or_default()
.insert(agent.clone(), value.clone());
}
out
}
/// Validate agent name for safe use in file paths.
/// Rejects empty names, names containing path separators or traversal sequences.
fn validate_agent_name(name: &str) -> Result<(), OrchestratorError> {
if name.is_empty()
|| name.contains('/')
|| name.contains('\\')
|| name.contains("..")
|| !name
.chars()
.all(|c| c.is_alphanumeric() || c == '-' || c == '_')
{
return Err(OrchestratorError::InvalidAgentName(name.to_string()));
}
Ok(())
}
/// Truncate a string to at most `max_bytes` UTF-8 bytes, honouring char
/// boundaries. If truncation occurs, append a marker so the reader knows.
pub(crate) fn truncate_for_issue(s: &str, max_bytes: usize) -> String {
if s.len() <= max_bytes {
return s.to_string();
}
let mut end = max_bytes;
while end > 0 && !s.is_char_boundary(end) {
end -= 1;
}
format!("{}... (truncated)", &s[..end])
}
impl AgentOrchestrator {
/// Create a new orchestrator from configuration.
pub fn new(config: OrchestratorConfig) -> Result<Self, OrchestratorError> {
// Set CARGO_TARGET_DIR so worktree agents share the main build cache,
// and RUSTC_WRAPPER=sccache for cross-worktree compilation caching.
let mut spawn_env = std::collections::HashMap::new();
let target_dir = config.working_dir.join("target");
spawn_env.insert(
"CARGO_TARGET_DIR".to_string(),
target_dir.to_string_lossy().to_string(),
);
if std::process::Command::new("sccache")
.arg("--version")
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok()
{
spawn_env.insert("RUSTC_WRAPPER".to_string(), "sccache".to_string());
info!("sccache detected, enabling shared compilation cache for worktrees");
}
let spawner = AgentSpawner::new()
.with_working_dir(&config.working_dir)
.with_env_vars(spawn_env);
let router = RoutingEngine::new();
let nightwatch = NightwatchMonitor::new(config.nightwatch.clone());
let scheduler = TimeScheduler::new(&config.agents, Some(&config.compound_review.schedule))?;
let compound_workflow =
CompoundReviewWorkflow::from_compound_config(config.compound_review.clone());
let agent_registry = AgentRegistry::from_config(&config)?;
// Layer 2 startup sweep (epic #1567, issue #1570).
//
// Reconcile any worktree residue left by a previous instance
// before we accept ticks. Synchronous: must finish before the
// tick thread is spawned in `run()` so a fresh review cycle
// never races against half-killed `review-*` directories.
//
// `extra_roots` mirrors the per-agent worktree convention
// from `lib.rs:5393`. If you change that literal there, change
// it here too.
//
// `cfg(not(test))` gate: the in-lib `test_config()` (see
// `lib.rs:7926`) points `repo_path` at the live terraphim-ai
// checkout. Without this gate, the sweep's
// `git worktree prune --verbose` races against
// `test_orchestrator_compound_review_manual`'s concurrent
// `git worktree add` on that shared real repo's
// `.git/worktrees/` admin registry. The production wiring is
// exercised end-to-end by `tests/sweep_on_startup_test.rs`,
// which builds an isolated `TempDir` repo and asserts the
// sweep DOES run from `AgentOrchestrator::new`. Do not remove
// this gate without first migrating the in-lib `test_config()`
// to a TempDir-based `repo_path`.
#[cfg(not(test))]
{
let sweep_report = compound_workflow.worktree_manager().sweep_stale(&[]);
if sweep_report.swept_count + sweep_report.root_owned_skipped > 10 {
warn!(
swept_count = sweep_report.swept_count,
root_owned_skipped = sweep_report.root_owned_skipped,
failed_count = sweep_report.failed_count,
"large worktree backlog at startup -- prior crash storm likely"
);
}
}
let handoff_buffer = HandoffBuffer::new(config.handoff_buffer_ttl_secs.unwrap_or(86400));
let handoff_ledger = HandoffLedger::new(config.working_dir.join("handoff-ledger.jsonl"));
// Initialize cost tracker and register all agents with their budgets
let mut cost_tracker = CostTracker::new();
for agent_def in &config.agents {
cost_tracker.register(&agent_def.name, agent_def.budget_monthly_cents);
}
// Initialize persona registry - load from configured directory or create empty
let persona_registry = match &config.persona_data_dir {
Some(dir) => {
info!(dir = %dir.display(), "loading persona registry from directory");
PersonaRegistry::load_from_dir(dir).unwrap_or_else(|e| {
warn!(dir = %dir.display(), error = %e, "failed to load persona directory, using empty registry");
PersonaRegistry::new()
})
}
None => {
info!("no persona_data_dir configured, using empty registry");
PersonaRegistry::new()
}
};
// Initialize metaprompt renderer - check for custom template or use default
let metaprompt_renderer = match &config.persona_data_dir {
Some(dir) => {
let custom_template = dir.join("metaprompt-template.hbs");
if custom_template.exists() {
info!(path = %custom_template.display(), "using custom metaprompt template");
MetapromptRenderer::from_template_file(&custom_template).unwrap_or_else(|e| {
warn!(path = %custom_template.display(), error = %e, "failed to load custom template, using default");
MetapromptRenderer::new().expect("default template should always compile")
})
} else {
MetapromptRenderer::new().expect("default template should always compile")
}
}
None => MetapromptRenderer::new().expect("default template should always compile"),
};
// Initialize output poster. In multi-project mode this wires one
// tracker per project plus a legacy fallback from `config.gitea`; in
// legacy single-project mode it collapses to the top-level config.
let output_poster = OutputPoster::from_orchestrator_config(&config);
// Initialize KG router from taxonomy directory if configured
let kg_router = config.routing.as_ref().and_then(|routing_config| {
match kg_router::KgRouter::load(&routing_config.taxonomy_path) {
Ok(router) => {
info!(
path = %routing_config.taxonomy_path.display(),
rules = router.rule_count(),
"KG model router loaded"
);
Some(router)
}
Err(e) => {
warn!(error = %e, "KG router failed to load, using static model config");
None
}
}
});
let probe_ttl = config
.routing
.as_ref()
.map(|r| r.probe_ttl_secs)
.unwrap_or(300);
let provider_health =
provider_probe::ProviderHealthMap::new(std::time::Duration::from_secs(probe_ttl))
.with_rate_limiter(crate::rate_limiter::RateLimiter::new());
let telemetry_store = control_plane::TelemetryStore::new(3600);
let provider_budget_tracker = build_provider_budget_tracker(&config)?;
// Compile per-provider stderr signatures declared under
// `[[providers]].error_signatures`. Invalid regexes fail loud
// at startup so misconfiguration can never silently disable
// runtime classification.
let provider_error_signatures = error_signatures::build_signature_map(&config.providers)
.map_err(|e| OrchestratorError::Config(e.to_string()))?;
let project_failure_counter =
project_control::ProjectFailureCounter::new(config.project_circuit_breaker_threshold);
let pause_dir = config
.pause_dir
.clone()
.unwrap_or_else(|| PathBuf::from(project_control::DEFAULT_PAUSE_DIR));
#[cfg(not(test))]
let restart_state = Self::load_restart_state();
let learning_config = config.learning.clone();
// MentionCursor loaded lazily on first poll (async)
Ok(Self {
config: config.clone(),
agent_registry,
spawner,
router,
nightwatch,
scheduler,
compound_workflow,
active_agents: HashMap::new(),
rate_limiter: RateLimitTracker::default(),
shutdown_requested: false,
restart_counts: {
#[cfg(not(test))]
{
flatten_restart_counts(&restart_state)
}
#[cfg(test)]
{
HashMap::new()
}
},
restart_last_failure_unix_secs: {
#[cfg(not(test))]
{
flatten_restart_failures(&restart_state)
}
#[cfg(test)]
{
HashMap::new()
}
},
restart_cooldowns: HashMap::new(),
last_tick_time: chrono::Utc::now(),
handoff_buffer,
handoff_ledger,
cost_tracker,
persona_registry,
metaprompt_renderer,
output_poster,
circuit_breakers: Arc::new(Mutex::new(HashMap::new())),
last_run_commits: HashMap::new(),
last_cron_fire: HashMap::new(),
last_compound_review_fired_at: None,
pre_check_tracker: None,
active_flows: HashMap::new(),
active_compound_review: None,
mention_cursors: HashMap::new(),
webhook_dispatch_rx: None,
tick_count: 0,
#[cfg(feature = "quickwit")]
quickwit_sink: None,
exit_classifier: ExitClassifier::new(),
kg_router,
provider_health,
telemetry_store,
provider_budget_tracker,
provider_error_signatures,
provider_rate_limits: ProviderRateLimitWindow::new(),
retry_counts: HashMap::new(),
unknown_error_dedupe: Arc::new(Mutex::new(std::collections::HashSet::new())),
project_failure_counter,
pause_dir,
dispatcher: dispatcher::Dispatcher::new(),
pr_poll_rate_limiter: pr_poller::PrPollRateLimiter::new(
pr_poller::PR_POLL_MIN_INTERVAL,
),
auto_merge_enqueued: pr_poller::AutoMergeDedupeSet::new(),
auto_merge_failure_dedupe: pr_poller::AutoMergeFailureDedupe::new(
std::time::Duration::from_secs(86400),
),
learning_store: None,