lex-api 0.9.4

HTTP/JSON + MCP server surface for the Lex toolchain.
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
//! M8 acceptance per spec §12.4.
//!
//! - All CLI commands work end-to-end on §3.13 examples (covered by
//!   crate-level tests across the workspace).
//! - The agent API server starts, handles 100 sequential requests
//!   without leaking memory, and returns the same results as the CLI.
//! - A scripted agent loop (publish → run → trace → patch → run)
//!   completes successfully. We exercise publish → run → trace → diff
//!   here; patch lands in a follow-up.

use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::sync::Arc;
use std::thread;
use std::time::Duration;

use lex_api::handlers::State;
use serde_json::json;
use tempfile::TempDir;

struct Server {
    addr: SocketAddr,
    _join: Option<thread::JoinHandle<()>>,
    _server_holder: Arc<()>,
}

fn start_server() -> (Server, TempDir) {
    let tmp = TempDir::new().unwrap();
    let server = tiny_http::Server::http(("127.0.0.1", 0))
        .expect("bind ephemeral port");
    let addr: SocketAddr = match server.server_addr() {
        tiny_http::ListenAddr::IP(addr) => addr,
        _ => panic!("expected IP listener"),
    };
    let state = Arc::new(State::open(tmp.path().to_path_buf()).unwrap());
    let join = thread::spawn(move || {
        lex_api::serve_on(server, state);
    });
    // Give the OS a moment to actually start listening.
    thread::sleep(Duration::from_millis(20));
    (Server { addr, _join: Some(join), _server_holder: Arc::new(()) }, tmp)
}

fn http(addr: &SocketAddr, method: &str, path: &str, body: &str) -> (u16, String) {
    let mut s = TcpStream::connect(addr).unwrap();
    s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
    let req = format!(
        "{method} {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
        body.len(), body
    );
    s.write_all(req.as_bytes()).unwrap();
    let mut buf = String::new();
    s.read_to_string(&mut buf).unwrap();
    let (head, body) = buf.split_once("\r\n\r\n").unwrap_or((&buf, ""));
    let status = head.split_whitespace().nth(1).unwrap_or("0").parse().unwrap_or(0);
    (status, body.to_string())
}

#[test]
fn health_check() {
    let (srv, _tmp) = start_server();
    let (status, body) = http(&srv.addr, "GET", "/v1/health", "");
    assert_eq!(status, 200);
    assert!(body.contains("\"ok\":true"));
}

#[test]
fn parse_then_check_pipeline() {
    let (srv, _tmp) = start_server();
    let src = "fn add(x :: Int, y :: Int) -> Int { x + y }\n";
    let body = json!({"source": src}).to_string();
    let (s1, b1) = http(&srv.addr, "POST", "/v1/parse", &body);
    assert_eq!(s1, 200);
    assert!(b1.contains("FnDecl"));
    let (s2, b2) = http(&srv.addr, "POST", "/v1/check", &body);
    assert_eq!(s2, 200);
    assert!(b2.contains("\"ok\":true"));
}

#[test]
fn parse_returns_4xx_on_syntax_error() {
    let (srv, _tmp) = start_server();
    let body = json!({"source": "fn"}).to_string();
    let (s, _) = http(&srv.addr, "POST", "/v1/parse", &body);
    assert!((400..500).contains(&s), "expected 4xx, got {s}");
}

#[test]
fn check_returns_422_on_type_error() {
    let (srv, _tmp) = start_server();
    let src = "fn bad(x :: Int) -> Str { x }\n";
    let body = json!({"source": src}).to_string();
    let (s, b) = http(&srv.addr, "POST", "/v1/check", &body);
    assert_eq!(s, 422);
    assert!(b.contains("type_mismatch"), "expected type_mismatch, body: {b}");
}

#[test]
fn agent_loop_publish_run_trace_diff() {
    // §12.4: a scripted agent loop completes successfully.
    let (srv, _tmp) = start_server();
    let src = "fn factorial(n :: Int) -> Int { match n { 0 => 1, _ => n * factorial(n - 1) } }\n";

    // 1) publish (and activate so resolve_sig works)
    let pub_body = json!({"source": src, "activate": true}).to_string();
    let (s, b) = http(&srv.addr, "POST", "/v1/publish", &pub_body);
    assert_eq!(s, 200, "publish status: {b}");
    let v: serde_json::Value = serde_json::from_str(&b).unwrap();
    // Response is {"ops": [...], "head_op": "..."}; first op is AddFunction.
    let ops = v["ops"].as_array().unwrap();
    assert!(!ops.is_empty(), "expected at least one op, got: {b}");
    let first_op = &ops[0];
    let stage_id = first_op["kind"]["stage_id"].as_str().unwrap();
    let _sig_id = first_op["kind"]["sig_id"].as_str().unwrap();
    assert!(v["head_op"].is_string(), "head_op should be set");

    // 2) get the published stage back
    let (s, b) = http(&srv.addr, "GET", &format!("/v1/stage/{stage_id}"), "");
    assert_eq!(s, 200, "stage GET: {b}");
    assert!(b.contains("FnDecl"));

    // 2b) #132: TypeCheck attestation written by the store-write
    // gate is queryable via /v1/stage/<id>/attestations.
    let (s, b) = http(&srv.addr, "GET", &format!("/v1/stage/{stage_id}/attestations"), "");
    assert_eq!(s, 200, "attestations GET: {b}");
    let v: serde_json::Value = serde_json::from_str(&b).unwrap();
    let atts = v["attestations"].as_array().expect("attestations array");
    assert!(!atts.is_empty(), "publish should have produced a TypeCheck attestation");
    assert_eq!(atts[0]["kind"]["kind"], "type_check");
    assert_eq!(atts[0]["result"]["result"], "passed");
    assert_eq!(atts[0]["produced_by"]["tool"], "lex-store");

    // 2c) Unknown stage_id → 404 (matches /v1/stage/<id>'s shape).
    let (s, _) = http(&srv.addr, "GET", "/v1/stage/nonexistent/attestations", "");
    assert_eq!(s, 404, "unknown stage_id should 404");

    // 3) run the function
    let run_body = json!({"source": src, "fn": "factorial", "args": [5]}).to_string();
    let (s, b) = http(&srv.addr, "POST", "/v1/run", &run_body);
    assert_eq!(s, 200);
    let v: serde_json::Value = serde_json::from_str(&b).unwrap();
    assert_eq!(v["output"], json!(120));
    let run_id_a = v["run_id"].as_str().unwrap().to_string();

    // 4) read the trace
    let (s, b) = http(&srv.addr, "GET", &format!("/v1/trace/{run_id_a}"), "");
    assert_eq!(s, 200);
    assert!(b.contains("factorial"));

    // 5) run again with a different argument and diff the two traces
    let run_body2 = json!({"source": src, "fn": "factorial", "args": [4]}).to_string();
    let (_, b2) = http(&srv.addr, "POST", "/v1/run", &run_body2);
    let v2: serde_json::Value = serde_json::from_str(&b2).unwrap();
    let run_id_b = v2["run_id"].as_str().unwrap().to_string();

    let (s, body) = http(&srv.addr, "GET", &format!("/v1/diff?a={run_id_a}&b={run_id_b}"), "");
    assert_eq!(s, 200);
    // Different inputs ⇒ a divergence.
    assert!(body.contains("node_id"), "expected divergence body: {body}");
}

#[test]
fn handles_100_sequential_requests() {
    // §12.4: server handles 100 sequential requests without crashing.
    let (srv, _tmp) = start_server();
    let body = json!({"source": "fn id(x :: Int) -> Int { x }\n"}).to_string();
    for _ in 0..100 {
        let (s, _) = http(&srv.addr, "POST", "/v1/check", &body);
        assert_eq!(s, 200);
    }
}

#[test]
fn run_rejects_undeclared_effect() {
    // §12.5: a program declaring [io] without policy is rejected at policy time.
    let (srv, _tmp) = start_server();
    let src = "import \"std.io\" as io\nfn say(line :: Str) -> [io] Nil { io.print(line) }\n";
    let body = json!({"source": src, "fn": "say", "args": ["x"]}).to_string();
    let (s, b) = http(&srv.addr, "POST", "/v1/run", &body);
    assert_eq!(s, 403, "expected 403, got {s}: {b}");
    assert!(b.contains("policy violation"));
    assert!(b.contains("io"));
}

#[test]
fn run_with_policy_succeeds() {
    let (srv, _tmp) = start_server();
    let src = "import \"std.io\" as io\nfn say(line :: Str) -> [io] Nil { io.print(line) }\n";
    let body = json!({
        "source": src, "fn": "say", "args": ["hello"],
        "policy": {"allow_effects": ["io"]},
    }).to_string();
    let (s, b) = http(&srv.addr, "POST", "/v1/run", &body);
    assert_eq!(s, 200, "expected 200, got {s}: {b}");
}

#[test]
fn merge_start_unknown_branch_returns_404() {
    let (srv, _tmp) = start_server();
    let body = json!({"src_branch": "nonexistent_a", "dst_branch": "nonexistent_b"}).to_string();
    let (s, b) = http(&srv.addr, "POST", "/v1/merge/start", &body);
    assert_eq!(s, 404, "unknown branch should 404, got {s}: {b}");
}

#[test]
fn merge_start_returns_session_id_and_no_conflicts_for_disjoint_branches() {
    // Two branches that touch *different* sigs auto-resolve into a
    // clean merge — no conflicts. The endpoint should still mint a
    // session, return the conflict list (empty), and report the
    // count of auto-resolved sigs so the agent can audit what the
    // engine took unilaterally.
    let (srv, tmp) = start_server();

    // 1) Publish fn foo on main.
    let src_main = "fn foo(n :: Int) -> Int { n + 1 }\n";
    let pub_main = json!({"source": src_main, "activate": true}).to_string();
    let (s, b) = http(&srv.addr, "POST", "/v1/publish", &pub_main);
    assert_eq!(s, 200, "publish main: {b}");

    // 2) Create + switch to feature, publish fn bar.
    {
        let store = lex_store::Store::open(tmp.path()).unwrap();
        store.create_branch("feature", lex_store::DEFAULT_BRANCH)
            .expect("create feature");
        store.set_current_branch("feature").expect("switch to feature");
    }
    let src_feature = "fn foo(n :: Int) -> Int { n + 1 }\nfn bar(n :: Int) -> Int { n - 1 }\n";
    let pub_feat = json!({"source": src_feature, "activate": true}).to_string();
    let (s, b) = http(&srv.addr, "POST", "/v1/publish", &pub_feat);
    assert_eq!(s, 200, "publish feature: {b}");

    // 3) Switch back to main so it remains the dst.
    {
        let store = lex_store::Store::open(tmp.path()).unwrap();
        store.set_current_branch(lex_store::DEFAULT_BRANCH).expect("switch back");
    }

    // 4) Start the merge.
    let body = json!({"src_branch": "feature", "dst_branch": lex_store::DEFAULT_BRANCH}).to_string();
    let (s, b) = http(&srv.addr, "POST", "/v1/merge/start", &body);
    assert_eq!(s, 200, "merge/start: {b}");
    let v: serde_json::Value = serde_json::from_str(&b).unwrap();
    assert!(v["merge_id"].as_str().is_some(), "merge_id should be set");
    let conflicts = v["conflicts"].as_array().unwrap();
    assert_eq!(conflicts.len(), 0, "disjoint adds shouldn't conflict, got {conflicts:?}");
    assert!(v["auto_resolved_count"].as_u64().unwrap() >= 1, "at least one sig auto-resolved");
}

/// Set up two branches that *both* modify the same fn (`foo`).
/// Returns the running server, the temp store dir, and the session
/// `merge_id` produced by `/v1/merge/start`. Used by the resolve
/// tests to avoid duplicating the divergence setup.
fn with_modify_modify_session() -> (Server, TempDir, String) {
    let (srv, tmp) = start_server();

    // 1) Publish initial fn on main.
    let v0 = "fn foo(n :: Int) -> Int { n }\n";
    let (s, b) = http(&srv.addr, "POST", "/v1/publish", &json!({"source": v0, "activate": true}).to_string());
    assert_eq!(s, 200, "publish v0: {b}");

    // 2) Create + switch to feature, modify foo.
    {
        let store = lex_store::Store::open(tmp.path()).unwrap();
        store.create_branch("feature", lex_store::DEFAULT_BRANCH).unwrap();
        store.set_current_branch("feature").unwrap();
    }
    let v_feat = "fn foo(n :: Int) -> Int { n + 1 }\n";
    let (s, b) = http(&srv.addr, "POST", "/v1/publish", &json!({"source": v_feat, "activate": true}).to_string());
    assert_eq!(s, 200, "publish feature: {b}");

    // 3) Switch back to main, modify foo differently.
    {
        let store = lex_store::Store::open(tmp.path()).unwrap();
        store.set_current_branch(lex_store::DEFAULT_BRANCH).unwrap();
    }
    let v_main = "fn foo(n :: Int) -> Int { n + 2 }\n";
    let (s, b) = http(&srv.addr, "POST", "/v1/publish", &json!({"source": v_main, "activate": true}).to_string());
    assert_eq!(s, 200, "publish main: {b}");

    // 4) Start the merge — should produce a ModifyModify conflict on `foo`.
    let body = json!({"src_branch": "feature", "dst_branch": lex_store::DEFAULT_BRANCH}).to_string();
    let (s, b) = http(&srv.addr, "POST", "/v1/merge/start", &body);
    assert_eq!(s, 200, "merge/start: {b}");
    let v: serde_json::Value = serde_json::from_str(&b).unwrap();
    let merge_id = v["merge_id"].as_str().unwrap().to_string();
    let conflicts = v["conflicts"].as_array().unwrap();
    assert_eq!(conflicts.len(), 1, "expected exactly one conflict, got: {conflicts:?}");
    (srv, tmp, merge_id)
}

#[test]
fn merge_resolve_take_ours_clears_the_conflict() {
    let (srv, _tmp, merge_id) = with_modify_modify_session();
    let path = format!("/v1/merge/{merge_id}/resolve");
    // Find the conflict id (same as sig_id of `foo`).
    let (_, start_body) = http(&srv.addr, "POST", "/v1/merge/start", &json!({
        "src_branch": "feature", "dst_branch": lex_store::DEFAULT_BRANCH,
    }).to_string());
    // Re-run start to pull a fresh conflict list keyed to a *new* merge_id —
    // but the resolution we're testing is against `merge_id` from the
    // helper, so the conflict_id is the same (sig).
    let v: serde_json::Value = serde_json::from_str(&start_body).unwrap();
    let conflict_id = v["conflicts"][0]["conflict_id"].as_str().unwrap().to_string();

    let body = json!({
        "resolutions": [
            {"conflict_id": conflict_id, "resolution": {"kind": "take_ours"}}
        ]
    }).to_string();
    let (s, b) = http(&srv.addr, "POST", &path, &body);
    assert_eq!(s, 200, "resolve: {b}");
    let v: serde_json::Value = serde_json::from_str(&b).unwrap();
    let verdicts = v["verdicts"].as_array().unwrap();
    assert_eq!(verdicts.len(), 1);
    assert_eq!(verdicts[0]["accepted"], true);
    let remaining = v["remaining_conflicts"].as_array().unwrap();
    assert_eq!(remaining.len(), 0, "the take_ours resolution should clear the conflict");
}

#[test]
fn merge_resolve_unknown_conflict_is_rejected_per_entry() {
    let (srv, _tmp, merge_id) = with_modify_modify_session();
    let path = format!("/v1/merge/{merge_id}/resolve");
    let body = json!({
        "resolutions": [
            {"conflict_id": "definitely-not-a-real-sig", "resolution": {"kind": "take_ours"}}
        ]
    }).to_string();
    let (s, b) = http(&srv.addr, "POST", &path, &body);
    assert_eq!(s, 200, "resolve should still 200 with per-entry verdicts");
    let v: serde_json::Value = serde_json::from_str(&b).unwrap();
    let verdicts = v["verdicts"].as_array().unwrap();
    assert_eq!(verdicts[0]["accepted"], false);
    assert_eq!(verdicts[0]["rejection"]["kind"], "unknown_conflict");
}

#[test]
fn web_activity_stream_lists_recent_attestations() {
    // The new home page (lex-tea v2) is an activity stream sourced
    // from the attestation log. After a publish, there's at least
    // one TypeCheck::Passed event the page should render.
    let (srv, _tmp) = start_server();
    let src = "fn foo(n :: Int) -> Int { n }\n";
    let (s, _) = http(&srv.addr, "POST", "/v1/publish", &json!({"source": src, "activate": true}).to_string());
    assert_eq!(s, 200);

    let (s, b) = http(&srv.addr, "GET", "/", "");
    assert_eq!(s, 200, "GET /: {b}");
    assert!(b.contains("<title>") && b.contains("lex-tea"), "html title: {b}");
    assert!(b.contains("activity"), "activity heading expected: {b}");
    assert!(b.contains("TypeCheck"), "auto-emitted TypeCheck row expected: {b}");
    assert!(b.contains("/web/stage/"), "should link to stage detail: {b}");
}

#[test]
fn web_branches_page_lists_branches() {
    // The v1 home moved to /web/branches in v2; verify it still
    // renders the branch list.
    let (srv, _tmp) = start_server();
    let src = "fn foo(n :: Int) -> Int { n }\n";
    let (s, _) = http(&srv.addr, "POST", "/v1/publish", &json!({"source": src, "activate": true}).to_string());
    assert_eq!(s, 200);

    let (s, b) = http(&srv.addr, "GET", "/web/branches", "");
    assert_eq!(s, 200, "GET /web/branches: {b}");
    assert!(b.contains("main"), "branch list should mention main: {b}");
}

#[test]
fn web_trust_page_groups_by_producer() {
    // After a publish, the trust page should show a row for the
    // store-side producer (`lex-store`) since the type-check gate
    // auto-emitted a TypeCheck attestation under that name.
    let (srv, _tmp) = start_server();
    let src = "fn foo(n :: Int) -> Int { n }\n";
    let (s, _) = http(&srv.addr, "POST", "/v1/publish", &json!({"source": src, "activate": true}).to_string());
    assert_eq!(s, 200);

    let (s, b) = http(&srv.addr, "GET", "/web/trust", "");
    assert_eq!(s, 200, "GET /web/trust: {b}");
    assert!(b.contains("trust"), "trust heading: {b}");
    assert!(b.contains("lex-store"), "lex-store producer row: {b}");
}

#[test]
fn web_attention_empty_when_only_passed_attestations_exist() {
    // The exceptions table should be empty when every attestation
    // is Passed — the "clear runway" message renders. Exercises
    // the attention page's empty-state path so a regression that
    // accidentally shows passed attestations as exceptions is
    // caught.
    let (srv, _tmp) = start_server();
    let src = "fn foo(n :: Int) -> Int { n }\n";
    let (s, _) = http(&srv.addr, "POST", "/v1/publish", &json!({"source": src, "activate": true}).to_string());
    assert_eq!(s, 200);

    let (s, b) = http(&srv.addr, "GET", "/web/attention", "");
    assert_eq!(s, 200, "GET /web/attention: {b}");
    assert!(b.contains("attention"), "attention heading: {b}");
    assert!(b.contains("clear runway") || b.contains("no failed"),
        "empty-state copy expected: {b}");
}

#[test]
fn web_branch_page_lists_fn_with_stage_link() {
    let (srv, _tmp) = start_server();
    let src = "fn foo(n :: Int) -> Int { n }\n";
    let (s, _) = http(&srv.addr, "POST", "/v1/publish", &json!({"source": src, "activate": true}).to_string());
    assert_eq!(s, 200);

    let (s, b) = http(&srv.addr, "GET", "/web/branch/main", "");
    assert_eq!(s, 200, "GET /web/branch/main: {b}");
    assert!(b.contains("foo"), "fn name should appear: {b}");
    assert!(b.contains("/web/stage/"), "should link to stage page: {b}");
}

#[test]
fn web_stage_page_shows_attestations() {
    let (srv, _tmp) = start_server();
    let src = "fn foo(n :: Int) -> Int { n }\n";
    let (s, b) = http(&srv.addr, "POST", "/v1/publish", &json!({"source": src, "activate": true}).to_string());
    assert_eq!(s, 200);
    let v: serde_json::Value = serde_json::from_str(&b).unwrap();
    let stage_id = v["ops"][0]["kind"]["stage_id"].as_str().unwrap();

    let (s, b) = http(&srv.addr, "GET", &format!("/web/stage/{stage_id}"), "");
    assert_eq!(s, 200, "GET /web/stage/<id>: {b}");
    // The TypeCheck attestation auto-emitted by publish_program
    // should show up on the page.
    assert!(b.contains("TypeCheck"), "TypeCheck attestation row expected: {b}");
    assert!(b.contains("passed"), "passed result expected: {b}");
    assert!(b.contains("foo"), "fn name in heading expected: {b}");
}

#[test]
fn web_unknown_stage_returns_404_html() {
    let (srv, _tmp) = start_server();
    let (s, _) = http(&srv.addr, "GET", "/web/stage/no_such_stage", "");
    assert_eq!(s, 404);
}

#[test]
fn merge_resolve_unknown_session_returns_404() {
    let (srv, _tmp) = start_server();
    let body = json!({"resolutions": []}).to_string();
    let (s, _) = http(&srv.addr, "POST", "/v1/merge/no_such_session/resolve", &body);
    assert_eq!(s, 404, "unknown merge_id should 404");
}

#[test]
fn merge_commit_advances_dst_branch_after_take_theirs() {
    // Full e2e: start → resolve(take_theirs) → commit. dst branch
    // head must move to a new Merge op whose StageTransition picks
    // up src's stage for the resolved sig.
    let (srv, _tmp, merge_id) = with_modify_modify_session();
    let path_resolve = format!("/v1/merge/{merge_id}/resolve");
    let path_commit  = format!("/v1/merge/{merge_id}/commit");

    // Pull the conflict id.
    let (_, b) = http(&srv.addr, "POST", "/v1/merge/start", &json!({
        "src_branch": "feature", "dst_branch": lex_store::DEFAULT_BRANCH,
    }).to_string());
    let v: serde_json::Value = serde_json::from_str(&b).unwrap();
    let conflict_id = v["conflicts"][0]["conflict_id"].as_str().unwrap().to_string();

    // Resolve as take_theirs.
    let body = json!({
        "resolutions": [
            {"conflict_id": conflict_id, "resolution": {"kind": "take_theirs"}}
        ]
    }).to_string();
    let (s, _) = http(&srv.addr, "POST", &path_resolve, &body);
    assert_eq!(s, 200);

    // Commit.
    let (s, b) = http(&srv.addr, "POST", &path_commit, "");
    assert_eq!(s, 200, "commit: {b}");
    let v: serde_json::Value = serde_json::from_str(&b).unwrap();
    let new_head = v["new_head_op"].as_str().expect("new_head_op set");
    assert!(!new_head.is_empty());
    assert_eq!(v["dst_branch"], lex_store::DEFAULT_BRANCH);
}

#[test]
fn merge_commit_with_unresolved_conflicts_returns_422() {
    // No resolutions submitted → conflicts remaining → 422.
    let (srv, _tmp, merge_id) = with_modify_modify_session();
    let path_commit = format!("/v1/merge/{merge_id}/commit");
    let (s, b) = http(&srv.addr, "POST", &path_commit, "");
    assert_eq!(s, 422, "expected 422 conflicts remaining: {b}");
    assert!(b.contains("conflicts remaining"));
}

#[test]
fn merge_commit_unknown_session_returns_404() {
    let (srv, _tmp) = start_server();
    let (s, _) = http(&srv.addr, "POST", "/v1/merge/no_such/commit", "");
    assert_eq!(s, 404);
}

#[test]
fn merge_commit_with_custom_resolution_lands_agent_supplied_stage() {
    // Same ModifyModify setup as the take_theirs test, but the
    // agent submits a `Custom { op }` whose ModifyBody.to_stage_id
    // names a brand-new stage. commit folds the op's target into
    // the merge entries.
    let (srv, _tmp, merge_id) = with_modify_modify_session();
    let path_resolve = format!("/v1/merge/{merge_id}/resolve");
    let path_commit  = format!("/v1/merge/{merge_id}/commit");

    // Pull conflict + ours/theirs stage ids from the fresh session
    // start (same merge_id; conflict_id == sig).
    let (_, b) = http(&srv.addr, "POST", "/v1/merge/start", &json!({
        "src_branch": "feature", "dst_branch": lex_store::DEFAULT_BRANCH,
    }).to_string());
    let v: serde_json::Value = serde_json::from_str(&b).unwrap();
    let conflict = &v["conflicts"][0];
    let conflict_id = conflict["conflict_id"].as_str().unwrap().to_string();
    let ours_stage = conflict["ours"].as_str().unwrap().to_string();
    let theirs_stage = conflict["theirs"].as_str().unwrap().to_string();
    let custom_stage = "stage-agent-resolved-001".to_string();

    let resolve_body = json!({
        "resolutions": [
            {
                "conflict_id": conflict_id,
                "resolution": {
                    "kind": "custom",
                    "op": {
                        // Operation's `kind` is #[serde(flatten)],
                        // so OperationKind's tag + fields appear at
                        // the top level alongside `parents`.
                        "op": "modify_body",
                        "sig_id": conflict_id,
                        "from_stage_id": ours_stage,
                        "to_stage_id":   custom_stage,
                        "parents": [
                            // Conflict resolution must list both
                            // sides; MergeSession enforces parents.len() ≥ 2.
                            ours_stage.clone(),
                            theirs_stage,
                        ],
                    }
                }
            }
        ]
    }).to_string();
    let (s, b) = http(&srv.addr, "POST", &path_resolve, &resolve_body);
    assert_eq!(s, 200, "resolve: {b}");
    let rv: serde_json::Value = serde_json::from_str(&b).unwrap();
    assert_eq!(rv["verdicts"][0]["accepted"], true);

    let (s, b) = http(&srv.addr, "POST", &path_commit, "");
    assert_eq!(s, 200, "commit: {b}");
    // After commit, dst's branch_head for `foo` should be the
    // agent-supplied custom stage. We can verify via the public
    // /v1/stage/<id> endpoint isn't present (it's not a real
    // stage), but the merge op recorded the head delta — read the
    // op log via /v1/diff is overkill; instead just check the
    // response's new_head_op is set.
    let cv: serde_json::Value = serde_json::from_str(&b).unwrap();
    assert!(cv["new_head_op"].as_str().is_some());
}

#[test]
fn merge_commit_rejects_custom_op_targeting_wrong_sig() {
    let (srv, _tmp, merge_id) = with_modify_modify_session();
    let path_resolve = format!("/v1/merge/{merge_id}/resolve");
    let path_commit  = format!("/v1/merge/{merge_id}/commit");

    let (_, b) = http(&srv.addr, "POST", "/v1/merge/start", &json!({
        "src_branch": "feature", "dst_branch": lex_store::DEFAULT_BRANCH,
    }).to_string());
    let v: serde_json::Value = serde_json::from_str(&b).unwrap();
    let conflict_id = v["conflicts"][0]["conflict_id"].as_str().unwrap().to_string();

    let resolve_body = json!({
        "resolutions": [{
            "conflict_id": conflict_id,
            "resolution": {
                "kind": "custom",
                "op": {
                    "op": "modify_body",
                    "sig_id": "fn::not_the_conflict_sig",
                    "from_stage_id": "x",
                    "to_stage_id":   "y",
                    "parents": ["a", "b"],
                }
            }
        }]
    }).to_string();
    let (s, _) = http(&srv.addr, "POST", &path_resolve, &resolve_body);
    assert_eq!(s, 200, "resolve accepts; mismatch caught at commit");
    let (s, b) = http(&srv.addr, "POST", &path_commit, "");
    assert_eq!(s, 422, "commit should 422 on mismatched-sig custom op: {b}");
    assert!(b.contains("targets a different sig"));
}

#[test]
fn replay_with_overrides() {
    let (srv, _tmp) = start_server();
    let src = "import \"std.io\" as io\nfn read_one(p :: Str) -> [io] Result[Str, Str] { io.read(p) }\n";

    // First run: io.read fails because path doesn't exist; result is Err(...) value-level.
    let run = json!({
        "source": src, "fn": "read_one", "args": ["/no/such"],
        "policy": {"allow_effects": ["io"]},
    }).to_string();
    let (s, b) = http(&srv.addr, "POST", "/v1/run", &run);
    assert_eq!(s, 200);
    let v: serde_json::Value = serde_json::from_str(&b).unwrap();
    let run_id = v["run_id"].as_str().unwrap().to_string();

    // Pull the trace, find the io.read NodeId.
    let (_, body) = http(&srv.addr, "GET", &format!("/v1/trace/{run_id}"), "");
    let trace: serde_json::Value = serde_json::from_str(&body).unwrap();
    let mut effect_node_id: Option<String> = None;
    fn find(n: &serde_json::Value, out: &mut Option<String>) {
        if let Some(arr) = n.as_array() {
            for c in arr { find(c, out); }
            return;
        }
        if let Some(kind) = n.get("kind").and_then(|k| k.as_str()) {
            if kind == "effect" {
                if let Some(nid) = n.get("node_id").and_then(|x| x.as_str()) {
                    *out = Some(nid.to_string());
                }
            }
        }
        if let Some(children) = n.get("children") { find(children, out); }
        if let Some(nodes) = n.get("nodes") { find(nodes, out); }
    }
    find(&trace, &mut effect_node_id);
    let nid = effect_node_id.expect("trace has an effect node");

    // Replay with override.
    let injected = json!({"$variant": "Ok", "args": ["INJECTED"]});
    let replay = json!({
        "source": src, "fn": "read_one", "args": ["/no/such"],
        "policy": {"allow_effects": ["io"]},
        "overrides": { nid: injected },
    }).to_string();
    let (s, b) = http(&srv.addr, "POST", "/v1/replay", &replay);
    assert_eq!(s, 200, "replay status: {s}, body: {b}");
    let v: serde_json::Value = serde_json::from_str(&b).unwrap();
    assert_eq!(v["output"], json!({"$variant": "Ok", "args": ["INJECTED"]}));
}

#[test]
fn patch_replaces_a_subexpression_and_publishes_new_stage() {
    // Publish a stage, patch a sub-expression, run the patched stage.
    let (srv, _tmp) = start_server();
    let src = "fn add_one(x :: Int) -> Int { x + 1 }\n";

    // 1. Publish the original.
    let pub_body = json!({"source": src, "activate": true}).to_string();
    let (s, b) = http(&srv.addr, "POST", "/v1/publish", &pub_body);
    assert_eq!(s, 200, "publish: {b}");
    let v: serde_json::Value = serde_json::from_str(&b).unwrap();
    let stage_id = v["ops"][0]["kind"]["stage_id"].as_str().unwrap().to_string();

    // 2. Patch the literal `1` with `100`. Body sits at n_0.2 (1 param);
    //    BinOp.rhs is at n_0.2.1.
    let patch_body = json!({
        "stage_id": stage_id,
        "patch": {
            "op": "replace",
            "target": "n_0.2.1",
            "with": { "node": "Literal", "value": { "kind": "Int", "value": 100 } }
        },
        "activate": true,
    }).to_string();
    let (s, b) = http(&srv.addr, "POST", "/v1/patch", &patch_body);
    assert_eq!(s, 200, "patch: {b}");
    let v: serde_json::Value = serde_json::from_str(&b).unwrap();
    let new_id = v["new_stage_id"].as_str().unwrap().to_string();
    assert_ne!(new_id, stage_id, "new StageId must differ from original");
    assert_eq!(v["status"], "active");

    // 3. Run the patched function: add_one(5) should now be 105.
    let run_body = json!({"source": "fn add_one(x :: Int) -> Int { x + 100 }\n",
                         "fn": "add_one", "args": [5]}).to_string();
    let (s, b) = http(&srv.addr, "POST", "/v1/run", &run_body);
    assert_eq!(s, 200);
    let v: serde_json::Value = serde_json::from_str(&b).unwrap();
    assert_eq!(v["output"], json!(105));
}

#[test]
fn patch_with_type_error_after_apply_returns_422() {
    // Replacing an Int with a Str should fail typecheck and surface 422
    // with the structured TypeError list.
    let (srv, _tmp) = start_server();
    let src = "fn add_one(x :: Int) -> Int { x + 1 }\n";

    let (s, b) = http(&srv.addr, "POST", "/v1/publish",
        &json!({"source": src, "activate": true}).to_string());
    assert_eq!(s, 200);
    let stage_id = serde_json::from_str::<serde_json::Value>(&b).unwrap()
        ["ops"][0]["kind"]["stage_id"].as_str().unwrap().to_string();

    // Replace `1` (Int) with `"oops"` (Str).
    let patch_body = json!({
        "stage_id": stage_id,
        "patch": {
            "op": "replace",
            "target": "n_0.2.1",
            "with": { "node": "Literal", "value": { "kind": "Str", "value": "oops" } }
        },
    }).to_string();
    let (s, b) = http(&srv.addr, "POST", "/v1/patch", &patch_body);
    assert_eq!(s, 422, "expected 422 on type-incompatible patch, got {s}: {b}");
    assert!(b.contains("type_mismatch"), "body should carry structured TypeError: {b}");
}

#[test]
fn patch_with_unknown_node_returns_422() {
    let (srv, _tmp) = start_server();
    let (s, b) = http(&srv.addr, "POST", "/v1/publish",
        &json!({"source": "fn one() -> Int { 1 }\n", "activate": true}).to_string());
    assert_eq!(s, 200);
    let stage_id = serde_json::from_str::<serde_json::Value>(&b).unwrap()
        ["ops"][0]["kind"]["stage_id"].as_str().unwrap().to_string();

    let patch_body = json!({
        "stage_id": stage_id,
        "patch": {
            "op": "replace",
            "target": "n_0.99.99",
            "with": { "node": "Literal", "value": { "kind": "Int", "value": 0 } }
        },
    }).to_string();
    let (s, b) = http(&srv.addr, "POST", "/v1/patch", &patch_body);
    assert_eq!(s, 422);
    assert!(b.contains("unknown_node"), "expected unknown_node in body: {b}");
}