layoutd 0.1.0

CLI tool to diff and classify Anchor/Solana account struct layout changes as Safe, Review, or Danger
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
/// CLI integration tests.
///
/// Each test spawns the real `layoutd` binary and asserts on:
///   - exit code
///   - stdout content
///   - produced files (SARIF, etc.)
///
/// Fixtures live in tests/fixtures/ so they are committed to the repo.
use std::io::Write as _;
use std::path::{Path, PathBuf};

use assert_cmd::Command;
use tempfile::NamedTempFile;

// ── path helpers ──────────────────────────────────────────────────────────────

fn fixture(name: &str) -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures")
        .join(name)
}

fn layoutd() -> Command {
    Command::cargo_bin("layoutd").unwrap()
}

fn write_temp(content: &str) -> NamedTempFile {
    let mut f = NamedTempFile::new().unwrap();
    write!(f, "{content}").unwrap();
    f
}

// ══════════════════════════════════════════════════════════════════════════════
// `diff` command
// ══════════════════════════════════════════════════════════════════════════════

#[test]
fn diff_identical_idls_exits_0() {
    layoutd()
        .args(["diff", fixture("vault_v1.json").to_str().unwrap(),
                       fixture("vault_v1.json").to_str().unwrap(),
               "--account", "Vault"])
        .assert()
        .success();
}

#[test]
fn diff_prints_field_names_and_safety_tags() {
    let out = layoutd()
        .args(["diff", fixture("vault_v1.json").to_str().unwrap(),
                       fixture("vault_v2_safe.json").to_str().unwrap(),
               "--account", "Vault"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(out).unwrap();
    assert!(stdout.contains("version"), "should mention the new field");
    assert!(stdout.contains("SAFE"),    "should print SAFE tag");
}

#[test]
fn diff_danger_prints_danger_tag_but_still_exits_0() {
    // `diff` is informational only — it always exits 0.
    let out = layoutd()
        .args(["diff", fixture("vault_v1.json").to_str().unwrap(),
                       fixture("vault_v2_danger.json").to_str().unwrap(),
               "--account", "Vault"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(out).unwrap();
    assert!(stdout.contains("DANGER"), "diff should print DANGER for removal");
}

#[test]
fn diff_shows_review_for_widen() {
    let out = layoutd()
        .args(["diff", fixture("vault_v1.json").to_str().unwrap(),
                       fixture("vault_v2_widen.json").to_str().unwrap(),
               "--account", "Vault"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(out).unwrap();
    assert!(stdout.contains("REVIEW"), "widen should produce REVIEW");
}

#[test]
fn diff_with_source_rs_file_exits_0() {
    layoutd()
        .args(["diff", fixture("vault_zc.rs").to_str().unwrap(),
                       fixture("vault_zc.rs").to_str().unwrap(),
               "--account", "VaultZC", "--zero-copy"])
        .assert()
        .success();
}

// ══════════════════════════════════════════════════════════════════════════════
// `gen` command
// ══════════════════════════════════════════════════════════════════════════════

#[test]
fn gen_exits_0_for_safe_changes() {
    layoutd()
        .args(["gen", fixture("vault_v1.json").to_str().unwrap(),
                      fixture("vault_v2_safe.json").to_str().unwrap(),
               "--account", "Vault"])
        .assert()
        .success();
}

#[test]
fn gen_outputs_rust_migration_struct() {
    let out = layoutd()
        .args(["gen", fixture("vault_v1.json").to_str().unwrap(),
                      fixture("vault_v2_safe.json").to_str().unwrap(),
               "--account", "Vault"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(out).unwrap();
    assert!(stdout.contains("impl Migration"), "gen must emit impl Migration block");
    assert!(stdout.contains("pub fn migrate"), "gen must emit migrate function");
    assert!(stdout.contains("Vault"),          "gen must reference account name");
}

#[test]
fn gen_includes_size_comment_when_field_added() {
    let out = layoutd()
        .args(["gen", fixture("vault_v1.json").to_str().unwrap(),
                      fixture("vault_v2_safe.json").to_str().unwrap(),
               "--account", "Vault"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(out).unwrap();
    // A field was added → size grew → size comment must be present.
    assert!(stdout.contains("Size:"), "gen must emit size comment when account grows");
    assert!(stdout.contains("realloc"), "gen must mention realloc in size comment");
}

#[test]
fn gen_emits_danger_warning_for_removed_field() {
    let out = layoutd()
        .args(["gen", fixture("vault_v1.json").to_str().unwrap(),
                      fixture("vault_v2_danger.json").to_str().unwrap(),
               "--account", "Vault"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(out).unwrap();
    assert!(stdout.contains("DANGER"),   "gen must mark removed field as DANGER");
    assert!(stdout.contains("WARNING"),  "gen must print WARNING header for danger");
}

// ══════════════════════════════════════════════════════════════════════════════
// `check` command — exit codes
// ══════════════════════════════════════════════════════════════════════════════

#[test]
fn check_safe_change_exits_0() {
    layoutd()
        .args(["check", fixture("vault_v1.json").to_str().unwrap(),
                        fixture("vault_v2_safe.json").to_str().unwrap(),
               "--account", "Vault"])
        .assert()
        .success();
}

#[test]
fn check_identical_idls_exits_0() {
    layoutd()
        .args(["check", fixture("vault_v1.json").to_str().unwrap(),
                        fixture("vault_v1.json").to_str().unwrap(),
               "--account", "Vault"])
        .assert()
        .success();
}

#[test]
fn check_danger_exits_1() {
    layoutd()
        .args(["check", fixture("vault_v1.json").to_str().unwrap(),
                        fixture("vault_v2_danger.json").to_str().unwrap(),
               "--account", "Vault"])
        .assert()
        .failure()
        .code(1);
}

#[test]
fn check_review_alone_exits_0() {
    // A widen (Review) should NOT fail CI by default.
    layoutd()
        .args(["check", fixture("vault_v1.json").to_str().unwrap(),
                        fixture("vault_v2_widen.json").to_str().unwrap(),
               "--account", "Vault"])
        .assert()
        .success();
}

#[test]
fn check_danger_stdout_names_field_and_reason() {
    let out = layoutd()
        .args(["check", fixture("vault_v1.json").to_str().unwrap(),
                        fixture("vault_v2_danger.json").to_str().unwrap(),
               "--account", "Vault"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(out).unwrap();
    assert!(stdout.contains("DANGER"),  "check must print DANGER for field removal");
    assert!(stdout.contains("balance"), "check must name the removed field");
}

#[test]
fn check_prints_ok_when_all_safe() {
    let out = layoutd()
        .args(["check", fixture("vault_v1.json").to_str().unwrap(),
                        fixture("vault_v1.json").to_str().unwrap(),
               "--account", "Vault"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(out).unwrap();
    assert!(stdout.contains("OK"), "check must print OK when all safe");
}

#[test]
fn check_suggests_gen_on_failure() {
    let out = layoutd()
        .args(["check", fixture("vault_v1.json").to_str().unwrap(),
                        fixture("vault_v2_danger.json").to_str().unwrap(),
               "--account", "Vault"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(out).unwrap();
    assert!(stdout.contains("gen"), "check failure should suggest running `layoutd gen`");
}

// ══════════════════════════════════════════════════════════════════════════════
// `check --sarif` — SARIF 2.1.0 output
// ══════════════════════════════════════════════════════════════════════════════

#[test]
fn check_sarif_creates_valid_json_file() {
    let sarif_file = tempfile::NamedTempFile::new().unwrap();
    let sarif_path = sarif_file.path().to_str().unwrap().to_string();

    layoutd()
        .args(["check", fixture("vault_v1.json").to_str().unwrap(),
                        fixture("vault_v2_danger.json").to_str().unwrap(),
               "--account", "Vault",
               "--sarif", &sarif_path])
        .assert()
        .failure(); // danger present → exit 1

    let content = std::fs::read_to_string(&sarif_path).expect("SARIF file must be created");
    let doc: serde_json::Value = serde_json::from_str(&content)
        .expect("SARIF output must be valid JSON");

    assert_eq!(doc["version"], "2.1.0", "SARIF version must be 2.1.0");
    assert!(doc["runs"].is_array(), "SARIF must have a 'runs' array");
    let runs = doc["runs"].as_array().unwrap();
    assert!(!runs.is_empty(), "SARIF runs must not be empty");
    assert!(runs[0]["results"].is_array(), "SARIF run must have a 'results' array");
}

#[test]
fn check_sarif_results_contain_rule_ids() {
    let sarif_file = tempfile::NamedTempFile::new().unwrap();
    let sarif_path = sarif_file.path().to_str().unwrap().to_string();

    layoutd()
        .args(["check", fixture("vault_v1.json").to_str().unwrap(),
                        fixture("vault_v2_danger.json").to_str().unwrap(),
               "--account", "Vault",
               "--sarif", &sarif_path])
        .assert()
        .failure();

    let content = std::fs::read_to_string(&sarif_path).unwrap();
    let doc: serde_json::Value = serde_json::from_str(&content).unwrap();
    let results = doc["runs"][0]["results"].as_array().unwrap();
    assert!(!results.is_empty(), "SARIF must have at least one result for a danger");
    for result in results {
        let rule_id = result["ruleId"].as_str().unwrap_or("");
        assert!(
            rule_id.starts_with("LD"),
            "every SARIF result must have an LD-prefixed rule ID, got '{rule_id}'"
        );
    }
}

#[test]
fn check_sarif_written_even_when_safe() {
    let sarif_file = tempfile::NamedTempFile::new().unwrap();
    let sarif_path = sarif_file.path().to_str().unwrap().to_string();

    layoutd()
        .args(["check", fixture("vault_v1.json").to_str().unwrap(),
                        fixture("vault_v1.json").to_str().unwrap(),
               "--account", "Vault",
               "--sarif", &sarif_path])
        .assert()
        .success();

    // File must still exist and be valid JSON (empty results array).
    let content = std::fs::read_to_string(&sarif_path).expect("SARIF file must exist even for safe runs");
    let doc: serde_json::Value = serde_json::from_str(&content).expect("must be valid JSON");
    assert_eq!(doc["version"], "2.1.0");
    let results = doc["runs"][0]["results"].as_array().unwrap();
    assert!(results.is_empty(), "safe run must produce empty SARIF results");
}

// ══════════════════════════════════════════════════════════════════════════════
// `check --ack` — acknowledgement file
// ══════════════════════════════════════════════════════════════════════════════

#[test]
fn check_ack_named_danger_exits_0() {
    let ack = write_temp(r#"{
        "acknowledged": [
            { "account": "Vault", "field": "balance", "change": "removed", "note": "intentional" }
        ]
    }"#);
    layoutd()
        .args(["check", fixture("vault_v1.json").to_str().unwrap(),
                        fixture("vault_v2_danger.json").to_str().unwrap(),
               "--account", "Vault",
               "--ack", ack.path().to_str().unwrap()])
        .assert()
        .success();
}

#[test]
fn check_ack_wrong_field_name_still_fails() {
    // Ack names 'other_field' but danger is 'balance' → must still fail.
    let ack = write_temp(r#"{
        "acknowledged": [
            { "account": "Vault", "field": "other_field", "change": "removed", "note": "typo" }
        ]
    }"#);
    layoutd()
        .args(["check", fixture("vault_v1.json").to_str().unwrap(),
                        fixture("vault_v2_danger.json").to_str().unwrap(),
               "--account", "Vault",
               "--ack", ack.path().to_str().unwrap()])
        .assert()
        .failure()
        .code(1);
}

#[test]
fn check_ack_stale_entry_is_reported() {
    // Ack names a field that no longer has any danger → stale ack warning.
    let ack = write_temp(r#"{
        "acknowledged": [
            { "account": "Vault", "field": "non_existent_field", "change": "removed", "note": "stale" }
        ]
    }"#);
    let out = layoutd()
        .args(["check", fixture("vault_v1.json").to_str().unwrap(),
                        fixture("vault_v1.json").to_str().unwrap(), // identical → no dangers
               "--account", "Vault",
               "--ack", ack.path().to_str().unwrap()])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(out).unwrap();
    assert!(
        stdout.contains("WARN") || stdout.contains("stale"),
        "stale ack must be reported: {stdout}"
    );
}

// ══════════════════════════════════════════════════════════════════════════════
// `check --hints` — rename disambiguation
// ══════════════════════════════════════════════════════════════════════════════

#[test]
fn check_with_hints_file_exits_0_for_hinted_rename() {
    // Cross-position rename: 'balance' renamed to 'collateral' AND moved to a
    // different index (swapped with bump). Auto-detection requires same index,
    // so without a hint it sees balance=Removed (Danger) + collateral=Added.
    //
    // vault_v1:   [owner(pubkey,0), balance(u64,1), bump(u8,2)]
    // v2_swapped: [owner(pubkey,0), bump(u8,1),     collateral(u64,2)]
    let v2_swapped = write_temp(r#"{
        "types": [{
            "name": "Vault",
            "type": {
                "kind": "struct",
                "fields": [
                    { "name": "owner",      "type": "pubkey" },
                    { "name": "bump",       "type": "u8"     },
                    { "name": "collateral", "type": "u64"    }
                ]
            }
        }]
    }"#);

    // Without hint: balance at idx 1, collateral at idx 2 — different indices,
    // auto-detection won't pair them → balance=Removed (Danger) → exit 1.
    layoutd()
        .args(["check", fixture("vault_v1.json").to_str().unwrap(),
                        v2_swapped.path().to_str().unwrap(),
               "--account", "Vault"])
        .assert()
        .failure()
        .code(1);

    // With hint: balance→collateral is forced regardless of index change → Renamed (Safe).
    let hints = write_temp(r#"{
        "renames": [{ "account": "Vault", "from": "balance", "to": "collateral" }]
    }"#);
    layoutd()
        .args(["check", fixture("vault_v1.json").to_str().unwrap(),
                        v2_swapped.path().to_str().unwrap(),
               "--account", "Vault",
               "--hints", hints.path().to_str().unwrap()])
        .assert()
        .success();
}

// ══════════════════════════════════════════════════════════════════════════════
// `check --zero-copy` — stricter rules
// ══════════════════════════════════════════════════════════════════════════════

#[test]
fn check_zero_copy_reorder_exits_1() {
    // Identical struct, but in ZC mode reorder is Danger.
    let old_rs = write_temp(r#"
        #[account(zero_copy)] pub struct VaultZC {
            pub owner: Pubkey, pub balance: u64, pub bump: u8,
        }
    "#);
    let new_rs = write_temp(r#"
        #[account(zero_copy)] pub struct VaultZC {
            pub owner: Pubkey, pub bump: u8, pub balance: u64,
        }
    "#);
    // Rename temp files to .rs so the CLI picks the source adapter.
    let old_path = {
        let p = tempfile::Builder::new().suffix(".rs").tempfile().unwrap();
        std::fs::write(p.path(), std::fs::read_to_string(old_rs.path()).unwrap()).unwrap();
        p
    };
    let new_path = {
        let p = tempfile::Builder::new().suffix(".rs").tempfile().unwrap();
        std::fs::write(p.path(), std::fs::read_to_string(new_rs.path()).unwrap()).unwrap();
        p
    };
    layoutd()
        .args(["check", old_path.path().to_str().unwrap(),
                        new_path.path().to_str().unwrap(),
               "--account", "VaultZC", "--zero-copy"])
        .assert()
        .failure()
        .code(1);
}

#[test]
fn check_zero_copy_add_at_end_exits_0() {
    let old_rs = tempfile::Builder::new().suffix(".rs").tempfile().unwrap();
    std::fs::write(old_rs.path(), r#"
        #[account(zero_copy)] pub struct VaultZC {
            pub owner: Pubkey, pub balance: u64,
        }
    "#).unwrap();
    let new_rs = tempfile::Builder::new().suffix(".rs").tempfile().unwrap();
    std::fs::write(new_rs.path(), r#"
        #[account(zero_copy)] pub struct VaultZC {
            pub owner: Pubkey, pub balance: u64, pub bump: u8,
        }
    "#).unwrap();
    layoutd()
        .args(["check", old_rs.path().to_str().unwrap(),
                        new_rs.path().to_str().unwrap(),
               "--account", "VaultZC", "--zero-copy"])
        .assert()
        .success();
}

// ══════════════════════════════════════════════════════════════════════════════
// Determinism
// ══════════════════════════════════════════════════════════════════════════════

#[test]
fn check_is_deterministic_across_two_runs() {
    fn run_check() -> (Vec<u8>, i32) {
        let sarif_file = tempfile::NamedTempFile::new().unwrap();
        let result = layoutd()
            .args(["check", fixture("vault_v1.json").to_str().unwrap(),
                            fixture("vault_v2_danger.json").to_str().unwrap(),
                   "--account", "Vault",
                   "--sarif", sarif_file.path().to_str().unwrap()])
            .output()
            .unwrap();
        let content = std::fs::read_to_string(sarif_file.path()).unwrap_or_default();
        let code = result.status.code().unwrap_or(-1);
        (content.into_bytes(), code)
    }
    let (out1, code1) = run_check();
    let (out2, code2) = run_check();
    assert_eq!(code1, code2, "exit codes must be identical across runs");
    assert_eq!(out1, out2, "SARIF output must be identical across runs");
}

// ══════════════════════════════════════════════════════════════════════════════
// Robustness
// ══════════════════════════════════════════════════════════════════════════════

#[test]
fn missing_idl_file_exits_nonzero_with_message() {
    let out = layoutd()
        .args(["check", "/nonexistent/old.json", "/nonexistent/new.json",
               "--account", "Vault"])
        .assert()
        .failure()
        .get_output()
        .stderr
        .clone();
    let stderr = String::from_utf8(out).unwrap();
    assert!(!stderr.is_empty(), "missing file must produce stderr message");
}

#[test]
fn unknown_account_in_idl_exits_nonzero_with_message() {
    let out = layoutd()
        .args(["check", fixture("vault_v1.json").to_str().unwrap(),
                        fixture("vault_v1.json").to_str().unwrap(),
               "--account", "DoesNotExist"])
        .assert()
        .failure()
        .get_output()
        .stderr
        .clone();
    let stderr = String::from_utf8(out).unwrap();
    assert!(stderr.contains("DoesNotExist"), "error must name the missing account");
}

#[test]
fn malformed_json_idl_exits_nonzero() {
    let bad = write_temp("this is not json !!!!");
    layoutd()
        .args(["check", bad.path().to_str().unwrap(),
                        bad.path().to_str().unwrap(),
               "--account", "Vault"])
        .assert()
        .failure();
}