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