fallow-api 3.48.0

Programmatic API contract types for fallow
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use std::env;
use std::fs;
use std::io;
use std::path::PathBuf;

use serde::Deserialize;

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ProtocolManifest {
    schema_version: u32,
    wire_protocol_version: u32,
    semantic_schema_version: u32,
    analysis_operation: String,
    status_operation: String,
    mutant_typecheck_operation: String,
    call_evidence_operation: String,
    query_operations: Vec<String>,
    session_envelope_types: Vec<String>,
    backend: Backend,
    experimental_backends: Vec<Backend>,
    sidecar: Sidecar,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Backend {
    family: String,
    package: String,
    version: String,
    supported_ranges: Vec<VersionRange>,
}

/// A half-open `major.minor.patch` range: `minimum_version` is inclusive and
/// `below_version` is the first unsupported version.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct VersionRange {
    minimum_version: String,
    below_version: String,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Sidecar {
    package: String,
    version_source: String,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SimilarCodeProtocolManifest {
    schema_version: u32,
    wire_protocol_version: u32,
    extraction_semantics_version: u32,
    embedding_semantics_version: u32,
    analysis_operation: String,
    status_operation: String,
    setup_operation: String,
    session_envelope_types: Vec<String>,
    model: SimilarCodeModel,
    sidecar: SimilarCodeSidecar,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SimilarCodeModel {
    id: String,
    revision: String,
    license: String,
    dimensions: usize,
    max_tokens: usize,
    normalization: String,
    artifacts: Vec<SimilarCodeArtifact>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SimilarCodeArtifact {
    path: String,
    size: u64,
    sha256: String,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SimilarCodeSidecar {
    binary: String,
    package: String,
    version_source: String,
}

fn rust_string(value: &str) -> String {
    format!("{value:?}")
}

fn rust_string_slice(values: &[String]) -> String {
    values
        .iter()
        .map(|value| rust_string(value))
        .collect::<Vec<_>>()
        .join(", ")
}

fn invalid_manifest(message: &'static str) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, message)
}

/// The canonical source of the embedded mutation companion, relative to this
/// crate. Only a repository checkout has it; a published crate has the copy
/// only.
const COMPANION_SOURCE: &str = "../../tools/mutation-runner/src";

/// The generated copy that `include_str!` embeds.
const COMPANION_COPY: &str = "src/mutation/companion";

/// The first line that the generator writes on each copied companion file.
const COMPANION_HEADER: &str = "// Generated from ";

/// Warns when the embedded companion differs from its source. A binary built
/// after an edit of `tools/mutation-runner/src` and before
/// `npm run generate:contracts` runs the old companion, so a probe on a real
/// project tests the wrong code.
fn warn_on_stale_companion() {
    let source_root = std::path::Path::new(COMPANION_SOURCE);
    if !source_root.is_dir() {
        return;
    }
    println!("cargo:rerun-if-changed={COMPANION_SOURCE}");
    println!("cargo:rerun-if-changed={COMPANION_COPY}");
    let mut stale = Vec::new();
    let mut pending = vec![source_root.to_path_buf()];
    while let Some(dir) = pending.pop() {
        let Ok(entries) = fs::read_dir(&dir) else {
            continue;
        };
        for path in entries.flatten().map(|entry| entry.path()) {
            if path.is_dir() {
                pending.push(path);
                continue;
            }
            let Ok(relative) = path.strip_prefix(source_root) else {
                continue;
            };
            let copy = fs::read_to_string(std::path::Path::new(COMPANION_COPY).join(relative));
            let body = copy.as_deref().ok().map(|text| {
                text.strip_prefix(COMPANION_HEADER)
                    .and_then(|rest| rest.split_once('\n'))
                    .map_or(text, |(_, body)| body)
            });
            if body != fs::read_to_string(&path).ok().as_deref() {
                stale.push(relative.display().to_string());
            }
        }
    }
    if !stale.is_empty() {
        stale.sort();
        println!(
            "cargo:warning=the embedded mutation companion differs from {COMPANION_SOURCE} ({}); run `npm run generate:contracts` before you use this binary",
            stale.join(", ")
        );
    }
}

/// Validates the backend entries: unique families, non-empty names, and
/// ascending, disjoint `supported_ranges` that contain the tested version.
fn validate_backends(backends: &[&Backend]) -> io::Result<()> {
    let mut families: Vec<&str> = backends.iter().map(|b| b.family.as_str()).collect();
    families.sort_unstable();
    families.dedup();
    if families.len() != backends.len() {
        return Err(invalid_manifest("backend families must be unique"));
    }
    if backends
        .iter()
        .any(|b| b.package.is_empty() || b.version.is_empty())
    {
        return Err(invalid_manifest(
            "backend package and version must not be empty",
        ));
    }
    if backends.iter().any(|b| {
        b.supported_ranges.is_empty()
            || b.supported_ranges.iter().any(|range| {
                !is_version_core(&range.minimum_version) || !is_version_core(&range.below_version)
            })
    }) {
        return Err(invalid_manifest(
            "backend supported_ranges must be a non-empty list of major.minor.patch bounds",
        ));
    }
    if backends.iter().any(|b| {
        let ranges: Vec<_> = b
            .supported_ranges
            .iter()
            .map(|range| {
                (
                    version_core(&range.minimum_version),
                    version_core(&range.below_version),
                )
            })
            .collect();
        let ascending = ranges.iter().all(|(minimum, below)| minimum < below)
            && ranges.windows(2).all(|pair| pair[0].1 <= pair[1].0);
        let tested = version_core(&b.version);
        !ascending
            || !ranges
                .iter()
                .any(|(minimum, below)| (minimum..below).contains(&&tested))
    }) {
        return Err(invalid_manifest(
            "backend supported_ranges must be ascending and disjoint, and version must be in one of them",
        ));
    }
    Ok(())
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    warn_on_stale_companion();
    const MANIFEST_PATH: &str = "type-aware-protocol.json";
    println!("cargo:rerun-if-changed={MANIFEST_PATH}");

    let source = fs::read_to_string(MANIFEST_PATH)?;
    let manifest: ProtocolManifest = serde_json::from_str(&source)?;
    if manifest.schema_version != 1 {
        return Err(invalid_manifest("unsupported manifest schema").into());
    }
    if manifest.wire_protocol_version == 0 || manifest.semantic_schema_version == 0 {
        return Err(
            invalid_manifest("protocol and semantic schema versions must be positive").into(),
        );
    }
    if manifest.query_operations.is_empty() {
        return Err(invalid_manifest("query operations must not be empty").into());
    }
    let backends: Vec<&Backend> = std::iter::once(&manifest.backend)
        .chain(&manifest.experimental_backends)
        .collect();
    validate_backends(&backends)?;
    if manifest.sidecar.version_source != "workspace-package" {
        return Err(invalid_manifest("unsupported sidecar version source").into());
    }

    let generated = format!(
        "// Generated from crates/api/type-aware-protocol.json. Do not edit.\n\
         pub(super) const WIRE_PROTOCOL_VERSION: u32 = {};\n\
         pub(super) const SEMANTIC_SCHEMA_VERSION: u32 = {};\n\
         pub(super) const ANALYSIS_OPERATION: &str = {};\n\
         pub(super) const STATUS_OPERATION: &str = {};\n\
         pub(super) const MUTANT_TYPECHECK_OPERATION: &str = {};\n\
         pub(super) const CALL_EVIDENCE_OPERATION: &str = {};\n\
         pub(super) const QUERY_OPERATIONS: &[&str] = &[{}];\n\
         pub(super) const SESSION_ENVELOPE_TYPES: &[&str] = &[{}];\n\
         pub(super) const BACKEND_FAMILY: &str = {};\n\
         pub(super) const BACKEND_VERSION: &str = {};\n\
         pub(super) const BACKENDS: &[BackendSpec] = &[{}];\n\
         pub(super) const SIDECAR_PACKAGE: &str = {};\n",
        manifest.wire_protocol_version,
        manifest.semantic_schema_version,
        rust_string(&manifest.analysis_operation),
        rust_string(&manifest.status_operation),
        rust_string(&manifest.mutant_typecheck_operation),
        rust_string(&manifest.call_evidence_operation),
        rust_string_slice(&manifest.query_operations),
        rust_string_slice(&manifest.session_envelope_types),
        rust_string(&manifest.backend.family),
        rust_string(&manifest.backend.version),
        backends
            .iter()
            .map(|b| format!(
                "BackendSpec {{ family: {}, package: {}, version: {}, supported_ranges: &[{}] }}",
                rust_string(&b.family),
                rust_string(&b.package),
                rust_string(&b.version),
                b.supported_ranges
                    .iter()
                    .map(|range| format!(
                        "({}, {})",
                        rust_string(&range.minimum_version),
                        rust_string(&range.below_version)
                    ))
                    .collect::<Vec<_>>()
                    .join(", "),
            ))
            .collect::<Vec<_>>()
            .join(", "),
        rust_string(&manifest.sidecar.package),
    );
    let output = PathBuf::from(
        env::var_os("OUT_DIR")
            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "OUT_DIR is not set"))?,
    );
    fs::write(output.join("type_aware_protocol.rs"), generated)?;
    generate_similar_code_protocol(&output)?;
    Ok(())
}

fn generate_similar_code_protocol(
    output: &std::path::Path,
) -> Result<(), Box<dyn std::error::Error>> {
    const MANIFEST_PATH: &str = "similar-code-protocol.json";
    println!("cargo:rerun-if-changed={MANIFEST_PATH}");

    let source = fs::read_to_string(MANIFEST_PATH)?;
    let manifest: SimilarCodeProtocolManifest = serde_json::from_str(&source)?;
    if manifest.schema_version != 1 {
        return Err(invalid_manifest("unsupported similar-code manifest schema").into());
    }
    if manifest.wire_protocol_version == 0
        || manifest.extraction_semantics_version == 0
        || manifest.embedding_semantics_version == 0
        || manifest.model.dimensions == 0
        || manifest.model.max_tokens == 0
        || manifest.model.artifacts.is_empty()
    {
        return Err(invalid_manifest("similar-code protocol values must be positive").into());
    }
    if manifest.model.revision.len() != 40
        || !manifest
            .model
            .revision
            .bytes()
            .all(|byte| byte.is_ascii_hexdigit())
        || manifest.model.artifacts.iter().any(|artifact| {
            artifact.path.is_empty()
                || artifact.size == 0
                || artifact.sha256.len() != 64
                || !artifact.sha256.bytes().all(|byte| byte.is_ascii_hexdigit())
        })
    {
        return Err(invalid_manifest("invalid similar-code model provenance").into());
    }
    if manifest.sidecar.version_source != "workspace-package" {
        return Err(invalid_manifest("unsupported similar-code sidecar version source").into());
    }

    let artifacts = manifest
        .model
        .artifacts
        .iter()
        .map(|artifact| {
            format!(
                "SimilarCodeArtifact {{ path: {}, size: {}, sha256: {} }}",
                rust_string(&artifact.path),
                artifact.size,
                rust_string(&artifact.sha256),
            )
        })
        .collect::<Vec<_>>()
        .join(", ");
    let generated = format!(
        "// Generated from crates/api/similar-code-protocol.json. Do not edit.\n\
         pub(super) const WIRE_PROTOCOL_VERSION: u32 = {};\n\
         pub(super) const EXTRACTION_SEMANTICS_VERSION: u32 = {};\n\
         pub(super) const EMBEDDING_SEMANTICS_VERSION: u32 = {};\n\
         pub(super) const ANALYSIS_OPERATION: &str = {};\n\
         pub(super) const STATUS_OPERATION: &str = {};\n\
         pub(super) const SETUP_OPERATION: &str = {};\n\
         pub(super) const SESSION_ENVELOPE_TYPES: &[&str] = &[{}];\n\
         pub(super) const MODEL_ID: &str = {};\n\
         pub(super) const MODEL_REVISION: &str = {};\n\
         pub(super) const MODEL_LICENSE: &str = {};\n\
         pub(super) const MODEL_DIMENSIONS: usize = {};\n\
         pub(super) const MODEL_MAX_TOKENS: usize = {};\n\
         pub(super) const MODEL_NORMALIZATION: &str = {};\n\
         pub(super) const MODEL_ARTIFACTS: &[SimilarCodeArtifact] = &[{}];\n\
         pub(super) const SIDECAR_BINARY: &str = {};\n\
         pub(super) const SIDECAR_PACKAGE: &str = {};\n",
        manifest.wire_protocol_version,
        manifest.extraction_semantics_version,
        manifest.embedding_semantics_version,
        rust_string(&manifest.analysis_operation),
        rust_string(&manifest.status_operation),
        rust_string(&manifest.setup_operation),
        rust_string_slice(&manifest.session_envelope_types),
        rust_string(&manifest.model.id),
        rust_string(&manifest.model.revision),
        rust_string(&manifest.model.license),
        manifest.model.dimensions,
        manifest.model.max_tokens,
        rust_string(&manifest.model.normalization),
        artifacts,
        rust_string(&manifest.sidecar.binary),
        rust_string(&manifest.sidecar.package),
    );
    fs::write(output.join("similar_code_protocol.rs"), generated)?;
    Ok(())
}

fn is_version_core(version: &str) -> bool {
    let parts: Vec<&str> = version.split('.').collect();
    parts.len() == 3
        && parts
            .iter()
            .all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()))
}

/// `major.minor.patch` of a version, with any prerelease or build tag cut off.
/// An unparsable part becomes 0. The manifest check above validates the
/// range ends, and `version` must still land inside them.
fn version_core(version: &str) -> (u64, u64, u64) {
    let end = version.find(['-', '+']).unwrap_or(version.len());
    let mut parts = version[..end]
        .split('.')
        .map(|part| part.parse::<u64>().unwrap_or(0));
    (
        parts.next().unwrap_or(0),
        parts.next().unwrap_or(0),
        parts.next().unwrap_or(0),
    )
}