Skip to main content

taskfast_cli/cmd/
task.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast task` — read + mutate operations on tasks.
3//!
4//! Read (am-e3u.4): `list` + `get`. Worker mutation (am-edc): `submit`.
5//! Poster mutations (am-plyy): `approve` / `dispute` / `cancel` — all
6//! unsigned per spec; server owns the state-machine gates and returns
7//! 403/409 for role/state violations, which we surface via `map_api_error`.
8//! The client-signed settle step (am-e3u.7, server bead am-iyp6) lives at
9//! top-level `taskfast settle` — it's a separate verb because it signs an
10//! EIP-712 `DistributionApproval`, not just an auth-gated state transition.
11//!
12//! # List semantics
13//!
14//! Three server endpoints hide behind `--kind`:
15//!
16//! | `--kind`  | Endpoint                       | Response         |
17//! |-----------|--------------------------------|------------------|
18//! | `mine`    | `GET /agents/me/tasks`         | worker's active workload (default; supports `--status`) |
19//! | `queue`   | `GET /agents/me/queue`         | assigned-but-unclaimed work |
20//! | `posted`  | `GET /agents/me/posted_tasks`  | tasks this agent posted |
21//!
22//! `--status` is only meaningful with `--kind=mine`; supplying it with any
23//! other kind is a [`CmdError::Usage`] rather than a silent no-op (ambiguous
24//! flag combinations should fail loud).
25
26use std::path::PathBuf;
27
28use clap::{Parser, Subcommand, ValueEnum};
29use serde_json::json;
30use uuid::Uuid;
31
32use super::{CmdError, CmdResult, Ctx};
33use crate::envelope::Envelope;
34
35use taskfast_client::api::types::{
36    CompletionSubmission, DisputeRequest, ListMyTasksStatusItem, ReassignTaskBody, TaskEditRequest,
37};
38use taskfast_client::map_api_error;
39use taskfast_client::TaskFastClient;
40
41#[derive(Debug, Subcommand)]
42pub enum Command {
43    /// List tasks (see `--kind` for which collection).
44    List(ListArgs),
45    /// GET /tasks/{id} — full task detail.
46    Get(GetArgs),
47    /// Worker: upload artifacts (if any) and submit completion.
48    Submit(SubmitArgs),
49    /// Poster: approve an under-review submission — releases payment.
50    Approve(ApproveArgs),
51    /// Poster: raise a dispute during the review window.
52    Dispute(DisputeArgs),
53    /// Poster: cancel a task before the state machine locks it in.
54    Cancel(CancelArgs),
55    /// Worker: claim an assigned task (moves `assigned` → `in_progress`).
56    Claim(IdOnlyArgs),
57    /// Worker: refuse an assigned task before claiming it.
58    Refuse(IdOnlyArgs),
59    /// Worker: resubmit completion against a disputed task (remedy flow).
60    Remedy(SubmitArgs),
61    /// Worker: concede a dispute (accepts the poster's position, no appeal).
62    Concede(IdOnlyArgs),
63    /// Worker: abort a claimed task before submission.
64    Abort(IdOnlyArgs),
65    /// Poster: list bids received on a task (paginated).
66    Bids(BidsArgs),
67    /// Poster: reassign a direct-assigned task to a different agent.
68    Reassign(ReassignArgs),
69    /// Poster: flip a direct-assigned task back to `assigned` state.
70    Reopen(IdOnlyArgs),
71    /// Poster: convert a direct-assigned task into an open bid auction.
72    Open(IdOnlyArgs),
73    /// Poster: edit task metadata (title/description/budget/windows).
74    Edit(EditArgs),
75}
76
77#[derive(Debug, Parser)]
78pub struct ReassignArgs {
79    /// Task UUID.
80    pub id: String,
81
82    /// New assignee UUID.
83    #[arg(long)]
84    pub agent_id: String,
85}
86
87#[derive(Debug, Parser)]
88pub struct EditArgs {
89    /// Task UUID.
90    pub id: String,
91
92    #[arg(long)]
93    pub title: Option<String>,
94
95    #[arg(long)]
96    pub description: Option<String>,
97
98    /// New max budget (decimal string, e.g. `100.00`).
99    #[arg(long)]
100    pub budget_max: Option<String>,
101
102    #[arg(long)]
103    pub review_window_hours: Option<i64>,
104
105    #[arg(long)]
106    pub remedy_window_hours: Option<i64>,
107}
108
109#[derive(Debug, Parser)]
110pub struct ListArgs {
111    /// Which collection to list. See module docs for the endpoint mapping.
112    #[arg(long, default_value = "mine")]
113    pub kind: ListKind,
114
115    /// Filter by task status. Only valid with `--kind=mine`; supplying it
116    /// with another kind is a usage error. Omit it to get the server's
117    /// active set (assigned / in_progress / under_review / disputed /
118    /// remedied) — this endpoint only ever returns active-state tasks, so
119    /// the active set is both the default and the maximum.
120    #[arg(long)]
121    pub status: Option<TaskStatus>,
122
123    /// Opaque pagination cursor from a previous response's `next_cursor`.
124    #[arg(long)]
125    pub cursor: Option<String>,
126
127    /// Page size requested from the server. Defaults to 20 — keeps
128    /// `task list` envelopes compact for routine worker polling.
129    #[arg(long, default_value_t = 20)]
130    pub limit: i64,
131}
132
133#[derive(Debug, Parser)]
134pub struct GetArgs {
135    /// Task ID (UUID).
136    pub id: String,
137}
138
139/// Shared shape for subcommands that take only a task UUID and no body —
140/// claim / refuse / concede / abort. Named `IdOnlyArgs` rather than reusing
141/// `GetArgs` so the intent reads at the call site.
142#[derive(Debug, Parser)]
143pub struct IdOnlyArgs {
144    /// Task UUID.
145    pub id: String,
146}
147
148#[derive(Debug, Parser)]
149pub struct BidsArgs {
150    /// Task UUID. Must be posted by this agent; 403 otherwise.
151    pub id: String,
152
153    /// Opaque pagination cursor from a previous response's `next_cursor`.
154    #[arg(long)]
155    pub cursor: Option<String>,
156
157    /// Max items per page. Defaults to 20.
158    #[arg(long, default_value_t = 20)]
159    pub limit: i64,
160}
161
162#[derive(Debug, Parser)]
163pub struct ApproveArgs {
164    /// Task UUID. Must be in `:under_review` and posted by this agent.
165    pub id: String,
166}
167
168#[derive(Debug, Parser)]
169pub struct DisputeArgs {
170    /// Task UUID. Must be in `:under_review` and posted by this agent.
171    pub id: String,
172
173    /// Dispute reason shown to the assignee. Required; empty/whitespace
174    /// fails locally so the server never sees a 400 that we could catch.
175    #[arg(long)]
176    pub reason: String,
177}
178
179#[derive(Debug, Parser)]
180pub struct CancelArgs {
181    /// Task UUID. Allowed from open/bidding/assigned/unassigned/abandoned.
182    pub id: String,
183}
184
185#[derive(Debug, Parser)]
186pub struct SubmitArgs {
187    /// Task ID (UUID) to submit completion for.
188    pub id: String,
189
190    /// Human-readable summary of the completed work. Required by the API.
191    #[arg(long)]
192    pub summary: String,
193
194    /// Path to an artifact file. Repeat for multiple artifacts. Each file
195    /// is uploaded via multipart `POST /tasks/{id}/artifacts`; the resulting
196    /// artifact IDs are passed to the final completion submission.
197    #[arg(long)]
198    pub artifact: Vec<PathBuf>,
199}
200
201#[derive(Debug, Clone, Copy, ValueEnum)]
202pub enum ListKind {
203    /// Tasks where the agent is the assigned worker (default).
204    Mine,
205    /// Assigned-but-unclaimed queue (subset of `mine` with server-specific shape).
206    Queue,
207    /// Tasks this agent has posted.
208    Posted,
209}
210
211/// Mirror of `ListMyTasksStatusItem` carved as a clap-friendly `ValueEnum`.
212///
213/// The generated enum already derives `ValueEnum`-compatible serde, but
214/// clap's `ValueEnum` needs kebab-case variants and the `Display` impl
215/// already lives on the generated type — cheaper to keep a thin mirror here
216/// than to teach clap about foreign traits.
217#[derive(Debug, Clone, Copy, ValueEnum)]
218pub enum TaskStatus {
219    InProgress,
220    UnderReview,
221    Disputed,
222    Remedied,
223    Assigned,
224}
225
226impl From<TaskStatus> for ListMyTasksStatusItem {
227    fn from(s: TaskStatus) -> Self {
228        match s {
229            TaskStatus::InProgress => Self::InProgress,
230            TaskStatus::UnderReview => Self::UnderReview,
231            TaskStatus::Disputed => Self::Disputed,
232            TaskStatus::Remedied => Self::Remedied,
233            TaskStatus::Assigned => Self::Assigned,
234        }
235    }
236}
237
238pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
239    match cmd {
240        Command::List(args) => list(ctx, args).await,
241        Command::Get(args) => get(ctx, args).await,
242        Command::Submit(args) => submit(ctx, args, SubmitKind::Completion).await,
243        Command::Approve(args) => approve(ctx, args).await,
244        Command::Dispute(args) => dispute(ctx, args).await,
245        Command::Cancel(args) => cancel(ctx, args).await,
246        Command::Claim(args) => claim(ctx, args).await,
247        Command::Refuse(args) => refuse(ctx, args).await,
248        Command::Remedy(args) => submit(ctx, args, SubmitKind::Remedy).await,
249        Command::Concede(args) => concede(ctx, args).await,
250        Command::Abort(args) => abort(ctx, args).await,
251        Command::Bids(args) => bids(ctx, args).await,
252        Command::Reassign(args) => reassign(ctx, args).await,
253        Command::Reopen(args) => reopen(ctx, args).await,
254        Command::Open(args) => open(ctx, args).await,
255        Command::Edit(args) => edit(ctx, args).await,
256    }
257}
258
259/// Selects the server endpoint for a completion-shaped POST. Remedy hits
260/// `/tasks/:id/remedy` (dispute-only) while Completion hits the submission
261/// endpoint. The wire body is identical — only the verb + URL differ.
262#[derive(Debug, Clone, Copy)]
263enum SubmitKind {
264    Completion,
265    Remedy,
266}
267
268async fn approve(ctx: &Ctx, args: ApproveArgs) -> CmdResult {
269    let task_id = Uuid::parse_str(&args.id)
270        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
271    if ctx.dry_run {
272        return Ok(Envelope::success(
273            ctx.environment,
274            ctx.dry_run,
275            json!({
276                "action": "would_approve",
277                "task_id": task_id.to_string(),
278            }),
279        ));
280    }
281    let client = ctx.client()?;
282    let resp = match client.inner().approve_task(&task_id).await {
283        Ok(v) => v.into_inner(),
284        Err(e) => return Err(map_api_error(e).await.into()),
285    };
286    Ok(Envelope::success(
287        ctx.environment,
288        ctx.dry_run,
289        json!({
290            "task_id": resp.task_id,
291            "status": resp.status,
292        }),
293    ))
294}
295
296async fn dispute(ctx: &Ctx, args: DisputeArgs) -> CmdResult {
297    let task_id = Uuid::parse_str(&args.id)
298        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
299    // Server returns 400 on empty reason; catch it locally so orchestrators
300    // see a Usage error (retry-never) rather than a Validation error.
301    if args.reason.trim().is_empty() {
302        return Err(CmdError::Usage("--reason must not be empty".into()));
303    }
304    if ctx.dry_run {
305        return Ok(Envelope::success(
306            ctx.environment,
307            ctx.dry_run,
308            json!({
309                "action": "would_dispute",
310                "task_id": task_id.to_string(),
311                "reason": args.reason,
312            }),
313        ));
314    }
315    let client = ctx.client()?;
316    let body = DisputeRequest {
317        reason: args.reason.clone(),
318    };
319    let resp = match client.inner().raise_dispute(&task_id, &body).await {
320        Ok(v) => v.into_inner(),
321        Err(e) => return Err(map_api_error(e).await.into()),
322    };
323    Ok(Envelope::success(
324        ctx.environment,
325        ctx.dry_run,
326        json!({
327            "task_id": resp.task_id,
328            "status": resp.status,
329            "dispute": resp.dispute,
330            "message": resp.message,
331        }),
332    ))
333}
334
335async fn cancel(ctx: &Ctx, args: CancelArgs) -> CmdResult {
336    let task_id = Uuid::parse_str(&args.id)
337        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
338    if ctx.dry_run {
339        return Ok(Envelope::success(
340            ctx.environment,
341            ctx.dry_run,
342            json!({
343                "action": "would_cancel",
344                "task_id": task_id.to_string(),
345            }),
346        ));
347    }
348    let client = ctx.client()?;
349    let resp = match client.inner().cancel_task(&task_id).await {
350        Ok(v) => v.into_inner(),
351        Err(e) => return Err(map_api_error(e).await.into()),
352    };
353    Ok(Envelope::success(
354        ctx.environment,
355        ctx.dry_run,
356        json!({
357            "id": resp.id,
358            "status": resp.status,
359        }),
360    ))
361}
362
363async fn submit(ctx: &Ctx, args: SubmitArgs, kind: SubmitKind) -> CmdResult {
364    // Parse the task ID locally so bad input never costs a round-trip.
365    let task_id = Uuid::parse_str(&args.id)
366        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
367
368    // Resolve each artifact path upfront — fail-fast on missing files so a
369    // half-uploaded set isn't left dangling on the server.
370    let resolved: Vec<ResolvedArtifact> = args
371        .artifact
372        .iter()
373        .map(|p| ResolvedArtifact::from_path(p))
374        .collect::<Result<_, _>>()?;
375
376    let action = match kind {
377        SubmitKind::Completion => "would_submit",
378        SubmitKind::Remedy => "would_remedy",
379    };
380
381    if ctx.dry_run {
382        return Ok(Envelope::success(
383            ctx.environment,
384            ctx.dry_run,
385            json!({
386                "action": action,
387                "task_id": task_id.to_string(),
388                "summary": args.summary,
389                "artifacts": resolved.iter().map(|r| r.display_path()).collect::<Vec<_>>(),
390            }),
391        ));
392    }
393
394    let client = ctx.client()?;
395
396    // Upload each artifact, collect IDs. Sequential to keep ordering
397    // deterministic — artifact_ids are semantically ordered by the server.
398    let mut artifact_ids: Vec<uuid::Uuid> = Vec::with_capacity(resolved.len());
399    let mut uploaded_meta: Vec<serde_json::Value> = Vec::with_capacity(resolved.len());
400    for r in resolved {
401        let bytes = std::fs::read(&r.path)
402            .map_err(|e| CmdError::Usage(format!("read {}: {e}", r.path.display())))?;
403        let artifact = client
404            .upload_artifact(&task_id, r.filename.clone(), r.content_type.clone(), bytes)
405            .await
406            .map_err(CmdError::from)?;
407        artifact_ids.push(artifact.id);
408        uploaded_meta.push(json!({
409            "id": artifact.id,
410            "filename": artifact.filename,
411            "content_type": artifact.content_type,
412            "size_bytes": artifact.size_bytes,
413        }));
414    }
415
416    let body = CompletionSubmission {
417        summary: args.summary.clone(),
418        artifact_ids: artifact_ids.clone(),
419        metadata: serde_json::Map::new(),
420    };
421    let result = match kind {
422        SubmitKind::Completion => match client.inner().submit_completion(&task_id, &body).await {
423            Ok(v) => {
424                serde_json::to_value(v.into_inner()).map_err(|e| CmdError::Decode(e.to_string()))?
425            }
426            Err(e) => return Err(map_api_error(e).await.into()),
427        },
428        SubmitKind::Remedy => match client.inner().submit_remedy(&task_id, &body).await {
429            Ok(v) => {
430                serde_json::to_value(v.into_inner()).map_err(|e| CmdError::Decode(e.to_string()))?
431            }
432            Err(e) => return Err(map_api_error(e).await.into()),
433        },
434    };
435
436    Ok(Envelope::success(
437        ctx.environment,
438        ctx.dry_run,
439        json!({
440            "task_id": task_id.to_string(),
441            "artifacts": uploaded_meta,
442            "submission": result,
443        }),
444    ))
445}
446
447async fn claim(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
448    let task_id = Uuid::parse_str(&args.id)
449        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
450    if ctx.dry_run {
451        return Ok(Envelope::success(
452            ctx.environment,
453            ctx.dry_run,
454            json!({ "action": "would_claim", "task_id": task_id.to_string() }),
455        ));
456    }
457    let client = ctx.client()?;
458    let resp = match client.inner().claim_task(&task_id).await {
459        Ok(v) => v.into_inner(),
460        Err(e) => {
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
669async fn edit(ctx: &Ctx, args: EditArgs) -> CmdResult {
670    let task_id = Uuid::parse_str(&args.id)
671        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
672    // Reject empty edits locally — server would 422 and we'd rather fail fast.
673    let any_change = args.title.is_some()
674        || args.description.is_some()
675        || args.budget_max.is_some()
676        || args.review_window_hours.is_some()
677        || args.remedy_window_hours.is_some();
678    if !any_change {
679        return Err(CmdError::Usage(
680            "edit requires at least one of --title/--description/--budget-max/--review-window-hours/--remedy-window-hours".into(),
681        ));
682    }
683    let body = TaskEditRequest {
684        title: args.title.clone(),
685        description: args.description.clone(),
686        budget_max: args.budget_max.clone(),
687        review_window_hours: args.review_window_hours,
688        remedy_window_hours: args.remedy_window_hours,
689        completion_criteria: Vec::new(),
690    };
691    if ctx.dry_run {
692        return Ok(Envelope::success(
693            ctx.environment,
694            ctx.dry_run,
695            json!({
696                "action": "would_edit",
697                "task_id": task_id.to_string(),
698                "patch": body,
699            }),
700        ));
701    }
702    let client = ctx.client()?;
703    let resp = match client.inner().edit_task(&task_id, &body).await {
704        Ok(v) => v.into_inner(),
705        Err(e) => return Err(map_api_error(e).await.into()),
706    };
707    Ok(Envelope::success(
708        ctx.environment,
709        ctx.dry_run,
710        json!({ "task": resp }),
711    ))
712}
713
714async fn bids(ctx: &Ctx, args: BidsArgs) -> CmdResult {
715    let task_id = Uuid::parse_str(&args.id)
716        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
717    let client = ctx.client()?;
718    let resp = match client
719        .inner()
720        .list_task_bids(
721            &task_id,
722            args.cursor.as_deref(),
723            taskfast_client::page_limit(args.limit),
724        )
725        .await
726    {
727        Ok(v) => v.into_inner(),
728        Err(e) => return Err(map_api_error(e).await.into()),
729    };
730    Ok(Envelope::success(
731        ctx.environment,
732        ctx.dry_run,
733        json!({
734            "task_id": task_id.to_string(),
735            "bids": resp.data,
736            "meta": resp.meta,
737        }),
738    ))
739}
740
741/// Path + derived metadata (filename, content_type) needed for multipart
742/// upload. Parsed upfront so a missing file fails before any network I/O.
743struct ResolvedArtifact {
744    path: PathBuf,
745    filename: String,
746    content_type: String,
747}
748
749impl ResolvedArtifact {
750    fn from_path(p: &std::path::Path) -> Result<Self, CmdError> {
751        if !p.exists() {
752            return Err(CmdError::Usage(format!(
753                "artifact file not found: {}",
754                p.display()
755            )));
756        }
757        let filename = p
758            .file_name()
759            .and_then(|s| s.to_str())
760            .ok_or_else(|| {
761                CmdError::Usage(format!("artifact path has no filename: {}", p.display()))
762            })?
763            .to_string();
764        let ext = p
765            .extension()
766            .and_then(|s| s.to_str())
767            .map(|s| s.to_ascii_lowercase())
768            .unwrap_or_default();
769        let content_type = content_type_for_ext(&ext).to_string();
770        Ok(Self {
771            path: p.to_path_buf(),
772            filename,
773            content_type,
774        })
775    }
776
777    fn display_path(&self) -> String {
778        self.path.display().to_string()
779    }
780}
781
782/// Map file extension to the MIME types the server accepts. Anything
783/// unrecognized falls through to `application/octet-stream`; the server
784/// rejects unsupported types with 415 which our error mapping surfaces as
785/// `CmdError::Validation`.
786pub(super) fn content_type_for_ext(ext: &str) -> &'static str {
787    match ext {
788        "txt" => "text/plain",
789        // Markdown is plain UTF-8 text; the server allow-list accepts text/plain
790        // but not text/markdown, and .md is the canonical deliverable format in
791        // the agent skill (gh#674). Without this, .md uploads fall through to
792        // application/octet-stream and the server 415s the submission.
793        "md" | "markdown" => "text/plain",
794        "csv" => "text/csv",
795        "json" => "application/json",
796        "xml" => "application/xml",
797        "pdf" => "application/pdf",
798        "doc" => "application/msword",
799        "png" => "image/png",
800        "jpg" | "jpeg" => "image/jpeg",
801        "gif" => "image/gif",
802        "webp" => "image/webp",
803        "svg" => "image/svg+xml",
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}