Repository navigation
Expand file tree
/
Copy pathcommon.rs
More file actions
2800 lines (2576 loc) · 101 KB
/
Copy pathcommon.rs
File metadata and controls
2800 lines (2576 loc) · 101 KB
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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Shared hook functions — deliver, poll, bind, bootstrap, finalize.
use std::collections::BTreeSet;
use std::io::Read;
use std::net::TcpListener;
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use rusqlite::params;
use serde_json::Value;
use crate::bootstrap;
use crate::db::{HcomDb, InstanceRow, Message};
use crate::identity;
use crate::instance_lifecycle as lifecycle;
use crate::instances;
use crate::log;
use crate::messages;
use crate::shared::constants::MAX_MESSAGES_PER_DELIVERY;
use crate::shared::context::HcomContext;
use crate::shared::{ST_ACTIVE, ST_INACTIVE, ST_LISTENING};
/// Run a hook handler with panic safety.
///
/// Catches panics in the handler closure, logs them, and returns the fallback
/// value instead of crashing the host process. Used by all tool dispatchers.
pub(crate) fn dispatch_with_panic_guard<R>(
tool: &str,
hook_name: &str,
fallback: R,
f: impl FnOnce() -> R,
) -> R {
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
Ok(r) => r,
Err(_) => {
log::log_error(
"hooks",
&format!("{tool}.dispatch.panic"),
&format!("hook={hook_name}"),
);
fallback
}
}
}
/// Commands auto-approved in tool permission rules (Claude/Gemini/Codex settings).
///
/// Included: read-only queries, messaging, and session lifecycle commands that
/// agents need to run without user approval prompts.
/// Excluded: `stop`, `kill`, `run`, `reset` — these are destructive or
/// admin-level and require explicit user approval.
pub(crate) const SAFE_HCOM_COMMANDS: &[&str] = &[
"send",
"start",
"help",
"--help",
"-h",
"list",
"events",
"listen",
"relay",
"config",
"transcript",
"archive",
"bundle",
"status",
"term",
"hooks",
"--version",
"-v",
"--new-terminal",
];
/// Whether a shell command line is exactly one `hcom <safe command> …` (or
/// `uvx hcom …`), for tools where hcom approves commands at runtime.
///
/// Anything the shell could turn into a second command fails: unquoted
/// `; & | < > ( )`, backticks, newlines, and `$` outside single quotes. A
/// prefix match alone would approve `hcom send @x -- hi; rm -rf ~`.
pub(crate) fn is_safe_hcom_command(command: &str) -> bool {
let (mut single, mut double, mut escaped) = (false, false, false);
for ch in command.chars() {
if escaped {
escaped = false;
continue;
}
match ch {
'\n' | '\r' => return false,
'\'' if !double => single = !single,
_ if single => {}
'\\' => escaped = true,
'"' => double = !double,
'$' | '`' => return false,
';' | '&' | '|' | '<' | '>' | '(' | ')' if !double => return false,
_ => {}
}
}
if single || double || escaped {
return false;
}
let Ok(words) = shell_words::split(command) else {
return false;
};
let rest = match words.as_slice() {
[hcom, rest @ ..] if hcom == "hcom" => rest,
[uvx, hcom, rest @ ..] if uvx == "uvx" && hcom == "hcom" => rest,
_ => return false,
};
rest.first()
.is_none_or(|command| SAFE_HCOM_COMMANDS.contains(&command.as_str()))
}
/// Pre-gate check: should hooks proceed?
///
///
/// - HCOM-launched (process_id or is_launched) → always proceed
/// - Otherwise: check if DB has any instances → if not, skip (exit 0, empty output)
///
/// This prevents outputting hints/errors when hcom is installed but not actively used.
pub fn hook_gate_check(ctx: &HcomContext, db: &HcomDb) -> bool {
if ctx.process_id.is_some() || ctx.is_launched {
return true;
}
// Check if any instances exist — distinguish "no rows" from DB error
match db
.conn()
.query_row("SELECT 1 FROM instances LIMIT 1", [], |_| Ok(()))
{
Ok(()) => true,
Err(rusqlite::Error::QueryReturnedNoRows) => false,
Err(e) => {
log::log_warn(
"hooks",
"gate.db_error",
&format!("hook gate DB check failed: {e}, proceeding anyway"),
);
true // On DB error, proceed rather than silently disabling hooks
}
}
}
/// Convert a db::Message to a serde_json::Value object.
pub(crate) fn message_to_value(m: &Message) -> Value {
let mut obj = serde_json::Map::new();
obj.insert("from".into(), Value::String(m.from.clone()));
obj.insert("message".into(), Value::String(m.text.clone()));
if let Some(ref intent) = m.intent {
obj.insert("intent".into(), Value::String(intent.clone()));
}
if let Some(ref thread) = m.thread {
obj.insert("thread".into(), Value::String(thread.clone()));
}
if let Some(id) = m.event_id {
obj.insert("event_id".into(), serde_json::json!(id));
}
if let Some(ref ts) = m.timestamp {
obj.insert("timestamp".into(), Value::String(ts.clone()));
}
if let Some(ref delivered_to) = m.delivered_to {
obj.insert("delivered_to".into(), serde_json::json!(delivered_to));
}
if let Some(ref bundle_id) = m.bundle_id {
obj.insert("bundle_id".into(), Value::String(bundle_id.clone()));
}
Value::Object(obj)
}
/// Load config hints string (from instance-level or global config).
/// Call once per hook invocation and pass to format functions.
pub(crate) fn load_config_hints() -> String {
crate::config::HcomConfig::load(None)
.map(|c| c.hints.clone())
.unwrap_or_default()
}
/// Build instance-data lookup function for message formatting.
pub(crate) fn make_instance_lookup(db: &HcomDb) -> impl Fn(&str) -> Option<Value> + '_ {
|name: &str| db.get_instance(name).ok().flatten()
}
/// Build a tip-tracking callback for hook message formatting.
pub(crate) fn make_tip_checker(db: &HcomDb) -> impl Fn(&str, &str) -> (bool, Box<dyn Fn()>) + '_ {
move |instance_name: &str, tip_key: &str| {
let seen = crate::core::tips::has_seen_tip(db, instance_name, tip_key);
let db_path = db.path().to_path_buf();
let instance_name = instance_name.to_string();
let tip_key = tip_key.to_string();
let mark = Box::new(move || {
if let Ok(mark_db) = HcomDb::open_at(&db_path) {
crate::core::tips::mark_tip_seen(&mark_db, &instance_name, &tip_key);
}
}) as Box<dyn Fn()>;
(seen, mark)
}
}
/// Prepared delivery — messages formatted but cursor not yet advanced.
///
/// Used by tools that need to ensure stdout write succeeds before committing.
pub struct PreparedDelivery {
pub messages: Vec<Value>,
pub formatted: String,
pub ack: super::DeliveryAck,
}
/// Options for [`assemble_gemini_family_lifecycle_outputs`].
pub(crate) struct GeminiFamilyLifecycleOpts {
/// BeforeAgent only: return wake-only context when agy has no pending messages.
pub allow_wake_no_pending: bool,
/// Set instance status to active/prompt when there are no pending messages.
/// Should be true only for BeforeAgent; false for AfterTool (which fires mid-turn
/// after every tool call and must not overwrite the current in-progress status).
pub set_status_on_empty: bool,
}
/// Combined lifecycle hook text + optional deferred ack / early wake-only return.
pub(crate) struct GeminiFamilyLifecycleOutput {
pub parts: Vec<String>,
pub delivery_ack: Option<super::DeliveryAck>,
pub early_wake_context: Option<String>,
}
/// Shared beforeagent/aftertool output assembly for Gemini and Antigravity.
pub(crate) fn assemble_gemini_family_lifecycle_outputs(
db: &HcomDb,
ctx: &HcomContext,
instance: &InstanceRow,
is_agy: bool,
opts: GeminiFamilyLifecycleOpts,
) -> GeminiFamilyLifecycleOutput {
let instance_name = &instance.name;
let mut parts: Vec<String> = Vec::new();
let mut delivery_ack = None;
if is_agy {
// agy gets one short anti-stall preamble before each delivery (see
// ANTIGRAVITY_DELIVERY_ACTION). On an empty wake it gets nothing and
// simply ends its turn — no discovery prompt is needed.
if let Some(prepared) = prepare_pending_messages(db, instance_name) {
parts.push(bootstrap::ANTIGRAVITY_DELIVERY_ACTION.to_string());
parts.push(prepared.formatted);
delivery_ack = Some(prepared.ack);
} else if opts.allow_wake_no_pending && instance.name_announced != 0 {
return GeminiFamilyLifecycleOutput {
parts: vec![],
delivery_ack: None,
early_wake_context: None,
};
}
if let Some(bootstrap) =
inject_bootstrap_once(db, ctx, instance_name, instance, &instance.tool)
{
parts.push(bootstrap);
}
} else {
if let Some(bootstrap) =
inject_bootstrap_once(db, ctx, instance_name, instance, &instance.tool)
{
parts.push(bootstrap);
}
if let Some(prepared) = prepare_pending_messages(db, instance_name) {
parts.push(prepared.formatted);
delivery_ack = Some(prepared.ack);
} else if opts.set_status_on_empty {
lifecycle::set_status(db, instance_name, ST_ACTIVE, "prompt", Default::default());
}
}
GeminiFamilyLifecycleOutput {
parts,
delivery_ack,
early_wake_context: None,
}
}
pub(crate) fn limit_delivery_messages(messages: &[Value]) -> Vec<Value> {
if messages.len() > MAX_MESSAGES_PER_DELIVERY {
messages[..MAX_MESSAGES_PER_DELIVERY].to_vec()
} else {
messages.to_vec()
}
}
pub(crate) fn format_messages_json_for_instance(
db: &HcomDb,
messages: &[Value],
instance_name: &str,
) -> String {
let get_instance_data = make_instance_lookup(db);
let hints = load_config_hints();
let get_config_hints = || hints.clone();
let tip_checker = make_tip_checker(db);
messages::format_messages_json(
messages,
instance_name,
&get_instance_data,
&get_config_hints,
Some(&tip_checker),
)
}
pub(crate) fn format_hook_messages_for_instance(
db: &HcomDb,
messages: &[Value],
instance_name: &str,
) -> String {
let get_instance_data = make_instance_lookup(db);
let hints = load_config_hints();
let get_config_hints = || hints.clone();
messages::format_hook_messages(
messages,
instance_name,
&get_instance_data,
&get_config_hints,
None,
)
}
/// Prepare pending messages for delivery without committing cursor advance.
///
/// Returns formatted text + ack token. Caller must call `commit_delivery_ack`
/// after the output is successfully written (e.g. stdout flush).
pub fn prepare_pending_messages(db: &HcomDb, instance_name: &str) -> Option<PreparedDelivery> {
let raw_messages = db.get_unread_messages(instance_name);
prepare_raw_messages(db, instance_name, raw_messages)
}
/// Commit a deferred delivery ack — advance cursor and set status.
pub fn commit_delivery_ack(db: &HcomDb, ack: &super::DeliveryAck) {
// Forward-only: a delayed ack must not rewind a newer concurrent delivery.
// Cursor and announcement move together so a partial ack can't re-announce.
if let Err(e) = db.ack_hook_delivery(&ack.instance_name, ack.last_event_id, ack.mark_announced)
{
crate::log::log_error("hooks", "commit_delivery_ack", &format!("{e}"));
}
lifecycle::set_status(
db,
&ack.instance_name,
ST_ACTIVE,
&ack.status_context,
lifecycle::StatusUpdate {
msg_ts: &ack.msg_ts,
..Default::default()
},
);
}
/// Prepare raw messages into a PreparedDelivery without committing cursor/status.
///
/// Cursor advance and status update are deferred to `commit_delivery_ack`.
fn prepare_raw_messages(
db: &HcomDb,
instance_name: &str,
raw_messages: Vec<Message>,
) -> Option<PreparedDelivery> {
if raw_messages.is_empty() {
return None;
}
let messages: Vec<Value> = raw_messages.iter().map(message_to_value).collect();
let deliver = limit_delivery_messages(&messages);
let formatted = format_messages_json_for_instance(db, &deliver, instance_name);
let sender = deliver
.first()
.and_then(|m| m.get("from").and_then(|v| v.as_str()))
.unwrap_or("unknown");
let sender_display = identity::get_display_name(db, sender);
let last_id = deliver
.last()
.and_then(|m| m.get("event_id").and_then(|v| v.as_i64()))
.unwrap_or(0);
let msg_ts = deliver
.last()
.and_then(|m| m.get("timestamp").and_then(|v| v.as_str()))
.unwrap_or("")
.to_string();
Some(PreparedDelivery {
messages: deliver,
formatted,
ack: super::DeliveryAck {
instance_name: instance_name.to_string(),
last_event_id: last_id,
status_context: format!("deliver:{}", sender_display),
msg_ts,
mark_announced: false,
},
})
}
/// Fetch unread messages, update cursor, set delivery status.
///
/// Returns (delivered_messages, formatted_json). Empty vec and None if no messages.
/// Callers that need additional formatting can use the returned messages vec.
///
pub fn deliver_pending_messages(db: &HcomDb, instance_name: &str) -> (Vec<Value>, Option<String>) {
let raw_messages = db.get_unread_messages(instance_name);
let Some(prepared) = prepare_raw_messages(db, instance_name, raw_messages) else {
return (vec![], None);
};
commit_delivery_ack(db, &prepared.ack);
(prepared.messages, Some(prepared.formatted))
}
/// Result of [`poll_messages`].
pub struct PollResult {
/// True if a message was delivered (Stop/SubagentStop should be blocked
/// so Claude sees `output` on its next turn instead of ending).
pub delivered: bool,
/// `{"decision":"block","reason":...}` when `delivered`, else `None`.
pub output: Option<Value>,
pub timed_out: bool,
/// Deferred cursor/status commit. Caller must call `commit_delivery_ack`
/// only after `output` has been successfully written to stdout — never
/// before, since Claude only reads `output` on exit 0 and a premature
/// commit would advance the cursor past a message Claude never saw.
pub ack: Option<super::DeliveryAck>,
}
/// Stop hook polling loop — NOT used by main PTY path.
///
/// Runs for: headless instances and subagent polling.
/// Main PTY path bypasses this (HCOM_PTY_MODE=1, PTY wrapper handles injection).
///
/// Uses select() on a TCP socket for efficient wake-on-message delivery.
/// Senders call `crate::notify::wake` (kind=`hook`) to wake the select().
///
/// Always exits 0: Claude ignores stdout JSON on exit 2 for Stop/SubagentStop
/// (stderr-only feedback), so a delivered message must go out as exit 0 +
/// `{"decision":"block"}` or Claude never sees it.
pub fn poll_messages(
db: &HcomDb,
instance_name: &str,
timeout_secs: u64,
is_background: bool,
) -> PollResult {
match poll_messages_inner(db, instance_name, timeout_secs, is_background) {
Ok(result) => result,
Err(e) => {
log::log_error(
"hooks",
"hook.error",
&format!("hook=poll_messages err={}", e),
);
PollResult {
delivered: false,
output: None,
timed_out: false,
ack: None,
}
}
}
}
fn poll_messages_inner(
db: &HcomDb,
instance_name: &str,
timeout_secs: u64,
is_background: bool,
) -> Result<PollResult> {
// Check instance exists
let instance_data = db
.get_instance_full(instance_name)
.context("DB error checking instance")?;
if instance_data.is_none() {
return Ok(PollResult {
delivered: false,
output: None,
timed_out: false,
ack: None,
});
}
// Setup TCP notification socket
let (notify_server, tcp_mode) = setup_tcp_notification(instance_name);
let notify_port = notify_server
.as_ref()
.and_then(|s| s.local_addr().ok())
.map(|a| a.port());
// Register TCP mode
let mut updates = serde_json::Map::new();
updates.insert("tcp_mode".into(), serde_json::json!(tcp_mode));
instances::update_instance_position(db, instance_name, &updates);
// Register hook notify endpoint
if let Some(port) = notify_port {
register_hook_notify_port(db, instance_name, port);
}
// Set listening status
lifecycle::set_status(db, instance_name, ST_LISTENING, "", Default::default());
let start = Instant::now();
let timeout = Duration::from_secs(timeout_secs);
let result = poll_loop(
db,
instance_name,
timeout,
start,
is_background,
notify_server.as_ref(),
);
// Cleanup: close socket, remove notify endpoint
drop(notify_server);
delete_hook_notify_endpoint(db, instance_name);
result
}
fn poll_loop(
db: &HcomDb,
instance_name: &str,
timeout: Duration,
start: Instant,
is_background: bool,
notify_server: Option<&TcpListener>,
) -> Result<PollResult> {
let empty = || PollResult {
delivered: false,
output: None,
timed_out: false,
ack: None,
};
let mut waited = false;
while start.elapsed() < timeout {
// Check if instance still exists (stopped = row deleted)
let instance_data = db.get_instance_full(instance_name)?;
if instance_data.is_none() {
return Ok(empty());
}
// Poll for messages BEFORE select to catch transition gap
let raw_messages = db.get_unread_messages(instance_name);
if !raw_messages.is_empty() {
// Orphan detection: don't deliver if parent died.
// Only check after we've waited at least once — on the first iteration stdin
// may legitimately be closed (e.g. subprocess invocation via `input=...`).
if waited && !is_background && check_stdin_closed() {
return Ok(empty());
}
if let Some(prepared) = prepare_raw_messages(db, instance_name, raw_messages) {
// Do NOT commit the ack here — the caller must only advance
// the cursor after `output` is actually flushed to stdout.
// Claude discards stdout JSON on exit 2, so this must be
// reported via exit 0 + decision:block for Claude to see it.
let output = serde_json::json!({
"decision": "block",
"reason": prepared.formatted,
});
return Ok(PollResult {
delivered: true,
output: Some(output),
timed_out: false,
ack: Some(prepared.ack),
});
}
}
// Calculate remaining time
let elapsed = start.elapsed();
if elapsed >= timeout {
break;
}
let remaining = timeout - elapsed;
// TCP select for notifications (or fallback poll). Relay imports
// (pull.rs) call `crate::notify::wake_all` after every batch, so the
// TCP wake fires as soon as remote events land — no separate relay
// polling needed.
let wait_time = if notify_server.is_some() {
remaining.min(Duration::from_secs(30))
} else {
remaining.min(Duration::from_millis(100))
};
if let Some(server) = notify_server {
// Block until a wake-up connection arrives instead of busy-looping
if crate::sys::net::wait_readable(server, wait_time) {
// Drain all pending connections
if let Err(e) = server.set_nonblocking(true) {
log::log_warn(
"hooks",
"poll.nonblocking_failed",
&format!("set_nonblocking failed: {e}, skipping drain"),
);
} else {
while let Ok((conn, _)) = server.accept() {
drop(conn);
}
}
}
} else {
std::thread::sleep(wait_time);
}
waited = true;
// Update heartbeat (also re-asserts tcp_mode=1 for self-healing)
let _ = db.update_heartbeat(instance_name);
}
// Timeout reached
Ok(PollResult {
delivered: false,
output: None,
timed_out: true,
ack: None,
})
}
/// Check if stdin is closed (orphan detection heuristic).
///
/// Piped stdin (normal for hook subprocess invocation) always gets POLLHUP
/// after the payload is consumed — this is NOT an orphan signal. Only check
/// POLLERR (broken pipe) and POLLNVAL (fd was closed/invalidated).
///
fn check_stdin_closed() -> bool {
crate::sys::io::stdin_appears_broken()
}
/// Create TCP server socket for instant message wake notifications.
fn setup_tcp_notification(instance_name: &str) -> (Option<TcpListener>, bool) {
match TcpListener::bind("127.0.0.1:0") {
Ok(listener) => {
listener.set_nonblocking(true).unwrap_or(());
(Some(listener), true)
}
Err(e) => {
log::log_error(
"hooks",
"hook.error",
&format!("hook=tcp_notification instance={} err={}", instance_name, e),
);
(None, false)
}
}
}
/// Register hook notify port in DB.
fn register_hook_notify_port(db: &HcomDb, instance_name: &str, port: u16) {
if let Err(e) = db.upsert_notify_endpoint(instance_name, "hook", port) {
log::log_warn(
"native",
"hooks.register_notify_fail",
&format!(
"Failed to register hook notify port for {}: {}",
instance_name, e
),
);
}
}
/// Remove hook notify endpoint from DB.
fn delete_hook_notify_endpoint(db: &HcomDb, instance_name: &str) {
let _ = db.conn().execute(
"DELETE FROM notify_endpoints WHERE instance = ? AND kind = 'hook'",
params![instance_name],
);
}
/// Inject bootstrap text if not already announced.
///
/// Idempotent — checks name_announced flag and only injects once
/// per instance lifecycle. Returns bootstrap text if injection needed,
/// None if already announced.
///
pub fn inject_bootstrap_once(
db: &HcomDb,
ctx: &HcomContext,
instance_name: &str,
instance_data: &InstanceRow,
tool: &str,
) -> Option<String> {
if instance_data.name_announced != 0 {
return None;
}
let bootstrap_text = bootstrap::get_bootstrap(db, ctx, instance_name, tool);
// Mark as announced
let mut updates = serde_json::Map::new();
updates.insert("name_announced".into(), serde_json::json!(true));
instances::update_instance_position(db, instance_name, &updates);
Some(bootstrap_text)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum TranscriptOwnerResolution {
Owner(String),
Ambiguous(Vec<String>),
Unknown,
}
/// Resolve Claude ownership from bounded, structured transcript/session evidence.
///
/// Only envelope metadata is inspected. Ordinary message content, summaries,
/// tool output, bootstrap text, and `[hcom:name]` markers are intentionally out
/// of scope for lineage resolution.
pub(crate) fn resolve_claude_transcript_owner(
db: &HcomDb,
transcript_path: &str,
incoming_session_id: Option<&str>,
) -> Result<TranscriptOwnerResolution> {
const MAX_BYTES: usize = 512 * 1024;
const MAX_RECORDS: usize = 2048;
let mut owners = BTreeSet::new();
let mut structured_session_ids = BTreeSet::new();
let incoming_is_validated = match incoming_session_id.filter(|value| !value.is_empty()) {
Some(session_id) => db.get_validated_claude_session_owner(session_id)?.is_some(),
None => false,
};
if incoming_is_validated && let Some(session_id) = incoming_session_id {
// A hook-provided incoming ID is only self-authenticating after a
// trusted SessionStart or prior structured-lineage validation.
structured_session_ids.insert(session_id.to_string());
}
if !transcript_path.is_empty() {
owners.extend(db.get_instances_by_transcript_path(transcript_path)?);
match std::fs::File::open(transcript_path) {
Ok(file) => {
// Head-biased by design: fork ancestry is copied into the first
// records, and SessionStart must never stall on a huge transcript.
let mut input = Vec::with_capacity(MAX_BYTES + 1);
file.take((MAX_BYTES + 1) as u64).read_to_end(&mut input)?;
let input_is_truncated = input.len() > MAX_BYTES;
input.truncate(MAX_BYTES);
for line in input
.split_inclusive(|byte| *byte == b'\n')
.take(MAX_RECORDS)
{
// The bounded read may end in the middle of a UTF-8 code
// point or JSON record. Ignore only that incomplete tail
// rather than failing after valid earlier rows.
if input_is_truncated && !line.ends_with(b"\n") {
break;
}
let Ok(line) = std::str::from_utf8(line) else {
continue;
};
let Ok(value) = serde_json::from_str::<Value>(line) else {
continue;
};
for session_id in [
value.get("sessionId").and_then(Value::as_str),
value.get("session_id").and_then(Value::as_str),
]
.into_iter()
.flatten()
.filter(|value| !value.is_empty())
{
// Claude rewrites top-level IDs to the new fork UUID.
// Until that incoming binding is validated, the same ID
// cannot prove its own ownership. Different top-level
// IDs remain useful structured ancestry evidence.
if incoming_session_id != Some(session_id) || incoming_is_validated {
structured_session_ids.insert(session_id.to_string());
}
}
if let Some(session_id) = value
.get("message")
.and_then(|message| message.get("session_id"))
.and_then(Value::as_str)
.filter(|value| !value.is_empty())
{
// Envelope message.session_id is independent structured
// provenance and may legitimately equal the current ID.
structured_session_ids.insert(session_id.to_string());
}
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
}
for session_id in structured_session_ids {
if let Some(owner) = db.get_session_binding(&session_id)? {
owners.insert(owner);
}
}
Ok(match owners.len() {
0 => TranscriptOwnerResolution::Unknown,
1 => TranscriptOwnerResolution::Owner(owners.into_iter().next().unwrap()),
_ => TranscriptOwnerResolution::Ambiguous(owners.into_iter().collect()),
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ClaudeIdentityEvidence {
pub process_binding: Option<(Option<String>, String)>,
pub process_session_id: Option<String>,
pub process_owner: Option<String>,
pub session_owner: Option<String>,
pub validated_session_owner: Option<String>,
pub owners_disagree: bool,
pub lineage_scanned: bool,
pub lineage: TranscriptOwnerResolution,
}
/// Load the identity facts shared by SessionStart and ordinary Claude hooks.
///
/// The caller supplies only the lineage-scan policy; owner selection remains
/// local to each resolution path.
pub(crate) fn load_claude_identity_evidence(
db: &HcomDb,
process_id: &str,
session_id: &str,
transcript_path: &str,
should_scan_lineage: impl FnOnce(&ClaudeIdentityEvidence) -> bool,
) -> Result<ClaudeIdentityEvidence> {
let process_binding = db.get_process_binding_full(process_id)?;
let process_session_id = process_binding
.as_ref()
.and_then(|(session_id, _)| session_id.clone());
let process_owner = process_binding
.as_ref()
.map(|(_, instance_name)| instance_name.clone());
let session_owner = if session_id.is_empty() {
None
} else {
db.get_session_binding(session_id)?
};
let validated_session_owner = if session_id.is_empty() {
None
} else {
db.get_validated_claude_session_owner(session_id)?
};
let owners_disagree = matches!(
(&process_owner, &session_owner),
(Some(process_owner), Some(session_owner)) if process_owner != session_owner
);
let mut evidence = ClaudeIdentityEvidence {
process_binding,
process_session_id,
process_owner,
session_owner,
validated_session_owner,
owners_disagree,
lineage_scanned: false,
lineage: TranscriptOwnerResolution::Unknown,
};
evidence.lineage_scanned = should_scan_lineage(&evidence);
if evidence.lineage_scanned {
evidence.lineage = resolve_claude_transcript_owner(
db,
transcript_path,
(!session_id.is_empty()).then_some(session_id),
)?;
}
Ok(evidence)
}
/// Initialize instance context from hook data via binding lookup.
///
/// Hooks only run in hcom-launched Claude processes, but one process can
/// switch sessions (`/resume`, `/clear`, `/branch`, `--fork-session`) while
/// its process binding still names the previous generation's owner. So
/// structured session/transcript identity wins over a conflicting process
/// binding. Transcript scanning stays off the common hot path: it runs only
/// when the session is unbound or its binding has not yet been validated.
///
/// Returns (instance_name, metadata_updates, is_matched_resume). A hook with
/// no hcom process id never resolves an identity.
pub fn init_hook_context(
db: &HcomDb,
ctx: &HcomContext,
session_id: &str,
transcript_path: &str,
) -> (Option<String>, serde_json::Map<String, Value>, bool) {
let Some(process_id) = ctx.process_id.as_deref() else {
return (None, serde_json::Map::new(), false);
};
let start = Instant::now();
let evidence = match load_claude_identity_evidence(
db,
process_id,
session_id,
transcript_path,
|evidence| {
let binding_needs_validation = evidence.session_owner.is_some()
&& evidence.validated_session_owner.as_ref() != evidence.session_owner.as_ref();
evidence.session_owner.is_none() || binding_needs_validation
},
) {
Ok(evidence) => evidence,
Err(error) => {
log::log_warn(
"hooks",
"init_hook_context.identity_evidence_error",
&format!(
"session_id={} transcript_path={} process_id={:?} err={}",
session_id, transcript_path, ctx.process_id, error
),
);
return (None, serde_json::Map::new(), false);
}
};
let evidence_ms = start.elapsed().as_secs_f64() * 1000.0;
let historical_process_binding = evidence
.process_session_id
.as_deref()
.filter(|bound_session_id| !bound_session_id.is_empty())
.is_some_and(|bound_session_id| bound_session_id != session_id);
let instance_name = if let Some(validated_owner) = evidence.validated_session_owner.clone() {
Some(validated_owner)
} else if evidence.lineage_scanned {
match &evidence.lineage {
TranscriptOwnerResolution::Owner(owner) => Some(owner.clone()),
TranscriptOwnerResolution::Ambiguous(owners) => {
log::log_warn(
"hooks",
"init_hook_context.identity_ambiguous",
&format!(
"session_id={} transcript_path={} process_id={:?} process_owner={:?} session_owner={:?} transcript_owners={:?}",
session_id,
transcript_path,
ctx.process_id,
evidence.process_owner,
evidence.session_owner,
owners,
),
);
None
}
TranscriptOwnerResolution::Unknown => {
if evidence.session_owner.is_some() {
log::log_warn(
"hooks",
"init_hook_context.unvalidated_session_rejected",
&format!(
"session_id={} transcript_path={} process_id={:?} process_owner={:?} session_owner={:?}",
session_id,
transcript_path,
ctx.process_id,
evidence.process_owner,
evidence.session_owner,
),
);
None
} else if historical_process_binding {
log::log_warn(
"hooks",
"init_hook_context.historical_process_rejected",
&format!(
"session_id={} transcript_path={} process_id={:?} process_session_id={:?} process_owner={:?}",
session_id,
transcript_path,
ctx.process_id,
evidence.process_session_id,
evidence.process_owner,
),
);
None
} else {
evidence.process_owner.clone()
}
}
}
} else {
evidence
.session_owner
.clone()
.or_else(|| evidence.process_owner.clone())
};
let Some(name) = instance_name else {
log::log_info(
"hooks",
"init_hook_context.timing",
&format!(
"evidence_ms={:.2} total_ms={:.2} result=no_instance owners_disagree={}",
evidence_ms,
start.elapsed().as_secs_f64() * 1000.0,
evidence.owners_disagree
),
);
return (None, serde_json::Map::new(), false);
};
let mut updates = serde_json::Map::new();
updates.insert(
"directory".into(),
Value::String(ctx.cwd.to_string_lossy().to_string()),
);
if !transcript_path.is_empty() {
updates.insert(