assay-lua 0.20.2

General-purpose enhanced Lua runtime. Batteries-included scripting, automation, and web services.
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
//! assay.forge against the forge MCP shapes probed live on 2026-09-04,
//! anonymised. What is pinned: the per-product header, the domain name arriving
//! as `sld` and `tld` and never whole, the health report's tri-state where an
//! omitted check is unknown rather than failing, warm-up read off the two halves
//! of the curve, a placement row with no counts reading as no test rather than
//! as zero, Warmforge paging by `totalPages`, the frame being chosen by its
//! JSON-RPC id, and auth and rate limits reading as themselves.

#[path = "../common/mod.rs"]
mod common;

use common::run_lua;
use serde_json::json;
use wiremock::matchers::{body_string_contains, header, headers, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

const WS: &str = "wks_xa1";

fn client(product: &str, uri: &str) -> String {
    format!(
        "local f = require(\"assay.forge\")\n\
         local c = f.{product}({{ api_key = \"k\", workspace_id = \"{WS}\", base_url = \"{uri}\" }})\n"
    )
}

/// The tool's own payload arrives as a JSON string nested in the reply's text
/// part, which is why the envelope is parsed twice.
fn reply(payload: serde_json::Value) -> ResponseTemplate {
    ResponseTemplate::new(200).set_body_json(json!({
        "jsonrpc": "2.0",
        "id": 1,
        "result": { "content": [{ "type": "text", "text": payload.to_string() }] },
    }))
}

async fn mount_tool(server: &MockServer, key_header: &str, tool: &str, payload: serde_json::Value) {
    Mock::given(method("POST"))
        .and(path("/"))
        .and(header(key_header, "k"))
        // A Streamable-HTTP endpoint decides between a JSON body and an SSE
        // stream from this header. Sending only one of the two would leave the
        // module unable to read half of what the server may legally answer, so
        // both media types are pinned, in order.
        .and(headers(
            "accept",
            vec!["application/json", "text/event-stream"],
        ))
        .and(header("content-type", "application/json"))
        .and(body_string_contains(tool))
        .respond_with(reply(payload))
        .mount(server)
        .await;
}

fn warmforge_row() -> serde_json::Value {
    json!({
        "id": "mbx_xa1", "address": "ada@example.test", "status": "active",
        "provider": "smtp", "warm": false, "warmupEnabled": true,
        "warmupDaysCompleted": 9, "warmupDaysLeft": 5,
        "healthReport": {
            "address": "ada@example.test", "domain": "example.test", "id": "mbx_xa1",
            "heatScore": 82, "warmupDays": 9, "lastCheckedAt": "2026-09-04T01:08:08Z",
            "spf": { "status": "valid", "value": "v=spf1 include:_spf.example.test ~all" },
            "dkim": { "status": "valid", "selector": "google" },
            "mx": { "status": "invalid", "value": "" },
            "blacklists": {
                "detectedCount": 1,
                "checks": [
                    { "id": "clean.example.test", "name": "Clean", "detected": false },
                    { "id": "listed.example.test", "name": "Listed", "detected": true },
                ],
            },
        },
    })
}

/// The vendor answers the name in two halves and never as one string. A reader
/// that looks only for a whole name finds no domains at all.
#[tokio::test]
async fn test_a_primeforge_domain_name_is_sld_and_tld_joined() {
    let server = MockServer::start().await;
    mount_tool(
        &server,
        "X-Primeforge-Key",
        "primeforge_list_domains",
        json!({
            "pagination": { "limit": 10, "offset": 0 },
            "results": [
                { "id": "dom_xa1", "sld": "Example", "tld": "TEST", "status": "active" },
                { "id": "dom_xa2", "status": "active" },
            ],
        }),
    )
    .await;
    run_lua(&format!(
        "{}{}",
        client("primeforge", &server.uri()),
        r#"
        local rows = c:domains()
        assert.eq(#rows, 1)
        assert.eq(rows[1].domain, "example.test")
        assert.eq(rows[1].provider, "primeforge")
        assert.eq(rows[1].provider_ref, "dom_xa1")
        "#
    ))
    .await
    .unwrap();
}

/// `primeforge_list_mailboxes` takes `workspaceId` and nothing else — probed
/// live, it ignores `limit` and `offset` and answers the same ten rows at every
/// offset. So the domain filter is applied to what the vendor gives, and the
/// request must not claim to send one.
#[tokio::test]
async fn test_primeforge_filters_mailboxes_by_domain_without_sending_a_filter() {
    let server = MockServer::start().await;
    mount_tool(
        &server,
        "X-Primeforge-Key",
        "primeforge_list_mailboxes",
        json!({ "results": [
            { "id": "mbx_xa1", "address": "Ada@Example.TEST", "status": "ACTIVE",
              "domainId": "dom_xa1", "password": "hunter2", "appPassword": "abcd efgh" },
            { "id": "mbx_xa2", "address": "bo@other.test", "status": "active",
              "domainId": "dom_xa2" },
        ] }),
    )
    .await;
    run_lua(&format!(
        "{}{}",
        client("primeforge", &server.uri()),
        r#"
        assert.eq(#c:mailboxes(), 2)
        local rows, meta = c:mailboxes("dom_xa1")
        assert.eq(#rows, 1)
        assert.eq(rows[1].address, "ada@example.test")
        assert.eq(rows[1].domain, "example.test")
        assert.eq(rows[1].raw.password, "[redacted]")
        assert.eq(rows[1].raw.appPassword, "[redacted]")
        -- Two rows is under the cap, so this window really is everything.
        assert.eq(meta.truncated, false)
        assert.eq(meta.cap, 10)
        assert.eq(meta.seen, 2)
        "#
    ))
    .await
    .unwrap();
    let sent = &server.received_requests().await.unwrap()[0];
    let body = String::from_utf8(sent.body.clone()).unwrap();
    assert!(body.contains(WS), "workspace not sent: {body}");
    assert!(
        !body.contains("limit"),
        "sent a paging argument the tool ignores: {body}"
    );
    assert!(
        !body.contains("domainId"),
        "sent a filter the tool does not accept: {body}"
    );
}

/// Each product authenticates with its own header on the one shared endpoint.
/// Sending Primeforge's header to Warmforge reads as a refused key.
#[tokio::test]
async fn test_each_product_sends_its_own_key_header() {
    let server = MockServer::start().await;
    mount_tool(
        &server,
        "X-Warmforge-Key",
        "warmforge_list_mailboxes",
        json!({ "mailboxes": [warmforge_row()], "page": 1, "pageSize": 50, "totalPages": 1 }),
    )
    .await;
    run_lua(&format!(
        "{}{}",
        client("warmforge", &server.uri()),
        r#"
        local rows = c:mailboxes()
        assert.eq(#rows, 1)
        assert.eq(rows[1].address, "ada@example.test")
        assert.eq(rows[1].provider, "warmforge")
        assert.eq(rows[1].provider_ref, "mbx_xa1")
        "#
    ))
    .await
    .unwrap();
    // A Primeforge client against the same mock never matches the header, so the
    // endpoint answers 404 rather than data.
    run_lua(&format!(
        "{}{}",
        client("primeforge", &server.uri()),
        r#"
        local rows, err = c:mailboxes()
        assert.eq(rows, nil)
        assert.eq(err.code, "http")
        "#
    ))
    .await
    .unwrap();
}

/// A check the report does not mention has not been run. Reading an omitted one
/// as a failure tells an operator a record they published is missing.
#[tokio::test]
async fn test_the_health_report_is_tri_state_and_an_omitted_check_is_unknown() {
    let server = MockServer::start().await;
    mount_tool(
        &server,
        "X-Warmforge-Key",
        "warmforge_list_mailboxes",
        json!({ "mailboxes": [warmforge_row()], "totalPages": 1 }),
    )
    .await;
    run_lua(&format!(
        "{}{}",
        client("warmforge", &server.uri()),
        r#"
        local h = c:health("ADA@example.test")
        assert.eq(h.spf, "valid")
        assert.eq(h.dkim, "valid")
        assert.eq(h.mx, "invalid")
        -- The row carries no dmarc at all. It is not a failing DMARC.
        assert.eq(h.dmarc, "unknown")
        assert.eq(h.heat, 82)
        assert.eq(h.blacklists.detected, 1)
        assert.eq(h.blacklists.lists[1], "listed.example.test")
        "#
    ))
    .await
    .unwrap();
}

/// The vendor reports days done and days left, so the curve's length is their
/// sum rather than a constant this module keeps in step with the vendor's.
#[tokio::test]
async fn test_warmup_day_and_total_come_off_the_two_halves_of_the_curve() {
    let server = MockServer::start().await;
    mount_tool(
        &server,
        "X-Warmforge-Key",
        "warmforge_list_mailboxes",
        json!({ "mailboxes": [warmforge_row()], "totalPages": 1 }),
    )
    .await;
    run_lua(&format!(
        "{}{}",
        client("warmforge", &server.uri()),
        r#"
        local w = c:warmup("ada@example.test")
        assert.eq(w.day, 9)
        assert.eq(w.total_days, 14)
        assert.eq(w.heat, 82)
        assert.eq(w.enabled, true)
        local missing, err = c:warmup("nobody@example.test")
        assert.eq(missing, nil)
        assert.eq(err.code, "not_found")
        "#
    ))
    .await
    .unwrap();
}

/// A heat score outside 0..100, or not a number, is not a reading.
#[tokio::test]
async fn test_a_heat_score_outside_the_scale_is_not_a_reading() {
    run_lua(
        r#"
        local f = require("assay.forge")
        assert.eq(f.heat(82), 82)
        assert.eq(f.heat(140), nil)
        assert.eq(f.heat(-1), nil)
        assert.eq(f.heat("hot"), nil)
        "#,
    )
    .await
    .unwrap();
}

/// The tool answers a row per mailbox whether or not a test has ever run, so a
/// row with no folder counts is a test nobody took and not a placement of zero.
#[tokio::test]
async fn test_a_placement_row_with_no_counts_is_no_test_not_a_zero() {
    let server = MockServer::start().await;
    mount_tool(
        &server,
        "X-Warmforge-Key",
        "warmforge_list_mailboxes",
        json!({ "mailboxes": [warmforge_row()], "totalPages": 1 }),
    )
    .await;
    mount_tool(
        &server,
        "X-Warmforge-Key",
        "warmforge_get_latest_mailbox_placement_results",
        json!({ "results": [
            { "address": "ada@example.test", "mailboxId": "mbx_xa1", "provider": "smtp" },
        ] }),
    )
    .await;
    run_lua(&format!(
        "{}{}",
        client("warmforge", &server.uri()),
        r#"
        local p, err = c:placement("ada@example.test")
        assert.eq(p, nil)
        assert.eq(err, nil)
        local f = require("assay.forge")
        assert.eq(f.placement(80, 15, 5).inbox, 0.8)
        assert.eq(f.placement(0.8, 0.15, 0.05).spam, 0.15)
        assert.eq(f.placement(0, 0, 0), nil)
        "#
    ))
    .await
    .unwrap();
}

/// Warmforge pages for real: `page` and `page_size` are not optional and
/// `totalPages` is the stop condition. A caller that read one page would report
/// a fleet smaller than the one it holds.
#[tokio::test]
async fn test_warmforge_pages_to_total_pages() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(body_string_contains("\"page\":1"))
        .respond_with(reply(json!({
            "mailboxes": [{ "id": "mbx_xp1", "address": "one@example.test" }],
            "page": 1, "pageSize": 50, "totalPages": 2,
        })))
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(body_string_contains("\"page\":2"))
        .respond_with(reply(json!({
            "mailboxes": [{ "id": "mbx_xp2", "address": "two@example.test" }],
            "page": 2, "pageSize": 50, "totalPages": 2,
        })))
        .mount(&server)
        .await;
    run_lua(&format!(
        "{}{}",
        client("warmforge", &server.uri()),
        r#"
        local rows = c:mailboxes()
        assert.eq(#rows, 2)
        assert.eq(rows[2].address, "two@example.test")
        "#
    ))
    .await
    .unwrap();
}

/// A Streamable-HTTP endpoint may answer with a stream, and a stream can carry
/// frames this call did not ask for. Taking the last frame reads a server
/// notification as an answer, so the frame is chosen by its JSON-RPC id.
#[tokio::test]
async fn test_the_reply_frame_is_chosen_by_its_json_rpc_id() {
    let server = MockServer::start().await;
    let answer = json!({ "results": [{ "id": "dom_xa1", "sld": "example", "tld": "test" }] });
    let stream = format!(
        "event: message\ndata: {}\n\nevent: message\ndata: {}\n\n",
        json!({ "jsonrpc": "2.0", "id": 1,
                "result": { "content": [{ "text": answer.to_string() }] } }),
        json!({ "jsonrpc": "2.0", "method": "notifications/progress", "params": {} }),
    );
    Mock::given(method("POST"))
        .respond_with(ResponseTemplate::new(200).set_body_raw(stream, "text/event-stream"))
        .mount(&server)
        .await;
    run_lua(&format!(
        "{}{}",
        client("primeforge", &server.uri()),
        r#"
        local rows = c:domains()
        assert.eq(#rows, 1)
        assert.eq(rows[1].domain, "example.test")
        "#
    ))
    .await
    .unwrap();
}

/// A refused key is not an empty workspace.
#[tokio::test]
async fn test_auth_and_rate_limits_read_as_themselves_not_as_absence() {
    for (status, code) in [
        (401u16, "auth"),
        (403, "auth"),
        (429, "rate_limit"),
        (502, "server"),
    ] {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .respond_with(ResponseTemplate::new(status))
            .mount(&server)
            .await;
        let check = format!(
            r#"
            local rows, err = c:domains()
            assert.eq(rows, nil)
            assert.eq(err.code, "{code}")
            assert.eq(err.status, {status})
            assert.contains(tostring(err), "forge: ")
            "#
        );
        run_lua(&format!("{}{check}", client("primeforge", &server.uri())))
            .await
            .unwrap();
    }
}

/// A tool that answers with a JSON-RPC error says so; read as an empty payload
/// it would look like a workspace with nothing in it.
#[tokio::test]
async fn test_a_tool_error_reads_as_a_tool_error() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0", "id": 1,
            "error": { "code": -32602, "message": "unknown workspace" },
        })))
        .mount(&server)
        .await;
    run_lua(&format!(
        "{}{}",
        client("primeforge", &server.uri()),
        r#"
        local rows, err = c:domains()
        assert.eq(rows, nil)
        assert.eq(err.code, "tool")
        assert.contains(err.message, "unknown workspace")
        "#
    ))
    .await
    .unwrap();
}

/// A client with no key, no workspace, or an unknown product is a programming
/// error rather than a vendor answer.
#[tokio::test]
async fn test_a_client_refuses_to_build_without_a_key_or_a_workspace() {
    for args in [r#"{ workspace_id = "wks_xa1" }"#, r#"{ api_key = "k" }"#] {
        let err = run_lua(&format!(
            "local f = require(\"assay.forge\")\nf.primeforge({args})"
        ))
        .await
        .unwrap_err()
        .to_string();
        assert!(err.contains("required"), "gave {err}");
    }
    run_lua(
        r#"
        local f = require("assay.forge")
        local payload, err = f.mcp("nopeforge", "k", "any_tool")
        assert.eq(payload, nil)
        assert.eq(err.code, "product")
        "#,
    )
    .await
    .unwrap();
}

/// The vendor answering exactly its cap has said nothing about what lies past
/// it. A domain whose boxes fall outside that window returns no rows and no
/// error, so without `meta` the caller reads a truncated window as a domain
/// with nothing on it.
#[tokio::test]
async fn test_a_full_primeforge_window_reports_itself_as_truncated() {
    let server = MockServer::start().await;
    let ten: Vec<serde_json::Value> = (0..10)
        .map(|n| {
            json!({ "id": format!("mbx_x{n}"), "address": format!("p{n}@example.test"),
                    "domainId": "dom_xa1", "status": "active" })
        })
        .collect();
    mount_tool(
        &server,
        "X-Primeforge-Key",
        "primeforge_list_mailboxes",
        json!({ "results": ten, "pagination": { "limit": 10, "offset": 0 } }),
    )
    .await;
    run_lua(&format!(
        "{}{}",
        client("primeforge", &server.uri()),
        r#"
        local rows, meta = c:mailboxes()
        assert.eq(#rows, 10)
        assert.eq(meta.truncated, true)
        assert.eq(meta.cap, 10)
        assert.eq(meta.seen, 10)
        -- The silent case the signal exists for: a domain with no rows in this
        -- window looks identical to a domain with no mailboxes at all.
        local none, none_meta = c:mailboxes("dom_elsewhere")
        assert.eq(#none, 0)
        assert.eq(none_meta.truncated, true)
        "#
    ))
    .await
    .unwrap();
}

/// A short answer is the vendor running out of rows, which is the whole set.
#[tokio::test]
async fn test_a_short_primeforge_domain_list_is_not_truncated() {
    let server = MockServer::start().await;
    mount_tool(
        &server,
        "X-Primeforge-Key",
        "primeforge_list_domains",
        json!({ "results": [{ "id": "dom_xa1", "sld": "example", "tld": "test" }] }),
    )
    .await;
    run_lua(&format!(
        "{}{}",
        client("primeforge", &server.uri()),
        r#"
        local rows, meta = c:domains()
        assert.eq(#rows, 1)
        assert.eq(meta.truncated, false)
        assert.eq(meta.seen, 1)
        "#
    ))
    .await
    .unwrap();
}

/// An address missing from a truncated window is not an address the workspace
/// lacks, and the error has to say which of the two it is.
#[tokio::test]
async fn test_a_miss_inside_a_truncated_window_says_so() {
    let server = MockServer::start().await;
    let full: Vec<serde_json::Value> = (0..50)
        .map(|n| json!({ "id": format!("mbx_x{n}"), "address": format!("p{n}@example.test") }))
        .collect();
    // Every page answers full and the vendor names no `totalPages`, so the walk
    // can only ever stop at the page cap.
    Mock::given(method("POST"))
        .respond_with(reply(json!({ "mailboxes": full })))
        .mount(&server)
        .await;
    run_lua(&format!(
        "{}{}",
        client("warmforge", &server.uri()),
        r#"
        local rows, meta = c:mailboxes()
        assert.eq(meta.truncated, true)
        assert.eq(meta.cap, 2500)
        local missing, err = c:warmup("nobody@example.test")
        assert.eq(missing, nil)
        assert.eq(err.code, "not_found")
        assert.contains(err.message, "truncated")
        "#
    ))
    .await
    .unwrap();
}

/// A walk that stopped because the vendor said `totalPages` has everything.
#[tokio::test]
async fn test_a_warmforge_walk_that_reaches_total_pages_is_not_truncated() {
    let server = MockServer::start().await;
    mount_tool(
        &server,
        "X-Warmforge-Key",
        "warmforge_list_mailboxes",
        json!({ "mailboxes": [warmforge_row()], "page": 1, "pageSize": 50, "totalPages": 1 }),
    )
    .await;
    run_lua(&format!(
        "{}{}",
        client("warmforge", &server.uri()),
        r#"
        local rows, meta = c:mailboxes()
        assert.eq(#rows, 1)
        assert.eq(meta.truncated, false)
        assert.eq(meta.seen, 1)
        "#
    ))
    .await
    .unwrap();
}