nightporter 0.3.0

Handles your PRs while you're away: an agentic night shift for GitHub and GitLab
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
//! Forge-neutral types plus enum dispatch over GitHub, GitLab and Forgejo/Gitea.

pub mod forgejo;
pub mod github;
pub mod gitlab;

use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::fmt;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
#[serde(rename_all = "lowercase")]
pub enum ForgeKind {
    GitHub,
    GitLab,
    /// Forgejo and Gitea (one API). `gitea` is accepted in config.
    #[serde(alias = "gitea")]
    Forgejo,
}

impl ForgeKind {
    pub fn as_str(self) -> &'static str {
        match self {
            ForgeKind::GitHub => "github",
            ForgeKind::GitLab => "gitlab",
            ForgeKind::Forgejo => "forgejo",
        }
    }
    pub fn default_host(self) -> &'static str {
        match self {
            ForgeKind::GitHub => "github.com",
            ForgeKind::GitLab => "gitlab.com",
            ForgeKind::Forgejo => "codeberg.org",
        }
    }
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "github" => Some(Self::GitHub),
            "gitlab" => Some(Self::GitLab),
            "forgejo" | "gitea" => Some(Self::Forgejo),
            _ => None,
        }
    }
}

/// A repository on a forge. `path` is `owner/name` (GitLab may nest: `group/sub/name`).
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct RepoId {
    pub forge: ForgeKind,
    pub host: String,
    pub path: String,
}

impl RepoId {
    pub fn new(forge: ForgeKind, host: &str, path: &str) -> Self {
        Self { forge, host: host.to_ascii_lowercase(), path: path.trim_matches('/').trim_end_matches(".git").to_string() }
    }
    /// Stable key used in the database: `github:github.com/owner/name`.
    pub fn key(&self) -> String {
        format!("{}:{}/{}", self.forge.as_str(), self.host, self.path)
    }
    pub fn parse_key(s: &str) -> Option<Self> {
        let (forge, rest) = s.split_once(':')?;
        let (host, path) = rest.split_once('/')?;
        Some(Self::new(ForgeKind::parse(forge)?, host, path))
    }
}

impl fmt::Display for RepoId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.path)
    }
}

/// Normalised author role. Ordered from least to most privileged.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    None,
    Contributor,
    Collaborator,
    Member,
    Maintainer,
    Owner,
}

impl Role {
    /// GitHub `author_association`.
    pub fn from_github(assoc: &str) -> Self {
        match assoc {
            "OWNER" => Role::Owner,
            "MEMBER" => Role::Member,
            "COLLABORATOR" => Role::Collaborator,
            "CONTRIBUTOR" | "FIRST_TIME_CONTRIBUTOR" | "FIRST_TIMER" => Role::Contributor,
            _ => Role::None,
        }
    }
    /// GitLab access level (10 guest, 20 reporter, 30 developer, 40 maintainer, 50 owner).
    pub fn from_gitlab(level: u32) -> Self {
        match level {
            50.. => Role::Owner,
            40..=49 => Role::Maintainer,
            30..=39 => Role::Collaborator,
            1..=29 => Role::Contributor,
            0 => Role::None,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Trigger {
    ReviewComment,
    Review,
    Comment,
    CiFailure,
    MergeConflict,
}

/// What a trusted maintainer asked for in maintainer mode.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Verb {
    Triage,
    Reproduce,
    Fix,
    Review,
}

impl Verb {
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "triage" => Some(Self::Triage),
            "reproduce" => Some(Self::Reproduce),
            "fix" => Some(Self::Fix),
            "review" => Some(Self::Review),
            _ => None,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Mode {
    /// Activity on a PR/MR the user authored.
    MyPrs,
    /// A trusted user asked Night Porter to work on someone else's issue/MR.
    Maintainer,
}

/// Kind of thing the event targets.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Target {
    Pr,
    Issue,
}

/// One piece of activity, after polling. Bodies are untrusted until `trust::decide` says otherwise.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Event {
    /// Forge-unique id used for de-duplication, e.g. `gh-review-comment-123`.
    pub id: String,
    pub repo: RepoId,
    pub target: Target,
    pub number: u64,
    pub trigger: Trigger,
    pub author: String,
    pub role: Role,
    pub is_bot: bool,
    pub body: String,
    pub url: String,
    /// Review thread / discussion id to reply to, when there is one.
    pub thread: Option<String>,
    pub path: Option<String>,
    pub line: Option<u64>,
    pub created_at: String,
    /// Set when the event is a maintainer-mode request (label or `/nightporter <verb>`).
    pub verb: Option<Verb>,
}

impl Event {
    pub fn mode(&self) -> Mode {
        if self.verb.is_some() { Mode::Maintainer } else { Mode::MyPrs }
    }
}

/// Current time as `YYYY-MM-DDTHH:MM:SSZ` (what both forge APIs accept in queries).
pub fn now_iso() -> String {
    jiff::Timestamp::now().strftime("%Y-%m-%dT%H:%M:%SZ").to_string()
}

/// How far back each poll re-reads, to cover late indexing and clock drift.
pub const OVERLAP_SECS: i64 = 300;

/// `since` moved back by [`OVERLAP_SECS`].
pub fn overlap(since: &str) -> String {
    match since.parse::<jiff::Timestamp>() {
        Ok(t) => (t - jiff::SignedDuration::from_secs(OVERLAP_SECS)).strftime("%Y-%m-%dT%H:%M:%SZ").to_string(),
        Err(_) => since.to_string(),
    }
}

/// `ts` is strictly after `since`. Parses timestamps (forges mix `Z`, offsets and fractions);
/// falls back to string comparison if either doesn't parse.
pub fn newer(ts: &str, since: Option<&str>) -> bool {
    let Some(since) = since else { return true };
    match (ts.parse::<jiff::Timestamp>(), since.parse::<jiff::Timestamp>()) {
        (Ok(a), Ok(b)) => a > b,
        _ => ts > since,
    }
}

/// Parse a `/nightporter <verb>` command from the first line that starts with it.
pub fn parse_command(body: &str) -> Option<Verb> {
    body.lines().find_map(|l| {
        let mut it = l.trim().strip_prefix("/nightporter")?.split_whitespace();
        Verb::parse(it.next()?)
    })
}

/// A job command you post on the PR/MR yourself (e.g. from the forge's mobile app). Acts on Night
/// Porter's newest job for that PR, never on the PR itself.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Control {
    Approve,
    Dismiss,
    Retry,
    Status,
}

/// Parse `/nightporter approve|dismiss|retry|status` from the first line that starts with it.
pub fn parse_control(body: &str) -> Option<Control> {
    body.lines().find_map(|l| {
        let mut it = l.split_whitespace();
        if it.next()? != "/nightporter" {
            return None;
        }
        match it.next()? {
            "approve" => Some(Control::Approve),
            "dismiss" => Some(Control::Dismiss),
            "retry" => Some(Control::Retry),
            "status" => Some(Control::Status),
            _ => None,
        }
    })
}

/// A [`Control`] comment written by the token's own user (checked by user id).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ControlComment {
    /// The forge's comment/note id (for the reaction and the processed-once record).
    pub id: String,
    pub control: Control,
}

/// The command in a comment, if the token's own user posted it after `since`.
/// `me_id == 0` (unknown) never matches. Night Porter's own posts never count.
pub fn control_of(me_id: u64, author_id: u64, via_app: bool, body: &str, created_at: &str, since: &str) -> Option<Control> {
    if me_id == 0 || author_id != me_id || via_app || body.contains(crate::prompts::FOOTER_MARK) || !newer(created_at, Some(since)) {
        return None;
    }
    parse_control(body)
}

/// What we need to check out and push a PR/MR.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct PrInfo {
    pub number: u64,
    pub title: String,
    pub author: String,
    pub state: PrState,
    pub head_ref: String,
    pub head_sha: String,
    /// Clone URLs of the repo holding the head branch (may be a fork).
    pub head_repo_ssh: String,
    pub head_repo_https: String,
    pub base_ref: String,
    pub draft: bool,
    pub body: String,
}

/// An issue's text, for maintainer mode. Always untrusted.
#[derive(Clone, Debug, Default)]
pub struct IssueInfo {
    pub title: String,
    pub body: String,
    pub author: String,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PrState {
    #[default]
    Open,
    Closed,
    Merged,
}

/// One reply the agent wants posted.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Reply {
    /// Event id this answers (thread replies), or `None` for a top-level comment.
    #[serde(default)]
    pub event: Option<String>,
    pub body: String,
}

/// A forge client. Enum dispatch (three forges, no trait objects needed).
pub enum Forge {
    GitHub(github::GitHub),
    GitLab(gitlab::GitLab),
    Forgejo(forgejo::Forgejo),
}

impl Forge {
    /// Comments on `number` posted after `since` by the token's own user that are job commands,
    /// oldest first.
    pub async fn controls(&self, repo: &RepoId, target: Target, number: u64, since: &str) -> Result<Vec<ControlComment>> {
        match self {
            Forge::GitHub(g) => g.controls(repo, number, since).await,
            Forge::GitLab(g) => g.controls(repo, target, number, since).await,
            Forge::Forgejo(g) => g.controls(repo, number, since).await,
        }
    }
    /// Acknowledge a command comment with a thumbs-up.
    pub async fn ack(&self, repo: &RepoId, target: Target, number: u64, comment: &str) -> Result<()> {
        match self {
            Forge::GitHub(g) => g.ack(repo, comment).await,
            Forge::GitLab(g) => g.ack(repo, target, number, comment).await,
            Forge::Forgejo(g) => g.ack(repo, comment).await,
        }
    }
    pub fn me(&self) -> &str {
        match self {
            Forge::GitHub(g) => &g.me,
            Forge::GitLab(g) => &g.me,
            Forge::Forgejo(g) => &g.me,
        }
    }
    pub async fn login(&mut self) -> Result<()> {
        match self {
            Forge::GitHub(g) => g.login().await,
            Forge::GitLab(g) => g.login().await,
            Forge::Forgejo(g) => g.login().await,
        }
    }
    /// New events since the last poll. `cursor` is opaque, persisted by the caller.
    pub async fn poll(&mut self, cursor: &mut Cursor) -> Result<Vec<Event>> {
        if cursor.since.is_none() {
            // First run: start from now. Never replay history (old comments, CI already red).
            cursor.since = Some(now_iso());
            cursor.last_sweep = Some(crate::state::now());
            return Ok(vec![]);
        }
        match self {
            Forge::GitHub(g) => g.poll(cursor).await,
            Forge::GitLab(g) => g.poll(cursor).await,
            Forge::Forgejo(g) => g.poll(cursor).await,
        }
    }
    pub async fn pr(&self, repo: &RepoId, number: u64) -> Result<PrInfo> {
        match self {
            Forge::GitHub(g) => g.pr(repo, number).await,
            Forge::GitLab(g) => g.mr(repo, number).await,
            Forge::Forgejo(g) => g.pr(repo, number).await,
        }
    }
    pub async fn issue(&self, repo: &RepoId, number: u64) -> Result<IssueInfo> {
        match self {
            Forge::GitHub(g) => g.issue(repo, number).await,
            Forge::GitLab(g) => g.issue(repo, number).await,
            Forge::Forgejo(g) => g.issue(repo, number).await,
        }
    }
    /// Reply in the event's thread when it has one, else a top-level comment on the PR/issue.
    pub async fn reply(&self, repo: &RepoId, target: Target, number: u64, to: Option<&Event>, body: &str) -> Result<()> {
        match self {
            Forge::GitHub(g) => g.reply(repo, target, number, to, body).await,
            Forge::GitLab(g) => g.reply(repo, target, number, to, body).await,
            Forge::Forgejo(g) => g.reply(repo, number, to, body).await,
        }
    }
    pub async fn resolve(&self, repo: &RepoId, number: u64, thread: &str) -> Result<()> {
        match self {
            Forge::GitHub(g) => g.resolve(repo, thread).await,
            Forge::GitLab(g) => g.resolve(repo, number, thread).await,
            Forge::Forgejo(g) => g.resolve(repo, thread).await,
        }
    }
    /// Open a draft PR/MR (maintainer `fix`). Returns its URL.
    pub async fn open_draft(&self, repo: &RepoId, head: &str, base: &str, title: &str, body: &str) -> Result<String> {
        match self {
            Forge::GitHub(g) => g.open_draft(repo, head, base, title, body).await,
            Forge::GitLab(g) => g.open_draft(repo, head, base, title, body).await,
            Forge::Forgejo(g) => g.open_draft(repo, head, base, title, body).await,
        }
    }
    pub async fn in_team(&self, team: &str, user: &str) -> Result<bool> {
        match self {
            Forge::GitHub(g) => g.in_team(team, user).await,
            Forge::GitLab(g) => g.in_group(team, user).await,
            Forge::Forgejo(g) => g.in_team(team, user).await,
        }
    }
}

/// A small map whose entries expire after an hour (role and team lookups).
pub struct Ttl<K, V>(std::sync::Mutex<std::collections::HashMap<K, (i64, V)>>);

impl<K: std::hash::Hash + Eq, V: Clone> Default for Ttl<K, V> {
    fn default() -> Self {
        Self(std::sync::Mutex::default())
    }
}

impl<K: std::hash::Hash + Eq, V: Clone> Ttl<K, V> {
    pub fn get(&self, k: &K) -> Option<V> {
        let m = self.0.lock().unwrap();
        m.get(k).filter(|(at, _)| crate::state::now() - at < 3600).map(|(_, v)| v.clone())
    }
    pub fn put(&self, k: K, v: V) {
        self.0.lock().unwrap().insert(k, (crate::state::now(), v));
    }
}

/// Opaque per-account poll cursor, stored as JSON in the state db.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Cursor {
    #[serde(default)]
    pub last_modified: Option<String>,
    #[serde(default)]
    pub since: Option<String>,
    #[serde(default)]
    pub poll_interval_secs: Option<u64>,
    /// Last time the slow "my open PRs" sweep ran (unix secs).
    #[serde(default)]
    pub last_sweep: Option<i64>,
    /// Mergeable / CI status seen last sweep, per `repo#n`, so we only fire on change.
    #[serde(default)]
    pub seen_status: std::collections::BTreeMap<String, String>,
    /// A first (record-only) sweep has happened.
    #[serde(default)]
    pub swept: bool,
}

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

    #[test]
    fn repo_key_roundtrip() {
        let r = RepoId::new(ForgeKind::GitLab, "Git.DrupalCode.org", "project/token.git");
        assert_eq!(r.key(), "gitlab:git.drupalcode.org/project/token");
        assert_eq!(RepoId::parse_key(&r.key()), Some(r));
    }

    #[test]
    fn timestamps() {
        assert!(newer("2026-11-05T10:00:01Z", Some("2026-11-05T10:00:00Z")));
        assert!(!newer("2026-11-05T10:00:00Z", Some("2026-11-05T10:00:00Z")));
        assert!(newer("2026-11-05T11:30:00.000+01:00", Some("2026-11-05T10:00:00Z")));
        assert!(!newer("2026-11-05T10:30:00.000+01:00", Some("2026-11-05T10:00:00Z")));
        assert!(newer("x", None));
        assert_eq!(overlap("2026-11-05T10:05:00Z"), "2026-11-05T10:00:00Z");
    }

    #[test]
    fn commands() {
        assert_eq!(parse_command("thanks!\n/nightporter fix please"), Some(Verb::Fix));
        assert_eq!(parse_command("  /nightporter triage"), Some(Verb::Triage));
        assert_eq!(parse_command("/nightporter merge"), None);
        assert_eq!(parse_command("see /nightporter fix"), None);
    }

    #[test]
    fn controls() {
        assert_eq!(parse_control("/nightporter approve"), Some(Control::Approve));
        assert_eq!(parse_control("lgtm\n  /nightporter retry now"), Some(Control::Retry));
        assert_eq!(parse_control("/nightporter dismiss"), Some(Control::Dismiss));
        assert_eq!(parse_control("/nightporter status"), Some(Control::Status));
        assert_eq!(parse_control("/nightporter merge"), None);
        assert_eq!(parse_control("/nightporter fix"), None);
        assert_eq!(parse_control("please /nightporter approve"), None);
        assert_eq!(parse_control("/nightporterapprove"), None);
        let at = "2026-11-05T10:00:01Z";
        let since = "2026-11-05T10:00:00Z";
        assert_eq!(control_of(7, 7, false, "/nightporter approve", at, since), Some(Control::Approve));
        assert_eq!(control_of(7, 8, false, "/nightporter approve", at, since), None, "someone else");
        assert_eq!(control_of(0, 0, false, "/nightporter approve", at, since), None, "unknown id");
        assert_eq!(control_of(7, 7, true, "/nightporter approve", at, since), None, "an app acting as me");
        assert_eq!(control_of(7, 7, false, "/nightporter approve", since, since), None, "older than the job");
        let ours = format!("/nightporter approve\n{}", crate::prompts::FOOTER_MARK);
        assert_eq!(control_of(7, 7, false, &ours, at, since), None, "our own post");
    }

    #[test]
    fn roles() {
        assert_eq!(Role::from_github("MEMBER"), Role::Member);
        assert_eq!(Role::from_github("NONE"), Role::None);
        assert_eq!(Role::from_gitlab(40), Role::Maintainer);
        assert_eq!(Role::from_gitlab(30), Role::Collaborator);
        assert!(Role::Owner > Role::Contributor);
    }

    #[test]
    fn forgejo_kind() {
        assert_eq!(ForgeKind::parse("gitea"), Some(ForgeKind::Forgejo));
        assert_eq!(toml::from_str::<toml::Table>("f='gitea'").unwrap()["f"].clone().try_into::<ForgeKind>().unwrap(), ForgeKind::Forgejo);
        let r = RepoId::new(ForgeKind::Forgejo, "Codeberg.org", "o/r");
        assert_eq!(RepoId::parse_key(&r.key()), Some(r));
    }
}