pushkin 0.2.0

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
//! `pushkin enable/disable git-hooks` (2026-08-18 refactor): the
//! human-plane switch for the git-plane floor, persisted as the
//! manifest's `[features]` table.
//!
//! The contract under test, end to end:
//!   - `disable git-hooks` records `git_hooks = false` in pushkin.toml
//!     (comments preserved) AND removes both pushkin-owned surfaces —
//!     the lefthook block and the native `.git/hooks/pre-commit` shim.
//!   - `init --agent lefthook|git` refuses loudly while disabled and
//!     names the re-enable verb.
//!   - `enable git-hooks` re-allows install; it installs nothing itself.
//!   - `check --staged` passes with a stderr notice while disabled —
//!     the committed manifest governs every clone's floor, not the
//!     floor's local install state. Agent write-time gating (`hook`,
//!     stdin `check`) is out of the flag's scope by design.
//!   - `doctor` under the switch: disabled is not unhealthy; a
//!     still-installed floor IS the finding, and `--repair` removes it.
//!
//! Helpers return `Result` and tests propagate with `?` — the house
//! pattern for satisfying the workspace's `unwrap_used`/`expect_used`
//! deny without a suppression (N9).

use assert_cmd::Command;
use std::fs;
use std::path::Path;
use std::process::Command as StdCommand;

type TestResult = Result<(), Box<dyn std::error::Error>>;

const MANIFEST: &str = r#"
version = 1
canonical = "json-schema-2020-12"
authoring = "zod"

[[contracts]]
name = "user"
source = "contracts/user.zod.ts"
emit = ["zod"]

[[mappings]]
glob = "app/api/**/*.ts"
contracts = ["user"]
require = "boundary-validation"

# gates comment a splice must not disturb
[gates]
protected_paths = ["pushkin.toml"]
"#;

const NONCONFORMING: &str = "export async function POST(req: Request) {\n\
  const body = await req.json();\n\
  return Response.json({ name: body.name });\n\
}\n";

const ROUTE: &str = "app/api/users/route.ts";

fn disabled_manifest() -> String {
    format!("{MANIFEST}\n[features]\ngit_hooks = false\n")
}

fn repo() -> Result<tempfile::TempDir, Box<dyn std::error::Error>> {
    let dir = tempfile::tempdir()?;
    fs::write(dir.path().join("pushkin.toml"), MANIFEST)?;
    Ok(dir)
}

/// A real git repo, for the shim and `--staged` surfaces.
fn git_repo() -> Result<tempfile::TempDir, Box<dyn std::error::Error>> {
    let dir = repo()?;
    for args in [
        ["init", "--initial-branch=main"].as_slice(),
        ["config", "user.email", "test@example.invalid"].as_slice(),
        ["config", "user.name", "Pushkin Test"].as_slice(),
        ["config", "commit.gpgsign", "false"].as_slice(),
    ] {
        git(dir.path(), args)?;
    }
    Ok(dir)
}

fn git(dir: &Path, args: &[&str]) -> TestResult {
    let output = StdCommand::new("git")
        .args(args)
        .current_dir(dir)
        .output()?;
    assert!(
        output.status.success(),
        "git {args:?}: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    Ok(())
}

struct Verdict {
    code: Option<i32>,
    stdout: String,
    stderr: String,
}

fn run(dir: &Path, args: &[&str]) -> Result<Verdict, Box<dyn std::error::Error>> {
    let output = Command::cargo_bin("pushkin")?
        .current_dir(dir)
        .args(args)
        .output()?;
    Ok(Verdict {
        code: output.status.code(),
        stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
        stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
    })
}

fn manifest_text(dir: &Path) -> Result<String, Box<dyn std::error::Error>> {
    Ok(fs::read_to_string(dir.join("pushkin.toml"))?)
}

// ---------- disable: record + uninstall, one verb ----------

#[test]
fn disable_records_the_flag_and_removes_floor_and_shim() -> TestResult {
    let dir = git_repo()?;
    let installed_floor = run(dir.path(), &["init", "--agent", "lefthook"])?;
    assert_eq!(installed_floor.code, Some(0), "{}", installed_floor.stderr);
    let installed_shim = run(dir.path(), &["init", "--agent", "git"])?;
    assert_eq!(installed_shim.code, Some(0), "{}", installed_shim.stderr);
    assert!(dir.path().join(".git/hooks/pre-commit").exists());

    let verdict = run(dir.path(), &["disable", "git-hooks"])?;
    assert_eq!(
        verdict.code,
        Some(0),
        "{}{}",
        verdict.stdout,
        verdict.stderr
    );

    let manifest = manifest_text(dir.path())?;
    assert!(manifest.contains("[features]"), "flag recorded: {manifest}");
    assert!(manifest.contains("git_hooks = false"));
    assert!(
        !dir.path().join("lefthook.yml").exists()
            || !fs::read_to_string(dir.path().join("lefthook.yml"))?.contains("pushkin"),
        "the pushkin floor is gone"
    );
    assert!(
        !dir.path().join(".git/hooks/pre-commit").exists(),
        "the native shim is gone"
    );
    Ok(())
}

#[test]
fn disable_preserves_manifest_comments_and_reparses() -> TestResult {
    let dir = repo()?;
    let verdict = run(dir.path(), &["disable", "git-hooks"])?;
    assert_eq!(
        verdict.code,
        Some(0),
        "{}{}",
        verdict.stdout,
        verdict.stderr
    );
    let manifest = manifest_text(dir.path())?;
    assert!(
        manifest.contains("# gates comment a splice must not disturb"),
        "comments survive the splice: {manifest}"
    );
    assert!(manifest.contains("protected_paths = [\"pushkin.toml\"]"));
    Ok(())
}

#[test]
fn disable_then_enable_round_trips_to_one_flag_line() -> TestResult {
    let dir = repo()?;
    run(dir.path(), &["disable", "git-hooks"])?;
    run(dir.path(), &["enable", "git-hooks"])?;
    let manifest = manifest_text(dir.path())?;
    assert_eq!(
        manifest.matches("git_hooks").count(),
        1,
        "repeat toggles rewrite one line, never stack: {manifest}"
    );
    assert!(manifest.contains("git_hooks = true"));
    Ok(())
}

#[test]
fn disable_without_a_manifest_is_a_loud_error() -> TestResult {
    let dir = tempfile::tempdir()?;
    let verdict = run(dir.path(), &["disable", "git-hooks"])?;
    assert_ne!(verdict.code, Some(0));
    assert!(
        verdict.stderr.contains("pushkin.toml"),
        "the error names the missing manifest: {}",
        verdict.stderr
    );
    Ok(())
}

#[test]
fn unknown_feature_is_named_with_the_known_set() -> TestResult {
    let dir = repo()?;
    let verdict = run(dir.path(), &["enable", "telemetry"])?;
    assert_ne!(verdict.code, Some(0));
    assert!(
        verdict.stderr.contains("telemetry") && verdict.stderr.contains("git-hooks"),
        "unknown feature errors name the known set: {}",
        verdict.stderr
    );
    Ok(())
}

// ---------- init: refusal while disabled ----------

#[test]
fn init_lefthook_refuses_while_disabled() -> TestResult {
    let dir = repo()?;
    fs::write(dir.path().join("pushkin.toml"), disabled_manifest())?;
    let verdict = run(dir.path(), &["init", "--agent", "lefthook"])?;
    assert_ne!(verdict.code, Some(0), "install must refuse");
    assert!(
        verdict.stderr.contains("pushkin enable git-hooks"),
        "the refusal names the re-enable verb: {}",
        verdict.stderr
    );
    assert!(
        !dir.path().join("lefthook.yml").exists(),
        "nothing was installed"
    );
    Ok(())
}

#[test]
fn init_git_shim_refuses_while_disabled() -> TestResult {
    let dir = git_repo()?;
    fs::write(dir.path().join("pushkin.toml"), disabled_manifest())?;
    let verdict = run(dir.path(), &["init", "--agent", "git"])?;
    assert_ne!(verdict.code, Some(0), "install must refuse");
    assert!(verdict.stderr.contains("pushkin enable git-hooks"));
    assert!(!dir.path().join(".git/hooks/pre-commit").exists());
    Ok(())
}

#[test]
fn enable_reallows_install_without_installing_itself() -> TestResult {
    let dir = repo()?;
    fs::write(dir.path().join("pushkin.toml"), disabled_manifest())?;
    let enabled = run(dir.path(), &["enable", "git-hooks"])?;
    assert_eq!(
        enabled.code,
        Some(0),
        "{}{}",
        enabled.stdout,
        enabled.stderr
    );
    assert!(
        !dir.path().join("lefthook.yml").exists(),
        "enable records the flag; install stays the explicit init path"
    );
    let installed = run(dir.path(), &["init", "--agent", "lefthook"])?;
    assert_eq!(installed.code, Some(0), "{}", installed.stderr);
    assert!(fs::read_to_string(dir.path().join("lefthook.yml"))?.contains("pushkin:begin"));
    Ok(())
}

#[test]
fn other_agent_packs_are_out_of_the_flag_scope() -> TestResult {
    let dir = repo()?;
    fs::write(dir.path().join("pushkin.toml"), disabled_manifest())?;
    let verdict = run(dir.path(), &["init", "--agent", "claude"])?;
    assert_eq!(
        verdict.code,
        Some(0),
        "agent write-time packs install regardless of the git-plane switch: {}",
        verdict.stderr
    );
    assert!(dir.path().join(".claude/settings.json").exists());
    Ok(())
}

// ---------- check --staged: the committed manifest governs the floor ----------

#[test]
fn staged_check_blocks_when_enabled_and_skips_when_disabled() -> TestResult {
    let dir = git_repo()?;
    let route = dir.path().join(ROUTE);
    if let Some(parent) = route.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&route, NONCONFORMING)?;
    git(dir.path(), &["add", ROUTE])?;

    // Fixture validity: with the plane enabled this staged content blocks.
    let enabled = run(dir.path(), &["check", "--staged", "--json"])?;
    assert_eq!(
        enabled.code,
        Some(2),
        "{}{}",
        enabled.stdout,
        enabled.stderr
    );

    fs::write(dir.path().join("pushkin.toml"), disabled_manifest())?;
    let disabled = run(dir.path(), &["check", "--staged", "--json"])?;
    assert_eq!(
        disabled.code,
        Some(0),
        "disabled plane passes the same staged violation: {}{}",
        disabled.stdout,
        disabled.stderr
    );
    assert!(
        disabled.stderr.contains("git hooks disabled"),
        "the skip is a notice, never silence: {}",
        disabled.stderr
    );
    Ok(())
}

#[test]
fn stdin_write_gate_ignores_the_switch() -> TestResult {
    let dir = repo()?;
    fs::write(dir.path().join("pushkin.toml"), disabled_manifest())?;
    let payload = format!(
        "{{\"tool_name\":\"Write\",\"tool_input\":{{\"file_path\":\"{ROUTE}\",\"content\":{}}}}}",
        serde_json::to_string(NONCONFORMING)?
    );
    let output = Command::cargo_bin("pushkin")?
        .current_dir(dir.path())
        .args(["check"])
        .write_stdin(payload)
        .output()?;
    assert_eq!(
        output.status.code(),
        Some(2),
        "write-time gating is out of the flag's scope: {}",
        String::from_utf8_lossy(&output.stdout)
    );
    Ok(())
}

// ---------- doctor under the switch ----------

/// Doctor runs with `HERMES_HOME` pinned inside the temp repo and the
/// under-test binary's own directory prepended to PATH — the
/// `doctor_agents.rs` precondition pattern (adapter pass A3(b)):
/// resolvability is a declared precondition, so exit codes here assert
/// the git-plane switch, never the runner's ambient PATH.
fn doctor(dir: &Path, args: &[&str]) -> Result<Verdict, Box<dyn std::error::Error>> {
    let mut command = Command::cargo_bin("pushkin")?;
    command
        .current_dir(dir)
        .env("HERMES_HOME", dir.join(".hermes-home"))
        .args(args);
    if let Some(binary_dir) = Path::new(env!("CARGO_BIN_EXE_pushkin")).parent() {
        let ambient = std::env::var("PATH").unwrap_or_default();
        command.env(
            "PATH",
            format!("{}:{ambient}", binary_dir.to_string_lossy()),
        );
    }
    let output = command.output()?;
    Ok(Verdict {
        code: output.status.code(),
        stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
        stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
    })
}

/// The claude pack installed (bare `init`) so the only doctor variable
/// left is the git plane itself.
fn baseline_packs(dir: &Path) -> TestResult {
    let verdict = run(dir, &["init"])?;
    assert_eq!(verdict.code, Some(0), "{}", verdict.stderr);
    Ok(())
}

#[test]
fn doctor_reports_disabled_as_healthy_when_nothing_is_installed() -> TestResult {
    let dir = repo()?;
    baseline_packs(dir.path())?;
    fs::write(dir.path().join("pushkin.toml"), disabled_manifest())?;
    let verdict = doctor(dir.path(), &["doctor"])?;
    assert_eq!(
        verdict.code,
        Some(0),
        "{}{}",
        verdict.stdout,
        verdict.stderr
    );
    assert!(
        verdict.stdout.contains("lefthook: git hooks disabled")
            && verdict.stdout.contains("git shim: git hooks disabled"),
        "doctor names the disabled plane instead of checking it: {}",
        verdict.stdout
    );
    Ok(())
}

#[test]
fn doctor_flags_a_floor_still_installed_while_disabled_and_repair_removes_it() -> TestResult {
    let dir = git_repo()?;
    baseline_packs(dir.path())?;
    let installed = run(dir.path(), &["init", "--agent", "lefthook"])?;
    assert_eq!(installed.code, Some(0), "{}", installed.stderr);
    fs::write(dir.path().join("pushkin.toml"), disabled_manifest())?;

    let unhealthy = doctor(dir.path(), &["doctor"])?;
    assert_eq!(
        unhealthy.code,
        Some(1),
        "still-installed is the finding: {}",
        unhealthy.stdout
    );
    assert!(
        unhealthy.stdout.contains("still"),
        "the finding names the leftover floor: {}",
        unhealthy.stdout
    );

    let repaired = doctor(dir.path(), &["doctor", "--repair"])?;
    assert!(
        !fs::read_to_string(dir.path().join("lefthook.yml"))
            .unwrap_or_default()
            .contains("pushkin:begin"),
        "repair removed the floor: {}{}",
        repaired.stdout,
        repaired.stderr
    );

    let healthy = doctor(dir.path(), &["doctor"])?;
    assert_eq!(
        healthy.code,
        Some(0),
        "after removal the disabled plane is healthy: {}",
        healthy.stdout
    );
    Ok(())
}