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
|
//! Contract API methods.
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use super::client::{ApiClient, ApiError};
use super::supervisor::JsonValue;
// Request types
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReportRequest {
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub task_id: Option<Uuid>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CompletionActionRequest {
pub lines_added: i32,
pub lines_removed: i32,
pub has_code_changes: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub task_id: Option<Uuid>,
#[serde(skip_serializing_if = "Option::is_none")]
pub files_modified: Option<Vec<String>>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateFileRequest {
pub content: String,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateFileRequest {
pub name: String,
pub content: String,
}
/// Request to update a contract.
#[derive(Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct UpdateContractRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
/// Request to create a new contract.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateContractRequest {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub contract_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub initial_phase: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub autonomous_loop: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phase_guard: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub local_only: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub auto_merge_local: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub red_team_enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub red_team_prompt: Option<String>,
}
impl ApiClient {
/// List all contracts for the authenticated user.
pub async fn list_contracts(&self) -> Result<JsonValue, ApiError> {
self.get("/api/v1/contracts").await
}
/// Create a new contract.
pub async fn create_contract(&self, req: CreateContractRequest) -> Result<JsonValue, ApiError> {
self.post("/api/v1/contracts", &req).await
}
/// Get a contract with its tasks, files, and repositories.
pub async fn get_contract(&self, contract_id: Uuid) -> Result<JsonValue, ApiError> {
self.get(&format!("/api/v1/contracts/{}", contract_id)).await
}
/// Delete a contract.
pub async fn delete_contract(&self, contract_id: Uuid) -> Result<(), ApiError> {
self.delete(&format!("/api/v1/contracts/{}", contract_id))
.await
}
/// Update a contract.
pub async fn update_contract(
&self,
contract_id: Uuid,
name: Option<String>,
description: Option<String>,
) -> Result<JsonValue, ApiError> {
let req = UpdateContractRequest { name, description };
self.put(&format!("/api/v1/contracts/{}", contract_id), &req)
.await
}
/// Get contract status.
pub async fn contract_status(&self, contract_id: Uuid) -> Result<JsonValue, ApiError> {
self.get(&format!("/api/v1/contracts/{}/daemon/status", contract_id))
.await
}
/// Get phase checklist.
pub async fn contract_checklist(&self, contract_id: Uuid) -> Result<JsonValue, ApiError> {
self.get(&format!("/api/v1/contracts/{}/daemon/checklist", contract_id))
.await
}
/// Get contract goals.
pub async fn contract_goals(&self, contract_id: Uuid) -> Result<JsonValue, ApiError> {
self.get(&format!("/api/v1/contracts/{}/daemon/goals", contract_id))
.await
}
/// List contract files.
pub async fn contract_files(&self, contract_id: Uuid) -> Result<JsonValue, ApiError> {
self.get(&format!("/api/v1/contracts/{}/daemon/files", contract_id))
.await
}
/// Get a specific file.
pub async fn contract_file(
&self,
contract_id: Uuid,
file_id: Uuid,
) -> Result<JsonValue, ApiError> {
self.get(&format!(
"/api/v1/contracts/{}/daemon/files/{}",
contract_id, file_id
))
.await
}
/// Report progress.
pub async fn contract_report(
&self,
contract_id: Uuid,
message: &str,
task_id: Option<Uuid>,
) -> Result<JsonValue, ApiError> {
let req = ReportRequest {
message: message.to_string(),
task_id,
};
self.post(&format!("/api/v1/contracts/{}/daemon/report", contract_id), &req)
.await
}
/// Get suggested action.
pub async fn contract_suggest_action(&self, contract_id: Uuid) -> Result<JsonValue, ApiError> {
self.post_empty(&format!(
"/api/v1/contracts/{}/daemon/suggest-action",
contract_id
))
.await
}
/// Get completion action recommendation.
pub async fn contract_completion_action(
&self,
contract_id: Uuid,
task_id: Option<Uuid>,
files_modified: Option<Vec<String>>,
lines_added: i32,
lines_removed: i32,
has_code_changes: bool,
) -> Result<JsonValue, ApiError> {
let req = CompletionActionRequest {
task_id,
files_modified,
lines_added,
lines_removed,
has_code_changes,
};
self.post(
&format!("/api/v1/contracts/{}/daemon/completion-action", contract_id),
&req,
)
.await
}
/// Update a file.
pub async fn contract_update_file(
&self,
contract_id: Uuid,
file_id: Uuid,
content: &str,
) -> Result<JsonValue, ApiError> {
let req = UpdateFileRequest {
content: content.to_string(),
};
self.put(
&format!("/api/v1/contracts/{}/daemon/files/{}", contract_id, file_id),
&req,
)
.await
}
/// Create a new file.
pub async fn contract_create_file(
&self,
contract_id: Uuid,
name: &str,
content: &str,
) -> Result<JsonValue, ApiError> {
let req = CreateFileRequest {
name: name.to_string(),
content: content.to_string(),
};
self.post(&format!("/api/v1/contracts/{}/daemon/files", contract_id), &req)
.await
}
/// Get task output history.
pub async fn get_task_output(&self, task_id: Uuid) -> Result<JsonValue, ApiError> {
self.get(&format!("/api/v1/mesh/tasks/{}/output", task_id))
.await
}
/// Get repository suggestions for autocomplete.
/// Returns recently used repositories sorted by usage frequency and recency.
pub async fn get_repository_suggestions(
&self,
source_type: Option<&str>,
limit: Option<i32>,
) -> Result<JsonValue, ApiError> {
let mut params = Vec::new();
if let Some(st) = source_type {
params.push(format!("source_type={}", st));
}
if let Some(l) = limit {
params.push(format!("limit={}", l));
}
let query_string = if params.is_empty() {
String::new()
} else {
format!("?{}", params.join("&"))
};
self.get(&format!("/api/v1/settings/repository-history/suggestions{}", query_string))
.await
}
/// Add a remote repository to a contract.
pub async fn add_remote_repository(
&self,
contract_id: Uuid,
name: &str,
repository_url: &str,
is_primary: bool,
) -> Result<JsonValue, ApiError> {
let req = AddRemoteRepositoryRequest {
name: name.to_string(),
repository_url: repository_url.to_string(),
is_primary,
};
self.post(&format!("/api/v1/contracts/{}/repositories/remote", contract_id), &req)
.await
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct AddRemoteRepositoryRequest {
name: String,
repository_url: String,
is_primary: bool,
}
// ============================================================================
// Contracts cleanup types
// ============================================================================
/// Request for batch contract operations (cleanup, archive, etc.).
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BatchOperationRequest {
/// The operation to perform: "archive", "delete_archived", "cleanup_worktrees"
pub operation: String,
/// Age threshold in seconds (for archive and delete operations)
#[serde(skip_serializing_if = "Option::is_none")]
pub older_than_seconds: Option<u64>,
/// Status filter for the operation
#[serde(skip_serializing_if = "Option::is_none")]
pub status_filter: Option<Vec<String>>,
/// If true, only show what would be affected without making changes
#[serde(skip_serializing_if = "Option::is_none")]
pub dry_run: Option<bool>,
}
/// Response from a batch operation.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BatchOperationResponse {
/// The operation that was performed
pub operation: String,
/// Number of items affected
pub affected_count: usize,
/// IDs of affected items
#[serde(default)]
pub affected_ids: Vec<Uuid>,
/// Any errors that occurred
#[serde(default)]
pub errors: Vec<String>,
/// Whether this was a dry run
#[serde(default)]
pub dry_run: bool,
}
/// Summary of contracts that would be affected by cleanup.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CleanupPreviewResponse {
/// Contracts that would be archived
#[serde(default)]
pub to_archive: Vec<ContractSummary>,
/// Archived contracts that would be deleted
#[serde(default)]
pub to_delete: Vec<ContractSummary>,
/// Orphaned worktrees that would be cleaned up
#[serde(default)]
pub orphaned_worktrees: Vec<String>,
}
/// Brief summary of a contract for cleanup operations.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ContractSummary {
pub id: Uuid,
pub name: String,
pub status: String,
#[serde(default)]
pub updated_at: Option<String>,
}
impl ApiClient {
// ========================================================================
// Contracts cleanup operations
// ========================================================================
/// Preview cleanup operations (dry run).
/// Returns what would be affected by archive, delete, and worktree cleanup.
pub async fn cleanup_preview(
&self,
older_than_seconds: u64,
archive: bool,
delete_archived: bool,
worktrees: bool,
) -> Result<CleanupPreviewResponse, ApiError> {
let mut params = vec![
format!("older_than_seconds={}", older_than_seconds),
"dry_run=true".to_string(),
];
if archive {
params.push("archive=true".to_string());
}
if delete_archived {
params.push("delete_archived=true".to_string());
}
if worktrees {
params.push("worktrees=true".to_string());
}
let query = params.join("&");
let result: JsonValue = self.get(&format!("/api/v1/contracts/cleanup?{}", query)).await?;
serde_json::from_value(result.0)
.map_err(|e| ApiError::Parse(format!("Failed to parse cleanup preview: {}", e)))
}
/// Archive completed/failed contracts older than the threshold.
pub async fn archive_contracts(
&self,
older_than_seconds: u64,
dry_run: bool,
) -> Result<BatchOperationResponse, ApiError> {
let req = BatchOperationRequest {
operation: "archive".to_string(),
older_than_seconds: Some(older_than_seconds),
status_filter: Some(vec!["completed".to_string(), "failed".to_string()]),
dry_run: Some(dry_run),
};
let result: JsonValue = self.post("/api/v1/contracts/batch", &req).await?;
serde_json::from_value(result.0)
.map_err(|e| ApiError::Parse(format!("Failed to parse archive response: {}", e)))
}
/// Delete archived contracts older than the threshold.
pub async fn delete_archived_contracts(
&self,
older_than_seconds: u64,
dry_run: bool,
) -> Result<BatchOperationResponse, ApiError> {
let req = BatchOperationRequest {
operation: "delete_archived".to_string(),
older_than_seconds: Some(older_than_seconds),
status_filter: Some(vec!["archived".to_string()]),
dry_run: Some(dry_run),
};
let result: JsonValue = self.post("/api/v1/contracts/batch", &req).await?;
serde_json::from_value(result.0)
.map_err(|e| ApiError::Parse(format!("Failed to parse delete response: {}", e)))
}
/// Clean up orphaned worktrees.
pub async fn cleanup_worktrees(&self, dry_run: bool) -> Result<BatchOperationResponse, ApiError> {
let req = BatchOperationRequest {
operation: "cleanup_worktrees".to_string(),
older_than_seconds: None,
status_filter: None,
dry_run: Some(dry_run),
};
let result: JsonValue = self.post("/api/v1/contracts/batch", &req).await?;
serde_json::from_value(result.0)
.map_err(|e| ApiError::Parse(format!("Failed to parse worktree cleanup response: {}", e)))
}
/// List contracts with filtering options.
pub async fn list_contracts_filtered(
&self,
status: Option<&str>,
phase: Option<&str>,
stale: bool,
stale_threshold_seconds: Option<u64>,
) -> Result<JsonValue, ApiError> {
let mut params = Vec::new();
if let Some(s) = status {
params.push(format!("status={}", s));
}
if let Some(p) = phase {
params.push(format!("phase={}", p));
}
if stale {
params.push("stale=true".to_string());
if let Some(threshold) = stale_threshold_seconds {
params.push(format!("stale_threshold={}", threshold));
}
}
let query_string = if params.is_empty() {
String::new()
} else {
format!("?{}", params.join("&"))
};
self.get(&format!("/api/v1/contracts{}", query_string)).await
}
}
|