conkit_sketch/lib.rs
1//! Byte-in, byte-out sketch contracts for Contract Kit.
2//!
3//! The `conkit-sketch` crate checks source bytes against expected code snippets stored
4//! in combined contract YAML, refreshes linked sketch code, and compares sketch
5//! catalogs semantically. Callers provide logical [`CatalogPath`] names and bytes
6//! through [`FileCatalog`], then decide where returned reports or updated combined
7//! documents should be stored.
8//!
9//! Sketch matching is intentionally language-neutral. The crate normalizes
10//! contract snippets and source files the same way, then verifies that each
11//! expected normalized line sequence appears in the declared source file.
12//! A minimal signature index follows each top-level signature's `sketch` link
13//! to infer the sketch's source file and signature type. Rust parsing and
14//! AST-derived source extraction remain outside this crate.
15//!
16//! # Contracts and matching
17//!
18//! Each YAML document contains exactly `root`, `files`, `signatures`, and
19//! `sketches`. A flattened sketch record has a null-valued identifier beside
20//! `signature_type` and `code`; its linked signature owns the `file` and
21//! `sketch` fields. The later `version`/`language` reverse-link dialect is not
22//! accepted. Only direct root-level `.yaml` and `.yml` catalog entries are
23//! considered; nested YAML entries are ignored.
24//!
25//! Matching collapses whitespace within each line, removes empty lines, and
26//! compares the remaining lines as one contiguous ordered sequence. Source
27//! bytes do not need to be UTF-8: malformed source lines use an ASCII-whitespace
28//! fallback that preserves every other byte. A sketch still matches only the
29//! logical source path declared by its linked signature.
30//!
31//! # Semantic diffing
32//!
33//! [`SketchContractKit::diff`] treats the sketch identifier as identity. For a
34//! sketch present in both catalogs, the linked source file, linked signature
35//! label, `signature_type`, and normalized code are semantic. The containing
36//! contract document, YAML formatting, YAML comments outside `code`, and mapping
37//! order are nonsemantic.
38//!
39//! Normalization removes blank lines and collapses whitespace within each line,
40//! so those changes alone do not produce a diff. Line order and every token or
41//! comment inside `code` remain semantic.
42//!
43//! # Generation and reports
44//!
45//! Generation accepts one [`SketchSeed`] for every explicit signature link and
46//! refreshes only the flattened sketch's `code`. It preserves the combined
47//! document's root, file allowlist, signatures, links, identifiers, and kinds.
48//! The response returns the complete input catalog, including unchanged nested
49//! YAML and non-YAML passthrough entries, and counts the linked sketches that
50//! were refreshed. Returned catalog bytes are deterministic and are never
51//! written to the operating system by this crate.
52//!
53//! A check can return YAML or JSON report bytes through [`ReportRequest`]. The
54//! caller chooses the logical output path and persists those bytes if desired.
55//!
56//! # Errors and diagnostics
57//!
58//! Malformed YAML, invalid contract fields, duplicate sketch identifiers, and
59//! invalid generation seeds return [`SketchContractKitError`]. A valid sketch
60//! that references a missing source file or whose snippet does not match is
61//! represented by [`SketchDiagnostic`] in a successful [`CheckResponse`].
62//! [`CheckMode`] determines whether those diagnostics make the response fail.
63//!
64//! # Runtime and storage boundaries
65//!
66//! `conkit-sketch` owns sketch YAML parsing, normalization, matching, semantic
67//! diffing, diagnostics, report bytes, and generation from caller-provided
68//! resolved seeds. Filesystem walking, path normalization, terminal output, and
69//! cross-domain orchestration belong to callers such as the `conkit` crate.
70//!
71//! Start with [`SketchContractKit::builder`] to configure the local kit and call
72//! its operations directly with `.await`. The futures are executor-neutral: the
73//! crate does not select the executor that polls them. To place an operation in
74//! a spawned task, that task must own both its request and the kit, commonly by
75//! moving an [`Arc`](std::sync::Arc) clone into an `async move` block. That
76//! owning future and its output satisfy `Send + 'static`; a method future which
77//! still borrows a local kit is not promised to be `'static`.
78//!
79//! CPU work runs on a reusable Rayon-backed pool. [`WorkOptions`] documents the
80//! complete worker-budget, root-admission, cancellation, and caller-deadline
81//! contract. Catalogs, diagnostics, generated entries, and rendered output
82//! remain deterministic regardless of worker scheduling.
83//!
84//! # Examples
85//!
86//! Refresh a linked sketch, then check the same source against it.
87//!
88//! ```
89//! use conkit_sketch::{
90//! CatalogPath, CheckMode, CheckRequest, FileCatalog, GenerateRequest,
91//! ReportRequest, SketchContractKit, SketchSeed,
92//! };
93//!
94//! let source_path = CatalogPath::new("lib.rs")?;
95//! let contract_path = CatalogPath::new("main.yml")?;
96//! let mut source_files = FileCatalog::new();
97//! source_files.insert(
98//! source_path.clone(),
99//! b"pub fn answer() -> u8 { 42 }\n".to_vec(),
100//! )?;
101//! let mut contract_files = FileCatalog::new();
102//! contract_files.insert(contract_path.clone(), br#"root: ../src
103//! files: [lib.rs]
104//! signatures:
105//! - answer_signature:
106//! file: lib.rs
107//! signature_type: function
108//! sketch: answer_body
109//! sketches:
110//! - answer_body:
111//! signature_type: function
112//! code: old code
113//! "#.to_vec())?;
114//!
115//! let kit = SketchContractKit::builder().build()?;
116//! let generated = futures_executor::block_on(kit.generate(GenerateRequest {
117//! contract_files,
118//! seeds: vec![SketchSeed {
119//! contract_file: contract_path.clone(),
120//! sketch_id: "answer_body".to_owned(),
121//! signature_type: "function".to_owned(),
122//! file: source_path.clone(),
123//! code: "pub fn answer() -> u8 { 42 }".to_owned(),
124//! }],
125//! }))?;
126//!
127//! assert_eq!(generated.sketch_count, 1);
128//! assert!(generated
129//! .contract_files
130//! .get(&contract_path)
131//! .is_some());
132//!
133//! let checked = futures_executor::block_on(kit.check(CheckRequest {
134//! source_files,
135//! contract_files: generated.contract_files,
136//! report: ReportRequest::None,
137//! mode: CheckMode::Strict,
138//! }))?;
139//!
140//! assert!(checked.passed);
141//! assert!(checked.diagnostics.is_empty());
142//! assert_eq!(checked.counts.matched_sketch_count, 1);
143//! # Ok::<(), Box<dyn std::error::Error>>(())
144//! ```
145#![deny(missing_docs)]
146#![deny(rustdoc::broken_intra_doc_links)]
147#![deny(rustdoc::private_intra_doc_links)]
148
149mod api;
150mod contract;
151mod error;
152mod files;
153mod generate;
154mod id;
155mod inventory;
156mod matcher;
157mod normalize;
158mod report;
159mod work;
160
161pub use crate::api::{
162 CheckMode, CheckRequest, CheckResponse, DiffEntry, DiffRequest, DiffResponse, GenerateRequest,
163 GenerateResponse, SketchContractKit, SketchContractKitBuilder, SketchSeed,
164};
165pub use crate::error::SketchContractKitError;
166pub use crate::files::{CatalogPath, FileCatalog, FileCatalogError};
167pub use crate::inventory::{SketchCheckCounts, SketchDiagnostic};
168pub use crate::report::{ReportFormat, ReportRequest};
169pub use crate::work::{WorkOptions, WorkParallelism};