taskfast-cli 0.21.0

`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
// SPDX-License-Identifier: MIT
//! Wiremock tests for `taskfast artifact`.

use std::io::Write;

use serde_json::json;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

use taskfast_cli::cmd::artifact::{
    run, CidArgs, CidStatusArg, CidStatusArgs, Command, GetArgs, ListArgs, UploadArgs,
};
use taskfast_cli::cmd::{CmdError, Ctx};
use taskfast_cli::{Envelope, Environment};

const TASK: &str = "11111111-1111-1111-1111-111111111111";
const ART: &str = "22222222-2222-2222-2222-222222222222";
const CID: &str = "bafybeih7n7nlocgmhshggjxpvwfaiy6dsj7n6gswi4yp7yz4xz4f6vzgpa";

fn ctx_for(server: &MockServer) -> Ctx {
    Ctx {
        api_key: Some("k".into()),
        environment: Environment::Local,
        api_base: Some(server.uri()),
        config_path: std::path::PathBuf::from("/dev/null"),
        dry_run: false,
        quiet: true,
        ..Default::default()
    }
}

fn env_value(e: &Envelope) -> serde_json::Value {
    serde_json::to_value(e).unwrap()
}

#[tokio::test]
async fn artifact_list_happy_path() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path(format!("/tasks/{TASK}/artifacts")))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": [{
                "id": ART,
                "filename": "a.txt",
                "content_type": "text/plain",
                "size_bytes": 5,
                "created_at": "2026-01-01T00:00:00Z",
                "url": "https://example.com/a.txt",
            }],
            "meta": {"next_cursor": null, "has_more": false, "total_count": 1}
        })))
        .mount(&server)
        .await;
    let envelope = run(
        &ctx_for(&server),
        Command::List(ListArgs {
            task_id: TASK.into(),
            cursor: None,
            limit: None,
        }),
    )
    .await
    .expect("list ok");
    let v = env_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["artifacts"].as_array().unwrap().len(), 1);
}

#[tokio::test]
async fn artifact_delete_404_maps_to_server() {
    let server = MockServer::start().await;
    Mock::given(method("DELETE"))
        .and(path(format!("/tasks/{TASK}/artifacts/{ART}")))
        .respond_with(ResponseTemplate::new(404).set_body_json(json!({"error": "gone"})))
        .mount(&server)
        .await;
    let err = run(
        &ctx_for(&server),
        Command::Delete(GetArgs {
            task_id: TASK.into(),
            artifact_id: ART.into(),
        }),
    )
    .await
    .expect_err("404 surfaces");
    // 404 is an unmapped status → decode path or server path; the point is
    // it's surfaced as an error, not silently swallowed.
    assert_ne!(err.code(), "ok");
}

#[tokio::test]
async fn artifact_upload_dry_run_skips_network() {
    let server = MockServer::start().await;
    // No mocks registered — if we hit the network, wiremock returns 404
    // and the test fails with an error-envelope surfacing.
    let tmp = tempfile::NamedTempFile::new().unwrap();
    writeln!(tmp.as_file(), "hello").unwrap();

    let ctx = Ctx {
        dry_run: true,
        ..ctx_for(&server)
    };
    let envelope = run(
        &ctx,
        Command::Upload(UploadArgs {
            task_id: TASK.into(),
            file: tmp.path().to_path_buf(),
        }),
    )
    .await
    .expect("dry-run upload ok");
    let v = env_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["action"], "would_upload_artifact");
}

#[tokio::test]
async fn artifact_upload_rejects_missing_file() {
    let server = MockServer::start().await;
    let err = run(
        &ctx_for(&server),
        Command::Upload(UploadArgs {
            task_id: TASK.into(),
            file: "/nonexistent/file.txt".into(),
        }),
    )
    .await
    .expect_err("missing file → usage");
    assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
}

#[tokio::test]
async fn artifact_cid_happy_path() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK}/artifacts/cid")))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "id": ART,
            "output_cid": CID,
            "task_id": TASK,
            "uploaded_by_id": "33333333-3333-3333-3333-333333333333",
            "created_at": "2026-01-01T00:00:00Z",
        })))
        .mount(&server)
        .await;
    let envelope = run(
        &ctx_for(&server),
        Command::Cid(CidArgs {
            task_id: TASK.into(),
            output_cid: CID.into(),
        }),
    )
    .await
    .expect("cid submit ok");
    let v = env_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["artifact"]["output_cid"], CID);
    assert_eq!(v["data"]["artifact"]["id"], ART);
}

#[tokio::test]
async fn artifact_cid_dry_run_skips_network() {
    let server = MockServer::start().await;
    // No mocks: a real request would 404 and surface an error envelope.
    let ctx = Ctx {
        dry_run: true,
        ..ctx_for(&server)
    };
    let envelope = run(
        &ctx,
        Command::Cid(CidArgs {
            task_id: TASK.into(),
            output_cid: CID.into(),
        }),
    )
    .await
    .expect("dry-run cid ok");
    let v = env_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["action"], "would_submit_cid");
    assert_eq!(v["data"]["output_cid"], CID);
}

#[tokio::test]
async fn artifact_cid_rejects_empty_cid() {
    let server = MockServer::start().await;
    let err = run(
        &ctx_for(&server),
        Command::Cid(CidArgs {
            task_id: TASK.into(),
            output_cid: "   ".into(),
        }),
    )
    .await
    .expect_err("empty cid → usage");
    assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
}

#[tokio::test]
async fn artifact_cid_status_happy_path() {
    let server = MockServer::start().await;
    Mock::given(method("PATCH"))
        .and(path(format!("/tasks/{TASK}/artifacts/{ART}/cid_status")))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "id": ART,
            "output_cid": CID,
            "cid_status": "unverifiable",
            "task_id": TASK,
            "updated_at": "2026-01-02T00:00:00Z",
        })))
        .mount(&server)
        .await;
    let envelope = run(
        &ctx_for(&server),
        Command::CidStatus(CidStatusArgs {
            task_id: TASK.into(),
            artifact_id: ART.into(),
            status: CidStatusArg::Unverifiable,
        }),
    )
    .await
    .expect("cid-status ok");
    let v = env_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["artifact"]["cid_status"], "unverifiable");
}

#[tokio::test]
async fn artifact_cid_status_dry_run_skips_network() {
    let server = MockServer::start().await;
    let ctx = Ctx {
        dry_run: true,
        ..ctx_for(&server)
    };
    let envelope = run(
        &ctx,
        Command::CidStatus(CidStatusArgs {
            task_id: TASK.into(),
            artifact_id: ART.into(),
            status: CidStatusArg::Witnessed,
        }),
    )
    .await
    .expect("dry-run cid-status ok");
    let v = env_value(&envelope);
    assert_eq!(v["ok"], true);
    assert_eq!(v["data"]["action"], "would_update_cid_status");
    assert_eq!(v["data"]["cid_status"], "witnessed");
}

// --- direct upload to R2 (gh#193) ---------------------------------------

const UPLOAD: &str = "33333333-3333-3333-3333-333333333333";

fn artifact_body() -> serde_json::Value {
    json!({
        "id": ART,
        "filename": "a.txt",
        "content_type": "text/plain",
        "size_bytes": 6,
        "created_at": "2026-01-01T00:00:00Z",
        "url": "artifacts/a.txt",
    })
}

fn put_ticket(url: String) -> serde_json::Value {
    json!({
        "upload_id": UPLOAD,
        "method": "put",
        "url": url,
        "headers": {"content-type": "text/plain"},
        "expires_at": (chrono::Utc::now() + chrono::Duration::minutes(15)).to_rfc3339(),
    })
}

async fn mount_initiate(server: &MockServer, resp: ResponseTemplate) {
    Mock::given(method("POST"))
        .and(path(format!("/tasks/{TASK}/artifacts/uploads")))
        .respond_with(resp)
        .mount(server)
        .await;
}

async fn upload_with(ctx: &Ctx) -> Result<Envelope, CmdError> {
    let tmp = tempfile::Builder::new().suffix(".txt").tempfile().unwrap();
    writeln!(tmp.as_file(), "hello").unwrap();
    run(
        ctx,
        Command::Upload(UploadArgs {
            task_id: TASK.into(),
            file: tmp.path().to_path_buf(),
        }),
    )
    .await
}

fn staging(server: &MockServer) -> Ctx {
    Ctx {
        environment: Environment::Staging,
        ..ctx_for(server)
    }
}

#[tokio::test]
async fn artifact_upload_puts_to_storage_then_completes() {
    let server = MockServer::start().await;
    mount_initiate(
        &server,
        ResponseTemplate::new(201).set_body_json(put_ticket(format!("{}/pending/x", server.uri()))),
    )
    .await;
    Mock::given(method("PUT"))
        .and(path("/pending/x"))
        .respond_with(ResponseTemplate::new(200))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path(format!(
            "/tasks/{TASK}/artifacts/uploads/{UPLOAD}/complete"
        )))
        .respond_with(ResponseTemplate::new(201).set_body_json(artifact_body()))
        .expect(1)
        .mount(&server)
        .await;

    // The mock is not an R2 host, so only --allow-custom-endpoints lets it through.
    let ctx = Ctx {
        allow_custom_endpoints: true,
        ..staging(&server)
    };
    let v = env_value(&upload_with(&ctx).await.expect("direct upload ok"));
    assert_eq!(v["data"]["artifact"]["id"], ART);
}

#[tokio::test]
async fn artifact_upload_refuses_non_r2_url_without_putting() {
    let server = MockServer::start().await;
    mount_initiate(
        &server,
        ResponseTemplate::new(201).set_body_json(put_ticket(format!("{}/pending/x", server.uri()))),
    )
    .await;
    Mock::given(method("PUT"))
        .respond_with(ResponseTemplate::new(200))
        .expect(0)
        .mount(&server)
        .await;
    let err = upload_with(&staging(&server))
        .await
        .expect_err("non-R2 host");
    assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
}

#[tokio::test]
async fn artifact_upload_on_staging_never_falls_back_to_multipart() {
    for initiate in [
        ResponseTemplate::new(404),
        ResponseTemplate::new(200).set_body_json(json!({"method": "multipart"})),
    ] {
        let server = MockServer::start().await;
        mount_initiate(&server, initiate).await;
        Mock::given(method("POST"))
            .and(path(format!("/tasks/{TASK}/artifacts")))
            .respond_with(ResponseTemplate::new(201).set_body_json(artifact_body()))
            .expect(0)
            .mount(&server)
            .await;
        let err = upload_with(&staging(&server))
            .await
            .expect_err("no fallback");
        assert_eq!(
            err.to_string(),
            "server: this server does not offer direct uploads"
        );
    }
}

#[tokio::test]
async fn artifact_upload_on_local_falls_back_to_multipart() {
    for initiate in [
        ResponseTemplate::new(404),
        ResponseTemplate::new(200).set_body_json(json!({"method": "multipart"})),
    ] {
        let server = MockServer::start().await;
        mount_initiate(&server, initiate).await;
        Mock::given(method("POST"))
            .and(path(format!("/tasks/{TASK}/artifacts")))
            .respond_with(ResponseTemplate::new(201).set_body_json(artifact_body()))
            .expect(1)
            .mount(&server)
            .await;
        let v = env_value(&upload_with(&ctx_for(&server)).await.expect("multipart ok"));
        assert_eq!(v["data"]["artifact"]["id"], ART);
    }
}

#[tokio::test]
async fn artifact_upload_413_passes_on_server_limit() {
    let server = MockServer::start().await;
    mount_initiate(
        &server,
        ResponseTemplate::new(413).set_body_json(json!({
            "error": "file_too_large",
            "message": "file size 6 bytes exceeds maximum of 50 MB",
            "max_bytes": 52_428_800,
        })),
    )
    .await;
    let err = upload_with(&staging(&server)).await.expect_err("413");
    assert_eq!(
        err.to_string(),
        "validation [file_too_large]: file size 6 bytes exceeds maximum of 50 MB (max_bytes: 52428800)"
    );
}