wsb-github 0.251.6311

GitHub issues, pull requests, gists and Projects boards, mirrored once per machine for every project under $PRJ
Documentation
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
//! Everything a person does with GitHub here, once.
//!
//! A command line, a daemon serving pages, and any other surface call these
//! and nothing beneath them. Reads come from the mirror: no token, no network,
//! no waiting, and every answer carries how old it is. Writes go to GitHub
//! FIRST and are mirrored from what GitHub hands back — the other order shows
//! a change and takes it away again on the next sync, and a surface that does
//! that is one nobody believes.

use std::collections::BTreeMap;
use std::fs::File;
use std::path::PathBuf;

use anyhow::Context;
use serde::Serialize;

use crate::boards::BoardRef;
use crate::checkout::Repository;
use crate::client::{
    CreateGistRequest, CreateIssueRequest, GitHubClient, GitHubComment, GitHubGist, GitHubIssue,
    GitHubProject, GitHubProjectItem, ProjectFieldWrite, UpdateGistRequest, UpdateIssueRequest,
};
use crate::mirror::{Document, Mirror, Scope, Standing};
use crate::sync::{self, SyncReport};

/// Why an operation did not happen.
///
/// Three different things, and every surface says them differently: a request
/// that was wrong (a draft with no title), GitHub refusing or failing, and the
/// mirror itself failing.
#[derive(Debug)]
pub enum Failure {
    /// The request itself is wrong; nothing was asked of anybody.
    Invalid(String),
    /// Answering needs GitHub, and there is no token to ask with.
    NoToken(String),
    /// GitHub refused or could not be reached.
    GitHub(anyhow::Error),
    /// The mirror could not be read or written.
    Mirror(anyhow::Error),
}

impl Failure {
    /// Whether this is about the token: there is none, or GitHub refused the
    /// one there is — it is invalid, or lacks the access the request needs.
    pub fn is_authorization(&self) -> bool {
        match self {
            Self::NoToken(_) => true,
            Self::GitHub(error) => {
                let message = format!("{error:#}");
                message.contains("status 401") || message.contains("status 403")
            }
            _ => false,
        }
    }
}

impl std::fmt::Display for Failure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Invalid(message) | Self::NoToken(message) => f.write_str(message),
            Self::GitHub(error) => write!(f, "{error:#}"),
            Self::Mirror(error) => write!(f, "the GitHub mirror failed: {error:#}"),
        }
    }
}

impl std::error::Error for Failure {}

pub type Outcome<T> = std::result::Result<T, Failure>;

fn mirror_failure(error: anyhow::Error) -> Failure {
    Failure::Mirror(error)
}

fn github_failure(error: anyhow::Error) -> Failure {
    Failure::GitHub(error)
}

/// Which issues a read wants.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IssueState {
    Open,
    Closed,
    All,
}

impl std::str::FromStr for IssueState {
    type Err = String;
    fn from_str(text: &str) -> Result<Self, String> {
        match text {
            "open" => Ok(Self::Open),
            "closed" => Ok(Self::Closed),
            "all" => Ok(Self::All),
            other => Err(format!("unsupported issue state '{other}': open, closed or all")),
        }
    }
}

impl IssueState {
    fn admits(self, issue: &serde_json::Value) -> bool {
        let state = issue.get("state").and_then(|value| value.as_str()).unwrap_or("");
        match self {
            Self::Open => state == "open",
            Self::Closed => state == "closed",
            Self::All => true,
        }
    }
}

/// A repository whose last refresh failed, and why.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RepoFailure {
    pub repo: String,
    pub error: String,
}

/// Issues across several repositories, as the mirror holds them.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct IssueList {
    /// Newest movement first, each carrying `repo`.
    pub issues: Vec<serde_json::Value>,
    pub failures: Vec<RepoFailure>,
    /// Per repository, how current its copy is.
    pub sync: BTreeMap<String, Standing>,
}

/// A list scope's documents and how current they are.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Listed {
    pub items: Vec<serde_json::Value>,
    pub sync: Standing,
}

/// A single-document scope's document — `None` when not read yet — and how
/// current it is.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Single {
    pub item: Option<serde_json::Value>,
    pub sync: Standing,
}

/// What the mirror knows about one repository, for a row that draws it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RepoFacts {
    pub open_issues: i64,
    pub open_pulls: i64,
    /// Absent until the repository has been read: a repository wrongly drawn
    /// as public is how something private gets pasted somewhere.
    pub private: Option<bool>,
    pub archived: Option<bool>,
    pub stars: Option<i64>,
    /// CI's verdict on the commit this checkout has the repository at.
    pub checks: Option<String>,
}

/// The boards a project references, and why any could not be shown.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct BoardList {
    pub boards: Vec<GitHubProject>,
    pub problems: Vec<String>,
    /// Per owner board-list scope, how current it is.
    pub sync: BTreeMap<String, Standing>,
}

/// Why an owner's boards are listed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Relation {
    /// The account the token belongs to.
    Account,
    /// An organisation that account is a member of.
    Organization,
    /// Neither — it owns a board some project references.
    Referenced,
}

/// One owner of boards, and how current its board list is.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct BoardOwner {
    pub login: String,
    pub relation: Relation,
    pub sync: Standing,
}

/// Every board this person reaches, as the mirror holds them.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct AllBoards {
    /// The account first, then its organisations, then the owners of
    /// referenced boards that are neither — the order the boards are in.
    pub owners: Vec<BoardOwner>,
    /// Owner by owner, open boards before closed, most recently changed first.
    pub boards: Vec<GitHubProject>,
    /// The node ids of the boards the asking project references, in the order
    /// it lists them.
    pub referenced: Vec<String>,
    /// How current the knowledge of whose boards these are is.
    pub account: Standing,
    pub problems: Vec<String>,
}

/// One board's cards and how current they are.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Cards {
    pub items: Vec<GitHubProjectItem>,
    pub sync: Standing,
}

/// A gist, and whether it came from the mirror or had to be fetched.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct GistAnswer {
    pub gist: serde_json::Value,
    pub from_mirror: bool,
}

/// The machine's GitHub, read through the mirror and written through GitHub.
#[derive(Debug, Clone)]
pub struct Service {
    mirror: Mirror,
}

impl Service {
    pub fn new(mirror: Mirror) -> Self {
        Self { mirror }
    }

    pub fn mirror(&self) -> &Mirror {
        &self.mirror
    }

    // ------------------------------------------------------------- reading

    fn standing(&self, scope: &Scope) -> Outcome<Standing> {
        Ok(self.mirror.state(scope).map_err(mirror_failure)?.standing())
    }

    /// Every mirrored issue of these repositories.
    pub fn issues(&self, repos: &[String], wanted: IssueState) -> Outcome<IssueList> {
        let mut issues = Vec::new();
        let mut failures = Vec::new();
        let mut standing = BTreeMap::new();
        for repo in repos {
            let scope = Scope::Issues(repo.clone());
            for mut issue in self.mirror.payloads(&scope).map_err(mirror_failure)? {
                if !wanted.admits(&issue) {
                    continue;
                }
                if let Some(object) = issue.as_object_mut() {
                    object.insert("repo".to_string(), serde_json::json!(repo));
                }
                issues.push(issue);
            }
            let state = self.mirror.state(&scope).map_err(mirror_failure)?;
            // A repository that has never synced is not a failure to report;
            // it is one not reached yet, and its standing says so.
            if let Some(error) = &state.last_error {
                failures.push(RepoFailure {
                    repo: repo.clone(),
                    error: error.clone(),
                });
            }
            standing.insert(repo.clone(), state.standing());
        }
        issues.sort_by(|a, b| updated_of(b).cmp(updated_of(a)));
        Ok(IssueList {
            issues,
            failures,
            sync: standing,
        })
    }

    /// A list scope as it stands.
    pub fn list(&self, scope: &Scope) -> Outcome<Listed> {
        Ok(Listed {
            items: self.mirror.payloads(scope).map_err(mirror_failure)?,
            sync: self.standing(scope)?,
        })
    }

    /// A single-document scope as it stands.
    pub fn single(&self, scope: &Scope) -> Outcome<Single> {
        Ok(Single {
            item: self.mirror.only(scope).map_err(mirror_failure)?,
            sync: self.standing(scope)?,
        })
    }

    /// What the mirror knows about each repository of a checkout, in one read.
    pub fn overview(&self, repositories: &[Repository]) -> Outcome<BTreeMap<String, RepoFacts>> {
        let open_issues = self.mirror.open_counts("issues").map_err(mirror_failure)?;
        let open_pulls = self.mirror.open_counts("pulls").map_err(mirror_failure)?;
        let mut facts = BTreeMap::new();
        for repository in repositories {
            let repo = &repository.name;
            let metadata = self
                .mirror
                .only(&Scope::Repository(repo.clone()))
                .map_err(mirror_failure)?;
            let checks = match &repository.head {
                Some(commit) => self
                    .mirror
                    .only(&Scope::Checks {
                        repo: repo.clone(),
                        commit: commit.clone(),
                    })
                    .map_err(mirror_failure)?,
                None => None,
            };
            facts.insert(
                repo.clone(),
                RepoFacts {
                    open_issues: open_issues.get(repo).copied().unwrap_or(0),
                    open_pulls: open_pulls.get(repo).copied().unwrap_or(0),
                    private: metadata.as_ref().and_then(|m| m.get("private")?.as_bool()),
                    archived: metadata.as_ref().and_then(|m| m.get("archived")?.as_bool()),
                    stars: metadata.as_ref().and_then(|m| m.get("stargazers_count")?.as_i64()),
                    checks: checks
                        .as_ref()
                        .and_then(|c| c.get("state")?.as_str().map(str::to_string)),
                },
            );
        }
        Ok(facts)
    }

    /// The person's gists. Summaries until one is opened.
    pub fn gists(&self) -> Outcome<Listed> {
        self.list(&Scope::Gists)
    }

    /// One gist with its file contents.
    ///
    /// The mirror answers when it holds the whole gist. Often it does not —
    /// the list endpoint omits file contents — and opening one is the moment
    /// where reaching GitHub is right: a person is waiting for exactly this,
    /// and what comes back is stored, so the next open is instant.
    pub async fn gist(&self, client: Option<&GitHubClient>, id: &str) -> Outcome<GistAnswer> {
        if let Some(held) = self.mirror.document(&Scope::Gists, id).map_err(mirror_failure)? {
            if held.complete {
                return Ok(GistAnswer {
                    gist: held.payload,
                    from_mirror: true,
                });
            }
        }
        let client = client.ok_or_else(|| {
            Failure::NoToken(format!(
                "gist {id} is held only as a summary, and there is no GitHub token to read it with \
                 (log in with `gh auth login`)"
            ))
        })?;
        let gist = client.get_gist(id).await.map_err(github_failure)?;
        let payload = self.record_gist(&gist)?;
        Ok(GistAnswer {
            gist: payload,
            from_mirror: false,
        })
    }

    /// Comments on an issue or pull request.
    ///
    /// Opening a thread is what puts it in the sweep: a thread nobody opened
    /// is not worth a request per sweep. The first open reads it now, when a
    /// token is there to read with; after that the mirror answers.
    pub async fn comments(
        &self,
        client: Option<&GitHubClient>,
        repo: &str,
        number: i64,
    ) -> Outcome<Listed> {
        let scope = Scope::Comments {
            repo: repo.to_string(),
            number,
        };
        self.mirror.hold(&scope).map_err(mirror_failure)?;
        let state = self.mirror.state(&scope).map_err(mirror_failure)?;
        if !state.ever_synced() {
            if let Some(client) = client {
                let report = sync::sync_scopes(&self.mirror, client, &[scope.clone()], true).await;
                if let Some((_, error)) = report.failed.first() {
                    return Err(Failure::GitHub(anyhow::anyhow!("{error}")));
                }
            }
        }
        self.list(&scope)
    }

    // ------------------------------------------------------------- writing

    fn record_issue(&self, repo: &str, issue: &GitHubIssue) -> Outcome<()> {
        let payload = serde_json::to_value(issue).map_err(|e| mirror_failure(e.into()))?;
        self.mirror
            .put_one(
                &Scope::Issues(repo.to_string()),
                Document::of(issue.number.to_string(), payload),
            )
            .map_err(mirror_failure)?;
        Ok(())
    }

    fn record_gist(&self, gist: &GitHubGist) -> Outcome<serde_json::Value> {
        let payload = serde_json::to_value(gist).map_err(|e| mirror_failure(e.into()))?;
        // Whole: this came from the single-gist endpoint or from an edit, so it
        // carries the file contents an editor needs.
        self.mirror
            .put_one(&Scope::Gists, Document::of(gist.id.clone(), payload.clone()))
            .map_err(mirror_failure)?;
        Ok(payload)
    }

    pub async fn create_issue(
        &self,
        client: &GitHubClient,
        owner: &str,
        repo: &str,
        request: &CreateIssueRequest,
    ) -> Outcome<GitHubIssue> {
        if request.title.trim().is_empty() {
            return Err(Failure::Invalid("an issue needs a title".to_string()));
        }
        let issue = client
            .create_issue(owner, repo, request)
            .await
            .map_err(github_failure)?;
        // Mirrored now, not at the next sweep: a person who just created an
        // issue must see it.
        self.record_issue(&format!("{owner}/{repo}"), &issue)?;
        Ok(issue)
    }

    pub async fn update_issue(
        &self,
        client: &GitHubClient,
        owner: &str,
        repo: &str,
        number: i64,
        request: &UpdateIssueRequest,
    ) -> Outcome<GitHubIssue> {
        let issue = client
            .update_issue(owner, repo, number, request)
            .await
            .map_err(github_failure)?;
        self.record_issue(&format!("{owner}/{repo}"), &issue)?;
        Ok(issue)
    }

    pub async fn add_comment(
        &self,
        client: &GitHubClient,
        owner: &str,
        repo: &str,
        number: i64,
        body: &str,
    ) -> Outcome<GitHubComment> {
        if body.trim().is_empty() {
            return Err(Failure::Invalid("a comment needs a body".to_string()));
        }
        let comment = client
            .add_comment(owner, repo, number, body)
            .await
            .map_err(github_failure)?;
        let scope = Scope::Comments {
            repo: format!("{owner}/{repo}"),
            number,
        };
        let payload = serde_json::to_value(&comment).map_err(|e| mirror_failure(e.into()))?;
        self.mirror.hold(&scope).map_err(mirror_failure)?;
        self.mirror
            .put_one(&scope, Document::of(comment.id.to_string(), payload))
            .map_err(mirror_failure)?;
        Ok(comment)
    }

    pub async fn create_gist(
        &self,
        client: &GitHubClient,
        request: &CreateGistRequest,
    ) -> Outcome<serde_json::Value> {
        if request.files.is_empty() {
            return Err(Failure::Invalid("a gist needs at least one file".to_string()));
        }
        let gist = client.create_gist(request).await.map_err(github_failure)?;
        self.record_gist(&gist)
    }

    pub async fn update_gist(
        &self,
        client: &GitHubClient,
        id: &str,
        request: &UpdateGistRequest,
    ) -> Outcome<serde_json::Value> {
        let gist = client.update_gist(id, request).await.map_err(github_failure)?;
        self.record_gist(&gist)
    }

    // -------------------------------------------------------------- boards

    /// The boards a project references, as the mirror knows them.
    pub fn boards(&self, references: &[BoardRef]) -> Outcome<BoardList> {
        let wanted = references.iter().cloned().collect();
        let (boards, problems) =
            sync::resolve_boards(&self.mirror, &wanted).map_err(mirror_failure)?;
        // In the order the project lists them, not the order they resolved.
        let mut ordered = Vec::new();
        for reference in references {
            if let Some(board) = boards
                .iter()
                .find(|board| board.owner == reference.owner && board.number == reference.number)
            {
                ordered.push(board.clone());
            }
        }
        let mut standing = BTreeMap::new();
        for reference in references {
            let scope = Scope::Projects(reference.owner.clone());
            standing.insert(scope.key(), self.standing(&scope)?);
        }
        Ok(BoardList {
            boards: ordered,
            problems,
            sync: standing,
        })
    }

    /// Every board of the token's account, of each of its organisations, and
    /// of the owner of every board `references` names — with which of them
    /// those references are.
    ///
    /// Boards belong to owners, not to projects, so this is the same list from
    /// whichever project it is asked; the references only mark the boards that
    /// project works with. An owner whose list has never been read is reported
    /// beside the boards that could be listed, never dropped silently.
    pub fn all_boards(&self, references: &[BoardRef]) -> Outcome<AllBoards> {
        let account = self.standing(&Scope::Viewer)?;
        let viewer = sync::viewer(&self.mirror).map_err(mirror_failure)?;
        let mut problems = Vec::new();

        let mut owners: Vec<(String, Relation)> = Vec::new();
        match viewer {
            Some(viewer) => {
                owners.push((viewer.login, Relation::Account));
                let mut organizations = viewer.organizations;
                organizations.sort_by_key(|login| login.to_lowercase());
                owners.extend(organizations.into_iter().map(|login| (login, Relation::Organization)));
            }
            None => problems.push(match &account.last_error {
                Some(error) => format!("whose boards these are could not be read: {error}"),
                None => "who the GitHub token belongs to has not been read yet, so only referenced \
                         boards are listed"
                    .to_string(),
            }),
        }
        for reference in references {
            if !owners.iter().any(|(login, _)| *login == reference.owner) {
                owners.push((reference.owner.clone(), Relation::Referenced));
            }
        }

        let mut listed = Vec::new();
        let mut boards = Vec::new();
        let mut unread = std::collections::BTreeSet::new();
        for (login, relation) in owners {
            let scope = Scope::Projects(login.clone());
            match sync::owner_boards(&self.mirror, &login).map_err(mirror_failure)? {
                Ok(mut held) => {
                    held.sort_by(|a, b| a.closed.cmp(&b.closed).then(b.updated_at.cmp(&a.updated_at)));
                    boards.extend(held);
                }
                Err(reason) => {
                    problems.push(reason);
                    unread.insert(login.clone());
                }
            }
            listed.push(BoardOwner {
                sync: self.standing(&scope)?,
                login,
                relation,
            });
        }

        let mut referenced = Vec::new();
        for reference in references {
            match boards
                .iter()
                .find(|board| board.owner == reference.owner && board.number == reference.number)
            {
                Some(board) => referenced.push(board.id.clone()),
                // An owner whose list was never read is already reported.
                None if unread.contains(&reference.owner) => {}
                None => problems.push(format!("{} has no board {}", reference.owner, reference.number)),
            }
        }

        Ok(AllBoards {
            owners: listed,
            boards,
            referenced,
            account,
            problems,
        })
    }

    /// One board's cards, in TODAY'S shape.
    ///
    /// Every card is parsed into the type this version defines: a row an
    /// older version wrote takes the defaults of the fields it did not have,
    /// and a payload that does not parse AT ALL is raised — half a board is
    /// the silent wrong answer.
    pub fn cards(&self, board: &str) -> Outcome<Cards> {
        let scope = Scope::ProjectItems(board.to_string());
        let items = self
            .mirror
            .payloads(&scope)
            .map_err(mirror_failure)?
            .into_iter()
            .map(|payload| {
                serde_json::from_value::<GitHubProjectItem>(payload).map_err(|e| {
                    Failure::Mirror(anyhow::anyhow!(
                        "a mirrored card of {board} cannot be read by this version ({e}); \
                         sync the board to read it again"
                    ))
                })
            })
            .collect::<Outcome<Vec<_>>>()?;
        Ok(Cards {
            items,
            sync: self.standing(&scope)?,
        })
    }

    /// Bring every board current now — who the token is, each owner's list,
    /// the cards being kept — without the rest of the machine's mirror.
    pub async fn refresh_boards(&self, client: &GitHubClient, references: &[BoardRef]) -> SyncReport {
        let references = references.iter().cloned().collect();
        sync::sync_boards(&self.mirror, client, &references, true).await
    }

    /// Bring one board's cards current before it is shown, if due — or whether
    /// due or not, with `force` — and nothing else.
    ///
    /// The board is one the mirror already lists, so its owner's list has
    /// nothing to add. Reading more inside the request that opens a board made
    /// that request slow enough for its caller to give up, and a cancelled
    /// read left the board "not read yet" until the next scheduled pass
    /// (20 Oct 2026). A board's cards need nothing but the board.
    pub async fn refresh_board(
        &self,
        client: &GitHubClient,
        board: &GitHubProject,
        force: bool,
    ) -> SyncReport {
        sync::sync_scopes(&self.mirror, client, &[Scope::ProjectItems(board.id.clone())], force).await
    }

    fn record_card(&self, board: &str, item: &GitHubProjectItem) -> Outcome<()> {
        let payload = serde_json::to_value(item).map_err(|e| mirror_failure(e.into()))?;
        self.mirror
            .put_one(
                &Scope::ProjectItems(board.to_string()),
                Document::of(item.id.clone(), payload),
            )
            .map_err(mirror_failure)?;
        Ok(())
    }

    /// Set one field of one card, or take its value off with `None`.
    ///
    /// Clearing is its own act rather than an empty value: an empty text IS a
    /// value, and a board that could not tell "no due date" from "a due date
    /// of nothing" shows a column of blanks where it means to show none.
    pub async fn set_field(
        &self,
        client: &GitHubClient,
        board: &str,
        item: &str,
        field: &str,
        value: Option<&ProjectFieldWrite>,
    ) -> Outcome<GitHubProjectItem> {
        let updated = match value {
            Some(value) => client.set_project_field(board, item, field, value).await,
            None => client.clear_project_field(board, item, field).await,
        }
        .map_err(github_failure)?;
        self.record_card(board, &updated)?;
        Ok(updated)
    }

    /// Order a card: behind `after`, or first with `None`.
    pub async fn move_card(
        &self,
        client: &GitHubClient,
        board: &str,
        item: &str,
        after: Option<&str>,
    ) -> Outcome<GitHubProjectItem> {
        if after == Some(item) {
            return Err(Failure::Invalid("a card cannot be moved behind itself".to_string()));
        }
        let updated = client
            .move_project_item_after(board, item, after)
            .await
            .map_err(github_failure)?;
        self.record_card(board, &updated)?;
        Ok(updated)
    }

    /// Archive a card, or bring it back. Stated rather than toggled: a toggle
    /// acts on what the caller last saw.
    pub async fn set_archived(
        &self,
        client: &GitHubClient,
        board: &str,
        item: &str,
        archived: bool,
    ) -> Outcome<GitHubProjectItem> {
        let updated = client
            .archive_project_item(board, item, archived)
            .await
            .map_err(github_failure)?;
        self.record_card(board, &updated)?;
        Ok(updated)
    }

    /// Rewrite a draft card's title and body, whole.
    pub async fn edit_draft(
        &self,
        client: &GitHubClient,
        board: &str,
        item: &str,
        content: &str,
        title: &str,
        body: &str,
    ) -> Outcome<GitHubProjectItem> {
        if title.trim().is_empty() {
            return Err(Failure::Invalid(
                "a draft card needs a title; an untitled card is one nobody can find".to_string(),
            ));
        }
        let updated = client
            .update_project_draft(item, content, title, body)
            .await
            .map_err(github_failure)?;
        self.record_card(board, &updated)?;
        Ok(updated)
    }

    /// A card that lives only on the board.
    pub async fn add_draft(
        &self,
        client: &GitHubClient,
        board: &str,
        title: &str,
        body: &str,
    ) -> Outcome<GitHubProjectItem> {
        if title.trim().is_empty() {
            return Err(Failure::Invalid("a draft card needs a title".to_string()));
        }
        let added = client
            .add_project_draft(board, title, body)
            .await
            .map_err(github_failure)?;
        self.record_card(board, &added)?;
        Ok(added)
    }

    /// A card for an issue or pull request that already exists, by its URL.
    pub async fn add_existing(
        &self,
        client: &GitHubClient,
        board: &str,
        url: &str,
    ) -> Outcome<GitHubProjectItem> {
        let added = client
            .add_project_item_by_url(board, url)
            .await
            .map_err(github_failure)?;
        self.record_card(board, &added)?;
        Ok(added)
    }

    /// Take a card off the board. The issue itself is untouched — a board
    /// owns cards, not issues — and a draft has nowhere else to be.
    pub async fn remove_card(&self, client: &GitHubClient, board: &str, item: &str) -> Outcome<()> {
        client
            .delete_project_item(board, item)
            .await
            .map_err(github_failure)?;
        // Gone from the mirror now rather than at the next sync: a card that
        // stayed until then is one somebody removes twice.
        self.mirror
            .remove_one(&Scope::ProjectItems(board.to_string()), item)
            .map_err(mirror_failure)?;
        Ok(())
    }

    /// Add a column to a board's single-select field.
    pub async fn add_column(
        &self,
        client: &GitHubClient,
        board: &str,
        field: &str,
        name: &str,
        color: &str,
        description: &str,
    ) -> Outcome<(GitHubProject, Vec<GitHubProjectItem>)> {
        let _lock = self.column_lock().await?;
        let updated = client
            .add_project_column(board, field, name, color, description)
            .await
            .map_err(github_failure)?;
        let items = client.project_items(board).await.map_err(github_failure)?;
        self.record_board(&updated, &items)?;
        Ok((updated, items))
    }

    /// Remove a column. GitHub clears that value from affected cards; every
    /// card is read again before the mirror changes, so they land in no column.
    pub async fn remove_column(
        &self,
        client: &GitHubClient,
        board: &str,
        field: &str,
        option: &str,
    ) -> Outcome<(GitHubProject, Vec<GitHubProjectItem>)> {
        let _lock = self.column_lock().await?;
        let updated = client
            .remove_project_column(board, field, option)
            .await
            .map_err(github_failure)?;
        let items = client.project_items(board).await.map_err(github_failure)?;
        self.record_board(&updated, &items)?;
        Ok((updated, items))
    }

    /// Store a board and the complete card set GitHub returned after it
    /// changed, as one act.
    fn record_board(&self, board: &GitHubProject, items: &[GitHubProjectItem]) -> Outcome<()> {
        let board_value = serde_json::to_value(board).map_err(|e| mirror_failure(e.into()))?;
        let documents = items
            .iter()
            .map(|item| {
                serde_json::to_value(item)
                    .map(|value| Document::of(item.id.clone(), value))
                    .map_err(|e| mirror_failure(e.into()))
            })
            .collect::<Outcome<Vec<_>>>()?;
        self.mirror
            .put_project_write(
                &Scope::Projects(board.owner.clone()),
                Document::of(board.id.clone(), board_value),
                &Scope::ProjectItems(board.id.clone()),
                &documents,
            )
            .map_err(mirror_failure)
    }

    /// Serialise column writes across every process on the machine.
    ///
    /// GitHub replaces a single-select field's WHOLE option list. Two writers
    /// that both read the same list and each wrote it back with one change
    /// would have the later erase the earlier — and the writers are separate
    /// processes, a command line and a daemon, so the lock is a file.
    async fn column_lock(&self) -> Outcome<ColumnLock> {
        let path = self.mirror.path().with_extension("columns.lock");
        tokio::task::spawn_blocking(move || ColumnLock::acquire(path))
            .await
            .map_err(|e| Failure::Mirror(anyhow::anyhow!("the column lock could not be taken: {e}")))?
            .map_err(mirror_failure)
    }
}

/// An exclusive lock on a file, held while this value lives.
struct ColumnLock {
    file: File,
}

impl ColumnLock {
    fn acquire(path: PathBuf) -> anyhow::Result<Self> {
        let file = std::fs::OpenOptions::new()
            .create(true)
            .truncate(false)
            .write(true)
            .open(&path)
            .with_context(|| format!("cannot open {}", path.display()))?;
        file.lock()
            .with_context(|| format!("cannot lock {}", path.display()))?;
        Ok(Self { file })
    }
}

impl Drop for ColumnLock {
    fn drop(&mut self) {
        // Closing the file releases the lock as well; unlocking first says so
        // in the code rather than leaving it to the descriptor's end.
        let _ = self.file.unlock();
    }
}

fn updated_of(issue: &serde_json::Value) -> &str {
    issue
        .get("updated_at")
        .and_then(|value| value.as_str())
        .unwrap_or("")
}

#[cfg(test)]
#[path = "service_tests.rs"]
mod tests;