trusty-memory 0.28.0

MCP server (stdio + Unix socket) for trusty-memory
Documentation
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
//! Handler for `trusty-memory prompt-context`.
//!
//! Why: Claude Code's `UserPromptSubmit` hooks inject any stdout produced by
//! the hook command as additional context for the model. The trusty-memory
//! setup command installs a hook that runs `trusty-memory prompt-context`
//! before every prompt, so the model gets a freshly-rendered block of
//! palace context (drawer recall + KG triples + global hot facts) without
//! paying the per-message MCP tool-call tax. This handler is the actual
//! command the hook invokes.
//!
//! What: a side-effect-only command that talks to the running trusty-memory
//! HTTP daemon and prints a formatted Markdown injection block to stdout.
//! Composition (issue #134):
//!
//!   1. Workspace hot facts (existing `GET /api/v1/kg/prompt-context`).
//!   2. Drawers recalled from the cwd-resolved palace
//!      (`GET /api/v1/palaces/{slug}/recall?q=<prompt>`).
//!   3. Knowledge-graph triples whose subject appears in the prompt
//!      (`GET /api/v1/palaces/{slug}/kg/all?limit=200`).
//!
//! Failures on any branch are isolated — each fetch is bounded by
//! `CALL_TIMEOUT` and individual errors are skipped without failing the
//! hook. When every section is empty the command prints **nothing** (#5819):
//! this runs on every prompt of every session, so an injection that has no
//! content to carry must cost no tokens to say so.
//!
//! Note on MPM sub-agents: unlike `trusty-mpm hook`, this command is
//! **intentionally NOT** gated on the `CLAUDE_MPM_SUB_AGENT` environment
//! variable. Sub-agents benefit from the parent palace's prompt-fact block
//! just as much as the PM does — withholding it would force every nested
//! agent to rediscover project conventions from scratch. The token cost is
//! a single rendered fact list and the signal payoff (consistent style,
//! vocabulary, and architectural facts across the agent tree) is high. The
//! suppression of nested hook traffic happens at the `trusty-mpm hook`
//! layer instead, where doubled audit events are the real failure mode.
//!
//! Test: daemon-touching paths are exercised via integration tests in this
//! module (`prompt_context_recalls_palace_drawers`,
//! `prompt_context_empty_palace_falls_back_to_global`,
//! `prompt_context_returns_ok_without_daemon`).

mod fetch;
mod filter;
// #4891: `backfill_report` must render a drawer's preview byte-for-byte as the
// injection does, or its log join silently under-counts. Sharing the one
// implementation is what makes that guarantee hold.
pub(crate) mod format;
mod query;

use anyhow::Result;
use serde_json::Value;
use std::time::{Duration, Instant};

use crate::hook_emit::{post_hook_event, HookEventPayload};
use crate::prompt_log::{PromptLogEntry, PromptLogger, RecallQueryShape};
use crate::{hook_prompt_excerpt, HookType, InjectionKind};

use fetch::{fetch_global_prompt_context, fetch_palace_kg_triples, fetch_palace_recall};
use filter::{
    filter_drawers_by_deny_tags, filter_drawers_by_project_scope,
    filter_drawers_by_relevance_floor, select_relevant_triples,
};
use format::{compose_injection, count_facts};
use query::{configured_query_budget, shape_recall_query, warn_if_reshaped};
use trusty_common::memory_core::retrieval::DEFAULT_RELEVANCE_FLOOR;

pub use query::ENV_QUERY_TOKEN_BUDGET;

/// Connect + total request timeout. Kept short so a slow/dead daemon can
/// never block a Claude Code prompt for more than a couple seconds.
pub(super) const CALL_TIMEOUT: Duration = Duration::from_millis(2500);

/// Deadline for reading the `UserPromptSubmit` stdin payload (issue #2043).
///
/// Why: `read_stdin_best_effort` used to be an untimed blocking read —
/// proven under a slow FIFO writer to block the whole process for as long
/// as the writer took (measured: a 4 s-delayed writer blocked the process
/// 4.1 s). Under host contention (many concurrent hook subprocesses from
/// sibling sub-agents) that read can eat the entire Claude Code hook
/// budget before a single HTTP call is even attempted. 300 ms is generous
/// for Claude Code's actual stdin write (a small JSON blob written and
/// closed immediately) and short enough that a stalled/adversarial writer
/// can never meaningfully delay the prompt.
/// What: the timeout passed to [`bounded_blocking`] wrapping the
/// `spawn_blocking` stdin read in [`read_stdin_bounded`].
/// Test: `bounded_blocking_times_out_on_slow_closure` exercises the
/// underlying deadline mechanism directly; manual FIFO-writer verification
/// is documented in the #2043 PR description.
const STDIN_READ_DEADLINE: Duration = Duration::from_millis(300);

/// Deadline for the fetch + compose phase of [`build_injection_body`]
/// (issue #2043).
///
/// Why: Claude Code's own hook ceiling is far lower than the `"timeout":
/// 60` configured in `settings.json` implies (observed timeouts around
/// 15 s) and prior to this budget the handler had no upper bound of its
/// own beyond the sum of individual HTTP timeouts — the global fetch was
/// awaited sequentially before the per-palace `tokio::join!`, so a
/// degraded (not dead — dead fails fast) daemon could burn close to
/// 2× [`CALL_TIMEOUT`] before compose even started. This deadline is the
/// hard backstop: if fetching + composing is not done in time, the hook
/// fails open with whatever body it has (empty, if nothing finished).
/// What: passed to [`tokio::time::timeout`] around `build_injection_body`
/// in [`handle_prompt_context`].
/// Test: `handle_prompt_context_fails_open_on_slow_daemon`.
const BODY_DEADLINE: Duration = Duration::from_millis(1500);

/// Deadline for the best-effort `HookFired` activity POST (issue #2043).
///
/// Why: `emit_hook_event` is pure telemetry — the activity feed being
/// empty for one prompt is a cosmetic problem, while losing an already-
/// composed injection body would be a real regression. It therefore gets
/// its own short, separate deadline *after* the body has been printed
/// rather than being folded into [`BODY_DEADLINE`], so a hung daemon on
/// the telemetry POST can never cost us content that already rendered
/// successfully. Combined with [`STDIN_READ_DEADLINE`] and
/// [`BODY_DEADLINE`], the worst-case total wall time for the whole
/// command is bounded at ~300 ms + 1.5 s + 300 ms = 2.1 s — well under
/// Claude Code's real hook ceiling.
/// What: passed to [`tokio::time::timeout`] around `emit_hook_event`.
/// Test: covered indirectly — `emit_hook_event`'s own no-daemon path is
/// exercised by `dispatch_hook_fired_emits_activity`.
const EMIT_DEADLINE: Duration = Duration::from_millis(300);

/// Default top-K for drawer recall and KG triple selection.
///
/// Why (#5037): 5 was a hard limit on how much a *good* recall could return,
/// chosen when nothing distinguished a good recall from a bad one — every
/// query returned 5 entries whether or not any of them matched, so a bigger K
/// only meant more noise. The relevance floor removes that coupling: above the
/// floor, extra slots can only fill with candidates that actually cleared it,
/// and below it they stay empty. Measured over 80 real logged hook prompts
/// against the live palace, K=12 with the floor active renders a drawer section
/// of at most ~2.7 KB, which fits [`INJECTION_BYTE_CAP`] alongside hot facts
/// and KG triples.
/// What: a `usize` constant used unless the env override below is set.
/// Test: `prompt_context_recalls_palace_drawers` uses the default.
pub(super) const DEFAULT_TOP_K: usize = 12;

/// Upper bound on the operator-supplied [`ENV_TOP_K`] override.
///
/// Why: the ceiling exists so a mistyped override cannot blow the byte budget.
/// It has to stay above [`DEFAULT_TOP_K`] to remain an escape hatch at all.
/// What: `30`, raised from 20 alongside the default (#5037).
/// Test: `configured_top_k_clamps_to_bounds`.
pub(super) const MAX_TOP_K: usize = 30;

// A ceiling at or below the default would silently cap every operator override,
// which is the escape hatch dead. Enforced at compile time so the two constants
// cannot drift apart in a later edit.
const _: () = assert!(MAX_TOP_K > DEFAULT_TOP_K);

/// Hard byte cap on the rendered injection.
///
/// Why: hook-injection budgets in Claude Code are small and every byte we emit
/// is a token the model has to spend reading. #5037 raised this from 4 KB
/// because the relevance floor changed what fills it: the cap now bounds
/// *above-floor* content rather than a fixed-size mixture of hits and noise, so
/// the same ceiling was costing real matches to hold room for candidates that
/// no longer get rendered.
/// What: `8 * 1024` bytes. Sections are appended until the cap is hit;
/// truncation emits an explicit `…` marker so downstream readers know
/// the block was cut.
/// Test: `compose_injection_truncates_at_cap`;
/// `prompt_context_recalls_palace_drawers` exercises the budget implicitly by
/// asserting a real (non-placeholder) injection.
pub(super) const INJECTION_BYTE_CAP: usize = 8 * 1024;

/// Per-drawer-content preview cap inside the injection.
///
/// Why: dumping the full drawer body would burn the byte budget on a
/// single entry; a short single-line preview is enough to remind the model
/// what's available and lets it pull more via MCP recall if needed.
/// What: `220` characters of the whitespace-collapsed content.
/// Test: indirectly via `prompt_context_recalls_palace_drawers`.
pub(super) const DRAWER_PREVIEW_CHARS: usize = 220;

/// Env override for the top-K used by both recall and KG walks.
///
/// Why: gives operators an emergency knob without re-deploying. Optional
/// — when unset / unparseable / zero, [`DEFAULT_TOP_K`] is used.
/// What: a string env var parsed as a `usize`; clamped to `[1, MAX_TOP_K]` to
/// keep the byte budget meaningful.
/// Test: `configured_top_k_clamps_to_bounds` covers the clamp arithmetic.
pub const ENV_TOP_K: &str = "TRUSTY_MEMORY_PROMPT_TOP_K";

/// Env override for the relevance floor applied to recalled drawers.
///
/// Why (issue #5037): the ticket asks for a *configurable* minimum, because the
/// right threshold depends on the embedder and on how a given palace is
/// written, and neither is knowable from here. Setting it to `0` disables the
/// gate and restores the pre-#5037 behaviour exactly, which is the escape hatch
/// an operator needs if the default over-cuts on their corpus.
/// What: a string env var parsed as an `f32` and clamped to `[0.0, 1.0]`; when
/// unset or unparseable, `trusty_common`'s `DEFAULT_RELEVANCE_FLOOR` is used.
/// Test: `configured_relevance_floor_clamps_to_bounds`.
pub const ENV_MIN_SCORE: &str = "TRUSTY_MEMORY_PROMPT_MIN_SCORE";

/// Env override for the deny-listed drawer tags filtered out of recall.
///
/// Why (issue #139): operators need a way to widen or narrow the noise
/// filter without a rebuild — e.g. add project-specific synthetic tags
/// that have polluted a palace from an upstream hook source. Optional —
/// when unset, the recall path uses [`DEFAULT_DENY_TAGS`].
/// What: a comma-separated list of tag strings. Whitespace around each
/// entry is trimmed; empty entries are ignored; matching is case-
/// insensitive against the drawer's tag list.
/// Test: `prompt_context_recall_env_override_extends_deny_list` exercises
/// the env-driven path with a synthetic noise tag.
pub const ENV_RECALL_DENY_TAGS: &str = "TRUSTY_MEMORY_PROMPT_RECALL_DENY_TAGS";

/// Default deny list applied to recalled drawer tags before composition.
///
/// Why (issue #139): live evidence in the user's palace showed that the
/// auto-capture hook (`trusty-memory hooks fire claude.user-prompt`,
/// wired by `trusty-mpm-core::session_launch`) persists every user prompt
/// as a drawer tagged `claude-session` + `user-prompt`. These drawers
/// dominate recall and crowd out signal content — three sample sessions
/// returned the literal token "yes" five times across semantically
/// distinct prompts. Filtering by tag is cheap, safe (empty tag lists
/// pass through unchanged), and reversible via [`ENV_RECALL_DENY_TAGS`].
/// What: a `&[&str]` of tag names. A drawer is filtered when ANY of its
/// tags matches (case-insensitive) ANY entry in this list.
/// Test: `prompt_context_recall_filters_deny_tags` covers the default
/// path; `prompt_context_recall_all_filtered_falls_back_to_global` covers
/// the all-filtered fallback.
const DEFAULT_DENY_TAGS: &[&str] = &["claude-session", "user-prompt"];

/// Placeholder body emitted when no daemon is reachable or every fetch
/// returned nothing useful.
///
/// Why: kept verbatim from the pre-#134 behaviour so the empty-palace
/// case is byte-identical for downstream tooling. The non-empty palace
/// path now overrides it with real content.
/// What: a static string.
/// Test: `prompt_context_empty_palace_falls_back_to_global`.
pub(super) const EMPTY_PLACEHOLDER: &str = "No prompt facts stored yet.";

/// Entry point for `trusty-memory prompt-context`.
///
/// Why: every error path in this handler must result in a clean exit 0 — the
/// `UserPromptSubmit` hook is wired into every Claude Code prompt the user
/// types, so any non-zero exit (or panic) would either block the prompt or
/// inject a confusing error into the model's context. Logging to stderr is
/// fine because Claude Code only ingests stdout from hook commands.
/// What:
///   1. Read stdin (the UserPromptSubmit JSON payload) — extract `cwd` and
///      `prompt`.
///   2. Resolve the palace slug from the stdin `cwd` (fall back to process
///      cwd).
///   3. Fetch the global prompt-context block + per-palace recall + per-
///      palace KG triples (each best-effort, bounded by [`CALL_TIMEOUT`]).
///   4. Compose a single Markdown injection capped at
///      [`INJECTION_BYTE_CAP`] bytes and print it.
///   5. Log a [`PromptLogEntry`] for the hook event (failure-isolated).
///
/// Sub-agent behaviour: deliberately unguarded. MPM-spawned sub-agents inject
/// the same prompt-context block as the PM because the marginal token cost
/// is small and the convention/style signal is high — see the module-level
/// note for the full rationale.
///
/// Deadline behaviour (issue #2043): every blocking or network-bound step
/// is individually bounded — stdin read ([`STDIN_READ_DEADLINE`]), fetch +
/// compose ([`BODY_DEADLINE`]), and activity emit ([`EMIT_DEADLINE`]) — so
/// the command can never hang regardless of host contention or daemon
/// health. A deadline miss always fails open (empty stdin, empty body, or
/// a skipped activity event) rather than propagating an error, preserving
/// the "never block the user's prompt" contract.
/// Test: `prompt_context_returns_ok_without_daemon` covers the no-daemon
/// branch; live-daemon paths are exercised by
/// `prompt_context_recalls_palace_drawers` and
/// `prompt_context_empty_palace_falls_back_to_global`;
/// `bounded_blocking_times_out_on_slow_closure` and
/// `handle_prompt_context_fails_open_on_slow_daemon` cover the deadline
/// fail-open paths added by #2043. This wrapper itself is intentionally
/// NOT unit-tested (see [`handle_prompt_context_with_payload`]) — it would
/// require a real blocking stdin read inside a `#[tokio::test]`, which is
/// exactly the orphaned-thread hang fixed by issue #2079.
pub async fn handle_prompt_context() -> Result<()> {
    let trigger_payload = read_stdin_bounded().await;
    handle_prompt_context_with_payload(trigger_payload).await
}

/// Core body of [`handle_prompt_context`], parameterised over the stdin
/// payload (issue #2079).
///
/// Why: #2048 bounded the stdin read with `spawn_blocking` + a timeout, but
/// a blocking OS thread can't be cancelled — on timeout it keeps running,
/// parked in the real `read_to_string` syscall, until stdin actually closes.
/// In production that's harmless (`run_prompt_context_and_exit` calls
/// `std::process::exit(0)` right after, abandoning the thread). But the
/// `#[tokio::test]` functions that used to call `handle_prompt_context()`
/// directly returned normally, so their per-test `Runtime::drop()` waited
/// for that orphaned thread — which never finished when the test binary's
/// own stdin was a held-open, non-EOF pipe (exactly the shape of GitHub
/// Actions' runner stdin), wedging `cargo test --workspace` forever.
/// Splitting the payload out means the tested logic never spawns a real
/// stdin read, so it can never hang regardless of the test process's stdin.
/// What: takes the already-resolved stdin payload, builds the injection
/// body (bounded by [`BODY_DEADLINE`]), prints it, and best-effort emits
/// the `HookFired` activity event (bounded by [`EMIT_DEADLINE`]). Identical
/// behaviour to the pre-#2079 `handle_prompt_context` body.
/// Test: `prompt_context_returns_ok_without_daemon`,
/// `prompt_context_logs_attempt_without_daemon`,
/// `handle_prompt_context_fails_open_on_slow_daemon` — all call this
/// directly with a fixed in-memory payload instead of
/// `handle_prompt_context()`.
pub(crate) async fn handle_prompt_context_with_payload(trigger_payload: String) -> Result<()> {
    let start = Instant::now();

    // Fetch + compose, hard-capped at BODY_DEADLINE. On timeout there is
    // nothing safe to print yet, so fail open to an empty body — identical
    // in effect to the existing "no daemon reachable" branch.
    let body = tokio::time::timeout(BODY_DEADLINE, build_injection_body(&trigger_payload))
        .await
        .unwrap_or_default();

    if !body.is_empty() {
        if body.ends_with('\n') {
            print!("{body}");
        } else {
            println!("{body}");
        }
    }

    // Submission-logging Part A: emit a `HookFired` activity event so the
    // dashboard / TUI feed shows this prompt-context invocation. Best-effort
    // in two senses: failures are swallowed inside `post_hook_event`, and the
    // whole call is separately deadline-bounded so a hung POST can never
    // consume the budget we already spent producing `body` above.
    let _ = tokio::time::timeout(
        EMIT_DEADLINE,
        emit_hook_event(&trigger_payload, &body, start),
    )
    .await;

    Ok(())
}

/// POST a `HookFired` event to the daemon's activity ingestion endpoint.
///
/// Why: surfaces every prompt-context hook firing in the activity feed
/// (issue: TUI activity feed was empty in sessions whose only daemon
/// traffic was hooks).
/// What: builds a `HookEventPayload` carrying the resolved palace, the
/// rendered injection length, a short excerpt of the user prompt, and
/// the hook's elapsed wall-clock duration, then calls `post_hook_event`.
/// Test: `dispatch_hook_fired_emits_activity` in this module.
async fn emit_hook_event(trigger_payload: &str, injection: &str, start: Instant) {
    let user_prompt = parse_user_prompt(trigger_payload);
    let palace_id = resolve_palace_slug(trigger_payload);
    let payload = HookEventPayload {
        palace_id: palace_id.clone(),
        palace_name: palace_id,
        hook_type: HookType::UserPromptSubmit,
        injection_kind: InjectionKind::PromptContext,
        injection_length: injection.len() as u64,
        trigger_prompt_excerpt: hook_prompt_excerpt(&user_prompt),
        duration_ms: start.elapsed().as_millis() as u64,
    };
    post_hook_event(payload).await;
}

/// Run [`handle_prompt_context`] then terminate the process immediately.
///
/// Why (issue #2043): every blocking step in `handle_prompt_context` is
/// bounded by [`bounded_blocking`] (`spawn_blocking` + `tokio::time::timeout`),
/// but a timeout only stops the *caller* from awaiting the blocking thread
/// — it cannot cancel the thread itself (blocking OS threads aren't
/// preemptible). If the stdin data a slow/adversarial writer eventually
/// sends never arrives, that thread stays parked in a blocking read
/// syscall indefinitely. Returning normally from `main` would let
/// `#[tokio::main]` drop its `Runtime`, and `Runtime::drop` waits for
/// exactly that kind of outstanding blocking-pool thread before the
/// process can exit — silently reintroducing the original hang this issue
/// fixes, just moved from "awaiting the future" to "process teardown".
/// `std::process::exit` terminates the whole process immediately without
/// running that wait, so a stalled reader thread is simply abandoned (the
/// OS reclaims it) instead of blocking the user's prompt.
/// What: awaits `handle_prompt_context()` for its side effects (stdout
/// print + best-effort logging/activity-emit), flushes stdout defensively
/// (it already line-buffers, so this makes the ordering an explicit
/// guarantee rather than an implicit one), then calls
/// `std::process::exit(0)` — matching the documented "always exit 0"
/// contract, since every internal path already degrades to `Ok(())`.
/// Never actually returns, hence `-> !`.
/// Test: not unit-tested directly — `process::exit` would terminate the
/// test binary. The underlying deadline mechanism it depends on is
/// covered by `bounded_blocking_times_out_on_slow_closure` and
/// `handle_prompt_context_fails_open_on_slow_daemon`; the fail-open
/// contract of the awaited call is covered by
/// `prompt_context_returns_ok_without_daemon`. Manual verification (a
/// slow-writer pipe returning promptly instead of blocking for the
/// writer's full delay) is documented in the #2043 PR description.
pub async fn run_prompt_context_and_exit() -> ! {
    let _ = handle_prompt_context().await;
    use std::io::Write as _;
    let _ = std::io::stdout().flush();
    std::process::exit(0);
}

/// Build the prompt-context injection body for a given stdin payload.
///
/// Why: factored out of [`handle_prompt_context`] so integration tests can
/// drive the full enrichment pipeline against a real HTTP daemon without
/// trampling the process' stdout. Production code wraps this with
/// [`handle_prompt_context`] which prints the result and returns `Ok(())`.
/// What: same flow as the original — resolve daemon → resolve palace →
/// fetch global facts + recall + KG → compose injection → log. Returns
/// the rendered body verbatim. Never panics; every failure path degrades
/// to the legacy placeholder or an empty string.
/// Test: `prompt_context_recalls_palace_drawers`,
/// `prompt_context_empty_palace_falls_back_to_global`.
pub(crate) async fn build_injection_body(trigger_payload: &str) -> String {
    let start = Instant::now();
    let user_prompt = parse_user_prompt(trigger_payload);

    // 1. Resolve the daemon's socket. #6286 removed the `http_addr` discovery
    //    file this used to read: the path is DERIVED, so an unresolvable data
    //    directory is the only way this fails, and it means the same thing the
    //    missing file did — nothing to call. Return empty so the caller exits
    //    silently with no stdout output.
    let socket = match crate::transport::uds::socket_path() {
        Ok(socket) => socket,
        Err(_) => {
            log_entry(trigger_payload, "", 0, start, None);
            return String::new();
        }
    };

    // 3. Resolve the palace slug from the stdin `cwd` first, then fall back
    //    to the process cwd. Both lookups are wrapped in `ok()` so failure
    //    just yields `None` (we'll skip palace-specific sections).
    let palace_slug = resolve_palace_slug(trigger_payload);
    // #5819: resolved once per firing, not per drawer — the walk touches the
    // filesystem and the answer is the same for every candidate.
    let session_root = resolve_session_project_root(trigger_payload);

    // 4. Fan out the fetches. Each is best-effort; failures are skipped.
    //
    // Issue #2043: all three calls race concurrently via a single
    // `tokio::join!` instead of awaiting the global fetch sequentially
    // before starting the palace-scoped pair. The prior sequential shape
    // could cost up to ~2× CALL_TIMEOUT worst-case (global, then the
    // slower of drawers/kg); joining all three caps the fetch phase at
    // ~1× CALL_TIMEOUT regardless of palace_slug. Each call opens its own
    // connection, which is what makes the join real — the socket server
    // spawns a task per connection.
    let global_fut = fetch_global_prompt_context(&socket, CALL_TIMEOUT);
    let mut query_shape: Option<RecallQueryShape> = None;
    let (global_facts, drawers, withheld, kg_triples) = match &palace_slug {
        Some(slug) => {
            let top_k = configured_top_k();
            // #4972: `user_prompt` is still parsed whole (#5037 requirement 3 —
            // `hook_prompt_excerpt` is telemetry and must never be the query),
            // but it is no longer handed to the embedder raw. Past the 512-token
            // window the embedder cut it mid-word and said nothing; shaping
            // strips the notification envelope and, if still over, keeps whole
            // units and reports the reduction.
            let shaped = shape_recall_query(&user_prompt, configured_query_budget());
            warn_if_reshaped(&shaped.shape);
            query_shape = Some(shaped.shape);
            let drawers_fut = fetch_palace_recall(&socket, CALL_TIMEOUT, slug, &shaped.text, top_k);
            let kg_fut = fetch_palace_kg_triples(&socket, CALL_TIMEOUT, slug);
            let (global_facts, drawers, kg_all) = tokio::join!(global_fut, drawers_fut, kg_fut);
            // Issue #139: drop low-signal drawers (e.g. `claude-session` /
            // `user-prompt` auto-captures) before composition. When this
            // filter empties the recall set, `compose_injection` falls
            // back to global hot facts via the existing branch below.
            let deny_tags = configured_deny_tags();
            let drawers = filter_drawers_by_deny_tags(drawers, &deny_tags);
            // #5819: a second provenance gate — drop drawers written while
            // working on a different repository. Runs before the floor for the
            // same reason the deny filter does.
            let scope = filter_drawers_by_project_scope(drawers, session_root.as_deref());
            // #5819: the count is the alarm. Two fail-closed defects shipped
            // through this filter unobserved because it dropped silently.
            tracing::debug!(
                session_root = session_root.as_deref().unwrap_or("<unresolved>"),
                kept = scope.kept.len(),
                dropped = scope.dropped,
                "prompt-context project-scope filter"
            );
            let drawers = scope.kept;
            // #5037: the deny filter judges provenance; this one judges
            // relevance. It runs last so a drawer excluded for where it came
            // from is never also counted as "withheld below the floor" — the
            // notice would then promise `memory_recall` results the provenance
            // gates also suppress.
            let floor = filter_drawers_by_relevance_floor(drawers, configured_relevance_floor());
            // #4972: the KG selector matches literal words, not vectors — it has
            // no token window, so it keeps the whole prompt. Shaping is a fix
            // for the embedder, not a general narrowing of what we look at.
            let kg_filtered = select_relevant_triples(&kg_all, &user_prompt, top_k);
            (global_facts, floor.kept, floor.withheld, kg_filtered)
        }
        None => (global_fut.await, Vec::new(), 0, Vec::new()),
    };

    // 5. Compose the injection. An empty composition stays empty — #5819
    //    replaced the `EMPTY_PLACEHOLDER` fallback, which spent 27 bytes per
    //    firing announcing that there was nothing to inject. The constant
    //    survives because `fetch_global_prompt_context` still recognises it as
    //    the daemon's own empty-body response.
    let body = compose_injection(
        global_facts.as_deref(),
        &drawers,
        withheld,
        &kg_triples,
        palace_slug.as_deref(),
    );

    // Best-effort log entry — `count_facts` approximates the number of
    // bulleted facts in the rendered Markdown block. Errors are swallowed
    // inside the logger.
    let facts_count = count_facts(&body);
    log_entry(trigger_payload, &body, facts_count, start, query_shape);

    body
}

/// Read the hook's stdin into a string, capped at 64 KiB, with a bounded
/// deadline (issue #2043).
///
/// Why (issue #105, hardened by #2043): the UserPromptSubmit hook delivers
/// the user prompt as stdin so we capture it for the enriched-prompt log.
/// The underlying read is a synchronous, unbounded
/// `Read::read_to_string` — proven to block the whole process for as long
/// as the writer takes to finish (measured: a FIFO writer delayed 4 s
/// blocked the process 4.1 s). Under host contention from concurrent
/// sub-agent hook subprocesses, that unbounded read could consume the
/// entire Claude Code hook budget before a single HTTP call is attempted.
/// What: runs [`read_stdin_best_effort`] through [`bounded_blocking`],
/// bounded by [`STDIN_READ_DEADLINE`]. On timeout (or a join error)
/// degrades to an empty string immediately; the abandoned blocking thread
/// is left to finish reading in the background and its result is simply
/// dropped — it never blocks the caller.
/// Test: `bounded_blocking_times_out_on_slow_closure` and
/// `bounded_blocking_returns_value_when_fast_enough` cover the underlying
/// deadline mechanism directly (a real `std::io::Stdin` can't be swapped
/// in-process, so the mechanism is tested via a synthetic slow closure
/// rather than a synthetic stdin).
async fn read_stdin_bounded() -> String {
    bounded_blocking(read_stdin_best_effort, STDIN_READ_DEADLINE)
        .await
        .unwrap_or_default()
}

/// Run a blocking closure on a dedicated thread, bounded by `deadline`
/// (issue #2043).
///
/// Why: several hot-path steps in this handler are synchronous and
/// potentially unbounded (currently just the stdin read); the pattern
/// "spawn on a blocking thread, race it against a deadline, fail open on
/// timeout" is the same each time and worth a single, independently
/// testable helper rather than re-deriving it per call site.
/// What: spawns `f` via `tokio::task::spawn_blocking`, races it against
/// `deadline` with `tokio::time::timeout`. Returns `Some(value)` when `f`
/// completes in time, `None` on timeout or a join error (e.g. `f`
/// panicked). On timeout the spawned thread is *not* cancelled — blocking
/// threads cannot be preempted — so it keeps running in the background and
/// its eventual result is simply dropped; this never delays the caller.
/// Test: `bounded_blocking_times_out_on_slow_closure`,
/// `bounded_blocking_returns_value_when_fast_enough`.
async fn bounded_blocking<F, T>(f: F, deadline: Duration) -> Option<T>
where
    F: FnOnce() -> T + Send + 'static,
    T: Send + 'static,
{
    match tokio::time::timeout(deadline, tokio::task::spawn_blocking(f)).await {
        Ok(Ok(value)) => Some(value),
        Ok(Err(_)) | Err(_) => None,
    }
}

/// Read the hook's stdin into a string, capped at 64 KiB.
///
/// Why (issue #105): the UserPromptSubmit hook delivers the user prompt as
/// stdin so we capture it for the enriched-prompt log. Stdin may be empty
/// (e.g. when the daemon is probed manually). The cap defends against an
/// adversarial prompt the size of a novel from inflating the log file. This
/// function is itself still a blocking, unbounded read — [`read_stdin_bounded`]
/// is the deadline-aware entry point every caller should use; this is kept
/// as a plain sync fn so it can run on a `spawn_blocking` thread.
/// What: synchronously reads stdin to EOF (or 64 KiB), returns the trimmed
/// payload. Failures degrade to an empty string — the hook continues either
/// way.
/// Test: not unit-tested directly (process stdin is hard to mock);
/// `read_stdin_bounded` and its wrapping deadline are covered by
/// `prompt_context_stdin_read_bounded_by_deadline`.
fn read_stdin_best_effort() -> String {
    use std::io::Read;
    const STDIN_CAP_BYTES: usize = 64 * 1024;
    // `is_terminal()` lets us bail when stdin is the controlling TTY — there
    // is no prompt to read in that case and `read_to_string` would block.
    let stdin = std::io::stdin();
    if std::io::IsTerminal::is_terminal(&stdin) {
        return String::new();
    }
    let mut buf = String::new();
    let _ = stdin
        .lock()
        .take(STDIN_CAP_BYTES as u64)
        .read_to_string(&mut buf);
    buf
}

/// Extract the user prompt string from the stdin JSON payload.
///
/// Why (issue #134): the recall query against the palace's vectors needs
/// the actual prompt text the user typed. Claude Code's UserPromptSubmit
/// hook payload carries `"prompt": "..."`; without it we'd have to recall
/// against an empty string and return generic results.
/// What: best-effort `serde_json` parse — on success and when the JSON has
/// a string `prompt` field, returns it trimmed. On any failure (non-JSON,
/// missing field) returns the raw stdin payload trimmed, so a manually-
/// piped prompt still drives recall.
/// Test: `parse_user_prompt_prefers_prompt_field`.
fn parse_user_prompt(stdin_payload: &str) -> String {
    if stdin_payload.trim().is_empty() {
        return String::new();
    }
    if let Ok(value) = serde_json::from_str::<Value>(stdin_payload) {
        if let Some(p) = value.get("prompt").and_then(|v| v.as_str()) {
            return p.trim().to_string();
        }
    }
    stdin_payload.trim().to_string()
}

/// Read the optional [`ENV_TOP_K`] env var, clamped to a sane range.
///
/// Why: operator escape hatch with a strict ceiling so accidental large
/// values can't blow the byte budget.
/// What: reads the env var and hands the raw string to [`clamp_top_k`], which
/// owns the parse and the clamp so both are testable without env mutation.
/// Test: `configured_top_k_clamps_to_bounds` covers [`clamp_top_k`]; the
/// default path is covered by `prompt_context_recalls_palace_drawers`.
fn configured_top_k() -> usize {
    clamp_top_k(std::env::var(ENV_TOP_K).ok().as_deref())
}

/// Parse and clamp a raw [`ENV_TOP_K`] value.
///
/// Why: split from [`configured_top_k`] so the arithmetic can be asserted
/// directly — env mutation across parallel tests is hostile.
/// What: parses `raw` as a `usize` and clamps to `[1, MAX_TOP_K]`. `None`,
/// unparseable, and zero all fall back to [`DEFAULT_TOP_K`].
/// Test: `configured_top_k_clamps_to_bounds`.
fn clamp_top_k(raw: Option<&str>) -> usize {
    raw.and_then(|v| v.trim().parse::<usize>().ok())
        .filter(|k| *k > 0)
        .map(|k| k.clamp(1, MAX_TOP_K))
        .unwrap_or(DEFAULT_TOP_K)
}

/// Read the optional [`ENV_MIN_SCORE`] env var, clamped to `[0.0, 1.0]`.
///
/// Why (issue #5037): see [`ENV_MIN_SCORE`] — the floor has to be tunable per
/// corpus, and settable to `0` to turn the gate off entirely.
/// What: reads the env var and hands the raw string to [`clamp_floor`].
/// Test: `configured_relevance_floor_clamps_to_bounds` covers [`clamp_floor`].
fn configured_relevance_floor() -> f32 {
    clamp_floor(std::env::var(ENV_MIN_SCORE).ok().as_deref())
}

/// Parse and clamp a raw [`ENV_MIN_SCORE`] value.
///
/// Why: same split as [`clamp_top_k`] — assertable without touching the
/// process environment.
/// What: parses `raw` as an `f32` and clamps to `[0.0, 1.0]`. `None`,
/// unparseable, and NaN fall back to `DEFAULT_RELEVANCE_FLOOR`. A parsed `0.0`
/// is honoured, disabling the gate.
/// Test: `configured_relevance_floor_clamps_to_bounds`.
fn clamp_floor(raw: Option<&str>) -> f32 {
    raw.and_then(|v| v.trim().parse::<f32>().ok())
        .filter(|f| !f.is_nan())
        .map(|f| f.clamp(0.0, 1.0))
        .unwrap_or(DEFAULT_RELEVANCE_FLOOR)
}

/// Resolve the effective deny-list of drawer tags for prompt-context recall.
///
/// Why (issue #139): centralises the env-override + default logic so the
/// filter call site stays small and the deny list is testable in isolation.
/// What: returns the lowercase tag strings parsed from
/// [`ENV_RECALL_DENY_TAGS`] when set (comma-separated, whitespace-trimmed,
/// empty entries skipped). Falls back to [`DEFAULT_DENY_TAGS`] when the env
/// var is unset, empty, or contains nothing but whitespace/commas.
/// Test: not unit-tested directly (env mutation races); covered indirectly
/// via `prompt_context_recall_env_override_extends_deny_list` and
/// `prompt_context_recall_filters_deny_tags`.
fn configured_deny_tags() -> Vec<String> {
    if let Ok(raw) = std::env::var(ENV_RECALL_DENY_TAGS) {
        let parsed: Vec<String> = raw
            .split(',')
            .map(|s| s.trim().to_lowercase())
            .filter(|s| !s.is_empty())
            .collect();
        if !parsed.is_empty() {
            return parsed;
        }
    }
    DEFAULT_DENY_TAGS.iter().map(|s| s.to_lowercase()).collect()
}

/// Resolve the palace slug from the stdin payload.
///
/// Why (issue #125 + #134): the hook's recall + KG enrichment both target
/// the project palace that owns the user's actual cwd, not the cwd the
/// hook process was launched with. The stdin `cwd` is the source of truth.
/// What: parse stdin as JSON, take `cwd`, derive slug via
/// [`crate::messaging::cwd_palace_slug_at`]. Falls back to the process
/// cwd's slug. Returns `None` only when neither resolves cleanly. The derived
/// slug then goes through [`crate::palace_id_derive::follow_palace_alias`], so
/// every consumer of this value — the injection header, the recall and KG
/// requests, the prompt log, the activity event — names the palace the daemon
/// will actually open rather than the pre-redirect slug.
/// Test: `resolve_palace_for_log_prefers_stdin_cwd` (the log helper uses
/// the same chain), `prompt_context_header_names_the_alias_target`.
fn resolve_palace_slug(stdin_payload: &str) -> Option<String> {
    let derived = palace_slug_from_stdin_cwd(stdin_payload)
        .or_else(|| crate::messaging::cwd_palace_slug().ok())?;
    // #5810: the header printed the derived slug while the drawers under it came
    // from the alias target, naming a palace `palace_list` never returns.
    Some(crate::palace_id_derive::follow_palace_alias(derived))
}

/// Resolve the project tree this firing belongs to, normalised for comparison
/// against a drawer's recorded `creator:cwd`.
///
/// Why (#5819): [`filter_drawers_by_project_scope`] needs one stable answer to
/// "which project is this session working on?". The stdin `cwd` is the source of
/// truth for the same reason [`resolve_palace_slug`] uses it — the hook process'
/// own cwd is whatever Claude Code launched it with, not where the user is.
///
/// The resolver has to agree with the one that picked the palace these drawers
/// came out of. It was [`crate::project_root::find_project_root`], whose marker
/// list includes `Cargo.toml` and whose walk is inclusive of `start`, so in a
/// Cargo workspace it stopped at the CRATE directory while
/// [`crate::messaging::cwd_palace_slug_at`] resolved the palace from the
/// workspace root. Recall then ran against the right palace and the filter
/// dropped every drawer written from the repo root or a sibling crate — silently,
/// uncounted, and against this filter's own fail-open contract.
/// What: asks [`trusty_common::palace_resolve::main_worktree_root`] — the level-4
/// probe `resolve_palace` uses — for the MAIN worktree root of the stdin `cwd`,
/// falling back to the process cwd. `--git-common-dir` names the main repo's
/// `.git` from inside a linked worktree, so a dispatched agent under
/// `.claude/worktrees/<name>` and the main checkout answer with one path.
/// Returns `None` when git cannot name a repository, and also when the answer
/// cannot be confirmed as a working tree of that repository — inside a submodule
/// the common dir is `<outer>/.git/modules/<name>`, whose parent is a git
/// internals directory rather than a checkout. Either way the filter is disabled
/// rather than pointed at a path no drawer can sit under; the confirmation lives
/// in [`trusty_common::palace_resolve::main_worktree_root`] so every consumer of
/// that probe gets it. Deliberately without `find_project_root`'s marker walk as
/// a fallback, since that walk is the defect above.
/// Test: `session_project_root_resolves_a_worktree_to_its_main_checkout`,
/// `session_project_root_is_none_inside_a_separate_git_dir_child`,
/// `project_scope_keeps_a_repo_root_writer_when_the_session_is_in_a_crate`.
fn resolve_session_project_root(stdin_payload: &str) -> Option<String> {
    let start = payload_cwd(stdin_payload)
        .map(std::path::PathBuf::from)
        .or_else(|| std::env::current_dir().ok())?;
    let root = trusty_common::palace_resolve::main_worktree_root(&start)?;
    let normalised = filter::normalise_project_path(&root.to_string_lossy());
    if normalised.is_empty() {
        None
    } else {
        Some(normalised)
    }
}

/// Extract the `cwd` field from the stdin JSON payload.
///
/// Why: [`palace_slug_from_stdin_cwd`] and [`resolve_session_project_root`] both
/// need it, and two spellings of "read cwd out of the payload" would drift.
/// What: `Some(cwd)` when the payload parses as JSON carrying a non-empty
/// string `cwd`; `None` otherwise.
/// Test: `resolve_palace_for_log_prefers_stdin_cwd` exercises the same read.
fn payload_cwd(stdin_payload: &str) -> Option<String> {
    if stdin_payload.trim().is_empty() {
        return None;
    }
    let value: Value = serde_json::from_str(stdin_payload).ok()?;
    let cwd = value.get("cwd")?.as_str()?;
    if cwd.is_empty() {
        None
    } else {
        Some(cwd.to_string())
    }
}

/// Resolve the palace identifier for the log entry.
///
/// Why (issue #125): see [`resolve_palace_slug`]; the log helper keeps
/// the legacy `"<unknown>"` sentinel so log shape stays stable.
/// Test: `resolve_palace_for_log_prefers_stdin_cwd`.
fn resolve_palace_for_log(stdin_payload: &str) -> String {
    resolve_palace_slug(stdin_payload).unwrap_or_else(|| "<unknown>".to_string())
}

/// Parse `stdin_payload` as JSON and, when it carries a `cwd` string, derive
/// the palace slug from that path.
///
/// Why: factored out so the unit test can exercise the stdin-override path
/// without manipulating the process cwd.
/// What: returns `Some(slug)` only when the payload parses as a JSON object,
/// contains a non-empty string `cwd`, and slug derivation succeeds for that
/// path. Returns `None` on every failure mode so the caller can fall back.
/// Test: `resolve_palace_for_log_prefers_stdin_cwd`.
fn palace_slug_from_stdin_cwd(stdin_payload: &str) -> Option<String> {
    let cwd = payload_cwd(stdin_payload)?;
    crate::messaging::cwd_palace_slug_at(std::path::Path::new(&cwd)).ok()
}

/// Append one log entry to the enriched-prompt log, swallowing failures.
///
/// Why: prompt logging is best-effort — a write failure must never block
/// the hook from completing.
/// What: constructs a `PromptLogEntry` and writes it via `PromptLogger`.
/// `query_shape` (#4972) is `None` on the paths that never reached a recall —
/// no daemon, no HTTP client, no resolved palace.
/// Test: `prompt_context_logs_attempt_without_daemon`,
/// `prompt_context_logs_recall_query_shape`.
fn log_entry(
    trigger_prompt: &str,
    injection: &str,
    facts_count: usize,
    start: Instant,
    query_shape: Option<RecallQueryShape>,
) {
    let logger = PromptLogger::from_env();
    let palace = resolve_palace_for_log(trigger_prompt);
    let entry = PromptLogEntry::new(
        "UserPromptSubmit",
        "prompt-context-facts",
        palace,
        trigger_prompt,
        injection,
    )
    .with_palace_facts_count(facts_count)
    .with_recall_query(query_shape)
    .with_duration_ms(start.elapsed().as_millis() as u64);
    logger.log(entry);
}

#[cfg(test)]
mod tests;