pushkin 0.2.1

Schema-first enforcement harness that gates AI coding agents' file writes against project contracts
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! `pushkin floor`: stage-5 lint/typecheck orchestration (spec §8.2 stage 5).
//! Authorized by `docs/claude_stage5-floor-verb-charter-2026-08-18.md`
//! (Workstream A step 1 of `docs/charters/2026-08-18-coding-standards-stream.md`,
//! RATIFIED 2026-08-18). Workstream C's manifest rule classes are NOT authorized
//! and nothing here anticipates them (N12): no per-path lint profile, no new
//! `require` value, no write-time rule id.
//!
//! The `[floor]` table in `pushkin.toml` is the ONE copy of the §C.13 floor —
//! the same sequence the `Makefile`, `scripts/floor.sh` and CI run. "Mirrors CI
//! commands exactly" has to be mechanical for the reason D7(a) exists:
//! completeness must not depend on anyone remembering.
//!
//! CI-shaped exit contract, the same one `check` and `db` carry (ruling R-C):
//! **0 = clean, 2 = findings (blocks), 1 = the gate itself could not run.** This
//! inverts ESLint/ruff's numbering; the inversion is disclosed in `--help` and
//! here rather than left for someone to trip over. Any nonzero aborts a git hook
//! either way. The distinction is the point: a floor that cannot tell "your code
//! is wrong" from "I could not look" reports clean when it checked nothing, and
//! that is the F62 class — a cited number counting less than it claimed.
//!
//! A missing binary is a loud, named failure carrying its declared install
//! command, exit 1 — never a silent skip (§7 rider, the `db.rs` `run_tool`
//! pattern). Anything skipped by configuration is disclosed BY NAME, and a
//! skipped run never prints a bare green verdict: that is `scripts/floor.sh`'s
//! EXCLUDED banner generalized, which exists so partial output "cannot be
//! mistaken for, or pasted as, a full floor."
//!
//! **Deliberately NOT in scope.** No per-file execution: everything declared
//! runs whole-repo, and the `scope` field is recorded contract for a future warm
//! charter, not a switch this verb reads. No decomposition of clippy — it is a
//! whole-crate rustc driver and has no per-file mode. No daemon or warm path:
//! this verb is cold-path only, so Workstream D is untouched. No `Decision`
//! arm, no `CheckResult` field, no change to the §8.3 write-time envelope —
//! stage 5 does not ride it, which is why `check_write` is byte-identical
//! before and after this pass.

use anyhow::{bail, Result};
use pushkin_core::envelope::{Severity, Violation};
use pushkin_core::floor_report::{reconcile, tally, IgnoredVerdict, Tally};
use pushkin_core::manifest::{Floor, FloorCommand, Manifest};
use std::time::Instant;

use super::load_manifest;

/// What one declared command did.
struct Ran<'a> {
    command: &'a FloorCommand,
    green: bool,
    millis: u128,
    counts: Tally,
    /// stdout+stderr, kept so a Stop block can carry the failing tail.
    captured: String,
}

/// `pushkin floor`.
///
/// # Errors
/// Propagates manifest load/parse failure. A declared command that cannot be
/// launched is reported and returns exit 1 rather than erroring, so the
/// commands that already ran are still credited.
pub fn run(skip: &[String]) -> Result<i32> {
    let manifest = load_manifest()?;
    let floor = require_floor(&manifest)?;
    let planned = plan(floor, skip)?;

    // The verdict names its own basis (F73, ruling §2.2): which tree, and which
    // manifest declared the table that produced it.
    println!(
        "pushkin floor — {} — manifest {}",
        head_sha(),
        super::manifest_display()
    );
    if !skip.is_empty() {
        println!("EXCLUDED (--skip): {}", skip.join(", "));
        println!("THIS IS NOT A FULL FLOOR. Do not cite this output as one.");
    }
    println!();

    let mut ran: Vec<Ran> = Vec::with_capacity(planned.len());
    for command in &planned {
        match execute(command) {
            Ok(outcome) => {
                print!("{}", outcome.captured);
                report_line(&outcome);
                ran.push(outcome);
            }
            Err(error) => {
                // Could-not-run. Credit what already ran, then exit 1 — never 2
                // (that would call a toolchain gap a finding) and never 0.
                println!();
                summarize_partial(&ran);
                eprintln!("pushkin floor: {error}");
                return Ok(1);
            }
        }
    }

    let verdicts = reconcile_all(&ran, floor, skip);
    Ok(finish(&ran, &verdicts, skip, floor))
}

/// Short HEAD SHA for the header, matching what `scripts/floor.sh` printed for
/// every floor citation in this repo's history — the line a reader uses to tell
/// which tree a pasted floor belongs to. `no git` when there is no repo, rather
/// than an empty header that reads as a missing field.
fn head_sha() -> String {
    super::git::head_sha().unwrap_or_else(|| "no git".to_owned())
}

fn require_floor(manifest: &Manifest) -> Result<&Floor> {
    let Some(floor) = manifest.floor.as_ref() else {
        bail!(
            "no [floor] table in pushkin.toml — declare the floor commands \
             before running the mechanical floor. A repo that has not declared \
             its floor has not got one, and reporting green over zero commands \
             would be the loudest possible way to count less than you claim."
        );
    };
    if floor.commands.is_empty() {
        bail!(
            "[floor] in pushkin.toml declares no commands — there is nothing to \
             run, and a verdict over zero commands is vacuous, not green."
        );
    }
    Ok(floor)
}

/// Resolves `--skip` against the declared table. An unmatched name is an error,
/// not a no-op: a typo that silently skipped nothing would let an operator
/// believe they had excluded a gate they in fact ran, or the reverse.
fn plan<'a>(floor: &'a Floor, skip: &[String]) -> Result<Vec<&'a FloorCommand>> {
    for name in skip {
        if !floor.commands.iter().any(|c| &c.name == name) {
            let declared: Vec<&str> = floor.commands.iter().map(|c| c.name.as_str()).collect();
            bail!(
                "--skip named '{name}', which is not a declared floor command; \
                 declared commands: {}",
                declared.join(", ")
            );
        }
    }
    let planned: Vec<&FloorCommand> = floor
        .commands
        .iter()
        .filter(|c| !skip.contains(&c.name))
        .collect();
    if planned.is_empty() {
        bail!(
            "--skip excluded every declared floor command; there is nothing \
             left to run, and an empty run is not a green floor."
        );
    }
    Ok(planned)
}

/// Runs one declared command. `Err` is could-not-run (exit 1); a nonzero status
/// is a finding, which is `Ok` with `green: false`.
fn execute(command: &FloorCommand) -> Result<Ran<'_>> {
    // argv, never a shell string: a shell string is an injection surface and a
    // quoting-bug surface, and neither belongs in a gate.
    let (program, args) = command
        .run
        .split_first()
        .ok_or_else(|| anyhow::anyhow!("floor command '{}' has an empty run", command.name))?;
    let started = Instant::now();
    // FACADE-EXEMPT: the [floor] table runner executes operator-declared argv
    // from pushkin.toml — running that command IS the product, not a vendored
    // tool behind a facade (charter 2026-08-20-r1-facades §3c).
    let output = match std::process::Command::new(program).args(args).output() {
        Ok(output) => output,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            let hint = command.install.as_deref().map_or_else(
                || " (no install hint declared for it in [floor])".to_owned(),
                |install| format!(" (install it: `{install}`)"),
            );
            bail!(
                "floor command '{}' needs `{program}`, which is not installed{hint}",
                command.name
            );
        }
        Err(error) => bail!(
            "floor command '{}' could not run `{program}`: {error}",
            command.name
        ),
    };
    let millis = started.elapsed().as_millis();
    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    // NOT printed here: `on_stop_violations` runs the same function inside the
    // hook, whose stdout must be pure JSON for the host to parse. Streaming is
    // the verb's job, done by its caller.
    Ok(Ran {
        command,
        green: output.status.success(),
        millis,
        counts: tally(&combined),
        captured: combined,
    })
}

fn report_line(outcome: &Ran) {
    println!(
        "  {:<12} {:<11} {:<9} {:>7}ms  {}",
        outcome.command.name,
        scope_label(outcome.command),
        inputs_label(outcome.command),
        outcome.millis,
        if outcome.green { "green" } else { "RED" }
    );
}

fn scope_label(command: &FloorCommand) -> &'static str {
    use pushkin_core::manifest::FloorScope;
    match command.scope {
        FloorScope::PerFile => "per_file",
        FloorScope::PerCrate => "per_crate",
        FloorScope::WholeRepo => "whole_repo",
    }
}

fn inputs_label(command: &FloorCommand) -> &'static str {
    use pushkin_core::manifest::FloorInputs;
    match command.inputs.value() {
        FloorInputs::Repo => "repo",
        FloorInputs::Toolchain => "toolchain",
        FloorInputs::Network => "network",
        FloorInputs::Machine => "machine",
    }
}

/// F79's disclosure. A display-only value the parser did not recognize was
/// degraded to its default instead of rejecting the manifest (ADR-0007), and a
/// degradation that leaves no trace is the F71/F74 shape — so the one place
/// the field is rendered is the place that says so. Names the row, the raw
/// text and the applied class: a NOTE that only says "something degraded"
/// sends the reader back to guess which line. Silent when nothing degraded —
/// a disclosure that always prints is noise.
fn disclose_degraded_inputs(floor: &Floor) {
    let degraded: Vec<String> = floor
        .commands
        .iter()
        .filter_map(|command| {
            command.inputs.degraded_from().map(|raw| {
                format!(
                    "{} (inputs = \"{raw}\", reported as \"{}\")",
                    command.name,
                    inputs_label(command)
                )
            })
        })
        .collect();
    if degraded.is_empty() {
        return;
    }
    println!(
        "NOTE: an inputs value was not recognized on {} — the field is \
         display-only, so the command ran and is reported with the default \
         class. Valid values: repo, toolchain, network, machine. Fix the \
         spelling to make this line go away.",
        degraded.join(", ")
    );
    println!();
}

/// One `reconcile_ignored` command's accounting outcome.
struct Accounting<'a> {
    name: &'a str,
    verdict: IgnoredVerdict,
    /// The declared coverer exists but was excluded by `--skip`.
    ///
    /// Such a run is still reported — the gap is stated in full — but it does
    /// not turn the floor RED, because the run has ALREADY disclaimed
    /// completeness: `--skip` prints the EXCLUDED banner, marks the output NOT
    /// A FULL FLOOR, and qualifies the verdict. RED exists for a run that
    /// CLAIMS completeness and does not have it, which is the F62 defect. A run
    /// that announces the exact gap the operator asked for is not that, and
    /// making it RED anyway would mean the only way to skip the slow gate is to
    /// accept a red floor — which teaches people to ignore red.
    excused_by_skip: bool,
}

/// Grades every `reconcile_ignored` command against its declared coverer.
///
/// The coverer is looked up among commands that ACTUALLY RAN, not among those
/// declared: a coverer excluded by `--skip` covers nothing, and counting its
/// tests as run would let a skip launder the accounting into a green it did not
/// earn. So the verdict stays honest — uncovered is uncovered — and the skip is
/// recorded separately as the reason, rather than by falsifying the count.
fn reconcile_all<'a>(ran: &[Ran<'a>], floor: &Floor, skip: &[String]) -> Vec<Accounting<'a>> {
    let mut verdicts = Vec::new();
    for outcome in ran.iter().filter(|r| r.command.reconcile_ignored) {
        let name = outcome.command.name.as_str();
        let covered = ran
            .iter()
            .find(|r| r.command.covers_ignored_of.as_deref() == Some(name))
            .map(|r| r.counts.passed);
        // Excused only when a coverer IS declared for this command and the
        // operator skipped that specific command. An undeclared coverer is the
        // F62 defect and stays RED however the run was invoked — `--skip` must
        // not become a way to silence a gap nobody asked about.
        let excused_by_skip = covered.is_none()
            && floor
                .commands
                .iter()
                .any(|c| c.covers_ignored_of.as_deref() == Some(name) && skip.contains(&c.name));
        verdicts.push(Accounting {
            name,
            verdict: reconcile(outcome.counts.ignored, covered),
            excused_by_skip,
        });
    }
    verdicts
}

fn summarize_partial(ran: &[Ran]) {
    if ran.is_empty() {
        println!("--- no floor command completed before the failure ---");
        return;
    }
    println!("--- commands that ran before the failure ---");
    for outcome in ran {
        println!(
            "  {:<12} {}",
            outcome.command.name,
            if outcome.green { "green" } else { "RED" }
        );
    }
}

/// The summary block and the exit code.
fn finish(ran: &[Ran], verdicts: &[Accounting], skip: &[String], floor: &Floor) -> i32 {
    println!();
    let reds: Vec<&str> = ran
        .iter()
        .filter(|r| !r.green)
        .map(|r| r.command.name.as_str())
        .collect();
    let passed: u64 = ran.iter().map(|r| r.counts.passed).sum();
    let failed: u64 = ran.iter().map(|r| r.counts.failed).sum();

    if !verdicts.is_empty() {
        println!("--- ignored-test reconciliation ---");
        for entry in verdicts {
            // The excused case gets its OWN wording rather than the core
            // verdict's. `Uncovered`'s prose says "no command declares
            // covers_ignored_of", which is false here — one does, and the
            // operator skipped it. Printing a message that is wrong about why
            // is how a correct gate loses an operator's trust.
            if entry.excused_by_skip {
                println!(
                    "  {}: {} ignored, and the command declared to cover them \
                     was excluded by --skip. They did NOT run. Not counted \
                     against this floor — the run is already marked NOT A FULL \
                     FLOOR — but re-run without --skip before citing anything.",
                    entry.name,
                    entry.verdict.ignored_count()
                );
            } else {
                println!("  {}: {}", entry.name, entry.verdict.message());
            }
        }
        println!();
    }

    // F69's rider, disclosed only when it applies: a disclosure that always
    // prints is noise, and noise is what gets ignored.
    let networked: Vec<&str> = floor
        .commands
        .iter()
        .filter(|c| {
            matches!(
                c.inputs.value(),
                pushkin_core::manifest::FloorInputs::Network
            )
        })
        .map(|c| c.name.as_str())
        .collect();
    if !networked.is_empty() {
        println!(
            "NOTE: {} consult(s) a network source, so this verdict is not a pure \
             function of the commit — an unchanged commit can newly fail when \
             upstream data changes.",
            networked.join(", ")
        );
        println!();
    }

    // F76's addendum. A separate line from the network one on purpose: the
    // causes differ, and "upstream data changed" is simply the wrong reason for
    // a latency flake. Scoped to commands that actually ran: a --skip'd command
    // produced no verdict, so naming it here points "re-run quiet before citing
    // a RED" at a RED that does not exist (CI runs `floor --skip bench`, and
    // bench is the sole machine-class command).
    let load_bound: Vec<&str> = floor
        .commands
        .iter()
        .filter(|c| {
            matches!(
                c.inputs.value(),
                pushkin_core::manifest::FloorInputs::Machine
            )
        })
        .filter(|c| !skip.contains(&c.name))
        .map(|c| c.name.as_str())
        .collect();
    if !load_bound.is_empty() {
        println!(
            "NOTE: {} measure(s) wall-clock time, so this verdict depends on what \
             else the machine is doing — a busy machine can fail a commit that \
             passes on a quiet one. Re-run quiet before citing a RED.",
            load_bound.join(", ")
        );
        println!();
    }

    disclose_degraded_inputs(floor);

    println!("  commands: {} run, {} red", ran.len(), reds.len());
    if passed > 0 || failed > 0 {
        println!("  tests:    {passed} passed / {failed} failed");
    }

    let accounting_red = verdicts
        .iter()
        .any(|entry| entry.verdict.is_red() && !entry.excused_by_skip);
    let excluded = if skip.is_empty() {
        String::new()
    } else {
        format!(" (EXCLUDED: {})", skip.join(", "))
    };

    if reds.is_empty() && !accounting_red {
        println!("FLOOR: green{excluded}");
        0
    } else {
        if !reds.is_empty() {
            println!("  red:      {}", reds.join(", "));
        }
        println!("FLOOR: RED{excluded}");
        2
    }
}

/// The `on_stop` subset, run for the Stop sweep (W6) — returns one `Violation`
/// per declared command that failed or could not run.
///
/// **Ships dark by construction.** `on_stop` defaults to `false`, so a manifest
/// that has not opted a command in returns an empty vector and Stop behaves
/// exactly as it did before this existed. A repo with no `[floor]` table returns
/// empty too: the verb's refusal to run without one is the VERB's contract, and
/// inheriting it here would turn every Stop in every undeclared repo into a
/// block — well past what opting in to nothing should cost.
///
/// **A command that could not run BLOCKS.** That is the §7 rider at Stop: a gate
/// that could not run is not a gate that passed, and the alternative is the
/// silent skip the whole posture forbids. The install hint travels in the fix
/// hint so the block is actionable.
///
/// The rule id is `floor.<name>` so the agent — and the event log — can tell
/// WHICH gate objected. These violations exist only inside the Stop sweep's
/// result; no rule id is added to `pipeline.rs`, because a write-time stage-5
/// rule is the Workstream C groundwork N12 forbids.
#[must_use]
pub fn on_stop_violations(manifest: &Manifest) -> Vec<Violation> {
    let Some(floor) = manifest.floor.as_ref() else {
        return Vec::new();
    };
    let mut violations = Vec::new();
    for command in floor.commands.iter().filter(|c| c.on_stop) {
        let (rule, detail) = match execute(command) {
            Ok(outcome) if outcome.green => continue,
            Ok(outcome) => (
                format!("floor.{}", command.name),
                tail_of(&outcome.captured),
            ),
            Err(error) => (format!("floor.{}", command.name), error.to_string()),
        };
        violations.push(Violation {
            file: String::new(),
            line: 0,
            rule,
            contract: None,
            fix_hint: format!("{detail} — run `pushkin floor` locally to reproduce and fix it."),
            suggestions: Vec::new(),
            severity: Severity::Error,
        });
    }
    violations
}

/// The `on_new_read_only` subset, run by `check --staged` when a commit stages a
/// NEW file under a `read_only_paths` glob (F72) — returns one `Violation` per
/// declared command that failed or could not run.
///
/// This is the deliberate sibling of [`on_stop_violations`]: same filter shape,
/// same could-not-run-BLOCKS rider, same `floor.<name>` rule id. The two differ
/// only in the bool they read and the moment they run. The pre-RED gate fires at
/// the last commit before editing the staged file becomes an N10 violation, so a
/// lint failure caught here is fixable while the file is still free to change —
/// the whole point of F72.
///
/// **Ships dark by construction.** `on_new_read_only` defaults to `false`, so a
/// manifest that has opted nothing in returns an empty vector and `check
/// --staged` behaves exactly as it did before this existed. A repo with no
/// `[floor]` table returns empty too — the verb's refusal to run without one is
/// the verb's contract, not this arm's.
#[must_use]
pub fn new_read_only_violations(manifest: &Manifest) -> Vec<Violation> {
    let Some(floor) = manifest.floor.as_ref() else {
        return Vec::new();
    };
    let mut violations = Vec::new();
    for command in floor.commands.iter().filter(|c| c.on_new_read_only) {
        let (rule, detail) = match execute(command) {
            Ok(outcome) if outcome.green => continue,
            Ok(outcome) => (
                format!("floor.{}", command.name),
                tail_of(&outcome.captured),
            ),
            Err(error) => (format!("floor.{}", command.name), error.to_string()),
        };
        violations.push(Violation {
            file: String::new(),
            line: 0,
            rule,
            contract: None,
            fix_hint: format!(
                "{detail} — a new read-only file was staged; run `pushkin floor` \
                 locally to reproduce and fix it before committing."
            ),
            suggestions: Vec::new(),
            severity: Severity::Error,
        });
    }
    violations
}

/// Last few lines of a failing command's output — enough to say what broke
/// without pasting an entire test run into a hook payload.
fn tail_of(output: &str) -> String {
    let lines: Vec<&str> = output.lines().filter(|l| !l.trim().is_empty()).collect();
    let start = lines.len().saturating_sub(FAILURE_TAIL_LINES);
    lines[start..].join("\n")
}

/// How much of a failing command's output travels into the Stop block.
const FAILURE_TAIL_LINES: usize = 8;