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