kranz-engine 0.2.2

Governed mission engine for auditable AI coding-agent work.
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! Repo-configured merge-gate runner.
//!
//! The gate suite is read from the live base branch's tracked
//! [`.kranz/merge-gates.json`](MERGE_GATES_PATH). Keeping the suite on the
//! base branch prevents a mission from weakening the checks that judge its own
//! diff, and lets non-Rust repositories define gates in their own language.
//! The runner itself is pure and injectable: production wraps the existing
//! bounded shell runner while tests inject deterministic outcomes.
//!
//! The suite also runs through the first-class gate interface
//! ([`crate::gate`], ticket `.kranz/tickets/gate-plugin-interface.md`) via
//! [`MergeSuiteGate`]; [`crate::merge`] drives it that way. The adaptation
//! changes nothing about ownership or behavior: the suite bytes are still
//! read from the live base branch, gates still run in declared order, and
//! the suite still stops at the first failure.

use serde::Deserialize;
use std::path::{Component, Path, PathBuf};

pub const MERGE_GATES_PATH: &str = ".kranz/merge-gates.json";

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct GateSuite {
    pub gates: Vec<Gate>,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Gate {
    pub command: String,
    #[serde(default = "default_cwd")]
    pub cwd: String,
    /// Relative path prefixes. Empty means the gate always runs; otherwise it
    /// runs when at least one changed path equals or is below a prefix.
    #[serde(default)]
    pub when_paths: Vec<String>,
}

fn default_cwd() -> String {
    ".".to_string()
}

/// Result of running the applicable gates in a suite.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GateSuiteResult {
    Passed,
    Failed { gate: String, output: String },
}

/// Parse and validate a tracked gate-suite file. Invalid or empty suites fail
/// closed: a Merge action must never become green merely because its repo
/// config is absent or malformed.
pub fn parse_gate_suite(bytes: &[u8]) -> Result<GateSuite, String> {
    let mut suite: GateSuite =
        serde_json::from_slice(bytes).map_err(|e| format!("invalid {MERGE_GATES_PATH}: {e}"))?;
    validate_gate_suite(&suite)?;
    for gate in &mut suite.gates {
        gate.cwd = normalize_relative_path(&gate.cwd, true);
        for prefix in &mut gate.when_paths {
            *prefix = normalize_relative_path(prefix, false);
            if prefix.is_empty() {
                return Err(format!(
                    "{MERGE_GATES_PATH} whenPaths entries must name a repo path, not only '.' components"
                ));
            }
        }
    }
    Ok(suite)
}

/// Message-free `.`-component normalization, shared with the pack contract
/// ([`crate::pack`]) — same normalization, pack-worded errors live with the
/// caller.
pub(crate) fn normalize_relative_path(raw: &str, dot_for_empty: bool) -> String {
    let normalized = Path::new(raw)
        .components()
        .filter_map(|component| match component {
            Component::Normal(part) => Some(part.to_string_lossy().into_owned()),
            Component::CurDir => None,
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("/");
    if normalized.is_empty() && dot_for_empty {
        ".".to_string()
    } else {
        normalized
    }
}

fn validate_gate_suite(suite: &GateSuite) -> Result<(), String> {
    if suite.gates.is_empty() {
        return Err(format!(
            "{MERGE_GATES_PATH} must define at least one merge gate"
        ));
    }
    if !suite.gates.iter().any(|gate| gate.when_paths.is_empty()) {
        return Err(format!(
            "{MERGE_GATES_PATH} must include at least one unconditional gate so every diff is validated"
        ));
    }

    for (index, gate) in suite.gates.iter().enumerate() {
        if gate.command.trim().is_empty() {
            return Err(format!(
                "{MERGE_GATES_PATH} gate {} has an empty command",
                index + 1
            ));
        }
        if gate.command.contains(['\n', '\r', '\0']) {
            return Err(format!(
                "{MERGE_GATES_PATH} gate {} command must be a single non-NUL line",
                index + 1
            ));
        }
        validate_relative_path(&gate.cwd, "cwd", index)?;
        for prefix in &gate.when_paths {
            validate_relative_path(prefix, "whenPaths entry", index)?;
            if prefix == "." {
                return Err(format!(
                    "{MERGE_GATES_PATH} gate {} should omit whenPaths to run unconditionally",
                    index + 1
                ));
            }
        }
    }
    Ok(())
}

fn validate_relative_path(raw: &str, field: &str, gate_index: usize) -> Result<(), String> {
    if raw.trim().is_empty() {
        return Err(format!(
            "{MERGE_GATES_PATH} gate {} has an empty {field}",
            gate_index + 1
        ));
    }
    let path = Path::new(raw);
    if path.is_absolute()
        || path
            .components()
            .any(|part| !matches!(part, Component::CurDir | Component::Normal(_)))
    {
        return Err(format!(
            "{MERGE_GATES_PATH} gate {} {field} must be repo-relative without parent components: {raw:?}",
            gate_index + 1
        ));
    }
    Ok(())
}

/// Run applicable gates in declared order, stopping on the first failure.
pub fn run_gate_suite<F>(
    repo_root: &Path,
    changed_paths: &[String],
    suite: &GateSuite,
    executor: F,
) -> GateSuiteResult
where
    F: Fn(&str, &Path) -> (bool, String),
{
    for gate in &suite.gates {
        if !gate_applies(gate, changed_paths) {
            continue;
        }
        let cwd: PathBuf = if gate.cwd == "." {
            repo_root.to_path_buf()
        } else {
            repo_root.join(&gate.cwd)
        };
        let (ok, output) = executor(&gate.command, &cwd);
        if !ok {
            return GateSuiteResult::Failed {
                gate: gate.command.clone(),
                output,
            };
        }
    }
    GateSuiteResult::Passed
}

fn gate_applies(gate: &Gate, changed_paths: &[String]) -> bool {
    when_paths_match(&gate.when_paths, changed_paths)
}

/// The `whenPaths` applicability rule, shared with the pack contract
/// ([`crate::pack`]): empty prefixes match everything (the gate runs
/// unconditionally); otherwise at least one changed path must equal a prefix
/// or sit below it. Trailing slashes on a prefix are insignificant.
pub(crate) fn when_paths_match(when_paths: &[String], changed_paths: &[String]) -> bool {
    when_paths.is_empty()
        || when_paths.iter().any(|prefix| {
            let prefix = prefix.trim_end_matches('/');
            changed_paths.iter().any(|path| {
                path == prefix
                    || path
                        .strip_prefix(prefix)
                        .is_some_and(|rest| rest.starts_with('/'))
            })
        })
}

/// The merge-gate suite adapted to the first-class [`crate::gate::Gate`]
/// interface (ticket `.kranz/tickets/gate-plugin-interface.md`).
///
/// The adapter is a thin, behavior-preserving wrapper: `evaluate` delegates
/// to [`run_gate_suite`], so the suite runs the same commands in the same
/// declared order and still stops at the first failure. The suite is a
/// deterministic, boolean-only gate — it reports no confidence score — and
/// its artefact is the failing gate's command plus captured output, or the
/// tracked suite path when every gate passed. Ownership is unchanged: the
/// suite bytes are read from the live base branch by [`crate::merge`], so a
/// mission cannot weaken or reorder the gates that judge its own diff.
pub struct MergeSuiteGate<F> {
    repo_root: PathBuf,
    changed_paths: Vec<String>,
    suite: GateSuite,
    executor: F,
}

impl<F> MergeSuiteGate<F>
where
    F: Fn(&str, &Path) -> (bool, String),
{
    pub fn new(repo_root: &Path, changed_paths: &[String], suite: GateSuite, executor: F) -> Self {
        Self {
            repo_root: repo_root.to_path_buf(),
            changed_paths: changed_paths.to_vec(),
            suite,
            executor,
        }
    }
}

impl<F> crate::gate::Gate for MergeSuiteGate<F>
where
    F: Fn(&str, &Path) -> (bool, String),
{
    fn name(&self) -> &str {
        "merge-gate-suite"
    }

    fn kind(&self) -> crate::gate::GateKind {
        crate::gate::GateKind::Deterministic
    }

    fn evaluate(&self) -> crate::gate::GateOutcome {
        use crate::gate::{ArtefactRef, GateOutcome};
        match run_gate_suite(
            &self.repo_root,
            &self.changed_paths,
            &self.suite,
            &self.executor,
        ) {
            GateSuiteResult::Passed => GateOutcome::pass(ArtefactRef::new(MERGE_GATES_PATH)),
            GateSuiteResult::Failed { gate, output } => {
                GateOutcome::fail(ArtefactRef::new(gate).with_detail(output))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::RefCell;

    struct FakeExecutor {
        calls: RefCell<Vec<(String, PathBuf)>>,
        failing_command: Option<&'static str>,
    }

    impl FakeExecutor {
        fn all_pass() -> Self {
            Self {
                calls: RefCell::new(Vec::new()),
                failing_command: None,
            }
        }

        fn failing(command: &'static str) -> Self {
            Self {
                calls: RefCell::new(Vec::new()),
                failing_command: Some(command),
            }
        }

        fn run(&self, command: &str, cwd: &Path) -> (bool, String) {
            self.calls
                .borrow_mut()
                .push((command.to_string(), cwd.to_path_buf()));
            if self.failing_command == Some(command) {
                (false, "gate failed".to_string())
            } else {
                (true, String::new())
            }
        }
    }

    fn suite() -> GateSuite {
        parse_gate_suite(
            br#"{
                "gates": [
                    {"command":"cargo test --workspace","cwd":"."},
                    {"command":"npm test","cwd":"apps/dashboard","whenPaths":["apps/dashboard"]}
                ]
            }"#,
        )
        .unwrap()
    }

    #[test]
    fn parse_rejects_empty_or_conditional_only_suites() {
        assert!(parse_gate_suite(br#"{"gates":[]}"#)
            .unwrap_err()
            .contains("at least one"));
        assert!(
            parse_gate_suite(br#"{"gates":[{"command":"npm test","whenPaths":["web"]}]}"#)
                .unwrap_err()
                .contains("unconditional")
        );
    }

    /// Composition audit (ticket `config-fail-open-audit`): the merge-gate
    /// suite fails CLOSED on every weakening shape — an unparseable file, an
    /// empty gate list, a suite with no unconditional gate (every gate
    /// skippable by a narrow diff), a `whenPaths` entry spelling `.` (which
    /// must be omitted, not spelled), and path escapes. A merge must never
    /// go green because the config judging it got narrower.
    #[test]
    fn composition_audit_merge_gate_suite_fails_closed_on_every_weakening_shape() {
        assert!(parse_gate_suite(b"not json").is_err());
        assert!(parse_gate_suite(br#"{"gates":[]}"#).is_err());
        assert!(
            parse_gate_suite(br#"{"gates":[{"command":"npm test","whenPaths":["web"]}]}"#).is_err()
        );
        assert!(parse_gate_suite(
            br#"{"gates":[{"command":"a","whenPaths":["."]},{"command":"b"}]}"#
        )
        .is_err());
        assert!(parse_gate_suite(br#"{"gates":[{"command":"a","cwd":"../x"}]}"#).is_err());
        // The same weakening shapes are refused when the suite is otherwise
        // well-formed — the fail-closed checks are not order-dependent.
        assert!(parse_gate_suite(
            br#"{"gates":[{"command":"ok"},{"command":"npm test","whenPaths":["web"]}]}"#
        )
        .is_ok());
    }

    #[test]
    fn parse_rejects_paths_that_escape_the_repo() {
        for text in [
            br#"{"gates":[{"command":"test","cwd":"../outside"}]}"#.as_slice(),
            br#"{"gates":[{"command":"test","whenPaths":["/tmp"]},{"command":"ok"}]}"#.as_slice(),
        ] {
            assert!(parse_gate_suite(text)
                .unwrap_err()
                .contains("repo-relative without parent components"));
        }
    }

    #[test]
    fn unconditional_and_matching_conditional_gates_run_in_order() {
        let root = PathBuf::from("/repo");
        let exec = FakeExecutor::all_pass();
        let result = run_gate_suite(
            &root,
            &["apps/dashboard/src/App.tsx".to_string()],
            &suite(),
            |cmd, cwd| exec.run(cmd, cwd),
        );
        assert_eq!(result, GateSuiteResult::Passed);
        assert_eq!(
            *exec.calls.borrow(),
            vec![
                ("cargo test --workspace".to_string(), root.clone()),
                ("npm test".to_string(), root.join("apps/dashboard")),
            ]
        );
    }

    #[test]
    fn dot_prefixed_paths_are_normalized_before_matching() {
        let suite = parse_gate_suite(
            br#"{"gates":[{"command":"always"},{"command":"web","cwd":"./apps/dashboard","whenPaths":["./apps/dashboard/"]}]}"#,
        )
        .unwrap();
        assert_eq!(suite.gates[1].cwd, "apps/dashboard");
        assert_eq!(suite.gates[1].when_paths, ["apps/dashboard"]);

        let exec = FakeExecutor::all_pass();
        let result = run_gate_suite(
            Path::new("/repo"),
            &["apps/dashboard/src/App.tsx".to_string()],
            &suite,
            |cmd, cwd| exec.run(cmd, cwd),
        );
        assert_eq!(result, GateSuiteResult::Passed);
        assert_eq!(exec.calls.borrow().len(), 2);
    }

    #[test]
    fn unrelated_diff_skips_conditional_gate() {
        let root = PathBuf::from("/repo");
        let exec = FakeExecutor::all_pass();
        run_gate_suite(
            &root,
            &["crates/engine/src/lib.rs".to_string()],
            &suite(),
            |cmd, cwd| exec.run(cmd, cwd),
        );
        assert_eq!(exec.calls.borrow().len(), 1);
        assert_eq!(exec.calls.borrow()[0].0, "cargo test --workspace");
    }

    #[test]
    fn first_failure_stops_the_suite() {
        let root = PathBuf::from("/repo");
        let exec = FakeExecutor::failing("cargo test --workspace");
        let result = run_gate_suite(
            &root,
            &["apps/dashboard/src/App.tsx".to_string()],
            &suite(),
            |cmd, cwd| exec.run(cmd, cwd),
        );
        assert_eq!(
            result,
            GateSuiteResult::Failed {
                gate: "cargo test --workspace".to_string(),
                output: "gate failed".to_string(),
            }
        );
        assert_eq!(exec.calls.borrow().len(), 1);
    }

    #[test]
    fn gate_plugin_merge_suite_runs_through_the_interface_unchanged() {
        use crate::gate::Gate;
        let root = PathBuf::from("/repo");
        let exec = FakeExecutor::all_pass();
        let gate = MergeSuiteGate::new(
            &root,
            &["apps/dashboard/src/App.tsx".to_string()],
            suite(),
            |cmd, cwd| exec.run(cmd, cwd),
        );
        assert_eq!(gate.name(), "merge-gate-suite");
        assert_eq!(gate.kind(), crate::gate::GateKind::Deterministic);

        let outcome = gate.evaluate();
        assert!(outcome.passed());
        assert_eq!(outcome.score, None, "the suite is a boolean-only gate");
        assert_eq!(outcome.artefact.reference, MERGE_GATES_PATH);
        assert_eq!(outcome.artefact.detail, None);
        assert_eq!(
            *exec.calls.borrow(),
            vec![
                ("cargo test --workspace".to_string(), root.clone()),
                ("npm test".to_string(), root.join("apps/dashboard")),
            ],
            "same commands, same order as run_gate_suite"
        );
    }

    #[test]
    fn gate_plugin_merge_suite_stops_at_first_failure_through_the_interface() {
        use crate::gate::Gate;
        let root = PathBuf::from("/repo");
        let exec = FakeExecutor::failing("cargo test --workspace");
        let gate = MergeSuiteGate::new(
            &root,
            &["apps/dashboard/src/App.tsx".to_string()],
            suite(),
            |cmd, cwd| exec.run(cmd, cwd),
        );

        let outcome = gate.evaluate();
        assert!(!outcome.passed());
        assert_eq!(outcome.artefact.reference, "cargo test --workspace");
        assert_eq!(outcome.artefact.detail.as_deref(), Some("gate failed"));
        assert_eq!(exec.calls.borrow().len(), 1, "later gates never ran");
    }

    #[test]
    fn gate_plugin_merge_suite_skips_unrelated_conditional_gates() {
        use crate::gate::Gate;
        let root = PathBuf::from("/repo");
        let exec = FakeExecutor::all_pass();
        let gate = MergeSuiteGate::new(
            &root,
            &["crates/engine/src/lib.rs".to_string()],
            suite(),
            |cmd, cwd| exec.run(cmd, cwd),
        );

        assert!(gate.evaluate().passed());
        assert_eq!(exec.calls.borrow().len(), 1);
        assert_eq!(exec.calls.borrow()[0].0, "cargo test --workspace");
    }
}