Repository navigation
Expand file tree
/
Copy pathbuild.rs
More file actions
1202 lines (1142 loc) · 46.7 KB
/
Copy pathbuild.rs
File metadata and controls
1202 lines (1142 loc) · 46.7 KB
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
use std::collections::BTreeSet;
use std::env;
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{self, Command};
use toml::Value;
#[derive(Clone, Copy, Eq, PartialEq)]
enum ValidationMode {
ActivePathOverride,
StrictOptIn,
}
#[derive(Clone, Copy)]
struct DependencyContract {
label: &'static str,
dep_table: &'static str,
dep_key: &'static str,
crate_package_name: &'static str,
manifest_package_field: Option<&'static str>,
expected_git: &'static str,
expected_rev: &'static str,
expected_version: &'static str,
expected_features: &'static [&'static str],
expected_default_features: Option<bool>,
repo_rel: &'static str,
manifest_rel: &'static str,
patch_url: Option<&'static str>,
patch_key: Option<&'static str>,
mode: ValidationMode,
}
struct GitState {
head: String,
dirty: bool,
}
const STRICT_PATH_DEP_FEATURE: &str = "strict-path-dep-validation";
const STRICT_PATH_DEP_ENV: &str = "CASS_STRICT_PATH_DEP_VALIDATION";
const CONTRACTS: &[DependencyContract] = &[
DependencyContract {
label: "frankensqlite facade",
dep_table: "dependencies",
dep_key: "frankensqlite",
crate_package_name: "fsqlite",
manifest_package_field: Some("fsqlite"),
// Exact upstream source pin (established with the fsqlite 0.2.1
// migration, bead bo000; now at 0.4.9. 0.3.15 was evaluated on
// 2026-09-02 (bead gh382-fsqlite-pin) and NOT adopted: cass's own
// writable open still looped on a large archive with a large WAL
// (reclaim sweep x per-page WAL rescan, cass GH #382 / bead g3zyo).
// 0.3.16 carries that fix — frankensqlite 8d012706a, index the
// appended WAL tail once per stable tail instead of rescanning it
// per page — plus the GH#405 FTS5 undo log (savepoints no longer
// clone the whole table), the GH#406 content-backed INSERT as an
// incremental segment append, lazy contentless FTS5 on the ordinary
// open path, prefix-BM25 scoring parity, and the 0.3.15 line (FTS5
// 'optimize', origin-poison self-heal, macOS clippy gate). Adopted
// 2026-09-04 by owner instruction. The 0.3.13 semantics CASS relies
// on (asupersync 0.4.3 runtime migration, GH#333/GH#334, the
// cass#393 namespace-sidecar repair, the GH#438 Windows sidecar-less
// read-only close, integrity-check through read-only guards, and
// the cass#434 autoindex-vanish fixes) all carry forward.
// 0.3.17 adds incremental WAL-tail folding, reserved lock-byte and
// freelist repair (GH#410), FTS metadata/visibility fixes (GH#408),
// and prepared-read schema-retry cleanup. 0.3.18 adds parameterized
// rowid seeks (GH#415/cass#382), read-only WAL preservation, reader
// registration error propagation and I/O lifetime fixes. The 0.4.1
// release preserves the facade API and requires asupersync 0.5.0.
// It includes the GH#462 reserved-page WAL repair and GH#411 shared
// WAL-index publication fixes; CASS archive acceptance is separate.
// 0.4.2 adds explicit derived WAL-index recovery for read-only
// connections, including the dedicated async owner (GH#477).
// 0.4.6 stops a live B-tree page from being freed and granted again
// across a WAL generation (bd-b5vmw) and fixes the lost-index-entry
// race (bd-11sz4). 0.4.7 keeps index entries whole past register
// 65,535 in large multi-row INSERTs (bd-2eebi), fixes the serialized
// DDL index race (bd-4iaoi), carries the GH#503 legacy FTS5
// shadow-autoindex repair open (ENGINE_REPAIRS_MISSING_FTS5_SHADOW_
// AUTOINDEX is true), bounds the published-page plane (5s1la) and
// stops the first sqlite_master query reading the whole file (k2k20).
// 0.4.7 also slowed strict read-only opens on a stale WAL index to
// ~30 s, so CASS skipped it; 0.4.9 (replacing the withdrawn 0.4.8)
// refuses that index promptly again (48c6cf6b2) and lets the first
// write after stock SQLite's empty, unindexed WAL index establish the
// WAL generation instead of failing BusyRecovery forever (GH#443,
// cass#509).
// fsqlite resolves from crates.io at the exact version below.
expected_git: "",
expected_rev: "",
expected_version: "0.4.9",
// `async-api` exposes frankensqlite::AsyncConnection, which
// src/search/query.rs uses (as SearchSqliteConnection) for the
// no-hit alternate-agent suggestions without a full storage open.
expected_features: &["fts5", "async-api"],
expected_default_features: None,
repo_rel: "../frankensqlite",
manifest_rel: "crates/fsqlite/Cargo.toml",
patch_url: None,
patch_key: None,
mode: ValidationMode::StrictOptIn,
},
DependencyContract {
label: "frankensqlite shared types (production)",
dep_table: "dependencies",
dep_key: "fsqlite-types",
crate_package_name: "fsqlite-types",
manifest_package_field: Some("fsqlite-types"),
// The 0.4.9 release publishes the entire family at one version.
expected_git: "",
expected_rev: "",
expected_version: "0.4.9",
expected_features: &[],
expected_default_features: None,
repo_rel: "../frankensqlite",
manifest_rel: "crates/fsqlite-types/Cargo.toml",
patch_url: None,
patch_key: None,
mode: ValidationMode::StrictOptIn,
},
DependencyContract {
label: "frankensqlite shared types (test)",
dep_table: "dev-dependencies",
dep_key: "fsqlite-types",
crate_package_name: "fsqlite-types",
manifest_package_field: Some("fsqlite-types"),
// Match the production shared types from the published family.
expected_git: "",
expected_rev: "",
expected_version: "0.4.9",
expected_features: &[],
expected_default_features: None,
repo_rel: "../frankensqlite",
manifest_rel: "crates/fsqlite-types/Cargo.toml",
patch_url: None,
patch_key: None,
mode: ValidationMode::StrictOptIn,
},
DependencyContract {
label: "franken_agent_detection",
dep_table: "dependencies",
dep_key: "franken-agent-detection",
crate_package_name: "franken-agent-detection",
manifest_package_field: None,
// GH#416: registry pin. crates.io 0.2.3 (2026-09-07) probes the
// Antigravity IDE store as well as the agy CLI store (cass#454),
// honors CLAUDE_CONFIG_DIR/XDG_CONFIG_HOME for Claude Code (cass#448),
// and carries the Codex token-usage, Claude tool-result, Cursor/OpenCode
// dedupe and Shelley canonical-discovery fixes on top of 0.2.2's
// (upstream tag f19e7e0) cursor/antigravity/grok scan-root scoping and
// aider/copilot-cli/amp/opencode/clawdbot/muse session-loss fixes.
// The Shelley connector, FAD#22 source-boundary seam, and the
// chatgpt/omp injection seams are published in 0.2.3.
// 0.2.4 (2026-09-10) restores the legacy Copilot CLI
// `history.json` `workspacePath` alias that 0.2.3 dropped when CLI
// parsing moved out of copilot.rs -- those sessions were coming back
// with no workspace at all -- and reads Cursor Agent workspaces from
// the `.workspace-trusted` sidecar instead of guessing them from the
// hyphenated project slug (cass#459), which no decoder can do
// correctly because `parent-project/my-app` and `parent/project/my/app`
// encode identically.
// The 0.3.0 candidate moves SQLite connectors onto the same 0.4.x
// engine and 0.5.x runtime as CASS; publication must precede adoption.
// 0.3.1 (2026-09-25) indexes Claude Code prompts typed mid-turn
// (queued_command attachments, cass#500), honors CASS_EXCLUDE_PATHS in
// the Codex and Pi-family connectors (cass#486), and caps session
// reads while reading. 0.3.2 (2026-09-26) lets CASS set that Codex
// rollout read cap, which 0.3.1 fixed at 100 MiB regardless of
// CASS_CODEX_MAX_SOURCE_BYTES. 0.3.3 (2026-09-28) indexes OpenCode 2.x
// sessions from session_v2/session_message (cass#504) and decodes
// OpenClaw's zstd-compressed transcript events (FAD#25). 0.3.4
// (2026-10-05) indexes native Codebuff transcripts, whose timestamps
// are a locale time of day, taking each instant from the message ID
// (cass#511); 0.3.5 keeps indexing a Codebuff store's other chats when
// one transcript does not parse, and names that transcript. 0.3.6
// (codex-zstd) reads Codex rollouts compressed to .jsonl.zst (cass#513).
// 0.3.7 adds the pi_durable connector (FAD#28; its SQLite stores need
// pi-durable) and pi_agent_rust SQLite sessions (pi-sqlite). 0.3.8
// resolves `..`, relative and symlink-alias CASS_EXCLUDE_PATHS
// entries for the Claude, Pi and Codex readers (cass 0f1k0).
// crates.io refuses git dependencies, hence version-only.
expected_git: "",
expected_rev: "",
expected_version: "0.3.8",
// Match the always-on SQLite transcript readers in Cargo.toml. Their
// features are required even for --no-default-features CASS builds.
expected_features: &[
"chatgpt",
"codebuff",
"codex-zstd",
"connectors",
"copilot-vscdb",
"crush",
"cursor",
"devin",
"goose",
"grok-bot",
"hermes",
"openclaw-sqlite",
"opencode",
"pi-durable",
"pi-sqlite",
"shelley",
],
expected_default_features: None,
repo_rel: "../franken_agent_detection",
manifest_rel: "Cargo.toml",
patch_url: Some("https://github.com/Dicklesworthstone/franken_agent_detection"),
patch_key: Some("franken-agent-detection"),
mode: ValidationMode::StrictOptIn,
},
DependencyContract {
label: "asupersync",
dep_table: "dependencies",
dep_key: "asupersync",
crate_package_name: "asupersync",
manifest_package_field: None,
// crates.io-only exact pin: every source (direct dep, frankensqlite
// transitive, frankensearch transitive) resolves to a single published
// release. SQLite 0.4.x, FAD 0.3.0 and FrankenSearch 0.7.1 use
// asupersync 0.5.x native contexts; mixing the old runtime would
// split caller context, cancellation and capability identity.
// Empty `expected_git` signals `validate_manifest_dependency_spec`
// to skip git/rev checks.
expected_git: "",
expected_rev: "",
expected_version: "0.5.0",
expected_features: &["test-internals", "tls-native-roots"],
expected_default_features: None,
repo_rel: "../asupersync",
manifest_rel: "Cargo.toml",
patch_url: None,
patch_key: None,
mode: ValidationMode::StrictOptIn,
},
DependencyContract {
label: "frankensearch",
dep_table: "dependencies",
dep_key: "frankensearch",
crate_package_name: "frankensearch",
manifest_package_field: None,
// Registry release on asupersync 0.5. Preserve explicit native
// MiniLM, Quill and cass-compat lexical behavior; a manifest pin
// alone is not runtime acceptance.
// Empty `expected_git` signals `validate_manifest_dependency_spec`
// to skip git/rev checks.
expected_git: "",
expected_rev: "",
expected_version: "0.7.1",
// cass #308: the ort/ONNX `fastembed` stack was removed; semantic
// embedding + reranking are now pure-Rust via frankensearch's `native`
// feature, kept always-on here (no AVX/ONNX static-init hazard, so no
// separate `-baseline` build is needed). Bead tg5o9 retired the vacuous
// cass `semantic` feature; semantic readiness is now determined solely
// by runtime model/vector assets.
// `quill` added for the CASS->Quill lexical flip: it links the native
// Quill engine alongside the Tantivy incumbent so the two can be
// compared before Tantivy is dropped. `cass-compat` leaves with
// Tantivy once the flip completes.
expected_features: &["ann", "cass-compat", "hash", "native", "quill"],
expected_default_features: Some(false),
repo_rel: "../frankensearch",
manifest_rel: "frankensearch/Cargo.toml",
patch_url: None,
patch_key: None,
mode: ValidationMode::StrictOptIn,
},
DependencyContract {
label: "ftui facade",
dep_table: "dependencies",
dep_key: "ftui",
crate_package_name: "ftui",
manifest_package_field: None,
expected_git: "",
expected_rev: "",
expected_version: "0.5.0",
expected_features: &[],
expected_default_features: None,
repo_rel: "../frankentui",
manifest_rel: "crates/ftui/Cargo.toml",
patch_url: None,
patch_key: None,
mode: ValidationMode::StrictOptIn,
},
DependencyContract {
label: "ftui-runtime",
dep_table: "dependencies",
dep_key: "ftui-runtime",
crate_package_name: "ftui-runtime",
manifest_package_field: None,
expected_git: "",
expected_rev: "",
expected_version: "0.5.0",
expected_features: &["crossterm-compat", "native-backend"],
expected_default_features: None,
repo_rel: "../frankentui",
manifest_rel: "crates/ftui-runtime/Cargo.toml",
patch_url: None,
patch_key: None,
mode: ValidationMode::StrictOptIn,
},
DependencyContract {
label: "ftui-tty",
dep_table: "dependencies",
dep_key: "ftui-tty",
crate_package_name: "ftui-tty",
manifest_package_field: None,
expected_git: "",
expected_rev: "",
expected_version: "0.5.0",
expected_features: &[],
expected_default_features: None,
repo_rel: "../frankentui",
manifest_rel: "crates/ftui-tty/Cargo.toml",
patch_url: None,
patch_key: None,
mode: ValidationMode::StrictOptIn,
},
DependencyContract {
label: "ftui-extras",
dep_table: "dependencies",
dep_key: "ftui-extras",
crate_package_name: "ftui-extras",
manifest_package_field: None,
expected_git: "",
expected_rev: "",
expected_version: "0.5.0",
expected_features: &[
"canvas",
"charts",
"clipboard",
"clipboard-fallback",
"export",
"forms",
"help",
"markdown",
"syntax",
"theme",
"validation",
"visual-fx",
],
expected_default_features: Some(false),
repo_rel: "../frankentui",
manifest_rel: "crates/ftui-extras/Cargo.toml",
patch_url: None,
patch_key: None,
mode: ValidationMode::StrictOptIn,
},
DependencyContract {
label: "toon",
dep_table: "dependencies",
dep_key: "toon",
crate_package_name: "tru",
manifest_package_field: Some("tru"),
// GH#416: registry pin. crates.io 0.2.4 differs from the previously
// pinned git rev d7185c78 by exactly one TEST assertion line
// (src/decode/event_builder.rs); production sources are
// byte-identical (verified by tree diff, not the version field).
expected_git: "",
expected_rev: "",
expected_version: "0.2.4",
expected_features: &[],
expected_default_features: None,
repo_rel: "../toon_rust",
manifest_rel: "Cargo.toml",
patch_url: None,
patch_key: None,
mode: ValidationMode::StrictOptIn,
},
];
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=Cargo.toml");
println!("cargo:rerun-if-env-changed={STRICT_PATH_DEP_ENV}");
// MSVC reserves only 1 MiB for an executable's main thread by default.
// CASS's clap command graph and startup state exceed that in debug builds,
// causing even `cass --version` to abort before argument dispatch. Reserve
// virtual address space here for the actual binary; thread stacks remain
// independently bounded by their structured spawn sites.
if env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
println!("cargo:rustc-link-arg-bin=cass=/STACK:8388608");
}
let manifest_dir = match env::var("CARGO_MANIFEST_DIR") {
Ok(value) => PathBuf::from(value),
Err(err) => fatal(format!(
"CARGO_MANIFEST_DIR should be set by Cargo before running build.rs: {err}"
)),
};
let manifest_path = manifest_dir.join("Cargo.toml");
let manifest_text = match fs::read_to_string(&manifest_path) {
Ok(text) => text,
Err(err) => fatal(format!("failed to read {}: {err}", manifest_path.display())),
};
let manifest: Value = match toml::from_str(&manifest_text) {
Ok(value) => value,
Err(err) => fatal(format!(
"failed to parse {}: {err}",
manifest_path.display()
)),
};
let packaged_manifest = manifest_dir.join("Cargo.toml.orig").is_file();
validate_path_dependency_contracts(&manifest_dir, &manifest, packaged_manifest);
emit_vergen_metadata();
emit_build_commit_metadata(&manifest_dir);
emit_source_ingest_contract(&manifest_dir);
}
/// A completed source is reusable only by the parser/normalizer that read it.
/// Hash build inputs rather than Git HEAD: release tarballs have no Git metadata,
/// and two dirty builds at the same commit can contain different parser fixes.
fn emit_source_ingest_contract(manifest_dir: &Path) {
// Cargo pins registry/git source bytes, but a local path dependency can
// change its parser without changing this crate's manifest or lockfile.
// Such development builds must reparse instead of reusing an unproven
// completion. In particular, hashing only a sibling's version is unsafe.
let lock_text = fs::read_to_string(manifest_dir.join("Cargo.lock"))
.unwrap_or_else(|error| fatal(format!("cannot read ingest dependency lock: {error}")));
let lock: Value = toml::from_str(&lock_text)
.unwrap_or_else(|error| fatal(format!("cannot parse ingest dependency lock: {error}")));
let crate_name = env::var("CARGO_PKG_NAME").unwrap_or_default();
let crate_version = env::var("CARGO_PKG_VERSION").unwrap_or_default();
let packages = lock
.get("package")
.and_then(Value::as_array)
.map(Vec::as_slice)
.unwrap_or_default();
// The first package that disables reuse, named so `cass capabilities` can
// tell an operator why (GH#426): a source build with a local path override
// reparses every source on every incremental run.
let reuse_blocker = if packages.is_empty() {
Some("Cargo.lock lists no packages".to_string())
} else {
packages
.iter()
.find(|package| {
package.get("source").and_then(Value::as_str).is_none()
&& !(package.get("name").and_then(Value::as_str) == Some(crate_name.as_str())
&& package.get("version").and_then(Value::as_str)
== Some(crate_version.as_str()))
})
.map(|package| {
format!(
"{} {} has no registry or git source (local path dependency or [patch])",
package.get("name").and_then(Value::as_str).unwrap_or("?"),
package
.get("version")
.and_then(Value::as_str)
.unwrap_or("?"),
)
})
};
let pinned_dependencies = reuse_blocker.is_none();
println!("cargo:rustc-env=CASS_SOURCE_INGEST_REUSE={pinned_dependencies}");
println!(
"cargo:rustc-env=CASS_SOURCE_INGEST_REUSE_BLOCKER={}",
reuse_blocker.unwrap_or_default()
);
let mut inputs = BTreeSet::from([
PathBuf::from("Cargo.toml"),
PathBuf::from("Cargo.lock"),
PathBuf::from("build.rs"),
]);
let mut directories = vec![PathBuf::from("src")];
while let Some(directory) = directories.pop() {
println!("cargo:rerun-if-changed={}", directory.display());
let entries = fs::read_dir(manifest_dir.join(&directory))
.unwrap_or_else(|error| fatal(format!("cannot read ingest inputs: {error}")));
for entry in entries {
let entry = entry
.unwrap_or_else(|error| fatal(format!("cannot inspect ingest input: {error}")));
let path = directory.join(entry.file_name());
let kind = entry.file_type().unwrap_or_else(|error| {
fatal(format!("cannot inspect ingest input type: {error}"))
});
if kind.is_dir() {
directories.push(path);
} else {
inputs.insert(path);
}
}
}
let mut hasher = blake3::Hasher::new();
hasher.update(b"cass-source-ingest-contract-v1\0");
for input in inputs {
println!("cargo:rerun-if-changed={}", input.display());
let name = input.to_string_lossy().replace('\\', "/");
let bytes = fs::read(manifest_dir.join(&input))
.unwrap_or_else(|error| fatal(format!("cannot read ingest input {name}: {error}")));
hasher.update(&(name.len() as u64).to_le_bytes());
hasher.update(name.as_bytes());
hasher.update(&(bytes.len() as u64).to_le_bytes());
hasher.update(&bytes);
}
let features: BTreeSet<_> = env::vars()
.filter(|(name, _)| name.starts_with("CARGO_FEATURE_"))
.collect();
for (name, value) in features {
hasher.update(name.as_bytes());
hasher.update(b"=");
hasher.update(value.as_bytes());
hasher.update(b"\0");
}
println!(
"cargo:rustc-env=CASS_SOURCE_INGEST_CONTRACT={}",
hasher.finalize()
);
}
/// Embed the build commit at compile time (GH #399).
///
/// A binary built from `main` and the binary from the nearest tag are
/// otherwise indistinguishable at runtime: bare `version` in clap prints only
/// `CARGO_PKG_VERSION`. Resolve the commit HERE, against the crate's own
/// checkout (`CARGO_MANIFEST_DIR`), never at runtime against the process CWD
/// (ubs#79 is the failure mode to avoid: a runtime `git rev-parse` reports
/// the *scanned* repository's commit as the build SHA).
///
/// Emits:
/// - `VERGEN_GIT_SHA` — full commit hash (name kept because doctor run
/// journaling already reads `option_env!("VERGEN_GIT_SHA")`); only when
/// resolvable.
/// - `CASS_BUILD_COMMIT` — short (12-char) hash with a `-dirty` suffix when
/// the worktree has uncommitted tracked changes; only when resolvable.
/// - `CASS_BUILD_COMMIT_DATE` — commit date (`YYYY-MM-DD`); only when
/// resolvable.
/// - `CASS_VERSION_FULL` — ALWAYS emitted: `<semver> (<short-sha> <date>)`
/// when git metadata is available, plain `<semver>` otherwise (crates.io /
/// tarball builds have no `.git`).
fn emit_build_commit_metadata(manifest_dir: &Path) {
let crate_version = env::var("CARGO_PKG_VERSION").unwrap_or_default();
// Rebuild when HEAD moves or the checked-out branch's ref advances, so a
// cached build script cannot pin a stale SHA into a fresh binary.
let git_dir = manifest_dir.join(".git");
if git_dir.exists() {
let head = git_dir.join("HEAD");
if head.exists() {
println!("cargo:rerun-if-changed={}", head.display());
}
if let Ok(head_contents) = fs::read_to_string(&head)
&& let Some(reference) = head_contents.trim().strip_prefix("ref: ")
{
let ref_path = git_dir.join(reference);
if ref_path.exists() {
println!("cargo:rerun-if-changed={}", ref_path.display());
}
}
}
let state = git_state(manifest_dir).ok();
let commit_date = git_output(manifest_dir, &["show", "-s", "--format=%cs", "HEAD"])
.map(|s| s.trim().to_string())
.ok();
let full_version = match &state {
Some(state) if state.head.len() >= 12 => {
let mut short = state.head[..12].to_string();
if state.dirty {
short.push_str("-dirty");
}
println!("cargo:rustc-env=VERGEN_GIT_SHA={}", state.head);
println!("cargo:rustc-env=CASS_BUILD_COMMIT={short}");
if let Some(date) = &commit_date {
println!("cargo:rustc-env=CASS_BUILD_COMMIT_DATE={date}");
format!("{crate_version} ({short} {date})")
} else {
format!("{crate_version} ({short})")
}
}
_ => crate_version.clone(),
};
println!("cargo:rustc-env=CASS_VERSION_FULL={full_version}");
}
fn validate_path_dependency_contracts(
manifest_dir: &Path,
manifest: &Value,
packaged_manifest: bool,
) {
let strict_enabled = strict_path_dep_validation_enabled();
validate_fsqlite_source_pin(manifest_dir, manifest, packaged_manifest);
for contract in CONTRACTS {
validate_manifest_dependency_spec(manifest, contract, packaged_manifest);
if contract.mode == ValidationMode::ActivePathOverride {
validate_patch_path(manifest, contract);
}
if contract.mode == ValidationMode::ActivePathOverride || strict_enabled {
validate_local_contract(manifest_dir, contract, strict_enabled);
}
}
}
fn validate_fsqlite_source_pin(manifest_dir: &Path, manifest: &Value, packaged_manifest: bool) {
// The fsqlite engine family must resolve exclusively from crates.io at
// the uniform published 0.4.9 version, including the shared types.
// One source per package remains load-bearing for read-only integrity.
const EXPECTED_REGISTRY_SOURCE: &str = "registry+https://github.com/rust-lang/crates.io-index";
// 1. With the family on crates.io (e926644f), a `[patch]` table is no
// longer required — but if one exists, it must not silently redirect
// any fsqlite family member back to a shadow source.
if !packaged_manifest
&& let Some(patch_tables) = manifest.get("patch")
&& let Some(crates_io) = patch_tables.get("crates-io").and_then(Value::as_table)
{
for dependency in crates_io.keys() {
if dependency == "fsqlite" || dependency.starts_with("fsqlite-") {
fatal(format!(
"dependency source contract violation for {dependency}: the fsqlite \
family resolves from the pinned crates.io package versions; a \
[patch.crates-io] redirect would reintroduce an unreviewed shadow \
source"
));
}
}
}
// 2. Lockfile convergence: every resolved fsqlite-family package must be
// its pinned registry version, with exactly one version per crate.
// Cargo resolves the lockfile before running build scripts, so the
// lockfile is authoritative here. Packaged manifests (`cargo package`
// verification builds) re-resolve into a fresh lockfile that inherits
// these same requirements from the manifest pin.
let lock_path = manifest_dir.join("Cargo.lock");
println!("cargo:rerun-if-changed={}", lock_path.display());
let lock_text = match fs::read_to_string(&lock_path) {
Ok(text) => text,
Err(err) => {
if packaged_manifest {
return;
}
fatal(format!(
"dependency source contract: failed to read {}: {err}",
lock_path.display()
))
}
};
let lock: Value = match toml::from_str(&lock_text) {
Ok(value) => value,
Err(err) => fatal(format!(
"dependency source contract: failed to parse {}: {err}",
lock_path.display()
)),
};
let packages = lock
.get("package")
.and_then(Value::as_array)
.unwrap_or_else(|| {
fatal("dependency source contract: Cargo.lock has no [[package]] entries")
});
// Collect EVERY off-pin family member before failing, and print the
// exact remediation for each (GH#417): reporting only the first
// mismatch made a multi-member drift a whack-a-mole loop, and only 2 of
// the ~20 family members are direct dependencies, so a bare
// `cargo update` can float any transitive member off-pin.
let mut seen: BTreeSet<&str> = BTreeSet::new();
let mut violations: Vec<String> = Vec::new();
let mut remediations: Vec<String> = Vec::new();
for package in packages {
let name = package.get("name").and_then(Value::as_str).unwrap_or("");
if !(name == "fsqlite" || name.starts_with("fsqlite-")) {
continue;
}
let expected_version = "0.4.9";
let version = package.get("version").and_then(Value::as_str).unwrap_or("");
if !seen.insert(name) {
violations.push(format!(
"`{name}` resolves more than once; the fsqlite family must converge on \
a single registry version per package"
));
}
if version != expected_version {
violations.push(format!(
"`{name}` resolves at `{version}`, expected `{expected_version}`"
));
remediations.push(format!(
"cargo update -p {name}@{version} --precise {expected_version}"
));
}
let source = package.get("source").and_then(Value::as_str).unwrap_or("");
if source != EXPECTED_REGISTRY_SOURCE {
violations.push(format!(
"`{name}` resolves from `{source}`, expected the crates.io registry \
(`{EXPECTED_REGISTRY_SOURCE}`)"
));
}
}
if !seen.contains("fsqlite") {
violations.push(
"Cargo.lock does not resolve `fsqlite`; the engine dependency is missing".to_owned(),
);
}
if !violations.is_empty() {
let mut message = format!(
"dependency source contract violation: {} fsqlite-family problem(s) in Cargo.lock:\n",
violations.len()
);
for violation in &violations {
message.push_str(" - ");
message.push_str(violation);
message.push('\n');
}
if !remediations.is_empty() {
message.push_str("remediate every off-pin member, then rebuild:\n");
for remediation in &remediations {
message.push_str(" ");
message.push_str(remediation);
message.push('\n');
}
}
fatal(message);
}
}
fn validate_manifest_dependency_spec(
manifest: &Value,
contract: &DependencyContract,
packaged_manifest: bool,
) {
let spec = inline_table(
table(manifest, contract.dep_table, "manifest root"),
contract.dep_key,
contract.dep_table,
);
validate_manifest_dependency_version(spec, contract, packaged_manifest);
if contract.expected_git.is_empty() {
// Pure crates.io dependency: lock in the registry version, which is the
// only source identity crates.io gives us.
if spec.contains_key("git") || spec.contains_key("rev") {
contract_error(
contract,
format!(
"dependency `{}` in [{}] is a crates.io dep in this contract; remove `git`/`rev`",
contract.dep_key, contract.dep_table
),
);
}
} else if packaged_manifest && !spec.contains_key("git") && !spec.contains_key("rev") {
// Cargo rewrites git dependencies to registry dependencies in the
// generated package manifest used by `cargo publish` verification.
// Validate that rewritten shape against the version we expect instead
// of requiring `git`/`rev` keys that no longer exist there.
} else {
let actual_git = string_value(spec, "git", contract.dep_key);
if actual_git != contract.expected_git {
contract_error(
contract,
format!(
"dependency `{}` in [{}] must pin git = `{}`, found `{}`",
contract.dep_key, contract.dep_table, contract.expected_git, actual_git
),
);
}
let actual_rev = string_value(spec, "rev", contract.dep_key);
if actual_rev != contract.expected_rev {
contract_error(
contract,
format!(
"dependency `{}` in [{}] must pin rev = `{}`, found `{}`",
contract.dep_key, contract.dep_table, contract.expected_rev, actual_rev
),
);
}
}
let actual_package = spec.get("package").and_then(Value::as_str);
if actual_package != contract.manifest_package_field {
let expected = contract.manifest_package_field.unwrap_or("<omitted>");
let actual = actual_package.unwrap_or("<omitted>");
contract_error(
contract,
format!(
"dependency `{}` in [{}] must use package = `{}`, found `{}`",
contract.dep_key, contract.dep_table, expected, actual
),
);
}
let actual_features = feature_set(spec.get("features"));
let expected_features: BTreeSet<String> = contract
.expected_features
.iter()
.map(|feature| (*feature).to_string())
.collect();
if actual_features != expected_features {
contract_error(
contract,
format!(
"dependency `{}` in [{}] must enable features {:?}, found {:?}",
contract.dep_key, contract.dep_table, expected_features, actual_features
),
);
}
if let Some(expected_default_features) = contract.expected_default_features {
let actual_default_features = spec
.get("default-features")
.and_then(Value::as_bool)
.unwrap_or(true);
if actual_default_features != expected_default_features {
contract_error(
contract,
format!(
"dependency `{}` in [{}] must use default-features = `{}`, found `{}`",
contract.dep_key,
contract.dep_table,
expected_default_features,
actual_default_features
),
);
}
}
}
fn validate_manifest_dependency_version(
spec: &toml::map::Map<String, Value>,
contract: &DependencyContract,
packaged_manifest: bool,
) {
let actual_version = string_value(spec, "version", contract.dep_key);
let expected_manifest_version = expected_manifest_version_requirement(contract);
let package_manifest_may_strip_exact_operator =
packaged_manifest || !contract.expected_git.is_empty();
let version_matches = actual_version == expected_manifest_version
|| (package_manifest_may_strip_exact_operator
&& actual_version == contract.expected_version);
if !version_matches {
contract_error(
contract,
format!(
"dependency `{}` in [{}] must pin version = `{}`, found `{}`",
contract.dep_key, contract.dep_table, expected_manifest_version, actual_version
),
);
}
}
fn expected_manifest_version_requirement(contract: &DependencyContract) -> String {
format!("={}", contract.expected_version)
}
fn validate_patch_path(manifest: &Value, contract: &DependencyContract) {
let Some(patch_url) = contract.patch_url else {
contract_error(
contract,
"active path override contracts must provide patch_url".to_string(),
);
};
let Some(patch_key) = contract.patch_key else {
contract_error(
contract,
"active path override contracts must provide patch_key".to_string(),
);
};
let patch_tables = table(manifest, "patch", "manifest root");
let patch_source = table_value(Some(patch_tables), patch_url, "patch source");
let Some(patch_source_table) = patch_source.as_table() else {
contract_error(
contract,
format!("[patch] source `{patch_url}` must be a TOML table"),
);
};
let patch_entry = inline_table(patch_source_table, patch_key, "[patch] source");
let actual_path = string_value(patch_entry, "path", patch_key);
let expected_path = expected_patch_path(contract);
if actual_path != expected_path {
contract_error(
contract,
format!(
"[patch.\"{patch_url}\"].{patch_key}.path must be `{expected_path}`, found `{actual_path}`"
),
);
}
}
fn validate_local_contract(
manifest_dir: &Path,
contract: &DependencyContract,
strict_enabled: bool,
) {
let repo_root = manifest_dir.join(contract.repo_rel);
let manifest_path = repo_root.join(contract.manifest_rel);
println!("cargo:rerun-if-changed={}", manifest_path.display());
let local_manifest_text = match fs::read_to_string(&manifest_path) {
Ok(text) => text,
Err(err) if contract.mode == ValidationMode::StrictOptIn => {
// Optional sibling repo not checked out; skip validation.
// Only ActivePathOverride repos are required on disk.
println!(
"cargo:warning=skipping {} contract validation: sibling manifest `{}` not found: {err}",
contract.label,
manifest_path.display()
);
return;
}
Err(err) => contract_error(
contract,
format!(
"expected sibling manifest at `{}` but could not read it: {err}",
manifest_path.display()
),
),
};
let local_manifest: Value = toml::from_str(&local_manifest_text).unwrap_or_else(|err| {
contract_error(
contract,
format!(
"failed to parse sibling manifest `{}`: {err}",
manifest_path.display()
),
)
});
let package_table = table(
&local_manifest,
"package",
&manifest_path.display().to_string(),
);
let package_name = table_value(Some(package_table), "name", "package")
.as_str()
.unwrap_or_else(|| {
contract_error(
contract,
format!(
"sibling manifest `{}` is missing a string package.name",
manifest_path.display()
),
)
});
if package_name != contract.crate_package_name {
contract_error(
contract,
format!(
"sibling manifest `{}` must expose package `{}`, found `{}`",
manifest_path.display(),
contract.crate_package_name,
package_name
),
);
}
let version = table_value(Some(package_table), "version", "package")
.as_str()
.unwrap_or_else(|| {
contract_error(
contract,
format!(
"sibling manifest `{}` is missing a string package.version",
manifest_path.display()
),
)
});
if version != contract.expected_version {
contract_error(
contract,
format!(
"sibling manifest `{}` must expose version `{}`, found `{}`",
manifest_path.display(),
contract.expected_version,
version
),
);
}
let features = local_manifest.get("features").and_then(Value::as_table);
let missing_feature = contract
.expected_features
.iter()
.copied()
.find(|feature| !features.is_some_and(|table| table.contains_key(*feature)));
if let Some(feature) = missing_feature {
contract_error(
contract,
format!(
"sibling manifest `{}` must provide feature `{}` because cass enables it",
manifest_path.display(),
feature
),
);
}
match (strict_enabled, contract.mode, git_state(&repo_root)) {
(true, _, Ok(state)) => validate_strict_git_state(contract, &repo_root, &state),
(true, _, Err(err)) => contract_error(