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
//! F68 — Stop-time verdicts must reach the agent (spec §8.1, addendum §4).
//!
//! Authorized by `docs/claude_stage5-floor-verb-charter-2026-08-18.md`, W4.
//! A NEW file per N10; `hook_verdicts.rs`, `ladder.rs` and
//! `gate_dispatch_conformance.rs` are read-only here and must stay green
//! untouched.
//!
//! **The defect.** `.claude/settings.json` wires Stop to `pushkin hook claude`.
//! `hook.rs`'s `evaluate` returns `sweep_repo(manifest)` for `action.is_stop`,
//! and `run()` then renders any findings through `encode_deny` — which hardcodes
//! a `hookEventName` of `PreToolUse` and exits 0. Every host documents a DIFFERENT
//! shape for Stop, and none of them is that one, so the verdict is discarded and
//! the agent stops with violations sitting on the floor. Both existing Stop
//! tests (`authoring_and_stop.rs`) exercise `check`, not `hook`, so the wired
//! production path had no coverage at all.
//!
//! **The three documented dialects, checked during this pass** (they are three
//! different shapes, which is why one encoder cannot serve them):
//!
//! | host   | Stop block shape                                                              |
//! |--------|-------------------------------------------------------------------------------|
//! | Claude | top-level `{"decision":"block","reason":…}` — explicitly NOT `hookSpecificOutput` |
//! | Codex  | top-level `{"decision":"block","reason":…}`; `hookSpecificOutput` unsupported at Stop |
//! | Auggie | `hookSpecificOutput` nested, with `hookEventName` = `Stop`, plus `decision`/`reason` |
//!
//! Sources: `code.claude.com/docs/en/hooks.md`; `learn.chatgpt.com/docs/hooks`
//! (plus `openai/codex#18887`, "Stop hook invalid JSON error is too opaque for
//! unsupported fields", which is what an extra `hookSpecificOutput` produces);
//! `docs.augmentcode.com/cli/hooks`. Note Auggie's Stop shape is NOT Claude's,
//! despite the two sharing a `PreToolUse` deny dialect — the existing comment in
//! `hook.rs` saying they "speak the identical deny dialect" is true only for
//! `PreToolUse`.
//!
//! **A second gap, disclosed rather than fixed here.** Auggie cannot reach the
//! Stop path at all: `normalize_auggie` returns `Err(None)` when the payload
//! carries no `tool_input` (agents.rs), so an Auggie `stop_hook_active` payload
//! is treated as malformed and never becomes `is_stop`. That is a NORMALIZER
//! gap; W4's scope is the ENCODER. Encoding Auggie's documented dialect now
//! means the arm is right when the normalizer is fixed, and the gap is named
//! here so nobody reads the untested arm as tested. The issuing brief said
//! Auggie normalizes `stop_hook_active` via `normalize_claude_family`; verified
//! against the tree, it does not.
//!
//! **Exit code stays 0.** Every host documents JSON-on-stdout with exit 0 as the
//! structured-control channel for Stop; exit 2 is `PreToolUse`'s blocking channel
//! and does not carry a reason.
//!
//! **Deliberately NOT in scope.** No change to `PreToolUse` encoding — asserted
//! below, because the two shapes must not bleed. No normalizer change. No new
//! `Decision` arm. No floor command runs at Stop in this file; that is W6's,
//! and it ships dark.

use assert_cmd::Command;
use serde_json::Value;
use std::fs;
use std::path::Path;

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

/// Arms its own gate: this repo's `pushkin.toml` has every `[gates]` line
/// commented out, so a suite leaning on the real manifest would assert nothing.
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]
"#;

/// A mapped handler that consumes `req.json()` without parsing it through the
/// generated schema — `contract.boundary.unvalidated_input`.
const NONCONFORMING: &str = "export async function POST(req: Request) {\n\
  const body = await req.json();\n\
  return Response.json({ name: body.name });\n\
}\n";

fn repo_with_violation() -> Result<tempfile::TempDir, Box<dyn std::error::Error>> {
    let dir = tempfile::tempdir()?;
    fs::write(dir.path().join("pushkin.toml"), MANIFEST)?;
    let api = dir.path().join("app/api/users");
    fs::create_dir_all(&api)?;
    fs::write(api.join("route.ts"), NONCONFORMING)?;
    Ok(dir)
}

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

struct Run {
    code: i32,
    stdout: String,
    stderr: String,
}

fn hook(dir: &Path, agent: &str, payload: &str) -> Result<Run, Box<dyn std::error::Error>> {
    let output = Command::cargo_bin("pushkin")?
        .current_dir(dir)
        .env("PUSHKIN_DAEMON", "off")
        .args(["hook", agent])
        .write_stdin(payload.to_owned())
        .output()?;
    Ok(Run {
        code: output.status.code().unwrap_or(-1),
        stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
        stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
    })
}

const STOP_PAYLOAD: &str = r#"{"session_id":"s-stop","stop_hook_active":true}"#;

/// Parses the hook's stdout, asserting JSON-ness first so a non-JSON verdict
/// fails here with the actual output rather than three rows later as a
/// mysterious `None`.
fn json(run: &Run) -> Value {
    let parsed = serde_json::from_str::<Value>(&run.stdout);
    assert!(parsed.is_ok(), "stdout must be JSON; got:\n{}", run.stdout);
    parsed.unwrap_or(Value::Null)
}

// ---------- Claude: the wired production path ----------

#[test]
fn claude_stop_denial_uses_the_top_level_decision_shape() -> TestResult {
    let dir = repo_with_violation()?;
    let run = hook(dir.path(), "claude", STOP_PAYLOAD)?;
    let value = json(&run);
    assert_eq!(
        value.get("decision").and_then(Value::as_str),
        Some("block"),
        "Stop blocks with a TOP-LEVEL decision field; got:\n{}",
        run.stdout
    );
    assert!(
        value.get("reason").and_then(Value::as_str).is_some(),
        "the block must carry a reason; got:\n{}",
        run.stdout
    );
    Ok(())
}

#[test]
fn claude_stop_denial_carries_the_violation_in_its_reason() -> TestResult {
    // The reason is the whole payload of a Stop block — it is what gets injected
    // back into the agent's context. An empty or generic reason would block the
    // agent without telling it what to fix.
    let dir = repo_with_violation()?;
    let run = hook(dir.path(), "claude", STOP_PAYLOAD)?;
    let value = json(&run);
    let reason = value
        .get("reason")
        .and_then(Value::as_str)
        .unwrap_or_default();
    assert!(
        reason.contains("route.ts"),
        "the reason must name the offending file; got:\n{reason}"
    );
    assert!(
        reason.contains("contract.boundary.unvalidated_input"),
        "the reason must name the rule; got:\n{reason}"
    );
    Ok(())
}

#[test]
fn claude_stop_denial_never_emits_the_pretooluse_shape() -> TestResult {
    // This is the defect itself, asserted directly: Claude's docs state Stop
    // does NOT use hookSpecificOutput, so emitting it is why the verdict was
    // discarded.
    let dir = repo_with_violation()?;
    let run = hook(dir.path(), "claude", STOP_PAYLOAD)?;
    let value = json(&run);
    assert!(
        value.get("hookSpecificOutput").is_none(),
        "Stop must not carry hookSpecificOutput; got:\n{}",
        run.stdout
    );
    assert!(
        !run.stdout.contains("PreToolUse"),
        "a Stop verdict must never claim to be a PreToolUse one; got:\n{}",
        run.stdout
    );
    Ok(())
}

#[test]
fn claude_stop_denial_exits_zero() -> TestResult {
    // Exit 0 is the documented structured-control channel: the JSON is what
    // blocks. Exit 2 is PreToolUse's channel and carries no reason.
    let dir = repo_with_violation()?;
    let run = hook(dir.path(), "claude", STOP_PAYLOAD)?;
    assert_eq!(run.code, 0, "got stdout:\n{}", run.stdout);
    Ok(())
}

#[test]
fn a_clean_repo_at_stop_still_allows() -> TestResult {
    // The fix must not turn every Stop into a block. A repo with no mapped
    // findings sweeps clean and passes through the EXISTING allow encoding,
    // which for the Claude family is silence — `encode_allow` returns an empty
    // string, and emitting a `{"decision":"allow"}` here instead would be a
    // behavior change this pass has no mandate for.
    let dir = clean_repo()?;
    let run = hook(dir.path(), "claude", STOP_PAYLOAD)?;
    assert_eq!(run.code, 0, "got stdout:\n{}", run.stdout);
    assert!(
        run.stdout.trim().is_empty(),
        "silence is allow for the Claude family; got:\n{}",
        run.stdout
    );
    Ok(())
}

// ---------- Codex: a second documented dialect ----------

#[test]
fn codex_stop_denial_uses_the_top_level_decision_shape() -> TestResult {
    let dir = repo_with_violation()?;
    let run = hook(dir.path(), "codex", STOP_PAYLOAD)?;
    let value = json(&run);
    assert_eq!(
        value.get("decision").and_then(Value::as_str),
        Some("block"),
        "got:\n{}",
        run.stdout
    );
    assert!(
        value.get("reason").and_then(Value::as_str).is_some(),
        "got:\n{}",
        run.stdout
    );
    Ok(())
}

#[test]
fn codex_stop_denial_omits_hook_specific_output_entirely() -> TestResult {
    // Codex's PreToolUse deny deliberately carries BOTH the modern shape and
    // the legacy decision field. At Stop that is not merely redundant — the
    // Stop schema does not support hookSpecificOutput, and an unsupported field
    // makes the whole payload invalid (openai/codex#18887). So Codex is doubly
    // broken at Stop today: wrong shape AND rejected outright.
    let dir = repo_with_violation()?;
    let run = hook(dir.path(), "codex", STOP_PAYLOAD)?;
    assert!(
        json(&run).get("hookSpecificOutput").is_none(),
        "Codex's Stop schema rejects hookSpecificOutput; got:\n{}",
        run.stdout
    );
    Ok(())
}

// ---------- PreToolUse must not change ----------

#[test]
fn a_pretooluse_deny_still_carries_the_permission_decision_shape() -> TestResult {
    // The two shapes must not bleed. If this row and the Stop rows are ever both
    // green while the encoder has one branch, something has collapsed them.
    let dir = clean_repo()?;
    let payload = r#"{"session_id":"s-write","tool_name":"Write","tool_input":{"file_path":"app/api/users/route.ts","content":"export async function POST(req: Request) {\n  const body = await req.json();\n  return Response.json({ name: body.name });\n}\n"}}"#;
    let run = hook(dir.path(), "claude", payload)?;
    let value = json(&run);
    let specific = value
        .get("hookSpecificOutput")
        .unwrap_or_else(|| panic!("PreToolUse keeps its shape; got:\n{}", run.stdout));
    assert_eq!(
        specific.get("hookEventName").and_then(Value::as_str),
        Some("PreToolUse"),
        "got:\n{}",
        run.stdout
    );
    assert_eq!(
        specific.get("permissionDecision").and_then(Value::as_str),
        Some("deny"),
        "got:\n{}",
        run.stdout
    );
    assert!(
        value.get("decision").is_none(),
        "a PreToolUse deny must not grow a top-level Stop decision; got:\n{}",
        run.stdout
    );
    Ok(())
}

// ---------- check vs hook, structurally (gate-dispatch register) ----------

#[test]
fn check_and_hook_agree_on_the_stop_verdict() -> TestResult {
    // The gate-dispatch contract applied to Stop: two surfaces, one verdict.
    // `check` renders the §8.3 envelope and exits 2; `hook` renders the host
    // dialect and exits 0. The RENDERINGS legitimately differ — the DECISION
    // may not. Written as a new row in a new file; gate_dispatch_conformance.rs
    // is committed and read-only (N10).
    let dir = repo_with_violation()?;

    let check = Command::cargo_bin("pushkin")?
        .current_dir(dir.path())
        .env("PUSHKIN_DAEMON", "off")
        .args(["check", "--json"])
        .write_stdin(STOP_PAYLOAD.to_owned())
        .output()?;
    let check_json: Value = serde_json::from_slice(&check.stdout)?;
    assert_eq!(
        check_json.get("decision").and_then(Value::as_str),
        Some("block"),
        "check must block on this fixture; got:\n{}",
        String::from_utf8_lossy(&check.stdout)
    );

    let run = hook(dir.path(), "claude", STOP_PAYLOAD)?;
    assert_eq!(
        json(&run).get("decision").and_then(Value::as_str),
        Some("block"),
        "hook must reach the same decision as check; got:\n{}",
        run.stdout
    );
    Ok(())
}

#[test]
fn check_and_hook_agree_on_a_clean_stop_too() -> TestResult {
    // Agreement on block is half the contract; agreement on allow is the other
    // half, and it is the half a always-block regression would pass.
    let dir = clean_repo()?;

    let check = Command::cargo_bin("pushkin")?
        .current_dir(dir.path())
        .env("PUSHKIN_DAEMON", "off")
        .args(["check", "--json"])
        .write_stdin(STOP_PAYLOAD.to_owned())
        .output()?;
    let check_json: Value = serde_json::from_slice(&check.stdout)?;
    assert_eq!(
        check_json.get("decision").and_then(Value::as_str),
        Some("allow"),
        "got:\n{}",
        String::from_utf8_lossy(&check.stdout)
    );

    let run = hook(dir.path(), "claude", STOP_PAYLOAD)?;
    assert!(
        run.stdout.trim().is_empty(),
        "hook must agree with check's allow — silence, not a block; got:\n{}",
        run.stdout
    );
    Ok(())
}

// ---------- F70: Auggie Stop payloads reach the gate ----------
//
// APPENDED after this file was committed. N10 permits adding to a committed
// suite; nothing above this line is modified.
//
// **A correction to this file's own header, which cannot be edited under N10.**
// The block at the top says "an Auggie `stop_hook_active` payload". That is
// WRONG, and it is the same error F70 was raised to stop being inherited:
// Auggie has no `stop_hook_active` field anywhere in its schema. Its documented
// Stop payload is
//
//   {"hook_event_name":"Stop","conversation_id":"conv-xyz789",
//    "workspace_roots":["…"],"agent_stop_cause":"end_turn"}
//
// so the discriminator is `hook_event_name == "Stop"` — a COMMON base field
// present on every Auggie event — and the session key is `conversation_id`,
// not `session_id`. `agent_stop_cause` carries why it stopped ("end_turn",
// "interrupted", "max_iterations", "error") and is deliberately NOT used as the
// marker: it says why, not what. Source: docs.augmentcode.com/cli/hooks.
//
// The gap was never that Auggie's dialect was wrong — F68 encoded it correctly.
// It was that `normalize_auggie` returned `Err(None)` on any payload without
// `tool_input`, so a Stop payload was malformed before the encoder was reached.

/// Auggie's real Stop payload: no `tool_input`, no `stop_hook_active`.
const AUGGIE_STOP_PAYLOAD: &str = r#"{"hook_event_name":"Stop","conversation_id":"conv-f70","workspace_roots":["/tmp"],"agent_stop_cause":"end_turn"}"#;

#[test]
fn auggie_stop_denial_uses_auggies_nested_stop_dialect() -> TestResult {
    let dir = repo_with_violation()?;
    let run = hook(dir.path(), "auggie", AUGGIE_STOP_PAYLOAD)?;
    let value = json(&run);
    let specific = value.get("hookSpecificOutput").unwrap_or_else(|| {
        panic!(
            "Auggie's Stop dialect nests under hookSpecificOutput; got:\n{}",
            run.stdout
        )
    });
    assert_eq!(
        specific.get("hookEventName").and_then(Value::as_str),
        Some("Stop"),
        "the nested event name must be Stop, not PreToolUse; got:\n{}",
        run.stdout
    );
    assert_eq!(
        specific.get("decision").and_then(Value::as_str),
        Some("block"),
        "Auggie blocks with decision/reason, not permissionDecision; got:\n{}",
        run.stdout
    );
    assert!(
        specific.get("reason").and_then(Value::as_str).is_some(),
        "the block must carry a reason; got:\n{}",
        run.stdout
    );
    Ok(())
}

#[test]
fn auggie_stop_denial_carries_the_violation_and_exits_zero() -> TestResult {
    let dir = repo_with_violation()?;
    let run = hook(dir.path(), "auggie", AUGGIE_STOP_PAYLOAD)?;
    assert_eq!(run.code, 0, "got stdout:\n{}", run.stdout);
    let value = json(&run);
    let reason = value
        .get("hookSpecificOutput")
        .and_then(|s| s.get("reason"))
        .and_then(Value::as_str)
        .unwrap_or_default();
    assert!(
        reason.contains("route.ts") && reason.contains("contract.boundary.unvalidated_input"),
        "the reason must name the file and the rule; got:\n{reason}"
    );
    Ok(())
}

#[test]
fn a_clean_repo_at_auggie_stop_still_allows() -> TestResult {
    // Reaching the Stop path must not mean blocking on it. Silence is allow for
    // the Claude family, and Auggie is in it for the allow encoding.
    let dir = clean_repo()?;
    let run = hook(dir.path(), "auggie", AUGGIE_STOP_PAYLOAD)?;
    assert_eq!(run.code, 0, "got stdout:\n{}", run.stdout);
    assert!(
        run.stdout.trim().is_empty(),
        "a clean sweep must not block; got:\n{}",
        run.stdout
    );
    Ok(())
}

#[test]
fn an_auggie_payload_without_tool_input_or_a_stop_marker_is_still_malformed() -> TestResult {
    // The narrowness guard, and the row that makes the repair a repair rather
    // than a hole. Only a payload positively identifying itself as Stop takes
    // the new branch; anything else keeps the existing malformed handling, which
    // is what gate_unreadable_payload depends on.
    //
    // F76: under clean_repo() both branches print byte-identical EMPTY stdout,
    // so the original stdout-only assertion was true whichever branch ran — it
    // was green at its own committed-RED commit ecfbbd5. The discriminator is
    // stderr: the malformed handler discloses "failing open", the Stop sweep
    // says nothing. The test now proves the malformed trigger FIRED instead of
    // inferring it from silence, and goes RED against the overwiden defect it
    // guards (a marker-less payload taking the Stop branch).
    let dir = clean_repo()?;
    let run = hook(
        dir.path(),
        "auggie",
        r#"{"conversation_id":"conv-junk","workspace_roots":["/tmp"]}"#,
    )?;
    assert_eq!(run.code, 0, "malformed fails OPEN; stdout:\n{}", run.stdout);
    assert!(
        run.stderr.contains("failing open"),
        "the payload must take the MALFORMED branch, whose handler discloses \
         itself on stderr; silence here means the Stop branch swallowed a \
         payload that never claimed to be a Stop. stderr:\n{}",
        run.stderr
    );
    assert!(
        !run.stdout.contains("\"hookEventName\":\"Stop\""),
        "a payload with no Stop marker must not be treated as a Stop; got:\n{}",
        run.stdout
    );
    Ok(())
}

#[test]
fn an_auggie_write_payload_is_unaffected_by_the_stop_branch() -> TestResult {
    // The regression guard: normal Auggie write traffic still normalizes through
    // tool_input and still denies in the PreToolUse dialect.
    let dir = clean_repo()?;
    let payload = r#"{"hook_event_name":"PreToolUse","conversation_id":"conv-w","tool_name":"save-file","tool_input":{"path":"app/api/users/route.ts","file_content":"export async function POST(req: Request) {\n  const body = await req.json();\n  return Response.json({ name: body.name });\n}\n"}}"#;
    let run = hook(dir.path(), "auggie", payload)?;
    let value = json(&run);
    let specific = value
        .get("hookSpecificOutput")
        .unwrap_or_else(|| panic!("a write deny keeps its shape; got:\n{}", run.stdout));
    assert_eq!(
        specific.get("hookEventName").and_then(Value::as_str),
        Some("PreToolUse"),
        "write traffic must still render as PreToolUse; got:\n{}",
        run.stdout
    );
    Ok(())
}