Skip to main content

taskfast_cli/cmd/
task.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast task` — read + mutate operations on tasks.
3//!
4//! Read (am-e3u.4): `list` + `get`. Worker mutation (am-edc): `submit`.
5//! Poster mutations (am-plyy): `approve` / `dispute` / `cancel` — all
6//! unsigned per spec; server owns the state-machine gates and returns
7//! 403/409 for role/state violations, which we surface via `map_api_error`.
8//! The client-signed settle step (am-e3u.7, server bead am-iyp6) lives at
9//! top-level `taskfast settle` — it's a separate verb because it signs an
10//! EIP-712 `DistributionApproval`, not just an auth-gated state transition.
11//!
12//! # List semantics
13//!
14//! Three server endpoints hide behind `--kind`:
15//!
16//! | `--kind`  | Endpoint                       | Response         |
17//! |-----------|--------------------------------|------------------|
18//! | `mine`    | `GET /agents/me/tasks`         | worker's active workload (default; supports `--status`) |
19//! | `queue`   | `GET /agents/me/queue`         | assigned-but-unclaimed work |
20//! | `posted`  | `GET /agents/me/posted_tasks`  | tasks this agent posted |
21//!
22//! `--status` is only meaningful with `--kind=mine`; supplying it with any
23//! other kind is a [`CmdError::Usage`] rather than a silent no-op (ambiguous
24//! flag combinations should fail loud).
25
26use std::path::PathBuf;
27
28use clap::{Parser, Subcommand, ValueEnum};
29use serde_json::json;
30use uuid::Uuid;
31
32use super::{CmdError, CmdResult, Ctx};
33use crate::envelope::Envelope;
34
35use taskfast_client::api::types::{
36    CompletionSubmission, DisputeRequest, ListMyTasksStatus, ReassignTaskBody, TaskEditRequest,
37};
38use taskfast_client::map_api_error;
39use taskfast_client::TaskFastClient;
40
41#[derive(Debug, Subcommand)]
42pub enum Command {
43    /// List tasks (see `--kind` for which collection).
44    List(ListArgs),
45    /// GET /tasks/{id} — full task detail.
46    Get(GetArgs),
47    /// Worker: upload artifacts (if any) and submit completion.
48    Submit(SubmitArgs),
49    /// Poster: approve an under-review submission — releases payment.
50    Approve(ApproveArgs),
51    /// Poster: raise a dispute during the review window.
52    Dispute(DisputeArgs),
53    /// Poster: cancel a task before the state machine locks it in.
54    Cancel(CancelArgs),
55    /// Worker: claim an assigned task (moves `assigned` → `in_progress`).
56    Claim(IdOnlyArgs),
57    /// Worker: refuse an assigned task before claiming it.
58    Refuse(IdOnlyArgs),
59    /// Worker: resubmit completion against a disputed task (remedy flow).
60    Remedy(SubmitArgs),
61    /// Worker: concede a dispute (accepts the poster's position, no appeal).
62    Concede(IdOnlyArgs),
63    /// Worker: abort a claimed task before submission.
64    Abort(IdOnlyArgs),
65    /// Poster: list bids received on a task (paginated).
66    Bids(BidsArgs),
67    /// Poster: reassign a direct-assigned task to a different agent.
68    Reassign(ReassignArgs),
69    /// Poster: flip a direct-assigned task back to `assigned` state.
70    Reopen(IdOnlyArgs),
71    /// Poster: convert a direct-assigned task into an open bid auction.
72    Open(IdOnlyArgs),
73    /// Poster: edit task metadata (title/description/budget/windows).
74    Edit(EditArgs),
75}
76
77#[derive(Debug, Parser)]
78pub struct ReassignArgs {
79    /// Task UUID.
80    pub id: String,
81
82    /// New assignee UUID.
83    #[arg(long)]
84    pub agent_id: String,
85}
86
87#[derive(Debug, Parser)]
88pub struct EditArgs {
89    /// Task UUID.
90    pub id: String,
91
92    #[arg(long)]
93    pub title: Option<String>,
94
95    #[arg(long)]
96    pub description: Option<String>,
97
98    /// New max budget (decimal string, e.g. `100.00`).
99    #[arg(long)]
100    pub budget_max: Option<String>,
101
102    #[arg(long)]
103    pub review_window_hours: Option<i64>,
104
105    #[arg(long)]
106    pub remedy_window_hours: Option<i64>,
107}
108
109#[derive(Debug, Parser)]
110pub struct ListArgs {
111    /// Which collection to list. See module docs for the endpoint mapping.
112    #[arg(long, default_value = "mine")]
113    pub kind: ListKind,
114
115    /// Filter by task status. Only valid with `--kind=mine`; supplying it
116    /// with another kind is a usage error. When omitted on `--kind=mine`,
117    /// results are filtered client-side to the active set (assigned /
118    /// in_progress / under_review / disputed / remedied). Pass
119    /// `--status all` to restore the unfiltered historical view.
120    #[arg(long)]
121    pub status: Option<TaskStatus>,
122
123    /// Opaque pagination cursor from a previous response's `next_cursor`.
124    #[arg(long)]
125    pub cursor: Option<String>,
126
127    /// Max items per page. Defaults to 20 — keeps `task list` envelopes
128    /// compact for routine worker polling.
129    #[arg(long, default_value_t = 20)]
130    pub limit: i64,
131}
132
133#[derive(Debug, Parser)]
134pub struct GetArgs {
135    /// Task ID (UUID).
136    pub id: String,
137}
138
139/// Shared shape for subcommands that take only a task UUID and no body —
140/// claim / refuse / concede / abort. Named `IdOnlyArgs` rather than reusing
141/// `GetArgs` so the intent reads at the call site.
142#[derive(Debug, Parser)]
143pub struct IdOnlyArgs {
144    /// Task UUID.
145    pub id: String,
146}
147
148#[derive(Debug, Parser)]
149pub struct BidsArgs {
150    /// Task UUID. Must be posted by this agent; 403 otherwise.
151    pub id: String,
152
153    /// Opaque pagination cursor from a previous response's `next_cursor`.
154    #[arg(long)]
155    pub cursor: Option<String>,
156
157    /// Max items per page. Defaults to 20.
158    #[arg(long, default_value_t = 20)]
159    pub limit: i64,
160}
161
162#[derive(Debug, Parser)]
163pub struct ApproveArgs {
164    /// Task UUID. Must be in `:under_review` and posted by this agent.
165    pub id: String,
166}
167
168#[derive(Debug, Parser)]
169pub struct DisputeArgs {
170    /// Task UUID. Must be in `:under_review` and posted by this agent.
171    pub id: String,
172
173    /// Dispute reason shown to the assignee. Required; empty/whitespace
174    /// fails locally so the server never sees a 400 that we could catch.
175    #[arg(long)]
176    pub reason: String,
177}
178
179#[derive(Debug, Parser)]
180pub struct CancelArgs {
181    /// Task UUID. Allowed from open/bidding/assigned/unassigned/abandoned.
182    pub id: String,
183}
184
185#[derive(Debug, Parser)]
186pub struct SubmitArgs {
187    /// Task ID (UUID) to submit completion for.
188    pub id: String,
189
190    /// Human-readable summary of the completed work. Required by the API.
191    #[arg(long)]
192    pub summary: String,
193
194    /// Path to an artifact file. Repeat for multiple artifacts. Each file
195    /// is uploaded via multipart `POST /tasks/{id}/artifacts`; the resulting
196    /// artifact IDs are passed to the final completion submission.
197    #[arg(long)]
198    pub artifact: Vec<PathBuf>,
199}
200
201#[derive(Debug, Clone, Copy, ValueEnum)]
202pub enum ListKind {
203    /// Tasks where the agent is the assigned worker (default).
204    Mine,
205    /// Assigned-but-unclaimed queue (subset of `mine` with server-specific shape).
206    Queue,
207    /// Tasks this agent has posted.
208    Posted,
209}
210
211/// Mirror of `ListMyTasksStatus` carved as a clap-friendly `ValueEnum`.
212///
213/// The generated enum already derives `ValueEnum`-compatible serde, but
214/// clap's `ValueEnum` needs kebab-case variants and the `Display` impl
215/// already lives on the generated type — cheaper to keep a thin mirror here
216/// than to teach clap about foreign traits.
217#[derive(Debug, Clone, Copy, ValueEnum)]
218pub enum TaskStatus {
219    InProgress,
220    UnderReview,
221    Disputed,
222    Remedied,
223    Assigned,
224    All,
225}
226
227impl From<TaskStatus> for ListMyTasksStatus {
228    fn from(s: TaskStatus) -> Self {
229        match s {
230            TaskStatus::InProgress => Self::InProgress,
231            TaskStatus::UnderReview => Self::UnderReview,
232            TaskStatus::Disputed => Self::Disputed,
233            TaskStatus::Remedied => Self::Remedied,
234            TaskStatus::Assigned => Self::Assigned,
235            TaskStatus::All => Self::All,
236        }
237    }
238}
239
240pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
241    match cmd {
242        Command::List(args) => list(ctx, args).await,
243        Command::Get(args) => get(ctx, args).await,
244        Command::Submit(args) => submit(ctx, args, SubmitKind::Completion).await,
245        Command::Approve(args) => approve(ctx, args).await,
246        Command::Dispute(args) => dispute(ctx, args).await,
247        Command::Cancel(args) => cancel(ctx, args).await,
248        Command::Claim(args) => claim(ctx, args).await,
249        Command::Refuse(args) => refuse(ctx, args).await,
250        Command::Remedy(args) => submit(ctx, args, SubmitKind::Remedy).await,
251        Command::Concede(args) => concede(ctx, args).await,
252        Command::Abort(args) => abort(ctx, args).await,
253        Command::Bids(args) => bids(ctx, args).await,
254        Command::Reassign(args) => reassign(ctx, args).await,
255        Command::Reopen(args) => reopen(ctx, args).await,
256        Command::Open(args) => open(ctx, args).await,
257        Command::Edit(args) => edit(ctx, args).await,
258    }
259}
260
261/// Selects the server endpoint for a completion-shaped POST. Remedy hits
262/// `/tasks/:id/remedy` (dispute-only) while Completion hits the submission
263/// endpoint. The wire body is identical — only the verb + URL differ.
264#[derive(Debug, Clone, Copy)]
265enum SubmitKind {
266    Completion,
267    Remedy,
268}
269
270async fn approve(ctx: &Ctx, args: ApproveArgs) -> CmdResult {
271    let task_id = Uuid::parse_str(&args.id)
272        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
273    if ctx.dry_run {
274        return Ok(Envelope::success(
275            ctx.environment,
276            ctx.dry_run,
277            json!({
278                "action": "would_approve",
279                "task_id": task_id.to_string(),
280            }),
281        ));
282    }
283    let client = ctx.client()?;
284    let resp = match client.inner().approve_task(&task_id).await {
285        Ok(v) => v.into_inner(),
286        Err(e) => return Err(map_api_error(e).await.into()),
287    };
288    Ok(Envelope::success(
289        ctx.environment,
290        ctx.dry_run,
291        json!({
292            "task_id": resp.task_id,
293            "status": resp.status,
294        }),
295    ))
296}
297
298async fn dispute(ctx: &Ctx, args: DisputeArgs) -> CmdResult {
299    let task_id = Uuid::parse_str(&args.id)
300        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
301    // Server returns 400 on empty reason; catch it locally so orchestrators
302    // see a Usage error (retry-never) rather than a Validation error.
303    if args.reason.trim().is_empty() {
304        return Err(CmdError::Usage("--reason must not be empty".into()));
305    }
306    if ctx.dry_run {
307        return Ok(Envelope::success(
308            ctx.environment,
309            ctx.dry_run,
310            json!({
311                "action": "would_dispute",
312                "task_id": task_id.to_string(),
313                "reason": args.reason,
314            }),
315        ));
316    }
317    let client = ctx.client()?;
318    let body = DisputeRequest {
319        reason: args.reason.clone(),
320    };
321    let resp = match client.inner().raise_dispute(&task_id, &body).await {
322        Ok(v) => v.into_inner(),
323        Err(e) => return Err(map_api_error(e).await.into()),
324    };
325    Ok(Envelope::success(
326        ctx.environment,
327        ctx.dry_run,
328        json!({
329            "task_id": resp.task_id,
330            "status": resp.status,
331            "dispute": resp.dispute,
332            "message": resp.message,
333        }),
334    ))
335}
336
337async fn cancel(ctx: &Ctx, args: CancelArgs) -> CmdResult {
338    let task_id = Uuid::parse_str(&args.id)
339        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
340    if ctx.dry_run {
341        return Ok(Envelope::success(
342            ctx.environment,
343            ctx.dry_run,
344            json!({
345                "action": "would_cancel",
346                "task_id": task_id.to_string(),
347            }),
348        ));
349    }
350    let client = ctx.client()?;
351    let resp = match client.inner().cancel_task(&task_id).await {
352        Ok(v) => v.into_inner(),
353        Err(e) => return Err(map_api_error(e).await.into()),
354    };
355    Ok(Envelope::success(
356        ctx.environment,
357        ctx.dry_run,
358        json!({
359            "id": resp.id,
360            "status": resp.status,
361        }),
362    ))
363}
364
365async fn submit(ctx: &Ctx, args: SubmitArgs, kind: SubmitKind) -> CmdResult {
366    // Parse the task ID locally so bad input never costs a round-trip.
367    let task_id = Uuid::parse_str(&args.id)
368        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
369
370    // Resolve each artifact path upfront — fail-fast on missing files so a
371    // half-uploaded set isn't left dangling on the server.
372    let resolved: Vec<ResolvedArtifact> = args
373        .artifact
374        .iter()
375        .map(|p| ResolvedArtifact::from_path(p))
376        .collect::<Result<_, _>>()?;
377
378    let action = match kind {
379        SubmitKind::Completion => "would_submit",
380        SubmitKind::Remedy => "would_remedy",
381    };
382
383    if ctx.dry_run {
384        return Ok(Envelope::success(
385            ctx.environment,
386            ctx.dry_run,
387            json!({
388                "action": action,
389                "task_id": task_id.to_string(),
390                "summary": args.summary,
391                "artifacts": resolved.iter().map(|r| r.display_path()).collect::<Vec<_>>(),
392            }),
393        ));
394    }
395
396    let client = ctx.client()?;
397
398    // Upload each artifact, collect IDs. Sequential to keep ordering
399    // deterministic — artifact_ids are semantically ordered by the server.
400    let mut artifact_ids: Vec<uuid::Uuid> = Vec::with_capacity(resolved.len());
401    let mut uploaded_meta: Vec<serde_json::Value> = Vec::with_capacity(resolved.len());
402    for r in resolved {
403        let bytes = std::fs::read(&r.path)
404            .map_err(|e| CmdError::Usage(format!("read {}: {e}", r.path.display())))?;
405        let artifact = client
406            .upload_artifact(&task_id, r.filename.clone(), r.content_type.clone(), bytes)
407            .await
408            .map_err(CmdError::from)?;
409        artifact_ids.push(artifact.id);
410        uploaded_meta.push(json!({
411            "id": artifact.id,
412            "filename": artifact.filename,
413            "content_type": artifact.content_type,
414            "size_bytes": artifact.size_bytes,
415        }));
416    }
417
418    let body = CompletionSubmission {
419        summary: args.summary.clone(),
420        artifact_ids: artifact_ids.clone(),
421        metadata: serde_json::Map::new(),
422    };
423    let result = match kind {
424        SubmitKind::Completion => match client.inner().submit_completion(&task_id, &body).await {
425            Ok(v) => {
426                serde_json::to_value(v.into_inner()).map_err(|e| CmdError::Decode(e.to_string()))?
427            }
428            Err(e) => return Err(map_api_error(e).await.into()),
429        },
430        SubmitKind::Remedy => match client.inner().submit_remedy(&task_id, &body).await {
431            Ok(v) => {
432                serde_json::to_value(v.into_inner()).map_err(|e| CmdError::Decode(e.to_string()))?
433            }
434            Err(e) => return Err(map_api_error(e).await.into()),
435        },
436    };
437
438    Ok(Envelope::success(
439        ctx.environment,
440        ctx.dry_run,
441        json!({
442            "task_id": task_id.to_string(),
443            "artifacts": uploaded_meta,
444            "submission": result,
445        }),
446    ))
447}
448
449async fn claim(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
450    let task_id = Uuid::parse_str(&args.id)
451        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
452    if ctx.dry_run {
453        return Ok(Envelope::success(
454            ctx.environment,
455            ctx.dry_run,
456            json!({ "action": "would_claim", "task_id": task_id.to_string() }),
457        ));
458    }
459    let client = ctx.client()?;
460    let resp = match client.inner().claim_task(&task_id).await {
461        Ok(v) => v.into_inner(),
462        Err(e) => return Err(map_api_error(e).await.into()),
463    };
464    Ok(Envelope::success(
465        ctx.environment,
466        ctx.dry_run,
467        json!({ "claim": resp }),
468    ))
469}
470
471async fn refuse(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
472    let task_id = Uuid::parse_str(&args.id)
473        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
474    if ctx.dry_run {
475        return Ok(Envelope::success(
476            ctx.environment,
477            ctx.dry_run,
478            json!({ "action": "would_refuse", "task_id": task_id.to_string() }),
479        ));
480    }
481    let client = ctx.client()?;
482    let resp = match client.inner().refuse_task(&task_id).await {
483        Ok(v) => v.into_inner(),
484        Err(e) => return Err(map_api_error(e).await.into()),
485    };
486    Ok(Envelope::success(
487        ctx.environment,
488        ctx.dry_run,
489        json!({ "refuse": resp }),
490    ))
491}
492
493async fn concede(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
494    let task_id = Uuid::parse_str(&args.id)
495        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
496    if ctx.dry_run {
497        return Ok(Envelope::success(
498            ctx.environment,
499            ctx.dry_run,
500            json!({ "action": "would_concede", "task_id": task_id.to_string() }),
501        ));
502    }
503    let client = ctx.client()?;
504    let resp = match client.inner().concede_dispute(&task_id).await {
505        Ok(v) => v.into_inner(),
506        Err(e) => return Err(map_api_error(e).await.into()),
507    };
508    Ok(Envelope::success(
509        ctx.environment,
510        ctx.dry_run,
511        json!({ "concede": resp }),
512    ))
513}
514
515async fn abort(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
516    let task_id = Uuid::parse_str(&args.id)
517        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
518    if ctx.dry_run {
519        return Ok(Envelope::success(
520            ctx.environment,
521            ctx.dry_run,
522            json!({ "action": "would_abort", "task_id": task_id.to_string() }),
523        ));
524    }
525    let client = ctx.client()?;
526    let resp = match client.inner().abort_task(&task_id).await {
527        Ok(v) => v.into_inner(),
528        Err(e) => return Err(map_api_error(e).await.into()),
529    };
530    Ok(Envelope::success(
531        ctx.environment,
532        ctx.dry_run,
533        json!({ "abort": resp }),
534    ))
535}
536
537async fn reassign(ctx: &Ctx, args: ReassignArgs) -> CmdResult {
538    let task_id = Uuid::parse_str(&args.id)
539        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
540    let agent_id = Uuid::parse_str(&args.agent_id)
541        .map_err(|e| CmdError::Usage(format!("--agent-id must be a UUID: {e}")))?;
542    if ctx.dry_run {
543        return Ok(Envelope::success(
544            ctx.environment,
545            ctx.dry_run,
546            json!({
547                "action": "would_reassign",
548                "task_id": task_id.to_string(),
549                "agent_id": agent_id.to_string(),
550            }),
551        ));
552    }
553    let client = ctx.client()?;
554    let body = ReassignTaskBody { agent_id };
555    let resp = match client.inner().reassign_task(&task_id, &body).await {
556        Ok(v) => v.into_inner(),
557        Err(e) => return Err(map_api_error(e).await.into()),
558    };
559    Ok(Envelope::success(
560        ctx.environment,
561        ctx.dry_run,
562        json!({ "reassign": resp }),
563    ))
564}
565
566async fn reopen(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
567    let task_id = Uuid::parse_str(&args.id)
568        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
569    if ctx.dry_run {
570        return Ok(Envelope::success(
571            ctx.environment,
572            ctx.dry_run,
573            json!({ "action": "would_reopen", "task_id": task_id.to_string() }),
574        ));
575    }
576    let client = ctx.client()?;
577    let resp = match client.inner().reopen_task(&task_id).await {
578        Ok(v) => v.into_inner(),
579        Err(e) => return Err(map_api_error(e).await.into()),
580    };
581    Ok(Envelope::success(
582        ctx.environment,
583        ctx.dry_run,
584        json!({ "reopen": resp }),
585    ))
586}
587
588async fn open(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
589    let task_id = Uuid::parse_str(&args.id)
590        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
591    if ctx.dry_run {
592        return Ok(Envelope::success(
593            ctx.environment,
594            ctx.dry_run,
595            json!({ "action": "would_open", "task_id": task_id.to_string() }),
596        ));
597    }
598    let client = ctx.client()?;
599    let resp = match client.inner().open_task(&task_id).await {
600        Ok(v) => v.into_inner(),
601        Err(e) => return Err(map_api_error(e).await.into()),
602    };
603    Ok(Envelope::success(
604        ctx.environment,
605        ctx.dry_run,
606        json!({ "open": resp }),
607    ))
608}
609
610async fn edit(ctx: &Ctx, args: EditArgs) -> CmdResult {
611    let task_id = Uuid::parse_str(&args.id)
612        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
613    // Reject empty edits locally — server would 422 and we'd rather fail fast.
614    let any_change = args.title.is_some()
615        || args.description.is_some()
616        || args.budget_max.is_some()
617        || args.review_window_hours.is_some()
618        || args.remedy_window_hours.is_some();
619    if !any_change {
620        return Err(CmdError::Usage(
621            "edit requires at least one of --title/--description/--budget-max/--review-window-hours/--remedy-window-hours".into(),
622        ));
623    }
624    let body = TaskEditRequest {
625        title: args.title.clone(),
626        description: args.description.clone(),
627        budget_max: args.budget_max.clone(),
628        review_window_hours: args.review_window_hours,
629        remedy_window_hours: args.remedy_window_hours,
630        completion_criteria: Vec::new(),
631    };
632    if ctx.dry_run {
633        return Ok(Envelope::success(
634            ctx.environment,
635            ctx.dry_run,
636            json!({
637                "action": "would_edit",
638                "task_id": task_id.to_string(),
639                "patch": body,
640            }),
641        ));
642    }
643    let client = ctx.client()?;
644    let resp = match client.inner().edit_task(&task_id, &body).await {
645        Ok(v) => v.into_inner(),
646        Err(e) => return Err(map_api_error(e).await.into()),
647    };
648    Ok(Envelope::success(
649        ctx.environment,
650        ctx.dry_run,
651        json!({ "task": resp }),
652    ))
653}
654
655async fn bids(ctx: &Ctx, args: BidsArgs) -> CmdResult {
656    let task_id = Uuid::parse_str(&args.id)
657        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
658    let client = ctx.client()?;
659    let resp = match client
660        .inner()
661        .list_task_bids(
662            &task_id,
663            args.cursor.as_deref(),
664            taskfast_client::page_limit(args.limit),
665        )
666        .await
667    {
668        Ok(v) => v.into_inner(),
669        Err(e) => return Err(map_api_error(e).await.into()),
670    };
671    Ok(Envelope::success(
672        ctx.environment,
673        ctx.dry_run,
674        json!({
675            "task_id": task_id.to_string(),
676            "bids": resp.data,
677            "meta": resp.meta,
678        }),
679    ))
680}
681
682/// Path + derived metadata (filename, content_type) needed for multipart
683/// upload. Parsed upfront so a missing file fails before any network I/O.
684struct ResolvedArtifact {
685    path: PathBuf,
686    filename: String,
687    content_type: String,
688}
689
690impl ResolvedArtifact {
691    fn from_path(p: &std::path::Path) -> Result<Self, CmdError> {
692        if !p.exists() {
693            return Err(CmdError::Usage(format!(
694                "artifact file not found: {}",
695                p.display()
696            )));
697        }
698        let filename = p
699            .file_name()
700            .and_then(|s| s.to_str())
701            .ok_or_else(|| {
702                CmdError::Usage(format!("artifact path has no filename: {}", p.display()))
703            })?
704            .to_string();
705        let ext = p
706            .extension()
707            .and_then(|s| s.to_str())
708            .map(|s| s.to_ascii_lowercase())
709            .unwrap_or_default();
710        let content_type = content_type_for_ext(&ext).to_string();
711        Ok(Self {
712            path: p.to_path_buf(),
713            filename,
714            content_type,
715        })
716    }
717
718    fn display_path(&self) -> String {
719        self.path.display().to_string()
720    }
721}
722
723/// Map file extension to the MIME types the server accepts. Anything
724/// unrecognized falls through to `application/octet-stream`; the server
725/// rejects unsupported types with 415 which our error mapping surfaces as
726/// `CmdError::Validation`.
727pub(super) fn content_type_for_ext(ext: &str) -> &'static str {
728    match ext {
729        "txt" => "text/plain",
730        "csv" => "text/csv",
731        "json" => "application/json",
732        "xml" => "application/xml",
733        "pdf" => "application/pdf",
734        "doc" => "application/msword",
735        "png" => "image/png",
736        "jpg" | "jpeg" => "image/jpeg",
737        "gif" => "image/gif",
738        "webp" => "image/webp",
739        "svg" => "image/svg+xml",
740        "zip" => "application/zip",
741        "tar" => "application/x-tar",
742        "gz" => "application/gzip",
743        "html" | "htm" => "text/html",
744        "css" => "text/css",
745        "js" => "application/javascript",
746        _ => "application/octet-stream",
747    }
748}
749
750async fn list(ctx: &Ctx, args: ListArgs) -> CmdResult {
751    if args.status.is_some() && !matches!(args.kind, ListKind::Mine) {
752        return Err(CmdError::Usage(
753            "--status is only valid with --kind=mine".into(),
754        ));
755    }
756    let client = ctx.client()?;
757    let data = match args.kind {
758        ListKind::Mine => list_mine(&client, &args).await?,
759        ListKind::Queue => list_queue(&client, &args).await?,
760        ListKind::Posted => list_posted(&client, &args).await?,
761    };
762    Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
763}
764
765/// Task statuses considered "active" by the default `list --kind mine`
766/// filter. Everything outside this set (completed, cancelled, expired,
767/// …) is treated as closed noise and dropped unless the caller opts in
768/// with `--status all` or a specific `--status <name>`.
769const ACTIVE_STATUSES: &[&str] = &[
770    "assigned",
771    "in_progress",
772    "under_review",
773    "disputed",
774    "remedied",
775];
776
777/// Multiplier applied to `--limit` when the active-only filter is in
778/// effect. The server doesn't expose an `Active` aggregate, so we
779/// over-fetch and filter client-side to keep the user-visible page
780/// roughly limit-sized even when some rows get dropped. A strict
781/// pagination invariant is impossible without server support; this is
782/// a best-effort mitigation.
783const ACTIVE_FETCH_MULTIPLIER: i64 = 2;
784
785async fn list_mine(
786    client: &TaskFastClient,
787    args: &ListArgs,
788) -> Result<serde_json::Value, CmdError> {
789    let apply_active_filter = args.status.is_none();
790    let status = args.status.map(ListMyTasksStatus::from);
791    let fetch_limit = if apply_active_filter {
792        args.limit.saturating_mul(ACTIVE_FETCH_MULTIPLIER)
793    } else {
794        args.limit
795    };
796    let resp = match client
797        .inner()
798        .list_my_tasks(
799            args.cursor.as_deref(),
800            taskfast_client::page_limit(fetch_limit),
801            status,
802        )
803        .await
804    {
805        Ok(v) => v.into_inner(),
806        Err(e) => return Err(map_api_error(e).await.into()),
807    };
808    let tasks = if apply_active_filter {
809        let limit_usize = usize::try_from(args.limit.max(0)).unwrap_or(usize::MAX);
810        resp.data
811            .into_iter()
812            .filter(|t| ACTIVE_STATUSES.contains(&t.status.as_str()))
813            .take(limit_usize)
814            .collect::<Vec<_>>()
815    } else {
816        resp.data
817    };
818    Ok(json!({
819        "kind": "mine",
820        "tasks": tasks,
821        "meta": resp.meta,
822    }))
823}
824
825async fn list_queue(
826    client: &TaskFastClient,
827    args: &ListArgs,
828) -> Result<serde_json::Value, CmdError> {
829    let resp = match client
830        .inner()
831        .get_agent_queue(
832            args.cursor.as_deref(),
833            taskfast_client::page_limit(args.limit),
834        )
835        .await
836    {
837        Ok(v) => v.into_inner(),
838        Err(e) => return Err(map_api_error(e).await.into()),
839    };
840    Ok(json!({
841        "kind": "queue",
842        "tasks": resp.data,
843        "meta": resp.meta,
844    }))
845}
846
847async fn list_posted(
848    client: &TaskFastClient,
849    args: &ListArgs,
850) -> Result<serde_json::Value, CmdError> {
851    let resp = match client
852        .inner()
853        .get_agent_posted_tasks(
854            args.cursor.as_deref(),
855            taskfast_client::page_limit(args.limit),
856        )
857        .await
858    {
859        Ok(v) => v.into_inner(),
860        Err(e) => return Err(map_api_error(e).await.into()),
861    };
862    Ok(json!({
863        "kind": "posted",
864        "tasks": resp.data,
865        "meta": resp.meta,
866    }))
867}
868
869async fn get(ctx: &Ctx, args: GetArgs) -> CmdResult {
870    // Validate UUID locally — bad IDs shouldn't cost a round-trip.
871    let id = Uuid::parse_str(&args.id)
872        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
873    let client = ctx.client()?;
874    let task = match client.inner().get_task(&id).await {
875        Ok(v) => v.into_inner(),
876        Err(e) => return Err(map_api_error(e).await.into()),
877    };
878    Ok(Envelope::success(
879        ctx.environment,
880        ctx.dry_run,
881        json!({ "task": task }),
882    ))
883}
884
885#[cfg(test)]
886mod tests {
887    use super::*;
888
889    #[test]
890    fn task_status_maps_to_generated_enum() {
891        // Pin the mapping — changing it would be a silent wire-shape change.
892        for (ours, theirs) in [
893            (TaskStatus::InProgress, ListMyTasksStatus::InProgress),
894            (TaskStatus::UnderReview, ListMyTasksStatus::UnderReview),
895            (TaskStatus::Disputed, ListMyTasksStatus::Disputed),
896            (TaskStatus::Remedied, ListMyTasksStatus::Remedied),
897            (TaskStatus::Assigned, ListMyTasksStatus::Assigned),
898            (TaskStatus::All, ListMyTasksStatus::All),
899        ] {
900            // `ListMyTasksStatus: Display` — compare as strings to avoid
901            // needing PartialEq on the foreign type.
902            assert_eq!(
903                ListMyTasksStatus::from(ours).to_string(),
904                theirs.to_string()
905            );
906        }
907    }
908}