domainforge-core 0.22.2

Rust core library implementing the SEA DSL primitives and validation engine.
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
//! Application contract construction tests (plan Task 7; Tasks 8+ extend).

use domainforge_core::application::{
    resolve_application_contract, AccessMode, ApplicationContractDocument, ApplicationDiagnostic,
    ConcurrencyStrategy, EffectKind, IdempotencyStrategy, OperationContract, TransactionBoundary,
};
use domainforge_core::concept_id::ConceptId;

fn resolve_fixture_contract(
    entry: &str,
) -> Result<ApplicationContractDocument, Vec<ApplicationDiagnostic>> {
    let sources = serde_json::json!({
        "flagship/command-write.sea": include_str!(
            "../../fixtures/application_generation/flagship/command-write.sea"),
        "flagship/query-read.sea": include_str!(
            "../../fixtures/application_generation/flagship/query-read.sea"),
    })
    .to_string();
    resolve_application_contract(entry, &sources)
}

fn resolve_single(source: &str) -> Result<ApplicationContractDocument, Vec<ApplicationDiagnostic>> {
    let sources = serde_json::json!({ "main.sea": source }).to_string();
    resolve_application_contract("main.sea", &sources)
}

fn codes(err: &[ApplicationDiagnostic]) -> Vec<String> {
    err.iter()
        .map(|d| {
            serde_json::to_value(d.code)
                .unwrap()
                .as_str()
                .unwrap()
                .to_string()
        })
        .collect()
}

#[test]
fn resolves_flagship_types_without_changing_concept_identity() {
    let doc = resolve_fixture_contract("flagship/command-write.sea").unwrap();
    assert_eq!(
        doc.contract.records[0].id.0,
        "flagship.orders.record.PlaceOrderInput"
    );
    let order = doc
        .contract
        .entities
        .iter()
        .find(|e| e.name == "Order")
        .unwrap();
    assert_eq!(
        order.concept_id,
        ConceptId::from_concept("flagship.orders", "Order")
    );
    assert_eq!(order.key_field, "order_id");
    assert_eq!(
        doc.contract.enums[0].id.0,
        "flagship.orders.enum.OrderStatus"
    );
    assert!(doc.inputs.source_set_hash.starts_with("sha256:"));
}

#[test]
fn resolves_flagship_closure_through_relative_import() {
    let doc = resolve_fixture_contract("flagship/query-read.sea").unwrap();
    assert!(doc
        .contract
        .records
        .iter()
        .any(|r| r.id.0 == "flagship.orders.record.GetOrderStatusInput"));
    // The imported module's declarations are part of the same closure.
    assert!(doc.contract.entities.iter().any(|e| e.name == "Order"));
}

#[test]
fn unknown_named_type_is_app002() {
    let err = resolve_single("@namespace \"t\"\nrecord R {\n    x: Missing\n}\n").unwrap_err();
    assert_eq!(codes(&err), ["APP002"]);
}

#[test]
fn entity_used_as_dto_field_type_is_rejected() {
    let err = resolve_single(
        "@namespace \"t\"\nentity \"E\" {\n    key id: uuid\n}\nrecord R {\n    x: E\n}\n",
    )
    .unwrap_err();
    assert_eq!(codes(&err), ["APP002"]);
}

#[test]
fn nested_record_field_is_app003() {
    let err = resolve_single(
        "@namespace \"t\"\nrecord Inner {\n    x: string\n}\nrecord Outer {\n    y: Inner\n}\n",
    )
    .unwrap_err();
    assert_eq!(codes(&err), ["APP003"]);
}

#[test]
fn duplicate_fields_are_app004() {
    let err =
        resolve_single("@namespace \"t\"\nrecord R {\n    x: string\n    x: int\n}\n").unwrap_err();
    assert_eq!(codes(&err), ["APP004"]);
}

#[test]
fn entity_key_violations_are_app005() {
    // no key
    let err = resolve_single("@namespace \"t\"\nentity \"E\" {\n    x: string\n}\n").unwrap_err();
    assert_eq!(codes(&err), ["APP005"]);
    // multiple keys
    let err =
        resolve_single("@namespace \"t\"\nentity \"E\" {\n    key a: uuid\n    key b: uuid\n}\n")
            .unwrap_err();
    assert_eq!(codes(&err), ["APP005"]);
    // invalid key type
    let err = resolve_single("@namespace \"t\"\nentity \"E\" {\n    key a: int\n}\n").unwrap_err();
    assert_eq!(codes(&err), ["APP005"]);
}

#[test]
fn record_defaults_are_app003() {
    let err = resolve_single("@namespace \"t\"\nrecord R {\n    x: string default \"v\"\n}\n")
        .unwrap_err();
    assert_eq!(codes(&err), ["APP003"]);
}

#[test]
fn enum_duplicate_names_and_wires_are_app013() {
    let err = resolve_single("@namespace \"t\"\nenum E {\n    a = \"a\",\n    a = \"b\"\n}\n")
        .unwrap_err();
    assert_eq!(codes(&err), ["APP013"]);
    let err =
        resolve_single("@namespace \"t\"\nenum E {\n    a = \"same\",\n    b = \"same\"\n}\n")
            .unwrap_err();
    assert_eq!(codes(&err), ["APP013"]);
}

#[test]
fn operation_input_resolving_to_enum_is_app006() {
    let clauses = READ_CLAUSES_OK.replace("input In", "input Kind");
    let err = resolve_single(&(read_op(&clauses) + "enum Kind {\n    a = \"a\"\n}\n")).unwrap_err();
    assert_eq!(codes(&err), ["APP006"]);
}

#[test]
fn operation_unknown_input_is_app002() {
    let clauses = READ_CLAUSES_OK.replace("input In", "input Missing");
    let err = resolve_single(&read_op(&clauses)).unwrap_err();
    assert_eq!(codes(&err), ["APP002"]);
}

fn operation<'a>(doc: &'a ApplicationContractDocument, name: &str) -> &'a OperationContract {
    doc.contract
        .operations
        .iter()
        .find(|o| o.name == name)
        .unwrap()
}

#[test]
fn command_and_query_lower_to_the_closed_v01_semantics() {
    let command = resolve_fixture_contract("flagship/command-write.sea").unwrap();
    let place = operation(&command, "place_order");
    assert!(matches!(place.effect, EffectKind::Creates));
    assert!(matches!(
        place.transaction,
        TransactionBoundary::SingleAggregate
    ));
    assert!(matches!(place.idempotency,
        IdempotencyStrategy::KeyedBy { ref field } if field == "client_order_id"));
    assert!(matches!(place.concurrency,
        ConcurrencyStrategy::UniqueKey { ref field } if field == "client_order_id"));
    assert!(matches!(place.access, AccessMode::PolicyGoverned { .. }));
    assert_eq!(place.id.0, "flagship.orders.operation.place_order");
    assert_eq!(place.input.0, "flagship.orders.record.PlaceOrderInput");
    assert_eq!(place.failures.len(), 3);

    let query = resolve_fixture_contract("flagship/query-read.sea").unwrap();
    let read = operation(&query, "get_order_status");
    assert!(matches!(read.access, AccessMode::Public));
    assert!(matches!(read.effect, EffectKind::Reads));
    assert!(matches!(read.transaction, TransactionBoundary::ReadOnly));
    assert!(matches!(read.idempotency, IdempotencyStrategy::Inherent));
    assert!(matches!(
        read.concurrency,
        ConcurrencyStrategy::ReadSnapshot
    ));
}

const READ_PREAMBLE: &str = "@namespace \"t\"\n\
entity \"E\" {\n    key id: uuid\n    n: int\n}\n\
record In {\n    id: uuid\n}\n\
record Out {\n    id: uuid\n}\n";

fn read_op(clauses: &str) -> String {
    format!("{READ_PREAMBLE}operation op {{\n{clauses}}}\n")
}

const READ_CLAUSES_OK: &str = "    intent \"read\"\n    direction inbound\n    actor anonymous\n    access public\n    input In\n    output Out\n    state E\n    effect reads E\n    transaction read_only\n    failure not_found for missing_state \"absent\"\n    idempotency inherent\n    concurrency read_snapshot\n    evidence operation_trace\n    lifecycle synchronous_request_response\n";

#[test]
fn valid_inline_read_operation_lowers() {
    resolve_single(&read_op(READ_CLAUSES_OK)).unwrap();
}

#[test]
fn app001_reports_all_clause_defects_together() {
    // Missing intent + outbound direction + wrong transaction: one APP001.
    let clauses = READ_CLAUSES_OK
        .replace("    intent \"read\"\n", "")
        .replace("direction inbound", "direction outbound")
        .replace("transaction read_only", "transaction single_aggregate");
    let err = resolve_single(&read_op(&clauses)).unwrap_err();
    assert_eq!(codes(&err), ["APP001"]);
    let msg = &err[0].message;
    for needle in ["intent", "outbound", "transaction"] {
        assert!(msg.contains(needle), "APP001 message must mention {needle}");
    }
}

#[test]
fn app001_covers_duplicate_and_out_of_order_clauses() {
    let dup = READ_CLAUSES_OK.replace(
        "    direction inbound\n",
        "    direction inbound\n    direction inbound\n",
    );
    assert_eq!(
        codes(&resolve_single(&read_op(&dup)).unwrap_err()),
        ["APP001"]
    );
    let out_of_order = READ_CLAUSES_OK.replace(
        "    intent \"read\"\n    direction inbound\n",
        "    direction inbound\n    intent \"read\"\n",
    );
    assert_eq!(
        codes(&resolve_single(&read_op(&out_of_order)).unwrap_err()),
        ["APP001"]
    );
}

#[test]
fn anonymous_actor_requires_public_access() {
    let src = "@namespace \"t\"\n\
policy p per Constraint Obligation priority 1 as: n >= 0\n\
entity \"E\" {\n    key id: uuid\n    n: int\n}\n\
record In {\n    id: uuid\n}\nrecord Out {\n    id: uuid\n}\n\
operation op {\n    intent \"read\"\n    direction inbound\n    actor anonymous\n    access policy_governed by p at precondition fails with not_found\n    input In\n    output Out\n    state E\n    effect reads E\n    transaction read_only\n    failure not_found for missing_state \"absent\"\n    idempotency inherent\n    concurrency read_snapshot\n    evidence operation_trace\n    lifecycle synchronous_request_response\n}\n";
    assert_eq!(codes(&resolve_single(src).unwrap_err()), ["APP001"]);
}

#[test]
fn failure_defects_are_app008() {
    // Uppercase failure code.
    let bad_code = READ_CLAUSES_OK.replace("failure not_found", "failure NotFound");
    let bad_code = bad_code.replace("with not_found", "with NotFound");
    assert!(
        codes(&resolve_single(&read_op(&bad_code)).unwrap_err()).contains(&"APP008".to_string())
    );
    // Duplicate kind across failures in one operation.
    let dup_kind = READ_CLAUSES_OK.replace(
        "    failure not_found for missing_state \"absent\"\n",
        "    failure not_found for missing_state \"absent\"\n    failure gone for missing_state \"also absent\"\n",
    );
    assert!(
        codes(&resolve_single(&read_op(&dup_kind)).unwrap_err()).contains(&"APP008".to_string())
    );
    // Missing mapped path: reads without a missing_state failure.
    let no_missing_state = READ_CLAUSES_OK.replace(
        "    failure not_found for missing_state \"absent\"\n",
        "    failure oops for input_validation \"bad input\"\n",
    );
    assert!(
        codes(&resolve_single(&read_op(&no_missing_state)).unwrap_err())
            .contains(&"APP008".to_string())
    );
}

#[test]
fn strategy_effect_mismatches_are_app009() {
    // reads with keyed_by idempotency.
    let keyed = READ_CLAUSES_OK.replace("idempotency inherent", "idempotency keyed_by id");
    assert!(codes(&resolve_single(&read_op(&keyed)).unwrap_err()).contains(&"APP009".to_string()));
    // reads with unique_key concurrency.
    let unique = READ_CLAUSES_OK.replace("concurrency read_snapshot", "concurrency unique_key id");
    assert!(codes(&resolve_single(&read_op(&unique)).unwrap_err()).contains(&"APP009".to_string()));
}

#[test]
fn not_applicable_is_legal_only_on_reads() {
    let ok = READ_CLAUSES_OK.replace(
        "idempotency inherent",
        "idempotency not_applicable(read_only, \"no retry semantics\")",
    );
    let doc = resolve_single(&read_op(&ok)).unwrap();
    assert!(matches!(
        operation(&doc, "op").idempotency,
        IdempotencyStrategy::NotApplicable(_)
    ));
}

/// APP010 (M0 gate finding 1): `not_applicable` rejects write operations
/// outright. The `read_only` reason invariant is enforced earlier by the
/// grammar (`na_reason = { ^"read_only" }`), so only write-op rejection is
/// behaviorally testable through the public resolver.
#[test]
fn app010_rejects_not_applicable_on_write_operations() {
    let src = "@namespace \"t\"\n\
entity \"E\" {\n    key id: uuid\n    n: int\n}\n\
record In {\n    id: uuid\n    n: int\n}\n\
record Out {\n    id: uuid\n}\n\
operation op {\n    intent \"create\"\n    direction inbound\n    actor anonymous\n    access public\n    input In\n    output Out\n    state E\n    effect creates E\n    transaction single_aggregate\n    failure conflict for idempotency_conflict, concurrency_conflict \"dup\"\n    idempotency not_applicable(read_only, \"no retry\")\n    concurrency unique_key id\n    evidence operation_trace\n    lifecycle synchronous_request_response\n}\n";
    let err = resolve_single(src).unwrap_err();
    let d = err
        .iter()
        .find(|d| d.code == domainforge_core::application::ApplicationDiagnosticCode::App010)
        .expect("expected APP010 for not_applicable on a write op");
    assert_eq!(d.context.logical_module_id.as_deref(), Some("main.sea"));
    assert!(d.context.line.is_some() && d.context.column.is_some());
}

/// APP009 (M0 gate finding 1): `keyed_by`/`unique_key` strategy fields must
/// be required scalar input fields of the right type; an optional or wrong-
/// typed field is rejected.
#[test]
fn app009_rejects_non_int_or_optional_strategy_fields() {
    // unique_key references an optional field — APP009 fires.
    let src = "@namespace \"t\"\n\
entity \"E\" {\n    key id: uuid\n}\n\
record In {\n    id: uuid\n    version: int optional\n}\n\
record Out {\n    id: uuid\n}\n\
operation op {\n    intent \"create\"\n    direction inbound\n    actor anonymous\n    access public\n    input In\n    output Out\n    state E\n    effect creates E\n    transaction single_aggregate\n    failure conflict for idempotency_conflict, concurrency_conflict \"dup\"\n    idempotency keyed_by id\n    concurrency optimistic_version version\n    evidence operation_trace\n    lifecycle synchronous_request_response\n}\n";
    let err = resolve_single(src).unwrap_err();
    assert!(
        codes(&err).contains(&"APP009".to_string()),
        "expected APP009 for optional optimistic_version field, got {err:?}"
    );
}

#[test]
fn app001_missing_semantics_fixture_fails() {
    let sources = serde_json::json!({ "main.sea": include_str!(
        "../../fixtures/application_generation/invalid/app001-missing-application-semantics.sea") })
    .to_string();
    let err = resolve_application_contract("main.sea", &sources).unwrap_err();
    assert_eq!(codes(&err), ["APP001"]);
}

#[test]
fn app011_effect_state_mismatch_fixture_fails() {
    let sources = serde_json::json!({ "main.sea": include_str!(
        "../../fixtures/application_generation/invalid/app011-effect-state-mismatch.sea") })
    .to_string();
    let err = resolve_application_contract("main.sea", &sources).unwrap_err();
    assert!(codes(&err).contains(&"APP011".to_string()));
}

#[test]
fn create_without_required_state_source_is_app011() {
    // Entity field `n` is required with no default and absent from the input.
    let src = "@namespace \"t\"\n\
entity \"E\" {\n    key id: uuid\n    n: int\n}\n\
record In {\n    id: uuid\n    n: int\n}\n\
record Bad {\n    id: uuid\n}\n\
record Out {\n    id: uuid\n}\n\
operation op {\n    intent \"create\"\n    direction inbound\n    actor anonymous\n    access public\n    input Bad\n    output Out\n    state E\n    effect creates E\n    transaction single_aggregate\n    failure conflict for idempotency_conflict, concurrency_conflict \"dup\"\n    idempotency keyed_by id\n    concurrency unique_key id\n    evidence operation_trace\n    lifecycle synchronous_request_response\n}\n";
    assert!(codes(&resolve_single(src).unwrap_err()).contains(&"APP011".to_string()));
}

#[test]
fn output_projection_must_match_state_fields() {
    // Output field `extra` projects nothing in state.
    let bad_out = read_op(&READ_CLAUSES_OK.replace("output Out", "output Wide"))
        + "record Wide {\n    id: uuid\n    extra: string\n}\n";
    assert!(codes(&resolve_single(&bad_out).unwrap_err()).contains(&"APP011".to_string()));
}

// ---- Milestone 0 stop gate (plan Task 15) ----
//
// Reference coverage matrix (docs/reference/sea-application-contract.md):
//   §2  grammar/partial AST      -> application_parser_tests.rs
//   §4  operation semantics      -> command_and_query_lower_to_the_closed_v01_semantics,
//                                   app001_*, failure_defects_are_app008,
//                                   strategy_effect_mismatches_are_app009,
//                                   not_applicable_is_legal_only_on_reads,
//                                   create_without_required_state_source_is_app011,
//                                   output_projection_must_match_state_fields
//   §4  policy subset/evaluator  -> application_policy_tests.rs
//   §5  diagnostics registry     -> application_diagnostic_tests.rs
//   §6  canonicalization         -> source_set_hash_is_framed_sorted_and_path_independent,
//                                   canonical_decimal_strips_trailing_zeros,
//                                   input_fingerprint_is_key_order_and_scale_independent,
//                                   document_self_hash_omits_only_self_hash,
//                                   semantic_pack_compat_tests.rs
//   §6/§8 envelope               -> application_schema_tests.rs
//   §7  import/identity          -> module resolver unit tests,
//                                   resolves_flagship_closure_through_relative_import,
//                                   diamond_imports_build_one_graph_without_duplicates,
//                                   application_diagnostic_tests.rs (APP014 reasons)
//   §8  public types             -> application_public_types_tests.rs
//   §9  bindings                 -> tests/test_parser.py,
//                                   typescript-tests/native-binding.test.ts,
//                                   domainforge-core/tests/wasm_tests.rs
//   §10 compatibility            -> application_compatibility_tests.rs, printer_tests.rs
//   §13 traceability             -> fixed_logical_source_set_is_byte_deterministic,
//                                   d9_flagship_contract_matches_the_accepted_document

#[test]
fn fixed_logical_source_set_is_byte_deterministic() {
    use domainforge_core::application::resolve_application_contract_json;
    let sources = flagship_sources_json();
    let first = resolve_application_contract_json("flagship/query-read.sea", &sources).unwrap();
    let second = resolve_application_contract_json("flagship/query-read.sea", &sources).unwrap();
    assert_eq!(first.as_bytes(), second.as_bytes());
    let doc: ApplicationContractDocument = serde_json::from_str(&first).unwrap();
    let again: ApplicationContractDocument = serde_json::from_str(&second).unwrap();
    assert_eq!(doc.semantic_closure_hash, again.semantic_closure_hash);
}

#[test]
fn d9_flagship_contract_matches_the_accepted_document() {
    use domainforge_core::application::{
        ActorRef, EnforcementPoint, FailureKind, FieldType, TypedValue,
    };
    let doc = resolve_fixture_contract("flagship/command-write.sea").unwrap();
    let place = operation(&doc, "place_order");

    // Defaulted status on the Order aggregate.
    let order = doc
        .contract
        .entities
        .iter()
        .find(|e| e.name == "Order")
        .unwrap();
    let status = order.fields.iter().find(|f| f.name == "status").unwrap();
    assert!(matches!(
        &status.default,
        Some(TypedValue::Enum { wire, .. }) if wire == "placed"
    ));
    assert!(matches!(&status.field_type, FieldType::Enum { symbol }
        if symbol.0 == "flagship.orders.enum.OrderStatus"));

    // Failure mapping: kinds may share one declared code.
    let conflict = place
        .failures
        .iter()
        .find(|f| f.code == "idempotency_conflict")
        .unwrap();
    assert_eq!(
        conflict.kinds,
        vec![
            FailureKind::IdempotencyConflict,
            FailureKind::ConcurrencyConflict
        ]
    );

    // Policy binding at the precondition with the declared failure code.
    let AccessMode::PolicyGoverned { bindings } = &place.access else {
        panic!("place_order is policy-governed");
    };
    assert_eq!(bindings.len(), 1);
    assert!(matches!(
        bindings[0].enforcement_point,
        EnforcementPoint::Precondition
    ));
    assert_eq!(bindings[0].failure_code, "order_limit_exceeded");
    assert!(matches!(&place.actor, ActorRef::Role { .. }));

    // State/effect target the Order aggregate.
    assert_eq!(place.state, order.concept_id);

    // Public query output projects only non-sensitive state fields.
    let query = resolve_fixture_contract("flagship/query-read.sea").unwrap();
    let output = query
        .contract
        .records
        .iter()
        .find(|r| r.name == "GetOrderStatusOutput")
        .unwrap();
    let names: Vec<&str> = output.fields.iter().map(|f| f.name.as_str()).collect();
    assert_eq!(names, ["order_id", "status"]);

    // Restart-stable IDs: identity depends only on the source set.
    let restarted = resolve_fixture_contract("flagship/command-write.sea").unwrap();
    assert_eq!(restarted.self_hash, doc.self_hash);
}

// ---- shared Graph/contract ownership (plan Task 13) ----

fn flagship_sources_json() -> String {
    serde_json::json!({
        "flagship/command-write.sea": include_str!(
            "../../fixtures/application_generation/flagship/command-write.sea"),
        "flagship/query-read.sea": include_str!(
            "../../fixtures/application_generation/flagship/query-read.sea"),
    })
    .to_string()
}

#[test]
fn graph_and_contract_share_order_and_role_concept_ids() {
    use domainforge_core::application::{resolve_application_graph, ActorRef};
    let sources = flagship_sources_json();
    let doc = resolve_fixture_contract("flagship/command-write.sea").unwrap();
    let graph = resolve_application_graph("flagship/command-write.sea", &sources).unwrap();
    let order = doc
        .contract
        .entities
        .iter()
        .find(|e| e.name == "Order")
        .unwrap();
    assert!(graph.has_entity(&order.concept_id));
    let place = operation(&doc, "place_order");
    let ActorRef::Role { role } = &place.actor else {
        panic!("place_order must have the Customer actor");
    };
    assert!(graph.get_role(role).is_some());
}

#[test]
fn diamond_imports_build_one_graph_without_duplicates() {
    use domainforge_core::application::resolve_application_graph;
    use domainforge_core::concept_id::ConceptId;
    let sources = serde_json::json!({
        "base.sea": "@namespace \"d\"\nexport entity \"Base\" {\n    key id: uuid\n}\n",
        "left.sea": "@namespace \"d\"\nimport { Base } from \"./base.sea\"\nexport record L {\n    id: uuid\n}\n",
        "right.sea": "@namespace \"d\"\nimport { Base } from \"./base.sea\"\nexport record R {\n    id: uuid\n}\n",
        "top.sea": "@namespace \"d\"\nimport { L } from \"./left.sea\"\nimport { R } from \"./right.sea\"\n",
    })
    .to_string();
    let graph = resolve_application_graph("top.sea", &sources).unwrap();
    assert!(graph.has_entity(&ConceptId::from_concept("d", "Base")));
}

// ---- canonicalization (plan Task 11) ----

#[test]
fn source_set_hash_is_framed_sorted_and_path_independent() {
    use domainforge_core::application::source_set_hash;
    let a = source_set_hash([("b.sea", "Entity \"B\""), ("a.sea", "Entity \"A\"")]).unwrap();
    let b = source_set_hash([("a.sea", "Entity \"A\""), ("b.sea", "Entity \"B\"")]).unwrap();
    assert_eq!(a, b);
    assert!(a.starts_with("sha256:"));
    assert_eq!(a.len(), 71);
    // NFC-equivalent logical IDs hash identically; duplicates are rejected.
    let composed = source_set_hash([("caf\u{e9}.sea", "x")]).unwrap();
    let decomposed = source_set_hash([("cafe\u{301}.sea", "x")]).unwrap();
    assert_eq!(composed, decomposed);
    assert!(source_set_hash([("a.sea", "x"), ("a.sea", "y")]).is_err());
}

#[test]
fn canonical_decimal_strips_trailing_zeros() {
    use domainforge_core::application::canonical_decimal;
    use rust_decimal::Decimal;
    use std::str::FromStr;
    assert_eq!(
        canonical_decimal(Decimal::from_str("125.00").unwrap()),
        "125"
    );
    assert_eq!(canonical_decimal(Decimal::from_str("0.00").unwrap()), "0");
    assert_eq!(canonical_decimal(Decimal::from_str("1.50").unwrap()), "1.5");
}

#[test]
fn input_fingerprint_is_key_order_and_scale_independent() {
    use domainforge_core::application::{input_fingerprint, TypedValue};
    use rust_decimal::Decimal;
    use std::str::FromStr;
    let mut a = indexmap::IndexMap::new();
    a.insert(
        "total".to_string(),
        TypedValue::Decimal(Decimal::from_str("125.00").unwrap()),
    );
    a.insert("id".to_string(), TypedValue::Int(1));
    let mut b = indexmap::IndexMap::new();
    b.insert("id".to_string(), TypedValue::Int(1));
    b.insert(
        "total".to_string(),
        TypedValue::Decimal(Decimal::from_str("125").unwrap()),
    );
    assert_eq!(input_fingerprint(&a), input_fingerprint(&b));
    assert!(input_fingerprint(&a).starts_with("sha256:"));
}

#[test]
fn document_self_hash_omits_only_self_hash() {
    use domainforge_core::application::document_self_hash;
    let doc = resolve_fixture_contract("flagship/command-write.sea").unwrap();
    assert_eq!(doc.self_hash, document_self_hash(&doc));
    assert_ne!(doc.self_hash, format!("sha256:{}", "0".repeat(64)));
    // The self-hash covers every other field, including inputs hashes.
    let mut tampered = doc.clone();
    tampered.inputs.source_set_hash = format!("sha256:{}", "1".repeat(64));
    assert_ne!(document_self_hash(&tampered), doc.self_hash);
}

#[test]
fn invalid_enum_default_wire_is_app003() {
    let err = resolve_single(
        "@namespace \"t\"\nenum Status {\n    a = \"a\"\n}\nentity \"E\" {\n    key id: uuid\n    s: Status default \"nope\"\n}\n",
    )
    .unwrap_err();
    assert_eq!(codes(&err), ["APP003"]);
}