-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgithub_ops.rs
More file actions
3038 lines (2696 loc) · 110 KB
/
Copy pathgithub_ops.rs
File metadata and controls
3038 lines (2696 loc) · 110 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
//! GitHub connector - operation tools: issue, PR, review, list repos, etc.
//!
//! These tools are part of the GitHub connector. They call the GitHub REST API
//! directly using the OAuth token stored in the local SQLite database.
//! No backend proxy required for these operations.
//!
//! Token is loaded from `config.db_path` on each execute call.
use super::traits::{Tool, ToolResult};
use crate::config::ZerobuildConfig;
use crate::store;
use async_trait::async_trait;
use serde_json::json;
use std::path::PathBuf;
use std::sync::Arc;
const GITHUB_API_BASE: &str = "https://api.github.com";
// ── Issue/PR Format Constants ──────────────────────────────────────────────────
/// Valid issue title prefixes (bracketed format)
const VALID_ISSUE_PREFIXES: &[&str] = &[
"[Feature]:",
"[Bug]:",
"[Chore]:",
"[Docs]:",
"[Security]:",
"[Refactor]:",
"[Test]:",
"[Perf]:",
];
/// Valid type labels that must be present on every issue/PR
const VALID_TYPE_LABELS: &[&str] = &[
"feature", "bug", "chore", "docs", "security", "refactor", "test", "perf",
];
/// Required sections for issue body
const REQUIRED_ISSUE_SECTIONS: &[&str] = &[
"## Summary",
"## Problem Statement",
"## Proposed Solution",
"## Non-goals / Out of Scope",
"## Acceptance Criteria",
"## Architecture Impact",
"## Risk and Rollback",
"## Breaking Change",
"## Data Hygiene Checks",
];
/// Required sections for PR body
const REQUIRED_PR_SECTIONS: &[&str] = &[
"## Summary",
"## Problem",
"## Root Cause",
"## Changes",
"## Validation",
"## Scope",
"## Risk",
"## Rollback",
];
/// Validates that an issue title follows the bracketed prefix format
fn validate_issue_title(title: &str) -> Result<(), String> {
if title.trim().is_empty() {
return Err("Issue title is required".to_string());
}
let has_valid_prefix = VALID_ISSUE_PREFIXES
.iter()
.any(|prefix| title.trim().starts_with(prefix));
if !has_valid_prefix {
return Err(format!(
"Issue title must start with a bracketed type prefix. Valid prefixes: {}. \
Example: '[Feature]: Add user authentication'",
VALID_ISSUE_PREFIXES.join(", ")
));
}
Ok(())
}
/// Validates that at least one type label is present
fn validate_labels(labels: &[String]) -> Result<(), String> {
if labels.is_empty() {
return Err(
"At least one label is required. Must include a type label: \
feature, bug, chore, docs, security, refactor, test, or perf"
.to_string(),
);
}
let has_type_label = labels
.iter()
.any(|label| VALID_TYPE_LABELS.contains(&label.as_str()));
if !has_type_label {
return Err(format!(
"Must include at least one type label: {}",
VALID_TYPE_LABELS.join(", ")
));
}
Ok(())
}
/// Sanitizes labels to only include valid type labels and known scope labels.
/// Removes labels with spaces (like "help wanted") that cause 422 errors.
fn sanitize_labels(labels: &[String]) -> Vec<String> {
// Known valid scope labels that don't contain spaces
const VALID_SCOPE_LABELS: &[&str] = &[
"provider",
"channel",
"tool",
"gateway",
"memory",
"runtime",
"config",
"ci",
"performance",
"ui",
"api",
"database",
"deps",
];
labels
.iter()
.filter(|label| {
let label_lower = label.to_lowercase();
// Keep type labels
if VALID_TYPE_LABELS.contains(&label_lower.as_str()) {
return true;
}
// Keep known scope labels
if VALID_SCOPE_LABELS.contains(&label_lower.as_str()) {
return true;
}
// Skip labels with spaces (cause 422 errors if not pre-created in repo)
if label.contains(' ') {
tracing::warn!(label = %label, "Skipping label with space - may not exist in repository");
return false;
}
// Keep other labels that don't have spaces (might work if they exist)
true
})
.cloned()
.collect()
}
/// Validates that PR title follows conventional commit format
fn validate_pr_title(title: &str) -> Result<(), String> {
if title.trim().is_empty() {
return Err("PR title is required".to_string());
}
// Conventional commit pattern: type(scope): description
let conventional_pattern = regex::Regex::new(
r"^(feat|fix|chore|docs|style|refactor|perf|test|build|ci|revert)(\([^)]+\))?: .+",
)
.unwrap();
if !conventional_pattern.is_match(title.trim()) {
return Err(
"PR title must follow conventional commit format: 'type(scope): description'. \
Valid types: feat, fix, chore, docs, style, refactor, perf, test, build, ci, revert. \
Example: 'feat(auth): add OAuth2 token refresh'"
.to_string(),
);
}
Ok(())
}
/// Checks if body contains required sections (returns missing sections)
fn check_required_sections(body: &str, required: &[&str]) -> Vec<String> {
required
.iter()
.filter(|section| !body.contains(**section))
.map(|s| s.to_string())
.collect()
}
/// Extract a summary from the title by removing the prefix
fn extract_summary_from_title(title: &str) -> String {
// Remove bracketed prefix like "[Feature]:" or "[Bug]:"
let re = regex::Regex::new(r"^\[[^\]]+\]:\s*").unwrap();
re.replace(title, "").to_string()
}
/// Generates a full issue template from a brief summary
fn generate_issue_template(title: &str, summary: &str) -> String {
format!(
r#"## Summary
{}
## Problem Statement
[Describe the current behavior, gap, or pain point. For bugs: include exact reproduction steps and error messages.]
## Proposed Solution
[For features: what the new behavior should look like. For bugs: what correct behavior looks like.]
## Non-goals / Out of Scope
- [Explicitly list what this issue will NOT address.]
## Alternatives Considered
- [Alternatives evaluated and why they were not chosen.]
## Acceptance Criteria
- [ ] [Concrete, testable condition 1]
- [ ] [Concrete, testable condition 2]
## Architecture Impact
- Affected subsystems: [list modules, traits, tools, or channels impacted]
- New dependencies: [none or list]
- Config/schema changes: [yes/no — if yes, describe]
## Risk and Rollback
- Risk: [low / medium / high — and why]
- Rollback: [how to revert if the fix or feature causes a regression]
## Breaking Change?
- [ ] Yes — describe impact and migration path
- [ ] No
## Data Hygiene Checks
- [ ] I removed personal/sensitive data from examples, payloads, and logs.
- [ ] I used neutral, project-focused wording and placeholders.
"#,
summary.trim()
)
}
/// Generates a full PR template from a brief summary
fn generate_pr_template(title: &str, summary: &str) -> String {
format!(
r#"## Summary
{}
## Problem
[What broken/missing behavior or gap does this PR address?]
## Root Cause
[For bug fixes: what was the underlying cause? For features: what need or gap drove this?]
## Changes
- [Concrete change 1 — module / file / behavior]
- [Concrete change 2]
## Validation
- [ ] `cargo fmt --all -- --check` passed
- [ ] `cargo clippy --all-targets -- -D warnings` passed
- [ ] `cargo test` passed
- [ ] Manual test / scenario: [describe]
## Scope
- Affected subsystems: [list]
- Files changed: [count or list key files]
## Risk
- Risk tier: [low / medium / high]
- Blast radius: [which subsystems or users could be affected by a regression]
## Rollback
- Revert strategy: [`git revert <commit>` or specific steps]
- Migration needed on rollback: [yes / no — if yes, describe]
"#,
summary.trim()
)
}
// ── Shared helpers ─────────────────────────────────────────────────────────────
/// Extract owner and repo from various input formats:
/// - "owner/repo" (e.g., "potlock/zerobuild")
/// - "https://github.com/owner/repo"
/// - "github.com/owner/repo"
/// Returns (owner, repo) or None if parsing fails
fn extract_owner_repo_from_input(input: &str) -> Option<(String, String)> {
if input.is_empty() {
return None;
}
// Handle full URL format: https://github.com/owner/repo
if input.contains("github.com/") {
let parts: Vec<&str> = input.split("github.com/").collect();
if parts.len() >= 2 {
let path = parts[1].trim_end_matches('/');
let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
if segments.len() >= 2 {
return Some((segments[0].to_string(), segments[1].to_string()));
}
}
}
// Handle "owner/repo" format
if input.contains('/') {
let segments: Vec<&str> = input.split('/').filter(|s| !s.is_empty()).collect();
if segments.len() >= 2 {
return Some((segments[0].to_string(), segments[1].to_string()));
}
}
None
}
/// Load the GitHub token from the local store.
fn load_token(db_path: &PathBuf) -> Result<crate::store::tokens::GitHubToken, ToolResult> {
let conn = store::init_db(db_path).map_err(|e| ToolResult {
success: false,
output: String::new(),
error: Some(format!("Failed to open store DB: {e}")),
error_hint: None,
})?;
match store::tokens::load_github_token(&conn) {
Ok(Some(tok)) => Ok(tok),
Ok(None) => Err(ToolResult {
success: false,
output: String::new(),
error: Some(
"GitHub is not connected. Use github_connect to authenticate first.".to_string(),
),
error_hint: None,
}),
Err(e) => Err(ToolResult {
success: false,
output: String::new(),
error: Some(format!("Failed to load GitHub token: {e}")),
error_hint: None,
}),
}
}
/// Build a pre-configured reqwest client for GitHub API calls.
fn gh_client() -> anyhow::Result<reqwest::Client> {
reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.user_agent("ZeroBuild/0.1")
.build()
.map_err(|e| anyhow::anyhow!("Failed to build HTTP client: {e}"))
}
/// GET a GitHub API endpoint and return the response body as ToolResult.
async fn github_get(token: &str, url: &str) -> anyhow::Result<ToolResult> {
let client = gh_client()?;
let resp = client
.get(url)
.header("Authorization", format!("Bearer {token}"))
.header("Accept", "application/vnd.github+json")
.send()
.await
.map_err(|e| anyhow::anyhow!("GitHub API request failed: {e}"))?;
let status = resp.status();
let body = resp
.text()
.await
.unwrap_or_else(|_| "<unreadable>".to_string());
if !status.is_success() {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some(format!("GitHub API returned {status}: {body}")),
error_hint: None,
});
}
Ok(ToolResult {
success: true,
output: body,
error: None,
error_hint: None,
})
}
/// POST to a GitHub API endpoint and return the response body as ToolResult.
async fn github_post_api(
token: &str,
url: &str,
body: serde_json::Value,
) -> anyhow::Result<ToolResult> {
let client = gh_client()?;
let resp = client
.post(url)
.header("Authorization", format!("Bearer {token}"))
.header("Accept", "application/vnd.github+json")
.json(&body)
.send()
.await
.map_err(|e| anyhow::anyhow!("GitHub API request failed: {e}"))?;
let status = resp.status();
let resp_body = resp
.text()
.await
.unwrap_or_else(|_| "<unreadable>".to_string());
if !status.is_success() {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some(format!("GitHub API returned {status}: {resp_body}")),
error_hint: None,
});
}
Ok(ToolResult {
success: true,
output: resp_body,
error: None,
error_hint: None,
})
}
/// PATCH a GitHub API endpoint and return the response body as ToolResult.
async fn github_patch_api(
token: &str,
url: &str,
body: serde_json::Value,
) -> anyhow::Result<ToolResult> {
let client = gh_client()?;
let resp = client
.patch(url)
.header("Authorization", format!("Bearer {token}"))
.header("Accept", "application/vnd.github+json")
.json(&body)
.send()
.await
.map_err(|e| anyhow::anyhow!("GitHub API request failed: {e}"))?;
let status = resp.status();
let resp_body = resp
.text()
.await
.unwrap_or_else(|_| "<unreadable>".to_string());
if !status.is_success() {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some(format!("GitHub API returned {status}: {resp_body}")),
error_hint: None,
});
}
Ok(ToolResult {
success: true,
output: resp_body,
error: None,
error_hint: None,
})
}
/// Resolve the `owner` field: use provided value or fall back to stored username.
fn resolve_owner(
args: &serde_json::Value,
stored_username: Option<&str>,
) -> Result<String, ToolResult> {
if let Some(o) = args["owner"].as_str().filter(|s| !s.is_empty()) {
return Ok(o.to_string());
}
stored_username
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.ok_or_else(|| ToolResult {
success: false,
output: String::new(),
error: Some(
"owner is required (or will be inferred from the authenticated user). \
Try reconnecting GitHub via github_connect."
.to_string(),
),
error_hint: None,
})
}
// ── Helper: Extract hashtags from text ────────────────────────────────────────
fn extract_hashtags(text: &str) -> Vec<String> {
let mut hashtags = Vec::new();
for word in text.split_whitespace() {
if word.starts_with('#') && word.len() > 1 {
let tag = word[1..]
.trim_matches(|c: char| c.is_ascii_punctuation())
.to_lowercase();
if !tag.is_empty() && !hashtags.contains(&tag) {
hashtags.push(tag);
}
}
}
hashtags
}
// ── github_create_issue ────────────────────────────────────────────────────────
pub struct GitHubCreateIssueTool {
config: Arc<ZerobuildConfig>,
}
impl GitHubCreateIssueTool {
pub fn new(config: Arc<ZerobuildConfig>) -> Self {
Self { config }
}
}
#[async_trait]
impl Tool for GitHubCreateIssueTool {
fn name(&self) -> &str {
"github_create_issue"
}
fn description(&self) -> &str {
"CREATE A GITHUB ISSUE - Use this when user says '#issue', '#bug', 'create issue', or wants to report a bug/request a feature. \
\
WORKFLOW (MUST FOLLOW): \
1. First call with confirm:false → Shows preview to user, STOPS and waits for user response \
2. After user says 'create it' or 'confirm', call again with confirm:true → Actually creates the issue \
\
TRIGGER PHRASES: '#issue', '#bug', '#feature', 'create issue', 'file issue', 'report bug'. \
\
REQUIRED FORMAT (ENFORCED): \
- Title MUST start with bracketed prefix: [Feature]:, [Bug]:, [Chore]:, [Docs]:, [Security]:, [Refactor]:, [Test]:, or [Perf]: \
- At least one type label is REQUIRED (feature, bug, chore, docs, security, refactor, test, perf) \
- Body should follow the standard template with sections: Summary, Problem Statement, Proposed Solution, etc. \
\
DO NOT use this for file searches or reading code - use file_read or glob_search instead. \
All content MUST be in English. \
The user must have connected their GitHub account first."
}
fn parameters_schema(&self) -> serde_json::Value {
json!({
"type": "object",
"properties": {
"repo": {
"type": "string",
"description": "Repository name (e.g. my-app)"
},
"owner": {
"type": "string",
"description": "Repository owner (GitHub username or org). Defaults to the authenticated user."
},
"title": {
"type": "string",
"description": "Issue title. MUST use format: [Feature]: ..., [Bug]: ..., [Chore]: ..., [Docs]: ..., [Security]: ..., [Refactor]: ..., [Test]: ..., [Perf]: ..."
},
"body": {
"type": "string",
"description": "Issue body (Markdown). Should include: ## Summary, ## Problem Statement, ## Proposed Solution, ## Non-goals / Out of Scope, ## Acceptance Criteria, ## Architecture Impact, ## Risk and Rollback, ## Breaking Change, ## Data Hygiene Checks. If not provided, a template will be generated for you."
},
"labels": {
"type": "array",
"items": { "type": "string" },
"description": "REQUIRED: At least one type label. Valid: feature, bug, chore, docs, security, refactor, test, perf"
},
"confirm": {
"type": "boolean",
"description": "REQUIRED: Set to false first to preview the issue. After user approves the preview, call again with confirm: true to actually create the issue."
}
},
"required": ["repo", "title", "labels", "confirm"]
})
}
async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
let db_path = PathBuf::from(&self.config.db_path);
let tok = match load_token(&db_path) {
Ok(t) => t,
Err(e) => return Ok(e),
};
let repo_input = args["repo"].as_str().unwrap_or("").trim().to_string();
let title = args["title"].as_str().unwrap_or("").trim().to_string();
// Validate title format
if let Err(e) = validate_issue_title(&title) {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some(e),
error_hint: Some(format!(
"Valid prefixes: {}. Example: '[Feature]: Add dark mode toggle'",
VALID_ISSUE_PREFIXES.join(", ")
)),
});
}
if repo_input.is_empty() {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("repo is required".to_string()),
error_hint: Some(
"Provide repo as: 'owner/repo' or 'https://github.com/owner/repo'".to_string(),
),
});
}
// Extract owner and repo from input (handles "owner/repo" or URL formats)
let (owner_from_repo, repo) = match extract_owner_repo_from_input(&repo_input) {
Some((o, r)) => (Some(o), r),
None => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some(format!("Could not parse owner/repo from: '{}'", repo_input)),
error_hint: Some(
"Use format: 'owner/repo' or 'https://github.com/owner/repo'".to_string(),
),
});
}
};
// Extract and validate labels
let labels: Vec<String> = args["labels"]
.as_array()
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect()
})
.unwrap_or_default();
if let Err(e) = validate_labels(&labels) {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some(e),
error_hint: Some(format!(
"Required type labels: {}. You may also add scope labels like: provider, channel, tool, gateway, memory, runtime, config, ci",
VALID_TYPE_LABELS.join(", ")
)),
});
}
// Sanitize labels to remove problematic ones (e.g., "help wanted" with spaces)
let labels = sanitize_labels(&labels);
// Resolve owner: explicit args > parsed from repo > stored username
let owner = if let Some(o) = args["owner"].as_str().filter(|s| !s.is_empty()) {
o.to_string()
} else if let Some(o) = owner_from_repo {
o
} else {
match tok.username.as_deref().filter(|s| !s.is_empty()) {
Some(u) => u.to_string(),
None => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("owner is required (could not determine from repo or authenticated user)".to_string()),
error_hint: Some("Provide owner explicitly or use format: 'owner/repo'".to_string()),
});
}
}
};
// Get body - auto-generate template if missing or insufficient
let body_content = args["body"].as_str().unwrap_or("").trim().to_string();
let final_body = if body_content.is_empty()
|| check_required_sections(&body_content, REQUIRED_ISSUE_SECTIONS).len() > 5
{
// Auto-generate template from title/summary
let summary = extract_summary_from_title(&title);
generate_issue_template(&title, &summary)
} else {
body_content
};
// Check if user confirmed
let confirmed = args["confirm"].as_bool().unwrap_or(false);
if !confirmed {
// Return preview for user approval
let labels_str = labels.join(", ");
let preview = format!(
"📋 ISSUE PREVIEW — Please review before creating\n\
═══════════════════════════════════════════\n\n\
**Repository:** {}/{}\n\
**Title:** {}\n\
**Labels:** {}\n\n\
**Body:**\n\
```markdown\n{}\n```\n\n\
─────────────────────────────────────────────\n\n\
⏳ WAITING FOR YOUR CONFIRMATION\n\n\
Reply \"create it\" or \"confirm\" to CREATE this issue\n\
Reply with corrections to EDIT the information\n\
Reply \"cancel\" to ABORT",
owner, repo, title, labels_str, final_body
);
// Return as error to stop agent loop - user must explicitly confirm
return Ok(ToolResult {
success: false,
output: preview,
error: Some("⏳ PREVIEW MODE — Issue not created yet. Waiting for user confirmation. DO NOT auto-confirm. Ask the user to review and respond.".to_string()),
error_hint: Some("User must explicitly say 'create it' or 'confirm' before proceeding. Do NOT call this tool again with confirm:true until user responds.".to_string()),
});
}
// User confirmed - create the issue
let url = format!("{GITHUB_API_BASE}/repos/{owner}/{repo}/issues");
let mut body = json!({ "title": title, "body": final_body });
if !labels.is_empty() {
body["labels"] = json!(labels);
}
let result = github_post_api(&tok.token, &url, body).await?;
if !result.success {
return Ok(result);
}
let parsed: serde_json::Value = serde_json::from_str(&result.output).unwrap_or_default();
let issue_url = parsed["html_url"].as_str().unwrap_or("");
let issue_num = parsed["number"].as_u64().unwrap_or(0);
Ok(ToolResult {
success: true,
output: format!("✅ Issue #{issue_num} created: {issue_url}"),
error: None,
error_hint: None,
})
}
}
// ── github_create_pr ──────────────────────────────────────────────────────────
pub struct GitHubCreatePRTool {
config: Arc<ZerobuildConfig>,
}
impl GitHubCreatePRTool {
pub fn new(config: Arc<ZerobuildConfig>) -> Self {
Self { config }
}
}
#[async_trait]
impl Tool for GitHubCreatePRTool {
fn name(&self) -> &str {
"github_create_pr"
}
fn description(&self) -> &str {
"CREATE A GITHUB PULL REQUEST - Use this when user says '#pr', '#pullrequest', 'create PR', or wants to submit code for review. \
\
WORKFLOW (MUST FOLLOW): \
1. First call with confirm:false → Shows preview to user, STOPS and waits for user response \
2. After user says 'create it' or 'confirm', call again with confirm:true → Actually creates the PR \
\
TRIGGER PHRASES: '#pr', '#pullrequest', 'create PR', 'open PR', 'submit PR', 'make pull request'. \
\
REQUIRED FORMAT (ENFORCED): \
- Title MUST follow conventional commit format: 'type(scope): description' \
Valid types: feat, fix, chore, docs, style, refactor, perf, test, build, ci, revert \
Example: 'feat(auth): add OAuth2 token refresh' \
- At least one type label is REQUIRED (feature, bug, chore, docs, security, refactor, test, perf) \
- Body should follow the standard template with sections: Summary, Problem, Root Cause, Changes, Validation, Scope, Risk, Rollback \
\
DO NOT use this for creating issues or general queries. \
All content MUST be in English. \
The user must have connected their GitHub account first."
}
fn parameters_schema(&self) -> serde_json::Value {
json!({
"type": "object",
"properties": {
"repo": { "type": "string", "description": "Repository name" },
"owner": { "type": "string", "description": "Repository owner. Defaults to authenticated user." },
"title": { "type": "string", "description": "Pull request title. MUST use conventional commit format: 'type(scope): description'. Valid types: feat, fix, chore, docs, style, refactor, perf, test, build, ci, revert" },
"body": { "type": "string", "description": "Pull request description (Markdown). Should include: ## Summary, ## Problem, ## Root Cause, ## Changes, ## Validation, ## Scope, ## Risk, ## Rollback" },
"head": { "type": "string", "description": "Branch to merge from" },
"base": { "type": "string", "description": "Branch to merge into. Default: main." },
"labels": {
"type": "array",
"items": { "type": "string" },
"description": "REQUIRED: At least one type label. Valid: feature, bug, chore, docs, security, refactor, test, perf. Also recommended: size labels (size: XS/S/M/L/XL)"
},
"confirm": {
"type": "boolean",
"description": "REQUIRED: Set to false first to preview the PR. After user approves the preview, call again with confirm: true to actually create the PR."
}
},
"required": ["repo", "title", "head", "labels", "confirm"]
})
}
async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
let db_path = PathBuf::from(&self.config.db_path);
let tok = match load_token(&db_path) {
Ok(t) => t,
Err(e) => return Ok(e),
};
let repo_input = args["repo"].as_str().unwrap_or("").trim().to_string();
let title = args["title"].as_str().unwrap_or("").trim().to_string();
let head = args["head"].as_str().unwrap_or("").trim().to_string();
// Validate PR title format (conventional commits)
if let Err(e) = validate_pr_title(&title) {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some(e),
error_hint: Some(
"Use format: 'type(scope): description'. \
Valid types: feat, fix, chore, docs, style, refactor, perf, test, build, ci, revert. \
Examples: 'feat(auth): add OAuth flow', 'fix(api): resolve null pointer'".to_string()
),
});
}
if repo_input.is_empty() || head.is_empty() {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("repo and head are required".to_string()),
error_hint: Some(
"Provide repo as: 'owner/repo' or 'https://github.com/owner/repo'".to_string(),
),
});
}
// Extract owner and repo from input (handles "owner/repo" or URL formats)
let (owner_from_repo, repo) = match extract_owner_repo_from_input(&repo_input) {
Some((o, r)) => (Some(o), r),
None => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some(format!("Could not parse owner/repo from: '{}'", repo_input)),
error_hint: Some(
"Use format: 'owner/repo' or 'https://github.com/owner/repo'".to_string(),
),
});
}
};
// Extract and validate labels
let labels: Vec<String> = args["labels"]
.as_array()
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect()
})
.unwrap_or_default();
if let Err(e) = validate_labels(&labels) {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some(e),
error_hint: Some(format!(
"Required type labels: {}. \
Also recommended: size labels (size: XS, size: S, size: M, size: L, size: XL)",
VALID_TYPE_LABELS.join(", ")
)),
});
}
// Sanitize labels to remove problematic ones (e.g., "help wanted" with spaces)
let labels = sanitize_labels(&labels);
// Resolve owner: explicit args > parsed from repo > stored username
let owner = if let Some(o) = args["owner"].as_str().filter(|s| !s.is_empty()) {
o.to_string()
} else if let Some(o) = owner_from_repo {
o
} else {
match tok.username.as_deref().filter(|s| !s.is_empty()) {
Some(u) => u.to_string(),
None => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("owner is required (could not determine from repo or authenticated user)".to_string()),
error_hint: Some("Provide owner explicitly or use format: 'owner/repo'".to_string()),
});
}
}
};
let base = args["base"].as_str().unwrap_or("main").to_string();
// Get body - auto-generate template if missing or insufficient
let body_content = args["body"].as_str().unwrap_or("").trim().to_string();
let final_body = if body_content.is_empty()
|| check_required_sections(&body_content, REQUIRED_PR_SECTIONS).len() > 5
{
// Auto-generate template from title/summary
let summary = extract_summary_from_title(&title);
generate_pr_template(&title, &summary)
} else {
body_content
};
// Check if user confirmed
let confirmed = args["confirm"].as_bool().unwrap_or(false);
if !confirmed {
// Return preview for user approval
let labels_str = labels.join(", ");
let preview = format!(
"📋 PULL REQUEST PREVIEW — Please review before creating\n\
═══════════════════════════════════════════════\n\n\
**Repository:** {}/{}\n\
**Title:** {}\n\
**Branch:** {} → {}\n\
**Labels:** {}\n\n\
**Body:**\n\
```markdown\n{}\n```\n\n\
─────────────────────────────────────────────\n\n\
⏳ WAITING FOR YOUR CONFIRMATION\n\n\
Reply \"create it\" or \"confirm\" to CREATE this PR\n\
Reply with corrections to EDIT the information\n\
Reply \"cancel\" to ABORT",
owner, repo, title, head, base, labels_str, final_body
);
// Return as error to stop agent loop - user must explicitly confirm
return Ok(ToolResult {
success: false,
output: preview,
error: Some("⏳ PREVIEW MODE — Pull Request not created yet. Waiting for user confirmation. DO NOT auto-confirm. Ask the user to review and respond.".to_string()),
error_hint: Some("User must explicitly say 'create it' or 'confirm' before proceeding. Do NOT call this tool again with confirm:true until user responds.".to_string()),
});
}
// User confirmed - create the PR
let url = format!("{GITHUB_API_BASE}/repos/{owner}/{repo}/pulls");
let mut body = json!({ "title": title, "head": head, "base": base, "body": final_body });
let result = github_post_api(&tok.token, &url, body).await?;
if !result.success {
return Ok(result);
}
let parsed: serde_json::Value = serde_json::from_str(&result.output).unwrap_or_default();
let pr_url = parsed["html_url"].as_str().unwrap_or("");
let pr_num = parsed["number"].as_u64().unwrap_or(0);
// Apply labels
if !labels.is_empty() {
let labels_url =
format!("{GITHUB_API_BASE}/repos/{owner}/{repo}/issues/{pr_num}/labels");
let _ = github_post_api(&tok.token, &labels_url, json!({ "labels": labels })).await;
}
Ok(ToolResult {
success: true,
output: format!("✅ Pull request #{pr_num} created: {pr_url}"),
error: None,
error_hint: None,
})
}
}
// ── github_review_pr ──────────────────────────────────────────────────────────
pub struct GitHubReviewPRTool {
config: Arc<ZerobuildConfig>,
}
impl GitHubReviewPRTool {
pub fn new(config: Arc<ZerobuildConfig>) -> Self {
Self { config }
}
}
#[async_trait]
impl Tool for GitHubReviewPRTool {
fn name(&self) -> &str {
"github_review_pr"
}
fn description(&self) -> &str {
"Submit a review on a GitHub pull request. \
Can approve, request changes, or leave a comment."
}
fn parameters_schema(&self) -> serde_json::Value {
json!({
"type": "object",
"properties": {
"repo": { "type": "string", "description": "Repository name" },
"owner": { "type": "string", "description": "Repository owner. Defaults to authenticated user." },
"pr_number": { "type": "integer", "description": "Pull request number" },
"body": { "type": "string", "description": "Review comment body" },
"event": {
"type": "string",
"enum": ["APPROVE", "REQUEST_CHANGES", "COMMENT"],
"description": "Review action"
}
},
"required": ["repo", "pr_number", "event"]
})
}
async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
let db_path = PathBuf::from(&self.config.db_path);