thirdshift 0.36.0

Turn a GitHub issue into a ready-for-review pull request, unattended
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
//! Resolve a Command's GitHub target (issue, pull requests, and titles) for reader pages.

use std::collections::BTreeSet;

use serde_json::Value;

use super::super::command_record::Issue;
use super::super::github::Kept;
use super::super::reading::{Command, Observation};
use crate::issue::IssueUrl;
use crate::review::PullRequestUrl;

pub(in crate::logs) const MAX_DISPATCH_DEPTH: usize = 8;

/// One validated GitHub issue or pull request link and its optional title.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct TargetLink {
    pub label: String,
    pub url: Option<String>,
    pub title: Option<String>,
}

/// The GitHub issue and/or pull requests worked on by a selected Command.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct GitHubTarget {
    pub primary: Option<TargetLink>,
    pub pull_requests: Vec<TargetLink>,
}

impl GitHubTarget {
    /// Extract a target from a local snapshot `Observation` and optional `Kept` GitHub cache.
    pub(in crate::logs) fn from_observation(
        observation: Observation<'_>,
        kept: Option<&Kept>,
    ) -> Option<Self> {
        let selector = observation.selector();
        match observation {
            Observation::Record(command) => {
                let repository = command.record.repository.as_str();
                let primary = issue_target(command.record.issue.as_ref(), repository);
                let mut pull_requests = Vec::new();
                let mut seen = BTreeSet::new();
                collect_pr_links(
                    CommandPrSource { command, kept },
                    repository,
                    selector.as_deref(),
                    &mut pull_requests,
                    &mut seen,
                    0,
                );
                finalize(primary, pull_requests)
            }
            Observation::History(historical) => {
                let primary = issue_target(historical.issue.as_ref(), &historical.repository);
                finalize(primary, Vec::new())
            }
        }
    }

    /// Extract and validate a target from a remote peer's `/api/v1/peek` `command` JSON object.
    pub(crate) fn from_details(command: &Value) -> Option<Self> {
        let repository = command["repository"].as_str().unwrap_or("");
        let primary = issue_from_value(&command["issue"], repository);
        let subjects = &command["github"]["subjects"];
        let mut pull_requests = Vec::new();
        let mut seen = BTreeSet::new();
        collect_pr_links(
            DetailsPrSource {
                node: command,
                subjects,
            },
            repository,
            None,
            &mut pull_requests,
            &mut seen,
            0,
        );
        finalize(primary, pull_requests)
    }
}

fn non_empty(text: Option<&str>) -> Option<String> {
    text.filter(|value| !value.trim().is_empty())
        .map(str::to_owned)
}

pub(super) fn is_safe_github_url(raw: &str) -> bool {
    reqwest::Url::parse(raw).is_ok_and(|parsed| {
        parsed.scheme() == "https"
            && parsed.host_str() == Some("github.com")
            && parsed.port().is_none()
            && parsed.username().is_empty()
            && parsed.password().is_none()
            && parsed.query().is_none()
            && parsed.fragment().is_none()
    })
}

fn valid_repo_issue(issue: &IssueUrl, repository: &str) -> bool {
    issue.number > 0
        && crate::github::valid_repo_slug(repository)
        && crate::github::valid_repo_slug(&issue.repo_slug())
        && issue.repo_slug().eq_ignore_ascii_case(repository)
}

fn validated_issue_url(url: &str, repository: &str, expected_number: u64) -> Option<IssueUrl> {
    is_safe_github_url(url)
        .then(|| IssueUrl::parse(url).ok())
        .flatten()
        .filter(|parsed| parsed.number == expected_number && valid_repo_issue(parsed, repository))
}

pub(super) fn validated_pr_url(url: &str, repository: &str) -> Option<PullRequestUrl> {
    is_safe_github_url(url)
        .then(|| PullRequestUrl::parse(url).ok())
        .flatten()
        .filter(|parsed| valid_repo_issue(&parsed.issue, repository))
}

fn issue_target(issue: Option<&Issue>, repository: &str) -> Option<TargetLink> {
    let issue = issue?;
    if issue.number == 0 {
        return None;
    }
    let title = non_empty(issue.title.as_deref());
    if let Some(parsed) = validated_issue_url(&issue.url, repository, issue.number) {
        return Some(TargetLink {
            label: format!("{}#{}", parsed.repo_slug(), parsed.number),
            url: Some(parsed.url),
            title,
        });
    }
    crate::github::valid_repo_slug(repository).then(|| TargetLink {
        label: format!("{repository}#{}", issue.number),
        url: None,
        title,
    })
}

fn issue_from_value(issue: &Value, repository: &str) -> Option<TargetLink> {
    let object = issue.as_object()?;
    let number = object.get("number").and_then(Value::as_u64)?;
    let url = object.get("url").and_then(Value::as_str).unwrap_or("");
    let title = object
        .get("title")
        .and_then(Value::as_str)
        .map(str::to_owned);
    let candidate = Issue {
        number,
        url: url.to_owned(),
        title,
    };
    issue_target(Some(&candidate), repository)
}

fn merge_pull_request(prs: &mut Vec<TargetLink>, seen: &mut BTreeSet<String>, link: TargetLink) {
    if let Some(url) = link.url.as_deref()
        && !seen.insert(url.to_owned())
    {
        if link.title.is_some()
            && let Some(existing) = prs
                .iter_mut()
                .find(|item| item.url.as_deref() == Some(url) && item.title.is_none())
        {
            existing.title = link.title;
        }
        return;
    }
    prs.push(link);
}

fn kept_pr_title(url: &str, rows: &[&str], kept: Option<&Kept>) -> Option<String> {
    let kept = kept?;
    for row in rows {
        if let Some(title) = kept
            .pull_request(row, url)
            .and_then(|state| non_empty(state.title.as_deref()))
        {
            return Some(title);
        }
    }
    kept.pull_request("", url)
        .and_then(|state| non_empty(state.title.as_deref()))
}

trait PrSource<'a>: Sized {
    fn repository(&self) -> Option<&'a str>;
    fn pull_request(&self) -> Option<&'a str>;
    fn pr_title(&self, parsed_url: &str, outer_row: Option<&str>) -> Option<String>;
    fn dispatched(&self) -> Vec<Self>;
}

struct CommandPrSource<'a> {
    command: &'a Command,
    kept: Option<&'a Kept>,
}

impl<'a> PrSource<'a> for CommandPrSource<'a> {
    fn repository(&self) -> Option<&'a str> {
        Some(self.command.record.repository.as_str())
    }

    fn pull_request(&self) -> Option<&'a str> {
        self.command.record.pull_request.as_deref()
    }

    fn pr_title(&self, parsed_url: &str, outer_row: Option<&str>) -> Option<String> {
        let own_selector = Observation::Record(self.command).selector();
        let mut rows = Vec::new();
        if let Some(sel) = own_selector.as_deref() {
            rows.push(sel);
        }
        if let Some(sel) = outer_row
            && !rows.contains(&sel)
        {
            rows.push(sel);
        }
        kept_pr_title(parsed_url, &rows, self.kept)
            .or_else(|| non_empty(self.command.record.pull_request_title.as_deref()))
    }

    fn dispatched(&self) -> Vec<Self> {
        self.command
            .dispatched
            .iter()
            .map(|child| CommandPrSource {
                command: child,
                kept: self.kept,
            })
            .collect()
    }
}

struct DetailsPrSource<'a> {
    node: &'a Value,
    subjects: &'a Value,
}

impl<'a> PrSource<'a> for DetailsPrSource<'a> {
    fn repository(&self) -> Option<&'a str> {
        self.node["repository"].as_str()
    }

    fn pull_request(&self) -> Option<&'a str> {
        self.node["pull_request"].as_str()
    }

    fn pr_title(&self, parsed_url: &str, _outer_row: Option<&str>) -> Option<String> {
        non_empty(self.subjects[parsed_url]["facts"]["title"].as_str())
            .or_else(|| non_empty(self.node["pull_request_title"].as_str()))
    }

    fn dispatched(&self) -> Vec<Self> {
        self.node["dispatched"]
            .as_array()
            .into_iter()
            .flatten()
            .map(|child| DetailsPrSource {
                node: child,
                subjects: self.subjects,
            })
            .collect()
    }
}

fn collect_pr_links<'a, S: PrSource<'a>>(
    source: S,
    fallback_repo: &'a str,
    outer_row: Option<&str>,
    prs: &mut Vec<TargetLink>,
    seen: &mut BTreeSet<String>,
    depth: usize,
) {
    if depth > MAX_DISPATCH_DEPTH {
        return;
    }
    let repo = source
        .repository()
        .filter(|repo| !repo.is_empty())
        .unwrap_or(fallback_repo);
    if let Some(pr_url) = source.pull_request()
        && let Some(parsed) = validated_pr_url(pr_url, repo)
    {
        let title = source.pr_title(&parsed.url, outer_row);
        merge_pull_request(
            prs,
            seen,
            TargetLink {
                label: format!("{}#{}", parsed.issue.repo_slug(), parsed.issue.number),
                url: Some(parsed.url),
                title,
            },
        );
    }
    for child in source.dispatched() {
        collect_pr_links(child, repo, outer_row, prs, seen, depth + 1);
    }
}

fn finalize(
    primary: Option<TargetLink>,
    mut pull_requests: Vec<TargetLink>,
) -> Option<GitHubTarget> {
    if let Some(issue_title) = primary.as_ref().and_then(|issue| issue.title.as_deref()) {
        for pr in &mut pull_requests {
            if pr.title.as_deref() == Some(issue_title) {
                pr.title = None;
            }
        }
    }
    if primary.is_none() && pull_requests.is_empty() {
        None
    } else {
        Some(GitHubTarget {
            primary,
            pull_requests,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn from_details_suppresses_identical_pr_title_and_keeps_distinct_pr_title() {
        let same = json!({
            "repository": "acme/widgets",
            "issue": {"number": 42, "url": "https://github.com/acme/widgets/issues/42", "title": "Fix race"},
            "pull_request": "https://github.com/acme/widgets/pull/100",
            "pull_request_title": "Fix race",
            "dispatched": []
        });
        let target = GitHubTarget::from_details(&same).unwrap();
        assert_eq!(
            target
                .primary
                .as_ref()
                .and_then(|link| link.title.as_deref()),
            Some("Fix race")
        );
        assert_eq!(target.pull_requests.len(), 1);
        assert_eq!(target.pull_requests[0].label, "acme/widgets#100");
        assert_eq!(target.pull_requests[0].title, None);

        let distinct = json!({
            "repository": "acme/widgets",
            "issue": {"number": 42, "url": "https://github.com/acme/widgets/issues/42", "title": "Fix race"},
            "pull_request": null,
            "dispatched": [{
                "repository": "acme/widgets",
                "pull_request": "https://github.com/acme/widgets/pull/101",
                "pull_request_title": "PR: fix race & add test",
                "dispatched": []
            }]
        });
        let target = GitHubTarget::from_details(&distinct).unwrap();
        assert_eq!(
            target.pull_requests[0].title.as_deref(),
            Some("PR: fix race & add test")
        );
    }

    #[test]
    fn from_details_prefers_kept_pr_title_over_recorded_title() {
        let details = json!({
            "repository": "acme/widgets",
            "issue": null,
            "pull_request": "https://github.com/acme/widgets/pull/229",
            "pull_request_title": "Old recorded title",
            "github": {
                "subjects": {
                    "https://github.com/acme/widgets/pull/229": {
                        "facts": {
                            "state": "Open",
                            "title": "Renamed on GitHub",
                            "merged_at": null,
                            "closed_at": null,
                            "ci": "unknown",
                            "mergeable": "unknown"
                        },
                        "answered_at": "2026-11-01T12:00:00Z"
                    }
                }
            },
            "dispatched": []
        });
        let target = GitHubTarget::from_details(&details).unwrap();
        assert!(target.primary.is_none());
        assert_eq!(target.pull_requests.len(), 1);
        assert_eq!(target.pull_requests[0].label, "acme/widgets#229");
        assert_eq!(
            target.pull_requests[0].title.as_deref(),
            Some("Renamed on GitHub")
        );
    }

    #[test]
    fn from_details_rejects_non_github_urls_cross_repo_prs_and_deep_nesting() {
        let spoofed = json!({
            "repository": "acme/widgets",
            "issue": {"number": 7, "url": "https://evil.example/acme/widgets/issues/7", "title": "  "},
            "pull_request": "https://github.com/acme/widgets/pull/8?tab=files#diff",
            "dispatched": [{
                "repository": "acme/widgets",
                "pull_request": "https://github.com/other/repo/pull/9",
                "dispatched": []
            }]
        });
        let target = GitHubTarget::from_details(&spoofed).unwrap();
        let primary = target.primary.unwrap();
        assert_eq!(primary.label, "acme/widgets#7");
        assert_eq!(primary.url, None);
        assert_eq!(primary.title, None);
        assert!(target.pull_requests.is_empty());

        let invalid_repo = json!({
            "repository": "not a slug",
            "issue": {"number": 7, "url": "javascript:alert(1)", "title": "x"}
        });
        assert!(GitHubTarget::from_details(&invalid_repo).is_none());

        let mut nested = json!({
            "repository": "acme/widgets",
            "pull_request": "https://github.com/acme/widgets/pull/99",
            "dispatched": []
        });
        for _ in 0..10 {
            nested = json!({
                "repository": "acme/widgets",
                "dispatched": [nested]
            });
        }
        assert!(GitHubTarget::from_details(&nested).is_none());
    }

    #[test]
    fn from_details_rejects_missing_or_dot_segment_repository_urls() {
        let missing_repo = json!({
            "issue": {"number": 7, "url": "https://github.com/../widgets/issues/7", "title": "x"},
            "pull_request": "https://github.com/other/repo/pull/9",
            "dispatched": []
        });
        assert_eq!(GitHubTarget::from_details(&missing_repo), None);

        let dot_repo = json!({
            "repository": "../widgets",
            "pull_request": "https://github.com/../widgets/pull/9",
            "dispatched": []
        });
        assert_eq!(GitHubTarget::from_details(&dot_repo), None);
    }
}