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
//! `pushkin check`: stdin hook payload → gate decision. Exit 0 allow,
//! exit 2 block (+ retry prompt on stderr). A Stop payload (no `tool_input`)
//! sweeps every mapped file in the repo (spec §8.1: cheap per-edit,
//! expensive on Stop). Fail-open on malformed input is LOGGED as an event;
//! a partial parse that reveals a protected-path target fails CLOSED
//! (review directives, Phase 1 plan).
//!
//! `--staged` (spec §12) gates the git INDEX instead of reading stdin —
//! the pre-commit floor's scope: only files this commit actually ships.
//! `--json` swaps the prose retry prompt for the §8.3 envelope on stdout.

use anyhow::Result;
use pushkin_core::envelope::{CheckResult, Decision, Violation};
use pushkin_core::events::EventLog;
use pushkin_core::manifest::Manifest;
use pushkin_core::pipeline::{check_write, WriteRequest};
use std::io::Read;

use super::{apply_waivers, events_db_path, load_manifest};

/// How the verdict is rendered: prose retry prompt (the agent-facing
/// default) or the uniform §8.3 envelope as JSON (spec §17's floor).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Output {
    Prose,
    Json,
}

impl Output {
    fn from_flag(json: bool) -> Self {
        if json {
            Output::Json
        } else {
            Output::Prose
        }
    }
}

/// The `pushkin check` invocation (spec §12): gate the git index (`staged`) or
/// stdin, rendered as the §8.3 JSON envelope (`json`) or prose. Bundled so the
/// two flags never read as a bare `run(true, false)` at the call site.
#[derive(Clone, Copy)]
pub struct CheckArgs {
    pub staged: bool,
    pub json: bool,
}

pub fn run(args: CheckArgs) -> Result<i32> {
    let CheckArgs { staged, json } = args;
    let output = Output::from_flag(json);
    // F71 Phase B, Addendum 4 (2026-08-19): the ratified N13 rider holds here
    // — "no error class of a check that ran fails open". An unloadable
    // manifest errs loudly below and blocks the commit with its own error
    // text; `git commit --no-verify` is the documented escape. Addendum 1's
    // warn-and-pass reading was corrected — it had not priced the rider's
    // error clause or `lefthook_fail_open.rs`, which pins this exact case.
    let manifest = load_manifest()?;

    // The [features] git-plane switch covers the staged check itself, so
    // a floor still installed somewhere (a teammate's clone, CI) obeys
    // the committed manifest rather than its own install state. Positive
    // probe only: a broken manifest already erred loudly above, exactly
    // per the ratified N13 exit contract. A notice, not silence — a
    // skipped gate the human turned off is still worth one stderr line.
    // Agent write-time gating (the stdin path below) is deliberately
    // untouched.
    if staged && !manifest.git_hooks_enabled() {
        eprintln!(
            "pushkin: git hooks disabled ([features] git_hooks = false in \
             pushkin.toml); staged check skipped"
        );
        return Ok(0);
    }

    let log = EventLog::open(events_db_path()?)?;
    let session = log.begin_session()?;

    // --staged never touches stdin: git is the input (spec §12).
    if staged {
        let result = apply_waivers(check_staged(&manifest)?);
        log.append(&session, &result)?;
        return Ok(emit(&result, output));
    }

    let mut raw = String::new();
    std::io::stdin().read_to_string(&mut raw)?;

    // The three well-formed shapes route through the shared evaluation
    // (`super::decide`, Shape 2) as the `Floor` surface; each keeps check's own
    // rendering below. `ToolAction.session` is unread by `decide` — check tracks
    // its own session for the event log — so it is left empty here.
    let action = match parse_payload(&raw) {
        Ok(Payload::Write(request)) => crate::agents::ToolAction {
            session: String::new(),
            files: vec![crate::agents::FileWrite {
                path: request.file_path,
                content: request.content,
                edits: vec![],
            }],
            is_stop: false,
            intent: crate::agents::Intent::Write,
            command: None,
        },
        Ok(Payload::Stop) => crate::agents::ToolAction {
            session: String::new(),
            files: vec![],
            is_stop: true,
            intent: crate::agents::Intent::Write,
            command: None,
        },
        // F48 Phase A — path rules decide from the payload, content rules refuse
        // rather than being skipped. `decide` runs the identical leaf for both
        // surfaces, so this is no longer a parallel implementation to keep in step.
        Ok(Payload::MutateNoContent { file, tool }) => crate::agents::ToolAction {
            session: String::new(),
            files: vec![file],
            is_stop: false,
            intent: crate::agents::Intent::MutateNoContent(tool),
            command: None,
        },
        Err(partial) => {
            // Partial parse revealing a protected-path target → fail CLOSED.
            if let Some(file_path) = partial {
                if manifest.is_protected(&file_path) {
                    let result = check_write(
                        &manifest,
                        &WriteRequest {
                            file_path,
                            content: String::new(),
                        },
                    );
                    log.append(&session, &result)?;
                    return Ok(emit(&result, output));
                }
            }
            // F60 — same contract as the hook verb: a payload we cannot read
            // still fails closed when it NAMES a path under an unwaivable rule.
            // The two surfaces are parallel implementations of one rule, so a
            // change to either is a change to both.
            let scanned = apply_waivers(super::gate_unreadable_payload(&manifest, &raw));
            if !scanned.violations.is_empty() {
                log.append(&session, &scanned)?;
                return Ok(emit(&scanned, output));
            }
            // Otherwise fail open — loudly, and on the record.
            log.append_failopen(&session, "malformed hook payload")?;
            eprintln!(
                "pushkin: unrecognized hook payload, failing open (event logged; \
                 run `pushkin doctor` if this repeats)"
            );
            return Ok(0);
        }
    };

    let result = super::decide(&super::DecideRequest {
        manifest: &manifest,
        action: &action,
        surface: super::Surface::Floor,
    })?;
    log.append(&session, &result)?;
    Ok(emit(&result, output))
}

/// Renders the verdict in the requested shape and returns the exit code:
/// 0 allow, 2 block. JSON goes to stdout (machine-readable, spec §17);
/// prose stays on stderr, where the agent-facing retry prompt has always
/// been.
/// The §8.3 envelope plus the resolved manifest path (F73, ruling §2.2).
///
/// The field is added HERE rather than to `CheckResult` on purpose. `CheckResult`
/// crosses the daemon's IPC wire under `deny_unknown_fields` and is constructed at
/// 26 sites, and `pushkin-core` is deliberately free of filesystem knowledge — it
/// cannot know which manifest the CLI resolved. So the type and the wire are
/// untouched and only the rendered envelope grows a key. Additive: `decision`,
/// `violations` and `durationMs` are unchanged, which is what
/// `gate_dispatch_conformance` reads.
fn envelope_json(result: &CheckResult) -> Option<String> {
    let mut value = serde_json::to_value(result).ok()?;
    value
        .as_object_mut()?
        .insert("manifest".to_owned(), super::manifest_display().into());
    serde_json::to_string_pretty(&value).ok()
}

fn emit(result: &CheckResult, output: Output) -> i32 {
    match output {
        Output::Json => println!(
            "{}",
            envelope_json(result).unwrap_or_else(|| {
                // Unreachable — `CheckResult` is plain derived data that
                // `serde_json` cannot fail to serialize — but a fallback
                // that ever fired must fail loud: deny-shaped by
                // construction, so a serialization bug can never launder a
                // blocking verdict into an allow-shaped envelope (M3).
                r#"{"decision":"block","violations":[],"durationMs":0.0}"#.to_owned()
            })
        ),
        Output::Prose => {
            if !result.violations.is_empty() {
                eprintln!("{}", render(result));
            }
        }
    }
    if result.violations.is_empty() {
        0
    } else {
        2
    }
}

/// Evidence half of the amended charter option B: was an agent denied a
/// protected write to `file` that is still uncommitted?
///
/// The window opens at the last commit TOUCHING this path, so committing the
/// file is what resolves the evidence — which is precisely what "a human
/// should own this change" means in practice. `RULE_PROTECTED_PATH` is
/// deliberately never waivable (`waivers.rs:179-183`, "the harness cannot be
/// negotiated with"), so a waiver is not available as an exit and must not
/// be the design's assumed one.
///
/// Fails OPEN on every error — a missing, locked, or unreadable event log
/// yields `false`, so the floor degrades to the S2d advisory rather than
/// inventing a block from an absent record. The write-time gate is the one
/// that matters; this is a second line, and a second line that guesses is
/// worse than one that abstains.
fn agent_was_denied(file: &str) -> bool {
    let Ok(log) = pushkin_core::events::EventLog::open(std::path::Path::new(super::EVENTS_DB))
    else {
        return false;
    };
    let since = super::last_commit_touching(file).unwrap_or_default();
    log.denied_since(pushkin_core::pipeline::RULE_PROTECTED_PATH, file, &since)
        .unwrap_or(false)
}

/// The pre-commit floor's pass (spec §12, §17): every staged path with a
/// manifest mapping, gated on its INDEX content — `git show :<path>`, not
/// the working tree, because the commit ships the index. Files the author
/// never touched are out of scope by construction.
fn check_staged(manifest: &Manifest) -> Result<CheckResult> {
    let started = std::time::Instant::now();
    let mut violations: Vec<Violation> = Vec::new();
    // Whether any staged path is a NEW file under a read_only_paths glob — the
    // trigger for the pre-RED lint gate (F72). The lints are workspace-scoped,
    // so they run at most once after the loop regardless of how many such files
    // are staged.
    let mut has_new_read_only = false;
    for file_path in super::git::staged_files()? {
        // Protected surface staged: an ADVISORY, never a deny (S2d). The
        // floor runs for humans too, and a human commit of the manifest
        // is legitimate — the write path already denies agents at edit
        // time (and cannot see Bash-side writes; that boundary is the
        // advisory's reason to be loud). The notice stays on stderr so a
        // --json envelope on stdout is unchanged.
        if manifest.is_protected(&file_path) || file_path.starts_with("pushkin/") {
            // ...UNLESS an agent was denied this exact path in the current
            // commit cycle and it is staged anyway. Then the write reached
            // the tree through a surface PreToolUse never saw (`ed`,
            // `git apply`, a shell redirect), and the advisory's own reason
            // to be loud has become evidence: a recorded deny plus a changed
            // tree. That is not a guess about authorship, so it can block.
            // One event, one message — the notice stands down when it does.
            if agent_was_denied(&file_path) {
                violations.push(pushkin_core::pipeline::protected_path_bypass_violation(
                    &file_path,
                ));
                continue;
            }
            eprintln!(
                "pushkin: note — protected surface staged ({file_path}); the write \
                 gate denies agent edits here and this floor does not block commits. \
                 A human should own this change."
            );
        }
        // Read-only paths are checked BEFORE the mapping skip: committed
        // test suites have no contract mapping, and the pre-commit floor
        // is exactly where an agent edit to one must be caught. A staged
        // NEW file is not in HEAD and passes.
        if manifest.is_read_only(&file_path) {
            if super::committed_in_head(&file_path) {
                violations.push(pushkin_core::pipeline::read_only_violation(&file_path));
                continue;
            }
            // A NEW read-only file: the last commit before editing it becomes
            // an N10 violation. Note it so the opted-in lints run once below
            // (F72). It has no contract mapping, so it also skips the rest.
            has_new_read_only = true;
            continue;
        }
        if manifest.mapping_for(&file_path).is_none() {
            continue;
        }
        let Some(content) = super::git::staged_content(&file_path)? else {
            continue;
        };
        violations.extend(check_write(manifest, &WriteRequest { file_path, content }).violations);
    }
    // The pre-RED lint gate (F72): if a NEW read-only file is being frozen, run
    // the commands opted in via `on_new_read_only`. Ships dark — this is empty
    // until a human opts a command in, so a repo that has not returns nothing
    // and this loop is a no-op.
    if has_new_read_only {
        violations.extend(super::floor::new_read_only_violations(manifest));
    }
    Ok(CheckResult {
        decision: if violations.is_empty() {
            Decision::Allow
        } else {
            Decision::Block
        },
        violations,
        duration_ms: started.elapsed().as_secs_f64() * 1000.0,
    })
}

enum Payload {
    Write(WriteRequest),
    Stop,
    /// F48 Phase A — `Edit`/`MultiEdit`: a target named, content absent.
    /// Phase B carries the edit operations too, so the check verb can
    /// reconstruct exactly as the hook verb does.
    MutateNoContent {
        file: crate::agents::FileWrite,
        tool: &'static str,
    },
}

/// `Ok(Write)` on a well-formed `PreToolUse` payload; `Ok(Stop)` on a
/// Stop-event payload (no `tool_input`); `Ok(MutateNoContent)` on an
/// `Edit`/`MultiEdit` payload, which names a target and carries no content;
/// Err(Some(path)) when malformed but a file-path
/// target was recoverable; Err(None) when nothing was.
fn parse_payload(raw: &str) -> Result<Payload, Option<String>> {
    let value: serde_json::Value = serde_json::from_str(raw).map_err(|_| None)?;
    let Some(tool_input) = value.get("tool_input") else {
        // Claude's Stop hook payload carries `stop_hook_active`, never `tool_input`.
        if value.get("stop_hook_active").is_some() {
            return Ok(Payload::Stop);
        }
        return Err(None);
    };
    let file_path = tool_input
        .get("file_path")
        .and_then(serde_json::Value::as_str)
        .ok_or(None)?
        .to_owned();

    let tool_name = value.get("tool_name").and_then(serde_json::Value::as_str);

    // F48 Phase A — recognized BEFORE the write parse below, which treats
    // absent content as malformed. Mirrors `normalize_claude_family`; the two
    // parsers are parallel and must stay in step.
    let mutation_tool = match tool_name {
        Some("Edit") => Some("Edit"),
        Some("MultiEdit") => Some("MultiEdit"),
        _ => None,
    };
    if let Some(tool) = mutation_tool {
        return Ok(Payload::MutateNoContent {
            file: crate::agents::FileWrite {
                path: file_path,
                content: String::new(),
                edits: crate::agents::claude_replacements(tool_input),
            },
            tool,
        });
    }

    let well_formed = tool_name.is_some();
    let content = tool_input
        .get("content")
        .and_then(serde_json::Value::as_str);
    match (well_formed, content) {
        (true, Some(content)) => Ok(Payload::Write(WriteRequest {
            file_path,
            content: content.to_owned(),
        })),
        _ => Err(Some(file_path)),
    }
}

/// The expensive whole-repo pass: every mapped file re-checked with the same
/// core the per-write gate uses. Shared with the hook verb's Stop handling.
pub fn sweep_repo(manifest: &Manifest) -> Result<CheckResult> {
    let started = std::time::Instant::now();
    let mut violations: Vec<Violation> = Vec::new();
    for file_path in walk_repo(std::path::Path::new("."))? {
        if manifest.mapping_for(&file_path).is_none() {
            continue;
        }
        let content = std::fs::read_to_string(&file_path)?;
        violations.extend(check_write(manifest, &WriteRequest { file_path, content }).violations);
    }
    Ok(CheckResult {
        decision: if violations.is_empty() {
            Decision::Allow
        } else {
            Decision::Block
        },
        violations,
        duration_ms: started.elapsed().as_secs_f64() * 1000.0,
    })
}

const IGNORED_DIRS: &[&str] = &["node_modules", ".git", ".pushkin", ".scout", "target"];

fn walk_repo(root: &std::path::Path) -> Result<Vec<String>> {
    let mut files = Vec::new();
    let mut pending = vec![root.to_path_buf()];
    while let Some(dir) = pending.pop() {
        for entry in std::fs::read_dir(&dir)? {
            let entry = entry?;
            let path = entry.path();
            let name = entry.file_name().to_string_lossy().into_owned();
            if path.is_dir() {
                if !IGNORED_DIRS.contains(&name.as_str()) {
                    pending.push(path);
                }
            } else if let Ok(relative) = path.strip_prefix(root) {
                files.push(relative.to_string_lossy().into_owned());
            }
        }
    }
    files.sort();
    Ok(files)
}

fn render(result: &CheckResult) -> String {
    let mut lines = vec!["pushkin: write blocked. Fix the violations below and retry.".to_owned()];
    for violation in &result.violations {
        let contract = violation
            .contract
            .as_deref()
            .map(|name| format!(" (contract: {name})"))
            .unwrap_or_default();
        lines.push(format!(
            "  {}:{} [{}]{contract}",
            violation.file, violation.line, violation.rule
        ));
        lines.push(format!("    fix: {}", violation.fix_hint));
        for suggestion in &violation.suggestions {
            lines.push(format!("    try: {suggestion}"));
        }
    }
    lines.join("\n")
}