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