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::artifact::{upload_file, ResolvedArtifact};
33use super::{CmdError, CmdResult, Ctx};
34use crate::envelope::Envelope;
35
36use taskfast_client::api::types::{
37    CompletionSubmission, DisputeRequest, ListMyTasksStatusItem, TaskEditRequest,
38};
39use taskfast_client::map_api_error;
40use taskfast_client::TaskFastClient;
41
42#[derive(Debug, Subcommand)]
43pub enum Command {
44    /// List tasks (see `--kind` for which collection).
45    List(ListArgs),
46    /// GET /tasks/{id} — full task detail.
47    Get(GetArgs),
48    /// Worker: upload artifacts (if any) and submit completion.
49    Submit(SubmitArgs),
50    /// Poster: approve an under-review submission — releases payment.
51    Approve(ApproveArgs),
52    /// Poster: raise a dispute during the review window.
53    Dispute(DisputeArgs),
54    /// Poster: cancel a task before the state machine locks it in.
55    Cancel(CancelArgs),
56    /// Worker: claim an assigned task (moves `assigned` → `in_progress`).
57    Claim(IdOnlyArgs),
58    /// Worker: refuse an assigned task before claiming it.
59    Refuse(IdOnlyArgs),
60    /// Worker: resubmit completion against a disputed task (remedy flow).
61    Remedy(SubmitArgs),
62    /// Worker: concede a dispute (accepts the poster's position, no appeal).
63    Concede(IdOnlyArgs),
64    /// Worker: abort a claimed task before submission.
65    Abort(IdOnlyArgs),
66    /// Poster: list bids received on a task (paginated).
67    Bids(BidsArgs),
68    /// Poster: reopen an `abandoned` task for rebidding (returns to `open`).
69    Reopen(IdOnlyArgs),
70    /// Poster: return an `unassigned` task (refused or timed out) to open bidding.
71    Open(IdOnlyArgs),
72    /// Superseded: prints a redirect to `taskfast fee retry` (the server now
73    /// requires the poster's freshly signed fee transfer). Makes no request.
74    RetryFee(IdOnlyArgs),
75    /// Poster: edit task metadata (title/description/budget/windows).
76    Edit(EditArgs),
77}
78
79#[derive(Debug, Parser)]
80pub struct EditArgs {
81    /// Task UUID.
82    pub id: String,
83
84    #[arg(long)]
85    pub title: Option<String>,
86
87    #[arg(long)]
88    pub description: Option<String>,
89
90    /// New max budget (decimal string, e.g. `100.00`).
91    #[arg(long)]
92    pub budget_max: Option<String>,
93
94    #[arg(long)]
95    pub review_window_hours: Option<i64>,
96
97    #[arg(long)]
98    pub remedy_window_hours: Option<i64>,
99}
100
101#[derive(Debug, Parser)]
102pub struct ListArgs {
103    /// Which collection to list. See module docs for the endpoint mapping.
104    #[arg(long, default_value = "mine")]
105    pub kind: ListKind,
106
107    /// Filter by task status. Only valid with `--kind=mine`; supplying it
108    /// with another kind is a usage error. Omit it to get the server's
109    /// active set (assigned / in_progress / under_review / disputed /
110    /// remedied) — this endpoint only ever returns active-state tasks, so
111    /// the active set is both the default and the maximum.
112    #[arg(long)]
113    pub status: Option<TaskStatus>,
114
115    /// Opaque pagination cursor from a previous response's `next_cursor`.
116    #[arg(long)]
117    pub cursor: Option<String>,
118
119    /// Page size requested from the server. Defaults to 20 — keeps
120    /// `task list` envelopes compact for routine worker polling.
121    #[arg(long, default_value_t = 20)]
122    pub limit: i64,
123}
124
125#[derive(Debug, Parser)]
126pub struct GetArgs {
127    /// Task ID (UUID).
128    pub id: String,
129}
130
131/// Shared shape for subcommands that take only a task UUID and no body —
132/// claim / refuse / concede / abort / retry-fee. Named `IdOnlyArgs` rather
133/// than reusing `GetArgs` so the intent reads at the call site.
134#[derive(Debug, Parser)]
135pub struct IdOnlyArgs {
136    /// Task UUID.
137    pub id: String,
138}
139
140#[derive(Debug, Parser)]
141pub struct BidsArgs {
142    /// Task UUID. Must be posted by this agent; 403 otherwise.
143    pub id: String,
144
145    /// Opaque pagination cursor from a previous response's `next_cursor`.
146    #[arg(long)]
147    pub cursor: Option<String>,
148
149    /// Max items per page. Defaults to 20.
150    #[arg(long, default_value_t = 20)]
151    pub limit: i64,
152}
153
154#[derive(Debug, Parser)]
155pub struct ApproveArgs {
156    /// Task UUID. Must be in `:under_review` and posted by this agent.
157    pub id: String,
158}
159
160#[derive(Debug, Parser)]
161pub struct DisputeArgs {
162    /// Task UUID. Must be in `:under_review` and posted by this agent.
163    pub id: String,
164
165    /// Dispute reason shown to the assignee. Required; empty/whitespace
166    /// fails locally so the server never sees a 400 that we could catch.
167    #[arg(long)]
168    pub reason: String,
169}
170
171#[derive(Debug, Parser)]
172pub struct CancelArgs {
173    /// Task UUID. Allowed from open/bidding/assigned/unassigned/abandoned.
174    pub id: String,
175}
176
177#[derive(Debug, Parser)]
178pub struct SubmitArgs {
179    /// Task ID (UUID) to submit completion for.
180    pub id: String,
181
182    /// Human-readable summary of the completed work. Required by the API.
183    #[arg(long)]
184    pub summary: String,
185
186    /// Path to an artifact file. Repeat for multiple artifacts. Each file
187    /// is uploaded via multipart `POST /tasks/{id}/artifacts`; the resulting
188    /// artifact IDs are passed to the final completion submission.
189    #[arg(long)]
190    pub artifact: Vec<PathBuf>,
191}
192
193#[derive(Debug, Clone, Copy, ValueEnum)]
194pub enum ListKind {
195    /// Tasks where the agent is the assigned worker (default).
196    Mine,
197    /// Assigned-but-unclaimed queue (subset of `mine` with server-specific shape).
198    Queue,
199    /// Tasks this agent has posted.
200    Posted,
201}
202
203/// Mirror of `ListMyTasksStatusItem` carved as a clap-friendly `ValueEnum`.
204///
205/// The generated enum already derives `ValueEnum`-compatible serde, but
206/// clap's `ValueEnum` needs kebab-case variants and the `Display` impl
207/// already lives on the generated type — cheaper to keep a thin mirror here
208/// than to teach clap about foreign traits.
209#[derive(Debug, Clone, Copy, ValueEnum)]
210pub enum TaskStatus {
211    InProgress,
212    UnderReview,
213    Disputed,
214    Remedied,
215    Assigned,
216}
217
218impl From<TaskStatus> for ListMyTasksStatusItem {
219    fn from(s: TaskStatus) -> Self {
220        match s {
221            TaskStatus::InProgress => Self::InProgress,
222            TaskStatus::UnderReview => Self::UnderReview,
223            TaskStatus::Disputed => Self::Disputed,
224            TaskStatus::Remedied => Self::Remedied,
225            TaskStatus::Assigned => Self::Assigned,
226        }
227    }
228}
229
230pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
231    match cmd {
232        Command::List(args) => list(ctx, args).await,
233        Command::Get(args) => get(ctx, args).await,
234        Command::Submit(args) => submit(ctx, args, SubmitKind::Completion).await,
235        Command::Approve(args) => approve(ctx, args).await,
236        Command::Dispute(args) => dispute(ctx, args).await,
237        Command::Cancel(args) => cancel(ctx, args).await,
238        Command::Claim(args) => claim(ctx, args).await,
239        Command::Refuse(args) => refuse(ctx, args).await,
240        Command::Remedy(args) => submit(ctx, args, SubmitKind::Remedy).await,
241        Command::Concede(args) => concede(ctx, args).await,
242        Command::Abort(args) => abort(ctx, args).await,
243        Command::Bids(args) => bids(ctx, args).await,
244        Command::Reopen(args) => reopen(ctx, args).await,
245        Command::Open(args) => open(ctx, args).await,
246        Command::RetryFee(args) => retry_fee(&args),
247        Command::Edit(args) => edit(ctx, args).await,
248    }
249}
250
251/// Selects the server endpoint for a completion-shaped POST. Remedy hits
252/// `/tasks/:id/remedy` (dispute-only) while Completion hits the submission
253/// endpoint. The wire body is identical — only the verb + URL differ.
254#[derive(Debug, Clone, Copy)]
255enum SubmitKind {
256    Completion,
257    Remedy,
258}
259
260async fn approve(ctx: &Ctx, args: ApproveArgs) -> CmdResult {
261    let task_id = Uuid::parse_str(&args.id)
262        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
263    if ctx.dry_run {
264        return Ok(Envelope::success(
265            ctx.environment,
266            ctx.dry_run,
267            json!({
268                "action": "would_approve",
269                "task_id": task_id.to_string(),
270            }),
271        ));
272    }
273    let client = ctx.client()?;
274    let resp = match client.inner().approve_task(&task_id).await {
275        Ok(v) => v.into_inner(),
276        Err(e) => return Err(map_api_error(e).await.into()),
277    };
278    Ok(Envelope::success(
279        ctx.environment,
280        ctx.dry_run,
281        json!({
282            "task_id": resp.task_id,
283            "status": resp.status,
284        }),
285    ))
286}
287
288async fn dispute(ctx: &Ctx, args: DisputeArgs) -> CmdResult {
289    let task_id = Uuid::parse_str(&args.id)
290        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
291    // Server returns 400 on empty reason; catch it locally so orchestrators
292    // see a Usage error (retry-never) rather than a Validation error.
293    if args.reason.trim().is_empty() {
294        return Err(CmdError::Usage("--reason must not be empty".into()));
295    }
296    if ctx.dry_run {
297        return Ok(Envelope::success(
298            ctx.environment,
299            ctx.dry_run,
300            json!({
301                "action": "would_dispute",
302                "task_id": task_id.to_string(),
303                "reason": args.reason,
304            }),
305        ));
306    }
307    let client = ctx.client()?;
308    let body = DisputeRequest {
309        reason: args.reason.clone(),
310    };
311    let resp = match client.inner().raise_dispute(&task_id, &body).await {
312        Ok(v) => v.into_inner(),
313        Err(e) => return Err(map_api_error(e).await.into()),
314    };
315    Ok(Envelope::success(
316        ctx.environment,
317        ctx.dry_run,
318        json!({
319            "task_id": resp.task_id,
320            "status": resp.status,
321            "dispute": resp.dispute,
322            "message": resp.message,
323        }),
324    ))
325}
326
327async fn cancel(ctx: &Ctx, args: CancelArgs) -> CmdResult {
328    let task_id = Uuid::parse_str(&args.id)
329        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
330    if ctx.dry_run {
331        return Ok(Envelope::success(
332            ctx.environment,
333            ctx.dry_run,
334            json!({
335                "action": "would_cancel",
336                "task_id": task_id.to_string(),
337            }),
338        ));
339    }
340    let client = ctx.client()?;
341    let resp = match client.inner().cancel_task(&task_id).await {
342        Ok(v) => v.into_inner(),
343        Err(e) => return Err(map_api_error(e).await.into()),
344    };
345    Ok(Envelope::success(
346        ctx.environment,
347        ctx.dry_run,
348        json!({
349            "id": resp.id,
350            "status": resp.status,
351        }),
352    ))
353}
354
355async fn submit(ctx: &Ctx, args: SubmitArgs, kind: SubmitKind) -> CmdResult {
356    // Parse the task ID locally so bad input never costs a round-trip.
357    let task_id = Uuid::parse_str(&args.id)
358        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
359
360    // Resolve each artifact path upfront — fail-fast on missing files so a
361    // half-uploaded set isn't left dangling on the server.
362    let resolved: Vec<ResolvedArtifact> = args
363        .artifact
364        .iter()
365        .map(|p| ResolvedArtifact::from_path(p))
366        .collect::<Result<_, _>>()?;
367
368    let action = match kind {
369        SubmitKind::Completion => "would_submit",
370        SubmitKind::Remedy => "would_remedy",
371    };
372
373    if ctx.dry_run {
374        return Ok(Envelope::success(
375            ctx.environment,
376            ctx.dry_run,
377            json!({
378                "action": action,
379                "task_id": task_id.to_string(),
380                "summary": args.summary,
381                "artifacts": resolved.iter().map(|r| r.display_path()).collect::<Vec<_>>(),
382            }),
383        ));
384    }
385
386    let client = ctx.client()?;
387
388    // Upload each artifact, collect IDs. Sequential to keep ordering
389    // deterministic — artifact_ids are semantically ordered by the server.
390    let mut artifact_ids: Vec<uuid::Uuid> = Vec::with_capacity(resolved.len());
391    let mut uploaded_meta: Vec<serde_json::Value> = Vec::with_capacity(resolved.len());
392    for r in resolved {
393        let artifact = upload_file(ctx, &client, &task_id, &r).await?;
394        artifact_ids.push(artifact.id);
395        uploaded_meta.push(json!({
396            "id": artifact.id,
397            "filename": artifact.filename,
398            "content_type": artifact.content_type,
399            "size_bytes": artifact.size_bytes,
400        }));
401    }
402
403    let body = CompletionSubmission {
404        summary: args.summary.clone(),
405        artifact_ids: artifact_ids.clone(),
406        metadata: serde_json::Map::new(),
407    };
408    let result = match kind {
409        SubmitKind::Completion => match client.inner().submit_completion(&task_id, &body).await {
410            Ok(v) => {
411                serde_json::to_value(v.into_inner()).map_err(|e| CmdError::Decode(e.to_string()))?
412            }
413            Err(e) => return Err(map_api_error(e).await.into()),
414        },
415        SubmitKind::Remedy => match client.inner().submit_remedy(&task_id, &body).await {
416            Ok(v) => {
417                serde_json::to_value(v.into_inner()).map_err(|e| CmdError::Decode(e.to_string()))?
418            }
419            Err(e) => return Err(map_api_error(e).await.into()),
420        },
421    };
422
423    Ok(Envelope::success(
424        ctx.environment,
425        ctx.dry_run,
426        json!({
427            "task_id": task_id.to_string(),
428            "artifacts": uploaded_meta,
429            "submission": result,
430        }),
431    ))
432}
433
434async fn claim(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
435    let task_id = Uuid::parse_str(&args.id)
436        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
437    if ctx.dry_run {
438        return Ok(Envelope::success(
439            ctx.environment,
440            ctx.dry_run,
441            json!({ "action": "would_claim", "task_id": task_id.to_string() }),
442        ));
443    }
444    let client = ctx.client()?;
445    let resp = match client.inner().claim_task(&task_id).await {
446        Ok(v) => v.into_inner(),
447        Err(e) => {
448            let err = map_api_error(e).await;
449            // gh#143: dev work-start receipts auto-advance `assigned` →
450            // `in_progress`, racing the documented explicit claim. A 409
451            // `invalid_status` then means "already claimed" — confirm via a
452            // status re-check and report success with a note. Other 409
453            // codes (the `receipt_pending` / `bond_pending` work-start
454            // guards) are real rejections and stay errors.
455            if matches!(&err, taskfast_client::Error::Validation { code, .. } if code == "invalid_status")
456            {
457                if let Some(status) =
458                    current_status_if(&client, &task_id, status_at_or_past_in_progress).await
459                {
460                    return Ok(Envelope::success(
461                        ctx.environment,
462                        ctx.dry_run,
463                        json!({
464                            "claim": {
465                                "success": true,
466                                "task_id": task_id.to_string(),
467                                "status": status,
468                                "message": format!("already {status}"),
469                            }
470                        }),
471                    ));
472                }
473            }
474            return Err(err.into());
475        }
476    };
477    Ok(Envelope::success(
478        ctx.environment,
479        ctx.dry_run,
480        json!({ "claim": resp }),
481    ))
482}
483
484/// Task statuses at or past the `claim` target (`in_progress`) in the task
485/// state machine (wiki/Agent-State-Machines.md). gh#143: a 409
486/// `invalid_status` from claim means the server advanced first; when the
487/// task sits in one of these, the caller's goal is already met. Terminal
488/// states reached *before* `in_progress` (cancelled, expired, …) are
489/// deliberately absent — claiming those stays an error.
490fn status_at_or_past_in_progress(status: &str) -> bool {
491    matches!(
492        status,
493        "in_progress"
494            | "under_review"
495            | "disputed"
496            | "remedied"
497            | "complete"
498            | "disbursement_pending"
499            | "settled"
500    )
501}
502
503/// Re-fetch the task's current status, returning it only when `keep` says the
504/// idempotency target is met. A failed fetch or a non-matching status yields
505/// `None` so the caller surfaces the original error — the re-check must
506/// never mask the server's first answer (gh#143).
507async fn current_status_if(
508    client: &TaskFastClient,
509    task_id: &Uuid,
510    keep: fn(&str) -> bool,
511) -> Option<String> {
512    let task = client.inner().get_task(task_id).await.ok()?.into_inner();
513    let status = task.status?;
514    keep(&status).then_some(status)
515}
516
517async fn refuse(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
518    let task_id = Uuid::parse_str(&args.id)
519        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
520    if ctx.dry_run {
521        return Ok(Envelope::success(
522            ctx.environment,
523            ctx.dry_run,
524            json!({ "action": "would_refuse", "task_id": task_id.to_string() }),
525        ));
526    }
527    let client = ctx.client()?;
528    let resp = match client.inner().refuse_task(&task_id).await {
529        Ok(v) => v.into_inner(),
530        Err(e) => return Err(map_api_error(e).await.into()),
531    };
532    Ok(Envelope::success(
533        ctx.environment,
534        ctx.dry_run,
535        json!({ "refuse": resp }),
536    ))
537}
538
539async fn concede(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
540    let task_id = Uuid::parse_str(&args.id)
541        .map_err(|e| CmdError::Usage(format!("task 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!({ "action": "would_concede", "task_id": task_id.to_string() }),
547        ));
548    }
549    let client = ctx.client()?;
550    let resp = match client.inner().concede_dispute(&task_id).await {
551        Ok(v) => v.into_inner(),
552        Err(e) => return Err(map_api_error(e).await.into()),
553    };
554    Ok(Envelope::success(
555        ctx.environment,
556        ctx.dry_run,
557        json!({ "concede": resp }),
558    ))
559}
560
561async fn abort(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
562    let task_id = Uuid::parse_str(&args.id)
563        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
564    if ctx.dry_run {
565        return Ok(Envelope::success(
566            ctx.environment,
567            ctx.dry_run,
568            json!({ "action": "would_abort", "task_id": task_id.to_string() }),
569        ));
570    }
571    let client = ctx.client()?;
572    let resp = match client.inner().abort_task(&task_id).await {
573        Ok(v) => v.into_inner(),
574        Err(e) => return Err(map_api_error(e).await.into()),
575    };
576    Ok(Envelope::success(
577        ctx.environment,
578        ctx.dry_run,
579        json!({ "abort": resp }),
580    ))
581}
582
583async fn reopen(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
584    let task_id = Uuid::parse_str(&args.id)
585        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
586    if ctx.dry_run {
587        return Ok(Envelope::success(
588            ctx.environment,
589            ctx.dry_run,
590            json!({ "action": "would_reopen", "task_id": task_id.to_string() }),
591        ));
592    }
593    let client = ctx.client()?;
594    let resp = match client.inner().reopen_task(&task_id).await {
595        Ok(v) => v.into_inner(),
596        Err(e) => return Err(map_api_error(e).await.into()),
597    };
598    Ok(Envelope::success(
599        ctx.environment,
600        ctx.dry_run,
601        json!({ "reopen": resp }),
602    ))
603}
604
605async fn open(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
606    let task_id = Uuid::parse_str(&args.id)
607        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
608    if ctx.dry_run {
609        return Ok(Envelope::success(
610            ctx.environment,
611            ctx.dry_run,
612            json!({ "action": "would_open", "task_id": task_id.to_string() }),
613        ));
614    }
615    let client = ctx.client()?;
616    let resp = match client.inner().open_task(&task_id).await {
617        Ok(v) => v.into_inner(),
618        Err(e) => return Err(map_api_error(e).await.into()),
619    };
620    Ok(Envelope::success(
621        ctx.environment,
622        ctx.dry_run,
623        json!({ "open": resp }),
624    ))
625}
626
627/// Redirect only. Since 2026-11-01 `POST /tasks/{id}/retry-fee` requires the
628/// poster's freshly signed fee transfer (or the hash of one already
629/// broadcast) in the body; the original voucher cannot be reused. Changing
630/// this subcommand's args would break the library API without a version bump,
631/// so the voucher-carrying command is `taskfast fee retry`. Makes no HTTP
632/// call, in `--dry-run` or otherwise.
633fn retry_fee(args: &IdOnlyArgs) -> CmdResult {
634    Err(CmdError::Usage(format!(
635        "`task retry-fee` no longer sends a request: since 2026-11-01 the server requires the \
636         poster's freshly signed fee transfer (or the hash of one the poster already \
637         broadcast) for a retry. Use `taskfast fee retry {} --submission-fee-voucher <0x...>`.",
638        args.id
639    )))
640}
641
642async fn edit(ctx: &Ctx, args: EditArgs) -> CmdResult {
643    let task_id = Uuid::parse_str(&args.id)
644        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
645    // Reject empty edits locally — server would 422 and we'd rather fail fast.
646    let any_change = args.title.is_some()
647        || args.description.is_some()
648        || args.budget_max.is_some()
649        || args.review_window_hours.is_some()
650        || args.remedy_window_hours.is_some();
651    if !any_change {
652        return Err(CmdError::Usage(
653            "edit requires at least one of --title/--description/--budget-max/--review-window-hours/--remedy-window-hours".into(),
654        ));
655    }
656    let body = TaskEditRequest {
657        title: args.title.clone(),
658        description: args.description.clone(),
659        budget_max: args.budget_max.clone(),
660        review_window_hours: args.review_window_hours,
661        remedy_window_hours: args.remedy_window_hours,
662        completion_criteria: Vec::new(),
663    };
664    if ctx.dry_run {
665        return Ok(Envelope::success(
666            ctx.environment,
667            ctx.dry_run,
668            json!({
669                "action": "would_edit",
670                "task_id": task_id.to_string(),
671                "patch": body,
672            }),
673        ));
674    }
675    let client = ctx.client()?;
676    let resp = match client.inner().edit_task(&task_id, &body).await {
677        Ok(v) => v.into_inner(),
678        Err(e) => return Err(map_api_error(e).await.into()),
679    };
680    Ok(Envelope::success(
681        ctx.environment,
682        ctx.dry_run,
683        json!({ "task": resp }),
684    ))
685}
686
687async fn bids(ctx: &Ctx, args: BidsArgs) -> CmdResult {
688    let task_id = Uuid::parse_str(&args.id)
689        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
690    let client = ctx.client()?;
691    let resp = match client
692        .inner()
693        .list_task_bids(
694            &task_id,
695            args.cursor.as_deref(),
696            taskfast_client::page_limit(args.limit),
697        )
698        .await
699    {
700        Ok(v) => v.into_inner(),
701        Err(e) => return Err(map_api_error(e).await.into()),
702    };
703    Ok(Envelope::success(
704        ctx.environment,
705        ctx.dry_run,
706        json!({
707            "task_id": task_id.to_string(),
708            "bids": resp.data,
709            "meta": resp.meta,
710        }),
711    ))
712}
713
714/// Map file extension to the MIME types the server accepts. Anything
715/// unrecognized falls through to `application/octet-stream`; the server
716/// rejects unsupported types with 415 which our error mapping surfaces as
717/// `CmdError::Validation`.
718pub(super) fn content_type_for_ext(ext: &str) -> &'static str {
719    match ext {
720        "txt" => "text/plain",
721        // Markdown is plain UTF-8 text; the server allow-list accepts text/plain
722        // but not text/markdown, and .md is the canonical deliverable format in
723        // the agent skill (gh#674). Without this, .md uploads fall through to
724        // application/octet-stream and the server 415s the submission.
725        "md" | "markdown" => "text/plain",
726        "csv" => "text/csv",
727        "json" => "application/json",
728        "xml" => "application/xml",
729        "pdf" => "application/pdf",
730        "doc" => "application/msword",
731        "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
732        "xls" => "application/vnd.ms-excel",
733        "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
734        "png" => "image/png",
735        "jpg" | "jpeg" => "image/jpeg",
736        "gif" => "image/gif",
737        "webp" => "image/webp",
738        "svg" => "image/svg+xml",
739        // gh#190: the server allow-list accepts these video types
740        // (taskfast#1679); without them, video artifacts fall through to
741        // application/octet-stream and the upload 415s.
742        "mp4" => "video/mp4",
743        "webm" => "video/webm",
744        "mov" => "video/quicktime",
745        // gh#199: the server allow-list accepts these audio types
746        // (taskfast#1741, taskfast#2833); without them, audio artifacts fall
747        // through to application/octet-stream and the upload 415s.
748        "mp3" => "audio/mpeg",
749        "wav" => "audio/wav",
750        "ogg" => "audio/ogg",
751        "m4a" => "audio/mp4",
752        "flac" => "audio/flac",
753        "zip" => "application/zip",
754        "tar" => "application/x-tar",
755        "gz" => "application/gzip",
756        "html" | "htm" => "text/html",
757        "css" => "text/css",
758        "js" => "application/javascript",
759        _ => "application/octet-stream",
760    }
761}
762
763async fn list(ctx: &Ctx, args: ListArgs) -> CmdResult {
764    if args.status.is_some() && !matches!(args.kind, ListKind::Mine) {
765        return Err(CmdError::Usage(
766            "--status is only valid with --kind=mine".into(),
767        ));
768    }
769    let client = ctx.client()?;
770    let data = match args.kind {
771        ListKind::Mine => list_mine(&client, &args).await?,
772        ListKind::Queue => list_queue(&client, &args).await?,
773        ListKind::Posted => list_posted(&client, &args).await?,
774    };
775    Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
776}
777
778async fn list_mine(
779    client: &TaskFastClient,
780    args: &ListArgs,
781) -> Result<serde_json::Value, CmdError> {
782    // The server owns the active-status classification: with no `status`
783    // filter, `GET /agents/me/tasks` returns exactly the active set
784    // (assigned / in_progress / under_review / disputed / remedied), and a
785    // supplied `--status` narrows within it (taskfast#941). One page in, one
786    // page out — no client-side filtering or re-paging.
787    let status = args.status.map(|s| vec![ListMyTasksStatusItem::from(s)]);
788    let resp = match client
789        .inner()
790        .list_my_tasks(
791            args.cursor.as_deref(),
792            taskfast_client::page_limit(args.limit),
793            status.as_ref(),
794        )
795        .await
796    {
797        Ok(v) => v.into_inner(),
798        Err(e) => return Err(map_api_error(e).await.into()),
799    };
800    Ok(json!({
801        "kind": "mine",
802        "tasks": resp.data,
803        "meta": resp.meta,
804    }))
805}
806
807async fn list_queue(
808    client: &TaskFastClient,
809    args: &ListArgs,
810) -> Result<serde_json::Value, CmdError> {
811    let resp = match client
812        .inner()
813        .get_agent_queue(
814            args.cursor.as_deref(),
815            taskfast_client::page_limit(args.limit),
816        )
817        .await
818    {
819        Ok(v) => v.into_inner(),
820        Err(e) => return Err(map_api_error(e).await.into()),
821    };
822    Ok(json!({
823        "kind": "queue",
824        "tasks": resp.data,
825        "meta": resp.meta,
826    }))
827}
828
829async fn list_posted(
830    client: &TaskFastClient,
831    args: &ListArgs,
832) -> Result<serde_json::Value, CmdError> {
833    let resp = match client
834        .inner()
835        .get_agent_posted_tasks(
836            args.cursor.as_deref(),
837            taskfast_client::page_limit(args.limit),
838        )
839        .await
840    {
841        Ok(v) => v.into_inner(),
842        Err(e) => return Err(map_api_error(e).await.into()),
843    };
844    Ok(json!({
845        "kind": "posted",
846        "tasks": resp.data,
847        "meta": resp.meta,
848    }))
849}
850
851async fn get(ctx: &Ctx, args: GetArgs) -> CmdResult {
852    // Validate UUID locally — bad IDs shouldn't cost a round-trip.
853    let id = Uuid::parse_str(&args.id)
854        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
855    let client = ctx.client()?;
856    let task = match client.inner().get_task(&id).await {
857        Ok(v) => v.into_inner(),
858        Err(e) => return Err(map_api_error(e).await.into()),
859    };
860    Ok(Envelope::success(
861        ctx.environment,
862        ctx.dry_run,
863        json!({ "task": task }),
864    ))
865}
866
867#[cfg(test)]
868mod tests {
869    use super::*;
870
871    #[test]
872    fn task_status_maps_to_generated_enum() {
873        // Pin the mapping — changing it would be a silent wire-shape change.
874        for (ours, theirs) in [
875            (TaskStatus::InProgress, ListMyTasksStatusItem::InProgress),
876            (TaskStatus::UnderReview, ListMyTasksStatusItem::UnderReview),
877            (TaskStatus::Disputed, ListMyTasksStatusItem::Disputed),
878            (TaskStatus::Remedied, ListMyTasksStatusItem::Remedied),
879            (TaskStatus::Assigned, ListMyTasksStatusItem::Assigned),
880        ] {
881            // `ListMyTasksStatusItem: Display` — compare as strings to avoid
882            // needing PartialEq on the foreign type.
883            assert_eq!(
884                ListMyTasksStatusItem::from(ours).to_string(),
885                theirs.to_string()
886            );
887        }
888    }
889
890    #[test]
891    fn content_type_maps_markdown_to_text_plain() {
892        // gh#674 regression guard: the server allow-list accepts text/plain but
893        // not text/markdown, so .md/.markdown must map to text/plain or the
894        // submission 415s. Dropping either arm reintroduces the bug.
895        assert_eq!(content_type_for_ext("md"), "text/plain");
896        assert_eq!(content_type_for_ext("markdown"), "text/plain");
897        // A representative non-markdown mapping and the unknown fallthrough,
898        // so a future edit to the match can't silently collapse the table.
899        assert_eq!(content_type_for_ext("json"), "application/json");
900        assert_eq!(
901            content_type_for_ext("unknownext"),
902            "application/octet-stream"
903        );
904    }
905
906    #[test]
907    fn content_type_maps_video_extensions() {
908        // gh#190 regression guard: the server allow-list accepts video/mp4,
909        // video/webm and video/quicktime (taskfast#1679), so these extensions
910        // must not fall through to application/octet-stream or the upload
911        // 415s. Dropping any arm reintroduces the bug.
912        assert_eq!(content_type_for_ext("mp4"), "video/mp4");
913        assert_eq!(content_type_for_ext("webm"), "video/webm");
914        assert_eq!(content_type_for_ext("mov"), "video/quicktime");
915    }
916
917    #[test]
918    fn content_type_maps_office_document_extensions() {
919        // gh#199 regression guard: the server allow-list accepts Word (.docx)
920        // and Excel (.xls, .xlsx) documents, so these extensions must not fall
921        // through to application/octet-stream and trigger 415.
922        assert_eq!(
923            content_type_for_ext("docx"),
924            "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
925        );
926        assert_eq!(content_type_for_ext("xls"), "application/vnd.ms-excel");
927        assert_eq!(
928            content_type_for_ext("xlsx"),
929            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
930        );
931    }
932
933    #[test]
934    fn content_type_maps_audio_extensions() {
935        // gh#199 regression guard: the server allow-list accepts mp3, wav, ogg,
936        // m4a, and flac audio deliverables (taskfast#1741, taskfast#2833), so
937        // these extensions must not fall through to application/octet-stream and
938        // trigger 415.
939        assert_eq!(content_type_for_ext("mp3"), "audio/mpeg");
940        assert_eq!(content_type_for_ext("wav"), "audio/wav");
941        assert_eq!(content_type_for_ext("ogg"), "audio/ogg");
942        assert_eq!(content_type_for_ext("m4a"), "audio/mp4");
943        assert_eq!(content_type_for_ext("flac"), "audio/flac");
944    }
945}