Skip to main content

orch/store/tasks/
cli_ref.rs

1//! CLI task references and their resolution
2
3use crate::store::TaskStore;
4use sqlx::Row;
5use sqlx::sqlite::SqliteRow;
6
7/// How an operator names a task on the CLI.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum CliTaskSpec {
10    /// `internal:58`
11    Internal(i64),
12    /// `owner/repo#58`
13    Issue { repo: String, number: i64 },
14    /// `58` or `#58`
15    Bare(i64),
16}
17
18/// A task picked by [`TaskStore::resolve_cli_id`].
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct CliTaskRef {
21    pub store_id: Option<i64>,
22    pub repo: String,
23    pub origin: String,
24    pub title: String,
25    pub external_id: String,
26    pub status: String,
27}
28
29impl CliTaskRef {
30    pub fn is_internal(&self) -> bool {
31        self.origin == "internal"
32    }
33
34    pub fn unsynced_issue(repo: String, number: i64) -> Self {
35        Self {
36            store_id: None,
37            repo,
38            origin: "github".to_string(),
39            title: String::new(),
40            external_id: number.to_string(),
41            status: String::new(),
42        }
43    }
44
45    pub fn display_spec(&self) -> String {
46        if self.is_internal() {
47            match self.store_id {
48                Some(id) => format!("internal:{id}"),
49                None => self.external_id.clone(),
50            }
51        } else {
52            format!("{}#{}", self.repo, self.external_id)
53        }
54    }
55
56    fn from_row(row: &SqliteRow) -> anyhow::Result<Self> {
57        let id: i64 = row.try_get("id")?;
58        let origin: String = row.try_get("origin")?;
59        let external_id: Option<String> = row.try_get("external_id")?;
60        let external_id = external_id.unwrap_or_else(|| {
61            if origin == "internal" {
62                format!("internal:{id}")
63            } else {
64                String::new()
65            }
66        });
67        Ok(Self {
68            store_id: Some(id),
69            repo: row.try_get("repo")?,
70            origin,
71            title: row.try_get("title")?,
72            external_id,
73            status: row.try_get("status")?,
74        })
75    }
76
77    fn format_match(&self) -> String {
78        format!(
79            "  {}  [{}]  {}",
80            self.display_spec(),
81            if self.status.is_empty() {
82                "unknown"
83            } else {
84                &self.status
85            },
86            if self.title.is_empty() {
87                "-"
88            } else {
89                &self.title
90            }
91        )
92    }
93}
94
95/// Parse `internal:N`, `owner/repo#N`, `#N`, or a bare number.
96pub fn parse_cli_task_spec(raw: &str) -> anyhow::Result<CliTaskSpec> {
97    let spec = raw.trim();
98    if spec.is_empty() {
99        anyhow::bail!("empty task id");
100    }
101    if let Some(suffix) = spec.strip_prefix("internal:") {
102        let number: i64 = suffix
103            .parse()
104            .map_err(|_| anyhow::anyhow!("internal task id '{suffix}' is not numeric"))?;
105        if number <= 0 {
106            anyhow::bail!("internal task id must be a positive number");
107        }
108        return Ok(CliTaskSpec::Internal(number));
109    }
110    if let Some((repo, number)) = parse_repo_issue(spec) {
111        return Ok(CliTaskSpec::Issue { repo, number });
112    }
113    let bare = spec.strip_prefix('#').unwrap_or(spec);
114    if let Ok(number) = bare.parse::<i64>()
115        && number > 0
116    {
117        return Ok(CliTaskSpec::Bare(number));
118    }
119    anyhow::bail!("invalid task id '{spec}': use a number, owner/repo#N, or internal:N")
120}
121
122fn parse_repo_issue(spec: &str) -> Option<(String, i64)> {
123    let (repo, number) = spec.rsplit_once('#')?;
124    if repo.is_empty() {
125        return None;
126    }
127    let number: i64 = number.parse().ok()?;
128    if number <= 0 {
129        return None;
130    }
131    let mut parts = repo.split('/');
132    let owner = parts.next()?;
133    let name = parts.next()?;
134    if parts.next().is_some() || owner.is_empty() || name.is_empty() {
135        return None;
136    }
137    let ok = |part: &str| {
138        part.chars()
139            .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.' | '-'))
140    };
141    if !ok(owner) || !ok(name) {
142        return None;
143    }
144    Some((repo.to_string(), number))
145}
146
147fn ambiguous_cli_id_error(spec: &str, matches: &[CliTaskRef]) -> anyhow::Error {
148    let mut lines = vec![format!("task ID {spec} matches more than one task:")];
149    for task in matches {
150        lines.push(task.format_match());
151    }
152    lines.push(ambiguous_cli_id_hint(matches));
153    anyhow::anyhow!(lines.join("\n"))
154}
155
156fn ambiguous_cli_id_hint(matches: &[CliTaskRef]) -> String {
157    let github = matches
158        .iter()
159        .find(|task| !task.is_internal())
160        .map(CliTaskRef::display_spec);
161    let internal = matches
162        .iter()
163        .find(|task| task.is_internal())
164        .map(CliTaskRef::display_spec);
165    match (github, internal) {
166        (Some(github), Some(internal)) => {
167            format!("Use {github} for the GitHub task or {internal} for the internal one")
168        }
169        _ => "Use owner/repo#N for an issue, or internal:N for an internal task.".to_string(),
170    }
171}
172
173fn dedup_cli_refs(rows: Vec<SqliteRow>) -> anyhow::Result<Vec<CliTaskRef>> {
174    let mut seen = Vec::new();
175    let mut out = Vec::new();
176    for row in rows {
177        let task = CliTaskRef::from_row(&row)?;
178        if let Some(id) = task.store_id {
179            if seen.contains(&id) {
180                continue;
181            }
182            seen.push(id);
183        }
184        out.push(task);
185    }
186    Ok(out)
187}
188
189impl TaskStore {
190    /// Resolve a task_id (e.g. "42" or "internal:3") to a store internal ID.
191    /// Returns None if the task is not in the store yet.
192    pub async fn resolve_task_id(&self, repo: &str, task_id: &str) -> anyhow::Result<Option<i64>> {
193        if let Some(suffix) = task_id.strip_prefix("internal:") {
194            // Internal tasks: look up by external_id="internal:{n}" with origin='internal'
195            if let Some(id) = self.resolve_id_by_external(repo, task_id).await? {
196                return Ok(Some(id));
197            }
198            // Fallback: try the numeric suffix as a direct store ID.
199            // Must include the repo filter to avoid resolving a task that
200            // belongs to a different repository in a multi-repo setup.
201            if let Ok(id) = suffix.parse::<i64>() {
202                let exists = sqlx::query("SELECT id FROM tasks WHERE id = ? AND repo = ?")
203                    .bind(id)
204                    .bind(repo)
205                    .fetch_optional(&self.pool)
206                    .await?;
207                if exists.is_some() {
208                    return Ok(Some(id));
209                }
210            }
211            return Ok(None);
212        }
213        // External tasks: look up by external_id using the lightweight id-only
214        // lookup to avoid deserializing the full Task row.
215        self.resolve_id_by_external(repo, task_id).await
216    }
217
218    /// Resolve a task_id globally (across all repos) when a repo-scoped lookup fails.
219    ///
220    /// Returns `(internal_id, repo)` if found unambiguously, `None` if not found,
221    /// or an error if the external_id matches tasks in multiple repos (GitHub issue
222    /// numbers are not globally unique).
223    pub async fn resolve_task_id_globally(
224        &self,
225        task_id: &str,
226    ) -> anyhow::Result<Option<(i64, String)>> {
227        if let Some(suffix) = task_id.strip_prefix("internal:") {
228            // internal:N — external_id is globally unique; primary key is also unique.
229            let row = sqlx::query("SELECT id, repo FROM tasks WHERE external_id = ?")
230                .bind(task_id)
231                .fetch_optional(&self.pool)
232                .await?;
233            if let Some(r) = row {
234                return Ok(Some((r.try_get("id")?, r.try_get("repo")?)));
235            }
236            if let Ok(id) = suffix.parse::<i64>() {
237                let row = sqlx::query("SELECT id, repo FROM tasks WHERE id = ?")
238                    .bind(id)
239                    .fetch_optional(&self.pool)
240                    .await?;
241                if let Some(r) = row {
242                    return Ok(Some((r.try_get("id")?, r.try_get("repo")?)));
243                }
244            }
245            return Ok(None);
246        }
247        // External IDs (e.g. GitHub issue numbers) may collide across repos.
248        let rows = sqlx::query("SELECT id, repo FROM tasks WHERE external_id = ?")
249            .bind(task_id)
250            .fetch_all(&self.pool)
251            .await?;
252        match rows.len() {
253            0 => Ok(None),
254            1 => Ok(Some((rows[0].try_get("id")?, rows[0].try_get("repo")?))),
255            _ => {
256                let repos: Vec<String> = rows
257                    .iter()
258                    .filter_map(|r| r.try_get::<String, _>("repo").ok())
259                    .collect();
260                anyhow::bail!(
261                    "task ID {task_id:?} is ambiguous — found in multiple repos: {}. \
262                     Run from the repo worktree so the current-repo lookup resolves it.",
263                    repos.join(", ")
264                )
265            }
266        }
267    }
268
269    /// Resolve a CLI task id. A bare number in a project is that project's issue first
270    pub async fn resolve_cli_id(
271        &self,
272        spec: &str,
273        current_repo: Option<&str>,
274    ) -> anyhow::Result<Option<CliTaskRef>> {
275        let current_repo = current_repo.filter(|repo| !repo.is_empty());
276        match parse_cli_task_spec(spec)? {
277            CliTaskSpec::Internal(number) => self.lookup_internal_cli_id(number).await,
278            CliTaskSpec::Issue { repo, number } => self.lookup_issue_cli_id(&repo, number).await,
279            CliTaskSpec::Bare(number) => {
280                if let Some(repo) = current_repo {
281                    if let Some(task) = self.lookup_issue_cli_id(repo, number).await? {
282                        return Ok(Some(task));
283                    }
284                    if let Some(task) = self.lookup_internal_in_repo(number, repo).await? {
285                        return Ok(Some(task));
286                    }
287                    return Ok(None);
288                }
289                let mut matches = self.lookup_bare_cli_id_matches(number).await?;
290                match matches.len() {
291                    0 => Ok(None),
292                    1 => Ok(matches.pop()),
293                    _ => Err(ambiguous_cli_id_error(spec, &matches)),
294                }
295            }
296        }
297    }
298
299    async fn lookup_internal_cli_id(&self, number: i64) -> anyhow::Result<Option<CliTaskRef>> {
300        let ext = format!("internal:{number}");
301        let rows = sqlx::query(
302            "SELECT id, repo, origin, title, external_id, status FROM tasks \
303             WHERE origin = 'internal' AND (id = ? OR external_id = ?) \
304             ORDER BY id",
305        )
306        .bind(number)
307        .bind(&ext)
308        .fetch_all(&self.pool)
309        .await?;
310        let mut matches = dedup_cli_refs(rows)?;
311        match matches.len() {
312            0 => Ok(None),
313            1 => Ok(matches.pop()),
314            _ => Err(ambiguous_cli_id_error(&ext, &matches)),
315        }
316    }
317
318    async fn lookup_internal_in_repo(
319        &self,
320        number: i64,
321        repo: &str,
322    ) -> anyhow::Result<Option<CliTaskRef>> {
323        let row = sqlx::query(
324            "SELECT id, repo, origin, title, external_id, status FROM tasks \
325             WHERE origin = 'internal' AND id = ? AND repo = ?",
326        )
327        .bind(number)
328        .bind(repo)
329        .fetch_optional(&self.pool)
330        .await?;
331        match row {
332            Some(row) => Ok(Some(CliTaskRef::from_row(&row)?)),
333            None => Ok(None),
334        }
335    }
336
337    async fn lookup_issue_cli_id(
338        &self,
339        repo: &str,
340        number: i64,
341    ) -> anyhow::Result<Option<CliTaskRef>> {
342        let ext = number.to_string();
343        let rows = sqlx::query(
344            "SELECT id, repo, origin, title, external_id, status FROM tasks \
345             WHERE repo = ? AND origin != 'internal' AND external_id = ? \
346             ORDER BY id",
347        )
348        .bind(repo)
349        .bind(&ext)
350        .fetch_all(&self.pool)
351        .await?;
352        let mut matches = dedup_cli_refs(rows)?;
353        match matches.len() {
354            0 => Ok(None),
355            1 => Ok(matches.pop()),
356            _ => Err(ambiguous_cli_id_error(
357                &format!("{repo}#{number}"),
358                &matches,
359            )),
360        }
361    }
362
363    async fn lookup_bare_cli_id_matches(&self, number: i64) -> anyhow::Result<Vec<CliTaskRef>> {
364        let ext = number.to_string();
365        let rows = sqlx::query(
366            "SELECT id, repo, origin, title, external_id, status FROM tasks \
367             WHERE (origin = 'internal' AND id = ?) \
368                OR (origin != 'internal' AND external_id = ?) \
369             ORDER BY repo, id",
370        )
371        .bind(number)
372        .bind(&ext)
373        .fetch_all(&self.pool)
374        .await?;
375        dedup_cli_refs(rows)
376    }
377}