memstead_base/preparation.rs
1//! The engine-owned **preparation registry** — the one place that says which
2//! preparations exist, on which anchor grains, at which engine touchpoint,
3//! and what each grain's PREPARED FORM is.
4//!
5//! A source declares at most one preparation ([`crate::pipeline::Source::preparation`],
6//! a string identifier). The engine refuses any identifier this registry
7//! does not know ([`crate::binding::CapabilityError::PreparationUnsupported`],
8//! raised by [`crate::binding::validate_binding`] and mirrored on the
9//! brief-render path for a record that acquired one by hand) and consults the
10//! registry at exactly two touchpoints:
11//!
12//! - **Touchpoint A — prepared form.** Anchor observation asks the registry
13//! for an artifact's prepared form before hashing it (the engine's one
14//! per-anchor observation site). The standalone `verify-anchors` operation
15//! and the binding-backed verify share that site, so both inherit every
16//! registered preparation without redesign.
17//! - **Touchpoint B — delivery units.** The ingest delivery path asks the
18//! registry for a source's unit sequence ([`unitize`]): one file can carry
19//! many delivery units, addressed `<path>#<key>`, and the units of a whole
20//! source form one deterministic total order derived from the units' own
21//! keys ([`Touchpoint::DeliveryUnits`], first entry [`DATED_ENTRIES`]).
22//! A source declaring no delivery preparation keeps file-granularity
23//! delivery unchanged.
24//!
25//! **Identity.** [`crate::binding::PREPARATION_IMPL_VERSION`] is hashed into
26//! every binding's `hash(D)` next to the declared identifier. Landing or
27//! changing an implementation bumps the constant, which invalidates every
28//! finding keyed on the old hash by construction (`ingest::findings` keys on
29//! `hash(D)` alone).
30//!
31//! **Prepared forms per grain.** The path grains (`span` / `file`) hash their
32//! bytes through [`crate::anchor::prepared_content_hash`] (the minimal
33//! canonicalization: BOM, line endings, final newline). The `url` grain uses
34//! the **same canonicalization over observation-supplied content** — the
35//! engine never fetches, so whoever observed the URL supplies the bytes at
36//! write time (`AnchorInput::content`) — and defaults to `hash_stability:
37//! unstable`, a served page being a moving target. The `entity` grain's
38//! prepared form is computed from the live graph, never from supplied bytes:
39//! the canonical rendered markdown by default, or — under
40//! [`ENTITY_LOAD_BEARING`] — the stable serialization of the type's
41//! load-bearing sections.
42//!
43//! **Non-goal, by standing decision:** PDF / DOCX / audio conversion. An
44//! agent with a capable read tool extracts; the raw-byte fallback of the
45//! prepared-content hash already drift-detects a binary artifact.
46
47use serde::{Deserialize, Serialize};
48
49use crate::anchor::{AnchorGrain, AnchorHashStability, prepared_content_hash};
50use crate::entity::Entity;
51
52/// The engine touchpoint a registered preparation plugs into.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(rename_all = "kebab-case")]
55pub enum Touchpoint {
56 /// Touchpoint A: anchor observation asks the registry for the prepared
57 /// form an artifact hashes as (content and code-map flavours).
58 PreparedForm,
59 /// Touchpoint B: the ingest delivery path asks the registry for a
60 /// source's unit sequence (the delivery flavour).
61 DeliveryUnits,
62}
63
64/// One registered preparation.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct Preparation {
67 /// The identifier a source declares (`Source::preparation`).
68 pub id: &'static str,
69 /// Which engine touchpoint consults it.
70 pub touchpoint: Touchpoint,
71 /// The anchor grains it produces a prepared form for. A binding may
72 /// declare it only over a medium whose anchor namespace admits at least
73 /// one of these grains (checked at binding validation).
74 pub grains: &'static [AnchorGrain],
75 /// One sentence for the operator and the refusal payloads.
76 pub description: &'static str,
77}
78
79/// Content preparation on the `entity` grain: the prepared form is the stable
80/// serialization of the entity type's **load-bearing sections** (see
81/// [`load_bearing_sections`]), so a dependent's prepared hash breaks when a
82/// load-bearing sentence changes and holds when a comma lands in the notes.
83pub const ENTITY_LOAD_BEARING: &str = "entity-load-bearing";
84
85/// Delivery preparation on path-shaped sources: a file is a sequence of
86/// **dated entries**. A unit begins at every line that opens with an ISO
87/// date or date-time (`2026-08-24`, `2026-08-24 10:05`, `2026-08-24T10:05:00Z`,
88/// after any leading markdown markers such as `## `, `- `, `> `, `[`); it
89/// runs to the next such line. Text before the first entry folds into the
90/// first unit; a file with no dated line is one unit keyed
91/// [`WHOLE_FILE_UNIT`]. The unit key is the stamp normalized to
92/// `YYYY-MM-DDTHH:MM:SS` (missing time parts read `00`), with `.2`, `.3`, …
93/// appended to the second, third, … entry carrying the same stamp in one
94/// file, in file order — so appending entries never renames an existing
95/// unit. The order key is the normalized stamp; across a whole source, units
96/// sort by stamp, then path, then key, which is what makes a chronological
97/// corpus deliver in its own order regardless of how files were discovered.
98/// Undated files (order key empty) come first, in path order. Fractional
99/// seconds and zone designators are accepted and ignored for ordering.
100pub const DATED_ENTRIES: &str = "dated-entries";
101
102/// The key of the single unit a file yields when a delivery preparation finds
103/// no unit boundary in it — the whole file, still addressable as
104/// `<path>#whole`.
105pub const WHOLE_FILE_UNIT: &str = "whole";
106
107/// Code-map preparation on path-shaped sources (touchpoint A): a scoped
108/// file's prepared form is its **interface digest** — imports, exports and
109/// declarations with their signatures; comments, formatting and bodies are
110/// invisible. The digest is heuristic and language-family aware by file
111/// extension: C-like families (JS/TS, Rust, Go, Java, Kotlin, Swift, C#, C,
112/// C++, PHP, Dart, Scala) keep top-level declaration lines and class or
113/// object member signatures, cut at the body's opening brace; Python keeps
114/// imports, `def`/`class` lines (top level and one level in), decorators and
115/// upper-case module constants; a Vue single-file component is its script
116/// block under the C-like rule; JSON is its canonical compact form; every
117/// other file is taken whole. A `tree`-grain anchor under this preparation
118/// hashes the digest of every scoped file under the tree (path and file
119/// hash, path order), which is what closes the tree grain's
120/// recorded-but-unhashed residue for code sources. Values inside
121/// declarations (a config object's members, an array literal's contents
122/// beyond its first line, a scalar property value) are body, not
123/// interface: the digest sees names and signatures. A literal object
124/// restructured between one line and many reads as a shape change.
125pub const CODE_MAP: &str = "code-map";
126
127/// Quoted-phrase preparation on the text-bearing grains (touchpoint A): the
128/// artifact `<path-or-url-or-entity-id>#<phrase>` addresses **the occurrence
129/// of a literal phrase** in a text, and its prepared form is the phrase
130/// itself. While the text still carries the phrase (an exact substring
131/// match after the minimal canonicalization of line endings), the anchor
132/// resolves; when the words are gone the unit is absent and the anchor reads
133/// `orphaned`, whatever else changed around it. A citation anchor, then: "this
134/// document still says X", quiet under every rewrite that keeps the words
135/// and loud the moment they leave. Applies to `span` (a file, read live),
136/// `url` (observation-supplied content: the engine never fetches) and
137/// `entity` (the live entity's canonical markdown). An artifact under this
138/// preparation that names no `#<phrase>` keeps the grain's whole-text form.
139pub const QUOTED_PHRASE: &str = "quoted-phrase";
140
141/// The registry — every preparation this engine implements. The refusal in
142/// [`crate::binding::validate_binding`] is exactly "not in this list".
143pub const REGISTRY: &[Preparation] = &[
144 Preparation {
145 id: ENTITY_LOAD_BEARING,
146 touchpoint: Touchpoint::PreparedForm,
147 grains: &[AnchorGrain::Entity],
148 description: "an entity's prepared form is the stable serialization of its type's \
149 load-bearing sections (explicitly declared, else the required sections, \
150 else every section) — notes-only edits keep dependents' anchors resolving",
151 },
152 Preparation {
153 id: DATED_ENTRIES,
154 touchpoint: Touchpoint::DeliveryUnits,
155 grains: &[AnchorGrain::Span],
156 description: "a file is a sequence of entries opening with an ISO date or date-time; \
157 each entry is one delivery unit `<path>#<stamp>`, and a source's units \
158 deliver in stamp order, identical on every pass — a chronological corpus \
159 (logs, transcripts, journals, mail threads) is never shuffled",
160 },
161 Preparation {
162 id: CODE_MAP,
163 touchpoint: Touchpoint::PreparedForm,
164 grains: &[AnchorGrain::File, AnchorGrain::Span, AnchorGrain::Tree],
165 description: "a scoped code file's prepared form is its interface digest (imports, \
166 exports, declarations and their signatures; comments, formatting and \
167 bodies invisible), and a tree's is the digest of every scoped file under \
168 it — an anchor drifts when an interface changes and stays quiet when \
169 only an implementation does",
170 },
171 Preparation {
172 id: QUOTED_PHRASE,
173 touchpoint: Touchpoint::PreparedForm,
174 grains: &[AnchorGrain::Span, AnchorGrain::Url, AnchorGrain::Entity],
175 description: "an artifact `<path-or-url-or-entity>#<phrase>` addresses the occurrence of \
176 a literal phrase in a text and its prepared form is the phrase itself — the \
177 anchor resolves while the file, the observed page or the entity still says \
178 those words and reads orphaned once they are gone, whatever else changed",
179 },
180];
181
182/// Every registered preparation.
183pub fn registry() -> &'static [Preparation] {
184 REGISTRY
185}
186
187/// Look a declared identifier up.
188pub fn lookup(id: &str) -> Option<&'static Preparation> {
189 REGISTRY.iter().find(|p| p.id == id)
190}
191
192/// Whether `id` names a registered preparation.
193pub fn is_registered(id: &str) -> bool {
194 lookup(id).is_some()
195}
196
197/// The registered identifiers, in registry order — the recovery payload of
198/// the unknown-identifier refusal.
199pub fn registered_identifiers() -> Vec<&'static str> {
200 REGISTRY.iter().map(|p| p.id).collect()
201}
202
203/// The delivery preparation a source declares, if its declared identifier
204/// is a registered touchpoint-B entry — `None` for no declaration, an
205/// unregistered identifier, or a prepared-form (touchpoint A) flavour.
206pub fn delivery_preparation(declared: Option<&str>) -> Option<&'static Preparation> {
207 lookup(declared?).filter(|p| p.touchpoint == Touchpoint::DeliveryUnits)
208}
209
210/// Whether a registered preparation can apply over a medium whose anchor
211/// namespace is `anchor_namespace` (see
212/// [`crate::binding::medium_capabilities`]): at least one of the
213/// preparation's grains must be expressible there. `entity-load-bearing`
214/// over a `codebase` source would never meet an entity-grain anchor, so it
215/// is refused at declaration rather than silently never applying.
216pub fn applies_to_namespace(preparation: &Preparation, anchor_namespace: &str) -> bool {
217 preparation
218 .grains
219 .iter()
220 .any(|g| g.supported_by_namespace(anchor_namespace))
221}
222
223// ---------------------------------------------------------------------------
224// Per-grain prepared forms
225// ---------------------------------------------------------------------------
226
227/// The medium-declared default hash stability per grain. A `url` anchor
228/// defaults to `unstable` — a served page is a moving target, so a hash
229/// break resolves `recheck`, never `drifted`, unless the author asserts
230/// `stable` explicitly. Every other grain keeps its `stable` default.
231pub fn default_hash_stability(grain: AnchorGrain) -> AnchorHashStability {
232 match grain {
233 AnchorGrain::Url => AnchorHashStability::Unstable,
234 AnchorGrain::Span | AnchorGrain::File | AnchorGrain::Tree | AnchorGrain::Entity => {
235 AnchorHashStability::Stable
236 }
237 }
238}
239
240/// The `url` grain's canonicalization entry: the prepared form of a URL
241/// artifact is the observation-supplied content under the same minimal
242/// canonicalization the path grains use, so a `url` anchor's recorded hash
243/// means the same thing a `file` anchor's does. The engine never fetches;
244/// the observer supplies the bytes.
245pub fn url_prepared_hash(content: &[u8]) -> String {
246 prepared_content_hash(content)
247}
248
249/// The prepared-content hash of **supplied** content for a grain — the
250/// write-time observation an agent performs when it hands the engine what it
251/// read (`AnchorInput::content`). `None` for a grain whose prepared form
252/// is never computed from supplied bytes: `entity` (computed from the live
253/// graph, so a supplied rendering could disagree with the store) and `tree`
254/// (its prepared form is a digest over the enumerated scoped files —
255/// observation-side work no single supplied byte-string can represent).
256pub fn supplied_content_hash(grain: AnchorGrain, content: &[u8]) -> Option<String> {
257 match grain {
258 AnchorGrain::Span | AnchorGrain::File => Some(prepared_content_hash(content)),
259 AnchorGrain::Url => Some(url_prepared_hash(content)),
260 AnchorGrain::Tree | AnchorGrain::Entity => None,
261 }
262}
263
264// ---------------------------------------------------------------------------
265// Touchpoint A for path grains: the prepared form of a file or tree
266// ---------------------------------------------------------------------------
267
268/// What a path-grain observation yields under a source's preparation.
269#[derive(Debug, Clone, PartialEq, Eq)]
270pub enum PathPrepared {
271 /// The prepared-content hash to record or compare.
272 Hash(String),
273 /// The grain has no prepared form at this single-artifact touchpoint (a
274 /// `tree`, whose digest needs its files enumerated — the caller's job):
275 /// observe no hash here, resolve `recheck` where no digest arrives.
276 NoHash,
277 /// The artifact addresses a sub-file unit the file no longer yields (a
278 /// `<path>#<key>` span under a delivery preparation): an absent artifact.
279 UnitAbsent,
280}
281
282/// The prepared-content hash of one path-grain artifact's bytes under
283/// `preparation` — the one rule anchor observation and the write-time
284/// `content` path share, so a hash recorded at write time is the hash a
285/// later observation computes. No preparation (or one that does not prepare
286/// path grains): the file's bytes under the minimal canonicalization for
287/// `file`/`span`. [`DATED_ENTRIES`]: a `<path>#<key>`
288/// span hashes its unit ([`PathPrepared::UnitAbsent`] when the key is gone),
289/// a bare file its bytes. [`CODE_MAP`]: `file`/`span` hash the interface
290/// digest. A `tree` needs its files enumerated, which is the caller's job
291/// under every preparation ([`code_map_tree_digest`] /
292/// [`plain_tree_digest`]), so it answers `NoHash` here.
293pub fn path_prepared_hash(
294 preparation: Option<&str>,
295 artifact: &str,
296 grain: AnchorGrain,
297 bytes: &[u8],
298) -> PathPrepared {
299 let (path, locator) = split_unit_id(artifact);
300 match (preparation, grain) {
301 (Some(QUOTED_PHRASE), AnchorGrain::Span | AnchorGrain::Url) if locator.is_some() => {
302 quoted_phrase_prepared(locator.unwrap_or_default(), &String::from_utf8_lossy(bytes))
303 }
304 (_, AnchorGrain::Url | AnchorGrain::Entity | AnchorGrain::Tree) => PathPrepared::NoHash,
305 (Some(DATED_ENTRIES), AnchorGrain::Span) if locator.is_some() => {
306 let text = String::from_utf8_lossy(bytes);
307 match unitize(DATED_ENTRIES, &text)
308 .and_then(|units| units.into_iter().find(|u| Some(u.key.as_str()) == locator))
309 {
310 Some(unit) => PathPrepared::Hash(unit.hash),
311 None => PathPrepared::UnitAbsent,
312 }
313 }
314 (Some(CODE_MAP), AnchorGrain::File | AnchorGrain::Span) => {
315 let text = String::from_utf8_lossy(bytes);
316 PathPrepared::Hash(prepared_content_hash(
317 code_map_digest(path, &text).as_bytes(),
318 ))
319 }
320 (_, AnchorGrain::File | AnchorGrain::Span) => {
321 PathPrepared::Hash(prepared_content_hash(bytes))
322 }
323 }
324}
325
326/// Touchpoint A under [`QUOTED_PHRASE`]: the prepared form of `text` for the
327/// artifact `…#<phrase>`. The phrase is matched as an exact substring after
328/// the minimal canonicalization the path grains share (a BOM and `\r\n`
329/// line endings never decide a citation); present, the prepared form is the
330/// phrase and the hash is stable for as long as the words stand; absent, the
331/// unit is gone ([`PathPrepared::UnitAbsent`]) and the anchor reads
332/// `orphaned`. An empty phrase addresses nothing and is absent by
333/// definition, so a `#` with nothing after it can never resolve clean.
334pub fn quoted_phrase_prepared(phrase: &str, text: &str) -> PathPrepared {
335 let phrase = phrase.trim();
336 if phrase.is_empty() {
337 return PathPrepared::UnitAbsent;
338 }
339 let canonical_text = canonical_text(text);
340 let canonical_phrase = canonical_text_owned(phrase);
341 if canonical_text.contains(canonical_phrase.as_str()) {
342 PathPrepared::Hash(prepared_content_hash(canonical_phrase.as_bytes()))
343 } else {
344 PathPrepared::UnitAbsent
345 }
346}
347
348/// The text a phrase is matched against: BOM stripped, `\r\n` folded to
349/// `\n` — the same two normalizations `prepared_content_hash` applies, so a
350/// phrase that resolves on one platform resolves on every other.
351fn canonical_text(text: &str) -> String {
352 canonical_text_owned(text)
353}
354
355fn canonical_text_owned(text: &str) -> String {
356 text.strip_prefix('\u{feff}')
357 .unwrap_or(text)
358 .replace("\r\n", "\n")
359}
360
361// ---------------------------------------------------------------------------
362// Quoted spans: the canonical form a span is checked and hashed in
363// ---------------------------------------------------------------------------
364
365/// The **canonical span form**: the one text form a quoted span
366/// ([`crate::anchor::Anchor::span`]) is compared in, at write (is the span in
367/// the supplied `content`?), at observation (is it still in the observed
368/// text?) and when hashed ([`span_hash`]). One function serves all three
369/// sites, so a span that passed the write check is the span the observation
370/// looks for.
371///
372/// It removes exactly the noise two extractions of one document disagree on,
373/// and nothing else:
374///
375/// - Unicode NFC composition (a decomposed umlaut matches a composed one);
376/// - a soft hyphen (U+00AD) is removed;
377/// - typographic quotes (`‘ ’ ‚ ‛ “ ” „ ‟ ‹ › « »`) become their ASCII forms
378/// (`'` and `"`), and typographic dashes (U+2010 to U+2015, U+2212) become
379/// `-`;
380/// - the ligatures ff fi fl ffi ffl ſt st resolve to their letter pairs;
381/// - a hyphen directly followed by a line break is removed, together with
382/// the break and the indentation after it, so a word split at a line end
383/// matches its unsplit form;
384/// - every run of whitespace (spaces, tabs, line breaks, non-breaking
385/// spaces) becomes one space, a space directly after an opening bracket
386/// or before a closing one (`(`, `[`, `{` and their closers) is removed,
387/// and the ends are trimmed.
388///
389/// Digits, decimal marks, units, case and word order are untouched: beyond
390/// this form the match is exact, and no similarity threshold exists on any
391/// path. Case folding is deliberately absent (capitalisation carries meaning
392/// in the sources' languages) and so is NFKC (it would equate `m²` with
393/// `m2`, a changed unit).
394///
395/// The form is a function of its text alone, so the span's hash
396/// ([`span_hash`]) is one value wherever the span is quoted. The line-end
397/// hyphen is the one fold that loses a distinction (`statement-\nlevel`
398/// may be a split `statementlevel` or a compound `statement-level`), and
399/// the text side of a comparison answers it: [`span_occurs`] looks for
400/// the span in the joined form and in the form that keeps the hyphen
401/// ([`canonical_text_forms`]), so both readings are found and no rule
402/// has to guess from the rest of the document.
403pub fn canonical_span_form(text: &str) -> String {
404 canonical_form(text, LineEndHyphen::Join)
405}
406
407/// The two canonical forms of an observed TEXT a span is looked for in:
408/// the joined form ([`canonical_span_form`], a hyphen at a line end is a
409/// split word) and the form that keeps the hyphen (a compound word broken
410/// at the line end: `statement-\nlevel` reads `statement-level`). The
411/// second is omitted when it equals the first (no hyphen sat at a line
412/// end), so a text without the ambiguity costs one form.
413pub fn canonical_text_forms(text: &str) -> Vec<String> {
414 let joined = canonical_form(text, LineEndHyphen::Join);
415 let kept = canonical_form(text, LineEndHyphen::Keep);
416 if kept == joined {
417 vec![joined]
418 } else {
419 vec![joined, kept]
420 }
421}
422
423/// What a hyphen directly before a line break becomes in a canonical form.
424#[derive(Clone, Copy, PartialEq, Eq)]
425enum LineEndHyphen {
426 /// The hyphen, the break and the indentation go: a split word rejoins.
427 Join,
428 /// The hyphen stays, the break and the indentation go: a compound word
429 /// broken at the line end keeps its hyphen, with nothing around it.
430 Keep,
431}
432
433fn canonical_form(text: &str, line_end_hyphen: LineEndHyphen) -> String {
434 use unicode_normalization::UnicodeNormalization;
435 let composed: String = text.nfc().collect();
436 let mut mapped = String::with_capacity(composed.len());
437 for c in composed.chars() {
438 match c {
439 '\u{00AD}' => {}
440 '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}' | '\u{2039}' | '\u{203A}' => {
441 mapped.push('\'');
442 }
443 '\u{201C}' | '\u{201D}' | '\u{201E}' | '\u{201F}' | '\u{00AB}' | '\u{00BB}' => {
444 mapped.push('"');
445 }
446 '\u{2010}' | '\u{2011}' | '\u{2012}' | '\u{2013}' | '\u{2014}' | '\u{2015}'
447 | '\u{2212}' => mapped.push('-'),
448 '\u{FB00}' => mapped.push_str("ff"),
449 '\u{FB01}' => mapped.push_str("fi"),
450 '\u{FB02}' => mapped.push_str("fl"),
451 '\u{FB03}' => mapped.push_str("ffi"),
452 '\u{FB04}' => mapped.push_str("ffl"),
453 '\u{FB05}' | '\u{FB06}' => mapped.push_str("st"),
454 other => mapped.push(other),
455 }
456 }
457 // A hyphen at a line end: the break and any indentation that follows
458 // go, and the hyphen goes with them (a split word rejoins) or stays (a
459 // compound word keeps its hyphen), as the caller asked.
460 let mut joined = String::with_capacity(mapped.len());
461 let mut chars = mapped.chars().peekable();
462 while let Some(c) = chars.next() {
463 if c == '-' {
464 let mut ahead = chars.clone();
465 let mut consumed = 0usize;
466 if ahead.peek() == Some(&'\r') {
467 ahead.next();
468 consumed += 1;
469 }
470 if ahead.peek() == Some(&'\n') {
471 ahead.next();
472 consumed += 1;
473 while matches!(ahead.peek(), Some(' ') | Some('\t')) {
474 ahead.next();
475 consumed += 1;
476 }
477 for _ in 0..consumed {
478 chars.next();
479 }
480 if line_end_hyphen == LineEndHyphen::Keep {
481 joined.push('-');
482 }
483 continue;
484 }
485 }
486 joined.push(c);
487 }
488 // Whitespace runs become one space, except directly inside a bracket
489 // pair, where typesetting puts a space the words never had.
490 let mut out = String::with_capacity(joined.len());
491 let mut pending_space = false;
492 for c in joined.chars() {
493 if c.is_whitespace() {
494 pending_space = !out.is_empty();
495 } else {
496 if pending_space {
497 let after_opener = out.ends_with(['(', '[', '{']);
498 let before_closer = matches!(c, ')' | ']' | '}');
499 if !after_opener && !before_closer {
500 out.push(' ');
501 }
502 pending_space = false;
503 }
504 out.push(c);
505 }
506 }
507 out
508}
509
510/// Whether `span` occurs in `text`: the span in the canonical span form,
511/// the text in each of its canonical forms ([`canonical_text_forms`]), so
512/// a span quoting a compound word the text breaks at a line end
513/// (`statement-level` against `statement-\nlevel`) is found as surely as
514/// a split word (`generated` against `gener-\nated`). An empty span (empty
515/// after canonicalisation) occurs nowhere: it names no words, and the
516/// write path refuses it before it can be stored.
517pub fn span_occurs(span: &str, text: &str) -> bool {
518 let span = canonical_span_form(span);
519 if span.is_empty() {
520 return false;
521 }
522 canonical_text_forms(text)
523 .iter()
524 .any(|form| form.contains(span.as_str()))
525}
526
527/// The hash a span row records for its span: the house prepared-content
528/// hash over the canonical span form, so two writers quoting the same words
529/// with different quote marks or line breaks record the same value.
530pub fn span_hash(span: &str) -> String {
531 prepared_content_hash(canonical_span_form(span).as_bytes())
532}
533
534/// The code map of a tree: one line per scoped file under it, `<file digest
535/// hash> <path>`, in path order — hashed by the caller through
536/// [`prepared_content_hash`]. A file joining, leaving, or changing its
537/// interface changes the tree's map; an implementation edit does not.
538pub fn code_map_tree_digest(files: &[(String, String)]) -> String {
539 let mut rows: Vec<(&str, &str)> = files
540 .iter()
541 .map(|(path, text)| (path.as_str(), text.as_str()))
542 .collect();
543 rows.sort();
544 rows.iter()
545 .map(|(path, text)| {
546 format!(
547 "{} {path}",
548 prepared_content_hash(code_map_digest(path, text).as_bytes())
549 )
550 })
551 .collect::<Vec<_>>()
552 .join("\n")
553}
554
555/// The plain digest of a tree: one line per scoped file under it,
556/// `<prepared-content hash> <path>`, in path order — hashed by the caller
557/// through [`prepared_content_hash`]. Any byte change in any scoped file,
558/// and any file joining or leaving the tree, changes the digest — the same
559/// whole-content posture a `file` anchor has, lifted to the directory. This
560/// is the no-preparation counterpart of [`code_map_tree_digest`]; it is what
561/// lets a plain `tree` anchor adjudicate deterministically instead of
562/// resting in `recheck` forever.
563pub fn plain_tree_digest(files: &[(String, Vec<u8>)]) -> String {
564 let mut rows: Vec<(&str, &[u8])> = files
565 .iter()
566 .map(|(path, bytes)| (path.as_str(), bytes.as_slice()))
567 .collect();
568 rows.sort();
569 rows.iter()
570 .map(|(path, bytes)| format!("{} {path}", prepared_content_hash(bytes)))
571 .collect::<Vec<_>>()
572 .join("\n")
573}
574
575/// The interface digest of one file's text under [`CODE_MAP`].
576pub fn code_map_digest(path: &str, text: &str) -> String {
577 match family_of(path) {
578 Family::Text => text.to_string(),
579 Family::Json => serde_json::from_str::<serde_json::Value>(text)
580 .map(|v| v.to_string())
581 .unwrap_or_else(|_| text.to_string()),
582 Family::Vue => {
583 declaration_lines(&strip_c_comments(&vue_script_blocks(text)), Family::CLike)
584 }
585 Family::CLike => declaration_lines(&strip_c_comments(text), Family::CLike),
586 Family::Rust => declaration_lines(&strip_c_comments(text), Family::Rust),
587 Family::Python => declaration_lines(&strip_python_comments(text), Family::Python),
588 }
589}
590
591#[derive(Debug, Clone, Copy, PartialEq, Eq)]
592enum Family {
593 CLike,
594 /// C-like braces, but a struct field is interface only with `pub`
595 /// (a `key: Type` line without it is body), and enum variants are.
596 Rust,
597 Python,
598 Json,
599 Vue,
600 Text,
601}
602
603fn family_of(path: &str) -> Family {
604 let name = path.rsplit('/').next().unwrap_or(path);
605 let ext = match name.rsplit_once('.') {
606 Some((_, ext)) => ext.to_ascii_lowercase(),
607 None => return Family::Text,
608 };
609 match ext.as_str() {
610 "rs" => Family::Rust,
611 "js" | "mjs" | "cjs" | "jsx" | "ts" | "tsx" | "mts" | "cts" | "go" | "java" | "kt"
612 | "kts" | "swift" | "cs" | "c" | "h" | "cc" | "cpp" | "hpp" | "m" | "mm" | "php"
613 | "dart" | "scala" => Family::CLike,
614 "py" | "pyi" => Family::Python,
615 "json" => Family::Json,
616 "vue" | "svelte" => Family::Vue,
617 _ => Family::Text,
618 }
619}
620
621/// The concatenated `<script>` blocks of a single-file component (the
622/// template and styles are not interface).
623fn vue_script_blocks(text: &str) -> String {
624 let lower = text.to_ascii_lowercase();
625 let mut out = String::new();
626 let mut from = 0;
627 while let Some(open) = lower[from..].find("<script") {
628 let open = from + open;
629 let Some(tag_end) = lower[open..].find('>') else {
630 break;
631 };
632 let body_start = open + tag_end + 1;
633 let Some(close) = lower[body_start..].find("</script") else {
634 out.push_str(&text[body_start..]);
635 break;
636 };
637 out.push_str(&text[body_start..body_start + close]);
638 out.push('\n');
639 from = body_start + close + 8;
640 }
641 out
642}
643
644/// Strip `//` line comments and `/* */` block comments, outside string
645/// literals (a `'`/`"` string ends at its line; a template literal may span
646/// lines). Newlines are kept so line structure survives.
647fn strip_c_comments(text: &str) -> String {
648 let mut out = String::with_capacity(text.len());
649 let mut chars = text.chars().peekable();
650 let mut in_str: Option<char> = None;
651 let mut escape = false;
652 while let Some(c) = chars.next() {
653 if let Some(q) = in_str {
654 out.push(c);
655 if escape {
656 escape = false;
657 } else if c == '\\' {
658 escape = true;
659 } else if c == q || (c == '\n' && q != '`') {
660 in_str = None;
661 }
662 continue;
663 }
664 match c {
665 '"' | '\'' | '`' => {
666 in_str = Some(c);
667 out.push(c);
668 }
669 '/' => match chars.peek() {
670 Some('/') => {
671 for n in chars.by_ref() {
672 if n == '\n' {
673 out.push('\n');
674 break;
675 }
676 }
677 }
678 Some('*') => {
679 chars.next();
680 let mut prev = '\0';
681 for n in chars.by_ref() {
682 if n == '\n' {
683 out.push('\n');
684 }
685 if prev == '*' && n == '/' {
686 break;
687 }
688 prev = n;
689 }
690 }
691 _ => out.push(c),
692 },
693 _ => out.push(c),
694 }
695 }
696 out
697}
698
699/// Strip `#` comments outside strings and drop triple-quoted strings whole
700/// (docstrings and block literals are never interface).
701fn strip_python_comments(text: &str) -> String {
702 let mut out = String::with_capacity(text.len());
703 let bytes: Vec<char> = text.chars().collect();
704 let mut i = 0;
705 let mut in_str: Option<char> = None;
706 let mut triple: Option<char> = None;
707 while i < bytes.len() {
708 let c = bytes[i];
709 if let Some(q) = triple {
710 if c == q && i + 2 < bytes.len() && bytes[i + 1] == q && bytes[i + 2] == q {
711 triple = None;
712 i += 3;
713 continue;
714 }
715 if c == '\n' {
716 out.push('\n');
717 }
718 i += 1;
719 continue;
720 }
721 if let Some(q) = in_str {
722 out.push(c);
723 if c == '\\' && i + 1 < bytes.len() {
724 out.push(bytes[i + 1]);
725 i += 2;
726 continue;
727 }
728 if c == q || c == '\n' {
729 in_str = None;
730 }
731 i += 1;
732 continue;
733 }
734 match c {
735 '"' | '\'' => {
736 if i + 2 < bytes.len() && bytes[i + 1] == c && bytes[i + 2] == c {
737 triple = Some(c);
738 i += 3;
739 continue;
740 }
741 in_str = Some(c);
742 out.push(c);
743 }
744 '#' => {
745 while i < bytes.len() && bytes[i] != '\n' {
746 i += 1;
747 }
748 continue;
749 }
750 _ => out.push(c),
751 }
752 i += 1;
753 }
754 out
755}
756
757const C_LIKE_TOP_LEVEL: &[&str] = &[
758 "import ",
759 "export ",
760 "module.exports",
761 "exports.",
762 "function ",
763 "async function ",
764 "class ",
765 "interface ",
766 "type ",
767 "enum ",
768 "declare ",
769 "const ",
770 "let ",
771 "var ",
772 "pub ",
773 "fn ",
774 "struct ",
775 "trait ",
776 "impl ",
777 "impl<",
778 "mod ",
779 "use ",
780 "static ",
781 "macro_rules!",
782 "package ",
783 "func ",
784 "namespace ",
785 "using ",
786 "#include",
787 "#[",
788 "@",
789 "public ",
790 "private ",
791 "protected ",
792 "abstract ",
793 "final ",
794 "override ",
795 "typedef ",
796 "extern ",
797 "template",
798 "def ",
799];
800
801const C_LIKE_MEMBER: &[&str] = &[
802 "pub ",
803 "fn ",
804 "public ",
805 "private ",
806 "protected ",
807 "static ",
808 "abstract ",
809 "override ",
810 "readonly ",
811 "async ",
812 "get ",
813 "set ",
814 "constructor",
815 "#[",
816 "@",
817];
818
819/// A member signature: an optionally qualified identifier followed by a
820/// parameter list.
821fn method_re() -> &'static regex::Regex {
822 static METHOD: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
823 METHOD.get_or_init(|| {
824 regex::Regex::new(r"^(?:(?:async|static|get|set|public|private|protected|override)\s+)*[A-Za-z_$][\w$]*\s*(?:<[^>]*>)?\s*\(").unwrap()
825 })
826}
827
828/// A property member (`key: …`, an optional `readonly`/`?`), whatever its
829/// value: an object literal's member, an interface member's type, a bare
830/// key a formatter broke away from its value. Scalar values are cut later.
831fn property_re() -> &'static regex::Regex {
832 static PROPERTY: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
833 PROPERTY.get_or_init(|| {
834 regex::Regex::new(r#"^(?:readonly\s+)?(?:['"]?)[A-Za-z_$][\w$]*(?:['"]?)\??\s*:"#).unwrap()
835 })
836}
837
838/// An interface's method member: a signature carrying a return type and no
839/// body (`load(id: string): Promise<void>`, an optional `?` after the name,
840/// a trailing `;`). A ternary statement (`f(a) ? b : c`) is not one: its
841/// `?` is followed by a space, a member's never is.
842fn typed_member_re() -> &'static regex::Regex {
843 static TYPED_MEMBER: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
844 TYPED_MEMBER.get_or_init(|| {
845 regex::Regex::new(
846 r"^(?:readonly\s+)?[A-Za-z_$][\w$]*\??\s*(?:<[^>]*>)?\s*\(.*\)\s*:\s*[^{;]+[;,]?$",
847 )
848 .unwrap()
849 })
850}
851
852fn typed_member(line: &str) -> bool {
853 typed_member_re().is_match(line) && !line.contains("? ")
854}
855
856/// An enum member (`Blue`, `Blue = 2,`): a capitalized bare identifier line.
857fn enum_member_re() -> &'static regex::Regex {
858 static ENUM_MEMBER: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
859 ENUM_MEMBER
860 .get_or_init(|| regex::Regex::new(r"^[A-Z][A-Za-z0-9_]*(?:\s*=\s*[^,]+)?,?$").unwrap())
861}
862
863/// Whether a kept depth-1 or depth-2 line was kept ONLY as a member
864/// signature (not by a keyword prefix, not as a property): such a line must
865/// open a body once joined, or it was a wrapped call statement, not a
866/// signature.
867fn member_signature_only(line: &str, depth: i32) -> bool {
868 depth >= 1
869 && !C_LIKE_MEMBER.iter().any(|p| line.starts_with(p))
870 && !property_re().is_match(line)
871 && !typed_member(line)
872 && method_re().is_match(line)
873}
874
875fn c_like_keeps(line: &str, depth: i32, next_opens_body: bool, properties: bool) -> bool {
876 let method = method_re();
877 let property = property_re();
878 // A member signature opens a body (`{`, on this line or, Allman-style,
879 // on the next), or is wrapped across lines (ends with `(` or `,`); a
880 // finished call statement ends with `)` and is followed by anything else.
881 let signature_shaped = |line: &str| {
882 method.is_match(line)
883 && !line.starts_with("if ")
884 && !line.starts_with("for ")
885 && !line.starts_with("while ")
886 && !line.starts_with("switch ")
887 && !line.starts_with("return ")
888 && !line.starts_with("catch ")
889 && (line.ends_with('{')
890 || line.ends_with('(')
891 || line.ends_with(',')
892 || (line.ends_with(')') && next_opens_body))
893 };
894 match depth {
895 0 => C_LIKE_TOP_LEVEL.iter().any(|p| line.starts_with(p)),
896 1 => {
897 C_LIKE_MEMBER.iter().any(|p| line.starts_with(p))
898 || signature_shaped(line)
899 || (properties && (property.is_match(line) || typed_member(line)))
900 || enum_member_re().is_match(line)
901 }
902 2 => signature_shaped(line),
903 _ => false,
904 }
905}
906
907fn python_keeps(line: &str, indent: usize) -> bool {
908 static CONSTANT: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
909 let constant = CONSTANT
910 .get_or_init(|| regex::Regex::new(r"^(?:[A-Z_][A-Z0-9_]*|__all__)\s*[:=]").unwrap());
911 let decl = line.starts_with("def ")
912 || line.starts_with("async def ")
913 || line.starts_with("class ")
914 || line.starts_with('@');
915 if indent == 0 {
916 decl || line.starts_with("import ") || line.starts_with("from ") || constant.is_match(line)
917 } else {
918 indent <= 4 && decl
919 }
920}
921
922/// For a Python module constant (`NAME = value`, `NAME: type = value`), the
923/// byte index just past the `=`; `None` for any other line.
924fn python_constant_cut(line: &str) -> Option<usize> {
925 static CONSTANT: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
926 let constant = CONSTANT.get_or_init(|| {
927 regex::Regex::new(r"^(?:[A-Z_][A-Z0-9_]*|__all__)(?:\s*:\s*[^=]+?)?\s*=").unwrap()
928 });
929 constant.find(line).map(|m| m.end())
930}
931
932fn paren_balance(s: &str) -> i32 {
933 s.chars()
934 .map(|c| match c {
935 '(' => 1,
936 ')' => -1,
937 _ => 0,
938 })
939 .sum()
940}
941
942fn brace_delta(s: &str) -> i32 {
943 s.chars()
944 .map(|c| match c {
945 '{' => 1,
946 '}' => -1,
947 _ => 0,
948 })
949 .sum()
950}
951
952/// Cut a declaration at its body: the first `{` outside parentheses for a
953/// C-like line (an import, `use`, or re-export list is not a body and is
954/// kept whole), the trailing `:` for Python.
955fn cut_at_body(sig: &str, family: Family) -> String {
956 match family {
957 Family::Python => sig.trim_end_matches(':').trim_end().to_string(),
958 _ if sig.starts_with("import ")
959 || sig.starts_with("use ")
960 || sig.starts_with("export {")
961 || sig.starts_with("export type {")
962 || sig.starts_with("export * ") =>
963 {
964 sig.trim_end().to_string()
965 }
966 _ => {
967 // The body opens at the first `{` outside parentheses, or, for
968 // an arrow whose body is an expression, right after the `=>`:
969 // an expression body is body whatever line it wraps onto.
970 let mut depth = 0i32;
971 let mut cut = sig.len();
972 let bytes = sig.as_bytes();
973 for (i, c) in sig.char_indices() {
974 match c {
975 '(' | '[' => depth += 1,
976 ')' | ']' => depth -= 1,
977 '{' if depth <= 0 => {
978 cut = i;
979 break;
980 }
981 '=' if depth <= 0 && bytes.get(i + 1) == Some(&b'>') => {
982 let rest = sig[i + 2..].trim_start();
983 if !rest.starts_with('{') {
984 cut = i + 2;
985 break;
986 }
987 }
988 _ => {}
989 }
990 }
991 sig[..cut].trim_end().to_string()
992 }
993 }
994}
995
996/// Normalize a kept declaration so that formatting inside it is invisible:
997/// trailing semicolons dropped, double quotes read as single quotes, runs of
998/// whitespace collapsed, and no whitespace next to punctuation — so
999/// `f(a,b)`, `f(a, b)` and a signature wrapped across lines digest alike,
1000/// while every token that carries meaning survives.
1001fn normalize_signature(sig: &str) -> String {
1002 let collapsed: Vec<&str> = sig
1003 .trim()
1004 .trim_end_matches(';')
1005 .split_whitespace()
1006 .collect();
1007 let joined = collapsed.join(" ").replace('"', "'");
1008 let is_punct = |c: char| "()[]{},;:=<>|&?!-+*/.".contains(c);
1009 let mut out = String::with_capacity(joined.len());
1010 let chars: Vec<char> = joined.chars().collect();
1011 for (i, &c) in chars.iter().enumerate() {
1012 if c == ' ' {
1013 let before = chars[..i].iter().rev().find(|x| **x != ' ').copied();
1014 let after = chars[i + 1..].iter().find(|x| **x != ' ').copied();
1015 if before.is_some_and(is_punct) || after.is_some_and(is_punct) {
1016 continue;
1017 }
1018 }
1019 out.push(c);
1020 }
1021 // Trailing commas are a formatter's choice, never a signature's: drop
1022 // one before a closing bracket and at the end of the line.
1023 let out = out
1024 .replace(",)", ")")
1025 .replace(",]", "]")
1026 .replace(",}", "}")
1027 .replace(",>", ">");
1028 let out = out.trim_end_matches(',').to_string();
1029 // A union type wrapped by a formatter leads its first member with `|`.
1030 let out = out.replace("=|", "=");
1031 // A kept line that opens a body keeps nothing of the brace itself.
1032 let out = out.trim_end_matches('{').trim_end().to_string();
1033 // Formatter defaults that are not signatures: a quoted property key
1034 // reads as the bare key; `(x)=>` reads as `x=>`; a Python import list's
1035 // parentheses (black's wrapped form) vanish.
1036 static QUOTED_KEY: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
1037 static ARROW_PARENS: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
1038 let quoted_key =
1039 QUOTED_KEY.get_or_init(|| regex::Regex::new(r"^'([A-Za-z_$][\w$]*)':").unwrap());
1040 let arrow_parens =
1041 ARROW_PARENS.get_or_init(|| regex::Regex::new(r"\(([A-Za-z_$][\w$]*)\)=>").unwrap());
1042 let out = quoted_key.replace(&out, "$1:").into_owned();
1043 let out = arrow_parens.replace_all(&out, "$1=>").into_owned();
1044 // A scalar property value (`name: 'Auth'`, `port: 3000`) is body, exactly
1045 // as a one-line literal's members are: keep the key alone.
1046 static SCALAR_PROPERTY: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
1047 let scalar = SCALAR_PROPERTY
1048 .get_or_init(|| regex::Regex::new(r#"^([A-Za-z_$][\w$]*:)(?:'|`|-?\d)"#).unwrap());
1049 let out = match scalar.captures(&out) {
1050 Some(caps) => caps[1].to_string(),
1051 None => out,
1052 };
1053 if out.starts_with("from ") || out.starts_with("import ") {
1054 return out
1055 .replace('(', " ")
1056 .replace(')', "")
1057 .split_whitespace()
1058 .collect::<Vec<_>>()
1059 .join(" ");
1060 }
1061 out
1062}
1063
1064/// A top-level binding whose value is not a function is cut right after its
1065/// `=` (and a default export that is not a function or object literal right
1066/// after `default`): the value is body, so its wrapping, its operators and
1067/// its literal shape never reach the digest. A function-valued binding keeps
1068/// its signature. `None` when the line is not such a binding.
1069fn cut_value_binding(line: &str) -> Option<String> {
1070 static BINDING: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
1071 static DEFAULT: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
1072 let binding = BINDING.get_or_init(|| {
1073 regex::Regex::new(
1074 r"^((?:(?:export\s+)?(?:pub(?:\([^)]*\))?\s+)?(?:(?:static|readonly|private|public|protected|declare|override|const|let|var)\s+)*(?:[A-Za-z_$][\w$]*|\{[^}]*\}|\[[^\]]*\])(?:\s*:\s*[^=]+?)?|(?:module\.)?exports(?:\.[A-Za-z_$][\w$]*)?)\s*=)\s*(.*)$",
1075 )
1076 .unwrap()
1077 });
1078 let default =
1079 DEFAULT.get_or_init(|| regex::Regex::new(r"^(export\s+default)\s+(.*)$").unwrap());
1080 let function_like = |value: &str| {
1081 static ARROW: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
1082 let arrow = ARROW
1083 .get_or_init(|| regex::Regex::new(r"^(?:async\s+)?[A-Za-z_$][\w$]*\s*=>").unwrap());
1084 value.starts_with('(')
1085 || value.starts_with("async ")
1086 || value.starts_with("async(")
1087 || value.starts_with("function")
1088 || value.starts_with("class")
1089 || arrow.is_match(value)
1090 };
1091 if let Some(caps) = binding.captures(line) {
1092 let value = caps[2].trim();
1093 // The `=` of an arrow `=>` (a property whose type annotation the
1094 // regex read as `key: (params)`) is not an assignment.
1095 if value.starts_with('>') {
1096 return None;
1097 }
1098 // A module's object-literal export (`module.exports = {`) is an
1099 // interface container like `export default {`: its members stay.
1100 let module_export = caps[1].starts_with("exports") || caps[1].starts_with("module.exports");
1101 // An empty value means a formatter broke it onto the next line:
1102 // still a value, still body (the caller skips that line).
1103 if function_like(value) || (module_export && value.starts_with('{')) {
1104 return None;
1105 }
1106 return Some(caps[1].to_string());
1107 }
1108 if let Some(caps) = default.captures(line) {
1109 let value = caps[2].trim();
1110 if value.is_empty() || value.starts_with('{') || function_like(value) {
1111 return None;
1112 }
1113 return Some(caps[1].to_string());
1114 }
1115 None
1116}
1117
1118fn angle_balance(s: &str) -> i32 {
1119 // Generics only: `->` and `=>` carry a `>` that is not a bracket.
1120 let s = s.replace("->", " ").replace("=>", " ");
1121 s.chars()
1122 .map(|c| match c {
1123 '<' => 1,
1124 '>' => -1,
1125 _ => 0,
1126 })
1127 .sum::<i32>()
1128 .max(0)
1129}
1130
1131fn bracket_balance(s: &str) -> i32 {
1132 s.chars()
1133 .map(|c| match c {
1134 '[' => 1,
1135 ']' => -1,
1136 _ => 0,
1137 })
1138 .sum()
1139}
1140
1141/// A binding whose destructuring pattern a formatter wrapped: the pattern
1142/// opens on the binding line (`const {`, `let [`) and closes on a later one.
1143fn opens_destructure(line: &str) -> bool {
1144 static DESTRUCTURE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
1145 let re = DESTRUCTURE
1146 .get_or_init(|| regex::Regex::new(r"^(?:export\s+)?(?:const|let|var)\s+[\{\[]").unwrap());
1147 re.is_match(line) && brace_delta(line) + bracket_balance(line) > 0
1148}
1149
1150/// An import, `use`, or re-export list wraps across lines on its braces;
1151/// nothing else joins on a brace (a brace elsewhere opens a body).
1152fn is_list_declaration(sig: &str) -> bool {
1153 sig.starts_with("import ")
1154 || sig.starts_with("use ")
1155 || sig.starts_with("export {")
1156 || sig.starts_with("export type {")
1157}
1158
1159fn declaration_lines(stripped: &str, family: Family) -> String {
1160 let lines: Vec<&str> = stripped.lines().collect();
1161 let mut out: Vec<String> = Vec::new();
1162 let mut depth: i32 = 0;
1163 // After a binding whose value was cut as body, the value's own lines
1164 // are skipped whole until every bracket the value opened has closed:
1165 // (brace, bracket, paren) balances accumulated from the binding line.
1166 let mut body_skip: Option<(i32, i32, i32)> = None;
1167 let mut i = 0;
1168 while i < lines.len() {
1169 let raw = lines[i];
1170 let line = raw.trim();
1171 if line.is_empty() {
1172 i += 1;
1173 continue;
1174 }
1175 if let Some((braces, brackets, parens)) = body_skip {
1176 let braces = braces + brace_delta(raw);
1177 let brackets = brackets + bracket_balance(raw);
1178 let parens = parens + paren_balance(raw);
1179 depth += brace_delta(raw);
1180 body_skip = if braces <= 0 && brackets <= 0 && parens <= 0 {
1181 None
1182 } else {
1183 Some((braces, brackets, parens))
1184 };
1185 i += 1;
1186 continue;
1187 }
1188 let indent = raw.len() - raw.trim_start().len();
1189 let next_opens_body = lines[i + 1..]
1190 .iter()
1191 .map(|l| l.trim())
1192 .find(|l| !l.is_empty())
1193 .is_some_and(|l| l.starts_with('{'));
1194 let keep = match family {
1195 Family::Python => python_keeps(line, indent),
1196 _ => c_like_keeps(line, depth, next_opens_body, family != Family::Rust),
1197 };
1198 if keep
1199 && family == Family::Python
1200 && indent == 0
1201 && let Some(eq) = python_constant_cut(line)
1202 {
1203 // A module constant's value is body, as a JS binding's is.
1204 out.push(normalize_signature(&line[..eq]));
1205 i += 1;
1206 continue;
1207 }
1208 // A destructuring pattern a formatter wrapped (`const {\n a,\n b,\n} = …`)
1209 // joins across its brackets before the binding rule sees it, so the
1210 // names inside are interface in the wrapped form as in the one-line form.
1211 let mut binding_end = i;
1212 let destructured = if keep && family != Family::Python && opens_destructure(line) {
1213 let mut joined = line.to_string();
1214 while brace_delta(&joined) + bracket_balance(&joined) > 0
1215 && binding_end + 1 < lines.len()
1216 && binding_end - i < 60
1217 {
1218 binding_end += 1;
1219 if lines[binding_end].trim().is_empty() {
1220 continue;
1221 }
1222 joined.push(' ');
1223 joined.push_str(lines[binding_end].trim());
1224 }
1225 Some(joined)
1226 } else {
1227 None
1228 };
1229 let binding_line = destructured.as_deref().unwrap_or(line);
1230 if keep
1231 && family != Family::Python
1232 && !(depth >= 1 && enum_member_re().is_match(line))
1233 && let Some(cut) = cut_value_binding(binding_line)
1234 {
1235 // (An enum member's explicit value is interface, not a binding's
1236 // body: `Green = 2,` keeps its value.)
1237 // The value is body: keep the binding's name, count its braces,
1238 // and skip the value's lines until every bracket it opened closes.
1239 out.push(normalize_signature(&cut));
1240 let span = &lines[i..=binding_end];
1241 let mut opened = (
1242 span.iter().map(|l| brace_delta(l)).sum::<i32>(),
1243 span.iter().map(|l| bracket_balance(l)).sum::<i32>(),
1244 span.iter().map(|l| paren_balance(l)).sum::<i32>(),
1245 );
1246 depth += opened.0;
1247 i = binding_end + 1;
1248 if binding_line.trim_end().ends_with('=') {
1249 // The value starts on the next non-empty line: consume it
1250 // and whatever it opens.
1251 while i < lines.len() && lines[i].trim().is_empty() {
1252 i += 1;
1253 }
1254 if i < lines.len() {
1255 let v = lines[i];
1256 opened = (
1257 opened.0 + brace_delta(v),
1258 opened.1 + bracket_balance(v),
1259 opened.2 + paren_balance(v),
1260 );
1261 depth += brace_delta(v);
1262 i += 1;
1263 }
1264 }
1265 if opened.0 > 0 || opened.1 > 0 || opened.2 > 0 {
1266 body_skip = Some(opened);
1267 }
1268 continue;
1269 }
1270 if keep {
1271 // A signature wrapped across lines joins on its parentheses, a
1272 // wrapped array literal on its brackets, a wrapped import or
1273 // export list on its braces — so a formatter's line width is
1274 // invisible and a member added inside a wrapped list is not.
1275 let mut sig = line.to_string();
1276 let mut j = i;
1277 let c_like = family != Family::Python;
1278 // Continuation: an open bracket of any kind, or (C-like) a next
1279 // line a formatter led with an operator (`|` in a union type,
1280 // `.` in a chain, `?`/`:` in a ternary, `&&`/`||`/`+`).
1281 let next_is_operator_led = |k: usize| {
1282 c_like
1283 && lines[k + 1..]
1284 .iter()
1285 .map(|l| l.trim())
1286 .find(|l| !l.is_empty())
1287 .is_some_and(|l| {
1288 l.starts_with('|')
1289 || l.starts_with('&')
1290 || l.starts_with('?')
1291 || l.starts_with(':')
1292 || l.starts_with('.')
1293 || l.starts_with('+')
1294 })
1295 };
1296 // A line that ends by opening a body (`{`) joins nothing: what
1297 // follows is body, even inside a callback argument's parentheses.
1298 // An import or export list's brace opens a list, not a body.
1299 // A line that ends in `=` or `:` (a formatter broke the value or
1300 // the type onto the next line) joins its continuation.
1301 let ends_open = |s: &str| {
1302 let t = s.trim_end();
1303 c_like && (t.ends_with('=') || t.ends_with(':'))
1304 };
1305 while (!sig.trim_end().ends_with('{') || is_list_declaration(&sig))
1306 && (paren_balance(&sig) > 0
1307 || bracket_balance(&sig) > 0
1308 || (c_like && angle_balance(&sig) > 0)
1309 || (is_list_declaration(&sig) && brace_delta(&sig) > 0)
1310 || ends_open(&sig)
1311 || next_is_operator_led(j))
1312 && j + 1 < lines.len()
1313 && j - i < 60
1314 {
1315 j += 1;
1316 if lines[j].trim().is_empty() {
1317 continue;
1318 }
1319 sig.push(' ');
1320 sig.push_str(lines[j].trim());
1321 }
1322 // A line kept only as a member signature must open a body once
1323 // joined; a wrapped call statement joins to `name(args)` with no
1324 // body after it and is dropped, as its one-line form would be.
1325 // Judged on the joined signature: a typed member a formatter
1326 // wrapped (`load(\n id: string,\n): Promise<void>`) is typed.
1327 let opens_body = sig.trim_end().ends_with('{')
1328 || sig.contains("=>")
1329 || lines[j + 1..]
1330 .iter()
1331 .map(|l| l.trim())
1332 .find(|l| !l.is_empty())
1333 .is_some_and(|l| l.starts_with('{'));
1334 if c_like && member_signature_only(&sig, depth) && !opens_body {
1335 for l in &lines[i..=j] {
1336 depth += brace_delta(l);
1337 }
1338 i = j + 1;
1339 continue;
1340 }
1341 out.push(normalize_signature(&cut_at_body(&sig, family)));
1342 if c_like {
1343 for l in &lines[i..=j] {
1344 depth += brace_delta(l);
1345 }
1346 }
1347 i = j + 1;
1348 } else {
1349 if family != Family::Python {
1350 depth += brace_delta(raw);
1351 }
1352 i += 1;
1353 }
1354 }
1355 out.join("\n")
1356}
1357
1358/// The load-bearing sections of a type, in the type's declared order:
1359///
1360/// 1. the sections declaring `load_bearing: true`, when any does;
1361/// 2. otherwise the required sections, minus any declaring
1362/// `load_bearing: false`, when that leaves at least one;
1363/// 3. otherwise every section — a type with no required sections and no
1364/// declaration has no notes/claim split the engine can honour, and an
1365/// empty set would hash to a constant that never drifts.
1366pub fn load_bearing_sections(
1367 type_def: &memstead_schema::types::TypeDefinition,
1368) -> Vec<&memstead_schema::types::SectionDef> {
1369 let explicit: Vec<_> = type_def
1370 .sections
1371 .iter()
1372 .filter(|s| s.load_bearing == Some(true))
1373 .collect();
1374 if !explicit.is_empty() {
1375 return explicit;
1376 }
1377 let required: Vec<_> = type_def
1378 .sections
1379 .iter()
1380 .filter(|s| s.required && s.load_bearing != Some(false))
1381 .collect();
1382 if !required.is_empty() {
1383 return required;
1384 }
1385 type_def.sections.iter().collect()
1386}
1387
1388/// The `entity-load-bearing` prepared form: the entity's load-bearing
1389/// sections serialized stably — each as `## <key>`, a blank line, the
1390/// trimmed content, a blank line — in the type's declared section order.
1391/// Keyed by section KEY (not heading) so a heading rename in the schema
1392/// does not read as a content change; a section the entity does not carry
1393/// is skipped. Title, metadata, and relationships are outside the form:
1394/// the anchor's artifact is the entity id, and a rename orphans the anchor
1395/// on its own. Without a type definition (a type the mem's schema does not
1396/// declare) every section the entity carries is load-bearing, in the
1397/// entity's own order.
1398pub fn entity_load_bearing_form(
1399 entity: &Entity,
1400 type_def: Option<&memstead_schema::types::TypeDefinition>,
1401) -> String {
1402 fn push(out: &mut String, key: &str, content: &str) {
1403 out.push_str("## ");
1404 out.push_str(key);
1405 out.push_str("\n\n");
1406 out.push_str(content.trim());
1407 out.push_str("\n\n");
1408 }
1409 let mut out = String::new();
1410 match type_def {
1411 Some(td) => {
1412 for section in load_bearing_sections(td) {
1413 if let Some(content) = entity.sections.get(§ion.key) {
1414 push(&mut out, §ion.key, content);
1415 }
1416 }
1417 }
1418 None => {
1419 for (key, content) in &entity.sections {
1420 push(&mut out, key, content);
1421 }
1422 }
1423 }
1424 out
1425}
1426
1427/// The prepared hash of ONE load-bearing section, in the same unit form
1428/// [`entity_load_bearing_form`] serializes it into (`## <key>`, a blank
1429/// line, the trimmed content). The key rides inside the hashed bytes, so
1430/// the same prose moved to another section key is a different mark.
1431///
1432/// The per-section grain exists because the whole-form hash collapses a
1433/// type's load-bearing sections to one bit: an owner who rewrites one of
1434/// three sections would clear a mark that still covers the other two, and
1435/// a contributor's remaining claims would be served as the workspace's own
1436/// prose.
1437pub fn entity_section_prepared_hash(key: &str, content: &str) -> String {
1438 prepared_content_hash(format!("## {key}\n\n{}\n\n", content.trim()).as_bytes())
1439}
1440
1441/// One prepared hash per load-bearing section the entity carries, keyed by
1442/// section key. The section set is the type's
1443/// ([`load_bearing_sections`]), or every section the entity carries when
1444/// the type is unknown, matching [`entity_load_bearing_form`].
1445///
1446/// Empty sections are skipped deliberately. A mark over an empty section
1447/// would match every entity whose same section is empty, which is the one
1448/// way this comparison could brand unrelated content.
1449pub fn entity_load_bearing_section_marks(
1450 entity: &Entity,
1451 type_def: Option<&memstead_schema::types::TypeDefinition>,
1452) -> std::collections::BTreeMap<String, String> {
1453 let mut out = std::collections::BTreeMap::new();
1454 let mut add = |key: &String, content: &String| {
1455 if !content.trim().is_empty() {
1456 out.insert(key.clone(), entity_section_prepared_hash(key, content));
1457 }
1458 };
1459 match type_def {
1460 Some(td) => {
1461 for section in load_bearing_sections(td) {
1462 if let Some(content) = entity.sections.get(§ion.key) {
1463 add(§ion.key, content);
1464 }
1465 }
1466 }
1467 None => {
1468 for (key, content) in &entity.sections {
1469 add(key, content);
1470 }
1471 }
1472 }
1473 out
1474}
1475
1476/// Touchpoint A for the `entity` grain: the prepared-content hash of an
1477/// entity under the source's declared preparation. `None` declares
1478/// nothing — the canonical rendered markdown, byte-for-byte today's form.
1479/// [`ENTITY_LOAD_BEARING`] hashes [`entity_load_bearing_form`]. An
1480/// identifier the registry does not know yields `None`: the form cannot be
1481/// computed, and observation reports the anchor unobserved rather than
1482/// hashing a fabricated form (validation refuses such a record at every
1483/// edit path; only a hand-edited file reaches here).
1484pub fn entity_prepared_hash(
1485 entity: &Entity,
1486 type_def: Option<&memstead_schema::types::TypeDefinition>,
1487 preparation: Option<&str>,
1488) -> Option<String> {
1489 match entity_prepared(entity, type_def, preparation, None) {
1490 PathPrepared::Hash(h) => Some(h),
1491 PathPrepared::NoHash | PathPrepared::UnitAbsent => None,
1492 }
1493}
1494
1495/// [`entity_prepared_hash`] with the artifact's `#<locator>` in hand: under
1496/// [`QUOTED_PHRASE`] the locator is the phrase and the prepared form is the
1497/// phrase where the entity's canonical markdown still carries it
1498/// ([`PathPrepared::UnitAbsent`] where it does not); every other
1499/// preparation ignores the locator and answers as [`entity_prepared_hash`]
1500/// does, [`PathPrepared::NoHash`] for an identifier the registry does not
1501/// prepare entities under.
1502pub fn entity_prepared(
1503 entity: &Entity,
1504 type_def: Option<&memstead_schema::types::TypeDefinition>,
1505 preparation: Option<&str>,
1506 locator: Option<&str>,
1507) -> PathPrepared {
1508 let form = match preparation {
1509 None => crate::render::render_entity_markdown(entity, None),
1510 Some(ENTITY_LOAD_BEARING) => entity_load_bearing_form(entity, type_def),
1511 Some(QUOTED_PHRASE) => {
1512 let rendered = crate::render::render_entity_markdown(entity, None);
1513 return match locator {
1514 Some(phrase) => quoted_phrase_prepared(phrase, &rendered),
1515 None => PathPrepared::Hash(prepared_content_hash(rendered.as_bytes())),
1516 };
1517 }
1518 Some(_) => return PathPrepared::NoHash,
1519 };
1520 PathPrepared::Hash(prepared_content_hash(form.as_bytes()))
1521}
1522
1523// ---------------------------------------------------------------------------
1524// Touchpoint B: delivery units
1525// ---------------------------------------------------------------------------
1526
1527/// One delivery unit of a file under a delivery preparation.
1528#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1529pub struct DeliveryUnit {
1530 /// The unit's key, unique within its file; the addressed form is
1531 /// `<path>#<key>` ([`unit_id`]).
1532 pub key: String,
1533 /// The intrinsic key the source's units sort by (a normalized stamp for
1534 /// [`DATED_ENTRIES`]); empty for a [`WHOLE_FILE_UNIT`].
1535 pub order_key: String,
1536 /// First line of the unit, 1-based.
1537 pub start_line: usize,
1538 /// Last line of the unit, 1-based, inclusive.
1539 pub end_line: usize,
1540 /// The prepared-content hash of the unit's text — what a span anchor
1541 /// over the unit records, and what a change run compares.
1542 pub hash: String,
1543}
1544
1545/// How a unit changed between two states of its file.
1546#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1547#[serde(rename_all = "lowercase")]
1548pub enum UnitChange {
1549 /// The key is new.
1550 Added,
1551 /// The key existed; the unit's text changed.
1552 Modified,
1553 /// The key is gone.
1554 Deleted,
1555}
1556
1557/// The addressed form of a unit: `<path>#<key>`.
1558pub fn unit_id(path: &str, key: &str) -> String {
1559 format!("{path}#{key}")
1560}
1561
1562/// Split an artifact id into its path and, when it addresses a unit, the
1563/// unit key after the first `#`.
1564pub fn split_unit_id(id: &str) -> (&str, Option<&str>) {
1565 match id.find('#') {
1566 Some(cut) => (&id[..cut], Some(&id[cut + 1..])),
1567 None => (id, None),
1568 }
1569}
1570
1571/// Touchpoint B: the delivery units of one file's content under a delivery
1572/// preparation, in file order. `None` when `preparation` is not a registered
1573/// delivery preparation (the caller keeps file-granularity delivery).
1574pub fn unitize(preparation: &str, content: &str) -> Option<Vec<DeliveryUnit>> {
1575 match preparation {
1576 DATED_ENTRIES => Some(dated_entries(content)),
1577 _ => None,
1578 }
1579}
1580
1581/// The text of one unit, lines `start_line..=end_line` of `content`.
1582pub fn unit_text(content: &str, unit: &DeliveryUnit) -> String {
1583 content
1584 .lines()
1585 .skip(unit.start_line.saturating_sub(1))
1586 .take(unit.end_line + 1 - unit.start_line.max(1))
1587 .collect::<Vec<_>>()
1588 .join("\n")
1589}
1590
1591/// The units that differ between two states of one file, keyed by unit key:
1592/// a key only in `after` is [`UnitChange::Added`], a key in both whose hash
1593/// differs is [`UnitChange::Modified`] (the `after` unit), a key only in
1594/// `before` is [`UnitChange::Deleted`] (the `before` unit, so its order key
1595/// still places it). Unchanged units are not delivered again.
1596pub fn diff_units(
1597 before: &[DeliveryUnit],
1598 after: &[DeliveryUnit],
1599) -> Vec<(DeliveryUnit, UnitChange)> {
1600 let old: std::collections::BTreeMap<&str, &DeliveryUnit> =
1601 before.iter().map(|u| (u.key.as_str(), u)).collect();
1602 let new: std::collections::BTreeMap<&str, &DeliveryUnit> =
1603 after.iter().map(|u| (u.key.as_str(), u)).collect();
1604 let mut out = Vec::new();
1605 for u in after {
1606 match old.get(u.key.as_str()) {
1607 None => out.push((u.clone(), UnitChange::Added)),
1608 Some(prev) if prev.hash != u.hash => out.push((u.clone(), UnitChange::Modified)),
1609 Some(_) => {}
1610 }
1611 }
1612 for u in before {
1613 if !new.contains_key(u.key.as_str()) {
1614 out.push((u.clone(), UnitChange::Deleted));
1615 }
1616 }
1617 out
1618}
1619
1620fn dated_entries(content: &str) -> Vec<DeliveryUnit> {
1621 let lines: Vec<&str> = content.lines().collect();
1622 let starts: Vec<(usize, String)> = lines
1623 .iter()
1624 .enumerate()
1625 .filter_map(|(i, line)| leading_stamp(line).map(|stamp| (i, stamp)))
1626 .collect();
1627 if starts.is_empty() {
1628 return vec![DeliveryUnit {
1629 key: WHOLE_FILE_UNIT.to_string(),
1630 order_key: String::new(),
1631 start_line: 1,
1632 end_line: lines.len().max(1),
1633 hash: prepared_content_hash(content.as_bytes()),
1634 }];
1635 }
1636 let mut seen: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
1637 let mut units = Vec::with_capacity(starts.len());
1638 for (n, (start, stamp)) in starts.iter().enumerate() {
1639 // The preamble (anything before the first stamp) folds into the
1640 // first unit: it is context for the entries, never a unit of its own.
1641 let from = if n == 0 { 0 } else { *start };
1642 let to = starts.get(n + 1).map_or(lines.len(), |(next, _)| *next);
1643 let text = lines[from..to].join("\n");
1644 let count = seen
1645 .entry(stamp.clone())
1646 .and_modify(|c| *c += 1)
1647 .or_insert(1);
1648 let key = if *count == 1 {
1649 stamp.clone()
1650 } else {
1651 format!("{stamp}.{count}")
1652 };
1653 units.push(DeliveryUnit {
1654 key,
1655 order_key: stamp.clone(),
1656 start_line: from + 1,
1657 end_line: to,
1658 hash: prepared_content_hash(text.as_bytes()),
1659 });
1660 }
1661 units
1662}
1663
1664/// The ISO stamp a line opens with (after leading markdown markers),
1665/// normalized to `YYYY-MM-DDTHH:MM:SS`; `None` when the line opens with
1666/// anything else or the stamp is out of range.
1667fn leading_stamp(line: &str) -> Option<String> {
1668 static STAMP: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
1669 let re = STAMP.get_or_init(|| {
1670 regex::Regex::new(
1671 r"^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)?\b",
1672 )
1673 .expect("the stamp regex compiles")
1674 });
1675 let s = line.trim_start_matches(|c: char| {
1676 c.is_whitespace() || matches!(c, '#' | '-' | '*' | '>' | '[' | '(' | '|' | '`' | '+')
1677 });
1678 let caps = re.captures(s)?;
1679 let num = |i: usize| -> u32 {
1680 caps.get(i)
1681 .map(|m| m.as_str().parse().unwrap_or(0))
1682 .unwrap_or(0)
1683 };
1684 let (y, mo, d, h, mi, sec) = (num(1), num(2), num(3), num(4), num(5), num(6));
1685 let days_in_month = match mo {
1686 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
1687 4 | 6 | 9 | 11 => 30,
1688 2 => 29,
1689 _ => return None,
1690 };
1691 if !(1..=days_in_month).contains(&d) || h > 23 || mi > 59 || sec > 59 {
1692 return None;
1693 }
1694 Some(format!("{y:04}-{mo:02}-{d:02}T{h:02}:{mi:02}:{sec:02}"))
1695}
1696
1697#[cfg(test)]
1698mod tests;