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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
//! `pushkin hook <agent>`: the adapter boundary. Normalizes the agent's
//! hook payload, runs the shared pipeline, renders the escalation ladder
//! (addendum §5/§7), and encodes the verdict in the agent's native dialect.
//! One brain, five mouths — this file only translates and counts.

use anyhow::Result;
use pushkin_core::delivery::{Delivery, DeliveryIndex, DeliveryRequest};
use pushkin_core::envelope::{CheckResult, Severity, Violation};
use pushkin_core::events::{EventLog, SessionId, Telemetry};
use pushkin_core::manifest::Manifest;
use pushkin_core::pipeline::{check_write, WriteRequest};
use std::io::Read;

use crate::agents::families::{encode_allow, encode_deny, encode_stop_deny};
use crate::agents::{normalize, Agent, Intent, ToolAction};

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

const ATTEMPT_CAP: u64 = 3;

/// Delivery-index key for the session digest (one epoch = one emission).
const DIGEST_SLICE_KEY: &str = "instructions/digest";

/// Character cap for a contract-slice excerpt inside a deny envelope.
const EXCERPT_CAP: usize = 1200;

pub fn run(agent_name: &str) -> Result<i32> {
    let agent = Agent::parse(agent_name)?;
    // Worktree policy (spec §9): detached worktrees get silence — the
    // gate stands down entirely, before any manifest or stdin parsing.
    if super::policy::evaluate().is_detached() {
        return Ok(0);
    }
    // F71 Phase B: the load outcome is held, not unwrapped — which branch runs
    // depends on the payload shape (a session start is not a write) and on
    // provenance (`load_manifest_for_gate`'s scoping).
    let gate = super::load_manifest_for_gate();
    let log = EventLog::open(events_db_path()?)?;

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

    if let Some(lifecycle) = session_lifecycle(&raw) {
        return match gate {
            super::GateManifest::Loaded(manifest) => {
                handle_session_start(agent, &manifest, &lifecycle)
            }
            super::GateManifest::Deny { error } => {
                eprintln!(
                    "pushkin: cannot load the manifest ({error}); a session start is \
                     not a write, so nothing is denied here — the first write will be."
                );
                Ok(0)
            }
            super::GateManifest::Unpinned { error } => Err(error),
        };
    }
    if agent == Agent::Opencode {
        if let Some(investigation) = opencode_investigation(&raw) {
            return handle_investigation(&log, &investigation);
        }
    }
    let manifest = match gate {
        super::GateManifest::Loaded(manifest) => manifest,
        super::GateManifest::Deny { error } => return render_skew_deny(agent, &log, &raw, &error),
        super::GateManifest::Unpinned { error } => return Err(error),
    };
    let action = match normalize(agent, &raw) {
        Ok(action) => action,
        Err(partial) => return handle_malformed(agent, &manifest, &log, partial, &raw),
    };
    let session = SessionId::from_name(&action.session);

    // Waivers are applied inside `decide` per leaf (Shape 2); `evaluate` returns
    // the already-waived verdict.
    let mut result = evaluate(&manifest, &action)?;
    for violation in claim_violations(&action) {
        result.decision = pushkin_core::envelope::Decision::Block;
        result.violations.push(violation);
    }
    // Count PRIOR hits before appending, so this denial is attempt N.
    let attempt = match result.violations.first() {
        Some(first) => log.attempts(&session, &first.rule, &first.file)? + 1,
        None => 0,
    };
    log.append(&session, &result)?;

    if result.violations.is_empty() {
        print!("{}", encode_allow(agent));
        return Ok(0);
    }

    if attempt >= ATTEMPT_CAP {
        log.append_escalation(&session, "attempt cap reached; agent told to STOP")?;
    }
    let mut prose = render_ladder_for(&result, attempt.min(ATTEMPT_CAP), action.intent);
    let context = SliceContext {
        manifest: &manifest,
        session: &session,
        log: &log,
        action: &action,
    };
    prose.push_str(&slice_enrichment(&context, &result)?);
    if let Some(nudge) = nudge_line(&context, attempt)? {
        prose.push_str(&nudge);
    }
    // The verdict names the manifest it was computed from (F73, ruling §2.2). A
    // verdict silent about its own basis cannot be audited — and until F73 the
    // basis genuinely varied with the caller's working directory.
    prose.push_str("\n  manifest: ");
    prose.push_str(&super::manifest_agent_display());
    // F68 — a Stop denial is a different hook event with a different documented
    // schema on every host, so it cannot ride PreToolUse's encoding. A host that
    // declares no Stop dialect keeps the existing output rather than being sent
    // an invented one.
    let encoded = if action.is_stop {
        encode_stop_deny(agent, &prose).unwrap_or_else(|| encode_deny(agent, &prose))
    } else {
        encode_deny(agent, &prose)
    };
    print!("{encoded}");
    Ok(0)
}

// ---------- just-in-time nudges (spec §7.4) ----------

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NudgeMode {
    Off,
    Ab,
    On,
}

/// Mode gate: env today, persisted config when the daemon lands
/// (resolution order env → config → default per §7.4). Default `ab`.
fn nudge_mode() -> NudgeMode {
    match std::env::var("PUSHKIN_NUDGE").as_deref() {
        Ok("off") => NudgeMode::Off,
        Ok("on") => NudgeMode::On,
        _ => NudgeMode::Ab,
    }
}

/// A non-write opencode tool call (the blanket `tool.execute.before`
/// hook sees all tool traffic — today the only surface where the
/// grep-for-the-schema anti-pattern is visible).
struct Investigation {
    session: SessionId,
    tool: String,
}

fn opencode_investigation(raw: &str) -> Option<Investigation> {
    let value: serde_json::Value = serde_json::from_str(raw).ok()?;
    let tool = value.get("tool")?.as_str()?;
    if !matches!(tool, "grep" | "glob") {
        return None;
    }
    let session = value.get("sessionID")?.as_str()?;
    Some(Investigation {
        session: SessionId::from_name(session),
        tool: tool.to_owned(),
    })
}

/// Investigation traffic is always allowed; a search fired after a block
/// is the anti-pattern signal (blocked → agent greps for the schema),
/// recorded for the next denial to answer with a pointer.
fn handle_investigation(log: &EventLog, investigation: &Investigation) -> Result<i32> {
    if nudge_mode() != NudgeMode::Off && log.block_count(&investigation.session)? > 0 {
        let payload = serde_json::json!({ "tool": investigation.tool }).to_string();
        log.append_telemetry(
            &investigation.session,
            Telemetry {
                rule: "pushkin.nudge.antipattern",
                payload,
            },
        )?;
    }
    print!("{}", encode_allow(Agent::Opencode));
    Ok(0)
}

/// One nudge line at the response choke point, mode-gated and A/B-armed.
/// Both arms record telemetry; only the treatment arm speaks. Arm
/// assignment hashes the session with FNV-1a — std hashers are not
/// contractually stable across toolchains (§7.4).
fn nudge_line(context: &SliceContext<'_>, attempt: u64) -> Result<Option<String>> {
    let mode = nudge_mode();
    if mode == NudgeMode::Off {
        return Ok(None);
    }
    let searched = context
        .log
        .rule_count(context.session, "pushkin.nudge.antipattern")?
        > 0;
    if attempt < 2 && !searched {
        return Ok(None);
    }
    let arm = match mode {
        NudgeMode::On => "treatment",
        NudgeMode::Ab => fnv_arm(context.session.as_str()),
        NudgeMode::Off => unreachable!("returned above"),
    };
    let payload = serde_json::json!({
        "arm": arm,
        "trigger": if searched { "grep-after-block" } else { "repeat-block" },
    })
    .to_string();
    context.log.append_telemetry(
        context.session,
        Telemetry {
            rule: "pushkin.nudge",
            payload,
        },
    )?;
    if arm == "control" {
        return Ok(None);
    }
    Ok(Some(
        "\n    nudge: the contract can be shown instead of searched — run \
         `pushkin instructions` before retrying."
            .to_owned(),
    ))
}

fn fnv_arm(scope: &str) -> &'static str {
    if fnv1a64(scope).is_multiple_of(2) {
        "control"
    } else {
        "treatment"
    }
}

fn fnv1a64(text: &str) -> u64 {
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for byte in text.bytes() {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    }
    hash
}

/// Everything the slice enricher needs, bundled (AGENTS.md ≤2-arg rule).
struct SliceContext<'a> {
    manifest: &'a Manifest,
    session: &'a SessionId,
    log: &'a EventLog,
    action: &'a ToolAction,
}

/// Contract-slice enrichment with progressive compression (spec §7.4):
/// the first denial in a (session, cwd) scope carries the slice excerpt
/// from the contract's authoring source; repeats collapse to a pointer
/// line and record the saving as a telemetry event. The violated
/// constraint itself (rule, file, fix) lives in the ladder prose and is
/// never subject to this collapse.
fn slice_enrichment(context: &SliceContext<'_>, result: &CheckResult) -> Result<String> {
    let index = DeliveryIndex::open(events_db_path()?)?;
    let cwd = std::env::current_dir()?.display().to_string();
    let mut lines: Vec<String> = Vec::new();
    let mut seen: Vec<&str> = Vec::new();
    for violation in &result.violations {
        let Some(name) = violation.contract.as_deref() else {
            continue;
        };
        if seen.contains(&name) {
            continue;
        }
        seen.push(name);
        let Some(excerpt) = contract_excerpt(context, name) else {
            continue;
        };
        let key = format!("contract/{name}");
        let decision = index.decide(&DeliveryRequest {
            session: context.session,
            cwd: &cwd,
            slice_key: &key,
            complete: excerpt.complete,
        })?;
        match decision {
            Delivery::Full => {
                lines.push(format!("    contract '{name}' slice:"));
                for line in excerpt.text.lines() {
                    lines.push(format!("      {line}"));
                }
            }
            Delivery::Pointer => {
                let payload = serde_json::json!({
                    "saved_chars": excerpt.text.len(),
                    "contract": name,
                })
                .to_string();
                context.log.append_telemetry(
                    context.session,
                    Telemetry {
                        rule: "pushkin.compression",
                        payload,
                    },
                )?;
                lines.push(format!("    contract '{name}' already shown — unchanged"));
            }
        }
    }
    Ok(if lines.is_empty() {
        String::new()
    } else {
        format!("\n{}", lines.join("\n"))
    })
}

/// The excerpt lives in `text`; `complete` says whether it carries the
/// slice uncut (a truncated excerpt is never recorded as delivered).
struct Excerpt {
    text: String,
    complete: bool,
}

/// Slice excerpt from the contract's authoring source: the declaration
/// lines of symbols the write touches (via the mapper), or the whole
/// source when it touches none — deliver the full contract. A missing
/// or unreadable source skips enrichment: this tier is advisory by
/// construction and must never turn a gate decision into an error.
fn contract_excerpt(context: &SliceContext<'_>, name: &str) -> Option<Excerpt> {
    let source_path = context
        .manifest
        .contracts
        .iter()
        .find(|contract| contract.name.as_str() == name)
        .map(|contract| contract.source.as_str())?;
    let source = std::fs::read_to_string(source_path).ok()?;
    let file = context.action.files.first()?;
    let symbols = pushkin_core::mapper::slices_for_write(
        context.manifest,
        &file.path,
        &file.content,
        &[(name, &source)],
    )
    .into_iter()
    .find(|slice| slice.contract.as_str() == name)
    .map(|slice| slice.symbols)
    .unwrap_or_default();
    let filtered = if symbols.is_empty() {
        source
    } else {
        source
            .lines()
            .filter(|line| symbols.iter().any(|symbol| line.contains(symbol)))
            .collect::<Vec<_>>()
            .join("\n")
    };
    let complete = filtered.len() <= EXCERPT_CAP;
    let mut text = filtered;
    if !complete {
        let mut cut = EXCERPT_CAP;
        while cut > 0 && !text.is_char_boundary(cut) {
            cut -= 1;
        }
        text.truncate(cut);
    }
    Some(Excerpt { text, complete })
}

/// A session-lifecycle payload (addendum §6): `SessionStart` with the
/// firing source. Detected BEFORE normalization so lifecycle events never
/// count as malformed write payloads.
struct SessionLifecycle {
    session: SessionId,
    source: String,
}

fn session_lifecycle(raw: &str) -> Option<SessionLifecycle> {
    let value: serde_json::Value = serde_json::from_str(raw).ok()?;
    if value.get("hook_event_name")?.as_str()? != "SessionStart" {
        return None;
    }
    let session = value.get("session_id")?.as_str()?;
    let source = value
        .get("source")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("startup");
    Some(SessionLifecycle {
        session: SessionId::from_name(session),
        source: source.to_owned(),
    })
}

/// Digest injection, compaction-aware and deduplicated (spec §7.2/§7.3):
/// once per epoch per (session, cwd); a compact-sourced start clears the
/// scope so the digest re-emits in full; repeats are silent — the digest
/// is never stacked in a long session (addendum §6).
fn handle_session_start(
    agent: Agent,
    manifest: &Manifest,
    lifecycle: &SessionLifecycle,
) -> Result<i32> {
    let index = DeliveryIndex::open(events_db_path()?)?;
    let cwd = std::env::current_dir()?.display().to_string();
    if lifecycle.source == "compact" {
        index.clear(&lifecycle.session, &cwd)?;
    }
    let decision = index.decide(&DeliveryRequest {
        session: &lifecycle.session,
        cwd: &cwd,
        slice_key: DIGEST_SLICE_KEY,
        complete: true,
    })?;
    if decision == Delivery::Pointer {
        return Ok(0);
    }
    let digest = super::instructions::render_digest(manifest)?;
    match agent {
        Agent::Claude | Agent::Codex | Agent::Auggie => print!(
            "{}",
            serde_json::json!({
                "hookSpecificOutput": {
                    "hookEventName": "SessionStart",
                    "additionalContext": digest,
                }
            })
        ),
        // Hermes/opencode lifecycle wrappers relay raw text themselves.
        Agent::Hermes | Agent::Opencode => print!("{digest}"),
    }
    Ok(0)
}

/// Malformed payloads: a partial parse revealing a protected path fails CLOSED,
/// then (F60) a payload NAMING a path under an unwaivable rule fails closed,
/// and anything else fails open ON THE RECORD (Phase 1 review directives, same
/// contract as the check verb).
/// F71 Phase B: the gate cannot load its rules, so it refuses the write.
///
/// Terminal and ladder-exempt (charter Addendum 1, sixth question): the remedy
/// is human-only, so every repeat carries the same actionable text and the
/// attempt counter is never consulted. The message contract (question 5) is
/// pinned by `hook_manifest_skew_deny.rs`: the load error verbatim, the
/// reinstall command, and the escape with one clause on what it disables.
fn render_skew_deny(agent: Agent, log: &EventLog, raw: &str, error: &str) -> Result<i32> {
    let session = SessionId::from_name("anonymous-session");
    let record = CheckResult {
        decision: pushkin_core::envelope::Decision::Block,
        violations: vec![Violation {
            file: super::manifest_agent_display(),
            line: 0,
            rule: "pushkin.manifest_unavailable".to_owned(),
            contract: None,
            fix_hint: "reinstall the pushkin binary or repair the manifest".to_owned(),
            suggestions: Vec::new(),
            severity: pushkin_core::envelope::Severity::Error,
        }],
        duration_ms: 0.0,
    };
    log.append(&session, &record)?;
    let prose = format!(
        "pushkin: write DENIED — the gate cannot load its rules, and a gate that \
         cannot read its rules refuses rather than waving writes through (F71).\n  \
         {error}\n  If this binary is older than the manifest schema, reinstall it: \
         cargo install --path crates/pushkin-cli\n  Emergency escape: \
         PUSHKIN_DISABLE=1 disables all pushkin write-gating in this environment \
         until unset.\n  This deny repeats for every write until a human fixes the \
         manifest or the binary — do not retry variations; report it."
    );
    let encoded = match normalize(agent, raw) {
        Ok(action) if action.is_stop => {
            encode_stop_deny(agent, &prose).unwrap_or_else(|| encode_deny(agent, &prose))
        }
        _ => encode_deny(agent, &prose),
    };
    print!("{encoded}");
    Ok(0)
}

fn handle_malformed(
    agent: Agent,
    manifest: &Manifest,
    log: &EventLog,
    partial: Option<String>,
    raw: &str,
) -> Result<i32> {
    let session = SessionId::from_name("anonymous-session");
    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)?;
            let prose = render_with_ladder(&result, 1);
            print!("{}", encode_deny(agent, &prose));
            return Ok(0);
        }
    }
    // F60 — the payload could not be read, so what it DOES is unknown. If it
    // names a path under an unwaivable rule, refuse: three findings in this
    // program (F48, F58, F59) were writes that reached a gated path precisely
    // because the normalizer did not recognize their shape.
    let scanned = apply_waivers(gate_unreadable_payload(manifest, raw));
    if !scanned.violations.is_empty() {
        log.append(&session, &scanned)?;
        let prose = render_with_ladder(&scanned, 1);
        print!("{}", encode_deny(agent, &prose));
        return Ok(0);
    }
    log.append_failopen(&session, "malformed hook payload")?;
    eprintln!(
        "pushkin: unrecognized {} hook payload, failing open (event logged; \
         run `pushkin doctor` if this repeats)",
        agent.as_str()
    );
    print!("{}", encode_allow(agent));
    Ok(0)
}

/// Cross-agent claim check (spec §9): active only when the orchestrator
/// exported `PUSHKIN_RUN_ID` + `PUSHKIN_AGENT_ID`. A write to a path
/// another agent holds in this run is deterministically denied, holder
/// named. No board / no env = no claim gating (single-agent sessions are
/// unaffected). Board read errors fail open here — the claim layer is
/// coordination, not the contract gate; the contract pipeline already ran.
fn claim_violations(action: &ToolAction) -> Vec<Violation> {
    let (Ok(run), Ok(agent_id)) = (
        std::env::var("PUSHKIN_RUN_ID"),
        std::env::var("PUSHKIN_AGENT_ID"),
    ) else {
        return Vec::new();
    };
    if !std::path::Path::new(super::board::BOARD_DB).exists() {
        return Vec::new();
    }
    let Ok(board) = super::board::open_board(&run) else {
        return Vec::new();
    };
    action
        .files
        .iter()
        .filter_map(|write| {
            let holder = board.blocking_holder(&agent_id, &write.path).ok()??;
            Some(Violation {
                file: write.path.clone(),
                line: 0,
                rule: "pushkin.board.claimed_path".to_owned(),
                contract: None,
                fix_hint: format!(
                    "{} is claimed by {holder} in run {run}. Do not edit it; \
                     coordinate via `pushkin board send --to {holder}` or \
                     work elsewhere until the claim is released.",
                    write.path
                ),
                suggestions: Vec::new(),
                severity: Severity::Error,
            })
        })
        .collect()
}

/// The agent write-time verdict: the shared rule evaluation
/// (`super::decide`) asked as the `AgentWriteTime` surface. Waivers are applied
/// inside `decide` per leaf (Shape 2, charter 2026-08-18 Addendum 1); this
/// verb keeps its own payload normalization (`normalize`) and rendering.
fn evaluate(manifest: &Manifest, action: &ToolAction) -> Result<CheckResult> {
    super::decide(&super::DecideRequest {
        manifest,
        action,
        surface: super::Surface::AgentWriteTime,
    })
}

/// The uniform envelope prose plus the escalation ladder (addendum §5):
/// attempt 1 = full retry prompt; attempt 2 = firmer, no-identical-retry;
/// attempt 3 = the STOP shape with the hand-back instruction. The waiver
/// pointer is present at every rung, addressed to the human.
fn render_with_ladder(result: &CheckResult, attempt: u64) -> String {
    render_ladder_for(result, attempt, Intent::Write)
}

/// The ladder, told in terms of the action the agent actually took. The
/// rungs are identical in force — only the noun changes, so a denied read
/// is never narrated as a blocked write (D1).
fn render_ladder_for(result: &CheckResult, attempt: u64, intent: Intent) -> String {
    let action = match intent {
        // An Edit/MultiEdit is a write in everything but the payload shape —
        // narrating it as anything else would misname what the agent did.
        Intent::Write | Intent::MutateNoContent(_) => "write",
        // D1 again: the noun names what the agent actually did. A refused
        // delete narrated as a blocked "write" would send the agent looking
        // for content it never sent.
        Intent::Delete => "delete",
        // A shell read is still a read: the noun names what the agent did,
        // and the compliant alternative is the same one.
        Intent::ReadWhole | Intent::ReadRange | Intent::Shell => "read",
    };
    let mut lines: Vec<String> = Vec::new();
    match attempt {
        0 | 1 => {
            lines.push(format!(
                "pushkin: {action} blocked. Fix the violations below and retry."
            ));
        }
        2 => lines.push(format!(
            "pushkin: {action} blocked AGAIN. Do not retry the same {action} — the \
             result will be identical. Fix the violations below or stop."
        )),
        _ => lines.push(format!(
            "pushkin: STOP. This {action} has been blocked 3 times. Do not attempt it \
             again. Report the blocker to the human with the violation details below."
        )),
    }
    for violation in &result.violations {
        let contract = violation
            .contract
            .as_deref()
            .map(|name| format!(" (contract: '{name}')"))
            .unwrap_or_default();
        lines.push(format!(
            "  {}:{} [{}]{contract} — attempt {}/{ATTEMPT_CAP}",
            violation.file,
            violation.line,
            violation.rule,
            attempt.max(1)
        ));
        lines.push(format!("    fix: {}", violation.fix_hint));
        for suggestion in &violation.suggestions {
            lines.push(format!("    try: {suggestion}"));
        }
        // D2: a waiver is the exit for a rule the agent CANNOT satisfy
        // itself. The read contract is not one of those — narrowing the
        // read, or asking the retrieval tool, always clears it — so
        // pointing at a human here would invite escalation over
        // self-service.
        if violation.rule != pushkin_core::pipeline::RULE_RAW_READ {
            lines.push(format!(
                "    waiver: a human (not you) can run `pushkin waive {}` to record an exception.",
                violation.rule
            ));
        }
    }
    lines.join("\n")
}