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, and the ends are trimmed.
386///
387/// Digits, decimal marks, units, case and word order are untouched: beyond
388/// this form the match is exact, and no similarity threshold exists on any
389/// path. Case folding is deliberately absent (capitalisation carries meaning
390/// in the sources' languages) and so is NFKC (it would equate `m²` with
391/// `m2`, a changed unit).
392pub fn canonical_span_form(text: &str) -> String {
393 use unicode_normalization::UnicodeNormalization;
394 let composed: String = text.nfc().collect();
395 let mut mapped = String::with_capacity(composed.len());
396 for c in composed.chars() {
397 match c {
398 '\u{00AD}' => {}
399 '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}' | '\u{2039}' | '\u{203A}' => {
400 mapped.push('\'');
401 }
402 '\u{201C}' | '\u{201D}' | '\u{201E}' | '\u{201F}' | '\u{00AB}' | '\u{00BB}' => {
403 mapped.push('"');
404 }
405 '\u{2010}' | '\u{2011}' | '\u{2012}' | '\u{2013}' | '\u{2014}' | '\u{2015}'
406 | '\u{2212}' => mapped.push('-'),
407 '\u{FB00}' => mapped.push_str("ff"),
408 '\u{FB01}' => mapped.push_str("fi"),
409 '\u{FB02}' => mapped.push_str("fl"),
410 '\u{FB03}' => mapped.push_str("ffi"),
411 '\u{FB04}' => mapped.push_str("ffl"),
412 '\u{FB05}' | '\u{FB06}' => mapped.push_str("st"),
413 other => mapped.push(other),
414 }
415 }
416 // A hyphen at a line end joins the word it split: the hyphen, the break
417 // and any indentation that follows go.
418 let mut joined = String::with_capacity(mapped.len());
419 let mut chars = mapped.chars().peekable();
420 while let Some(c) = chars.next() {
421 if c == '-' {
422 let mut ahead = chars.clone();
423 let mut consumed = 0usize;
424 if ahead.peek() == Some(&'\r') {
425 ahead.next();
426 consumed += 1;
427 }
428 if ahead.peek() == Some(&'\n') {
429 ahead.next();
430 consumed += 1;
431 while matches!(ahead.peek(), Some(' ') | Some('\t')) {
432 ahead.next();
433 consumed += 1;
434 }
435 for _ in 0..consumed {
436 chars.next();
437 }
438 continue;
439 }
440 }
441 joined.push(c);
442 }
443 let mut out = String::with_capacity(joined.len());
444 let mut pending_space = false;
445 for c in joined.chars() {
446 if c.is_whitespace() {
447 pending_space = !out.is_empty();
448 } else {
449 if pending_space {
450 out.push(' ');
451 pending_space = false;
452 }
453 out.push(c);
454 }
455 }
456 out
457}
458
459/// Whether `span` occurs in `text`, both taken in the canonical span form.
460/// An empty span (empty after canonicalisation) occurs nowhere: it names no
461/// words, and the write path refuses it before it can be stored.
462pub fn span_occurs(span: &str, text: &str) -> bool {
463 let span = canonical_span_form(span);
464 if span.is_empty() {
465 return false;
466 }
467 canonical_span_form(text).contains(span.as_str())
468}
469
470/// The hash a span row records for its span: the house prepared-content
471/// hash over the canonical span form, so two writers quoting the same words
472/// with different quote marks or line breaks record the same value.
473pub fn span_hash(span: &str) -> String {
474 prepared_content_hash(canonical_span_form(span).as_bytes())
475}
476
477/// The code map of a tree: one line per scoped file under it, `<file digest
478/// hash> <path>`, in path order — hashed by the caller through
479/// [`prepared_content_hash`]. A file joining, leaving, or changing its
480/// interface changes the tree's map; an implementation edit does not.
481pub fn code_map_tree_digest(files: &[(String, String)]) -> String {
482 let mut rows: Vec<(&str, &str)> = files
483 .iter()
484 .map(|(path, text)| (path.as_str(), text.as_str()))
485 .collect();
486 rows.sort();
487 rows.iter()
488 .map(|(path, text)| {
489 format!(
490 "{} {path}",
491 prepared_content_hash(code_map_digest(path, text).as_bytes())
492 )
493 })
494 .collect::<Vec<_>>()
495 .join("\n")
496}
497
498/// The plain digest of a tree: one line per scoped file under it,
499/// `<prepared-content hash> <path>`, in path order — hashed by the caller
500/// through [`prepared_content_hash`]. Any byte change in any scoped file,
501/// and any file joining or leaving the tree, changes the digest — the same
502/// whole-content posture a `file` anchor has, lifted to the directory. This
503/// is the no-preparation counterpart of [`code_map_tree_digest`]; it is what
504/// lets a plain `tree` anchor adjudicate deterministically instead of
505/// resting in `recheck` forever.
506pub fn plain_tree_digest(files: &[(String, Vec<u8>)]) -> String {
507 let mut rows: Vec<(&str, &[u8])> = files
508 .iter()
509 .map(|(path, bytes)| (path.as_str(), bytes.as_slice()))
510 .collect();
511 rows.sort();
512 rows.iter()
513 .map(|(path, bytes)| format!("{} {path}", prepared_content_hash(bytes)))
514 .collect::<Vec<_>>()
515 .join("\n")
516}
517
518/// The interface digest of one file's text under [`CODE_MAP`].
519pub fn code_map_digest(path: &str, text: &str) -> String {
520 match family_of(path) {
521 Family::Text => text.to_string(),
522 Family::Json => serde_json::from_str::<serde_json::Value>(text)
523 .map(|v| v.to_string())
524 .unwrap_or_else(|_| text.to_string()),
525 Family::Vue => {
526 declaration_lines(&strip_c_comments(&vue_script_blocks(text)), Family::CLike)
527 }
528 Family::CLike => declaration_lines(&strip_c_comments(text), Family::CLike),
529 Family::Rust => declaration_lines(&strip_c_comments(text), Family::Rust),
530 Family::Python => declaration_lines(&strip_python_comments(text), Family::Python),
531 }
532}
533
534#[derive(Debug, Clone, Copy, PartialEq, Eq)]
535enum Family {
536 CLike,
537 /// C-like braces, but a struct field is interface only with `pub`
538 /// (a `key: Type` line without it is body), and enum variants are.
539 Rust,
540 Python,
541 Json,
542 Vue,
543 Text,
544}
545
546fn family_of(path: &str) -> Family {
547 let name = path.rsplit('/').next().unwrap_or(path);
548 let ext = match name.rsplit_once('.') {
549 Some((_, ext)) => ext.to_ascii_lowercase(),
550 None => return Family::Text,
551 };
552 match ext.as_str() {
553 "rs" => Family::Rust,
554 "js" | "mjs" | "cjs" | "jsx" | "ts" | "tsx" | "mts" | "cts" | "go" | "java" | "kt"
555 | "kts" | "swift" | "cs" | "c" | "h" | "cc" | "cpp" | "hpp" | "m" | "mm" | "php"
556 | "dart" | "scala" => Family::CLike,
557 "py" | "pyi" => Family::Python,
558 "json" => Family::Json,
559 "vue" | "svelte" => Family::Vue,
560 _ => Family::Text,
561 }
562}
563
564/// The concatenated `<script>` blocks of a single-file component (the
565/// template and styles are not interface).
566fn vue_script_blocks(text: &str) -> String {
567 let lower = text.to_ascii_lowercase();
568 let mut out = String::new();
569 let mut from = 0;
570 while let Some(open) = lower[from..].find("<script") {
571 let open = from + open;
572 let Some(tag_end) = lower[open..].find('>') else {
573 break;
574 };
575 let body_start = open + tag_end + 1;
576 let Some(close) = lower[body_start..].find("</script") else {
577 out.push_str(&text[body_start..]);
578 break;
579 };
580 out.push_str(&text[body_start..body_start + close]);
581 out.push('\n');
582 from = body_start + close + 8;
583 }
584 out
585}
586
587/// Strip `//` line comments and `/* */` block comments, outside string
588/// literals (a `'`/`"` string ends at its line; a template literal may span
589/// lines). Newlines are kept so line structure survives.
590fn strip_c_comments(text: &str) -> String {
591 let mut out = String::with_capacity(text.len());
592 let mut chars = text.chars().peekable();
593 let mut in_str: Option<char> = None;
594 let mut escape = false;
595 while let Some(c) = chars.next() {
596 if let Some(q) = in_str {
597 out.push(c);
598 if escape {
599 escape = false;
600 } else if c == '\\' {
601 escape = true;
602 } else if c == q || (c == '\n' && q != '`') {
603 in_str = None;
604 }
605 continue;
606 }
607 match c {
608 '"' | '\'' | '`' => {
609 in_str = Some(c);
610 out.push(c);
611 }
612 '/' => match chars.peek() {
613 Some('/') => {
614 for n in chars.by_ref() {
615 if n == '\n' {
616 out.push('\n');
617 break;
618 }
619 }
620 }
621 Some('*') => {
622 chars.next();
623 let mut prev = '\0';
624 for n in chars.by_ref() {
625 if n == '\n' {
626 out.push('\n');
627 }
628 if prev == '*' && n == '/' {
629 break;
630 }
631 prev = n;
632 }
633 }
634 _ => out.push(c),
635 },
636 _ => out.push(c),
637 }
638 }
639 out
640}
641
642/// Strip `#` comments outside strings and drop triple-quoted strings whole
643/// (docstrings and block literals are never interface).
644fn strip_python_comments(text: &str) -> String {
645 let mut out = String::with_capacity(text.len());
646 let bytes: Vec<char> = text.chars().collect();
647 let mut i = 0;
648 let mut in_str: Option<char> = None;
649 let mut triple: Option<char> = None;
650 while i < bytes.len() {
651 let c = bytes[i];
652 if let Some(q) = triple {
653 if c == q && i + 2 < bytes.len() && bytes[i + 1] == q && bytes[i + 2] == q {
654 triple = None;
655 i += 3;
656 continue;
657 }
658 if c == '\n' {
659 out.push('\n');
660 }
661 i += 1;
662 continue;
663 }
664 if let Some(q) = in_str {
665 out.push(c);
666 if c == '\\' && i + 1 < bytes.len() {
667 out.push(bytes[i + 1]);
668 i += 2;
669 continue;
670 }
671 if c == q || c == '\n' {
672 in_str = None;
673 }
674 i += 1;
675 continue;
676 }
677 match c {
678 '"' | '\'' => {
679 if i + 2 < bytes.len() && bytes[i + 1] == c && bytes[i + 2] == c {
680 triple = Some(c);
681 i += 3;
682 continue;
683 }
684 in_str = Some(c);
685 out.push(c);
686 }
687 '#' => {
688 while i < bytes.len() && bytes[i] != '\n' {
689 i += 1;
690 }
691 continue;
692 }
693 _ => out.push(c),
694 }
695 i += 1;
696 }
697 out
698}
699
700const C_LIKE_TOP_LEVEL: &[&str] = &[
701 "import ",
702 "export ",
703 "module.exports",
704 "exports.",
705 "function ",
706 "async function ",
707 "class ",
708 "interface ",
709 "type ",
710 "enum ",
711 "declare ",
712 "const ",
713 "let ",
714 "var ",
715 "pub ",
716 "fn ",
717 "struct ",
718 "trait ",
719 "impl ",
720 "impl<",
721 "mod ",
722 "use ",
723 "static ",
724 "macro_rules!",
725 "package ",
726 "func ",
727 "namespace ",
728 "using ",
729 "#include",
730 "#[",
731 "@",
732 "public ",
733 "private ",
734 "protected ",
735 "abstract ",
736 "final ",
737 "override ",
738 "typedef ",
739 "extern ",
740 "template",
741 "def ",
742];
743
744const C_LIKE_MEMBER: &[&str] = &[
745 "pub ",
746 "fn ",
747 "public ",
748 "private ",
749 "protected ",
750 "static ",
751 "abstract ",
752 "override ",
753 "readonly ",
754 "async ",
755 "get ",
756 "set ",
757 "constructor",
758 "#[",
759 "@",
760];
761
762/// A member signature: an optionally qualified identifier followed by a
763/// parameter list.
764fn method_re() -> &'static regex::Regex {
765 static METHOD: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
766 METHOD.get_or_init(|| {
767 regex::Regex::new(r"^(?:(?:async|static|get|set|public|private|protected|override)\s+)*[A-Za-z_$][\w$]*\s*(?:<[^>]*>)?\s*\(").unwrap()
768 })
769}
770
771/// A property member (`key: …`, an optional `readonly`/`?`), whatever its
772/// value: an object literal's member, an interface member's type, a bare
773/// key a formatter broke away from its value. Scalar values are cut later.
774fn property_re() -> &'static regex::Regex {
775 static PROPERTY: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
776 PROPERTY.get_or_init(|| {
777 regex::Regex::new(r#"^(?:readonly\s+)?(?:['"]?)[A-Za-z_$][\w$]*(?:['"]?)\??\s*:"#).unwrap()
778 })
779}
780
781/// An interface's method member: a signature carrying a return type and no
782/// body (`load(id: string): Promise<void>`, an optional `?` after the name,
783/// a trailing `;`). A ternary statement (`f(a) ? b : c`) is not one: its
784/// `?` is followed by a space, a member's never is.
785fn typed_member_re() -> &'static regex::Regex {
786 static TYPED_MEMBER: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
787 TYPED_MEMBER.get_or_init(|| {
788 regex::Regex::new(
789 r"^(?:readonly\s+)?[A-Za-z_$][\w$]*\??\s*(?:<[^>]*>)?\s*\(.*\)\s*:\s*[^{;]+[;,]?$",
790 )
791 .unwrap()
792 })
793}
794
795fn typed_member(line: &str) -> bool {
796 typed_member_re().is_match(line) && !line.contains("? ")
797}
798
799/// An enum member (`Blue`, `Blue = 2,`): a capitalized bare identifier line.
800fn enum_member_re() -> &'static regex::Regex {
801 static ENUM_MEMBER: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
802 ENUM_MEMBER
803 .get_or_init(|| regex::Regex::new(r"^[A-Z][A-Za-z0-9_]*(?:\s*=\s*[^,]+)?,?$").unwrap())
804}
805
806/// Whether a kept depth-1 or depth-2 line was kept ONLY as a member
807/// signature (not by a keyword prefix, not as a property): such a line must
808/// open a body once joined, or it was a wrapped call statement, not a
809/// signature.
810fn member_signature_only(line: &str, depth: i32) -> bool {
811 depth >= 1
812 && !C_LIKE_MEMBER.iter().any(|p| line.starts_with(p))
813 && !property_re().is_match(line)
814 && !typed_member(line)
815 && method_re().is_match(line)
816}
817
818fn c_like_keeps(line: &str, depth: i32, next_opens_body: bool, properties: bool) -> bool {
819 let method = method_re();
820 let property = property_re();
821 // A member signature opens a body (`{`, on this line or, Allman-style,
822 // on the next), or is wrapped across lines (ends with `(` or `,`); a
823 // finished call statement ends with `)` and is followed by anything else.
824 let signature_shaped = |line: &str| {
825 method.is_match(line)
826 && !line.starts_with("if ")
827 && !line.starts_with("for ")
828 && !line.starts_with("while ")
829 && !line.starts_with("switch ")
830 && !line.starts_with("return ")
831 && !line.starts_with("catch ")
832 && (line.ends_with('{')
833 || line.ends_with('(')
834 || line.ends_with(',')
835 || (line.ends_with(')') && next_opens_body))
836 };
837 match depth {
838 0 => C_LIKE_TOP_LEVEL.iter().any(|p| line.starts_with(p)),
839 1 => {
840 C_LIKE_MEMBER.iter().any(|p| line.starts_with(p))
841 || signature_shaped(line)
842 || (properties && (property.is_match(line) || typed_member(line)))
843 || enum_member_re().is_match(line)
844 }
845 2 => signature_shaped(line),
846 _ => false,
847 }
848}
849
850fn python_keeps(line: &str, indent: usize) -> bool {
851 static CONSTANT: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
852 let constant = CONSTANT
853 .get_or_init(|| regex::Regex::new(r"^(?:[A-Z_][A-Z0-9_]*|__all__)\s*[:=]").unwrap());
854 let decl = line.starts_with("def ")
855 || line.starts_with("async def ")
856 || line.starts_with("class ")
857 || line.starts_with('@');
858 if indent == 0 {
859 decl || line.starts_with("import ") || line.starts_with("from ") || constant.is_match(line)
860 } else {
861 indent <= 4 && decl
862 }
863}
864
865/// For a Python module constant (`NAME = value`, `NAME: type = value`), the
866/// byte index just past the `=`; `None` for any other line.
867fn python_constant_cut(line: &str) -> Option<usize> {
868 static CONSTANT: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
869 let constant = CONSTANT.get_or_init(|| {
870 regex::Regex::new(r"^(?:[A-Z_][A-Z0-9_]*|__all__)(?:\s*:\s*[^=]+?)?\s*=").unwrap()
871 });
872 constant.find(line).map(|m| m.end())
873}
874
875fn paren_balance(s: &str) -> i32 {
876 s.chars()
877 .map(|c| match c {
878 '(' => 1,
879 ')' => -1,
880 _ => 0,
881 })
882 .sum()
883}
884
885fn brace_delta(s: &str) -> i32 {
886 s.chars()
887 .map(|c| match c {
888 '{' => 1,
889 '}' => -1,
890 _ => 0,
891 })
892 .sum()
893}
894
895/// Cut a declaration at its body: the first `{` outside parentheses for a
896/// C-like line (an import, `use`, or re-export list is not a body and is
897/// kept whole), the trailing `:` for Python.
898fn cut_at_body(sig: &str, family: Family) -> String {
899 match family {
900 Family::Python => sig.trim_end_matches(':').trim_end().to_string(),
901 _ if sig.starts_with("import ")
902 || sig.starts_with("use ")
903 || sig.starts_with("export {")
904 || sig.starts_with("export type {")
905 || sig.starts_with("export * ") =>
906 {
907 sig.trim_end().to_string()
908 }
909 _ => {
910 // The body opens at the first `{` outside parentheses, or, for
911 // an arrow whose body is an expression, right after the `=>`:
912 // an expression body is body whatever line it wraps onto.
913 let mut depth = 0i32;
914 let mut cut = sig.len();
915 let bytes = sig.as_bytes();
916 for (i, c) in sig.char_indices() {
917 match c {
918 '(' | '[' => depth += 1,
919 ')' | ']' => depth -= 1,
920 '{' if depth <= 0 => {
921 cut = i;
922 break;
923 }
924 '=' if depth <= 0 && bytes.get(i + 1) == Some(&b'>') => {
925 let rest = sig[i + 2..].trim_start();
926 if !rest.starts_with('{') {
927 cut = i + 2;
928 break;
929 }
930 }
931 _ => {}
932 }
933 }
934 sig[..cut].trim_end().to_string()
935 }
936 }
937}
938
939/// Normalize a kept declaration so that formatting inside it is invisible:
940/// trailing semicolons dropped, double quotes read as single quotes, runs of
941/// whitespace collapsed, and no whitespace next to punctuation — so
942/// `f(a,b)`, `f(a, b)` and a signature wrapped across lines digest alike,
943/// while every token that carries meaning survives.
944fn normalize_signature(sig: &str) -> String {
945 let collapsed: Vec<&str> = sig
946 .trim()
947 .trim_end_matches(';')
948 .split_whitespace()
949 .collect();
950 let joined = collapsed.join(" ").replace('"', "'");
951 let is_punct = |c: char| "()[]{},;:=<>|&?!-+*/.".contains(c);
952 let mut out = String::with_capacity(joined.len());
953 let chars: Vec<char> = joined.chars().collect();
954 for (i, &c) in chars.iter().enumerate() {
955 if c == ' ' {
956 let before = chars[..i].iter().rev().find(|x| **x != ' ').copied();
957 let after = chars[i + 1..].iter().find(|x| **x != ' ').copied();
958 if before.is_some_and(is_punct) || after.is_some_and(is_punct) {
959 continue;
960 }
961 }
962 out.push(c);
963 }
964 // Trailing commas are a formatter's choice, never a signature's: drop
965 // one before a closing bracket and at the end of the line.
966 let out = out
967 .replace(",)", ")")
968 .replace(",]", "]")
969 .replace(",}", "}")
970 .replace(",>", ">");
971 let out = out.trim_end_matches(',').to_string();
972 // A union type wrapped by a formatter leads its first member with `|`.
973 let out = out.replace("=|", "=");
974 // A kept line that opens a body keeps nothing of the brace itself.
975 let out = out.trim_end_matches('{').trim_end().to_string();
976 // Formatter defaults that are not signatures: a quoted property key
977 // reads as the bare key; `(x)=>` reads as `x=>`; a Python import list's
978 // parentheses (black's wrapped form) vanish.
979 static QUOTED_KEY: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
980 static ARROW_PARENS: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
981 let quoted_key =
982 QUOTED_KEY.get_or_init(|| regex::Regex::new(r"^'([A-Za-z_$][\w$]*)':").unwrap());
983 let arrow_parens =
984 ARROW_PARENS.get_or_init(|| regex::Regex::new(r"\(([A-Za-z_$][\w$]*)\)=>").unwrap());
985 let out = quoted_key.replace(&out, "$1:").into_owned();
986 let out = arrow_parens.replace_all(&out, "$1=>").into_owned();
987 // A scalar property value (`name: 'Auth'`, `port: 3000`) is body, exactly
988 // as a one-line literal's members are: keep the key alone.
989 static SCALAR_PROPERTY: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
990 let scalar = SCALAR_PROPERTY
991 .get_or_init(|| regex::Regex::new(r#"^([A-Za-z_$][\w$]*:)(?:'|`|-?\d)"#).unwrap());
992 let out = match scalar.captures(&out) {
993 Some(caps) => caps[1].to_string(),
994 None => out,
995 };
996 if out.starts_with("from ") || out.starts_with("import ") {
997 return out
998 .replace('(', " ")
999 .replace(')', "")
1000 .split_whitespace()
1001 .collect::<Vec<_>>()
1002 .join(" ");
1003 }
1004 out
1005}
1006
1007/// A top-level binding whose value is not a function is cut right after its
1008/// `=` (and a default export that is not a function or object literal right
1009/// after `default`): the value is body, so its wrapping, its operators and
1010/// its literal shape never reach the digest. A function-valued binding keeps
1011/// its signature. `None` when the line is not such a binding.
1012fn cut_value_binding(line: &str) -> Option<String> {
1013 static BINDING: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
1014 static DEFAULT: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
1015 let binding = BINDING.get_or_init(|| {
1016 regex::Regex::new(
1017 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*(.*)$",
1018 )
1019 .unwrap()
1020 });
1021 let default =
1022 DEFAULT.get_or_init(|| regex::Regex::new(r"^(export\s+default)\s+(.*)$").unwrap());
1023 let function_like = |value: &str| {
1024 static ARROW: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
1025 let arrow = ARROW
1026 .get_or_init(|| regex::Regex::new(r"^(?:async\s+)?[A-Za-z_$][\w$]*\s*=>").unwrap());
1027 value.starts_with('(')
1028 || value.starts_with("async ")
1029 || value.starts_with("async(")
1030 || value.starts_with("function")
1031 || value.starts_with("class")
1032 || arrow.is_match(value)
1033 };
1034 if let Some(caps) = binding.captures(line) {
1035 let value = caps[2].trim();
1036 // The `=` of an arrow `=>` (a property whose type annotation the
1037 // regex read as `key: (params)`) is not an assignment.
1038 if value.starts_with('>') {
1039 return None;
1040 }
1041 // A module's object-literal export (`module.exports = {`) is an
1042 // interface container like `export default {`: its members stay.
1043 let module_export = caps[1].starts_with("exports") || caps[1].starts_with("module.exports");
1044 // An empty value means a formatter broke it onto the next line:
1045 // still a value, still body (the caller skips that line).
1046 if function_like(value) || (module_export && value.starts_with('{')) {
1047 return None;
1048 }
1049 return Some(caps[1].to_string());
1050 }
1051 if let Some(caps) = default.captures(line) {
1052 let value = caps[2].trim();
1053 if value.is_empty() || value.starts_with('{') || function_like(value) {
1054 return None;
1055 }
1056 return Some(caps[1].to_string());
1057 }
1058 None
1059}
1060
1061fn angle_balance(s: &str) -> i32 {
1062 // Generics only: `->` and `=>` carry a `>` that is not a bracket.
1063 let s = s.replace("->", " ").replace("=>", " ");
1064 s.chars()
1065 .map(|c| match c {
1066 '<' => 1,
1067 '>' => -1,
1068 _ => 0,
1069 })
1070 .sum::<i32>()
1071 .max(0)
1072}
1073
1074fn bracket_balance(s: &str) -> i32 {
1075 s.chars()
1076 .map(|c| match c {
1077 '[' => 1,
1078 ']' => -1,
1079 _ => 0,
1080 })
1081 .sum()
1082}
1083
1084/// A binding whose destructuring pattern a formatter wrapped: the pattern
1085/// opens on the binding line (`const {`, `let [`) and closes on a later one.
1086fn opens_destructure(line: &str) -> bool {
1087 static DESTRUCTURE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
1088 let re = DESTRUCTURE
1089 .get_or_init(|| regex::Regex::new(r"^(?:export\s+)?(?:const|let|var)\s+[\{\[]").unwrap());
1090 re.is_match(line) && brace_delta(line) + bracket_balance(line) > 0
1091}
1092
1093/// An import, `use`, or re-export list wraps across lines on its braces;
1094/// nothing else joins on a brace (a brace elsewhere opens a body).
1095fn is_list_declaration(sig: &str) -> bool {
1096 sig.starts_with("import ")
1097 || sig.starts_with("use ")
1098 || sig.starts_with("export {")
1099 || sig.starts_with("export type {")
1100}
1101
1102fn declaration_lines(stripped: &str, family: Family) -> String {
1103 let lines: Vec<&str> = stripped.lines().collect();
1104 let mut out: Vec<String> = Vec::new();
1105 let mut depth: i32 = 0;
1106 // After a binding whose value was cut as body, the value's own lines
1107 // are skipped whole until every bracket the value opened has closed:
1108 // (brace, bracket, paren) balances accumulated from the binding line.
1109 let mut body_skip: Option<(i32, i32, i32)> = None;
1110 let mut i = 0;
1111 while i < lines.len() {
1112 let raw = lines[i];
1113 let line = raw.trim();
1114 if line.is_empty() {
1115 i += 1;
1116 continue;
1117 }
1118 if let Some((braces, brackets, parens)) = body_skip {
1119 let braces = braces + brace_delta(raw);
1120 let brackets = brackets + bracket_balance(raw);
1121 let parens = parens + paren_balance(raw);
1122 depth += brace_delta(raw);
1123 body_skip = if braces <= 0 && brackets <= 0 && parens <= 0 {
1124 None
1125 } else {
1126 Some((braces, brackets, parens))
1127 };
1128 i += 1;
1129 continue;
1130 }
1131 let indent = raw.len() - raw.trim_start().len();
1132 let next_opens_body = lines[i + 1..]
1133 .iter()
1134 .map(|l| l.trim())
1135 .find(|l| !l.is_empty())
1136 .is_some_and(|l| l.starts_with('{'));
1137 let keep = match family {
1138 Family::Python => python_keeps(line, indent),
1139 _ => c_like_keeps(line, depth, next_opens_body, family != Family::Rust),
1140 };
1141 if keep
1142 && family == Family::Python
1143 && indent == 0
1144 && let Some(eq) = python_constant_cut(line)
1145 {
1146 // A module constant's value is body, as a JS binding's is.
1147 out.push(normalize_signature(&line[..eq]));
1148 i += 1;
1149 continue;
1150 }
1151 // A destructuring pattern a formatter wrapped (`const {\n a,\n b,\n} = …`)
1152 // joins across its brackets before the binding rule sees it, so the
1153 // names inside are interface in the wrapped form as in the one-line form.
1154 let mut binding_end = i;
1155 let destructured = if keep && family != Family::Python && opens_destructure(line) {
1156 let mut joined = line.to_string();
1157 while brace_delta(&joined) + bracket_balance(&joined) > 0
1158 && binding_end + 1 < lines.len()
1159 && binding_end - i < 60
1160 {
1161 binding_end += 1;
1162 if lines[binding_end].trim().is_empty() {
1163 continue;
1164 }
1165 joined.push(' ');
1166 joined.push_str(lines[binding_end].trim());
1167 }
1168 Some(joined)
1169 } else {
1170 None
1171 };
1172 let binding_line = destructured.as_deref().unwrap_or(line);
1173 if keep
1174 && family != Family::Python
1175 && !(depth >= 1 && enum_member_re().is_match(line))
1176 && let Some(cut) = cut_value_binding(binding_line)
1177 {
1178 // (An enum member's explicit value is interface, not a binding's
1179 // body: `Green = 2,` keeps its value.)
1180 // The value is body: keep the binding's name, count its braces,
1181 // and skip the value's lines until every bracket it opened closes.
1182 out.push(normalize_signature(&cut));
1183 let span = &lines[i..=binding_end];
1184 let mut opened = (
1185 span.iter().map(|l| brace_delta(l)).sum::<i32>(),
1186 span.iter().map(|l| bracket_balance(l)).sum::<i32>(),
1187 span.iter().map(|l| paren_balance(l)).sum::<i32>(),
1188 );
1189 depth += opened.0;
1190 i = binding_end + 1;
1191 if binding_line.trim_end().ends_with('=') {
1192 // The value starts on the next non-empty line: consume it
1193 // and whatever it opens.
1194 while i < lines.len() && lines[i].trim().is_empty() {
1195 i += 1;
1196 }
1197 if i < lines.len() {
1198 let v = lines[i];
1199 opened = (
1200 opened.0 + brace_delta(v),
1201 opened.1 + bracket_balance(v),
1202 opened.2 + paren_balance(v),
1203 );
1204 depth += brace_delta(v);
1205 i += 1;
1206 }
1207 }
1208 if opened.0 > 0 || opened.1 > 0 || opened.2 > 0 {
1209 body_skip = Some(opened);
1210 }
1211 continue;
1212 }
1213 if keep {
1214 // A signature wrapped across lines joins on its parentheses, a
1215 // wrapped array literal on its brackets, a wrapped import or
1216 // export list on its braces — so a formatter's line width is
1217 // invisible and a member added inside a wrapped list is not.
1218 let mut sig = line.to_string();
1219 let mut j = i;
1220 let c_like = family != Family::Python;
1221 // Continuation: an open bracket of any kind, or (C-like) a next
1222 // line a formatter led with an operator (`|` in a union type,
1223 // `.` in a chain, `?`/`:` in a ternary, `&&`/`||`/`+`).
1224 let next_is_operator_led = |k: usize| {
1225 c_like
1226 && lines[k + 1..]
1227 .iter()
1228 .map(|l| l.trim())
1229 .find(|l| !l.is_empty())
1230 .is_some_and(|l| {
1231 l.starts_with('|')
1232 || l.starts_with('&')
1233 || l.starts_with('?')
1234 || l.starts_with(':')
1235 || l.starts_with('.')
1236 || l.starts_with('+')
1237 })
1238 };
1239 // A line that ends by opening a body (`{`) joins nothing: what
1240 // follows is body, even inside a callback argument's parentheses.
1241 // An import or export list's brace opens a list, not a body.
1242 // A line that ends in `=` or `:` (a formatter broke the value or
1243 // the type onto the next line) joins its continuation.
1244 let ends_open = |s: &str| {
1245 let t = s.trim_end();
1246 c_like && (t.ends_with('=') || t.ends_with(':'))
1247 };
1248 while (!sig.trim_end().ends_with('{') || is_list_declaration(&sig))
1249 && (paren_balance(&sig) > 0
1250 || bracket_balance(&sig) > 0
1251 || (c_like && angle_balance(&sig) > 0)
1252 || (is_list_declaration(&sig) && brace_delta(&sig) > 0)
1253 || ends_open(&sig)
1254 || next_is_operator_led(j))
1255 && j + 1 < lines.len()
1256 && j - i < 60
1257 {
1258 j += 1;
1259 if lines[j].trim().is_empty() {
1260 continue;
1261 }
1262 sig.push(' ');
1263 sig.push_str(lines[j].trim());
1264 }
1265 // A line kept only as a member signature must open a body once
1266 // joined; a wrapped call statement joins to `name(args)` with no
1267 // body after it and is dropped, as its one-line form would be.
1268 // Judged on the joined signature: a typed member a formatter
1269 // wrapped (`load(\n id: string,\n): Promise<void>`) is typed.
1270 let opens_body = sig.trim_end().ends_with('{')
1271 || sig.contains("=>")
1272 || lines[j + 1..]
1273 .iter()
1274 .map(|l| l.trim())
1275 .find(|l| !l.is_empty())
1276 .is_some_and(|l| l.starts_with('{'));
1277 if c_like && member_signature_only(&sig, depth) && !opens_body {
1278 for l in &lines[i..=j] {
1279 depth += brace_delta(l);
1280 }
1281 i = j + 1;
1282 continue;
1283 }
1284 out.push(normalize_signature(&cut_at_body(&sig, family)));
1285 if c_like {
1286 for l in &lines[i..=j] {
1287 depth += brace_delta(l);
1288 }
1289 }
1290 i = j + 1;
1291 } else {
1292 if family != Family::Python {
1293 depth += brace_delta(raw);
1294 }
1295 i += 1;
1296 }
1297 }
1298 out.join("\n")
1299}
1300
1301/// The load-bearing sections of a type, in the type's declared order:
1302///
1303/// 1. the sections declaring `load_bearing: true`, when any does;
1304/// 2. otherwise the required sections, minus any declaring
1305/// `load_bearing: false`, when that leaves at least one;
1306/// 3. otherwise every section — a type with no required sections and no
1307/// declaration has no notes/claim split the engine can honour, and an
1308/// empty set would hash to a constant that never drifts.
1309pub fn load_bearing_sections(
1310 type_def: &memstead_schema::types::TypeDefinition,
1311) -> Vec<&memstead_schema::types::SectionDef> {
1312 let explicit: Vec<_> = type_def
1313 .sections
1314 .iter()
1315 .filter(|s| s.load_bearing == Some(true))
1316 .collect();
1317 if !explicit.is_empty() {
1318 return explicit;
1319 }
1320 let required: Vec<_> = type_def
1321 .sections
1322 .iter()
1323 .filter(|s| s.required && s.load_bearing != Some(false))
1324 .collect();
1325 if !required.is_empty() {
1326 return required;
1327 }
1328 type_def.sections.iter().collect()
1329}
1330
1331/// The `entity-load-bearing` prepared form: the entity's load-bearing
1332/// sections serialized stably — each as `## <key>`, a blank line, the
1333/// trimmed content, a blank line — in the type's declared section order.
1334/// Keyed by section KEY (not heading) so a heading rename in the schema
1335/// does not read as a content change; a section the entity does not carry
1336/// is skipped. Title, metadata, and relationships are outside the form:
1337/// the anchor's artifact is the entity id, and a rename orphans the anchor
1338/// on its own. Without a type definition (a type the mem's schema does not
1339/// declare) every section the entity carries is load-bearing, in the
1340/// entity's own order.
1341pub fn entity_load_bearing_form(
1342 entity: &Entity,
1343 type_def: Option<&memstead_schema::types::TypeDefinition>,
1344) -> String {
1345 fn push(out: &mut String, key: &str, content: &str) {
1346 out.push_str("## ");
1347 out.push_str(key);
1348 out.push_str("\n\n");
1349 out.push_str(content.trim());
1350 out.push_str("\n\n");
1351 }
1352 let mut out = String::new();
1353 match type_def {
1354 Some(td) => {
1355 for section in load_bearing_sections(td) {
1356 if let Some(content) = entity.sections.get(§ion.key) {
1357 push(&mut out, §ion.key, content);
1358 }
1359 }
1360 }
1361 None => {
1362 for (key, content) in &entity.sections {
1363 push(&mut out, key, content);
1364 }
1365 }
1366 }
1367 out
1368}
1369
1370/// The prepared hash of ONE load-bearing section, in the same unit form
1371/// [`entity_load_bearing_form`] serializes it into (`## <key>`, a blank
1372/// line, the trimmed content). The key rides inside the hashed bytes, so
1373/// the same prose moved to another section key is a different mark.
1374///
1375/// The per-section grain exists because the whole-form hash collapses a
1376/// type's load-bearing sections to one bit: an owner who rewrites one of
1377/// three sections would clear a mark that still covers the other two, and
1378/// a contributor's remaining claims would be served as the workspace's own
1379/// prose.
1380pub fn entity_section_prepared_hash(key: &str, content: &str) -> String {
1381 prepared_content_hash(format!("## {key}\n\n{}\n\n", content.trim()).as_bytes())
1382}
1383
1384/// One prepared hash per load-bearing section the entity carries, keyed by
1385/// section key. The section set is the type's
1386/// ([`load_bearing_sections`]), or every section the entity carries when
1387/// the type is unknown, matching [`entity_load_bearing_form`].
1388///
1389/// Empty sections are skipped deliberately. A mark over an empty section
1390/// would match every entity whose same section is empty, which is the one
1391/// way this comparison could brand unrelated content.
1392pub fn entity_load_bearing_section_marks(
1393 entity: &Entity,
1394 type_def: Option<&memstead_schema::types::TypeDefinition>,
1395) -> std::collections::BTreeMap<String, String> {
1396 let mut out = std::collections::BTreeMap::new();
1397 let mut add = |key: &String, content: &String| {
1398 if !content.trim().is_empty() {
1399 out.insert(key.clone(), entity_section_prepared_hash(key, content));
1400 }
1401 };
1402 match type_def {
1403 Some(td) => {
1404 for section in load_bearing_sections(td) {
1405 if let Some(content) = entity.sections.get(§ion.key) {
1406 add(§ion.key, content);
1407 }
1408 }
1409 }
1410 None => {
1411 for (key, content) in &entity.sections {
1412 add(key, content);
1413 }
1414 }
1415 }
1416 out
1417}
1418
1419/// Touchpoint A for the `entity` grain: the prepared-content hash of an
1420/// entity under the source's declared preparation. `None` declares
1421/// nothing — the canonical rendered markdown, byte-for-byte today's form.
1422/// [`ENTITY_LOAD_BEARING`] hashes [`entity_load_bearing_form`]. An
1423/// identifier the registry does not know yields `None`: the form cannot be
1424/// computed, and observation reports the anchor unobserved rather than
1425/// hashing a fabricated form (validation refuses such a record at every
1426/// edit path; only a hand-edited file reaches here).
1427pub fn entity_prepared_hash(
1428 entity: &Entity,
1429 type_def: Option<&memstead_schema::types::TypeDefinition>,
1430 preparation: Option<&str>,
1431) -> Option<String> {
1432 match entity_prepared(entity, type_def, preparation, None) {
1433 PathPrepared::Hash(h) => Some(h),
1434 PathPrepared::NoHash | PathPrepared::UnitAbsent => None,
1435 }
1436}
1437
1438/// [`entity_prepared_hash`] with the artifact's `#<locator>` in hand: under
1439/// [`QUOTED_PHRASE`] the locator is the phrase and the prepared form is the
1440/// phrase where the entity's canonical markdown still carries it
1441/// ([`PathPrepared::UnitAbsent`] where it does not); every other
1442/// preparation ignores the locator and answers as [`entity_prepared_hash`]
1443/// does, [`PathPrepared::NoHash`] for an identifier the registry does not
1444/// prepare entities under.
1445pub fn entity_prepared(
1446 entity: &Entity,
1447 type_def: Option<&memstead_schema::types::TypeDefinition>,
1448 preparation: Option<&str>,
1449 locator: Option<&str>,
1450) -> PathPrepared {
1451 let form = match preparation {
1452 None => crate::render::render_entity_markdown(entity, None),
1453 Some(ENTITY_LOAD_BEARING) => entity_load_bearing_form(entity, type_def),
1454 Some(QUOTED_PHRASE) => {
1455 let rendered = crate::render::render_entity_markdown(entity, None);
1456 return match locator {
1457 Some(phrase) => quoted_phrase_prepared(phrase, &rendered),
1458 None => PathPrepared::Hash(prepared_content_hash(rendered.as_bytes())),
1459 };
1460 }
1461 Some(_) => return PathPrepared::NoHash,
1462 };
1463 PathPrepared::Hash(prepared_content_hash(form.as_bytes()))
1464}
1465
1466// ---------------------------------------------------------------------------
1467// Touchpoint B: delivery units
1468// ---------------------------------------------------------------------------
1469
1470/// One delivery unit of a file under a delivery preparation.
1471#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1472pub struct DeliveryUnit {
1473 /// The unit's key, unique within its file; the addressed form is
1474 /// `<path>#<key>` ([`unit_id`]).
1475 pub key: String,
1476 /// The intrinsic key the source's units sort by (a normalized stamp for
1477 /// [`DATED_ENTRIES`]); empty for a [`WHOLE_FILE_UNIT`].
1478 pub order_key: String,
1479 /// First line of the unit, 1-based.
1480 pub start_line: usize,
1481 /// Last line of the unit, 1-based, inclusive.
1482 pub end_line: usize,
1483 /// The prepared-content hash of the unit's text — what a span anchor
1484 /// over the unit records, and what a change run compares.
1485 pub hash: String,
1486}
1487
1488/// How a unit changed between two states of its file.
1489#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1490#[serde(rename_all = "lowercase")]
1491pub enum UnitChange {
1492 /// The key is new.
1493 Added,
1494 /// The key existed; the unit's text changed.
1495 Modified,
1496 /// The key is gone.
1497 Deleted,
1498}
1499
1500/// The addressed form of a unit: `<path>#<key>`.
1501pub fn unit_id(path: &str, key: &str) -> String {
1502 format!("{path}#{key}")
1503}
1504
1505/// Split an artifact id into its path and, when it addresses a unit, the
1506/// unit key after the first `#`.
1507pub fn split_unit_id(id: &str) -> (&str, Option<&str>) {
1508 match id.find('#') {
1509 Some(cut) => (&id[..cut], Some(&id[cut + 1..])),
1510 None => (id, None),
1511 }
1512}
1513
1514/// Touchpoint B: the delivery units of one file's content under a delivery
1515/// preparation, in file order. `None` when `preparation` is not a registered
1516/// delivery preparation (the caller keeps file-granularity delivery).
1517pub fn unitize(preparation: &str, content: &str) -> Option<Vec<DeliveryUnit>> {
1518 match preparation {
1519 DATED_ENTRIES => Some(dated_entries(content)),
1520 _ => None,
1521 }
1522}
1523
1524/// The text of one unit, lines `start_line..=end_line` of `content`.
1525pub fn unit_text(content: &str, unit: &DeliveryUnit) -> String {
1526 content
1527 .lines()
1528 .skip(unit.start_line.saturating_sub(1))
1529 .take(unit.end_line + 1 - unit.start_line.max(1))
1530 .collect::<Vec<_>>()
1531 .join("\n")
1532}
1533
1534/// The units that differ between two states of one file, keyed by unit key:
1535/// a key only in `after` is [`UnitChange::Added`], a key in both whose hash
1536/// differs is [`UnitChange::Modified`] (the `after` unit), a key only in
1537/// `before` is [`UnitChange::Deleted`] (the `before` unit, so its order key
1538/// still places it). Unchanged units are not delivered again.
1539pub fn diff_units(
1540 before: &[DeliveryUnit],
1541 after: &[DeliveryUnit],
1542) -> Vec<(DeliveryUnit, UnitChange)> {
1543 let old: std::collections::BTreeMap<&str, &DeliveryUnit> =
1544 before.iter().map(|u| (u.key.as_str(), u)).collect();
1545 let new: std::collections::BTreeMap<&str, &DeliveryUnit> =
1546 after.iter().map(|u| (u.key.as_str(), u)).collect();
1547 let mut out = Vec::new();
1548 for u in after {
1549 match old.get(u.key.as_str()) {
1550 None => out.push((u.clone(), UnitChange::Added)),
1551 Some(prev) if prev.hash != u.hash => out.push((u.clone(), UnitChange::Modified)),
1552 Some(_) => {}
1553 }
1554 }
1555 for u in before {
1556 if !new.contains_key(u.key.as_str()) {
1557 out.push((u.clone(), UnitChange::Deleted));
1558 }
1559 }
1560 out
1561}
1562
1563fn dated_entries(content: &str) -> Vec<DeliveryUnit> {
1564 let lines: Vec<&str> = content.lines().collect();
1565 let starts: Vec<(usize, String)> = lines
1566 .iter()
1567 .enumerate()
1568 .filter_map(|(i, line)| leading_stamp(line).map(|stamp| (i, stamp)))
1569 .collect();
1570 if starts.is_empty() {
1571 return vec![DeliveryUnit {
1572 key: WHOLE_FILE_UNIT.to_string(),
1573 order_key: String::new(),
1574 start_line: 1,
1575 end_line: lines.len().max(1),
1576 hash: prepared_content_hash(content.as_bytes()),
1577 }];
1578 }
1579 let mut seen: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
1580 let mut units = Vec::with_capacity(starts.len());
1581 for (n, (start, stamp)) in starts.iter().enumerate() {
1582 // The preamble (anything before the first stamp) folds into the
1583 // first unit: it is context for the entries, never a unit of its own.
1584 let from = if n == 0 { 0 } else { *start };
1585 let to = starts.get(n + 1).map_or(lines.len(), |(next, _)| *next);
1586 let text = lines[from..to].join("\n");
1587 let count = seen
1588 .entry(stamp.clone())
1589 .and_modify(|c| *c += 1)
1590 .or_insert(1);
1591 let key = if *count == 1 {
1592 stamp.clone()
1593 } else {
1594 format!("{stamp}.{count}")
1595 };
1596 units.push(DeliveryUnit {
1597 key,
1598 order_key: stamp.clone(),
1599 start_line: from + 1,
1600 end_line: to,
1601 hash: prepared_content_hash(text.as_bytes()),
1602 });
1603 }
1604 units
1605}
1606
1607/// The ISO stamp a line opens with (after leading markdown markers),
1608/// normalized to `YYYY-MM-DDTHH:MM:SS`; `None` when the line opens with
1609/// anything else or the stamp is out of range.
1610fn leading_stamp(line: &str) -> Option<String> {
1611 static STAMP: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
1612 let re = STAMP.get_or_init(|| {
1613 regex::Regex::new(
1614 r"^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)?\b",
1615 )
1616 .expect("the stamp regex compiles")
1617 });
1618 let s = line.trim_start_matches(|c: char| {
1619 c.is_whitespace() || matches!(c, '#' | '-' | '*' | '>' | '[' | '(' | '|' | '`' | '+')
1620 });
1621 let caps = re.captures(s)?;
1622 let num = |i: usize| -> u32 {
1623 caps.get(i)
1624 .map(|m| m.as_str().parse().unwrap_or(0))
1625 .unwrap_or(0)
1626 };
1627 let (y, mo, d, h, mi, sec) = (num(1), num(2), num(3), num(4), num(5), num(6));
1628 let days_in_month = match mo {
1629 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
1630 4 | 6 | 9 | 11 => 30,
1631 2 => 29,
1632 _ => return None,
1633 };
1634 if !(1..=days_in_month).contains(&d) || h > 23 || mi > 59 || sec > 59 {
1635 return None;
1636 }
1637 Some(format!("{y:04}-{mo:02}-{d:02}T{h:02}:{mi:02}:{sec:02}"))
1638}
1639
1640#[cfg(test)]
1641mod tests;