cairnlang-core 0.5.0

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

use crate::edit::{ExprSpec, FunctionSpec, StepSpec, TypeDefSpec};
use crate::node::{BinOp, Param, Produces};
use crate::ty::{Confidence, Effect, Type};
use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;

/// How a stored TEXT column round-trips to/from a record field. The
/// closed set the four real CRM entities use — no kind no real entity
/// needs.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum FieldKind {
    /// Integer column. decode `StrToNumber(field)`, encode
    /// `NumberToStr(value)`.
    Num,
    /// Text column. decode = the field verbatim, encode = the value
    /// verbatim.
    Text,
    /// `Decimal` stored as its raw mantissa. decode
    /// `IntToDecimal(StrToNumber(field)) / 10000` (the documented
    /// round-trip), encode `NumberToStr(DecimalRaw(value))`.
    Decimal,
    /// A named-variant field round-tripped by app-provided pure
    /// functions (the one shell→logic seam, by name) — e.g. the
    /// `Status` machine: `decode = "status_of_str"`, `encode =
    /// "status_to_str"`.
    Variant { decode: String, encode: String },
}

/// One column: the record field name, the DB column name (usually
/// equal — they differ for `LineItem.unit_price` ↔ `price_raw`), and
/// the round-trip kind. Fields are listed in column order (= the
/// SELECT/INSERT order).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FieldSpec {
    pub field: String,
    pub column: String,
    pub kind: FieldKind,
}

impl FieldSpec {
    /// Sugar: column name equals the field name (the common case).
    pub fn new(field: &str, kind: FieldKind) -> Self {
        FieldSpec {
            field: field.into(),
            column: field.into(),
            kind,
        }
    }
    /// Field and column names differ (`unit_price` ↔ `price_raw`).
    pub fn col(field: &str, column: &str, kind: FieldKind) -> Self {
        FieldSpec {
            field: field.into(),
            column: column.into(),
            kind,
        }
    }
}

/// One entity's shape. Names are bespoke per entity (the CRM uses
/// `contacts_from_rows`/`crm_save_lines`, and save-param names
/// `cs`/`js`/`xs`) — carried here so generation is byte-identical to
/// the hand form, not normalised.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EntitySpec {
    pub record: String,
    pub table: String,
    pub rows_fn: String,
    pub save_fn: String,
    pub save_param: String,
    pub fields: Vec<FieldSpec>,
}

/// `save`/`save_step` use these as internal step/index bindings. A
/// `save_param` equal to one of them shadows the generator's own
/// code and produces a type violation in functions the author never
/// wrote — fail *closed* on it instead.
const RESERVED_SAVE_PARAMS: &[&str] = &["i", "n", "ins"];

impl EntitySpec {
    /// Reject a spec that would generate corrupt or self-shadowing
    /// code, with a message that names the fix — rather than silently
    /// emitting broken SQL (e.g. a `SELECT … ORDER BY id` over
    /// columns that include no `id`) or a type violation inside the
    /// generated code. A well-formed spec is the caller's to get
    /// right; a malformed one must fail loudly at the seam, never
    /// corrupt the store. (Typical specs pass unchanged: first field
    /// is the `id` PK, save-param is not a reserved binding.)
    pub fn validate(&self) -> Result<(), String> {
        if self.fields.is_empty() {
            return Err(
                "EntitySpec.fields is empty: an entity needs at \
                 least an `id` column"
                    .into(),
            );
        }
        // `create_table` makes field 0 the `id INTEGER PRIMARY KEY`
        // and `select_all` is `… ORDER BY id`; a first column that is
        // not `id` yields SQL that orders by a column it never
        // selects — the silent corruption when the `FieldSpec` middle
        // element (the SQL *column name*, not a Cairn type) is wrong.
        if self.fields[0].column != "id" {
            return Err(format!(
                "EntitySpec.fields[0] column is `{}`, must be `id`: \
                 the first field is the INTEGER PRIMARY KEY and the \
                 generated SELECT is `ORDER BY id`. A FieldSpec is \
                 [field_name, sql_column_name, kind] — the middle \
                 element is the column name, NOT a Cairn type.",
                self.fields[0].column
            ));
        }
        if RESERVED_SAVE_PARAMS.contains(&self.save_param.as_str()) {
            return Err(format!(
                "EntitySpec.save_param `{}` collides with a binding \
                 the generated save/save_step use internally \
                 ({:?}); pick another name (the CRM uses \
                 `cs`/`js`/`xs`).",
                self.save_param, RESERVED_SAVE_PARAMS
            ));
        }
        Ok(())
    }
}

// --- byte-exact builders (mirror the app-local terse builders the
// CRM hand-used, so generated AST == hand-authored AST node-for-node)

fn rref(n: &str) -> ExprSpec {
    ExprSpec::Ref(n.into())
}
fn call(func: &str, args: Vec<ExprSpec>) -> ExprSpec {
    ExprSpec::Call {
        func: func.into(),
        args,
    }
}
fn bin(op: BinOp, a: ExprSpec, b: ExprSpec) -> ExprSpec {
    ExprSpec::BinOp {
        op,
        lhs: Box::new(a),
        rhs: Box::new(b),
    }
}
fn s2n(e: ExprSpec) -> ExprSpec {
    ExprSpec::StrToNumber(Box::new(e))
}
fn n2s(e: ExprSpec) -> ExprSpec {
    ExprSpec::NumberToStr(Box::new(e))
}
fn p(name: &str, ty: Type) -> Param {
    Param {
        name: name.into(),
        ty,
        min_confidence: Confidence::External,
    }
}
fn ext(ty: Type) -> Produces {
    Produces {
        ty,
        confidence: Confidence::External,
    }
}
fn db_eff() -> BTreeSet<Effect> {
    [Effect::Db].into_iter().collect()
}
/// `field(rows[i], k)` — the framework column accessor.
fn field_at(k: i64) -> ExprSpec {
    call(
        "field",
        vec![
            ExprSpec::ListGet {
                list: Box::new(rref("rows")),
                index: Box::new(rref("i")),
            },
            ExprSpec::Lit(k),
        ],
    )
}
/// `param[i].FIELD` — the per-row record-field accessor used by save.
fn item_field(param: &str, record: &str, field: &str) -> ExprSpec {
    ExprSpec::Field {
        base: Box::new(ExprSpec::ListGet {
            list: Box::new(rref(param)),
            index: Box::new(rref("i")),
        }),
        type_name: record.into(),
        field: field.into(),
    }
}

/// Decode column `k` into a record field — byte-identical to the
/// CRM's hand form (`s2n`/verbatim/`IntToDecimal(s2n)/1e4`/`decoder`).
fn decode(kind: &FieldKind, k: i64) -> ExprSpec {
    let f = field_at(k);
    match kind {
        FieldKind::Num => s2n(f),
        FieldKind::Text => f,
        FieldKind::Decimal => ExprSpec::DecimalOp {
            op: BinOp::Div,
            lhs: Box::new(ExprSpec::IntToDecimal(Box::new(s2n(f)))),
            rhs: Box::new(ExprSpec::Decimal(10000.0)),
        },
        FieldKind::Variant { decode, .. } => call(decode, vec![f]),
    }
}

/// Encode a record field into its bound `?` param — the exact inverse
/// of `decode`, byte-identical to the hand form.
fn encode(fs: &FieldSpec, param: &str, record: &str) -> ExprSpec {
    let v = item_field(param, record, &fs.field);
    match &fs.kind {
        FieldKind::Num => n2s(v),
        FieldKind::Text => v,
        FieldKind::Decimal => n2s(ExprSpec::DecimalRaw(Box::new(v))),
        FieldKind::Variant { encode, .. } => call(encode, vec![v]),
    }
}

/// The SQLite column type for a field kind. `Decimal` stores its raw
/// mantissa as an `INTEGER`; a `Variant` stores its canonical name as
/// `TEXT`. (The first column is special-cased to the `id` PRIMARY KEY
/// in `create_table` — every real entity's first field is `id`.)
fn sql_type(k: &FieldKind) -> &'static str {
    match k {
        FieldKind::Num | FieldKind::Decimal => "INTEGER",
        FieldKind::Text | FieldKind::Variant { .. } => "TEXT",
    }
}

/// Generate the `CREATE TABLE IF NOT EXISTS …` DDL — byte-identical
/// to the hand `*CREATE` constants (first column `id INTEGER PRIMARY
/// KEY`, the rest `<column> <INTEGER|TEXT>`).
pub fn create_table(s: &EntitySpec) -> String {
    let cols: Vec<String> = s
        .fields
        .iter()
        .enumerate()
        .map(|(i, f)| {
            if i == 0 {
                format!("{} INTEGER PRIMARY KEY", f.column)
            } else {
                format!("{} {}", f.column, sql_type(&f.kind))
            }
        })
        .collect();
    format!(
        "CREATE TABLE IF NOT EXISTS {} ({})",
        s.table,
        cols.join(", ")
    )
}

/// Generate the `SELECT … FROM … ORDER BY id` the parser consumes —
/// byte-identical to the hand `*SELECT` constants, columns in the
/// same order `from_rows` decodes them.
pub fn select_all(s: &EntitySpec) -> String {
    let cols: Vec<&str> =
        s.fields.iter().map(|f| f.column.as_str()).collect();
    format!(
        "SELECT {} FROM {} ORDER BY id",
        cols.join(", "),
        s.table
    )
}

/// Generate the `*_from_rows` recursive load parser.
pub fn from_rows(s: &EntitySpec) -> FunctionSpec {
    let elem = Type::Named(s.record.clone());
    let fields: Vec<(String, ExprSpec)> = s
        .fields
        .iter()
        .enumerate()
        .map(|(k, fs)| (fs.field.clone(), decode(&fs.kind, k as i64)))
        .collect();
    FunctionSpec {
        name: s.rows_fn.clone(),
        type_params: vec![],
        params: vec![
            p("rows", Type::List(Box::new(Type::String))),
            p("i", Type::Number),
        ],
        produces: ext(Type::List(Box::new(elem.clone()))),
        requires: BTreeSet::new(),
        on_failure: vec![],
        steps: vec![StepSpec {
            binding: "n".into(),
            value: ExprSpec::ListLen(Box::new(rref("rows"))),
        }],
        result: ExprSpec::If {
            cond: Box::new(bin(BinOp::Eq, rref("i"), rref("n"))),
            then_branch: Box::new(ExprSpec::ListEmpty {
                elem: elem.clone(),
            }),
            else_branch: Box::new(ExprSpec::ListCons {
                head: Box::new(ExprSpec::Record {
                    type_name: s.record.clone(),
                    fields,
                }),
                tail: Box::new(call(
                    &s.rows_fn,
                    vec![
                        rref("rows"),
                        bin(BinOp::Add, rref("i"), ExprSpec::Lit(1)),
                    ],
                )),
            }),
        },
    }
}

/// Generate the `(save, save_step)` pair — the DELETE+re-INSERT
/// persist driver and its one-row INSERT step. Byte-identical to the
/// hand form (the bespoke `save_fn`/`save_param`/`table`/`column`
/// names are carried in the spec precisely so).
pub fn save_pair(s: &EntitySpec) -> (FunctionSpec, FunctionSpec) {
    let list_ty = Type::List(Box::new(Type::Named(s.record.clone())));
    let step_fn = format!("{}_step", s.save_fn);
    let prm = s.save_param.as_str();

    let save = FunctionSpec {
        name: s.save_fn.clone(),
        type_params: vec![],
        params: vec![p(prm, list_ty.clone()), p("i", Type::Number)],
        produces: ext(Type::Number),
        requires: db_eff(),
        on_failure: vec![],
        steps: vec![StepSpec {
            binding: "n".into(),
            value: ExprSpec::ListLen(Box::new(rref(prm))),
        }],
        result: ExprSpec::If {
            cond: Box::new(bin(BinOp::Eq, rref("i"), rref("n"))),
            then_branch: Box::new(ExprSpec::Lit(0)),
            else_branch: Box::new(call(
                &step_fn,
                vec![rref(prm), rref("i")],
            )),
        },
    };

    let cols: Vec<&str> =
        s.fields.iter().map(|f| f.column.as_str()).collect();
    let qs: Vec<&str> = s.fields.iter().map(|_| "?").collect();
    let sql = format!(
        "INSERT INTO {} ({}) VALUES ({})",
        s.table,
        cols.join(", "),
        qs.join(", "),
    );
    let params: Vec<ExprSpec> = s
        .fields
        .iter()
        .map(|fs| encode(fs, prm, &s.record))
        .collect();

    let step = FunctionSpec {
        name: step_fn,
        type_params: vec![],
        params: vec![p(prm, list_ty), p("i", Type::Number)],
        produces: ext(Type::Number),
        requires: db_eff(),
        on_failure: vec![],
        steps: vec![StepSpec {
            binding: "ins".into(),
            value: ExprSpec::DbQuery {
                sql: Box::new(ExprSpec::Str(sql)),
                params: Box::new(ExprSpec::List(params)),
            },
        }],
        result: call(
            &s.save_fn,
            vec![
                rref(prm),
                bin(BinOp::Add, rref("i"), ExprSpec::Lit(1)),
            ],
        ),
    };
    (save, step)
}

/// The canonical Cairn app shape, declared — Cairn's analogue of a
/// Rails `rails new` skeleton. It is *not* convention-over-
/// configuration magic: nothing is discovered by name at runtime. It
/// is the explicit Elm-Architecture shape every Cairn web app shares
/// (model record + `Msg` variant + the five pure-ish functions
/// `run_app` composes + the `route` entry), emitted so an author
/// reproduces the conventional shape rather than reconstructing it.
/// The skeleton emits a *working, checkable, runnable* placeholder;
/// the author fills the model fields, the `Msg` cases + `update`
/// arms, the real `view`, and real persistence (or composes
/// [`save_pair`]). Shell only, never the reasoning — the same firm
/// boundary as the entity scaffolder.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AppSpec {
    /// The app/model name, e.g. `Counter`. The message variant is
    /// `<app>Msg`; the five TEA functions are prefixed with the
    /// lowercased name; the served entry is always `route` (the
    /// CLI-`serve` convention the blog and CRM use).
    pub app: String,
}

fn named(n: &str) -> Type {
    Type::Named(n.into())
}
fn no_eff() -> BTreeSet<Effect> {
    BTreeSet::new()
}
fn db_time() -> BTreeSet<Effect> {
    [Effect::Db, Effect::Time].into_iter().collect()
}
fn func(
    name: &str,
    params: Vec<Param>,
    out: Type,
    requires: BTreeSet<Effect>,
    result: ExprSpec,
) -> FunctionSpec {
    FunctionSpec {
        name: name.into(),
        type_params: vec![],
        params,
        produces: ext(out),
        requires,
        on_failure: vec![],
        steps: vec![],
        result,
    }
}

/// Generate the canonical TEA app shell from one [`AppSpec`]: the
/// model record + `<app>Msg` variant, the five functions `run_app`
/// composes (`*_route_msg`/`*_load`/`*_update`/`*_view`/`*_persist`),
/// and the `route` entry that wires them through `run_app` by
/// `FuncRef`. It is **not** standalone:
/// `Request`/`Response`/`Element`/`run_app`/`render_html` resolve
/// from the framework splice, exactly like the entity scaffolder's
/// `field`. The caller composes the returned types + functions into
/// one `ModuleSpec` with the framework, then `apply_module`. The
/// placeholders are deliberately the minimal *valid, runnable* shape
/// (a one-field model, a single `Touch` message, an identity
/// `update`, a view of state, a no-op `persist`) — a starting point
/// that type-checks and returns a real `200`, never a stub: filling
/// it in is the shell→logic seam.
pub fn app_skeleton(spec: &AppSpec) -> (Vec<TypeDefSpec>, Vec<FunctionSpec>) {
    let app = spec.app.as_str();
    let msg = format!("{app}Msg");
    let pfx = app.to_lowercase();

    let types = vec![
        TypeDefSpec::Record {
            name: app.into(),
            fields: vec![("count".into(), Type::Number)],
        },
        TypeDefSpec::Variant {
            name: msg.clone(),
            cases: vec![("Touch".into(), vec![])],
        },
    ];

    let model = || ExprSpec::Record {
        type_name: app.into(),
        fields: vec![("count".into(), ExprSpec::Lit(0))],
    };

    // route_msg: a real app routes on `req.path`; the skeleton emits
    // the one message so it checks and runs (the bound permits a
    // pure route_msg — see `run_app`).
    let route_msg = func(
        &format!("{pfx}_route_msg"),
        vec![p("req", named("Request"))],
        named(&msg),
        no_eff(),
        ExprSpec::Variant {
            type_name: msg.clone(),
            case: "Touch".into(),
            fields: vec![],
        },
    );
    // load: a real app reads persisted state ({Db}); the skeleton
    // returns the initial model (pure satisfies the {Db} bound).
    let load = func(
        &format!("{pfx}_load"),
        vec![],
        named(app),
        no_eff(),
        model(),
    );
    // update: exhaustive Match on the message — a forgotten case is
    // a check error. Identity until the author fills the arms.
    let update = func(
        &format!("{pfx}_update"),
        vec![p("m", named(app)), p("msg", named(&msg))],
        named(app),
        no_eff(),
        ExprSpec::Match {
            scrutinee: Box::new(rref("msg")),
            type_name: msg.clone(),
            arms: vec![("Touch".into(), vec![], rref("m"))],
        },
    );
    // view: pure Element of state — the canonical view-of-model
    // pattern, visibly a placeholder until the agent rewrites it.
    let view = func(
        &format!("{pfx}_view"),
        vec![p("m", named(app))],
        named("Element"),
        no_eff(),
        ExprSpec::Variant {
            type_name: "Element".into(),
            case: "El".into(),
            fields: vec![
                ("tag".into(), ExprSpec::Str("main".into())),
                (
                    "kids".into(),
                    ExprSpec::List(vec![ExprSpec::Variant {
                        type_name: "Element".into(),
                        case: "Text".into(),
                        fields: vec![(
                            "content".into(),
                            ExprSpec::StrConcat(
                                Box::new(ExprSpec::Str(format!(
                                    "{app} skeleton — fill in view; count="
                                ))),
                                Box::new(ExprSpec::NumberToStr(Box::new(
                                    ExprSpec::Field {
                                        base: Box::new(rref("m")),
                                        type_name: app.into(),
                                        field: "count".into(),
                                    },
                                ))),
                            ),
                        )],
                    }]),
                ),
            ],
        },
    );
    // persist: a real app writes ({Db}); the skeleton no-ops (pure
    // satisfies the bound). The agent fills this with real
    // persistence or composes `scaffold_entity`.
    let persist = func(
        &format!("{pfx}_persist"),
        vec![p("m", named(app))],
        Type::Number,
        no_eff(),
        ExprSpec::Lit(0),
    );
    // route: the served entry (the CLI-`serve` convention). Pure
    // wiring — compose the five through `run_app` by `FuncRef`. Its
    // effects are `run_app`'s declared `{Db,Time}` bound, unioned
    // even though the skeleton's functions are pure (the accepted
    // coarse-bound cost — see `run_app`).
    let route = func(
        "route",
        vec![p("req", named("Request"))],
        named("Response"),
        db_time(),
        ExprSpec::Call {
            func: "run_app".into(),
            args: vec![
                rref("req"),
                ExprSpec::FuncRef(format!("{pfx}_route_msg")),
                ExprSpec::FuncRef(format!("{pfx}_load")),
                ExprSpec::FuncRef(format!("{pfx}_update")),
                ExprSpec::FuncRef(format!("{pfx}_view")),
                ExprSpec::FuncRef(format!("{pfx}_persist")),
            ],
        },
    );

    (
        types,
        vec![route_msg, load, update, view, persist, route],
    )
}

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

    fn contact() -> EntitySpec {
        EntitySpec {
            record: "Contact".into(),
            table: "contacts".into(),
            rows_fn: "contacts_from_rows".into(),
            save_fn: "crm_save_contacts".into(),
            save_param: "cs".into(),
            fields: vec![
                FieldSpec::new("id", FieldKind::Num),
                FieldSpec::new("name", FieldKind::Text),
                FieldSpec::new("phone", FieldKind::Text),
                FieldSpec::new("kind", FieldKind::Text),
            ],
        }
    }

    /// Byte-exactness vs the hand-authored `contacts_from_rows`.
    #[test]
    fn from_rows_is_byte_identical_to_the_hand_form() {
        let gen = from_rows(&contact());
        let hand = FunctionSpec {
            name: "contacts_from_rows".into(),
            type_params: vec![],
            params: vec![
                p("rows", Type::List(Box::new(Type::String))),
                p("i", Type::Number),
            ],
            produces: ext(Type::List(Box::new(Type::Named(
                "Contact".into(),
            )))),
            requires: BTreeSet::new(),
            on_failure: vec![],
            steps: vec![StepSpec {
                binding: "n".into(),
                value: ExprSpec::ListLen(Box::new(rref("rows"))),
            }],
            result: ExprSpec::If {
                cond: Box::new(bin(BinOp::Eq, rref("i"), rref("n"))),
                then_branch: Box::new(ExprSpec::ListEmpty {
                    elem: Type::Named("Contact".into()),
                }),
                else_branch: Box::new(ExprSpec::ListCons {
                    head: Box::new(ExprSpec::Record {
                        type_name: "Contact".into(),
                        fields: vec![
                            ("id".into(), s2n(field_at(0))),
                            ("name".into(), field_at(1)),
                            ("phone".into(), field_at(2)),
                            ("kind".into(), field_at(3)),
                        ],
                    }),
                    tail: Box::new(call(
                        "contacts_from_rows",
                        vec![
                            rref("rows"),
                            bin(BinOp::Add, rref("i"), ExprSpec::Lit(1)),
                        ],
                    )),
                }),
            },
        };
        assert_eq!(
            serde_json::to_string(&gen).unwrap(),
            serde_json::to_string(&hand).unwrap(),
            "generated *_from_rows must be byte-identical to hand"
        );
    }

    /// Byte-exactness vs the hand-authored
    /// `crm_save_contacts`/`_step`.
    #[test]
    fn save_pair_is_byte_identical_to_the_hand_form() {
        let (save, step) = save_pair(&contact());

        let hand_save = FunctionSpec {
            name: "crm_save_contacts".into(),
            type_params: vec![],
            params: vec![
                p(
                    "cs",
                    Type::List(Box::new(Type::Named("Contact".into()))),
                ),
                p("i", Type::Number),
            ],
            produces: ext(Type::Number),
            requires: db_eff(),
            on_failure: vec![],
            steps: vec![StepSpec {
                binding: "n".into(),
                value: ExprSpec::ListLen(Box::new(rref("cs"))),
            }],
            result: ExprSpec::If {
                cond: Box::new(bin(BinOp::Eq, rref("i"), rref("n"))),
                then_branch: Box::new(ExprSpec::Lit(0)),
                else_branch: Box::new(call(
                    "crm_save_contacts_step",
                    vec![rref("cs"), rref("i")],
                )),
            },
        };
        let hand_step = FunctionSpec {
            name: "crm_save_contacts_step".into(),
            type_params: vec![],
            params: vec![
                p(
                    "cs",
                    Type::List(Box::new(Type::Named("Contact".into()))),
                ),
                p("i", Type::Number),
            ],
            produces: ext(Type::Number),
            requires: db_eff(),
            on_failure: vec![],
            steps: vec![StepSpec {
                binding: "ins".into(),
                value: ExprSpec::DbQuery {
                    sql: Box::new(ExprSpec::Str(
                        "INSERT INTO contacts (id, name, phone, kind) \
                         VALUES (?, ?, ?, ?)"
                            .into(),
                    )),
                    params: Box::new(ExprSpec::List(vec![
                        n2s(item_field("cs", "Contact", "id")),
                        item_field("cs", "Contact", "name"),
                        item_field("cs", "Contact", "phone"),
                        item_field("cs", "Contact", "kind"),
                    ])),
                },
            }],
            result: call(
                "crm_save_contacts",
                vec![
                    rref("cs"),
                    bin(BinOp::Add, rref("i"), ExprSpec::Lit(1)),
                ],
            ),
        };
        assert_eq!(
            serde_json::to_string(&save).unwrap(),
            serde_json::to_string(&hand_save).unwrap(),
            "generated save must be byte-identical to hand"
        );
        assert_eq!(
            serde_json::to_string(&step).unwrap(),
            serde_json::to_string(&hand_step).unwrap(),
            "generated save_step must be byte-identical to hand"
        );
    }

    #[test]
    fn ddl_and_select_are_byte_identical_to_the_hand_constants() {
        // Contact (all columns == fields).
        assert_eq!(
            create_table(&contact()),
            "CREATE TABLE IF NOT EXISTS contacts \
             (id INTEGER PRIMARY KEY, name TEXT, phone TEXT, kind TEXT)"
        );
        assert_eq!(
            select_all(&contact()),
            "SELECT id, name, phone, kind FROM contacts ORDER BY id"
        );
        // LineItem: column ≠ field (`unit_price`↔`price_raw`),
        // Decimal→INTEGER.
        let li = EntitySpec {
            record: "LineItem".into(),
            table: "line_items".into(),
            rows_fn: "lineitems_from_rows".into(),
            save_fn: "crm_save_lines".into(),
            save_param: "xs".into(),
            fields: vec![
                FieldSpec::new("id", FieldKind::Num),
                FieldSpec::new("estimate_id", FieldKind::Num),
                FieldSpec::new("description", FieldKind::Text),
                FieldSpec::new("qty", FieldKind::Num),
                FieldSpec::col(
                    "unit_price",
                    "price_raw",
                    FieldKind::Decimal,
                ),
            ],
        };
        assert_eq!(
            create_table(&li),
            "CREATE TABLE IF NOT EXISTS line_items \
             (id INTEGER PRIMARY KEY, estimate_id INTEGER, \
             description TEXT, qty INTEGER, price_raw INTEGER)"
        );
        assert_eq!(
            select_all(&li),
            "SELECT id, estimate_id, description, qty, price_raw \
             FROM line_items ORDER BY id"
        );
    }

    #[test]
    fn decimal_and_variant_round_trip_match_documented_forms() {
        // decode Decimal == IntToDecimal(s2n(field))/1e4
        let d = decode(&FieldKind::Decimal, 4);
        let want = ExprSpec::DecimalOp {
            op: BinOp::Div,
            lhs: Box::new(ExprSpec::IntToDecimal(Box::new(s2n(
                field_at(4),
            )))),
            rhs: Box::new(ExprSpec::Decimal(10000.0)),
        };
        assert_eq!(
            serde_json::to_string(&d).unwrap(),
            serde_json::to_string(&want).unwrap()
        );
        // encode Decimal == n2s(DecimalRaw(value))
        let fs = FieldSpec::col(
            "unit_price",
            "price_raw",
            FieldKind::Decimal,
        );
        let e = encode(&fs, "xs", "LineItem");
        let want_e = n2s(ExprSpec::DecimalRaw(Box::new(item_field(
            "xs",
            "LineItem",
            "unit_price",
        ))));
        assert_eq!(
            serde_json::to_string(&e).unwrap(),
            serde_json::to_string(&want_e).unwrap()
        );
        // Variant round-trips through the named decode/encode fns.
        let vk = FieldKind::Variant {
            decode: "status_of_str".into(),
            encode: "status_to_str".into(),
        };
        assert_eq!(
            serde_json::to_string(&decode(&vk, 3)).unwrap(),
            serde_json::to_string(&call(
                "status_of_str",
                vec![field_at(3)]
            ))
            .unwrap()
        );
        let vfs = FieldSpec::new("status", vk);
        assert_eq!(
            serde_json::to_string(&encode(&vfs, "js", "Job")).unwrap(),
            serde_json::to_string(&call(
                "status_to_str",
                vec![item_field("js", "Job", "status")]
            ))
            .unwrap()
        );
    }

    /// The canonical app skeleton is the exact shape `run_app`
    /// expects: the model + `<app>Msg` types, the five prefixed TEA
    /// functions all pure (the bound permits it), and `route` wiring
    /// them by `FuncRef` with `run_app`'s `{Db,Time}` effects. Pins
    /// the convention so it cannot silently drift (the content-
    /// addressed analogue of a Rails generator that cannot rot).
    #[test]
    fn app_skeleton_emits_the_canonical_tea_shape() {
        let (types, fns) = app_skeleton(&AppSpec {
            app: "Counter".into(),
        });

        // triad types: the model record + the message variant.
        match &types[0] {
            TypeDefSpec::Record { name, fields } => {
                assert_eq!(name, "Counter");
                assert_eq!(fields[0].0, "count");
            }
            _ => panic!("first type is the model record"),
        }
        match &types[1] {
            TypeDefSpec::Variant { name, cases } => {
                assert_eq!(name, "CounterMsg");
                assert_eq!(cases[0].0, "Touch");
            }
            _ => panic!("second type is the Msg variant"),
        }

        let names: Vec<&str> =
            fns.iter().map(|f| f.name.as_str()).collect();
        assert_eq!(
            names,
            vec![
                "counter_route_msg",
                "counter_load",
                "counter_update",
                "counter_view",
                "counter_persist",
                "route",
            ],
            "the five TEA functions (prefixed) + the `route` entry"
        );

        let by = |n: &str| fns.iter().find(|f| f.name == n).unwrap();
        // `route` carries run_app's declared {Db,Time} bound; the
        // five composed functions are pure (the bound permits it).
        let dt: BTreeSet<Effect> =
            [Effect::Db, Effect::Time].into_iter().collect();
        assert_eq!(by("route").requires, dt);
        for n in [
            "counter_route_msg",
            "counter_load",
            "counter_update",
            "counter_view",
            "counter_persist",
        ] {
            assert!(
                by(n).requires.is_empty(),
                "{n} is pure in the skeleton"
            );
        }
        // `route` is the served entry: a Request → Response wiring
        // that calls run_app with the five FuncRefs in order.
        match &by("route").result {
            ExprSpec::Call { func, args } => {
                assert_eq!(func, "run_app");
                assert!(matches!(&args[0], ExprSpec::Ref(r) if r == "req"));
                let refs: Vec<&str> = args[1..]
                    .iter()
                    .map(|a| match a {
                        ExprSpec::FuncRef(n) => n.as_str(),
                        _ => panic!("run_app args are FuncRefs"),
                    })
                    .collect();
                assert_eq!(
                    refs,
                    vec![
                        "counter_route_msg",
                        "counter_load",
                        "counter_update",
                        "counter_view",
                        "counter_persist"
                    ]
                );
            }
            _ => panic!("route composes run_app"),
        }
    }

    /// Fail-closed on the malformed-spec cases; pass well-formed
    /// specs unchanged.
    #[test]
    fn entity_spec_validate_rejects_malformed_specs() {
        // The good CRM `Contact` spec validates.
        assert!(contact().validate().is_ok());

        // Empty fields.
        let mut e = contact();
        e.fields = vec![];
        assert!(e.validate().is_err());

        // First column not `id` — the silent-corrupt-DDL case
        // (`["id","Number","Num"]` parsed as column "Number").
        let bad = EntitySpec {
            record: "Note".into(),
            table: "notes".into(),
            rows_fn: "note_from_rows".into(),
            save_fn: "note_save".into(),
            save_param: "notes".into(),
            fields: vec![
                FieldSpec::col("id", "Number", FieldKind::Num),
                FieldSpec::col("body", "String", FieldKind::Text),
            ],
        };
        let err = bad.validate().unwrap_err();
        assert!(
            err.contains("must be `id`") && err.contains("NOT a Cairn type"),
            "names the fix: {err}"
        );

        // save_param shadowing the generator's internal `n`.
        let mut collide = contact();
        collide.save_param = "n".into();
        assert!(collide.validate().unwrap_err().contains("collides"));
        // …and the other reserved names.
        for r in ["i", "ins"] {
            let mut c = contact();
            c.save_param = r.into();
            assert!(c.validate().is_err(), "{r} is reserved");
        }
    }
}