bock 1.0.0

The Bock language compiler and CLI — feature-declarative, target-agnostic programming language with AI-native transpilation
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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
//! Implementation of the `bock build` command.
//!
//! Full multi-file pipeline:
//! 1. Discover sources
//! 2. Lex + parse all files
//! 3. Build dependency graph → topological sort
//! 4. Compile in dependency order (with [`bock_air::registry::ModuleRegistry`] for cross-file imports)
//! 5. Code-generate → (optionally) invoke target compiler

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process;
use std::time::Instant;

use bock_air::{
    lower_module, resolve_names_with_registry, Binding, ModuleRegistry, NameKind, NodeIdGen,
    ResolvedName, SymbolTable,
};
use bock_ast::Visibility;
use bock_build::dep_graph::{self, DepGraph};
use bock_build::toolchain::ToolchainRegistry;
use bock_codegen::{
    run_scaffolder, CodeGenerator, GoGenerator, JsGenerator, PyGenerator, RsGenerator,
    ScaffoldConfig, SourceInfo, TsGenerator,
};
use bock_errors::{Diagnostic, DiagnosticBag, FileId, Severity, Span};
use bock_lexer::Lexer;
use bock_parser::Parser;
use bock_source::SourceMap;
use bock_types::{collect_exports, seed_imports, seed_prelude, Strictness, TypeChecker};

/// Known target identifiers.
const KNOWN_TARGETS: &[&str] = &["js", "ts", "python", "rust", "go"];

/// Options for the build command.
pub struct BuildOptions {
    /// Target language(s) to build for.
    pub targets: Vec<String>,
    /// Enable release optimizations (accepted, minimal behavior for v1).
    pub release: bool,
    /// Emit generated code without invoking the target compiler.
    pub source_only: bool,
    /// Use only rule-based codegen (skip AI-assisted generation).
    /// Currently all codegen is rule-based, so this is a no-op for v1.
    #[allow(dead_code)]
    pub deterministic: bool,
    /// Force production strictness for this build regardless of the
    /// project's configured default. Implies the pre-build unpinned-
    /// decision gate (§17.6).
    pub strict: bool,
    /// After a successful build, pin every unpinned build-scope
    /// decision in `.bock/decisions/build/`.
    pub pin_all: bool,
    /// Emit source map sidecar files alongside generated code.
    pub source_map: bool,
}

/// Run the `bock build` command.
///
/// Uses the multi-file pipeline: parse all → dependency sort → compile in order
/// with cross-file name resolution via [`bock_air::registry::ModuleRegistry`], then codegen.
pub fn run(options: &BuildOptions) -> anyhow::Result<()> {
    let total_start = Instant::now();

    // Discover source files
    let files = discover_bock_files_recursive(".")?;
    if files.is_empty() {
        eprintln!("error: no .bock files found");
        process::exit(1);
    }

    println!(
        "build: compiling {} source file{}",
        files.len(),
        if files.len() == 1 { "" } else { "s" }
    );

    let strictness = if options.strict || options.release {
        Strictness::Production
    } else {
        Strictness::Development
    };

    // Project-mode scaffolding config (§20.6.2 / §20.7). Parsing + validating
    // the per-target `[targets.<T>]` / `[targets.<T>.scaffolding]` tables up
    // front means an unknown value (e.g. an unsupported `test_framework`)
    // fails the build *before* any output is written, pointing the user at the
    // documented options for that target. Source mode (`--source-only`) does
    // not scaffold, but we still validate so a misconfigured field is caught
    // in either mode.
    let (scaffold_config, project_name) = read_scaffold_config()?;

    // §17.6 governance gate: in production strictness, fail early on
    // any unpinned build-scope decision. This runs before we touch the
    // frontend so the user sees the actionable error without waiting
    // for a full compile.
    if matches!(strictness, Strictness::Production) {
        let project_root = std::env::current_dir()
            .map_err(|e| anyhow::anyhow!("could not read current directory: {e}"))?;
        run_production_gate(&project_root)?;
    }

    // ── Phase 1: Parse all files ──────────────────────────────────────────────
    let frontend_start = Instant::now();
    let mut source_map = SourceMap::new();
    let mut parsed_files: Vec<ParsedFile> = Vec::new();
    let mut found_errors = false;

    // Prepend the embedded core-stdlib sources so they compile and register
    // through the SAME pipeline before user modules, letting a user module
    // resolve and codegen `use core.<name>.{...}` with no special-casing. Each
    // core module is emitted per target exactly like a user module.
    for src in crate::stdlib::core_sources() {
        match parse_stdlib_source(&src, &mut source_map) {
            Ok(pf) => parsed_files.push(pf),
            Err(()) => found_errors = true,
        }
    }

    for file_path in &files {
        match parse_file(file_path, &mut source_map) {
            Ok(pf) => parsed_files.push(pf),
            Err(()) => found_errors = true,
        }
    }

    if found_errors {
        eprintln!("build: aborting due to parse errors");
        process::exit(1);
    }

    // ── Phase 2: Build dependency graph ───────────────────────────────────────
    let mut dep_graph = DepGraph::new();
    let mut id_to_index: HashMap<String, usize> = HashMap::new();

    // Embedded core (`is_stdlib`) module ids — every user module implicitly
    // depends on them so the §18.2 prelude can seed core-defined symbols even
    // without an explicit `use` (see `check::run`).
    let core_module_ids: Vec<String> = parsed_files
        .iter()
        .enumerate()
        .filter(|(_, pf)| pf.is_stdlib)
        .map(|(i, pf)| dep_graph::module_id_from_module(&pf.module, i))
        .collect();

    for (i, pf) in parsed_files.iter().enumerate() {
        let module_id = dep_graph::module_id_from_module(&pf.module, i);
        let mut deps = dep_graph::extract_dependencies(&pf.module.imports);
        if !pf.is_stdlib {
            dep_graph::add_prelude_deps(&mut deps, &module_id, &core_module_ids);
        }
        dep_graph.add_module_with_deps(module_id.clone(), deps);
        id_to_index.insert(module_id, i);
    }

    // ── Phase 3: Topological sort + cycle detection ───────────────────────────
    let topo_order = match dep_graph.topological_order() {
        Some(order) => order,
        None => {
            eprintln!("error: circular module dependency detected");
            process::exit(1);
        }
    };

    // ── Phase 4: Compile in dependency order ──────────────────────────────────
    let mut registry = ModuleRegistry::new();
    let mut air_modules = Vec::new();
    let mut source_infos = Vec::new();
    let mut module_source_paths: Vec<PathBuf> = Vec::new();

    for module_id in &topo_order {
        let Some(&idx) = id_to_index.get(module_id) else {
            continue; // external dependency — not in our source files
        };

        let pf = &parsed_files[idx];
        let source_file = source_map.get_file(pf.file_id);

        match compile_frontend_with_registry(
            &pf.module,
            &pf.filename,
            source_file,
            &registry,
            strictness,
            pf.is_stdlib,
        ) {
            Ok((air_module, checker)) => {
                // Register exports for downstream modules
                let exports = collect_exports(module_id, &pf.path, &checker, &air_module);
                registry.register(exports);

                air_modules.push(air_module);
                source_infos.push(pf.filename.clone());
                module_source_paths.push(pf.path.clone());
            }
            Err(()) => found_errors = true,
        }
    }

    if found_errors {
        eprintln!("build: aborting due to errors");
        process::exit(1);
    }

    let frontend_ms = frontend_start.elapsed().as_millis();
    println!(
        "  frontend: {frontend_ms}ms ({} modules)",
        air_modules.len()
    );

    // Generate code for each target
    let toolchain_registry = ToolchainRegistry::with_builtins();

    for target in &options.targets {
        let target_start = Instant::now();
        let output_dir = if options.release {
            PathBuf::from(format!("build/release/{target}"))
        } else {
            PathBuf::from(format!("build/{target}"))
        };

        // Create output directory
        std::fs::create_dir_all(&output_dir).map_err(|e| {
            anyhow::anyhow!(
                "failed to create output directory {}: {e}",
                output_dir.display()
            )
        })?;

        // Create the generator for this target
        let generator: Box<dyn CodeGenerator> = create_generator(target)?;

        println!("  target: {target}");

        // Generate output: one file per module, mirroring source structure
        // under `build/<target>/` per spec §20.6.1.
        let mut total_files_written = 0;
        let module_inputs: Vec<(&bock_types::AIRModule, &Path)> = air_modules
            .iter()
            .zip(module_source_paths.iter())
            .map(|(m, p)| (m, p.as_path()))
            .collect();
        // Files emitted by codegen for this target — captured so the
        // project-mode scaffolding pass can avoid clobbering them.
        let mut emitted_files: Vec<bock_codegen::OutputFile> = Vec::new();
        match generator.generate_project(&module_inputs) {
            Ok(mut generated) => {
                let emit_url_comment = matches!(target.as_str(), "js" | "ts");

                for output_file in &mut generated.files {
                    if options.source_map {
                        if let Some(sm) = output_file.source_map.as_mut() {
                            populate_source_map(sm, &parsed_files, &source_map);
                        }
                    }

                    let dest = output_dir.join(&output_file.path);
                    if let Some(parent) = dest.parent() {
                        std::fs::create_dir_all(parent)?;
                    }

                    if options.source_map {
                        if let Some(sm) = &output_file.source_map {
                            let map_name = format!(
                                "{}.map",
                                output_file
                                    .path
                                    .file_name()
                                    .and_then(|s| s.to_str())
                                    .unwrap_or("output")
                            );
                            let map_path = dest.with_file_name(&map_name);
                            std::fs::write(&map_path, sm.to_source_map_v3_json())?;
                            if emit_url_comment {
                                if !output_file.content.is_empty()
                                    && !output_file.content.ends_with('\n')
                                {
                                    output_file.content.push('\n');
                                }
                                output_file
                                    .content
                                    .push_str(&format!("//# sourceMappingURL={map_name}\n"));
                            }
                            total_files_written += 1;
                        }
                    }

                    std::fs::write(&dest, &output_file.content)?;
                    total_files_written += 1;
                    emitted_files.push(output_file.clone());
                }
            }
            Err(e) => {
                eprintln!("error: codegen failed for target {target}: {e}");
                found_errors = true;
            }
        }

        if found_errors {
            eprintln!("build: aborting due to codegen errors");
            process::exit(1);
        }

        // ── Project-mode scaffolding pass (§20.6.2) ──────────────────────────
        // Runs ONLY in the default (project) mode — never under
        // `--source-only`, which emits "no manifests, scaffolding, or
        // entry-point wiring." For S5 the per-target scaffolder bodies are
        // minimal stubs (a placeholder README); S6 fills them with real
        // manifests, transpiled tests, and formatter/linter configs.
        if !options.source_only {
            let target_config = scaffold_config.target(target).cloned().unwrap_or_default();
            match run_scaffolder(
                target,
                &target_config,
                &emitted_files,
                project_name.as_deref(),
            ) {
                Ok(scaffold_files) => {
                    for sf in &scaffold_files {
                        let dest = output_dir.join(&sf.path);
                        if let Some(parent) = dest.parent() {
                            std::fs::create_dir_all(parent)?;
                        }
                        std::fs::write(&dest, &sf.content)?;
                        total_files_written += 1;
                    }
                }
                Err(e) => {
                    eprintln!("error: scaffolding failed for target {target}: {e}");
                    found_errors = true;
                }
            }
        }

        if found_errors {
            eprintln!("build: aborting due to scaffolding errors");
            process::exit(1);
        }

        // ── Transpiled-test pass (§20.6.2) ───────────────────────────────────
        // Project mode transpiles each Bock `@test` function into the target's
        // idiomatic test framework so `cargo test` / `go test` / `npm test` /
        // `pytest` run them. Skipped under `--source-only` (bare transpilation,
        // no scaffolding). The framework variant comes from the validated deep
        // config (defaulting per §20.6.2) so the emitted test files match the
        // scaffolded manifest.
        if !options.source_only {
            let target_config = scaffold_config.target(target).cloned().unwrap_or_default();
            let framework = bock_codegen::effective_test_framework(target, &target_config);
            match generator.generate_tests(&module_inputs, &framework) {
                Ok(artifacts) => {
                    for tf in &artifacts.files {
                        let dest = output_dir.join(&tf.path);
                        if let Some(parent) = dest.parent() {
                            std::fs::create_dir_all(parent)?;
                        }
                        std::fs::write(&dest, &tf.content)?;
                        total_files_written += 1;
                    }
                    // Some targets (Rust) wire their inline test module into the
                    // entry file. Append the snippet to the already-written entry.
                    if let Some(append) = &artifacts.entry_append {
                        if let Some(entry_rel) = entry_file_rel(target) {
                            let entry_path = output_dir.join(entry_rel);
                            if entry_path.exists() {
                                let mut content = std::fs::read_to_string(&entry_path)?;
                                content.push_str(append);
                                std::fs::write(&entry_path, content)?;
                            }
                        }
                    }
                }
                Err(e) => {
                    eprintln!("error: test transpilation failed for target {target}: {e}");
                    found_errors = true;
                }
            }
        }

        if found_errors {
            eprintln!("build: aborting due to test-transpilation errors");
            process::exit(1);
        }

        // ── Post-emit formatter pass (§20.6.2 codegen-formatter agreement) ───
        // For Rust and Go the formatter is universal and always-on: emitted
        // output must pass `rustfmt --check` / `gofmt -l` cleanly as a
        // release-readiness baseline. Rather than hand-match each formatter's
        // alignment/wrapping algorithm in codegen, project mode runs the
        // formatter in-place (`gofmt -w` / `rustfmt`) over the emitted tree as
        // a bounded post-emit step. The formatter ships with the target's
        // toolchain (which project mode already invokes to validate), so it is
        // present whenever the target is being built; if it is somehow absent,
        // we warn and skip rather than fail the build. Go has no source-map
        // dependency (the `//# sourceMappingURL` affordance is js/ts-only), so
        // reformatting is always safe. Skipped under `--source-only` (bare
        // transpilation, no scaffolding).
        if !options.source_only {
            if let Err(e) = format_output_tree(target, &output_dir) {
                eprintln!("  warning: post-emit formatting skipped for {target}: {e}");
            }
        }

        // Optionally invoke target compiler
        if !options.source_only {
            // Some targets (rust/go) emit a real project (Cargo crate / Go
            // module) and validate the whole output dir at once; the rest
            // validate each emitted source file independently.
            if toolchain_registry.validates_per_project(target) {
                match toolchain_registry.invoke_project(target, &output_dir, false) {
                    Ok(_result) => {}
                    Err(bock_build::toolchain::ToolchainError::NotFound {
                        install_hint, ..
                    }) => {
                        eprintln!(
                            "  warning: {target} toolchain not found, skipping compilation.\n  \
                             hint: {install_hint}"
                        );
                    }
                    Err(e) => {
                        eprintln!("error: target compilation failed: {e}");
                        found_errors = true;
                    }
                }
            } else {
                // Walk the output directory and invoke the toolchain on each
                // generated file.
                let ext = target_file_extension(target);
                let generated_files = find_files_with_extension(&output_dir, &ext)?;
                for gen_file in &generated_files {
                    // The transpiled test files (`bock.test.{js,ts}`,
                    // `test_bock.py`) are validated by the test framework
                    // (`npm test` / `pytest`), not by the build-time per-file
                    // toolchain check that targets the runtime source tree: they
                    // import the test framework (which may be absent) and use the
                    // framework's module-resolution semantics. Skip them here.
                    if is_transpiled_test_file(gen_file) {
                        continue;
                    }
                    match toolchain_registry.invoke(target, gen_file, false) {
                        Ok(_result) => {}
                        Err(bock_build::toolchain::ToolchainError::NotFound {
                            install_hint,
                            ..
                        }) => {
                            eprintln!(
                                "  warning: {target} toolchain not found, skipping compilation.\n  \
                                 hint: {install_hint}"
                            );
                            break;
                        }
                        Err(e) => {
                            eprintln!("error: target compilation failed: {e}");
                            found_errors = true;
                        }
                    }
                }
            }
        }

        let target_ms = target_start.elapsed().as_millis();
        println!(
            "    wrote {total_files_written} file{} to {} ({target_ms}ms)",
            if total_files_written == 1 { "" } else { "s" },
            output_dir.display()
        );
    }

    if found_errors {
        eprintln!("build: completed with errors");
        process::exit(1);
    }

    // Post-build: `--pin-all` pins every unpinned build-scope decision
    // so the next production build passes the governance gate. Intended
    // workflow: run in development with `--pin-all`, commit the pins,
    // then ship with `--strict`/`--release`.
    if options.pin_all {
        let project_root = std::env::current_dir()
            .map_err(|e| anyhow::anyhow!("could not read current directory: {e}"))?;
        let pinned = pin_all_build_decisions(&project_root)?;
        println!("build: pin-all pinned {pinned} decision(s)");
    }

    let total_ms = total_start.elapsed().as_millis();
    println!("build: done ({total_ms}ms)");
    Ok(())
}

/// The build-root-relative path of the entry file a target's transpiled-test
/// pass appends its inline-test wiring to, or `None` for targets that place
/// tests in standalone files (no entry wiring needed).
///
/// Only Rust wires an inline `#[cfg(test)] mod bock_tests;` into `src/main.rs`
/// (see [`bock_codegen::TestArtifacts::entry_append`]); js/ts/python/go emit
/// freestanding test files the framework discovers on its own.
fn entry_file_rel(target: &str) -> Option<&'static str> {
    match target {
        "rust" | "rs" => Some("src/main.rs"),
        _ => None,
    }
}

/// Run the post-emit formatter over a target's emitted output tree
/// (§20.6.2 codegen-formatter agreement).
///
/// For Rust and Go the formatter is universal and always-on, so project mode
/// reformats the emitted tree in place rather than trying to hand-match each
/// formatter's exact alignment/wrapping output in codegen. This guarantees
/// `gofmt -l` / `rustfmt --check`-clean output without a brittle dependency on
/// reproducing the formatter's algorithm.
///
/// - **go** — runs `gofmt -w <output_dir>`, which recursively rewrites every
///   `.go` file in place. `gofmt` ships with the Go toolchain (the same
///   toolchain project mode invokes to validate), so it is present whenever the
///   go target is built.
/// - **rust** — runs `rustfmt --edition 2021` on each emitted `.rs` file.
///   Rust codegen is already `rustfmt`-clean; this is belt-and-suspenders against
///   future drift, and a no-op on already-clean output.
/// - **other targets** — no-op (js/ts/python formatting is user-optional per
///   §20.6.2 and is left to the user's configured formatter; post-emit prettier
///   would also break js/ts source maps).
///
/// A missing formatter binary is reported as an error so the caller can downgrade
/// it to a non-fatal warning — the build does not hard-fail on an absent
/// formatter. Returns `Ok(())` for targets with no universal formatter.
fn format_output_tree(target: &str, output_dir: &Path) -> anyhow::Result<()> {
    match target {
        "go" => {
            // `gofmt -w` rewrites every .go file under the directory in place.
            let status = process::Command::new("gofmt")
                .arg("-w")
                .arg(output_dir)
                .status()
                .map_err(|e| anyhow::anyhow!("gofmt not available: {e}"))?;
            if !status.success() {
                anyhow::bail!("gofmt -w exited with status {status}");
            }
            Ok(())
        }
        "rust" | "rs" => {
            // rustfmt operates per file; collect every emitted .rs file and
            // format them in a single invocation.
            let rs_files = find_files_with_extension(output_dir, "rs")?;
            if rs_files.is_empty() {
                return Ok(());
            }
            let status = process::Command::new("rustfmt")
                .args(["--edition", "2021"])
                .args(&rs_files)
                .status()
                .map_err(|e| anyhow::anyhow!("rustfmt not available: {e}"))?;
            if !status.success() {
                anyhow::bail!("rustfmt exited with status {status}");
            }
            Ok(())
        }
        _ => Ok(()),
    }
}

/// Read + validate the project-mode scaffolding config from `bock.project`.
///
/// Returns the validated [`ScaffoldConfig`] (per-target `[targets.<T>]` /
/// `[targets.<T>.scaffolding]` tables — §20.6.2/§20.7) and the `[project] name`,
/// if present. When no `bock.project` exists in the current directory (e.g. a
/// bare `bock build` in a directory of `.bock` files, or the conformance
/// harness), an all-default config and `None` name are returned — the build
/// proceeds with target-appropriate defaults.
///
/// An unknown config value (e.g. an unsupported `test_framework`) is surfaced
/// as a hard error here, before any output is written, with a message pointing
/// at the documented options for that target (§20.6.2).
fn read_scaffold_config() -> anyhow::Result<(ScaffoldConfig, Option<String>)> {
    let path = Path::new("bock.project");
    if !path.is_file() {
        return Ok((ScaffoldConfig::default(), None));
    }
    let source = std::fs::read_to_string(path)
        .map_err(|e| anyhow::anyhow!("could not read bock.project: {e}"))?;
    ScaffoldConfig::from_project_toml_with_name(&source)
        .map_err(|e| anyhow::anyhow!("invalid project-mode configuration: {e}"))
}

/// Run the §17.6 production validation step.
///
/// Reads the build manifest and exits with the spec-mandated error if
/// any entry is unpinned. Called before the frontend so users see the
/// actionable message without waiting for a full compile.
fn run_production_gate(project_root: &Path) -> anyhow::Result<()> {
    let writer = bock_ai::ManifestWriter::new(project_root);
    let decisions = writer
        .read_build()
        .map_err(|e| anyhow::anyhow!("could not read build manifest: {e}"))?;
    let report = bock_ai::validate_production(&decisions);
    if !report.is_empty() {
        eprint!("{}", report.render_error());
        process::exit(1);
    }
    Ok(())
}

/// Walk every JSON file under `.bock/decisions/build/`, flipping any
/// unpinned decision's `pinned` flag to `true` with pin metadata.
///
/// Returns the number of decisions newly pinned. Returns `Ok(0)` when
/// the tree is missing — a fresh project has nothing to pin.
fn pin_all_build_decisions(project_root: &Path) -> anyhow::Result<usize> {
    let build_root = project_root.join(".bock").join("decisions").join("build");
    if !build_root.exists() {
        return Ok(0);
    }

    let mut files: Vec<PathBuf> = Vec::new();
    collect_json_files(&build_root, &mut files)?;

    let who = pinned_by();
    let now = chrono::Utc::now();
    let mut total_pinned = 0usize;

    for file in files {
        let bytes = std::fs::read(&file)
            .map_err(|e| anyhow::anyhow!("could not read {}: {e}", file.display()))?;
        let mut entries: Vec<bock_ai::Decision> = serde_json::from_slice(&bytes)
            .map_err(|e| anyhow::anyhow!("could not parse {}: {e}", file.display()))?;
        let mut changed = false;
        for entry in entries.iter_mut() {
            if entry.pinned {
                continue;
            }
            entry.pinned = true;
            entry.pin_reason = Some(format!("bulk-pinned via `bock build --pin-all` by {who}"));
            entry.pinned_at = Some(now);
            entry.pinned_by = Some(who.clone());
            changed = true;
            total_pinned += 1;
        }
        if changed {
            let pretty = serde_json::to_vec_pretty(&entries)
                .map_err(|e| anyhow::anyhow!("could not serialize {}: {e}", file.display()))?;
            std::fs::write(&file, pretty)
                .map_err(|e| anyhow::anyhow!("could not write {}: {e}", file.display()))?;
        }
    }

    Ok(total_pinned)
}

fn collect_json_files(root: &Path, out: &mut Vec<PathBuf>) -> anyhow::Result<()> {
    for entry in std::fs::read_dir(root)? {
        let entry = entry?;
        let path = entry.path();
        let file_type = entry.file_type()?;
        if file_type.is_dir() {
            collect_json_files(&path, out)?;
        } else if path.extension().and_then(|e| e.to_str()) == Some("json") {
            out.push(path);
        }
    }
    Ok(())
}

fn pinned_by() -> String {
    std::env::var("USER")
        .or_else(|_| std::env::var("USERNAME"))
        .unwrap_or_else(|_| "unknown".into())
}

/// A successfully parsed source file, ready for compilation.
struct ParsedFile {
    path: PathBuf,
    filename: String,
    file_id: bock_errors::FileId,
    module: bock_ast::Module,
    /// Whether this is an embedded core-stdlib source (prepended by the loader)
    /// rather than a user file. Stdlib modules compile and emit like any other,
    /// but their non-error diagnostics are not surfaced to the user.
    is_stdlib: bool,
}

/// Lex and parse a single file, adding it to the shared [`SourceMap`].
///
/// Returns `Err(())` if lexing or parsing produced errors (already printed).
fn parse_file(path: &Path, source_map: &mut SourceMap) -> Result<ParsedFile, ()> {
    let content = match std::fs::read_to_string(path) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("error: {}: {e}", path.display());
            return Err(());
        }
    };

    let filename = path.display().to_string();
    let file_id = source_map.add_file(path.to_path_buf(), content);
    let source_file = source_map.get_file(file_id);

    let mut diags: Vec<Diagnostic> = Vec::new();

    // Lex
    let mut lexer = Lexer::new(source_file);
    let tokens = lexer.tokenize();
    collect_diagnostics(&mut diags, lexer.diagnostics());

    if has_errors(&diags) {
        print_diagnostics(&diags, &filename, &source_file.content);
        return Err(());
    }

    // Parse
    let mut parser = Parser::new(tokens, source_file);
    let module = parser.parse_module();
    collect_diagnostics(&mut diags, parser.diagnostics());

    if has_errors(&diags) {
        print_diagnostics(&diags, &filename, &source_file.content);
        return Err(());
    }

    Ok(ParsedFile {
        path: path.to_path_buf(),
        filename,
        file_id,
        module,
        is_stdlib: false,
    })
}

/// Lex and parse an embedded core-stdlib source into a [`ParsedFile`].
///
/// Mirrors [`parse_file`] but takes the source text directly (the embedded
/// stdlib is compiled into the binary, not read from disk) and registers it in
/// the shared [`SourceMap`] under its logical (repo-relative) path.
fn parse_stdlib_source(
    src: &crate::stdlib::StdlibSource,
    source_map: &mut SourceMap,
) -> Result<ParsedFile, ()> {
    let filename = src.logical_path.display().to_string();
    let file_id = source_map.add_file(src.logical_path.clone(), src.source.clone());
    let source_file = source_map.get_file(file_id);

    let mut diags: Vec<Diagnostic> = Vec::new();

    let mut lexer = Lexer::new(source_file);
    let tokens = lexer.tokenize();
    collect_diagnostics(&mut diags, lexer.diagnostics());

    if has_errors(&diags) {
        print_diagnostics(&diags, &filename, &source_file.content);
        return Err(());
    }

    let mut parser = Parser::new(tokens, source_file);
    let module = parser.parse_module();
    collect_diagnostics(&mut diags, parser.diagnostics());

    if has_errors(&diags) {
        print_diagnostics(&diags, &filename, &source_file.content);
        return Err(());
    }

    Ok(ParsedFile {
        path: src.logical_path.clone(),
        filename,
        file_id,
        module,
        is_stdlib: true,
    })
}

/// Run the frontend pipeline on a pre-parsed module with cross-file registry.
///
/// Resolve → lower → type-check → analysis passes.
/// Returns the AIR module and the type checker (needed for export collection).
fn compile_frontend_with_registry(
    module: &bock_ast::Module,
    filename: &str,
    source_file: &bock_source::SourceFile,
    registry: &ModuleRegistry,
    strictness: Strictness,
    is_stdlib: bool,
) -> Result<(bock_types::AIRModule, TypeChecker), ()> {
    // Embedded stdlib modules are always compiled at development strictness,
    // regardless of the user's `--strict`/`--release`: the user's strictness
    // governs their code, not trusted internal stdlib sources. This keeps
    // stdlib completeness gaps as warnings (suppressed below for stdlib) rather
    // than errors that would fail a `--strict` build on unauthored code.
    let strictness = if is_stdlib {
        Strictness::Development
    } else {
        strictness
    };

    let mut all_diagnostics: Vec<Diagnostic> = Vec::new();

    // Name resolution (with registry for cross-file imports)
    let mut symbols = SymbolTable::new();
    register_builtins(&mut symbols);
    let resolve_diags = resolve_names_with_registry(module, &mut symbols, registry);
    collect_diagnostics(&mut all_diagnostics, &resolve_diags);

    if has_errors(&all_diagnostics) {
        print_diagnostics(&all_diagnostics, filename, &source_file.content);
        return Err(());
    }

    // Lower to S-AIR
    let id_gen = NodeIdGen::new();
    let mut air_module = lower_module(module, &id_gen, &symbols);

    // Type check (T-AIR)
    let mut checker = TypeChecker::new();
    register_type_builtins(&mut checker);
    seed_prelude(&mut checker, registry);
    seed_imports(&mut checker, &module.imports, registry);
    checker.check_module(&mut air_module);
    collect_diagnostics(&mut all_diagnostics, &checker.diags);

    if has_errors(&all_diagnostics) {
        print_diagnostics(&all_diagnostics, filename, &source_file.content);
        return Err(());
    }

    // Analysis passes (ownership, effects, capabilities)
    let ownership_diags = bock_types::analyze_ownership(&air_module);
    collect_diagnostics(&mut all_diagnostics, &ownership_diags);

    let effect_diags = bock_types::track_effects(&air_module, strictness);
    collect_diagnostics(&mut all_diagnostics, &effect_diags);

    let capability_diags = bock_types::verify_capabilities(&air_module, strictness);
    collect_diagnostics(&mut all_diagnostics, &capability_diags);

    if has_errors(&all_diagnostics) {
        print_diagnostics(&all_diagnostics, filename, &source_file.content);
        return Err(());
    }

    // Print warnings. Stdlib modules surface only errors (compiler defects):
    // their development-mode warnings describe internal code the user did not
    // author and would otherwise be noise on every `bock build`.
    if !is_stdlib {
        let warnings: Vec<&Diagnostic> = all_diagnostics
            .iter()
            .filter(|d| d.severity != Severity::Error)
            .collect();
        if !warnings.is_empty() {
            let to_render: Vec<Diagnostic> = warnings.into_iter().cloned().collect();
            print_diagnostics(&to_render, filename, &source_file.content);
        }
    }

    Ok((air_module, checker))
}

/// Fill in `sources` + `src_line`/`src_col` on a codegen-produced source map.
/// Uses the compilation's parsed files and their contents from `source_map`.
fn populate_source_map(
    sm: &mut bock_codegen::SourceMap,
    parsed: &[ParsedFile],
    source_map: &SourceMap,
) {
    // Determine the highest file id referenced by any mapping so we only
    // include relevant sources.
    let max_file_id = sm.mappings.iter().map(|m| m.src_file_id).max().unwrap_or(0);

    // Build a map from FileId → (path, content) by iterating known parsed
    // files. Each parsed file's `file_id` gives us a stable index.
    let mut contents: Vec<Option<(String, String)>> =
        vec![None; (max_file_id as usize).saturating_add(1)];
    for pf in parsed {
        let file = source_map.get_file(pf.file_id);
        let idx = pf.file_id.0 as usize;
        if idx < contents.len() {
            contents[idx] = Some((file.path.display().to_string(), file.content.clone()));
        }
    }

    // Attach sources in file-id order; absent slots become placeholder entries.
    sm.sources = contents
        .iter()
        .enumerate()
        .map(|(i, opt)| match opt {
            Some((path, content)) => SourceInfo {
                path: path.clone(),
                content: Some(content.clone()),
            },
            None => SourceInfo {
                path: format!("<unknown-{i}>"),
                content: None,
            },
        })
        .collect();

    // Resolve each mapping's (src_line, src_col) from its byte offset.
    let content_refs: Vec<&str> = contents
        .iter()
        .map(|o| o.as_ref().map(|(_, c)| c.as_str()).unwrap_or(""))
        .collect();
    sm.resolve_positions(&content_refs);
}

/// Create a code generator for the given target ID.
fn create_generator(target: &str) -> anyhow::Result<Box<dyn CodeGenerator>> {
    match target {
        "js" => Ok(Box::new(JsGenerator::new())),
        "ts" => Ok(Box::new(TsGenerator::new())),
        "python" => Ok(Box::new(PyGenerator::new())),
        "rust" => Ok(Box::new(RsGenerator::new())),
        "go" => Ok(Box::new(GoGenerator::new())),
        _ => {
            anyhow::bail!(
                "unknown target '{target}'. Valid targets: {}",
                KNOWN_TARGETS.join(", ")
            );
        }
    }
}

/// Whether `path` is one of the transpiled-test files (S7) — `bock.test.js`,
/// `bock.test.ts`, or `test_bock.py`. These are exercised by the target's test
/// framework (`npm test` / `pytest`), not by the build-time per-file toolchain
/// validation that targets the runtime source tree.
fn is_transpiled_test_file(path: &Path) -> bool {
    matches!(
        path.file_name().and_then(|s| s.to_str()),
        Some("bock.test.js" | "bock.test.ts" | "test_bock.py")
    )
}

/// Get the file extension for a target's generated files.
///
/// Single source of truth lives on each [`bock_codegen::TargetProfile`] —
/// this helper just delegates so call sites don't duplicate the table.
fn target_file_extension(target: &str) -> String {
    bock_codegen::TargetProfile::from_id(target)
        .map(|p| p.conventions.file_extension)
        .unwrap_or_else(|| "txt".to_string())
}

/// Find all files with a given extension in a directory (recursive).
fn find_files_with_extension(dir: &Path, ext: &str) -> anyhow::Result<Vec<PathBuf>> {
    let mut result = Vec::new();
    if !dir.is_dir() {
        return Ok(result);
    }
    let entries = std::fs::read_dir(dir)?;
    for entry in entries {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            result.extend(find_files_with_extension(&path, ext)?);
        } else if path.extension().and_then(|e| e.to_str()) == Some(ext) {
            result.push(path);
        }
    }
    result.sort();
    Ok(result)
}

/// Discover `.bock` files recursively from the given directory.
fn discover_bock_files_recursive(dir: &str) -> anyhow::Result<Vec<PathBuf>> {
    let mut files = Vec::new();
    walk_dir_recursive(Path::new(dir), &mut files)?;
    files.sort();
    Ok(files)
}

/// Recursively walk a directory collecting `.bock` files.
fn walk_dir_recursive(dir: &Path, files: &mut Vec<PathBuf>) -> anyhow::Result<()> {
    let entries = std::fs::read_dir(dir)
        .map_err(|e| anyhow::anyhow!("could not read directory '{}': {e}", dir.display()))?;

    for entry in entries {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            // Skip build output directories and hidden directories
            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                if name.starts_with('.')
                    || name == "build"
                    || name == "target"
                    || name == "node_modules"
                    || name == "test"
                    || name == "tests"
                {
                    continue;
                }
            }
            walk_dir_recursive(&path, files)?;
        } else if path.is_file() {
            if let Some(ext) = path.extension() {
                if ext == "bock" {
                    files.push(path);
                }
            }
        }
    }

    Ok(())
}

/// Collect diagnostics from a bag into the accumulator.
fn collect_diagnostics(acc: &mut Vec<Diagnostic>, bag: &DiagnosticBag) {
    for diag in bag.iter() {
        acc.push(diag.clone());
    }
}

/// Check if any diagnostic in the list is an error.
fn has_errors(diagnostics: &[Diagnostic]) -> bool {
    diagnostics.iter().any(|d| d.severity == Severity::Error)
}

/// Print diagnostics with source context.
fn print_diagnostics(diagnostics: &[Diagnostic], filename: &str, source: &str) {
    let rendered = bock_errors::render(diagnostics, filename, source);
    eprint!("{rendered}");
}

/// Register builtin function types in the type checker.
fn register_type_builtins(checker: &mut TypeChecker) {
    use bock_types::{FnType, PrimitiveType, Type};
    let io_fn_ty = Type::Function(FnType {
        params: vec![Type::Primitive(PrimitiveType::String)],
        ret: Box::new(Type::Primitive(PrimitiveType::Void)),
        effects: vec![],
    });
    for name in ["print", "println", "debug"] {
        checker.env.define(name, io_fn_ty.clone());
    }

    // Duration, Instant, Channel: named prelude types. Type::Error accepts
    // any method or associated-function access without friction; runtime
    // dispatch via qualified globals handles correctness.
    for name in ["Duration", "Instant", "Channel"] {
        checker.env.define(name, Type::Error);
    }

    // sleep: (Duration) -> Void with Clock (effect elided at this layer)
    let sleep_fn_ty = Type::Function(FnType {
        params: vec![Type::Error],
        ret: Box::new(Type::Primitive(PrimitiveType::Void)),
        effects: vec![],
    });
    checker.env.define("sleep", sleep_fn_ty);

    // spawn: (Future[T]) -> Future[T]
    let spawn_fn_ty = Type::Function(FnType {
        params: vec![Type::Error],
        ret: Box::new(Type::Error),
        effects: vec![],
    });
    checker.env.define("spawn", spawn_fn_ty);

    // assert: (Bool, String?) -> Void
    let assert_ty = Type::Function(FnType {
        params: vec![Type::Primitive(PrimitiveType::Bool)],
        ret: Box::new(Type::Primitive(PrimitiveType::Void)),
        effects: vec![],
    });
    checker.env.define("assert", assert_ty);

    // expect: (Any) -> Expectation (test assertion builtin)
    let expect_fn_ty = Type::Function(FnType {
        params: vec![Type::Error],
        ret: Box::new(Type::Error),
        effects: vec![],
    });
    checker.env.define("expect", expect_fn_ty);

    // todo, unreachable: () -> Never (diverging builtins)
    let never_fn_ty = Type::Function(FnType {
        params: vec![],
        ret: Box::new(Type::Primitive(PrimitiveType::Never)),
        effects: vec![],
    });
    for name in ["todo", "unreachable"] {
        checker.env.define(name, never_fn_ty.clone());
    }

    // Ok, Err: (T) -> Result[T, E] — modeled as generic-like via Error
    let constructor_fn_ty = Type::Function(FnType {
        params: vec![Type::Error],
        ret: Box::new(Type::Error),
        effects: vec![],
    });
    for name in ["Ok", "Err"] {
        checker.env.define(name, constructor_fn_ty.clone());
    }

    // Some: (T) -> Optional[T]
    checker.env.define("Some", constructor_fn_ty);

    // None: Optional[T] (a value, not a function)
    checker.env.define("None", Type::Error);
}

/// Register interpreter builtin globals in the symbol table for name resolution.
fn register_builtins(symbols: &mut SymbolTable) {
    let builtin_span = Span {
        file: FileId(0),
        start: 0,
        end: 0,
    };
    let builtins = [
        ("print", u32::MAX - 1),
        ("println", u32::MAX - 2),
        ("debug", u32::MAX - 3),
        ("Ok", u32::MAX - 10),
        ("Err", u32::MAX - 11),
        ("Some", u32::MAX - 12),
        ("None", u32::MAX - 13),
    ];
    for (name, def_id) in builtins {
        symbols.define(
            name.to_string(),
            Binding {
                name: name.to_string(),
                resolved: ResolvedName {
                    def_id,
                    kind: NameKind::Function,
                },
                visibility: Visibility::Public,
                span: builtin_span,
                used: true,
                is_import: false,
            },
        );
    }
}

/// Parse a target list, validating each target ID.
pub fn parse_targets(target: Option<String>, all_targets: bool) -> anyhow::Result<Vec<String>> {
    if all_targets {
        return Ok(KNOWN_TARGETS.iter().map(|s| (*s).to_string()).collect());
    }

    match target {
        Some(t) => {
            if !KNOWN_TARGETS.contains(&t.as_str()) {
                anyhow::bail!(
                    "unknown target '{t}'. Valid targets: {}",
                    KNOWN_TARGETS.join(", ")
                );
            }
            Ok(vec![t])
        }
        None => {
            // Default to js
            Ok(vec!["js".to_string()])
        }
    }
}