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
//! Content hashing and generated-file headers.
//!
//! Every file produced by alef gets a standard header that identifies it as
//! generated, tells agents/developers how to fix issues, and embeds a blake3
//! hash so `alef verify` can detect staleness without external state.
//!
//! # Hash semantics
//!
//! The embedded `alef:hash:<hex>` value is **not** [`compute_inputs_hash`]'s
//! output. It is [`compute_file_hash`]'s output, which folds that inputs
//! fingerprint together with the file's own emitted content — every call site
//! that injects a hash line passes it `compute_file_hash`'s result, never
//! `compute_inputs_hash`'s directly:
//!
//! ```text
//! inputs_hash = blake3(
//! "alef:inputs\0"
//! || CODEGEN_FORMAT_VERSION || "\0"
//! || sources_hash || "\0"
//! || canonical_toml ← parse + key-sort + re-serialize alef.toml
//! )
//!
//! alef:hash:<hex> = blake3(
//! "sources\0" || inputs_hash || "\0content\0" || file_content_without_hash_line
//! )
//! ```
//!
//! Where `sources_hash` is [`compute_sources_hash`] over the sorted Rust source
//! files alef parses to build the IR, and `canonical_toml` is the normalized
//! form of `alef.toml` (comments stripped, keys sorted, whitespace and line
//! endings normalized). Because the file's own bytes are folded in, the
//! embedded hash answers a strictly stronger question than "were these inputs
//! used" — it answers **"was this exact file content produced by these
//! inputs?"** A hand-edit to an emitted file (a reverted dependency bump, a
//! manually patched line) changes `file_content_without_hash_line` without
//! touching `inputs_hash`, so it changes the embedded value and `alef verify`
//! reports it stale, exactly like an inputs change would.
//!
//! Post-generation formatter drift (rustfmt, ruff, rumdl-fmt, oxfmt, etc.) is
//! *not* a false positive, but not because content is excluded — it is
//! included. The reason is ordering: `generate::write::finalize_hashes`
//! stamps the hash *after* every formatter has already run
//! (`write_files_report` writes the header with no hash line; formatters run;
//! `finalize_hashes` then hashes the final, formatted bytes). So the embedded
//! hash reflects the post-format content from the start, and a later run of
//! the same formatter over already-formatted content is a no-op, not drift.
//! Routine alef crate releases do not change the hash because the alef crate
//! version (`ALEF_REV`) is not an input to `inputs_hash`. Separately, bumping the
//! `[workspace] alef_version` pin inside `alef.toml` — the standard consumer upgrade step —
//! also does not change the hash: that one key is stripped from `canonical_toml` before
//! hashing, because nothing in codegen branches on it (see `strip_alef_version_pin`).
//! Every other key in `alef.toml` is still a real input, so a genuine config change still
//! rehashes.
//!
//! `alef verify` (`bin_cli::helpers::verify_walk` / `verify_walk_multi`)
//! re-derives `inputs_hash` from the current `alef.toml` and Rust sources,
//! reads each on-disk file, strips its `alef:hash:` line, recomputes
//! [`compute_file_hash`] over `inputs_hash` plus the *actual on-disk bytes*,
//! and compares that to the embedded line. It is read-only — no
//! regeneration, no writes — but it is not a bare line comparison: the
//! on-disk content is rehashed on every run, which is exactly what lets it
//! catch content drift without regenerating.
//!
//! What this mechanism cannot see is scoped precisely by two other things, not
//! by the hash formula: a file whose extension isn't in
//! `bin_cli::helpers::VERIFY_SCAN_EXTENSIONS`/`VERIFY_SCAN_FILENAMES` is
//! never opened at all, and a file whose format cannot carry a comment marker
//! (`.json`, `.jar`, lockfiles) is tracked only by path presence in
//! `cli::cache::OWNERSHIP_MANIFEST`, which has no content hash to compare —
//! for those, `alef verify` can confirm alef once wrote the path but not that
//! its current bytes still match. Both gaps are enumerated, not this hash
//! design; see the doc comments at the definitions above.
//!
//! # Migration from v0.10.1 — v0.20.x
//!
//! Pre-v0.21.0 alef embedded `blake3(sources_hash || file_content_without_hash_line)` —
//! already content-inclusive, just without the `inputs_hash` domain
//! separation and canonicalized-`alef.toml` mixing described above. Any file
//! regenerated with v0.21.0+ will carry a new hash value; `alef verify` from
//! v0.21.0+ rejects old-format hashes. Run `alef generate` once after
//! upgrading to stamp all files with the new format.
const HASH_PREFIX: &str = "alef:hash:";
const DEFAULT_REGENERATE_COMMAND: &str = "alef generate";
const DEFAULT_VERIFY_COMMAND: &str = "alef verify";
/// The first line of the standard alef header, emitted by every [`header`]/[`header_for_config`]
/// call — the single source for the `"auto-generated by alef"` spelling, so a marker-spelling test
/// can assert against the real value instead of a hand-copied duplicate. ~keep
pub const STANDARD_HEADER_LINE: &str = "This file is auto-generated by alef — DO NOT EDIT.";
/// Marker line for the umbrella `RUST_BRIDGE_C_H` header Swift's binding generation writes.
///
/// Shared between `backends::swift::gen_bindings::bridge_artifacts::emit_swift_bridge_files` and
/// `scaffold::languages::swift::render_rust_bridge_c_header`, which independently build the same
/// header text on two different code paths (fresh generation vs. reconciling an existing file) —
/// hoisted here so the two can never spell it differently. ~keep
pub const SWIFT_C_UMBRELLA_HEADER_MARKER: &str = "// Auto-generated by alef — do not edit by hand.";
/// Marker line for the generated `CITATION.cff` header, written by
/// `cli::pipeline::version_text::render_citation_cff`. ~keep
pub const CITATION_CFF_HEADER_LINE: &str =
"# This file is generated by alef sync-versions; do not edit by hand.";
/// Marker line shared by every backend that self-marks instead of prepending [`header`]/
/// [`header_for_config`] — Dart, Gleam, Kotlin (JVM, Multiplatform, and Android), Swift, and the
/// Gleam/Kotlin-Android e2e project generators each write this exact text at one or more call
/// sites; hoisted here so none of them can drift to a spelling `content_has_alef_marker` would
/// still accept but this constant no longer names. ~keep
pub const SELF_MARKING_HEADER_LINE: &str = "// Generated by alef. Do not edit by hand.";
/// [`inject_stamp_line`]/[`extract_stamp`] key for the opaque-handle ABI
/// generation a file was produced against (pointer vs. `u64` registry key,
/// or any future representation). Backends that emit an FFI-consuming
/// artifact encoding that representation (the FFI header/glue itself, and
/// any binding backend whose template hardcodes the handle's native type
/// instead of deriving it live from the FFI header at build time — zig's
/// `_handle: u64` fields and C#'s `IntPtr`-based `SafeHandle` wrapper are the
/// known cases) should stamp their generated files with this key so a
/// verify-time consistency check can catch two different ABI generations
/// coexisting in one tree — the hazard is silent because pointer and `u64`
/// are both 8 bytes on 64-bit targets, so a straddle compiles and then
/// misinterprets a pointer as a registry index at runtime. No backend calls
/// this yet; the constant exists so the first one to do so and the verify
/// side (`crate::bin_cli::helpers::find_stamp_disagreement`) agree on the
/// key without a second source of truth. ~keep
pub const HANDLE_ABI_STAMP_KEY: &str = "handle-abi";
/// Comment style for the generated header.
/// Return the standard alef header as a comment block.
///
/// ```text
/// // This file is auto-generated by alef — DO NOT EDIT.
/// // To regenerate: alef generate
/// // To verify freshness: alef verify
/// ```
/// Return the standard alef header using metadata from a resolved crate config.
/// The substring shared by every marker spelling alef emits or must recognize on read-back,
/// matched case-insensitively (see [`line_has_marker`]). A single substring subsumes every
/// capitalization variant produced across backends -- `"auto-generated by alef"`, `"Auto-generated
/// by alef"`, `"Generated by alef"`, `"generated by alef"` -- and also Go's own `"Code generated
/// ... by alef"` convention, which alef should honour rather than fight. Previously this was two
/// case-sensitive literals (`"auto-generated by alef"` / `"Generated by alef"`); that check missed
/// every other capitalization a backend or a hand-adopted file might use, silently refusing to ever
/// stamp or verify the file again. ~keep
const MARKER_SUBSTRING: &str = "generated by alef";
/// Additional contiguous substrings that are unambiguous alef ownership claims but do not contain
/// [`MARKER_SUBSTRING`].
///
/// A consumer census of every marker alef actually emits found 18 distinct forms; 16 contain
/// `generated by alef` outright and differ only in capitalisation and trailing punctuation. The two
/// below do not, and both land in shipped output rather than throwaway files -- a Homebrew
/// `Brewfile` that says "managed by" instead of "generated by", and an R entrypoint whose header
/// names alef and says "do not edit" without ever putting the two words adjacent. A human reading
/// either sees an obvious ownership marker; a contiguous substring test does not.
///
/// These are recognised rather than merely re-spelled at the emitter because a file already on disk
/// in a consumer tree carries the old spelling, and a predicate that refuses it also refuses to
/// rewrite it -- the file would be permanently unadoptable by the very fix meant to free it. ~keep
const ALTERNATE_MARKER_SUBSTRINGS: & = &;
/// Case-insensitive ASCII substring search for `needle` within `haystack`.
///
/// Used instead of `haystack.to_lowercase().contains(needle)` to avoid allocating a lowercased
/// copy of every scanned line: this only ever runs against the first [`MARKER_SCAN_LINES`] lines
/// of a file, so the cost is already bounded, but a byte-window scan with
/// [`u8::eq_ignore_ascii_case`] gets the same correctness for free. Marker text is always plain
/// ASCII, so ASCII-only case-folding is sufficient here. ~keep
/// Whether a single line carries [`MARKER_SUBSTRING`], case-insensitively.
///
/// The one predicate every marker-scanning function in this module shares --
/// [`content_has_alef_marker`], [`inject_hash_line`], [`inject_stamp_line`], and
/// [`generated_hash_line`] (which backs [`extract_hash`]/[`strip_hash_line`]) -- so a line that one
/// of them treats as a marker is treated as one by all of them. They must agree: a marker
/// `content_has_alef_marker` accepts but `inject_hash_line` cannot find is a file claimed by `alef
/// verify` and never stamped, permanently stale. ~keep
/// Whether `content` carries an alef header marker in its leading lines.
///
/// This is the single definition of "alef owns this file's provenance". Both
/// the stamping pass and the callers that assemble its input set must agree on
/// it, otherwise a marked file can be emitted, claimed by `alef verify`, and
/// never stamped — leaving it permanently stale. ~keep
/// A leading line that looks like a failed attempt at an alef marker -- it mentions both "alef"
/// and "generated" (independently, case-insensitively) but doesn't satisfy [`line_has_marker`] --
/// without actually being one. Surfaced so a write-time refusal can name what's wrong instead of
/// looking identical to a plain hand-written file that never tried. Returns `None` when nothing in
/// the scan window is even close (including when a real marker is already present: a matching line
/// is never a near miss of itself). ~keep
pub
/// How far into a file the header marker is searched for.
///
/// Deliberately 10 and not 11, even though `poly`'s built-in generated-file skip scans the first
/// **11** lines for a `<tool>:hash:<40-or-64 hex>` line. The two bounds measure different things:
/// this one bounds where the *prose* marker may sit, and [`inject_hash_line`] always writes the
/// `alef:hash:` line on the line *immediately after* it. A marker on lines 1..=10 therefore puts
/// its hash on lines 2..=11 — exactly poly's window, with nothing to spare. Widening this to 11
/// would let a marker on line 11 push its hash to line 12, where poly no longer sees it, so alef
/// would claim a file poly still reformats: the ping-pong this bound exists to prevent,
/// re-introduced at the boundary. If poly's window ever widens, this may follow it — never lead
/// it. ~keep
const MARKER_SCAN_LINES: usize = 10;
/// How many leading lines `poly`'s built-in generated-file skip reads when looking for a
/// `<tool>:hash:<40-or-64 hex>` line.
///
/// Measured against poly 0.21.6 by bisection, with `[discovery] exclude = []` and nothing else
/// configured: a marker on line 11 is skipped, one on line 12 is not. The skip is compiled into
/// the poly binary — no `poly.toml` key drives it, and the `<tool>` segment is not alef-specific —
/// so alef cannot negotiate this bound, only stay inside it. Held as a constant rather than
/// described in prose so [`MARKER_SCAN_LINES`]'s relationship to it is checkable by a test. ~keep
pub const POLY_GENERATED_SCAN_LINES: usize = 11;
/// The last line number (1-based) on which [`inject_hash_line`] can place an `alef:hash:` line,
/// given a marker anywhere in [`MARKER_SCAN_LINES`]. Must stay `<= POLY_GENERATED_SCAN_LINES` or
/// alef claims files poly still reformats.
pub const
/// Blake3 hash of a content string, returned as hex.
///
/// Used by the IR / language caches and any caller that needs a hash of an
/// in-memory string. **Not used for the embedded `alef:hash:` header** — that
/// is computed by [`compute_file_hash`].
/// Compute a stable hash over the Rust source files that alef extracts.
///
/// This is the "source side" of the per-file verify hash. Sources are sorted
/// by path so the hash is stable regardless of ordering in
/// `alef.toml`'s `[crate].sources`. The path is mixed in alongside the
/// content because the same byte-content at a different path produces
/// different IR (the `rust_path` on extracted types differs).
///
/// Used by [`compute_file_hash`]; not by itself the value embedded in any
/// file header.
///
/// # Errors
/// Returns an error if any source file is missing or unreadable.
/// Compute a stable hex-encoded Blake3 hash over all Rust source files
/// belonging to a [`crate::core::config::resolved::ResolvedCrateConfig`].
///
/// Returns a hex string so callers can feed the result directly to
/// [`compute_file_hash`], matching [`compute_sources_hash`]'s return type.
///
/// The hash covers the union of:
/// - `crate_cfg.sources` (direct sources on the crate)
/// - every `source_crates[*].sources` entry
///
/// All paths are sorted before hashing so the result is independent of the
/// order they appear in `alef.toml`. The path string is mixed in alongside
/// the file content because the same byte-content at a different path produces
/// different IR (the `rust_path` on extracted types differs).
///
/// # Phase 3 migration note
///
/// Phase 3 callers should migrate from the per-file `compute_sources_hash` to
/// this function when they have a `ResolvedCrateConfig` available, so that
/// multi-source-crate workspaces produce a single stable hash across all
/// contributing source files.
///
/// # Errors
///
/// Returns an error if any source file is missing or unreadable.
/// Compute the generation-inputs hash that alef embeds in each generated file.
///
/// The hash covers the [`CODEGEN_FORMAT_VERSION`] constant (stable across
/// crate releases — only bumped for breaking codegen changes), the Rust
/// source fingerprint, and a **canonical normalized form** of `alef.toml`
/// (parsed and re-serialized as TOML, stripping comments, whitespace churn,
/// key-order differences, CRLF line endings, and the `[workspace] alef_version`
/// pin — see [`strip_alef_version_pin`]). It does **not** include the
/// emitted file content, so post-generation formatter rewrites (rustfmt, ruff,
/// rumdl-fmt, oxfmt, …) never invalidate the embedded hash. It also does
/// **not** include the alef crate version (`ALEF_REV`), so upgrading alef
/// between releases — including bumping the `alef_version` pin in `alef.toml`, the
/// standard way to record that upgrade — does not mass-invalidate client bindings.
///
/// - **Generate**: compute once per run, inject into every generated file header.
/// - **Verify**: re-derive from the current inputs, compare to the embedded line.
/// No file content is read or hashed — pure input comparison.
///
/// # Arguments
///
/// * `sources_hash` — output of [`compute_sources_hash`] or
/// [`compute_crate_sources_hash`] for the crate being generated.
/// * `alef_toml_bytes` — raw bytes of the `alef.toml` config file. Pass an
/// empty slice when the config path is unavailable (e.g. in tests); the hash
/// will still change when `sources_hash` changes.
///
/// [`CODEGEN_FORMAT_VERSION`]: crate::core::template_versions::precommit::CODEGEN_FORMAT_VERSION
/// Normalize raw `alef.toml` bytes into a canonical string for hashing.
///
/// Parses the bytes as TOML, recursively sorts table keys, then re-serializes.
/// This strips comments, normalizes whitespace, eliminates CRLF vs LF
/// differences, and makes key ordering deterministic. Falls back to:
/// - empty string for empty / non-UTF-8 input
/// - raw UTF-8 string if the bytes are valid UTF-8 but not parseable as TOML
/// (avoids silently swallowing malformed configs while still producing a
/// deterministic hash for the data that is present)
/// Remove `[workspace] alef_version` before hashing `alef.toml`.
///
/// The pin only feeds `cli::version_pin::check_alef_toml_version`, which logs a mismatch
/// warning and never branches codegen — confirmed by grepping every read of
/// `WorkspaceConfig::alef_version` in `src/`. Folding it into `inputs_hash` therefore rehashed
/// every generated file on the standard upgrade workflow (bump the pin in `alef.toml`) even
/// though emitted content never changed. Stripping only this one key, rather than the field's
/// whole containing table, keeps any other future `[workspace]` key an input. ~keep
/// Recursively sort the keys of every TOML table so that key-ordering
/// differences in `alef.toml` do not produce different hashes.
/// Normalize a source-file path for stable hashing across machines and
/// operating systems.
///
/// Attempts to produce a repo-relative path by stripping the current working
/// directory prefix. Falls back to the original path if relativization fails
/// (e.g. the file lives outside the working directory, or `current_dir()`
/// is unavailable). In both cases `\\` is replaced with `/` so that hashes
/// are stable across Windows and POSIX builds of the same repo.
/// Compute the per-file verify hash that alef embeds in each generated file.
///
/// `sources_hash` may be the output of [`compute_sources_hash`] or the canonical
/// generation-input fingerprint from [`compute_inputs_hash`]. `content` is the file
/// content; any pre-existing `alef:hash:` line is stripped before hashing so
/// the function is idempotent.
/// Inject an `alef:hash:<hex>` line immediately after the first header marker
/// line found in the first [`MARKER_SCAN_LINES`] lines. The comment syntax is
/// inferred from the marker line itself.
///
/// The window must stay tied to [`MARKER_SCAN_LINES`] rather than repeat its value: a marker this
/// function declines to stamp is still one [`content_has_alef_marker`] claims, and a claimed but
/// unstamped file is invisible to poly's hash-keyed skip. See that constant for why 10 is the
/// value both sides carry. ~keep
///
/// If no marker line is found, the content is returned unchanged.
/// Inject an arbitrary `alef:<key>:<value>` stamp line immediately after the
/// first header marker line found in the first [`MARKER_SCAN_LINES`] lines.
///
/// Generalizes the single-purpose `alef:hash:` mechanism ([`inject_hash_line`])
/// for other per-file, plaintext-extractable stamps — for example an ABI
/// generation marker that a cross-artifact consistency check (comparing an FFI
/// header against a binding backend's opaque-handle template) can read
/// directly, without re-deriving [`compute_inputs_hash`]'s generation-inputs
/// fingerprint the way `alef:hash:` requires. `key` must not itself contain a
/// colon. Call this *before* [`inject_hash_line`] when both are used on the
/// same content, so the final `alef:hash:` line reflects the stamped content
/// rather than the other way around. If no marker line is found, the content
/// is returned unchanged.
///
/// Deliberately duplicates `inject_hash_line`'s comment-style detection
/// instead of sharing it, so this new, unused-by-any-caller-yet primitive
/// cannot change `alef:hash:` injection behavior. ~keep
/// Extract the value of an `alef:<key>:<value>` stamp line injected by
/// [`inject_stamp_line`], searching the first [`MARKER_SCAN_LINES`] lines.
///
/// Returns `None` when the header marker itself is absent, or when no line in
/// the scan window matches `alef:<key>:`. Unlike [`extract_hash`], the value is
/// returned as-is with no hex-digit constraint, since a generation marker need
/// not be a hash (a small integer version is the expected case).
/// Extract the hash from the generated stamp following an alef header marker.
/// Strip the generated hash stamp from content (for fallback comparison).