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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
|
//! HTTP handlers for supervisor-specific mesh operations.
//!
//! These endpoints are used by supervisor tasks (via supervisor.sh) to orchestrate
//! contract work: spawning tasks, waiting for completion, reading worktree files, etc.
use axum::{
extract::{Path, State},
http::{HeaderMap, StatusCode},
response::IntoResponse,
Json,
};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;
use crate::db::models::{CreateTaskRequest, Task, TaskSummary};
use crate::db::repository;
use crate::server::handlers::mesh::{extract_auth, AuthSource};
use crate::server::messages::ApiError;
use crate::server::state::{DaemonCommand, SharedState};
// =============================================================================
// Request/Response Types
// =============================================================================
/// Request to spawn a new task from supervisor.
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct SpawnTaskRequest {
pub name: String,
pub plan: String,
pub contract_id: Uuid,
pub parent_task_id: Option<Uuid>,
pub checkpoint_sha: Option<String>,
/// Repository URL for the task (supervisor should provide this)
pub repository_url: Option<String>,
}
/// Request to wait for task completion.
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct WaitForTaskRequest {
#[serde(default = "default_timeout")]
pub timeout_seconds: i32,
}
fn default_timeout() -> i32 {
300
}
/// Request to read a file from task worktree.
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ReadWorktreeFileRequest {
pub file_path: String,
}
/// Request to create a checkpoint.
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreateCheckpointRequest {
pub message: String,
}
/// Response for task tree.
#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct TaskTreeResponse {
pub tasks: Vec<TaskSummary>,
pub supervisor_task_id: Option<Uuid>,
pub total_count: usize,
}
/// Response for wait operation.
#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct WaitResponse {
pub task_id: Uuid,
pub status: String,
pub completed: bool,
pub output_summary: Option<String>,
}
/// Response for read file operation.
#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ReadFileResponse {
pub task_id: Uuid,
pub file_path: String,
pub content: String,
pub exists: bool,
}
/// Response for checkpoint operations.
#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CheckpointResponse {
pub task_id: Uuid,
pub checkpoint_number: i32,
pub commit_sha: String,
pub message: String,
}
/// Task checkpoint info.
#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct TaskCheckpoint {
pub id: Uuid,
pub task_id: Uuid,
pub checkpoint_number: i32,
pub commit_sha: String,
pub branch_name: String,
pub message: String,
pub files_changed: Option<serde_json::Value>,
pub lines_added: i32,
pub lines_removed: i32,
pub created_at: chrono::DateTime<chrono::Utc>,
}
/// Response for list checkpoints.
#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CheckpointListResponse {
pub task_id: Uuid,
pub checkpoints: Vec<TaskCheckpoint>,
}
// =============================================================================
// Helper Functions
// =============================================================================
/// Verify the request comes from a supervisor task and extract ownership info.
async fn verify_supervisor_auth(
state: &SharedState,
headers: &HeaderMap,
contract_id: Option<Uuid>,
) -> Result<(Uuid, Uuid), (StatusCode, Json<ApiError>)> {
let auth = extract_auth(state, headers);
let task_id = match auth {
AuthSource::ToolKey(task_id) => task_id,
_ => {
return Err((
StatusCode::UNAUTHORIZED,
Json(ApiError::new("UNAUTHORIZED", "Supervisor endpoints require tool key auth")),
));
}
};
// Get the task to verify it's a supervisor and get owner_id
let pool = state.db_pool.as_ref().ok_or_else(|| {
(
StatusCode::SERVICE_UNAVAILABLE,
Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
)
})?;
let task = repository::get_task(pool, task_id)
.await
.map_err(|e| {
tracing::error!(error = %e, "Failed to get supervisor task");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(ApiError::new("DB_ERROR", "Failed to verify supervisor")),
)
})?
.ok_or_else(|| {
(
StatusCode::NOT_FOUND,
Json(ApiError::new("NOT_FOUND", "Task not found")),
)
})?;
// Verify task is a supervisor
if !task.is_supervisor {
return Err((
StatusCode::FORBIDDEN,
Json(ApiError::new("NOT_SUPERVISOR", "Only supervisor tasks can use these endpoints")),
));
}
// If contract_id provided, verify the supervisor belongs to that contract
if let Some(cid) = contract_id {
if task.contract_id != Some(cid) {
return Err((
StatusCode::FORBIDDEN,
Json(ApiError::new("CONTRACT_MISMATCH", "Supervisor does not belong to this contract")),
));
}
}
Ok((task_id, task.owner_id))
}
// =============================================================================
// Contract Task Handlers
// =============================================================================
/// List all tasks in a contract's tree.
#[utoipa::path(
get,
path = "/api/v1/mesh/supervisor/contracts/{contract_id}/tasks",
params(
("contract_id" = Uuid, Path, description = "Contract ID")
),
responses(
(status = 200, description = "List of tasks in contract", body = TaskTreeResponse),
(status = 401, description = "Unauthorized"),
(status = 403, description = "Forbidden - not a supervisor"),
(status = 500, description = "Internal server error"),
),
tag = "Mesh Supervisor"
)]
pub async fn list_contract_tasks(
State(state): State<SharedState>,
Path(contract_id): Path<Uuid>,
headers: HeaderMap,
) -> impl IntoResponse {
let (_supervisor_id, owner_id) = match verify_supervisor_auth(&state, &headers, Some(contract_id)).await {
Ok(ids) => ids,
Err(e) => return e.into_response(),
};
let pool = state.db_pool.as_ref().unwrap();
// Get all tasks for this contract
match repository::list_tasks_by_contract(pool, contract_id, owner_id).await {
Ok(tasks) => {
let supervisor_task_id = tasks.iter().find(|t| t.is_supervisor).map(|t| t.id);
let summaries: Vec<TaskSummary> = tasks.into_iter().map(TaskSummary::from).collect();
let total_count = summaries.len();
(
StatusCode::OK,
Json(TaskTreeResponse {
tasks: summaries,
supervisor_task_id,
total_count,
}),
).into_response()
}
Err(e) => {
tracing::error!(error = %e, "Failed to list contract tasks");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(ApiError::new("DB_ERROR", "Failed to list tasks")),
).into_response()
}
}
}
/// Get full task tree structure for a contract.
#[utoipa::path(
get,
path = "/api/v1/mesh/supervisor/contracts/{contract_id}/tree",
params(
("contract_id" = Uuid, Path, description = "Contract ID")
),
responses(
(status = 200, description = "Task tree structure", body = TaskTreeResponse),
(status = 401, description = "Unauthorized"),
(status = 403, description = "Forbidden - not a supervisor"),
(status = 500, description = "Internal server error"),
),
tag = "Mesh Supervisor"
)]
pub async fn get_contract_tree(
State(state): State<SharedState>,
Path(contract_id): Path<Uuid>,
headers: HeaderMap,
) -> impl IntoResponse {
// Same as list_contract_tasks for now - can add tree structure later
list_contract_tasks(State(state), Path(contract_id), headers).await
}
// =============================================================================
// Task Spawn Handler
// =============================================================================
/// Spawn a new task (supervisor only).
#[utoipa::path(
post,
path = "/api/v1/mesh/supervisor/tasks",
request_body = SpawnTaskRequest,
responses(
(status = 201, description = "Task created", body = Task),
(status = 400, description = "Invalid request"),
(status = 401, description = "Unauthorized"),
(status = 403, description = "Forbidden - not a supervisor"),
(status = 500, description = "Internal server error"),
),
tag = "Mesh Supervisor"
)]
pub async fn spawn_task(
State(state): State<SharedState>,
headers: HeaderMap,
Json(request): Json<SpawnTaskRequest>,
) -> impl IntoResponse {
let (supervisor_id, owner_id) = match verify_supervisor_auth(&state, &headers, Some(request.contract_id)).await {
Ok(ids) => ids,
Err(e) => return e.into_response(),
};
let pool = state.db_pool.as_ref().unwrap();
// Verify contract exists
let _contract = match repository::get_contract_for_owner(pool, request.contract_id, owner_id).await {
Ok(Some(c)) => c,
Ok(None) => {
return (
StatusCode::NOT_FOUND,
Json(ApiError::new("NOT_FOUND", "Contract not found")),
).into_response();
}
Err(e) => {
tracing::error!(error = %e, "Failed to get contract");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ApiError::new("DB_ERROR", "Failed to get contract")),
).into_response();
}
};
// Get repository URL from the contract's primary repository
let repo_url = match repository::list_contract_repositories(pool, request.contract_id).await {
Ok(repos) => {
// Prefer primary repo, fallback to first repo
repos.iter()
.find(|r| r.is_primary)
.or(repos.first())
.and_then(|r| r.repository_url.clone())
}
Err(e) => {
tracing::warn!(error = %e, "Failed to get contract repositories, continuing without repo URL");
None
}
};
// Supervisor can override with explicit repository_url
let repo_url = request.repository_url.clone().or(repo_url);
// Create task request
let create_req = CreateTaskRequest {
name: request.name.clone(),
description: None,
plan: request.plan.clone(),
repository_url: repo_url.clone(),
contract_id: request.contract_id,
parent_task_id: request.parent_task_id,
is_supervisor: false,
checkpoint_sha: request.checkpoint_sha.clone(),
merge_mode: Some("manual".to_string()),
priority: 0,
base_branch: None,
target_branch: None,
target_repo_path: None,
completion_action: None,
continue_from_task_id: None,
copy_files: None,
};
// Create task in DB
let task = match repository::create_task_for_owner(pool, owner_id, create_req).await {
Ok(t) => t,
Err(e) => {
tracing::error!(error = %e, "Failed to create task");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ApiError::new("DB_ERROR", "Failed to create task")),
).into_response();
}
};
tracing::info!(
supervisor_id = %supervisor_id,
task_id = %task.id,
task_name = %task.name,
"Supervisor spawned new task"
);
// Start task on a daemon
// Find a daemon that belongs to this owner
for entry in state.daemon_connections.iter() {
let daemon = entry.value();
if daemon.owner_id == owner_id {
// Send spawn command to first available daemon
let cmd = DaemonCommand::SpawnTask {
task_id: task.id,
task_name: task.name.clone(),
plan: task.plan.clone(),
repo_url: repo_url.clone(),
base_branch: task.base_branch.clone(),
target_branch: task.target_branch.clone(),
parent_task_id: task.parent_task_id,
depth: task.depth,
is_orchestrator: false,
target_repo_path: task.target_repo_path.clone(),
completion_action: task.completion_action.clone(),
continue_from_task_id: task.continue_from_task_id,
copy_files: task.copy_files.as_ref().and_then(|v| serde_json::from_value(v.clone()).ok()),
contract_id: task.contract_id,
is_supervisor: false,
};
if let Err(e) = state.send_daemon_command(daemon.id, cmd).await {
tracing::warn!(error = %e, daemon_id = %daemon.id, "Failed to send spawn command");
} else {
tracing::info!(task_id = %task.id, daemon_id = %daemon.id, repo_url = ?repo_url, "Task spawn command sent");
}
break;
}
}
(StatusCode::CREATED, Json(task)).into_response()
}
// =============================================================================
// Wait for Task Handler
// =============================================================================
/// Wait for a task to complete.
#[utoipa::path(
post,
path = "/api/v1/mesh/supervisor/tasks/{task_id}/wait",
params(
("task_id" = Uuid, Path, description = "Task ID to wait for")
),
request_body = WaitForTaskRequest,
responses(
(status = 200, description = "Task completed or timed out", body = WaitResponse),
(status = 401, description = "Unauthorized"),
(status = 403, description = "Forbidden - not a supervisor"),
(status = 404, description = "Task not found"),
(status = 500, description = "Internal server error"),
),
tag = "Mesh Supervisor"
)]
pub async fn wait_for_task(
State(state): State<SharedState>,
Path(task_id): Path<Uuid>,
headers: HeaderMap,
Json(request): Json<WaitForTaskRequest>,
) -> impl IntoResponse {
let (_supervisor_id, owner_id) = match verify_supervisor_auth(&state, &headers, None).await {
Ok(ids) => ids,
Err(e) => return e.into_response(),
};
let pool = state.db_pool.as_ref().unwrap();
// Verify task belongs to same owner
let task = match repository::get_task_for_owner(pool, task_id, owner_id).await {
Ok(Some(t)) => t,
Ok(None) => {
return (
StatusCode::NOT_FOUND,
Json(ApiError::new("NOT_FOUND", "Task not found")),
).into_response();
}
Err(e) => {
tracing::error!(error = %e, "Failed to get task");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ApiError::new("DB_ERROR", "Failed to get task")),
).into_response();
}
};
// Check if already done
if task.status == "done" || task.status == "failed" || task.status == "merged" {
return (
StatusCode::OK,
Json(WaitResponse {
task_id,
status: task.status,
completed: true,
output_summary: None,
}),
).into_response();
}
// Subscribe to task completions
let mut rx = state.task_completions.subscribe();
let timeout = tokio::time::Duration::from_secs(request.timeout_seconds as u64);
// Wait for completion or timeout
let result = tokio::time::timeout(timeout, async {
loop {
match rx.recv().await {
Ok(notification) => {
if notification.task_id == task_id {
return Some(notification);
}
}
Err(_) => {
// Channel closed or lagged - check DB directly
if let Ok(Some(t)) = repository::get_task(pool, task_id).await {
if t.status == "done" || t.status == "failed" || t.status == "merged" {
return Some(crate::server::state::TaskCompletionNotification {
task_id: t.id,
owner_id: Some(t.owner_id),
contract_id: t.contract_id,
parent_task_id: t.parent_task_id,
status: t.status,
output_summary: None,
worktree_path: None,
error_message: t.error_message,
});
}
}
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
}
}
}
}).await;
match result {
Ok(Some(notification)) => {
(
StatusCode::OK,
Json(WaitResponse {
task_id,
status: notification.status,
completed: true,
output_summary: notification.output_summary,
}),
).into_response()
}
Ok(None) | Err(_) => {
// Timeout - check final status
let final_status = repository::get_task(pool, task_id)
.await
.ok()
.flatten()
.map(|t| t.status)
.unwrap_or_else(|| "unknown".to_string());
(
StatusCode::OK,
Json(WaitResponse {
task_id,
status: final_status.clone(),
completed: final_status == "done" || final_status == "failed" || final_status == "merged",
output_summary: None,
}),
).into_response()
}
}
}
// =============================================================================
// Read Worktree File Handler
// =============================================================================
/// Read a file from a task's worktree.
#[utoipa::path(
post,
path = "/api/v1/mesh/supervisor/tasks/{task_id}/read-file",
params(
("task_id" = Uuid, Path, description = "Task ID")
),
request_body = ReadWorktreeFileRequest,
responses(
(status = 200, description = "File content", body = ReadFileResponse),
(status = 401, description = "Unauthorized"),
(status = 403, description = "Forbidden - not a supervisor"),
(status = 404, description = "Task not found"),
(status = 500, description = "Internal server error"),
),
tag = "Mesh Supervisor"
)]
pub async fn read_worktree_file(
State(state): State<SharedState>,
Path(task_id): Path<Uuid>,
headers: HeaderMap,
Json(request): Json<ReadWorktreeFileRequest>,
) -> impl IntoResponse {
let (_supervisor_id, owner_id) = match verify_supervisor_auth(&state, &headers, None).await {
Ok(ids) => ids,
Err(e) => return e.into_response(),
};
let pool = state.db_pool.as_ref().unwrap();
// Get task to verify ownership
let task = match repository::get_task_for_owner(pool, task_id, owner_id).await {
Ok(Some(t)) => t,
Ok(None) => {
return (
StatusCode::NOT_FOUND,
Json(ApiError::new("NOT_FOUND", "Task not found")),
).into_response();
}
Err(e) => {
tracing::error!(error = %e, "Failed to get task");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ApiError::new("DB_ERROR", "Failed to get task")),
).into_response();
}
};
// TODO: Implement file reading via worktree path
// For now, return not implemented - supervisor should use local file access via worktree
let _ = (task, request);
(
StatusCode::NOT_IMPLEMENTED,
Json(ApiError::new(
"NOT_IMPLEMENTED",
"Worktree file reading via API not yet implemented. Use local filesystem access via worktree path.",
)),
).into_response()
}
// =============================================================================
// Checkpoint Handlers
// =============================================================================
/// Create a git checkpoint for a task.
#[utoipa::path(
post,
path = "/api/v1/mesh/tasks/{task_id}/checkpoint",
params(
("task_id" = Uuid, Path, description = "Task ID")
),
request_body = CreateCheckpointRequest,
responses(
(status = 201, description = "Checkpoint created", body = CheckpointResponse),
(status = 401, description = "Unauthorized"),
(status = 404, description = "Task not found"),
(status = 500, description = "Internal server error"),
),
tag = "Mesh Supervisor"
)]
pub async fn create_checkpoint(
State(state): State<SharedState>,
Path(task_id): Path<Uuid>,
headers: HeaderMap,
Json(request): Json<CreateCheckpointRequest>,
) -> impl IntoResponse {
let auth = extract_auth(&state, &headers);
let task_id_from_auth = match auth {
AuthSource::ToolKey(tid) => tid,
_ => {
return (
StatusCode::UNAUTHORIZED,
Json(ApiError::new("UNAUTHORIZED", "Tool key required")),
).into_response();
}
};
// Can only create checkpoint for own task
if task_id_from_auth != task_id {
return (
StatusCode::FORBIDDEN,
Json(ApiError::new("FORBIDDEN", "Can only create checkpoint for own task")),
).into_response();
}
let pool = state.db_pool.as_ref().unwrap();
// Get task
let task = match repository::get_task(pool, task_id).await {
Ok(Some(t)) => t,
Ok(None) => {
return (
StatusCode::NOT_FOUND,
Json(ApiError::new("NOT_FOUND", "Task not found")),
).into_response();
}
Err(e) => {
tracing::error!(error = %e, "Failed to get task");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ApiError::new("DB_ERROR", "Failed to get task")),
).into_response();
}
};
// TODO: Implement checkpoint creation via daemon command
// For now, checkpoints should be created by the task itself via git commands
let _ = (task, request);
(
StatusCode::NOT_IMPLEMENTED,
Json(ApiError::new(
"NOT_IMPLEMENTED",
"Checkpoint creation via API not yet implemented. Use git commands directly in the task.",
)),
).into_response()
}
/// List checkpoints for a task.
#[utoipa::path(
get,
path = "/api/v1/mesh/tasks/{task_id}/checkpoints",
params(
("task_id" = Uuid, Path, description = "Task ID")
),
responses(
(status = 200, description = "List of checkpoints", body = CheckpointListResponse),
(status = 401, description = "Unauthorized"),
(status = 404, description = "Task not found"),
(status = 500, description = "Internal server error"),
),
tag = "Mesh Supervisor"
)]
pub async fn list_checkpoints(
State(state): State<SharedState>,
Path(task_id): Path<Uuid>,
headers: HeaderMap,
) -> impl IntoResponse {
let auth = extract_auth(&state, &headers);
let _task_id_from_auth = match auth {
AuthSource::ToolKey(tid) => tid,
_ => {
return (
StatusCode::UNAUTHORIZED,
Json(ApiError::new("UNAUTHORIZED", "Tool key required")),
).into_response();
}
};
let pool = state.db_pool.as_ref().unwrap();
// Get checkpoints from DB
match repository::list_task_checkpoints(pool, task_id).await {
Ok(checkpoints) => {
let checkpoint_list: Vec<TaskCheckpoint> = checkpoints
.into_iter()
.map(|c| TaskCheckpoint {
id: c.id,
task_id: c.task_id,
checkpoint_number: c.checkpoint_number,
commit_sha: c.commit_sha,
branch_name: c.branch_name,
message: c.message,
files_changed: c.files_changed,
lines_added: c.lines_added.unwrap_or(0),
lines_removed: c.lines_removed.unwrap_or(0),
created_at: c.created_at,
})
.collect();
(
StatusCode::OK,
Json(CheckpointListResponse {
task_id,
checkpoints: checkpoint_list,
}),
).into_response()
}
Err(e) => {
tracing::error!(error = %e, "Failed to list checkpoints");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(ApiError::new("DB_ERROR", "Failed to list checkpoints")),
).into_response()
}
}
}
// =============================================================================
// Git Operations - Request/Response Types
// =============================================================================
/// Request to create a new branch.
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreateBranchRequest {
pub branch_name: String,
pub from_ref: Option<String>,
}
/// Response for branch creation.
#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreateBranchResponse {
pub success: bool,
pub branch_name: String,
pub message: String,
}
/// Request to merge task changes.
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct MergeTaskRequest {
pub target_branch: Option<String>,
#[serde(default)]
pub squash: bool,
}
/// Response for merge operation.
#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct MergeTaskResponse {
pub task_id: Uuid,
pub success: bool,
pub message: String,
pub commit_sha: Option<String>,
pub conflicts: Option<Vec<String>>,
}
/// Request to create a pull request.
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreatePRRequest {
pub task_id: Uuid,
pub title: String,
pub body: Option<String>,
#[serde(default = "default_base_branch")]
pub base_branch: String,
}
fn default_base_branch() -> String {
"main".to_string()
}
/// Response for PR creation.
#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreatePRResponse {
pub task_id: Uuid,
pub success: bool,
pub message: String,
pub pr_url: Option<String>,
pub pr_number: Option<i32>,
}
/// Response for task diff.
#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct TaskDiffResponse {
pub task_id: Uuid,
pub success: bool,
pub diff: Option<String>,
pub error: Option<String>,
}
// =============================================================================
// Git Operations - Handlers
// =============================================================================
/// Create a new branch from supervisor's worktree.
#[utoipa::path(
post,
path = "/api/v1/mesh/supervisor/branches",
request_body = CreateBranchRequest,
responses(
(status = 201, description = "Branch created", body = CreateBranchResponse),
(status = 400, description = "Invalid request"),
(status = 401, description = "Unauthorized"),
(status = 403, description = "Forbidden - not a supervisor"),
(status = 500, description = "Internal server error"),
),
tag = "Mesh Supervisor"
)]
pub async fn create_branch(
State(state): State<SharedState>,
headers: HeaderMap,
Json(request): Json<CreateBranchRequest>,
) -> impl IntoResponse {
let (supervisor_id, owner_id) = match verify_supervisor_auth(&state, &headers, None).await {
Ok(ids) => ids,
Err(e) => return e.into_response(),
};
// Find daemon running supervisor
let daemon_id = {
let pool = state.db_pool.as_ref().unwrap();
match repository::get_task(pool, supervisor_id).await {
Ok(Some(task)) => task.daemon_id,
_ => None,
}
};
let Some(daemon_id) = daemon_id else {
return (
StatusCode::SERVICE_UNAVAILABLE,
Json(ApiError::new("NO_DAEMON", "Supervisor has no assigned daemon")),
).into_response();
};
// Send CreateBranch command to daemon
let cmd = DaemonCommand::CreateBranch {
task_id: supervisor_id,
branch_name: request.branch_name.clone(),
from_ref: request.from_ref,
};
if let Err(e) = state.send_daemon_command(daemon_id, cmd).await {
tracing::error!(error = %e, "Failed to send CreateBranch command");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ApiError::new("COMMAND_FAILED", "Failed to send command to daemon")),
).into_response();
}
// Note: Real implementation would wait for daemon response
// For now, return success immediately - daemon will send response via WebSocket
(
StatusCode::CREATED,
Json(CreateBranchResponse {
success: true,
branch_name: request.branch_name,
message: "Branch creation command sent".to_string(),
}),
).into_response()
}
/// Merge a task's changes to a target branch.
#[utoipa::path(
post,
path = "/api/v1/mesh/supervisor/tasks/{task_id}/merge",
params(
("task_id" = Uuid, Path, description = "Task ID to merge")
),
request_body = MergeTaskRequest,
responses(
(status = 200, description = "Merge initiated", body = MergeTaskResponse),
(status = 400, description = "Invalid request"),
(status = 401, description = "Unauthorized"),
(status = 403, description = "Forbidden - not a supervisor"),
(status = 404, description = "Task not found"),
(status = 500, description = "Internal server error"),
),
tag = "Mesh Supervisor"
)]
pub async fn merge_task(
State(state): State<SharedState>,
Path(task_id): Path<Uuid>,
headers: HeaderMap,
Json(request): Json<MergeTaskRequest>,
) -> impl IntoResponse {
let (_supervisor_id, owner_id) = match verify_supervisor_auth(&state, &headers, None).await {
Ok(ids) => ids,
Err(e) => return e.into_response(),
};
let pool = state.db_pool.as_ref().unwrap();
// Get the target task
let task = match repository::get_task_for_owner(pool, task_id, owner_id).await {
Ok(Some(t)) => t,
Ok(None) => {
return (
StatusCode::NOT_FOUND,
Json(ApiError::new("NOT_FOUND", "Task not found")),
).into_response();
}
Err(e) => {
tracing::error!(error = %e, "Failed to get task");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ApiError::new("DB_ERROR", "Failed to get task")),
).into_response();
}
};
// Get daemon running the task
let Some(daemon_id) = task.daemon_id else {
return (
StatusCode::SERVICE_UNAVAILABLE,
Json(ApiError::new("NO_DAEMON", "Task has no assigned daemon")),
).into_response();
};
// Send MergeTaskToTarget command to daemon
let cmd = DaemonCommand::MergeTaskToTarget {
task_id,
target_branch: request.target_branch,
squash: request.squash,
};
if let Err(e) = state.send_daemon_command(daemon_id, cmd).await {
tracing::error!(error = %e, "Failed to send MergeTaskToTarget command");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ApiError::new("COMMAND_FAILED", "Failed to send command to daemon")),
).into_response();
}
(
StatusCode::OK,
Json(MergeTaskResponse {
task_id,
success: true,
message: "Merge command sent".to_string(),
commit_sha: None,
conflicts: None,
}),
).into_response()
}
/// Create a pull request for a task's changes.
#[utoipa::path(
post,
path = "/api/v1/mesh/supervisor/pr",
request_body = CreatePRRequest,
responses(
(status = 201, description = "PR created", body = CreatePRResponse),
(status = 400, description = "Invalid request"),
(status = 401, description = "Unauthorized"),
(status = 403, description = "Forbidden - not a supervisor"),
(status = 404, description = "Task not found"),
(status = 500, description = "Internal server error"),
),
tag = "Mesh Supervisor"
)]
pub async fn create_pr(
State(state): State<SharedState>,
headers: HeaderMap,
Json(request): Json<CreatePRRequest>,
) -> impl IntoResponse {
let (_supervisor_id, owner_id) = match verify_supervisor_auth(&state, &headers, None).await {
Ok(ids) => ids,
Err(e) => return e.into_response(),
};
let pool = state.db_pool.as_ref().unwrap();
// Get the target task
let task = match repository::get_task_for_owner(pool, request.task_id, owner_id).await {
Ok(Some(t)) => t,
Ok(None) => {
return (
StatusCode::NOT_FOUND,
Json(ApiError::new("NOT_FOUND", "Task not found")),
).into_response();
}
Err(e) => {
tracing::error!(error = %e, "Failed to get task");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ApiError::new("DB_ERROR", "Failed to get task")),
).into_response();
}
};
// Get daemon running the task
let Some(daemon_id) = task.daemon_id else {
return (
StatusCode::SERVICE_UNAVAILABLE,
Json(ApiError::new("NO_DAEMON", "Task has no assigned daemon")),
).into_response();
};
// Send CreatePR command to daemon
let cmd = DaemonCommand::CreatePR {
task_id: request.task_id,
title: request.title.clone(),
body: request.body.clone(),
base_branch: request.base_branch.clone(),
};
if let Err(e) = state.send_daemon_command(daemon_id, cmd).await {
tracing::error!(error = %e, "Failed to send CreatePR command");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ApiError::new("COMMAND_FAILED", "Failed to send command to daemon")),
).into_response();
}
(
StatusCode::CREATED,
Json(CreatePRResponse {
task_id: request.task_id,
success: true,
message: "PR creation command sent".to_string(),
pr_url: None,
pr_number: None,
}),
).into_response()
}
/// Get the diff for a task's changes.
#[utoipa::path(
get,
path = "/api/v1/mesh/supervisor/tasks/{task_id}/diff",
params(
("task_id" = Uuid, Path, description = "Task ID")
),
responses(
(status = 200, description = "Task diff", body = TaskDiffResponse),
(status = 401, description = "Unauthorized"),
(status = 403, description = "Forbidden - not a supervisor"),
(status = 404, description = "Task not found"),
(status = 500, description = "Internal server error"),
),
tag = "Mesh Supervisor"
)]
pub async fn get_task_diff(
State(state): State<SharedState>,
Path(task_id): Path<Uuid>,
headers: HeaderMap,
) -> impl IntoResponse {
let (_supervisor_id, owner_id) = match verify_supervisor_auth(&state, &headers, None).await {
Ok(ids) => ids,
Err(e) => return e.into_response(),
};
let pool = state.db_pool.as_ref().unwrap();
// Get the target task
let task = match repository::get_task_for_owner(pool, task_id, owner_id).await {
Ok(Some(t)) => t,
Ok(None) => {
return (
StatusCode::NOT_FOUND,
Json(ApiError::new("NOT_FOUND", "Task not found")),
).into_response();
}
Err(e) => {
tracing::error!(error = %e, "Failed to get task");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ApiError::new("DB_ERROR", "Failed to get task")),
).into_response();
}
};
// Get daemon running the task
let Some(daemon_id) = task.daemon_id else {
return (
StatusCode::SERVICE_UNAVAILABLE,
Json(ApiError::new("NO_DAEMON", "Task has no assigned daemon")),
).into_response();
};
// Send GetTaskDiff command to daemon
let cmd = DaemonCommand::GetTaskDiff { task_id };
if let Err(e) = state.send_daemon_command(daemon_id, cmd).await {
tracing::error!(error = %e, "Failed to send GetTaskDiff command");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ApiError::new("COMMAND_FAILED", "Failed to send command to daemon")),
).into_response();
}
(
StatusCode::OK,
Json(TaskDiffResponse {
task_id,
success: true,
diff: None,
error: Some("Diff command sent - response will be streamed".to_string()),
}),
).into_response()
}
|