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, ListMyTasksStatusItem, 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. Omit it to get the server's
117    /// active set (assigned / in_progress / under_review / disputed /
118    /// remedied) — this endpoint only ever returns active-state tasks, so
119    /// the active set is both the default and the maximum.
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    /// Page size requested from the server. Defaults to 20 — keeps
128    /// `task list` envelopes 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 `ListMyTasksStatusItem` 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}
225
226impl From<TaskStatus> for ListMyTasksStatusItem {
227    fn from(s: TaskStatus) -> Self {
228        match s {
229            TaskStatus::InProgress => Self::InProgress,
230            TaskStatus::UnderReview => Self::UnderReview,
231            TaskStatus::Disputed => Self::Disputed,
232            TaskStatus::Remedied => Self::Remedied,
233            TaskStatus::Assigned => Self::Assigned,
234        }
235    }
236}
237
238pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
239    match cmd {
240        Command::List(args) => list(ctx, args).await,
241        Command::Get(args) => get(ctx, args).await,
242        Command::Submit(args) => submit(ctx, args, SubmitKind::Completion).await,
243        Command::Approve(args) => approve(ctx, args).await,
244        Command::Dispute(args) => dispute(ctx, args).await,
245        Command::Cancel(args) => cancel(ctx, args).await,
246        Command::Claim(args) => claim(ctx, args).await,
247        Command::Refuse(args) => refuse(ctx, args).await,
248        Command::Remedy(args) => submit(ctx, args, SubmitKind::Remedy).await,
249        Command::Concede(args) => concede(ctx, args).await,
250        Command::Abort(args) => abort(ctx, args).await,
251        Command::Bids(args) => bids(ctx, args).await,
252        Command::Reassign(args) => reassign(ctx, args).await,
253        Command::Reopen(args) => reopen(ctx, args).await,
254        Command::Open(args) => open(ctx, args).await,
255        Command::Edit(args) => edit(ctx, args).await,
256    }
257}
258
259/// Selects the server endpoint for a completion-shaped POST. Remedy hits
260/// `/tasks/:id/remedy` (dispute-only) while Completion hits the submission
261/// endpoint. The wire body is identical — only the verb + URL differ.
262#[derive(Debug, Clone, Copy)]
263enum SubmitKind {
264    Completion,
265    Remedy,
266}
267
268async fn approve(ctx: &Ctx, args: ApproveArgs) -> CmdResult {
269    let task_id = Uuid::parse_str(&args.id)
270        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
271    if ctx.dry_run {
272        return Ok(Envelope::success(
273            ctx.environment,
274            ctx.dry_run,
275            json!({
276                "action": "would_approve",
277                "task_id": task_id.to_string(),
278            }),
279        ));
280    }
281    let client = ctx.client()?;
282    let resp = match client.inner().approve_task(&task_id).await {
283        Ok(v) => v.into_inner(),
284        Err(e) => return Err(map_api_error(e).await.into()),
285    };
286    Ok(Envelope::success(
287        ctx.environment,
288        ctx.dry_run,
289        json!({
290            "task_id": resp.task_id,
291            "status": resp.status,
292        }),
293    ))
294}
295
296async fn dispute(ctx: &Ctx, args: DisputeArgs) -> CmdResult {
297    let task_id = Uuid::parse_str(&args.id)
298        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
299    // Server returns 400 on empty reason; catch it locally so orchestrators
300    // see a Usage error (retry-never) rather than a Validation error.
301    if args.reason.trim().is_empty() {
302        return Err(CmdError::Usage("--reason must not be empty".into()));
303    }
304    if ctx.dry_run {
305        return Ok(Envelope::success(
306            ctx.environment,
307            ctx.dry_run,
308            json!({
309                "action": "would_dispute",
310                "task_id": task_id.to_string(),
311                "reason": args.reason,
312            }),
313        ));
314    }
315    let client = ctx.client()?;
316    let body = DisputeRequest {
317        reason: args.reason.clone(),
318    };
319    let resp = match client.inner().raise_dispute(&task_id, &body).await {
320        Ok(v) => v.into_inner(),
321        Err(e) => return Err(map_api_error(e).await.into()),
322    };
323    Ok(Envelope::success(
324        ctx.environment,
325        ctx.dry_run,
326        json!({
327            "task_id": resp.task_id,
328            "status": resp.status,
329            "dispute": resp.dispute,
330            "message": resp.message,
331        }),
332    ))
333}
334
335async fn cancel(ctx: &Ctx, args: CancelArgs) -> CmdResult {
336    let task_id = Uuid::parse_str(&args.id)
337        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
338    if ctx.dry_run {
339        return Ok(Envelope::success(
340            ctx.environment,
341            ctx.dry_run,
342            json!({
343                "action": "would_cancel",
344                "task_id": task_id.to_string(),
345            }),
346        ));
347    }
348    let client = ctx.client()?;
349    let resp = match client.inner().cancel_task(&task_id).await {
350        Ok(v) => v.into_inner(),
351        Err(e) => return Err(map_api_error(e).await.into()),
352    };
353    Ok(Envelope::success(
354        ctx.environment,
355        ctx.dry_run,
356        json!({
357            "id": resp.id,
358            "status": resp.status,
359        }),
360    ))
361}
362
363async fn submit(ctx: &Ctx, args: SubmitArgs, kind: SubmitKind) -> CmdResult {
364    // Parse the task ID locally so bad input never costs a round-trip.
365    let task_id = Uuid::parse_str(&args.id)
366        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
367
368    // Resolve each artifact path upfront — fail-fast on missing files so a
369    // half-uploaded set isn't left dangling on the server.
370    let resolved: Vec<ResolvedArtifact> = args
371        .artifact
372        .iter()
373        .map(|p| ResolvedArtifact::from_path(p))
374        .collect::<Result<_, _>>()?;
375
376    let action = match kind {
377        SubmitKind::Completion => "would_submit",
378        SubmitKind::Remedy => "would_remedy",
379    };
380
381    if ctx.dry_run {
382        return Ok(Envelope::success(
383            ctx.environment,
384            ctx.dry_run,
385            json!({
386                "action": action,
387                "task_id": task_id.to_string(),
388                "summary": args.summary,
389                "artifacts": resolved.iter().map(|r| r.display_path()).collect::<Vec<_>>(),
390            }),
391        ));
392    }
393
394    let client = ctx.client()?;
395
396    // Upload each artifact, collect IDs. Sequential to keep ordering
397    // deterministic — artifact_ids are semantically ordered by the server.
398    let mut artifact_ids: Vec<uuid::Uuid> = Vec::with_capacity(resolved.len());
399    let mut uploaded_meta: Vec<serde_json::Value> = Vec::with_capacity(resolved.len());
400    for r in resolved {
401        let bytes = std::fs::read(&r.path)
402            .map_err(|e| CmdError::Usage(format!("read {}: {e}", r.path.display())))?;
403        let artifact = client
404            .upload_artifact(&task_id, r.filename.clone(), r.content_type.clone(), bytes)
405            .await
406            .map_err(CmdError::from)?;
407        artifact_ids.push(artifact.id);
408        uploaded_meta.push(json!({
409            "id": artifact.id,
410            "filename": artifact.filename,
411            "content_type": artifact.content_type,
412            "size_bytes": artifact.size_bytes,
413        }));
414    }
415
416    let body = CompletionSubmission {
417        summary: args.summary.clone(),
418        artifact_ids: artifact_ids.clone(),
419        metadata: serde_json::Map::new(),
420    };
421    let result = match kind {
422        SubmitKind::Completion => match client.inner().submit_completion(&task_id, &body).await {
423            Ok(v) => {
424                serde_json::to_value(v.into_inner()).map_err(|e| CmdError::Decode(e.to_string()))?
425            }
426            Err(e) => return Err(map_api_error(e).await.into()),
427        },
428        SubmitKind::Remedy => match client.inner().submit_remedy(&task_id, &body).await {
429            Ok(v) => {
430                serde_json::to_value(v.into_inner()).map_err(|e| CmdError::Decode(e.to_string()))?
431            }
432            Err(e) => return Err(map_api_error(e).await.into()),
433        },
434    };
435
436    Ok(Envelope::success(
437        ctx.environment,
438        ctx.dry_run,
439        json!({
440            "task_id": task_id.to_string(),
441            "artifacts": uploaded_meta,
442            "submission": result,
443        }),
444    ))
445}
446
447async fn claim(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
448    let task_id = Uuid::parse_str(&args.id)
449        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
450    if ctx.dry_run {
451        return Ok(Envelope::success(
452            ctx.environment,
453            ctx.dry_run,
454            json!({ "action": "would_claim", "task_id": task_id.to_string() }),
455        ));
456    }
457    let client = ctx.client()?;
458    let resp = match client.inner().claim_task(&task_id).await {
459        Ok(v) => v.into_inner(),
460        Err(e) => return Err(map_api_error(e).await.into()),
461    };
462    Ok(Envelope::success(
463        ctx.environment,
464        ctx.dry_run,
465        json!({ "claim": resp }),
466    ))
467}
468
469async fn refuse(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
470    let task_id = Uuid::parse_str(&args.id)
471        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
472    if ctx.dry_run {
473        return Ok(Envelope::success(
474            ctx.environment,
475            ctx.dry_run,
476            json!({ "action": "would_refuse", "task_id": task_id.to_string() }),
477        ));
478    }
479    let client = ctx.client()?;
480    let resp = match client.inner().refuse_task(&task_id).await {
481        Ok(v) => v.into_inner(),
482        Err(e) => return Err(map_api_error(e).await.into()),
483    };
484    Ok(Envelope::success(
485        ctx.environment,
486        ctx.dry_run,
487        json!({ "refuse": resp }),
488    ))
489}
490
491async fn concede(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
492    let task_id = Uuid::parse_str(&args.id)
493        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
494    if ctx.dry_run {
495        return Ok(Envelope::success(
496            ctx.environment,
497            ctx.dry_run,
498            json!({ "action": "would_concede", "task_id": task_id.to_string() }),
499        ));
500    }
501    let client = ctx.client()?;
502    let resp = match client.inner().concede_dispute(&task_id).await {
503        Ok(v) => v.into_inner(),
504        Err(e) => return Err(map_api_error(e).await.into()),
505    };
506    Ok(Envelope::success(
507        ctx.environment,
508        ctx.dry_run,
509        json!({ "concede": resp }),
510    ))
511}
512
513async fn abort(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
514    let task_id = Uuid::parse_str(&args.id)
515        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
516    if ctx.dry_run {
517        return Ok(Envelope::success(
518            ctx.environment,
519            ctx.dry_run,
520            json!({ "action": "would_abort", "task_id": task_id.to_string() }),
521        ));
522    }
523    let client = ctx.client()?;
524    let resp = match client.inner().abort_task(&task_id).await {
525        Ok(v) => v.into_inner(),
526        Err(e) => return Err(map_api_error(e).await.into()),
527    };
528    Ok(Envelope::success(
529        ctx.environment,
530        ctx.dry_run,
531        json!({ "abort": resp }),
532    ))
533}
534
535async fn reassign(ctx: &Ctx, args: ReassignArgs) -> CmdResult {
536    let task_id = Uuid::parse_str(&args.id)
537        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
538    let agent_id = Uuid::parse_str(&args.agent_id)
539        .map_err(|e| CmdError::Usage(format!("--agent-id must be a UUID: {e}")))?;
540    if ctx.dry_run {
541        return Ok(Envelope::success(
542            ctx.environment,
543            ctx.dry_run,
544            json!({
545                "action": "would_reassign",
546                "task_id": task_id.to_string(),
547                "agent_id": agent_id.to_string(),
548            }),
549        ));
550    }
551    let client = ctx.client()?;
552    let body = ReassignTaskBody { agent_id };
553    let resp = match client.inner().reassign_task(&task_id, &body).await {
554        Ok(v) => v.into_inner(),
555        Err(e) => return Err(map_api_error(e).await.into()),
556    };
557    Ok(Envelope::success(
558        ctx.environment,
559        ctx.dry_run,
560        json!({ "reassign": resp }),
561    ))
562}
563
564async fn reopen(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
565    let task_id = Uuid::parse_str(&args.id)
566        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
567    if ctx.dry_run {
568        return Ok(Envelope::success(
569            ctx.environment,
570            ctx.dry_run,
571            json!({ "action": "would_reopen", "task_id": task_id.to_string() }),
572        ));
573    }
574    let client = ctx.client()?;
575    let resp = match client.inner().reopen_task(&task_id).await {
576        Ok(v) => v.into_inner(),
577        Err(e) => return Err(map_api_error(e).await.into()),
578    };
579    Ok(Envelope::success(
580        ctx.environment,
581        ctx.dry_run,
582        json!({ "reopen": resp }),
583    ))
584}
585
586async fn open(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
587    let task_id = Uuid::parse_str(&args.id)
588        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
589    if ctx.dry_run {
590        return Ok(Envelope::success(
591            ctx.environment,
592            ctx.dry_run,
593            json!({ "action": "would_open", "task_id": task_id.to_string() }),
594        ));
595    }
596    let client = ctx.client()?;
597    let resp = match client.inner().open_task(&task_id).await {
598        Ok(v) => v.into_inner(),
599        Err(e) => return Err(map_api_error(e).await.into()),
600    };
601    Ok(Envelope::success(
602        ctx.environment,
603        ctx.dry_run,
604        json!({ "open": resp }),
605    ))
606}
607
608async fn edit(ctx: &Ctx, args: EditArgs) -> CmdResult {
609    let task_id = Uuid::parse_str(&args.id)
610        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
611    // Reject empty edits locally — server would 422 and we'd rather fail fast.
612    let any_change = args.title.is_some()
613        || args.description.is_some()
614        || args.budget_max.is_some()
615        || args.review_window_hours.is_some()
616        || args.remedy_window_hours.is_some();
617    if !any_change {
618        return Err(CmdError::Usage(
619            "edit requires at least one of --title/--description/--budget-max/--review-window-hours/--remedy-window-hours".into(),
620        ));
621    }
622    let body = TaskEditRequest {
623        title: args.title.clone(),
624        description: args.description.clone(),
625        budget_max: args.budget_max.clone(),
626        review_window_hours: args.review_window_hours,
627        remedy_window_hours: args.remedy_window_hours,
628        completion_criteria: Vec::new(),
629    };
630    if ctx.dry_run {
631        return Ok(Envelope::success(
632            ctx.environment,
633            ctx.dry_run,
634            json!({
635                "action": "would_edit",
636                "task_id": task_id.to_string(),
637                "patch": body,
638            }),
639        ));
640    }
641    let client = ctx.client()?;
642    let resp = match client.inner().edit_task(&task_id, &body).await {
643        Ok(v) => v.into_inner(),
644        Err(e) => return Err(map_api_error(e).await.into()),
645    };
646    Ok(Envelope::success(
647        ctx.environment,
648        ctx.dry_run,
649        json!({ "task": resp }),
650    ))
651}
652
653async fn bids(ctx: &Ctx, args: BidsArgs) -> CmdResult {
654    let task_id = Uuid::parse_str(&args.id)
655        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
656    let client = ctx.client()?;
657    let resp = match client
658        .inner()
659        .list_task_bids(
660            &task_id,
661            args.cursor.as_deref(),
662            taskfast_client::page_limit(args.limit),
663        )
664        .await
665    {
666        Ok(v) => v.into_inner(),
667        Err(e) => return Err(map_api_error(e).await.into()),
668    };
669    Ok(Envelope::success(
670        ctx.environment,
671        ctx.dry_run,
672        json!({
673            "task_id": task_id.to_string(),
674            "bids": resp.data,
675            "meta": resp.meta,
676        }),
677    ))
678}
679
680/// Path + derived metadata (filename, content_type) needed for multipart
681/// upload. Parsed upfront so a missing file fails before any network I/O.
682struct ResolvedArtifact {
683    path: PathBuf,
684    filename: String,
685    content_type: String,
686}
687
688impl ResolvedArtifact {
689    fn from_path(p: &std::path::Path) -> Result<Self, CmdError> {
690        if !p.exists() {
691            return Err(CmdError::Usage(format!(
692                "artifact file not found: {}",
693                p.display()
694            )));
695        }
696        let filename = p
697            .file_name()
698            .and_then(|s| s.to_str())
699            .ok_or_else(|| {
700                CmdError::Usage(format!("artifact path has no filename: {}", p.display()))
701            })?
702            .to_string();
703        let ext = p
704            .extension()
705            .and_then(|s| s.to_str())
706            .map(|s| s.to_ascii_lowercase())
707            .unwrap_or_default();
708        let content_type = content_type_for_ext(&ext).to_string();
709        Ok(Self {
710            path: p.to_path_buf(),
711            filename,
712            content_type,
713        })
714    }
715
716    fn display_path(&self) -> String {
717        self.path.display().to_string()
718    }
719}
720
721/// Map file extension to the MIME types the server accepts. Anything
722/// unrecognized falls through to `application/octet-stream`; the server
723/// rejects unsupported types with 415 which our error mapping surfaces as
724/// `CmdError::Validation`.
725pub(super) fn content_type_for_ext(ext: &str) -> &'static str {
726    match ext {
727        "txt" => "text/plain",
728        // Markdown is plain UTF-8 text; the server allow-list accepts text/plain
729        // but not text/markdown, and .md is the canonical deliverable format in
730        // the agent skill (gh#674). Without this, .md uploads fall through to
731        // application/octet-stream and the server 415s the submission.
732        "md" | "markdown" => "text/plain",
733        "csv" => "text/csv",
734        "json" => "application/json",
735        "xml" => "application/xml",
736        "pdf" => "application/pdf",
737        "doc" => "application/msword",
738        "png" => "image/png",
739        "jpg" | "jpeg" => "image/jpeg",
740        "gif" => "image/gif",
741        "webp" => "image/webp",
742        "svg" => "image/svg+xml",
743        "zip" => "application/zip",
744        "tar" => "application/x-tar",
745        "gz" => "application/gzip",
746        "html" | "htm" => "text/html",
747        "css" => "text/css",
748        "js" => "application/javascript",
749        _ => "application/octet-stream",
750    }
751}
752
753async fn list(ctx: &Ctx, args: ListArgs) -> CmdResult {
754    if args.status.is_some() && !matches!(args.kind, ListKind::Mine) {
755        return Err(CmdError::Usage(
756            "--status is only valid with --kind=mine".into(),
757        ));
758    }
759    let client = ctx.client()?;
760    let data = match args.kind {
761        ListKind::Mine => list_mine(&client, &args).await?,
762        ListKind::Queue => list_queue(&client, &args).await?,
763        ListKind::Posted => list_posted(&client, &args).await?,
764    };
765    Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
766}
767
768async fn list_mine(
769    client: &TaskFastClient,
770    args: &ListArgs,
771) -> Result<serde_json::Value, CmdError> {
772    // The server owns the active-status classification: with no `status`
773    // filter, `GET /agents/me/tasks` returns exactly the active set
774    // (assigned / in_progress / under_review / disputed / remedied), and a
775    // supplied `--status` narrows within it (taskfast#941). One page in, one
776    // page out — no client-side filtering or re-paging.
777    let status = args.status.map(|s| vec![ListMyTasksStatusItem::from(s)]);
778    let resp = match client
779        .inner()
780        .list_my_tasks(
781            args.cursor.as_deref(),
782            taskfast_client::page_limit(args.limit),
783            status.as_ref(),
784        )
785        .await
786    {
787        Ok(v) => v.into_inner(),
788        Err(e) => return Err(map_api_error(e).await.into()),
789    };
790    Ok(json!({
791        "kind": "mine",
792        "tasks": resp.data,
793        "meta": resp.meta,
794    }))
795}
796
797async fn list_queue(
798    client: &TaskFastClient,
799    args: &ListArgs,
800) -> Result<serde_json::Value, CmdError> {
801    let resp = match client
802        .inner()
803        .get_agent_queue(
804            args.cursor.as_deref(),
805            taskfast_client::page_limit(args.limit),
806        )
807        .await
808    {
809        Ok(v) => v.into_inner(),
810        Err(e) => return Err(map_api_error(e).await.into()),
811    };
812    Ok(json!({
813        "kind": "queue",
814        "tasks": resp.data,
815        "meta": resp.meta,
816    }))
817}
818
819async fn list_posted(
820    client: &TaskFastClient,
821    args: &ListArgs,
822) -> Result<serde_json::Value, CmdError> {
823    let resp = match client
824        .inner()
825        .get_agent_posted_tasks(
826            args.cursor.as_deref(),
827            taskfast_client::page_limit(args.limit),
828        )
829        .await
830    {
831        Ok(v) => v.into_inner(),
832        Err(e) => return Err(map_api_error(e).await.into()),
833    };
834    Ok(json!({
835        "kind": "posted",
836        "tasks": resp.data,
837        "meta": resp.meta,
838    }))
839}
840
841async fn get(ctx: &Ctx, args: GetArgs) -> CmdResult {
842    // Validate UUID locally — bad IDs shouldn't cost a round-trip.
843    let id = Uuid::parse_str(&args.id)
844        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
845    let client = ctx.client()?;
846    let task = match client.inner().get_task(&id).await {
847        Ok(v) => v.into_inner(),
848        Err(e) => return Err(map_api_error(e).await.into()),
849    };
850    Ok(Envelope::success(
851        ctx.environment,
852        ctx.dry_run,
853        json!({ "task": task }),
854    ))
855}
856
857#[cfg(test)]
858mod tests {
859    use super::*;
860
861    #[test]
862    fn task_status_maps_to_generated_enum() {
863        // Pin the mapping — changing it would be a silent wire-shape change.
864        for (ours, theirs) in [
865            (TaskStatus::InProgress, ListMyTasksStatusItem::InProgress),
866            (TaskStatus::UnderReview, ListMyTasksStatusItem::UnderReview),
867            (TaskStatus::Disputed, ListMyTasksStatusItem::Disputed),
868            (TaskStatus::Remedied, ListMyTasksStatusItem::Remedied),
869            (TaskStatus::Assigned, ListMyTasksStatusItem::Assigned),
870        ] {
871            // `ListMyTasksStatusItem: Display` — compare as strings to avoid
872            // needing PartialEq on the foreign type.
873            assert_eq!(
874                ListMyTasksStatusItem::from(ours).to_string(),
875                theirs.to_string()
876            );
877        }
878    }
879
880    #[test]
881    fn content_type_maps_markdown_to_text_plain() {
882        // gh#674 regression guard: the server allow-list accepts text/plain but
883        // not text/markdown, so .md/.markdown must map to text/plain or the
884        // submission 415s. Dropping either arm reintroduces the bug.
885        assert_eq!(content_type_for_ext("md"), "text/plain");
886        assert_eq!(content_type_for_ext("markdown"), "text/plain");
887        // A representative non-markdown mapping and the unknown fallthrough,
888        // so a future edit to the match can't silently collapse the table.
889        assert_eq!(content_type_for_ext("json"), "application/json");
890        assert_eq!(
891            content_type_for_ext("unknownext"),
892            "application/octet-stream"
893        );
894    }
895}