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