rustio-core 2.0.5

Runtime core for RustIO: HTTP server, router, middleware, ORM, admin, and migrations.
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
//! Tests for the rule-based AI planner. Kept in its own file (rather
//! than inline) because the grammar surface is wide enough that the
//! test list is long and benefits from being read on its own.
//!
//! Invariants every test enforces:
//!
//! - Planner output **always** passes `Plan::validate(&schema)`.
//! - Planner **never** emits `CreateMigration` (developer-only).
//! - Planner is deterministic — same prompt + schema → same plan.

use super::planner::{
    generate_plan, render_plan_human, render_plan_json, ContextConfig, PlanError, PlanRequest,
};
use super::{Primitive, RelationKind};
use crate::schema::{Schema, SchemaField, SchemaModel, SCHEMA_VERSION};

fn pkg_version() -> String {
    env!("CARGO_PKG_VERSION").to_string()
}

fn task_schema() -> Schema {
    Schema {
        version: SCHEMA_VERSION,
        rustio_version: pkg_version(),
        models: vec![SchemaModel {
            name: "Task".into(),
            table: "tasks".into(),
            admin_name: "tasks".into(),
            display_name: "Tasks".into(),
            singular_name: "Task".into(),
            fields: vec![
                SchemaField {
                    name: "id".into(),
                    ty: "i64".into(),
                    nullable: false,
                    editable: false,
                    relation: None,
                },
                SchemaField {
                    name: "title".into(),
                    ty: "String".into(),
                    nullable: false,
                    editable: true,
                    relation: None,
                },
            ],
            relations: vec![],
            core: false,
        }],
    }
}

fn applicant_schema() -> Schema {
    Schema {
        version: SCHEMA_VERSION,
        rustio_version: pkg_version(),
        models: vec![SchemaModel {
            name: "Applicant".into(),
            table: "applicants".into(),
            admin_name: "applicants".into(),
            display_name: "Applicants".into(),
            singular_name: "Applicant".into(),
            fields: vec![SchemaField {
                name: "id".into(),
                ty: "i64".into(),
                nullable: false,
                editable: false,
                relation: None,
            }],
            relations: vec![],
            core: false,
        }],
    }
}

fn schema_with_core_user() -> Schema {
    Schema {
        version: SCHEMA_VERSION,
        rustio_version: pkg_version(),
        models: vec![SchemaModel {
            name: "User".into(),
            table: "rustio_users".into(),
            admin_name: "users".into(),
            display_name: "Users".into(),
            singular_name: "User".into(),
            fields: vec![
                SchemaField {
                    name: "id".into(),
                    ty: "i64".into(),
                    nullable: false,
                    editable: false,
                    relation: None,
                },
                SchemaField {
                    name: "email".into(),
                    ty: "String".into(),
                    nullable: false,
                    editable: true,
                    relation: None,
                },
            ],
            relations: vec![],
            core: true,
        }],
    }
}

// ---------- simple add field ----------

#[test]
fn simple_add_field_infers_i32_for_priority() {
    let schema = task_schema();
    let res = generate_plan(&schema, None, PlanRequest::new("Add priority to tasks"))
        .expect("plan should succeed");
    assert_eq!(res.plan.steps.len(), 1);
    match &res.plan.steps[0] {
        Primitive::AddField(a) => {
            assert_eq!(a.model, "Task");
            assert_eq!(a.field.name, "priority");
            assert_eq!(a.field.ty, "i32");
            assert!(!a.field.nullable);
            assert!(a.field.editable);
        }
        other => panic!("expected AddField, got {other:?}"),
    }
    // Plan must survive the real Plan::validate against the same schema.
    res.plan.validate(&schema).unwrap();
    assert!(res.explanation.contains("priority"));
}

#[test]
fn monetary_names_infer_i64() {
    // 0.7.2: `*_income`, `*_amount`, `*_total`, `price`, `balance`
    // resolve to `i64` — we store monetary amounts in minor units
    // where `i32` can overflow.
    let schema = task_schema();
    for (prompt, field, expected_ty) in [
        ("add annual_income to tasks", "annual_income", "i64"),
        ("add balance to tasks", "balance", "i64"),
        ("add price to tasks", "price", "i64"),
        ("add total_amount to tasks", "total_amount", "i64"),
        ("add order_total to tasks", "order_total", "i64"),
    ] {
        let res = generate_plan(&schema, None, PlanRequest::new(prompt))
            .unwrap_or_else(|e| panic!("prompt `{prompt}` failed: {e}"));
        match &res.plan.steps[0] {
            Primitive::AddField(a) => {
                assert_eq!(a.field.name, field, "field mismatch for `{prompt}`");
                assert_eq!(a.field.ty, expected_ty, "type mismatch for `{prompt}`",);
            }
            other => panic!("expected AddField for `{prompt}`, got {other:?}"),
        }
    }
}

#[test]
fn count_suffix_still_infers_i32() {
    // Regression canary: adding the `_income`/`_amount`/`_total`
    // branch must not disturb the existing `_count` → i32 rule.
    let schema = task_schema();
    let res = generate_plan(&schema, None, PlanRequest::new("add order_count to tasks")).unwrap();
    match &res.plan.steps[0] {
        Primitive::AddField(a) => assert_eq!(a.field.ty, "i32"),
        _ => panic!("wrong primitive"),
    }
}

#[test]
fn add_due_date_infers_datetime_and_nullable_on_hint() {
    let schema = task_schema();
    let res = generate_plan(
        &schema,
        None,
        PlanRequest::new("Add optional due date to tasks"),
    )
    .unwrap();
    match &res.plan.steps[0] {
        Primitive::AddField(a) => {
            assert_eq!(a.field.name, "due_date");
            assert_eq!(a.field.ty, "DateTime");
            assert!(a.field.nullable);
        }
        _ => panic!("wrong primitive"),
    }
}

#[test]
fn add_field_with_explicit_type_wins_over_heuristics() {
    let schema = task_schema();
    // `priority` would normally resolve to i32; `as i64` forces it.
    let res = generate_plan(
        &schema,
        None,
        PlanRequest::new("add priority as i64 to tasks"),
    )
    .unwrap();
    match &res.plan.steps[0] {
        Primitive::AddField(a) => {
            assert_eq!(a.field.ty, "i64");
        }
        _ => panic!("wrong primitive"),
    }
}

#[test]
fn add_field_that_already_exists_is_rejected() {
    let schema = task_schema();
    let err = generate_plan(&schema, None, PlanRequest::new("add title to tasks"))
        .expect_err("should reject");
    match err {
        PlanError::FieldAlreadyExists { model, field } => {
            assert_eq!(model, "Task");
            assert_eq!(field, "title");
        }
        other => panic!("wrong error: {other:?}"),
    }
}

// ---------- rename field ----------

#[test]
fn rename_field_emits_rename_primitive_not_remove_plus_add() {
    let schema = task_schema();
    let res = generate_plan(
        &schema,
        None,
        PlanRequest::new("rename title to name in tasks"),
    )
    .unwrap();
    assert_eq!(res.plan.steps.len(), 1);
    match &res.plan.steps[0] {
        Primitive::RenameField(r) => {
            assert_eq!(r.model, "Task");
            assert_eq!(r.from, "title");
            assert_eq!(r.to, "name");
        }
        other => panic!("expected RenameField, got {other:?}"),
    }
    res.plan.validate(&schema).unwrap();
}

#[test]
fn rename_missing_field_errors() {
    let schema = task_schema();
    let err = generate_plan(
        &schema,
        None,
        PlanRequest::new("rename nope to something in tasks"),
    )
    .expect_err("should reject");
    assert!(matches!(err, PlanError::FieldDoesNotExist { .. }));
}

#[test]
fn rename_field_collides_with_existing_target() {
    let mut schema = task_schema();
    schema.models[0].fields.push(SchemaField {
        name: "name".into(),
        ty: "String".into(),
        nullable: false,
        editable: true,
        relation: None,
    });
    let err = generate_plan(
        &schema,
        None,
        PlanRequest::new("rename title to name in tasks"),
    )
    .expect_err("should reject");
    match err {
        PlanError::FieldAlreadyExists { model, field } => {
            assert_eq!(model, "Task");
            assert_eq!(field, "name");
        }
        other => panic!("wrong error: {other:?}"),
    }
}

// ---------- invalid model ----------

#[test]
fn unknown_model_is_reported_with_hint() {
    let schema = task_schema();
    let err = generate_plan(&schema, None, PlanRequest::new("add priority to widgets"))
        .expect_err("should reject");
    match err {
        PlanError::UnknownModel { hint } => assert_eq!(hint, "widgets"),
        other => panic!("wrong error: {other:?}"),
    }
}

// ---------- context-aware ----------

#[test]
fn swedish_context_upgrades_personnummer_to_string() {
    let schema = applicant_schema();
    let ctx = ContextConfig {
        country: Some("SE".into()),
        ..Default::default()
    };
    let res = generate_plan(
        &schema,
        Some(&ctx),
        PlanRequest::new("add personnummer to applicants"),
    )
    .unwrap();
    match &res.plan.steps[0] {
        Primitive::AddField(a) => {
            assert_eq!(a.field.name, "personnummer");
            assert_eq!(a.field.ty, "String");
            assert!(!a.field.nullable);
        }
        other => panic!("expected AddField, got {other:?}"),
    }
    assert!(
        res.explanation.to_lowercase().contains("personnummer"),
        "explanation should mention personnummer: {}",
        res.explanation,
    );
}

#[test]
fn without_context_personnummer_still_parses_but_has_generic_rationale() {
    let schema = applicant_schema();
    let res = generate_plan(
        &schema,
        None,
        PlanRequest::new("add personnummer to applicants"),
    )
    .unwrap();
    // Without SE context we still infer String (identifier fallback).
    match &res.plan.steps[0] {
        Primitive::AddField(a) => assert_eq!(a.field.ty, "String"),
        other => panic!("expected AddField, got {other:?}"),
    }
    // But no Swedish sentence.
    assert!(
        !res.explanation.contains("Swedish"),
        "explanation should not reference Sweden without context: {}",
        res.explanation,
    );
}

// ---------- plan validation failure ----------

#[test]
fn emitted_plan_always_passes_plan_validate() {
    // Property-style: across every prompt that succeeds, the returned
    // plan must survive `Plan::validate(&schema)`.
    let schema = task_schema();
    let prompts = [
        "add priority to tasks",
        "add optional notes to tasks",
        "rename title to name in tasks",
        "change title in tasks to String",
        "make title in tasks optional",
        "remove title from tasks",
    ];
    for p in prompts {
        let res = generate_plan(&schema, None, PlanRequest::new(p))
            .unwrap_or_else(|e| panic!("prompt `{p}` failed: {e}"));
        res.plan
            .validate(&schema)
            .unwrap_or_else(|e| panic!("prompt `{p}` produced invalid plan: {e}"));
        // And no developer-only primitives slipped in.
        for step in &res.plan.steps {
            assert!(
                !step.is_developer_only(),
                "planner emitted a developer-only primitive for `{p}`",
            );
        }
    }
}

#[test]
fn planner_never_emits_create_migration() {
    let schema = task_schema();
    let res = generate_plan(&schema, None, PlanRequest::new("add priority to tasks")).unwrap();
    for step in &res.plan.steps {
        assert!(
            !matches!(step, Primitive::CreateMigration(_)),
            "planner must never emit CreateMigration"
        );
    }
}

#[test]
fn developer_only_requests_are_rejected_loudly() {
    let schema = task_schema();
    for bad in [
        "create migration foo",
        "run sql: drop table tasks",
        "execute sql DELETE FROM tasks",
        "add raw sql to tasks",
    ] {
        let err = generate_plan(&schema, None, PlanRequest::new(bad))
            .expect_err(&format!("should reject `{bad}`"));
        assert!(
            matches!(err, PlanError::DeveloperOnlyRequested(_)),
            "wrong error for `{bad}`: {err:?}",
        );
    }
}

// ---------- chaining (rename → change type) via two sequential calls ----------

#[test]
fn rename_then_change_type_composes_as_two_validated_plans() {
    // Each plan is single-step in 0.5.0; the caller chains by applying
    // the shadow of plan 1 to the schema before building plan 2.
    let mut schema = task_schema();

    let plan1 = generate_plan(
        &schema,
        None,
        PlanRequest::new("rename title to name in tasks"),
    )
    .unwrap();
    plan1.plan.validate(&schema).unwrap();
    // Shadow-apply step 1 to the schema so step 2 sees the new name.
    for step in &plan1.plan.steps {
        crate::ai::validate_against(step, &schema).unwrap();
    }
    // Simulate the shadow using the public Plan::validate on a
    // fresh schema (mutation path inside ai.rs is private; the public
    // surface is `Plan::validate` which runs the shadow internally).
    // For chaining across calls we mutate the schema ourselves:
    if let Primitive::RenameField(r) = &plan1.plan.steps[0] {
        let model = schema
            .models
            .iter_mut()
            .find(|m| m.name == r.model)
            .unwrap();
        model
            .fields
            .iter_mut()
            .find(|f| f.name == r.from)
            .unwrap()
            .name = r.to.clone();
    } else {
        panic!("expected RenameField");
    }

    let plan2 = generate_plan(
        &schema,
        None,
        PlanRequest::new("change name in tasks to String"),
    )
    .unwrap();
    plan2.plan.validate(&schema).unwrap();
    match &plan2.plan.steps[0] {
        Primitive::ChangeFieldType(c) => {
            assert_eq!(c.model, "Task");
            assert_eq!(c.field, "name");
            assert_eq!(c.new_type, "String");
        }
        _ => panic!("wrong primitive"),
    }
}

// ---------- misc robustness ----------

#[test]
fn empty_prompt_is_rejected() {
    let schema = task_schema();
    let err = generate_plan(&schema, None, PlanRequest::new("   ")).expect_err("should reject");
    assert!(matches!(err, PlanError::EmptyPrompt));
}

#[test]
fn unknown_intent_returns_supported_forms_list() {
    let schema = task_schema();
    let err = generate_plan(&schema, None, PlanRequest::new("please do something nice"))
        .expect_err("should reject");
    match err {
        PlanError::InvalidIntent(msg) => {
            for needle in ["add ", "rename ", "remove ", "change ", "make "] {
                assert!(
                    msg.contains(needle),
                    "supported-forms message should list `{needle}` — got: {msg}",
                );
            }
        }
        other => panic!("wrong error: {other:?}"),
    }
}

#[test]
fn remove_field_refuses_on_missing_field() {
    let schema = task_schema();
    let err = generate_plan(&schema, None, PlanRequest::new("remove nope from tasks"))
        .expect_err("should reject");
    assert!(matches!(err, PlanError::FieldDoesNotExist { .. }));
}

#[test]
fn remove_model_is_developer_only_not_a_plan() {
    let schema = task_schema();
    let err = generate_plan(&schema, None, PlanRequest::new("remove model tasks"))
        .expect_err("should reject");
    assert!(matches!(err, PlanError::DeveloperOnlyRequested(_)));
}

#[test]
fn core_models_are_protected() {
    let schema = schema_with_core_user();
    let err = generate_plan(&schema, None, PlanRequest::new("add nickname to users"))
        .expect_err("should reject");
    assert!(
        matches!(err, PlanError::CoreModelProtected(ref n) if n == "User"),
        "wrong error: {err:?}",
    );
}

#[test]
fn rename_model_emits_schema_level_rename() {
    let schema = task_schema();
    let res = generate_plan(&schema, None, PlanRequest::new("rename model Task to Todo")).unwrap();
    match &res.plan.steps[0] {
        Primitive::RenameModel(r) => {
            assert_eq!(r.from, "Task");
            assert_eq!(r.to, "Todo");
        }
        _ => panic!("wrong primitive"),
    }
    res.plan.validate(&schema).unwrap();
}

#[test]
fn change_field_type_accepts_synonyms() {
    let schema = task_schema();
    for (prompt, expected) in [
        ("change title in tasks to text", "String"),
        ("change title in tasks to datetime", "DateTime"),
        ("change title in tasks to int", "i32"),
        ("change title in tasks to bigint", "i64"),
        ("change title in tasks to boolean", "bool"),
    ] {
        let res = generate_plan(&schema, None, PlanRequest::new(prompt))
            .unwrap_or_else(|e| panic!("prompt `{prompt}` failed: {e}"));
        match &res.plan.steps[0] {
            Primitive::ChangeFieldType(c) => assert_eq!(c.new_type, expected, "prompt `{prompt}`"),
            _ => panic!("wrong primitive for `{prompt}`"),
        }
    }
}

#[test]
fn change_field_type_unknown_type_is_rejected() {
    let schema = task_schema();
    let err = generate_plan(
        &schema,
        None,
        PlanRequest::new("change title in tasks to foo"),
    )
    .expect_err("should reject");
    assert!(matches!(err, PlanError::UnknownType(_)));
}

#[test]
fn make_optional_emits_change_nullability() {
    let schema = task_schema();
    let res = generate_plan(
        &schema,
        None,
        PlanRequest::new("make title in tasks optional"),
    )
    .unwrap();
    match &res.plan.steps[0] {
        Primitive::ChangeFieldNullability(c) => {
            assert_eq!(c.model, "Task");
            assert_eq!(c.field, "title");
            assert!(c.nullable);
        }
        _ => panic!("wrong primitive"),
    }
}

// ---------- planner is deterministic ----------

#[test]
fn same_prompt_produces_byte_for_byte_same_plan_json() {
    let schema = task_schema();
    let req = || PlanRequest::new("add priority to tasks");
    let a = generate_plan(&schema, None, req()).unwrap();
    let b = generate_plan(&schema, None, req()).unwrap();
    assert_eq!(
        render_plan_json(&a.plan, &a.explanation),
        render_plan_json(&b.plan, &b.explanation),
    );
}

// ---------- relation kind is unused in 0.5.0 planner ----------

#[test]
fn relation_kind_symbol_is_linked_for_future_use() {
    // Prevents a dead-import warning in release mode; the grammar
    // doesn't emit relations in 0.5.0 but the symbol is wired up so
    // future parsers can see it.
    let _ = RelationKind::HasMany;
}

// ---------- 0.8.0 relations ----------

fn housing_schema() -> Schema {
    Schema {
        version: SCHEMA_VERSION,
        rustio_version: pkg_version(),
        models: vec![
            SchemaModel {
                name: "Applicant".into(),
                table: "applicants".into(),
                admin_name: "applicants".into(),
                display_name: "Applicants".into(),
                singular_name: "Applicant".into(),
                fields: vec![SchemaField {
                    name: "id".into(),
                    ty: "i64".into(),
                    nullable: false,
                    editable: false,
                    relation: None,
                }],
                relations: vec![],
                core: false,
            },
            SchemaModel {
                name: "Application".into(),
                table: "applications".into(),
                admin_name: "applications".into(),
                display_name: "Applications".into(),
                singular_name: "Application".into(),
                fields: vec![SchemaField {
                    name: "id".into(),
                    ty: "i64".into(),
                    nullable: false,
                    editable: false,
                    relation: None,
                }],
                relations: vec![],
                core: false,
            },
        ],
    }
}

#[test]
fn add_relation_from_to_emits_belongs_to() {
    let schema = housing_schema();
    let res = generate_plan(
        &schema,
        None,
        PlanRequest::new("add relation from Application to Applicant"),
    )
    .expect("planner should accept a well-formed relation prompt");
    assert_eq!(res.plan.steps.len(), 1, "expected a single primitive");
    match &res.plan.steps[0] {
        Primitive::AddRelation(r) => {
            assert_eq!(r.from, "Application");
            assert_eq!(r.to, "Applicant");
            assert_eq!(r.via, "applicant_id");
            assert_eq!(r.kind, RelationKind::BelongsTo);
        }
        other => panic!("expected AddRelation, got {other:?}"),
    }
    assert!(
        res.explanation.contains("belongs_to"),
        "explanation should name the kind: {}",
        res.explanation,
    );
    assert!(
        res.explanation.contains("FOREIGN KEY"),
        "0.9.0 explanation should state the FK clause is emitted: {}",
        res.explanation,
    );
    assert!(
        res.explanation.contains("on_delete:restrict"),
        "explanation should name the default on_delete policy: {}",
        res.explanation,
    );
}

#[test]
fn link_verb_is_synonymous_with_add_relation() {
    let schema = housing_schema();
    let via_add = generate_plan(
        &schema,
        None,
        PlanRequest::new("add relation from Application to Applicant"),
    )
    .unwrap();
    let via_link = generate_plan(
        &schema,
        None,
        PlanRequest::new("link Application to Applicant"),
    )
    .unwrap();
    assert_eq!(
        render_plan_json(&via_add.plan, ""),
        render_plan_json(&via_link.plan, ""),
        "`link X to Y` must produce the same plan as `add relation from X to Y`",
    );
}

#[test]
fn connect_verb_is_synonymous_with_add_relation() {
    let schema = housing_schema();
    let via_add = generate_plan(
        &schema,
        None,
        PlanRequest::new("add relation from Application to Applicant"),
    )
    .unwrap();
    let via_connect = generate_plan(
        &schema,
        None,
        PlanRequest::new("connect Application to Applicant"),
    )
    .unwrap();
    assert_eq!(
        render_plan_json(&via_add.plan, ""),
        render_plan_json(&via_connect.plan, ""),
    );
}

#[test]
fn relation_already_exists_is_refused() {
    // Seed the "from" model with the column the planner would infer
    // (`applicant_id`); the planner must refuse, not overwrite.
    let mut schema = housing_schema();
    let from = schema
        .models
        .iter_mut()
        .find(|m| m.name == "Application")
        .unwrap();
    from.fields.push(SchemaField {
        name: "applicant_id".into(),
        ty: "i64".into(),
        nullable: false,
        editable: true,
        relation: None,
    });

    let err = generate_plan(
        &schema,
        None,
        PlanRequest::new("link Application to Applicant"),
    )
    .expect_err("planner must refuse when the FK column already exists");
    assert!(
        matches!(err, PlanError::FieldAlreadyExists { ref field, .. } if field == "applicant_id"),
        "expected FieldAlreadyExists(applicant_id), got {err:?}",
    );
}

#[test]
fn relation_to_unknown_target_is_refused() {
    let schema = housing_schema();
    let err = generate_plan(
        &schema,
        None,
        PlanRequest::new("link Application to Martian"),
    )
    .expect_err("unknown target model must refuse");
    assert!(
        matches!(err, PlanError::UnknownModel { .. }),
        "expected UnknownModel, got {err:?}",
    );
}

#[test]
fn relation_from_unknown_source_is_refused() {
    let schema = housing_schema();
    let err = generate_plan(&schema, None, PlanRequest::new("link Martian to Applicant"))
        .expect_err("unknown source model must refuse");
    assert!(
        matches!(err, PlanError::UnknownModel { .. }),
        "expected UnknownModel, got {err:?}",
    );
}

// ---------- renderers ----------

#[test]
fn render_plan_json_matches_documented_shape() {
    let schema = task_schema();
    let res = generate_plan(&schema, None, PlanRequest::new("add priority to tasks")).unwrap();
    let json = render_plan_json(&res.plan, &res.explanation);
    // Spot-check the documented keys at a string level.
    assert!(
        json.contains(r#""op": "AddField""#),
        "missing op tag: {json}"
    );
    assert!(
        json.contains(r#""field": "priority""#),
        "missing field key: {json}",
    );
    assert!(
        json.contains(r#""type": "i32""#),
        "missing type key: {json}"
    );
    assert!(
        json.contains(r#""nullable": false"#),
        "missing nullable: {json}"
    );
    assert!(
        json.contains(r#""explanation""#),
        "missing explanation: {json}",
    );
}

#[test]
fn render_plan_human_reads_like_a_changelog() {
    let schema = task_schema();
    let res = generate_plan(
        &schema,
        None,
        PlanRequest::new("rename title to name in tasks"),
    )
    .unwrap();
    let text = render_plan_human(&res.plan, &res.explanation);
    assert!(
        text.starts_with("Plan:\n"),
        "should start with Plan:\n\n{text}"
    );
    assert!(
        text.contains("Rename field \"Task.title\" to \"name\""),
        "human summary shape: {text}",
    );
    assert!(text.contains("Explanation:"), "missing Explanation block");
}

// ---- 0.9.0 relation option grammar --------------------------------------

#[test]
fn link_accepts_trailing_required_option() {
    let schema = housing_schema();
    let res = generate_plan(
        &schema,
        None,
        PlanRequest::new("link Application to Applicant required"),
    )
    .expect("grammar should accept trailing `required`");
    match &res.plan.steps[0] {
        Primitive::AddRelation(r) => {
            assert!(
                r.required,
                "required flag should propagate to the primitive"
            );
        }
        other => panic!("expected AddRelation, got {other:?}"),
    }
}

#[test]
fn link_accepts_trailing_on_delete_cascade() {
    let schema = housing_schema();
    let res = generate_plan(
        &schema,
        None,
        PlanRequest::new("link Application to Applicant on_delete:cascade"),
    )
    .expect("grammar should accept trailing on_delete token");
    match &res.plan.steps[0] {
        Primitive::AddRelation(r) => {
            assert_eq!(r.on_delete, crate::ai::OnDelete::Cascade);
        }
        other => panic!("expected AddRelation, got {other:?}"),
    }
}

#[test]
fn link_combines_required_and_on_delete_set_null() {
    let schema = housing_schema();
    let res = generate_plan(
        &schema,
        None,
        PlanRequest::new("link Application to Applicant required on_delete:set_null"),
    )
    .unwrap();
    match &res.plan.steps[0] {
        Primitive::AddRelation(r) => {
            assert!(r.required);
            assert_eq!(r.on_delete, crate::ai::OnDelete::SetNull);
        }
        other => panic!("expected AddRelation, got {other:?}"),
    }
}

#[test]
fn link_rejects_unknown_option_instead_of_guessing() {
    let schema = housing_schema();
    let err = generate_plan(
        &schema,
        None,
        PlanRequest::new("link Application to Applicant frobnicate"),
    )
    .expect_err("unknown option must refuse, not silently drop");
    match err {
        PlanError::InvalidIntent(msg) => {
            assert!(
                msg.contains("frobnicate"),
                "error should name the bad token: {msg}"
            );
        }
        other => panic!("expected InvalidIntent, got {other:?}"),
    }
}

#[test]
fn link_rejects_unknown_on_delete_policy() {
    let schema = housing_schema();
    let err = generate_plan(
        &schema,
        None,
        PlanRequest::new("link Application to Applicant on_delete:nuke"),
    )
    .expect_err("unknown on_delete must refuse");
    match err {
        PlanError::InvalidIntent(msg) => {
            assert!(msg.contains("on_delete") || msg.contains("nuke"));
        }
        other => panic!("expected InvalidIntent, got {other:?}"),
    }
}