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, ListMyTasksStatus, 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. When omitted on `--kind=mine`,
117    /// results are filtered client-side to the active set (assigned /
118    /// in_progress / under_review / disputed / remedied). Pass
119    /// `--status all` to restore the unfiltered historical view.
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. The default active-only mine
128    /// view treats this as a stop threshold: it pages in whole pages so a
129    /// resume never skips rows, and may return a few more items than this.
130    /// Defaults to 20 — keeps `task list` envelopes compact for routine
131    /// worker polling.
132    #[arg(long, default_value_t = 20)]
133    pub limit: i64,
134}
135
136#[derive(Debug, Parser)]
137pub struct GetArgs {
138    /// Task ID (UUID).
139    pub id: String,
140}
141
142/// Shared shape for subcommands that take only a task UUID and no body —
143/// claim / refuse / concede / abort. Named `IdOnlyArgs` rather than reusing
144/// `GetArgs` so the intent reads at the call site.
145#[derive(Debug, Parser)]
146pub struct IdOnlyArgs {
147    /// Task UUID.
148    pub id: String,
149}
150
151#[derive(Debug, Parser)]
152pub struct BidsArgs {
153    /// Task UUID. Must be posted by this agent; 403 otherwise.
154    pub id: String,
155
156    /// Opaque pagination cursor from a previous response's `next_cursor`.
157    #[arg(long)]
158    pub cursor: Option<String>,
159
160    /// Max items per page. Defaults to 20.
161    #[arg(long, default_value_t = 20)]
162    pub limit: i64,
163}
164
165#[derive(Debug, Parser)]
166pub struct ApproveArgs {
167    /// Task UUID. Must be in `:under_review` and posted by this agent.
168    pub id: String,
169}
170
171#[derive(Debug, Parser)]
172pub struct DisputeArgs {
173    /// Task UUID. Must be in `:under_review` and posted by this agent.
174    pub id: String,
175
176    /// Dispute reason shown to the assignee. Required; empty/whitespace
177    /// fails locally so the server never sees a 400 that we could catch.
178    #[arg(long)]
179    pub reason: String,
180}
181
182#[derive(Debug, Parser)]
183pub struct CancelArgs {
184    /// Task UUID. Allowed from open/bidding/assigned/unassigned/abandoned.
185    pub id: String,
186}
187
188#[derive(Debug, Parser)]
189pub struct SubmitArgs {
190    /// Task ID (UUID) to submit completion for.
191    pub id: String,
192
193    /// Human-readable summary of the completed work. Required by the API.
194    #[arg(long)]
195    pub summary: String,
196
197    /// Path to an artifact file. Repeat for multiple artifacts. Each file
198    /// is uploaded via multipart `POST /tasks/{id}/artifacts`; the resulting
199    /// artifact IDs are passed to the final completion submission.
200    #[arg(long)]
201    pub artifact: Vec<PathBuf>,
202}
203
204#[derive(Debug, Clone, Copy, ValueEnum)]
205pub enum ListKind {
206    /// Tasks where the agent is the assigned worker (default).
207    Mine,
208    /// Assigned-but-unclaimed queue (subset of `mine` with server-specific shape).
209    Queue,
210    /// Tasks this agent has posted.
211    Posted,
212}
213
214/// Mirror of `ListMyTasksStatus` carved as a clap-friendly `ValueEnum`.
215///
216/// The generated enum already derives `ValueEnum`-compatible serde, but
217/// clap's `ValueEnum` needs kebab-case variants and the `Display` impl
218/// already lives on the generated type — cheaper to keep a thin mirror here
219/// than to teach clap about foreign traits.
220#[derive(Debug, Clone, Copy, ValueEnum)]
221pub enum TaskStatus {
222    InProgress,
223    UnderReview,
224    Disputed,
225    Remedied,
226    Assigned,
227    All,
228}
229
230impl From<TaskStatus> for ListMyTasksStatus {
231    fn from(s: TaskStatus) -> Self {
232        match s {
233            TaskStatus::InProgress => Self::InProgress,
234            TaskStatus::UnderReview => Self::UnderReview,
235            TaskStatus::Disputed => Self::Disputed,
236            TaskStatus::Remedied => Self::Remedied,
237            TaskStatus::Assigned => Self::Assigned,
238            TaskStatus::All => Self::All,
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::Edit(args) => edit(ctx, args).await,
261    }
262}
263
264/// Selects the server endpoint for a completion-shaped POST. Remedy hits
265/// `/tasks/:id/remedy` (dispute-only) while Completion hits the submission
266/// endpoint. The wire body is identical — only the verb + URL differ.
267#[derive(Debug, Clone, Copy)]
268enum SubmitKind {
269    Completion,
270    Remedy,
271}
272
273async fn approve(ctx: &Ctx, args: ApproveArgs) -> CmdResult {
274    let task_id = Uuid::parse_str(&args.id)
275        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
276    if ctx.dry_run {
277        return Ok(Envelope::success(
278            ctx.environment,
279            ctx.dry_run,
280            json!({
281                "action": "would_approve",
282                "task_id": task_id.to_string(),
283            }),
284        ));
285    }
286    let client = ctx.client()?;
287    let resp = match client.inner().approve_task(&task_id).await {
288        Ok(v) => v.into_inner(),
289        Err(e) => return Err(map_api_error(e).await.into()),
290    };
291    Ok(Envelope::success(
292        ctx.environment,
293        ctx.dry_run,
294        json!({
295            "task_id": resp.task_id,
296            "status": resp.status,
297        }),
298    ))
299}
300
301async fn dispute(ctx: &Ctx, args: DisputeArgs) -> CmdResult {
302    let task_id = Uuid::parse_str(&args.id)
303        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
304    // Server returns 400 on empty reason; catch it locally so orchestrators
305    // see a Usage error (retry-never) rather than a Validation error.
306    if args.reason.trim().is_empty() {
307        return Err(CmdError::Usage("--reason must not be empty".into()));
308    }
309    if ctx.dry_run {
310        return Ok(Envelope::success(
311            ctx.environment,
312            ctx.dry_run,
313            json!({
314                "action": "would_dispute",
315                "task_id": task_id.to_string(),
316                "reason": args.reason,
317            }),
318        ));
319    }
320    let client = ctx.client()?;
321    let body = DisputeRequest {
322        reason: args.reason.clone(),
323    };
324    let resp = match client.inner().raise_dispute(&task_id, &body).await {
325        Ok(v) => v.into_inner(),
326        Err(e) => return Err(map_api_error(e).await.into()),
327    };
328    Ok(Envelope::success(
329        ctx.environment,
330        ctx.dry_run,
331        json!({
332            "task_id": resp.task_id,
333            "status": resp.status,
334            "dispute": resp.dispute,
335            "message": resp.message,
336        }),
337    ))
338}
339
340async fn cancel(ctx: &Ctx, args: CancelArgs) -> CmdResult {
341    let task_id = Uuid::parse_str(&args.id)
342        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
343    if ctx.dry_run {
344        return Ok(Envelope::success(
345            ctx.environment,
346            ctx.dry_run,
347            json!({
348                "action": "would_cancel",
349                "task_id": task_id.to_string(),
350            }),
351        ));
352    }
353    let client = ctx.client()?;
354    let resp = match client.inner().cancel_task(&task_id).await {
355        Ok(v) => v.into_inner(),
356        Err(e) => return Err(map_api_error(e).await.into()),
357    };
358    Ok(Envelope::success(
359        ctx.environment,
360        ctx.dry_run,
361        json!({
362            "id": resp.id,
363            "status": resp.status,
364        }),
365    ))
366}
367
368async fn submit(ctx: &Ctx, args: SubmitArgs, kind: SubmitKind) -> CmdResult {
369    // Parse the task ID locally so bad input never costs a round-trip.
370    let task_id = Uuid::parse_str(&args.id)
371        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
372
373    // Resolve each artifact path upfront — fail-fast on missing files so a
374    // half-uploaded set isn't left dangling on the server.
375    let resolved: Vec<ResolvedArtifact> = args
376        .artifact
377        .iter()
378        .map(|p| ResolvedArtifact::from_path(p))
379        .collect::<Result<_, _>>()?;
380
381    let action = match kind {
382        SubmitKind::Completion => "would_submit",
383        SubmitKind::Remedy => "would_remedy",
384    };
385
386    if ctx.dry_run {
387        return Ok(Envelope::success(
388            ctx.environment,
389            ctx.dry_run,
390            json!({
391                "action": action,
392                "task_id": task_id.to_string(),
393                "summary": args.summary,
394                "artifacts": resolved.iter().map(|r| r.display_path()).collect::<Vec<_>>(),
395            }),
396        ));
397    }
398
399    let client = ctx.client()?;
400
401    // Upload each artifact, collect IDs. Sequential to keep ordering
402    // deterministic — artifact_ids are semantically ordered by the server.
403    let mut artifact_ids: Vec<uuid::Uuid> = Vec::with_capacity(resolved.len());
404    let mut uploaded_meta: Vec<serde_json::Value> = Vec::with_capacity(resolved.len());
405    for r in resolved {
406        let bytes = std::fs::read(&r.path)
407            .map_err(|e| CmdError::Usage(format!("read {}: {e}", r.path.display())))?;
408        let artifact = client
409            .upload_artifact(&task_id, r.filename.clone(), r.content_type.clone(), bytes)
410            .await
411            .map_err(CmdError::from)?;
412        artifact_ids.push(artifact.id);
413        uploaded_meta.push(json!({
414            "id": artifact.id,
415            "filename": artifact.filename,
416            "content_type": artifact.content_type,
417            "size_bytes": artifact.size_bytes,
418        }));
419    }
420
421    let body = CompletionSubmission {
422        summary: args.summary.clone(),
423        artifact_ids: artifact_ids.clone(),
424        metadata: serde_json::Map::new(),
425    };
426    let result = match kind {
427        SubmitKind::Completion => match client.inner().submit_completion(&task_id, &body).await {
428            Ok(v) => {
429                serde_json::to_value(v.into_inner()).map_err(|e| CmdError::Decode(e.to_string()))?
430            }
431            Err(e) => return Err(map_api_error(e).await.into()),
432        },
433        SubmitKind::Remedy => match client.inner().submit_remedy(&task_id, &body).await {
434            Ok(v) => {
435                serde_json::to_value(v.into_inner()).map_err(|e| CmdError::Decode(e.to_string()))?
436            }
437            Err(e) => return Err(map_api_error(e).await.into()),
438        },
439    };
440
441    Ok(Envelope::success(
442        ctx.environment,
443        ctx.dry_run,
444        json!({
445            "task_id": task_id.to_string(),
446            "artifacts": uploaded_meta,
447            "submission": result,
448        }),
449    ))
450}
451
452async fn claim(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
453    let task_id = Uuid::parse_str(&args.id)
454        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
455    if ctx.dry_run {
456        return Ok(Envelope::success(
457            ctx.environment,
458            ctx.dry_run,
459            json!({ "action": "would_claim", "task_id": task_id.to_string() }),
460        ));
461    }
462    let client = ctx.client()?;
463    let resp = match client.inner().claim_task(&task_id).await {
464        Ok(v) => v.into_inner(),
465        Err(e) => return Err(map_api_error(e).await.into()),
466    };
467    Ok(Envelope::success(
468        ctx.environment,
469        ctx.dry_run,
470        json!({ "claim": resp }),
471    ))
472}
473
474async fn refuse(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
475    let task_id = Uuid::parse_str(&args.id)
476        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
477    if ctx.dry_run {
478        return Ok(Envelope::success(
479            ctx.environment,
480            ctx.dry_run,
481            json!({ "action": "would_refuse", "task_id": task_id.to_string() }),
482        ));
483    }
484    let client = ctx.client()?;
485    let resp = match client.inner().refuse_task(&task_id).await {
486        Ok(v) => v.into_inner(),
487        Err(e) => return Err(map_api_error(e).await.into()),
488    };
489    Ok(Envelope::success(
490        ctx.environment,
491        ctx.dry_run,
492        json!({ "refuse": resp }),
493    ))
494}
495
496async fn concede(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
497    let task_id = Uuid::parse_str(&args.id)
498        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
499    if ctx.dry_run {
500        return Ok(Envelope::success(
501            ctx.environment,
502            ctx.dry_run,
503            json!({ "action": "would_concede", "task_id": task_id.to_string() }),
504        ));
505    }
506    let client = ctx.client()?;
507    let resp = match client.inner().concede_dispute(&task_id).await {
508        Ok(v) => v.into_inner(),
509        Err(e) => return Err(map_api_error(e).await.into()),
510    };
511    Ok(Envelope::success(
512        ctx.environment,
513        ctx.dry_run,
514        json!({ "concede": resp }),
515    ))
516}
517
518async fn abort(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
519    let task_id = Uuid::parse_str(&args.id)
520        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
521    if ctx.dry_run {
522        return Ok(Envelope::success(
523            ctx.environment,
524            ctx.dry_run,
525            json!({ "action": "would_abort", "task_id": task_id.to_string() }),
526        ));
527    }
528    let client = ctx.client()?;
529    let resp = match client.inner().abort_task(&task_id).await {
530        Ok(v) => v.into_inner(),
531        Err(e) => return Err(map_api_error(e).await.into()),
532    };
533    Ok(Envelope::success(
534        ctx.environment,
535        ctx.dry_run,
536        json!({ "abort": resp }),
537    ))
538}
539
540async fn reassign(ctx: &Ctx, args: ReassignArgs) -> CmdResult {
541    let task_id = Uuid::parse_str(&args.id)
542        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
543    let agent_id = Uuid::parse_str(&args.agent_id)
544        .map_err(|e| CmdError::Usage(format!("--agent-id must be a UUID: {e}")))?;
545    if ctx.dry_run {
546        return Ok(Envelope::success(
547            ctx.environment,
548            ctx.dry_run,
549            json!({
550                "action": "would_reassign",
551                "task_id": task_id.to_string(),
552                "agent_id": agent_id.to_string(),
553            }),
554        ));
555    }
556    let client = ctx.client()?;
557    let body = ReassignTaskBody { agent_id };
558    let resp = match client.inner().reassign_task(&task_id, &body).await {
559        Ok(v) => v.into_inner(),
560        Err(e) => return Err(map_api_error(e).await.into()),
561    };
562    Ok(Envelope::success(
563        ctx.environment,
564        ctx.dry_run,
565        json!({ "reassign": resp }),
566    ))
567}
568
569async fn reopen(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
570    let task_id = Uuid::parse_str(&args.id)
571        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
572    if ctx.dry_run {
573        return Ok(Envelope::success(
574            ctx.environment,
575            ctx.dry_run,
576            json!({ "action": "would_reopen", "task_id": task_id.to_string() }),
577        ));
578    }
579    let client = ctx.client()?;
580    let resp = match client.inner().reopen_task(&task_id).await {
581        Ok(v) => v.into_inner(),
582        Err(e) => return Err(map_api_error(e).await.into()),
583    };
584    Ok(Envelope::success(
585        ctx.environment,
586        ctx.dry_run,
587        json!({ "reopen": resp }),
588    ))
589}
590
591async fn open(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
592    let task_id = Uuid::parse_str(&args.id)
593        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
594    if ctx.dry_run {
595        return Ok(Envelope::success(
596            ctx.environment,
597            ctx.dry_run,
598            json!({ "action": "would_open", "task_id": task_id.to_string() }),
599        ));
600    }
601    let client = ctx.client()?;
602    let resp = match client.inner().open_task(&task_id).await {
603        Ok(v) => v.into_inner(),
604        Err(e) => return Err(map_api_error(e).await.into()),
605    };
606    Ok(Envelope::success(
607        ctx.environment,
608        ctx.dry_run,
609        json!({ "open": resp }),
610    ))
611}
612
613async fn edit(ctx: &Ctx, args: EditArgs) -> CmdResult {
614    let task_id = Uuid::parse_str(&args.id)
615        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
616    // Reject empty edits locally — server would 422 and we'd rather fail fast.
617    let any_change = args.title.is_some()
618        || args.description.is_some()
619        || args.budget_max.is_some()
620        || args.review_window_hours.is_some()
621        || args.remedy_window_hours.is_some();
622    if !any_change {
623        return Err(CmdError::Usage(
624            "edit requires at least one of --title/--description/--budget-max/--review-window-hours/--remedy-window-hours".into(),
625        ));
626    }
627    let body = TaskEditRequest {
628        title: args.title.clone(),
629        description: args.description.clone(),
630        budget_max: args.budget_max.clone(),
631        review_window_hours: args.review_window_hours,
632        remedy_window_hours: args.remedy_window_hours,
633        completion_criteria: Vec::new(),
634    };
635    if ctx.dry_run {
636        return Ok(Envelope::success(
637            ctx.environment,
638            ctx.dry_run,
639            json!({
640                "action": "would_edit",
641                "task_id": task_id.to_string(),
642                "patch": body,
643            }),
644        ));
645    }
646    let client = ctx.client()?;
647    let resp = match client.inner().edit_task(&task_id, &body).await {
648        Ok(v) => v.into_inner(),
649        Err(e) => return Err(map_api_error(e).await.into()),
650    };
651    Ok(Envelope::success(
652        ctx.environment,
653        ctx.dry_run,
654        json!({ "task": resp }),
655    ))
656}
657
658async fn bids(ctx: &Ctx, args: BidsArgs) -> CmdResult {
659    let task_id = Uuid::parse_str(&args.id)
660        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
661    let client = ctx.client()?;
662    let resp = match client
663        .inner()
664        .list_task_bids(
665            &task_id,
666            args.cursor.as_deref(),
667            taskfast_client::page_limit(args.limit),
668        )
669        .await
670    {
671        Ok(v) => v.into_inner(),
672        Err(e) => return Err(map_api_error(e).await.into()),
673    };
674    Ok(Envelope::success(
675        ctx.environment,
676        ctx.dry_run,
677        json!({
678            "task_id": task_id.to_string(),
679            "bids": resp.data,
680            "meta": resp.meta,
681        }),
682    ))
683}
684
685/// Path + derived metadata (filename, content_type) needed for multipart
686/// upload. Parsed upfront so a missing file fails before any network I/O.
687struct ResolvedArtifact {
688    path: PathBuf,
689    filename: String,
690    content_type: String,
691}
692
693impl ResolvedArtifact {
694    fn from_path(p: &std::path::Path) -> Result<Self, CmdError> {
695        if !p.exists() {
696            return Err(CmdError::Usage(format!(
697                "artifact file not found: {}",
698                p.display()
699            )));
700        }
701        let filename = p
702            .file_name()
703            .and_then(|s| s.to_str())
704            .ok_or_else(|| {
705                CmdError::Usage(format!("artifact path has no filename: {}", p.display()))
706            })?
707            .to_string();
708        let ext = p
709            .extension()
710            .and_then(|s| s.to_str())
711            .map(|s| s.to_ascii_lowercase())
712            .unwrap_or_default();
713        let content_type = content_type_for_ext(&ext).to_string();
714        Ok(Self {
715            path: p.to_path_buf(),
716            filename,
717            content_type,
718        })
719    }
720
721    fn display_path(&self) -> String {
722        self.path.display().to_string()
723    }
724}
725
726/// Map file extension to the MIME types the server accepts. Anything
727/// unrecognized falls through to `application/octet-stream`; the server
728/// rejects unsupported types with 415 which our error mapping surfaces as
729/// `CmdError::Validation`.
730pub(super) fn content_type_for_ext(ext: &str) -> &'static str {
731    match ext {
732        "txt" => "text/plain",
733        // Markdown is plain UTF-8 text; the server allow-list accepts text/plain
734        // but not text/markdown, and .md is the canonical deliverable format in
735        // the agent skill (gh#674). Without this, .md uploads fall through to
736        // application/octet-stream and the server 415s the submission.
737        "md" | "markdown" => "text/plain",
738        "csv" => "text/csv",
739        "json" => "application/json",
740        "xml" => "application/xml",
741        "pdf" => "application/pdf",
742        "doc" => "application/msword",
743        "png" => "image/png",
744        "jpg" | "jpeg" => "image/jpeg",
745        "gif" => "image/gif",
746        "webp" => "image/webp",
747        "svg" => "image/svg+xml",
748        "zip" => "application/zip",
749        "tar" => "application/x-tar",
750        "gz" => "application/gzip",
751        "html" | "htm" => "text/html",
752        "css" => "text/css",
753        "js" => "application/javascript",
754        _ => "application/octet-stream",
755    }
756}
757
758async fn list(ctx: &Ctx, args: ListArgs) -> CmdResult {
759    if args.status.is_some() && !matches!(args.kind, ListKind::Mine) {
760        return Err(CmdError::Usage(
761            "--status is only valid with --kind=mine".into(),
762        ));
763    }
764    let client = ctx.client()?;
765    let data = match args.kind {
766        ListKind::Mine => list_mine(&client, &args).await?,
767        ListKind::Queue => list_queue(&client, &args).await?,
768        ListKind::Posted => list_posted(&client, &args).await?,
769    };
770    Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
771}
772
773/// Task statuses considered "active" by the default `list --kind mine`
774/// filter. Everything outside this set (completed, cancelled, expired,
775/// …) is treated as closed noise and dropped unless the caller opts in
776/// with `--status all` or a specific `--status <name>`.
777///
778/// ponytail: presentation-only workaround — this classification is server
779/// state-machine knowledge; delete it (and the paging loop below) once the
780/// API grows an active/status filter on `GET /agents/me/tasks`.
781const ACTIVE_STATUSES: &[&str] = &[
782    "assigned",
783    "in_progress",
784    "under_review",
785    "disputed",
786    "remedied",
787];
788
789async fn list_mine(
790    client: &TaskFastClient,
791    args: &ListArgs,
792) -> Result<serde_json::Value, CmdError> {
793    if let Some(status) = args.status {
794        let resp = match client
795            .inner()
796            .list_my_tasks(
797                args.cursor.as_deref(),
798                taskfast_client::page_limit(args.limit),
799                Some(ListMyTasksStatus::from(status)),
800            )
801            .await
802        {
803            Ok(v) => v.into_inner(),
804            Err(e) => return Err(map_api_error(e).await.into()),
805        };
806        return Ok(json!({
807            "kind": "mine",
808            "tasks": resp.data,
809            "meta": resp.meta,
810        }));
811    }
812    // Active-only default view. The server has no active-status filter yet
813    // (upstream ask), so filter client-side — but advance in whole pages so
814    // the emitted `next_cursor` only ever points past fully-consumed pages
815    // and a resume never skips a filtered-out row. `--limit` is a stop
816    // threshold: paging stops at the first page boundary with at least that
817    // many matches, so a page may surface a few extra rows.
818    let want = usize::try_from(args.limit.max(0)).unwrap_or(usize::MAX);
819    let mut cursor = args.cursor.clone();
820    let mut tasks = Vec::new();
821    loop {
822        let resp = match client
823            .inner()
824            .list_my_tasks(
825                cursor.as_deref(),
826                taskfast_client::page_limit(args.limit),
827                None,
828            )
829            .await
830        {
831            Ok(v) => v.into_inner(),
832            Err(e) => return Err(map_api_error(e).await.into()),
833        };
834        tasks.extend(
835            resp.data
836                .into_iter()
837                .filter(|t| ACTIVE_STATUSES.contains(&t.status.as_str())),
838        );
839        let next = resp.meta.next_cursor.clone();
840        if tasks.len() >= want || next.is_none() {
841            return Ok(json!({
842                "kind": "mine",
843                "tasks": tasks,
844                "meta": resp.meta,
845            }));
846        }
847        cursor = next;
848    }
849}
850
851async fn list_queue(
852    client: &TaskFastClient,
853    args: &ListArgs,
854) -> Result<serde_json::Value, CmdError> {
855    let resp = match client
856        .inner()
857        .get_agent_queue(
858            args.cursor.as_deref(),
859            taskfast_client::page_limit(args.limit),
860        )
861        .await
862    {
863        Ok(v) => v.into_inner(),
864        Err(e) => return Err(map_api_error(e).await.into()),
865    };
866    Ok(json!({
867        "kind": "queue",
868        "tasks": resp.data,
869        "meta": resp.meta,
870    }))
871}
872
873async fn list_posted(
874    client: &TaskFastClient,
875    args: &ListArgs,
876) -> Result<serde_json::Value, CmdError> {
877    let resp = match client
878        .inner()
879        .get_agent_posted_tasks(
880            args.cursor.as_deref(),
881            taskfast_client::page_limit(args.limit),
882        )
883        .await
884    {
885        Ok(v) => v.into_inner(),
886        Err(e) => return Err(map_api_error(e).await.into()),
887    };
888    Ok(json!({
889        "kind": "posted",
890        "tasks": resp.data,
891        "meta": resp.meta,
892    }))
893}
894
895async fn get(ctx: &Ctx, args: GetArgs) -> CmdResult {
896    // Validate UUID locally — bad IDs shouldn't cost a round-trip.
897    let id = Uuid::parse_str(&args.id)
898        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
899    let client = ctx.client()?;
900    let task = match client.inner().get_task(&id).await {
901        Ok(v) => v.into_inner(),
902        Err(e) => return Err(map_api_error(e).await.into()),
903    };
904    Ok(Envelope::success(
905        ctx.environment,
906        ctx.dry_run,
907        json!({ "task": task }),
908    ))
909}
910
911#[cfg(test)]
912mod tests {
913    use super::*;
914
915    #[test]
916    fn task_status_maps_to_generated_enum() {
917        // Pin the mapping — changing it would be a silent wire-shape change.
918        for (ours, theirs) in [
919            (TaskStatus::InProgress, ListMyTasksStatus::InProgress),
920            (TaskStatus::UnderReview, ListMyTasksStatus::UnderReview),
921            (TaskStatus::Disputed, ListMyTasksStatus::Disputed),
922            (TaskStatus::Remedied, ListMyTasksStatus::Remedied),
923            (TaskStatus::Assigned, ListMyTasksStatus::Assigned),
924            (TaskStatus::All, ListMyTasksStatus::All),
925        ] {
926            // `ListMyTasksStatus: Display` — compare as strings to avoid
927            // needing PartialEq on the foreign type.
928            assert_eq!(
929                ListMyTasksStatus::from(ours).to_string(),
930                theirs.to_string()
931            );
932        }
933    }
934
935    #[test]
936    fn content_type_maps_markdown_to_text_plain() {
937        // gh#674 regression guard: the server allow-list accepts text/plain but
938        // not text/markdown, so .md/.markdown must map to text/plain or the
939        // submission 415s. Dropping either arm reintroduces the bug.
940        assert_eq!(content_type_for_ext("md"), "text/plain");
941        assert_eq!(content_type_for_ext("markdown"), "text/plain");
942        // A representative non-markdown mapping and the unknown fallthrough,
943        // so a future edit to the match can't silently collapse the table.
944        assert_eq!(content_type_for_ext("json"), "application/json");
945        assert_eq!(
946            content_type_for_ext("unknownext"),
947            "application/octet-stream"
948        );
949    }
950}