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
206/// A reference to an issue the store has not synced yet, or the error for a task that is not there
207fn unsynced_ref(spec: &str, current_repo: Option<&str>, shown: &str) -> anyhow::Result<CliTaskRef> {
208    match parse_cli_task_spec(spec)? {
209        CliTaskSpec::Issue { repo, number } => Ok(CliTaskRef::unsynced_issue(repo, number)),
210        CliTaskSpec::Bare(number) => {
211            let repo = current_repo
212                .map(str::to_string)
213                .ok_or_else(|| anyhow::anyhow!("task not found: {shown}"))?;
214            Ok(CliTaskRef::unsynced_issue(repo, number))
215        }
216        CliTaskSpec::Internal(_) => anyhow::bail!("internal task '{shown}' not found"),
217    }
218}
219
220impl TaskStore {
221    /// The task `spec` names, or for an issue number the store has not synced yet, a reference to
222    /// it. `shown` is the id as the operator typed it, for the error
223    pub async fn resolve_cli_ref(
224        &self,
225        spec: &str,
226        current_repo: Option<&str>,
227        shown: &str,
228    ) -> anyhow::Result<CliTaskRef> {
229        match self.resolve_cli_id(spec, current_repo).await? {
230            Some(task) => Ok(task),
231            None => unsynced_ref(spec, current_repo, shown),
232        }
233    }
234
235    /// Resolve a task_id (e.g. "42" or "internal:3") to a store internal ID.
236    /// Returns None if the task is not in the store yet.
237    pub async fn resolve_task_id(&self, repo: &str, task_id: &str) -> anyhow::Result<Option<i64>> {
238        if let Some(suffix) = task_id.strip_prefix("internal:") {
239            // Internal tasks: look up by external_id="internal:{n}" with origin='internal'
240            if let Some(id) = self.resolve_id_by_external(repo, task_id).await? {
241                return Ok(Some(id));
242            }
243            // Fallback: try the numeric suffix as a direct store ID.
244            // Must include the repo filter to avoid resolving a task that
245            // belongs to a different repository in a multi-repo setup.
246            if let Ok(id) = suffix.parse::<i64>() {
247                let exists = sqlx::query("SELECT id FROM tasks WHERE id = ? AND repo = ?")
248                    .bind(id)
249                    .bind(repo)
250                    .fetch_optional(&self.pool)
251                    .await?;
252                if exists.is_some() {
253                    return Ok(Some(id));
254                }
255            }
256            return Ok(None);
257        }
258        // External tasks: look up by external_id using the lightweight id-only
259        // lookup to avoid deserializing the full Task row.
260        self.resolve_id_by_external(repo, task_id).await
261    }
262
263    /// Resolve a task_id globally (across all repos) when a repo-scoped lookup fails.
264    ///
265    /// Returns `(internal_id, repo)` if found unambiguously, `None` if not found,
266    /// or an error if the external_id matches tasks in multiple repos (GitHub issue
267    /// numbers are not globally unique).
268    pub async fn resolve_task_id_globally(
269        &self,
270        task_id: &str,
271    ) -> anyhow::Result<Option<(i64, String)>> {
272        if let Some(suffix) = task_id.strip_prefix("internal:") {
273            // internal:N — external_id is globally unique; primary key is also unique.
274            let row = sqlx::query("SELECT id, repo FROM tasks WHERE external_id = ?")
275                .bind(task_id)
276                .fetch_optional(&self.pool)
277                .await?;
278            if let Some(r) = row {
279                return Ok(Some((r.try_get("id")?, r.try_get("repo")?)));
280            }
281            if let Ok(id) = suffix.parse::<i64>() {
282                let row = sqlx::query("SELECT id, repo FROM tasks WHERE id = ?")
283                    .bind(id)
284                    .fetch_optional(&self.pool)
285                    .await?;
286                if let Some(r) = row {
287                    return Ok(Some((r.try_get("id")?, r.try_get("repo")?)));
288                }
289            }
290            return Ok(None);
291        }
292        // External IDs (e.g. GitHub issue numbers) may collide across repos.
293        let rows = sqlx::query("SELECT id, repo FROM tasks WHERE external_id = ?")
294            .bind(task_id)
295            .fetch_all(&self.pool)
296            .await?;
297        match rows.len() {
298            0 => Ok(None),
299            1 => Ok(Some((rows[0].try_get("id")?, rows[0].try_get("repo")?))),
300            _ => {
301                let repos: Vec<String> = rows
302                    .iter()
303                    .filter_map(|r| r.try_get::<String, _>("repo").ok())
304                    .collect();
305                anyhow::bail!(
306                    "task ID {task_id:?} is ambiguous — found in multiple repos: {}. \
307                     Run from the repo worktree so the current-repo lookup resolves it.",
308                    repos.join(", ")
309                )
310            }
311        }
312    }
313
314    /// Resolve a CLI task id. A bare number in a project is that project's issue first
315    pub async fn resolve_cli_id(
316        &self,
317        spec: &str,
318        current_repo: Option<&str>,
319    ) -> anyhow::Result<Option<CliTaskRef>> {
320        let current_repo = current_repo.filter(|repo| !repo.is_empty());
321        match parse_cli_task_spec(spec)? {
322            CliTaskSpec::Internal(number) => self.lookup_internal_cli_id(number).await,
323            CliTaskSpec::Issue { repo, number } => self.lookup_issue_cli_id(&repo, number).await,
324            CliTaskSpec::Bare(number) => {
325                if let Some(repo) = current_repo {
326                    if let Some(task) = self.lookup_issue_cli_id(repo, number).await? {
327                        return Ok(Some(task));
328                    }
329                    if let Some(task) = self.lookup_internal_in_repo(number, repo).await? {
330                        return Ok(Some(task));
331                    }
332                    return Ok(None);
333                }
334                let mut matches = self.lookup_bare_cli_id_matches(number).await?;
335                match matches.len() {
336                    0 => Ok(None),
337                    1 => Ok(matches.pop()),
338                    _ => Err(ambiguous_cli_id_error(spec, &matches)),
339                }
340            }
341        }
342    }
343
344    async fn lookup_internal_cli_id(&self, number: i64) -> anyhow::Result<Option<CliTaskRef>> {
345        let ext = format!("internal:{number}");
346        let rows = sqlx::query(
347            "SELECT id, repo, origin, title, external_id, status FROM tasks \
348             WHERE origin = 'internal' AND (id = ? OR external_id = ?) \
349             ORDER BY id",
350        )
351        .bind(number)
352        .bind(&ext)
353        .fetch_all(&self.pool)
354        .await?;
355        let mut matches = dedup_cli_refs(rows)?;
356        match matches.len() {
357            0 => Ok(None),
358            1 => Ok(matches.pop()),
359            _ => Err(ambiguous_cli_id_error(&ext, &matches)),
360        }
361    }
362
363    async fn lookup_internal_in_repo(
364        &self,
365        number: i64,
366        repo: &str,
367    ) -> anyhow::Result<Option<CliTaskRef>> {
368        let row = sqlx::query(
369            "SELECT id, repo, origin, title, external_id, status FROM tasks \
370             WHERE origin = 'internal' AND id = ? AND repo = ?",
371        )
372        .bind(number)
373        .bind(repo)
374        .fetch_optional(&self.pool)
375        .await?;
376        match row {
377            Some(row) => Ok(Some(CliTaskRef::from_row(&row)?)),
378            None => Ok(None),
379        }
380    }
381
382    async fn lookup_issue_cli_id(
383        &self,
384        repo: &str,
385        number: i64,
386    ) -> anyhow::Result<Option<CliTaskRef>> {
387        let ext = number.to_string();
388        let rows = sqlx::query(
389            "SELECT id, repo, origin, title, external_id, status FROM tasks \
390             WHERE repo = ? AND origin != 'internal' AND external_id = ? \
391             ORDER BY id",
392        )
393        .bind(repo)
394        .bind(&ext)
395        .fetch_all(&self.pool)
396        .await?;
397        let mut matches = dedup_cli_refs(rows)?;
398        match matches.len() {
399            0 => Ok(None),
400            1 => Ok(matches.pop()),
401            _ => Err(ambiguous_cli_id_error(
402                &format!("{repo}#{number}"),
403                &matches,
404            )),
405        }
406    }
407
408    async fn lookup_bare_cli_id_matches(&self, number: i64) -> anyhow::Result<Vec<CliTaskRef>> {
409        let ext = number.to_string();
410        let rows = sqlx::query(
411            "SELECT id, repo, origin, title, external_id, status FROM tasks \
412             WHERE (origin = 'internal' AND id = ?) \
413                OR (origin != 'internal' AND external_id = ?) \
414             ORDER BY repo, id",
415        )
416        .bind(number)
417        .bind(&ext)
418        .fetch_all(&self.pool)
419        .await?;
420        dedup_cli_refs(rows)
421    }
422}