Skip to main content

comindly_api/
team.rs

1use anyhow::Result;
2use serde::{Deserialize, Serialize};
3
4/// What everyone using an index shares; `None` leaves comindly's default.
5#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
6pub struct TeamSettings {
7    #[serde(default, skip_serializing_if = "Option::is_none")]
8    pub name: Option<String>,
9    #[serde(default, skip_serializing_if = "Option::is_none")]
10    pub llm_base_url: Option<String>,
11    #[serde(default, skip_serializing_if = "Option::is_none")]
12    pub llm_model: Option<String>,
13    /// The model for one LLM task in place of `llm_model`.
14    #[serde(default, skip_serializing_if = "Option::is_none")]
15    pub llm_model_summary: Option<String>,
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    pub llm_model_guide: Option<String>,
18    #[serde(default, skip_serializing_if = "Option::is_none")]
19    pub llm_model_flow: Option<String>,
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    pub embed_model: Option<String>,
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub enrich: Option<bool>,
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub flows: Option<bool>,
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub guide: Option<bool>,
28    /// Search embeddings when indexing.
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub embed: Option<bool>,
31    /// Most symbols summarised by the LLM, most central first.
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub max_enrich: Option<usize>,
34    /// Most flows given a written walkthrough, furthest-reaching first.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub max_flows: Option<usize>,
37    /// LLM requests in flight at once.
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub llm_concurrency: Option<usize>,
40    /// The LLM's price in USD per million input tokens, to show what indexing costs.
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub llm_price_in: Option<f64>,
43    /// The LLM's price in USD per million output tokens.
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub llm_price_out: Option<f64>,
46    /// What MCP tools return as text: `md` (default) or `json`; the JSON is always attached too.
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub format: Option<String>,
49    /// SCIP use when indexing: `auto` (default), `require` or `off`.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub scip: Option<String>,
52    /// Re-index when a listed repository's default branch moves on its remote.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub auto_index: Option<bool>,
55    /// Also run the LLM steps on automatic re-indexes, for new or changed code only.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub auto_index_llm: Option<bool>,
58    /// Minutes between checks whether a default branch moved (default 5).
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub auto_index_minutes: Option<usize>,
61    /// Days without a post after which indexing closes a discussion (default 30, 0 never).
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    pub discussion_inactive_days: Option<usize>,
64    /// Clone URLs of the team's repositories, so everyone can get the same set.
65    #[serde(default, skip_serializing_if = "Vec::is_empty")]
66    pub repos: Vec<String>,
67    /// Teams labelling repositories; `None` until set up, so an upgrade can backfill once.
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub teams: Option<Vec<TeamDef>>,
70}
71
72/// A team: a label on repositories (by indexed name); a repository may carry several.
73#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
74pub struct TeamDef {
75    pub name: String,
76    #[serde(default)]
77    pub repos: Vec<String>,
78    /// Members' emails, lowercase; what they see first and how their notes are marked.
79    #[serde(default)]
80    pub members: Vec<String>,
81    /// How notes from people outside the team on its code count.
82    #[serde(default)]
83    pub incoming: Incoming,
84}
85
86impl TeamSettings {
87    pub fn team_list(&self) -> &[TeamDef] {
88        self.teams.as_deref().unwrap_or_default()
89    }
90
91    /// Teams labelling `repo`, in the order they were defined.
92    pub fn teams_of(&self, repo: &str) -> Vec<String> {
93        self.team_list()
94            .iter()
95            .filter(|t| t.repos.iter().any(|r| r == repo))
96            .map(|t| t.name.clone())
97            .collect()
98    }
99
100    /// The teams owning `repos` when the writer is in none of them; `None` inside or unlabelled.
101    pub fn outside(&self, writer: &[String], repos: &[&str]) -> Option<Vec<String>> {
102        if writer.is_empty() {
103            return None;
104        }
105        let mut owners: Vec<String> = Vec::new();
106        for r in repos {
107            for t in self.teams_of(r) {
108                if !owners.contains(&t) {
109                    owners.push(t);
110                }
111            }
112        }
113        let inside = owners
114            .iter()
115            .any(|o| writer.iter().any(|w| w.eq_ignore_ascii_case(o)));
116        (!owners.is_empty() && !inside).then_some(owners)
117    }
118
119    /// Refuses a note from outside when every team owning `repos` is closed to them.
120    pub fn accepts(&self, writer: &[String], repos: &[&str]) -> Result<()> {
121        if let Some(owners) = self.outside(writer, repos) {
122            let (takes, their) = if owners.len() == 1 {
123                ("takes", "its")
124            } else {
125                ("take", "their")
126            };
127            anyhow::ensure!(
128                self.incoming(&owners) != Incoming::Closed,
129                "{} {takes} notes on this code only from {their} members; ask one of them to record it",
130                owners.join(" and ")
131            );
132        }
133        Ok(())
134    }
135
136    /// The most open policy among `owners` for notes from outside.
137    pub fn incoming(&self, owners: &[String]) -> Incoming {
138        self.team_list()
139            .iter()
140            .filter(|t| owners.iter().any(|o| o.eq_ignore_ascii_case(&t.name)))
141            .map(|t| t.incoming)
142            .min()
143            .unwrap_or_default()
144    }
145
146    /// Teams `email` belongs to.
147    pub fn teams_of_member(&self, email: &str) -> Vec<String> {
148        let email = email.trim().to_lowercase();
149        self.team_list()
150            .iter()
151            .filter(|t| t.members.contains(&email))
152            .map(|t| t.name.clone())
153            .collect()
154    }
155
156    /// Put `email` in exactly the existing teams named in `teams`.
157    pub fn set_member(&mut self, email: &str, teams: &[String]) -> Result<()> {
158        let email = email.trim().to_lowercase();
159        for n in teams {
160            anyhow::ensure!(
161                self.team_list()
162                    .iter()
163                    .any(|t| t.name.eq_ignore_ascii_case(n.trim())),
164                "there is no team called {n}"
165            );
166        }
167        for t in self.teams.iter_mut().flatten() {
168            let want = teams.iter().any(|n| n.trim().eq_ignore_ascii_case(&t.name));
169            t.members.retain(|m| *m != email);
170            if want {
171                t.members.push(email.clone());
172            }
173        }
174        Ok(())
175    }
176
177    /// Whether `repo` is in view for the `selected` teams (empty: everything; `none`: unlabelled).
178    pub fn in_view(&self, repo: &str, selected: &[String]) -> bool {
179        if selected.is_empty() {
180            return true;
181        }
182        let labels = self.teams_of(repo);
183        selected.iter().any(|s| match s.as_str() {
184            UNASSIGNED => labels.is_empty(),
185            name => labels.iter().any(|l| l.eq_ignore_ascii_case(name)),
186        })
187    }
188
189    /// Trim names, drop empty and duplicate teams and repeated repositories.
190    pub fn tidy_teams(&mut self) -> Result<()> {
191        let Some(teams) = self.teams.as_mut() else {
192            return Ok(());
193        };
194        let mut seen = std::collections::HashSet::new();
195        for t in teams.iter_mut() {
196            t.name = t.name.trim().to_string();
197            anyhow::ensure!(!t.name.is_empty(), "a team needs a name");
198            anyhow::ensure!(
199                !t.name.eq_ignore_ascii_case(UNASSIGNED),
200                "`{UNASSIGNED}` is reserved for repositories without a team"
201            );
202            anyhow::ensure!(
203                seen.insert(t.name.to_lowercase()),
204                "two teams are called {}",
205                t.name
206            );
207            let mut repos = std::collections::BTreeSet::new();
208            t.repos.retain(|r| repos.insert(r.clone()));
209            for m in t.members.iter_mut() {
210                *m = m.trim().to_lowercase();
211            }
212            let mut members = std::collections::BTreeSet::new();
213            t.members
214                .retain(|m| !m.is_empty() && members.insert(m.clone()));
215        }
216        Ok(())
217    }
218
219    /// Remove `repo` from every team.
220    pub fn unlabel(&mut self, repo: &str) {
221        for t in self.teams.iter_mut().flatten() {
222            t.repos.retain(|r| r != repo);
223        }
224    }
225
226    /// Set exactly `teams` on `repo`, creating teams that don't exist yet.
227    pub fn label(&mut self, repo: &str, teams: &[String]) {
228        let list = self.teams.get_or_insert_with(Vec::new);
229        for t in list.iter_mut() {
230            let want = teams.iter().any(|n| n.trim().eq_ignore_ascii_case(&t.name));
231            let has = t.repos.iter().any(|r| r == repo);
232            match (want, has) {
233                (true, false) => t.repos.push(repo.to_string()),
234                (false, true) => t.repos.retain(|r| r != repo),
235                _ => {}
236            }
237        }
238        for n in teams.iter().map(|n| n.trim()).filter(|n| !n.is_empty()) {
239            if !list.iter().any(|t| t.name.eq_ignore_ascii_case(n)) {
240                list.push(TeamDef {
241                    name: n.to_string(),
242                    repos: vec![repo.to_string()],
243                    ..Default::default()
244                });
245            }
246        }
247    }
248
249    /// A first team named after the org with these repos and members, when teams were never set up.
250    pub fn backfill(&self, repos: &[String], members: &[String]) -> Option<TeamSettings> {
251        let name = self.name.as_deref()?.trim();
252        if self.teams.is_some() || name.is_empty() {
253            return None;
254        }
255        let mut repos = repos.to_vec();
256        repos.sort();
257        repos.dedup();
258        let mut next = TeamSettings {
259            teams: Some(vec![TeamDef {
260                name: name.to_string(),
261                repos,
262                members: members.to_vec(),
263                ..Default::default()
264            }]),
265            ..self.clone()
266        };
267        next.tidy_teams().ok()?;
268        Some(next)
269    }
270}
271
272/// Ordered from most to least open.
273#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
274#[serde(rename_all = "lowercase")]
275pub enum Incoming {
276    Open,
277    #[default]
278    Review,
279    Closed,
280}
281
282/// The `none` filter value: repositories no team labels.
283pub const UNASSIGNED: &str = "none";