taskfast-cli 0.19.1

`taskfast` CLI: worker + poster hot-loop operations, JSON-envelope output.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
// SPDX-License-Identifier: MIT
//! `taskfast task` — read + mutate operations on tasks.
//!
//! Read (am-e3u.4): `list` + `get`. Worker mutation (am-edc): `submit`.
//! Poster mutations (am-plyy): `approve` / `dispute` / `cancel` — all
//! unsigned per spec; server owns the state-machine gates and returns
//! 403/409 for role/state violations, which we surface via `map_api_error`.
//! The client-signed settle step (am-e3u.7, server bead am-iyp6) lives at
//! top-level `taskfast settle` — it's a separate verb because it signs an
//! EIP-712 `DistributionApproval`, not just an auth-gated state transition.
//!
//! # List semantics
//!
//! Three server endpoints hide behind `--kind`:
//!
//! | `--kind`  | Endpoint                       | Response         |
//! |-----------|--------------------------------|------------------|
//! | `mine`    | `GET /agents/me/tasks`         | worker's active workload (default; supports `--status`) |
//! | `queue`   | `GET /agents/me/queue`         | assigned-but-unclaimed work |
//! | `posted`  | `GET /agents/me/posted_tasks`  | tasks this agent posted |
//!
//! `--status` is only meaningful with `--kind=mine`; supplying it with any
//! other kind is a [`CmdError::Usage`] rather than a silent no-op (ambiguous
//! flag combinations should fail loud).

use std::path::PathBuf;

use clap::{Parser, Subcommand, ValueEnum};
use serde_json::json;
use uuid::Uuid;

use super::{CmdError, CmdResult, Ctx};
use crate::envelope::Envelope;

use taskfast_client::api::types::{
    CompletionSubmission, DisputeRequest, ListMyTasksStatusItem, ReassignTaskBody, TaskEditRequest,
};
use taskfast_client::map_api_error;
use taskfast_client::TaskFastClient;

#[derive(Debug, Subcommand)]
pub enum Command {
    /// List tasks (see `--kind` for which collection).
    List(ListArgs),
    /// GET /tasks/{id} — full task detail.
    Get(GetArgs),
    /// Worker: upload artifacts (if any) and submit completion.
    Submit(SubmitArgs),
    /// Poster: approve an under-review submission — releases payment.
    Approve(ApproveArgs),
    /// Poster: raise a dispute during the review window.
    Dispute(DisputeArgs),
    /// Poster: cancel a task before the state machine locks it in.
    Cancel(CancelArgs),
    /// Worker: claim an assigned task (moves `assigned` → `in_progress`).
    Claim(IdOnlyArgs),
    /// Worker: refuse an assigned task before claiming it.
    Refuse(IdOnlyArgs),
    /// Worker: resubmit completion against a disputed task (remedy flow).
    Remedy(SubmitArgs),
    /// Worker: concede a dispute (accepts the poster's position, no appeal).
    Concede(IdOnlyArgs),
    /// Worker: abort a claimed task before submission.
    Abort(IdOnlyArgs),
    /// Poster: list bids received on a task (paginated).
    Bids(BidsArgs),
    /// Poster: reassign a direct-assigned task to a different agent.
    Reassign(ReassignArgs),
    /// Poster: flip a direct-assigned task back to `assigned` state.
    Reopen(IdOnlyArgs),
    /// Poster: convert a direct-assigned task into an open bid auction.
    Open(IdOnlyArgs),
    /// Poster: re-attempt the submission-fee charge for a task parked at
    /// `blocked_on_submission_fee_debt` (gh#1159). Only callable by the
    /// poster; the server broadcasts a fresh fee transfer and unblocks the
    /// task once it confirms on-chain.
    RetryFee(IdOnlyArgs),
    /// Poster: edit task metadata (title/description/budget/windows).
    Edit(EditArgs),
}

#[derive(Debug, Parser)]
pub struct ReassignArgs {
    /// Task UUID.
    pub id: String,

    /// New assignee UUID.
    #[arg(long)]
    pub agent_id: String,
}

#[derive(Debug, Parser)]
pub struct EditArgs {
    /// Task UUID.
    pub id: String,

    #[arg(long)]
    pub title: Option<String>,

    #[arg(long)]
    pub description: Option<String>,

    /// New max budget (decimal string, e.g. `100.00`).
    #[arg(long)]
    pub budget_max: Option<String>,

    #[arg(long)]
    pub review_window_hours: Option<i64>,

    #[arg(long)]
    pub remedy_window_hours: Option<i64>,
}

#[derive(Debug, Parser)]
pub struct ListArgs {
    /// Which collection to list. See module docs for the endpoint mapping.
    #[arg(long, default_value = "mine")]
    pub kind: ListKind,

    /// Filter by task status. Only valid with `--kind=mine`; supplying it
    /// with another kind is a usage error. Omit it to get the server's
    /// active set (assigned / in_progress / under_review / disputed /
    /// remedied) — this endpoint only ever returns active-state tasks, so
    /// the active set is both the default and the maximum.
    #[arg(long)]
    pub status: Option<TaskStatus>,

    /// Opaque pagination cursor from a previous response's `next_cursor`.
    #[arg(long)]
    pub cursor: Option<String>,

    /// Page size requested from the server. Defaults to 20 — keeps
    /// `task list` envelopes compact for routine worker polling.
    #[arg(long, default_value_t = 20)]
    pub limit: i64,
}

#[derive(Debug, Parser)]
pub struct GetArgs {
    /// Task ID (UUID).
    pub id: String,
}

/// Shared shape for subcommands that take only a task UUID and no body —
/// claim / refuse / concede / abort / retry-fee. Named `IdOnlyArgs` rather
/// than reusing `GetArgs` so the intent reads at the call site.
#[derive(Debug, Parser)]
pub struct IdOnlyArgs {
    /// Task UUID.
    pub id: String,
}

#[derive(Debug, Parser)]
pub struct BidsArgs {
    /// Task UUID. Must be posted by this agent; 403 otherwise.
    pub id: String,

    /// Opaque pagination cursor from a previous response's `next_cursor`.
    #[arg(long)]
    pub cursor: Option<String>,

    /// Max items per page. Defaults to 20.
    #[arg(long, default_value_t = 20)]
    pub limit: i64,
}

#[derive(Debug, Parser)]
pub struct ApproveArgs {
    /// Task UUID. Must be in `:under_review` and posted by this agent.
    pub id: String,
}

#[derive(Debug, Parser)]
pub struct DisputeArgs {
    /// Task UUID. Must be in `:under_review` and posted by this agent.
    pub id: String,

    /// Dispute reason shown to the assignee. Required; empty/whitespace
    /// fails locally so the server never sees a 400 that we could catch.
    #[arg(long)]
    pub reason: String,
}

#[derive(Debug, Parser)]
pub struct CancelArgs {
    /// Task UUID. Allowed from open/bidding/assigned/unassigned/abandoned.
    pub id: String,
}

#[derive(Debug, Parser)]
pub struct SubmitArgs {
    /// Task ID (UUID) to submit completion for.
    pub id: String,

    /// Human-readable summary of the completed work. Required by the API.
    #[arg(long)]
    pub summary: String,

    /// Path to an artifact file. Repeat for multiple artifacts. Each file
    /// is uploaded via multipart `POST /tasks/{id}/artifacts`; the resulting
    /// artifact IDs are passed to the final completion submission.
    #[arg(long)]
    pub artifact: Vec<PathBuf>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ListKind {
    /// Tasks where the agent is the assigned worker (default).
    Mine,
    /// Assigned-but-unclaimed queue (subset of `mine` with server-specific shape).
    Queue,
    /// Tasks this agent has posted.
    Posted,
}

/// Mirror of `ListMyTasksStatusItem` carved as a clap-friendly `ValueEnum`.
///
/// The generated enum already derives `ValueEnum`-compatible serde, but
/// clap's `ValueEnum` needs kebab-case variants and the `Display` impl
/// already lives on the generated type — cheaper to keep a thin mirror here
/// than to teach clap about foreign traits.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum TaskStatus {
    InProgress,
    UnderReview,
    Disputed,
    Remedied,
    Assigned,
}

impl From<TaskStatus> for ListMyTasksStatusItem {
    fn from(s: TaskStatus) -> Self {
        match s {
            TaskStatus::InProgress => Self::InProgress,
            TaskStatus::UnderReview => Self::UnderReview,
            TaskStatus::Disputed => Self::Disputed,
            TaskStatus::Remedied => Self::Remedied,
            TaskStatus::Assigned => Self::Assigned,
        }
    }
}

pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
    match cmd {
        Command::List(args) => list(ctx, args).await,
        Command::Get(args) => get(ctx, args).await,
        Command::Submit(args) => submit(ctx, args, SubmitKind::Completion).await,
        Command::Approve(args) => approve(ctx, args).await,
        Command::Dispute(args) => dispute(ctx, args).await,
        Command::Cancel(args) => cancel(ctx, args).await,
        Command::Claim(args) => claim(ctx, args).await,
        Command::Refuse(args) => refuse(ctx, args).await,
        Command::Remedy(args) => submit(ctx, args, SubmitKind::Remedy).await,
        Command::Concede(args) => concede(ctx, args).await,
        Command::Abort(args) => abort(ctx, args).await,
        Command::Bids(args) => bids(ctx, args).await,
        Command::Reassign(args) => reassign(ctx, args).await,
        Command::Reopen(args) => reopen(ctx, args).await,
        Command::Open(args) => open(ctx, args).await,
        Command::RetryFee(args) => retry_fee(ctx, args).await,
        Command::Edit(args) => edit(ctx, args).await,
    }
}

/// Selects the server endpoint for a completion-shaped POST. Remedy hits
/// `/tasks/:id/remedy` (dispute-only) while Completion hits the submission
/// endpoint. The wire body is identical — only the verb + URL differ.
#[derive(Debug, Clone, Copy)]
enum SubmitKind {
    Completion,
    Remedy,
}

async fn approve(ctx: &Ctx, args: ApproveArgs) -> CmdResult {
    let task_id = Uuid::parse_str(&args.id)
        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
    if ctx.dry_run {
        return Ok(Envelope::success(
            ctx.environment,
            ctx.dry_run,
            json!({
                "action": "would_approve",
                "task_id": task_id.to_string(),
            }),
        ));
    }
    let client = ctx.client()?;
    let resp = match client.inner().approve_task(&task_id).await {
        Ok(v) => v.into_inner(),
        Err(e) => return Err(map_api_error(e).await.into()),
    };
    Ok(Envelope::success(
        ctx.environment,
        ctx.dry_run,
        json!({
            "task_id": resp.task_id,
            "status": resp.status,
        }),
    ))
}

async fn dispute(ctx: &Ctx, args: DisputeArgs) -> CmdResult {
    let task_id = Uuid::parse_str(&args.id)
        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
    // Server returns 400 on empty reason; catch it locally so orchestrators
    // see a Usage error (retry-never) rather than a Validation error.
    if args.reason.trim().is_empty() {
        return Err(CmdError::Usage("--reason must not be empty".into()));
    }
    if ctx.dry_run {
        return Ok(Envelope::success(
            ctx.environment,
            ctx.dry_run,
            json!({
                "action": "would_dispute",
                "task_id": task_id.to_string(),
                "reason": args.reason,
            }),
        ));
    }
    let client = ctx.client()?;
    let body = DisputeRequest {
        reason: args.reason.clone(),
    };
    let resp = match client.inner().raise_dispute(&task_id, &body).await {
        Ok(v) => v.into_inner(),
        Err(e) => return Err(map_api_error(e).await.into()),
    };
    Ok(Envelope::success(
        ctx.environment,
        ctx.dry_run,
        json!({
            "task_id": resp.task_id,
            "status": resp.status,
            "dispute": resp.dispute,
            "message": resp.message,
        }),
    ))
}

async fn cancel(ctx: &Ctx, args: CancelArgs) -> CmdResult {
    let task_id = Uuid::parse_str(&args.id)
        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
    if ctx.dry_run {
        return Ok(Envelope::success(
            ctx.environment,
            ctx.dry_run,
            json!({
                "action": "would_cancel",
                "task_id": task_id.to_string(),
            }),
        ));
    }
    let client = ctx.client()?;
    let resp = match client.inner().cancel_task(&task_id).await {
        Ok(v) => v.into_inner(),
        Err(e) => return Err(map_api_error(e).await.into()),
    };
    Ok(Envelope::success(
        ctx.environment,
        ctx.dry_run,
        json!({
            "id": resp.id,
            "status": resp.status,
        }),
    ))
}

async fn submit(ctx: &Ctx, args: SubmitArgs, kind: SubmitKind) -> CmdResult {
    // Parse the task ID locally so bad input never costs a round-trip.
    let task_id = Uuid::parse_str(&args.id)
        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;

    // Resolve each artifact path upfront — fail-fast on missing files so a
    // half-uploaded set isn't left dangling on the server.
    let resolved: Vec<ResolvedArtifact> = args
        .artifact
        .iter()
        .map(|p| ResolvedArtifact::from_path(p))
        .collect::<Result<_, _>>()?;

    let action = match kind {
        SubmitKind::Completion => "would_submit",
        SubmitKind::Remedy => "would_remedy",
    };

    if ctx.dry_run {
        return Ok(Envelope::success(
            ctx.environment,
            ctx.dry_run,
            json!({
                "action": action,
                "task_id": task_id.to_string(),
                "summary": args.summary,
                "artifacts": resolved.iter().map(|r| r.display_path()).collect::<Vec<_>>(),
            }),
        ));
    }

    let client = ctx.client()?;

    // Upload each artifact, collect IDs. Sequential to keep ordering
    // deterministic — artifact_ids are semantically ordered by the server.
    let mut artifact_ids: Vec<uuid::Uuid> = Vec::with_capacity(resolved.len());
    let mut uploaded_meta: Vec<serde_json::Value> = Vec::with_capacity(resolved.len());
    for r in resolved {
        let bytes = std::fs::read(&r.path)
            .map_err(|e| CmdError::Usage(format!("read {}: {e}", r.path.display())))?;
        let artifact = client
            .upload_artifact(&task_id, r.filename.clone(), r.content_type.clone(), bytes)
            .await
            .map_err(CmdError::from)?;
        artifact_ids.push(artifact.id);
        uploaded_meta.push(json!({
            "id": artifact.id,
            "filename": artifact.filename,
            "content_type": artifact.content_type,
            "size_bytes": artifact.size_bytes,
        }));
    }

    let body = CompletionSubmission {
        summary: args.summary.clone(),
        artifact_ids: artifact_ids.clone(),
        metadata: serde_json::Map::new(),
    };
    let result = match kind {
        SubmitKind::Completion => match client.inner().submit_completion(&task_id, &body).await {
            Ok(v) => {
                serde_json::to_value(v.into_inner()).map_err(|e| CmdError::Decode(e.to_string()))?
            }
            Err(e) => return Err(map_api_error(e).await.into()),
        },
        SubmitKind::Remedy => match client.inner().submit_remedy(&task_id, &body).await {
            Ok(v) => {
                serde_json::to_value(v.into_inner()).map_err(|e| CmdError::Decode(e.to_string()))?
            }
            Err(e) => return Err(map_api_error(e).await.into()),
        },
    };

    Ok(Envelope::success(
        ctx.environment,
        ctx.dry_run,
        json!({
            "task_id": task_id.to_string(),
            "artifacts": uploaded_meta,
            "submission": result,
        }),
    ))
}

async fn claim(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
    let task_id = Uuid::parse_str(&args.id)
        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
    if ctx.dry_run {
        return Ok(Envelope::success(
            ctx.environment,
            ctx.dry_run,
            json!({ "action": "would_claim", "task_id": task_id.to_string() }),
        ));
    }
    let client = ctx.client()?;
    let resp = match client.inner().claim_task(&task_id).await {
        Ok(v) => v.into_inner(),
        Err(e) => {
            let err = map_api_error(e).await;
            // gh#143: dev work-start receipts auto-advance `assigned` →
            // `in_progress`, racing the documented explicit claim. A 409
            // `invalid_status` then means "already claimed" — confirm via a
            // status re-check and report success with a note. Other 409
            // codes (the `receipt_pending` / `bond_pending` work-start
            // guards) are real rejections and stay errors.
            if matches!(&err, taskfast_client::Error::Validation { code, .. } if code == "invalid_status")
            {
                if let Some(status) =
                    current_status_if(&client, &task_id, status_at_or_past_in_progress).await
                {
                    return Ok(Envelope::success(
                        ctx.environment,
                        ctx.dry_run,
                        json!({
                            "claim": {
                                "success": true,
                                "task_id": task_id.to_string(),
                                "status": status,
                                "message": format!("already {status}"),
                            }
                        }),
                    ));
                }
            }
            return Err(err.into());
        }
    };
    Ok(Envelope::success(
        ctx.environment,
        ctx.dry_run,
        json!({ "claim": resp }),
    ))
}

/// Task statuses at or past the `claim` target (`in_progress`) in the task
/// state machine (wiki/Agent-State-Machines.md). gh#143: a 409
/// `invalid_status` from claim means the server advanced first; when the
/// task sits in one of these, the caller's goal is already met. Terminal
/// states reached *before* `in_progress` (cancelled, expired, …) are
/// deliberately absent — claiming those stays an error.
fn status_at_or_past_in_progress(status: &str) -> bool {
    matches!(
        status,
        "in_progress"
            | "under_review"
            | "disputed"
            | "remedied"
            | "complete"
            | "disbursement_pending"
            | "settled"
    )
}

/// Re-fetch the task's current status, returning it only when `keep` says the
/// idempotency target is met. A failed fetch or a non-matching status yields
/// `None` so the caller surfaces the original error — the re-check must
/// never mask the server's first answer (gh#143).
async fn current_status_if(
    client: &TaskFastClient,
    task_id: &Uuid,
    keep: fn(&str) -> bool,
) -> Option<String> {
    let task = client.inner().get_task(task_id).await.ok()?.into_inner();
    let status = task.status?;
    keep(&status).then_some(status)
}

async fn refuse(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
    let task_id = Uuid::parse_str(&args.id)
        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
    if ctx.dry_run {
        return Ok(Envelope::success(
            ctx.environment,
            ctx.dry_run,
            json!({ "action": "would_refuse", "task_id": task_id.to_string() }),
        ));
    }
    let client = ctx.client()?;
    let resp = match client.inner().refuse_task(&task_id).await {
        Ok(v) => v.into_inner(),
        Err(e) => return Err(map_api_error(e).await.into()),
    };
    Ok(Envelope::success(
        ctx.environment,
        ctx.dry_run,
        json!({ "refuse": resp }),
    ))
}

async fn concede(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
    let task_id = Uuid::parse_str(&args.id)
        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
    if ctx.dry_run {
        return Ok(Envelope::success(
            ctx.environment,
            ctx.dry_run,
            json!({ "action": "would_concede", "task_id": task_id.to_string() }),
        ));
    }
    let client = ctx.client()?;
    let resp = match client.inner().concede_dispute(&task_id).await {
        Ok(v) => v.into_inner(),
        Err(e) => return Err(map_api_error(e).await.into()),
    };
    Ok(Envelope::success(
        ctx.environment,
        ctx.dry_run,
        json!({ "concede": resp }),
    ))
}

async fn abort(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
    let task_id = Uuid::parse_str(&args.id)
        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
    if ctx.dry_run {
        return Ok(Envelope::success(
            ctx.environment,
            ctx.dry_run,
            json!({ "action": "would_abort", "task_id": task_id.to_string() }),
        ));
    }
    let client = ctx.client()?;
    let resp = match client.inner().abort_task(&task_id).await {
        Ok(v) => v.into_inner(),
        Err(e) => return Err(map_api_error(e).await.into()),
    };
    Ok(Envelope::success(
        ctx.environment,
        ctx.dry_run,
        json!({ "abort": resp }),
    ))
}

async fn reassign(ctx: &Ctx, args: ReassignArgs) -> CmdResult {
    let task_id = Uuid::parse_str(&args.id)
        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
    let agent_id = Uuid::parse_str(&args.agent_id)
        .map_err(|e| CmdError::Usage(format!("--agent-id must be a UUID: {e}")))?;
    if ctx.dry_run {
        return Ok(Envelope::success(
            ctx.environment,
            ctx.dry_run,
            json!({
                "action": "would_reassign",
                "task_id": task_id.to_string(),
                "agent_id": agent_id.to_string(),
            }),
        ));
    }
    let client = ctx.client()?;
    let body = ReassignTaskBody { agent_id };
    let resp = match client.inner().reassign_task(&task_id, &body).await {
        Ok(v) => v.into_inner(),
        Err(e) => return Err(map_api_error(e).await.into()),
    };
    Ok(Envelope::success(
        ctx.environment,
        ctx.dry_run,
        json!({ "reassign": resp }),
    ))
}

async fn reopen(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
    let task_id = Uuid::parse_str(&args.id)
        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
    if ctx.dry_run {
        return Ok(Envelope::success(
            ctx.environment,
            ctx.dry_run,
            json!({ "action": "would_reopen", "task_id": task_id.to_string() }),
        ));
    }
    let client = ctx.client()?;
    let resp = match client.inner().reopen_task(&task_id).await {
        Ok(v) => v.into_inner(),
        Err(e) => return Err(map_api_error(e).await.into()),
    };
    Ok(Envelope::success(
        ctx.environment,
        ctx.dry_run,
        json!({ "reopen": resp }),
    ))
}

async fn open(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
    let task_id = Uuid::parse_str(&args.id)
        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
    if ctx.dry_run {
        return Ok(Envelope::success(
            ctx.environment,
            ctx.dry_run,
            json!({ "action": "would_open", "task_id": task_id.to_string() }),
        ));
    }
    let client = ctx.client()?;
    let resp = match client.inner().open_task(&task_id).await {
        Ok(v) => v.into_inner(),
        Err(e) => return Err(map_api_error(e).await.into()),
    };
    Ok(Envelope::success(
        ctx.environment,
        ctx.dry_run,
        json!({ "open": resp }),
    ))
}

/// Poster: re-attempt the submission-fee charge for a task parked at
/// `blocked_on_submission_fee_debt` (gh#1159, CLI gh#156). Wraps
/// `POST /tasks/{id}/retry-fee` — the same call the task detail's
/// `next_action_command` advertises, so the recovery path is a real CLI
/// verb instead of a raw HTTP request. 409 `retry_not_needed` (transfer
/// still confirming) and `retry_in_progress` map to Validation so
/// orchestrators see the server's stable code.
async fn retry_fee(ctx: &Ctx, args: IdOnlyArgs) -> CmdResult {
    let task_id = Uuid::parse_str(&args.id)
        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
    if ctx.dry_run {
        return Ok(Envelope::success(
            ctx.environment,
            ctx.dry_run,
            json!({ "action": "would_retry_fee", "task_id": task_id.to_string() }),
        ));
    }
    let client = ctx.client()?;
    let resp = match client.inner().retry_submission_fee(&task_id).await {
        Ok(v) => v.into_inner(),
        Err(e) => return Err(map_api_error(e).await.into()),
    };
    Ok(Envelope::success(
        ctx.environment,
        ctx.dry_run,
        json!({
            "task_id": resp.task_id,
            "status": resp.status,
            "message": resp.message,
        }),
    ))
}

async fn edit(ctx: &Ctx, args: EditArgs) -> CmdResult {
    let task_id = Uuid::parse_str(&args.id)
        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
    // Reject empty edits locally — server would 422 and we'd rather fail fast.
    let any_change = args.title.is_some()
        || args.description.is_some()
        || args.budget_max.is_some()
        || args.review_window_hours.is_some()
        || args.remedy_window_hours.is_some();
    if !any_change {
        return Err(CmdError::Usage(
            "edit requires at least one of --title/--description/--budget-max/--review-window-hours/--remedy-window-hours".into(),
        ));
    }
    let body = TaskEditRequest {
        title: args.title.clone(),
        description: args.description.clone(),
        budget_max: args.budget_max.clone(),
        review_window_hours: args.review_window_hours,
        remedy_window_hours: args.remedy_window_hours,
        completion_criteria: Vec::new(),
    };
    if ctx.dry_run {
        return Ok(Envelope::success(
            ctx.environment,
            ctx.dry_run,
            json!({
                "action": "would_edit",
                "task_id": task_id.to_string(),
                "patch": body,
            }),
        ));
    }
    let client = ctx.client()?;
    let resp = match client.inner().edit_task(&task_id, &body).await {
        Ok(v) => v.into_inner(),
        Err(e) => return Err(map_api_error(e).await.into()),
    };
    Ok(Envelope::success(
        ctx.environment,
        ctx.dry_run,
        json!({ "task": resp }),
    ))
}

async fn bids(ctx: &Ctx, args: BidsArgs) -> CmdResult {
    let task_id = Uuid::parse_str(&args.id)
        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
    let client = ctx.client()?;
    let resp = match client
        .inner()
        .list_task_bids(
            &task_id,
            args.cursor.as_deref(),
            taskfast_client::page_limit(args.limit),
        )
        .await
    {
        Ok(v) => v.into_inner(),
        Err(e) => return Err(map_api_error(e).await.into()),
    };
    Ok(Envelope::success(
        ctx.environment,
        ctx.dry_run,
        json!({
            "task_id": task_id.to_string(),
            "bids": resp.data,
            "meta": resp.meta,
        }),
    ))
}

/// Path + derived metadata (filename, content_type) needed for multipart
/// upload. Parsed upfront so a missing file fails before any network I/O.
struct ResolvedArtifact {
    path: PathBuf,
    filename: String,
    content_type: String,
}

impl ResolvedArtifact {
    fn from_path(p: &std::path::Path) -> Result<Self, CmdError> {
        if !p.exists() {
            return Err(CmdError::Usage(format!(
                "artifact file not found: {}",
                p.display()
            )));
        }
        let filename = p
            .file_name()
            .and_then(|s| s.to_str())
            .ok_or_else(|| {
                CmdError::Usage(format!("artifact path has no filename: {}", p.display()))
            })?
            .to_string();
        let ext = p
            .extension()
            .and_then(|s| s.to_str())
            .map(|s| s.to_ascii_lowercase())
            .unwrap_or_default();
        let content_type = content_type_for_ext(&ext).to_string();
        Ok(Self {
            path: p.to_path_buf(),
            filename,
            content_type,
        })
    }

    fn display_path(&self) -> String {
        self.path.display().to_string()
    }
}

/// Map file extension to the MIME types the server accepts. Anything
/// unrecognized falls through to `application/octet-stream`; the server
/// rejects unsupported types with 415 which our error mapping surfaces as
/// `CmdError::Validation`.
pub(super) fn content_type_for_ext(ext: &str) -> &'static str {
    match ext {
        "txt" => "text/plain",
        // Markdown is plain UTF-8 text; the server allow-list accepts text/plain
        // but not text/markdown, and .md is the canonical deliverable format in
        // the agent skill (gh#674). Without this, .md uploads fall through to
        // application/octet-stream and the server 415s the submission.
        "md" | "markdown" => "text/plain",
        "csv" => "text/csv",
        "json" => "application/json",
        "xml" => "application/xml",
        "pdf" => "application/pdf",
        "doc" => "application/msword",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "webp" => "image/webp",
        "svg" => "image/svg+xml",
        "zip" => "application/zip",
        "tar" => "application/x-tar",
        "gz" => "application/gzip",
        "html" | "htm" => "text/html",
        "css" => "text/css",
        "js" => "application/javascript",
        _ => "application/octet-stream",
    }
}

async fn list(ctx: &Ctx, args: ListArgs) -> CmdResult {
    if args.status.is_some() && !matches!(args.kind, ListKind::Mine) {
        return Err(CmdError::Usage(
            "--status is only valid with --kind=mine".into(),
        ));
    }
    let client = ctx.client()?;
    let data = match args.kind {
        ListKind::Mine => list_mine(&client, &args).await?,
        ListKind::Queue => list_queue(&client, &args).await?,
        ListKind::Posted => list_posted(&client, &args).await?,
    };
    Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
}

async fn list_mine(
    client: &TaskFastClient,
    args: &ListArgs,
) -> Result<serde_json::Value, CmdError> {
    // The server owns the active-status classification: with no `status`
    // filter, `GET /agents/me/tasks` returns exactly the active set
    // (assigned / in_progress / under_review / disputed / remedied), and a
    // supplied `--status` narrows within it (taskfast#941). One page in, one
    // page out — no client-side filtering or re-paging.
    let status = args.status.map(|s| vec![ListMyTasksStatusItem::from(s)]);
    let resp = match client
        .inner()
        .list_my_tasks(
            args.cursor.as_deref(),
            taskfast_client::page_limit(args.limit),
            status.as_ref(),
        )
        .await
    {
        Ok(v) => v.into_inner(),
        Err(e) => return Err(map_api_error(e).await.into()),
    };
    Ok(json!({
        "kind": "mine",
        "tasks": resp.data,
        "meta": resp.meta,
    }))
}

async fn list_queue(
    client: &TaskFastClient,
    args: &ListArgs,
) -> Result<serde_json::Value, CmdError> {
    let resp = match client
        .inner()
        .get_agent_queue(
            args.cursor.as_deref(),
            taskfast_client::page_limit(args.limit),
        )
        .await
    {
        Ok(v) => v.into_inner(),
        Err(e) => return Err(map_api_error(e).await.into()),
    };
    Ok(json!({
        "kind": "queue",
        "tasks": resp.data,
        "meta": resp.meta,
    }))
}

async fn list_posted(
    client: &TaskFastClient,
    args: &ListArgs,
) -> Result<serde_json::Value, CmdError> {
    let resp = match client
        .inner()
        .get_agent_posted_tasks(
            args.cursor.as_deref(),
            taskfast_client::page_limit(args.limit),
        )
        .await
    {
        Ok(v) => v.into_inner(),
        Err(e) => return Err(map_api_error(e).await.into()),
    };
    Ok(json!({
        "kind": "posted",
        "tasks": resp.data,
        "meta": resp.meta,
    }))
}

async fn get(ctx: &Ctx, args: GetArgs) -> CmdResult {
    // Validate UUID locally — bad IDs shouldn't cost a round-trip.
    let id = Uuid::parse_str(&args.id)
        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
    let client = ctx.client()?;
    let task = match client.inner().get_task(&id).await {
        Ok(v) => v.into_inner(),
        Err(e) => return Err(map_api_error(e).await.into()),
    };
    Ok(Envelope::success(
        ctx.environment,
        ctx.dry_run,
        json!({ "task": task }),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn task_status_maps_to_generated_enum() {
        // Pin the mapping — changing it would be a silent wire-shape change.
        for (ours, theirs) in [
            (TaskStatus::InProgress, ListMyTasksStatusItem::InProgress),
            (TaskStatus::UnderReview, ListMyTasksStatusItem::UnderReview),
            (TaskStatus::Disputed, ListMyTasksStatusItem::Disputed),
            (TaskStatus::Remedied, ListMyTasksStatusItem::Remedied),
            (TaskStatus::Assigned, ListMyTasksStatusItem::Assigned),
        ] {
            // `ListMyTasksStatusItem: Display` — compare as strings to avoid
            // needing PartialEq on the foreign type.
            assert_eq!(
                ListMyTasksStatusItem::from(ours).to_string(),
                theirs.to_string()
            );
        }
    }

    #[test]
    fn content_type_maps_markdown_to_text_plain() {
        // gh#674 regression guard: the server allow-list accepts text/plain but
        // not text/markdown, so .md/.markdown must map to text/plain or the
        // submission 415s. Dropping either arm reintroduces the bug.
        assert_eq!(content_type_for_ext("md"), "text/plain");
        assert_eq!(content_type_for_ext("markdown"), "text/plain");
        // A representative non-markdown mapping and the unknown fallthrough,
        // so a future edit to the match can't silently collapse the table.
        assert_eq!(content_type_for_ext("json"), "application/json");
        assert_eq!(
            content_type_for_ext("unknownext"),
            "application/octet-stream"
        );
    }
}