frame-cli 0.2.0

CLI for Frame — frame new scaffolds a complete Frame application: Rust composition host, Gleam component, and a connected browser page served by one binary
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
//! End-to-end acceptance for deterministic, atomic Frame application
//! scaffolds: the mechanical gates (fmt/clippy/test/doc), the manifest and
//! file-shape assertions, byte-determinism and atomicity, and — leg 5 (gate
//! hardening) — a `cargo tree --duplicates` assertion against the B6 skew
//! and the generated page's own real-browser `npm run e2e` executed as part
//! of this gate, not merely shipped (design §8 leg 5, tightened at dispatch:
//! see `docs/design/scaffold-unification/DESIGN.md` §9's leg-5 amendment).

mod support;

use std::error::Error;
use std::fs;
use std::path::Path;
use std::process::{Command, Output};

use frame_cli::NewError;
use support::{TestDirectory, generate, generated_files, options};

type TestResult = Result<(), Box<dyn Error>>;

#[test]
fn generated_project_passes_all_gates_and_real_browser_e2e_untouched() -> TestResult {
    require_gleam()?;
    require_npm()?;
    require_chrome()?;
    let directory = TestDirectory::new("all-gates")?;
    let project = generate(&options(directory.path(), "gate_app"))?;

    // The page must be built BEFORE `cargo test --workspace`: the generated
    // host/tests/e2e.rs full-stack boot test serves the real page/dist and
    // fails loudly (never silently) if it is missing.
    assert_success(
        run(&project.join("page"), "npm", &["install"])?,
        "npm --prefix page install",
    )?;
    assert_success(
        run(&project.join("page"), "npm", &["run", "build"])?,
        "npm --prefix page run build",
    )?;
    let lockfile = fs::read_to_string(project.join("page/package-lock.json"))?;
    assert!(
        !lockfile.contains("file:") && !lockfile.contains("\"link\""),
        "the resolved page lockfile must carry no file:/link: entries (registry packages only)"
    );

    let before = generated_files(&project)?;

    assert_success(
        run(&project, "cargo", &["fmt", "--all"])?,
        "cargo fmt --all",
    )?;
    assert_success(
        run(
            &project,
            "cargo",
            &[
                "clippy",
                "--workspace",
                "--all-targets",
                "--",
                "-D",
                "warnings",
            ],
        )?,
        "cargo clippy --workspace --all-targets -- -D warnings",
    )?;

    // B6 (§5.3): a fresh scaffold's resolution must carry exactly one
    // beamr/haematite/frame-* line apiece. `cargo tree --duplicates` prints
    // every crate resolved at more than one semver-incompatible version;
    // ordinary transitive duplicates among unrelated crates (syn, bitflags,
    // etc.) are expected and not this gate's concern — only a duplicated
    // Frame-stack crate is a regression of the skew leg 2/3 killed.
    let tree_output = run(&project, "cargo", &["tree", "--duplicates"])?;
    if !tree_output.status.success() {
        return Err(format!(
            "cargo tree --duplicates failed with {}\nstdout:\n{}\nstderr:\n{}",
            tree_output.status,
            String::from_utf8_lossy(&tree_output.stdout),
            String::from_utf8_lossy(&tree_output.stderr)
        )
        .into());
    }
    let tree_stdout = String::from_utf8_lossy(&tree_output.stdout).into_owned();
    let offenders = duplicate_offenders(&tree_stdout);
    assert!(
        offenders.is_empty(),
        "cargo tree --duplicates reported duplicate Frame-stack crates (B6 regression): \
         {offenders:#?}\nfull output:\n{tree_stdout}"
    );

    // cargo test --workspace exercises host/tests/e2e.rs, which now includes
    // the full-stack boot proof (component + embedded messaging server + page
    // server, on ephemeral ports, SIGTERM teardown, zero listeners left) in
    // addition to the bounded lifecycle/storage round trip and the Gleam
    // component test — this IS the "does the generated project actually
    // build and run" proof.
    assert_success(
        run(&project, "cargo", &["test", "--workspace"])?,
        "cargo test --workspace",
    )?;
    let mut doc = Command::new("cargo");
    doc.args(["doc", "--workspace", "--no-deps"])
        .env("RUSTDOCFLAGS", "-D warnings")
        .current_dir(&project);
    assert_success(
        doc.output()?,
        "RUSTDOCFLAGS=-D warnings cargo doc --workspace --no-deps",
    )?;

    // Leg 5 (gate hardening): the generated page's own real-browser proof
    // (`page/scripts/e2e.mjs`, playwright-core driving installed Chrome)
    // now runs as part of THIS gate — not merely asserted present. The
    // script builds the page, builds and boots the real `app-host` binary,
    // drives real Chrome to a live page, sends a real message, and requires
    // clean SIGTERM teardown with nothing left listening; any failure here
    // fails this test with the script's own actionable stderr, never a skip.
    assert_success(
        run(&project.join("page"), "npm", &["run", "e2e"])?,
        "npm --prefix page run e2e",
    )?;

    assert_eq!(
        before,
        generated_files(&project)?,
        "gates changed generated source"
    );
    Ok(())
}

#[test]
fn generated_manifests_pin_the_actual_dependency_set_and_files_stay_bounded() -> TestResult {
    let directory = TestDirectory::new("manifest-pins")?;
    let project = generate(&options(directory.path(), "pinned_app"))?;
    let root_manifest = fs::read_to_string(project.join("Cargo.toml"))?;
    assert!(root_manifest.contains("frame-core = { version = \"=0.2.0\" }"));
    assert!(root_manifest.contains("frame-state = { version = \"=0.2.0\" }"));
    // frame-host repinned to 0.2.1 (leg 5, 2026-07-21): the boot-visibility
    // fix (serve-order + /frame/app/status.json snapshot) that closes this
    // leg's browser-e2e finding shipped there; frame-core/frame-state did
    // not republish and stay pinned at 0.2.0.
    assert!(root_manifest.contains("frame-host = { version = \"=0.2.1\" }"));
    assert!(
        !root_manifest.contains("beamr"),
        "the unified scaffold carries zero beamr manifest entries (B6): the runtime and its \
         feature selection are frame-core's own published dependency"
    );
    assert!(
        !root_manifest.contains("path ="),
        "registry-pinned scaffold must carry no path dependencies"
    );
    assert!(!root_manifest.contains("haematite ="));
    for (path, bytes) in generated_files(&project)? {
        assert!(
            !bytes
                .windows(b"{{FRAME_ROOT}}".len())
                .any(|window| window == b"{{FRAME_ROOT}}"),
            "{} carried {{{{FRAME_ROOT}}}} residue",
            path.display()
        );
    }

    let host_source = fs::read_to_string(project.join("host/src/lib.rs"))?;
    assert!(host_source.contains("Process observation is event-driven"));
    assert!(!host_source.contains("observation_interval"));
    assert!(!host_source.contains("OBSERVATION_INTERVAL"));
    assert!(
        !host_source.contains("beamr"),
        "the generated host must carry no beamr token (B6)"
    );

    let host_manifest = fs::read_to_string(project.join("host/Cargo.toml"))?;
    let dependency_block = host_manifest
        .split_once("[dependencies]")
        .and_then(|(_, tail)| tail.split_once("[lints]"))
        .map(|(dependencies, _)| dependencies)
        .ok_or("generated host manifest lacked its dependency block")?;
    assert_eq!(
        dependency_block
            .lines()
            .filter(|line| !line.trim().is_empty())
            .collect::<Vec<_>>(),
        [
            "frame-core = { workspace = true }",
            "frame-state = { workspace = true }",
            "frame-host = { workspace = true }",
            "serde_json = { workspace = true }",
            "tracing = { workspace = true }",
            "tracing-subscriber = { workspace = true }",
        ]
    );

    let page_manifest = fs::read_to_string(project.join("page/package.json"))?;
    assert!(page_manifest.contains("\"@ablative/liminal\""));
    assert!(
        !page_manifest.contains("file:") && !page_manifest.contains("link:"),
        "the page manifest must carry no file:/link: dependencies (registry packages only)"
    );
    assert!(
        !page_manifest.contains("\"dev\""),
        "the page manifest must declare no dev script: the bundler is build-only"
    );

    for (path, bytes) in generated_files(&project)? {
        assert!(
            bytes.split(|byte| *byte == b'\n').count() < 500,
            "{} exceeded the 500-line cap",
            path.display()
        );
    }
    Ok(())
}

#[test]
fn generation_is_byte_deterministic_and_frame_core_name_cannot_collide() -> TestResult {
    let left = TestDirectory::new("deterministic-left")?;
    let right = TestDirectory::new("deterministic-right")?;
    let first = generate(&options(left.path(), "same_app"))?;
    let second = generate(&options(right.path(), "same_app"))?;
    assert_eq!(tree_hash(&first)?, tree_hash(&second)?);

    let collision = generate(&options(left.path(), "frame-core"));
    assert!(matches!(collision, Err(NewError::InvalidBothNames { .. })));
    Ok(())
}

#[test]
fn existing_target_is_typed_and_untouched() -> TestResult {
    let directory = TestDirectory::new("existing")?;
    let target = directory.path().join("kept_app");
    fs::create_dir(&target)?;
    fs::write(target.join("marker"), b"untouched")?;
    let result = generate(&options(directory.path(), "kept_app"));
    assert!(matches!(result, Err(NewError::TargetExists { .. })));
    assert_eq!(fs::read(target.join("marker"))?, b"untouched");
    Ok(())
}

#[test]
fn missing_gleam_is_actionable_and_never_skipped() -> TestResult {
    let directory = TestDirectory::new("missing-gleam")?;
    let project = generate(&options(directory.path(), "tool_app"))?;
    let builder = directory.path().join("generated-build-script");
    assert_success(
        Command::new("rustc")
            .args(["--edition", "2024"])
            .arg(project.join("host/build.rs"))
            .arg("-o")
            .arg(&builder)
            .output()?,
        "compile generated build script",
    )?;
    let output = Command::new(builder)
        .current_dir(project.join("host"))
        .env("PATH", directory.path())
        .env("OUT_DIR", directory.path())
        .output()?;
    assert!(!output.status.success());
    let message = String::from_utf8_lossy(&output.stderr);
    assert!(message.contains("Gleam toolchain is required"));
    assert!(message.contains("https://gleam.run/getting-started/installing/"));
    Ok(())
}

/// Parses `cargo tree --duplicates` output for duplicated Frame-stack
/// crates. Header lines (one per duplicated package) start at column zero
/// with the bare package name — every other line in that package's
/// reverse-dependency subtree is indented or prefixed with a box-drawing
/// character. B6's skew was exactly this shape (`beamr` resolving to two
/// semver-incompatible versions); this generalizes to any duplicated
/// `beamr`, `haematite`, or `frame-*` crate so a future upstream regression
/// fails this gate loudly instead of silently re-forking the runtime
/// (design §5.3).
fn duplicate_offenders(tree_output: &str) -> Vec<String> {
    tree_output
        .lines()
        .filter(|line| line.starts_with(|c: char| c.is_ascii_alphanumeric()))
        .filter(|line| {
            let name = line.split_whitespace().next().unwrap_or("");
            name == "beamr" || name == "haematite" || name == "frame" || name.starts_with("frame-")
        })
        .map(str::to_owned)
        .collect()
}

/// Gleam is a mandatory scaffold-acceptance toolchain requirement: a loud,
/// actionable refusal, never a silent skip.
fn require_gleam() -> Result<(), Box<dyn Error>> {
    let output = Command::new("gleam").arg("--version").output().map_err(|error| {
        std::io::Error::new(
            error.kind(),
            format!("Gleam is mandatory for scaffold acceptance; install it from https://gleam.run/getting-started/installing/: {error}"),
        )
    })?;
    assert_success(output, "mandatory gleam --version")
}

/// Node/npm are mandatory scaffold-acceptance toolchain requirements exactly
/// as Gleam is: a loud, actionable refusal, never a silent skip — the
/// unified scaffold's page half only builds and proves itself with them
/// present.
fn require_npm() -> Result<(), Box<dyn Error>> {
    let output = Command::new("npm").arg("--version").output().map_err(|error| {
        std::io::Error::new(
            error.kind(),
            format!("npm is mandatory for scaffold acceptance; install Node.js 20+ from https://nodejs.org/: {error}"),
        )
    })?;
    assert_success(output, "mandatory npm --version")
}

/// Real, installed Chrome is a mandatory scaffold-acceptance requirement for
/// the generated page's own real-browser proof (design leg 5, §8): the
/// generated `page/scripts/e2e.mjs` launches Chromium through
/// `playwright-core`, which — unlike the full `playwright` package —
/// bundles and downloads no browser of its own; it only drives one supplied
/// by `executablePath`. `CHROME_BIN` overrides the default macOS
/// installation path the generated script itself falls back to. A missing
/// browser is a loud, actionable refusal, never a silent skip: the arc's
/// one-product claim rests on a real browser proving the page live, not a
/// mocked one.
fn require_chrome() -> Result<(), Box<dyn Error>> {
    const DEFAULT_CHROME: &str = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
    let path = std::env::var("CHROME_BIN").unwrap_or_else(|_| DEFAULT_CHROME.to_owned());
    require_chrome_at(&path)
}

fn require_chrome_at(path: &str) -> Result<(), Box<dyn Error>> {
    if Path::new(path).is_file() {
        return Ok(());
    }
    Err(format!(
        "installed Chrome is mandatory for the scaffold's real-browser e2e gate; no executable \
         found at `{path}`. playwright-core does not bundle or download a browser: set \
         CHROME_BIN to an installed Chrome/Chromium executable, or install Google Chrome at the \
         default macOS path."
    )
    .into())
}

fn run(directory: &Path, program: &str, args: &[&str]) -> Result<Output, std::io::Error> {
    Command::new(program)
        .args(args)
        .current_dir(directory)
        .output()
}

fn assert_success(output: Output, command: &str) -> Result<(), Box<dyn Error>> {
    let Output {
        status,
        stdout,
        stderr,
    } = output;
    if status.success() {
        return Ok(());
    }
    Err(format!(
        "{command} failed with {status}\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&stdout),
        String::from_utf8_lossy(&stderr)
    )
    .into())
}

fn tree_hash(root: &Path) -> Result<blake3::Hash, std::io::Error> {
    let mut hasher = blake3::Hasher::new();
    for (path, bytes) in generated_files(root)? {
        let path = path.to_string_lossy();
        hasher.update(&(path.len() as u64).to_le_bytes());
        hasher.update(path.as_bytes());
        hasher.update(&(bytes.len() as u64).to_le_bytes());
        hasher.update(&bytes);
    }
    Ok(hasher.finalize())
}

#[cfg(test)]
mod duplicate_offenders_tests {
    use super::duplicate_offenders;

    /// Shape of a real `cargo tree --duplicates` capture against a
    /// deliberately seeded duplicate `beamr` (a generated `host/Cargo.toml`
    /// given an extra direct `beamr = "0.13"` dependency alongside the
    /// workspace's `=0.15.4` pin — the exact B6 skew). The untruncated,
    /// unedited capture this excerpt is drawn from is committed at
    /// `evidence/cargo-tree-duplicates-red.txt`.
    const SEEDED_DUPLICATE_EXCERPT: &str = "\
beamr v0.13.0
└── app-host v0.1.0 (/tmp/example_app/host)

beamr v0.15.4
├── frame-core v0.2.0
│   └── app-host v0.1.0 (/tmp/example_app/host) (*)
└── frame-host v0.2.0 (*)
";

    /// Shape of a real `cargo tree --duplicates` capture against an
    /// unmodified fresh scaffold (leg 4 baseline, no Frame-stack
    /// duplication) — ordinary transitive duplicates (syn, bitflags,
    /// hashbrown, …) must never trip this gate. The untruncated capture is
    /// committed at `evidence/cargo-tree-duplicates-green.txt`.
    const CLEAN_EXCERPT: &str = "\
bitflags v1.3.2
└── region v3.0.2
    └── cranelift-jit v0.131.3
        └── beamr v0.15.4 (*)

syn v2.0.119
└── clap_derive v4.5.41 (proc-macro)
    └── clap v4.5.41 (*)

syn v3.0.2
└── async-trait v0.1.91 (proc-macro)
    └── liminal-rs v0.3.1 (*)
";

    #[test]
    fn flags_a_seeded_duplicate_beamr() {
        let offenders = duplicate_offenders(SEEDED_DUPLICATE_EXCERPT);
        assert_eq!(offenders, vec!["beamr v0.13.0", "beamr v0.15.4"]);
    }

    #[test]
    fn does_not_flag_ordinary_transitive_duplicates() {
        assert!(duplicate_offenders(CLEAN_EXCERPT).is_empty());
    }
}

#[cfg(test)]
mod require_chrome_tests {
    use super::require_chrome_at;

    #[test]
    fn refuses_loudly_when_chrome_binary_is_missing() {
        let message = require_chrome_at("/nonexistent/definitely-not-chrome")
            .err()
            .map(|error| error.to_string())
            .unwrap_or_default();
        assert!(message.contains("installed Chrome is mandatory"));
        assert!(message.contains("playwright-core does not bundle or download a browser"));
    }
}