openlatch-client 0.3.3

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
// openlatch-hook: Minimal hook handler binary (CloudEvents Mode A).
//
// Reads raw agent event JSON from stdin, wraps it in a CloudEvents v1.0.2
// structured-mode envelope, POSTs to the local daemon at /hooks, and writes
// the agent-specific hook-output JSON to stdout. The daemon speaks
// OpenLatch's agent-neutral `VerdictResponse`; this binary translates into
// whatever the caller agent expects (see `openlatch_client::hook_output`).
//
// Fail-open: if the daemon is unreachable OR its response fails to parse,
// emit the agent's silent "continue normally" shape (typically `{}`) and
// append the envelope to `fallback.jsonl` for later replay. Fail-open is
// silent on stdout — any operator-facing diagnostic goes to the log, never
// to the user's transcript.
//
// CRITICAL: binary must stay <20MB and cold-start in <3ms.
// No file I/O at startup. No DNS. No full tokio runtime.
//
// SECURITY (T-02-10): stdin read is capped at 1MB to prevent memory exhaustion.
// SECURITY (T-02-11): fallback log path is pinned under `~/.openlatch/logs/`.

use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::Duration;

use openlatch_client::hook_output::{self, Verdict, VerdictContext};

/// Maximum stdin payload size: 1MB (mirrors daemon's request body limit).
const MAX_INPUT_SIZE: usize = 1_048_576;

/// Mirrors the default `cloud.fallback_max_bytes` (50 MB). Hardcoded because
/// the hook can't read `config.toml` without breaking its size + cold-start
/// budgets; the daemon is authoritative when up.
const FALLBACK_MAX_BYTES: u64 = 52_428_800;

/// Connect timeout for daemon POST: fail fast if daemon is not listening.
const CONNECT_TIMEOUT: Duration = Duration::from_millis(100);

/// Total request timeout: allows daemon to process and respond.
const TOTAL_TIMEOUT: Duration = Duration::from_millis(500);

/// CloudEvents structured-mode Content-Type (single event).
const CT_CLOUDEVENTS_SINGLE: &str = "application/cloudevents+json";

/// Entry point for the openlatch-hook binary.
///
/// Fully synchronous: the one HTTP request this binary makes is a blocking `ureq`
/// call, so there is no async runtime to start. tokio remains a workspace dependency
/// for the other binary — this saves runtime startup, not tree size.
fn main() {
    // `--version` / `-V`, answered BEFORE the stdin read below.
    //
    // This binary stamps `clientversion` onto every envelope it emits, but had
    // no way to report that version to a human: `parse_hook_args` only
    // recognises `--agent` / `--event`, so `--version` fell through to the
    // normal hook path and printed the fail-open `{}` with exit 0. The release
    // smoke test in publish.yml ran exactly that command, so it proved only
    // that the binary starts.
    //
    // Ordering is load-bearing. The hook is normally fed event JSON on stdin;
    // run `--version` on a terminal after the read below and it blocks forever
    // waiting for input that is never coming.
    //
    // Hand-rolled rather than clap: this binary is held under 20MB and 3ms of
    // cold start (see the module header), which is the same reason
    // `parse_hook_args` exists.
    if std::env::args()
        .skip(1)
        .any(|a| a == "--version" || a == "-V")
    {
        println!("openlatch-hook {}", env!("OPENLATCH_VERSION"));
        return;
    }

    // Stdin is capped at MAX_INPUT_SIZE per T-02-10.
    let mut input = String::new();
    let mut stdin = std::io::stdin().take(MAX_INPUT_SIZE as u64);
    let _ = stdin.read_to_string(&mut input);

    // Agent identity comes from either `--agent`/`--event` CLI flags (preferred,
    // cross-platform) or OPENLATCH_AGENT_TYPE / OPENLATCH_EVENT_TYPE env vars
    // (POSIX-only fallback). Hook-config generators emit CLI flags so the
    // command string works identically on Windows cmd.exe, PowerShell, and
    // POSIX shells. Unknown/missing values fall through to best-effort
    // inference — a misconfigured hook still produces a valid CloudEvent.
    let args = parse_hook_args(&std::env::args().skip(1).collect::<Vec<_>>());
    let agent_type = args
        .agent
        .or_else(|| std::env::var("OPENLATCH_AGENT_TYPE").ok())
        .unwrap_or_else(|| "unknown".into());
    let event_type = args
        .event
        .or_else(|| std::env::var("OPENLATCH_EVENT_TYPE").ok())
        .or_else(|| detect_event_type(&input).map(str::to_string))
        .unwrap_or_else(|| "unknown".into());

    let (port, token) = resolve_secrets(args.openlatch_dir.as_deref());

    let envelope = build_cloudevent(&agent_type, &event_type, &input);

    // SECURITY: daemon binds 127.0.0.1 only. We hit the literal IPv4 loopback
    // rather than `localhost` because on Windows `localhost` often resolves
    // `::1` first — the daemon isn't listening there, and the 100ms connect
    // timeout would elapse before the IPv4 fallback kicks in.
    let url = format!("http://127.0.0.1:{port}/hooks");
    let body = serde_json::to_string(&envelope).unwrap_or_else(|_| "{}".to_string());

    let result = forward_to_daemon(&url, &token, &body);

    // Success path: parse the daemon's `VerdictResponse` and translate to
    // the caller agent's stdout shape. Parse failure degrades to the
    // silent fail-open default so a malformed daemon response never
    // surfaces a schema-validation error in the agent.
    // Failure path: log the envelope for later replay, emit the agent's
    // silent "continue normally" shape. No user-visible diagnostic.
    let output = match result {
        Ok(response) if !response.is_empty() => {
            translate_daemon_response(&agent_type, &event_type, &response)
        }
        _ => {
            let _ = append_fallback_log(&body);
            hook_output::translate(&agent_type, &event_type, &Verdict::allow())
        }
    };

    println!("{output}");
}

/// Parse the daemon's `VerdictResponse` body and translate it into the
/// caller agent's stdout JSON. Returns the silent allow shape if the body
/// isn't valid JSON — a defensive posture so daemon-side issues never
/// trip the agent's output validator.
fn translate_daemon_response(agent: &str, event: &str, body: &str) -> serde_json::Value {
    let parsed: serde_json::Value = match serde_json::from_str(body) {
        Ok(v) => v,
        Err(_) => return hook_output::translate(agent, event, &Verdict::allow()),
    };
    let decision = parsed
        .get("verdict")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("allow");
    let reason = parsed.get("reason").and_then(serde_json::Value::as_str);
    // Optional `context` carries pending-alert headline + body that the
    // translator surfaces as SessionStart `additionalContext` or
    // PreToolUse `ask` reason. The daemon stamps it on outbound
    // responses when a queued alert matches the session_ref_id.
    let ctx_obj = parsed.get("context").and_then(serde_json::Value::as_object);
    let context_owned: Option<VerdictContext<'_>> = ctx_obj.and_then(|o| {
        let headline = o.get("headline").and_then(serde_json::Value::as_str)?;
        let body = o.get("body").and_then(serde_json::Value::as_str)?;
        Some(VerdictContext { headline, body })
    });
    let context = context_owned.as_ref();
    hook_output::translate(
        agent,
        event,
        &Verdict {
            decision,
            reason,
            context,
        },
    )
}

/// Everything the hook reads off its own command line.
#[derive(Debug, Default, PartialEq)]
struct HookArgs {
    /// `--agent <slug>`.
    agent: Option<String>,
    /// `--event <name>`.
    event: Option<String>,
    /// `--openlatch-dir <path>` — where both secrets live, for an agent that
    /// cannot forward environment variables into the hook process.
    openlatch_dir: Option<PathBuf>,
}

/// Parse `--agent <slug>`, `--event <name>` and `--openlatch-dir <path>` from
/// argv without pulling in the `clap` crate (binary stays <20MB). Accepts
/// `--flag=VALUE` and `--flag VALUE` for each. Unknown flags are silently
/// ignored — the hook binary must never fail-closed because the agent handed it
/// something unexpected.
///
/// Takes its input rather than reading `std::env::args()` so a test can supply
/// one: the flag it exists for is unreachable from the process environment.
fn parse_hook_args(args: &[String]) -> HookArgs {
    let mut parsed = HookArgs::default();
    let mut i = 0;
    while i < args.len() {
        let arg = &args[i];
        if let Some(v) = arg.strip_prefix("--agent=") {
            parsed.agent = Some(v.to_string());
            i += 1;
        } else if arg == "--agent" {
            if let Some(v) = args.get(i + 1) {
                parsed.agent = Some(v.clone());
                i += 2;
            } else {
                i += 1;
            }
        } else if let Some(v) = arg.strip_prefix("--event=") {
            parsed.event = Some(v.to_string());
            i += 1;
        } else if arg == "--event" {
            if let Some(v) = args.get(i + 1) {
                parsed.event = Some(v.clone());
                i += 2;
            } else {
                i += 1;
            }
        } else if let Some(v) = arg.strip_prefix("--openlatch-dir=") {
            parsed.openlatch_dir = Some(PathBuf::from(v));
            i += 1;
        } else if arg == "--openlatch-dir" {
            if let Some(v) = args.get(i + 1) {
                parsed.openlatch_dir = Some(PathBuf::from(v));
                i += 2;
            } else {
                i += 1;
            }
        } else {
            i += 1;
        }
    }
    parsed
}

/// The daemon port and bearer token this hook process should use.
///
/// `Some(dir)` — an agent whose channel is `OpenlatchDirArg`: both secrets come
/// out of that directory's `daemon.port` and `daemon.token`, the same two files
/// the rest of the client writes. The token value never reaches the agent's
/// config at all.
///
/// `None` — today's resolution, unchanged: `OPENLATCH_PORT` from the
/// environment, else the default directory's `daemon.port`, else 7443; and the
/// token from `OPENLATCH_TOKEN`.
fn resolve_secrets(dir: Option<&Path>) -> (u16, String) {
    match dir {
        Some(dir) => {
            let port = std::fs::read_to_string(dir.join("daemon.port"))
                .ok()
                .and_then(|p| p.trim().parse::<u16>().ok())
                .unwrap_or(7443);
            let token = std::fs::read_to_string(dir.join("daemon.token"))
                .map(|t| t.trim().to_string())
                .unwrap_or_default();
            (port, token)
        }
        None => {
            // Port resolution: OPENLATCH_PORT env > daemon.port file > 7443.
            let port = std::env::var("OPENLATCH_PORT")
                .ok()
                .and_then(|p| p.parse::<u16>().ok())
                .or_else(read_port_file)
                .unwrap_or(7443);
            let token = std::env::var("OPENLATCH_TOKEN").unwrap_or_default();
            (port, token)
        }
    }
}

/// Best-effort event type detection from raw JSON input.
///
/// Inspects the JSON structure for well-known field names to infer the
/// Claude Code hook event name. Only used as a fallback when
/// `OPENLATCH_EVENT_TYPE` is not set in the hook config.
fn detect_event_type(input: &str) -> Option<&'static str> {
    let v: serde_json::Value = serde_json::from_str(input).ok()?;
    if v.get("tool_name").is_some() || v.get("toolName").is_some() {
        Some("pre_tool_use")
    } else if v.get("prompt").is_some() {
        Some("user_prompt_submit")
    } else if v.get("stopReason").is_some() || v.get("stop_reason").is_some() {
        Some("stop")
    } else {
        None
    }
}

/// Build a CloudEvents v1.0.2 structured-mode envelope around the raw agent
/// payload. All OpenLatch metadata lives as lowercase-alphanumeric extension
/// attributes per the spec. Daemon stamps any missing extension values
/// (os/arch/localipv4/…) after receipt — the hook binary sets only what it
/// knows without touching disk.
fn build_cloudevent(agent_type: &str, event_type: &str, raw_input: &str) -> serde_json::Value {
    let data: serde_json::Value =
        serde_json::from_str(raw_input).unwrap_or(serde_json::Value::Null);
    let subject = extract_session_id(&data);

    serde_json::json!({
        "specversion": "1.0",
        "id": new_event_id(),
        "source": agent_type,
        "type": event_type,
        "time": now_rfc3339_z(),
        "datacontenttype": "application/json",
        "subject": subject,
        "data": data,
        "os": std::env::consts::OS,
        "arch": std::env::consts::ARCH,
        // Must agree with the daemon's own stamp in `daemon/handlers.rs` — one
        // wire attribute, one meaning. See build.rs for why this is not
        // CARGO_PKG_VERSION.
        "clientversion": env!("OPENLATCH_VERSION"),
    })
}

/// Extract `session_id` (Claude-Code-style) or `sessionId` from the raw event
/// body for use as the CloudEvents `subject` attribute.
fn extract_session_id(data: &serde_json::Value) -> String {
    data.get("session_id")
        .or_else(|| data.get("sessionId"))
        .and_then(|v| v.as_str())
        .unwrap_or("unknown")
        .to_string()
}

/// Generate an `evt_<UUIDv7>` identifier. Inlined here instead of depending
/// on the `uuid` crate so the hook binary stays minimal — UUIDv7 is 128 bits
/// of (unix_ts_ms << 80) | (rand | version | variant).
fn new_event_id() -> String {
    // Pull current time in milliseconds since the Unix epoch.
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default();
    let ms: u64 = now.as_millis() as u64;

    // Fill the low 10 bytes with process-derived randomness. We use the
    // nanosecond fraction + process id, which is adequate within the hook
    // binary's purpose — dedup and audit correlation do not need crypto-grade
    // randomness.
    let nanos = now.subsec_nanos() as u64;
    let pid = std::process::id() as u64;
    let mut rand_bytes = [0u8; 10];
    let mix = nanos.wrapping_mul(0x9e37_79b9_7f4a_7c15).wrapping_add(pid);
    for (i, b) in rand_bytes.iter_mut().enumerate() {
        *b = ((mix >> ((i % 8) * 8)) & 0xff) as u8;
    }

    // 48-bit ms timestamp
    let b0 = ((ms >> 40) & 0xff) as u8;
    let b1 = ((ms >> 32) & 0xff) as u8;
    let b2 = ((ms >> 24) & 0xff) as u8;
    let b3 = ((ms >> 16) & 0xff) as u8;
    let b4 = ((ms >> 8) & 0xff) as u8;
    let b5 = (ms & 0xff) as u8;

    // Byte 6: 0x7X (version 7) + high nibble of rand
    let b6 = 0x70 | (rand_bytes[0] & 0x0f);
    let b7 = rand_bytes[1];
    // Byte 8: 0b10xxxxxx (RFC 4122 variant)
    let b8 = 0x80 | (rand_bytes[2] & 0x3f);
    let b9 = rand_bytes[3];
    let b10 = rand_bytes[4];
    let b11 = rand_bytes[5];
    let b12 = rand_bytes[6];
    let b13 = rand_bytes[7];
    let b14 = rand_bytes[8];
    let b15 = rand_bytes[9];

    format!(
        "evt_{b0:02x}{b1:02x}{b2:02x}{b3:02x}-{b4:02x}{b5:02x}-{b6:02x}{b7:02x}-{b8:02x}{b9:02x}-{b10:02x}{b11:02x}{b12:02x}{b13:02x}{b14:02x}{b15:02x}"
    )
}

/// Current UTC time as RFC 3339 with the `Z` suffix.
///
/// Hand-rolled to avoid the chrono dependency on the hook-binary code path —
/// chrono is a full-cli-only dep and the hook binary must stay minimal.
fn now_rfc3339_z() -> String {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default();
    let secs = now.as_secs();
    let s = secs % 60;
    let m = (secs / 60) % 60;
    let h = (secs / 3600) % 24;
    let days = secs / 86400;
    let (year, month, day) = days_to_ymd(days);
    format!("{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{s:02}Z")
}

/// Proleptic Gregorian calendar: days since 1970-01-01 → (year, month, day).
fn days_to_ymd(days: u64) -> (u64, u64, u64) {
    let z = days + 719468;
    let era = z / 146097;
    let doe = z % 146097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    (y, m, d)
}

/// POST the serialised CloudEvent to the daemon and return the raw response.
///
/// Blocking on purpose: the hook is a fresh process making exactly one request, so
/// an async runtime buys nothing and costs startup. `ureq` rather than `reqwest`
/// keeps the whole hyper/tower graph out of the hot-path binary
/// (`ci/baselines/hook-deps.txt`).
fn forward_to_daemon(
    url: &str,
    token: &str,
    body: &str,
) -> Result<String, Box<dyn std::error::Error>> {
    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_connect(Some(CONNECT_TIMEOUT))
            .timeout_global(Some(TOTAL_TIMEOUT))
            // The caller branches on the body, exactly as it did with reqwest; a non-2xx
            // must not become a transport error and take the fail-open path.
            .http_status_as_error(false)
            // SECURITY: ureq reads ALL_PROXY / HTTP_PROXY from the environment by
            // default. `url` is the literal 127.0.0.1 daemon listener, so honouring
            // those would send the verdict request to a corporate proxy and break the
            // loopback hard-bypass invariant. The hook never proxies anything.
            .proxy(None)
            // SECURITY: ureq follows up to ten redirects by default. A stale process
            // squatting the daemon port could answer `302 Location: http://elsewhere/`
            // and the hook would leave 127.0.0.1 — resolving DNS and making an outbound
            // request — even though the proxy is disabled. The daemon never redirects.
            .max_redirects(0)
            .build(),
    );

    let mut response = agent
        .post(url)
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", CT_CLOUDEVENTS_SINGLE)
        .send(body)?;

    Ok(response.body_mut().read_to_string()?)
}

/// Append the serialised CloudEvent to the fallback log file.
///
/// `OPENLATCH_DIR` wins, else `%APPDATA%\openlatch` on Windows /
/// `~/.openlatch` elsewhere. Resolved inline to avoid pulling in `dirs`
/// (size budget). The cap check is best-effort — failures never
/// fail-close the hook.
fn append_fallback_log(event_json: &str) -> std::io::Result<()> {
    let log_dir = openlatch_log_dir();
    std::fs::create_dir_all(&log_dir)?;

    let path = log_dir.join("fallback.jsonl");
    let line_bytes = event_json.len() as u64 + 1;
    enforce_fallback_cap(&path, &log_dir.join("fallback.jsonl.offset"), line_bytes);

    use std::io::Write;
    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;
    writeln!(file, "{event_json}")?;
    Ok(())
}

/// Drop-oldest via offset advance — same algorithm as
/// `daemon::fallback_replay::enforce_fallback_size_cap`. Hot path
/// short-circuits on the metadata stat alone; only walks the file when
/// the raw size already exceeds the cap.
fn enforce_fallback_cap(path: &std::path::Path, offset_path: &std::path::Path, line_bytes: u64) {
    let Ok(metadata) = std::fs::metadata(path) else {
        return;
    };
    let total_len = metadata.len();
    // Fast path: file size alone proves the append fits without touching
    // the offset file. Trades worst-case eviction precision (we may keep
    // dead-prefix bytes longer) for one less syscall + one less alloc on
    // every hook invocation against the 3ms cold-start budget.
    if total_len + line_bytes <= FALLBACK_MAX_BYTES {
        return;
    }
    let cursor = read_offset_local(offset_path);
    let unread = total_len.saturating_sub(cursor);
    if unread + line_bytes <= FALLBACK_MAX_BYTES {
        return;
    }
    let excess = (unread + line_bytes) - FALLBACK_MAX_BYTES;

    use std::io::{BufRead, BufReader, Seek, SeekFrom};
    let Ok(file) = std::fs::File::open(path) else {
        return;
    };
    let mut reader = BufReader::new(file);
    if reader.seek(SeekFrom::Start(cursor)).is_err() {
        return;
    }
    let mut advanced: u64 = 0;
    let mut new_offset = cursor;
    for line in reader.lines() {
        let Ok(raw) = line else {
            return;
        };
        let len = raw.len() as u64 + 1;
        new_offset += len;
        advanced += len;
        if advanced >= excess {
            break;
        }
    }
    if new_offset == cursor {
        return;
    }
    write_offset_local(offset_path, new_offset);
}

// Local duplicates of core::cloud::offset helpers — the hook binary
// can't link core/cloud/ without breaking its <1MB / <3ms budgets.

fn read_offset_local(path: &std::path::Path) -> u64 {
    std::fs::read_to_string(path)
        .ok()
        .and_then(|s| s.trim().parse::<u64>().ok())
        .unwrap_or(0)
}

fn write_offset_local(path: &std::path::Path, value: u64) {
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let tmp = path.with_extension("offset.tmp");
    if let Ok(mut f) = std::fs::File::create(&tmp) {
        use std::io::Write;
        if writeln!(f, "{value}").is_ok() && f.sync_all().is_ok() {
            let _ = std::fs::rename(&tmp, path);
        }
    }
}

fn openlatch_log_dir() -> std::path::PathBuf {
    if let Ok(dir) = std::env::var("OPENLATCH_DIR") {
        if !dir.is_empty() {
            return std::path::PathBuf::from(dir).join("logs");
        }
    }
    #[cfg(windows)]
    {
        std::env::var("APPDATA")
            .map(std::path::PathBuf::from)
            .unwrap_or_else(|_| home_dir())
            .join("openlatch")
            .join("logs")
    }
    #[cfg(not(windows))]
    {
        home_dir().join(".openlatch").join("logs")
    }
}

fn home_dir() -> std::path::PathBuf {
    #[cfg(unix)]
    {
        std::env::var("HOME")
            .map(Into::into)
            .unwrap_or_else(|_| "/tmp".into())
    }
    #[cfg(windows)]
    {
        std::env::var("USERPROFILE")
            .map(Into::into)
            .unwrap_or_else(|_| "C:\\Temp".into())
    }
}

fn read_port_file() -> Option<u16> {
    #[cfg(windows)]
    let path = std::env::var("APPDATA")
        .map(std::path::PathBuf::from)
        .unwrap_or_else(|_| home_dir())
        .join("openlatch")
        .join("daemon.port");
    #[cfg(not(windows))]
    let path = home_dir().join(".openlatch").join("daemon.port");
    std::fs::read_to_string(path)
        .ok()?
        .trim()
        .parse::<u16>()
        .ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{BufRead, BufReader, Write};
    use std::net::{TcpListener, TcpStream};
    use std::sync::Mutex;
    use std::time::Instant;

    /// `forward_to_daemon` consults process-global proxy environment variables, so the
    /// tests that exercise it cannot run concurrently: one of them sets `ALL_PROXY` to
    /// prove the hook ignores it, and that variable is visible to every other thread.
    static HTTP_TEST_LOCK: Mutex<()> = Mutex::new(());

    /// Read one complete HTTP/1.1 request (headers plus a `Content-Length` body) off
    /// `sock`. A single `read()` would be a race: the headers and the body are not
    /// guaranteed to arrive in the same TCP segment.
    fn read_request(sock: &TcpStream) -> String {
        let mut reader = BufReader::new(sock);
        let mut head = String::new();
        let mut content_length = 0usize;
        loop {
            let mut line = String::new();
            if reader.read_line(&mut line).expect("read header line") == 0 {
                break;
            }
            if let Some(v) = line
                .to_ascii_lowercase()
                .strip_prefix("content-length:")
                .map(str::trim)
                .and_then(|v| v.parse::<usize>().ok())
            {
                content_length = v;
            }
            let done = line == "\r\n" || line == "\n";
            head.push_str(&line);
            if done {
                break;
            }
        }
        let mut body = vec![0u8; content_length];
        if content_length > 0 {
            std::io::Read::read_exact(&mut reader, &mut body).expect("read body");
        }
        head + &String::from_utf8_lossy(&body)
    }

    /// Accept exactly one connection, capture the request, and reply with `response`.
    fn one_shot(listener: TcpListener, response: &'static str) -> std::thread::JoinHandle<String> {
        std::thread::spawn(move || {
            let (mut sock, _) = listener.accept().expect("accept");
            let request = read_request(&sock);
            sock.write_all(response.as_bytes()).expect("write response");
            sock.flush().expect("flush");
            request
        })
    }

    fn loopback_listener() -> (TcpListener, String) {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
        let port = listener.local_addr().expect("local_addr").port();
        (listener, format!("http://127.0.0.1:{port}/hooks"))
    }

    #[test]
    fn posts_the_envelope_verbatim_to_the_daemon() {
        let _guard = HTTP_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let (listener, url) = loopback_listener();
        let server = one_shot(
            listener,
            "HTTP/1.1 200 OK\r\nContent-Length: 15\r\n\r\n{\"decision\":1}\n",
        );

        let body = r#"{"specversion":"1.0","type":"pre_tool_use"}"#;
        let response = forward_to_daemon(&url, "tok-123", body).expect("forward");

        let request = server.join().expect("server thread");
        let lower = request.to_ascii_lowercase();
        assert!(
            request.starts_with("POST /hooks HTTP/1.1\r\n"),
            "unexpected request line in:\n{request}"
        );
        assert!(
            lower.contains("authorization: bearer tok-123\r\n"),
            "missing bearer token in:\n{request}"
        );
        assert!(
            lower.contains(&format!(
                "content-type: {}\r\n",
                CT_CLOUDEVENTS_SINGLE.to_ascii_lowercase()
            )),
            "missing CloudEvents content-type in:\n{request}"
        );
        assert!(
            request.ends_with(body),
            "body not forwarded verbatim:\n{request}"
        );
        assert_eq!(response, "{\"decision\":1}\n");
    }

    #[test]
    fn non_2xx_is_returned_as_a_body_not_an_error() {
        let _guard = HTTP_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let (listener, url) = loopback_listener();
        let server = one_shot(
            listener,
            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 4\r\n\r\noops",
        );

        // `http_status_as_error(false)` keeps parity with the reqwest implementation:
        // `main` decides what to do with the body, and a 5xx must not be indistinguishable
        // from an unreachable daemon.
        let response =
            forward_to_daemon(&url, "t", "{}").expect("5xx must not be a transport error");
        assert_eq!(response, "oops");
        server.join().expect("server thread");
    }

    #[test]
    fn a_silent_daemon_times_out_within_the_budget() {
        let _guard = HTTP_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let (listener, url) = loopback_listener();
        // Accept, then never answer. `main` turns this `Err` into the fail-open path;
        // the unit's job is to prove the budget is enforced at all.
        let server = std::thread::spawn(move || {
            let (sock, _) = listener.accept().expect("accept");
            std::thread::sleep(Duration::from_secs(3));
            drop(sock);
        });

        let started = Instant::now();
        let result = forward_to_daemon(&url, "t", "{}");
        let elapsed = started.elapsed();

        assert!(result.is_err(), "a silent daemon must not resolve");
        assert!(
            elapsed < TOTAL_TIMEOUT + Duration::from_millis(200),
            "took {elapsed:?}, budget is {TOTAL_TIMEOUT:?}"
        );
        server.join().expect("server thread");
    }

    #[test]
    fn proxy_environment_never_diverts_the_loopback_post() {
        let _guard = HTTP_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let (listener, url) = loopback_listener();
        let trap = TcpListener::bind("127.0.0.1:0").expect("bind trap");
        let trap_url = format!("http://127.0.0.1:{}", trap.local_addr().unwrap().port());

        // NO_PROXY has to be CLEARED, not merely left alone. A developer machine that
        // already exempts 127.0.0.1 would make ureq bypass the proxy on its own, so
        // deleting `.proxy(None)` from production code would still leave the trap empty
        // and this test green -- the security control could vanish without a failure.
        let mut previous: Vec<(&str, Option<String>)> = ["NO_PROXY", "no_proxy"]
            .iter()
            .map(|k| {
                let old = std::env::var(k).ok();
                std::env::remove_var(k);
                (*k, old)
            })
            .collect();
        previous.extend(["ALL_PROXY", "HTTP_PROXY", "http_proxy"].iter().map(|k| {
            let old = std::env::var(k).ok();
            std::env::set_var(k, &trap_url);
            (*k, old)
        }));

        let server = one_shot(listener, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}");
        let response = forward_to_daemon(&url, "t", "{}");

        for (k, v) in previous {
            match v {
                Some(v) => std::env::set_var(k, v),
                None => std::env::remove_var(k),
            }
        }

        assert_eq!(response.expect("forward"), "{}");
        server.join().expect("server thread");

        // If the hook had honoured the proxy variables, the CONNECT/absolute-form request
        // would be sitting in the trap's accept backlog.
        trap.set_nonblocking(true).expect("set_nonblocking");
        assert!(
            matches!(trap.accept(), Err(e) if e.kind() == std::io::ErrorKind::WouldBlock),
            "the hook's loopback POST reached the proxy trap"
        );
    }

    // -----------------------------------------------------------------------
    // `--openlatch-dir`: the channel for an agent that cannot forward env vars
    // -----------------------------------------------------------------------
    //
    // Both of these are pure functions over a slice and a path. They spawn no
    // process and mutate no environment variable, so they deliberately do NOT
    // take `HTTP_TEST_LOCK` — that lock serialises the forwarding tests above,
    // and taking it here would slow them down for nothing.

    /// The `OpenlatchDirArg` channel: both secrets come out of the directory
    /// named on the command line, and neither `OPENLATCH_PORT` nor
    /// `OPENLATCH_TOKEN` is consulted — the `Some(dir)` arm reads no
    /// environment variable at all, which is the whole point for an agent that
    /// cannot forward one.
    #[test]
    fn hook_resolves_secrets_from_openlatch_dir_arg() {
        let dir = tempfile::tempdir().expect("temp dir");
        std::fs::write(dir.path().join("daemon.port"), "7551\n").expect("seed daemon.port");
        std::fs::write(dir.path().join("daemon.token"), "  a-real-token\n")
            .expect("seed daemon.token");

        let (port, token) = resolve_secrets(Some(dir.path()));

        assert_eq!(port, 7551, "the port comes from <dir>/daemon.port");
        assert_eq!(
            token, "a-real-token",
            "the token comes from <dir>/daemon.token, trimmed"
        );
    }

    /// Both spellings, and the shape rule the hand-rolled parser must keep: an
    /// unexpected argument is ignored, never an error. A hook that fails closed
    /// on something the agent handed it is the failure mode this binary must
    /// not have.
    #[test]
    fn parse_hook_args_reads_the_openlatch_dir_flag() {
        let spaced: Vec<String> = ["--openlatch-dir", "/tmp/ol"]
            .iter()
            .map(|s| (*s).to_string())
            .collect();
        assert_eq!(
            parse_hook_args(&spaced).openlatch_dir,
            Some(PathBuf::from("/tmp/ol"))
        );

        let equals: Vec<String> = vec!["--openlatch-dir=/tmp/ol".to_string()];
        assert_eq!(
            parse_hook_args(&equals).openlatch_dir,
            Some(PathBuf::from("/tmp/ol"))
        );

        let with_noise: Vec<String> = [
            "--surprise",
            "--openlatch-dir",
            "/tmp/ol",
            "--agent",
            "cursor",
            "--future-flag=1",
        ]
        .iter()
        .map(|s| (*s).to_string())
        .collect();
        assert_eq!(
            parse_hook_args(&with_noise),
            HookArgs {
                agent: Some("cursor".to_string()),
                event: None,
                openlatch_dir: Some(PathBuf::from("/tmp/ol")),
            },
            "an unknown flag is ignored, and the known ones still parse around it"
        );

        assert_eq!(
            parse_hook_args(&[]).openlatch_dir,
            None,
            "absent means today's resolution, byte for byte"
        );
    }
}